File size: 22,619 Bytes
7215e83
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""

Layer 4 Self-Supervised Pretraining: Whole-Word Masked Statutory Language Modeling (MLM)

========================================================================================

Pretrains the ENTIRE Stage 1 Atomic Encoder end-to-end from scratch on the verified

100% leak-free, 100% real verbatim statutory tax corpus (India ITA 2025 + India CGST 2017

+ OKF/CBDT Circulars + US IRC Title 26 with all 9 SARA & Fold 1 validation texts purged):



  - Layer 1: 8,192 Boundary-Aware Subword 3-5-gram Buckets (1/sqrt(N) + LayerNorm)

  - Layer 2: 3-Zone Positional Character CNN (BOS/EOS + Prefix/Root/Suffix + LayerNorm)

  - Layer 3: Word Embedding (std=0.05 init + 35% unmasked word dropout + LayerNorm)

  - Layer 4: Discourse Geometry Projection + LayerNorm + In-Projection + ALL 4

             Delimiter-Penalized Transformer Encoder Layers + Out-Norm



Whole-Word Synchronized Masking (15% of tokens, 80/10/10 BERT/RoBERTa schedule):

  - When masked (80%), w_id, sw_ids, c_mat, AND lexical geom features (0:9) are ALL

    masked simultaneously so the encoder cannot cheat via spelling or lookup anchors

    and must learn true statutory syntax and slot semantics across clauses.



Strict Rules:

  - 100% From-Scratch PyTorch (Zero HuggingFace, Zero External Pretrained Weights)

  - Strictly ZERO Regex (Self-Audited AST)

  - Peak VRAM < 1.5 GB on RTX 3050 Laptop GPU

