冬
gcw_IDzXRVNw/cv_resnet50_image-classification_cc-ascend
模型介绍文件和版本Pull Requests讨论分析
下载使用量0

cv_resnet50_image-classification_cc Ascend NPU 部署指南

项目简介

cv_resnet50_image-classification_cc 是基于 ResNet50 的图像分类模型,专用于 NSFW 内容检测与分类任务。该模型将图像映射到 10 维概率向量空间,可识别 5+1 类内容(部分类别名称未知)。模型基于 ResNet50 架构,参数量约 24.6M。

特性

  • 支持 Ascend NPU 推理加速
  • CPU 与 NPU 精度对比测试(相对误差 < 1%)
  • 10 类图像内容分类
  • 标准 ResNet50 主干网络(3-4-6-3 瓶颈块)
  • 输入尺寸 224×224,采用 ImageNet 预处理方式

环境要求

  • 硬件:华为 Ascend 910 系列 NPU
  • CANN:8.0.RC1 或更高版本
  • PyTorch:2.0+ 并附带 torch_npu
  • Docker:容器名称 test-modelagent
  • 依赖库:opencv-python、numpy

目录结构

cv_resnet50_image-classification_cc-ascend/
├── inference.py          # 推理测试脚本
├── log.txt               # 测试日志
├── README.md             # 本文档
├── test_image.jpg        # 测试图片
├── inference_result.json # 推理结果
└── precision_result.json # 精度测试结果

部署步骤

1. 进入容器

docker exec -it test-modelagent bash

2. 设置环境变量

source /usr/local/Ascend/ascend-toolkit/set_env.sh

3. 准备模型文件

模型文件位于 /data/ysws/agentsp/5-19-1/cv_resnet50_image-classification_cc/ 目录下:

  • iic/cv_resnet50_image-classification_cc/pytorch_model.pt - 模型权重(约 98.5MB)

4. 安装依赖

pip install opencv-python numpy torch torch_npu

Usage

Method 1: Normal Inference Mode (NPU)

Run the inference script for image classification:

cd /data/ysws/agentsp/5-19-1/cv_resnet50_image-classification_cc-ascend/

python3 inference.py

方式二:精度测试模式(CPU vs NPU)

运行精度对比测试,验证 NPU 计算结果与 CPU 一致性:

cd /data/ysws/agentsp/5-19-1/cv_resnet50_image-classification_cc-ascend/

python3 inference.py precision_test

测试验证

精度测试结果

指标实测值阈值状态
相对误差0.02%< 1.00%PASS
类别预测一致TrueTruePASS

性能数据

操作耗时
CPU 推理时间0.4115s
NPU 推理时间4.31s
测试图片content_check.jpg

推理结果示例

输入图片预测类别置信度
content_check.jpgclass_899.96%

各类别概率分布:

类别名称概率
0pornography images0.00%
1hentai images and pornographic drawings0.00%
2sexually explicit images0.00%
3safe for work neutral images0.00%
4safe for work drawings and anime0.00%
5class_5~0.00%
6class_6~0.00%
7class_70.04%
8class_899.96%
9class_9~0.00%

结果: CPU 和 NPU 预测均为 class_8,概率均为 99.96%,完全一致

完整测试日志

============================================================
cv_resnet50_image-classification_cc - Ascend NPU Inference Test
Output: /data/ysws/agentsp/5-19-1/cv_resnet50_image-classification_cc-ascend
============================================================

Mode: PRECISION TEST
NPU available: True
Device: npu:0

============================================================
Loading Model and Test Image
============================================================
Model loaded from: /data/ysws/agentsp/5-19-1/cv_resnet50_image-classification_cc/iic/cv_resnet50_image-classification_cc/pytorch_model.pt
Using cached test image: /data/ysws/agentsp/5-19-1/cv_resnet50_image-classification_cc-ascend/test_image.jpg
Test image shape: (1914, 1305, 3)
Input tensor shape: torch.Size([1, 3, 224, 224])

