Update README.md
Browse files6 unmodified lines7891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205216 unmodified lines- translation- machine-translation- english-to-vietnamese- vietnamese- onnx- seq2seq- bartpipeline_tag: translation---# AnViMt**AnViMt** là mô hình dịch máy **English → Vietnamese** được fine-tune để dịch cả văn bản thông thường lẫn nội dung kỹ thuật, hệ thống, lập trình và hội thoại.Tên model:> **An** = English> **Vi** = Vietnamese> **Mt** = Machine TranslationModel được export sang **ONNX** để chạy inference nhẹ và không cần cài toàn bộ Hugging Face Transformers.## ✨ Điểm nổi bật- 🇬🇧 English → 🇻🇳 Vietnamese- ⚡ ONNX Runtime inference- 📱 Có thể chạy trên Android / Termux- 💻 Có thể chạy trên CPU- 🧠 Kiến trúc Seq2Seq encoder-decoder- 🔧 Hỗ trợ khá tốt nội dung kỹ thuật- 💬 Có dữ liệu hội thoại và nhiều cách xưng hô tiếng Việt- 🖥️ Có dữ liệu về Linux, hệ điều hành, kernel, system calls, process, memory, networking- 🤖 Có dữ liệu AI / machine learning / inference- 📦 Runtime package tối giản---# Model filesBản ONNX runtime chỉ cần 3 file:```textAnViMt/├── encoder_model.onnx├── decoder_model.onnx└── spm.modelencoder_model.onnxEncoder nhận câu tiếng Anh đã được tokenize.English text↓Tokenizer↓Token IDs↓encoder_model.onnx↓Encoder hidden statesEncoder xử lý toàn bộ câu nguồn và tạo hidden states dùng cho decoder.---decoder_model.onnxDecoder sinh câu tiếng Việt theo từng token.Encoder hidden states+Previous generated tokens↓decoder_model.onnx↓Next token logits↓Select next token↓Repeat until EOSQuá trình dịch là autoregressive generation.---spm.modelTokenizer SentencePiece.File này chịu trách nhiệm:Text↓SentencePiece↓Token IDs↓ONNX model↓Generated token IDs↓SentencePiece decode↓Vietnamese translation---ArchitectureAnViMt sử dụng kiến trúc Transformer Seq2Seq encoder-decoder.SOURCEEnglish sentence│▼SentencePiece│▼Token IDs│▼┌─────────────────────────┐│ ENCODER ││ encoder_model.onnx │└─────────────────────────┘│▼Hidden states│▼┌─────────────────────────┐│ DECODER ││ decoder_model.onnx │└─────────────────────────┘│▼Output logits│▼Next token│└───────┐│Repeat│▼Vietnamese textModel thuộc nhóm encoder-decoder neural machine translation.---ParametersAnViMt được export từ checkpoint fine-tuned sang ONNX.Các tham số của model được lưu trực tiếp bên trong:encoder_model.onnxdecoder_model.onnxRuntime package ONNX không yêu cầu:config.jsonHugging Face TransformersPyTorchSafetensorsInference chỉ cần:onnxruntimenumpysentencepiece---InstallationPythonpip install onnxruntime numpy sentencepieceTermuxNếu đã có Python:pip install onnxruntime numpy sentencepiece---Quick StartĐặt 3 file:project/├── main.py├── encoder_model.onnx├── decoder_model.onnx└── spm.modelSau đó chạy:python main.py---main.pyVí dụ inference tối giản:import numpy as npimport onnxruntime as ortimport sentencepiece as spmENCODER_MODEL = "encoder_model.onnx"DECODER_MODEL = "decoder_model.onnx"TOKENIZER_MODEL = "spm.model"sp = spm.SentencePieceProcessor()sp.load(TOKENIZER_MODEL)encoder = ort.InferenceSession(ENCODER_MODEL,providers=["CPUExecutionProvider"])decoder = ort.InferenceSession(DECODER_MODEL,providers=["CPUExecutionProvider"])def translate(text, max_length=128):# Tokenize inputinput_ids = sp.encode(text,out_type=int)input_ids = np.array([input_ids],dtype=np.int64)attention_mask = np.ones_like(input_ids,dtype=np.int64)# Encoderencoder_outputs = encoder.run(None,{encoder.get_inputs()[0].name: input_ids,encoder.get_inputs()[1].name: attention_mask,})encoder_hidden_states = encoder_outputs[0]# Decoder start tokendecoder_ids = np.array([[sp.bos_id()]],dtype=np.int64)# Generatefor _ in range(max_length):decoder_inputs = {}for inp in decoder.get_inputs():name = inp.nameif "input_ids" in name:decoder_inputs[name] = decoder_idselif "encoder_hidden_states" in name:decoder_inputs[name] = encoder_hidden_stateselif "attention_mask" in name:decoder_inputs[name] = attention_maskoutputs = decoder.run(None,decoder_inputs)logits = outputs[0]next_token = np.argmax(logits[:, -1, :],axis=-1)decoder_ids = np.concatenate([decoder_ids,next_token[:, None]],axis=1)if int(next_token[0]) == sp.eos_id():breaktokens = decoder_ids[0].tolist()# Remove special tokenstokens = [x for x in tokensif x not in {sp.bos_id(),sp.eos_id(),sp.pad_id()}]return sp.decode(tokens)if __name__ == "__main__":while True:text = input("\nEN > ").strip()if not text:continueif text.lower() in {"exit","quit","q"}:breakresult = translate(text)print("VI >", result)---ExampleInput:The system automatically restarts the failed service after detecting an unexpected process crash.Output:Hệ thống tự động khởi động lại dịch vụ gặp lỗi sau khi phát hiện tiến trình bị sập bất ngờ.---Another exampleInput:The application uses asynchronous I/O so network requests do not block the main execution thread.Expected translation style:Ứng dụng sử dụng I/O bất đồng bộ để các yêu cầu mạng không chặn luồng thực thi chính.---Technical examplesInput:The kernel schedules CPU time according to process priority and current system load.The database transaction was rolled back because a constraint violation occurred during the update.Gradient accumulation allows the model to simulate a larger effective batch size when GPU memory is limited.The inference engine reuses cached key-value states to avoid recomputing previous attention activations.---Conversation examplesInput:Hey bro, can you help me fix this problem? I have been stuck on it for hours.Input:Don't worry, I'll take a look at the logs and see what caused the crash.Input:Could you please restart the service and check whether the error still occurs?AnViMt được train thêm dữ liệu hội thoại để hỗ trợ cách diễn đạt tự nhiên và nhiều phong cách xưng hô tiếng Việt.---Runtime dependenciesAnViMt ONNX runtime chỉ sử dụng 3 thư viện Python:onnxruntimenumpysentencepieceLibrary Purposeonnxruntime Chạy encoder và decoder ONNXnumpy Xử lý tensor / token IDssentencepiece Tokenization và decodingKhông cần:torchtransformersoptimumtensorflow---Supported environmentAnViMt có thể chạy trên:LinuxWindowsmacOSAndroid TermuxCPU environmentsTùy phiên bản ONNX Runtime, có thể sử dụng execution provider khác nếu môi trường hỗ trợ.---LimitationsModel tập trung vào English → Vietnamese.Chất lượng có thể giảm với câu cực dài hoặc cấu trúc hiếm.Một số thuật ngữ chuyên ngành mới có thể được giữ nguyên tiếng Anh.Tên riêng và thuật ngữ kỹ thuật có thể cần hậu kiểm.Bản ONNX runtime này ưu tiên inference đơn giản và nhẹ.---LicenseThis model is released under:CC BY-NC 4.0You are allowed to:DownloadUseShareModifyFine-tuneYou are not allowed to use this model for commercial purposes without permission.Commercial use includes using the model to generate revenue, provide paid services, or integrate it into commercial products.---AuthorPhitran21Model: AnViMtEnglish → Vietnamese Machine Translation6 unmodified lines7891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191206 unmodified lines- translation- machine-translation- english-to-vietnamese- onnx- seq2seq- bartpipeline_tag: translationwidget:- text: "Machine translation is useful for multilingual applications."example_title: "EN → VI"---# AnViMt**AnViMt** — **An**=English **Vi**=Vietnamese **Mt**=Machine Translation — dịch **EN → VI** cho văn bản thường + kỹ thuật/hệ thống/lập trình/hội thoại.Export sang **ONNX** để chạy chỉ với `onnxruntime + sentencepiece + numpy` (không cần `torch/transformers`).## Architecture**Base:** `transformers.BartForConditionalGeneration` train từ đầu, không phải pretrained BART.- `vocab_size=32000` (SentencePiece BPE, `byte_fallback=True`)- `d_model=512` | `encoder_layers=6` | `decoder_layers=6`- `encoder_ffn_dim=2048` | `decoder_ffn_dim=2048`- `encoder_attention_heads=8` | `decoder_attention_heads=8`- `max_position_embeddings=256` | `dropout 0.1`- `tie_word_embeddings=True` | `is_encoder_decoder=True`- `pad_token_id=0` (`<pad>`) | `unk_token_id=1` (`<unk>`) | `bos_token_id=2` (`<s>`) | `eos_token_id=3` (`</s>`) | `decoder_start_token_id=2`- **Params:** ~60.79M```EN text↓ spm.model [2] + BPE ids + [3] (pad 0, bos 2, eos 3, max 256)↓encoder_model.onnx (input_ids, attention_mask → encoder_hidden_states [batch, seq, 512])↓decoder_model.onnx / decoder_with_past_model.onnx(decoder_input_ids [2] + encoder_hidden_states + encoder_attention_mask + past_key_values → logits)↓ autoregressive greedy (argmax) đến eos 3↓ sp.decode → VI text```## FilesExport bằng `optimum` `task=seq2seq-lm` `opset=14`:```AnViMt/├── encoder_model.onnx # 136M├── decoder_model.onnx # 223M├── decoder_with_past_model.onnx # KV cache (tùy chọn, tăng tốc)├── spm.model # 752K, vocab 32000└── spm.vocab```Runtime tối thiểu chỉ cần `encoder_model.onnx` + `decoder_model.onnx` + `spm.model`. `decoder_with_past_model.onnx` dùng khi muốn KV-cache.Không cần: `config.json`, `pytorch_model.bin`, `safetensors`, `torch`, `transformers`.## Installation```bashpip install onnxruntime sentencepiece numpy# Termux: apt install python3-onnxruntime python3-sentencepiece python3-numpy```## Quick Start```project/├── main.py├── encoder_model.onnx├── decoder_model.onnx└── spm.model # (decoder_with_past_model.onnx nếu có)````main.py` thực tế (đã test, xử lý đúng BOS/EOS/pad):```pythonimport numpy as np, onnxruntime as ort, sentencepiece as spmsp = spm.SentencePieceProcessor(); sp.load("spm.model")enc = ort.InferenceSession("encoder_model.onnx", providers=["CPUExecutionProvider"])dec = ort.InferenceSession("decoder_model.onnx", providers=["CPUExecutionProvider"])BOS, EOS, PAD = 2, 3, 0def translate(text, max_len=256):ids = [BOS] + sp.encode(text, out_type=int)[:254] + [EOS]input_ids = np.array([ids], dtype=np.int64)attn = np.ones_like(input_ids)enc_hs = enc.run(None, {"input_ids": input_ids, "attention_mask": attn})[0]gen = [BOS]for _ in range(max_len):dec_ids = np.array([gen], dtype=np.int64)logits = dec.run(None, {"input_ids": dec_ids, "encoder_hidden_states": enc_hs, "encoder_attention_mask": attn})[0]nxt = int(np.argmax(logits[0, -1]))gen.append(nxt)if nxt == EOS: breakout = [x for x in gen[1:] if x not in (BOS, EOS, PAD)]if EOS in out: out = out[:out.index(EOS)]return sp.decode(out)```## Training DataPretrain 1.13M EN-VI (PhoMT + TED + TECH) → finetune 200k TECH → finetune 27k v3 (hội thoại + kỹ thuật). Tokenizer BPE 32k train trên 400k pairs reservoir sampled, `nmt_nfkc`, `split_digits`, `byte_fallback`.## LimitationsEN → VI only. Câu >254 BPE tokens bị cắt. Thuật ngữ mới có thể giữ nguyên EN.## LicenseCC BY-NC 4.0 — non-commercial.Author: Phitran21
README.md+84-485