change-bench / scripts /recompute_entry01.py
Mimarin's picture
Change Bench v0 (manifest e9200d808c16f8ecde8589ab612ec99b2f178e6c7593f64b3ab7738637add2c6)
68d3a5d verified
Raw History Blame Contribute Delete
7.72 kB
"""recompute_entry01.py: recomputes entry 01's results table offline from the released files alone.
No GPU, no simulator, no network: Python 3 and NumPy. It reads
results/entry-01/inputs/calib-inputs/gate_a_reading_2026-10-11.json (the Gate A reading: N, Df by seed, T)
results/entry-01/inputs/told-inputs/seed{2,3,4}-Df-bridge_adapt.json (the learned arm's per-episode records)
results/entry-01/arms/identity.json, results/entry-01/arms/K-plan2.json (the valid run's two arms)
results/entry-01/told2.json (the valid run's own record, cross-checked)
and recomputes N, Df_bar, the told mean, the paired differences, the threshold Df_bar - T, the identity check, the
registered outcome and the learned arm's cost. Every recomputed value is compared with what told2.json recorded; the
script exits 1 on any disagreement.
Usage (from the package root or from scripts/):
python3 scripts/recompute_entry01.py [path/to/results/entry-01]
"""
import json
import os
import sys
from datetime import datetime
import numpy as np
import calib_logic as CL
import told2_logic as T2
SEEDS = CL.GATE_A_SEEDS
HERE = os.path.dirname(os.path.abspath(__file__))
DEFAULT_ENTRY_DIR = os.path.join(HERE, "..", "results", "entry-01")
AGREEMENT_TOLERANCE = 1e-9 # recomputed against recorded floats; both come from the same float64 arithmetic
def load_json(path):
with open(path) as f:
return json.load(f)
def load_entry(entry_dir):
"""Every released file the recomputation reads, by role."""
inputs = os.path.join(entry_dir, "inputs")
return {
"gate_a": load_json(os.path.join(inputs, "calib-inputs", "gate_a_reading_2026-10-11.json")),
"a_block": load_json(os.path.join(inputs, "calib-inputs", "seed2-Df-bridge_adapt.json")),
"df": {s: load_json(os.path.join(inputs, "told-inputs", f"seed{s}-Df-bridge_adapt.json")) for s in SEEDS},
"identity": load_json(os.path.join(entry_dir, "arms", "identity.json")),
"told": load_json(os.path.join(entry_dir, "arms", "K-plan2.json")),
"record": load_json(os.path.join(entry_dir, "told2.json")),
}
def minutes_between(started, finished):
fmt = "%Y-%m-%dT%H:%M:%SZ"
return (datetime.strptime(finished, fmt) - datetime.strptime(started, fmt)).total_seconds() / 60.0
def recompute(files):
"""The results table from the released inputs. Raises ValueError where the inputs contradict each other."""
comp = CL.comparators(files["gate_a"])
run = CL.RUN_TASK
df_episodes = {}
for s in SEEDS:
rec = files["df"][s]
if int(rec["seed"]) != s:
raise ValueError(f"the seed {s} Df record says seed {rec['seed']}")
after = rec["after"][run]
recomputed_mean = float(np.mean(after["episodes"]))
if abs(recomputed_mean - comp["Df_running_after_by_seed"][s]) > 1e-6:
raise ValueError(f"seed {s}: Df episodes average {recomputed_mean}, Gate A says {comp['Df_running_after_by_seed'][s]}")
df_episodes[s] = after["episodes"]
saved_a = files["a_block"]["A"][run]["episodes"]
if abs(float(np.mean(saved_a)) - comp["N"]) > 1e-6:
raise ValueError("the A block file and the Gate A reading disagree on N")
identity_episodes = files["identity"]["result"]["episodes"]
told_episodes = files["told"]["result"]["episodes"]
identity_check = CL.n_check(identity_episodes, saved_a)
told_mean = float(np.mean(told_episodes))
paired = {s: float(np.mean(np.array(told_episodes) - np.array(df_episodes[s]))) for s in SEEDS}
threshold = comp["Df_bar"] - comp["T"]
outcome = T2.outcome(identity_check["reproduces"], told_mean, comp["Df_bar"], comp["N"], comp["T"])
cost = {s: {k: files["df"][s]["accounting"][k] for k in ("decisions", "gradient_updates", "adapt_seconds")}
for s in SEEDS}
for s in SEEDS:
cost[s]["job_minutes"] = minutes_between(files["df"][s]["started"], files["df"][s]["finished"])
record = files["record"]
return {"N": comp["N"], "identity_mean": float(np.mean(identity_episodes)), "Df_bar": comp["Df_bar"],
"Df_by_seed": comp["Df_running_after_by_seed"], "T": comp["T"], "threshold": threshold,
"told_mean": told_mean, "told_sd": float(np.std(told_episodes)), # population sd, as the runner records it
"told_range": (min(told_episodes), max(told_episodes)), "paired": paired,
"identity_check": identity_check, "outcome": outcome, "Df_cost": cost,
"told_run_minutes": minutes_between(record["started"], record["finished"])}
def disagreements(table, record):
"""Every place the recomputed table differs from what the valid run recorded in told2.json."""
found = []
def close(name, a, b):
if abs(float(a) - float(b)) > AGREEMENT_TOLERANCE:
found.append(f"{name}: recomputed {a!r}, recorded {b!r}")
rc = record["comparators"]
close("N", table["N"], rc["N"])
close("Df_bar", table["Df_bar"], rc["Df_bar"])
close("T", table["T"], rc["T"])
for s in SEEDS:
close(f"Df seed {s}", table["Df_by_seed"][s], rc["Df_running_after_by_seed"][str(s)])
close(f"paired seed {s}", table["paired"][s], record["paired_vs_Df_after"][str(s)]["mean"])
close("told mean", table["told_mean"], record["arms"]["K-plan2"]["result"]["mean"])
close("told sd", table["told_sd"], record["arms"]["K-plan2"]["result"]["sd"])
close("identity max diff", table["identity_check"]["max_abs_diff"],
record["arms"]["identity"]["vs_saved_A_block"]["max_abs_diff"])
if table["outcome"] != record["outcome"]:
found.append(f"outcome: recomputed {table['outcome']!r}, recorded {record['outcome']!r}")
return found
def render(table):
lines = [
"Entry 01, recomputed offline from the released files",
f" N (stored old solution, Gate A A block) {table['N']:.4f} identity arm mean {table['identity_mean']:.4f}",
f" identity check vs saved A block max |diff| {table['identity_check']['max_abs_diff']:.4f}, "
f"reproduces {table['identity_check']['reproduces']}",
" Df by seed 2 / 3 / 4 " + " / ".join(f"{table['Df_by_seed'][s]:.4f}" for s in SEEDS),
f" Df_bar {table['Df_bar']:.4f}",
f" told planner K-plan2 mean {table['told_mean']:.4f} (sd {table['told_sd']:.1f}, "
f"episodes {table['told_range'][0]:.1f} to {table['told_range'][1]:.1f})",
" paired told minus Df, seed 2 / 3 / 4 " + " / ".join(f"{table['paired'][s]:+.4f}" for s in SEEDS),
f" T {table['T']:.4f}",
f" threshold Df_bar - T {table['threshold']:.4f}",
f" registered outcome {table['outcome']}",
" Df cost per seed (decisions, updates, adaptation s, job min)",
]
for s in SEEDS:
c = table["Df_cost"][s]
lines.append(f" seed {s}: {c['decisions']}, {c['gradient_updates']}, {c['adapt_seconds']:.0f}, {c['job_minutes']:.1f}")
lines.append(f" valid run wall time (both arms) {table['told_run_minutes']:.1f} min")
return "\n".join(lines)
def main(argv):
entry_dir = argv[1] if len(argv) > 1 else DEFAULT_ENTRY_DIR
files = load_entry(entry_dir)
table = recompute(files)
print(render(table))
found = disagreements(table, files["record"])
if found:
print("DISAGREES with told2.json:\n " + "\n ".join(found))
return 1
print("AGREES with told2.json on every recomputed value")
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv))