"""Time a full and a four-row physical forward on the same disposable GSM8K training update.""" import gc import time import torch from novel_tokens.model import Policy from novel_tokens.policy import step from novel_tokens.runtime import RESULTS, check_postponed, event, now, open_log, save_json from novel_tokens.tasks import panel, stable from novel_tokens.training import build_optimizer def measure(problems, forward_rows): """Keep weights, real prompts, draw order and artificial calibration rewards fixed.""" check_postponed() model = Policy(818, "symbols", device="cuda") model.forward_rows = forward_rows # This disposable timing probe can stop between denoiser passes if the live usage guard fires. model.body.register_forward_pre_hook(lambda module, inputs: check_postponed()) optimizer = build_optimizer(model) rng = torch.Generator(device=model.device).manual_seed(192) torch.cuda.synchronize() torch.cuda.reset_peak_memory_stats() started = time.perf_counter() metrics, outputs = step(model, optimizer, problems, "symbols", rng, numeric=True, calibration=True) torch.cuda.synchronize() result = { "physical_rows": forward_rows or len(outputs), "seconds": time.perf_counter() - started, "peak_allocated_bytes": torch.cuda.max_memory_allocated(), "peak_reserved_bytes": torch.cuda.max_memory_reserved(), "grad_norm_before_clipping": metrics["grad_norm"], "max_replay_error": metrics["replay_error"], } event("math_memory_probe", measurement=result, outputs=outputs) actions = [(r["reveal_order"], r["trace_ids"], r["answer"]) for r in outputs] gradients = torch.cat([p.grad.detach().float().cpu().flatten() for p in model.parameters() if p.requires_grad and p.grad is not None]) return result, actions, gradients, rng.get_state() def main(): """The first slow training update defines this timing case. No held-out scores enter the decision.""" open_log("math-memory-probe") problems = panel("gsm", "train", 4, stable((17, "gsm", 6, "rl"))) full, full_actions, full_gradient, full_rng = measure(problems, None) gc.collect() torch.cuda.empty_cache() small, small_actions, small_gradient, small_rng = measure(problems, 4) relative = float((small_gradient-full_gradient).norm()/full_gradient.norm().clamp_min(1e-12)) result = { "timestamp": now(), "task": "gsm", "split": "train", "timing_case_update": 6, "full": full, "chunked": small, "identical_action_rows": sum(a == b for a,b in zip(full_actions,small_actions,strict=True)), "logical_rollouts": len(full_actions), "matching_generator_state": torch.equal(full_rng,small_rng), "relative_clipped_gradient_error": relative, } save_json(RESULTS / "math-memory-probe.json", result) event("math_memory_comparison", **result) if __name__ == "__main__": main()