本文档记录 iic/nlp_structbert_sentence-similarity_chinese-tiny 在昇腾 NPU(Ascend910)环境的快速部署与验证结果。
StructBERT 句子相似度模型,基于 HuggingFace transformers 框架,支持语义文本相似度(STS)计算与句向量匹配。
相关获取地址:
参考文档:
| 组件 | 版本 |
|---|---|
torch | 2.5.1 |
torch_npu | 2.5.1 |
transformers | >=4.48.0 |
sentence-transformers | >=3.0.0 |
CANN | 8.5.RC1 |
256512PyTorch + transformerspip install transformers torch sentence-transformersimport torch
from transformers import AutoModel, AutoTokenizer
from sklearn.metrics.pairwise import cosine_similarity
import numpy as np
device = torch.device("npu:0" if torch.npu.is_available() else "cpu")
tokenizer = AutoTokenizer.from_pretrained("iic/nlp_structbert_sentence-similarity_chinese-tiny")
model = AutoModel.from_pretrained("iic/nlp_structbert_sentence-similarity_chinese-tiny")
model = model.to(device).eval()
sentences = ["今天天气很好", "今天天气不错", "明天会下雨"]
inputs = tokenizer(sentences, padding=True, truncation=True, return_tensors="pt")
inputs = {k: v.to(device) for k, v in inputs.items()}
with torch.no_grad():
outputs = model(**inputs)
embeddings = outputs.last_hidden_state.mean(dim=1)
# 计算相似度矩阵
cpu_emb = embeddings.cpu().numpy()
sim_matrix = cosine_similarity(cpu_emb)
print("相似度矩阵:\n", sim_matrix)注意:该模型权重键名前缀为
encoder.,如需直接加载需将键名替换为bert.。
python3 inference.py验证结果:
npu:0[0, 1] 范围内,语义相近句子得分高测试条件:FP32 / batch=8 / warmup=5 / timed=100 runs,Ascend910 单卡。
| 指标 | 数值 |
|---|---|
| 平均推理时间 | 2.51 ms |
| QPS(每秒查询) | 3184.78 |
| 测试次数 | 100 |
NPU 与 CPU 输出对比,使用 8 组测试句子对,分别计算 CPU 与 NPU 的句向量,对比余弦相似度与相对误差。
| 指标 | 数值 |
|---|---|
| 平均余弦相似度 | 1.0 |
| 最低余弦相似度 | 1.0 |
| 最大向量差异 | 0.002119 |
| 平均向量差异 | 0.000298 |
| 最大相对误差 | 6.46%(仅极个别近零值) |
| 结论 | PASS |
精度判定标准:NPU 与 CPU 输出的句向量平均余弦相似度 > 0.999。
pooler_output 获取句向量,部分使用 mean pooling,需根据模型类型选择