File size: 27,458 Bytes
e5f3768
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
"""Controlled Trainer for Fork-and-Flush Probe: Control vs MG-CPIL.

Identical PyTorch training engine for both methods (zero framework confounds!):
  - method=control:
      Standard FP32 sequence Cross-Entropy on ModernBertForSequenceClassification ([CLS]),
      Length-bucketed random batching, AdamW + cosine schedule, validation-only selection.
  - method=mg_cpil (Multi-Granular Auxiliary Span + Top-K LME MIL + Same-Doc Contrastive Ranking):
      1. Primary Sequence Loss (L_seq): FP32 CE on ModernBertForSequenceClassification logits.
      2. Auxiliary Token-Span Loss (L_span): Training-only 2-layer MLP head over hypothesis tokens
         supervised by exact char->token spans (PsiloQA gold, MiniCheck composed bad sentences,
         SummEdits difflib edits, Synthetic Minimal-Edit Counterfactuals, and all-0 consistent tokens).
      3. Weakly-Supervised Top-K Log-Mean-Exp MIL Bag Loss (L_mil): Length-invariant, strictly
         monotonic smooth-max over top-8 hypothesis token logits (handles doc-level datasets like
         DocNLI/WANLI/MultiNLI without span labels).
      4. Cross-Granularity Symmetric KL Consistency (L_agree): Aligns sequence [CLS] probability
         with MIL token-bag probability so dense localized grounding transfers into [CLS] head!
      5. Same-Document Contrastive Pairwise Margin Ranking Loss (L_rank, CPIL + Bradley-Terry):
         Group-Aware Length-Bucketed Paired Batch Sampler packs same-document (pos, neg) pairs
         into the same micro-batch; pairwise logistic margin loss directly strips style/topic
         priors and optimizes ROC-AUC!

Exported model is 100% pure standard `ModernBertForSequenceClassification` (auxiliary head dropped
at save time -> ZERO inference overhead, ZERO `trust_remote_code`, 100% ONNX compatible!).
"""

from __future__ import annotations

import argparse
import contextlib
import gc
import json
import math
import os
import random
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 sklearn.metrics import accuracy_score, f1_score, roc_auc_score
from torch.utils.data import DataLoader, Dataset, Sampler
from transformers import (
    AutoConfig,
    AutoModelForSequenceClassification,
    AutoTokenizer,
    get_cosine_schedule_with_warmup,
    set_seed,
)

from schema import ID2LABEL, LABEL2ID, NUM_LABELS


def _load_jsonl(path: Path) -> list[dict[str, Any]]:
    with path.open("r", encoding="utf-8") as f:
        return [json.loads(ln) for ln in f if ln.strip()]


def _encode_dataset(
    rows: list[dict[str, Any]],
    tokenizer: Any,
    max_length: int,
    with_spans: bool,
) -> list[dict[str, Any]]:
    encoded: list[dict[str, Any]] = []
    gid_map: dict[str, int] = {}
    for r in 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 = tokenizer(
                prem,
                hyp,
                truncation="only_first",
                max_length=max_length,
                return_token_type_ids=False,
                return_offsets_mapping=with_spans,
            )
        except Exception:
            enc = tokenizer(
                prem,
                hyp,
                truncation="longest_first",
                max_length=max_length,
                return_token_type_ids=False,
                return_offsets_mapping=with_spans,
            )

        ids = enc["input_ids"]
        attn = enc["attention_mask"]
        item: dict[str, Any] = {
            "input_ids": ids,
            "attention_mask": attn,
            "label": lbl,
            "group_id": gid,
            "length": len(ids),
        }

        if with_spans:
            seq_ids = enc.sequence_ids()
            offsets = enc["offset_mapping"]
            has_span = bool(r.get("has_span", False))
            hal_spans = r.get("hal_spans") or []
            hyp_mask = [1 if sid == 1 else 0 for sid in seq_ids]
            span_labels = [-100] * len(ids)
            if has_span:
                for idx, (sid, (cs, ce)) in enumerate(zip(seq_ids, offsets)):
                    if sid != 1 or ce <= cs:
                        continue
                    if lbl == 1:
                        span_labels[idx] = 0
                    else:
                        hit = 0
                        for hs, he in hal_spans:
                            if cs < he and ce > hs:
                                hit = 1
                                break
                        span_labels[idx] = hit
                # Safety check: if a labeled-hallucinated row had its span truncated away, fall back to MIL
                if lbl == 0 and 1 not in span_labels:
                    span_labels = [-100] * len(ids)
            item["hyp_mask"] = hyp_mask
            item["span_labels"] = span_labels
        encoded.append(item)
    return encoded


