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
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
# Copyright (c) 2026 CLSA contributors
# SPDX-License-Identifier: MIT
"""Train the world model, the risk head, the monitors, and the admitted set.

Artifacts written per backbone:
  model.pt        world model + risk head weights, feature mask, thresholds
  artifacts.json  admission report, calibration numbers, metrics
"""
from __future__ import annotations

import json

import joblib
import numpy as np
import torch
import torch.nn.functional as F
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler

from clsa.controller.risk import (
    brier,
    conformal_threshold,
    expected_calibration_error,
    selective_risk,
)
from clsa.transcoder.admission import alignment_scores, choose_features, random_set
from clsa.transcoder.dataset import DERIVED
from clsa.util import load_config, seed_everything, set_threads
from clsa.world_model.dynamics import CausalWorldModel, RiskHead
from clsa.world_model.losses import total_cwl


def state_matrix(ds: dict) -> np.ndarray:
    return np.concatenate(
        [ds["z"], ds["b"], ds["e"], ds["image"], ds["tool"]], axis=1
    ).astype(np.float32)


def _split_mask(ds: dict, splits: set[str]) -> np.ndarray:
    return np.array([s in splits for s in ds["split"]], dtype=bool)


def train_world_model(
    ds: dict,
    cfg: dict,
    epochs: int = 220,
    lr: float = 2e-3,
    hidden: int = 192,
    seed: int = 0,
    verbose: bool = False,
) -> tuple[CausalWorldModel, RiskHead, dict]:
    set_threads(int(cfg.get("threads", 4)))
    torch.manual_seed(seed)
    S = state_matrix(ds)
    A = ds["action"].astype(np.float32)
    layout = ds["layout"]
    n_z, n_b, n_e, n_img, n_tool = layout
    lam = cfg.get("lambdas", {})

    wm = CausalWorldModel(
        S.shape[1], n_z=n_z, n_b=n_b, n_e=n_e, n_img=n_img, n_tool=n_tool, hidden=hidden
    )
    rh = RiskHead(S.shape[1], hidden=96)

    idx_tr = np.where(_split_mask(ds, {"train", "probe_train"}))[0]
    if len(idx_tr) == 0:
        idx_tr = np.arange(len(S))
    pairs = ds["pairs"]
    pairs = pairs[np.isin(pairs[:, 0], idx_tr)] if len(pairs) else pairs

    S_t = torch.as_tensor(S)
    A_t = torch.as_tensor(A)
    blocks = {
        "dz": slice(0, n_z),
        "db": slice(n_z, n_z + n_b),
        "de": slice(n_z + n_b, n_z + n_b + n_e),
        "dimg": slice(n_z + n_b + n_e, n_z + n_b + n_e + n_img),
        "dtool": slice(n_z + n_b + n_e + n_img, S.shape[1]),
    }
    opt = torch.optim.Adam(list(wm.parameters()) + list(rh.parameters()), lr=lr)
    # Risk-head augmentation: zero random z features so that masking at
    # inference time stays in-distribution.
    rng = np.random.default_rng(seed)

    n = len(idx_tr)
    bs = min(256, max(32, n // 4))
    history = []
    for epoch in range(epochs):
        perm = rng.permutation(idx_tr)
        ep_loss, ep_cf = 0.0, 0.0
        for start in range(0, n, bs):
            batch = perm[start : start + bs]
            s = S_t[batch]
            a = A_t[batch]
            mask = torch.as_tensor(rng.random(s.shape) > 0.25, dtype=torch.float32)
            mask[:, n_z:] = 1.0
            s_aug = s * mask
            out = wm(s_aug, a)
            p_hat, c_hat = rh(s_aug, a)
            harm = torch.as_tensor(ds["harm"][batch], dtype=torch.float32)
            succ = torch.as_tensor(ds["success"][batch], dtype=torch.float32)
            irr = torch.as_tensor(ds["irr"][batch], dtype=torch.float32)
            prog = torch.as_tensor(ds["progress"][batch], dtype=torch.float32)

            # L_state on real transitions inside episodes.
            if len(pairs):
                cond = np.isin(pairs[:, 0], batch)
                p_batch = pairs[cond][: bs]
                if len(p_batch):
                    i0, i1 = p_batch[:, 0], p_batch[:, 1]
                    out_t = wm(S_t[i0], A_t[i0])
                    target = {
                        k: (S_t[i1][:, sl] - S_t[i0][:, sl]) for k, sl in blocks.items()
                    }
                    state_out = {k: out_t[k] for k in blocks}
                else:
                    state_out = {k: out[k] for k in blocks}
                    target = {k: torch.zeros_like(out[k]) for k in blocks}
            else:
                state_out = {k: out[k] for k in blocks}
                target = {k: torch.zeros_like(out[k]) for k in blocks}

            cf_target = {"harm": harm, "success": succ, "irr": irr, "progress": prog}
            loss, logs = total_cwl(
                state_out,
                target,
                out,
                cf_target,
                s[:, :n_z],
                p_hat,
                harm,
                wm,
                lam,
            )
            opt.zero_grad()
            loss.backward()
            torch.nn.utils.clip_grad_norm_(
                list(wm.parameters()) + list(rh.parameters()), 1.0
            )
            opt.step()
            ep_loss += float(loss.detach())
            ep_cf += float(logs.get("cf_harm", 0.0))
        history.append(ep_loss / max(1, (n // bs) + 1))
        if verbose and epoch % 40 == 0:
            print(f"epoch {epoch} loss {history[-1]:.4f}")

    wm.eval()
    rh.eval()
    return wm, rh, {"loss_curve": history[-10:], "n_train": int(n), "epochs": epochs}


@torch.no_grad()
def predict_scores(wm, rh, ds: dict, idx: np.ndarray | None = None) -> dict:
    S = torch.as_tensor(state_matrix(ds))
    A = torch.as_tensor(ds["action"].astype(np.float32))
    if idx is not None:
        S, A = S[idx], A[idx]
    out = wm.predict(S, A)
    p_hat, c_hat = rh(S, A)
    return {
        "p_harm": out["p_harm"].numpy(),
        "p_success": out["p_success"].numpy(),
        "p_irr": out["p_irr"].numpy(),
        "progress": out["progress"].numpy(),
        "risk_head_p": p_hat.numpy(),
        "risk_head_c": c_hat.numpy(),
    }


def train_probes(ds: dict, seed: int, C: float = 0.05) -> dict:
    """Dense and sparse monitors, trained only on the commitment contrast."""
    train_mask = _split_mask(ds, {"train", "probe_train"})
    exec_mask = ds["executed"] > 0.5
    y = (ds["harm"] > 0.5).astype(int)
    m = train_mask & exec_mask

    out = {}
    for name, X in (
        ("dense", np.concatenate([ds["dense"], ds["action"]], axis=1)),
        ("sparse", np.concatenate([ds["z"], ds["action"]], axis=1)),
        ("behaviour", np.concatenate([ds["bow"], ds["action"]], axis=1)),
    ):
        if m.sum() < 20 or len(np.unique(y[m])) < 2:
            out[name] = None
            continue
        scaler = StandardScaler().fit(X[m])
        clf = LogisticRegression(
            C=C, class_weight="balanced", max_iter=2000, random_state=seed
        ).fit(scaler.transform(X[m]), y[m])
        out[name] = (scaler, clf)
    return out


def probe_predict(probe, X: np.ndarray) -> np.ndarray:
    scaler, clf = probe
    return clf.predict_proba(scaler.transform(X))[:, 1]


def fit_thresholds(ds: dict, p_by_policy: dict[str, np.ndarray], alpha: float) -> dict:
    """Conformal thresholds on the disjoint calibration split (per policy)."""
    calib = _split_mask(ds, {"calib"})
    harm = ds["harm"]
    out = {}
    for name, p in p_by_policy.items():
        safe = calib & (harm <= 0.5) & np.isfinite(p)
        if safe.sum() < 10:
            out[name] = 0.5
            continue
        out[name] = conformal_threshold(p[safe], alpha)
    return out


def admission_report(ds: dict, probe_sparse, threshold: float, cfg: dict) -> dict:
    """Run the Tiwari admission test and log all three flip rates."""
    acfg = cfg.get("admission", {})
    train_mask = _split_mask(ds, {"train", "probe_train"}) & (ds["executed"] > 0.5)
    test_mask = _split_mask(ds, {"test", "heldout"})
    y = (ds["harm"] > 0.5).astype(int)
    z = ds["z"]

    align = alignment_scores(z[train_mask], y[train_mask])

    # Behavioural sensitivity: does zeroing the feature flip the gate decision?
    def gate(p):
        return (p <= threshold).astype(int)

    base_p = probe_predict(probe_sparse, np.concatenate([z, ds["action"]], axis=1))
    base_dec = gate(base_p)
    flip_counts = np.zeros(z.shape[1], dtype=np.float32)
    n_test = int(test_mask.sum())
    for j in range(z.shape[1]):
        z2 = z.copy()
        z2[:, j] = 0.0
        p2 = probe_predict(probe_sparse, np.concatenate([z2, ds["action"]], axis=1))
        flip_counts[j] = float((gate(p2)[test_mask] != base_dec[test_mask]).mean())
    flip_scores = flip_counts

    align_thr = float(acfg.get("alignment_threshold", 0.12))
    flip_thr = float(acfg.get("flip_threshold", 0.05))
    sets = choose_features(align, flip_scores, align_thr, flip_thr)

    def set_flip(mask_idx: np.ndarray) -> float:
        if len(mask_idx) == 0:
            return 0.0
        z2 = z.copy()
        z2[:, mask_idx] = 0.0
        p2 = probe_predict(probe_sparse, np.concatenate([z2, ds["action"]], axis=1))
        return float((gate(p2)[test_mask] != base_dec[test_mask]).mean())

    shared_idx = np.where(sets["shared"])[0]
    probe_idx = np.where(sets["probe_only"])[0]
    rand_rates = []
    for i in range(int(acfg.get("n_random_sets", 5))):
        rmask = random_set(z.shape[1], max(1, len(shared_idx)), sets["shared"] | sets["probe_only"], int(acfg.get("random_seed", 13)) + i)
        rand_rates.append(set_flip(np.where(rmask)[0]))
    report = {
        "align_threshold": align_thr,
        "flip_threshold": flip_thr,
        "n_shared": int(len(shared_idx)),
        "n_probe_only": int(len(probe_idx)),
        "shared_features": shared_idx.tolist(),
        "probe_only_features": probe_idx.tolist(),
        "align_scores": [float(v) for v in align],
        "flip_scores": [float(v) for v in flip_scores],
        "flip_rate_shared": set_flip(shared_idx),
        "flip_rate_probe_only": set_flip(probe_idx),
        "flip_rate_random": float(np.mean(rand_rates)) if rand_rates else 0.0,
        "flip_rate_random_per_set": rand_rates,
        "n_test_items": n_test,
        "coherence_gate": bool(set_flip(shared_idx) > float(np.mean(rand_rates)) if rand_rates else False),
        "deviation": "fallback kept the most aligned sensitive feature"
        if not (sets["shared"].any() and len(shared_idx) > 0)
        else "",
    }
    return report


def evaluate_world_model(wm, rh, ds: dict, cfg: dict) -> dict:
    """Per-modality one-step error and counterfactual consistency on held-out data."""
    S = state_matrix(ds)
    blocks = {
        "dz": slice(0, ds["layout"][0]),
        "db": slice(ds["layout"][0], ds["layout"][0] + ds["layout"][1]),
        "de": slice(ds["layout"][0] + ds["layout"][1], ds["layout"][0] + ds["layout"][1] + ds["layout"][2]),
        "dimg": slice(sum(ds["layout"][:3]), sum(ds["layout"][:4])),
        "dtool": slice(sum(ds["layout"][:4]), sum(ds["layout"])),
    }
    te = _split_mask(ds, {"test", "heldout"})
    pairs = ds["pairs"]
    pairs_te = pairs[te[pairs[:, 0]]] if len(pairs) else pairs
    out = {}
    with torch.no_grad():
        if len(pairs_te):
            i0, i1 = torch.as_tensor(pairs_te[:, 0]), torch.as_tensor(pairs_te[:, 1])
            pred = wm(torch.as_tensor(S)[i0], torch.as_tensor(ds["action"])[i0])
            for k, sl in blocks.items():
                target = torch.as_tensor(S)[i1][:, sl] - torch.as_tensor(S)[i0][:, sl]
                out[f"mse_{k}"] = float(F.mse_loss(pred[k], target))
        sc = predict_scores(wm, rh, ds)
        harm = ds["harm"][te]
        succ = ds["success"][te]
        p = sc["p_harm"][te]
        out["cf_consistency"] = float(((p > 0.5) == (harm > 0.5)).mean()) if len(p) else 0.0
        out["cf_mse"] = float(np.mean((p - harm) ** 2)) if len(p) else 0.0
        out["success_consistency"] = (
            float(((sc["p_success"][te] > 0.5) == (succ > 0.5)).mean()) if len(succ) else 0.0
        )
        out["hallucinated_world_rate"] = float(
            np.mean((p > 0.5) & (harm <= 0.5))
        ) if len(p) else 0.0
    return out


def train_all(backbone: str, cfg: dict | None = None) -> dict:
    cfg = cfg or load_config("transcoder")
    seed = int(cfg.get("seed", 0))
    seed_everything(seed)
    from clsa.transcoder.dataset import load_dataset

    ds = load_dataset(backbone)
    alpha = float(load_config("controller").get("alpha", 0.1))
    wm, rh, wm_meta = train_world_model(ds, cfg, seed=seed)
    probes = train_probes(ds, seed, C=float(cfg.get("probe", {}).get("C", 0.05)))

    dense_X = np.concatenate([ds["dense"], ds["action"]], axis=1)
    sparse_X = np.concatenate([ds["z"], ds["action"]], axis=1)
    p_dense = probe_predict(probes["dense"], dense_X) if probes["dense"] else np.full(len(ds["z"]), 0.5)
    p_sparse = probe_predict(probes["sparse"], sparse_X) if probes["sparse"] else np.full(len(ds["z"]), 0.5)
    p_beh = probe_predict(probes["behaviour"], np.concatenate([ds["bow"], ds["action"]], axis=1)) if probes["behaviour"] else np.full(len(ds["z"]), 0.5)

    wm_scores = predict_scores(wm, rh, ds)
    p_wm = 0.5 * (wm_scores["p_harm"] + wm_scores["risk_head_p"])

    thresholds = fit_thresholds(
        ds, {"dense": p_dense, "sparse": p_sparse, "behaviour": p_beh, "clsa": p_wm}, alpha
    )
    adm = admission_report(ds, probes["sparse"], thresholds["sparse"], cfg) if probes["sparse"] else {}

    te = _split_mask(ds, {"test", "heldout"})
    cal = _split_mask(ds, {"calib"})
    wm_eval = evaluate_world_model(wm, rh, ds, cfg)

    cal_stats = {}
    for name, p in (("dense", p_dense), ("sparse", p_sparse), ("behaviour", p_beh), ("clsa", p_wm)):
        s = selective_risk(p[te], ds["harm"][te], thresholds[name])
        cal_stats[name] = {
            "threshold": thresholds[name],
            "ece": expected_calibration_error(p[cal], ds["harm"][cal]),
            "brier": brier(p[cal], ds["harm"][cal]),
            **s,
            "label": "diagnostic",
        }

    out_dir = DERIVED / backbone.replace("/", "__")
    torch.save(
        {
            "model_cfg": {
                "hidden": int(wm.hidden) if hasattr(wm, "hidden") else None,
                "risk_hidden": int(rh.body[0].out_features),
                "state_dim": int(state_matrix(ds).shape[1]),
                "action_dim": 16,
            },
            "world_model": wm.state_dict(),
            "risk_head": rh.state_dict(),
            "layout": ds["layout"],
            "thresholds": thresholds,
            "feature_mask": np.array(adm.get("shared_features", []), dtype=np.int64),
        },
        out_dir / "model.pt",
    )
    for name, probe in probes.items():
        if probe is not None:
            joblib.dump(probe, out_dir / f"probe_{name}.joblib")

    artifacts = {
        "backbone": backbone,
        "seed": seed,
        "alpha": alpha,
        "world_model": {**wm_meta, **wm_eval},
        "admission": adm,
        "thresholds": thresholds,
        "calibration": cal_stats,
        "probes_available": [k for k, v in probes.items() if v is not None],
        "dataset": {
            "n_items": int(len(ds["z"])),
            "n_states": int(len(ds["state_ids"])),
            "n_transitions": int(len(ds["pairs"])),
        },
    }
    with open(out_dir / "artifacts.json", "w", encoding="utf-8") as fh:
        json.dump(artifacts, fh, indent=2)
    return artifacts


@torch.no_grad()
def load_model(backbone: str):
    from clsa.transcoder.dataset import load_dataset

    out_dir = DERIVED / backbone.replace("/", "__")
    blob = torch.load(out_dir / "model.pt", map_location="cpu", weights_only=False)
    ds = load_dataset(backbone)
    layout = blob["layout"]
    cfg = blob.get("model_cfg") or {}
    # Infer widths from the checkpoint when the config block is absent, so an
    # older artefact still loads instead of failing on a hidden-size mismatch.
    wm_hidden = cfg.get("hidden")
    if not wm_hidden:
        for k, v in blob["world_model"].items():
            if k.endswith("body.0.weight"):
                wm_hidden = int(v.shape[0])
                break
    rh_hidden = cfg.get("risk_hidden") or int(blob["risk_head"]["body.0.weight"].shape[0])
    wm = CausalWorldModel(
        state_matrix(ds).shape[1],
        hidden=int(wm_hidden or 192),
        n_z=layout[0],
        n_b=layout[1],
        n_e=layout[2],
        n_img=layout[3],
        n_tool=layout[4],
    )
    wm.load_state_dict(blob["world_model"])
    wm.eval()
    rh = RiskHead(state_matrix(ds).shape[1], hidden=int(rh_hidden))
    rh.load_state_dict(blob["risk_head"])
    rh.eval()
    return wm, rh, blob, ds