#!/usr/bin/env python3 """One audited, resumable epoch of soft-label distillation; no held-out training.""" # ruff: noqa: E402, I001 # pyright: reportMissingImports=false import argparse import hashlib import json import math import random import signal import sys import time from collections import Counter from pathlib import Path ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "src")) import nb_shim import torch from huggingface_hub import hf_hub_download, snapshot_download from typed_decisions.encoder import Collator from typed_decisions.schema import Question def load_split(cfg, split, coll, limit=None): if cfg.get("local_data"): path = ROOT / cfg["local_data"] / (cfg.get("split_files", {}).get(split, split) + ".jsonl") else: path = hf_hub_download(cfg["dataset"], split + ".jsonl", repo_type="dataset", revision=cfg["dataset_revision"]) # Sample held-out rows uniformly, never use them as optimizer inputs. rng = random.Random(cfg["seed"]) rows, seen, ids = [], 0, set() try: with open(path) as f: for line in f: if not line.strip(): continue row = json.loads(line) seen += 1 if row["id"] in ids: raise ValueError(f"duplicate id in {split}: {row['id']}") ids.add(row["id"]) if limit is None or len(rows) < limit: rows.append(row) else: j = rng.randrange(seen) if j < limit: rows[j] = row except (OSError, json.JSONDecodeError) as exc: raise RuntimeError(f"cannot read {split} at row {seen}: {exc}") from exc encoded, truncated = [], 0 for row in rows: options, target = row["options"], row["target"] if (not isinstance(options, list) or not isinstance(target, list) or not 2 <= len(options) <= 255 or len(options) != len(target) or not all(isinstance(o, str) and o.strip() for o in options) or row["kind"] not in ("choice", "score", "noul") or not isinstance(row["state"], str) or not isinstance(row["question"], str) or not row["question"].strip() or not all(type(p) in (int, float) and math.isfinite(p) and 0 <= p <= 1 for p in target) or abs(sum(target)-1) > 1e-3): raise ValueError(f"invalid distillation row {row['id']}") if row["kind"] == "score" and not 2 <= len(options) <= 10: raise ValueError(f"score option count invalid: {row['id']}") allowed_noul = (["false", "true"], ["no", "yes"]) if cfg.get("local_data") else (["false", "true"],) if row["kind"] == "noul" and options not in allowed_noul: raise ValueError(f"unexpected noul order: {row['id']}") # Encoding is kind-independent; choice bypasses upstream's (no,yes) assertion. q = Question(row["id"], "choice", row["question"], options, 0) enc = coll.encode_one(row["state"], [q]) state_len = len(coll._ids(row["state"])) truncated += state_len > enc[2][0] - 2 if cfg.get("refuse_truncation"): full_len = 4 + state_len + len(coll._ids(row["question"])) + sum(1 + len(coll._ids(o)) for o in options) if state_len != enc[2][0] - 2 or len(enc[0]) != full_len: raise ValueError(f"refusing truncated record {row['id']}: state={state_len}, total={full_len}") encoded.append({"id": row["id"], "encoded": enc, "target": [p/sum(target) for p in target], "kind": row["kind"], "source": row["source"]}) print("DATA", split, {"total": seen, "selected": len(encoded), "truncated": truncated}, flush=True) return encoded, {"total": seen, "selected": len(encoded), "truncated": truncated, "useful_tokens": sum(len(r["encoded"][0]) for r in encoded), "maximum_tokens": max((len(r["encoded"][0]) for r in encoded), default=0)} def batch_plan(rows, seed, batch_size=8, token_budget=4096): rng = random.Random(seed) order = list(range(len(rows))) rng.shuffle(order) batches = [] # Shuffle globally, sort only local pools, then shuffle completed batches globally. # No source/domain grouping, no dropped tail, no replacement sampling. for start in range(0, len(order), 2048): pool = sorted(order[start:start+2048], key=lambda i: len(rows[i]["encoded"][0])) chunk = [] for i in pool: length = math.ceil(len(rows[i]["encoded"][0])/128)*128 if chunk and (len(chunk) >= batch_size or (len(chunk)+1)*length > token_budget): batches.append(chunk) chunk = [] chunk.append(i) if chunk: batches.append(chunk) rng.shuffle(batches) flat = [i for b in batches for i in b] assert len(flat) == len(rows) and len(set(flat)) == len(rows), "epoch coverage failed" return batches def make_batch(rows, indices, pad, device="cuda"): selected = [rows[i] for i in indices] length = math.ceil(max(len(r["encoded"][0]) for r in selected)/128)*128 om = max(len(r["target"]) for r in selected) b = len(selected) ids = torch.full((b, length), pad, dtype=torch.long) attn = torch.zeros_like(ids) pos = torch.full((b, 1, om), -1, dtype=torch.long) qp = torch.zeros((b, 1), dtype=torch.long) seg = torch.full_like(ids, om+1) target = torch.zeros((b, 1, om)) for j, row in enumerate(selected): toks, positions, questions, spans = row["encoded"] ids[j, :len(toks)] = torch.tensor(toks) attn[j, :len(toks)] = 1 pos[j, 0, :len(positions[0])] = torch.tensor(positions[0]) qp[j, 0] = questions[0] for sid, st, en in spans: seg[j, st:en] = om if sid < 0 else sid target[j, 0, :len(row["target"])] = torch.tensor(row["target"]) return tuple(t.to(device) for t in (ids, attn, pos, pos >= 0, qp, seg)), target.to(device) def soft_loss(logits, target, opt_mask): if not torch.isfinite(logits[opt_mask]).all(): raise RuntimeError("nonfinite logits on a real option") # Only padding is masked; nonfinite real-option logits must never be hidden. logp = logits.float().masked_fill(~opt_mask, float("-inf")).log_softmax(-1) ce = -(target * logp.masked_fill(~opt_mask, 0)).sum(-1).mean() brier = (logp.exp()-target).square().sum(-1).mean() return ce + brier @torch.no_grad() def evaluate(model, rows, pad, temperature=1.): model.eval() total, records = 0., [] for start in range(0, len(rows), 4): indices = list(range(start, min(start+4, len(rows)))) args, target = make_batch(rows, indices, pad) with torch.autocast("cuda", dtype=torch.bfloat16): logits = model(*args).float()/temperature loss = soft_loss(logits, target, args[3]) if not torch.isfinite(loss): raise RuntimeError("nonfinite validation loss") total += loss.item()*len(indices) for j, i in enumerate(indices): n = len(rows[i]["target"]) records.append((logits[j,0,:n].cpu(), target[j,0,:n].cpu())) return total/len(rows), records def atomic_save(value, path): tmp = path.with_suffix(path.suffix + ".tmp") torch.save(value, tmp) tmp.replace(path) def save_evaluation(path, rows, loss, records): values = [{"id": row["id"], "kind": row["kind"], "source": row["source"], "target": target.tolist(), "probabilities": logits.softmax(-1).tolist()} for row, (logits, target) in zip(rows, records, strict=True)] temporary = path.with_suffix(".json.tmp") temporary.write_text(json.dumps({"ce_plus_brier": loss, "records": values}, indent=2, allow_nan=False)+"\n") temporary.replace(path) def require_precision_loader(precision, custom_precision=None): if (precision not in {"bf16", "fp8", "mixed", "nvfp4_tetrajet_v2"} or (precision not in {"bf16", "fp8"} and precision != custom_precision)): raise ValueError("custom precision requires its matching probe loader; refusing BF16 fallback") def main(*, custom_precision=None): ap = argparse.ArgumentParser() ap.add_argument("--config", default="configs/jev-v3-epoch1.json") ap.add_argument("--probe", action="store_true") ap.add_argument("--resume", action="store_true") ap.add_argument("--checkpoint-ack", action="store_true", help="pause each save until local backup is acknowledged") a = ap.parse_args() try: cfg = json.loads(Path(a.config).read_text()) except (OSError, json.JSONDecodeError) as exc: ap.error(f"cannot read config {a.config}: {exc}") require_precision_loader(cfg["precision"], custom_precision) if cfg["epochs"] != 1: raise ValueError("this job is authorized for exactly one epoch") if not a.probe: try: split_audit = json.loads((ROOT / cfg.get("split_audit", "evidence/jev-v3-split-audit.json")).read_text()) except (OSError, json.JSONDecodeError) as exc: raise RuntimeError(f"full held-out audit is required: {exc}") from exc if not split_audit.get("passed") or split_audit.get("revision") != cfg["dataset_revision"]: raise RuntimeError("held-out audit failed or revision differs") if cfg.get("local_data"): for entry in split_audit["files"].values(): with (ROOT / entry["path"]).open("rb") as stream: if hashlib.file_digest(stream, "sha256").hexdigest() != entry["sha256"]: raise RuntimeError("audited data changed: " + entry["path"]) start = time.monotonic() stop = [False] for sig in (signal.SIGTERM, signal.SIGINT): signal.signal(sig, lambda *_: stop.__setitem__(0, True)) torch.manual_seed(cfg["seed"]) random.seed(cfg["seed"]) torch.set_float32_matmul_precision("high") torch.set_num_threads(8) out = ROOT / (cfg["out"] + ("-probe" if a.probe else "")) out.mkdir(parents=True, exist_ok=True) cfg_path = out / "config.json" if not a.resume and (out / "latest.pt").exists(): raise RuntimeError("checkpoint exists; use --resume, do not overwrite") saved = torch.load(out / "latest.pt", map_location="cpu", weights_only=False) if a.resume else None if saved is not None and saved["config"] != cfg: raise RuntimeError("resume config differs; original artifacts preserved") model_path = snapshot_download(cfg["model"], revision=cfg["model_revision"], allow_patterns=["*.json", "*.py", "*.safetensors", "*.model", "tokenizer*"]) tok = nb_shim.nanbeige_tokenizer(model_path) coll = Collator(tok, max_state_tokens=cfg["max_state"], max_len=cfg["max_len"]) train, data_stats = load_split(cfg, "train", coll, 2048 if a.probe else None) val, _ = load_split(cfg, "validation", coll, cfg["validation_rows"]) assert not ({r["id"] for r in train} & {r["id"] for r in val}), "validation id leakage" if not a.probe and len(train) != cfg.get("expected_train_rows", 655806): raise RuntimeError(f"unexpected train count: {len(train)}") batches = batch_plan(train, cfg["seed"], cfg["batch"], cfg["max_padded_tokens"]) flat_ids = [train[i]["id"] for b in batches for i in b] audit = {"seed": cfg["seed"], "rows": len(train), "batches": len(batches), "unique_rows": len(set(flat_ids)), "first20_ids": flat_ids[:20], "order_sha256": hashlib.sha256("\n".join(flat_ids).encode()).hexdigest(), "sources": dict(Counter(r["source"] for r in train)), "data": data_stats, "algorithm": "seeded full permutation; length sort inside shuffled pools of 2048; shuffle batch order; no drop_last"} if saved is not None and saved["order_sha256"] != audit["order_sha256"]: raise RuntimeError("resume order differs; original artifacts preserved") cfg_path.write_text(json.dumps(cfg, indent=2)+"\n") (out / "shuffle-audit.json").write_text(json.dumps(audit, indent=2)+"\n") del flat_ids if stop[0]: return model = nb_shim.load_decision_encoder(model_path, tok, lora=cfg["lora"], gradient_checkpointing=True).cuda() if cfg["precision"] == "fp8": from torchao.float8 import Float8LinearConfig, convert_to_float8_training def select(mod, name): return isinstance(mod, torch.nn.Linear) and "base_layer" in name and min(mod.weight.shape) >= 256 and all(d%16 == 0 for d in mod.weight.shape) convert_to_float8_training(model.backbone, config=Float8LinearConfig(pad_inner_dim=True), module_filter_fn=select) if "depth" in cfg: model.backbone.get_base_model().config.num_loops = cfg["depth"] params = {n:p for n,p in model.named_parameters() if p.requires_grad} if saved is not None: initial_weights = saved["trainable"] elif cfg.get("parent_checkpoint"): path = ROOT / cfg["parent_checkpoint"] with path.open("rb") as stream: if hashlib.file_digest(stream, "sha256").hexdigest() != cfg["parent_payload_sha256"]: raise RuntimeError("parent checkpoint hash mismatch") parent = torch.load(path, map_location="cpu", weights_only=True, mmap=True) if parent["source_checkpoint_sha256"] != cfg["parent_source_sha256"]: raise RuntimeError("parent source checkpoint differs") initial_weights = parent["trainable"] else: initial_weights = None if initial_weights is not None: if set(initial_weights) != set(params): raise RuntimeError("checkpoint trainable parameter names differ") with torch.no_grad(): for n,p in params.items(): if p.shape != initial_weights[n].shape or not torch.isfinite(initial_weights[n]).all(): raise RuntimeError("invalid checkpoint parameter: " + n) p.copy_(initial_weights[n]) del initial_weights opt = torch.optim.AdamW([ {"params": [p for n,p in params.items() if not n.startswith("head.")], "lr": cfg["lr"]}, {"params": list(model.head.parameters()), "lr": cfg["head_lr"]}], fused=True, weight_decay=.01) steps = min(128, len(batches)) if a.probe else len(batches) warm = max(1, int(steps*cfg["warmup"])) sched = torch.optim.lr_scheduler.LambdaLR(opt, lambda s: min(1., (s+1)/warm)*max(0., (steps-s)/max(1,steps-warm))) if saved is not None: initial_val = saved["initial_val"] else: initial_val, initial_records = evaluate(model, val, tok.pad_token_id) if cfg.get("save_evaluation_records"): save_evaluation(out/"parent-validation.json", val, initial_val, initial_records) del initial_records extra_rows = {name: load_split(cfg, name, coll, cfg.get("final_panel_rows", 128))[0] for name in cfg.get("extra_eval_splits", [])} initial_extra = saved.get("initial_extra", {}) if saved is not None else {} if saved is None: for name, rows in extra_rows.items(): score, records = evaluate(model, rows, tok.pad_token_id) initial_extra[name] = score if cfg.get("save_evaluation_records"): save_evaluation(out/("parent-"+name+".json"), rows, score, records) # Nanbeige checkpointing fails Dynamo dynamic tracing; fixed shapes passed the GPU benchmark. active = torch.compile(model, dynamic=False, fullgraph=False) if cfg["compile"] else model cursor, curve, tokens = 0, [], 0 if saved is not None: opt.load_state_dict(saved["optimizer"]) sched.load_state_dict(saved["scheduler"]) cursor, curve, tokens = saved["cursor"], saved["curve"], saved["tokens"] torch.set_rng_state(saved["rng"]) torch.cuda.set_rng_state_all(saved["cuda_rng"]) initial_val = saved.get("initial_val", initial_val) del saved checkpoint_s = 0. def save(status): nonlocal checkpoint_s checkpoint_start = time.monotonic() atomic_save({"config": cfg, "trainable": {n:p.detach().cpu() for n,p in params.items()}, "optimizer": opt.state_dict(), "scheduler": sched.state_dict(), "cursor": cursor, "curve": curve, "tokens": tokens, "initial_val": initial_val, "initial_extra": initial_extra, "order_sha256": audit["order_sha256"], "rng": torch.get_rng_state(), "cuda_rng": torch.cuda.get_rng_state_all(), "status": status}, out / "latest.pt") print("CHECKPOINT", status, cursor, flush=True) if a.checkpoint_ack: with (out / "latest.pt").open("rb") as f: digest = hashlib.file_digest(f, "sha256").hexdigest() event = {"run": out.name, "step": cursor, "sha256": digest} print("CHECKPOINT_SYNC " + json.dumps(event), flush=True) ack = sys.stdin.readline().strip() if ack != f"ACK {cursor} {digest}": raise RuntimeError("checkpoint not backed up locally; stopping at committed boundary") checkpoint_s += time.monotonic()-checkpoint_start if not a.resume: save("ready") last_save = time.monotonic() training_start = last_save session_start_tokens = tokens session_start_cursor = cursor initial_checkpoint_s = checkpoint_s try: while cursor < steps and not stop[0] and (cfg["max_hours"] is None or time.monotonic()-start < cfg["max_hours"]*3600): model.train() args, target = make_batch(train, batches[cursor], tok.pad_token_id) opt.zero_grad(set_to_none=True) with torch.autocast("cuda", dtype=torch.bfloat16): logits = active(*args) loss = soft_loss(logits, target, args[3]) if not torch.isfinite(loss): raise RuntimeError(f"nonfinite loss at {cursor}") loss.backward() norm = torch.nn.utils.clip_grad_norm_(list(params.values()), 1.) if not torch.isfinite(norm): raise RuntimeError(f"nonfinite gradients at {cursor}") opt.step() sched.step() tokens += int(args[1].sum()) curve.append(float(loss.detach())) cursor += 1 if cursor % 25 == 0 or cursor == 1: print("TRAIN", json.dumps({"step": cursor, "steps": steps, "loss": curve[-1], "mean_last25": sum(curve[-25:])/len(curve[-25:]), "tokens_s": (tokens-session_start_tokens)/(time.monotonic()-training_start), "elapsed_s": time.monotonic()-start, "fraction_complete": cursor/steps, "remaining_s_estimate": (time.monotonic()-training_start)*(steps-cursor)/max(1,cursor-session_start_cursor)}), flush=True) if time.monotonic()-last_save >= cfg["checkpoint_seconds"]: save("training") last_save = time.monotonic() train_loop_s = time.monotonic()-training_start train_compute_s = train_loop_s-(checkpoint_s-initial_checkpoint_s) save("trained" if cursor == steps else "budget_or_signal_stop") final_val = None final_extra = {} if cursor == steps: final_val, records = evaluate(model, val, tok.pad_token_id) if cfg.get("save_evaluation_records"): save_evaluation(out/"final-validation.json", val, final_val, records) for name, rows in extra_rows.items(): score, records = evaluate(model, rows, tok.pad_token_id) final_extra[name] = score if cfg.get("save_evaluation_records"): save_evaluation(out/("final-"+name+".json"), rows, score, records) report = {"steps": cursor, "total_steps": steps, "completed": cursor == steps, "probe": a.probe, "initial_val": initial_val, "final_val": final_val, "initial_extra": initial_extra, "final_extra": final_extra, "examples_seen": sum(len(b) for b in batches[:cursor]), "expected_train_rows": len(train), "tokens": tokens, "elapsed_s": time.monotonic()-start, "peak_gib": torch.cuda.max_memory_allocated()/2**30, "train_loop_s": train_loop_s, "train_compute_s": train_compute_s, "training_tokens_s": (tokens-session_start_tokens)/max(train_compute_s, 1e-9), "checkpoint_s": checkpoint_s, "mean_first25": sum(curve[:25])/max(1,len(curve[:25])), "mean_last25": sum(curve[-25:])/max(1,len(curve[-25:]))} (out / "report.json").write_text(json.dumps(report, indent=2)+"\n") print("REPORT", report, flush=True) if a.probe and (cursor != steps or final_val is None or final_val >= initial_val): raise RuntimeError("probe did not complete with improved held-out soft-label loss") tok.save_pretrained(out / "tokenizer") except BaseException: # Unexpected optimizer failures may leave partial mutations: preserve the last # atomic checkpoint from a committed batch boundary, never snapshot this state. print("ERROR: preserving last committed checkpoint", flush=True) raise if __name__ == "__main__": main()