本文档记录 nbroad/ESG-BERT 在昇腾 Ascend 910B3 NPU 上的迁移适配、推理部署与精度评测结果。
ESG-BERT 是一个基于 BertForSequenceClassification 的 ESG(环境、社会和治理)文本分类模型,支持 26 个 ESG 细分维度的分类。该模型使用标准的 BERT-base 架构(12 层 Transformer,768 隐藏维),参数量约 109.5M。
本次适配工作包括:
inference.pyeval.py相关获取地址:
参考文档:
| 组件 | 版本 |
|---|---|
Python | 3.9.13 |
torch | 2.8.0+cpu |
torch_npu | 2.8.0.post4 |
transformers | 4.57.6 |
numpy | 1.24.4 |
Ascend 910B3 × 8 逻辑卡25.5.2ESG-BERT 使用标准 BERT 架构,transformers 库原生支持。NPU 适配无需修改模型结构或权重,仅需将模型和输入张量迁移到 NPU 设备。
已验证通过的适配流程:
import torch
import torch_npu
from transformers import AutoModelForSequenceClassification, AutoTokenizer
model = AutoModelForSequenceClassification.from_pretrained("nbroad/ESG-BERT")
model = model.npu() # 迁移到 NPU
model.eval()
tokenizer = AutoTokenizer.from_pretrained("nbroad/ESG-BERT")
inputs = tokenizer(["ESG text"], padding=True, truncation=True, return_tensors="pt")
inputs = {k: v.npu() for k, v in inputs.items()}
with torch.no_grad():
outputs = model(**inputs)
logits = outputs.logits.cpu()pip install torch torch_npu transformers -i https://repo.huaweicloud.com/repository/pypi/simple/
# 如 HuggingFace 网络不通,使用镜像
export HF_ENDPOINT=https://hf-mirror.com# NPU 推理(自动检测设备)
python inference.py --text "Our company reduced carbon emissions by 30%"
# 指定 CPU 推理
python inference.py --text "ESG text" --device cpu
# 从文件批量推理
python inference.py --input texts.txt
# 列出支持的所有 ESG 标签
python inference.py --list-labels快速验证 NPU 推理是否正常:
python inference.py --text "Our company reduced carbon emissions by 30% through renewable energy initiatives."预期输出:
ESG Classification Results (NPU)
--- Result 1 ---
Text: Our company reduced carbon emissions by 30% through renewable energy initiatives.
Predicted: GHG_Emissions (confidence: 0.8360)测试条件:batch_size=20,seq_len=128,float32 精度,连续 20 次取平均。
| 指标 | CPU | NPU (Ascend 910B3) |
|---|---|---|
| 平均推理时间 (20 samples) | 1318.00 ms | 22.36 ms |
| 单样本平均耗时 | 65.90 ms | 1.12 ms |
| 加速比 | 1x | 58.95x |
| 参数量 | 109.50M | 109.50M |
| 模型大小 | 417.7 MB | 417.7 MB |
使用 20 条 ESG 相关文本进行评测:
| 指标 | 数值 | 要求 | 结果 |
|---|---|---|---|
| MSE (logits) | 3.60e-6 | - | - |
| Max Absolute Error | 1.09e-2 | - | - |
| Cosine Similarity | 0.99999892 | > 0.99 | ✓ |
| Prediction Agreement | 100.00% | > 99% | ✓ |
| Mean Prob Diff (softmax) | 0.0037% | < 1% | ✓ PASS |
| Max Prob Diff (softmax) | 0.2346% | < 1% | ✓ |
结论:NPU 精度误差 0.0037%,满足精度要求(< 1%),模型在 NPU 上的推理结果与 CPU 一致。
详细评测日志见 eval_log.txt。
.safetensors / .bin 文件即可batch_size ≤ 64 以获得最佳吞吐torch_npu 版本:确保 torch_npu 版本与 torch 版本匹配(当前均为 2.8.x)HF_ENDPOINT=https://hf-mirror.com