============================================================
Running CPU Inference
============================================================
CPU inference time: 0.4115s
CPU class index: 8 (prob: 0.9996)

============================================================
Running NPU Inference
============================================================
NPU inference time: 4.3059s
NPU class index: 8 (prob: 0.9996)

Speedup: 0.10x

============================================================
Precision Test Results
============================================================
Max absolute error: 7.629395e-02
Max relative error: 2.459372e-04 (0.02%)
Class prediction match: True (class_8 vs class_8)
Precision test: PASS

Test image saved: /data/ysws/agentsp/5-19-1/cv_resnet50_image-classification_cc-ascend/test_image.jpg

============================================================
Test Complete!
============================================================

模型结构

  • 架构类型: ResNet50(Bottleneck)
  • 主体结构: conv1(7×7) → bn1 → relu → maxpool → layer1(3) → layer2(4) → layer3(6) → layer4(3) → avgpool → fc0(2048→512) → fc3(512→10)
  • Bottleneck: conv1(1×1, 输入→64) → conv2(3×3, 64→64) → conv3(1×1, 64→256),扩展因子=4
  • 下采样: layer1.0、layer2.0、layer3.0、layer4.0 各包含 1×1 卷积下采样支路
  • 参数量: ~24.6M
组件输出通道说明
conv1647×7,步长=2,填充=3
layer12563 个 Bottleneck,步长=1
layer25124 个 Bottleneck,步长=2
layer310246 个 Bottleneck,步长=2
layer420483 个 Bottleneck,步长=2
fc0512线性层(2048→512)
fc310线性层(512→10)

预处理参数

  • 输入尺寸: 224×224
  • 归一化: ImageNet 均值=[0.485, 0.456, 0.406],标准差=[0.229, 0.224, 0.225]
  • 通道顺序: BGR → RGB(OpenCV 读取后转换)
  • 数值范围: [0, 255] → [0, 1] → 标准化

Python API 使用示例

import cv2
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F

MODEL_WEIGHT = "/data/ysws/agentsp/5-19-1/cv_resnet50_image-classification_cc/iic/cv_resnet50_image-classification_cc/pytorch_model.pt"

MEAN = np.array([0.485, 0.456, 0.406], dtype=np.float32)
STD = np.array([0.229, 0.224, 0.225], dtype=np.float32)

def preprocess_image(img, target_size=224):
    img = cv2.resize(img, (target_size, target_size))
    img = img.astype(np.float32) / 255.0
    img = (img - MEAN) / STD
    img = img.transpose(2, 0, 1)
    img = np.expand_dims(img, axis=0)
    return img

img = cv2.imread("test.jpg")
img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
img_tensor = torch.from_numpy(preprocess_image(img_rgb)).float()

# 加载模型(需自行实现 ResNet50CC 完整结构)
model = ...  # 参见 inference.py
model = model.to("npu:0")
model.eval()

with torch.no_grad():
    output = model(img_tensor.to("npu:0"))

probs = F.softmax(output, dim=1)
prob, cls = probs.max(dim=1)
print(f"Class: {cls.item()}, Probability: {prob.item():.4f}")

常见问题

Q: 精度测试失败?

A: 检查 NPU 驱动是否正确安装,确保 CANN 环境变量已 source。0.01-0.5% 的数值误差是正常的,因为 NPU 和 CPU 使用不同的计算精度。

Q: NPU 推理比 CPU 慢?

A: 对于小模型(24.6M 参数),NPU 的启动开销(模型编译、数据传输)可能大于实际计算时间,导致测得时间比 CPU 长。这是正常现象。在实际大模型推理中 NPU 会展现显著加速优势。

Q: 如何修改测试图片?

A: 替换 test_image.jpg 文件,或修改 TEST_IMAGE_URL 变量使用其他图片 URL。

参考链接

  • 原始模型: ModelScope cv_resnet50_image-classification_cc
  • ResNet 原始论文: https://arxiv.org/abs/1512.03385
  • PyTorch 官方: https://pytorch.org/

许可证

本项目遵循原始模型许可证