weixin_72661020/nlp_structbert_emotion-classification_chinese-tiny
模型介绍文件和版本Pull Requests讨论分析

iic/nlp_structbert_emotion-classification_chinese-tiny on Ascend NPU

1. 简介

本文档记录 iic/nlp_structbert_emotion-classification_chinese-tiny 在昇腾 Ascend910 环境的适配、验证与部署结果。

nlp_structbert_emotion-classification_chinese-tiny 是一个基于 StructBERT 的中文情感分类模型,参数量 33.5M,支持 7 类情感的多标签分类:

  • 恐惧、愤怒、厌恶、喜好、悲伤、高兴、惊讶

模型轻量小巧(hidden_size=256, 4 层 Transformer),非常适合边缘部署和实时推理场景。

相关获取地址:

  • 权重下载地址(ModelScope):https://modelscope.cn/models/iic/nlp_structbert_emotion-classification_chinese-tiny
  • 框架:PyTorch + transformers + torch_npu

2. 验证环境

组件版本
NPUAscend910 (64GB HBM)
CANN8.5.1
PyTorch2.9.0
torch_npu2.9.0 (CANN 8.5.1)
transformers4.25.1 (最低)
Python3.11.14
  • NPU:Ascend910 逻辑卡
  • 模型路径:~/iic/nlp_structbert_emotion-classification_chinese-tiny/model/iic/nlp_structbert_emotion-classification_chinese-tiny

3. 模型推理

由于该模型为 BERT 分类模型(非生成式模型),直接使用 transformers 库加载推理,无需启动 vLLM 服务。

import torch
from transformers import AutoModelForSequenceClassification, AutoTokenizer

device = "npu:0" if hasattr(torch, "npu") and torch.npu.is_available() else "cpu"
model_dir = "~/iic/nlp_structbert_emotion-classification_chinese-tiny/model/iic/nlp_structbert_emotion-classification_chinese-tiny"

tokenizer = AutoTokenizer.from_pretrained(model_dir)
model = AutoModelForSequenceClassification.from_pretrained(model_dir, torch_dtype=torch.float32)
model = model.to(device)
model.eval()

text = "今天天气真好,心情非常愉快!"
inputs = tokenizer(text, return_tensors="pt", padding=True, truncation=True, max_length=128)
inputs = {k: v.to(device) for k, v in inputs.items()}

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

probs = torch.sigmoid(outputs.logits)  # multi_label_classification
id2label = {0: "恐惧", 1: "愤怒", 2: "厌恶", 3: "喜好", 4: "悲伤", 5: "高兴", 6: "惊讶"}
for i, prob in enumerate(probs.cpu().numpy()[0]):
    print(f"{id2label[i]}: {prob:.4f}")

4. Smoke 验证

直接运行推理脚本:

cd ~/iic/nlp_structbert_emotion-classification_chinese-tiny
python3 inference.py

预期输出(部分示例):

--- Input: 今天天气真好,心情非常愉快! ---
  高兴: 0.8448
  喜好: 0.0879
  Predicted emotions: ['高兴']

5. 性能参考

测试条件:单样本推理,batch_size=1,max_length=128。

指标数值
平均推理延迟2.56 ms
P50 延迟2.55 ms
P90 延迟2.63 ms
吞吐量340 samples/sec
模型参数量33.5M
模型大小33.5 MB (pytorch_model.bin)

文本长度对延迟影响极小(短/中/长文本差异 < 0.1ms),表明模型推理主要由计算开销决定而非 IO。

6. 精度评测

使用 10 个自定义中文情感测试用例进行评估(多标签分类,sigmoid 阈值 0.5)。

指标数值
平均精度 (Accuracy@0.5)0.40
测试用例数10
情感类别数7

典型正确分类:

  • "今天天气真好,心情非常愉快!" -> 高兴 (84.5%)
  • "我失去了最好的朋友,太难过了。" -> 悲伤 (72.8%)
  • "听到这个消息,我感到非常震惊。" -> 惊讶 (52.2%)

注:多标签分类中当多个情感同时存在时,单一预测可能无法覆盖所有标签,实际使用时建议降低阈值或人工校验。

7. 注意事项

  • 该模型使用 multi_label_classification 问题类型,输出层使用 sigmoid 激活函数
  • 默认分类阈值为 0.5,可根据实际业务场景调整
  • 模型使用 StructBERT 架构(阿里达摩院),与标准 BERT 兼容
  • 推理时建议在 NPU 上进行,CPU 推理延迟可能高出 10-50 倍
  • 该 tiny 模型非常适合延迟敏感或资源受限的场景
下载使用量0