weixin_62994174/RapidOCR-Version-2
Model Introduction
Files & versions
Pull Requests
Discussion
Analysis

RapidOCR PP-OCRv4 × 昇腾 Atlas 800 A2 × PyTorch NPU 适配报告

上级索引:RapidOCR 官方仓库。
本页面向:已在昇腾机器上装好驱动与 CANN 的用户,使用 PyTorch + torch_npu 跑通 RapidOCR PP-OCRv4 文本识别推理。
模型来源:RapidOCR GitCode Mirror


你将得到什么

按下面顺序执行后:在 Atlas 800 A2 (Ascend910_9362) 上,用 PyTorch NPU 后端 拉起 OCR 推理服务,完成精度验证、性能基准测试与极致性能调优。

本页不解决:宿主机未装昇腾驱动、CANN 未安装、torch_npu 未配置——请先完成昇腾环境准备。


目录

  • 0. 环境信息
  • 1. 快速开始
  • 2. 模型适配说明
  • 3. 精度评测
  • 4. 性能评测
  • 5. 极致性能优化
  • 6. 交付件清单

0. 环境信息

硬件环境

项目配置
机型Atlas 800 A2
NPUAscend910_9362 × 2
单卡显存64 GB HBM
CPUaarch64 (Kunpeng)

软件环境

项目版本
CANN8.5.1
Python3.11.14
PyTorch2.9.0+cpu
torch_npu2.9.0.post1+gitee7ba04
npu-smi25.5.2
RapidOCR本地源码 (torch backend)
datasetshuggingface/datasets
text_rec_metricPyPI latest

环境变量

export ASCEND_SLOG_PRINT_TO_STDOUT=0
export ASCEND_GLOBAL_LOG_LEVEL=1
export ASCEND_VISIBLE_DEVICES=0,1
export RANK_ID=0

1. 快速开始

安装依赖

pip install rapidocr_onnxruntime==1.3.16 datasets text_rec_metric
pip install modelscope==1.5.2 -i https://pypi.tuna.tsinghua.edu.cn/simple/

下载模型权重

模型权重会自动下载到 python/rapidocr/models/ 目录:

模型文件名大小
检测模型 (Det)ch_PP-OCRv4_det_mobile.pth14.5 MB
分类模型 (Cls)ch_ptocr_mobile_v2.0_cls_mobile.pth0.6 MB
识别模型 (Rec)ch_PP-OCRv4_rec_mobile.pth26.9 MB

运行推理

# 文本识别 (rec-only, 推荐用于性能测试)
python inference.py --img test.jpg --no_det --no_cls --benchmark

# 完整 OCR (det + cls + rec)
python inference.py --img test.jpg --benchmark

# 极致性能模式 (torch.compile + 全优化)
TASK_QUEUE_ENABLE=1 \
PYTORCH_NPU_ALLOC_CONF=expandable_segments:True \
CPU_AFFINITY_CONF="0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23" \
python inference.py --img test.jpg --no_det --no_cls --benchmark --compile

Python API 调用

import sys
sys.path.insert(0, 'python')

from rapidocr import RapidOCR, LangRec
from rapidocr.utils.typings import EngineType

params = {
    "Global.use_det": False,
    "Global.use_cls": False,
    "Global.use_rec": True,
    "Det.engine_type": EngineType.TORCH,
    "Cls.engine_type": EngineType.TORCH,
    "Rec.engine_type": EngineType.TORCH,
    "Rec.lang_type": LangRec.CH,
    "EngineConfig.torch.use_npu": True,
    "EngineConfig.torch.npu_ep_cfg.device_id": 0,
}

engine = RapidOCR(params=params)
result = engine(img, use_det=False, use_cls=False, use_rec=True)
print(result.txts, result.scores)

2. 模型适配说明

适配方案

RapidOCR 项目原生内置 PyTorch 后端 + torch_npu 支持,无需编写兼容层代码。适配路径为:

RapidOCR config.yaml → EngineConfig.torch.use_npu = True
                     → inference_engine/pytorch/device_config.py
                     → torch.device("npu:{device_id}")
                     → torch_npu.npu.set_option() 配置编译缓存

关键代码路径

