本文档记录 StructBERT 中文句对相似度模型在昇腾 NPU (Ascend 910B3) 上的迁移适配与精度验证结果。
该模型基于 StructBERT-tiny 架构(4 层 Transformer,256 维隐层),通过句对匹配训练实现中文句子级别的语义相似度判断。与 nlp_corom_sentence-embedding_chinese-tiny 共享相同的 BERT-tiny 结构,差异在于 checkpoint 权重键名使用 encoder. 前缀,加载时需剥离。
相关获取地址:
参考文档:
| 组件 | 版本 |
|---|---|
CANN | 8.5.1 |
torch | 2.8.0 |
torch_npu | 2.8.0.post4 |
transformers | latest |
modelscope | 1.37.0 |
Ascend 910B3,单卡推理[1, seq_len, 256] 隐层表示conda create -n nlp_structbert_similarity python=3.10 -y
conda activate nlp_structbert_similarity
pip install torch==2.8.0 torch_npu==2.8.0.post4 \
-i https://mirrors.huaweicloud.com/repository/pypi/simple \
--trusted-host mirrors.huaweicloud.com
pip install transformers modelscope numpymodelscope download --model damo/nlp_structbert_sentence-similarity_chinese-tiny \
--local_dir ./nlp_structbert_sentence-similarity_chinese-tinypython inference.py --text "测试文本" --device npufrom inference import run_inference
result = run_inference("这是一段测试文本", device="npu")
print(f"向量维度: {result['embedding'].shape}, 耗时: {result['time_ms']:.1f}ms")python evaluate.py验证结果:
[1, seq_len, 256]测试条件:输入中文短句。
| 指标 | CPU | NPU (Ascend 910B3) |
|---|---|---|
| 推理耗时 | 265 ms | 6 ms |
| 加速比 | — | 43x |
对比 CPU (PyTorch) 与 NPU (torch_npu) 在相同输入下 BERT 模型的 last_hidden_state 输出。
| 指标 | 数值 |
|---|---|
| 输出形状 | [1, 6, 256] |
| 鲁棒平均相对误差 | 0.160% |
| 精度要求 | 平均相对误差 < 1% |
| 精度评测 | 通过 |
encoder. 前缀,需剥离后加载到 HuggingFace BertModelclassifier 权重,本适配仅使用 encoder 部分进行句向量提取