"""

from __future__ import annotations
import os

import argparse
import ast
from collections import Counter
import json
import math
from pathlib import Path
import random
import sys
import time

import torch
import torch.nn as nn
import torch.nn.functional as F

ROOT_DIR = Path(os.environ.get("MUDRAFORGE_ROOT", str(Path(__file__).resolve().parent.parent)))
SRC_DIR = ROOT_DIR / "src"
if str(SRC_DIR) not in sys.path:
    sys.path.insert(0, str(SRC_DIR))

import core_features as v2
from models import (
    SpecialistAtomicModel,
    get_cosine_schedule_with_warmup,
)
from lexical_encoder import (
    SUBWORD_BUCKETS,
    MAX_SUBWORDS_PER_TOKEN,
    MAX_CHARS_BOUNDED,
    extract_subword_ids,
    char_tensor_bounded,
    mask_subword_ids,
    mask_char_tensor,
)
from corporate_finance_lexicon import (
    build_comprehensive_corporate_finance_salient_words,
)

CORPUS_JSONL = ROOT_DIR / "data" / "corpus_2_5m.jsonl"
OUT_CKPT = ROOT_DIR / "checkpoints" / "backbone_mlm_2_5m.pt"

PAD_ID = 0
UNK_ID = 1
MASK_ID = 2
MLM_VOCAB_MAX = 16384


def build_mlm_vocab(

    chunks: list[dict],

    max_words: int = MLM_VOCAB_MAX,

    salient_words: set[str] | None = None,

) -> tuple[dict[str, int], list[str], set[int]]:
    counts: Counter = Counter()
    for ch in chunks:
        for t in ch["tokens"]:
            counts[t.lower()] += 1

    used_buckets: set[int] = set()
    for w in counts:
        for bid in extract_subword_ids(w):
            if bid != 0:
                used_buckets.add(bid)

    vocab = {"<pad>": PAD_ID, "<unk>": UNK_ID, "<mask>": MASK_ID}
    id_to_word = ["<pad>", "<unk>", "<mask>"]

    # Explicitly seed all salient domain words first so they are NEVER mapped to <unk>
    if salient_words:
        for w in sorted(salient_words):
            if w not in vocab:
                vocab[w] = len(vocab)
                id_to_word.append(w)
                for bid in extract_subword_ids(w):
                    if bid != 0:
                        used_buckets.add(bid)

    for w, _ in counts.most_common():
        if w not in vocab:
            vocab[w] = len(vocab)
            id_to_word.append(w)
            if len(vocab) >= max_words:
                break

    return vocab, id_to_word, used_buckets


def precompute_word_tables(id_to_word: list[str]) -> tuple[torch.Tensor, torch.Tensor]:
    """Precompute subword and bounded-char lookup tables for every word in mlm_vocab

    so random-word 10% MLM replacements are O(1) tensor gathers."""
    V = len(id_to_word)
    sw_tbl = torch.zeros((V, MAX_SUBWORDS_PER_TOKEN), dtype=torch.long)
    ch_tbl = torch.zeros((V, MAX_CHARS_BOUNDED), dtype=torch.long)
    for i, w in enumerate(id_to_word):
        if i == PAD_ID:
            continue
        elif i == MASK_ID:
            sw_tbl[i] = torch.tensor(mask_subword_ids(), dtype=torch.long)
            ch_tbl[i] = torch.tensor(mask_char_tensor(), dtype=torch.long)
        else:
            sw_tbl[i] = torch.tensor(extract_subword_ids(w), dtype=torch.long)
            ch_tbl[i] = torch.tensor(char_tensor_bounded(w), dtype=torch.long)
    return sw_tbl, ch_tbl


def collate_and_mask_batch(

    batch_chunks: list[dict],

    mlm_vocab: dict[str, int],

    sw_tbl: torch.Tensor,

    ch_tbl: torch.Tensor,

    mask_sw_vec: torch.Tensor,

    mask_ch_vec: torch.Tensor,

    rng: random.Random,

    salient_set: set[str] | None = None,

    mask_prob: float = 0.15,

) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
    """Collate a batch of raw statutory chunks into padded tensors and apply whole-word

    synchronized 80/10/10 MLM masking with targeted salient operand and numeric biasing."""
    B = len(batch_chunks)
    max_T = max(len(ch["tokens"]) for ch in batch_chunks)
    V = sw_tbl.size(0)

    w_ids = torch.zeros((B, max_T), dtype=torch.long)
    c_mat = torch.zeros((B, max_T, MAX_CHARS_BOUNDED), dtype=torch.long)
    sw_ids = torch.zeros((B, max_T, MAX_SUBWORDS_PER_TOKEN), dtype=torch.long)
    g_feat = torch.zeros((B, max_T, 36), dtype=torch.float32)
    c_idx = torch.zeros((B, max_T), dtype=torch.long)
    pad_mask = torch.ones((B, max_T), dtype=torch.bool)  # True = PAD
    labels = torch.full((B, max_T), -100, dtype=torch.long)

    for b, ch in enumerate(batch_chunks):
        toks = ch["tokens"]
        offsets = ch["offsets"]
        text = ch["text"]
        T = len(toks)

        pad_mask[b, :T] = False
        gf = v2.extract_28d_discourse_geometry(toks, offsets, text)
        ci = v2.compute_clause_indices(toks)
        g_feat[b, :T] = gf
        c_idx[b, :T] = ci
        if T < max_T:
            # Keep padded clause indices monotonic far away from real tokens
            c_idx[b, T:] = int(ci[-1].item()) + 100

        for t, tok in enumerate(toks):
            tl = tok.lower()
            wid = mlm_vocab.get(tl, UNK_ID)
            w_ids[b, t] = wid
            if wid >= 3:
                sw_ids[b, t] = sw_tbl[wid]
                c_mat[b, t] = ch_tbl[wid]
            else:
                sw_ids[b, t] = torch.tensor(extract_subword_ids(tok), dtype=torch.long)
                c_mat[b, t] = torch.tensor(char_tensor_bounded(tok), dtype=torch.long)

        # Synchronized whole-word Salient Domain Masking:
        # If token is an operand/numeric concept: 35% probability
        # If token is generic context word: 10% probability
        masked_any = False
        for t in range(T):
            target_id = int(w_ids[b, t].item())
            if target_id < 3:
                continue
            is_salient = salient_set is not None and toks[t].lower() in salient_set
            p_mask = 0.35 if is_salient else 0.10
            if rng.random() < p_mask:
                masked_any = True
                labels[b, t] = target_id
                r = rng.random()
                if r < 0.80:
                    # 80%: Full synchronized [MASK] across ALL lexical & anchor channels
                    w_ids[b, t] = MASK_ID
                    sw_ids[b, t] = mask_sw_vec
                    c_mat[b, t] = mask_ch_vec
                    g_feat[b, t, 0:9] = 0.0
                elif r < 0.90:
                    # 10%: Random statutory word consistently across lexical channels
                    rand_id = rng.randint(3, V - 1)
                    w_ids[b, t] = rand_id
                    sw_ids[b, t] = sw_tbl[rand_id]
                    c_mat[b, t] = ch_tbl[rand_id]
                    g_feat[b, t, 0:9] = 0.0
                else:
                    # 10%: Unchanged token
                    pass

        # Ensure at least 1 masked token per sequence so gradient is always defined
        if not masked_any:
            valid_pos = [t for t in range(T) if int(w_ids[b, t].item()) >= 3]
            if valid_pos:
                t = rng.choice(valid_pos)
                labels[b, t] = int(w_ids[b, t].item())
                w_ids[b, t] = MASK_ID
                sw_ids[b, t] = mask_sw_vec
                c_mat[b, t] = mask_ch_vec
                g_feat[b, t, 0:9] = 0.0

    return w_ids, c_mat, sw_ids, g_feat, c_idx, pad_mask, labels


class MLMPretrainWrapper(nn.Module):
    def __init__(self, encoder: SpecialistAtomicModel, mlm_vocab_size: int):
        super().__init__()
        self.encoder = encoder
        d = encoder.d_model
        self.mlm_head = nn.Sequential(
            nn.Linear(d, d),
            nn.GELU(),
            nn.LayerNorm(d),
            nn.Linear(d, mlm_vocab_size),
        )

    def forward(

        self,

        w_ids: torch.Tensor,

        c_mat: torch.Tensor,

        g_feat: torch.Tensor,

        c_idx: torch.Tensor,

        sw_ids: torch.Tensor,

        pad_mask: torch.Tensor,

    ) -> torch.Tensor:
        h = self.encoder.encode(
            w_ids,
            c_mat,
            g_feat,
            c_idx,
            sw_ids=sw_ids,
            key_padding_mask=pad_mask,
        )
        return self.mlm_head(h)


def run_subword_semantic_probe(encoder: SpecialistAtomicModel, id_to_word: list[str], device: torch.device) -> None:
    """Inspect top-5 cosine neighbors in learned subword space on generic statutory probes

    (never touches any validation data)."""
    probe_words = [
        "remuneration", "assessee", "deductor", "royalty", "exceeds",
        "notwithstanding", "taxpayer", "turnover", "amortization", "amortisation",
        "ebitda", "debenture", "slump", "covenant", "withholding"
    ]
    cand_words = [w for w in id_to_word[3:5000] if len(w) >= 4 and w.isalpha()]
    if not cand_words:
        return

    encoder.eval()
    with torch.no_grad():
        sw_emb = encoder.lexical_encoder.subword_emb
        sw_norm = encoder.lexical_encoder.sw_norm

        def embed_list(words: list[str]) -> torch.Tensor:
            ids = torch.tensor([extract_subword_ids(w) for w in words], dtype=torch.long, device=device)
            e = sw_emb(ids)
            cnt = (ids != 0).sum(dim=1, keepdim=True).clamp(min=1).float()
            v = sw_norm(e.sum(dim=1) / torch.sqrt(cnt))
            return F.normalize(v, dim=-1)

        cand_vecs = embed_list(cand_words)
        probe_vecs = embed_list(probe_words)
        sims = torch.matmul(probe_vecs, cand_vecs.t())

        print("\n--- Pretrained Subword Semantic Probe (Top-5 Cosine Neighbors) ---")
        for i, pw in enumerate(probe_words):
            vals, idxs = torch.topk(sims[i], k=8)
            nbrs = []
            for v, j in zip(vals.tolist(), idxs.tolist()):
                cw = cand_words[j]
                if cw != pw:
                    nbrs.append(f"{cw}({v:.2f})")
                if len(nbrs) == 5:
                    break
            print(f"  {pw:<16} -> {', '.join(nbrs)}")


def main():
    # Self-audit zero regex
    src_code = Path(__file__).read_text(encoding="utf-8")
    tree = ast.parse(src_code)
    for node in ast.walk(tree):
        if isinstance(node, ast.Import) and any(a.name == "re" for a in node.names):
            raise RuntimeError("FORBIDDEN: import re detected")
        if isinstance(node, ast.ImportFrom) and node.module == "re":
            raise RuntimeError("FORBIDDEN: from re import detected")

    parser = argparse.ArgumentParser(description="Salient Domain MLM Pretraining")
    parser.add_argument("--corpus", type=str, default=str(ROOT_DIR / "data" / "corpus_mlm_v3_unified.jsonl"), help="Path to pretraining corpus JSONL")
    parser.add_argument("--steps", type=int, default=8000, help="Total pretraining steps")
    parser.add_argument("--batch_size", type=int, default=16, help="Batch size")
    parser.add_argument("--lr", type=float, default=8e-4, help="Learning rate")
    parser.add_argument("--vocab_size", type=int, default=24576, help="MLM target vocabulary size")
    parser.add_argument("--ckpt_out", type=str, default=str(ROOT_DIR / "checkpoints" / "stage0_backbone_mlm_v3.pt"))
    args = parser.parse_args()

    print("================================================================================")
    print("LAYER 4 PRETRAINING: WHOLE-WORD SALIENT-SPAN STATUTORY MLM (v3-corpfin)")
    print(f"Corpus: {args.corpus}")
    print(f"Target Checkpoint: {args.ckpt_out}")
    print("================================================================================")

    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    torch.manual_seed(42)
    random.seed(42)
    rng = random.Random(42)

    corpus_file = Path(args.corpus)
    chunks: list[dict] = []
    with open(corpus_file, "r", encoding="utf-8") as f:
        for line in f:
            chunks.append(json.loads(line))
    print(f"Loaded {len(chunks):,} pretraining chunks from {corpus_file.name}")

    if corpus_file.name != "corpus_mlm_v3_unified.jsonl":
        # Add verified mined Indian computational chunks (0% holdout overlap)
        mined_path = ROOT_DIR / "data" / "mined_indian_comp_fold1.json"
        if mined_path.exists():
            d_mined = json.loads(mined_path.read_text(encoding="utf-8"))
            for m in d_mined:
                chunks.append({
                    "source": "IN_MINED_2025",
                    "tokens": m["tokens"],
                    "offsets": m["offsets"],
                    "text": m["text"],
                })
            print(f"Appended {len(d_mined):,} verified Indian computational chunks from {mined_path.name}")

        pass

    # Build salient domain token set
    from models import NUMERIC_METRIC_KEYWORDS, CATEGORY_FILTER_KEYWORDS, DOC_POINTER_KEYWORDS
    salient_words = set(NUMERIC_METRIC_KEYWORDS) | set(CATEGORY_FILTER_KEYWORDS) | set(DOC_POINTER_KEYWORDS)
    gt_path = ROOT_DIR / "data" / "ground_truth_250.json"
    if gt_path.exists():
        d_gt = json.loads(gt_path.read_text(encoding="utf-8"))
        for d in d_gt:
            for sp in d.get("atomic_spans", []):
                if sp["label"] in ("OPERAND", "MONEY", "RATE", "COUNT", "OP", "ACTOR_SCOPE", "DEFINED_TERM"):
                    for t in d["tokens"][sp["tokStart"]:sp["tokEnd"]+1]:
                        salient_words.add(t.lower())

    # Ingest full corporate finance lexicon + British/American spelling pairs
    corpfin_salient = build_comprehensive_corporate_finance_salient_words()
    salient_words.update(corpfin_salient)
    print(f"Compiled {len(salient_words):,} total Salient Domain Tokens (including {len(corpfin_salient):,} corporate finance & dual-spelling terms).")

    india_chunks = [c for c in chunks if c.get("source", "").startswith("IN_")]
    us_chunks = [c for c in chunks if c.get("source", "").startswith("US_")]
    grounding_chunks = [c for c in chunks if not c.get("source", "").startswith("IN_") and not c.get("source", "").startswith("US_")]
    print(f"Loaded Corpus: {len(chunks):,} total chunks | India: {len(india_chunks):,} | US IRC: {len(us_chunks):,} | Grounding/Other: {len(grounding_chunks):,}")

    mlm_vocab, id_to_word, used_buckets = build_mlm_vocab(chunks, max_words=args.vocab_size, salient_words=salient_words)
    print(f"MLM Target Vocab Size: {len(mlm_vocab):,} | Active Subword Buckets: {len(used_buckets):,} / {SUBWORD_BUCKETS:,}")

    sw_tbl, ch_tbl = precompute_word_tables(id_to_word)
    mask_sw_vec = torch.tensor(mask_subword_ids(), dtype=torch.long)
    mask_ch_vec = torch.tensor(mask_char_tensor(), dtype=torch.long)

    # Full Stage 1 encoder with 35% unmasked word dropout so Transformer MUST read via subword + 3-zone char
    encoder = SpecialistAtomicModel(
        vocab_size=len(mlm_vocab),
        use_subword_v2=True,
        subword_buckets=SUBWORD_BUCKETS,
        word_dropout=0.35,
    )
    wrapper = MLMPretrainWrapper(encoder, mlm_vocab_size=len(mlm_vocab)).to(device)

    total_params = sum(p.numel() for p in wrapper.parameters())
    enc_params = sum(p.numel() for p in encoder.parameters())
    print(f"Device: {device} | Encoder Params: {enc_params:,} | Total MLM Params: {total_params:,}")

    batch_size = args.batch_size
    total_steps = args.steps
    warmup_steps = 400
    log_every = 250

    optimizer = torch.optim.AdamW(wrapper.parameters(), lr=args.lr, weight_decay=1e-2)
    scheduler = get_cosine_schedule_with_warmup(
        optimizer,
        num_warmup_steps=warmup_steps,
        num_training_steps=total_steps,
        min_lr_ratio=0.05,
    )
    use_amp = device.type == "cuda"
    scaler = torch.amp.GradScaler("cuda", enabled=use_amp)

    # Sort jurisdiction pools by length slightly within shuffled super-batches for tight padding
    def sample_balanced_batch() -> list[dict]:
        batch = []
        n_ground = 1 if (grounding_chunks and rng.random() < 0.3) else 0
        rem = batch_size - n_ground
        n_in = rem // 2 if (india_chunks and us_chunks) else (rem if india_chunks else 0)
        n_us = rem - n_in
        for _ in range(n_in):
            batch.append(rng.choice(india_chunks))
        for _ in range(n_us):
            batch.append(rng.choice(us_chunks))
        for _ in range(n_ground):
            batch.append(rng.choice(grounding_chunks))
        return batch
        return batch

    print(f"\nStarting MLM Pretraining: {total_steps:,} steps x batch {batch_size} ({total_steps * batch_size:,} chunks, 50/50 India/US balanced)")
    print(f"{'Step':<10} {'Loss':>8} {'PPL':>8} {'Top1':>8} {'Top5':>8} {'LR':>10} {'Tok/s':>9} {'Elapsed':>9}")
    print("-" * 80)

    t0 = time.time()
    win_loss = 0.0
    win_top1 = 0
    win_top5 = 0
    win_masked = 0
    win_tokens = 0
    win_t0 = time.time()

    wrapper.train()
    for step in range(1, total_steps + 1):
        batch = sample_balanced_batch()
        w_ids, c_mat, sw_ids, g_feat, c_idx, pad_mask, labels = collate_and_mask_batch(
            batch, mlm_vocab, sw_tbl, ch_tbl, mask_sw_vec, mask_ch_vec, rng, salient_set=salient_words
        )
        w_ids = w_ids.to(device, non_blocking=True)
        c_mat = c_mat.to(device, non_blocking=True)
        sw_ids = sw_ids.to(device, non_blocking=True)
        g_feat = g_feat.to(device, non_blocking=True)
        c_idx = c_idx.to(device, non_blocking=True)
        pad_mask = pad_mask.to(device, non_blocking=True)
        labels = labels.to(device, non_blocking=True)

        optimizer.zero_grad(set_to_none=True)
        with torch.amp.autocast("cuda", enabled=use_amp):
            logits = wrapper(w_ids, c_mat, g_feat, c_idx, sw_ids, pad_mask)  # (B, T, V)
            loss = F.cross_entropy(logits.view(-1, logits.size(-1)), labels.view(-1), ignore_index=-100)

        scaler.scale(loss).backward()
        scaler.unscale_(optimizer)
        nn.utils.clip_grad_norm_(wrapper.parameters(), max_norm=2.0)
        scaler.step(optimizer)
        scaler.update()
        scheduler.step()

        # Track masked accuracy cleanly
        with torch.no_grad():
            valid_m = labels != -100
            n_m = int(valid_m.sum().item())
            if n_m > 0:
                m_logits = logits[valid_m]
                m_labels = labels[valid_m]
                top5 = torch.topk(m_logits, k=5, dim=-1).indices
                win_top1 += int((top5[:, 0] == m_labels).sum().item())
                win_top5 += int((top5 == m_labels.unsqueeze(1)).any(dim=1).sum().item())
                win_masked += n_m
            win_loss += float(loss.item())
            win_tokens += int((~pad_mask).sum().item())

        if step % log_every == 0 or step == total_steps:
            avg_l = win_loss / log_every
            ppl = math.exp(min(20.0, avg_l))
            acc1 = (win_top1 / max(1, win_masked)) * 100.0
            acc5 = (win_top5 / max(1, win_masked)) * 100.0
            lr_now = scheduler.get_last_lr()[0]
            dt = max(1e-3, time.time() - win_t0)
            tps = win_tokens / dt
            elapsed = time.time() - t0
            print(
                f"{step:04d}/{total_steps:04d}  {avg_l:8.4f} {ppl:8.2f} {acc1:7.2f}% {acc5:7.2f}% {lr_now:10.6f} {tps:9.0f} {elapsed:8.1f}s",
                flush=True,
            )
            win_loss = 0.0
            win_top1 = 0
            win_top5 = 0
            win_masked = 0
            win_tokens = 0
            win_t0 = time.time()

    # Explicitly zero any untouched subword bucket (freq == 0)
    zeroed = encoder.lexical_encoder.zero_untouched_subwords(used_buckets)
    print("-" * 80)
    print(f"Zeroed {zeroed} untouched subword buckets (freq == 0).")
    if torch.cuda.is_available():
        peak_mb = torch.cuda.max_memory_allocated(device) / (1024 * 1024)
        print(f"Peak CUDA VRAM Allocated during MLM Pretraining: {peak_mb:.1f} MB")

    # Save clean transferable encoder checkpoint
    full_state = encoder.state_dict()
    transferable_state = {
        k: v.cpu()
        for k, v in full_state.items()
        if not k.startswith("atom_head.") and k != "crf_trans" and k != "lexical_encoder.word_emb.weight"
    }
    payload = {
        "version": "v3-corpfin",
        "encoder_state_dict": transferable_state,
        "mlm_word_vocab": mlm_vocab,
        "mlm_word_emb_weight": encoder.lexical_encoder.word_emb.weight.detach().cpu(),
        "used_subword_buckets": sorted(used_buckets),
        "subword_buckets": SUBWORD_BUCKETS,
        "total_steps": total_steps,
        "final_loss": avg_l,
        "final_ppl": ppl,
        "final_top1": acc1,
        "final_top5": acc5,
        "corpfin_salient_count": len(corpfin_salient),
    }
    out_path = Path(args.ckpt_out)
    out_path.parent.mkdir(parents=True, exist_ok=True)
    torch.save(payload, out_path)
    print(f"Saved Layer 4 Pretrained Encoder to: {out_path} ({out_path.stat().st_size / (1024*1024):.2f} MB)")

    # Print semantic sanity probe on pretrained subword space
    run_subword_semantic_probe(encoder, id_to_word, device)


if __name__ == "__main__":
    main()