Download flysim/scripts/recalibrated_rule_validation.py from nynefold/flysim-malecns: direct link, hf CLI and curl.
- Browser
- Download file 13.4 kB
-
https://huggingface.co/datasets/nynefold/flysim-malecns/resolve/main/flysim/scripts/recalibrated_rule_validation.py
- Command line
-
hf download hf://datasets/nynefold/flysim-malecns/flysim/scripts/recalibrated_rule_validation.py
-
curl -L -o recalibrated_rule_validation.py https://huggingface.co/datasets/nynefold/flysim-malecns/resolve/main/flysim/scripts/recalibrated_rule_validation.py
13.4 kB
| """Validation of the recalibrated engine-check rule (records/preregistration.md, | |
| section 9), using our engine only. | |
| No Brian2 data is read here: the rule was validated without the engine check's Brian2 | |
| artifacts. Trials come from the reserved validation range (``SET_VALIDATION``), | |
| which no preregistered or exploratory comparison ever uses. | |
| # 1. our engine, the null pool: trials 5000-5149 of every condition | |
| python -m flysim.validation.engine_check run --fafb DIR --out runs/null --trials 150 \ | |
| --first-trial 5000 | |
| # 2. perturbed engines, trials 5200-5229 (seeds disjoint from the pool) | |
| python scripts/recalibrated_rule_validation.py perturb --fafb DIR --out runs/bug \ | |
| --perturbation refractory-bug | |
| python scripts/recalibrated_rule_validation.py perturb --fafb DIR --out runs/w105 \ | |
| --perturbation wsyn=1.05 | |
| # 3. null test: false-fail rates of both rules when there is no engine difference | |
| python scripts/recalibrated_rule_validation.py null --fafb DIR --runs runs/null --reps 200 | |
| # 4. detection: perturbed "ours" against resampled pools of the correct engine | |
| python scripts/recalibrated_rule_validation.py detect --fafb DIR --runs runs/null \ | |
| --perturbed runs/bug --reps 50 | |
| Null test, per replicate: a random permutation of the 150 pool trials gives a fake | |
| Brian2 pool (the first 60; set A is the first 30 of those) and a disjoint fake | |
| "ours" (the next 30). Three rules judge all 17 conditions: the recalibrated rule | |
| (``recalibrated``: splits of A ∪ ours), its first design (``recalibrated_design1``: | |
| splits of the Brian2 pool A ∪ B, rejected after this test) and the original rule of | |
| section 2.3 (``original``). A replicate is a false | |
| fail if any of the 68 condition checks fails. Replicates share trials (150 per | |
| condition), so they are not independent and the binomial interval is a lower bound | |
| on the uncertainty. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import dataclasses | |
| import json | |
| import multiprocessing as mp | |
| import sys | |
| import time | |
| from pathlib import Path | |
| import numba | |
| import numpy as np | |
| from flysim.engine import CpuEngine | |
| from flysim.engine import cpu as cpu_mod | |
| from flysim.validation import engine_check as ec | |
| from flysim.validation import fafb as fafb_mod | |
| from flysim.validation import metrics | |
| from flysim.validation import recalibrated as rc | |
| from flysim.validation.manifest import conditions, load_cases | |
| from flysim.validation.runs import RunSet | |
| NULL_TRIALS = range(5000, 5150) | |
| PERTURBED_TRIALS = range(5200, 5230) | |
| REPLICATE_SEED = 20261105 | |
| # -- perturbed engines ------------------------------------------------------------ | |
| def _buggy_run_steps(s0, s1, v, g, last, rfc, v_0, v_rst, v_th, a, b, c, w_syn, w_input, | |
| delay, indptr, indices, weights, in_ptr, in_idx, log, log_ptr, log_len): | |
| """The kernel before the refractory-input fix (validation log, 2026-11-03): input | |
| reaching a refractory neuron is not dropped but accumulates in ``g`` (frozen) and | |
| acts when the refractory period ends. Everything else is the production kernel.""" | |
| n = v.shape[0] | |
| zero = v.dtype.type(0) | |
| n_in_steps = in_ptr.shape[0] - 1 | |
| for s in range(s0, s1): | |
| if log_len + n > log.shape[0]: | |
| return s, log_len | |
| start = log_len | |
| log_ptr[s] = start | |
| for i in range(n): | |
| if s - last[i] < rfc[i]: | |
| continue | |
| vi = v[i] | |
| gi = g[i] | |
| if gi == zero and vi == v_0: | |
| continue | |
| vi = v_0 + (vi - v_0) * a + gi * b | |
| g[i] = gi * c | |
| v[i] = vi | |
| if vi > v_th: | |
| log[log_len] = i | |
| log_len += 1 | |
| last[i] = s | |
| log_ptr[s + 1] = log_len | |
| sd = s - delay | |
| if sd >= 0: | |
| for k in range(log_ptr[sd], log_ptr[sd + 1]): | |
| j = log[k] | |
| for e in range(indptr[j], indptr[j + 1]): | |
| g[indices[e]] += w_syn * weights[e] # the bug: no refractory guard | |
| if s < n_in_steps: | |
| for k in range(in_ptr[s], in_ptr[s + 1]): | |
| v[in_idx[k]] += w_input | |
| for k in range(start, log_len): | |
| i = log[k] | |
| v[i] = v_rst | |
| g[i] = zero | |
| return s1, log_len | |
| _w: dict = {} | |
| def _init_perturbed(fafb_dir: str, perturbation: str) -> None: | |
| params = ec.PARAMS | |
| if perturbation == "refractory-bug": | |
| cpu_mod.run_steps = _buggy_run_steps # this worker process only | |
| elif perturbation.startswith("wsyn="): | |
| params = dataclasses.replace(ec.PARAMS, w_syn=ec.PARAMS.w_syn | |
| * float(perturbation.split("=", 1)[1])) | |
| else: | |
| raise SystemExit(f"unknown perturbation {perturbation!r}") | |
| f = fafb_mod.load(Path(fafb_dir)) | |
| eng = CpuEngine(np.float32, skip_rest=False) # the reference kernel the gate ran on | |
| eng.load(f.matrix, params) | |
| _w.update(fafb=f, engine=eng, cases=load_cases(), params=params) | |
| def _perturbed_task(args: tuple[str, int]): | |
| key, trial = args | |
| cond = next(c for c in conditions() if c.key == key) | |
| steps, neurons = ec.run_trial(cond, trial, _w["fafb"], _w["engine"], _w["cases"]) | |
| return key, trial, steps, neurons | |
| def cmd_perturb(a: argparse.Namespace) -> int: | |
| conds = [c for c in conditions() if not a.only or c.key in a.only or c.case in a.only] | |
| tasks = [(c.key, t) for c in conds for t in PERTURBED_TRIALS] | |
| done: dict[str, list] = {c.key: [] for c in conds} | |
| n_neurons = len(fafb_mod.read_root_ids(a.fafb)) | |
| with mp.get_context("fork").Pool(a.jobs, initializer=_init_perturbed, | |
| initargs=(str(a.fafb), a.perturbation)) as pool: | |
| for key, trial, steps, neurons in pool.imap_unordered(_perturbed_task, tasks): | |
| done[key].append((trial, steps, neurons)) | |
| if len(done[key]) == len(PERTURBED_TRIALS): | |
| rs = RunSet.from_trials(done[key], n_neurons=n_neurons, n_steps=ec.N_STEPS, | |
| dt_ms=ec.PARAMS.dt, | |
| meta={"perturbation": a.perturbation, "key": key}) | |
| stem = next(c for c in conds if c.key == key).file_stem | |
| rs.save(a.out / f"{stem}.npz") | |
| print(f" {key}: {len(rs.neurons)} spikes", flush=True) | |
| return 0 | |
| # -- judging ------------------------------------------------------------------------ | |
| def _renumbered(rs: RunSet, trials: np.ndarray) -> RunSet: | |
| sub = rs.subset(trials) | |
| return dataclasses.replace(sub, trials=np.arange(len(trials), dtype=np.int32)) | |
| def _readouts(fafb_dir: Path) -> dict[str, int]: | |
| root_ids = fafb_mod.read_root_ids(fafb_dir) | |
| return {name: int(np.flatnonzero(root_ids == rid)[0]) | |
| for name, rid in load_cases()["readouts"].items()} | |
| def _judge_all(c, ours_rs: RunSet, pool_rs: RunSet, ro: int, ours_arr, pool_arr, | |
| masks: np.ndarray, design1: bool) -> dict[str, dict]: | |
| """The rules on one comparison. ``pool_*`` is the (fake) Brian2 pool of 60, set A | |
| first.""" | |
| a = pool_arr.take(range(rc.HALF)) | |
| new = rc.judge_rule(c.key, ours_arr, a, masks) | |
| old = metrics.compare_condition(c.key, ours_rs, pool_rs, ro) | |
| out = {"recalibrated": {k.name: k.passed for k in new.checks}, | |
| "original": {k.name: k.passed for k in old.checks}, | |
| "recalibrated_values": {k.name: [k.value, k.threshold] for k in new.checks}} | |
| if design1: | |
| first = rc.judge(c.key, ours_arr, a, rc.floors(pool_arr, masks)) | |
| out["recalibrated_design1"] = {k.name: k.passed for k in first.checks} | |
| return out | |
| def _summarise(per_rep: list[dict], label: str) -> dict: | |
| out: dict = {"label": label, "reps": len(per_rep), | |
| "conditions": len(per_rep[0]) if per_rep else 0} | |
| rules = [r for r in ("recalibrated", "recalibrated_design1", "original") | |
| if per_rep and all(r in cond for cond in per_rep[0].values())] | |
| for rule in rules: | |
| any_fail = [any(not ok for cond in rep.values() for ok in cond[rule].values()) | |
| for rep in per_rep] | |
| per_check: dict[str, int] = {} | |
| for rep in per_rep: | |
| for key, cond in rep.items(): | |
| for name, ok in cond[rule].items(): | |
| per_check[f"{key} {name}"] = per_check.get(f"{key} {name}", 0) + (not ok) | |
| k, n = int(sum(any_fail)), len(any_fail) | |
| out[rule] = {"replicates_with_a_fail": k, "rate": k / n, | |
| "wilson95": _wilson(k, n), | |
| "checks_failed": int(sum(per_check.values())), | |
| "failing_checks": {c: v for c, v in sorted(per_check.items()) if v}} | |
| return out | |
| def _wilson(k: int, n: int, z: float = 1.96) -> list[float]: | |
| p = k / n | |
| d = 1 + z * z / n | |
| mid = (p + z * z / (2 * n)) / d | |
| half = z * np.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / d | |
| return [round(float(mid - half), 4), round(float(mid + half), 4)] | |
| def _selected(only: list[str] | None): | |
| return [c for c in conditions() if not only or c.key in only or c.case in only] | |
| def _load(fafb_dir: Path, directory: Path, c, trials: range): | |
| ro = _readouts(fafb_dir)[c.readout] | |
| rs = RunSet.load(directory / f"{c.file_stem}.npz").subset(trials) | |
| return rs, ro, rc.trial_arrays(rs, ro) | |
| def _condition_job(args: tuple) -> tuple[str, list[dict], float]: | |
| """One condition, all replicates. ``perturbed`` None: null test; else detection.""" | |
| key, fafb_dir, runs, perturbed, reps, design1 = args | |
| t0 = time.perf_counter() | |
| c = next(c for c in conditions() if c.key == key) | |
| rs, ro, arr = _load(fafb_dir, runs, c, NULL_TRIALS) | |
| masks = rc.split_masks() | |
| out = [] | |
| if perturbed is None: | |
| rng = np.random.default_rng(REPLICATE_SEED) | |
| for _ in range(reps): | |
| p = rng.permutation(len(NULL_TRIALS)) | |
| pool_idx, ours_idx = p[:60], p[60:90] | |
| out.append(_judge_all(c, _renumbered(rs, rs.trials[ours_idx]), | |
| _renumbered(rs, rs.trials[pool_idx]), ro, | |
| arr.take(ours_idx), arr.take(pool_idx), masks, design1)) | |
| else: | |
| bad_rs, _, bad_arr = _load(fafb_dir, perturbed, c, PERTURBED_TRIALS) | |
| bad_rs = _renumbered(bad_rs, bad_rs.trials) | |
| rng = np.random.default_rng(REPLICATE_SEED + 1) | |
| for _ in range(reps): | |
| pool_idx = rng.permutation(len(NULL_TRIALS))[:60] | |
| out.append(_judge_all(c, bad_rs, _renumbered(rs, rs.trials[pool_idx]), ro, | |
| bad_arr, arr.take(pool_idx), masks, design1)) | |
| return key, out, time.perf_counter() - t0 | |
| def _run_jobs(a: argparse.Namespace, perturbed: Path | None) -> list[dict]: | |
| """Replicate i uses the same draw in every condition (the replicate seed is per | |
| condition, and conditions' trials are independent), so a replicate is one full | |
| 17-condition gate.""" | |
| jobs = [(c.key, a.fafb, a.runs, perturbed, a.reps, a.design1) for c in _selected(a.only)] | |
| per_rep: list[dict] = [{} for _ in range(a.reps)] | |
| with mp.get_context("fork").Pool(a.jobs) as pool: | |
| for key, results, secs in pool.imap_unordered(_condition_job, jobs): | |
| for i, r in enumerate(results): | |
| per_rep[i][key] = r | |
| print(f" {key}: {secs:.0f} s", flush=True) | |
| return per_rep | |
| def cmd_null(a: argparse.Namespace) -> int: | |
| per_rep = _run_jobs(a, None) | |
| _write(a.out, _summarise(per_rep, "null: correct engine on both sides"), per_rep) | |
| return 0 | |
| def cmd_detect(a: argparse.Namespace) -> int: | |
| per_rep = _run_jobs(a, a.perturbed) | |
| _write(a.out, _summarise(per_rep, f"detection: {a.perturbed.name} against the correct " | |
| "engine"), per_rep) | |
| return 0 | |
| def _write(out: Path | None, summary: dict, per_rep: list[dict]) -> None: | |
| text = json.dumps(summary, indent=1) | |
| print(text) | |
| if out: | |
| out.write_text(json.dumps({"summary": summary, "replicates": per_rep}, indent=0)) | |
| def main(argv: list[str] | None = None) -> int: | |
| p = argparse.ArgumentParser() | |
| sub = p.add_subparsers(dest="cmd", required=True) | |
| pr = sub.add_parser("perturb") | |
| pr.add_argument("--fafb", type=Path, required=True) | |
| pr.add_argument("--out", type=Path, required=True) | |
| pr.add_argument("--perturbation", required=True, help="refractory-bug | wsyn=<factor>") | |
| pr.add_argument("--jobs", type=int, default=mp.cpu_count()) | |
| pr.add_argument("--only", nargs="*") | |
| for name in ("null", "detect"): | |
| q = sub.add_parser(name) | |
| q.add_argument("--fafb", type=Path, required=True) | |
| q.add_argument("--runs", type=Path, required=True) | |
| q.add_argument("--reps", type=int, default=200 if name == "null" else 50) | |
| q.add_argument("--only", nargs="*") | |
| q.add_argument("--out", type=Path) | |
| q.add_argument("--jobs", type=int, default=mp.cpu_count()) | |
| q.add_argument("--design1", action="store_true", | |
| help="also judge by the rejected first design (splits of A ∪ B)") | |
| if name == "detect": | |
| q.add_argument("--perturbed", type=Path, required=True) | |
| a = p.parse_args(argv) | |
| return {"perturb": cmd_perturb, "null": cmd_null, "detect": cmd_detect}[a.cmd](a) | |
| if __name__ == "__main__": | |
| sys.exit(main()) | |