Views
No views yet
bert-base-multilingual-casedonnxruntime to extract embeddings for source and target sentences. It is truncated to Layer 8, the optimal layer for cross-lingual feature extraction. Alignments are then calculated using Cosine Similarity and Mutual Argmax (Intersection).1import numpy as np
2import onnxruntime as ort
3from transformers import AutoTokenizer
4
5# 1. Load Model and Tokenizer
6# For INT8: use "cstr/awesome-align-onnx-int8"
7model_id = "cstr/awesome-align-onnx"
8session = ort.InferenceSession("model.onnx", providers=['CPUExecutionProvider'])
9tokenizer = AutoTokenizer.from_pretrained(model_id)
10
11def get_word_embeddings(words):
12 # Tokenize with subword mapping
13 encoded = tokenizer(words, is_split_into_words=True, return_tensors="np")
14
15 # Track which subwords belong to which original word index
16 word_map = []
17 for i, w in enumerate(words):
18 sub_tokens = tokenizer.tokenize(w) or [tokenizer.unk_token]
19 word_map.extend([i] * len(sub_tokens))
20
21 # Run inference
22 outputs = session.run(None, {
23 "input_ids": encoded["input_ids"],
24 "attention_mask": encoded["attention_mask"]
25 })
26
27 # Slicing: [Batch 0, remove CLS/SEP, all hidden features]
28 embeddings = outputs[0][0, 1:-1, :]
29 return embeddings, word_map
30
31def align(src_words, tgt_words):
32 # Get embeddings and maps
33 src_embeds, src_map = get_word_embeddings(src_words)
34 tgt_embeds, tgt_map = get_word_embeddings(tgt_words)
35
36 # Compute Cosine Similarity
37 src_norm = src_embeds / np.linalg.norm(src_embeds, axis=-1, keepdims=True)
38 tgt_norm = tgt_embeds / np.linalg.norm(tgt_embeds, axis=-1, keepdims=True)
39 similarity = np.dot(src_norm, tgt_norm.T)
40
41 # Mutual Argmax (Intersection) Logic
42 best_tgt_for_src = np.argmax(similarity, axis=1)
43 best_src_for_tgt = np.argmax(similarity, axis=0)
44
45 alignment = set()
46 for i, j in enumerate(best_tgt_for_src):
47 if best_src_for_tgt[j] == i:
48 alignment.add((src_map[i], tgt_map[j]))
49
50 return sorted(list(alignment))
51
52# Example Usage
53src = ["the", "cat", "sat"]
54tgt = ["le", "chat", "assis"]
55links = align(src, tgt)
56
57print(f"Alignment Links: {links}")
58# Output: [(0, 0), (1, 1), (2, 2)]['ass', '##is']) back to their parent word index.session.run is the 768-dimensional hidden state of the 8th layer.similarity matrix.1>>> from transformers import pipeline
2>>> unmasker = pipeline('fill-mask', model='bert-base-multilingual-cased')
3>>> unmasker("Hello I'm a [MASK] model.")
4
5[{'sequence': "[CLS] Hello I'm a model model. [SEP]",
6 'score': 0.10182085633277893,
7 'token': 13192,
8 'token_str': 'model'},
9 {'sequence': "[CLS] Hello I'm a world model. [SEP]",
10 'score': 0.052126359194517136,
11 'token': 11356,
12 'token_str': 'world'},
13 {'sequence': "[CLS] Hello I'm a data model. [SEP]",
14 'score': 0.048930276185274124,
15 'token': 11165,
16 'token_str': 'data'},
17 {'sequence': "[CLS] Hello I'm a flight model. [SEP]",
18 'score': 0.02036019042134285,
19 'token': 23578,
20 'token_str': 'flight'},
21 {'sequence': "[CLS] Hello I'm a business model. [SEP]",
22 'score': 0.020079681649804115,
23 'token': 14155,
24 'token_str': 'business'}]1from transformers import BertTokenizer, BertModel
2tokenizer = BertTokenizer.from_pretrained('bert-base-multilingual-cased')
3model = BertModel.from_pretrained("bert-base-multilingual-cased")
4text = "Replace me by any text you'd like."
5encoded_input = tokenizer(text, return_tensors='pt')
6output = model(**encoded_input)1from transformers import BertTokenizer, TFBertModel
2tokenizer = BertTokenizer.from_pretrained('bert-base-multilingual-cased')
3model = TFBertModel.from_pretrained("bert-base-multilingual-cased")
4text = "Replace me by any text you'd like."
5encoded_input = tokenizer(text, return_tensors='tf')
6output = model(encoded_input)[CLS] Sentence A [SEP] Sentence B [SEP][MASK].1@article{DBLP:journals/corr/abs-1810-04805,
2 author = {Jacob Devlin and
3 Ming{-}Wei Chang and
4 Kenton Lee and
5 Kristina Toutanova},
6 title = {{BERT:} Pre-training of Deep Bidirectional Transformers for Language
7 Understanding},
8 journal = {CoRR},
9 volume = {abs/1810.04805},
10 year = {2018},
11 url = {http://arxiv.org/abs/1810.04805},
12 archivePrefix = {arXiv},
13 eprint = {1810.04805},
14 timestamp = {Tue, 30 Oct 2018 20:39:56 +0100},
15 biburl = {https://dblp.org/rec/journals/corr/abs-1810-04805.bib},
16 bibsource = {dblp computer science bibliography, https://dblp.org}
17}