YAML Metadata Warning:empty or missing yaml metadata in repo card
Check out the documentation for more information.
English ↔ Vietnamese Translation (ONNX)
This is a small neural machine translation model that can translate between English and Vietnamese in both directions.
Note: This is my first NMT model. I trained it for learning and pushed it here as a demo.
Files you need
nmt-en-vi-d128.onnx— the modeltok.json— the tokenizer
You need both files to run it.
How to use
Install:
pip install onnxruntime numpy
Then run this simple example:
import json
import numpy as np
import onnxruntime as ort
# Load model and tokenizer
sess = ort.InferenceSession("nmt-en-vi-d128.onnx")
with open("tok.json", encoding="utf-8") as f:
tok = json.load(f)
pieces = tok["pieces"]
merges = {(a, b): (i, c) for i, (a, b, c) in enumerate(tok["merges"])}
sp = tok["special"]
BOS, EOS, UNK = sp["BOS"], sp["EOS"], sp["UNK"]
TO_EN, TO_VI = sp["TO_EN"], sp["TO_VI"]
SPU = "\u2581"
sym2id = {p: i for i, p in enumerate(pieces)}
def encode_word(w):
ids = [sym2id.get(ch, UNK) for ch in (SPU + w)]
while len(ids) > 1:
best = (10**9, -1, 0)
for i in range(len(ids) - 1):
key = (ids[i], ids[i + 1])
if key in merges and merges[key][0] < best[0]:
best = (merges[key][0], i, merges[key][1])
if best[1] < 0:
break
ids[best[1]] = best[2]
del ids[best[1] + 1]
return ids
def encode(text, to_en=False):
ids = [TO_EN if to_en else TO_VI]
for w in text.split():
ids.extend(encode_word(w))
ids.append(EOS)
return ids
def detok(ids):
s = "".join(("<unk>" if i == UNK else pieces[i]) for i in ids if i > TO_VI or i == UNK)
return s.replace(SPU, " ").strip()
def translate(text, to_en=False, max_len=40):
src = np.array([encode(text, to_en=to_en)], dtype=np.int64)
ys = np.array([[BOS]], dtype=np.int64)
out = []
for _ in range(max_len):
logits = sess.run(None, {"src": src, "ys": ys})[0]
nxt = int(logits[0].argmax())
if nxt == EOS:
break
out.append(nxt)
ys = np.concatenate([ys, [[nxt]]], axis=1)
return detok(out)
# Try it
print(translate("I eat rice.")) # Tôi ăn gạo.
print(translate("Hello.")) # Xin chào.
print(translate("Xin chào.", to_en=True)) # Hello.
print(translate("Tôi yêu bạn.", to_en=True)) # I love you.
About the model
- Very small model (good for phone / CPU)
- Can translate both ways: English → Vietnamese and Vietnamese → English
- Works offline
- Quality is okay for short sentences, but not perfect for long or complex text
Limitations
This is a demo / learning model.
It is small, so the translation quality is limited.
Long sentences often become less accurate.
Made for learning and sharing.
Inference Providers NEW
This model isn't deployed by any Inference Provider. 🙋 Ask for provider support