class ListDataset(Dataset):
    def __init__(self, items: list[dict[str, Any]]) -> None:
        self.items = items

    def __len__(self) -> int:
        return len(self.items)

    def __getitem__(self, idx: int) -> dict[str, Any]:
        return self.items[idx]


class LengthBucketBatchSampler(Sampler[list[int]]):
    """Packs same-document (pos, neg) contrastive pairs into the same micro-batch when paired=True,
    while preserving length-bucketed efficiency (pad_to_multiple_of=8)."""

    def __init__(self, items: list[dict[str, Any]], batch_size: int, paired: bool, seed: int = 42) -> None:
        self.items = items
        self.batch_size = batch_size
        self.paired = paired
        self.seed = seed
        self.epoch = 0

    def set_epoch(self, epoch: int) -> None:
        self.epoch = epoch

    def _build_units(self, rng: random.Random) -> list[list[int]]:
        if not self.paired:
            return [[i] for i in range(len(self.items))]
        by_g: dict[int, dict[int, list[int]]] = defaultdict(lambda: {0: [], 1: []})
        for idx, it in enumerate(self.items):
            by_g[it["group_id"]][it["label"]].append(idx)
        units: list[list[int]] = []
        for _gid, cmap in by_g.items():
            pos, neg = cmap[1], cmap[0]
            rng.shuffle(pos)
            rng.shuffle(neg)
            n_pair = min(len(pos), len(neg))
            for k in range(n_pair):
                units.append([pos[k], neg[k]])
            for idx in pos[n_pair:]:
                units.append([idx])
            for idx in neg[n_pair:]:
                units.append([idx])
        return units

    def __iter__(self):
        rng = random.Random(self.seed + self.epoch * 9973)
        units = self._build_units(rng)
        rng.shuffle(units)

        mega_size = self.batch_size * 48
        batches: list[list[int]] = []
        for start in range(0, len(units), mega_size):
            chunk = units[start : start + mega_size]
            chunk.sort(key=lambda u: max(self.items[i]["length"] for i in u), reverse=True)
            cur: list[int] = []
            for u in chunk:
                if len(cur) + len(u) > self.batch_size and cur:
                    batches.append(cur)
                    cur = []
                cur.extend(u)
                if len(cur) >= self.batch_size:
                    batches.append(cur[: self.batch_size])
                    cur = cur[self.batch_size :]
            if cur:
                batches.append(cur)
        rng.shuffle(batches)
        for b in batches:
            yield b

    def __len__(self) -> int:
        return math.ceil(len(self.items) / self.batch_size)


