Download src/clsa/eval/experiments.py from fahadhafeezofficial/clsa-code: direct link, hf CLI and curl.
- Browser
- Download file 27.3 kB
-
https://huggingface.co/datasets/fahadhafeezofficial/clsa-code/resolve/main/src/clsa/eval/experiments.py
- Command line
-
hf download hf://datasets/fahadhafeezofficial/clsa-code/src/clsa/eval/experiments.py
-
curl -L -o experiments.py https://huggingface.co/datasets/fahadhafeezofficial/clsa-code/resolve/main/src/clsa/eval/experiments.py
27.3 kB
| # Copyright (c) 2026 CLSA contributors | |
| # SPDX-License-Identifier: MIT | |
| """E1-E9 runners. Every number here comes from a results file. | |
| Each function returns a JSON-serialisable dict and is called by a thin script in | |
| experiments/. Nothing is hand-written into a table. | |
| """ | |
| from __future__ import annotations | |
| import json | |
| import time | |
| import tracemalloc | |
| import joblib | |
| import numpy as np | |
| import torch | |
| from clsa.agents.policies import Ctx, build_policies | |
| from clsa.controller.risk import ( | |
| brier, | |
| expected_calibration_error, | |
| feasibility_abstention, | |
| reliability_curve, | |
| selective_risk, | |
| ) | |
| from clsa.eval.harness import budget_report, build_views, run_policy | |
| from clsa.eval.metrics import ( | |
| cluster_bootstrap, | |
| correct_rate, | |
| harm_per_dollar, | |
| harm_rate, | |
| irreversible_rate, | |
| paired_bootstrap, | |
| report, | |
| success_per_dollar, | |
| success_rate, | |
| ) | |
| from clsa.transcoder.dataset import DERIVED, load_dataset | |
| from clsa.util import load_config | |
| from clsa.world_model.train import load_model, probe_predict, predict_scores | |
| PRIMARY_SPLITS = {"test"} | |
| TRANSFER_SPLITS = {"heldout"} | |
| def _probes(backbone: str) -> dict: | |
| out = {} | |
| d = DERIVED / backbone.replace("/", "__") | |
| for name in ("dense", "sparse", "behaviour"): | |
| p = d / f"probe_{name}.joblib" | |
| if p.exists(): | |
| out[name] = joblib.load(p) | |
| return out | |
| def setup(backbone_key: str = "primary") -> dict: | |
| tcfg = load_config("transcoder") | |
| ccfg = load_config("controller") | |
| name = tcfg["backbones"].get(backbone_key, backbone_key) | |
| wm, rh, blob, ds = load_model(name) | |
| views = build_views(ds) | |
| probes = _probes(name) | |
| ctx = Ctx( | |
| world_model=wm, | |
| risk_head=rh, | |
| probes=probes, | |
| thresholds=blob["thresholds"], | |
| alpha=float(ccfg.get("alpha", 0.1)), | |
| budget_tokens=float(ccfg.get("B_tokens", 1200)), | |
| feature_mask=np.asarray(blob.get("feature_mask", []), dtype=int), | |
| seed=int(ccfg.get("seed", 0)), | |
| costs={k: float(v) for k, v in ccfg.get("costs", {}).items()} | |
| | {"rollout": float(ccfg.get("costs", {}).get("rollout", 12.0))}, | |
| ) | |
| return { | |
| "name": name, | |
| "wm": wm, | |
| "rh": rh, | |
| "blob": blob, | |
| "ds": ds, | |
| "views": views, | |
| "probes": probes, | |
| "ctx": ctx, | |
| "cfg": ccfg, | |
| "tcfg": tcfg, | |
| } | |
| def _bootstrap_all(rows: list[dict], seed: int = 0) -> dict: | |
| fns = { | |
| "harm_rate": harm_rate, | |
| "irreversible_rate": irreversible_rate, | |
| "success_rate": success_rate, | |
| "correct_rate": correct_rate, | |
| "execute_rate": lambda r: float(np.mean([x["decision"] == "execute" for x in r])), | |
| "false_abort_rate": lambda r: float( | |
| np.mean([x["decision"] != "execute" for x in r if x.get("safe_available")]) | |
| ) | |
| if any(x.get("safe_available") for x in r) | |
| else float("nan"), | |
| "tokens_per_decision": lambda r: float(np.mean([x["tokens"] for x in r])), | |
| "harm_per_dollar": harm_per_dollar, | |
| "success_per_dollar": success_per_dollar, | |
| } | |
| return {k: cluster_bootstrap(rows, f, seed=seed) for k, f in fns.items()} | |
| def e1_main(backbone_key: str = "primary", splits: set[str] | None = None) -> dict: | |
| """E1: CLSA versus every baseline at the same budget, paired by state.""" | |
| s = setup(backbone_key) | |
| splits = splits or (PRIMARY_SPLITS | TRANSFER_SPLITS) | |
| policies = build_policies(s["ctx"]) | |
| rows = {name: run_policy(p, s["views"], splits) for name, p in policies.items()} | |
| per_policy = {} | |
| for name, r in rows.items(): | |
| per_policy[name] = { | |
| "point": report(r), | |
| "ci": _bootstrap_all(r), | |
| "budget": budget_report(r), | |
| } | |
| comparisons = {} | |
| for base in ("language_first", "dense_probe", "clsa_no_dynamics"): | |
| comparisons[base] = { | |
| "harm_rate": paired_bootstrap(rows["clsa"], rows[base], harm_rate), | |
| "correct_rate": paired_bootstrap(rows["clsa"], rows[base], correct_rate), | |
| "irreversible_rate": paired_bootstrap(rows["clsa"], rows[base], irreversible_rate), | |
| "success_per_dollar": paired_bootstrap( | |
| rows["clsa"], rows[base], success_per_dollar | |
| ), | |
| } | |
| by_family = {} | |
| for fam in sorted({v.family for v in s["views"]}): | |
| sub = [v for v in s["views"] if v.family == fam] | |
| by_family[fam] = { | |
| name: report(run_policy(p, sub, splits)) for name, p in policies.items() | |
| } | |
| return { | |
| "backbone": s["name"], | |
| "splits": sorted(splits), | |
| "n_states": len({v.state_key for v in s["views"] if v.split in splits}), | |
| "per_policy": per_policy, | |
| "paired_vs_clsa": comparisons, | |
| "by_family": by_family, | |
| "raw_rows": {k: v for k, v in rows.items()}, | |
| } | |
| def episode_sequences(ds: dict) -> list[list[int]]: | |
| """Ordered state indices along each episode, requiring consecutive steps.""" | |
| by_state: dict[str, int] = {} | |
| for i, key in enumerate(ds["state_key"]): | |
| by_state[str(key)] = int(ds["state_index_item"][i]) | |
| steps: dict[str, int] = {} | |
| for key in by_state: | |
| ep, st = str(key).rsplit("|s", 1) | |
| steps[str(key)] = int(st) | |
| eps: dict[str, list[tuple[int, str]]] = {} | |
| for key, sidx in by_state.items(): | |
| ep = str(key).rsplit("|s", 1)[0] | |
| eps.setdefault(ep, []).append((steps[key], key)) | |
| seqs = [] | |
| for ep, items in eps.items(): | |
| items.sort() | |
| seq = [by_state[k] for _, k in items] | |
| if len(seq) >= 2: | |
| seqs.append(seq) | |
| return seqs | |
| def e2_world_model(backbone_key: str = "primary") -> dict: | |
| """E2: per-modality error, counterfactual consistency, horizon gap.""" | |
| s = setup(backbone_key) | |
| ds, wm, rh = s["ds"], s["wm"], s["rh"] | |
| layout = ds["layout"] | |
| n_z, n_b, n_e, n_img, n_tool = layout | |
| S = np.concatenate([ds["z"], ds["b"], ds["e"], ds["image"], ds["tool"]], axis=1) | |
| S_t = torch.as_tensor(S, dtype=torch.float32) | |
| A_t = torch.as_tensor(ds["action"], dtype=torch.float32) | |
| blocks = { | |
| "text": slice(0, n_z), | |
| "belief": slice(n_z, n_z + n_b), | |
| "evidence": slice(n_z + n_b, n_z + n_b + n_e), | |
| "image": slice(n_z + n_b + n_e, n_z + n_b + n_e + n_img), | |
| "tool_state": slice(n_z + n_b + n_e + n_img, S.shape[1]), | |
| } | |
| pairs = ds["pairs"] | |
| te = np.array([sp in ("test", "heldout") for sp in ds["split"]]) | |
| pairs_te = pairs[te[pairs[:, 0]]] if len(pairs) else pairs | |
| out: dict = {"backbone": s["name"], "n_transitions": int(len(pairs_te))} | |
| if len(pairs_te) == 0: | |
| return {**out, "blocked": "no transitions in the evaluation splits"} | |
| deltas = {"dz": "text", "db": "belief", "de": "evidence", "dimg": "image", "dtool": "tool_state"} | |
| seqs = episode_sequences(ds) | |
| te_states = set(int(i) for i in pairs_te[:, 0]) | |
| horizons = {} | |
| with torch.no_grad(): | |
| for horizon in (1, 2, 3): | |
| errs: dict[str, list[float]] = {k: [] for k in blocks} | |
| n_used = 0 | |
| for seq in seqs: | |
| for a_i in range(len(seq) - horizon): | |
| i0 = seq[a_i] | |
| if i0 not in te_states: | |
| continue | |
| cur = S_t[i0].clone().unsqueeze(0) | |
| for h in range(horizon): | |
| act_idx = seq[a_i + h] | |
| a = A_t[act_idx].unsqueeze(0) | |
| pred = wm(cur, a) | |
| nxt = cur.clone() | |
| for dkey, bkey in deltas.items(): | |
| sl = blocks[bkey] | |
| nxt[:, sl] = cur[:, sl] + pred[dkey] | |
| cur = nxt | |
| target = S_t[seq[a_i + horizon]].unsqueeze(0) | |
| for bkey, sl in blocks.items(): | |
| errs[bkey].append(float(torch.mean((cur[:, sl] - target[:, sl]) ** 2))) | |
| n_used += 1 | |
| if n_used: | |
| horizons[str(horizon)] = { | |
| "n": n_used, | |
| "mse": {k: float(np.mean(v)) for k, v in errs.items()}, | |
| "rmse": {k: float(np.sqrt(np.mean(v))) for k, v in errs.items()}, | |
| } | |
| out["horizons"] = horizons | |
| out["mse_h1"] = horizons.get("1", {}).get("mse", {}) | |
| sc = predict_scores(wm, rh, ds) | |
| p = sc["p_harm"][te] | |
| harm = ds["harm"][te] | |
| succ = ds["success"][te] | |
| out["cf_consistency"] = float(((p > 0.5) == (harm > 0.5)).mean()) | |
| out["cf_brier"] = brier(p, (harm > 0.5).astype(float)) | |
| out["success_consistency"] = float( | |
| ((sc["p_success"][te] > 0.5) == (succ > 0.5)).mean() | |
| ) | |
| out["hallucinated_world_rate"] = float(np.mean((p > 0.5) & (harm <= 0.5))) | |
| out["predicted_harm_mean"] = float(p.mean()) | |
| out["observed_harm_rate"] = float((harm > 0.5).mean()) | |
| return out | |
| def e3_budget(backbone_key: str = "primary") -> dict: | |
| """E3: success-per-dollar and harm-per-dollar Pareto curves.""" | |
| s = setup(backbone_key) | |
| splits = PRIMARY_SPLITS | TRANSFER_SPLITS | |
| base = s["ctx"] | |
| points = {} | |
| for mult in (0.15, 0.3, 0.5, 1.0, 2.0, 4.0): | |
| ctx = Ctx( | |
| world_model=base.world_model, | |
| risk_head=base.risk_head, | |
| probes=base.probes, | |
| thresholds=base.thresholds, | |
| alpha=base.alpha, | |
| budget_tokens=base.budget_tokens * mult, | |
| feature_mask=base.feature_mask, | |
| seed=base.seed, | |
| costs=base.costs, | |
| ) | |
| pol = build_policies(ctx) | |
| rows_c = run_policy(pol["clsa"], s["views"], splits) | |
| rows_l = run_policy(pol["language_first"], s["views"], splits) | |
| rows_d = run_policy(pol["dense_probe"], s["views"], splits) | |
| points[str(mult)] = { | |
| "budget": base.budget_tokens * mult, | |
| "clsa": { | |
| "harm_rate": harm_rate(rows_c), | |
| "success_rate": success_rate(rows_c), | |
| "harm_per_dollar": harm_per_dollar(rows_c), | |
| "success_per_dollar": success_per_dollar(rows_c), | |
| "tokens": float(np.mean([r["tokens"] for r in rows_c])), | |
| }, | |
| "language_first": { | |
| "harm_rate": harm_rate(rows_l), | |
| "success_rate": success_rate(rows_l), | |
| "harm_per_dollar": harm_per_dollar(rows_l), | |
| "success_per_dollar": success_per_dollar(rows_l), | |
| "tokens": float(np.mean([r["tokens"] for r in rows_l])), | |
| }, | |
| "dense_probe": { | |
| "harm_rate": harm_rate(rows_d), | |
| "success_rate": success_rate(rows_d), | |
| "harm_per_dollar": harm_per_dollar(rows_d), | |
| "success_per_dollar": success_per_dollar(rows_d), | |
| "tokens": float(np.mean([r["tokens"] for r in rows_d])), | |
| }, | |
| } | |
| # Marginal decision change per additional rollout (Figure 7). We vary the | |
| # number of Monte-Carlo rollouts used to score candidates and ask whether the | |
| # chosen action changes relative to a single rollout. | |
| from clsa.controller.mpc import rollout | |
| views = [v for v in s["views"] if v.split in splits] | |
| base_choices: list[int] = [] | |
| curve = [] | |
| for k in (1, 2, 3, 5, 8): | |
| choices = [] | |
| for v in views: | |
| out = rollout( | |
| base.world_model, | |
| base.risk_head, | |
| v.s, | |
| list(v.action_feats), | |
| n_samples=k, | |
| noise=0.03 * (k > 1), | |
| seed=base.seed, | |
| ) | |
| util = out["progress"] + 0.5 * out["p_success"] | |
| j = -util + 1.0 * out["p_hat"] * out["c_hat"] | |
| choices.append(int(np.argmin(j))) | |
| if k == 1: | |
| base_choices = choices | |
| curve.append( | |
| { | |
| "rollouts_per_candidate": k, | |
| "decision_change_rate": float( | |
| np.mean([a != b for a, b in zip(choices, base_choices)]) | |
| ), | |
| "tokens_per_decision": float(k * 12.0 * np.mean([len(v.candidates) for v in views])) | |
| if views | |
| else 0.0, | |
| } | |
| ) | |
| return {"backbone": s["name"], "points": points, "marginal": curve} | |
| def e4_calibration(backbone_key: str = "primary") -> dict: | |
| """E4: ECE, Brier, selective risk, realised-versus-promised, feasibility.""" | |
| s = setup(backbone_key) | |
| ds = s["ds"] | |
| te = np.array([sp in ("test", "heldout") for sp in ds["split"]]) | |
| cal = np.array([sp == "calib" for sp in ds["split"]]) | |
| sc = predict_scores(s["wm"], s["rh"], ds) | |
| p = 0.5 * (sc["p_harm"] + sc["risk_head_p"]) | |
| y = (ds["harm"] > 0.5).astype(float) | |
| th = float(s["blob"]["thresholds"].get("clsa", 0.5)) | |
| sel = selective_risk(p[te], y[te], th) | |
| mu = float(y[te].mean()) | |
| out = { | |
| "backbone": s["name"], | |
| "threshold": th, | |
| "ece": expected_calibration_error(p[te], y[te]), | |
| "brier": brier(p[te], y[te]), | |
| "selective": sel, | |
| "realised_minus_promised": float(sel["selective_risk"] - s["ctx"].alpha), | |
| "feasibility": { | |
| "base_risk": mu, | |
| "alpha": s["ctx"].alpha, | |
| "required_abstention": feasibility_abstention(mu, s["ctx"].alpha), | |
| "observed_abstention": 1.0 - sel["coverage"], | |
| "satisfied": bool((1.0 - sel["coverage"]) >= feasibility_abstention(mu, s["ctx"].alpha) - 1e-9) if mu > s["ctx"].alpha else True, | |
| }, | |
| "reliability": reliability_curve(p[te], y[te]), | |
| "by_alpha": {}, | |
| } | |
| # Naive acquire-then-refilter ablation: expected to break the bound. | |
| rows_naive = run_policy( | |
| build_policies(s["ctx"])["clsa_naive_acquire"], s["views"], {"test", "heldout"} | |
| ) | |
| rows_clsa = run_policy(build_policies(s["ctx"])["clsa"], s["views"], {"test", "heldout"}) | |
| for name, rows in (("clsa", rows_clsa), ("naive_acquire", rows_naive)): | |
| out.setdefault("policies", {})[name] = { | |
| "harm_rate": harm_rate(rows), | |
| "abstain_rate": float(np.mean([r["decision"] != "execute" for r in rows])), | |
| "n": len(rows), | |
| } | |
| for alpha in (0.05, 0.1, 0.2): | |
| from clsa.controller.risk import conformal_threshold | |
| th_a = conformal_threshold(p[cal & (y <= 0.5)], alpha) | |
| out["by_alpha"][str(alpha)] = { | |
| "threshold": th_a, | |
| **selective_risk(p[te], y[te], th_a), | |
| "promised": alpha, | |
| } | |
| out["false_abort_rate"] = float( | |
| np.mean( | |
| [ | |
| r["decision"] != "execute" | |
| for r in rows_clsa | |
| if r.get("safe_available") | |
| ] | |
| ) | |
| ) if rows_clsa else float("nan") | |
| return out | |
| def e5_causality(backbone_key: str = "primary") -> dict: | |
| """E5: Tiwari flip rates and steering effect under the coherence gate.""" | |
| s = setup(backbone_key) | |
| art = json.loads((DERIVED / s["name"].replace("/", "__") / "artifacts.json").read_text()) | |
| adm = art.get("admission", {}) | |
| ds = s["ds"] | |
| te = np.array([sp in ("test", "heldout") for sp in ds["split"]]) | |
| probe = s["probes"].get("sparse") | |
| z = ds["z"] | |
| X = np.concatenate([z, ds["action"]], axis=1) | |
| p = probe_predict(probe, X) | |
| th = float(s["blob"]["thresholds"].get("sparse", 0.5)) | |
| def score_fn(Z): | |
| return probe_predict(probe, np.concatenate([Z, ds["action"]], axis=1))[:, None] | |
| # Steering: scaled intervention on each set, measured as mean |Δp|. | |
| def steer(idx): | |
| if len(idx) == 0: | |
| return 0.0 | |
| Z2 = z.copy() | |
| Z2[:, idx] *= 2.0 | |
| p2 = probe_predict(probe, np.concatenate([Z2, ds["action"]], axis=1)) | |
| return float(np.mean(np.abs(p2[te] - p[te]))) | |
| shared = adm.get("shared_features", []) | |
| probe_only = adm.get("probe_only_features", []) | |
| rnd_rates = adm.get("flip_rate_random_per_set", []) | |
| return { | |
| "backbone": s["name"], | |
| "flip_rate_shared": adm.get("flip_rate_shared"), | |
| "flip_rate_probe_only": adm.get("flip_rate_probe_only"), | |
| "flip_rate_random": adm.get("flip_rate_random"), | |
| "flip_rate_random_per_set": rnd_rates, | |
| "steering_shared": steer(np.array(shared)), | |
| "steering_probe_only": steer(np.array(probe_only)), | |
| "n_shared": len(shared), | |
| "n_probe_only": len(probe_only), | |
| "coherence_gate": adm.get("coherence_gate"), | |
| "thresholds": adm.get("align_threshold"), | |
| "dissociation": bool( | |
| (adm.get("flip_rate_shared", 0.0) or 0.0) | |
| > max(1e-6, (adm.get("flip_rate_probe_only", 0.0) or 0.0)) | |
| ), | |
| } | |
| def _cross_backbone(primary: str, secondary_key: str = "secondary") -> dict: | |
| """Does the pipeline reproduce on a second backbone, and does the gate transfer? | |
| Three questions, each answered separately: | |
| 1. Replication: is the admission dissociation present on the other backbone? | |
| 2. Threshold transfer: carrying the primary gate's threshold to the second | |
| backbone's scores, with no recalibration. | |
| 3. Recalibration: the same threshold refitted on the second backbone's calib | |
| split, evaluated on its held-out states. | |
| A failure to load is reported as `not_run`, never as a null result. | |
| """ | |
| tcfg = load_config("transcoder") | |
| secondary = tcfg["backbones"].get(secondary_key) | |
| if not secondary: | |
| return {"status": "not_configured"} | |
| try: | |
| _wm2, _rh2, blob2, ds2 = load_model(secondary) | |
| art1 = json.loads((DERIVED / primary.replace("/", "__") / "artifacts.json").read_text()) | |
| art2 = json.loads((DERIVED / secondary.replace("/", "__") / "artifacts.json").read_text()) | |
| ds1 = load_dataset(primary) | |
| except (FileNotFoundError, OSError) as exc: | |
| return {"status": "not_run", "reason": f"{type(exc).__name__}: {exc}"} | |
| import joblib | |
| def probe_scores(backbone: str, ds: dict, kind: str = "sparse") -> np.ndarray: | |
| probe = joblib.load(DERIVED / backbone.replace("/", "__") / f"probe_{kind}.joblib") | |
| block = ds["z"] if kind == "sparse" else ds["dense"] | |
| return probe_predict(probe, np.concatenate([block, ds["action"]], axis=1)) | |
| p1 = probe_scores(primary, ds1) | |
| p2 = probe_scores(secondary, ds2) | |
| idx1 = {str(k): i for i, k in enumerate(ds1["state_key"])} | |
| shared = [ | |
| (idx1[str(k)], i) | |
| for i, k in enumerate(ds2["state_key"]) | |
| if str(k) in idx1 | |
| ] | |
| if not shared: | |
| return {"status": "not_run", "reason": "no shared states between backbones"} | |
| i1 = np.array([a for a, _ in shared]) | |
| i2 = np.array([b for _, b in shared]) | |
| y2 = (ds2["harm"] > 0.5).astype(float) | |
| ev2 = np.array([sp in ("test", "heldout") for sp in ds2["split"]]) | |
| cal2 = np.array([sp == "calib" for sp in ds2["split"]]) | |
| # The threshold carried across is the primary gate's, not the secondary's. | |
| tau1 = float((art1.get("thresholds") or {}).get("clsa", 0.5)) | |
| alpha = float(load_config("controller").get("alpha", 0.1)) | |
| out = { | |
| "status": "ok", | |
| "primary": primary, | |
| "secondary": secondary, | |
| "n_shared_states": int(len(shared)), | |
| "n_secondary_eval_states": int(ev2.sum()), | |
| "score_correlation": float(np.corrcoef(p1[i1], p2[i2])[0, 1]), | |
| "admission_primary": { | |
| "n_shared": art1.get("admission", {}).get("n_shared"), | |
| "flip_rate_shared": art1.get("admission", {}).get("flip_rate_shared"), | |
| "flip_rate_probe_only": art1.get("admission", {}).get("flip_rate_probe_only"), | |
| }, | |
| "admission_secondary": { | |
| "n_shared": art2.get("admission", {}).get("n_shared"), | |
| "flip_rate_shared": art2.get("admission", {}).get("flip_rate_shared"), | |
| "flip_rate_probe_only": art2.get("admission", {}).get("flip_rate_probe_only"), | |
| }, | |
| "threshold_transfer": { | |
| "threshold_from_primary": tau1, | |
| **selective_risk(p2[ev2], y2[ev2], tau1), | |
| "n": int(ev2.sum()), | |
| }, | |
| } | |
| from clsa.controller.risk import conformal_threshold | |
| if cal2.sum() >= 10 and (y2[cal2] <= 0.5).sum() >= 10: | |
| tau2 = conformal_threshold(p2[cal2 & (y2 <= 0.5)], alpha) | |
| out["recalibrated"] = { | |
| "threshold": tau2, | |
| **selective_risk(p2[ev2], y2[ev2], tau2), | |
| "n": int(ev2.sum()), | |
| } | |
| else: | |
| out["recalibrated"] = {"status": "not_run", "reason": "too few secondary calibration rows"} | |
| # Decision-level replication on the second backbone, using its own artefacts. | |
| try: | |
| s2 = setup(secondary_key) | |
| pol = build_policies(s2["ctx"]) | |
| rows = run_policy(pol["clsa"], s2["views"], {"test", "heldout"}) | |
| rows_lf = run_policy(pol["language_first"], s2["views"], {"test", "heldout"}) | |
| out["decision_level"] = { | |
| "clsa": report(rows), | |
| "language_first": report(rows_lf), | |
| "paired_harm": paired_bootstrap(rows, rows_lf, harm_rate), | |
| } | |
| except Exception as exc: # noqa: BLE001 - report, do not silently drop | |
| out["decision_level"] = {"status": "not_run", "reason": f"{type(exc).__name__}: {exc}"} | |
| return out | |
| def e6_transfer(backbone_key: str = "primary") -> dict: | |
| """E6: held-out benchmark with and without recalibration.""" | |
| s = setup(backbone_key) | |
| ds = s["ds"] | |
| hold = np.array([sp == "heldout" for sp in ds["split"]]) | |
| sc = predict_scores(s["wm"], s["rh"], ds) | |
| p = 0.5 * (sc["p_harm"] + sc["risk_head_p"]) | |
| y = (ds["harm"] > 0.5).astype(float) | |
| th_primary = float(s["blob"]["thresholds"].get("clsa", 0.5)) | |
| no_recal = selective_risk(p[hold], y[hold], th_primary) | |
| # Recalibrate on a deterministic half of the held-out split, evaluate on the other. | |
| idx = np.where(hold)[0] | |
| rng = np.random.default_rng(0) | |
| rng.shuffle(idx) | |
| half = len(idx) // 2 | |
| cal_idx, eval_idx = idx[:half], idx[half:] | |
| from clsa.controller.risk import conformal_threshold | |
| th_new = conformal_threshold(p[cal_idx][y[cal_idx] <= 0.5], s["ctx"].alpha) | |
| recal = selective_risk(p[eval_idx], y[eval_idx], th_new) | |
| no_recal_eval = selective_risk(p[eval_idx], y[eval_idx], th_primary) | |
| rows_clsa = run_policy(build_policies(s["ctx"])["clsa"], s["views"], {"heldout"}) | |
| rows_dense = run_policy(build_policies(s["ctx"])["dense_probe"], s["views"], {"heldout"}) | |
| return { | |
| "backbone": s["name"], | |
| "no_recalibration": {**no_recal, "threshold": th_primary}, | |
| "recalibrated": {**recal, "threshold": th_new}, | |
| "heldout_eval_only": { | |
| "no_recalibration": no_recal_eval, | |
| "recalibrated": recal, | |
| }, | |
| "decision_level": { | |
| "clsa": report(rows_clsa), | |
| "dense_probe": report(rows_dense), | |
| }, | |
| "delta_selective_risk": float( | |
| no_recal_eval["selective_risk"] - recal["selective_risk"] | |
| ), | |
| "cross_backbone": _cross_backbone(s["name"]), | |
| } | |
| def e7_multimodal(backbone_key: str = "primary") -> dict: | |
| """E7: GUI split, reversible versus irreversible, abstention vs fabrication.""" | |
| s = setup(backbone_key) | |
| views = [v for v in s["views"] if v.family == "gui_settings"] | |
| pol = build_policies(s["ctx"]) | |
| rows = {name: run_policy(pol[name], views, {"heldout", "test"}) for name in pol} | |
| out = {"backbone": s["name"], "n_states": len(views), "by_policy": {}} | |
| for name, r in rows.items(): | |
| rev = [x for x in r if x["irr"] is False] | |
| irr = [x for x in r if x["irr"] is True] | |
| out["by_policy"][name] = { | |
| "all": report(r), | |
| "reversible_chosen": report(rev) if rev else None, | |
| "irreversible_chosen": report(irr) if irr else None, | |
| "abstention_rate": float(np.mean([x["decision"] != "execute" for x in r])), | |
| "fabrication_rate": float( | |
| np.mean([x["decision"] == "execute" and x["harm"] > 0.5 for x in r]) | |
| ), | |
| } | |
| return out | |
| def e9_efficiency(backbone_key: str = "primary") -> dict: | |
| """E9: charged cost, latency, memory, and a distilled student check.""" | |
| s = setup(backbone_key) | |
| splits = PRIMARY_SPLITS | TRANSFER_SPLITS | |
| pol = build_policies(s["ctx"]) | |
| out = {"backbone": s["name"], "per_policy": {}} | |
| for name, p in pol.items(): | |
| tracemalloc.start() | |
| t0 = time.time() | |
| rows = run_policy(p, s["views"], splits) | |
| elapsed = time.time() - t0 | |
| current, peak = tracemalloc.get_traced_memory() | |
| tracemalloc.stop() | |
| out["per_policy"][name] = { | |
| "tokens_per_decision": float(np.mean([r["tokens"] for r in rows])), | |
| "latency_ms_per_decision": 1000 * elapsed / max(1, len(rows)), | |
| "peak_memory_mb": peak / (1024**2), | |
| "harm_rate": harm_rate(rows), | |
| "success_rate": success_rate(rows), | |
| "components": budget_report(rows), | |
| } | |
| # Distillation: a narrow student trained on the teacher's predicted scores. | |
| from clsa.world_model.dynamics import CausalWorldModel | |
| ds = s["ds"] | |
| S = np.concatenate([ds["z"], ds["b"], ds["e"], ds["image"], ds["tool"]], axis=1).astype(np.float32) | |
| A = ds["action"].astype(np.float32) | |
| tr = np.array([sp in ("train", "probe_train") for sp in ds["split"]]) | |
| with torch.no_grad(): | |
| teacher = s["wm"].predict( | |
| torch.as_tensor(S[tr]), torch.as_tensor(A[tr]) | |
| ) | |
| student = CausalWorldModel(S.shape[1], hidden=48, n_z=ds["layout"][0], n_b=ds["layout"][1], n_e=ds["layout"][2], n_img=ds["layout"][3], n_tool=ds["layout"][4]) | |
| opt = torch.optim.Adam(student.parameters(), lr=5e-3) | |
| S_t = torch.as_tensor(S[tr]) | |
| A_t = torch.as_tensor(A[tr]) | |
| for _ in range(120): | |
| out_s = student.predict(S_t, A_t) | |
| loss = ( | |
| torch.nn.functional.mse_loss(out_s["p_harm"], teacher["p_harm"]) | |
| + torch.nn.functional.mse_loss(out_s["progress"], teacher["progress"]) | |
| + 0.5 * torch.nn.functional.mse_loss(out_s["dz"], teacher["dz"]) | |
| ) | |
| opt.zero_grad() | |
| loss.backward() | |
| opt.step() | |
| te = np.array([sp in ("test", "heldout") for sp in ds["split"]]) | |
| with torch.no_grad(): | |
| st = student.predict(torch.as_tensor(S[te]), torch.as_tensor(A[te])) | |
| tt = s["wm"].predict(torch.as_tensor(S[te]), torch.as_tensor(A[te])) | |
| harm = ds["harm"][te] | |
| out["distillation"] = { | |
| "student_params": int(sum(p.numel() for p in student.parameters())), | |
| "teacher_params": int(sum(p.numel() for p in s["wm"].parameters())), | |
| "p_harm_agreement": float( | |
| ((st["p_harm"] > 0.5) == (tt["p_harm"] > 0.5)).float().mean() | |
| ), | |
| "student_brier": brier(st["p_harm"].numpy(), (harm > 0.5).astype(float)), | |
| "teacher_brier": brier(tt["p_harm"].numpy(), (harm > 0.5).astype(float)), | |
| "cf_consistency": float( | |
| ((st["p_harm"] > 0.5).numpy() == (harm > 0.5)).astype(float).mean() | |
| ), | |
| } | |
| out["memory_note"] = "tracemalloc measures Python allocations, not RSS; reported as a lower bound" | |
| return out | |