File size: 25,216 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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
"""The five line-recognizer arms of round R5.

A1, A2, A1s: kraken 7.2 PP-OCRv6 (medium, small, medium from scratch). Loss, optimizer groups and the auxiliary NRTR
             head follow kraken/train/ppocr.py (read in full); data loading is ours.
A3:          CRNN from scratch (6 conv layers, 2-layer BiLSTM of 256, CTC), about 6M parameters.
A4:          HTR-VT design (Li et al. 2024, arXiv 2409.08573; code github.com/YutingLi0606/HTR-VT, files model/HTR_VT.py,
             model/resnet18.py, utils/sam.py, utils/utils.py, run/lam.sh): ResNet-18 stem with 768 output channels,
             4 transformer layers of width 768 and 6 heads, span masking, CTC, SAM+AdamW, EMA.
"""
import copy
import math

import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F

CTC_BLANK = 0
AMP = {"on": True}
A4_OPTS = {"output_ln": True}   # A4 diagnostic variant v1 (clarification H8) sets output_ln False; the checkpoint records it       # bf16 autocast on CUDA; train_arm --no_amp switches it off


# ------------------------------------------------------------------------------------------------ helpers
def n_params(m):
    return sum(p.numel() for p in m.parameters())


def layer_report(m, depth=2):
    """List of (name, class, parameter count) for named modules down to the given depth, parameters counted from the
    module objects."""
    rows = [("total", type(m).__name__, n_params(m))]

    def rec(mod, prefix, d):
        for name, child in mod.named_children():
            full = prefix + "." + name if prefix else name
            rows.append((full, type(child).__name__, n_params(child)))
            if d + 1 < depth:
                rec(child, full, d + 1)
    rec(m, "", 0)
    return rows


def cosine_factor(step, total, warmup, min_ratio):
    if warmup and step < warmup:
        return (step + 1) / float(warmup + 1)
    prog = (step - warmup) / float(max(1, total - warmup))
    prog = min(1.0, max(0.0, prog))
    return min_ratio + (1 - min_ratio) * 0.5 * (1 + math.cos(math.pi * prog))


def set_lr(opt, lr):
    for g in opt.param_groups:
        g["lr"] = lr


def ctc_from_logits(logits_btc, in_lens, target, target_lens):
    """logits (B,T,C) any dtype -> mean CTC loss in float32."""
    lp = logits_btc.float().log_softmax(-1).permute(1, 0, 2)
    return F.ctc_loss(lp, target, in_lens, target_lens, blank=CTC_BLANK, zero_infinity=True, reduction="mean")


