latchgate 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
latchgate/compiler.py ADDED
@@ -0,0 +1,846 @@
1
+ """Adaptive Superposition Compiler (`latchgate fit`).
2
+
3
+ Given counterfactual `(honest/faithful, bad/sabotage/sycophantic, optional confounder)` activation
4
+ pairs or counterfactual JSONL traces (including ``mendmark export-latchgate`` exports), ``LatchCompiler``:
5
+ 1. Evaluates K-fold out-of-fold separability of a lightweight Dense Standardized Probe against a
6
+ Confounder-Penalized JumpReLU SAE + Instance-Indexed Anchor Subspace at 57.1% network depth.
7
+ 2. Automatically compiles a ``dense_latch`` when linear separability holds without confounder
8
+ collateral (typical of 7B-70B LLMs) or an ``sae_anchor_latch`` when 3D spacetime or edge
9
+ superposition collapses dense probes (typical of 2B-4B edge LLMs, video DiTs, and Cosmos world models).
10
+ 3. Supports ``< 10 s`` task calibration on frozen pre-trained base SAEs (``base_sae``) without
11
+ retraining the 16k dictionary, or single-GPU JumpReLU SAE training when no base dictionary exists.
12
+ 4. Calibrates ``threshold_tau`` strictly on clean/benign/confounder controls with a finite-sample
13
+ conformal quantile margin to target 0.0% benign false-positive rate.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ from dataclasses import asdict, dataclass, field
19
+ import json
20
+ from pathlib import Path
21
+ import time
22
+ from typing import Any
23
+ import numpy as np
24
+ import torch
25
+ import torch.nn.functional as F
26
+
27
+ from .exceptions import LatchGateError
28
+ from .format import LatchGate
29
+ from .sae import JumpReLUSAE, load_base_sae, train_jumprelu_sae
30
+
31
+
32
+ def _binary_auroc(y_true: np.ndarray, scores: np.ndarray) -> float:
33
+ """Exact Mann-Whitney U AUROC with tie handling (zero scikit-learn dependency)."""
34
+ y = np.asarray(y_true, dtype=np.int64).reshape(-1)
35
+ s = np.asarray(scores, dtype=np.float64).reshape(-1)
36
+ pos = s[y == 1]
37
+ neg = s[y == 0]
38
+ if len(pos) == 0 or len(neg) == 0:
39
+ return 0.5
40
+ # Pairwise comparison (N <= a few thousand in calibration; vectorized & exact)
41
+ diff = pos[:, None] - neg[None, :]
42
+ wins = float(np.sum(diff > 0.0) + 0.5 * np.sum(diff == 0.0))
43
+ return wins / float(len(pos) * len(neg))
44
+
45
+
46
+ def _fpr_at_tpr(y_true: np.ndarray, scores: np.ndarray, target_tpr: float = 0.80) -> float:
47
+ y = np.asarray(y_true, dtype=np.int64).reshape(-1)
48
+ s = np.asarray(scores, dtype=np.float64).reshape(-1)
49
+ pos = s[y == 1]
50
+ neg = s[y == 0]
51
+ if len(pos) == 0 or len(neg) == 0:
52
+ return 1.0
53
+ thresh = float(np.quantile(pos, max(0.0, 1.0 - target_tpr)))
54
+ return float(np.mean(neg >= thresh))
55
+
56
+
57
+ def _stratified_kfold_indices(y: np.ndarray, n_splits: int = 5, seed: int = 42) -> list[tuple[np.ndarray, np.ndarray]]:
58
+ rng = np.random.default_rng(seed)
59
+ pos_idx = np.where(y == 1)[0].copy()
60
+ neg_idx = np.where(y == 0)[0].copy()
61
+ rng.shuffle(pos_idx)
62
+ rng.shuffle(neg_idx)
63
+ k = max(2, min(n_splits, len(pos_idx), len(neg_idx)))
64
+ pos_folds = np.array_split(pos_idx, k)
65
+ neg_folds = np.array_split(neg_idx, k)
66
+ splits: list[tuple[np.ndarray, np.ndarray]] = []
67
+ all_idx = np.arange(len(y))
68
+ for i in range(k):
69
+ te = np.concatenate([pos_folds[i], neg_folds[i]])
70
+ tr_mask = np.ones(len(y), dtype=bool)
71
+ tr_mask[te] = False
72
+ splits.append((all_idx[tr_mask], te))
73
+ return splits
74
+
75
+
76
+ def fit_l2_logistic_probe(
77
+ X_raw: np.ndarray,
78
+ y: np.ndarray,
79
+ *,
80
+ c_reg: float = 0.08,
81
+ unit_norm: bool = True,
82
+ seed: int = 42,
83
+ ) -> tuple[torch.Tensor, float, torch.Tensor, torch.Tensor]:
84
+ """Fit an exact L2-penalized logistic regression probe in PyTorch using L-BFGS.
85
+
86
+ Matches scikit-learn ``LogisticRegression(C=0.08)`` objective:
87
+ ``min_{w, b} 0.5 * ||w||^2 + C * sum_i BCE(w^T x_i + b, y_i)``.
88
+ """
89
+ torch.manual_seed(seed)
90
+ X = np.asarray(X_raw, dtype=np.float32)
91
+ if X.ndim > 2:
92
+ X = X.reshape(X.shape[0], -1)
93
+ if unit_norm:
94
+ X = X / (np.linalg.norm(X, axis=-1, keepdims=True) + 1e-8)
95
+ mean = X.mean(axis=0)
96
+ scale = X.std(axis=0, ddof=0)
97
+ scale = np.where(scale < 1e-6, 1.0, scale)
98
+ X_s = torch.from_numpy((X - mean) / scale)
99
+ y_t = torch.from_numpy(np.asarray(y, dtype=np.float32))
100
+
101
+ d = X_s.shape[1]
102
+ w = torch.zeros(d, dtype=torch.float32, requires_grad=True)
103
+ b = torch.zeros(1, dtype=torch.float32, requires_grad=True)
104
+ n_samples = float(X_s.shape[0])
105
+ l2_penalty = 0.5 / max(1e-6, c_reg * n_samples)
106
+
107
+ opt = torch.optim.LBFGS([w, b], lr=1.0, max_iter=150, line_search_fn="strong_wolfe")
108
+
109
+ def _closure() -> torch.Tensor:
110
+ opt.zero_grad()
111
+ logits = X_s @ w + b
112
+ bce = F.binary_cross_entropy_with_logits(logits, y_t, reduction="mean")
113
+ loss = bce + l2_penalty * (w * w).sum()
114
+ loss.backward()
115
+ return loss
116
+
117
+ opt.step(_closure)
118
+ return (
119
+ w.detach().clone(),
120
+ float(b.detach().item()),
121
+ torch.from_numpy(mean.astype(np.float32)),
122
+ torch.from_numpy(scale.astype(np.float32)),
123
+ )
124
+
125
+
126
+ def fit_manifold_steering_direction(
127
+ X_raw: np.ndarray,
128
+ y: np.ndarray,
129
+ *,
130
+ c_reg: float = 1.0,
131
+ seed: int = 42,
132
+ ) -> torch.Tensor:
133
+ """Fit an RMS-normalized L2 logistic direction in unstandardized activation space for steering.
134
+
135
+ Unlike per-feature standardized probe weights (which divide by tiny channel variances and amplify
136
+ off-manifold noise axes when added back into the residual stream), RMS normalization preserves
137
+ residual covariance geometry and matches Paper 1's planning-block steering vectors.
138
+ """
139
+ torch.manual_seed(seed)
140
+ X = np.asarray(X_raw, dtype=np.float32)
141
+ if X.ndim > 2:
142
+ X = X.reshape(X.shape[0], -1)
143
+ rms = float(np.linalg.norm(X, axis=-1).mean()) + 1e-8
144
+ X_rms = torch.from_numpy(X / rms)
145
+ y_t = torch.from_numpy(np.asarray(y, dtype=np.float32))
146
+
147
+ d = X_rms.shape[1]
148
+ w = torch.zeros(d, dtype=torch.float32, requires_grad=True)
149
+ b = torch.zeros(1, dtype=torch.float32, requires_grad=True)
150
+ n_samples = float(X_rms.shape[0])
151
+ l2_penalty = 0.5 / max(1e-6, c_reg * n_samples)
152
+
153
+ opt = torch.optim.LBFGS([w, b], lr=1.0, max_iter=200, line_search_fn="strong_wolfe")
154
+
155
+ def _closure() -> torch.Tensor:
156
+ opt.zero_grad()
157
+ logits = X_rms @ w + b
158
+ bce = F.binary_cross_entropy_with_logits(logits, y_t, reduction="mean")
159
+ loss = bce + l2_penalty * (w * w).sum()
160
+ loss.backward()
161
+ return loss
162
+
163
+ opt.step(_closure)
164
+ w_det = w.detach().clone()
165
+ return w_det / w_det.norm().clamp_min(1e-8)
166
+
167
+
168
+ def calibrate_conformal_threshold(
169
+ pos_scores: np.ndarray,
170
+ clean_neg_scores: np.ndarray,
171
+ confounder_neg_scores: np.ndarray | None = None,
172
+ *,
173
+ max_benign_fpr: float = 0.0,
174
+ min_floor: float = 0.0,
175
+ ) -> dict[str, float]:
176
+ """Calibrate decision threshold ``tau`` on clean/confounder negatives with finite-sample margin.
177
+
178
+ When ``max_benign_fpr == 0.0``, sets ``tau`` at or above ``max(neg_scores) + safety_margin``
179
+ whenever positive scores still exceed it, guaranteeing 0.0% empirical false triggers on
180
+ calibration benign and high-motion/confounder controls.
181
+ """
182
+ pos = np.asarray(pos_scores, dtype=np.float64).reshape(-1)
183
+ neg_parts = [np.asarray(clean_neg_scores, dtype=np.float64).reshape(-1)]
184
+ if confounder_neg_scores is not None and len(confounder_neg_scores) > 0:
185
+ neg_parts.append(np.asarray(confounder_neg_scores, dtype=np.float64).reshape(-1))
186
+ neg = np.concatenate(neg_parts)
187
+ if len(neg) == 0:
188
+ raise LatchGateError("Threshold calibration requires at least one negative/benign example.")
189
+
190
+ n_neg = len(neg)
191
+ # Conformal finite-sample level: min(1.0, (1 - alpha) * (1 + 1 / n_neg))
192
+ conf_q = min(1.0, (1.0 - max_benign_fpr) * (1.0 + 1.0 / float(n_neg + 1)))
193
+ if max_benign_fpr <= 1e-9:
194
+ neg_cap = float(np.max(neg))
195
+ pos_above = pos[pos > neg_cap]
196
+ if len(pos_above) > 0:
197
+ margin = 0.25 * float(np.min(pos_above) - neg_cap)
198
+ tau_floor = neg_cap + max(1e-5, min(margin, 0.05 * abs(neg_cap) + 1e-3))
199
+ else:
200
+ tau_floor = neg_cap + 1e-5
201
+ else:
202
+ tau_floor = float(np.quantile(neg, conf_q))
203
+
204
+ tau_floor = max(float(min_floor), tau_floor)
205
+ hi = float(max(np.max(pos) if len(pos) else tau_floor, tau_floor))
206
+ candidates = np.unique(np.concatenate([[tau_floor], np.linspace(tau_floor, hi, 65)]))
207
+
208
+ best_tau = tau_floor
209
+ best_j = -2.0
210
+ for cand in candidates:
211
+ ben_fpr = float(np.mean(neg > cand))
212
+ if ben_fpr > max_benign_fpr + 1e-6 and cand > tau_floor + 1e-9:
213
+ continue
214
+ tpr = float(np.mean(pos > cand)) if len(pos) > 0 else 0.0
215
+ j_stat = tpr - ben_fpr
216
+ if j_stat > best_j:
217
+ best_j = j_stat
218
+ best_tau = float(cand)
219
+
220
+ y_all = np.concatenate([np.ones(len(pos), dtype=np.int64), np.zeros(len(neg), dtype=np.int64)])
221
+ s_all = np.concatenate([pos, neg])
222
+ return {
223
+ "threshold_tau": round(float(best_tau), 6),
224
+ "calibration_auroc": round(_binary_auroc(y_all, s_all), 4),
225
+ "calibration_tpr": round(float(np.mean(pos > best_tau)) if len(pos) else 0.0, 4),
226
+ "calibration_benign_fpr": round(float(np.mean(neg > best_tau)), 4),
227
+ "calibration_confounder_fpr": round(
228
+ float(np.mean(np.asarray(confounder_neg_scores) > best_tau))
229
+ if confounder_neg_scores is not None and len(confounder_neg_scores) > 0
230
+ else 0.0,
231
+ 4,
232
+ ),
233
+ }
234
+
235
+
236
+ def select_confounder_penalized_subspace(
237
+ *,
238
+ f_honest: torch.Tensor,
239
+ f_bad: torch.Tensor,
240
+ f_confounder: torch.Tensor | None = None,
241
+ f_anchor_honest: torch.Tensor | None = None,
242
+ f_anchor_bad: torch.Tensor | None = None,
243
+ f_anchor_confounder: torch.Tensor | None = None,
244
+ lambda_confound: float = 0.70,
245
+ top_k_bad: int = 48,
246
+ top_k_anchor: int = 64,
247
+ min_bad_fire_rate: float = 0.08,
248
+ ) -> dict[str, Any]:
249
+ """Identify ``D = TopK(d^bad - lambda * d^confound)`` and persistent anchor latents."""
250
+ d_sae = int(f_honest.shape[-1])
251
+ fh = f_honest.to(torch.float32)
252
+ fb = f_bad.to(torch.float32)
253
+ fc = f_confounder.to(torch.float32) if (f_confounder is not None and f_confounder.numel() > 0) else None
254
+
255
+ if f_anchor_honest is not None and f_anchor_bad is not None:
256
+ ah = f_anchor_honest.to(torch.float32)
257
+ ab = f_anchor_bad.to(torch.float32)
258
+ surge_h = torch.clamp(fh - ah[: fh.shape[0]], min=0.0)
259
+ surge_b = torch.clamp(fb - ab[: fb.shape[0]], min=0.0)
260
+ clean_surges = [surge_h]
261
+ if fc is not None:
262
+ ac = (
263
+ f_anchor_confounder.to(torch.float32)
264
+ if f_anchor_confounder is not None
265
+ else ah[: fc.shape[0]]
266
+ )
267
+ surge_c = torch.clamp(fc - ac[: fc.shape[0]], min=0.0)
268
+ clean_surges.append(surge_c)
269
+ else:
270
+ surge_c = None
271
+ clean_surge_pool = torch.cat(clean_surges, dim=0)
272
+ var_s = 0.5 * (surge_b.var(dim=0, unbiased=False) + clean_surge_pool.var(dim=0, unbiased=False))
273
+ surge_d = (surge_b.mean(dim=0) - clean_surge_pool.mean(dim=0)) / torch.sqrt(var_s + 1e-5)
274
+ else:
275
+ surge_h = fh
276
+ surge_c = fc
277
+ surge_d = None
278
+
279
+ clean_raw = torch.cat([fh, fc], dim=0) if fc is not None else fh
280
+ var_r = 0.5 * (fb.var(dim=0, unbiased=False) + clean_raw.var(dim=0, unbiased=False))
281
+ raw_d = (fb.mean(dim=0) - clean_raw.mean(dim=0)) / torch.sqrt(var_r + 1e-5)
282
+ d_bad = (0.65 * surge_d + 0.35 * raw_d) if surge_d is not None else raw_d
283
+
284
+ if surge_c is not None:
285
+ var_c = 0.5 * (surge_c.var(dim=0, unbiased=False) + surge_h.var(dim=0, unbiased=False))
286
+ d_confound = torch.clamp(
287
+ (surge_c.mean(dim=0) - surge_h.mean(dim=0)) / torch.sqrt(var_c + 1e-5),
288
+ min=0.0,
289
+ )
290
+ penalized_d = d_bad - float(lambda_confound) * d_confound
291
+ else:
292
+ penalized_d = d_bad
293
+
294
+ fire_rate_bad = (fb > 0).to(torch.float32).mean(dim=0)
295
+ scored = torch.where(fire_rate_bad >= min_bad_fire_rate, penalized_d, penalized_d - 5.0)
296
+ k_bad = min(top_k_bad, d_sae)
297
+ bad_vals, bad_idx = torch.topk(scored, k=k_bad)
298
+
299
+ # Anchor support persistence
300
+ ref_a = f_anchor_honest.to(torch.float32) if f_anchor_honest is not None else fh
301
+ n_pair = min(ref_a.shape[0], fh.shape[0])
302
+ a = ref_a[:n_pair]
303
+ b = fh[:n_pair]
304
+ col_cos = (a * b).sum(dim=0) / (a.norm(dim=0) * b.norm(dim=0)).clamp_min(1e-6)
305
+ fr = 0.5 * ((a > 0).to(torch.float32).mean(dim=0) + (b > 0).to(torch.float32).mean(dim=0))
306
+ sel = ((fr >= 0.02) & (fr <= 0.70)).to(torch.float32)
307
+ pers = col_cos * torch.sqrt(fr.clamp_min(1e-6)) * sel
308
+ pers[bad_idx] = -1e9
309
+ anc_vals, anc_idx = torch.topk(pers, k=min(top_k_anchor, d_sae))
310
+
311
+ return {
312
+ "bad_latent_ids": [int(i) for i in bad_idx.tolist()],
313
+ "anchor_latent_ids": [int(i) for i in anc_idx.tolist()],
314
+ "bad_cohens_d": [round(float(v), 4) for v in bad_vals.tolist()],
315
+ "anchor_persistence": [round(float(v), 4) for v in anc_vals.tolist()],
316
+ }
317
+
318
+
319
+ @dataclass(frozen=True)
320
+ class AdaptiveRouteDecision:
321
+ """Superposition gap diagnostic and selected circuit-breaker architecture."""
322
+
323
+ selected_mode: str
324
+ dense_cv_auroc: float
325
+ sae_cv_auroc: float
326
+ superposition_gap: float
327
+ dense_fpr_at_80_tpr: float
328
+ sae_fpr_at_80_tpr: float
329
+ rationale: str
330
+
331
+
332
+ @dataclass(frozen=True)
333
+ class CompileReport:
334
+ """Summary returned alongside a compiled ``LatchGate``."""
335
+
336
+ route: AdaptiveRouteDecision
337
+ calibration: dict[str, float]
338
+ compile_seconds: float
339
+ sae_stats: dict[str, float] = field(default_factory=dict)
340
+
341
+ def to_dict(self) -> dict[str, Any]:
342
+ return {
343
+ "route": asdict(self.route),
344
+ "calibration": self.calibration,
345
+ "compile_seconds": round(self.compile_seconds, 3),
346
+ "sae_stats": self.sae_stats,
347
+ }
348
+
349
+
350
+ class LatchCompiler:
351
+ """Two-tier adaptive circuit-breaker compiler."""
352
+
353
+ def __init__(
354
+ self,
355
+ *,
356
+ mode: str = "auto",
357
+ max_benign_fpr: float = 0.0,
358
+ lambda_confound: float = 0.70,
359
+ superposition_margin: float = 0.04,
360
+ dense_min_auroc: float = 0.90,
361
+ top_k_bad: int = 48,
362
+ top_k_anchor: int = 64,
363
+ d_sae: int = 4096,
364
+ seed: int = 42,
365
+ ) -> None:
366
+ if mode not in {"auto", "dense", "sae"}:
367
+ raise LatchGateError("mode must be 'auto', 'dense', or 'sae'.")
368
+ self.mode = mode
369
+ self.max_benign_fpr = float(max_benign_fpr)
370
+ self.lambda_confound = float(lambda_confound)
371
+ self.superposition_margin = float(superposition_margin)
372
+ self.dense_min_auroc = float(dense_min_auroc)
373
+ self.top_k_bad = int(top_k_bad)
374
+ self.top_k_anchor = int(top_k_anchor)
375
+ self.d_sae = int(d_sae)
376
+ self.seed = int(seed)
377
+
378
+ def fit(
379
+ self,
380
+ *,
381
+ honest_acts: torch.Tensor | np.ndarray,
382
+ bad_acts: torch.Tensor | np.ndarray,
383
+ confounder_acts: torch.Tensor | np.ndarray | None = None,
384
+ anchor_honest_acts: torch.Tensor | np.ndarray | None = None,
385
+ anchor_bad_acts: torch.Tensor | np.ndarray | None = None,
386
+ anchor_confounder_acts: torch.Tensor | np.ndarray | None = None,
387
+ base_sae: JumpReLUSAE | str | Path | None = None,
388
+ backbone_id: str = "custom-backbone",
389
+ layer_index: int = 16,
390
+ num_layers: int = 28,
391
+ timestep: float = 0.0,
392
+ bins: tuple[float, ...] = (0.0,),
393
+ steer_layers: tuple[int, ...] = (),
394
+ steer_vectors: torch.Tensor | np.ndarray | None = None,
395
+ alpha_steer: float = 0.25,
396
+ abort_step: int | None = None,
397
+ device: str | torch.device = "cpu",
398
+ ) -> tuple[LatchGate, CompileReport]:
399
+ """Compile a portable ``LatchGate`` from counterfactual residual representations."""
400
+ t0 = time.perf_counter()
401
+ dev = torch.device(device)
402
+
403
+ def _to_t(arr: torch.Tensor | np.ndarray | None) -> torch.Tensor | None:
404
+ if arr is None:
405
+ return None
406
+ return (
407
+ torch.from_numpy(np.asarray(arr, dtype=np.float32))
408
+ if not isinstance(arr, torch.Tensor)
409
+ else arr.detach().cpu().to(torch.float32)
410
+ )
411
+
412
+ h_hon = _to_t(honest_acts)
413
+ h_bad = _to_t(bad_acts)
414
+ h_conf = _to_t(confounder_acts)
415
+ a_hon = _to_t(anchor_honest_acts)
416
+ a_bad = _to_t(anchor_bad_acts)
417
+ a_conf = _to_t(anchor_confounder_acts)
418
+ assert h_hon is not None and h_bad is not None
419
+
420
+ if h_hon.shape[0] < 4 or h_bad.shape[0] < 4:
421
+ raise LatchGateError("latchgate fit requires at least 4 honest and 4 bad trajectories.")
422
+ d_model = int(h_hon.shape[-1])
423
+ if int(h_bad.shape[-1]) != d_model:
424
+ raise LatchGateError("honest_acts and bad_acts must share last dimension d_model.")
425
+
426
+ # Pool multi-token trajectories (N, T_tok, D) -> (N, D) for dense baseline evaluation
427
+ def _pool_dense(x: torch.Tensor, anc: torch.Tensor | None) -> np.ndarray:
428
+ xp = x.mean(dim=1) if x.ndim == 3 else x.reshape(x.shape[0], d_model)
429
+ if anc is not None:
430
+ ap = anc.mean(dim=1) if anc.ndim == 3 else anc.reshape(anc.shape[0], d_model)
431
+ xp = xp - ap[: xp.shape[0]]
432
+ return xp.numpy()
433
+
434
+ X_hon_d = _pool_dense(h_hon, a_hon)
435
+ X_bad_d = _pool_dense(h_bad, a_bad)
436
+ X_conf_d = _pool_dense(h_conf, a_conf) if h_conf is not None else None
437
+
438
+ neg_dense_parts = [X_hon_d] + ([X_conf_d] if X_conf_d is not None else [])
439
+ X_neg_d = np.concatenate(neg_dense_parts, axis=0)
440
+ X_all_d = np.concatenate([X_bad_d, X_neg_d], axis=0)
441
+ y_all = np.concatenate(
442
+ [np.ones(len(X_bad_d), dtype=np.int64), np.zeros(len(X_neg_d), dtype=np.int64)]
443
+ )
444
+
445
+ # 1. K-fold CV Dense Standardized Probe evaluation
446
+ splits = _stratified_kfold_indices(y_all, n_splits=5, seed=self.seed)
447
+ oof_dense = np.zeros(len(y_all), dtype=np.float32)
448
+ for tr, te in splits:
449
+ w_f, b_f, mu_f, sd_f = fit_l2_logistic_probe(X_all_d[tr], y_all[tr], seed=self.seed)
450
+ x_te = torch.from_numpy(X_all_d[te])
451
+ x_te = x_te / x_te.norm(dim=-1, keepdim=True).clamp_min(1e-8)
452
+ x_te_s = (x_te - mu_f.unsqueeze(0)) / sd_f.unsqueeze(0)
453
+ oof_dense[te] = torch.sigmoid(x_te_s @ w_f + b_f).numpy()
454
+
455
+ dense_auroc = _binary_auroc(y_all, oof_dense)
456
+ dense_fpr80 = _fpr_at_tpr(y_all, oof_dense, 0.80)
457
+
458
+ # 2. Load frozen base SAE (<10s fast path) OR train JumpReLU SAE unless mode == "dense"
459
+ sae_stats: dict[str, float] = {}
460
+ sae_obj: JumpReLUSAE | None = None
461
+ sae_auroc = dense_auroc
462
+ sae_fpr80 = dense_fpr80
463
+
464
+ if self.mode in {"auto", "sae"}:
465
+ if isinstance(base_sae, JumpReLUSAE):
466
+ sae_obj = base_sae.to(dev).eval()
467
+ sae_stats = {"source": 0.0, "retrained": 0.0}
468
+ elif isinstance(base_sae, (str, Path)):
469
+ sae_obj = load_base_sae(base_sae, device=dev)
470
+ sae_stats = {"retrained": 0.0}
471
+ else:
472
+ corpus_parts = [h_hon.reshape(-1, d_model), h_bad.reshape(-1, d_model)]
473
+ if h_conf is not None:
474
+ corpus_parts.append(h_conf.reshape(-1, d_model))
475
+ if a_hon is not None:
476
+ corpus_parts.append(a_hon.reshape(-1, d_model))
477
+ if a_bad is not None:
478
+ corpus_parts.append(a_bad.reshape(-1, d_model))
479
+ corpus = torch.cat(corpus_parts, dim=0)
480
+ b_idx_corpus = torch.full(
481
+ (corpus.shape[0],),
482
+ int(np.argmin([abs(timestep - b) for b in bins])),
483
+ dtype=torch.long,
484
+ )
485
+ sae_obj, sae_stats = train_jumprelu_sae(
486
+ token_acts=corpus,
487
+ token_bins=b_idx_corpus,
488
+ bins=bins,
489
+ confounder_acts=h_conf.reshape(-1, d_model) if h_conf is not None else None,
490
+ d_sae=self.d_sae,
491
+ device=dev,
492
+ seed=self.seed,
493
+ )
494
+ sae_obj.eval()
495
+
496
+ assert sae_obj is not None
497
+
498
+ def _enc_pool(t_in: torch.Tensor | None) -> torch.Tensor | None:
499
+ if t_in is None:
500
+ return None
501
+ if t_in.ndim == 2:
502
+ return sae_obj.encode(t_in.to(dev), timestep=timestep).cpu()
503
+ # Token-first encoding across (N, T_tok, D) BEFORE pooling!
504
+ return sae_obj.encode_tokens_then_pool(t_in.to(dev), timestep=timestep).cpu()
505
+
506
+ f_hon = _enc_pool(h_hon)
507
+ f_bad = _enc_pool(h_bad)
508
+ f_conf = _enc_pool(h_conf)
509
+ fa_hon = _enc_pool(a_hon)
510
+ fa_bad = _enc_pool(a_bad)
511
+ fa_conf = _enc_pool(a_conf)
512
+ assert f_hon is not None and f_bad is not None
513
+
514
+ f_neg = torch.cat([f_hon, f_conf], dim=0) if f_conf is not None else f_hon
515
+ f_all = torch.cat([f_bad, f_neg], dim=0)
516
+ has_anchors = fa_hon is not None and fa_bad is not None
517
+ if has_anchors:
518
+ assert fa_hon is not None and fa_bad is not None
519
+ fa_neg = (
520
+ torch.cat([fa_hon, fa_conf if fa_conf is not None else fa_hon[: f_conf.shape[0]]], dim=0)
521
+ if f_conf is not None
522
+ else fa_hon
523
+ )
524
+ fa_all = torch.cat([fa_bad, fa_neg], dim=0)
525
+ else:
526
+ fa_all = None
527
+
528
+ oof_sae = np.zeros(len(y_all), dtype=np.float32)
529
+ n_bad = f_bad.shape[0]
530
+ n_hon = f_hon.shape[0]
531
+ for tr, te in splits:
532
+ tr_bad = tr[tr < n_bad]
533
+ tr_hon = tr[(tr >= n_bad) & (tr < n_bad + n_hon)] - n_bad
534
+ tr_conf = tr[tr >= n_bad + n_hon] - (n_bad + n_hon)
535
+ sub_attr = select_confounder_penalized_subspace(
536
+ f_honest=f_hon[tr_hon],
537
+ f_bad=f_bad[tr_bad],
538
+ f_confounder=f_conf[tr_conf] if (f_conf is not None and len(tr_conf) > 0) else None,
539
+ f_anchor_honest=fa_hon[tr_hon] if fa_hon is not None else None,
540
+ f_anchor_bad=fa_bad[tr_bad] if fa_bad is not None else None,
541
+ f_anchor_confounder=(
542
+ fa_conf[tr_conf]
543
+ if (fa_conf is not None and f_conf is not None and len(tr_conf) > 0)
544
+ else None
545
+ ),
546
+ lambda_confound=self.lambda_confound,
547
+ top_k_bad=self.top_k_bad,
548
+ top_k_anchor=self.top_k_anchor,
549
+ )
550
+ bad_ids = torch.tensor(sub_attr["bad_latent_ids"], dtype=torch.long)
551
+ for j in te:
552
+ fj = f_all[j]
553
+ bad_cur = float(fj[bad_ids].mean().item()) if bad_ids.numel() > 0 else 0.0
554
+ if fa_all is not None:
555
+ aj = fa_all[j]
556
+ ref_c = aj.clone()
557
+ if bad_ids.numel() > 0:
558
+ ref_c[bad_ids] = 0.0
559
+ _, inst_i = torch.topk(ref_c, k=min(self.top_k_anchor, ref_c.shape[0]))
560
+ cos_i = F.cosine_similarity(
561
+ fj[inst_i].unsqueeze(0), ref_c[inst_i].unsqueeze(0), dim=-1
562
+ ).item()
563
+ decay = max(0.0, 1.0 - cos_i)
564
+ surge = (
565
+ float(torch.clamp(fj[bad_ids] - aj[bad_ids], min=0.0).mean().item())
566
+ if bad_ids.numel() > 0
567
+ else 0.0
568
+ )
569
+ oof_sae[j] = 0.08 * decay + 5.0 * surge + 2.0 * bad_cur
570
+ else:
571
+ oof_sae[j] = 7.0 * bad_cur
572
+
573
+ sae_auroc = _binary_auroc(y_all, oof_sae)
574
+ sae_fpr80 = _fpr_at_tpr(y_all, oof_sae, 0.80)
575
+
576
+ gap = round(float(sae_auroc - dense_auroc), 4)
577
+ if self.mode == "dense":
578
+ chosen = "dense_latch"
579
+ rationale = "Explicitly requested dense_latch mode."
580
+ elif self.mode == "sae":
581
+ chosen = "sae_anchor_latch"
582
+ rationale = "Explicitly requested sae_anchor_latch mode."
583
+ elif dense_auroc >= self.dense_min_auroc and gap < self.superposition_margin and dense_fpr80 <= 0.10:
584
+ chosen = "dense_latch"
585
+ rationale = (
586
+ f"Linear separability holds at layer {layer_index}/{num_layers} "
587
+ f"(Dense AUROC={dense_auroc:.4f}, SAE gap={gap:+.4f} < {self.superposition_margin:.2f}); "
588
+ "compiled lightweight dense_latch."
589
+ )
590
+ else:
591
+ chosen = "sae_anchor_latch"
592
+ rationale = (
593
+ f"Superposition or confounder entanglement degrades dense probe at layer {layer_index}/{num_layers} "
594
+ f"(Dense AUROC={dense_auroc:.4f} vs SAE AUROC={sae_auroc:.4f}, gap={gap:+.4f}); "
595
+ "compiled confounder-penalized sae_anchor_latch."
596
+ )
597
+
598
+ route = AdaptiveRouteDecision(
599
+ selected_mode=chosen,
600
+ dense_cv_auroc=round(float(dense_auroc), 4),
601
+ sae_cv_auroc=round(float(sae_auroc), 4),
602
+ superposition_gap=gap,
603
+ dense_fpr_at_80_tpr=round(float(dense_fpr80), 4),
604
+ sae_fpr_at_80_tpr=round(float(sae_fpr80), 4),
605
+ rationale=rationale,
606
+ )
607
+
608
+ sv_tensor = _to_t(steer_vectors)
609
+
610
+ if chosen == "dense_latch":
611
+ w_full, b_full, mu_full, sd_full = fit_l2_logistic_probe(X_all_d, y_all, seed=self.seed)
612
+ # Use out-of-fold scores for honest conformal threshold calibration!
613
+ n_b = len(X_bad_d)
614
+ n_h = len(X_hon_d)
615
+ cal = calibrate_conformal_threshold(
616
+ pos_scores=oof_dense[:n_b],
617
+ clean_neg_scores=oof_dense[n_b : n_b + n_h],
618
+ confounder_neg_scores=oof_dense[n_b + n_h :] if X_conf_d is not None else None,
619
+ max_benign_fpr=self.max_benign_fpr,
620
+ min_floor=0.45,
621
+ )
622
+ eff_steer_layers = steer_layers or (layer_index,)
623
+ if sv_tensor is None:
624
+ # Default steering direction = manifold-aligned RMS logistic direction (pointing toward bad/sabotage)
625
+ rms_dir = fit_manifold_steering_direction(X_all_d, y_all, seed=self.seed)
626
+ sv_tensor = rms_dir.unsqueeze(0).repeat(len(eff_steer_layers), 1)
627
+ gate = LatchGate(
628
+ mode="dense_latch",
629
+ backbone_id=backbone_id,
630
+ layer_index=layer_index,
631
+ num_layers=num_layers,
632
+ d_model=d_model,
633
+ threshold_tau=cal["threshold_tau"],
634
+ probe_weight=w_full,
635
+ probe_bias=b_full,
636
+ scaler_mean=mu_full,
637
+ scaler_scale=sd_full,
638
+ unit_norm_input=True,
639
+ steer_layers=eff_steer_layers,
640
+ steer_vectors=sv_tensor,
641
+ alpha_steer=alpha_steer,
642
+ abort_step=abort_step,
643
+ metadata={"route": asdict(route), "calibration": cal},
644
+ ).to(dev)
645
+ else:
646
+ assert sae_obj is not None
647
+ full_attr = select_confounder_penalized_subspace(
648
+ f_honest=f_hon,
649
+ f_bad=f_bad,
650
+ f_confounder=f_conf,
651
+ f_anchor_honest=fa_hon,
652
+ f_anchor_bad=fa_bad,
653
+ f_anchor_confounder=fa_conf,
654
+ lambda_confound=self.lambda_confound,
655
+ top_k_bad=self.top_k_bad,
656
+ top_k_anchor=self.top_k_anchor,
657
+ )
658
+ n_b = len(X_bad_d)
659
+ n_h = len(X_hon_d)
660
+ cal = calibrate_conformal_threshold(
661
+ pos_scores=oof_sae[:n_b],
662
+ clean_neg_scores=oof_sae[n_b : n_b + n_h],
663
+ confounder_neg_scores=oof_sae[n_b + n_h :] if X_conf_d is not None else None,
664
+ max_benign_fpr=self.max_benign_fpr,
665
+ min_floor=0.0,
666
+ )
667
+ eff_steer_layers = steer_layers or (layer_index,)
668
+ if sv_tensor is None and len(full_attr["bad_latent_ids"]) > 0:
669
+ bad_dec = sae_obj.W_dec[torch.tensor(full_attr["bad_latent_ids"], device=dev)].mean(dim=0)
670
+ sv_tensor = F.normalize(bad_dec.detach().cpu().unsqueeze(0), dim=-1).repeat(
671
+ len(eff_steer_layers), 1
672
+ )
673
+ gate = LatchGate(
674
+ mode="sae_anchor_latch",
675
+ backbone_id=backbone_id,
676
+ layer_index=layer_index,
677
+ num_layers=num_layers,
678
+ d_model=d_model,
679
+ threshold_tau=cal["threshold_tau"],
680
+ steer_layers=eff_steer_layers,
681
+ steer_vectors=sv_tensor,
682
+ alpha_steer=alpha_steer,
683
+ sae=sae_obj,
684
+ bad_latent_ids=full_attr["bad_latent_ids"],
685
+ anchor_latent_ids=full_attr["anchor_latent_ids"],
686
+ top_k_instance_anchor=self.top_k_anchor,
687
+ abort_step=abort_step,
688
+ metadata={
689
+ "route": asdict(route),
690
+ "calibration": cal,
691
+ "sae_stats": sae_stats,
692
+ "bad_cohens_d_top10": full_attr["bad_cohens_d"][:10],
693
+ },
694
+ ).to(dev)
695
+
696
+ report = CompileReport(
697
+ route=route,
698
+ calibration=cal,
699
+ compile_seconds=time.perf_counter() - t0,
700
+ sae_stats=sae_stats,
701
+ )
702
+ return gate, report
703
+
704
+
705
+ @dataclass(frozen=True)
706
+ class CounterfactualTracePair:
707
+ """Standard counterfactual JSONL record produced by ``mendmark export-latchgate`` or user logs."""
708
+
709
+ pair_id: str
710
+ honest_messages: list[dict[str, str]]
711
+ bad_messages: list[dict[str, str]]
712
+ honest_completion: str
713
+ bad_completion: str
714
+ confounder_messages: list[dict[str, str]] | None = None
715
+ confounder_completion: str | None = None
716
+ category: str = "tool_sabotage"
717
+ severity: str = "critical"
718
+ metadata: dict[str, Any] = field(default_factory=dict)
719
+
720
+
721
+ def load_counterfactual_jsonl(path: str | Path) -> list[CounterfactualTracePair]:
722
+ """Load and validate counterfactual calibration pairs from a JSONL file."""
723
+ resolved = Path(path).expanduser().resolve()
724
+ if not resolved.is_file():
725
+ raise LatchGateError(f"Counterfactual JSONL file does not exist: {resolved}")
726
+ pairs: list[CounterfactualTracePair] = []
727
+ for line_no, raw_line in enumerate(resolved.read_text(encoding="utf-8").splitlines(), start=1):
728
+ stripped = raw_line.strip()
729
+ if not stripped:
730
+ continue
731
+ try:
732
+ row = json.loads(stripped)
733
+ except json.JSONDecodeError as exc:
734
+ raise LatchGateError(f"Invalid JSON on line {line_no} of {resolved}: {exc}") from exc
735
+ if not isinstance(row, dict):
736
+ raise LatchGateError(f"Line {line_no} of {resolved} must be a JSON object.")
737
+ if row.get("schema_version", "latchgate.pair.v1") != "latchgate.pair.v1":
738
+ raise LatchGateError(
739
+ f"Unsupported schema_version on line {line_no}: {row.get('schema_version')!r}"
740
+ )
741
+ for req in ("pair_id", "honest_messages", "bad_messages", "honest_completion", "bad_completion"):
742
+ if req not in row:
743
+ raise LatchGateError(f"Missing required field {req!r} on line {line_no} of {resolved}")
744
+ pairs.append(
745
+ CounterfactualTracePair(
746
+ pair_id=str(row["pair_id"]),
747
+ honest_messages=list(row["honest_messages"]),
748
+ bad_messages=list(row["bad_messages"]),
749
+ honest_completion=str(row["honest_completion"]),
750
+ bad_completion=str(row["bad_completion"]),
751
+ confounder_messages=(
752
+ list(row["confounder_messages"])
753
+ if row.get("confounder_messages") is not None
754
+ else None
755
+ ),
756
+ confounder_completion=(
757
+ str(row["confounder_completion"])
758
+ if row.get("confounder_completion") is not None
759
+ else None
760
+ ),
761
+ category=str(row.get("category", "tool_sabotage")),
762
+ severity=str(row.get("severity", "critical")),
763
+ metadata=dict(row.get("metadata", {})),
764
+ )
765
+ )
766
+ if not pairs:
767
+ raise LatchGateError(f"Counterfactual JSONL file {resolved} contains no records.")
768
+ return pairs
769
+
770
+
771
+ @torch.no_grad()
772
+ def extract_llm_activations_from_pairs(
773
+ model: Any,
774
+ tokenizer: Any,
775
+ pairs: list[CounterfactualTracePair],
776
+ *,
777
+ layer_index: int | None = None,
778
+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor | None, int, int]:
779
+ """Extract 57.1%-depth residual vectors from ``(honest, bad, optional confounder)`` JSONL pairs."""
780
+ layers = getattr(getattr(model, "model", model), "layers", None)
781
+ if layers is None:
782
+ raise LatchGateError("Model must expose decoder blocks at model.model.layers or model.layers.")
783
+ num_layers = len(layers)
784
+ target_layer = int(layer_index) if layer_index is not None else int(round(0.5714 * num_layers))
785
+ dev = next(model.parameters()).device
786
+
787
+ def _encode_one(messages: list[dict[str, str]], completion: str) -> torch.Tensor:
788
+ if hasattr(tokenizer, "apply_chat_template") and getattr(tokenizer, "chat_template", None):
789
+ prompt = tokenizer.apply_chat_template(
790
+ messages, tokenize=False, add_generation_prompt=True
791
+ )
792
+ else:
793
+ prompt = "\n".join(f"{m.get('role', 'user')}: {m.get('content', '')}" for m in messages) + "\nassistant: "
794
+ prompt_ids = tokenizer.encode(prompt, add_special_tokens=True)
795
+ raw_enc = tokenizer(prompt + completion, return_tensors="pt", add_special_tokens=True)
796
+ full_enc = {
797
+ k: (v.to(dev) if isinstance(v, torch.Tensor) else v) for k, v in raw_enc.items()
798
+ }
799
+ captured: dict[str, torch.Tensor] = {}
800
+
801
+ def _hook(_mod: Any, _inp: Any, out: Any) -> None:
802
+ h = out[0] if isinstance(out, tuple) else out
803
+ captured["h"] = h[0].detach().to(torch.float32).cpu()
804
+
805
+ handle = layers[target_layer].register_forward_hook(_hook)
806
+ try:
807
+ inner = getattr(model, "model", model)
808
+ inner(**full_enc, use_cache=False)
809
+ finally:
810
+ handle.remove()
811
+
812
+ h_seq = captured["h"]
813
+ boundary_pos = min(max(0, len(prompt_ids) - 1), h_seq.shape[0] - 1)
814
+ # Mean-pool across early completion window starting at the pre-action decision boundary
815
+ end_pos = min(h_seq.shape[0], boundary_pos + 28)
816
+ return h_seq[boundary_pos:end_pos].mean(dim=0)
817
+
818
+ hon_list: list[torch.Tensor] = []
819
+ bad_list: list[torch.Tensor] = []
820
+ conf_list: list[torch.Tensor] = []
821
+ for pair in pairs:
822
+ hon_list.append(_encode_one(pair.honest_messages, pair.honest_completion))
823
+ bad_list.append(_encode_one(pair.bad_messages, pair.bad_completion))
824
+ if pair.confounder_messages is not None and pair.confounder_completion is not None:
825
+ conf_list.append(_encode_one(pair.confounder_messages, pair.confounder_completion))
826
+
827
+ conf_t = torch.stack(conf_list, dim=0) if len(conf_list) >= 2 else None
828
+ return torch.stack(hon_list, dim=0), torch.stack(bad_list, dim=0), conf_t, target_layer, num_layers
829
+
830
+
831
+ def fit_latchgate(**kwargs: Any) -> tuple[LatchGate, CompileReport]:
832
+ """Convenience functional wrapper around ``LatchCompiler(...).fit(...)``."""
833
+ compiler_keys = {
834
+ "mode",
835
+ "max_benign_fpr",
836
+ "lambda_confound",
837
+ "superposition_margin",
838
+ "dense_min_auroc",
839
+ "top_k_bad",
840
+ "top_k_anchor",
841
+ "d_sae",
842
+ "seed",
843
+ }
844
+ comp_kwargs = {k: kwargs.pop(k) for k in list(kwargs.keys()) if k in compiler_keys}
845
+ compiler = LatchCompiler(**comp_kwargs)
846
+ return compiler.fit(**kwargs)