File size: 4,603 Bytes
24aaa76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Arm geometry of RQ2 (design 'frames_per_character_matched'): input height H, width subsampling and micro-batch columns.

32 px arms: width subsampling 4 = the backbone's last parameter-free pooling becomes avg_pool2d(kernel=(h, 1)) instead of
(h, 2) (kraken 7.2 kraken/lib/ppocr/backbone.py PPLCNetV4.forward). 64 px arms keep (h, 2), subsampling 8. No weights change.
Neither the LightSVTR neck (necks.py lines 183-202) nor the NRTR guide head (nrtr.py line 189: memory = input_proj only)
has a positional term that depends on the sequence length, so the longer sequence at 32 px needs no other change.
"""
import hashlib
import os
import types

import torch.nn.functional as F

CODE = "/path/to/TURKIC_OCR_CODE"
DATA = "/path/to/TURKIC_OCR_DATA"
KRAKEN = CODE + "/.venv_kraken/lib/python3.12/site-packages/kraken/lib/ppocr"

GEOM = {
    32: {"subsampling": 4, "micro_columns": 12000, "pool_kernel_w": 1},
    64: {"subsampling": 8, "micro_columns": 24000, "pool_kernel_w": 2},
}
MAX_WIDTH = 2560

# files the wrappers depend on (sha256 read on the cluster 2026-11-26; design.json lists the same prefixes)
PINNED = {
    CODE + "/src/linedet/train_arm.py": "55369cd0773b08df064db8fd17e3586bf9bfc2ad84774c36198cbd2d74faef47",
    CODE + "/src/linedet/data.py": "0502c2f556e2cd0145b7afaa1fa19ec8760a112460a853b33d76aa524191cb6d",
    CODE + "/src/linedet/models.py": "9ada511fbc072c73069a5999adca7c90c2de29e9536ad481c101f734b4d7306b",
    CODE + "/src/linedet/predict.py": "0ad3f3d647e5f9af6846927673e4d3ae9999f42feb77a904e09114f33bff5ae9",
    CODE + "/src/linedet/common.py": "00d606e432e688d8f6f7620105cf9010a1d3138624416d32893b170bd868c52a",
    KRAKEN + "/backbone.py": "ab517cf88124847beb0cf3f1fd87c7270f9ec7fa8e3f773b6177b352f491462d",
    KRAKEN + "/network.py": "ed4592d7cf9937753cfd3d0fb5be6c083035370a2c3bc46bb647285ea9da48d1",
    KRAKEN + "/necks.py": "dcc7cb0ca045b71c2356ff82d97a7b91ab24b900ed3665feb274432d87c2b483",
    KRAKEN + "/nrtr.py": "4367a8839b8809648e431bdff8ce778a3589732a66f165b6734ada6d32a9f1d0",
}
PINNED_DATA = {
    DATA + "/data/processed/r5/mix_v1.yaml": "eda03a065a9cbcbcc64604ac3c4d0009e46ffa83ef86b0032c84954d44bbaed7",
    DATA + "/outputs/r5/linedet/codec_union.json": "d058a39de1a0d895212f9c9e6a32aaba02bd34471cceb55f13411e39bc84551a",
    DATA + "/data/raw/zenodo_ppocrv6_medium_21788410/medium.safetensors": "15313b51ace64cbfa81f8f6ef25ad64f04e5a6fb7f7823e67b107527bc081ac9",
}


def sha256_file(p, bufsize=1 << 22):
    h = hashlib.sha256()
    with open(p, "rb") as f:
        while True:
            b = f.read(bufsize)
            if not b:
                break
            h.update(b)
    return h.hexdigest()


def check_pinned(include_data=True):
    """Refuse to run when a wrapped file or a frozen input changed. Returns {path: sha256}."""
    out = {}
    items = dict(PINNED)
    if include_data:
        items.update(PINNED_DATA)
    for p, want in items.items():
        got = sha256_file(p)
        if got != want:
            raise SystemExit("REFUSED: %s has sha256 %s, expected %s" % (p, got, want))
        out[p] = got
    return out


def apply_spec(H):
    """linedet.data.SPECS['A1'] = ArmSpec('A1', H, 3, 4 if H == 32 else 8, 2560) and LINEDET_MICRO_COLUMNS."""
    from linedet import data as D
    g = GEOM[int(H)]
    D.SPECS["A1"] = D.ArmSpec("A1", int(H), 3, g["subsampling"], MAX_WIDTH)
    os.environ["LINEDET_MICRO_COLUMNS"] = str(g["micro_columns"])
    return D.SPECS["A1"]


def pool1_forward(self, x):
    """kraken PPLCNetV4.forward (backbone.py lines 332-341) with avg_pool2d(kernel=(h, 1)): width subsampling 4."""
    x = self.conv1(x)
    x = self.blocks2(x)
    x = self.blocks3(x)
    x = self.blocks4(x)
    x = self.blocks5(x)
    x = self.blocks6(x)
    h = x.shape[2]
    x = F.avg_pool2d(x, kernel_size=(h, 1))
    return x


def patch_pooling(arm, H):
    """Give the arm's backbone the pooling of height H (a bound method on the instance; state_dict unchanged)."""
    if GEOM[int(H)]["pool_kernel_w"] == 1:
        bb = arm.net.nn.backbone
        bb.forward = types.MethodType(pool1_forward, bb)
        arm.rq2_pooling = "avg_pool2d(kernel=(h, 1)), width subsampling 4"
    else:
        arm.rq2_pooling = "avg_pool2d(kernel=(h, 2)) (kraken default), width subsampling 8"
    return arm


def expected_frames(W, H):
    """Logit length of the patched network for an input of width W: the stem (two stride-2 3x3 convolutions with padding 1)
    gives ceil(W/4); the default pooling (h, 2) then halves it (floor)."""
    c4 = -(-int(W) // 4)
    return c4 if GEOM[int(H)]["pool_kernel_w"] == 1 else c4 // 2