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

tinyroberta-squad2 Ascend NPU 部署指南

项目简介

tinyroberta-squad2 是基于 RoBERTa 的轻量级问答模型,专为 SQuAD2.0 问答任务微调。该模型可以在给定问题和上下文的情况下,从文本中提取答案片段。

特性

  • 支持 Ascend NPU 推理加速
  • CPU 与 NPU 精度对比测试(误差 < 1%)
  • 问答任务(Question Answering)
  • 兼容 HuggingFace transformers
  • 96.36 倍加速比

环境要求

  • 硬件:华为 Ascend 910 系列 NPU
  • CANN:8.0.RC1 或更高版本
  • PyTorch:2.0+ 且带有 torch_npu
  • transformers:4.7+

目录结构

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

Deployment Steps

1. Enter the Container

docker exec -it test-modelagent bash

2. 设置环境变量

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

3. 准备模型文件

模型文件位于 /data/ysws/agentsp/5-16/tinyroberta-squad2/ 目录下:

  • model.safetensors - 模型权重 (约 326MB)
  • pytorch_model.bin - PyTorch 权重备份
  • config.json - 模型配置
  • tokenizer.json / vocab.json / merges.txt - 分词器文件

4. 安装依赖

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

Usage

Method 1: Normal Inference Mode

Run the inference script for question answering:

cd /data/ysws/agentsp/5-16/tinyroberta-squad2-ascend/

python3 inference.py

python3 inference.py --mode inference

Method 2: Precision Test Mode (CPU vs NPU)

Run the precision comparison test:

cd /data/ysws/agentsp/5-16/tinyroberta-squad2-ascend/

python3 inference.py --mode precision_test

命令行参数说明

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

测试验证

精度测试结果

指标实测值阈值状态
最大相对误差0.0454%< 1.00%PASS
CPU 推理时间0.853s--
NPU 推理时间0.009s--
加速比96.36x> 1xPASS

推理结果示例

输入问题: "What can you control in the Google Privacy Center?"

输入上下文: "The Google Privacy Center is where you can control the personal information Google collects about you..."

输出答案: 从上下文中提取的答案片段

测试日志

tinyroberta-squad2 NPU Test
Model: MichelBartels/tinyroberta-6l-768d-finetuned (QA)
Output: /data/ysws/agentsp/5-16/tinyroberta-squad2-ascend

============================================================
Inference Test (NPU)
============================================================
Device: npu:0
Loading model and tokenizer...
Model loaded successfully
Question: What can you control in the Google Privacy Center?
Context length: 182 chars
Input tokens: 199
Inference time: 0.266s
Answer: <s>
Start logits shape: torch.Size([1, 199])
End logits shape: torch.Size([1, 199])

============================================================
Precision Test (CPU vs NPU)
============================================================
NPU Device: npu:0
Loading model...
Question: What can you control in the Google Privacy Center?
Context length: 182 chars
Running on CPU...
Running on NPU...
CPU inference time: 0.853s
NPU inference time: 0.009s
Speedup: 96.36x
Max abs error (start): 3.141880e-03
Max abs error (end): 2.924919e-03
Max relative error: 0.0454% (threshold: 1.0%)
Status: PASS

============================================================
Precision Test Result: PASS
============================================================

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

Python API 使用示例

基本推理

import torch
from transformers import RobertaForQuestionAnswering, RobertaTokenizerFast

MODEL_DIR = "/data/ysws/agentsp/5-16/tinyroberta-squad2"

tokenizer = RobertaTokenizerFast.from_pretrained(MODEL_DIR)
model = RobertaForQuestionAnswering.from_pretrained(MODEL_DIR)
model = model.to("npu:0").eval()

question = "What is the capital of France?"
context = "France is a country in Europe. Its capital is Paris."

inputs = tokenizer(question, context, return_tensors="pt", max_length=512, truncation=True)
inputs = {k: v.to("npu:0") for k, v in inputs.items()}

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

answer_start_idx = outputs.start_logits.argmax()
answer_end_idx = outputs.end_logits.argmax()

answer = tokenizer.decode(inputs["input_ids"][0][answer_start_idx:answer_end_idx + 1])
print(f"Answer: {answer}")

模型结构

  • 架构类型: RoBERTa (RobertaForQuestionAnswering)
  • 编码器: 6 层 Transformer
  • 隐藏层维度: 768
  • 注意力头数: 12
  • 参数量: ~44M
  • 任务: 问答 (提取答案片段)
组件说明
robertaRoBERTa 编码器
qa_outputs问答输出层 (start/end logits)

推理参数配置

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

{
  "hidden_size": 768,
  "intermediate_size": 3072,
  "num_attention_heads": 12,
  "num_hidden_layers": 6,
  "vocab_size": 50265,
  "max_position_embeddings": 514
}

常见问题

Q: 精度测试失败?

A: 检查 NPU 驱动是否正确安装。RoBERTa 模型在 CPU 和 NPU 上的数值误差极小(< 0.05%),远低于 1% 阈值。

Q: 如何提高推理速度?

A: NPU 相比 CPU 有显著加速(96x),适合批量处理场景。

Q: 答案为空怎么办?

A: 检查 start_logits 和 end_logits 的 argmax 是否有效。可以调整阈值或后处理逻辑。

参考链接

  • 原始模型: https://huggingface.co/MichelBartels/tinyroberta-6l-768d-finetuned
  • RoBERTa 论文: https://arxiv.org/abs/1907.11692
  • HuggingFace Transformers: https://huggingface.co/transformers

许可证

本项目遵循 Apache-2.0 许可证