"""GPU measurements for Phase 0. Each runs as its own process so an out-of-memory error stays contained. python -m pocket_math.bench precision --model DIR --samples samples.jsonl.gz --out out.json python -m pocket_math.bench train-mem --model DIR --lens 4096,8192,16384,32768 --out out.json """ from __future__ import annotations import argparse import gc import sys import time import torch from .io import read_jsonl, write_json from .modeling import attach_lora, eval_model, load_model, score_logprobs, set_sdpa_gqa, train_logprobs def precision(model_dir: str, samples_path: str, trust: bool, vs_generator: bool = False, max_tokens: int = 4096) -> dict: """fp16 against fp32 log-probs on real answers. T4s have no bf16, and both teachers ship in bf16.""" rows = list(read_jsonl(samples_path))[:4] seqs = [(r["prompt_ids"] + r["response_ids"])[:max_tokens] for r in rows] starts = [len(r["prompt_ids"]) for r in rows] ref = [] model = eval_model(load_model(model_dir, torch.float32, "cuda", trust)) for ids, st in zip(seqs, starts, strict=True): ref.append(score_logprobs(model, torch.tensor(ids, device="cuda"), st).cpu()) del model gc.collect() torch.cuda.empty_cache() model = eval_model(load_model(model_dir, torch.float16, "cuda", trust)) diffs, vs_sampler, nonfinite = [], [], 0 for ids, st, r, row in zip(seqs, starts, ref, rows, strict=True): lp = score_logprobs(model, torch.tensor(ids, device="cuda"), st).cpu() nonfinite += int((~torch.isfinite(lp)).sum()) diffs.append((lp - r).abs()) if vs_generator: gen = torch.tensor([float("nan") if x is None else x for x in row["sampler_logprobs"][:len(lp)]]) keep = ~torch.isnan(gen) vs_sampler.append((lp[: len(gen)][keep] - gen[keep]).abs()) d = torch.cat(diffs) if diffs else torch.zeros(1) out = {"tokens": int(d.numel()), "mean_abs": float(d.mean()), "p99_abs": float(d.quantile(0.99)), "max_abs": float(d.max()), "nonfinite": nonfinite, "ok": nonfinite == 0 and float(d.mean()) < 0.02} if vs_sampler: g = torch.cat(vs_sampler) # The trainer's fp16 log-probs against vLLM's for the same tokens: a large gap means the # generator runs a different model (for example a config field vLLM reads differently). out.update({"hf_vs_vllm_mean_abs": float(g.mean()), "hf_vs_vllm_p99_abs": float(g.quantile(0.99))}) out["ok"] = out["ok"] and float(g.mean()) < 0.05 return out def train_memory(model_dir: str, lens: list[int], rank: int) -> dict: """Peak memory of one LoRA training step per sequence length, with repeated key/value heads (what training uses) and then with PyTorch's GQA path (what smoke run 2 measured).""" model = load_model(model_dir, torch.float16, "cuda") model.gradient_checkpointing_enable(gradient_checkpointing_kwargs={"use_reentrant": False}) model.config.use_cache = False model = attach_lora(model, {"rank": rank, "alpha": 32}, None) model.train() vocab = model.get_output_embeddings().weight.shape[0] out: dict[str, dict] = {} # Repeated heads first: an out-of-memory error in the GQA runs can fragment memory for later runs. for mode, gqa in (("repeat_kv", False), ("gqa", True)): set_sdpa_gqa(gqa) out[mode] = {} for n in lens: torch.cuda.empty_cache() torch.cuda.reset_peak_memory_stats() ids = torch.randint(0, min(vocab, 151000), (n,), device="cuda") t0 = time.time() try: with torch.autocast("cuda", dtype=torch.float16): lp, _ = train_logprobs(model, ids, 256) (-lp.float().mean()).backward() torch.cuda.synchronize() out[mode][str(n)] = {"ok": True, "seconds": round(time.time() - t0, 2), "peak_gb": round(torch.cuda.max_memory_allocated() / 2 ** 30, 2)} except torch.cuda.OutOfMemoryError: out[mode][str(n)] = {"ok": False, "error": "out of memory"} lp = None model.zero_grad(set_to_none=True) gc.collect() set_sdpa_gqa(False) return out def main(argv: list[str] | None = None) -> int: p = argparse.ArgumentParser() sub = p.add_subparsers(dest="cmd", required=True) a1 = sub.add_parser("precision") a1.add_argument("--model", required=True) a1.add_argument("--samples", required=True) a1.add_argument("--trust-remote-code", action="store_true") a1.add_argument("--vs-generator", action="store_true", help="also compare with the samples' vLLM log-probs") a1.add_argument("--out", required=True) a2 = sub.add_parser("train-mem") a2.add_argument("--model", required=True) a2.add_argument("--lens", default="4096,8192,16384,32768") a2.add_argument("--rank", type=int, default=64) a2.add_argument("--out", required=True) a = p.parse_args(argv) if a.cmd == "precision": result = precision(a.model, a.samples, a.trust_remote_code, a.vs_generator) else: result = train_memory(a.model, [int(x) for x in a.lens.split(",")], a.rank) write_json(a.out, result) print(result, flush=True) return 0 if __name__ == "__main__": sys.exit(main())