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

opus-mt_tiny_fra-eng Ascend NPU 部署指南

项目简介

opus-mt_tiny_fra-eng 是 Helsinki-NLP 开发的小型法英机器翻译模型,基于 Transformer 架构优化后的 MarianMT 模型。该模型参数量较小(tiny 版本),适合资源受限环境,同时保持较好的翻译质量。

特性

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

环境要求

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

目录结构

opus-mt_tiny_fra-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_fra-eng/Helsinki-NLP/opus-mt_tiny_fra-eng/ 目录下:

  • model.safetensors - 模型权重 (约 51MB)
  • 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/

Usage

Method 1: Normal Inference Mode

Run the inference script for French-English translation:

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

python3 inference.py --mode inference

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

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

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

python3 inference.py --mode precision_test

Method 3: Complete Test (Inference + Accuracy)

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

python3 inference.py --mode all

命令行参数说明

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

测试验证

精度测试结果

指标实测值阈值状态
最大相对误差0.0000%< 1.00%PASS
最大绝对误差0.00e+00--
CPU 推理时间0.121s--
NPU 推理时间0.053s--
加速比2.31x> 1xPASS
输出文本一致性完全一致-PASS

性能数据

操作耗时
NPU 推理时间0.831s
精度测试 CPU 时间0.121s
精度测试 NPU 时间0.053s

翻译结果示例

输入 (法语)输出 (英语)
Bonjour, comment allez-vous?Hello, how are you?
Je suis tres content de vous voir.I am very happy to see you.
La traduction automatique est tres utile.Automatic translation is very useful.
Merci beaucoup pour votre aide.Thank you very much for your help.

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

测试日志

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

============================================================
OPUS-MT-TINY-FRA-ENG Inference Test (NPU)
============================================================
Device: npu:0
Model: /data/ysws/agentsp/5-17/opus-mt_tiny_fra-eng/Helsinki-NLP/opus-mt_tiny_fra-eng
Loading tokenizer...
Loading model...
Loading weights: 100%|██████████| 151/151 [00:00<00:00, 5131.50it/s]
Model loaded successfully
Input text: ['Bonjour, comment allez-vous?']
Input shape: torch.Size([1, 8])
Generated text: ['Hello, how are you?']
Inference time: 0.831s

Inference result saved to /data/ysws/agentsp/5-17/opus-mt_tiny_fra-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, 4482.55it/s]
Loading model on npu:0...
Loading weights: 100%|██████████| 151/151 [00:00<00:00, 4699.83it/s]
Running inference on CPU...
Running inference on NPU...
CPU inference time: 0.121s
NPU inference time: 0.053s
Speedup: 2.31x
Max absolute error: 0.000000e+00
Max relative error: 0.0000% (threshold: 1.0%)
CPU output: ['Hello, how are you?']
NPU output: ['Hello, how are you?']
Output texts match: True
Status: PASS

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

============================================================
Creating Test Sample
============================================================
Saved test sample: /data/ysws/agentsp/5-17/opus-mt_tiny_fra-eng-ascend/test_sample.txt

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

Python API 使用示例

基本翻译

import torch
from transformers import MarianMTModel, MarianTokenizer

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

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

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

src_texts = ["Bonjour, comment allez-vous?"]
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 = [
    "Bonjour, comment allez-vous?",
    "Je suis tres content de vous voir.",
    "La traduction automatique est tres utile."
]

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 上的输出完全一致,误差为 0%。

Q: tiny 和 base 模型有什么区别?

A: tiny 版本使用 2 层解码器 (vs base 的 6 层),参数量更少,适合资源受限环境。翻译质量略有下降但仍保持较好水平。

Q: 如何提高翻译速度?

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

参考链接

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

许可证

本项目遵循 Apache-2.0 许可证