这是
Tencent HY-MT1.5-1.8B 翻译模型的 ONNX 导出版本,可直接使用 ONNX Runtime 进行高效推理,无需 PyTorch 依赖。
1 import numpy as np
2 import onnxruntime as ort
3 from transformers import AutoTokenizer
4
5 # ── 加载 ──────────────────────────────────────────
6 tokenizer = AutoTokenizer . from_pretrained ( "tencent/HY-MT1.5-1.8B" )
7
8 prefill = ort . InferenceSession ( "onnx/hy_mt_prefill.onnx" ,
9 providers = [ "CPUExecutionProvider" ] )
10 decode = ort . InferenceSession ( "onnx/hy_mt_decode.onnx" ,
11 providers = [ "CPUExecutionProvider" ] )
12
13 # ── Tokenize ──────────────────────────────────────
14 messages = [ { "role" : "user" , "content" : "将下面的英文翻译成中文: Hello, how are you?" } ]
15 input_ids = tokenizer . apply_chat_template (
16 messages , tokenize = True , add_generation_prompt = True ,
17 return_tensors = "np" ,
18 )
19
20 # ── Prefill ───────────────────────────────────────
21 seq_len = input_ids . shape [ 1 ]
22 attn_mask = np . ones ( ( 1 , seq_len ) , dtype = np . int64 )
23 prefill_out = prefill . run ( None , {
24 "input_ids" : input_ids ,
25 "attention_mask" : attn_mask ,
26 } )
27
28 # 提取 KV Cache
29 kv = { }
30 for i in range ( 32 ) :
31 kv [ f"past_key_ { i } " ] = prefill_out [ 1 + 2 * i ]
32 kv [ f"past_value_ { i } " ] = prefill_out [ 1 + 2 * i + 1 ]
33
34 # 采样第一个 token
35 logits = prefill_out [ 0 ] [ 0 , - 1 , : ]
36 next_token = int ( np . argmax ( logits ) )
37
38 # ── Decode 循环 ──────────────────────────────────
39 total_len = seq_len
40 generated = [ ]
41 for _ in range ( 256 ) :
42 total_len += 1
43 decode_out = decode . run ( None , {
44 "input_ids" : np . array ( [ [ next_token ] ] , dtype = np . int64 ) ,
45 "attention_mask" : np . ones ( ( 1 , total_len ) , dtype = np . int64 ) ,
46 ** kv ,
47 } )
48 # 更新 KV Cache
49 for i in range ( 32 ) :
50 kv [ f"past_key_ { i } " ] = decode_out [ 1 + 2 * i ]
51 kv [ f"past_value_ { i } " ] = decode_out [ 1 + 2 * i + 1 ]
52
53 next_token = int ( np . argmax ( decode_out [ 0 ] [ 0 , - 1 , : ] ) )
54 if next_token == 120020 : # EOS
55 break
56 generated . append ( next_token )
57
58 # ── Detokenize ────────────────────────────────────
59 output = tokenizer . decode ( generated , skip_special_tokens = True )
60 print ( output )
.
├── onnx
├── export_onnx_full.py # 完整导出脚本(prefill + decode)
├── inference_onnx.py # ONNX Runtime 推理脚本
├── compare_onnx_pt.py # ONNX vs PyTorch 精度对比
└── README.md
1 @misc{hy-mt1.5,
2 title={HY-MT1.5 Technical Report},
3 author={Mao Zheng and Zheng Li and Tao Chen and Mingyang Song and Di Wang},
4 year={2025},
5 eprint={2512.24092},
6 archivePrefix={arXiv},
7 primaryClass={cs.CL},
8 url={https://arxiv.org/abs/2512.24092},
9 }