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)
ViTModel (vit, image_size=224, patch_size=16, num_hidden_layers=12, hidden_size=768, num_attention_heads=12, intermediate_size=3072)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)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, FP32BertJapaneseTokenizer (cl-tohoku/bert-base-japanese-char-v2), vocab.txt 24K, 需 fugashi + unidic_lite官方最小示例:
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 一致性验证。
torch.npu.mem_get_info(0) free 60.91 GiB total 61.27 GiBtorch.npu.is_available()==True, device_name=Ascend910_9362, device_count=2/tmp/manga_cli3 (snapshots/aa6573bd10b0d446cbf622e29c3e084914df9741, 444 MB)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))"默认命令(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 # 默认 FP32inference.py 默认打印:模型名、任务、架构、加载后端、device、dtype、输入摘要、真实生成 token 与解码文本、同步后计时、验证结果与最终 PASS/FAIL, 失败时返回非零退出码。
在 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 [2, 2, 838, 1015, 807, 839, 3] → 文本 「 ロ ○ 」 (含日文引号与片假名, 6 字符含空格)[2, 2, 852, 1026, 3] → あ ー (平假名)first param device=npu:0, torch.npu.is_available=True, device_name=Ascend910_9362, 同步后计时真实输出截图见 assets/model_result.png.
相同权重、同输入、同 max_length=20, num_beams=4, early_stopping=True 在 CPU 与 NPU:0 上对比(torch.npu.synchronize() 包裹计时):
[2,2,838,1015,807,839,3] vs NPU [2,2,838,1015,807,839,3] → exact match = True, decode 「 ロ ○ 」 完全一致[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 数值一致。单样本与第二样本一致性验证,非全数据集评测。
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/spixel_values [1,3,224,224]npu:0 Ascend910_9362assets/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)torch_dtype 兼容性ViTImageProcessor 自动 resize 到 224,可能降低小字号漫画文本精度;官方训练亦为 224max_length=20 用于快速验证, 官方配置 max_length=300 可处理更长句, 但会增加延迟 (约线性)fugashi + unidic_lite (约 47MB + 682KB), 缺少时会报 MecabTokenizer 错误;已在 requirements.txt 固定topk_indices % vocab_size 会触发 allow_internal_format=False 警告, 不影响正确性Hardware: NPU, NPU, Ascend, Ascend910, manga-ocr, ocr, vision-encoder-decoder, vit, bert-japanese, japanese, manga, transformers, torch_npu