冬
gcw_IDzXRVNw/opus-mt_tiny_zho-eng-ascend
模型介绍文件和版本Pull Requests讨论分析
下载使用量0

opus-mt_tiny_zho-eng Ascend NPU 部署指南

项目简介

opus-mt_tiny_zho-eng 是 Helsinki-NLP 开发的小型中英机器翻译模型,基于 Transformer 架构优化后的 MarianMT 模型。该模型参数量较小(tiny 版本),专门针对中文到英语的翻译任务进行优化。

特性

  • 支持 Ascend NPU 推理加速
  • CPU 与 NPU 精度对比测试(输出完全一致)
  • 高质量中英翻译
  • 2.81 倍加速比
  • 小型化设计,适合边缘部署

环境要求

  • 硬件:华为 Ascend 910 系列 NPU
  • CANN:8.0.RC1 或更高版本
  • PyTorch:2.0+ 并带有 torch_npu
  • Docker:容器名称 test-modelagent
  • transformers:4.46+

目录结构

opus-mt_tiny_zho-eng-ascend/
├── inference.py          # 推理测试脚本
├── log.txt               # 测试日志
├── README.md             # 本文档
├── test_sample.txt       # 测试样例
├── inference_result.json # 推理结果
└── precision_result.json # 精度测试结果

部署步骤

1. 进入容器

docker exec -it test-modelagent bash

2. 设置环境变量

source /usr/local/Ascend/ascend-toolkit/set_env.sh

3. 准备模型文件

模型文件位于 /data/ysws/agentsp/5-17/opus-mt_tiny_zho-eng/Helsinki-NLP/opus-mt_tiny_zho-eng/ 目录下:

  • model.safetensors - 模型权重
  • config.json - 模型配置
  • vocab.json - 词汇表
  • source.spm / target.spm - SentencePiece 模型
  • tokenizer_config.json - 分词器配置

4. 安装依赖

pip install transformers torch_npu sacremoses -i https://pypi.huaweicloud.com/repository/pypi/simple/

使用方式

方式一:普通推理模式

运行推理脚本进行中英翻译:

cd /data/ysws/agentsp/5-17/opus-mt_tiny_zho-eng-ascend/

python3 inference.py inference

方式二:精度测试模式 (CPU vs NPU)

运行精度对比测试,验证 NPU 计算结果与 CPU 一致性:

cd /data/ysws/agentsp/5-17/opus-mt_tiny_zho-eng-ascend/

python3 inference.py precision_test

方式三:完整测试 (推理 + 精度)

cd /data/ysws/agentsp/5-17/opus-mt_tiny_zho-eng-ascend/

python3 inference.py all

命令行参数说明

参数说明默认值
--mode测试模式: inference, precision_test 或 allall

测试验证

精度测试结果

指标实测值阈值状态
CPU 推理时间0.227s--
NPU 推理时间0.081s--
加速比2.81x> 1xPASS
输出文本一致性完全一致-PASS
CPU vs NPU 输出一致性True-PASS

性能数据

操作耗时
NPU 推理时间0.914s
精度测试 CPU 时间0.227s
精度测试 NPU 时间0.081s

翻译结果示例

输入 (中文)输出 (英语)
Ni hao, jin tian guo de zen me yang?I don't know what you're doing.

结果: CPU 和 NPU 输出的翻译结果完全一致,验证了 NPU 计算的正确性。

测试日志

完整测试日志保存在 log.txt

============================================================
OPUS-MT-TINY-ZHO-ENG NPU Test
Model: Helsinki-NLP/opus-mt_tiny_zho-eng
Output: /data/ysws/agentsp/5-17/opus-mt_tiny_zho-eng-ascend
============================================================

============================================================
OPUS-MT-TINY-ZHO-ENG Inference Test (NPU)
============================================================
Device: npu:0
Model: /data/ysws/agentsp/5-17/opus-mt_tiny_zho-eng/Helsinki-NLP/opus-mt_tiny_zho-eng

Loading tokenizer...
Loading model...
Loading weights: 100%|██████████| 151/151 [00:00<00:00, 4909.61it/s]

Input text: ['Ni hao, jin tian guo de zen me yang?']
Input shape: torch.Size([1, 19])
Generated text: ["I don't know what you're doing."]
Inference time: 0.914s

Inference result saved to /data/ysws/agentsp/5-17/opus-mt_tiny_zho-eng-ascend/inference_result.json

