File size: 24,106 Bytes
878a77d ae083e8 878a77d 1cd4e74 878a77d 530b197 0a240d5 530b197 0a240d5 530b197 0a240d5 530b197 1cd4e74 878a77d 03b9f78 878a77d 3254bd9 878a77d ae083e8 878a77d 3254bd9 878a77d 1cd4e74 878a77d 3254bd9 878a77d 3254bd9 878a77d 530b197 878a77d 530b197 878a77d 3254bd9 878a77d 1cd4e74 878a77d | 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 | """
train_split_model_cuda.py — Train binary Sandhi boundary detector on any
device (CUDA / MPS / CPU), with HuggingFace-dataset support.
This is a device-agnostic extension of train_split_model.py. It reuses the
EXACT same model/dataset classes from train_split_model.py (imported, not
copied), so a checkpoint trained here loads identically in decode_best.py /
decode_v2.py. Nothing in the original files is modified.
What it adds over train_split_model.py:
* Explicit --device {auto,cuda,mps,cpu} selection (auto = cuda -> mps -> cpu).
* --data accepts a local path OR "hf://<owner>/<repo>/<file.jsonl>":
- the file is downloaded to the local HF cache with huggingface_hub
(works for private repos if HF_TOKEN is set in the environment),
- then trained on exactly like a local file.
* Optional --bf16 mixed precision (Ampere/Ada+ safe — A100, L40S, H100...;
OFF by default so the
run is numerically identical to the MPS run).
* --push-checkpoint <owner>/<repo>: uploads model.safetensors + config.json
to a HuggingFace MODEL repo when training finishes (requires HF_TOKEN).
* Defaults match the deployed checkpoint (num_modes=32, delay=2,
latent_dim=128, 2 layers, pos_weight=6.0) so a bare run reproduces the
same architecture.
* Config.json is ALWAYS written, so inference picks up num_modes/delay
instead of inferring them.
Usage:
# local, same device logic as before (MPS on a Mac, CUDA if available)
python train_split_model_cuda.py --data data/train_V2_fixed.jsonl \
--delay 2 --num-modes 32 --out checkpoints/delayed_model_save_fixed
# train from a HuggingFace dataset (private ok, needs HF_TOKEN)
python train_split_model_cuda.py \
--data hf://youruser/sanskrit-sandhi-boundaries-v2/train_V2_fixed.jsonl \
--delay 2 --num-modes 32 --epochs 3 --batch 32 --grad-accum 4
# smoke test (minutes anywhere): 500 samples, 2 epochs
python train_split_model_cuda.py --smoke
# force a specific device
python train_split_model_cuda.py --device cuda --data ...
"""
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 the SHARED classes from the original script (single source of
# truth -> guaranteed architecture compatibility with decode_best.py).
# Guard the torch.serialization call: `add_safe_globals` only exists on
# torch >= 2.6. On older torch the import would crash, so fail with a
# clear message instead of a confusing traceback on a paid run.
# ──────────────────────────────────────────────────────────────────────
if not hasattr(torch.serialization, "add_safe_globals"):
sys.exit(
"torch >= 2.6 is required (torch.serialization.add_safe_globals missing). "
"On Modal use the pinned image in modal_train.py; locally upgrade torch."
)
from train_split_model import ( # noqa: E402
BinaryBoundaryDataset,
compute_metrics,
VOCAB_SIZE,
PAD_ID,
)
from transformers import Trainer, TrainingArguments, TrainerCallback # noqa: E402
from model import HybridTimeScaleConfig # noqa: E402
def build_training_args(**kwargs) -> TrainingArguments:
"""Create TrainingArguments tolerant of old AND new transformers versions.
* Pre-4.9 transformers lack kwargs like warmup_ratio -> drop them.
* Pre-4.46 uses evaluation_strategy instead of eval_strategy -> rename.
* v5.x deprecates warmup_ratio (removal planned in v5.2) in favor of
warmup_steps, which now accepts a float ratio -> convert automatically.
Upgrade with `pip install -U transformers` to get full support.
"""
import inspect
try:
import transformers as _tf
tf_major = int(_tf.__version__.split(".")[0])
except Exception:
tf_major = 4
if tf_major >= 5 and "warmup_ratio" in kwargs:
kwargs["warmup_steps"] = kwargs.pop("warmup_ratio")
fields = getattr(TrainingArguments, "__dataclass_fields__", None)
known = set(fields) if fields else set(inspect.signature(TrainingArguments.__init__).parameters)
if "eval_strategy" in kwargs and "eval_strategy" not in known and "evaluation_strategy" in known:
kwargs["evaluation_strategy"] = kwargs.pop("eval_strategy")
unknown = [k for k in kwargs if k not in known]
if unknown:
print(f"[warn] transformers too old for kwargs {unknown} — dropping them "
f"(pip install -U transformers to enable)", file=sys.stderr)
for k in unknown:
kwargs.pop(k)
return TrainingArguments(**kwargs)
class PushCheckpointCallback(TrainerCallback):
"""Push every saved checkpoint to an HF model repo the moment it is saved.
With --push-checkpoint set, each checkpoint-<step>/ directory is uploaded
to hf://<repo>/checkpoints/step-<step>/ as soon as the Trainer writes it.
A mid-run kill (budget gone, instance recycled, Ctrl-C) therefore never
loses progress: the best-so-far weights are already on the Hub. The final
push_checkpoint() still uploads the best model to the repo root.
"""
def __init__(self, repo_id: str):
self.repo_id = repo_id
self._api = None
def _hub(self):
if self._api is None:
from huggingface_hub import HfApi
self._api = HfApi()
self._api.create_repo(repo_id=self.repo_id, repo_type="model", exist_ok=True)
return self._api
def on_save(self, args, state, control, **kwargs):
step = state.global_step
ckpt_dir = os.path.join(args.output_dir, f"checkpoint-{step}")
if not os.path.isdir(ckpt_dir):
return
try:
self._hub().upload_folder(
repo_id=self.repo_id,
folder_path=ckpt_dir,
repo_type="model",
path_in_repo=f"checkpoints/step-{step}",
commit_message=f"checkpoint step {step}",
)
print(f"[push] checkpoint-{step} -> hf://{self.repo_id}/checkpoints/step-{step}",
file=sys.stderr)
except Exception as e: # never let a push failure kill training
print(f"[push] WARNING: failed to push checkpoint-{step}: {e}",
file=sys.stderr)
def get_model_class(backbone: str):
"""Return the BinaryBoundaryModel class for the chosen backbone.
* 'local': train_split_model.BinaryBoundaryModel (model.py math) — the
default, byte-identical to the original training path.
* 'hf': hybrid_boundary_model.HybridBoundaryModel — built on the
HuggingFace CodeIsAbstract/HybridTimeScale backbone (chunked parallel
linear attention, explicit position_ids, KV-cache support). State-dict
keys are identical (blocks.*, head.*, pos_weight), so checkpoints
trained this way load in decode_best.py / decode_v2.py with zero
changes. Requires the HF model.py: pip install the package, set
HYBRID_HF_MODEL_PATH, or drop it at hf_backbone/model.py.
"""
if backbone == "local":
from train_split_model import BinaryBoundaryModel
return BinaryBoundaryModel
if backbone == "hf":
from hybrid_boundary_model import HybridBoundaryModel
return HybridBoundaryModel
sys.exit(f"[error] unknown --backbone {backbone} (local|hf)")
# ---------------------------------------------------------------------------
# HF dataset resolution
# ---------------------------------------------------------------------------
def resolve_data_path(data_arg: str) -> str:
"""Turn --data into a local jsonl path.
Accepts:
* a local path (used as-is), or
* hf://<owner>/<repo>/<file> -> downloaded via huggingface_hub to the
local HF cache (private repos work when HF_TOKEN is set).
"""
if not data_arg.startswith("hf://"):
if not os.path.exists(data_arg):
sys.exit(f"[error] data file not found: {data_arg}")
return data_arg
spec = data_arg[len("hf://"):]
parts = spec.split("/")
if len(parts) < 3:
sys.exit(
f"[error] hf:// spec must be hf://<owner>/<repo>/<file>: {data_arg}"
)
repo_id = f"{parts[0]}/{parts[1]}"
filename = "/".join(parts[2:])
from huggingface_hub import hf_hub_download
try:
path = hf_hub_download(repo_id=repo_id, filename=filename,
repo_type="dataset")
except Exception as e:
sys.exit(
f"[error] failed to download {repo_id}/{filename} from HF.\n"
f" If the repo is private, set HF_TOKEN (e.g. HF_TOKEN=... or "
f"modal.Secret.from_name('hf-token')).\n detail: {e}"
)
print(f"Downloaded dataset to HF cache: {path}", file=sys.stderr)
return path
# ---------------------------------------------------------------------------
# Device selection (explicit override + auto cuda -> mps -> cpu)
# ---------------------------------------------------------------------------
def get_device(device_arg: Optional[str]) -> torch.device:
if device_arg == "auto" or device_arg is None:
if torch.cuda.is_available():
return torch.device("cuda")
if torch.backends.mps.is_available():
return torch.device("mps")
return torch.device("cpu")
if device_arg == "cuda":
if not torch.cuda.is_available():
sys.exit("[error] --device cuda but CUDA is not available")
return torch.device("cuda")
if device_arg == "mps":
if not torch.backends.mps.is_available():
sys.exit("[error] --device mps but MPS is not available")
return torch.device("mps")
if device_arg == "cpu":
return torch.device("cpu")
sys.exit(f"[error] unknown --device {device_arg} (auto|cuda|mps|cpu)")
# ---------------------------------------------------------------------------
# HF checkpoint push
# ---------------------------------------------------------------------------
def push_checkpoint(out_dir: str, repo_id: str, config) -> None:
from huggingface_hub import HfApi, upload_folder
files = [f for f in os.listdir(out_dir) if f.endswith((".safetensors", ".bin", ".json", ".txt"))]
print(f"Pushing {len(files)} files from {out_dir} to hf://{repo_id}", file=sys.stderr)
api = HfApi()
api.create_repo(repo_id=repo_id, repo_type="model", exist_ok=True)
upload_folder(repo_id=repo_id, folder_path=out_dir, repo_type="model")
print(f"Checkpoint pushed to https://huggingface.co/{repo_id}", file=sys.stderr)
# ---------------------------------------------------------------------------
# Main
# ---------------------------------------------------------------------------
def main():
parser = argparse.ArgumentParser(description="Train binary Sandhi boundary detector (CUDA/MPS/CPU).")
parser.add_argument("--data", default="data/train_V2_fixed.jsonl",
help="local jsonl path OR hf://<owner>/<repo>/<file>.jsonl")
parser.add_argument("--out", default="checkpoints/delayed_model_save_fixed")
parser.add_argument("--epochs", type=int, default=3)
parser.add_argument("--batch", type=int, default=32)
parser.add_argument("--grad-accum", type=int, default=4)
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-layers", type=int, default=2,
help="number of blocks (requires --layer-types)")
parser.add_argument("--layer-types", default=None,
help="comma-separated block types, e.g. 'linear,softmax' or "
"'linear,softmax,linear' or 'linear,linear'. Default: "
"linear,softmax (matches the deployed model)")
parser.add_argument("--num-modes", type=int, default=32,
help="Fourier modes; 32 matches the deployed checkpoint")
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=2,
help="Delayed prediction: model at pos t predicts pos t-N (2 = deployed)")
parser.add_argument("--device", default="auto", choices=["auto", "cuda", "mps", "cpu"])
parser.add_argument("--backbone", default="local", choices=["local", "hf"],
help="'local' = model.py math (original); 'hf' = HuggingFace "
"CodeIsAbstract/HybridTimeScale backbone (chunked linear "
"attention, position_ids, KV cache). Same checkpoint format.")
parser.add_argument("--bf16", action="store_true",
help="Use bf16 autocast (Ampere/Ada+ GPUs: A100, L40S, H100...; "
"off by default for fp32 parity with MPS)")
parser.add_argument("--eval-steps", type=int, default=500)
parser.add_argument("--save-steps", type=int, default=500)
parser.add_argument("--dataloader-workers", type=int, default=0,
help="DataLoader workers (0 = main process). On A100 with "
"large batch sizes, 4-8 avoids data-loading stalls.")
parser.add_argument("--resume", default=None,
help="Resume from checkpoint dir (e.g. checkpoints/delayed_model_save_fixed/checkpoint-5500)")
parser.add_argument("--push-checkpoint", default=None,
help="hf repo id (owner/name) to push checkpoints to (needs HF_TOKEN). "
"Every saved checkpoint is pushed live to checkpoints/step-<n>/; "
"the best model is pushed to the repo root at the end.")
args = parser.parse_args()
# Auto-set output dir for delayed models (keeps naming conventions)
if args.out == "checkpoints/delayed_model_save_fixed" and args.delay > 0:
args.out = f"checkpoints/delayed_model_save_fixed_delay{args.delay}"
device = get_device(args.device)
print(f"Device: {device}", file=sys.stderr)
# ── Config ──────────────────────────────────────────────────────
if args.layer_types:
layer_types = [t.strip() for t in args.layer_types.split(",") if t.strip()]
valid = {"linear", "softmax"}
if not layer_types or any(t not in valid for t in layer_types):
sys.exit(f"[error] --layer-types must be comma-separated values from {valid}")
else:
# default pattern: alternate linear/softmax starting with linear
layer_types = (["linear", "softmax"] * args.num_layers)[: args.num_layers]
config = HybridTimeScaleConfig(
vocab_size=VOCAB_SIZE,
latent_dim=args.latent_dim,
num_layers=len(layer_types),
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, # shared with train_split_model.py
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_class = get_model_class(args.backbone)
model = model_class(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" backbone={args.backbone}, latent_dim={args.latent_dim}, num_modes={args.num_modes}, "
f"layers={layer_types}, delay={args.delay}", file=sys.stderr)
# ── Data ────────────────────────────────────────────────────────
if args.smoke:
args.limit = 500
args.epochs = 2
args.eval_steps = 20
args.save_steps = 20
print("SMOKE TEST: 500 samples, 2 epochs", file=sys.stderr)
data_path = resolve_data_path(args.data)
print(f"Data: {data_path}", file=sys.stderr)
full_ds = BinaryBoundaryDataset(
data_path, 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)
# Stratified eval: 1000 samples across complexity bins (deterministic, seed 42)
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)
train_subset = torch.utils.data.Subset(full_ds, train_indices)
eval_subset = torch.utils.data.Subset(full_ds, eval_indices)
# ── Training args ───────────────────────────────────────────────
# fp32 by default (numerically identical to the MPS run). bf16 is opt-in
# and safe on A100/H100 (loss is computed in fp32 internally).
use_bf16 = args.bf16 and device.type == "cuda"
training_args = build_training_args(
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,
logging_steps=10,
eval_strategy="steps",
eval_steps=args.eval_steps,
save_strategy="steps",
save_steps=args.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=False,
bf16=use_bf16,
dataloader_num_workers=args.dataloader_workers,
gradient_checkpointing=False,
seed=42,
use_cpu=(device.type == "cpu"),
remove_unused_columns=False,
)
# ── Resume ──────────────────────────────────────────────────────
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)
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 ─────────────────────────────────────────────────────
# Same custom trainer as train_split_model.py: keep labels in inputs so
# the model can compute the (imbalanced) BCE loss itself.
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")
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] labels sum: {inputs['labels'].sum().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,
)
# Live checkpoint push (every save — never loses a mid-run kill)
if args.push_checkpoint:
trainer.add_callback(PushCheckpointCallback(args.push_checkpoint))
# ── Train ───────────────────────────────────────────────────────
print(f"\nStarting training: {args.epochs} epochs, {len(train_indices)} samples "
f"on {device.type}", file=sys.stderr)
print(f"Effective batch size: {args.batch * args.grad_accum}", file=sys.stderr)
print(f"Mixed precision: {'bf16' if use_bf16 else 'fp32'}", 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)
# ── Optional push to HF ─────────────────────────────────────────
if args.push_checkpoint:
push_checkpoint(args.out, args.push_checkpoint, config)
if __name__ == "__main__":
main()
|