# ------------------------------------------------------------------------------------------------ PP-OCRv6 arms
class PPOCRArm:
    kind = "ppocr"

    def __init__(self, name, variant, codec, base_weights=None, height=96):
        from kraken.lib.ppocr import MODEL_VARIANTS, PPOCRv6Model
        from kraken.lib.ppocr.nrtr import NRTRHead
        self.name, self.variant, self.codec, self.height = name, variant, codec, height
        n_cls = codec.max_label + 1
        if base_weights:
            from kraken.models import load_models
            m = load_models(base_weights)[0]
            assert m.variant == variant, (m.variant, variant)
            self.height = m.input[2]
            m.add_codec(codec)
            m.resize_output(n_cls)
            self.base_info = {"weights": base_weights, "base_classes": "see base_*_info.json"}
        else:
            m = PPOCRv6Model(variant=variant, num_classes=n_cls, height=height, codec=codec.c2l,
                             seg_type="baselines", one_channel_mode="RGB", legacy_polygons=False)
        self.net = m
        cfg = MODEL_VARIANTS[variant]["nrtr"]
        self.bos, self.eos = codec.max_label + 1, codec.max_label + 2
        self.aux = NRTRHead(in_channels=m.nn.backbone.out_channels, vocab_size=codec.max_label + 3,
                            d_model=cfg["dim"], num_decoder_layers=cfg["num_decoder_layers"], max_len=2048)
        self.nrtr_ce = nn.CrossEntropyLoss(ignore_index=0, label_smoothing=0.1)

    # -- plumbing
    def modules(self):
        return [self.net, self.aux]

    def to(self, dev):
        for m in self.modules():
            m.to(dev)
        return self

    def train(self):
        for m in self.modules():
            m.train()

    def eval(self):
        for m in self.modules():
            m.eval()

    def deploy_params(self):
        return n_params(self.net)

    # -- optimizer
    def make_optimizer(self, lr):
        from kraken.train.optim import MuonWithAuxAdam, get_parameter_groups
        groups = get_parameter_groups(nn.ModuleList([self.net, self.aux]), base_lr=lr)
        self.opt = MuonWithAuxAdam(groups, lr=lr, weight_decay=0.01, momentum=0.95)
        self.group_report = [(g["name"], sum(p.numel() for p in g["params"]), g["use_muon"]) for g in groups]
        return self.opt

    # -- loss
    def _nrtr_targets(self, target, target_lens, device):
        # from kraken/train/ppocr.py _nrtr_targets; the pad length is the longest target in the batch plus BOS/EOS
        target = target.to(device).long()
        tl = target_lens.to(device)
        pad_len = int(tl.max()) + 2 if tl.numel() else 2
        rows = torch.arange(tl.numel(), device=device)
        starts = tl.cumsum(0) - tl
        cols = torch.arange(target.numel(), device=device) - starts.repeat_interleave(tl) + 1
        padded = torch.zeros(tl.numel(), pad_len, dtype=torch.long, device=device)
        padded[:, 0] = self.bos
        if target.numel():
            padded[rows.repeat_interleave(tl), cols] = target
        padded[rows, tl + 1] = self.eos
        return padded

    def train_step_loss(self, batch, device):
        img = batch["image"].to(device, non_blocking=True)
        sl = batch["seq_lens"].to(device)
        tg = batch["target"].to(device)
        tl = batch["target_lens"].to(device)
        with torch.autocast("cuda", dtype=torch.bfloat16, enabled=(device.type == "cuda" and AMP["on"])):
            logits, out_lens, feat = self.net.nn.forward_train(img, sl)
        lp = logits.float().log_softmax(1).squeeze(2).permute(2, 0, 1)
        ctc = F.ctc_loss(lp, tg, out_lens, tl, blank=CTC_BLANK, zero_infinity=True, reduction="mean")
        t = self._nrtr_targets(batch["target"], batch["target_lens"], device)
        mem_mask = torch.arange(feat.shape[-1], device=device)[None, :] < out_lens[:, None]
        with torch.autocast("cuda", dtype=torch.bfloat16, enabled=(device.type == "cuda" and AMP["on"])):
            nl = self.aux(feat, t[:, :-1], mem_mask)
        nrtr = self.nrtr_ce(nl.float().reshape(-1, nl.shape[-1]), t[:, 1:].reshape(-1))
        return ctc + nrtr, {"ctc": float(ctc.detach()), "nrtr": float(nrtr.detach())}

    def train_chunks(self, chunks, B, device, lr):
        """One optimizer step over `chunks` (micro-batches of one batch of B samples); gradients are accumulated, so the
        step equals a step on the whole batch up to the per-sample averaging inside the loss."""
        set_lr(self.opt, lr)
        self.opt.zero_grad(set_to_none=True)
        tot = {"loss": 0.0, "ctc": 0.0, "nrtr": 0.0}
        for ch in chunks:
            w = len(ch["gid"]) / float(B)
            loss, info = self.train_step_loss(ch, device)
            (loss * w).backward()
            tot["loss"] += float(loss.detach()) * w
            tot["ctc"] += info["ctc"] * w
            tot["nrtr"] += info["nrtr"] * w
        self.opt.step()
        return tot

    def clear_grads(self):
        self.opt.zero_grad(set_to_none=True)

    def after_step(self, step):
        pass

    # -- inference
    @torch.no_grad()
    def infer(self, images, seq_lens, device):
        with torch.autocast("cuda", dtype=torch.bfloat16, enabled=(device.type == "cuda" and AMP["on"])):
            logits, out_lens = self.net.nn(images.to(device), seq_lens.to(device))
        lp = logits.float().log_softmax(1).squeeze(2).permute(0, 2, 1)   # B,T,C
        return lp, out_lens

    # -- state
    def state(self):
        return {"net": self.net.state_dict(), "aux": self.aux.state_dict(), "opt": self.opt.state_dict()}

    def load_state(self, st, with_opt=True):
        self.net.load_state_dict(st["net"])
        self.aux.load_state_dict(st["aux"])
        if with_opt and "opt" in st and hasattr(self, "opt"):
            self.opt.load_state_dict(st["opt"])

    def inference_state(self):
        return {"net": self.net.state_dict()}

    def load_inference_state(self, st):
        self.net.load_state_dict(st["net"])

    def arch(self):
        return {"deployed": layer_report(self.net.nn), "aux_training_only": layer_report(self.aux, 1)[0]}


