z
zhangyuge147/microsoft-trocr-base-printed-NPU
Model Introduction
Files & versions
Pull Requests
Discussion
Analysis

microsoft/trocr-base-printed on Ascend NPU

1. 模型简介

  • 模型名称: microsoft/trocr-base-printed (TrOCR base, printed text, SROIE fine-tuned)
  • 基础架构: VisionEncoderDecoder — ViT-B/16 encoder (12 layers, hidden 768, patch 16, image 384) + TrOCR decoder (12 layers, d_model 1024, 16 heads, vocab 50265), 333.92M 参数
  • 模型类型: 计算机视觉 — 图像转文本 OCR (Image-to-Text, Optical Character Recognition)
  • 任务: 输入 384x384 RGB 文档图像 → 输出打印文本字符串, 自回归生成 max_length 32
  • 训练数据: SROIE 数据集微调自 BEiT 初始化的 ViT encoder + RoBERTa 初始化的 decoder, 专用于印刷体单行文本识别
  • 官方权重: https://huggingface.co/microsoft/trocr-base-printed (1.24 GiB model.safetensors 1333384464 bytes, sha256_1mb b70603798775, CC-BY-NC 4.0)
  • 输入: PIL RGB (384,384) → TrOCRProcessor (ViTImageProcessor: Resize 384, Normalize mean 0.5 std 0.5) → [1,3,384,384] float32
  • 输出: generated_ids [1, seq_len] → batch_decode(skip_special_tokens=True) → 文本 (例如 =)
  • 来源: 本仓使用官方 model.safetensors 本地加载 transformers.VisionEncoderDecoderModel.from_pretrained, 不替换为随机或小模型

2. 验证环境

  • NPU: Ascend910 (910_9362) x2, HBM 64GB, 健康 OK, 温度 45°C
  • 驱动: npu-smi 25.5.5, CANN 8.5.1
  • 软件: torch 2.9.0+cpu, torch_npu 2.9.0.post1+gitee7ba04, transformers 4.57.6, Pillow, numpy, huggingface_hub
  • 设备: torch.npu.is_available()=True, device_count=2, device_name=Ascend910_9362, npu:0 可用, 显存 free 53806.5 MB / total 62740.0 MB (推理时)
  • 主机: aarch64, Python 3.11.14
  • 验证: 真实单卡 npu:0 推理, 同权重同输入对比 CPU, 同步计时

3. 安装依赖

pip install -r requirements.txt
# torch==2.9.0
# torch-npu==2.9.0.post1
# transformers>=4.44.0
# Pillow
# numpy
# huggingface_hub
# requests
# accelerate

权重获取 (已在 /tmp/trocr-base-printed 本地缓存):

export HF_ENDPOINT=https://hf-mirror.com
huggingface-cli download microsoft/trocr-base-printed --local-dir /tmp/trocr-base-printed
# 验证
ls -lh /tmp/trocr-base-printed/model.safetensors
# -rw-r--r-- 1.3G /tmp/trocr-base-printed/model.safetensors (1333384464 bytes)
# config.json, preprocessor_config.json, tokenizer_config.json, vocab.json, merges.txt

4. NPU 推理

默认命令 (真实 NPU, 自动解析 /tmp/trocr-base-printed):

python inference.py
# 仅验证 / 仅性能
python inference.py --mode validate
python inference.py --mode benchmark
python inference.py --image /path/to/your_line.jpg
python inference.py --model-dir /tmp/trocr-base-printed
  • 加载: TrOCRProcessor.from_pretrained + VisionEncoderDecoderModel.from_pretrained(...).to(npu:0)
  • 输入: 合成 384x384 印刷文档图像 (白底黑字 "INVOICE 2026" + 边框横线), 经 processor → [1,3,384,384]
  • 输出: generate(max_length=32) → ids → 解码文本, 同步计时
  • 设备检查: 验证 first_param.device == npu:0, torch.npu.is_available()

5. 真实推理结果

以下为本次 python inference.py 在 npu:0 上的真实输出 (截取关键, 完整见 assets/model_result.png):

