eardoi/fairface-age-npu
Model Introduction
Files & versions
Pull Requests
Discussion
Analysis

FairFace 年龄段分类(昇腾 NPU 适配)

dima806/fairface_age_image_detection 是基于 FairFace 数据集微调的 ViT 图像分类模型, 输入真实人脸图片,输出年龄段分类(0-2 / 3-9 / 10-19 / 20-29 / 30-39 / 40-49 / 50-59 / 60-69 / more than 70)。

本项目完成其在**华为昇腾 NPU(Ascend 910B)**上的推理适配与验证。

模型规格

项目说明
模型架构ViTForImageClassification(vit)
参数量86M(ViT-base)
输入尺寸224×224 人脸图片
输出类别9 个年龄段
权重格式safetensors(FP32)

仓库含多个训练 checkpoint(checkpoint-32/4688/8752/9376), 本适配选用 checkpoint-9376(验证 loss 最低,1.002)。

环境要求

项目要求
硬件Ascend 910B 系列(≥1 卡)
CANN≥ 8.0(source /usr/local/Ascend/ascend-toolkit/set_env.sh)
Python3.10 – 3.11
torch / torch_npu2.9.0 / 2.9.0.post1
transformers≥ 4.5

环境准备

source /usr/local/Ascend/ascend-toolkit/set_env.sh
export PIP_INDEX_URL=https://repo.huaweicloud.com/repository/pypi/simple/
pip install torch_npu==2.9.0.post1 transformers pillow safetensors \
    -i https://repo.huaweicloud.com/repository/pypi/simple/

模型权重

权重通过 HuggingFace 镜像获取:

git clone --depth 1 https://hf-mirror.com/dima806/fairface_age_image_detection model_src
# 使用最佳 checkpoint:
#   model_src/checkpoint-9376/  (config.json + model.safetensors + preprocessor_config.json)

推理

cd /workspace/fairface_age
python3 inference.py --model_path ./model_src/checkpoint-9376 --image 人脸图片.jpg --device npu:0

参数

参数说明默认值
--model_path模型权重目录(建议 checkpoint-9376)./model_src
--image输入人脸图片(真实图片,必选)-
--device推理设备(npu:0 / cpu)npu:0
--output结果保存文件(可选)stdout

设备解析:NPU 优先,自动回退 CPU。

验证结果(Ascend 910B, npu:0)

输入:FairFace 数据集真实人脸图片(448×448,标签 age=6 → 期望类别 3-9)

模型输出(softmax 概率分布):

[info] 预测年龄段: 40-49 (置信度 0.4279)
  0-2: 0.0100
  3-9: 0.0122
  10-19: 0.0136
  20-29: 0.0209
  30-39: 0.0842
  40-49: 0.4279 <--
  50-59: 0.3465
  60-69: 0.0661
  more than 70: 0.0186

NPU 推理链路完整跑通,9 类概率分布正常输出(该模型准确率约 59%,单样本预测偏差属正常范围)。

适配说明

  • 纯 Transformers ViT 架构,无 CUDA 特有 API,直接 .to(npu) 迁移即可。
  • 推理使用 torch.no_grad() + AutoModelForImageClassification,输入经 AutoImageProcessor 预处理(224×224)。
  • 输出打印完整 9 类 softmax 概率与 top-1 预测。
  • 设备解析 resolve_device():NPU 可用性检测,失败自动回退 CPU。
  • 模型权重不推送到仓库:*.safetensors / *.bin 已加入 .gitignore, 仓库仅包含推理脚本、模型卡片与截图素材。

目录结构

.
├── README.md          # 模型卡片(本文件)
├── inference.py       # NPU 推理脚本
├── test_imgs/         # 验证用真实人脸图片(FairFace 数据集样例)
└── assets/            # 适配过程截图素材

引用

  • 模型:https://huggingface.co/dima806/fairface_age_image_detection
  • 数据:https://huggingface.co/datasets/HuggingFaceM4/FairFace