matched-depth-implementation · 72b892124fe4
Browse filesFiles changed (10)
3 unmodified lines45678910316 unmodified lines3273283293303313323338860 unmodified lines91949195919691979198919992008853 unmodified lines180541805518056180571805818059180608846 unmodified lines269072690826909269102691126912269138846 unmodified lines357603576135762357633576435765357668794 unmodified lines445614456244563445644456544566445678860 unmodified lines534285342953430534315343253433534348860 unmodified lines622956229662297622986229962300623018758 unmodified lines710607106171062710637106471065710668744 unmodified lines798117981279813798147981579816798178784 unmodified lines886028860388604886058860688607886088751 unmodified lines973609736197362973639736497365973668751 unmodified lines1061181061191061201061211061221061231061248860 unmodified lines1149851149861149871149881149891149901149918860 unmodified lines1238521238531238541238551238561238571238588860 unmodified lines1327191327201327211327221327231327241327258860 unmodified lines1415861415871415881415891415901415911415928860 unmodified lines1504531504541504551504561504571504581504598860 unmodified lines1593201593211593221593231593241593251593268758 unmodified lines1680851680861680871680881680891680901680918744 unmodified lines1768361768371768381768391768401768411768428784 unmodified lines1856271856281856291856301856311856321856338860 unmodified lines1944941944951944961944971944981944991945004454 unmodified lines1989551989561989571989581989591989601989613 unmodified lines "name": "base", "role": "solver", "reward": "untrained", "supplemental": false, "diagnostic": false, "family": "two-add", "seed": 17,316 unmodified lines "name": "d3-17", "role": "solver", "reward": "d3", "supplemental": false, "diagnostic": false, "family": "two-add", "seed": 17,8860 unmodified lines "name": "d2-17", "role": "solver", "reward": "d2", "supplemental": false, "diagnostic": false, "family": "two-add", "seed": 17,8853 unmodified lines "name": "d1-17", "role": "solver", "reward": "d1", "supplemental": false, "diagnostic": false, "family": "two-add", "seed": 17,8846 unmodified lines "name": "flat-17", "role": "solver", "reward": "flat", "supplemental": false, "diagnostic": false, "family": "two-add", "seed": 17,8846 unmodified lines "name": "oracle-17", "role": "solver", "reward": "oracle", "supplemental": false, "diagnostic": false, "family": "two-add", "seed": 17,8794 unmodified lines "name": "hybrid-17", "role": "solver", "reward": "hybrid", "supplemental": false, "diagnostic": false, "family": "two-add", "seed": 17,8860 unmodified lines "name": "shuffle-17", "role": "solver", "reward": "shuffle", "supplemental": false, "diagnostic": false, "family": "two-add", "seed": 17,8860 unmodified lines "name": "exact-j1", "role": "j1", "reward": "exact", "supplemental": false, "diagnostic": false, "family": "two-add", "seed": 17,8758 unmodified lines "name": "exact-j2", "role": "j2", "reward": "exact", "supplemental": false, "diagnostic": false, "family": "two-add", "seed": 17,8744 unmodified lines "name": "exact-j3", "role": "j3", "reward": "exact", "supplemental": false, "diagnostic": false, "family": "two-add", "seed": 17,8784 unmodified lines "name": "top-j2", "role": "j2", "reward": "teacher", "supplemental": false, "diagnostic": false, "family": "two-add", "seed": 17,8751 unmodified lines "name": "top-j1", "role": "j1", "reward": "teacher", "supplemental": false, "diagnostic": false, "family": "two-add", "seed": 17,8751 unmodified lines "name": "exact-prefix1", "role": "solver", "reward": "d3", "supplemental": false, "diagnostic": false, "family": "two-add", "seed": 17,8860 unmodified lines "name": "exact-prefix2", "role": "solver", "reward": "d3", "supplemental": false, "diagnostic": false, "family": "two-add", "seed": 17,8860 unmodified lines "name": "exact-prefix3", "role": "solver", "reward": "d3", "supplemental": false, "diagnostic": false, "family": "two-add", "seed": 17,8860 unmodified lines "name": "top-prefix1", "role": "solver", "reward": "d3", "supplemental": false, "diagnostic": false, "family": "two-add", "seed": 17,8860 unmodified lines "name": "top-prefix2", "role": "solver", "reward": "d3", "supplemental": false, "diagnostic": false, "family": "two-add", "seed": 17,8860 unmodified lines "name": "top-prefix3", "role": "solver", "reward": "d3", "supplemental": false, "diagnostic": false, "family": "two-add", "seed": 17,8860 unmodified lines "name": "alt-exact-j1", "role": "j1", "reward": "exact", "supplemental": false, "diagnostic": false, "family": "two-add", "seed": 17,8758 unmodified lines "name": "alt-exact-j2", "role": "j2", "reward": "exact", "supplemental": false, "diagnostic": false, "family": "two-add", "seed": 17,8744 unmodified lines "name": "alt-exact-j3", "role": "j3", "reward": "exact", "supplemental": false, "diagnostic": false, "family": "two-add", "seed": 17,8784 unmodified lines "name": "alt-exact-solver", "role": "solver", "reward": "d3", "supplemental": false, "diagnostic": false, "family": "two-add", "seed": 17,8860 unmodified lines "name": "learn-oracle-17", "role": "solver", "reward": "oracle", "supplemental": false, "diagnostic": true, "family": "two-add", "seed": 17,4454 unmodified lines "name": "learn-shuffle-17", "role": "solver", "reward": "oracle-shuffle", "supplemental": false, "diagnostic": true, "family": "two-add", "seed": 17,117 unmodified lines118119120121121122123124117 unmodified lines study = await response.json(); const p=study.primary; byId("primary").textContent=p.delta == null ? "Awaiting matched final checkpoints for all registered seeds." : "Three judges minus two: "+(p.delta*100).toFixed(2)+" points. 95% interval "+p.ci.map(x=>(100*x).toFixed(2)).join(" to ")+". Decision: "+p.status+"."; byId("progress").textContent=study.runs.filter(r=>r.updates != null && !r.diagnostic).length+" of "+study.planned+" registered training blocks completed. "+(study.sealed?"Checkpoint manifest sealed.":"Final test sealed during development."); byId("progress").textContent=study.runs.filter(r=>r.updates != null && !r.diagnostic && !r.supplemental).length+" of "+study.planned+" registered training blocks completed. "+(study.sealed?"Checkpoint manifest sealed.":"Final test sealed during development."); if (study.profile?.family) byId("progress").textContent += " Amended benchmark · "+study.profile.family+" arithmetic with "+study.profile.style+" prompts."; showMatched(study.matched_depth ?? []); const cal=study.learnability;11 unmodified lines121314151617181911 unmodified lines
After the final campaign completion receipt exists, the same report command regenerates `reports/reviews/final.md`. It re-executes every primary and transfer solution, checks natural and evidence-altered reviews, tests the observed training and development IDs against the reserved populations, verifies the seal, and tabulates matched gains and losses for each depth comparison. [Final review implementation](../src/study/final_review.py)
The calibrated campaign automatically runs the four additional matched-depth solvers and two fixed-answer judge-stack replays. In a calibrated environment, individual examples of the same entry points are `uv run study train --run exact-depth2` and `uv run study stack-replay --route exact`. The held-out extension requires both the original and additional checkpoint seals. [Matched-depth protocol](../reports/matched-depth-protocol.md)
Model inputs, token chunks and full outputs are printed and saved in timestamped JSONL under `logs`. Raw training and evaluation records live in `results`. Each row includes an expression identity. Training outputs include their assigned reward and independently computed complete-record label. Natural replay keeps all three reports and the three flat ballots on the identical solution. Twin interventions keep observed and expected records in both conditions.
The explorer shows every completed optimizer group for the selected run and the latest greedy development probe. Counts under each replay rule distinguish verdict agreement from whole-record evidence accuracy. Generation cost counts non-padding input and output tokens. CUDA-event durations measure elapsed device time around a batched generation call, including gaps between kernels. The pretrained judges share the pinned Qwen backbone. A frozen-adapter checksum with no input tensors means the run loaded no fitted judge adapters.9 unmodified lines1011121313141516173 unmodified lines212223232425262728293050 unmodified lines8182838485868788899091929394959616 unmodified lines11311411510211611711811912012112212312412512612712812913013110813213313413553 unmodified lines1891901911681921931941952 unmodified lines19819920020120220320420520634 unmodified lines2412422432442452462472482492509 unmodified linesfrom functools import partialfrom http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
from .design import PILOTS, Run, matrixfrom .benchmark import active_profilefrom .design import MATCHED_NAMES, PILOTS, ROUTES, Run, matched_runs, matrixfrom .storage import ORIGINAL_RESULTS, RESULTS, ROOT, STATE, TRACK, read_json, stamp, write_json
3 unmodified lines if name in PILOTS: from .learnability import pilot_spec return pilot_spec(name) return next(row for row in matrix() if row.name == name) if name in MATCHED_NAMES and TRACK!="calibrated": raise ValueError("The matched-depth solver runs require STUDY_TRACK=calibrated") profile=active_profile() return next(row for row in [*matrix(profile),*matched_runs(profile)] if row.name==name)
def worker(*args):50 unmodified lines worker("report") write_json(STATE/"local-milestones"/(milestone+".json"), {"time":stamp()})
def fitted_replays(phase): for route in ROUTES: milestone=f"stack-{route}-{phase}" if not (RESULTS/"matched-depth"/f"{route}-{phase}.json").exists(): worker("stack-replay","--route",route,*(("--final",) if phase=="final" else ())) if public and not (STATE/"publication"/(milestone+".json")).exists(): worker("publish","--milestone",milestone) elif not public: worker("report")
with study_lock("campaign"): if public: if not (STATE/"publication/protocol.json").exists():16 unmodified lines for run in matrix(): stage("train",run.name,"trained") stage("evaluate",run.name,"development") if not (RESULTS/"seal.json").exists(): if TRACK=="calibrated" and run.name=="alt-top-j3": # The supplemental arms reuse trained judges and the unchanged original solver schedule. fitted_replays("development") for extra in matched_runs(active_profile()): stage("train",extra.name,"trained") stage("evaluate",extra.name,"development") if not (RESULTS/"seal.json").exists() or (TRACK=="calibrated" and not (RESULTS/"matched-depth/seal.json").exists()): worker("seal") if public: worker("publish","--milestone","sealed-checkpoints") for name in ("base", *(r.name for r in matrix())): stage("evaluate",name,"final") if TRACK=="calibrated": fitted_replays("final") for extra in matched_runs(active_profile()): stage("evaluate",extra.name,"final") write_json(RESULTS/"completed.json",{"time":stamp(),"arms":len(matrix())}) write_json(RESULTS/"completed.json",{"time":stamp(),"arms":len(matrix()),"matched_depth_arms":len(matched_runs(active_profile()))}) if public: worker("publish","--milestone","complete") else:53 unmodified lines schedule.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({})] names=[*(r.name for r in matrix({})),*MATCHED_NAMES] actions.add_parser("train").add_argument("--run",required=True,choices=["timing",*PILOTS,*names]) calibration=actions.add_parser("learnability",description="Calibrate arithmetic and test actual solver improvement") calibration.add_argument("phase",choices=["screen","confirm","audit","evaluate","compare","campaign"])2 unmodified lines evaluate=actions.add_parser("evaluate") evaluate.add_argument("--run",required=True,choices=["base",*names]) evaluate.add_argument("--final",action="store_true") stacks=actions.add_parser("stack-replay",description="Measure each fitted judge depth on fixed base-solver answers") stacks.add_argument("--route",choices=ROUTES,required=True) stacks.add_argument("--final",action="store_true") actions.add_parser("seal") actions.add_parser("report") actions.add_parser("dashboard").add_argument("--port",default=8765,type=int)34 unmodified lines from .evaluate import evaluate with study_lock("evaluate-"+args.run+("-final" if args.final else "-dev")): evaluate(args.run,args.final) elif args.action=="stack-replay": from .evaluate import stack_replay with study_lock(f"stack-{args.route}-{'final' if args.final else 'development'}"): stack_replay(args.route,args.final) elif args.action == "seal": from .evaluate import seal seal()3 unmodified lines456789101125 unmodified lines37383938394041424316 unmodified lines6061626364656667686970717273743 unmodified lines
SEEDS = (17, 29, 43)PILOTS = ("learn-oracle-17","learn-shuffle-17")ROUTES = {"exact":("exact-j1","exact-j2","exact-j3"), "top":("top-j1","top-j2","exact-j3")}MATCHED_NAMES = tuple(f"{route}-depth{d}" for route in ROUTES for d in (1,2))BASE = "Qwen/Qwen2.5-1.5B-Instruct"REVISION = "989aa7980e4cf806f80c7fef2b1adb7bc71aa306"PROJECT = "verifying-verifier-of-verifier-llm-reinforcement-learning"25 unmodified lines from .benchmark import active_profile profile = active_profile() rows = [Run(f"{arm}-17", reward=arm) for arm in ("d3", "d2", "d1", "flat", "oracle", "hybrid", "shuffle")] direct = tuple(f"exact-j{i}" for i in (1, 2, 3)) top = ("top-j1", "top-j2", direct[2]) direct, top = ROUTES["exact"], ROUTES["top"] rows.extend(Run(name, role=f"j{i}", reward="exact") for i, name in enumerate(direct, 1)) rows.extend((Run(top[1], role="j2", reward="teacher", teacher=direct[2]), Run(top[0], role="j1", reward="teacher", teacher=top[1])))16 unmodified lines return rows
def matched_runs(profile): """Clone each fresh deep solver's complete training recipe and vary only the reward depth.""" if not profile: return [] originals = {r.name:r for r in matrix(profile)} return [replace(originals[route+"-prefix3"],name=f"{route}-depth{level}",reward=f"d{level}") for route in ROUTES for level in (1,2)]
def permute_groups(values, rng): if len(values) % 4: raise ValueError("A shuffled GRPO reward requires complete groups of four")3 unmodified lines45677891025 unmodified lines36373839404142434445464748495051525354556 unmodified lines62636451656667682 unmodified lines71727360747576774 unmodified lines828384718586878849 unmodified lines1381391401271411421431441451 unmodified line14714814915015115215315415515615713815815914016016116228 unmodified lines1911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272283 unmodified lines
from .backend import Backend, stream_seedfrom .benchmark import active_profile, populationfrom .design import matrixfrom .design import MATCHED_NAMES, ROUTES, matched_runs, matrixfrom .domain import problemsfrom .exposures import check_exposuresfrom .judging import chain, majority, twin, votes25 unmodified lines if not previous: exposures = check_exposures(RESULTS, matrix()) write_json(path, {"time": stamp(), "weights": manifest, "ordered_training_exposures": exposures}) extra = matched_runs(active_profile()) if extra: weights = {r.name:weights_digest(r.name) for r in extra} for r in extra: if weights[r.name] != read_json(RESULTS/r.name/"development.json",{}).get("weights"): raise RuntimeError(f"Unverified matched-depth checkpoint for {r.name}") references = [r for r in matrix() if r.name in ("d1-17","d2-17","d3-17","exact-prefix3","top-prefix3")] exposures = check_exposures(RESULTS,[*references,*extra]) extra_path = RESULTS/"matched-depth/seal.json" recorded = read_json(extra_path) if recorded and (recorded["weights"]!=weights or recorded["ordered_training_exposures"]!=exposures): raise RuntimeError("The matched-depth seal differs from the realized solver checkpoints or inputs") if not recorded: write_json(extra_path,dict(time=stamp(),weights=weights,ordered_training_exposures=exposures))
def batches(split, n, path, size=8, population=None):6 unmodified lines yield pos, batch, seen
def solutions(backend, run, snapshots, split, n, path, replay, stored_traces=None, pool=None):def solutions(backend, run, snapshots, split, n, path, replay, stored_traces=None, pool=None, panel=True): policy = run.name if run and run.role == "solver" else None for pos, batch, seen in batches(split, n, path, population=pool): seed = stream_seed("eval", split, pos)2 unmodified lines else: traces = backend.generate([backend.prompt("solver", p) for p in batch], policy, "eval_solver", seed, False) histories = chain(backend, batch, traces, snapshots, 3, seed) if replay else [[] for _ in batch] ballots = votes(backend, batch, traces, seed, snapshots) if replay else [[] for _ in batch] ballots = votes(backend, batch, traces, seed, snapshots) if replay and panel else [[] for _ in batch] for p, t, h, v in zip(batch, traces, histories, ballots, strict=True): if p.key in seen: continue4 unmodified lines malformed=numbers is None, split=split, reports=h, votes=v) if replay: bits = [terminal(report, i) for i, report in enumerate(h, 1)] entry.update(verdicts=bits, flat=majority(v), full_report_correct=[ entry.update(verdicts=bits, flat=majority(v) if panel else None, full_report_correct=[ int(sound(report, expected(p, t, h[:i]))) for i, report in enumerate(h)], judge_malformed=[parse(report, 3 if i == 0 else 6) is None for i, report in enumerate(h)], fixed=int(bits[1] != oracle[0] and bits[2] == oracle[0]),49 unmodified lines marker = directory / (phase+".json") if marker.is_file(): return read_json(marker) run = next((r for r in matrix() if r.name == name), None) profile = active_profile() run = next((r for r in [*matrix(profile),*matched_runs(profile)] if r.name == name), None) if not run and name != "base": raise ValueError(f"Unknown evaluation {name}") snapshots = list(run.judges if run else (None,)*3)1 unmodified line snapshots[int(run.role[1:])-1] = run.name if final: frozen = read_json(RESULTS / "seal.json") if profile and not (RESULTS/"matched-depth/seal.json").is_file(): raise RuntimeError("The calibrated final evaluation also requires the matched-depth seal") used = {s for s in snapshots if s} if run: used.add(name) weights = dict((frozen or {}).get("weights",{})) if name in MATCHED_NAMES: weights.update(read_json(RESULTS/"matched-depth/seal.json",{}).get("weights",{})) if not frozen or any(frozen["weights"].get(s) != weights_digest(s) for s in used): if not frozen or any(weights.get(s) != weights_digest(s) for s in used): raise RuntimeError("Final evaluation requires every participating checkpoint to match the seal") profile = active_profile() backend = Backend(Journal(name+"-"+phase), frozen=[*snapshots, name if run else None]) backend.prompt_style = profile.get("style", "registered") evidence_sources = {}28 unmodified lines **generation_cost(name+"-"+phase,backend.totals), "evidence_sources": evidence_sources, "profile": profile} write_json(marker, result) return result
def stack_replay(route,final=False): """Score all prefixes of the fitted stack on the literal responses archived for the starting solver.""" profile = active_profile() if not profile: raise ValueError("The matched-depth extension uses the calibrated benchmark") phase = "final" if final else "development" split = "test" if final else "dev" count = 128 if final else 32 target = RESULTS/"matched-depth"/f"{route}-{phase}" if target.with_suffix(".json").exists(): return if not (RESULTS/"base"/(phase+".json")).is_file(): raise RuntimeError("Wait for the base evaluation receipt") pool = population(profile,split,count) source = RESULTS/"base"/("judge-test.jsonl" if final else "replay.jsonl") saved = list(rows(source)) if [(r["key"],r["expression"]) for r in saved] != [(p.key,p.expression) for p in pool]: raise ValueError("The fitted stack requires the complete saved base-solver answers in registered order") snapshots = ROUTES[route] weights = {name:weights_digest(name) for name in snapshots} if final: sealed = read_json(RESULTS/"seal.json",{}).get("weights",{}) if not (RESULTS/"matched-depth/seal.json").exists() or any(sealed.get(k)!=v for k,v in weights.items()): raise RuntimeError("Fitted-stack final evaluation requires both recorded seals") name = f"stack-{route}-{phase}" backend = Backend(Journal(name),frozen=snapshots) backend.prompt_style = profile["style"] traces = {r["key"]:r["trace"] for r in saved} solutions(backend,None,snapshots,split,count,target.with_suffix(".jsonl"),True,traces,pool,panel=False) from .matched_tables import read_cohort scored = read_cohort(target.with_suffix(".jsonl"),saved,judge=True) write_json(target.with_suffix(".json"),dict(time=stamp(),phase=phase,weights=weights,source=source.name,n=len(scored), **generation_cost(name,backend.totals)))5 unmodified lines6789910111218 unmodified lines31323334343536378 unmodified lines464748494950515152535437 unmodified lines929394959697989910010110210310410 unmodified lines11511611711111811912011512112212312412512612712012812913013121 unmodified lines1531541551561571581591601611621631647 unmodified lines1721731741611751761771785 unmodified linesfrom .benchmark import populationfrom .curriculum import EXAMPLESfrom .depth_review import numbersfrom .design import SEEDS, matrixfrom .design import ROUTES, SEEDS, matched_runs, matrixfrom .domain import Problem, problemsfrom .exposures import check_exposuresfrom .learning_review import execute_steps18 unmodified lines raise ValueError(f"Incomplete cohort in {path}")
def grade_solutions(path, pool, split, fixed_traces=None):def grade_solutions(path, pool, split, fixed_traces=None, panel=True): """Execute the recorded steps and separately check the submitted trace, last value and format.""" outcomes = {} for p,r in cohort_rows(path,pool,split):8 unmodified lines reports = r["reports"] bits = [terminal(report,i) for i,report in enumerate(reports,1)] sound = [numbers(raw,3 if i==0 else 6) == expected(p,r["trace"],reports[:i]) for i,raw in enumerate(reports)] flat = sum(terminal(v,1) for v in r["votes"]) >= 2 flat = sum(terminal(v,1) for v in r["votes"]) >= 2 if panel else None correct = outcomes[p.key] if (r["trace"] != fixed_traces[p.key] or len(bits) != 3 or len(r["votes"]) != 3 or if (r["trace"] != fixed_traces[p.key] or len(bits) != 3 or len(r["votes"]) != (3 if panel else 0) or bits != r["verdicts"] or sound != r["full_report_correct"] or flat != r["flat"] or (r["fixed"],r["harmed"]) != (bits[1]!=correct and bits[2]==correct, bits[1]==correct and bits[2]!=correct)): raise ValueError(f"Natural review mismatch in {path} at {p.key}")37 unmodified lines if (set(seal["weights"]) != {r.name for r in schedule} or seal["ordered_training_exposures"] != check_exposures(root,schedule)): raise ValueError("The training exposures or checkpoint manifest differ from the published seal") extra=matched_runs(profile) supplemental_seal = read_json(root/"matched-depth/seal.json",{}) if extra: references=[r for r in schedule if r.name in ("d1-17","d2-17","d3-17","exact-prefix3","top-prefix3")] if (set(supplemental_seal.get("weights",{}))!={r.name for r in extra} or supplemental_seal.get("ordered_training_exposures")!=check_exposures(root,[*references,*extra])): raise ValueError("Unmatched input exposure or checkpoint manifest in the depth extension") suites = dict(test=2048,layout=128,long=128,mechanism=128) if profile and profile["family"] != "registered": suites["original-difficulty"] = 204810 unmodified lines if leakage: raise ValueError(f"Found {leakage} final IDs among previously observed study examples")
sealed_at = datetime.fromisoformat(seal["time"]) outcomes, origins = {}, {} graded = natural = twins = 0 unique_twins = {} names = {"base":"solver",**{r.name:r.role for r in schedule}} names = {"base":"solver",**{r.name:r.role for r in [*schedule,*extra]}} prefix = dict(list(pools["test"].items())[:128]) for name,role in names.items(): directory = root/name dev, final = [read_json(directory/(phase+".json")) for phase in ("development","final")] manifest = supplemental_seal if name in supplemental_seal.get("weights",{}) else seal sealed_at = datetime.fromisoformat(manifest["time"]) weights = seal["weights"].get(name,"frozen base") weights = manifest["weights"].get(name,"frozen base") if (dev["weights"] != weights or final["weights"] != weights or not datetime.fromisoformat(dev["time"]) <= sealed_at <= datetime.fromisoformat(final["time"])): raise ValueError(f"Evaluation receipt does not match the checkpoint seal for {name}")21 unmodified lines twins += count unique_twins[source,filename] = count
for route in ROUTES if extra else (): fixed = root/"matched-depth"/f"{route}-final" marker=read_json(fixed.with_suffix(".json")) if marker["weights"]!={j:seal["weights"][j] for j in ROUTES[route]}: raise ValueError(f"Fixed-solver judge stack differs from its seal for {route}") natural += len(grade_solutions(fixed.with_suffix(".jsonl"),prefix,"test",origins["base"],panel=False)) comparisons = [] for reference in ("d2","flat","d1"): seeds = SEEDS[:1] if reference=="d1" else SEEDS7 unmodified lines if not isclose(change,published,abs_tol=1e-12): raise ValueError("Paired published effect differs from independently rescored solutions") comparisons.append([seed,reference.upper(),len(a),gains,losses,f"{100*change:+.2f}"]) return dict(checkpoints=len(schedule),prior_ids=len(old),test_ids=len(all_test),overlap=leakage,solver_grades=graded, return dict(checkpoints=len(schedule)+len(extra),prior_ids=len(old),test_ids=len(all_test),overlap=leakage,solver_grades=graded, natural_reviews=natural,paired_records=twins,distinct_paired_records=sum(unique_twins.values()), comparisons=comparisons)
12334567889101163 unmodified lines7576777879787980818283"""Compare judge depths only when the arithmetic questions or saved solver answers are identical."""
from .design import ROUTESfrom .storage import read_json, rowsfrom .storage import rowsfrom .tables import markdown
HEADERS = ["Training condition","One judge · J1","Two judges · J2 checks J1","Three judges · J3 checks J2"]ROUTES = {"exact":("exact-j1","exact-j2","exact-j3"), "top":("top-j1","top-j2","exact-j3")}PENDING = "Pending"
63 unmodified lines if replay.with_suffix(".json").is_file(): records = read_cohort(replay.with_suffix(".jsonl"),shared,judge=True) fitted = [score(records,i) for i in range(3)] if fitted[0] != isolated[0]: raise ValueError(f"Identical trained Judge 1 differs across {route} conditions") first = read_cohort(root/ROUTES[route][0]/judge_file,shared,judge=True) if any(a["reports"][0]!=b["reports"][0] for a,b in zip(first,records,strict=True)): raise ValueError(f"Identical trained Judge 1 reports differ across {route} conditions") judge_table.append([label+" · all participating judges trained",*fitted]) grids.append(dict(phase=phase,solver=solver_table,judge=judge_table,solver_n=len(base),judge_n=len(shared), frozen_solver=cell(sum(r["correct"] for r in base),len(base))))7 unmodified lines8910111112131426 unmodified lines4142434445464746 unmodified lines94959696979899100514 unmodified lines6156166176186176186196206216226236246256266276287 unmodified lines
from .analysis import evidence_fields, paired_comparison, paired_primary, replay_metricsfrom .depth_review import collect_depth_review, readme_depth, review_text as depth_review_textfrom .design import GITHUB, PAGES, PILOTS, Run, matrixfrom .design import GITHUB, MATCHED_NAMES, PAGES, PILOTS, Run, matched_runs, matrixfrom .final_review import review_completed, review_text as final_review_textfrom .learnability_report import collect_learnability, learnability_text, learning_figurefrom .learning_review import check_release, review_text26 unmodified lines source = calibrated if profile else ORIGINAL_RESULTS manifest = {r.name: r for r in matrix(profile)} registered=len(manifest) manifest.update((r.name,r) for r in matched_runs(profile)) learning=collect_learnability(ORIGINAL_RESULTS) chosen=(learning["screen"] or {}).get("selected") if chosen:46 unmodified lines matched = e["correct"] if depth == 0 else e["full_report_correct"][depth-1] common_example = dict(key=e["key"], expression=e["expression"], actual=actual, expected=render(reference), correct=matched) runs.append(dict(name=name, role=role, reward=spec.reward if spec else "untrained", runs.append(dict(name=name, role=role, reward=spec.reward if spec else "untrained", supplemental=name in MATCHED_NAMES, diagnostic=name in PILOTS, family=spec.family if spec else profile.get("family"), seed=spec.seed if spec else 17, updates=trained.get("updates"), observations=len(training), initial=spec.initial if spec else None, judges=spec.judges if spec else (None,)*3,514 unmodified lines methods_table=markdown(["Run","Role","Reward","Seed","Problem source","Dev. parsed","Dev. exact","Held-out exact"],methods) atomic(experiments/"experiments.md","# Experiment index\n\nAll learned models use grouped reinforcement learning with one active LoRA adapter on the shared, quantized Qwen2.5-1.5B-Instruct backbone. The solver predicts values in signed-integer expression trees. Judges predict exact evidence records about earlier outputs. A parsed output supplies the required number of integers. An exact output also gets every field right.\n\n"+methods_table+"\n\n[Update counts and sample sizes](../summary.md) · [Objectives and curricula](../planned-runs.md) · [Analysis protocol](../preregistration.md)\n\n"+references+"\n") atomic(experiments/"learnings.md","# Experimental learnings\n\n"+("\n".join(notes) or "No experimental observations yet.")+"\n") core=[r for r in data["runs"] if r["name"]!="base" and not r["diagnostic"] and not r["supplemental"]] complete=sum(r["completed_final"] for r in data["runs"] if r["name"]!="base") trained=sum(r["updates"] is not None for r in data["runs"] if not r["diagnostic"]) complete=sum(r["completed_final"] for r in core) trained=sum(r["updates"] is not None for r in core) activity = [] if profile: extra=[r for r in data["runs"] if r["supplemental"]] activity.append(f"The matched-depth extension has trained {sum(r['updates'] is not None for r in extra)} " f"of {len(MATCHED_NAMES)} additional shallow solvers. [Extension](matched-depth-protocol.md).") if data["budget"]: b = data["budget"] activity.append(f"The timing pilot selected {b['updates']} updates per block at {b['seconds_per_update']:.1f} seconds per pilot update. A block at that rate would take {b['updates']*b['seconds_per_update']/3600:.2f} hours.")1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071"""Verify the additional four treatments use the registered solver path at their actual depths."""
import pytest
def test_extra_solvers_reuse_the_deep_conditions_except_for_terminal_depth(): from dataclasses import replace from study.design import matched_runs, matrix
profile={"family":"two-add","style":"demonstrated"} original={r.name:r for r in matrix(profile)} extra=matched_runs(profile) assert len(extra)==4 and len(original)==32 and not matched_runs({}) for spec in extra: route,depth=spec.name.split("-depth") deep=original[route+"-prefix3"] assert spec==replace(deep,name=spec.name,reward="d"+depth)
def test_fixed_stack_requires_persisted_identical_solver_answers(tmp_path,monkeypatch): evaluate=pytest.importorskip("study.evaluate") from study.domain import Problem from study.storage import append,write_json
monkeypatch.setattr(evaluate,"RESULTS",tmp_path) monkeypatch.setattr(evaluate,"active_profile",lambda: {"family":"two-add","style":"demonstrated"}) write_json(tmp_path/"base/development.json",{"phase":"development"}) problems=[Problem.from_expression(f"({i}+3)-2") for i in range(32)] monkeypatch.setattr(evaluate,"population",lambda *args:problems) for p in problems[:-1]: append(tmp_path/"base/replay.jsonl",dict(key=p.key,expression=p.expression,trace="wrong")) with pytest.raises(ValueError,match="complete saved"): evaluate.stack_replay("exact")
def test_fitted_stack_scores_all_prefixes_without_resampling_solver_or_adding_ballots(tmp_path,monkeypatch): evaluate=pytest.importorskip("study.evaluate") from study.design import ROUTES from study.domain import Problem from study.records import expected,render from study.storage import append,read_json,rows,write_json
pset=[Problem.from_expression(f"({i}+3)-2") for i in range(32)] calls=[] class Frozen: def __init__(self,journal,frozen): assert tuple(frozen)==ROUTES["exact"] self.totals={} def prompt(self,role,p,trace,history): return (p,trace,history) def generate(self,prompts,snapshot,role,seed,sample): calls.append(role) assert sample and snapshot=="exact-"+role return [render(expected(p,trace,history)) for p,trace,history in prompts] monkeypatch.setattr(evaluate,"RESULTS",tmp_path) monkeypatch.setattr(evaluate,"active_profile",lambda:{"family":"two-add","style":"demonstrated"}) monkeypatch.setattr(evaluate,"population",lambda *args:pset) monkeypatch.setattr(evaluate,"Backend",Frozen) monkeypatch.setattr(evaluate,"weights_digest",lambda key:"hash-"+key) monkeypatch.setattr(evaluate,"generation_cost",lambda name,totals:{"usage":totals}) write_json(tmp_path/"base/development.json",{"phase":"development"}) for i,p in enumerate(pset): trace=render(p.values) if i%2 else "an invalid answer" append(tmp_path/"base/replay.jsonl",dict(key=p.key,expression=p.expression,trace=trace,correct=i%2)) evaluate.stack_replay("exact") result=list(rows(tmp_path/"matched-depth/exact-development.jsonl")) assert calls==["j1","j2","j3"]*4 and len(result)==32 assert all(r["verdicts"]==[r["correct"]]*3 and not r["votes"] for r in result) assert read_json(tmp_path/"matched-depth/exact-development.json")["n"]==32 evaluate.stack_replay("exact") assert len(calls)==12docs/assets/study.json+25
docs/explorer.js+1-1
docs/usage.md+2
src/study/cli.py+36-5
src/study/design.py+12-2
src/study/evaluate.py+61-7
src/study/final_review.py+22-8
src/study/matched_tables.py+5-4
src/study/report.py+10-4
tests/test_depth_extension.pyAdded+71