Granite-Guardian-HAP-38M 是 IBM 的 38M 参数文本分类模型,用于检测仇恨言论 (Hate Speech)、攻击性语言 (Abuse) 和不当内容。该模型基于 RoBERTa 架构,针对内容安全场景优化。
granite-guardian-hap-38m-ascend/
├── inference.py # 推理测试脚本
├── log.txt # 测试日志
├── README.md # 本文档
├── test_sample.txt # 测试样本
├── inference_result.json # 推理结果
└── precision_result.json # 精度测试结果docker exec -it test-modelagent bashsource /usr/local/Ascend/ascend-toolkit/set_env.sh模型文件位于 /data/ysws/agentsp/5-18-2/granite-guardian-hap-38m/ibm-granite/granite-guardian-hap-38m/ 目录下:
pip install transformers torch_npucd /data/ysws/agentsp/5-18-2/granite-guardian-hap-38m-ascend/
python3 inference.pycd /data/ysws/agentsp/5-18-2/granite-guardian-hap-38m-ascend/
python3 inference.py precision_test| 指标 | 实测值 | 阈值 | 状态 |
|---|---|---|---|
| 预测一致性 | True | 100% | PASS |
| 最大相对误差 | 0.0204% | < 1% | PASS |
| NPU 加速比 | 6.65x | > 5x | PASS |
| 操作 | 耗时 |
|---|---|
| CPU 推理时间 | 0.040s |
| NPU 推理时间 | 0.006s |
| 加速比 | 6.65x |
| 输入文本 | 预测类别 |
|---|---|
| "This is a hate speech example with racial slurs." | hate_speech |
| "I love you guys, you are amazing!" | neither |
| "You are such a stupid idiot." | offensive_language |
结果: CPU 和 NPU 预测完全一致,相对误差仅 0.0204%,远优于 1% 阈值
完整测试日志如下:
============================================================
Granite-Guardian-HAP-38M NPU Test
Output: /data/ysws/agentsp/5-18-2/granite-guardian-hap-38m-ascend
============================================================
============================================================
Granite-Guardian-HAP-38M Inference Test (NPU)
============================================================
Device: npu:0
Model: /data/ysws/agentsp/5-18-2/granite-guardian-hap-38m/ibm-granite/granite-guardian-hap-38m
Loading tokenizer...
Loading model...
Loading weights: 100%|██████████| 73/73 [00:00<00:00, 4742.19it/s]
[W518 07:38:59.285068581 compiler_depend.ts:164] Warning: Device do not support double dtype now, dtype cast replace with float. (function operator())
Input text: ['This is a hate speech example with racial slurs.']
Input shape: torch.Size([1, 12])
Logits: tensor([[ 2.6934, -2.8224]], device='npu:0')
Predicted class: hate_speech
Inference time: 0.235s
============================================================
Precision Test (CPU vs NPU)
============================================================
Loading model on CPU...
Loading weights: 100%|██████████| 73/73 [00:00<00:00, 4694.64it/s]
Running inference on CPU...
Loading model on NPU...
Loading weights: 100%|██████████| 73/73 [00:00<00:00, 4721.35it/s]
Running inference on NPU...
CPU inference time: 0.040s
NPU inference time: 0.006s
Speedup: 6.65x
CPU prediction: hate_speech
NPU prediction: hate_speech
Predictions match: True
Max absolute error: 5.767345e-04
Max relative error: 2.043185e-04 (0.0204%)
Status: PASS
============================================================
Creating Test Sample
============================================================
Saved test sample
1. This is a hate speech example with racial slurs.
2. I love you guys, you are amazing!
3. You are such a stupid idiot.
============================================================
Test Complete!import torch
from transformers import AutoTokenizer, AutoModelForSequenceClassification
MODEL_DIR = "/data/ysws/agentsp/5-18-2/granite-guardian-hap-38m/ibm-granite/granite-guardian-hap-38m"
tokenizer = AutoTokenizer.from_pretrained(MODEL_DIR)
model = AutoModelForSequenceClassification.from_pretrained(MODEL_DIR)
model = model.to("npu:0")
model.eval()
labels = ["hate_speech", "offensive_language", "neither"]
texts = ["This is a hate speech example with racial slurs."]
inputs = tokenizer(texts, return_tensors="pt", padding=True, truncation=True, max_length=128)
inputs = {k: v.to("npu:0") for k, v in inputs.items()}
with torch.no_grad():
outputs = model(**inputs)
predictions = torch.argmax(outputs.logits, dim=-1)
predicted_label = labels[predictions.item()]
print(f"Predicted: {predicted_label}") # "hate_speech"| 组件 | 说明 |
|---|---|
| embeddings | RoBERTa 词嵌入(vocab_size=50265) |
| encoder | 4 层 Transformer 编码器 |
| classifier | 线性分类层(576 → 3) |
从 config.json 提取的关键参数:
{
"hidden_size": 576,
"intermediate_size": 768,
"num_attention_heads": 12,
"num_hidden_layers": 4,
"vocab_size": 50265,
"problem_type": "single_label_classification",
"torch_dtype": "float32"
}A: 检查 NPU 驱动是否正确安装,确保 CANN 环境变量已 source。
A: 使用 truncation=True 和 max_length=128 参数截断超长文本。
A: 模型输出 3 个类别:hate_speech (仇恨言论)、offensive_language (攻击性语言)、neither (正常内容)。
本项目遵循 Apache-2.0 许可证