knowledge-drift-experiments / analyze_single.py
Raniahossam33's picture
Upload folder using huggingface_hub
14b2318 verified
Raw
History Blame Contribute Delete
55.4 kB
#!/usr/bin/env python3
"""
analyze_single.py — Per-Model Disentanglement Analysis
=======================================================
Runs on cached hidden states only. Never touches the model.
Produces all per-model results, figures, and probe bundles.
Experiments:
[CORE] L1-ISTA probing: drift / uncertainty / correctness (true sparsity)
[IDEA-1] Drift vs Correctness dissociation — Cell B key result
[NEW-A] Null-space projection: project out uncertainty, re-probe drift
[NEW-B] Probe direction stability: L×L cosine matrix
[NEW-C] Logit lens: per-layer P(expected token) decay curve
[NEW-E] Temporal distance: drift score vs months since cutoff
[NEW-F] Calibration: reliability diagrams
[PERM] Permutation test at best layer
[SPARSE] Lambda-AUROC-neurons sparsity tradeoff
[REL] Per-relation breakdown
Outputs:
final_results.json Complete results summary
all_layer_results.json Per-layer JSON (resumable)
probe_bundle_{model}.npz Weight vectors + norms for cross-model
per_layer/layer_XX.json Individual layer results
figures/fig1..fig11.png Publication figures
Usage:
python analyze_single.py --model qwen25
python analyze_single.py --model llama31 --layers 20 21 22 23 24 25 26 27
python analyze_single.py --model qwen25 --skip_permutation --skip_logit_lens
"""
import argparse
import json
import logging
import time
import warnings
from datetime import datetime
from pathlib import Path
import numpy as np
import torch
import yaml
warnings.filterwarnings("ignore")
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s",
handlers=[logging.StreamHandler()])
logger = logging.getLogger(__name__)
# ─────────────────────────────────────────────────────────────────────────────
# CONFIG
# ─────────────────────────────────────────────────────────────────────────────
def load_config(config_path="models.yaml"):
with open(config_path) as f:
return yaml.safe_load(f)
# ─────────────────────────────────────────────────────────────────────────────
# L1-ISTA PROBE (true sparsity)
# ─────────────────────────────────────────────────────────────────────────────
def soft_threshold(w, lam):
return torch.sign(w) * torch.clamp(torch.abs(w) - lam, min=0.0)
class L1ProbeGPU:
"""L1-regularised logistic regression via ISTA on GPU."""
def __init__(self, dim, lam=1e-3, max_iter=2000, tol=1e-6, device="cuda"):
self.lam = lam
self.max_iter = max_iter
self.tol = tol
self.device = device
self.w = torch.zeros(dim, device=device)
self.b = torch.zeros(1, device=device)
self.coef_ = None
def _loss_grad(self, w, b, X, y):
z = torch.clamp(X @ w + b, -30, 30)
p = torch.sigmoid(z)
L = -((y * torch.log(p + 1e-12)) +
(1 - y) * torch.log(1 - p + 1e-12)).mean()
e = p - y
return L, (X.T @ e) / len(y), e.mean().unsqueeze(0)
def fit(self, X, y):
w = torch.zeros(X.shape[1], device=self.device)
b = torch.zeros(1, device=self.device)
lr = 1.0
for _ in range(self.max_iter):
L, gw, gb = self._loss_grad(w, b, X, y)
for _ in range(30):
wt = soft_threshold(w - lr * gw, lr * self.lam)
bt = b - lr * gb
Lt, _, _ = self._loss_grad(wt, bt, X, y)
if Lt <= L + 1e-4:
break
lr *= 0.5
lr = min(lr * 1.05, 10.0)
if (wt - w).abs().max().item() < self.tol:
w, b = wt, bt
break
w, b = wt, bt
self.w, self.b = w, b
self.coef_ = [w.cpu().numpy()]
return self
@torch.no_grad()
def predict_proba_t(self, X):
p = torch.sigmoid(torch.clamp(X @ self.w + self.b, -30, 30))
p = p.cpu().numpy().ravel()
return np.column_stack([1 - p, p])
class ProbeWrapper:
"""Wraps L1ProbeGPU with preprocessing and sklearn-like interface."""
def __init__(self, probe, mean, std, device):
self._p = probe
self._mean = mean
self._std = std
self._dev = device
self.coef_ = probe.coef_
def _to_gpu(self, X_np):
X = np.nan_to_num(X_np.astype(np.float32), nan=0., posinf=1e4, neginf=-1e4)
X = np.clip(X, -1e4, 1e4)
return torch.tensor((X - self._mean) / self._std,
dtype=torch.float32, device=self._dev)
def predict_proba(self, X_np):
return self._p.predict_proba_t(self._to_gpu(X_np))
@property
def w_np(self):
return self._p.w.cpu().numpy()
@property
def n_active(self):
return int(np.sum(self.w_np != 0))
@property
def norm_stats(self):
return {"mean": self._mean, "std": self._std}
def _preprocess(X_np):
X = np.nan_to_num(X_np.astype(np.float32), nan=0., posinf=1e4, neginf=-1e4)
X = np.clip(X, -1e4, 1e4)
m = X.mean(0, keepdims=True)
s = X.std(0, keepdims=True) + 1e-8
return X, m, s
def fit_probe(X_np, y_np, lam, device, max_iter=2000):
X, m, s = _preprocess(X_np)
Xt = torch.tensor((X - m) / s, dtype=torch.float32, device=device)
yt = torch.tensor(y_np.astype(np.float32), device=device)
p = L1ProbeGPU(Xt.shape[1], lam=lam, max_iter=max_iter, device=device)
p.fit(Xt, yt)
return ProbeWrapper(p, m, s, device)
def cv_auroc(X_np, y_np, lam, device, max_iter=500, n_splits=3):
from sklearn.model_selection import StratifiedKFold
from sklearn.metrics import roc_auc_score
min_c = min(int(y_np.sum()), int((1 - y_np).sum()))
k = min(n_splits, min_c)
if k < 2:
return 0.5
scores = []
for tr, va in StratifiedKFold(k, shuffle=True, random_state=42).split(X_np, y_np):
pw = fit_probe(X_np[tr], y_np[tr], lam, device, max_iter)
p = pw.predict_proba(X_np[va])[:, 1]
if len(np.unique(y_np[va])) > 1:
scores.append(roc_auc_score(y_np[va], p))
return float(np.mean(scores)) if scores else 0.5
def best_probe(X_np, y_np, device, lambda_grid, max_iter=2000, cv_max_iter=500):
best_au, best_lam = 0.0, lambda_grid[0]
for lam in lambda_grid:
au = cv_auroc(X_np, y_np, lam, device, max_iter=cv_max_iter)
if au > best_au:
best_au, best_lam = au, lam
return fit_probe(X_np, y_np, best_lam, device, max_iter), best_au, best_lam
# ─────────────────────────────────────────────────────────────────────────────
# UTILITIES
# ─────────────────────────────────────────────────────────────────────────────
def cosine(w1, w2):
n1, n2 = np.linalg.norm(w1), np.linalg.norm(w2)
return float(np.dot(w1, w2) / (n1 * n2 + 1e-12))
def jaccard(w1, w2):
s1 = set(np.where(w1 != 0)[0])
s2 = set(np.where(w2 != 0)[0])
u = len(s1 | s2)
return len(s1 & s2) / u if u > 0 else 0.0
# ─────────────────────────────────────────────────────────────────────────────
# PER-LAYER ANALYSIS
# ─────────────────────────────────────────────────────────────────────────────
def analyze_layer(layer, results, device, lambda_grid, max_iter=2000,
cv_max_iter=500):
from sklearn.metrics import roc_auc_score
t0 = time.time()
drifted = [r for r in results if r["is_drifted"]]
non_drifted = [r for r in results if not r["is_drifted"]]
X_all = np.array([r["hidden_states"][layer] for r in results])
y_drift = np.array([int(r["is_drifted"]) for r in results])
y_corr = np.array([int(r.get("correct", False)) for r in results])
# 1. Drift probe
dp, dp_au, dp_lam = best_probe(X_all, y_drift, device, lambda_grid,
max_iter, cv_max_iter)
w_d = dp.w_np
# 2. Uncertainty probe (on non-drifted only)
X_nd = np.array([r["hidden_states"][layer] for r in non_drifted])
ct = float(np.median([r["top_prob"] for r in non_drifted]))
y_unc = np.array([int(r["top_prob"] < ct) for r in non_drifted])
if y_unc.sum() < 5 or (len(y_unc) - y_unc.sum()) < 5:
ct = 0.5
y_unc = np.array([int(r["top_prob"] < ct) for r in non_drifted])
up, up_au, up_lam = best_probe(X_nd, y_unc, device, lambda_grid,
max_iter, cv_max_iter)
w_u = up.w_np
# 3. Correctness probe
cp, cp_au, cp_lam = None, 0.5, 0.0
w_c = np.zeros_like(w_d)
nc, nw = int(y_corr.sum()), int((1 - y_corr).sum())
if nc >= 10 and nw >= 10:
cp, cp_au, cp_lam = best_probe(X_all, y_corr, device, lambda_grid,
max_iter, cv_max_iter)
w_c = cp.w_np
# 4. Cosines + Jaccard
cos_du = cosine(w_d, w_u)
cos_dc = cosine(w_d, w_c)
cos_uc = cosine(w_u, w_c)
jac_du = jaccard(w_d, w_u)
jac_dc = jaccard(w_d, w_c)
# 5. [NEW-A] Null-space projection
ns_au = 0.5
wu_n = np.linalg.norm(w_u)
if wu_n > 1e-8:
u_hat = w_u / wu_n
X_perp = X_all - (X_all @ u_hat)[:, None] * u_hat[None, :]
_, ns_au, _ = best_probe(X_perp, y_drift, device, lambda_grid,
max_iter, cv_max_iter)
# 6. Cell analysis (Idea 1)
cells = {}
for cname, samps in [
("A_confident_stable", [r for r in non_drifted if r["top_prob"] >= ct]),
("B_confident_drifted", [r for r in drifted if r["top_prob"] >= ct]),
("C_uncertain_stable", [r for r in non_drifted if r["top_prob"] < ct]),
("D_uncertain_drifted", [r for r in drifted if r["top_prob"] < ct]),
]:
if not samps:
cells[cname] = {"n": 0}
continue
Xc = np.array([r["hidden_states"][layer] for r in samps])
p_d = dp.predict_proba(Xc)[:, 1]
p_c = cp.predict_proba(Xc)[:, 1] if cp else np.full(len(samps), 0.5)
p_u = up.predict_proba(Xc)[:, 1]
cells[cname] = {
"n": len(samps),
"drift_mean": float(np.mean(p_d)),
"drift_std": float(np.std(p_d)),
"correct_mean": float(np.mean(p_c)),
"correct_std": float(np.std(p_c)),
"uncertainty_mean": float(np.mean(p_u)),
"uncertainty_std": float(np.std(p_u)),
"drift_flag_rate": float(np.mean(p_d > 0.5)),
"correct_flag_rate": float(np.mean(p_c > 0.5)),
}
# 7. Per-relation probing
per_rel = {}
for rel in sorted(set(r.get("relation", "unknown") for r in results)):
rs = [r for r in results if r.get("relation", "unknown") == rel]
nd_ = sum(1 for r in rs if r["is_drifted"])
ns_ = len(rs) - nd_
if nd_ < 5 or ns_ < 5:
continue
Xr = np.array([r["hidden_states"][layer] for r in rs])
ydr = np.array([int(r["is_drifted"]) for r in rs])
ycr = np.array([int(r.get("correct", False)) for r in rs])
try:
au_d = roc_auc_score(ydr, dp.predict_proba(Xr)[:, 1])
except Exception:
au_d = 0.5
try:
au_c = (roc_auc_score(ycr, cp.predict_proba(Xr)[:, 1])
if cp else 0.5)
except Exception:
au_c = 0.5
per_rel[rel] = {"drift_auroc": au_d, "correct_auroc": au_c,
"n_drifted": nd_, "n_stable": ns_}
return {
"layer": layer,
"drift_auroc": dp_au,
"uncertainty_auroc": up_au,
"correctness_auroc": cp_au,
"drift_lam": dp_lam,
"cos_du": cos_du,
"cos_dc": cos_dc,
"cos_uc": cos_uc,
"jaccard_du": jac_du,
"jaccard_dc": jac_dc,
"n_active_drift": dp.n_active,
"n_active_unc": up.n_active,
"n_active_corr": int(np.sum(w_c != 0)),
"null_space_drift_auroc": ns_au,
"conf_threshold": ct,
"cells": cells,
"per_relation": per_rel,
"elapsed_s": time.time() - t0,
# Kept in memory for figures/bundle — stripped before JSON save
"_w_drift": w_d, "_w_unc": w_u, "_w_corr": w_c,
"_probes": {"drift": dp, "uncertainty": up, "correctness": cp},
}
# ─────────────────────────────────────────────────────────────────────────────
# [NEW-B] PROBE DIRECTION STABILITY
# ─────────────────────────────────────────────────────────────────────────────
def probe_direction_stability(all_lr):
layers = sorted(k for k in all_lr if "_w_drift" in all_lr[k])
n = len(layers)
mat = np.eye(n)
for i, l1 in enumerate(layers):
for j, l2 in enumerate(layers):
if i != j:
mat[i, j] = cosine(all_lr[l1]["_w_drift"],
all_lr[l2]["_w_drift"])
return layers, mat
# ─────────────────────────────────────────────────────────────────────────────
# [NEW-C] LOGIT LENS
# ─────────────────────────────────────────────────────────────────────────────
def logit_lens_analysis(results, model_dir, model_key, device):
lm_path = Path(model_dir) / f"lm_head_{model_key}.npz"
if not lm_path.exists():
logger.warning(f"lm_head not found: {lm_path}")
return None
lm = np.load(str(lm_path), allow_pickle=True)
lm_w = torch.tensor(lm["lm_head"], dtype=torch.float32, device=device)
ln_w = torch.tensor(lm["ln_weight"], dtype=torch.float32, device=device)
ln_b = torch.tensor(lm["ln_bias"], dtype=torch.float32, device=device)
layers = sorted(results[0]["hidden_states"].keys())
drifted = [r for r in results if r["is_drifted"]]
stable = [r for r in results if not r["is_drifted"]]
def layer_prob(samps, layer):
probs = []
for r in samps:
h = torch.tensor(r["hidden_states"][layer],
dtype=torch.float32, device=device)
h_n = (h - h.mean()) / (h.std() + 1e-5) * ln_w + ln_b
lgts = torch.clamp(lm_w @ h_n, -60, 60)
p = torch.softmax(lgts, dim=-1)
probs.append(float(p.max().item()))
return float(np.mean(probs)) if probs else 0.0
data = {"layers": layers, "drifted": [], "stable": []}
for l in layers:
data["drifted"].append(layer_prob(drifted, l))
data["stable"].append(layer_prob(stable, l))
if (l + 1) % 7 == 0:
logger.info(f" logit lens L{l}: "
f"drifted={data['drifted'][-1]:.4f} "
f"stable={data['stable'][-1]:.4f}")
return data
# ─────────────────────────────────────────────────────────────────────────────
# [NEW-E] TEMPORAL DISTANCE
# ─────────────────────────────────────────────────────────────────────────────
def temporal_distance_analysis(results, cutoff_months):
bins, scores = [], []
for r in results:
if not r["is_drifted"]:
continue
cd = r.get("drift_date")
if cd in (None, "", "None"):
continue
try:
pts = str(cd).split("T")[0].split("-")
y = int(pts[0])
m = int(pts[1]) if len(pts) > 1 else 6
dist = (y - 2020) * 12 + m - cutoff_months
except Exception:
continue
if not (-60 <= dist <= 60):
continue
bins.append(dist)
scores.append(r.get("_drift_score", 0.5))
if len(bins) < 20:
return None
bins, scores = np.array(bins), np.array(scores)
corr = float(np.corrcoef(bins, scores)[0, 1])
logger.info(f" Temporal corr: {corr:.4f} ({len(bins)} samples)")
return {"bins": bins.tolist(), "scores": scores.tolist(),
"correlation": corr}
# ─────────────────────────────────────────────────────────────────────────────
# PERMUTATION TEST
# ─────────────────────────────────────────────────────────────────────────────
def permutation_test(results, best_layer, n_perms, device, lambda_grid):
from sklearn.metrics import roc_auc_score
logger.info(f"Permutation test ({n_perms}) at layer {best_layer}")
X = np.array([r["hidden_states"][best_layer] for r in results])
y = np.array([int(r["is_drifted"]) for r in results])
_, true_au, _ = best_probe(X, y, device, lambda_grid, cv_max_iter=300)
logger.info(f" True AUROC: {true_au:.4f}")
nulls = []
for i in range(n_perms):
y_perm = np.random.permutation(y)
pw = fit_probe(X, y_perm, 1e-3, device, max_iter=300)
p_n = pw.predict_proba(X)[:, 1]
try:
nulls.append(roc_auc_score(y_perm, p_n))
except Exception:
nulls.append(0.5)
if (i + 1) % 250 == 0:
logger.info(f" {i+1}/{n_perms} null_mean={np.mean(nulls):.4f}")
nulls = np.array(nulls)
p_val = float(np.mean(nulls >= true_au))
logger.info(f" p={p_val:.6f} null_mean={nulls.mean():.4f}")
return {"true_auroc": float(true_au), "null_mean": float(nulls.mean()),
"null_std": float(nulls.std()), "p_value": p_val, "n": n_perms}
# ─────────────────────────────────────────────────────────────────────────────
# SPARSITY CURVE
# ─────────────────────────────────────────────────────────────────────────────
def sparsity_curve(results, best_layer, device, sparsity_lambdas):
logger.info(f"Sparsity curve at layer {best_layer}")
X = np.array([r["hidden_states"][best_layer] for r in results])
y = np.array([int(r["is_drifted"]) for r in results])
out = []
for lam in sparsity_lambdas:
pw = fit_probe(X, y, lam, device, max_iter=500)
au = cv_auroc(X, y, lam, device, max_iter=300)
out.append({"lambda": lam, "n_active": pw.n_active, "auroc": float(au)})
logger.info(f" lam={lam:.2e} active={pw.n_active:>5d} AUROC={au:.4f}")
return out
# ─────────────────────────────────────────────────────────────────────────────
# PROBE BUNDLE EXPORT (for cross-model analysis)
# ─────────────────────────────────────────────────────────────────────────────
def export_probe_bundle(all_lr, best_layer, results, model_key, out_dir):
"""Export probe weight vectors + normalization stats for cross_model.py."""
bl = all_lr[best_layer]
X = np.array([r["hidden_states"][best_layer] for r in results])
_, m, s = _preprocess(X)
bundle = {
"model_key": model_key,
"best_layer": best_layer,
"hidden_dim": X.shape[1],
"n_samples": len(results),
"w_drift": bl["_w_drift"],
"w_unc": bl["_w_unc"],
"w_corr": bl["_w_corr"],
"norm_mean": m,
"norm_std": s,
"drift_auroc": bl["drift_auroc"],
"n_active_drift": bl["n_active_drift"],
"cos_du": bl["cos_du"],
"cos_dc": bl["cos_dc"],
}
path = Path(out_dir) / f"probe_bundle_{model_key}.npz"
np.savez_compressed(str(path), **{k: v for k, v in bundle.items()})
logger.info(f" Probe bundle: {path}")
# ─────────────────────────────────────────────────────────────────────────────
# FIGURES (same as v3 — consolidated)
# ─────────────────────────────────────────────────────────────────────────────
def save_figures(all_lr, model_dir, model_key, results,
stability_data=None, lens_data=None,
sparsity_data=None, temporal_data=None):
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
fig_dir = Path(model_dir) / "figures"
fig_dir.mkdir(parents=True, exist_ok=True)
layers = sorted(k for k in all_lr if "drift_auroc" in all_lr[k])
if len(layers) < 2:
return
best = max(layers, key=lambda l: all_lr[l]["drift_auroc"])
P = {"drift": "#e74c3c", "unc": "#3498db", "corr": "#2ecc71",
"null": "#9b59b6", "neu": "#e67e22"}
# ── Fig 1: 6-panel dashboard ──────────────────────────────────────────
fig, axes = plt.subplots(2, 3, figsize=(22, 12))
fig.suptitle(f"[{model_key}] Disentanglement Dashboard", fontsize=16,
fontweight="bold")
ax = axes[0, 0]
for key, lbl, col, ls in [
("drift_auroc", "Drift", P["drift"], "-"),
("uncertainty_auroc", "Uncertainty", P["unc"], "--"),
("correctness_auroc", "Correctness", P["corr"], "-."),
("null_space_drift_auroc", "Drift (null-space)", P["null"], ":"),
]:
ax.plot(layers, [all_lr[l].get(key, np.nan) for l in layers],
f"o{ls}", color=col, lw=2, ms=5, label=lbl)
ax.axvline(best, color="gray", ls="--", alpha=0.4)
ax.set(xlabel="Layer", ylabel="AUROC", title="Probe AUROC by Layer",
ylim=(0.4, 1.05))
ax.legend(fontsize=9)
ax.grid(alpha=0.3)
ax = axes[0, 1]
for key, lbl, col in [
("cos_du", "|cos(drift, unc)|", P["drift"]),
("cos_dc", "|cos(drift, corr)|", P["corr"]),
("cos_uc", "|cos(unc, corr)|", P["unc"]),
]:
ax.plot(layers, [abs(all_lr[l].get(key, 0)) for l in layers],
"o-", color=col, lw=2, ms=5, label=lbl)
ax.axhline(0.3, color="gray", ls="--", alpha=0.4, label="0.3 threshold")
ax.set(xlabel="Layer", ylabel="|Cosine Similarity|",
title="3-Way Disentanglement", ylim=(0, 1.0))
ax.legend(fontsize=9)
ax.grid(alpha=0.3)
ax = axes[0, 2]
ax.plot(layers, [all_lr[l].get("n_active_drift", 0) for l in layers],
"o-", color=P["drift"], lw=2, ms=5, label="Drift")
ax.plot(layers, [all_lr[l].get("n_active_unc", 0) for l in layers],
"s-", color=P["unc"], lw=2, ms=5, label="Unc")
ax.plot(layers, [all_lr[l].get("n_active_corr", 0) for l in layers],
"^-", color=P["corr"], lw=2, ms=5, label="Corr")
ax2 = ax.twinx()
ax2.plot(layers, [all_lr[l].get("jaccard_du", 0) for l in layers],
"D--", color=P["null"], lw=2, ms=4, label="J(d,u)")
ax2.plot(layers, [all_lr[l].get("jaccard_dc", 0) for l in layers],
"P--", color=P["neu"], lw=2, ms=4, label="J(d,c)")
ax.set(xlabel="Layer", ylabel="Active neurons",
title="True Sparsity & Jaccard")
ax2.set_ylabel("Jaccard")
ax.legend(loc="upper left", fontsize=8)
ax2.legend(loc="upper right", fontsize=8)
ax.grid(alpha=0.3)
ax = axes[1, 0]
d_au = [all_lr[l]["drift_auroc"] for l in layers]
ns_au = [all_lr[l].get("null_space_drift_auroc", np.nan) for l in layers]
ax.plot(layers, d_au, "o-", color=P["drift"], lw=2.5, ms=7, label="Full")
ax.plot(layers, ns_au, "s--", color=P["null"], lw=2, ms=7,
label="Null-space of unc")
ax.fill_between(layers, ns_au, d_au, alpha=0.15, color=P["null"])
ax.set(xlabel="Layer", ylabel="AUROC",
title="[NEW-A] Null-Space Projection", ylim=(0.4, 1.05))
ax.legend(fontsize=10)
ax.grid(alpha=0.3)
ax = axes[1, 1]
bl = best
cells = all_lr[bl].get("cells", {})
cnames = ["A_confident_stable", "B_confident_drifted",
"C_uncertain_stable", "D_uncertain_drifted"]
if cells and any(cells.get(c, {}).get("n", 0) > 0 for c in cnames):
ns_ = [cells.get(c, {}).get("n", 0) for c in cnames]
dm_ = [cells.get(c, {}).get("drift_mean", 0) for c in cnames]
cm_ = [cells.get(c, {}).get("correct_mean", 0) for c in cnames]
x = np.arange(4)
w = 0.35
ax.bar(x - w / 2, dm_, w, color=P["drift"], label="Drift",
edgecolor="black", lw=0.5)
ax.bar(x + w / 2, cm_, w, color=P["corr"], label="Correctness",
edgecolor="black", lw=0.5)
ax.set_xticks(x)
ax.set_xticklabels([f"{c[:3]}\nn={ns_[i]}" for i, c in enumerate(cnames)],
fontsize=9)
ax.axhline(0.5, color="gray", ls="--", alpha=0.5)
ax.set(ylabel="Mean score", title="[IDEA-1] Cell B Dissociation",
ylim=(0, 1.1))
ax.legend(fontsize=9)
ax.grid(alpha=0.3, axis="y")
ax = axes[1, 2]
if lens_data:
ls_ = lens_data["layers"]
ax.plot(ls_, lens_data["stable"], "o-", color=P["unc"], lw=2,
label="Stable")
ax.plot(ls_, lens_data["drifted"], "s--", color=P["drift"], lw=2,
label="Drifted")
ax.fill_between(ls_, lens_data["drifted"], lens_data["stable"],
alpha=0.2, color=P["drift"])
ax.axvline(best, color="gray", ls=":", lw=1.5)
ax.set(xlabel="Layer", ylabel="P(expected token)",
title="[NEW-C] Logit Lens")
ax.legend(fontsize=10)
ax.grid(alpha=0.3)
else:
ax.text(0.5, 0.5, "Logit lens\n(enable with flag)",
ha="center", va="center", transform=ax.transAxes)
plt.tight_layout()
plt.savefig(fig_dir / "fig1_dashboard.png", dpi=300, bbox_inches="tight")
plt.close()
logger.info(" fig1 saved")
# ── Fig 2: Idea 1 deep dive ──────────────────────────────────────────
if cells and any(cells.get(c, {}).get("n", 0) > 0 for c in cnames):
fig, axes2 = plt.subplots(1, 3, figsize=(21, 7))
fig.suptitle(f"[{model_key}] IDEA-1: Cell B Dissociation (Layer {best})",
fontsize=14, fontweight="bold")
clrs = [P["unc"], P["drift"], "#95a5a6", P["neu"]]
ns_ = [cells.get(c, {}).get("n", 0) for c in cnames]
xlbls = [f"Cell {chr(65+i)}\nn={ns_[i]}" for i in range(4)]
x = np.arange(4)
w = 0.6
for ax, key, ekey, title in [
(axes2[0], "drift_mean", "drift_std", "Drift Probe"),
(axes2[1], "correct_mean", "correct_std", "Correctness Probe"),
(axes2[2], "uncertainty_mean", "uncertainty_std", "Uncertainty Probe"),
]:
vals = [cells.get(c, {}).get(key, 0) for c in cnames]
errs = [cells.get(c, {}).get(ekey, 0) for c in cnames]
ax.bar(x, vals, w, yerr=errs, capsize=7, color=clrs,
edgecolor="black", lw=0.7, alpha=0.85)
if vals[1] > 0:
ax.annotate("Cell B", xy=(1, vals[1] + errs[1]),
xytext=(1.6, vals[1] + errs[1] + 0.12),
arrowprops=dict(arrowstyle="->", color="red"),
fontsize=9, color="red", fontweight="bold")
ax.axhline(0.5, color="gray", ls="--", alpha=0.6)
ax.set_xticks(x)
ax.set_xticklabels(xlbls, fontsize=9)
ax.set(ylabel="Mean score", title=title, ylim=(0, 1.2))
ax.grid(alpha=0.3, axis="y")
plt.tight_layout()
plt.savefig(fig_dir / "fig2_idea1_dissociation.png",
dpi=300, bbox_inches="tight")
plt.close()
logger.info(" fig2 saved")
# ── Fig 3: 3×3 cosine heatmap ────────────────────────────────────────
bl = best
mat = np.array([
[1.0, all_lr[bl]["cos_du"], all_lr[bl]["cos_dc"]],
[all_lr[bl]["cos_du"], 1.0, all_lr[bl]["cos_uc"]],
[all_lr[bl]["cos_dc"], all_lr[bl]["cos_uc"], 1.0],
])
fig, ax = plt.subplots(figsize=(8, 7))
im = ax.imshow(mat, cmap="RdBu_r", vmin=-1, vmax=1)
lbls = ["Drift", "Uncertainty", "Correctness"]
ax.set_xticks(range(3))
ax.set_yticks(range(3))
ax.set_xticklabels(lbls, fontsize=13)
ax.set_yticklabels(lbls, fontsize=13)
for i in range(3):
for j in range(3):
c = "white" if abs(mat[i, j]) > 0.5 else "black"
ax.text(j, i, f"{mat[i,j]:+.3f}", ha="center", va="center",
fontsize=14, fontweight="bold", color=c)
ax.set_title(f"[{model_key}] Cosine Matrix — Layer {bl}", fontsize=13)
plt.colorbar(im, ax=ax, shrink=0.8)
plt.tight_layout()
plt.savefig(fig_dir / "fig3_cosine_matrix.png", dpi=300, bbox_inches="tight")
plt.close()
logger.info(" fig3 saved")
# ── Fig 4: PCA ───────────────────────────────────────────────────────
if "_w_drift" in all_lr.get(best, {}):
from sklearn.decomposition import PCA
bl = best
X_b = np.array([r["hidden_states"][bl] for r in results])
is_d = np.array([r["is_drifted"] for r in results])
is_c = np.array([r.get("correct", False) for r in results])
pca = PCA(n_components=2)
X2 = pca.fit_transform(X_b)
Xsc = (X_b - X_b.mean(0)) / (X_b.std(0) + 1e-8)
w_d = all_lr[bl]["_w_drift"]
w_u = all_lr[bl]["_w_unc"]
w_c = all_lr[bl]["_w_corr"]
nd, nu, nc_ = (np.linalg.norm(w_d), np.linalg.norm(w_u),
np.linalg.norm(w_c))
pd_ = Xsc @ (w_d / (nd + 1e-8))
pu_ = Xsc @ (w_u / (nu + 1e-8))
pc_ = (Xsc @ (w_c / (nc_ + 1e-8)) if nc_ > 1e-8
else np.zeros(len(results)))
fig, axes3 = plt.subplots(1, 3, figsize=(22, 7))
fig.suptitle(f"[{model_key}] Geometry — Layer {bl}", fontsize=14,
fontweight="bold")
ax = axes3[0]
ax.scatter(X2[~is_d, 0], X2[~is_d, 1], c=P["unc"], alpha=0.3,
s=20, label="Stable", edgecolors="none")
ax.scatter(X2[is_d, 0], X2[is_d, 1], c=P["drift"], alpha=0.7,
s=50, label="Drifted", edgecolors="black", lw=0.3,
marker="*")
ax.set(xlabel=f"PC1 ({pca.explained_variance_ratio_[0]:.1%})",
ylabel=f"PC2 ({pca.explained_variance_ratio_[1]:.1%})",
title="PCA")
ax.legend()
ax.grid(alpha=0.2)
ax = axes3[1]
ax.scatter(pd_[~is_d], pu_[~is_d], c=P["unc"], alpha=0.3, s=20,
label="Stable", edgecolors="none")
ax.scatter(pd_[is_d], pu_[is_d], c=P["drift"], alpha=0.7, s=50,
label="Drifted", edgecolors="black", lw=0.3, marker="*")
ax.axhline(0, color="gray", ls="--", alpha=0.3)
ax.axvline(0, color="gray", ls="--", alpha=0.3)
ax.set(xlabel="Drift direction", ylabel="Uncertainty direction",
title=f"cos={all_lr[bl]['cos_du']:+.3f}")
ax.legend()
ax.grid(alpha=0.2)
ax = axes3[2]
ax.scatter(pd_[is_c], pc_[is_c], c=P["corr"], alpha=0.5, s=20,
label="Correct", edgecolors="none")
ax.scatter(pd_[~is_c], pc_[~is_c], c=P["drift"], alpha=0.5, s=20,
label="Incorrect", edgecolors="none")
ax.axhline(0, color="gray", ls="--", alpha=0.3)
ax.axvline(0, color="gray", ls="--", alpha=0.3)
ax.set(xlabel="Drift direction", ylabel="Correctness direction",
title=f"cos={all_lr[bl]['cos_dc']:+.3f}")
ax.legend()
ax.grid(alpha=0.2)
plt.tight_layout()
plt.savefig(fig_dir / "fig4_pca_projection.png",
dpi=300, bbox_inches="tight")
plt.close()
logger.info(" fig4 saved")
# ── Fig 5: Direction stability ───────────────────────────────────────
if stability_data:
sl, sm = stability_data
fig, axes4 = plt.subplots(1, 2, figsize=(18, 7))
fig.suptitle(f"[{model_key}] [NEW-B] Direction Stability", fontsize=14,
fontweight="bold")
ax = axes4[0]
im = ax.imshow(sm, cmap="RdBu_r", vmin=-1, vmax=1, aspect="auto")
step = max(1, len(sl) // 8)
tp = list(range(0, len(sl), step))
ax.set_xticks(tp)
ax.set_yticks(tp)
ax.set_xticklabels([sl[i] for i in tp])
ax.set_yticklabels([sl[i] for i in tp])
ax.set(xlabel="Layer", ylabel="Layer",
title="cos(w_drift_i, w_drift_j)")
plt.colorbar(im, ax=ax, shrink=0.8)
ax = axes4[1]
mean_c = [np.mean([sm[i, j] for j in range(len(sl)) if j != i])
for i in range(len(sl))]
d_au_s = [all_lr[l]["drift_auroc"] for l in sl]
ax.plot(sl, mean_c, "o-", color=P["drift"], lw=2, ms=6,
label="Mean cross-layer cos")
ax3 = ax.twinx()
ax3.plot(sl, d_au_s, "s--", color="#7f8c8d", lw=2, ms=6,
label="Drift AUROC")
ax.set(xlabel="Layer", ylabel="Mean cosine",
title="Stability vs AUROC")
ax3.set_ylabel("AUROC")
ax.legend(loc="lower left", fontsize=9)
ax3.legend(loc="lower right", fontsize=9)
ax.grid(alpha=0.3)
plt.tight_layout()
plt.savefig(fig_dir / "fig5_probe_stability.png",
dpi=300, bbox_inches="tight")
plt.close()
logger.info(" fig5 saved")
# ── Fig 6: Logit lens ────────────────────────────────────────────────
if lens_data:
fig, axes5 = plt.subplots(1, 2, figsize=(16, 6))
fig.suptitle(f"[{model_key}] [NEW-C] Logit Lens", fontsize=14,
fontweight="bold")
ls_ = lens_data["layers"]
axes5[0].plot(ls_, lens_data["stable"], "o-", color=P["unc"], lw=2.5,
ms=7, label="Stable")
axes5[0].plot(ls_, lens_data["drifted"], "s--", color=P["drift"],
lw=2.5, ms=7, label="Drifted")
axes5[0].fill_between(ls_, lens_data["drifted"], lens_data["stable"],
alpha=0.2, color=P["drift"])
axes5[0].axvline(best, color="gray", ls=":", lw=1.5)
axes5[0].set(xlabel="Layer", ylabel="P(expected token)",
title="Per-layer probability")
axes5[0].legend()
axes5[0].grid(alpha=0.3)
gap = [s - d for s, d in zip(lens_data["stable"], lens_data["drifted"])]
axes5[1].plot(ls_, gap, "o-", color=P["neu"], lw=2.5, ms=7)
axes5[1].fill_between(ls_, 0, gap, alpha=0.3, color=P["neu"])
axes5[1].axhline(0, color="gray", ls="--", alpha=0.5)
axes5[1].axvline(best, color=P["drift"], ls=":", lw=1.5)
axes5[1].set(xlabel="Layer", ylabel="Stable − Drifted gap",
title="Knowledge gap curve")
axes5[1].grid(alpha=0.3)
plt.tight_layout()
plt.savefig(fig_dir / "fig6_logit_lens.png",
dpi=300, bbox_inches="tight")
plt.close()
logger.info(" fig6 saved")
# ── Fig 7: Sparsity tradeoff ─────────────────────────────────────────
if sparsity_data:
fig, ax1 = plt.subplots(figsize=(10, 6))
lams = [d["lambda"] for d in sparsity_data]
nus = [d["n_active"] for d in sparsity_data]
aus = [d["auroc"] for d in sparsity_data]
ax1.semilogx(lams, aus, "o-", color=P["drift"], lw=2.5, ms=8,
label="AUROC")
ax4 = ax1.twinx()
ax4.semilogx(lams, nus, "s--", color=P["unc"], lw=2.5, ms=8,
label="Active neurons")
ax1.set(xlabel="L1 lambda", ylabel="AUROC",
title=f"[{model_key}] Sparsity Tradeoff")
ax4.set_ylabel("Active neurons")
ax1.legend(loc="lower left")
ax4.legend(loc="upper right")
ax1.grid(alpha=0.3, which="both")
plt.tight_layout()
plt.savefig(fig_dir / "fig7_sparsity_tradeoff.png",
dpi=300, bbox_inches="tight")
plt.close()
logger.info(" fig7 saved")
# ── Fig 8: Calibration ───────────────────────────────────────────────
bl = best
pr_objs = all_lr[bl].get("_probes", {})
X_b = np.array([r["hidden_states"][bl] for r in results])
is_d = np.array([int(r["is_drifted"]) for r in results])
is_c = np.array([int(r.get("correct", False)) for r in results])
fig, axes6 = plt.subplots(1, 3, figsize=(18, 6))
fig.suptitle(f"[{model_key}] Reliability Diagrams (Layer {bl})",
fontsize=14, fontweight="bold")
for ax, pkey, yt, lbl, col in [
(axes6[0], "drift", is_d, "Drift", P["drift"]),
(axes6[1], "correctness", is_c, "Correctness", P["corr"]),
]:
probe = pr_objs.get(pkey)
if probe is None:
ax.set_visible(False)
continue
scores = probe.predict_proba(X_b)[:, 1]
bins_e = np.linspace(0, 1, 11)
mid = (bins_e[:-1] + bins_e[1:]) / 2
frac = [float(yt[(scores >= lo) & (scores < hi)].mean())
if ((scores >= lo) & (scores < hi)).sum() > 0 else np.nan
for lo, hi in zip(bins_e[:-1], bins_e[1:])]
ax.plot([0, 1], [0, 1], "k--", lw=1.5, label="Perfect")
ax.bar(mid, frac, 0.08, alpha=0.6, color=col, edgecolor="black",
lw=0.5, label=lbl)
ax.set(xlabel="Predicted prob", ylabel="Fraction positive",
title=lbl, xlim=(0, 1), ylim=(0, 1))
ax.legend()
ax.grid(alpha=0.3)
ax = axes6[2]
probe = pr_objs.get("drift")
if probe:
s = probe.predict_proba(X_b)[:, 1]
ax.hist(s[is_d == 0], 30, alpha=0.6, color=P["unc"], density=True,
label="Stable")
ax.hist(s[is_d == 1], 30, alpha=0.6, color=P["drift"], density=True,
label="Drifted")
ax.set(xlabel="Drift score", ylabel="Density",
title="Score distribution")
ax.legend()
ax.grid(alpha=0.3)
plt.tight_layout()
plt.savefig(fig_dir / "fig8_calibration.png", dpi=300, bbox_inches="tight")
plt.close()
logger.info(" fig8 saved")
# ── Fig 10: Temporal distance ────────────────────────────────────────
if temporal_data and len(temporal_data.get("bins", [])) > 10:
bins_ = np.array(temporal_data["bins"])
scrs_ = np.array(temporal_data["scores"])
fig, ax = plt.subplots(figsize=(10, 6))
be = np.linspace(bins_.min(), bins_.max(), 10)
bm = (be[:-1] + be[1:]) / 2
bmean = [scrs_[(bins_ >= lo) & (bins_ < hi)].mean()
if ((bins_ >= lo) & (bins_ < hi)).sum() > 0 else np.nan
for lo, hi in zip(be[:-1], be[1:])]
ax.scatter(bins_, scrs_, alpha=0.3, s=15, color=P["drift"])
ax.plot(bm, bmean, "o-", color="black", lw=2.5, ms=8,
label=f"Bin mean (r={temporal_data['correlation']:.3f})")
ax.axvline(0, color="gray", ls="--", alpha=0.6, label="Cutoff")
ax.set(xlabel="Months since cutoff",
ylabel="Drift probe score",
title=f"[{model_key}] [NEW-E] Temporal Distance")
ax.legend()
ax.grid(alpha=0.3)
plt.tight_layout()
plt.savefig(fig_dir / "fig10_temporal_distance.png",
dpi=300, bbox_inches="tight")
plt.close()
logger.info(" fig10 saved")
# ── Fig 11: Per-relation heatmap ─────────────────────────────────────
bl = best
pr_d = all_lr[bl].get("per_relation", {})
if len(pr_d) >= 3:
rels = sorted(pr_d.keys())
d_au = [pr_d[r]["drift_auroc"] for r in rels]
c_au = [pr_d[r]["correct_auroc"] for r in rels]
nd_ = [pr_d[r]["n_drifted"] for r in rels]
ns_ = [pr_d[r]["n_stable"] for r in rels]
fig, axes7 = plt.subplots(1, 2, figsize=(18, 7))
fig.suptitle(f"[{model_key}] Per-Relation AUROC (Layer {bl})",
fontsize=14, fontweight="bold")
x = np.arange(len(rels))
w = 0.35
axes7[0].bar(x - w / 2, d_au, w, color=P["drift"], edgecolor="black",
lw=0.5, label="Drift")
axes7[0].bar(x + w / 2, c_au, w, color=P["corr"], edgecolor="black",
lw=0.5, label="Correctness")
axes7[0].set_xticks(x)
axes7[0].set_xticklabels(rels, rotation=35, ha="right", fontsize=9)
axes7[0].axhline(0.5, color="gray", ls="--", alpha=0.5)
axes7[0].set(ylabel="AUROC", title="AUROC by relation")
axes7[0].legend()
axes7[0].grid(alpha=0.3, axis="y")
axes7[1].barh(rels, nd_, color=P["drift"], alpha=0.7, label="Drifted")
axes7[1].barh(rels, ns_, left=nd_, color=P["unc"], alpha=0.7,
label="Stable")
axes7[1].set(xlabel="Count", title="Class balance")
axes7[1].legend()
axes7[1].grid(alpha=0.3, axis="x")
plt.tight_layout()
plt.savefig(fig_dir / "fig11_relation_heatmap.png",
dpi=300, bbox_inches="tight")
plt.close()
logger.info(" fig11 saved")
logger.info(f"All figures -> {fig_dir}")
# ─────────────────────────────────────────────────────────────────────────────
# MAIN
# ─────────────────────────────────────────────────────────────────────────────
def run(model_key, cfg, output_dir, probe_device, layers_override,
n_permutations, max_iter, cv_max_iter,
skip_logit_lens, skip_sparsity, skip_permutation):
mcfg = cfg["models"][model_key]
defaults = cfg.get("defaults", {})
lambda_grid = defaults.get("lambda_grid",
[1e-5, 5e-5, 1e-4, 5e-4, 1e-3, 5e-3, 1e-2, 5e-2])
sparsity_lambdas = defaults.get("sparsity_lambdas",
[1e-6, 1e-5, 5e-5, 1e-4, 5e-4, 1e-3,
5e-3, 1e-2, 5e-2, 0.1, 0.2])
cutoff_months = mcfg.get("cutoff_months", 48)
model_dir = Path(output_dir) / model_key
model_dir.mkdir(parents=True, exist_ok=True)
(model_dir / "per_layer").mkdir(exist_ok=True)
fh = logging.FileHandler(model_dir / "analysis.log")
fh.setFormatter(logging.Formatter("%(asctime)s [%(levelname)s] %(message)s"))
logger.addHandler(fh)
# Load cache
cache_path = model_dir / f"cached_{model_key}.npz"
if not cache_path.exists():
logger.error(f"Cache not found: {cache_path}")
logger.error("Run extract_models.py first.")
sys.exit(1)
logger.info(f"\n{'='*70}")
logger.info(f" {model_key} — Analysis")
logger.info(f"{'='*70}")
logger.info(f"Loading cache: {cache_path}")
results = np.load(str(cache_path), allow_pickle=True)["results"].tolist()
n_d = sum(1 for r in results if r["is_drifted"])
logger.info(f" {len(results)} samples ({n_d} drifted, {len(results)-n_d} stable)")
# Determine layers
num_layers = max(max(r["hidden_states"].keys()) for r in results) + 1
all_layers = layers_override or list(range(num_layers))
# Resume from checkpoint
all_lr = {}
rj = model_dir / "all_layer_results.json"
if rj.exists():
with open(rj) as f:
saved = json.load(f)
all_lr = {int(k): v for k, v in saved.items()}
logger.info(f"Resumed: {len(all_lr)} layers done")
# Layer loop
for layer in all_layers:
if layer in all_lr and "drift_auroc" in all_lr[layer]:
logger.info(f"L{layer}: skip (AUROC={all_lr[layer]['drift_auroc']:.4f})")
continue
logger.info(f"\n── Layer {layer}/{num_layers-1} ──")
res = analyze_layer(layer, results, probe_device, lambda_grid,
max_iter, cv_max_iter)
logger.info(
f" Drift={res['drift_auroc']:.4f} "
f"(lam={res['drift_lam']:.0e}, act={res['n_active_drift']}) "
f"Unc={res['uncertainty_auroc']:.4f} "
f"Corr={res['correctness_auroc']:.4f}")
logger.info(
f" cos(d,u)={res['cos_du']:+.4f} "
f"cos(d,c)={res['cos_dc']:+.4f} "
f"null_space={res['null_space_drift_auroc']:.4f} "
f"drop={res['drift_auroc']-res['null_space_drift_auroc']:+.4f}")
logger.info(
f" Jaccard(d,u)={res['jaccard_du']:.2%} "
f"Jaccard(d,c)={res['jaccard_dc']:.2%} "
f"t={res['elapsed_s']:.1f}s")
cb = res["cells"].get("B_confident_drifted", {})
if cb.get("n", 0) > 0:
logger.info(
f" [CellB] drift={cb['drift_mean']:.3f} "
f"corr={cb['correct_mean']:.3f} "
f"d_flag={cb['drift_flag_rate']:.1%} "
f"c_flag={cb['correct_flag_rate']:.1%}")
# Save (strip weight vectors for JSON)
save_res = {k: v for k, v in res.items() if not k.startswith("_")}
all_lr[layer] = res # keep full for figures
with open(model_dir / "per_layer" / f"layer_{layer:02d}.json", "w") as f:
json.dump(save_res, f, indent=2, default=str)
with open(rj, "w") as f:
json.dump({int(k): {kk: vv for kk, vv in v.items()
if not kk.startswith("_")}
for k, v in all_lr.items()},
f, indent=2, default=str)
# Incremental figures
save_figures(all_lr, str(model_dir), model_key, results)
# Best layer
best_layer = int(max(all_lr, key=lambda l: all_lr[l]["drift_auroc"]))
logger.info(f"\nBest layer: {best_layer} "
f"AUROC={all_lr[best_layer]['drift_auroc']:.4f}")
# Re-fit best for full probe objects if needed
if "_w_drift" not in all_lr[best_layer]:
logger.info("Re-fitting best layer...")
all_lr[best_layer] = analyze_layer(
best_layer, results, probe_device, lambda_grid,
max_iter, cv_max_iter)
# [NEW-B] Direction stability
logger.info("[NEW-B] Direction stability...")
for l in all_layers:
if "_w_drift" not in all_lr.get(l, {}):
X = np.array([r["hidden_states"][l] for r in results])
y = np.array([int(r["is_drifted"]) for r in results])
pw = fit_probe(X, y, 1e-3, probe_device, 400)
if l not in all_lr:
all_lr[l] = {}
all_lr[l]["_w_drift"] = pw.w_np
stability_data = probe_direction_stability(all_lr)
mean_cos = float(np.mean(
stability_data[1][~np.eye(len(stability_data[1]), dtype=bool)]))
logger.info(f" Mean cross-layer cosine: {mean_cos:.4f}")
# [NEW-C] Logit lens
lens_data = None
if not skip_logit_lens:
logger.info("[NEW-C] Logit lens...")
lens_data = logit_lens_analysis(results, str(model_dir),
model_key, probe_device)
# [PERM] Permutation test
perm_res = None
if not skip_permutation:
perm_res = permutation_test(results, best_layer, n_permutations,
probe_device, lambda_grid)
# [SPARSE] Sparsity curve
sparsity_data = None
if not skip_sparsity:
sparsity_data = sparsity_curve(results, best_layer, probe_device,
sparsity_lambdas)
# [NEW-E] Temporal distance
X_all = np.array([r["hidden_states"][best_layer] for r in results])
dp = all_lr[best_layer]["_probes"]["drift"]
scores = dp.predict_proba(X_all)[:, 1]
for r, sc in zip(results, scores):
r["_drift_score"] = float(sc)
temporal_data = temporal_distance_analysis(results, cutoff_months)
# Final figures
save_figures(all_lr, str(model_dir), model_key, results,
stability_data=stability_data, lens_data=lens_data,
sparsity_data=sparsity_data, temporal_data=temporal_data)
# Export probe bundle
export_probe_bundle(all_lr, best_layer, results, model_key, str(model_dir))
# Final summary
bl = all_lr[best_layer]
drop = bl["drift_auroc"] - bl["null_space_drift_auroc"]
print(f"\n{'='*70}")
print(f" [{model_key}] FINAL RESULTS")
print(f"{'='*70}")
print(f" Best layer: {best_layer}")
print(f" Drift AUROC: {bl['drift_auroc']:.4f}")
print(f" Uncertainty AUROC: {bl['uncertainty_auroc']:.4f}")
print(f" Correctness AUROC: {bl['correctness_auroc']:.4f}")
print(f" Null-space drift AUROC: {bl['null_space_drift_auroc']:.4f}")
print(f" cos(drift, unc): {bl['cos_du']:+.4f}")
print(f" cos(drift, corr): {bl['cos_dc']:+.4f}")
print(f" Active neurons (drift): {bl['n_active_drift']}")
print(f" Jaccard(drift, unc): {bl['jaccard_du']:.2%}")
print(f" Null-space drop: {drop:+.4f}")
print(f" Mean cross-layer cos: {mean_cos:.4f}")
if perm_res:
print(f" Permutation p-value: {perm_res['p_value']:.6f}")
cb = bl.get("cells", {}).get("B_confident_drifted", {})
if cb.get("n", 0) > 0:
print(f"\n [IDEA-1] Cell B (n={cb['n']}):")
print(f" Drift: {cb['drift_mean']:.3f} "
f"(flagged {cb['drift_flag_rate']:.1%})")
print(f" Correctness: {cb['correct_mean']:.3f} "
f"(flagged {cb['correct_flag_rate']:.1%})")
if cb["drift_mean"] > 0.55 and cb["correct_mean"] < 0.55:
print(" DISSOCIATION CONFIRMED")
print()
if abs(bl["cos_du"]) < 0.1:
print(" ORTHOGONAL: |cos(drift,unc)| < 0.10")
if abs(bl["cos_dc"]) < 0.3:
print(" DISTINCT: |cos(drift,corr)| < 0.30")
if abs(drop) < 0.02:
print(f" NULL-SPACE STABLE: drop={drop:+.4f}")
if mean_cos > 0.5:
print(f" GLOBAL DIRECTION: mean_cos={mean_cos:.3f}")
print(f"{'='*70}")
# Save final results
final = {
"model_key": model_key,
"model_name": mcfg["name"],
"n_samples": len(results),
"n_drifted": n_d,
"best_layer": best_layer,
"best_layer_results": {k: v for k, v in bl.items()
if not k.startswith("_")},
"permutation_test": perm_res,
"sparsity_curve": sparsity_data,
"logit_lens": lens_data,
"temporal_distance": temporal_data,
"probe_stability": {
"layers": stability_data[0],
"mean_cross_layer_cosine": float(mean_cos),
},
"timestamp": datetime.now().isoformat(),
}
with open(model_dir / "final_results.json", "w") as f:
json.dump(final, f, indent=2, default=str)
logger.info(f"\nAll results saved to {model_dir}")
return results, best_layer
def main():
import sys
p = argparse.ArgumentParser(
description="Per-model disentanglement analysis",
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
p.add_argument("--model", required=True,
help="Model key from models.yaml")
p.add_argument("--config", default="models.yaml")
p.add_argument("--output_dir", default=None)
p.add_argument("--probe_device", default="cuda:0")
p.add_argument("--layers", type=int, nargs="+", default=None)
p.add_argument("--n_permutations", type=int, default=None)
p.add_argument("--max_iter", type=int, default=None)
p.add_argument("--cv_max_iter", type=int, default=None)
p.add_argument("--skip_logit_lens", action="store_true")
p.add_argument("--skip_sparsity", action="store_true")
p.add_argument("--skip_permutation", action="store_true")
args = p.parse_args()
cfg = load_config(args.config)
defaults = cfg.get("defaults", {})
output_dir = args.output_dir or defaults.get("output_dir",
"data/experiments/v4")
n_perms = args.n_permutations or defaults.get("n_permutations", 1000)
max_iter = args.max_iter or defaults.get("max_iter", 2000)
cv_max_iter = args.cv_max_iter or defaults.get("cv_max_iter", 500)
run(args.model, cfg, output_dir, args.probe_device, args.layers,
n_perms, max_iter, cv_max_iter,
args.skip_logit_lens, args.skip_sparsity, args.skip_permutation)
if __name__ == "__main__":
main()