"""Within-model fertility sweep: train and evaluate MTP on one romanization of the same Hindi. Identical to scripts/phase3_train.py -- frozen Llama-3.2-1B, one shared trainable layer, four predictors and a matched one-predictor baseline trained in the same process off one frozen forward pass, same token budget, same held-out documents -- except that the Hindi is written in IAST or ISO 15919, and acceptance is measured with the corrected decoder from scripts/phase4_speculative_eval.py rather than src.train.evaluate's. --existing re-scores a Phase 3 checkpoint (Devanagari or ITRANS) with that corrected decoder on the same documents, so all four scripts share one acceptance protocol. """ import argparse import csv import json import logging import os import sys import time from pathlib import Path os.environ.setdefault("CUDA_DEVICE_ORDER", "PCI_BUS_ID") sys.path.insert(0, str(Path(__file__).resolve().parents[1])) import torch import yaml from transformers import AutoModelForCausalLM, AutoTokenizer from scripts.phase3_train import build_stacks, git_hash from scripts.phase4_speculative_eval import acceptance_rows, load_trainable_stack, speculative_decode_verified from src.train.data import iter_batches, load_heldout_texts, load_train_ids from src.train.evaluate import evaluate_stack from src.train.trainer import train logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s") logging.getLogger("httpx").setLevel(logging.WARNING) logging.getLogger("huggingface_hub").setLevel(logging.WARNING) logger = logging.getLogger("phase4_fertility") DEVICE = "cuda:0" # the process is already restricted to one physical GPU by the caller def parse_args() -> argparse.Namespace: p = argparse.ArgumentParser(description=__doc__) p.add_argument("--config", default="configs/phase4_fertility.yaml") group = p.add_mutually_exclusive_group(required=True) group.add_argument("--condition", choices=["IAST", "ISO"], help="train and evaluate this romanization") group.add_argument("--existing", choices=["Devanagari", "ITRANS"], help="re-score a Phase 3 checkpoint's acceptance only") p.add_argument("--checkpoint-seed", default="seed0", help="which existing checkpoint to re-score") p.add_argument("--out", default=None, help="per-run CSV path (default: run_out_dir/.csv)") p.add_argument("--seed", type=int, default=None) p.add_argument("--max-steps", type=int, default=None, help="override; otherwise derived from the token budget") p.add_argument("--spec-docs", type=int, default=None, help="override the decoding document count") p.add_argument("--tag", default="", help="suffix distinguishing this run's checkpoints and logs") return p.parse_args() def whitespace_tables(tokenizer, vocab_size: int) -> tuple: """Per token id: does its decoded piece open / end with whitespace (word-start detection while decoding).""" pieces = tokenizer.batch_decode([[i] for i in range(vocab_size)]) opens = torch.tensor([p[:1].isspace() for p in pieces], dtype=torch.bool) closes = torch.tensor([p[-1:].isspace() for p in pieces], dtype=torch.bool) return opens, closes def write_rows(path: Path, rows: list) -> None: path.parent.mkdir(parents=True, exist_ok=True) with path.open("w", newline="", encoding="utf-8") as f: csv.writer(f).writerows(rows) def load_frozen_backbone(cfg: dict) -> tuple: tokenizer = AutoTokenizer.from_pretrained(cfg["backbone"]["hf_id"]) backbone = AutoModelForCausalLM.from_pretrained(cfg["backbone"]["hf_id"], dtype=torch.float32).to(DEVICE) backbone.eval() for param in backbone.parameters(): param.requires_grad = False return tokenizer, backbone def rescore_existing(cfg: dict, args: argparse.Namespace) -> None: """Corrected-decoder acceptance for an already-trained Phase 3 checkpoint.""" started = time.perf_counter() name = f"{args.existing}_{args.checkpoint_seed}" tokenizer, backbone = load_frozen_backbone(cfg) entry = cfg["existing"][args.existing] stack = load_trainable_stack(entry["checkpoints"][args.checkpoint_seed], backbone, cfg["n_heads"]) heldout = load_heldout_texts(entry["heldout"]) opens, closes = whitespace_tables(tokenizer, backbone.config.vocab_size) spec_docs = args.spec_docs or cfg["spec_docs"] torch.cuda.reset_peak_memory_stats(DEVICE) spec_start = time.perf_counter() spec = speculative_decode_verified( backbone, stack, tokenizer, heldout[:spec_docs], DEVICE, cfg["spec_prompt_tokens"], cfg["spec_completion_tokens"], opens, closes ) spec_seconds = time.perf_counter() - spec_start logger.info("%s: %.4f tokens per verification step over %d rounds (%.0fs)", name, spec.mean_accepted_per_forward, spec.n_rounds, spec_seconds) rows = [["arm", "metric", "value", "n"]] + acceptance_rows(name, spec) rows.append([name, "spec_docs", spec_docs, 1]) rows.append([name, "spec_seconds", f"{spec_seconds:.1f}", 1]) rows.append([name, "peak_gpu_mib", f"{torch.cuda.max_memory_allocated(DEVICE) / 1024**2:.1f}", 1]) rows.append([name, "wall_seconds", f"{time.perf_counter() - started:.1f}", 1]) out = Path(args.out) if args.out else Path(cfg["run_out_dir"]) / f"{name}_acceptance.csv" write_rows(out, rows) logger.info("wrote %s", out) def train_condition(cfg: dict, args: argparse.Namespace) -> None: seed = args.seed if args.seed is not None else cfg["seed"] c = args.condition tag = args.tag or f"seed{seed}" logger.info("config: %s", cfg) logger.info("condition=%s seed=%d use_shared_trunk=%s", c, seed, cfg["use_shared_trunk"]) torch.manual_seed(seed) started = time.perf_counter() tokenizer, backbone = load_frozen_backbone(cfg) mtp, ntp = build_stacks(backbone, cfg, cfg["use_shared_trunk"]) logger.info( "trainable params: mtp=%d ntp=%d", sum(p.numel() for p in mtp.trainable_parameters()), sum(p.numel() for p in ntp.trainable_parameters()), ) data_dir = Path(cfg["data_dir"]) train_ids = load_train_ids(str(data_dir / f"{c}_train_ids.npy")) heldout = load_heldout_texts(str(data_dir / f"{c}_heldout.jsonl")) logger.info("loaded %d train tokens, %d held-out docs", len(train_ids), len(heldout)) tokens_per_step = cfg["batch_size"] * cfg["seq_len"] max_steps = args.max_steps if args.max_steps is not None else len(train_ids) // tokens_per_step batches = iter_batches(train_ids, cfg["batch_size"], cfg["seq_len"], seed, max_steps=max_steps) torch.cuda.reset_peak_memory_stats(DEVICE) metrics = train(backbone, mtp, ntp, batches, DEVICE, cfg["learning_rate"], max_steps) logger.info( "training done: %d steps, %d tokens, %.1f tok/s, mtp_h1 %.4f ntp %.4f", metrics.steps, metrics.tokens, metrics.tokens_per_second, metrics.mtp_head_losses[0], metrics.ntp_loss, ) mtp.eval() ntp.eval() eval_start = time.perf_counter() mtp_stats = evaluate_stack(backbone, mtp, tokenizer, heldout, DEVICE, cfg["eval_max_tokens_per_doc"]) ntp_stats = evaluate_stack(backbone, ntp, tokenizer, heldout, DEVICE, cfg["eval_max_tokens_per_doc"]) eval_seconds = time.perf_counter() - eval_start d_value = mtp_stats.bpb - ntp_stats.bpb logger.info("BPB mtp=%.6f ntp=%.6f D=%.6f (relative %.4f%%)", mtp_stats.bpb, ntp_stats.bpb, d_value, 100 * d_value / ntp_stats.bpb) # checkpoints go to disk before decoding, so a decoding failure cannot cost the training run ckpt_dir = Path(cfg["checkpoint_dir"]) / f"{c}_{tag}" ckpt_dir.mkdir(parents=True, exist_ok=True) torch.save(mtp.state_dict(), ckpt_dir / "mtp.pt") torch.save(ntp.state_dict(), ckpt_dir / "ntp.pt") rows = [["condition", "metric", "value", "n"]] def add(metric: str, value, n) -> None: rows.append([c, metric, value, n]) add("seed", seed, 1) add("use_shared_trunk", int(cfg["use_shared_trunk"]), 1) add("train_tokens", metrics.tokens, 1) add("train_steps", metrics.steps, 1) add("tokens_per_second", f"{metrics.tokens_per_second:.3f}", 1) add("train_wall_seconds", f"{metrics.wall_seconds:.1f}", 1) add("train_loss_ntp_nats", f"{metrics.ntp_loss:.6f}", metrics.steps) for k, loss in enumerate(metrics.mtp_head_losses): add(f"train_loss_mtp_head{k + 1}_nats", f"{loss:.6f}", metrics.steps) add("bpb_mtp", f"{mtp_stats.bpb:.6f}", mtp_stats.n_bytes) add("bpb_ntp", f"{ntp_stats.bpb:.6f}", ntp_stats.n_bytes) add("d_bpb_mtp_minus_ntp", f"{d_value:.6f}", mtp_stats.n_bytes) add("d_relative_to_ntp", f"{d_value / ntp_stats.bpb:.6f}", mtp_stats.n_bytes) add("heldout_tokens", mtp_stats.n_tokens, 1) add("heldout_bytes", mtp_stats.n_bytes, 1) for k in range(len(mtp_stats.head_accuracy)): add(f"head{k + 1}_accuracy", f"{mtp_stats.head_accuracy[k]:.6f}", mtp_stats.n_tokens) add(f"head{k + 1}_accuracy_intraword", f"{mtp_stats.head_accuracy_intraword[k]:.6f}", mtp_stats.n_tokens) add(f"head{k + 1}_accuracy_boundary", f"{mtp_stats.head_accuracy_boundary[k]:.6f}", mtp_stats.n_tokens) add("ntp_head_accuracy", f"{ntp_stats.head_accuracy[0]:.6f}", ntp_stats.n_tokens) add("eval_seconds", f"{eval_seconds:.1f}", 1) add("peak_gpu_mib", f"{torch.cuda.max_memory_allocated(DEVICE) / 1024**2:.1f}", 1) out = Path(args.out) if args.out else Path(cfg["run_out_dir"]) / f"{c}_{tag}.csv" write_rows(out, rows) # held-out results are safe on disk before the slow decoding pass logger.info("wrote held-out rows to %s", out) opens, closes = whitespace_tables(tokenizer, backbone.config.vocab_size) spec_docs = args.spec_docs or cfg["spec_docs"] spec_start = time.perf_counter() spec = speculative_decode_verified( backbone, mtp, tokenizer, heldout[:spec_docs], DEVICE, cfg["spec_prompt_tokens"], cfg["spec_completion_tokens"], opens, closes ) spec_seconds = time.perf_counter() - spec_start logger.info( "verified decoding: %.4f tokens per verification step, boundary completion %.4f over %d spans (%.0fs)", spec.mean_accepted_per_forward, spec.boundary_completion_rate, spec.n_spans_scored, spec_seconds, ) for _, metric, value, n in acceptance_rows(c, spec): add(metric, value, n) add("spec_docs", spec_docs, 1) add("spec_seconds", f"{spec_seconds:.1f}", 1) wall = time.perf_counter() - started add("peak_gpu_mib_including_decoding", f"{torch.cuda.max_memory_allocated(DEVICE) / 1024**2:.1f}", 1) add("wall_seconds", f"{wall:.1f}", 1) write_rows(out, rows) log_dir = Path(cfg["run_log_dir"]) log_dir.mkdir(parents=True, exist_ok=True) with (log_dir / f"{c}_{tag}.json").open("w", encoding="utf-8") as f: json.dump( { "command": " ".join(sys.argv), "git_hash": git_hash(), "condition": c, "seed": seed, "wall_seconds": round(wall, 1), "tokens_processed": metrics.tokens, "tokens_per_second": round(metrics.tokens_per_second, 3), }, f, indent=2, ) logger.info("wrote %s and run log", out) def main() -> None: args = parse_args() with open(args.config, encoding="utf-8") as f: cfg = yaml.safe_load(f) if args.existing: rescore_existing(cfg, args) else: train_condition(cfg, args) if __name__ == "__main__": main()