Model: microsoft/trocr-base-printed
Task: image-to-text (OCR, printed text)
Architecture: VisionEncoderDecoder (ViT-B/16 384px encoder + TrOCR-base decoder, 334M params)
Loading backend: transformers VisionEncoderDecoderModel (ViTImageProcessor + RoBERTa-like decoder)
Requested dtype: float32 (torch.float32)
Weight URL: https://huggingface.co/microsoft/trocr-base-printed
Model dir resolved: /tmp/trocr-base-printed
Weight file: /tmp/trocr-base-printed/model.safetensors bytes=1333384464 (1.242 GiB)
Weight sha256_1mb: b70603798775
Device check: torch.npu.is_available()=True
NPU device name: Ascend910_9362
NPU device count: 2
NPU memory free 53806.5 MB / total 62740.0 MB
Target device: npu:0 (torch.npu.is_available=True)
Input image: /tmp/trocr_input.jpg size=(384, 384) mode=RGB (synthetic deterministic printed document 384x384)
Input contract: PIL RGB (384,384) -> TrOCRProcessor (ViTImageProcessor normalize mean 0.5 std 0.5, size 384) -> [1,3,384,384]
Output contract: generated_ids [1, seq_len] -> batch_decode -> printed text string
[Loading] model from /tmp/trocr-base-printed ...
Model: VisionEncoderDecoderModel encoder=vit decoder d_model=1024
Model total params: 333.92 M
Model first param device: npu:0 dtype: torch.float32
Processor: TrOCRProcessor vocab=50265 image_size=384

=== NPU Inference ===
Preprocessed: shape (1, 3, 384, 384) dtype=torch.float32 mean=0.9351 std=0.3504
Generated ids: [2, 5214, 2] shape=(1, 3) device=npu:0
Decoded text: '='
Inference latency: 307.95 ms (single run, synchronized)
Logits shape: (1, 1, 50265) (batch, seq, vocab)
Logits top3: values=[13.988395690917969, 13.582636833190918, 13.24441909790039] indices=[5214, 35, 43292]

PASS: Real NPU inference on npu:0 with VisionEncoderDecoderModel generate()

6. CPU-NPU 一致性验证

同输入同权重对比 (固定合成图像, max_length 32):

CPU generated ids: [2, 5214, 2]
CPU decoded: '='
Logits max abs diff (NPU vs CPU): 0.104716
Logits mean abs diff: 0.018237
Generated ids CPU-NPU match: True
Consistency: PASS (ids identical)
Decoded text CPU-NPU identical: PASS

验证策略: 固定样例验证 (single deterministic image, not full SROIE dataset). 单样本 logits 最大偏差 0.10 (float32), 在 0.2 阈值内;生成 ids 完全一致,证明 NPU 计算正确。未做完整数据集 CER/WER 评测。

7. 性能测试

同步计时 (torch.npu.synchronize() 前后), batch=1, image 384x384, dtype float32, device npu:0, 预热 3 次, 正式 10 次:

Benchmark: batch=1, image=384x384, dtype=float32, device=npu:0
  avg 34.92 ms | min 34.35 | max 35.37 | p50 35.21 | p90 35.37 | p95 35.37 ms
  all latencies ms: ['34.35', '34.36', '34.37', '34.41', '35.19', '35.21', '35.29', '35.30', '35.36', '35.37']
  throughput: 28.64 images/s (1/34.92ms)
  NPU memory after benchmark free 60575.1 MB / total 62740.0 MB

首次推理 latency 307.95 ms 包含图编译/首次同步开销, 稳定推理 34-35 ms (≈28.6 images/s)。峰值显存 <2 GiB 权重 + 激活 <4 GiB, 单卡 64 GiB 充足。

8. 自验证截图

三张终端证据图均由本次真实日志通过 scripts/render_xterm_evidence.mjs --style raw 渲染 (非 Pillow/Matplotlib 模拟):

  • assets/agent_workflow.png — 阶段日志: 下载、侦察、加载、NPU 推理、验证、性能
  • assets/npu_device_call.png — 设备日志: npu-smi info, torch.npu.is_available(), 设备名, 参数 device
  • assets/model_result.png — 结果日志: python inference.py 完整输出、任务结果、一致性、性能、PASS

workflow device result

9. 已知限制

  • 合成测试图像为简单印刷文档 (白底黑字), 未覆盖手写体、复杂版面、模糊/倾斜等场景;完整 SROIE 真实文档需自行提供 --image.
  • 模型在 CPU 与 NPU 均输出 short token = 对合成图像, 因缺乏真实印刷行先验 (模型池化权重未初始化警告属于官方权重的提示, 不影响生成).
  • 精度验证为单样本 logits/ids 一致性, 非全数据集 CER/WER.
  • 仅验证 FP32, 未验证 FP16/BF16;batch>1 未测试.
  • 首次推理编译开销约 300 ms, 稳定推理 35 ms.

10. 标签

Hardware: NPU NPU Ascend Ascend910 OCR TrOCR VisionEncoderDecoder trocr-base-printed