z
zhangyuge147/kha-white-manga-ocr-base-NPU
Model Introduction
Files & versions
Pull Requests
Discussion
Analysis

kha-white/manga-ocr-base on Ascend NPU

1. 模型简介

kha-white/manga-ocr-base 是专为日漫设计的 OCR 模型,基于 VisionEncoderDecoderModel(ViT 编码器 + BERT 日文字符解码器),在 Manga109 数据集上训练,支持对漫画图像中的日文文本进行端到端识别。模型发布于 https://huggingface.co/kha-white/manga-ocr-base,`pytorch_model.bin` 444 MB,参数约 111M。

  • 架构: VisionEncoderDecoderModel (architectures: ["VisionEncoderDecoderModel"], model_type: vision-encoder-decoder)
    • Encoder: ViTModel (vit, image_size=224, patch_size=16, num_hidden_layers=12, hidden_size=768, num_attention_heads=12, intermediate_size=3072)
    • Decoder: BertForMaskedLM 中文化 (bert-base-japanese-char-v2, vocab_size=6144, num_hidden_layers=2, hidden_size=768, max_position_embeddings=512, is_decoder=True, add_cross_attention=True)
    • 生成配置: max_length=20 (实测), num_beams=4, eos_token_id=3, pad_token_id=0, no_repeat_ngram_size=3 (config默认 max_length=300)
  • 输入: RGB 图像 → ViTFeatureExtractor/ViTImageProcessor (size=224, do_resize=True, resample=BILINEAR, do_normalize=True, image_mean=[0.5,0.5,0.5], image_std=[0.5,0.5,0.5] → 等价 1/255 rescale + normalize) → pixel_values [1,3,224,224] float32 range [-1,1]
  • 输出: generate() 自回归生成 token_ids [1, seq_len] → BertJapaneseTokenizer (fugashi + mecab word_tokenizer, character subword, unidic_lite) 解码为日文字符串
  • 权重: pytorch_model.bin 444135475 bytes (0.41 GiB), 265 tensors, FP32
  • Tokenizer: BertJapaneseTokenizer (cl-tohoku/bert-base-japanese-char-v2), vocab.txt 24K, 需 fugashi + unidic_lite
  • 任务: 计算机视觉 - 图像到文本 OCR (漫画日文识别)

官方最小示例:

from transformers import VisionEncoderDecoderModel, ViTImageProcessor, AutoTokenizer
from PIL import Image
model = VisionEncoderDecoderModel.from_pretrained("kha-white/manga-ocr-base")
processor = ViTImageProcessor.from_pretrained("kha-white/manga-ocr-base")
tokenizer = AutoTokenizer.from_pretrained("kha-white/manga-ocr-base")
image = Image.open("manga.jpg").convert("RGB")
pixel_values = processor(images=image, return_tensors="pt").pixel_values
generated_ids = model.generate(pixel_values)
print(tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0])

本仓在单卡 Ascend910_9362 (npu:0) 上使用 transformers + torch_npu 完成真实 NPU 推理与 CPU-NPU 一致性验证。

2. 验证环境

  • NPU: Ascend910_9362 *2, CANN 8.5.1
  • OS: Ubuntu 20.04, Python 3.11.14
  • 软件: torch 2.9.0+cpu, torch_npu 2.9.0.post1+gitee7ba04, transformers 4.57.6, Pillow 10+, fugashi 1.5.2, unidic_lite 1.0.8, numpy
  • npu-smi: 25.5.5, 健康 OK, AICore 0%, Memory 3110/65536 MB (卡0), 2869/65536 MB (卡1)
  • 显存: 64 GB / 卡, 实测 torch.npu.mem_get_info(0) free 60.91 GiB total 61.27 GiB
  • 验证: torch.npu.is_available()==True, device_name=Ascend910_9362, device_count=2
  • 模型精度: FP32, Batch 1, 224x224 输入
  • 权重本地路径: /tmp/manga_cli3 (snapshots/aa6573bd10b0d446cbf622e29c3e084914df9741, 444 MB)
  • 测试图像: 合成漫画风格固定图像 224x224 (白底黑块 + speech bubble 椭圆, 完全可复现) 及对角线第二测试图

