Datasets:
Formats:
parquet
Languages:
English
Size:
< 1K
Tags:
numerical-analysis
ordinary-differential-equations
solver-switching
sensitivity-analysis
research-artifacts
License:
Download source_artifacts/src/run_ablation.py from duj626/kea-ode-switching-sensitivity: direct link, hf CLI and curl.
- Browser
- Download file 10.3 kB
-
https://huggingface.co/datasets/duj626/kea-ode-switching-sensitivity/resolve/main/source_artifacts/src/run_ablation.py
- Command line
-
hf download hf://datasets/duj626/kea-ode-switching-sensitivity/source_artifacts/src/run_ablation.py
-
curl -L -o run_ablation.py https://huggingface.co/datasets/duj626/kea-ode-switching-sensitivity/resolve/main/source_artifacts/src/run_ablation.py
10.3 kB
| """Ablations for the trip-level calibration: sensitivity of the champion operating point. | |
| NOT part of the delivery: touches no pinned file and writes only | |
| results/ablation.json (candidates.json / comparison / delivery bytes are left | |
| untouched, so the delivery stays valid). Variants are derived from the frozen | |
| champion config in switcher.SWITCH_CONFIGS (single source of truth): | |
| shamp_dwell2 / shamp_dwell3 dwell band inside orego's @1e-6 run ceiling (max 3) | |
| shamp_dwell5 / shamp_dwell30 confirmation-rule (dwell) sensitivity | |
| shamp_thr_half / shamp_thr_2x threshold sensitivity (x0.5 / x2) | |
| Purpose: show whether the calibrated first-trip rule (threshold 7.911e-6, | |
| dwell 1) is a knife-edge point or a robust plateau -- the methodological core | |
| of the project is the trip-level calibration discipline, so its sensitivity is | |
| the natural ablation. dwell 2/3 complete the lower band: they are the deepest | |
| rules that still catch orego@1e-6 (post-gate runs there never exceed 3), so | |
| they measure the minimum achievable delay, and they pin down vdp5@1e-8's | |
| last-step dip length (<=4, since dwell 5/30 skip it). | |
| Crash safety mirrors run_candidates.py: atomic save after every solver block, | |
| flock single writer, resume iff (contract version, contentHash, methodsHash, | |
| grid_hash) all match; numpy scalars are converted for JSON. Comparisons in the | |
| summary read the frozen candidates.json (champion) and baseline.json (dopri5): | |
| same methodsHash guarantees both were produced by the same method code. | |
| Usage: .venv/bin/python src/run_ablation.py [variant ...] (default: all) | |
| """ | |
| import fcntl, hashlib, json, os, sys, time | |
| sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) | |
| import numpy as np | |
| import contract | |
| from score import GAMMA, BUDGET, TOLS, load_refs, get_ref_y | |
| from problems import PROBLEMS | |
| from switcher import SWITCH_CONFIGS, SwitchConfig, solve_switched | |
| ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | |
| OUT = os.path.join(ROOT, "results", "ablation.json") | |
| LOCK = os.path.join(ROOT, "results", "ablation.lock") | |
| CHAMP = "switch_S_shamp" | |
| STIFF = ["vdp100", "rober", "orego", "hires", "bruss2d"] | |
| NONSTIFF = ["vdp5", "bruss", "lotka", "kepler", "rossler"] | |
| TOLK = [f"tol_{t:g}" for t in sorted(TOLS.values())] | |
| def build_variants(): | |
| base = SWITCH_CONFIGS[CHAMP] | |
| def mk(name, **kw): | |
| d = dict(detector=base.detector, threshold=base.threshold, probe_steps=base.probe_steps, | |
| implicit=base.implicit, direction=base.direction, dwell=base.dwell) | |
| d.update(kw) | |
| return SwitchConfig(name, **d) | |
| return { | |
| "shamp_dwell2": mk("shamp_dwell2", dwell=2), | |
| "shamp_dwell3": mk("shamp_dwell3", dwell=3), | |
| "shamp_dwell5": mk("shamp_dwell5", dwell=5), | |
| "shamp_dwell30": mk("shamp_dwell30", dwell=30), | |
| "shamp_thr_half": mk("shamp_thr_half", threshold=base.threshold * 0.5), | |
| "shamp_thr_2x": mk("shamp_thr_2x", threshold=base.threshold * 2.0), | |
| } | |
| def grid_params(variants): | |
| return {n: {"detector": c.detector, "threshold": c.threshold, "probe_steps": c.probe_steps, | |
| "dwell": c.dwell, "implicit": c.implicit, "direction": c.direction} | |
| for n, c in variants.items()} | |
| def grid_hash(gp): | |
| return hashlib.sha256(json.dumps(gp, sort_keys=True).encode()).hexdigest()[:16] | |
| def _jsonable(o): | |
| if hasattr(o, "item"): | |
| try: | |
| return o.item() | |
| except Exception: | |
| pass | |
| return str(o) | |
| def save_atomic(out): | |
| tmp = OUT + ".tmp" | |
| with open(tmp, "w") as f: | |
| json.dump(out, f, indent=2, default=_jsonable) | |
| os.replace(tmp, OUT) | |
| def acquire_lock(): | |
| h = open(LOCK, "a+") | |
| try: | |
| fcntl.flock(h, fcntl.LOCK_EX | fcntl.LOCK_NB) | |
| except OSError: | |
| h.close() | |
| try: | |
| other = open(LOCK).read().strip() | |
| except OSError: | |
| other = "?" | |
| print(f"skip: another ablation run is active (lock held by pid {other})", flush=True) | |
| return None | |
| h.seek(0); h.truncate(); h.write(str(os.getpid())); h.flush() | |
| return h | |
| def load_resumable(v, h, mh, gh): | |
| if not os.path.exists(OUT): | |
| return None | |
| try: | |
| out = json.load(open(OUT)) | |
| c = out.get("contract", {}) | |
| if (c.get("version") == v and c.get("contentHash") == h | |
| and c.get("methodsHash") == mh and out.get("grid_hash") == gh): | |
| return out | |
| except Exception: | |
| pass | |
| return None | |
| def eval_variant(cfg, tol, verbose=True): | |
| """One variant x one tolerance over all verified problems (scoring contract parity).""" | |
| works, details = [], {} | |
| refs = load_refs() | |
| for name, cls in PROBLEMS.items(): | |
| if name not in refs: | |
| continue # excluded problem (no verifiable reference) | |
| if refs[name].get("ok") is not True: | |
| raise RuntimeError(f"problem {name} has no verified reference") | |
| p = cls() | |
| ok, err, nfev, njev, det = solve_switched(p, tol, cfg, get_ref_y(name)) | |
| work = float(nfev + GAMMA * njev if ok else BUDGET + GAMMA * njev) | |
| works.append(work) | |
| details[name] = { | |
| "ok": bool(ok), "err": None if err == np.inf else float(err), | |
| "nfev": int(nfev), "njev": int(njev), "work": work, | |
| "tripped": bool(det.get("tripped", False)), | |
| "trip_step": det.get("trip_step"), "t_switch": det.get("t_switch"), | |
| "over_budget": bool(det.get("over_budget", False)), | |
| "msg": str(det.get("msg", det.get("status", "")))[:80], | |
| } | |
| if verbose: | |
| print(f"# [{cfg.name}] {name:8s} ok={int(ok)} " | |
| f"err={err if err == np.inf else f'{err:.2e}':>12} " | |
| f"nfev={nfev:>9} njev={njev:>5} work={work:>10.1f} " | |
| f"tripped={int(details[name]['tripped'])} trip_step={details[name]['trip_step']}", | |
| flush=True) | |
| metric = float(np.mean(np.log10(works))) | |
| if verbose: | |
| print(f"METRIC [{cfg.name}] work_log={metric}", flush=True) | |
| return {"metric": metric, "works": works, "per_problem": details} | |
| def summarize(out, names): | |
| """Compare every completed variant against the frozen champion + dopri5. Read-only on frozen artifacts.""" | |
| if not all(all(tk in out["solvers"].get(n, {}) for tk in TOLK) for n in names): | |
| return None | |
| cand = json.load(open(os.path.join(ROOT, "results", "candidates.json")))[ "solvers"][CHAMP] | |
| base = json.load(open(os.path.join(ROOT, "results", "baseline.json")))["solvers"]["dopri5"] | |
| def works_of(blk): | |
| return {tk: {p: v["work"] for p, v in blk[tk]["per_problem"].items()} for tk in TOLK} | |
| champ_w, d5_w = works_of(cand), works_of(base) | |
| champ_m = {tk: cand[tk]["metric"] for tk in TOLK} | |
| d5_m = {tk: base[tk]["metric"] for tk in TOLK} | |
| summ = {"vs": {"champion": f"results/candidates.json solvers.{CHAMP}", | |
| "reference": "results/baseline.json solvers.dopri5"}, | |
| "variants": {}} | |
| for n in names: | |
| blk = out["solvers"][n] | |
| vw = {tk: {p: v["work"] for p, v in blk[tk]["per_problem"].items()} for tk in TOLK} | |
| vm = {tk: blk[tk]["metric"] for tk in TOLK} | |
| worst = max((vw[tk][p] / d5_w[tk][p], p, tk) for p in NONSTIFF for tk in TOLK) | |
| wins = {p: sum(1 for tk in TOLK if vw[tk][p] < d5_w[tk][p] * (1 - 1e-12)) for p in STIFF + NONSTIFF} | |
| trips = {tk: {p: blk[tk]["per_problem"][p]["trip_step"] for p in STIFF + NONSTIFF | |
| if blk[tk]["per_problem"][p]["tripped"]} for tk in TOLK} | |
| summ["variants"][n] = { | |
| "metric": vm, | |
| "dmetric_vs_champion": {tk: vm[tk] - champ_m[tk] for tk in TOLK}, | |
| "dmetric_vs_dopri5": {tk: vm[tk] - d5_m[tk] for tk in TOLK}, | |
| "metric_mean": float(np.mean([vm[tk] for tk in TOLK])), | |
| "stiff_wins_vs_dopri5": [p for p in STIFF if wins[p] >= 2], | |
| "worst_non_stiff_ratio_vs_dopri5": {"problem": worst[1], "tol": worst[2], "ratio": float(worst[0])}, | |
| "trips": trips, | |
| } | |
| out["summary"] = summ | |
| return summ | |
| def main(): | |
| lock = acquire_lock() | |
| if lock is None: | |
| return 0 | |
| v, h = contract.freeze() | |
| mh = contract.methods_hash() | |
| variants = build_variants() | |
| gp = grid_params(variants) | |
| gh = grid_hash(gp) | |
| names = [a for a in sys.argv[1:] if a in variants] or list(variants) | |
| out = load_resumable(v, h, mh, gh) | |
| if out is None: | |
| out = {"note": "operating-point sensitivity ablations; derived from frozen switch_S_shamp; " | |
| "not part of the delivery", | |
| "contract": {"version": v, "contentHash": h, "methodsHash": mh}, | |
| "grid_hash": gh, "variants": {n: gp[n] for n in names}, | |
| "solvers": {}, "run_at": time.time()} | |
| print(f"fresh run: grid_hash={gh}", flush=True) | |
| else: | |
| print("resume: file matches contract + methods + grid", flush=True) | |
| for n in names: | |
| out["variants"].setdefault(n, gp[n]) | |
| for n in names: | |
| block = out.get("solvers", {}).get(n, {}) | |
| if block and all(tk in block for tk in TOLK): | |
| continue # resume: this block is complete | |
| out["solvers"][n] = {} | |
| for tol in sorted(TOLS.values()): | |
| t0 = time.time() | |
| r = eval_variant(variants[n], tol, verbose=True) | |
| r["seconds"] = round(time.time() - t0, 1) | |
| out["solvers"][n][f"tol_{tol:g}"] = r | |
| print(f"# [{n}] tol_{tol:g} block done in {r['seconds']}s", flush=True) | |
| out["updated_at"] = time.time() | |
| save_atomic(out) | |
| print(f"checkpoint saved after {n} -> {OUT}", flush=True) | |
| summ = summarize(out, names) | |
| if summ is not None: | |
| save_atomic(out) | |
| for n in names: | |
| s = summ["variants"][n] | |
| print(f"summary [{n}] mean={s['metric_mean']:.4f} " | |
| f"(champ drift {s['dmetric_vs_champion'][TOLK[0]]:+.4f}/{s['dmetric_vs_champion'][TOLK[1]]:+.4f}/{s['dmetric_vs_champion'][TOLK[2]]:+.4f}) " | |
| f"stiff_wins={len(s['stiff_wins_vs_dopri5'])}/5 " | |
| f"worst_non={s['worst_non_stiff_ratio_vs_dopri5']['ratio']:.4f}", flush=True) | |
| print("saved", OUT) | |
| return 0 | |
| if __name__ == "__main__": | |
| sys.exit(main()) | |