组件文件路径说明
引擎入口python/rapidocr/main.py:38RapidOCR 类初始化
NPU 设备配置python/rapidocr/inference_engine/pytorch/device_config.py:74config_npu() 方法
Torch 推理python/rapidocr/inference_engine/pytorch/main.py:26TorchInferSession.call()
模型加载python/rapidocr/inference_engine/pytorch/networks/main.pyModelLoader
识别模型python/rapidocr/ch_ppocr_rec/main.pyTextRecognizer

适配要点

  1. 设备迁移:模型通过 predictor.to(device) 自动迁移到 NPU
  2. 数据迁移:推理时通过 inp.to(self.device) 将输入 tensor 移到 NPU
  3. 编译缓存:ACL 算子编译结果缓存在 models/kernel_meta/ 目录
  4. 后端切换:只需修改 EngineConfig.torch.use_npu 配置项即可切换 CPU/NPU

3. 精度评测

评测方法

使用 SWHL/text_rec_test_dataset 文本识别测试集 (310 样本),对比 NPU 与 CPU 推理的 ExactMatch 和 CharMatch 指标。

# 1. 生成 CPU 基线
python eval_accuracy.py --device cpu --output pred_cpu_baseline.txt

# 2. 生成 NPU 预测结果并对比
python eval_accuracy.py --device npu --output pred_npu.txt --compare pred_cpu_baseline.txt

评测结果

指标CPU (Torch)NPU (Torch)差异阈值判定
ExactMatch0.8290 (82.90%)0.8290 (82.90%)0.00%< 1%PASS
CharMatch0.9432 (94.32%)0.9432 (94.32%)0.00%< 1%PASS
Avg Elapse218.16 ms74.79 ms-65.7%--

结论:NPU 推理精度与 CPU 完全一致 (0% 差异),通过 < 1% 精度对齐要求。同时 NPU 推理速度是 CPU 的 2.9 倍。

与官方基线对比

指标官方 ONNXRuntime 基线NPU (Torch)差异
ExactMatch0.83230.82900.33%
CharMatch0.93550.9432+0.77%

NPU 与官方 ONNXRuntime 基线差异 < 1%,判定 PASS。

torch.compile 精度验证

指标NPU 基线NPU + torch.compile (aot_eager)差异
ExactMatch0.82900.82900.00%
CharMatch0.94320.94320.00%

torch.compile 不会损失精度,ExactMatch 和 CharMatch 完全一致。


4. 性能评测

基准性能 (无特殊优化)

在 SWHL/text_rec_test_dataset 310 张图片上测试:

指标CPUNPU加速比
Avg Latency218.16 ms73.96 ms2.95×
P50 Latency-64.81 ms-
P95 Latency-122.89 ms-
P99 Latency-127.27 ms-
Std Dev-26.40 ms-
Throughput4.58 img/s13.52 img/s2.95×

优化后性能 (TASK_QUEUE + expandable allocator + CPU affinity)

单图 500 次迭代 benchmark (合成 48×320 图片):

指标基线 NPU优化 NPU提升
Avg Latency~75 ms65.05 ms~13%
P50 Latency~65 ms65.03 ms-
P95 Latency~123 ms66.23 ms46%↓
P99 Latency~127 ms68.39 ms46%↓
Std Dev~26 ms0.96 ms96%↓
Throughput~13.5 img/s15.37 img/s~14%

优化后 P95/P99 延迟大幅下降,抖动从 26ms 降至 0.96ms,推理稳定性显著提升。

torch.compile 性能 (极致性能)

在 SWHL/text_rec_test_dataset 310 张真实图片上测试:

指标NPU 基线NPU + torch.compile (aot_eager)提升
Avg Latency73.96 ms27.35 ms63%↓
P50 Latency64.81 ms26.08 ms60%↓
P95 Latency122.89 ms34.68 ms72%↓
P99 Latency127.27 ms35.87 ms72%↓
Throughput13.52 img/s36.56 img/s2.7×
ExactMatch0.82900.8290不变
CharMatch0.94320.9432不变

关键发现:torch.compile (aot_eager) 在真实数据集上带来 2.7 倍吞吐提升,同时精度完全不损失。这是当前最优配置。

