""" 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()