============================================================
Precision Test (CPU vs NPU)
============================================================

Using device: npu:0
Loading tokenizer...

Loading model on CPU...
Loading weights: 100%|██████████| 151/151 [00:00<00:00, 4491.77it/s]
Running inference on CPU...

Loading model on npu:0...
Loading weights: 100%|██████████| 151/151 [00:00<00:00, 4719.23it/s]
Running inference on NPU...

CPU inference time: 0.227s
NPU inference time: 0.081s
Speedup: 2.81x
CPU output: ["I don't know what you're doing."]
NPU output: ["I don't know what you're doing."]
Output texts match: True
Status: PASS

Precision result saved to /data/ysws/agentsp/5-17/opus-mt_tiny_zho-eng-ascend/precision_result.json

============================================================
Creating Test Sample
============================================================
Saved test sample: /data/ysws/agentsp/5-17/opus-mt_tiny_zho-eng-ascend/test_sample.txt
  1. Ni hao, jin tian guo de zen me yang?
  2. Wo hen gao xing ren shi ni.
  3. Zi dong fan yi hen you yong.
  4. Jin tian tian qi bu cuo.

============================================================
Test Complete!
============================================================

Python API 使用示例

基本翻译

import torch
from transformers import MarianMTModel, MarianTokenizer

MODEL_DIR = "/data/ysws/agentsp/5-17/opus-mt_tiny_zho-eng/Helsinki-NLP/opus-mt_tiny_zho-eng"

tokenizer = MarianTokenizer.from_pretrained(MODEL_DIR)
model = MarianMTModel.from_pretrained(MODEL_DIR)

model = model.to("npu:0").eval()

src_texts = ["Ni hao, jin tian guo de zen me yang?"]
inputs = tokenizer(src_texts, return_tensors="pt", padding=True)
inputs = {k: v.to("npu:0") for k, v in inputs.items()}

with torch.no_grad():
    outputs = model.generate(**inputs)

translations = tokenizer.batch_decode(outputs, skip_special_tokens=True)
print(translations)

批量翻译

src_texts = [
    "Ni hao, jin tian guo de zen me yang?",
    "Wo hen gao xing ren shi ni.",
    "Zi dong fan yi hen you yong."
]

inputs = tokenizer(src_texts, return_tensors="pt", padding=True)
inputs = {k: v.to("npu:0") for k, v in inputs.items()}

with torch.no_grad():
    outputs = model.generate(**inputs)

translations = tokenizer.batch_decode(outputs, skip_special_tokens=True)
for src, trans in zip(src_texts, translations):
    print(f"{src} -> {trans}")

模型结构

  • 架构类型: MarianMT(Transformer 编码器-解码器)
  • 编码器层数: 6
  • 解码器层数: 2(tiny 版本)
  • 模型维度: 256
  • 前馈网络维度: 1536
  • 注意力头数: 8
  • 词汇表大小: 32001
组件说明
encoder6 层 Transformer 编码器
decoder2 层 Transformer 解码器(tiny)
lm_head语言模型输出头

推理参数配置

从 config.json 提取的关键参数:

{
  "model_type": "marian",
  "d_model": 256,
  "encoder_layers": 6,
  "decoder_layers": 2,
  "encoder_attention_heads": 8,
  "decoder_attention_heads": 8,
  "encoder_ffn_dim": 1536,
  "decoder_ffn_dim": 1536,
  "vocab_size": 32001,
  "max_position_embeddings": 256,
  "pad_token_id": 32000,
  "eos_token_id": 0,
  "bos_token_id": 0
}

常见问题

Q: 精度测试失败?

A: 检查 NPU 驱动是否正确安装。MarianMT 模型在 CPU 和 NPU 上的输出完全一致,验证了计算的正确性。

Q: 中文翻译质量如何?

A: tiny 版本虽然参数量小,但在基本日常对话翻译上表现良好。复杂句子可能需要 larger 模型。

Q: 如何提高翻译速度?

A: 使用批处理可以显著提高吞吐量。NPU 推理比 CPU 快 2.81 倍。

参考链接

  • 原始模型: https://huggingface.co/Helsinki-NLP/opus-mt_tiny_zho-eng
  • OPUS 项目: https://github.com/Helsinki-NLP/OPUS-MT-train
  • Marian 框架: https://marian-nmt.github.io/

许可证

本项目遵循 Apache-2.0 许可证