def make_collate_fn(pad_id: int, with_spans: bool):
    def _collate(batch: list[dict[str, Any]]) -> dict[str, torch.Tensor]:
        max_len = max(len(x["input_ids"]) for x in batch)
        max_len = ((max_len + 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)

        if with_spans:
            hyp_mask = torch.zeros((bs, max_len), dtype=torch.float32)
            span_labels = torch.full((bs, max_len), -100, dtype=torch.long)

        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"]
            if with_spans:
                hyp_mask[i, :L] = torch.tensor(x["hyp_mask"], dtype=torch.float32)
                span_labels[i, :L] = torch.tensor(x["span_labels"], dtype=torch.long)

        out = {
            "input_ids": input_ids,
            "attention_mask": attention_mask,
            "labels": labels,
            "group_ids": group_ids,
        }
        if with_spans:
            out["hyp_mask"] = hyp_mask
            out["span_labels"] = span_labels
        return out

    return _collate


class MultiGranularWrapper(nn.Module):
    """Wraps standard AutoModelForSequenceClassification with a training-only auxiliary
    token-level hallucination head. At export, ONLY `self.seq_model` is saved."""

    def __init__(self, seq_model: nn.Module, hidden_size: int) -> None:
        super().__init__()
        self.seq_model = seq_model
        self.tok_head = nn.Sequential(
            nn.Dropout(0.1),
            nn.Linear(hidden_size, hidden_size // 2),
            nn.GELU(),
            nn.Linear(hidden_size // 2, 1),
        )

    def forward(
        self,
        input_ids: torch.Tensor,
        attention_mask: torch.Tensor,
        need_tok: bool = False,
    ) -> tuple[torch.Tensor, torch.Tensor | None]:
        out = self.seq_model(
            input_ids=input_ids,
            attention_mask=attention_mask,
            output_hidden_states=need_tok,
        )
        seq_logits = out.logits
        if not need_tok:
            return seq_logits, None
        last_h = out.hidden_states[-1]
        tok_logits = self.tok_head(last_h).squeeze(-1)
        return seq_logits, tok_logits


def _topk_lme_mil(tok_logits: torch.Tensor, hyp_mask: torch.Tensor, k: int = 8, beta: float = 1.5) -> tuple[torch.Tensor, torch.Tensor]:
    """Length-invariant, strictly monotonic Top-K Log-Mean-Exp MIL pooling over hypothesis tokens.
    Returns (z_mil [B], valid_mask [B])."""
    bs, seq_len = tok_logits.shape
    counts = hyp_mask.sum(dim=1)  # [B]
    valid = counts >= 1.0
    masked = tok_logits.masked_fill(hyp_mask < 0.5, -1e4)
    kk = min(k, seq_len)
    top_vals, _ = torch.topk(masked, k=kk, dim=1)  # [B, kk]
    # Build mask for actual available hypothesis tokens up to kk
    ar = torch.arange(kk, device=tok_logits.device).unsqueeze(0)  # [1, kk]
    eff_k = counts.clamp(min=1.0, max=float(kk))  # [B]
    top_valid = ar < eff_k.unsqueeze(1)  # [B, kk]
    scaled = (top_vals * beta).masked_fill(~top_valid, -1e4)
    lse = torch.logsumexp(scaled, dim=1)  # [B]
    lme = (lse - torch.log(eff_k)) / beta
    return lme, valid


def compute_mg_cpil_loss(
    seq_logits: torch.Tensor,
    tok_logits: torch.Tensor,
    labels: torch.Tensor,
    group_ids: torch.Tensor,
    hyp_mask: torch.Tensor,
    span_labels: torch.Tensor,
    lam_span: float = 0.35,
    lam_mil: float = 0.25,
    lam_agree: float = 0.15,
    lam_rank: float = 0.30,
    rank_margin: float = 1.0,
) -> tuple[torch.Tensor, dict[str, float]]:
    z_seq = seq_logits.float()
    z_tok = tok_logits.float()
    y = labels.long()
    device = z_seq.device

    # 1. Primary Sequence Loss (FP32 CE)
    l_seq = F.cross_entropy(z_seq, y)

    # 2. Exact Token-Span Loss (per-example averaged, balanced pos_weight=2.0 for hallucinated tokens)
    valid_sp = (span_labels != -100) & (hyp_mask > 0.5)
    if valid_sp.any():
        sp_target = span_labels.clamp(min=0).float()
        bce_tok = F.binary_cross_entropy_with_logits(
            z_tok,
            sp_target,
            pos_weight=torch.tensor(2.0, device=device),
            reduction="none",
        )
        bce_tok = bce_tok * valid_sp.float()
        per_ex_cnt = valid_sp.float().sum(dim=1)
        has_ex = per_ex_cnt > 0
        per_ex_loss = bce_tok.sum(dim=1)[has_ex] / per_ex_cnt[has_ex]
        l_span = per_ex_loss.mean()
    else:
        l_span = torch.zeros((), device=device)

    # 3. Weakly-Supervised Top-8 Log-Mean-Exp MIL Bag Loss (1 - y = hallucinated!)
    z_mil, mil_valid = _topk_lme_mil(z_tok, hyp_mask, k=8, beta=1.5)
    if mil_valid.any():
        y_hal = (1 - y[mil_valid]).float()
        l_mil = F.binary_cross_entropy_with_logits(z_mil[mil_valid], y_hal)

        # 4. Cross-Granularity Symmetric KL Consistency (transfers dense token grounding -> [CLS] head!)
        # s_seq_hal = logit(hallucinated) - logit(consistent)
        s_seq_hal = z_seq[mil_valid, 0] - z_seq[mil_valid, 1]
        p_seq = torch.sigmoid(s_seq_hal).clamp(1e-5, 1.0 - 1e-5)
        p_mil = torch.sigmoid(z_mil[mil_valid]).clamp(1e-5, 1.0 - 1e-5)
        kl_mil_to_seq = (
            p_mil.detach() * torch.log(p_mil.detach() / p_seq)
            + (1.0 - p_mil.detach()) * torch.log((1.0 - p_mil.detach()) / (1.0 - p_seq))
        )
        kl_seq_to_mil = (
            p_seq.detach() * torch.log(p_seq.detach() / p_mil)
            + (1.0 - p_seq.detach()) * torch.log((1.0 - p_seq.detach()) / (1.0 - p_mil))
        )
        l_agree = 0.5 * (kl_mil_to_seq.mean() + kl_seq_to_mil.mean())
    else:
        l_mil = torch.zeros((), device=device)
        l_agree = torch.zeros((), device=device)

    # 5. Same-Document Contrastive Pairwise Margin Ranking Loss (CPIL + Bradley-Terry AUC)
    cons_margin = z_seq[:, 1] - z_seq[:, 0]  # higher = more consistent
    # Pairwise matrix (i = consistent, j = hallucinated)
    pos_m = (y == 1).unsqueeze(1)  # [B, 1]
    neg_m = (y == 0).unsqueeze(0)  # [1, B]
    diff_mat = cons_margin.unsqueeze(1) - cons_margin.unsqueeze(0)  # [B, B]
    same_doc = (group_ids.unsqueeze(1) == group_ids.unsqueeze(0)) & (group_ids.unsqueeze(1) > 0)
    same_pairs = pos_m & neg_m & same_doc
    all_pairs = pos_m & neg_m

    n_same = int(same_pairs.sum().item())
    if n_same > 0:
        l_rank_same = F.softplus(-(diff_mat[same_pairs] - rank_margin)).mean()
    else:
        l_rank_same = torch.zeros((), device=device)

    if all_pairs.any():
        l_rank_auc = F.softplus(-(diff_mat[all_pairs] - 0.5 * rank_margin)).mean()
    else:
        l_rank_auc = torch.zeros((), device=device)

    l_rank = l_rank_same + 0.25 * l_rank_auc

    total = l_seq + lam_span * l_span + lam_mil * l_mil + lam_agree * l_agree + lam_rank * l_rank
    stats = {
        "l_seq": float(l_seq.item()),
        "l_span": float(l_span.item()),
        "l_mil": float(l_mil.item()),
        "l_agree": float(l_agree.item()),
        "l_rank": float(l_rank.item()),
        "same_pairs": n_same,
    }
    return total, stats


@torch.no_grad()
def evaluate(wrapper: MultiGranularWrapper, val_loader: DataLoader, device: str, use_bf16: bool) -> dict[str, float]:
    wrapper.eval()
    all_logits = []
    all_labels = []
    dtype = torch.bfloat16 if use_bf16 else torch.float16
    for batch in val_loader:
        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=dtype) if device == "cuda" else contextlib.nullcontext():
            seq_logits, _ = wrapper(input_ids=input_ids, attention_mask=attention_mask, need_tok=False)
        all_logits.append(seq_logits.float().cpu().numpy())
        all_labels.append(batch["labels"].numpy())
    logits = np.concatenate(all_logits, axis=0)
    y = np.concatenate(all_labels, axis=0).astype(int)
    x = logits - np.max(logits, axis=-1, keepdims=True)
    p1 = (np.exp(x) / np.sum(np.exp(x), axis=-1, keepdims=True))[:, 1]
    pred = (p1 >= 0.5).astype(int)
    acc = float(accuracy_score(y, pred))
    macro_f1 = float(f1_score(y, pred, average="macro", zero_division=0))
    hal_f1 = float(f1_score(1 - y, 1 - pred, zero_division=0))
    cons_f1 = float(f1_score(y, pred, zero_division=0))
    auc = float(roc_auc_score(y, p1)) if len(set(y.tolist())) == 2 else 0.5
    wrapper.train()
    return {
        "accuracy": round(acc, 5),
        "macro_f1": round(macro_f1, 5),
        "hal_f1": round(hal_f1, 5),
        "consistent_f1": round(cons_f1, 5),
        "roc_auc": round(auc, 5),
        "selection_score": round(0.45 * macro_f1 + 0.55 * auc, 5),
    }


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--method", choices=["control", "mg_cpil"], required=True)
    parser.add_argument("--base-model", 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=2.0)
    parser.add_argument("--lr", type=float, default=2e-5)
    parser.add_argument("--batch-size", type=int, default=16)
    parser.add_argument("--grad-accum", type=int, default=4)
    parser.add_argument("--seed", type=int, default=42)
    parser.add_argument("--grad-checkpointing", action="store_true")
    parser.add_argument("--lam-span", type=float, default=0.35)
    parser.add_argument("--lam-mil", type=float, default=0.25)
    parser.add_argument("--lam-agree", type=float, default=0.15)
    parser.add_argument("--lam-rank", type=float, default=0.30)
    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)

    is_mg = args.method == "mg_cpil"
    data_dir = Path(args.data_dir)
    out_dir = Path(args.output_dir)
    out_dir.mkdir(parents=True, exist_ok=True)

    train_rows = _load_jsonl(data_dir / "train.jsonl")
    val_rows = _load_jsonl(data_dir / "val.jsonl")
    print(f"[train:{args.method}] Loaded {len(train_rows):,} train, {len(val_rows):,} val rows")

    tokenizer = AutoTokenizer.from_pretrained(args.base_model, use_fast=True)
    cfg = AutoConfig.from_pretrained(
        args.base_model,
        num_labels=NUM_LABELS,
        id2label=ID2LABEL,
        label2id=LABEL2ID,
        problem_type="single_label_classification",
    )
    if hasattr(cfg, "classifier_pooling"):
        cfg.classifier_pooling = "cls"
    if hasattr(cfg, "reference_compile"):
        cfg.reference_compile = False

    seq_model = AutoModelForSequenceClassification.from_pretrained(
        args.base_model,
        config=cfg,
        ignore_mismatched_sizes=True,
    )
    if args.grad_checkpointing and hasattr(seq_model, "gradient_checkpointing_enable"):
        seq_model.gradient_checkpointing_enable()

    wrapper = MultiGranularWrapper(seq_model, hidden_size=int(cfg.hidden_size))
    device = "cuda" if torch.cuda.is_available() else "cpu"
    use_bf16 = device == "cuda" and torch.cuda.is_bf16_supported()
    wrapper.to(device)

    t_enc = time.time()
    train_enc = _encode_dataset(train_rows, tokenizer, args.max_length, with_spans=is_mg)
    val_enc = _encode_dataset(val_rows, tokenizer, args.max_length, with_spans=False)
    del train_rows, val_rows
    gc.collect()
    print(f"[train:{args.method}] Pre-tokenized in {time.time() - t_enc:.1f}s (train={len(train_enc):,}, val={len(val_enc):,})")

    pad_id = tokenizer.pad_token_id if tokenizer.pad_token_id is not None else 0
    train_sampler = LengthBucketBatchSampler(train_enc, batch_size=args.batch_size, paired=is_mg, seed=args.seed)
    val_sampler = LengthBucketBatchSampler(val_enc, batch_size=max(32, args.batch_size), paired=False, seed=args.seed)

    train_loader = DataLoader(
        ListDataset(train_enc),
        batch_sampler=train_sampler,
        collate_fn=make_collate_fn(pad_id, with_spans=is_mg),
        num_workers=4,
        pin_memory=(device == "cuda"),
    )
    val_loader = DataLoader(
        ListDataset(val_enc),
        batch_sampler=val_sampler,
        collate_fn=make_collate_fn(pad_id, with_spans=False),
        num_workers=2,
        pin_memory=(device == "cuda"),
    )

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

    no_decay = ("bias", "LayerNorm.weight", "norm.weight")
    # Auxiliary token head gets 5x LR so it converges sharply right from early steps!
    param_groups = [
        {
            "params": [p for n, p in wrapper.seq_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 wrapper.seq_model.named_parameters() if any(nd in n for nd in no_decay)],
            "lr": args.lr,
            "weight_decay": 0.0,
        },
    ]
    if is_mg:
        param_groups.append(
            {
                "params": list(wrapper.tok_head.parameters()),
                "lr": args.lr * 5.0,
                "weight_decay": 0.01,
            }
        )

    optimizer = torch.optim.AdamW(param_groups, 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)
    scaler = torch.amp.GradScaler("cuda", enabled=(device == "cuda" and not use_bf16))
    amp_dtype = torch.bfloat16 if use_bf16 else torch.float16

    print(
        f"[train:{args.method}] Starting training: total_steps={total_steps}, warmup={warmup_steps}, "
        f"eval_every={eval_every}, eff_bs={args.batch_size * args.grad_accum}, bf16={use_bf16}"
    )

    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

    wrapper.train()
    optimizer.zero_grad(set_to_none=True)

    n_full_epochs = int(math.ceil(args.epochs))
    for ep in range(n_full_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)
            labels = batch["labels"].to(device, non_blocking=True)

            with torch.amp.autocast("cuda", dtype=amp_dtype) if device == "cuda" else contextlib.nullcontext():
                seq_logits, tok_logits = wrapper(input_ids=input_ids, attention_mask=attention_mask, need_tok=is_mg)

            if is_mg:
                loss, st = compute_mg_cpil_loss(
                    seq_logits=seq_logits,
                    tok_logits=tok_logits,
                    labels=labels,
                    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),
                    lam_span=args.lam_span,
                    lam_mil=args.lam_mil,
                    lam_agree=args.lam_agree,
                    lam_rank=args.lam_rank,
                )
                for k, v in st.items():
                    running[k] += v
            else:
                loss = F.cross_entropy(seq_logits.float(), labels.long())
                running["l_seq"] += float(loss.item())
            running["loss"] += float(loss.item())
            running_n += 1

            scaled_loss = loss / args.grad_accum
            if scaler.is_enabled():
                scaler.scale(scaled_loss).backward()
            else:
                scaled_loss.backward()
            accum_cnt += 1

            is_last_micro = (step_idx + 1 == len(train_loader))
            if accum_cnt == args.grad_accum or is_last_micro:
                if scaler.is_enabled():
                    scaler.unscale_(optimizer)
                gnorm = float(torch.nn.utils.clip_grad_norm_(wrapper.parameters(), 1.0).item())
                if scaler.is_enabled():
                    scaler.step(optimizer)
                    scaler.update()
                else:
                    optimizer.step()
                scheduler.step()
                optimizer.zero_grad(set_to_none=True)
                accum_cnt = 0
                global_step += 1

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

                if global_step % eval_every == 0 or global_step == total_steps:
                    vm = evaluate(wrapper, val_loader, device, use_bf16)
                    vm["step"] = global_step
                    val_history.append(vm)
                    print(f"[val @ step {global_step}] {json.dumps(vm)}", flush=True)
                    if vm["selection_score"] > best_score:
                        best_score = vm["selection_score"]
                        best_metrics = dict(vm)
                        # Save ONLY pure standard ModernBertForSequenceClassification (drops aux head!)
                        wrapper.seq_model.save_pretrained(str(out_dir), safe_serialization=True)
                        tokenizer.save_pretrained(str(out_dir))
                        print(f"[ckpt] New best selection_score={best_score:.5f} saved -> {out_dir}", flush=True)

    runtime = round(time.time() - t0, 1)
    summary = {
        "method": args.method,
        "base_model": args.base_model,
        "max_length": args.max_length,
        "epochs": args.epochs,
        "lr": args.lr,
        "eff_bs": args.batch_size * args.grad_accum,
        "pooling": "cls",
        "train_examples": len(train_enc),
        "val_examples": len(val_enc),
        "total_steps": global_step,
        "train_runtime_sec": runtime,
        "best_val_metrics": best_metrics,
        "val_history": val_history,
        "mg_cpil_weights": {
            "lam_span": args.lam_span,
            "lam_mil": args.lam_mil,
            "lam_agree": args.lam_agree,
            "lam_rank": args.lam_rank,
        } if is_mg else None,
    }
    (out_dir / "training_summary.json").write_text(json.dumps(summary, indent=2), encoding="utf-8")
    print(f"[train:{args.method}] DONE in {runtime}s! Best val:", json.dumps(best_metrics, indent=2))


if __name__ == "__main__":
    main()