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

opus-mt-da-en Ascend NPU 部署指南

项目简介

opus-mt-da-en 是 Helsinki-NLP 系列的多语言翻译模型,专门用于丹麦语(DA)到英语(EN)的翻译任务,采用 6层 Transformer 编码器 + 6层解码器架构,参数量约 74M。

特性

  • 支持 Ascend NPU 推理加速
  • CPU 与 NPU 精度对比测试(输出完全一致)
  • 丹麦语到英语翻译
  • 兼容 HuggingFace transformers
  • 支持批量翻译

环境要求

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

目录结构

opus-mt-da-en-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-1/opus-mt-da-en/Helsinki-NLP/opus-mt-da-en 目录下:

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

4. 安装依赖

pip install transformers torch_npu -i https://huaweimirror.com.cn/simple

Usage

Method 1: Normal Inference Mode

Run the inference script for translation:

cd /data/ysws/agentsp/5-17-1/opus-mt-da-en-ascend/

python3 inference.py

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

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

cd /data/ysws/agentsp/5-17-1/opus-mt-da-en-ascend/

python3 inference.py precision_test

测试验证

精度测试结果

指标实测值阈值状态
翻译一致性100%100%PASS
输出匹配TrueTruePASS

性能数据

操作耗时
CPU 推理时间2.028s
NPU 推理时间0.141s
加速比14.34x

推理结果示例

输入 (丹麦语)输出 (英语)
"Hej, hvordan har du det i dag?""Hey, how are you today?"
"Jeg er meget glad for at se dig.""I'm very happy to see you."
"Vejret er godt i dag.""The weather is good today."

结果: CPU 和 NPU 输出的翻译结果完全一致

测试日志

============================================================
OPUS-MT-DA-EN NPU Test
Model: Helsinki-NLP/opus-mt-da-en (DA → EN)
Output: /data/ysws/agentsp/5-17-1/opus-mt-da-en-ascend
============================================================

============================================================
OPUS-MT-DA-EN Inference Test (NPU)
============================================================
Device: npu:0
Model: /data/ysws/agentsp/5-17-1/opus-mt-da-en/Helsinki-NLP/opus-mt-da-en

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

Input text: ['Hej, hvordan har du det i dag?']
Input shape: torch.Size([1, 11])
Generated text: ['Hey, how are you today?']
Inference time: 0.959s

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

Loading tokenizer...

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

Loading model on NPU...
Loading weights: 100%|██████████| 258/258 [00:00<00:00, 12870.09it/s]
Running inference on NPU...

CPU inference time: 2.028s
NPU inference time: 0.141s
Speedup: 14.34x
CPU output: ['Hey, how are you today?']
NPU output: ['Hey, how are you today?']
Output texts match: True
Status: PASS

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

Python API 使用示例

基本翻译

import torch
from transformers import MarianMTModel, MarianTokenizer

MODEL_DIR = "/data/ysws/agentsp/5-17-1/opus-mt-da-en/Helsinki-NLP/opus-mt-da-en"

tokenizer = MarianTokenizer.from_pretrained(MODEL_DIR)
model = MarianMTModel.from_pretrained(MODEL_DIR)
model = model.to("npu:0")
model.eval()

src_texts = ["Hej, hvordan har du det i dag?"]
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['input_ids'], max_new_tokens=50)

translations = tokenizer.batch_decode(outputs, skip_special_tokens=True)
print(translations)  # ['Hey, how are you today?']

批量翻译

src_texts = [
    "Hej, hvordan har du det i dag?",
    "Jeg er meget glad for at se dig.",
    "Vejret er godt i dag."
]

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['input_ids'], max_new_tokens=50)

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

模型结构

  • 架构类型: MarianMT (transformer)
  • 编码器: 6 层 Transformer
  • 解码器: 6 层 Transformer
  • 隐藏层维度: 512
  • 注意力头数: 8
  • 参数量: ~74M
  • 词汇表大小: 58101

推理参数配置

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

{
  "vocab_size": 58101,
  "d_model": 512,
  "encoder_layers": 6,
  "decoder_layers": 6,
  "encoder_attention_heads": 8,
  "decoder_attention_heads": 8,
  "encoder_ffn_dim": 2048,
  "decoder_ffn_dim": 2048
}

常见问题

Q: 精度测试失败?

A: 检查 NPU 驱动是否正确安装,确保 CANN 环境变量已 source。

Q: 如何提高推理速度?

A: 使用批处理可以显著提高吞吐量。另外,首次推理会有编译开销,后续推理会更快。

Q: 模型支持哪些语言方向?

A: 本模型专门用于丹麦语到英语的翻译。如需其他语言对,请访问 Helsinki-NLP 模型库。

参考链接

  • 原始模型: https://huggingface.co/Helsinki-NLP/opus-mt-da-en
  • OPUS-MT: https://github.com/Helsinki-NLP/OPUS-MT-train
  • MarianMT: https://huggingface.co/transformers/model_doc/marian.html

许可证

本项目遵循 Apache-2.0 许可证