Y
gcw_hhrLdMXW/nsfw-image-detector-npu-deployment
Model Introduction
Files & versions
Pull Requests
Discussion
Analysis

nsfw_image_detector 昇腾 NPU 部署文档

1. 模型简介

模型名称: nsfw_image_detector(Freepik/nsfw_image_detector)

模型链接:

  • Hugging Face: https://huggingface.co/Freepik/nsfw_image_detector
  • AtomGit: https://ai.gitcode.com/hf_mirrors/Freepik/nsfw_image_detector

模型描述: Freepik/nsfw_image_detector 基于 timm/eva02_base_patch14_448 的 NSFW 图像安全检测模型,输出 4 级风险(neutral/low/medium/high),用于内容安全审查。

模型架构: TimmWrapperForImageClassification(eva02_base_patch14_448,448×448,4 级 NSFW 分类)

参数规模: 约 86.4M 参数。

适配引擎: 昇腾 torch_npu(torch.npu 设备接口调用 NPU)。


2. 环境依赖

依赖项版本要求说明
Python>= 3.10(推荐 3.11)本机 3.11.14
CANN Toolkit8.0.RC2+本机 8.5.1,昇腾开发套件
torch2.1.0+本机 2.9.0+cpu
torch_npu2.9.0.post1随 CANN 提供,昇腾 NPU 适配层
transformers4.57.6模型加载/预处理
safetensors0.4.3+权重加载
Pillow10+图像读取

硬件: 昇腾 Ascend910_9362(64GB HBM ×2)。

安装命令:

pip install -i https://pypi.tuna.tsinghua.edu.cn/simple \
    transformers==4.57.6 safetensors Pillow numpy
# 昇腾 NPU 组件(torch_npu / CANN / 驱动)由昇腾工具链安装

3. 推理步骤

3.1 模型资源准备

mkdir -p model
for f in config.json model.safetensors preprocessor_config.json; do
  timeout 280 curl -sSL -o "model/$f" \
    "https://hf-mirror.com/Freepik/nsfw_image_detector/resolve/main/$f?download=true"
done

3.2 检查 NPU 设备

npu-smi info
python3 -c "import torch, torch_npu; print(torch.npu.device_count())"   # 输出 2

3.3 运行推理

python3 inference.py --device npu:0
# 带性能基准
python3 inference.py --device npu:0 --benchmark

4. 测试样例及输出结果

命令:

python3 inference.py --device npu:0 --benchmark

输出:

[INFO] ========== 昇腾推理引擎 ==========
[INFO] torch      : 2.9.0+cpu
[INFO] torch_npu  : 2.9.0.post1+gitee7ba04
[INFO] NPU 可用   : True
[INFO] NPU 数量   : 2
[INFO] NPU 型号   : Ascend910_9362
[INFO] ==================================
[模型加载] 完成, 参数量 86.4M, 设备 npu:0, 耗时 1.82s

[结果] nsfw_image_detector NSFW 图像安全检测
    neutral: 99.89%
    high: 0.05%
    medium: 0.03%
    [判定] 安全

[性能基准] npu:0 warmup=3 runs=20
  平均推理时延 = 11.68 ms/张 (85.6 FPS)

结果分析: 模型在昇腾 NPU 上前向成功,任务级输出正确,确定性验证通过。


5. 注意事项

  • 推理脚本通过 torch_npu(torch.npu.is_available() / torch.device("npu:0"))调用昇腾 NPU,未检测到 NPU 时自动回退 CPU。
  • 首次前向会触发算子编译/动态追踪,计时前需预热(脚本默认 warmup=3)。
  • 权重需从 hf-mirror.com 镜像拉取(?download=true 必须),本环境无法直连 huggingface.co。