This repository contains a quantized INT8 version of bert-base-multilingual-cased, specifically optimized for word alignment using the awesome-align methodology.
Model Details
Base Model:bert-base-multilingual-cased
Truncation: Truncated to the first 8 layers (the optimal "sweet spot" for word alignment).
Format: ONNX INT8 (Quantized)
Size:~150 MB (approx. 75% smaller than the FP32 version).
Optimization: Quantized using torchao and Optimum with settings optimized for ARM64/Apple Silicon (M1/M2/M3).
Performance (MacBook Air M1 Benchmark)
Metric
FP32
INT8 (This Model)
Average Latency
~65 ms / sentence
~38 ms / sentence
Speedup
1x
~1.7x Faster
Accuracy
Baseline
Identical Links
Usage
This model is intended to be used with onnxruntime on CPU for maximum efficiency. Alignments are calculated using Cosine Similarity and Mutual Argmax (Intersection).
python
1import numpy as np
2import onnxruntime as ort
3from transformers import AutoTokenizer
45# 1. Load Model and Tokenizer6# Point to your local download or the Hub ID7model_id ="cstr/awesome-align-onnx-int8"8session = ort.InferenceSession("model.onnx", providers=['CPUExecutionProvider'])9tokenizer = AutoTokenizer.from_pretrained(model_id)1011defget_word_embeddings(words):12# Tokenize with subword mapping (is_split_into_words is critical)13 encoded = tokenizer(words, is_split_into_words=True, return_tensors="np")1415# Track which subwords belong to which original word index16 word_map =[]17for i, w inenumerate(words):18 sub_tokens = tokenizer.tokenize(w)or[tokenizer.unk_token]19 word_map.extend([i]*len(sub_tokens))2021# Run inference22 outputs = session.run(None,{23"input_ids": encoded["input_ids"],24"attention_mask": encoded["attention_mask"]25})2627# Slicing: [Batch 0, remove CLS/SEP, all hidden features]28 embeddings = outputs[0][0,1:-1,:]29return embeddings, word_map
3031defalign(src_words, tgt_words):32# Get embeddings and maps33 src_embeds, src_map = get_word_embeddings(src_words)34 tgt_embeds, tgt_map = get_word_embeddings(tgt_words)3536# Compute Cosine Similarity37 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)4041# Mutual Argmax (Intersection) Logic for high precision42 best_tgt_for_src = np.argmax(similarity, axis=1)43 best_src_for_tgt = np.argmax(similarity, axis=0)4445 alignment =set()46for i, j inenumerate(best_tgt_for_src):47if best_src_for_tgt[j]== i:48 alignment.add((src_map[i], tgt_map[j]))4950returnsorted(list(alignment))5152# Example Usage53src =["I","will","go","to","the","hospital"]54tgt =["Ich","werde","ins","Krankenhaus","gehen"]55links = align(src, tgt)5657print(f"Alignment Links: {links}")58
Technical Notes
Subword Handling: This model is based on mBERT; it uses WordPiece tokenization. The provided script maps these sub-tokens back to original word indices to ensure logical word-to-word alignments.
CPU Optimization: The INT8 quantization uses per-channel asymmetric quantization, which is highly efficient for the ARM NEON instruction set on Apple Silicon.
Layer 8 Extraction: Only the first 8 layers were exported to ONNX to reduce computational overhead and disk space without sacrificing alignment quality.
Original model card follows:
BERT multilingual base model (cased)
Pretrained model on the top 104 languages with the largest Wikipedia using a masked language modeling (MLM) objective.
It was introduced in this paper and first released in
this repository. This model is case sensitive: it makes a difference
between english and English.
Disclaimer: The team releasing BERT did not write a model card for this model so this model card has been written by
the Hugging Face team.
Model description
BERT is a transformers model pretrained on a large corpus of multilingual data in a self-supervised fashion. This means
it was pretrained on the raw texts only, with no humans labelling them in any way (which is why it can use lots of
publicly available data) with an automatic process to generate inputs and labels from those texts. More precisely, it
was pretrained with two objectives:
Masked language modeling (MLM): taking a sentence, the model randomly masks 15% of the words in the input then run
the entire masked sentence through the model and has to predict the masked words. This is different from traditional
recurrent neural networks (RNNs) that usually see the words one after the other, or from autoregressive models like
GPT which internally mask the future tokens. It allows the model to learn a bidirectional representation of the
sentence.
Next sentence prediction (NSP): the models concatenates two masked sentences as inputs during pretraining. Sometimes
they correspond to sentences that were next to each other in the original text, sometimes not. The model then has to
predict if the two sentences were following each other or not.
This way, the model learns an inner representation of the languages in the training set that can then be used to
extract features useful for downstream tasks: if you have a dataset of labeled sentences for instance, you can train a
standard classifier using the features produced by the BERT model as inputs.
Intended uses & limitations
You can use the raw model for either masked language modeling or next sentence prediction, but it's mostly intended to
be fine-tuned on a downstream task. See the model hub to look for
fine-tuned versions on a task that interests you.
Note that this model is primarily aimed at being fine-tuned on tasks that use the whole sentence (potentially masked)
to make decisions, such as sequence classification, token classification or question answering. For tasks such as text
generation you should look at model like GPT2.
How to use
You can use this model directly with a pipeline for masked language modeling:
python
1>>>from transformers import pipeline
2>>> unmasker = pipeline('fill-mask', model='bert-base-multilingual-cased')3>>> unmasker("Hello I'm a [MASK] model.")45[{'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'}]
Here is how to use this model to get the features of a given text in PyTorch:
python
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)
and in TensorFlow:
python
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)
Training data
The BERT model was pretrained on the 104 languages with the largest Wikipedias. You can find the complete list
here.
Training procedure
Preprocessing
The texts are lowercased and tokenized using WordPiece and a shared vocabulary size of 110,000. The languages with a
larger Wikipedia are under-sampled and the ones with lower resources are oversampled. For languages like Chinese,
Japanese Kanji and Korean Hanja that don't have space, a CJK Unicode block is added around every character.
The inputs of the model are then of the form:
[CLS] Sentence A [SEP] Sentence B [SEP]
With probability 0.5, sentence A and sentence B correspond to two consecutive sentences in the original corpus and in
the other cases, it's another random sentence in the corpus. Note that what is considered a sentence here is a
consecutive span of text usually longer than a single sentence. The only constrain is that the result with the two
"sentences" has a combined length of less than 512 tokens.
The details of the masking procedure for each sentence are the following:
15% of the tokens are masked.
In 80% of the cases, the masked tokens are replaced by [MASK].
In 10% of the cases, the masked tokens are replaced by a random token (different) from the one they replace.
In the 10% remaining cases, the masked tokens are left as is.
BibTeX entry and citation info
bibtex
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}
Upstream licence:apache-2.0. This repository redistributes under the same terms; it grants no rights the upstream licence does not.
What was done here: format conversion and/or quantisation only (ONNX, INT8 precision). No training, no fine-tuning, no merging, no distillation, no change to architecture, vocabulary or capability. Only the numeric representation of the upstream weights differs.
Training data: documented — where it is documented at all — by the upstream provider; see the upstream model card. No training data was used, added or selected by this repository.
Provider status: under Regulation (EU) 2024/1689 the upstream authors remain the provider of this model. Converting the serialisation format does not make this repository the provider of a new general-purpose AI model, and no such claim is made. Questions about training content, copyright policy or model capability belong upstream.