Views
No views yet
proxectonos/nos-coda_iacobus-en-es,
a English → Spanish translation model.optimum-cli cannot read.onmt_translate at beam 4 on
15 sentences.| build | exact match vs OpenNMT-py |
|---|---|
| fp32 | 15/15 |
| int8 | 15/15 |
OpenNMT-py .pt → PegasusForConditionalGeneration → optimum-cli export onnx.layernorm_embedding, a
sinusoidal position table, and a final_logits_bias to carry OpenNMT's
generator bias.[sin | cos]. HF drops position weights on save and rebuilds them from its
own formula, so the real table has to be force-persisted.[target | source]; encoder input ids are offset by
17864 (= target vocab size) and the source half is masked out of the
output distribution with final_logits_bias = -1e9.AutoTokenizer. As with the original, input must
be Moses-tokenized and then BPE-segmented with the published subword-nmt codes
(en_35k.code, included here).1import json, re, torch
2from sacremoses import MosesTokenizer, MosesDetokenizer
3from subword_nmt.apply_bpe import BPE
4from optimum.onnxruntime import ORTModelForSeq2SeqLM
5
6repo = "TigreGotico/nos-coda_iacobus-en-es-onnx"
7model = ORTModelForSeq2SeqLM.from_pretrained(repo) # add subfolder="int8" for int8
8meta = json.load(open("onmt_vocab.json")) # from this repo
9bpe = BPE(open("en_35k.code", encoding="utf-8"))
10mt, md = MosesTokenizer(lang="en"), MosesDetokenizer(lang="es")
11
12src_ix = {t: i for i, t in enumerate(meta["source_vocab"])}
13off, UNK, PAD = meta["source_offset"], 0, 1
14
15def translate(text):
16 toks = bpe.process_line(" ".join(mt.tokenize(text, escape=False))).split()
17 ids = torch.tensor([[src_ix.get(t, UNK) + off for t in toks]])
18 out = model.generate(input_ids=ids,
19 attention_mask=torch.ones_like(ids),
20 num_beams=4, max_length=256)
21 pieces = [meta["target_vocab"][i] for i in out[0].tolist() if i not in (1, 2, 3)]
22 return md.detokenize(re.sub(r"@\s*", "", " ".join(pieces)).split())
23
24print(translate('The children are playing in the garden.'))@@ is the subword-nmt continuation marker. Strip it with re.sub(r"@\s*", "", ...),
which is the upstream sed 's/@\s*//g' rule — a plain replace("@@ ", "") is not
equivalent and will corrupt words before punctuation.<unk> is kept in the output rather than silently dropped, so you can see where the
model failed. Expect some — the original onmt_translate emits <unk> in exactly the
same places. Upstream hides them with -replace_unk, which copies the aligned source
word using the decoder's cross-attention weights; that is not reproducible from an
exported graph, so they are left visible here. Separately, the original was trained on
text tokenized with Linguakit's tokenizer.pl, for which Moses is a close but not
identical substitute.encoder_model.onnx, decoder_model.onnx, decoder_with_past_model.onnx — fp32int8/ — dynamically quantized (MatMul only, output projection excluded)onmt_vocab.json — source vocab, target vocab, id offseten_35k.code — subword-nmt BPE codes