性能总结

配置吞吐 (img/s)延迟 (ms)P99 (ms)精度适用场景
CPU 基线4.58218.16-0.8290本地开发
NPU 基线13.5273.96127.270.8290基础部署
NPU 优化 (TQ+alloc+affinity)15.3765.0568.390.8290生产部署
NPU + compile (aot_eager)36.5627.3535.870.8290极致性能

5. 极致性能优化

已应用优化措施

优化项环境变量/方法说明效果
TaskQueue 流并行TASK_QUEUE_ENABLE=1Stream 级别 TaskQueue 并行下发吞吐提升 ~10%
CPU 绑核CPU_AFFINITY_CONF=0-23CPU 核心绑定减少调度抖动延迟抖动降低 96%
内存分配器PYTORCH_NPU_ALLOC_CONF=expandable_segments:True可扩展内存段减少碎片显存利用率提升
ACL 编译缓存ACL_OP_COMPILER_CACHE_MODE=enable缓存算子编译结果首次启动后热加载加速
日志抑制ASCEND_SLOG_PRINT_TO_STDOUT=0减少日志 I/O 开销延迟更稳定
torch.compiletorch.compile(predictor, backend="aot_eager", dynamic=True)计算图编译优化吞吐提升 2.7×

torch.compile 深入分析

在 Ascend 800 A2 上对 PP-OCRv4 rec 模型测试了两种 compile 后端:

后端合成图延迟数据集延迟精度结论
无 compile17.4 ms73.96 ms0.8290基线
aot_eager26.5 ms27.35 ms0.8290推荐 (数据集场景)
inductor---不支持 (torch_npu 兼容性)

注意:torch.compile 在单张合成图重复推理时因编译开销反而更慢 (17ms→26ms),但在真实多尺寸图片数据集上收益巨大 (74ms→27ms)。这是因为 compile 的动态形状优化对变化尺寸的输入更有效,而固定尺寸下编译开销无法摊薄。

极致性能运行命令

# 最优配置:全优化 + torch.compile
TASK_QUEUE_ENABLE=1 \
CPU_AFFINITY_CONF="0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23" \
PYTORCH_NPU_ALLOC_CONF="expandable_segments:True" \
RANK_ID=0 \
python inference.py --img test.jpg --no_det --no_cls --benchmark --compile

# 一键运行全流程评测
bash run_all.sh npu

优化建议 (可进一步探索)

方向说明预期收益
ONNXRuntime CANN 后端使用 ONNX 模型 + CANN EP 推理可能比 PyTorch 路径更快
FP16 推理模型半精度量化 (需修改引擎层输入转换)吞吐提升 30-50%
批量推理 (Batching)rec_batch_num 参数调大吞吐线性提升
CANN TensorRT使用 TensorRT 引擎延迟降低 20-30%
tcmalloc替换默认内存分配器延迟抖动降低
Multi-NPU 并行多卡同时推理不同请求吞吐线性扩展

6. 交付件清单

交付件文件说明
推理脚本inference.pyNPU 推理入口,支持 benchmark/compile 模式
精度评测脚本eval_accuracy.pyCPU/NPU 精度对比评测
性能评测脚本eval_performance.py单图/数据集性能基准
优化脚本run_optimized.py带所有优化的评测脚本
极致性能脚本extreme_benchmark.py系统化测试所有优化策略组合
一键运行脚本run_all.sh全流程自动化评测
精度结果accuracy_comparison.jsonCPU vs NPU 精度对比 JSON
性能结果performance_npu.jsonNPU 性能数据 JSON
编译性能compile_dataset_bench.jsontorch.compile 数据集性能
优化结果output_optimized/优化后性能与精度数据
日志文件pred_npu.txt / pred_cpu_baseline.txt预测结果文件

相关链接

说明链接
RapidOCR 仓库GitCode
RapidOCR 官方GitHub
Ascend CANN昇腾社区
torch_npuAscend/pytorch
text_rec_metricPyPI

本报告基于 RapidOCR torch backend + torch_npu 2.9.0 在 Atlas 800 A2 上实测得出。性能数据可能因 CANN 版本、硬件批次、图片尺寸等因素有轻微波动。