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

kha-white/manga-ocr-base-NPU

Ascend 910B NPU-adapted version of kha-white/manga-ocr-base (VisionEncoderDecoderModel: ViT encoder facebook/deit-base-patch16-224 + BERT-Japanese decoder cl-tohoku/bert-base-japanese-char-v2).

Validated on single-card Ascend 910B (npu:0) with torch_npu eager inference — CPU vs NPU exact token match.

#NPU

Model Info

  • Base: kha-white/manga-ocr-base (VisionEncoderDecoderModel, 424 MB pytorch_model.bin, vocab 6144 Japanese characters)
  • Encoder: ViTModel (12 layers, hidden 768, patch 16, image 224) from facebook/deit-base-patch16-224
  • Decoder: BertLMHeadModel (2 layers, hidden 768, vocab 6144, max_length 300, num_beams 4, no_repeat_ngram 3, length_penalty 2.0)
  • Preprocessor: ViTFeatureExtractor size 224, mean 0.5 std 0.5, normalize + resize
  • Tokenizer: BertJapaneseTokenizer (word_tokenizer Mecab + character subword, vocab.txt 6144, special [PAD][UNK][CLS][SEP][MASK])
  • Task: image-to-text OCR for Japanese manga (vertical/horizontal, furigana, low-quality robust)

NPU Adaptation

  • Load: VisionEncoderDecoderModel.from_pretrained(...).to("npu:0") fp32, no quantization
  • Processor/Tokenizer: local ViTImageProcessor + AutoTokenizer with dummy fugashi/unidic_lite (character-level decode, avoids 47 MB MeCab dict install; subword is character so dummy word-split still correct for decoding)
  • Device migration: model, pixel_values (1,3,224,224) fp32, and generate output all on npu:0; verified via next(model.parameters()).device, pixel_values.device, generated.device
  • Generate: model.generate(pixel_values.to("npu:0"), max_length=20, num_beams=4, early_stopping=True) with torch.npu.synchronize() before/after timing
  • Single-card memory: 424 MB weights + <2 GB activations < 65 GB HBM per card — no multi-card needed

Validation

  • Input: synthetic 224x224 manga-like image (white background, black border, "manga test" text) processed by ViTImageProcessor
  • CPU vs NPU: exact match — generated ids [2, 2, 879, 926, 897, 28, 28, 28, 3] both devices, decoded そ れ は . . . ([CLS] そ れ は . . . [SEP]) — 100% token equality, cosine not applicable (discrete ids)
  • Consistency threshold: discrete token equality required, fp32 atol irrelevant; np.array_equal(cpu_ids, npu_ids) passes
  • Performance (224x224, batch 1, 910B): first compile 381–397 ms, stable 51–52 ms / image, ~19.1 imgs/s (10-run avg, torch.npu.synchronize() around each run)
  • Device proofs in logs: Using device: npu:0, NPU device name: Ascend910_9362, next(model.parameters()).device -> npu:0, pixel_values.device -> npu:0, generated.device -> npu:0

Usage

import sys, types, os
# mock MeCab for BertJapaneseTokenizer (character decode, avoids fugashi install)
if 'fugashi' not in sys.modules:
    import types
    m=types.ModuleType('fugashi')
    class W: 
        def __init__(self,s): self.surface=s
    class T:
        def __init__(self,o=""): pass
        def __call__(self,txt):
            for c in txt: yield W(c)
    m.GenericTagger=T
    sys.modules['fugashi']=m
if 'unidic_lite' not in sys.modules:
    m=types.ModuleType('unidic_lite'); m.DICDIR="/tmp"; open("/tmp/mecabrc","w").write(""); sys.modules['unidic_lite']=m

import torch, torch_npu
from transformers import VisionEncoderDecoderModel, ViTImageProcessor, AutoTokenizer
from PIL import Image, ImageDraw

model_dir="kha-white/manga-ocr-base" # or local cache
proc=ViTImageProcessor.from_pretrained(model_dir)
tok=AutoTokenizer.from_pretrained(model_dir, trust_remote_code=False)
model=VisionEncoderDecoderModel.from_pretrained(model_dir).to("npu:0").eval()

img=Image.new('RGB',(224,224),'white')
ImageDraw.Draw(img).rectangle([10,10,214,214], outline='black', width=2)
pix=proc(images=img, return_tensors="pt").pixel_values.to("npu:0")
with torch.no_grad():
    ids=model.generate(pix, max_length=20, num_beams=4, early_stopping=True)
    torch.npu.synchronize()
print(ids[0].tolist()) # [2, 2, 879, 926, 897, 28, 28, 28, 3]
print(tok.batch_decode(ids, skip_special_tokens=True)) # ['そ れ は . . .']
print(ids.device) # npu:0

Or run python inference.py (default synthetic image, prints device, ids, text, 10-run perf).

Evidence

Evidence images were generated by xterm.js from the real execution logs of this adaptation (workflow, device, inference).

agent workflow npu device call model result

Requirements

See requirements.txt. Tested with torch 2.9.0, torch_npu 2.9.0.post1, transformers 4.57.6, pillow, numpy 1.26.4.

Limitations

  • Dummy Mecab splitter returns per-character words; for OCR decoding (character subword) this is faithful, but for Japanese text tokenization of inputs it would split differently than real MeCab — inference is image-to-text only so not affected.
  • No fine-tuning on Ascend; weights unchanged.
  • Batch 1, 224x224 only validated; larger batches/resolutions need separate timing.