File size: 23,975 Bytes
10784d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9a331b6
 
 
 
 
10784d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9a331b6
 
 
 
 
 
10784d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
train_split_model.py — Train binary Sandhi boundary detector.

Same HybridFourierLM backbone as train_model.py but with a single-bit
output: is this character position a split boundary (1) or not (0)?

Drops the 14 it-marker bits and 2 context bits — trains ONLY on boundary
detection, the task that matters for Vidyut vigraha.

Class imbalance: ~6.5 zeros per one (from dataset stats).
Handled via BCEWithLogitsLoss(pos_weight=6.0).

Delayed prediction (--delay N):
  Labels are shifted forward by N positions. Model at position t predicts
  whether position t-N is a boundary. This gives the model N chars of
  lookahead context, improving prefix-vs-reversed disambiguation.
  N pad chars are appended at the end of each sequence so the model can
  still predict boundaries in the last N-char window.

Usage:
    python train_split_model.py --smoke --epochs 2
    python train_split_model.py --epochs 5 --batch 8
    python train_split_model.py --epochs 10 --batch 128 --grad-accum 2 --num-modes 32

    # With 2-char delayed prediction
    python train_split_model.py --epochs 10 --batch 128 --grad-accum 2 --num-modes 32 --delay 2
"""

from __future__ import annotations

import argparse
import json
import os
import sys
import random
from typing import Dict, List, Optional, Tuple

import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import Dataset

from transformers import (
    AutoConfig,
    Trainer,
    TrainingArguments,
)
from model import HybridTimeScaleConfig, HybridSpectralBlock

# Fix PyTorch 2.6+ weights_only default breaking checkpoint resume
import numpy as np
import torch.serialization
torch.serialization.add_safe_globals([np.core.multiarray._reconstruct, np.ndarray, np.dtype])


# ---------------------------------------------------------------------------
# Char vocabulary (same as train_model.py)
# ---------------------------------------------------------------------------

SLP1_CHARS: str = "aAiIuUfFxXeEoOMHkKgGNcCjJYwWqQRtTdDnpPbBmyrlvSzshL' "
PAD_CHAR: str = " "
PAD_ID: int = SLP1_CHARS.index(PAD_CHAR)
char_to_idx: Dict[str, int] = {c: i for i, c in enumerate(SLP1_CHARS)}
VOCAB_SIZE: int = len(SLP1_CHARS)


# ---------------------------------------------------------------------------
# Dataset — binary labels only
# ---------------------------------------------------------------------------

class BinaryBoundaryDataset(Dataset):
    """
    Reads V2 JSONL. Each row: one compound with all boundaries.
    Returns (input_ids, attention_mask, labels) where labels is (L,) binary:
        1 at boundary positions, 0 everywhere else.

    With delay=N:
        - N pad chars prepended and appended to the sequence
        - Labels shifted forward by N: boundary at position bnd gets label
          at position bnd + N (model at pos bnd+N predicts for pos bnd)
        - attention_mask=1 covers positions N..N+L-1 (real chars)
          Loss is masked by attention_mask — pad positions at start/end
          are excluded automatically.
    """

    def __init__(self, jsonl_path: str, max_seq_len: int = 256,
                 delay: int = 0, limit: Optional[int] = None):
        self.samples: List[Dict] = []
        self.max_seq_len = max_seq_len
        self.delay = delay

        with open(jsonl_path, "r", encoding="utf-8") as f:
            for i, line in enumerate(f):
                if limit and i >= limit:
                    break
                p = json.loads(line)
                seq = p.get("seq", "")
                if not seq or len(seq) < 2:
                    continue
                self.samples.append(p)

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

    def __getitem__(self, idx: int) -> Dict[str, torch.Tensor]:
        p = self.samples[idx]
        seq = p["seq"]
        bnd_list = p.get("bnd", [])
        N = self.delay

        if N > 0:
            # Delayed prediction WITHOUT prepend pads.
            # Real chars at positions 0..L-1 (same as no-delay).
            # Append N pad chars at end so model can predict boundaries
            # in the last N-char window.
            # Labels shifted forward by N: boundary at position bnd gets
            # label at position bnd + N. Model at pos bnd+N predicts for pos bnd.
            # First N positions have no label (model hasn't seen enough context).
            max_real = self.max_seq_len - N  # reserve N for append pads
            L = min(len(seq), max_real)

            input_ids = torch.full((self.max_seq_len,), PAD_ID, dtype=torch.long)
            attention_mask = torch.zeros(self.max_seq_len, dtype=torch.long)
            labels = torch.zeros(self.max_seq_len, dtype=torch.float)

            # Real chars at positions 0..L-1
            for i, c in enumerate(seq[:L]):
                input_ids[i] = char_to_idx.get(c, PAD_ID)
                attention_mask[i] = 1

            # Append N pad chars at positions L..L+N-1 with attention_mask=0
            # (already zero by default)

            # Labels shifted by N: boundary at bnd -> label at bnd+N
            # attention_mask=1 at positions 0..L-1, but labels are at N..L+N-1
            # The loss mask needs to cover label positions that have real char context.
            # Model at pos bnd+N predicts for pos bnd. It has seen chars 0..bnd+N.
            # Valid predictions: positions N..L+N-1 (where bnd = 0..L-1).
            # But attention_mask only covers 0..L-1. We need the loss to be computed
            # at label positions N..min(L+N-1, max_seq_len-1) where attention_mask=1
            # at the predicted position. Since model output at pos bnd+N uses
            # attention over 0..bnd+N, and pos bnd+N might be a pad (if bnd+N >= L),
            # we only compute loss where bnd+N < L (label position within real chars).
            for bnd in bnd_list:
                if bnd < L and bnd + N < L:
                    labels[bnd + N] = 1.0

            # Extend attention_mask to cover append pad positions so the loss
            # is computed there too (model output at pad positions is valid for
            # predicting boundaries in the last N chars)
            # Actually: we want loss at positions N..L+N-1. But attention_mask
            # is 0 at L..L+N-1 (pads). So we need a separate label mask.
            # Simplest: just extend attention_mask to L+N so loss is computed
            # at the append pad positions too.
            attention_mask[L:L+N] = 1  # allow loss at append pad positions
        else:
            # No delay — standard
            L = min(len(seq), self.max_seq_len)
            input_ids = torch.full((self.max_seq_len,), PAD_ID, dtype=torch.long)
            attention_mask = torch.zeros(self.max_seq_len, dtype=torch.long)
            labels = torch.zeros(self.max_seq_len, dtype=torch.float)

            for i, c in enumerate(seq[:L]):
                input_ids[i] = char_to_idx.get(c, PAD_ID)
                attention_mask[i] = 1
            for bnd in bnd_list:
                if bnd < L:
                    labels[bnd] = 1.0

        # Set labels to -100 at attention-masked positions (tail pads)
        # so compute_metrics can filter them. Loss already masks these
        # via attention_mask, so -100 values are ignored during training.
        labels[attention_mask == 0] = -100.0

        return {
            "input_ids": input_ids,
            "attention_mask": attention_mask,
            "labels": labels,
        }


# ---------------------------------------------------------------------------
# Model — backbone + single-bit binary head
# ---------------------------------------------------------------------------

class BinaryBoundaryModel(nn.Module):
    """
    HybridFourierLM backbone + binary boundary head.

    Output: (B, L, 1) logits — sigmoid > 0.5 = boundary.
    Loss: BCEWithLogitsLoss(pos_weight=class_imbalance_ratio).
    """

    def __init__(self, config: HybridTimeScaleConfig, pos_weight: float = 6.0):
        super().__init__()
        self.config = config

        # Backbone (same as train_model.py)
        self.embedding = nn.Embedding(
            config.vocab_size, config.latent_dim, padding_idx=config.pad_token_id
        )
        self.blocks = nn.ModuleList([
            HybridSpectralBlock(
                config.latent_dim,
                config.num_modes,
                is_softmax=(lt == "softmax"),
                time_scale=config.time_scale,
                dropout=config.dropout,
            )
            for lt in config.layer_types
        ])
        self.ln_f = nn.LayerNorm(config.latent_dim)

        # Binary head: latent_dim -> 1
        self.head = nn.Sequential(
            nn.LayerNorm(config.latent_dim),
            nn.Linear(config.latent_dim, config.latent_dim // 2),
            nn.GELU(),
            nn.Dropout(config.dropout),
            nn.Linear(config.latent_dim // 2, 1),
        )

        # Loss with class imbalance weighting
        # Keep pos_weight in float32 even under bf16 to prevent overflow
        self.register_buffer(
            "pos_weight", torch.tensor([pos_weight], dtype=torch.float32)
        )
        self.loss_fct = nn.BCEWithLogitsLoss(
            pos_weight=self.pos_weight, reduction="none"
        )

        self._init_weights()

    def _init_weights(self):
        for m in self.modules():
            if isinstance(m, nn.Linear):
                nn.init.normal_(m.weight, mean=0.0, std=0.02)
                if m.bias is not None:
                    nn.init.zeros_(m.bias)
            elif isinstance(m, nn.Embedding):
                nn.init.normal_(m.weight, mean=0.0, std=0.02)
                if m.padding_idx is not None:
                    nn.init.zeros_(m.weight[m.padding_idx])
            elif isinstance(m, nn.LayerNorm):
                nn.init.ones_(m.weight)
                nn.init.zeros_(m.bias)

    def forward(
        self,
        input_ids: Optional[torch.Tensor] = None,
        attention_mask: Optional[torch.Tensor] = None,
        labels: Optional[torch.Tensor] = None,
        **kwargs,
    ) -> Dict[str, torch.Tensor]:
        z = self.embedding(input_ids)

        # Zero out pad positions before mixer to prevent NaN gradients
        # from causal attention on pad embeddings (especially with delay pads)
        if attention_mask is not None:
            z = z * attention_mask.unsqueeze(-1).to(dtype=z.dtype)

        for block in self.blocks:
            z = block(z, attention_mask=attention_mask)

        z = self.ln_f(z)
        logits = self.head(z).squeeze(-1)  # (B, L)

        loss = None
        if labels is not None:
            mask = attention_mask.float()  # (B, L)
            # Compute loss in float32 for numerical stability
            logits_f32 = logits.float()
            labels_f32 = labels.float()
            loss_fct = nn.BCEWithLogitsLoss(
                pos_weight=self.pos_weight, reduction="none"
            )
            loss_per_elem = loss_fct(logits_f32, labels_f32) * mask  # (B, L)
            loss = loss_per_elem.sum() / (mask.sum() + 1e-8)

        return {"loss": loss, "logits": logits}


# ---------------------------------------------------------------------------
# Metrics — precision, recall, F1 for binary boundary detection
# ---------------------------------------------------------------------------

def compute_metrics(eval_pred):
    logits, labels = eval_pred
    if isinstance(logits, tuple):
        logits = logits[0]

    preds = (torch.sigmoid(torch.tensor(logits)) > 0.5).float().numpy()
    labels = np.array(labels)

    # Filter to valid positions: dataset sets labels=-100 at
    # attention-masked tail pads (no loss, no gradient there, so logits
    # drift freely and would corrupt the metric with phantom FPs).
    valid = labels >= 0
    preds = preds[valid]
    labels = labels[valid]

    tp = ((preds == 1) & (labels == 1)).sum()
    fp = ((preds == 1) & (labels == 0)).sum()
    fn = ((preds == 0) & (labels == 1)).sum()
    tn = ((preds == 0) & (labels == 0)).sum()

    precision = tp / (tp + fp + 1e-8)
    recall = tp / (tp + fn + 1e-8)
    f1 = 2 * precision * recall / (precision + recall + 1e-8)
    accuracy = (tp + tn) / (tp + fp + fn + tn + 1e-8)

    return {
        "precision": float(precision),
        "recall": float(recall),
        "f1": float(f1),
        "accuracy": float(accuracy),
    }


# ---------------------------------------------------------------------------
# Device selection
# ---------------------------------------------------------------------------

def get_device() -> torch.device:
    if torch.cuda.is_available():
        return torch.device("cuda")
    elif torch.backends.mps.is_available():
        return torch.device("mps")
    return torch.device("cpu")


# ---------------------------------------------------------------------------
# Main
# ---------------------------------------------------------------------------

def main():
    parser = argparse.ArgumentParser(description="Train binary Sandhi boundary detector.")
    parser.add_argument("--data", default="data/train_V2.jsonl")
    parser.add_argument("--out", default="checkpoints/binary_boundary")
    parser.add_argument("--epochs", type=int, default=5)
    parser.add_argument("--batch", type=int, default=8)
    parser.add_argument("--grad-accum", type=int, default=2)
    parser.add_argument("--lr", type=float, default=3e-4)
    parser.add_argument("--max-seq-len", type=int, default=256)
    parser.add_argument("--latent-dim", type=int, default=128)
    parser.add_argument("--num-modes", type=int, default=4)
    parser.add_argument("--pos-weight", type=float, default=6.0,
                        help="Class imbalance weight (boundaries are 1-in-6.5)")
    parser.add_argument("--limit", type=int, default=None)
    parser.add_argument("--smoke", action="store_true")
    parser.add_argument("--delay", type=int, default=0,
                        help="Delayed prediction: shift labels forward by N positions. "
                             "Model at pos t predicts for pos t-N. Gives N chars of lookahead. "
                             "N pad chars prepended+appended. 0=standard (no delay).")
    parser.add_argument("--resume", default=None,
                        help="Resume from checkpoint dir (e.g. checkpoints/binary_boundary/checkpoint-5500)")
    args = parser.parse_args()

    # Auto-set output dir for delayed models
    if args.delay > 0 and args.out == "checkpoints/binary_boundary":
        args.out = f"checkpoints/binary_boundary_delay{args.delay}"
        print(f"Delayed mode (delay={args.delay}) -> output: {args.out}", file=sys.stderr)

    device = get_device()
    print(f"Device: {device}", file=sys.stderr)

    # ── Config ──────────────────────────────────────────────────────
    layer_types = ["linear", "softmax"]
    num_heads = 4

    config = HybridTimeScaleConfig(
        vocab_size=VOCAB_SIZE,
        latent_dim=args.latent_dim,
        num_layers=2,
        num_modes=args.num_modes,
        layer_types=layer_types,
        time_scale=float(2 * args.num_modes),  # Nyquist: time_scale = 2 * num_modes
        dropout=0.1,
        pad_token_id=PAD_ID,
        bos_token_id=0,
        eos_token_id=0,
        tie_word_embeddings=False,
    )
    # Store delay in config for inference to pick up
    config.delay = args.delay

    model = BinaryBoundaryModel(config, pos_weight=args.pos_weight)
    n_params = sum(p.numel() for p in model.parameters())
    print(f"Model parameters: {n_params:,} ({n_params/1e6:.2f}M)", file=sys.stderr)
    print(f"  latent_dim={args.latent_dim}, num_modes={args.num_modes}, heads={num_heads}",
          file=sys.stderr)
    print(f"  layers: {layer_types}", file=sys.stderr)
    print(f"  pos_weight={args.pos_weight} (class imbalance ~6.5:1)", file=sys.stderr)

    # ── Data ────────────────────────────────────────────────────────
    if args.smoke:
        args.limit = 500
        args.epochs = 2
        print("SMOKE TEST: 500 samples, 2 epochs", file=sys.stderr)

    full_ds = BinaryBoundaryDataset(
        args.data, max_seq_len=args.max_seq_len, delay=args.delay, limit=args.limit
    )
    print(f"Total samples: {len(full_ds)}", file=sys.stderr)
    if args.delay > 0:
        print(f"Delayed prediction: delay={args.delay}, labels shifted +{args.delay}, "
              f"{args.delay} pad chars appended at end", file=sys.stderr)
        print(f"Note: first {args.delay} positions have no predictions (no context yet)",
              file=sys.stderr)
        max_real = args.max_seq_len - args.delay
        print(f"Effective max real chars: {max_real} (from {args.max_seq_len} - {args.delay})",
              file=sys.stderr)

    # Stratified eval: 1000 samples across complexity bins
    random.seed(42)
    indices = list(range(len(full_ds)))
    random.shuffle(indices)

    eval_target = min(1000, len(full_ds) // 10)
    bins: Dict[str, List[int]] = {"1-2": [], "3-5": [], "6-10": [], "11+": []}
    for i in indices:
        nb = full_ds.samples[i].get("n_boundaries", 1)
        if nb <= 2:
            bins["1-2"].append(i)
        elif nb <= 5:
            bins["3-5"].append(i)
        elif nb <= 10:
            bins["6-10"].append(i)
        else:
            bins["11+"].append(i)

    eval_indices: List[int] = []
    per_bin = eval_target // len(bins)
    for key in bins:
        take = min(per_bin, len(bins[key]))
        eval_indices.extend(bins[key][:take])

    eval_set = set(eval_indices)
    train_indices = [i for i in indices if i not in eval_set]

    print(f"Stratified eval: {len(eval_indices)} samples", file=sys.stderr)
    for key in bins:
        n_in_eval = len(set(bins[key]) & eval_set)
        print(f"  {key} boundaries: {n_in_eval} eval / {len(bins[key])} total",
              file=sys.stderr)

    train_subset = torch.utils.data.Subset(full_ds, train_indices)
    eval_subset = torch.utils.data.Subset(full_ds, eval_indices)

    # ── Training args ───────────────────────────────────────────────
    use_fp16 = False  # Don't use fp16 — causes NaN with pos_weight on MPS
    use_bf16 = False  # Don't use bf16 — causes NaN gradients with pad positions

    eval_steps = 20 if args.smoke else 500
    save_steps = eval_steps

    training_args = TrainingArguments(
        output_dir=args.out,
        num_train_epochs=args.epochs,
        per_device_train_batch_size=args.batch,
        per_device_eval_batch_size=args.batch,
        gradient_accumulation_steps=args.grad_accum,
        learning_rate=args.lr,
        warmup_ratio=0.05,
        lr_scheduler_type="cosine",
        weight_decay=0.01,
        max_grad_norm=0.5,  # Lower to prevent NaN from bf16 gradient overflow
        logging_steps=10,
        eval_strategy="steps",
        eval_steps=eval_steps,
        save_strategy="steps",
        save_steps=save_steps,
        save_total_limit=3,
        load_best_model_at_end=True,
        metric_for_best_model="f1",
        greater_is_better=True,
        report_to="none",
        fp16=use_fp16,
        bf16=use_bf16,
        dataloader_num_workers=0,
        gradient_checkpointing=False,
        seed=42,
        use_cpu=(device.type == "cpu"),
        remove_unused_columns=False,
    )

    # ── Load pretrained weights if specified ─────────────────────────
    resume_from = args.resume
    if resume_from:
        if os.path.isdir(resume_from):
            print(f"Loading weights from {resume_from}", file=sys.stderr)
            from safetensors.torch import load_file
            sd_path = os.path.join(resume_from, "model.safetensors")
            if not os.path.exists(sd_path):
                sd_path = os.path.join(resume_from, "pytorch_model.bin")
                state_dict = torch.load(sd_path, map_location="cpu", weights_only=False)
            else:
                state_dict = load_file(sd_path)
            # Clean keys
            state_dict = {k.replace("_orig_mod.", ""): v for k, v in state_dict.items()}
            model.load_state_dict(state_dict, strict=False)
            print(f"Weights loaded (fresh LR schedule, no optimizer state)", file=sys.stderr)
        else:
            print(f"[warn] {resume_from} not found, starting fresh", file=sys.stderr)
            resume_from = None

    # ── Trainer ─────────────────────────────────────────────────────
    # Custom trainer: keep labels in inputs so model can compute loss.
    # Standard Trainer pops labels before model call, causing NaN in eval
    # because our model computes loss internally.
    class BoundaryTrainer(Trainer):
        def compute_loss(self, model, inputs, return_outputs=False, num_items_in_batch=None):
            outputs = model(**inputs)
            loss = outputs["loss"] if isinstance(outputs, dict) else outputs[0]
            return (loss, outputs) if return_outputs else loss

        def prediction_step(self, model, inputs, prediction_loss_only, ignore_keys=None):
            inputs = self._prepare_inputs(inputs)
            with torch.no_grad():
                outputs = model(**inputs)
                loss = outputs.get("loss")
                logits = outputs.get("logits")
                labels = inputs.get("labels")
            # Debug
            if loss is not None and torch.isnan(loss):
                print(f"[DEBUG] NaN loss! inputs keys: {list(inputs.keys())}", file=sys.stderr)
                print(f"[DEBUG] attention_mask sum: {inputs['attention_mask'].sum().item()}", file=sys.stderr)
                print(f"[DEBUG] labels sum: {inputs['labels'].sum().item()}", file=sys.stderr)
                print(f"[DEBUG] logits has NaN: {torch.isnan(logits).any().item()}", file=sys.stderr)
            if loss is not None:
                loss = loss.detach().cpu()
            if logits is not None:
                logits = logits.detach().cpu()
            if labels is not None:
                labels = labels.detach().cpu()
            return (loss, logits, labels)

    trainer = BoundaryTrainer(
        model=model,
        args=training_args,
        train_dataset=train_subset,
        eval_dataset=eval_subset,
        compute_metrics=compute_metrics,
    )

    # ── Train ───────────────────────────────────────────────────────
    print(f"\nStarting training: {args.epochs} epochs, {len(train_indices)} samples",
          file=sys.stderr)
    print(f"Effective batch size: {args.batch * args.grad_accum}", file=sys.stderr)
    print(f"Max seq len: {args.max_seq_len}", file=sys.stderr)
    print(f"Mixed precision: {'fp16' if use_fp16 else 'bf16' if use_bf16 else 'none'}",
          file=sys.stderr)
    print(file=sys.stderr)

    trainer.train()

    # ── Save ────────────────────────────────────────────────────────
    trainer.save_model(args.out)
    config.save_pretrained(args.out)
    print(f"\nModel saved to {args.out}", file=sys.stderr)

    # ── Final eval ──────────────────────────────────────────────────
    metrics = trainer.evaluate()
    print(f"\nFinal eval:", file=sys.stderr)
    for k, v in metrics.items():
        print(f"  {k}: {v}", file=sys.stderr)


if __name__ == "__main__":
    main()