File size: 3,333 Bytes
623e12e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | """小さな漫画の文字読み取りのモデル。timm の骨格の 1/16 の特徴を記憶にして、小さな Transformer のデコーダが 1 文字ずつ出す。
文字の表は kha-white/manga-ocr-base の tokenizer (文字単位、6144 語、Apache-2.0) をそのまま使う。
"""
import timm
import torch
from torch import nn
PAD, BOS, EOS = 0, 2, 3 # manga-ocr-base の tokenizer の [PAD]、[CLS]、[SEP]
class TinyOCR(nn.Module):
def __init__(self, arch: str, size: int = 224, d: int = 256, layers: int = 4, heads: int = 4, vocab: int = 6144, max_len: int = 128, pretrained: bool = True):
super().__init__()
enc = timm.create_model(arch, pretrained=False, features_only=True)
idx = enc.feature_info.reduction().index(16) # 224 なら 14x14 の特徴
self.encoder = timm.create_model(arch, pretrained=pretrained, features_only=True, out_indices=(idx,))
c = self.encoder.feature_info.channels()[0]
n = (size // 16) ** 2
self.proj = nn.Linear(c, d)
self.enc_pos = nn.Parameter(torch.zeros(1, n, d))
self.embed = nn.Embedding(vocab, d)
self.pos = nn.Parameter(torch.zeros(1, max_len, d))
layer = nn.TransformerDecoderLayer(d, heads, 4 * d, dropout=0.1, batch_first=True, norm_first=True)
self.decoder = nn.TransformerDecoder(layer, layers)
self.norm = nn.LayerNorm(d)
self.head = nn.Linear(d, vocab, bias=False)
self.head.weight = self.embed.weight
nn.init.trunc_normal_(self.enc_pos, std=0.02)
nn.init.trunc_normal_(self.pos, std=0.02)
nn.init.trunc_normal_(self.embed.weight, std=0.02) # 出力の重みと共有するので小さく始める
self.max_len = max_len
def encode(self, x: torch.Tensor) -> torch.Tensor:
f = self.encoder(x)[0]
if f.ndim == 4:
f = f.flatten(2).transpose(1, 2)
return self.proj(f) + self.enc_pos
def decode(self, mem: torch.Tensor, ids: torch.Tensor) -> torch.Tensor:
n = ids.shape[1]
mask = torch.triu(torch.full((n, n), float("-inf"), device=ids.device), 1)
# mask は作りからして因果なので、値を比べて確かめる処理 (ONNX への書き出しを止める) を飛ばす
h = self.decoder(self.embed(ids) + self.pos[:, :n], mem, tgt_mask=mask, tgt_is_causal=True)
return self.head(self.norm(h))
def forward(self, x: torch.Tensor, ids: torch.Tensor) -> torch.Tensor:
return self.decode(self.encode(x), ids)
@torch.no_grad()
def greedy(self, x: torch.Tensor, max_len: int | None = None) -> list[list[int]]:
mem = self.encode(x)
ids = torch.full((x.shape[0], 1), BOS, dtype=torch.long, device=x.device)
done = torch.zeros(x.shape[0], dtype=torch.bool, device=x.device)
for _ in range((max_len or self.max_len) - 1):
nxt = self.decode(mem, ids)[:, -1].argmax(-1)
nxt = torch.where(done, torch.full_like(nxt, PAD), nxt)
ids = torch.cat([ids, nxt[:, None]], 1)
done |= nxt == EOS
if done.all():
break
out = []
for row in ids[:, 1:].tolist():
out.append([t for t in row[: row.index(EOS)] if t != PAD] if EOS in row else [t for t in row if t != PAD])
return out
|