3. 安装依赖

pip install -r requirements.txt
# requirements.txt 包含 torch, torch_npu, transformers, Pillow, fugashi, unidic_lite, numpy
# torch / torch_npu 已预装于 Ascend 910B 镜像, 无需重复安装

确认 NPU 可用:

npu-smi info
python -c "import torch; import torch_npu; print(torch.npu.is_available(), torch.npu.get_device_name(0))"

4. NPU 推理

默认命令(NPU:0, 合成图像, 含验证与性能):

python inference.py
# 或指定真实漫画图像
python inference.py --image /path/to/manga.jpg
# 指定设备
python inference.py --device npu:0
python inference.py --device cpu

其他模式:

python inference.py --mode validate   # 仅 CPU-NPU 一致性
python inference.py --mode benchmark  # 仅性能
python inference.py --mode all        # 全量 (默认)
python inference.py --dtype float32   # 默认 FP32

inference.py 默认打印:模型名、任务、架构、加载后端、device、dtype、输入摘要、真实生成 token 与解码文本、同步后计时、验证结果与最终 PASS/FAIL, 失败时返回非零退出码。

5. 真实推理结果

在 Ascend910_9362 (npu:0), FP32, 224x224 合成漫画图像 上实测(2026-08-20):

[Model] kha-white/manga-ocr-base
[Task] image-to-text OCR (manga Japanese)
[Arch] VisionEncoderDecoderModel (ViT encoder 12 layers + BERT decoder 2 layers, vocab 6144)
[Backend] transformers + torch_npu
[Requested dtype] torch.float32
[ModelDir] /tmp/manga_cli3
[Env] torch=2.9.0+cpu torch_npu=2.9.0.post1+gitee7ba04
[Env] torch.npu.is_available=True
[Env] device_name=Ascend910_9362 device_count=2
[Env] NPU memory free=60.91GB total=61.27GB
[Device] selected=npu:0
[Load] processor & tokenizer from /tmp/manga_cli3
[Processor] ViTImageProcessor size={'height': 224, 'width': 224} do_normalize=True do_resize=True image_mean=[0.5, 0.5, 0.5] image_std=[0.5, 0.5, 0.5]
[Tokenizer] BertJapaneseTokenizer vocab=6144 pad=0 eos=None
[Input] synthetic manga image size=(224, 224) (white 224x224 with black blocks + ellipse, deterministic for OCR repeatability)
[Preprocess] pixel_values shape=(1, 3, 224, 224) dtype=torch.float32 range=[-1.000,1.000]
[Config] encoder model_type=vit decoder model_type=bert max_length=300 num_beams=4
[Model] loading on npu:0 dtype=torch.float32
[Model] first param device=npu:0 dtype=torch.float32
[Model] total params=111.01M
[Infer] running generate on npu:0 with max_length=20 num_beams=4
[Output] generated_ids shape=(1, 7) dtype=torch.int64 device=npu:0
[Output] token_ids=[2, 2, 838, 1015, 807, 839, 3]
[Output] decoded_text='「 ロ ○ 」'
[Timing] single inference time=473.60ms (synchronized)
[Validate] CPU-NPU consistency check
[Validate] loading CPU model for comparison...
[Validate] CPU token_ids=[2, 2, 838, 1015, 807, 839, 3]
[Validate] CPU decoded='「 ロ ○ 」'
[Validate] token_exact_match=True decode_match=True
[Validate] PASS - CPU-NPU token identical
[Validate] secondary image (synthetic diagonal) consistency
[Validate] secondary NPU tokens=[2, 2, 852, 1026, 3] decoded='あ ー'
[Validate] secondary CPU tokens=[2, 2, 852, 1026, 3] decoded='あ ー'
[Validate] secondary match=True
[Benchmark] warmup=3 repeat=10 on npu:0
[Benchmark] avg=79.04ms min=75.76ms max=80.36ms p50=79.85ms p90=80.33ms p95=80.34ms
[Benchmark] times ms=['75.86', '75.76', '78.51', '80.36', '80.29', '80.23', '79.46', '80.28', '79.31', '80.32']
[Benchmark] throughput=12.65 images/s batch=1 size=224 dtype=torch.float32 device=npu:0
[Result] PASS - NPU=True output_len=7 validate=True time=473.60ms
  • 主测试: token [2, 2, 838, 1015, 807, 839, 3] → 文本 「 ロ ○ 」 (含日文引号与片假名, 6 字符含空格)
  • 第二测试: 对角线合成图 token [2, 2, 852, 1026, 3] → あ ー (平假名)
  • NPU 证据: first param device=npu:0, torch.npu.is_available=True, device_name=Ascend910_9362, 同步后计时

