waylong/microsoft-trocr-small-handwritten-NPU
Model Introduction
Files & versions
Pull Requests
Discussion
Analysis

microsoft/trocr-small-handwritten on Ascend NPU

1. 模型简介

  • 模型名称: microsoft/trocr-small-handwritten
  • 模型权重URL: https://huggingface.co/microsoft/trocr-small-handwritten
  • 任务类型: 计算机视觉 - 手写OCR (image-to-text)
  • 架构: VisionEncoderDecoderModel (Encoder: deit ViT, Decoder: trocr Transformer, 12层 encoder + 6层 decoder)
  • 权重格式: pytorch_model.bin (245 MB) + sentencepiece.bpe.model (1.3 MB)
  • 预处理器: TrOCRProcessor = DeiTImageProcessor (size 384x384, normalize mean 0.5 std 0.5) + XLMRobertaTokenizer (vocab 64002)
  • 生成配置: bos_token_id=0, eos_token_id=2, pad_token_id=1, max_length=20, use_cache=False
  • 输入契约: pixel_values shape [B,3,384,384] float32, normalized to [-1,1]
  • 输出契约: generated_ids shape [B, seq_len] + decoded text string, encoder.last_hidden_state shape [B,578,384]

模型在 IAM 手写数据集上微调,用于手写文本行识别。默认 fp32 推理。

2. 验证环境

  • NPU: Ascend910_9362 (Ascend910B) x2, 单卡验证 npu:0 (Phy 14, Bus 0000:0A:00.0)
  • CANN: 8.5.1 / npu-smi 25.5.5
  • torch: 2.9.0+cpu | torch_npu: 2.9.0.post1+gitee7ba04 | torch.npu.is_available()=True | device_count=2
  • NPU 显存: 64 GiB (total 61.27 GiB via mem_get_info, free ~60 GiB)
  • transformers: 4.44.2, Pillow, sentencepiece
  • 本地权重目录: /data/.cache/models/microsoft/trocr-small-handwritten (snapshot_download)
  • 权重内存估算: ~0.23 GiB (FP32), 峰值 <2 GiB (batch 1, 384x384)

3. 安装依赖

pip install -r requirements.txt
# requirements.txt 包含:
# torch="=2.9.0"
# torch_npu="=2.9.0.post1"
# transformers="=4.44.2"
# Pillow>=9.0
# sentencepiece
# accelerate

4. NPU 推理

默认命令(真实 NPU 推理,已验证 npu:0):

python inference.py

其他模式:

# CPU-NPU 一致性验证 + 性能预热测试
python inference.py --mode validate

# 纯性能压测(10次正式 + 3次预热,同步计时)
python inference.py --mode benchmark

模型自动从本地缓存 /data/.cache/models/microsoft/trocr-small-handwritten 加载,无需运行时下载。

5. 真实推理结果

固定可复现输入:PIL 合成图像 384x384 白底黑字,文本 hello world 位于 (50,150),经 TrOCRProcessor 处理得到 pixel_values [1,3,384,384] (float32, range [-1,1]).

默认 NPU 推理 (python inference.py, FP32, npu:0):

[INPUT] pixel_values shape: torch.Size([1, 3, 384, 384]) | device: npu:0 | synthetic text: 'hello world'
[OUTPUT] generated_ids: [2, 10, 797, 9, 4, 1142, 2]
[OUTPUT] decoded text: 'a member of the Senate'
[PERF] Generation latency: 298.24 ms (single run, synchronized) | device: npu:0
[OUTPUT] encoder last_hidden_state shape: (1, 578, 384) | device: npu:0
[SUCCESS] Model microsoft/trocr-small-handwritten NPU inference PASS on npu:0 (Ascend910_9362) | dtype float32
[OUTPUT] second sample decoded: 'was also' | ids: [2, 19, 78, 2]
[PASS] NPU inference completed successfully

说明:合成的印刷体 hello world 对手写模型而言是域外输入,模型仍生成语法合理的文本(IAM 语言先验),但这证明了完整的 ViT 编码 + 自回归解码链路在 NPU 上真实执行。

第二样本: 384x384 文本 TrOCR test -> 'was also' ([2,19,78,2]).

6. CPU-NPU 一致性验证

执行 python inference.py --mode validate 对比 CPU 与 NPU 在相同输入、相同权重、相同 FP32 下的生成结果。

[VALIDATE] CPU generated_ids: [2, 10, 797, 9, 4, 1142, 2]
[VALIDATE] CPU decoded: 'a member of the Senate' | latency 1103.46ms
[VALIDATE] NPU generated_ids: [2, 10, 797, 9, 4, 1142, 2]
[VALIDATE] NPU decoded: 'a member of the Senate' | latency 296.81ms
[VALIDATE] CPU-NPU ids match: True
[VALIDATE] CPU-NPU text match: True
[VALIDATE] Second sample CPU: 'was also' | NPU: 'was also' | match: True
[PASS] CPU-NPU consistency validated (exact token match)

验证策略:固定单样本一致性(非全量数据集评测),检查 generated_ids 精确相等 + decoded text 相等。额外验证 encoder.last_hidden_state shape 一致。

7. 性能测试

所有计时在 torch.npu.synchronize() 包裹下,预热 3 次后正式 10 次。

NPU (npu:0, FP32, 384x384, batch=1):

  • 单次(首次含编译): ~298 ms
  • 稳态 10 次(--mode benchmark): avg 44.67 ms | min 44.48 | max 44.83 | median 44.64 | p90 44.81 | p95 44.83 | throughput 22.38 images/s
  • validate 模式内 10 次: avg 47.03 ms | min 46.69 | max 47.41 | p50 47.03 | p90 47.39

CPU 同输入生成延迟: ~1103 ms (NPU 加速 ~3.7x 首次, ~24x 稳态).

显存:推理后 free ~58-60 GiB / total 61.27 GiB, 峰值占用约 ~1-2 GiB.

复现命令:

python inference.py --mode benchmark

8. 自验证截图

三张证据图由本次真实日志通过 scripts/render_xterm_evidence.mjs --style raw 渲染:

  • assets/agent_workflow.png — 完整适配流水日志(下载、侦察、加载、NPU推理、验证、性能)
  • assets/npu_device_call.png — npu-smi info + torch.npu 可用性与设备名
  • assets/model_result.png — python inference.py 真实输出与 PASS

9. 已知限制

  • 仅验证合成固定样本的一致性,未在 IAM 完整测试集上做 CER/WER 评测
  • 当前为 FP32,未验证 FP16/BF16(小模型在 910B 上 FP32 已足够高效)
  • encoder.pooler.dense 权重为 MISSING(checkpoint 未包含,transformers 自动随机初始化,不影响生成路径)
  • 输入固定为 384x384,processor 已做 resize/normalize
  • 单卡 npu:0 验证,未测试多卡/分布式

10. 标签

Hardware: NPU, NPU, Ascend, Ascend910, Ascend910B, TrOCR, OCR, handwritten, vision-encoder-decoder, transformers