g
gcw_AVRCax4T/unirec-0.1b
模型介绍文件和版本Pull Requests讨论分析
下载使用量0

UniRec-0.1B Ascend NPU Adaptation

模型介绍 / Model Introduction

UniRec-0.1B 是一个仅 0.1B 参数量的统一识别模型(OCR),由 OpenOCR 项目开发,用于高精度文本、数学公式、中英文混合内容的识别。原始模型基于 FocalSVTR 视觉编码器 + M2M100 自回归解码器架构。

本仓库为 UniRec-0.1B 在华为昇腾 (Ascend) NPU 上的适配版本,支持基于 torch_npu 的推理部署。

  • 原始模型: topdktu/unirec-0.1b (ModelScope) / topdu/unirec-0.1b (HuggingFace)
  • 论文: UniRec-0.1B: Unified Text and Formula Recognition with 0.1B Parameters
  • 代码: OpenOCR

Ascend NPU 适配说明 / NPU Adaptation Notes

适配策略

由于原始模型 VLMOCRForConditionalGenerationNew 为自定义架构,无法直接通过 transformers.AutoModel 加载,本适配版本:

  1. 基于模型权重 (model.pth) 逆向还原了完整的模型结构定义
  2. 权重 key 命名与原始 checkpoint 完全对齐,支持直接加载
  3. 使用标准 PyTorch 算子(Conv2d, Linear, LayerNorm, BatchNorm2d, MultiheadAttention 等),天然兼容 torch_npu

模型架构

组件架构规格
Vision EncoderFocalSVTR (Focal Modulation)4 stages: dims [96,192,384,768], blocks [2,2,9,2]
DecoderM2M100 Transformer Decoder6 layers, d_model=768, heads=6, ffn=3072
VocabularySemantic-decoupled Tokenizervocab_size=56371
Total Parameters-~136M (0.1B)

算子兼容性

算子类型Ascend 兼容性说明
nn.Conv2d✅ 支持torch_npu 原生支持
nn.Linear✅ 支持torch_npu 原生支持
nn.LayerNorm✅ 支持torch_npu 原生支持
nn.BatchNorm2d✅ 支持torch_npu 原生支持
F.softmax✅ 支持torch_npu 原生支持
F.gelu✅ 支持torch_npu 原生支持
F.relu✅ 支持torch_npu 原生支持
深度可分离卷积 (groups=dim)✅ 支持torch_npu 原生支持
自定义 CUDA Kernel无模型不依赖 CUDA kernel

结论: 模型全部使用标准 PyTorch 算子,无 CUDA/Triton 依赖,对 Ascend NPU 零阻碍适配。

环境要求 / Environment Requirements

硬件要求

  • 华为 Ascend 910 系列 NPU (Atlas 800 A2/A3)
  • 驱动: Ascend Driver 25.5+
  • 固件: Ascend Firmware 25.5+

软件要求

组件版本说明
CANN8.5.1Ascend 计算架构
torch2.9.0PyTorch
torch_npu2.9.0.post1Ascend NPU 适配包
transformers>= 4.49.0HuggingFace Transformers
modelscopelatest模型下载
PIL / Pillowlatest图像处理
numpylatest数值计算

安装命令

# 安装 modelscope 用于模型下载
pip install modelscope

# 下载模型
modelscope download --model topdktu/unirec-0.1b

# 安装依赖
pip install transformers>=4.49.0 Pillow numpy

快速开始 / Quick Start

1. 下载模型与适配代码

# 下载模型权重
modelscope download --model topdktu/unirec-0.1b

# 适配代码位于本仓库
git clone <this-repo>
cd unirec_npu

2. 运行推理

import torch
import torch_npu
from modeling_unirec import VLMOCRForConditionalGenerationNew
from PIL import Image
import numpy as np

# 加载模型
model = VLMOCRForConditionalGenerationNew.from_pretrained_checkpoint(
    "/path/to/unirec-0.1b/model.pth"
)
model = model.to("npu:0")
model.eval()

# 预处理图像
def preprocess(image_path, size=(224, 224)):
    img = Image.open(image_path).convert("RGB").resize(size, Image.BICUBIC)
    arr = np.array(img, dtype=np.float32) / 255.0
    arr = (arr - [0.485, 0.456, 0.406]) / [0.229, 0.224, 0.225]
    return torch.from_numpy(arr).permute(2, 0, 1).unsqueeze(0)

