File size: 5,266 Bytes
566d53d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
"""OCR cleaner v1: standalone inference (needs only torch and safetensors).

A 0.65M-parameter looped transformer. Each step, every character attends to the others, a router
picks one of 8 learned operations for it, and the character stops ("halts") once it is done, so
clean text takes about 3 steps per character and damaged text about 5. Halted characters cost
nothing: only characters still working are computed.

  python ocr_clean.py < scan.txt > clean.txt
  python ocr_clean.py --weights model.safetensors --threads 4 < scan.txt

Each input character becomes 0-2 output characters, so the model can delete stray characters,
restore dropped ones, split "rn" back into "m", rejoin hyphenated line breaks, and so on.
Single line breaks are treated as wrapped lines (joined into running text); blank lines separate
paragraphs and are kept.

Licence: MIT OR Apache-2.0.
"""
import argparse
import json
import math
import os
import sys

import torch
import torch.nn.functional as F
from safetensors.torch import load_file

HERE = os.path.dirname(os.path.abspath(__file__))
CHARS = [chr(i) for i in range(32, 127)] + ["\n"]  # input and output alphabet
CI = {c: i for i, c in enumerate(CHARS)}
EMPTY = len(CHARS)  # output slot class meaning "no character"
V = len(CHARS) + 1


class OCRCleaner:
    def __init__(self, weights, config):
        self.w = load_file(weights)
        self.cfg = json.load(open(config))
        self.d = self.cfg["d"]
        self.H = self.cfg["heads"]
        self.T = self.cfg["max_steps"]

    def _ln(self, x, name):
        return F.layer_norm(x, (self.d,), self.w[name + ".weight"], self.w[name + ".bias"])

    @torch.no_grad()
    def run(self, ids):
        """ids: list of character ids. Returns (output slot ids [N, 2], steps per character [N])."""
        w, d, H = self.w, self.d, self.H
        dh = d // H
        N = len(ids)
        e = w["emb.ch.weight"][torch.tensor(ids)] + w["emb.pos.weight"][:N]
        h = torch.zeros_like(e)
        out = torch.zeros(N, 2 * V)
        steps = torch.zeros(N, dtype=torch.long)
        Kc, Vc = torch.zeros(H, N, dh), torch.zeros(H, N, dh)
        surv = torch.ones(N)
        idx = torch.arange(N)
        for t in range(self.T):
            z = h[idx] + e[idx] + w["step.weight"][min(t, w["step.weight"].shape[0] - 1)]
            q, k, v = (self._ln(z, "n1.0") @ w["attn.0.qkv.weight"].T).view(-1, 3, H, dh).permute(1, 2, 0, 3)
            Kc[:, idx], Vc[:, idx] = k, v  # halted characters keep their cached keys/values
            a = F.scaled_dot_product_attention(q, Kc, Vc).transpose(0, 1).reshape(-1, d) @ w["attn.0.o.weight"].T
            y = self._ln(z + a, "n2.0")
            choice = (y @ w["router.weight"].T + w["router.bias"]).argmax(-1)  # one operation per character
            m = torch.empty_like(y)
            for op in choice.unique().tolist():
                sel = choice == op
                m[sel] = F.gelu(y[sel] @ w["experts.w1"][op]) @ w["experts.w2"][op]
            hn = h[idx] + a + m
            hf = self._ln(hn, "nf")
            out[idx] = hf @ w["head.weight"].T + w["head.bias"]
            lam = torch.sigmoid(hf @ w["halt.weight"].T + w["halt.bias"]).squeeze(-1)
            h[idx] = hn
            steps[idx] = t + 1
            surv[idx] = surv[idx] * (1 - lam)
            idx = idx[(1 - surv[idx]) < 0.5]  # halt once P(halted) >= 0.5
            if len(idx) == 0:
                break
        return out.view(N, 2, V).argmax(-1), steps

    def clean(self, text, maxlen=110):
        paras, all_steps = [], []
        for para in text.split("\n\n"):
            parts = []
            for win in windows(para, maxlen):
                core = win.rstrip(" \n")  # training windows never end in whitespace
                tail = " " if len(core) < len(win) else ""
                if core:
                    slots, s = self.run([CI.get(c, CI["?"]) for c in core])
                    parts.append("".join(CHARS[c] for c in slots.reshape(-1).tolist() if c < EMPTY))
                    all_steps.append(s)
                parts.append(tail)
            paras.append("".join(parts))
        steps = torch.cat(all_steps) if all_steps else torch.zeros(0)
        return "\n\n".join(paras), steps


def windows(text, maxlen):
    """Cut at spaces or line breaks into pieces of at most maxlen characters (the model saw ~100)."""
    out, i = [], 0
    while i < len(text):
        j = min(len(text), i + maxlen)
        if j < len(text):
            k = max(text.rfind(" ", i + 1, j), text.rfind("\n", i + 1, j))
            j = k + 1 if k > i else j
        out.append(text[i:j])
        i = j
    return out


if __name__ == "__main__":
    ap = argparse.ArgumentParser(description="Clean OCR errors from text on stdin.")
    ap.add_argument("--weights", default=os.path.join(HERE, "model.safetensors"))
    ap.add_argument("--config", default=os.path.join(HERE, "config.json"))
    ap.add_argument("--threads", type=int, default=1)
    a = ap.parse_args()
    torch.set_num_threads(a.threads)
    model = OCRCleaner(a.weights, a.config)
    cleaned, steps = model.clean(sys.stdin.read())
    sys.stdout.write(cleaned)
    if len(steps):
        print(f"[{len(steps)} chars, mean steps {steps.float().mean():.2f}]", file=sys.stderr)