Beicicc's picture
ProbeShift reproducibility bundle: code + results + paper + figures
592942b verified
Raw
History Blame Contribute Delete
4.66 kB
"""The Probe Stability Score (claim C2).
Both components are computed from IID training activations ONLY (no labels from any OOD
distribution, no new human annotation) — that is the whole point: it must predict OOD
transfer *a priori*.
Component 1 — dispersion
Train K probes on K bootstrap resamples of the SAME IID training set. Each yields a
concept direction. dispersion = 1 - mean resultant length of the (unit) directions
(0 = all directions identical/stable, ->1 = scattered/unstable).
Component 2 — augmentation_consistency
Build `n_aug` label-preserving augmentations of the IID training set, fit a probe on
each, and measure the mean cosine of each augmented direction to the original.
(1 = direction unchanged by surface form, ->0 = direction is surface-form artefact.)
Pre-registered hypothesis: the *combination* predicts OOD drop; dispersion alone is
necessary-but-not-sufficient. `combine()` returns the headline scalar; we also report
each component separately and run a sensitivity sweep over the weights.
"""
from __future__ import annotations
import numpy as np
from config import StabilityConfig
from metrics import mean_class_cosine, subspace_principal_angle
from probes import make_probe
def _resultant_dispersion(directions: list[np.ndarray]) -> float:
"""1 - |mean of unit directions|, averaged over class rows. directions: list of [C,H]."""
if len(directions) < 2:
return float("nan")
stacked = np.stack(directions) # [K, C, H]
norms = np.linalg.norm(stacked, axis=2, keepdims=True)
norms[norms == 0] = 1.0
units = stacked / norms # [K, C, H]
mean_vec = units.mean(0) # [C, H]
resultant = np.linalg.norm(mean_vec, axis=1) # [C] in [0,1]
return float(1.0 - resultant.mean())
def dispersion(
X_iid: np.ndarray,
y_iid: np.ndarray,
num_labels: int,
probe_kind: str = "logreg",
k: int = 20,
seed: int = 0,
**probe_kwargs,
) -> float:
rng = np.random.default_rng(seed)
n = len(X_iid)
dirs = []
for j in range(k):
idx = rng.integers(0, n, n) # bootstrap resample
p = make_probe(probe_kind, num_labels=num_labels, seed=seed + j, **probe_kwargs)
p.fit(X_iid[idx], y_iid[idx])
if p.direction is None:
return float("nan") # e.g. MLP — no linear direction
dirs.append(p.direction)
return _resultant_dispersion(dirs)
def augmentation_consistency(
X_iid: np.ndarray,
y_iid: np.ndarray,
X_aug_list: list[np.ndarray], # activations of n_aug label-preserving augmentations
num_labels: int,
probe_kind: str = "logreg",
seed: int = 0,
**probe_kwargs,
) -> float:
base = make_probe(probe_kind, num_labels=num_labels, seed=seed, **probe_kwargs)
base.fit(X_iid, y_iid)
if base.direction is None:
return float("nan")
cosines = []
for Xa in X_aug_list:
p = make_probe(probe_kind, num_labels=num_labels, seed=seed, **probe_kwargs)
p.fit(Xa, y_iid) # same labels, augmented inputs
try:
cosines.append(mean_class_cosine(base.direction, p.direction))
except ValueError:
# multiclass row mismatch -> fall back to subspace agreement
ang = subspace_principal_angle(base.direction, p.direction)
cosines.append(float(np.cos(ang)))
return float(np.mean(cosines)) if cosines else float("nan")
def combine(disp: float, aug_cons: float, cfg: StabilityConfig) -> float:
"""Headline scalar. Higher = more stable = predicted to transfer better OOD.
stability = w_d * (1 - dispersion) + w_c * augmentation_consistency
"""
stable_from_disp = 1.0 - disp
z = cfg.w_dispersion + cfg.w_consistency
return float((cfg.w_dispersion * stable_from_disp + cfg.w_consistency * aug_cons) / z)
def stability_score(
X_iid: np.ndarray,
y_iid: np.ndarray,
X_aug_list: list[np.ndarray],
num_labels: int,
cfg: StabilityConfig,
probe_kind: str = "logreg",
seed: int = 0,
**probe_kwargs,
) -> dict:
"""Return {dispersion, augmentation_consistency, score} for one (model, dataset, layer)."""
disp = dispersion(X_iid, y_iid, num_labels, probe_kind, cfg.k_bootstrap, seed, **probe_kwargs)
aug = augmentation_consistency(
X_iid, y_iid, X_aug_list, num_labels, probe_kind, seed, **probe_kwargs
)
return {
"dispersion": disp,
"augmentation_consistency": aug,
"score": combine(disp, aug, cfg),
}