# ------------------------------------------------------------------------------------------------ A3: CRNN
def _cbr(i, o):
    return [nn.Conv2d(i, o, 3, padding=1, bias=False), nn.BatchNorm2d(o), nn.ReLU(inplace=True)]


class CRNN(nn.Module):
    """Input (B,1,64,W) -> (B, W//4, n_classes). 6 conv layers, two BiLSTM layers of 256."""

    def __init__(self, n_classes, hidden=256):
        super().__init__()
        layers = []
        layers += _cbr(1, 32) + [nn.MaxPool2d(2, 2)]
        layers += _cbr(32, 64) + [nn.MaxPool2d(2, 2)]
        layers += _cbr(64, 128) + _cbr(128, 128) + [nn.MaxPool2d((2, 1))]
        layers += _cbr(128, 256) + _cbr(256, 256) + [nn.MaxPool2d((2, 1))]
        self.cnn = nn.Sequential(*layers)
        self.drop = nn.Dropout(0.2)
        self.rnn = nn.LSTM(256 * 4, hidden, num_layers=2, bidirectional=True, batch_first=True, dropout=0.2)
        self.fc = nn.Linear(2 * hidden, n_classes)

    @staticmethod
    def out_lengths(seq_lens):
        return (seq_lens // 2) // 2

    def forward(self, x, seq_lens):
        f = self.cnn(x)                                  # B,256,4,W/4
        B, C, H, T = f.shape
        f = f.permute(0, 3, 1, 2).reshape(B, T, C * H)
        ol = self.out_lengths(seq_lens).clamp(min=1, max=T)
        packed = nn.utils.rnn.pack_padded_sequence(self.drop(f), ol.cpu(), batch_first=True, enforce_sorted=False)
        out, _ = self.rnn(packed)
        out, _ = nn.utils.rnn.pad_packed_sequence(out, batch_first=True, total_length=T)
        return self.fc(out), ol


class CRNNArm:
    kind = "crnn"

    def __init__(self, name, codec):
        self.name, self.codec = name, codec
        self.net = CRNN(codec.max_label + 1)

    def modules(self):
        return [self.net]

    def to(self, dev):
        self.net.to(dev)
        return self

    def train(self):
        self.net.train()

    def eval(self):
        self.net.eval()

    def deploy_params(self):
        return n_params(self.net)

    def make_optimizer(self, lr):
        self.opt = torch.optim.AdamW(self.net.parameters(), lr=lr, betas=(0.9, 0.999), weight_decay=0.01)
        self.group_report = [("adamw_all", n_params(self.net), False)]
        return self.opt

    def train_chunks(self, chunks, B, device, lr, max_grad=5.0):
        set_lr(self.opt, lr)
        self.opt.zero_grad(set_to_none=True)
        tot = 0.0
        for ch in chunks:
            w = len(ch["gid"]) / float(B)
            img = ch["image"].to(device, non_blocking=True)
            sl = ch["seq_lens"].to(device)
            with torch.autocast("cuda", dtype=torch.bfloat16, enabled=(device.type == "cuda" and AMP["on"])):
                logits, ol = self.net(img, sl)
            loss = ctc_from_logits(logits, ol, ch["target"].to(device), ch["target_lens"].to(device))
            (loss * w).backward()
            tot += float(loss.detach()) * w
        nn.utils.clip_grad_norm_(self.net.parameters(), max_grad)
        self.opt.step()
        return {"loss": tot, "ctc": tot}

    def clear_grads(self):
        self.opt.zero_grad(set_to_none=True)

    def after_step(self, step):
        pass

    @torch.no_grad()
    def infer(self, images, seq_lens, device):
        with torch.autocast("cuda", dtype=torch.bfloat16, enabled=(device.type == "cuda" and AMP["on"])):
            logits, ol = self.net(images.to(device), seq_lens.to(device))
        return logits.float().log_softmax(-1), ol

    def state(self):
        return {"net": self.net.state_dict(), "opt": self.opt.state_dict()}

    def load_state(self, st, with_opt=True):
        self.net.load_state_dict(st["net"])
        if with_opt and "opt" in st and hasattr(self, "opt"):
            self.opt.load_state_dict(st["opt"])

    def inference_state(self):
        return {"net": self.net.state_dict()}

    def load_inference_state(self, st):
        self.net.load_state_dict(st["net"])

    def arch(self):
        return {"deployed": layer_report(self.net)}


# ------------------------------------------------------------------------------------------------ A4: HTR-VT design
class _BasicBlock(nn.Module):
    def __init__(self, inp, planes, stride=1, downsample=None):
        super().__init__()
        self.conv1 = nn.Conv2d(inp, planes, 3, stride, 1, bias=False)
        self.bn1 = nn.BatchNorm2d(planes, eps=1e-5)
        self.relu = nn.ReLU(inplace=True)
        self.conv2 = nn.Conv2d(planes, planes, 3, 1, 1, bias=False)
        self.bn2 = nn.BatchNorm2d(planes, eps=1e-5)
        self.downsample = downsample

    def forward(self, x):
        res = x if self.downsample is None else self.downsample(x)
        out = self.relu(self.bn1(self.conv1(x)))
        out = self.bn2(self.conv2(out))
        return self.relu(out + res)


class _ResNet18Stem(nn.Module):
    """model/resnet18.py of HTR-VT: three stages (the last residual stage of ResNet-18 is removed), strides chosen so the
    height collapses and the width is divided by 4 (conv1/maxpool/layer1 stride (2,1), layer2/layer3 stride 2)."""

    def __init__(self, nb_feat=768):
        super().__init__()
        self.inplanes = nb_feat // 4
        self.conv1 = nn.Conv2d(1, nb_feat // 4, 3, stride=(2, 1), padding=1, bias=False)
        self.bn1 = nn.BatchNorm2d(nb_feat // 4, eps=1e-5)
        self.relu = nn.ReLU(inplace=True)
        self.maxpool = nn.MaxPool2d(3, stride=(2, 1), padding=1)
        self.layer1 = self._make(nb_feat // 4, 2, (2, 1))
        self.layer2 = self._make(nb_feat // 2, 2, 2)
        self.layer3 = self._make(nb_feat, 2, 2)

    def _make(self, planes, blocks, stride):
        ds = None
        if stride != 1 or self.inplanes != planes:
            ds = nn.Sequential(nn.Conv2d(self.inplanes, planes, 1, stride=stride, bias=False), nn.BatchNorm2d(planes, eps=1e-5))
        layers = [_BasicBlock(self.inplanes, planes, stride, ds)]
        self.inplanes = planes
        layers += [_BasicBlock(planes, planes) for _ in range(1, blocks)]
        return nn.Sequential(*layers)

    def forward(self, x):
        x = self.maxpool(self.relu(self.bn1(self.conv1(x))))
        x = self.layer3(self.layer2(self.layer1(x)))
        return self.maxpool(x)


def _sincos_1d(dim, pos):
    omega = 1.0 / 10000 ** (np.arange(dim // 2, dtype=np.float64) / (dim / 2.0))
    out = np.einsum("m,d->md", pos.reshape(-1), omega)
    return np.concatenate([np.sin(out), np.cos(out)], axis=1)


def sincos_2d(dim, grid_hw):
    gh = np.arange(grid_hw[0], dtype=np.float32)
    gw = np.arange(grid_hw[1], dtype=np.float32)
    grid = np.stack(np.meshgrid(gw, gh), axis=0).reshape([2, 1, grid_hw[0], grid_hw[1]])
    return np.concatenate([_sincos_1d(dim // 2, grid[0]), _sincos_1d(dim // 2, grid[1])], axis=1)


class _TBlock(nn.Module):
    def __init__(self, dim, heads, mlp_ratio=4):
        super().__init__()
        self.heads = heads
        self.norm1 = nn.LayerNorm(dim, eps=1e-6)
        self.qkv = nn.Linear(dim, dim * 3, bias=True)
        self.proj = nn.Linear(dim, dim)
        self.norm2 = nn.LayerNorm(dim, eps=1e-6)
        self.fc1 = nn.Linear(dim, int(dim * mlp_ratio))
        self.fc2 = nn.Linear(int(dim * mlp_ratio), dim)

    def forward(self, x):
        B, N, C = x.shape
        q, k, v = self.qkv(self.norm1(x)).reshape(B, N, 3, self.heads, C // self.heads).permute(2, 0, 3, 1, 4).unbind(0)
        a = F.scaled_dot_product_attention(q, k, v).transpose(1, 2).reshape(B, N, C)
        x = x + self.proj(a)
        return x + self.fc2(F.gelu(self.fc1(self.norm2(x))))


def _plain_ln(x):
    return F.layer_norm(x, x.size()[1:], weight=None, bias=None, eps=1e-5)


class HTRVT(nn.Module):
    """model/HTR_VT.py: layer norm of the input, ResNet stem, optional span masking with a learnable mask token, fixed
    sin-cos position embedding, 4 pre-norm transformer blocks, final norm, linear head, parameter-free layer norm of the
    logits. Image 64 high and 1024 wide gives 256 tokens (the paper uses 64 x 512 and 128 tokens)."""

    def __init__(self, n_classes, width_px=1024, dim=768, depth=4, heads=6, output_ln=True):
        super().__init__()
        self.output_ln = output_ln
        self.stem = _ResNet18Stem(dim)
        self.tokens = width_px // 4
        self.mask_token = nn.Parameter(torch.zeros(1, 1, dim))
        self.register_buffer("pos_embed", torch.from_numpy(sincos_2d(dim, (16, self.tokens // 16))).float().unsqueeze(0))
        self.blocks = nn.ModuleList([_TBlock(dim, heads) for _ in range(depth)])
        self.norm = nn.LayerNorm(dim, eps=1e-6)
        self.head = nn.Linear(dim, n_classes)
        nn.init.normal_(self.mask_token, std=0.02)
        for m in self.modules():
            if isinstance(m, nn.Linear):
                nn.init.xavier_uniform_(m.weight)
                if m.bias is not None:
                    nn.init.constant_(m.bias, 0)

    def span_mask(self, x, ratio, span):
        N, L, _ = x.shape
        mask = torch.ones(N, L, 1, device=x.device, dtype=x.dtype)
        n_spans = int(L * ratio) // span
        for _ in range(n_spans):
            idx = torch.randint(0, L - span, (N,), device=x.device)
            ar = torch.arange(L, device=x.device)[None, :]
            m = ((ar >= idx[:, None]) & (ar < idx[:, None] + span)).unsqueeze(-1)
            mask = mask * (~m).to(x.dtype)
        return x * mask + (1 - mask) * self.mask_token

    def forward(self, x, mask_ratio=0.0, span=1, use_masking=False):
        x = _plain_ln(x)
        x = self.stem(x)                                # B,768,1,T
        b, c = x.shape[:2]
        x = x.reshape(b, c, -1).permute(0, 2, 1)        # B,T,768
        if use_masking:
            x = self.span_mask(x, mask_ratio, span)
        x = x + self.pos_embed.to(x.dtype)
        for blk in self.blocks:
            x = blk(x)
        x = self.head(self.norm(x))
        return _plain_ln(x) if self.output_ln else x


class SAM(torch.optim.Optimizer):
    """utils/sam.py of HTR-VT (rho 0.05, not adaptive), unchanged in logic."""

    def __init__(self, params, base_optimizer, rho=0.05, **kwargs):
        defaults = dict(rho=rho, adaptive=False, **kwargs)
        super().__init__(params, defaults)
        self.base_optimizer = base_optimizer(self.param_groups, **kwargs)
        self.param_groups = self.base_optimizer.param_groups
        self.defaults.update(self.base_optimizer.defaults)

    @torch.no_grad()
    def first_step(self):
        gn = torch.norm(torch.stack([p.grad.norm(p=2) for g in self.param_groups for p in g["params"] if p.grad is not None]), p=2)
        for g in self.param_groups:
            scale = g["rho"] / (gn + 1e-12)
            for p in g["params"]:
                if p.grad is None:
                    continue
                self.state[p]["old_p"] = p.data.clone()
                p.add_(p.grad * scale.to(p))
        self.zero_grad()

    @torch.no_grad()
    def second_step(self):
        for g in self.param_groups:
            for p in g["params"]:
                if p.grad is None:
                    continue
                p.data = self.state[p]["old_p"]
        self.base_optimizer.step()
        self.zero_grad()


class HTRVTArm:
    kind = "htrvt"
    MASK_RATIO, SPAN = 0.4, 8      # run/lam.sh: --mask-ratio 0.4 --max-span-length 8

    def __init__(self, name, codec, width_px=1024):
        self.name, self.codec = name, codec
        self.net = HTRVT(codec.max_label + 1, width_px=width_px, output_ln=A4_OPTS["output_ln"])
        self.ema = copy.deepcopy(self.net).eval()
        for p in self.ema.parameters():
            p.requires_grad_(False)
        self.ema_decay = 0.9999
        self.n_updates = 0

    def modules(self):
        return [self.net, self.ema]

    def to(self, dev):
        self.net.to(dev)
        self.ema.to(dev)
        return self

    def train(self):
        self.net.train()
        self.ema.eval()

    def eval(self):
        self.net.eval()
        self.ema.eval()

    def deploy_params(self):
        return n_params(self.net)

    def make_optimizer(self, lr):
        # run/lam.sh and train.py: AdamW betas (0.9, 0.99), weight decay 0.5, SAM rho 0.05
        self.opt = SAM(self.net.parameters(), torch.optim.AdamW, lr=lr, betas=(0.9, 0.99), weight_decay=0.5)
        self.group_report = [("sam_adamw_all", n_params(self.net), False)]
        return self.opt

    def _loss(self, batch, device):
        img = batch["image"].to(device, non_blocking=True)
        with torch.autocast("cuda", dtype=torch.bfloat16, enabled=(device.type == "cuda" and AMP["on"])):
            logits = self.net(img, self.MASK_RATIO, self.SPAN, use_masking=True)
        B, T, _ = logits.shape
        il = torch.full((B,), T, dtype=torch.long, device=device)
        return ctc_from_logits(logits, il, batch["target"].to(device), batch["target_lens"].to(device))

    def train_chunks(self, chunks, B, device, lr):
        set_lr(self.opt, lr)
        self.opt.zero_grad(set_to_none=True)
        tot = 0.0
        self._perturbed = False
        for ch in chunks:
            w = len(ch["gid"]) / float(B)
            loss = self._loss(ch, device)
            (loss * w).backward()
            tot += float(loss.detach()) * w
        self.opt.first_step()
        self._perturbed = True
        for ch in chunks:
            w = len(ch["gid"]) / float(B)
            (self._loss(ch, device) * w).backward()
        self.opt.second_step()
        self._perturbed = False
        return {"loss": tot, "ctc": tot}

    def clear_grads(self):
        # after an out-of-memory error in the second pass the weights are still at the perturbed point: put them back
        if getattr(self, "_perturbed", False):
            with torch.no_grad():
                for g in self.opt.param_groups:
                    for p in g["params"]:
                        st = self.opt.state.get(p, {})
                        if "old_p" in st:
                            p.data = st["old_p"]
            self._perturbed = False
        self.opt.zero_grad(set_to_none=True)

    def after_step(self, step):
        # utils.ModelEma with num_updates = nb_iter / 2 as in train.py
        self.n_updates += 1
        n = self.n_updates / 2.0
        d = min(self.ema_decay, (1 + n) / (10 + n))
        with torch.no_grad():
            msd = self.net.state_dict()
            for k, ev in self.ema.state_dict().items():
                mv = msd[k].detach()
                if ev.dtype.is_floating_point:
                    ev.copy_(ev * d + (1.0 - d) * mv)
                else:
                    ev.copy_(mv)

    @torch.no_grad()
    def infer(self, images, seq_lens, device):
        with torch.autocast("cuda", dtype=torch.bfloat16, enabled=(device.type == "cuda" and AMP["on"])):
            logits = self.ema(images.to(device))
        B, T, _ = logits.shape
        return logits.float().log_softmax(-1), torch.full((B,), T, dtype=torch.long, device=device)

    def state(self):
        return {"net": self.net.state_dict(), "ema": self.ema.state_dict(), "opt": self.opt.state_dict(),
                "n_updates": self.n_updates}

    def load_state(self, st, with_opt=True):
        self.net.load_state_dict(st["net"])
        self.ema.load_state_dict(st["ema"])
        self.n_updates = st.get("n_updates", 0)
        if with_opt and "opt" in st and hasattr(self, "opt"):
            self.opt.load_state_dict(st["opt"])

    def inference_state(self):
        return {"ema": self.ema.state_dict()}

    def load_inference_state(self, st):
        self.ema.load_state_dict(st["ema"])

    def arch(self):
        return {"deployed": layer_report(self.net)}


# ------------------------------------------------------------------------------------------------ factory
BASE = {"A1": ("medium", "zenodo_ppocrv6_medium_21788410/medium.safetensors"),
        "A2": ("small", "zenodo_ppocrv6_small_21788405/small.safetensors")}


def build_arm(name, codec, data_dir):
    from .data import SPECS
    if name in ("A1", "A2"):
        variant, rel = BASE[name]
        return PPOCRArm(name, variant, codec, base_weights=data_dir + "/data/raw/" + rel)
    if name == "A1s":
        return PPOCRArm(name, "medium", codec, base_weights=None, height=SPECS[name].height)
    if name == "A3":
        return CRNNArm(name, codec)
    if name == "A4":
        return HTRVTArm(name, codec, width_px=SPECS[name].fixed_width)
    raise ValueError(name)


def build_arm_for_inference(name, codec):
    """Same architectures without base weights (the weights come from the checkpoint)."""
    from .data import SPECS
    if name in ("A1", "A2", "A1s"):
        variant = "small" if name == "A2" else "medium"
        return PPOCRArm(name, variant, codec, base_weights=None, height=SPECS[name].height)
    return build_arm(name, codec, None)