File size: 22,323 Bytes
ce6548c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Round-4 Distinct Bet: Cross-Tokenizer Character-Aligned Token-Span + Bag-Level MarginMSE
Knowledge Distillation from our Apache-2.0 307.5M Teacher (`b4cbedc831dd`, `mmBERT-base`)
into `jhu-clsp/ettin-encoder-32m` (32.0M, 10x smaller edge model!).

Solves cross-tokenizer mismatch (Gemma-2 256K teacher vocab vs ModernBERT 50K student vocab):
  1. Teacher inference over Stage-2 EN dataset (~82K rows) outputs:
       - Soft bag hallucination log-odds `t_z_mil` (Top-6 LME) & `t_z_max`
       - Character-level soft hallucination probability spans (compressed to word/char bins!)
         for EVERY hypothesis — turning span-free NLI/MiniCheck/Mixtral rows into dense
         soft-span supervision for the 32M student!
  2. Student (`ettin-encoder-32m`, initialized from Stage-1 NLI warm-up or trained 2-stage)
     trains with:
       - Hard-label Token-Span + Top-6 LME MIL + Max-Calib + Same-Doc Bag Ranking (0.50 weight)
       - Cross-Tokenizer Char-Aligned Soft Token BCE (`KL` to teacher's per-token soft probs, 0.70 weight)
       - Bag-Level Soft-Logit MarginMSE + Temperature-Scaled KL (`T=2.0`, 0.50 weight)
       - EMA weight averaging (`decay=0.996`) + strictly validation-only checkpoint selection!
"""

from __future__ import annotations

import argparse
import contextlib
import gc
import json
import math
import os
import time
from collections import defaultdict
from pathlib import Path
from typing import Any

import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader
from transformers import (
    AutoConfig,
    AutoModelForTokenClassification,
    AutoTokenizer,
    get_cosine_schedule_with_warmup,
    set_seed,
)

from train_mg_cpil import (
    LengthBucketBatchSampler,
    ListDataset,
    _encode_dataset,
    _load_jsonl,
    _topk_lme_mil,
    make_collate_fn,
)
from train_r2_tok import TOK_ID2LABEL, TOK_LABEL2ID, _clean_reinit_tok_head, evaluate_tok
from train_r3_tok import ModelEMA, compute_tok_mil_loss_v2, eval_topk_lme_addendum


@torch.no_grad()
def annotate_with_teacher(
    rows: list[dict[str, Any]],
    teacher_dir: Path,
    student_tokenizer: Any,
    max_length: int,
    device: str,
    use_bf16: bool,
    batch_size: int = 24,
) -> list[dict[str, Any]]:
    """Run 307.5M teacher (`mmBERT-base`) in one fast pass over `rows` and project teacher
    token probabilities directly onto student token indices via exact character offset overlap!"""
    t0 = time.time()
    t_tok = AutoTokenizer.from_pretrained(str(teacher_dir), use_fast=True)
    t_cfg = AutoConfig.from_pretrained(str(teacher_dir))
    if hasattr(t_cfg, "reference_compile"):
        t_cfg.reference_compile = False
    teacher = AutoModelForTokenClassification.from_pretrained(str(teacher_dir), config=t_cfg).to(device).eval()
    dtype = torch.bfloat16 if use_bf16 else torch.float16

    # Sort by approximate length for ultra-fast batched teacher inference
    order = sorted(range(len(rows)), key=lambda i: len(rows[i]["premise"]) + len(rows[i]["hypothesis"]), reverse=True)
    teacher_bag_mil = np.zeros(len(rows), dtype=np.float32)
    teacher_bag_max = np.zeros(len(rows), dtype=np.float32)
    # Store compact per-row teacher char-span probabilities: list of (cs, ce, p_hal)
    teacher_char_probs: list[list[tuple[int, int, float]]] = [[] for _ in range(len(rows))]

    for b_start in range(0, len(order), batch_size):
        idxs = order[b_start : b_start + batch_size]
        prems = [rows[i]["premise"] for i in idxs]
        hyps = [rows[i]["hypothesis"] for i in idxs]
        try:
            enc = t_tok(
                prems, hyps, padding=True, truncation="only_first", max_length=max_length,
                return_token_type_ids=False, return_offsets_mapping=True, return_tensors="pt",
            )
        except Exception:
            enc = t_tok(
                prems, hyps, padding=True, truncation="longest_first", max_length=max_length,
                return_token_type_ids=False, return_offsets_mapping=True, return_tensors="pt",
            )

        hmask = torch.zeros_like(enc["input_ids"], dtype=torch.float32)
        offsets_batch = enc["offset_mapping"].tolist()
        sids_batch = [enc.sequence_ids(j) for j in range(len(idxs))]
        for j, sids in enumerate(sids_batch):
            for t, sid in enumerate(sids):
                if sid == 1:
                    hmask[j, t] = 1.0

        tin = {"input_ids": enc["input_ids"].to(device), "attention_mask": enc["attention_mask"].to(device)}
        hm_dev = hmask.to(device)
        with torch.amp.autocast("cuda", dtype=dtype) if device == "cuda" else contextlib.nullcontext():
            logits = teacher(**tin).logits.float()

        z_hal = logits[:, :, 1] - logits[:, :, 0]
        p_hal = torch.sigmoid(z_hal).cpu().numpy()
        z_mil, _ = _topk_lme_mil(z_hal, hm_dev, k=6, beta=2.0)
        z_max = z_hal.masked_fill(hm_dev < 0.5, -1e4).max(dim=1).values
        zm_np = z_mil.cpu().numpy()
        zx_np = z_max.cpu().numpy()

        for j, orig_idx in enumerate(idxs):
            teacher_bag_mil[orig_idx] = float(np.clip(zm_np[j], -10.0, 10.0))
            teacher_bag_max[orig_idx] = float(np.clip(zx_np[j], -10.0, 10.0))
            spans_p: list[tuple[int, int, float]] = []
            for t, (sid, (cs, ce)) in enumerate(zip(sids_batch[j], offsets_batch[j])):
                if sid == 1 and ce > cs:
                    spans_p.append((int(cs), int(ce), float(p_hal[j, t])))
            teacher_char_probs[orig_idx] = spans_p

        if (b_start // batch_size) % 400 == 0:
            print(f"[distill] Teacher scored {min(len(order), b_start + batch_size):,}/{len(order):,} ({time.time() - t0:.0f}s)", flush=True)

    del teacher, t_tok
    gc.collect()
    if torch.cuda.is_available():
        torch.cuda.empty_cache()
    print(f"[distill] Teacher annotation finished in {time.time() - t0:.1f}s! Projecting onto student tokens ...", flush=True)

    # Now encode with student tokenizer and align teacher char probabilities to student tokens!
    t1 = time.time()
    encoded: list[dict[str, Any]] = []
    gid_map: dict[str, int] = {}
    for i, r in enumerate(rows):
        prem = r["premise"]
        hyp = r["hypothesis"]
        lbl = int(r["label"])
        gid_s = str(r.get("group_id") or "")
        if gid_s not in gid_map:
            gid_map[gid_s] = len(gid_map) + 1
        gid = gid_map[gid_s] if gid_s else 0

        try:
            enc = student_tokenizer(
                prem, hyp, truncation="only_first", max_length=max_length,
                return_token_type_ids=False, return_offsets_mapping=True,
            )
        except Exception:
            enc = student_tokenizer(
                prem, hyp, truncation="longest_first", max_length=max_length,
                return_token_type_ids=False, return_offsets_mapping=True,
            )

        ids = enc["input_ids"]
        attn = enc["attention_mask"]
        sids = enc.sequence_ids()
        offsets = enc["offset_mapping"]
        hyp_mask = [1 if sid == 1 else 0 for sid in sids]

        # Exact gold span labels (same as R3)
        has_span = bool(r.get("has_span", False))
        hal_spans = r.get("hal_spans") or []
        span_labels = [-100] * len(ids)
        if has_span:
            for idx, (sid, (cs, ce)) in enumerate(zip(sids, offsets)):
                if sid != 1 or ce <= cs:
                    continue
                if lbl == 1:
                    span_labels[idx] = 0
                else:
                    span_labels[idx] = 1 if any(cs < he and ce > hs for hs, he in hal_spans) else 0
            if lbl == 0 and 1 not in span_labels:
                span_labels = [-100] * len(ids)

        # Cross-tokenizer character-aligned soft teacher probability per student hypothesis token!
        t_spans = teacher_char_probs[i]
        t_tok_prob = [-1.0] * len(ids)
        if t_spans:
            ptr = 0
            n_ts = len(t_spans)
            for idx, (sid, (cs, ce)) in enumerate(zip(sids, offsets)):
                if sid != 1 or ce <= cs:
                    continue
                while ptr < n_ts and t_spans[ptr][1] <= cs:
                    ptr += 1
                num = 0.0
                den = 0.0
                q = ptr
                while q < n_ts and t_spans[q][0] < ce:
                    ov = min(ce, t_spans[q][1]) - max(cs, t_spans[q][0])
                    if ov > 0:
                        num += ov * t_spans[q][2]
                        den += ov
                    q += 1
                if den > 0:
                    t_tok_prob[idx] = num / den

        encoded.append({
            "input_ids": ids,
            "attention_mask": attn,
            "label": lbl,
            "group_id": gid,
            "length": len(ids),
            "hyp_mask": hyp_mask,
            "span_labels": span_labels,
            "t_tok_prob": t_tok_prob,
            "t_bag_mil": float(teacher_bag_mil[i]),
            "t_bag_max": float(teacher_bag_max[i]),
        })
    print(f"[distill] Student cross-tokenizer projection complete in {time.time() - t1:.1f}s ({len(encoded):,} rows)!", flush=True)
    return encoded


def make_distill_collate_fn(pad_id: int):
    def _collate(batch: list[dict[str, Any]]) -> dict[str, torch.Tensor]:
        max_len = ((max(len(x["input_ids"]) for x in batch) + 7) // 8) * 8
        bs = len(batch)
        input_ids = torch.full((bs, max_len), pad_id, dtype=torch.long)
        attention_mask = torch.zeros((bs, max_len), dtype=torch.long)
        labels = torch.zeros(bs, dtype=torch.long)
        group_ids = torch.zeros(bs, dtype=torch.long)
        hyp_mask = torch.zeros((bs, max_len), dtype=torch.float32)
        span_labels = torch.full((bs, max_len), -100, dtype=torch.long)
        t_tok_prob = torch.full((bs, max_len), -1.0, dtype=torch.float32)
        t_bag_mil = torch.zeros(bs, dtype=torch.float32)
        t_bag_max = torch.zeros(bs, dtype=torch.float32)

        for i, x in enumerate(batch):
            L = len(x["input_ids"])
            input_ids[i, :L] = torch.tensor(x["input_ids"], dtype=torch.long)
            attention_mask[i, :L] = torch.tensor(x["attention_mask"], dtype=torch.long)
            labels[i] = x["label"]
            group_ids[i] = x["group_id"]
            hyp_mask[i, :L] = torch.tensor(x["hyp_mask"], dtype=torch.float32)
            span_labels[i, :L] = torch.tensor(x["span_labels"], dtype=torch.long)
            t_tok_prob[i, :L] = torch.tensor(x["t_tok_prob"], dtype=torch.float32)
            t_bag_mil[i] = x["t_bag_mil"]
            t_bag_max[i] = x["t_bag_max"]

        return {
            "input_ids": input_ids,
            "attention_mask": attention_mask,
            "labels": labels,
            "group_ids": group_ids,
            "hyp_mask": hyp_mask,
            "span_labels": span_labels,
            "t_tok_prob": t_tok_prob,
            "t_bag_mil": t_bag_mil,
            "t_bag_max": t_bag_max,
        }

    return _collate


def compute_distill_loss(
    tok_logits_2: torch.Tensor,
    batch: dict[str, torch.Tensor],
    device: str,
) -> tuple[torch.Tensor, dict[str, float]]:
    # 1. Hard-label loss (exact spans + MIL + max + same-doc bag ranking)
    labels = batch["labels"].to(device, non_blocking=True)
    group_ids = batch["group_ids"].to(device, non_blocking=True)
    hyp_mask = batch["hyp_mask"].to(device, non_blocking=True)
    span_labels = batch["span_labels"].to(device, non_blocking=True)

    l_hard, st = compute_tok_mil_loss_v2(
        tok_logits_2=tok_logits_2,
        labels=labels,
        group_ids=group_ids,
        hyp_mask=hyp_mask,
        span_labels=span_labels,
        use_pair_rank=True,
        label_smooth=0.02,
    )

    # 2. Cross-Tokenizer Char-Aligned Soft Token-Span Distillation!
    logits = tok_logits_2.float()
    z_hal = logits[:, :, 1] - logits[:, :, 0]
    t_prob = batch["t_tok_prob"].to(device, non_blocking=True)
    valid_t = (t_prob >= 0.0) & (hyp_mask > 0.5)
    if valid_t.any():
        t_p = t_prob.clamp(1e-4, 1.0 - 1e-4)
        bce_soft = F.binary_cross_entropy_with_logits(z_hal, t_p, reduction="none") * valid_t.float()
        per_ex_c = valid_t.float().sum(dim=1)
        has_e = per_ex_c > 0
        l_tok_kd = (bce_soft.sum(dim=1)[has_e] / per_ex_c[has_e]).mean()
    else:
        l_tok_kd = torch.zeros((), device=device)

    # 3. Bag-Level Soft-Logit MarginMSE + Temperature-Scaled KL (T=2.0)
    z_mil, mil_valid = _topk_lme_mil(z_hal, hyp_mask, k=6, beta=2.0)
    z_max = z_hal.masked_fill(hyp_mask < 0.5, -1e4).max(dim=1).values
    t_mil = batch["t_bag_mil"].to(device, non_blocking=True)
    t_max = batch["t_bag_max"].to(device, non_blocking=True)

    if mil_valid.any():
        T = 2.0
        p_t_mil = torch.sigmoid(t_mil[mil_valid] / T)
        l_bag_kl = F.binary_cross_entropy_with_logits(z_mil[mil_valid] / T, p_t_mil) * (T * T)
        # Pairwise MarginMSE (Schlatt et al. 2025/2026) between student & teacher bag logits!
        s_b = z_mil[mil_valid]
        t_b = t_mil[mil_valid]
        s_diff = s_b.unsqueeze(1) - s_b.unsqueeze(0)
        t_diff = t_b.unsqueeze(1) - t_b.unsqueeze(0)
        l_margin_mse = F.smooth_l1_loss(s_diff, t_diff)
        l_max_mse = F.smooth_l1_loss(z_max[mil_valid], t_max[mil_valid])
    else:
        l_bag_kl = l_margin_mse = l_max_mse = torch.zeros((), device=device)

    total = 0.50 * l_hard + 0.80 * l_tok_kd + 0.25 * l_bag_kl + 0.20 * l_margin_mse + 0.15 * l_max_mse
    st["l_tok_kd"] = float(l_tok_kd.item())
    st["l_bag_kl"] = float(l_bag_kl.item())
    st["l_mmse"] = float(l_margin_mse.item())
    return total, st


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--student-model", type=str, default="jhu-clsp/ettin-encoder-32m")
    parser.add_argument("--teacher-dir", type=str, required=True)
    parser.add_argument("--data-dir", type=str, required=True)
    parser.add_argument("--output-dir", type=str, required=True)
    parser.add_argument("--max-length", type=int, default=3584)
    parser.add_argument("--epochs", type=float, default=3.0)
    parser.add_argument("--lr", type=float, default=6e-5)
    parser.add_argument("--seed", type=int, default=42)
    args = parser.parse_args()

    os.environ.setdefault("HF_HOME", "/tmp/hf")
    os.environ["TOKENIZERS_PARALLELISM"] = "true"
    os.environ["TORCH_COMPILE_DISABLE"] = "1"
    if hasattr(torch, "_dynamo"):
        torch._dynamo.config.disable = True
    set_seed(args.seed)

    data_dir = Path(args.data_dir)
    out_dir = Path(args.output_dir)
    out_dir.mkdir(parents=True, exist_ok=True)
    device = "cuda" if torch.cuda.is_available() else "cpu"
    use_bf16 = device == "cuda" and torch.cuda.is_bf16_supported()

    tokenizer = AutoTokenizer.from_pretrained(args.student_model, use_fast=True)
    pad_id = tokenizer.pad_token_id if tokenizer.pad_token_id is not None else 0

    # 1. Run 307.5M teacher over Stage-2 EN dataset (~82K) and project char->token soft probs!
    s2_rows = _load_jsonl(data_dir / "stage2_grounded.jsonl")
    train_enc = annotate_with_teacher(
        rows=s2_rows,
        teacher_dir=Path(args.teacher_dir),
        student_tokenizer=tokenizer,
        max_length=args.max_length,
        device=device,
        use_bf16=use_bf16,
        batch_size=24,
    )
    del s2_rows
    gc.collect()

    val_rows = _load_jsonl(data_dir / "val.jsonl")
    val_enc = _encode_dataset(val_rows, tokenizer, args.max_length, with_spans=True)
    del val_rows

    # 2. Load 32M student (start from R3 Stage-1/Stage-2 warm init OR fresh canonical ettin-encoder-32m!)
    # Start cleanly from canonical `jhu-clsp/ettin-encoder-32m` so this is a 100% clean-lineage distillation test!
    cfg = AutoConfig.from_pretrained(args.student_model, num_labels=2, id2label=TOK_ID2LABEL, label2id=TOK_LABEL2ID)
    if hasattr(cfg, "reference_compile"):
        cfg.reference_compile = False
    model = AutoModelForTokenClassification.from_pretrained(args.student_model, config=cfg, ignore_mismatched_sizes=True)
    _clean_reinit_tok_head(model)
    model.to(device)

    train_sampler = LengthBucketBatchSampler(train_enc, batch_size=32, paired=True, seed=args.seed)
    val_sampler = LengthBucketBatchSampler(val_enc, batch_size=32, paired=False, seed=args.seed)
    train_loader = DataLoader(ListDataset(train_enc), batch_sampler=train_sampler, collate_fn=make_distill_collate_fn(pad_id), num_workers=4, pin_memory=True)
    val_loader = DataLoader(ListDataset(val_enc), batch_sampler=val_sampler, collate_fn=make_collate_fn(pad_id, with_spans=True), num_workers=2, pin_memory=True)

    grad_accum = 2  # eff_bs = 64
    steps_per_epoch = max(1, math.ceil(len(train_loader) / grad_accum))
    total_steps = max(1, int(math.ceil(steps_per_epoch * args.epochs)))
    warmup_steps = max(150, int(0.10 * total_steps))
    eval_every = max(300, steps_per_epoch // 2)

    no_decay = ("bias", "LayerNorm.weight", "norm.weight")
    optimizer = torch.optim.AdamW(
        [
            {"params": [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay)], "lr": args.lr, "weight_decay": 0.01},
            {"params": [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay)], "lr": args.lr, "weight_decay": 0.0},
        ],
        betas=(0.9, 0.999),
        eps=1e-8,
    )
    scheduler = get_cosine_schedule_with_warmup(optimizer, num_warmup_steps=warmup_steps, num_training_steps=total_steps)
    amp_dtype = torch.bfloat16 if use_bf16 else torch.float16
    ema: ModelEMA | None = None

    print(f"[distill] Start 307M->32M Cross-Tokenizer Span+MarginMSE KD: rows={len(train_enc):,}, steps={total_steps}, lr={args.lr}")
    t0 = time.time()
    global_step = 0
    best_score = -1.0
    best_metrics: dict[str, float] = {}
    val_history: list[dict[str, Any]] = []
    running = defaultdict(float)
    running_n = 0
    model.train()
    optimizer.zero_grad(set_to_none=True)

    for ep in range(int(math.ceil(args.epochs))):
        train_sampler.set_epoch(ep)
        accum_cnt = 0
        for step_idx, batch in enumerate(train_loader):
            if global_step >= total_steps:
                break
            input_ids = batch["input_ids"].to(device, non_blocking=True)
            attention_mask = batch["attention_mask"].to(device, non_blocking=True)

            with torch.amp.autocast("cuda", dtype=amp_dtype) if device == "cuda" else contextlib.nullcontext():
                logits = model(input_ids=input_ids, attention_mask=attention_mask).logits

            loss, st = compute_distill_loss(logits, batch, device)
            for k, v in st.items():
                running[k] += v
            running["loss"] += float(loss.item())
            running_n += 1

            (loss / grad_accum).backward()
            accum_cnt += 1

            if accum_cnt == grad_accum or (step_idx + 1 == len(train_loader)):
                gnorm = float(torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0).item())
                optimizer.step()
                scheduler.step()
                optimizer.zero_grad(set_to_none=True)
                accum_cnt = 0
                global_step += 1

                if global_step == warmup_steps:
                    ema = ModelEMA(model, decay=0.996)
                elif ema is not None:
                    ema.update(model)

                if global_step % 250 == 0 or global_step == 10:
                    avg = {k: round(v / max(1, running_n), 4) for k, v in running.items()}
                    print(f"[kd {global_step:4d}/{total_steps}] lr={scheduler.get_last_lr()[0]:.2e} gnorm={gnorm:.2f} elapsed={time.time() - t0:.0f}s {avg}", flush=True)
                    running.clear()
                    running_n = 0

                if global_step % eval_every == 0 or global_step == total_steps:
                    vm = evaluate_tok(model, val_loader, device, use_bf16)
                    vm["step"] = global_step
                    vm["weights"] = "raw"
                    val_history.append(vm)
                    print(f"[val KD RAW @ {global_step}] {json.dumps(vm)}", flush=True)
                    if vm["selection_score"] > best_score:
                        best_score = vm["selection_score"]
                        best_metrics = dict(vm)
                        model.save_pretrained(str(out_dir), safe_serialization=True)
                        tokenizer.save_pretrained(str(out_dir))
                        print(f"[ckpt] New best KD RAW selection_score={best_score:.5f} saved!", flush=True)
                    if ema is not None:
                        bak = ema.swap_in(model)
                        vm_e = evaluate_tok(model, val_loader, device, use_bf16)
                        vm_e["step"] = global_step
                        vm_e["weights"] = "ema"
                        val_history.append(vm_e)
                        print(f"[val KD EMA @ {global_step}] {json.dumps(vm_e)}", flush=True)
                        if vm_e["selection_score"] > best_score:
                            best_score = vm_e["selection_score"]
                            best_metrics = dict(vm_e)
                            model.save_pretrained(str(out_dir), safe_serialization=True)
                            tokenizer.save_pretrained(str(out_dir))
                            print(f"[ckpt] New best KD EMA selection_score={best_score:.5f} saved!", flush=True)
                        ema.restore(model, bak)

    summary = {
        "method": "r4_cross_tok_span_kd_307m_to_32m",
        "student": args.student_model,
        "teacher": args.teacher_dir,
        "train_runtime_sec": round(time.time() - t0, 1),
        "best_val_metrics": best_metrics,
    }
    (out_dir / "training_summary.json").write_text(json.dumps(summary, indent=2), encoding="utf-8")
    print("[distill] DONE!", json.dumps(best_metrics, indent=2))

    del model
    gc.collect()
    if torch.cuda.is_available():
        torch.cuda.empty_cache()

    lme_res = eval_topk_lme_addendum(out_dir, data_dir, device, use_bf16)
    (out_dir.parent / "eval_topk_lme.json").write_text(json.dumps(lme_res, indent=2), encoding="utf-8")
    print("=== TOP-K LME ADDENDUM EVAL (R4 DISTILLED 32M) ===")
    print(json.dumps(lme_res, indent=2))


if __name__ == "__main__":
    main()