Beicicc's picture
ProbeShift reproducibility bundle: code + results + paper + figures
592942b verified
Raw
History Blame Contribute Delete
4.68 kB
"""Tier-1 refit analyses (read cache, refit probes). Run on the server pointing PROBE_CACHE
at a seed cache. Reads predictors from results/<predfile> (default predictors_1aug.jsonl, the
A run, since Tier 2 rewrites predictors.jsonl).
PROBE_CACHE=/root/rivermind-fs/cache_seed0 python analyze_refit.py layer
PROBE_CACHE=/root/rivermind-fs/cache_seed0 python analyze_refit.py whitened [predfile]
layer : mean paraphrase rotation per (relative) layer over a sample — is the rotation a
property of the chosen layer or pervasive? (defends "not layer-cherry-picked")
whitened : recompute paraphrase rotation with ID-whitened (Mahalanobis) cosine and re-rank the
predictors — does the circularity / ranking conclusion survive a better metric? (M3)
"""
from __future__ import annotations
import json
import sys
from pathlib import Path
import numpy as np
from scipy import linalg
import cache
import metrics
from config import DATASETS, MODELS, EXTRACT, RESULTS_DIR
from probes import make_probe
from run_pipeline import _select_layer, _rank_predictors
from baselines import PREDICTORS
SAMPLE_DS = ["sst2", "ag_news", "counterfact", "emotion", "subj"]
def _read(name):
p = RESULTS_DIR / name
return [json.loads(l) for l in p.read_text().splitlines() if l.strip()] if p.exists() else []
def _dir(X, y, nl, W=None):
if W is not None:
X = X @ W
return make_probe("logreg", num_labels=nl, seed=0, max_iter=500).fit(X, y).direction
def layer_curve(models=None, dsets=None):
models = models or list(MODELS)
dsets = dsets or SAMPLE_DS
print("\n########## LAYER ROBUSTNESS: paraphrase rotation by relative depth ##########")
buckets = {q: [] for q in [0.1, 0.25, 0.5, 0.75, 0.9, 1.0]}
for m in models:
for ds in dsets:
if not (cache.exists(m, ds, "train") and cache.exists(m, ds, "paraphrase")):
continue
nl = DATASETS[ds].num_labels
meta = cache.load_meta(m, ds, "train")
Xtr, ytr, _ = cache.load_shard(m, ds, "train")
Xpa, ypa, _ = cache.load_shard(m, ds, "paraphrase")
nl_layers = meta["n_layers"]
for q in buckets:
L = max(1, min(nl_layers - 1, int(q * (nl_layers - 1))))
da = _dir(np.asarray(Xtr[:, L, :], np.float32), ytr, nl)
db = _dir(np.asarray(Xpa[:, L, :], np.float32), ypa, nl)
buckets[q].append(_rotmag(da, db))
print(f"{'rel-depth':>10s}{'mean rotation (1-cos)':>24s}{'n':>5s}")
for q in sorted(buckets):
v = [x for x in buckets[q] if x == x]
if v:
print(f"{q:>10.2f}{np.mean(v):>24.3f}{len(v):>5d}")
print("(rotation present across depths -> not an artefact of the IID-selected layer)")
def _rotmag(da, db):
try:
return 1.0 - metrics.mean_class_cosine(da, db)
except Exception:
return 1.0 - float(np.cos(metrics.subspace_principal_angle(da, db)))
def whitened_target(predfile="predictors_1aug.jsonl"):
evals = _read("eval.jsonl")
preds = {(p["model"], p["dataset"], p["seed"]): p["predictors"] for p in _read(predfile)}
print(f"\n########## METRIC ABLATION: ID-whitened paraphrase rotation as target ##########")
print(f"(predictors from {predfile}; recomputing whitened rotation by refit on cache)")
rows = []
for e in evals:
if e.get("probe") != "logreg":
continue
m, ds, seed = e["model"], e["dataset"], e["seed"]
if (m, ds, seed) not in preds:
continue
if not (cache.exists(m, ds, "train") and cache.exists(m, ds, "paraphrase")):
continue
nl = DATASETS[ds].num_labels
layer = e.get("layer") or _select_layer(m, ds, nl, seed)
Xtr, ytr, _ = cache.load_shard(m, ds, "train", layer=layer)
Xpa, ypa, _ = cache.load_shard(m, ds, "paraphrase", layer=layer)
C = np.cov(np.asarray(Xtr, np.float64), rowvar=False) + 1e-3 * np.eye(Xtr.shape[1])
W = linalg.fractional_matrix_power(C, -0.5).real.astype(np.float32)
da = _dir(Xtr, ytr, nl, W=W)
db = _dir(Xpa, ypa, nl, W=W)
rows.append({"concept": DATASETS[ds].concept, "wrot": _rotmag(da, db), **preds[(m, ds, seed)]})
if len(rows) < 8:
print(f"only {len(rows)} configs — skipped")
return
_rank_predictors(rows, "wrot", f"WHITENED paraphrase rotation (n={len(rows)})")
if __name__ == "__main__":
mode = sys.argv[1] if len(sys.argv) > 1 else "layer"
if mode == "layer":
layer_curve()
elif mode == "whitened":
whitened_target(sys.argv[2] if len(sys.argv) > 2 else "predictors_1aug.jsonl")