本文档记录 rizvandwiki/gender-classification 性别分类模型在昇腾 NPU(Ascend 910B3)上的迁移适配、精度评测与性能验证结果。
该模型基于 ViT(Vision Transformer,12 层,768 维)在人脸数据集上微调,支持二分类:female(女性)和 male(男性)。输入为 224×224 RGB 人脸图像,通过 AutoImageProcessor 进行 resize + normalize 预处理,输出 2 维 softmax 概率分布。
模型属于轻量级 ViT 二分类器,适用于人脸属性分析、人口统计等应用场景。与多分类模型不同,二分类结构使推理效率更高。
相关获取地址:
| 组件 | 版本 |
|---|---|
torch | 2.8.0 |
torch_npu | 2.8.0.post4 |
transformers | 5.8.1 |
CANN | 8.5.1 |
8 × Ascend 910B3conda create -n rizvandwiki--gender-classification python=3.11 -y
conda activate rizvandwiki--gender-classification
pip install torch==2.8.0 torch_npu==2.8.0.post4 \
-i https://pypi.tuna.tsinghua.edu.cn/simple
pip install transformers torchvision pillow numpy \
-i https://pypi.tuna.tsinghua.edu.cn/simplepython inference.py --image face.jpg --device npu
python inference.py --image_dir ./faces/ --device npu编程接口:
from inference import AgeClassifier as GenderClassifier
clf = GenderClassifier(
model_path="./rizvandwiki--gender-classification", device="npu"
)
results = clf.predict(["face.jpg"])
# results[0] → {'female': 0.92, 'male': 0.08}python inference.py --image face.jpg --device npu预期输出:female 和 male 两种标签的概率值(和为 1.0),预测概率最高者为首选,无运行时错误。模型目录含示例图片(images/),可用于快速验证。
测试条件:10 张合成 224×224 图像(固定随机种子),batch_size=8,NPU 预热 1 轮。
| 指标 | 数值 |
|---|---|
| CPU 吞吐量 | 3.6 img/s |
| NPU 吞吐量 | 247.9 img/s |
| CPU/NPU 加速比 | 68.3 × |
ViT-base 在 NPU 上获得极高加速比(68×),主要得益于 NPU 对 Transformer 注意力算子的深度优化。二分类结构(2 维输出)进一步提升推理效率。
分别在 CPU 和 NPU 上推理 10 张合成图像(固定随机种子保证输入一致),比较 softmax 概率向量的余弦相似度、MAE 和 Top-1 分类一致性。
| 指标 | 数值 |
|---|---|
| 平均余弦相似度 | 1.000000 |
| MAE | 0.000096 |
| 精度误差率 | 0.0000% |
| Top-1 准确率 | 100.0% |
结论:精度误差率 0.0000%,NPU 与 CPU 输出完全一致,评测通过。
from_pretrained 自动兼容images/)和训练日志(runs/)AutoModelForImageClassification.from_pretrained() 加载model.to("npu:0") 一步迁移,ViT 的 Transformer 和 Patch Embedding 算子 NPU 原生支持AutoImageProcessor 在 CPU 完成图像预处理(resize 到 224×224 + ImageNet 标准化).to("npu:0") 转移至 NPU.cpu().numpy() 返回;二分类只需比较两个概率值即可决策import torch, torch_npu
from PIL import Image
from transformers import AutoImageProcessor, AutoModelForImageClassification
model = AutoModelForImageClassification.from_pretrained(
"gender-classification"
).to("npu:0")
processor = AutoImageProcessor.from_pretrained("gender-classification")
image = Image.open("face.jpg").convert("RGB")
inputs = processor(images=image, return_tensors="pt")
inputs = {k: v.to("npu:0") for k, v in inputs.items()}
with torch.no_grad():
outputs = model(**inputs)
probs = torch.softmax(outputs.logits, dim=-1)
gender = model.config.id2label[int(torch.argmax(probs))]
confidence = float(torch.max(probs))images/)可用作输入格式参考。from_pretrained 自动兼容。与 safetensors 相比,加载速度略慢但功能等价。