File size: 27,278 Bytes
fd5366a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
# 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