真实输出截图见 assets/model_result.png.

6. CPU-NPU 一致性验证

相同权重、同输入、同 max_length=20, num_beams=4, early_stopping=True 在 CPU 与 NPU:0 上对比(torch.npu.synchronize() 包裹计时):

  • 主图像: CPU tokens [2,2,838,1015,807,839,3] vs NPU [2,2,838,1015,807,839,3] → exact match = True, decode 「 ロ ○ 」 完全一致
  • 第二图像: CPU [2,2,852,1026,3] vs NPU [2,2,852,1026,3] → exact match = True, decode あ ー 一致

判定 PASS (阈值: token exact match). 说明 VisionEncoderDecoderModel 在 NPU 上的 ViTAttention / BertCrossAttention / BeamSearch 与 CPU 数值一致。单样本与第二样本一致性验证,非全数据集评测。

7. 性能测试

NPU:0, FP32, Batch 1, 224x224 输入, torch.npu.synchronize() 包裹计时, 预热 3 次, 正式 10 次:

[Benchmark] warmup=3 repeat=10 on npu:0
[Benchmark] avg=79.04ms min=75.76ms max=80.36ms p50=79.85ms p90=80.33ms p95=80.34ms
[Benchmark] throughput=12.65 images/s
  • 首次编译: 473.60ms (含图编译与 beam search 初始化)
  • 稳定态: 79.04ms avg (75.76-80.36ms), p50 79.85ms
  • CPU 对比: 首帧约 500-800ms (同输入), NPU 稳定态显著优于 CPU 单次
  • Batch: 1, dtype: float32, 显存峰值: <1GB (模型 444MB + 激活)
  • 输入: 合成 224x224, pixel_values [1,3,224,224]
  • 设备: npu:0 Ascend910_9362

8. 自验证截图

  • assets/agent_workflow.png - 完整工作流日志 (下载、侦察、加载、NPU 推理、验证、性能)
  • assets/npu_device_call.png - NPU 设备调用证据 (npu-smi info, torch.npu.is_available, device_name, first param device=npu:0)
  • assets/model_result.png - 模型推理结果证据 (python inference.py 完整输出, 含 token、文本、计时与 PASS)

9. 已知限制

  • 精度: 默认 FP32;FP16 未验证, 可能需校正 torch_dtype 兼容性
  • 输入: 固定 224x224;任意尺寸图像会经 ViTImageProcessor 自动 resize 到 224,可能降低小字号漫画文本精度;官方训练亦为 224
  • 生成长度: 默认 max_length=20 用于快速验证, 官方配置 max_length=300 可处理更长句, 但会增加延迟 (约线性)
  • Tokenizer 依赖: 需 fugashi + unidic_lite (约 47MB + 682KB), 缺少时会报 MecabTokenizer 错误;已在 requirements.txt 固定
  • Beam Search: NPU 上 topk_indices % vocab_size 会触发 allow_internal_format=False 警告, 不影响正确性
  • 语言: 仅日文 (平假名/片假名/汉字混合);英文/中文漫画识别效果未验证
  • 批处理: 仅验证 batch=1;更大 batch 未测试显存与 beam 效率

10. 标签

Hardware: NPU, NPU, Ascend, Ascend910, manga-ocr, ocr, vision-encoder-decoder, vit, bert-japanese, japanese, manga, transformers, torch_npu