# 推理
pixel_values = preprocess("path/to/image.png").to("npu:0")
with torch.no_grad():
    output_ids = model.generate(pixel_values, max_length=256)
    
# 解码输出
from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained(
    "/opt/atomgit/.cache/modelscope/hub/models/topdktu/unirec-0___1b",
    trust_remote_code=True
)
result = tokenizer.decode(output_ids[0], skip_special_tokens=True)
print(result)

3. 命令行推理

cd /opt/atomgit/unirec_npu
python inference.py --image /path/to/image.png --device npu

4. 运行完整评测

python inference.py --benchmark

精度评测 / Accuracy Evaluation

评测方法

使用 inference.py 对比 NPU 与 CPU 上的前向推理输出 Logits:

  • 数据: Demo 图像集 (来自原始模型仓库)
  • 指标: 最大相对误差 (Max Relative Error), 余弦相似度 (Cosine Similarity)
  • 标准: 最大相对误差 < 1%

评测结果

测试图像最大绝对误差最大相对误差余弦相似度结果
Snipaste_2025-04-13_21-11-35.png0.1277310.384%0.99999994✅ PASS
Snipaste_2025-04-13_21-51-45.png0.1464420.466%0.99999177✅ PASS

结论: NPU 推理结果与 CPU 基准高度一致,最大相对误差 0.466%,远低于 1% 阈值,精度验证 通过。

性能评测 / Performance Benchmark

评测方法

使用 inference.py --benchmark 进行端到端推理延迟测试(含 warmup):

  • 测试环境: Ascend 910 9362 × 2
  • 测试配置: 输入 224×224 图像, 最大生成长度 32 tokens
  • 指标: 平均推理延迟

评测结果

设备图像平均延迟中位延迟标准差
NPU (Ascend 910)Image 1191.46 ms190.73 ms5.86 ms
NPU (Ascend 910)Image 2192.08 ms191.28 ms3.37 ms
CPU (基准)Image 114449.09 ms14171.78 ms946.27 ms
CPU (基准)Image 214861.00 ms14355.69 ms1362.42 ms

性能分析

指标数值
NPU 平均延迟~192 ms
CPU 平均延迟~14,655 ms
NPU/CPU 加速比~76×

文件结构 / File Structure

unirec_npu/
├── modeling_unirec.py      # 模型结构定义 (FocalSVTR + M2M100 Decoder)
├── inference.py            # NPU 推理与评测脚本
├── README.md               # 本文档 (部署与评测报告)
├── output/
│   ├── evaluation_results.json  # 评测结果 (JSON)
│   └── evaluation.log           # 运行日志
└── screenshot/
    └── evaluation_pass.png      # 自验证截图

交付件清单 / Deliverables

交付件文件说明
✅ 推理脚本inference.pyNPU-adapted inference + evaluation
✅ 模型定义modeling_unirec.py完整模型结构定义 (FocalSVTR + Decoder)
✅ 部署文档README.md本文档
✅ 精度评测源码inference.py (含 compare_outputs 函数)自动对比 NPU vs CPU
✅ 自验证截图output/screenshots/运行结果截图
✅ 运行日志output/evaluation.log完整评测日志
✅ 模型卡片YAML frontmatter (见文件顶部)#NPU #Hardware 标签

已知限制 / Known Limitations

  1. 图像预处理: 当前使用标准 ImageNet 归一化,原始 OpenOCR 可能有特定的预处理流程(如动态尺寸、特定的归一化参数),实际 OCR 效果建议参照原始 OpenOCR 推理流程
  2. Token 解码: UniRec 使用语义解耦 Tokenizer (semantic-decoupled tokenizer),标准解码可能不完全匹配原始输出
  3. 批量推理: 当前脚本支持 batch=1 推理,多 batch 可通过调整 pixel_values 的第一个维度实现
  4. 输入尺寸: 当前固定 224×224 输入,原始模型支持动态尺寸 [w, h] 输入

引用 / Citation

@article{du2025unirec,
  title={UniRec-0.1B: Unified Text and Formula Recognition with 0.1B Parameters},
  author={Yongkun Du and Zhineng Chen and Yazhen Xie and Weikang Bai and Hao Feng and Wei Shi and Yuchen Su and Can Huang and Yu-Gang Jiang},
  journal={arXiv preprint arXiv:2512.21095},
  year={2025}
}

License

Apache License 2.0


模型适配: 基于 Ascend NPU (torch_npu 2.9.0) + CANN 8.5.1 完成 适配日期: 2026-05-20