solver-precision-protocol · 905fe44c7715
Browse filesFiles changed (12)
124 unmodified lines125126127128129130124 unmodified lines}}function showOnline() {const online=study?.online_solvers, block=byId("online-section");block.hidden=!online?.arms;if (block.hidden) return;124 unmodified lines125126127128129130131132133134135124 unmodified lines}}function showOnline() {const fits=study?.solver_fit ?? [], bodyFit=byId("solver-fit-rows");byId("solver-fit-section").hidden=!fits.length;bodyFit.replaceChildren();for (const f of fits) row(bodyFit,[f.model,f.precision.toUpperCase(),f.status,f.n ? f.parsed+"/"+f.n : "—",f.n ? f.correct+"/"+f.n : "—",f.after_step ? Math.round(f.after_step.solver_peak_mib)+" MiB" : "—"]);const online=study?.online_solvers, block=byId("online-section");block.hidden=!online?.arms;if (block.hidden) return;
11 unmodified lines121314151611 unmodified lines<section><h2>Trace explorer</h2><div class="controls"><label>Run <select id="run"></select></label><label>Solution <select id="out"><option value="all">All examples</option><option value="0">Incorrect</option><option value="1">Correct</option></select></label></div><div id="examples" aria-live="polite"></div></section><section><h2>Review evidence</h2><p id="pair"></p><div id="evidence"></div><div class="scroll"><table><caption>Verdicts on the same natural traces</caption><thead><tr><th>Split</th><th>Rule</th><th>Agreement</th><th>False accepts / invalid</th><th>False rejects / valid</th><th>Malformed / reports</th></tr></thead><tbody id="replay"></tbody></table></div></section><section><h2>Training metrics</h2><p id="training"></p><canvas id="trend" width="1000" height="245" role="img" aria-label="Assigned rewards and exact rollout accuracy across optimizer updates"></canvas><p id="probe"></p><div class="scroll"><table><caption>Most recent complete rollout groups</caption><thead><tr><th>Update</th><th>Assigned reward</th><th>Exact accuracy</th></tr></thead><tbody id="curve"></tbody></table></div></section><footer>Libor “Burny” Burian · <a href="https://huggingface.co/collections/BurnyCoder/recursive-llm-judges-for-grpo-6b081abfdc1b0975ad60b14a">Models and data</a></footer></main><script src="explorer.js" defer></script></body></html>11 unmodified lines12131415161711 unmodified lines<section><h2>Trace explorer</h2><div class="controls"><label>Run <select id="run"></select></label><label>Solution <select id="out"><option value="all">All examples</option><option value="0">Incorrect</option><option value="1">Correct</option></select></label></div><div id="examples" aria-live="polite"></div></section><section><h2>Review evidence</h2><p id="pair"></p><div id="evidence"></div><div class="scroll"><table><caption>Verdicts on the same natural traces</caption><thead><tr><th>Split</th><th>Rule</th><th>Agreement</th><th>False accepts / invalid</th><th>False rejects / valid</th><th>Malformed / reports</th></tr></thead><tbody id="replay"></tbody></table></div></section><section><h2>Training metrics</h2><p id="training"></p><canvas id="trend" width="1000" height="245" role="img" aria-label="Assigned rewards and exact rollout accuracy across optimizer updates"></canvas><p id="probe"></p><div class="scroll"><table><caption>Most recent complete rollout groups</caption><thead><tr><th>Update</th><th>Assigned reward</th><th>Exact accuracy</th></tr></thead><tbody id="curve"></tbody></table></div></section><section id="solver-fit-section" hidden><h2>Solver precision on the 8 GB GPU</h2><p>Each trial measures a real update alongside the frozen 4B judge. The starting scores use the same train-split problems before that update.</p><div class="scroll"><table><thead><tr><th>Solver</th><th>Precision</th><th>Hardware result</th><th>Parsed</th><th>Exact</th><th>Peak solver allocation</th></tr></thead><tbody id="solver-fit-rows"></tbody></table></div></section><footer>Libor “Burny” Burian · <a href="https://huggingface.co/collections/BurnyCoder/recursive-llm-judges-for-grpo-6b081abfdc1b0975ad60b14a">Models and data</a></footer></main><script src="explorer.js" defer></script></body></html>
63 unmodified lines64656667686963 unmodified lines### Train the original solver with the confirmed frozen judgesRun `uv run --extra gpu study online-solvers` in the default study track. This command verifies the confirmed model configuration, trains `new-judges/winner-d2` and `new-judges/winner-d3` in sequence and evaluates both resulting adapters. Run the same command after an interruption. To run one phase, use `study train --run new-judges/winner-d2` or `study evaluate --run new-judges/winner-d2` (substitute `winner-d3` for the other arm). Use `study dashboard` for live updates and `uv run study report` to regenerate the paper and comparisons. The public campaign adds `--publish` to release each training and development milestone. The experiment requires the CUDA llama.cpp runtime described above, the frozen confirmation receipts, calibrated profile and archived starting-solver traces. [Online solver protocol](../reports/newer-frozen-judges.md#online-solver-comparison)On Windows the device sampler records the llama.cpp process's dedicated and shared allocations and cumulative GPU engine running time. Each recorded native graph assignment is checked against CUDA0 when releasing the results. The Hugging Face dataset contains compressed server and prompt logs. These counters and the separate prompt-processing and decoding durations measure different parts of execution. [Windows GPU accounting](https://devblogs.microsoft.com/directx/gpus-in-the-task-manager/) · [Raw public archive](https://huggingface.co/datasets/BurnyCoder/recursive-judge-grpo-study)63 unmodified lines646566676869707163 unmodified lines### Train the original solver with the confirmed frozen judgesFor the separate hardware and starting-accuracy experiment run `uv run --extra gpu study solver-fit` on the idle study GPU. The optional `--candidate` runs one registered hardware configuration. [Precision and base-model protocol](../reports/solver-precision.md)Run `uv run --extra gpu study online-solvers` in the default study track. This command verifies the confirmed model configuration, trains `new-judges/winner-d2` and `new-judges/winner-d3` in sequence and evaluates both resulting adapters. Run the same command after an interruption. To run one phase, use `study train --run new-judges/winner-d2` or `study evaluate --run new-judges/winner-d2` (substitute `winner-d3` for the other arm). Use `study dashboard` for live updates and `uv run study report` to regenerate the paper and comparisons. The public campaign adds `--publish` to release each training and development milestone. The experiment requires the CUDA llama.cpp runtime described above, the frozen confirmation receipts, calibrated profile and archived starting-solver traces. [Online solver protocol](../reports/newer-frozen-judges.md#online-solver-comparison)On Windows the device sampler records the llama.cpp process's dedicated and shared allocations and cumulative GPU engine running time. Each recorded native graph assignment is checked against CUDA0 when releasing the results. The Hugging Face dataset contains compressed server and prompt logs. These counters and the separate prompt-processing and decoding durations measure different parts of execution. [Windows GPU accounting](https://devblogs.microsoft.com/directx/gpus-in-the-task-manager/) · [Raw public archive](https://huggingface.co/datasets/BurnyCoder/recursive-judge-grpo-study)
4 unmodified lines5674 unmodified linesTry the original Qwen2.5-1.5B-Instruct at its native BF16 precision with the confirmed frozen Qwen3.5-4B judge resident on the same 8 GB GPU. If BF16 cannot run a full update, try 8-bit. A second candidate is Qwen3.5-2B-Base at NF4. Qwen identifies that file as pretraining-only. The original Instruct model has undergone post-training. Its model card and the family report do not establish that it is free of prior RLVR. Changing its storage precision does not change its training history. [Original solver](https://huggingface.co/Qwen/Qwen2.5-1.5B-Instruct) · [Qwen2.5 training report](https://arxiv.org/html/2412.15115v1#S4) · [Pinned pretraining-only candidate](https://huggingface.co/Qwen/Qwen3.5-2B-Base/tree/b1485b2fa6dfa1287294f269f5fb618e03d52d7c)Use the train split for the feasibility probe and the published model files. Check CUDA placement, four real solver samples, the frozen judges' replies, a GRPO optimizer step, wall time and peak device memory. Record fit failures as hardware observations. A candidate may fit but give malformed answers or a constant reward group. One update supplies no estimate of learned accuracy. Keep the two registered solver arms on a common original NF4 initialization. A future precision or backbone comparison would need its own matched training arms.4 unmodified lines5678910114 unmodified linesTry the original Qwen2.5-1.5B-Instruct at its native BF16 precision with the confirmed frozen Qwen3.5-4B judge resident on the same 8 GB GPU. If BF16 cannot run a full update, try 8-bit. A second candidate is Qwen3.5-2B-Base at NF4. Qwen identifies that file as pretraining-only. The original Instruct model has undergone post-training. Its model card and the family report do not establish that it is free of prior RLVR. Changing its storage precision does not change its training history. [Original solver](https://huggingface.co/Qwen/Qwen2.5-1.5B-Instruct) · [Qwen2.5 training report](https://arxiv.org/html/2412.15115v1#S4) · [Pinned pretraining-only candidate](https://huggingface.co/Qwen/Qwen3.5-2B-Base/tree/b1485b2fa6dfa1287294f269f5fb618e03d52d7c)Use the train split for the feasibility probe and the published model files. Check CUDA placement, four real solver samples, the frozen judges' replies, a GRPO optimizer step, wall time and peak device memory. Record fit failures as hardware observations. A candidate may fit but give malformed answers or a constant reward group. One update supplies no estimate of learned accuracy. Keep the two registered solver arms on a common original NF4 initialization. A future precision or backbone comparison would need its own matched training arms.Run the original NF4 model as a hardware reference. Before any disposable update, score 16 greedy traces from positions 256–271 of the calibrated train stream with each configuration. Use the same demonstrated user messages, each model's native chat template and the exact complete-trace checker. The 2B candidate loads its pretrained text weights for this arithmetic-only task. Check for missing language weights. The program records the two processes' dedicated allocations and the solver's peak PyTorch allocation. Reproduce with `uv run --extra gpu study solver-fit`. [Transformers Qwen3.5 text model](https://huggingface.co/docs/transformers/model_doc/qwen3_5)The Qwen2.5 family report describes answer matching and execution feedback in preparing DPO preference pairs, and a learned reward model for its online GRPO phase. This gives a concrete reason to prefer the explicitly pretraining-only release when prior reward training is itself the scientific question. [Qwen2.5 offline and online post-training](https://arxiv.org/html/2412.15115v1#S4.SS2)
7 unmodified lines89101112131433 unmodified lines484950515253545556575859606162636465666768699 unmodified lines7980818283848529 unmodified lines1151161171181191201211227 unmodified linesimport torchfrom huggingface_hub import try_to_load_from_cachefrom peft import LoraConfig, PeftModel, get_peft_model, prepare_model_for_kbit_trainingfrom transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfigfrom .design import BASE, REVISIONfrom .prompts import messages33 unmodified linesclass Backend:def __init__(self, journal, initial=None, frozen=(), seed=17):if not torch.cuda.is_available():raise RuntimeError("The registered GPU profile requires a CUDA device")torch.manual_seed(seed)self.journal, self.label = journal, "solver"# A complete immutable snapshot can be opened locally without repository discovery requests.required=("config.json","generation_config.json","model.safetensors","tokenizer.json","tokenizer_config.json")cached=all(isinstance(try_to_load_from_cache(BASE,filename,revision=REVISION),str) for filename in required)self.tokenizer = AutoTokenizer.from_pretrained(BASE, revision=REVISION, padding_side="left",local_files_only=cached)self.tokenizer.padding_side = "left"quant = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_quant_type="nf4", bnb_4bit_use_double_quant=True,bnb_4bit_compute_dtype=torch.bfloat16)base = AutoModelForCausalLM.from_pretrained(BASE, revision=REVISION, quantization_config=quant,dtype=torch.bfloat16, device_map={"": 0}, attn_implementation="sdpa",local_files_only=cached)base = prepare_model_for_kbit_training(base, use_gradient_checkpointing=False)if initial:self.model = PeftModel.from_pretrained(base, adapter(initial), is_trainable=True)else:9 unmodified linesself.totals = {}self._instrument()journal.event("hardware", device=torch.cuda.get_device_name(), capability=torch.cuda.get_device_capability(),torch=torch.__version__, base=BASE, revision=REVISION, pid=os.getpid())def _instrument(self):"""Record both TRL policy sampling and our explicit judge calls through generate()."""29 unmodified linesself.model.generate = generatedef prompt(self, role, problem, trace="", history=()):return self.tokenizer.apply_chat_template(messages(role, problem, trace, history,style=getattr(self,"prompt_style","registered")), tokenize=False,add_generation_prompt=True)@contextlib.contextmanagerdef inference(self, snapshot, label, seed):7 unmodified lines89101112131433 unmodified lines484950515253545556575859606162636465666768697071727374757677787980818283848586879 unmodified lines97989910010110210329 unmodified lines1331341351361371381391401417 unmodified linesimport torchfrom huggingface_hub import try_to_load_from_cachefrom peft import LoraConfig, PeftModel, get_peft_model, prepare_model_for_kbit_trainingfrom transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfigfrom .design import BASE, REVISIONfrom .prompts import messages33 unmodified linesclass Backend:def __init__(self, journal, initial=None, frozen=(), seed=17, *, model_id=BASE, revision=REVISION, precision="nf4", text_only=False):if not torch.cuda.is_available():raise RuntimeError("The registered GPU profile requires a CUDA device")torch.manual_seed(seed)self.journal, self.label = journal, "solver"# A complete immutable snapshot can be opened locally without repository discovery requests.weight_index = "model.safetensors.index.json" if text_only else "model.safetensors"required=("config.json",weight_index,"tokenizer.json","tokenizer_config.json")cached=all(isinstance(try_to_load_from_cache(model_id,filename,revision=revision),str) for filename in required)self.tokenizer = AutoTokenizer.from_pretrained(model_id, revision=revision, padding_side="left",local_files_only=cached)self.tokenizer.padding_side = "left"options = dict(dtype=torch.bfloat16, device_map={"":0}, attn_implementation="sdpa",local_files_only=cached)if precision == "nf4":options["quantization_config"] = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_quant_type="nf4",bnb_4bit_use_double_quant=True, bnb_4bit_compute_dtype=torch.bfloat16)elif precision == "int8":options["quantization_config"] = BitsAndBytesConfig(load_in_8bit=True)elif precision != "bf16":raise ValueError(f"Unknown solver precision {precision}")self.text_only = text_onlyif text_only:# Transformers maps the VLM checkpoint's language_model prefix to the text-only model.# https://huggingface.co/docs/transformers/model_doc/qwen3_5options["config"] = AutoConfig.from_pretrained(model_id, revision=revision, local_files_only=cached).get_text_config()options["output_loading_info"] = Trueloaded = AutoModelForCausalLM.from_pretrained(model_id, revision=revision, **options)if text_only:base, info = loadedif info["missing_keys"] or info["mismatched_keys"] or info["error_msgs"]:raise ValueError(f"Incomplete pretrained language weights: {info}")else:base = loadedif precision != "bf16":base = prepare_model_for_kbit_training(base, use_gradient_checkpointing=False)if initial:self.model = PeftModel.from_pretrained(base, adapter(initial), is_trainable=True)else:9 unmodified linesself.totals = {}self._instrument()journal.event("hardware", device=torch.cuda.get_device_name(), capability=torch.cuda.get_device_capability(),torch=torch.__version__, base=model_id, revision=revision, precision=precision, pid=os.getpid())def _instrument(self):"""Record both TRL policy sampling and our explicit judge calls through generate()."""29 unmodified linesself.model.generate = generatedef prompt(self, role, problem, trace="", history=()):kwargs = {"enable_thinking":False} if getattr(self,"text_only",False) else {}return self.tokenizer.apply_chat_template(messages(role, problem, trace, history,style=getattr(self,"prompt_style","registered")), tokenize=False,add_generation_prompt=True, **kwargs)@contextlib.contextmanagerdef inference(self, snapshot, label, seed):
191 unmodified lines19219319419519619715 unmodified lines213214215216217218219191 unmodified linesfrozen.add_argument("--publish",action="store_true")online=actions.add_parser("online-solvers",help="Train fresh solvers with the independently confirmed frozen J2 and J3")online.add_argument("--publish",action="store_true")schedule.add_argument("--registered-only", action="store_true",help="Reproduce the original signed-arithmetic matrix independently")names=[*(r.name for r in matrix({})),*MATCHED_NAMES,*ONLINE_NAMES]15 unmodified linespub.add_argument("--milestone",required=True)pub.add_argument("--run")args=parser.parse_args()if args.action == "online-solvers":from .online_solvers import campaign as online_campaignonline_campaign(args.publish)elif args.action in ("train","evaluate") and args.run in ONLINE_NAMES:191 unmodified lines19219319419519619719819920020115 unmodified lines217218219220221222223224225226227228229230231232191 unmodified linesfrozen.add_argument("--publish",action="store_true")online=actions.add_parser("online-solvers",help="Train fresh solvers with the independently confirmed frozen J2 and J3")online.add_argument("--publish",action="store_true")from .solver_fit import CANDIDATESfit=actions.add_parser("solver-fit",help="Measure less-quantized and pretraining-only solvers on the study GPU")fit.add_argument("--candidate",choices=CANDIDATES)fit.add_argument("--publish",action="store_true")schedule.add_argument("--registered-only", action="store_true",help="Reproduce the original signed-arithmetic matrix independently")names=[*(r.name for r in matrix({})),*MATCHED_NAMES,*ONLINE_NAMES]15 unmodified linespub.add_argument("--milestone",required=True)pub.add_argument("--run")args=parser.parse_args()if args.action == "solver-fit":from .solver_fit import fit_candidates,probeif TRACK!="original":parser.error("Use the original results root for hardware probes")if args.candidate:with study_lock("fit-"+args.candidate):print(json.dumps(probe(args.candidate)),flush=True)else:fit_candidates(args.publish)elif args.action == "online-solvers":from .online_solvers import campaign as online_campaignonline_campaign(args.publish)elif args.action in ("train","evaluate") and args.run in ONLINE_NAMES:
194 unmodified lines195196197198199200194 unmodified linesdescription += " · "+receipt["model"]add("Newer frozen Qwen judges", "new-judges/"+key, description, state, receipt.get("result","Pending"),evidence="new-judges/"+key if folder.is_dir() else None)return ledger194 unmodified lines195196197198199200201202203204205206207208209210211212213194 unmodified linesdescription += " · "+receipt["model"]add("Newer frozen Qwen judges", "new-judges/"+key, description, state, receipt.get("result","Pending"),evidence="new-judges/"+key if folder.is_dir() else None)if (root/"new-judges/online-plan.json").is_file():from .solver_fit import CANDIDATESbf16 = read_json(root/"solver-fit/original-bf16/result.json", {})for key,(model,_,precision) in CANDIDATES.items():path = "solver-fit/"+keyreceipt = read_json(root/path/"result.json",{})status = "Scheduled"if key=="original-int8":status = "Conditional on BF16 fit failure" if not bf16 else "Scheduled" if bf16["status"]=="GPU fit unavailable" else "BF16 fit; fallback unnecessary"n = receipt.get("n")add("Solver hardware and train-split calibration",path,f"{model}, {precision.upper()}, disposable GRPO update",receipt.get("status",status), f"{receipt['correct']}/{n} exact before the update" if n else receipt.get("reason","Pending"),evidence=path if (root/path).exists() else None)return ledger
35 unmodified lines36373839404142434445464729 unmodified lines7778798081828 unmodified lines9192939495969763 unmodified lines16116216316416516616719 unmodified lines18718818935 unmodified linescomplete = [g for g in clusters if len(g)==4]samples = [r for g in complete for r in g]changes = [r for r in samples if len(r["reports"])==3 and terminal(r["reports"][1],2)!=r["reward"]]curves = [dict(step=g[0]["step"]+1, reward=mean(r["reward"] for r in g), exact=mean(r["label"] for r in g)) for g in complete]return dict(groups=len(complete), samples=len(samples), reward=sum(r["reward"] for r in samples),exact=sum(r["label"] for r in samples), false_accept=sum(r["reward"]>r["label"] for r in samples),false_reject=sum(r["reward"]<r["label"] for r in samples),mixed=sum(len({r["reward"] for r in g})>1 for g in complete), curves=curves,j3_fixed=sum(r["label"]==r["reward"] for r in changes), j3_harmed=sum(r["label"]!=r["reward"] for r in changes))def arm_progress(folder, target):29 unmodified lines"""Independently match every effective reward to its actual prompt chain and exact arithmetic label."""spec = read_json(folder/"recipe.json")receipt = read_json(folder/"trained.json")if (spec["initial_adapter_sha256"] != identity or receipt["initial_adapter_sha256"] != identityor receipt["updates"] != updates or spec["run"]["initial"] is not None):raise ValueError("Solver initialization or completed update count differs")8 unmodified linesraise ValueError(f"Training reward or split mismatch at {row['step']}/{row['sample']}")for level, output in enumerate(reports,1):call = calls[f"{row['step']}/{row['sample']}/j{level}"]if call["text"] != output or call["messages"] != messages(f"j{level}",p,trace,reports[:level-1],"demonstrated"):raise ValueError("Training rollout does not match the recorded frozen-judge call")return [r["answer"] for r in effective[:4]]63 unmodified linesf"relative to the two-judge solver (paired 95% interval {100*lo:+.1f} to {100*hi:+.1f}). "f"It gained {effect['fixed']} solutions and lost {effect['harmed']} on the {effect['n']} shared problems. "f"During three-judge training, Judge 3 fixed {signal['j3_fixed']} solution verdicts and introduced "f"{signal['j3_harmed']} errors across {signal['samples']:,} sampled answers. ""The interval conditions on these seed-17 checkpoints and the development population.")19 unmodified lineslink = f"[Raw solver and judge outputs]({GITHUB}/tree/main/results/{name})"atomic(target/"experiment.md", f"# Fresh solver with frozen Judge {arm['depth']}\n\n"+online_text(study)+note+" "+link+"\n")atomic(target/"learnings.md", f"# Training signal from frozen Judge {arm['depth']}\n\n"+note+" "+link+"\n")35 unmodified lines3637383940414243444546474849505152535429 unmodified lines8485868788899091928 unmodified lines10110210310410510610710863 unmodified lines17217317417517617717817919 unmodified lines19920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129235 unmodified linescomplete = [g for g in clusters if len(g)==4]samples = [r for g in complete for r in g]changes = [r for r in samples if len(r["reports"])==3 and terminal(r["reports"][1],2)!=r["reward"]]changed_groups = 0for group in complete:if all(len(r["reports"])==3 for r in group):j2 = [terminal(r["reports"][1],2) for r in group]j3 = [r["reward"] for r in group]changed_groups += j2 != j3 and (len(set(j2))>1 or len(set(j3))>1)curves = [dict(step=g[0]["step"]+1, reward=mean(r["reward"] for r in g), exact=mean(r["label"] for r in g)) for g in complete]return dict(groups=len(complete), samples=len(samples), reward=sum(r["reward"] for r in samples),exact=sum(r["label"] for r in samples), false_accept=sum(r["reward"]>r["label"] for r in samples),false_reject=sum(r["reward"]<r["label"] for r in samples),mixed=sum(len({r["reward"] for r in g})>1 for g in complete), curves=curves,j3_fixed=sum(r["label"]==r["reward"] for r in changes), j3_harmed=sum(r["label"]!=r["reward"] for r in changes),changed_advantage_groups=changed_groups)def arm_progress(folder, target):29 unmodified lines"""Independently match every effective reward to its actual prompt chain and exact arithmetic label."""spec = read_json(folder/"recipe.json")receipt = read_json(folder/"trained.json")confirmed = read_json(folder.parent/"confirm-winner/configuration.json")if read_json(folder/"configuration.json") != confirmed:raise ValueError("Solver training used a different frozen judge deployment")if (spec["initial_adapter_sha256"] != identity or receipt["initial_adapter_sha256"] != identityor receipt["updates"] != updates or spec["run"]["initial"] is not None):raise ValueError("Solver initialization or completed update count differs")8 unmodified linesraise ValueError(f"Training reward or split mismatch at {row['step']}/{row['sample']}")for level, output in enumerate(reports,1):call = calls[f"{row['step']}/{row['sample']}/j{level}"]if (call["artifact"].split("|")[0]!=confirmed["sha256"] or call["text"] != output orcall["messages"] != messages(f"j{level}",p,trace,reports[:level-1],"demonstrated")):raise ValueError("Training rollout does not match the recorded frozen-judge call")return [r["answer"] for r in effective[:4]]63 unmodified linesf"relative to the two-judge solver (paired 95% interval {100*lo:+.1f} to {100*hi:+.1f}). "f"It gained {effect['fixed']} solutions and lost {effect['harmed']} on the {effect['n']} shared problems. "f"During three-judge training, Judge 3 fixed {signal['j3_fixed']} solution verdicts and introduced "f"{signal['j3_harmed']} errors across {signal['samples']:,} sampled answers. Using Judge 3 changed "f"the within-group advantages in {signal['changed_advantage_groups']}/{signal['groups']} groups on those same samples. ""The interval conditions on these seed-17 checkpoints and the development population.")19 unmodified lineslink = f"[Raw solver and judge outputs]({GITHUB}/tree/main/results/{name})"atomic(target/"experiment.md", f"# Fresh solver with frozen Judge {arm['depth']}\n\n"+online_text(study)+note+" "+link+"\n")atomic(target/"learnings.md", f"# Training signal from frozen Judge {arm['depth']}\n\n"+note+" "+link+"\n")def solver_examples(study):examples = study.get("comparison",{}).get("examples",[])if not examples:return ""def show(ex,i):j2,j3 = ex["reports"][i][1:]return f"`{ex['traces'][i]}` ({'correct' if ex['correct'][i] else 'wrong'}), J2 `{j2}`, J3 `{j3}`"data = [[e["expression"], ", ".join(map(str,e["expected"])),show(e,0),show(e,1)] for e in examples]return ("### Both solvers on the same development calculation\n\n"+markdown(["Expression","Exact steps","Two-judge-trained solver and reviews","Three-judge-trained solver and reviews"],data)+"\n\nEach solver writes its answer before grading. In the six-number reviews, the first number audits the preceding judge and the fourth accepts or rejects the solver. The examples take the first problem in each observed pair of outcomes in evaluation order.\n\n")def fit_results(root):from .solver_fit import CANDIDATESmeasured = []for key in CANDIDATES:r = read_json(root/key/"result.json")if r:measured.append(dict(key=key, **r))return measureddef fit_table(measured):head = ["Solver", "Precision", "GPU test", "Parsed", "Exact", "Peak solver allocation"]table = []for r in measured:n = r.get("n")peak = r.get("after_step",{}).get("solver_peak_mib")table.append([r["model"].split("/")[-1],r["precision"].upper(),r["status"],f"{r['parsed']}/{n}" if n else "—",f"{r['correct']}/{n}" if n else "—",f"{peak:,.0f} MiB" if peak else "—"])return head,tabledef fit_text(measured):if not measured:return ""return ("### Solver precision and pretraining-only hardware checks\n\n"+markdown(*fit_table(measured))+"\n\nStarting accuracy uses greedy decoding on the same train-split calibration problems before the disposable update. ""The 4B judge ran on the same GPU. Peak allocation is PyTorch memory for the solver process alone. "f"[Hardware protocol]({GITHUB}/blob/main/reports/solver-precision.md) · [Measured costs and outcomes]({GITHUB}/tree/main/results/solver-fit).\n\n")def paired_review(study):"""Expose the initial-weight and exposure checks and every paired change, including negative results."""c=study.get("comparison",{})if not c:return ""data=[]for label, change in zip(("Two judges minus starting solver","Three judges minus starting solver","Three minus two"),[*c["vs_base"],c["d3_minus_d2"]],strict=True):lo,hi=change["interval"]data.append([label,change["n"],change["fixed"],change["harmed"],f"{100*change['delta']:+.1f}",f"{100*lo:+.1f} to {100*hi:+.1f}"])provenance=(f"The two fresh adapters had the same initial SHA-256 `{c['initial_adapter_sha256']}`. The actual prompt-order digest "f"for both training trajectories was `{next(iter(c['prompt_order_sha256'].values()))}`. "f"The first four sampled answers {'matched' if c['first_four_answers_matched'] else 'differed'}. ""Each effective training reward was recomputed from the raw terminal report and checked against its exact prompt history. ""Every finished checkpoint contributed one greedy trace per development problem. The training and development IDs were disjoint.")return ("# Independent review of the Qwen3.5-4B solver-reward comparison\n\n"+online_text(study)+markdown(["Paired comparison","Problems","Gained","Lost","Difference (pp)","95% interval (pp)"],data)+"\n\n"+provenance+"\n\n"+solver_examples(study))def plot_online(study, path):"""Plot only completed checkpoints, with the original solver and the realized reward signal explicitly labeled."""completed = [a for a in study.get("arms",[]) if a["n"]]if not completed:path.unlink(missing_ok=True)returnimport matplotlib.pyplot as pltfig,axes = plt.subplots(1,2,figsize=(10,3.8),layout="constrained")base=study["base"]def bars(ax, labels, pairs, colors, title):scales=[100*x/n for x,n in pairs]rectangles=ax.bar(labels,scales,color=colors)ax.set(ylim=(0,110),ylabel="Percent", title=title,yticks=[0,25,50,75,100])ax.bar_label(rectangles,labels=[f"{x}/{n}" for x,n in pairs],padding=3)ax.spines[["top","right"]].set_visible(False)labels=[f"{a['depth']} judges" for a in completed]colors=["#24796c","#4776ad"][:len(labels)]bars(axes[0],["Starting solver",*labels],[(base["correct"],base["n"]),*((a["correct"],a["n"]) for a in completed)],["#72807f",*colors],"Exact development solutions")bars(axes[1],labels,[(a["signal"]["mixed"],a["signal"]["groups"]) for a in completed],colors,"Training groups with mixed rewards")fig.suptitle("Training Qwen2.5-1.5B with frozen Qwen3.5-4B judges")fig.savefig(path,dpi=150)plt.close(fig)
139 unmodified lines14014114214314414516 unmodified lines162163164165166167321 unmodified lines489490491492493494128 unmodified lines623624625626627628139 unmodified linescontrasts = dict(primary=paired_primary(outcomes), flat=paired_comparison(outcomes,"flat"))return dict(runs=runs, inventory=inventory(ORIGINAL_RESULTS,profile,runs,contrasts),online_solvers=online_report.collect_online(ORIGINAL_RESULTS/"new-judges"),newer_judges=collect_frozen(ORIGINAL_RESULTS/"new-judges"), matched_depth=accuracy_grid(source,profile),**contrasts, planned=registered,learnability=learning, profile=profile, original_development=archive,16 unmodified linesdest = DOCS/"assets"dest.mkdir(parents=True, exist_ok=True)plot_scores(data["newer_judges"],dest/"frozen-judge-scores.png")learning_figure(data["learnability"],dest/"learnability.png")colors = ("#1e5260", "#177267", "#b65127")fig, ax = plt.subplots(figsize=(11, 2.45))321 unmodified linesline("Original solver trained with frozen Qwen3.5-4B judges","Heading2")table(*online_report.score_table(data["online_solvers"]))line(escape(online_report.conclusion(data["online_solvers"])))if data["newer_judges"]["results"]:line("Frozen Qwen verdict and evidence scores", "Heading2")chart=DOCS/"assets/frozen-judge-scores.png"128 unmodified linesheadline = confirmation_headline(data['newer_judges'])highlight = f"**Independent frozen-judge confirmation.** {headline}\n\n" if headline else ""online_summary = online_report.online_text(data["online_solvers"])highlight = online_summary + highlightif data['newer_judges'].get('review'):atomic(REPORTS/'reviews/frozen-confirmation.md',confirmation_review_text(data['newer_judges']))139 unmodified lines14014114214314414514616 unmodified lines163164165166167168169321 unmodified lines491492493494495496497498499500501502503504505506128 unmodified lines635636637638639640641642643644645646647139 unmodified linescontrasts = dict(primary=paired_primary(outcomes), flat=paired_comparison(outcomes,"flat"))return dict(runs=runs, inventory=inventory(ORIGINAL_RESULTS,profile,runs,contrasts),online_solvers=online_report.collect_online(ORIGINAL_RESULTS/"new-judges"),solver_fit=online_report.fit_results(ORIGINAL_RESULTS/"solver-fit"),newer_judges=collect_frozen(ORIGINAL_RESULTS/"new-judges"), matched_depth=accuracy_grid(source,profile),**contrasts, planned=registered,learnability=learning, profile=profile, original_development=archive,16 unmodified linesdest = DOCS/"assets"dest.mkdir(parents=True, exist_ok=True)plot_scores(data["newer_judges"],dest/"frozen-judge-scores.png")online_report.plot_online(data["online_solvers"],dest/"online-solvers.png")learning_figure(data["learnability"],dest/"learnability.png")colors = ("#1e5260", "#177267", "#b65127")fig, ax = plt.subplots(figsize=(11, 2.45))321 unmodified linesline("Original solver trained with frozen Qwen3.5-4B judges","Heading2")table(*online_report.score_table(data["online_solvers"]))line(escape(online_report.conclusion(data["online_solvers"])))online_figure=DOCS/"assets/online-solvers.png"if online_figure.is_file():story.append(Image(str(online_figure),width=164*mm,height=62.32*mm))for example in data["online_solvers"].get("comparison",{}).get("examples",[]):ref=", ".join(map(str,example["expected"]))line(escape(f"{example['expression']} requires {ref}. The two-judge solver wrote {example['traces'][0]!r}, and the three-judge solver wrote {example['traces'][1]!r}."))if data["solver_fit"]:line("Solver precision and pretraining-only hardware measurements","Heading2")table(*online_report.fit_table(data["solver_fit"]))line("Counts reflect greedy predictions on common train-split calibration prompts before a single disposable update with the frozen 4B judge. Peak allocation covers the solver process only.")if data["newer_judges"]["results"]:line("Frozen Qwen verdict and evidence scores", "Heading2")chart=DOCS/"assets/frozen-judge-scores.png"128 unmodified linesheadline = confirmation_headline(data['newer_judges'])highlight = f"**Independent frozen-judge confirmation.** {headline}\n\n" if headline else ""online_summary = online_report.online_text(data["online_solvers"])if (DOCS/"assets/online-solvers.png").is_file():online_summary += f"\n\n"online_summary += online_report.solver_examples(data["online_solvers"] or {}) + online_report.fit_text(data["solver_fit"])online_review = online_report.paired_review(data["online_solvers"] or {})if online_review:atomic(REPORTS/"reviews/online-solvers.md",online_review)online_summary += f"[Paired effects and independent reward checks]({GITHUB}/blob/main/reports/reviews/online-solvers.md).\n\n"highlight = online_summary + highlightif data['newer_judges'].get('review'):atomic(REPORTS/'reviews/frozen-confirmation.md',confirmation_review_text(data['newer_judges']))
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112"""Short, isolated hardware trials using the same real GRPO and frozen-judge code as the study."""
import osfrom functools import partialfrom time import monotonic
from .curriculum import curriculum_problemsfrom .design import BASE, REVISION, Runfrom .frozen_gpu import GPUFitError, device_memory, process_dedicated_memory, require_dedicated_memoryfrom .online_solvers import device_costs, initial_policy_digest, judge_session, score_chainfrom .records import parse, solver_truthfrom .storage import ORIGINAL_RESULTS, append, read_json, rows, stamp, write_json
BASE_ONLY = ("Qwen/Qwen3.5-2B-Base", "b1485b2fa6dfa1287294f269f5fb618e03d52d7c")CANDIDATES = {"original-nf4":(BASE, REVISION, "nf4"), "original-bf16":(BASE, REVISION, "bf16"), "original-int8":(BASE, REVISION, "int8"), "base-2b":(*BASE_ONLY, "nf4")}
def memory_check(model, server): """Measure live physical allocations for both processes alongside actual parameter storage.""" import torch storages = {t.untyped_storage().data_ptr():t.untyped_storage().nbytes() for t in (*model.parameters(),*model.buffers())} memory = dict(solver_state_mib=sum(storages.values())/2**20, solver_allocated_mib=torch.cuda.memory_allocated()/2**20, solver_peak_mib=torch.cuda.max_memory_allocated()/2**20, gpu=device_memory()) if os.name == "nt": memory["solver_dedicated_mib"] = process_dedicated_memory(os.getpid()) memory["judge_dedicated_mib"] = process_dedicated_memory(server.process.pid) require_dedicated_memory(server.placement, memory["judge_dedicated_mib"]) require_dedicated_memory(dict(weights_mib=memory["solver_state_mib"], cache_mib=0),memory["solver_dedicated_mib"]) return memory
def probe(key): import torch from .backend import Backend from .training import train
model_id, revision, precision = CANDIDATES[key] name = "solver-fit/"+key folder = ORIGINAL_RESULTS/name if (folder/"result.json").is_file(): return read_json(folder/"result.json") profile = read_json(ORIGINAL_RESULTS/"calibrated/profile.json") spec = Run(name, family=profile["family"], prompt_style=profile["style"], reward="d3") pool = curriculum_problems(spec.family,"train",272)[256:272] # These are fresh solver weights before this disposable step. The check never opens a test split. receipt = dict(model=model_id, revision=revision, precision=precision, start=stamp(), device_before=device_memory()) started = monotonic() try: with judge_session(name, "train") as runner: kept = [] def policy(*args): torch.cuda.reset_peak_memory_stats() b = Backend(*args, model_id=model_id, revision=revision, precision=precision, text_only=model_id==BASE_ONLY[0]) kept.append(b) initial_policy_digest(b.model) receipt["before_forward"] = memory_check(b.model, runner.backend) b.prompt_style = spec.prompt_style known = {r["key"] for r in rows(folder/"starting-answers.jsonl")} for pos in range(0,len(pool),4): problems = pool[pos:pos+4] if all(p.key in known for p in problems): continue answers = b.generate([b.prompt("solver",p) for p in problems], None,"fit_starting_solver", 911, False) for p,answer in zip(problems,answers,strict=True): if p.key not in known: append(folder/"starting-answers.jsonl",dict(key=p.key,expression=p.expression,answer=answer, correct=solver_truth(p,answer)[0],parsed=parse(answer,len(p.values)) is not None, time=stamp())) return b
effective = train(spec,1,partial(score_chain,runner.ask),backend_factory=policy) if kept: receipt["after_step"] = memory_check(kept[0].model,runner.backend) write_json(folder/"step-memory.json",receipt["after_step"]) elif (folder/"step-memory.json").is_file(): receipt["after_step"] = read_json(folder/"step-memory.json") else: raise ValueError("An interrupted probe has no post-update residency reading") samples = list(rows(folder/"rollouts.jsonl")) calibration = list(rows(folder/"starting-answers.jsonl")) if (effective["updates"]!=1 or len(samples)!=4 or [r["key"] for r in calibration]!=[p.key for p in pool] or any(len(s["reports"])!=3 for s in samples)): raise ValueError("Incomplete real GRPO hardware trial") receipt.update(status="One update completed", updates=1, group_rewards=[s["reward"] for s in samples], correct=sum(r["correct"] for r in calibration), parsed=sum(r["parsed"] for r in calibration), n=len(calibration), solver_usage=effective["usage"]) receipt["judge_cost"] = device_costs(name,"train") except (GPUFitError, torch.cuda.OutOfMemoryError) as error: receipt.update(status="GPU fit unavailable",reason=str(error)) receipt.update(time=stamp(), elapsed_seconds=monotonic()-started) write_json(folder/"result.json",receipt) return receipt
def fit_candidates(publish): """Probe the registered original precisions serially, then the documented pretraining-only candidate.""" from .cli import study_lock,worker with study_lock("solver-precision"): def stage(key): folder=ORIGINAL_RESULTS/"solver-fit"/key if not (folder/"result.json").is_file(): worker("solver-fit","--candidate",key) if publish: worker("publish","--milestone","solver-fit-"+key,"--run","solver-fit/"+key) return read_json(folder/"result.json") stage("original-nf4") if stage("original-bf16")["status"]=="GPU fit unavailable": stage("original-int8") stage("base-2b") if not publish: worker("report")164 unmodified lines1651661671681691701711 unmodified line173174175176177178179164 unmodified lineswrite_json(RESULTS / "budget.json", dict(updates=count, seconds_per_update=seconds, time=stamp()))def train(run, steps, external_chain=None):out = RESULTS / run.namefinished = read_json(out / "trained.json")if finished and (adapter(run.name) / "adapter_config.json").is_file():1 unmodified linerecord_timing_budget(finished)return finishedjournal = Journal(run.name)backend = Backend(journal, run.initial, frozen_sources(run), run.seed)backend.label = run.rolebackend.prompt_style = run.prompt_styleidentity = {}164 unmodified lines1651661671681691701711 unmodified line173174175176177178179164 unmodified lineswrite_json(RESULTS / "budget.json", dict(updates=count, seconds_per_update=seconds, time=stamp()))def train(run, steps, external_chain=None, backend_factory=None):out = RESULTS / run.namefinished = read_json(out / "trained.json")if finished and (adapter(run.name) / "adapter_config.json").is_file():1 unmodified linerecord_timing_budget(finished)return finishedjournal = Journal(run.name)backend = (backend_factory or Backend)(journal, run.initial, frozen_sources(run), run.seed)backend.label = run.rolebackend.prompt_style = run.prompt_styleidentity = {}
123456789101112131415161718192021222324252627282930313233343536373839"""Verify precision-trial selection, denominator reporting and the within-group reward counterfactual."""
import pytest
from study import cli, solver_fitfrom study.online_report import fit_results, fit_table, signalfrom study.storage import write_json
@pytest.mark.parametrize("bf16_fits", [True,False])def test_real_step_gate_selects_int8_only_on_bf16_fit_failure(tmp_path, monkeypatch, bf16_fits): observed = [] def worker(action,*args): if action=="report": return assert action=="solver-fit" and args[0]=="--candidate" key=args[1] observed.append(key) name,_,dtype=solver_fit.CANDIDATES[key] ok=key!="original-bf16" or bf16_fits receipt=dict(model=name,precision=dtype,status="One update completed" if ok else "GPU fit unavailable") if ok: receipt.update(n=16,correct=0,parsed=2,after_step={"solver_peak_mib":1024}) write_json(tmp_path/"solver-fit"/key/"result.json",receipt) monkeypatch.setattr(cli,"STATE",tmp_path/"state") monkeypatch.setattr(cli,"worker",worker) monkeypatch.setattr(solver_fit,"ORIGINAL_RESULTS",tmp_path) solver_fit.fit_candidates(False) assert observed == ["original-nf4","original-bf16",*([] if bf16_fits else ["original-int8"]),"base-2b"] _,data=fit_table(fit_results(tmp_path/"solver-fit")) assert data[0][4]=="0/16" and (data[1][4]=="—") == (not bf16_fits)
def test_all_approve_versus_all_reject_has_zero_centered_advantage(): def rollout(step,j2,j3): return dict(step=step,label=0,reward=j3,reports=["0,1,7",f"1,0,7,{j2},0,7",f"1,0,7,{j3},0,7"]) data = [rollout(0,0,1) for _ in range(4)] + [rollout(1,0,bit) for bit in (0,0,0,1)] s = signal(data) assert (s["groups"],s["j3_harmed"],s["changed_advantage_groups"],s["mixed"])==(2,5,1,1)docs/explorer.js+5
docs/index.html+1
docs/usage.md+2
reports/solver-precision.md+4
src/study/backend.py+32-13
src/study/cli.py+14-1
src/study/inventory.py+13
src/study/online_report.py+106-3
src/study/report.py+19
src/study/solver_fit.pyAdded+112
src/study/training.py+2-2
tests/test_solver_fit.pyAdded+39