"""Probes. All probes share a tiny interface so the pipeline is agnostic to type: probe = make_probe("logreg", num_labels=2, seed=0).fit(X_train, y_train) y_hat = probe.predict(X_eval) D = probe.direction # [C, H] concept-direction matrix, or None (MLP) `direction` is what claim C1/C2 measure rotation on. For LogReg it is the weight matrix; for mass-mean it is (class_centroid - global_mean). MLP has no single linear direction, so it returns None and the eval step skips rotation for it (still reports accuracy). """ from __future__ import annotations import numpy as np from sklearn.linear_model import LogisticRegression class BaseProbe: direction: np.ndarray | None = None def fit(self, X: np.ndarray, y: np.ndarray) -> "BaseProbe": raise NotImplementedError def predict(self, X: np.ndarray) -> np.ndarray: raise NotImplementedError class LogRegProbe(BaseProbe): """L2-regularised multinomial logistic regression (the default diagnostic probe).""" def __init__(self, num_labels: int, l2: float = 1.0, seed: int = 0, max_iter: int = 500, **_): self.num_labels = num_labels self.C = 1.0 / max(l2, 1e-8) self.seed = seed self.max_iter = max_iter self._clf: LogisticRegression | None = None def fit(self, X, y): self._clf = LogisticRegression( C=self.C, max_iter=self.max_iter, random_state=self.seed, ).fit(X, y) coef = self._clf.coef_ # [1,H] binary, [C,H] multiclass self.direction = coef.copy() return self def predict(self, X): return self._clf.predict(X) class MassMeanProbe(BaseProbe): """Difference-of-means / mass-mean probe. Predicts by nearest class centroid. Often *more* OOD-robust than LogReg (a hypothesis under claim C3). """ def __init__(self, num_labels: int, **_): self.num_labels = num_labels self._centroids: np.ndarray | None = None self._classes: np.ndarray | None = None def fit(self, X, y): y = np.asarray(y) self._classes = np.unique(y) centroids = np.stack([X[y == c].mean(0) for c in self._classes]) # [C,H] self._centroids = centroids self.direction = centroids - X.mean(0, keepdims=True) # [C,H] return self def predict(self, X): # nearest centroid (euclidean) d = np.linalg.norm(X[:, None, :] - self._centroids[None, :, :], axis=2) # [N,C] return self._classes[np.argmin(d, axis=1)] class MLPProbe(BaseProbe): """2-layer MLP probe (torch). No single linear direction -> direction stays None.""" def __init__(self, num_labels: int, hidden: int = 128, epochs: int = 50, lr: float = 1e-3, seed: int = 0, **_): self.num_labels = num_labels self.hidden = hidden self.epochs = epochs self.lr = lr self.seed = seed self._model = None self._device = None def fit(self, X, y): import torch import torch.nn as nn torch.manual_seed(self.seed) self._device = "cuda" if torch.cuda.is_available() else "cpu" Xt = torch.tensor(np.asarray(X), dtype=torch.float32, device=self._device) yt = torch.tensor(np.asarray(y), dtype=torch.long, device=self._device) self._model = nn.Sequential( nn.Linear(Xt.shape[1], self.hidden), nn.ReLU(), nn.Linear(self.hidden, self.num_labels), ).to(self._device) opt = torch.optim.Adam(self._model.parameters(), lr=self.lr) lossfn = nn.CrossEntropyLoss() self._model.train() for _ in range(self.epochs): opt.zero_grad() loss = lossfn(self._model(Xt), yt) loss.backward() opt.step() return self def predict(self, X): import torch self._model.eval() with torch.no_grad(): Xt = torch.tensor(np.asarray(X), dtype=torch.float32, device=self._device) return self._model(Xt).argmax(1).cpu().numpy() class ControlTaskProbe(LogRegProbe): """Hewitt & Liang control-task probe: fit on RANDOM labels to measure selectivity. selectivity = real_task_acc - control_task_acc. A high-selectivity probe reflects the representation, not probe memorisation. We report this to pre-empt the standard "your probe is just memorising" reviewer attack. """ def fit(self, X, y): rng = np.random.default_rng(self.seed) y_rand = rng.permutation(np.asarray(y)) # destroy structure, keep label marginal return super().fit(X, y_rand) _REGISTRY = { "logreg": LogRegProbe, "mass_mean": MassMeanProbe, "mlp": MLPProbe, "control": ControlTaskProbe, } def make_probe(kind: str, num_labels: int, **kwargs) -> BaseProbe: if kind not in _REGISTRY: raise KeyError(f"unknown probe '{kind}', choose from {list(_REGISTRY)}") return _REGISTRY[kind](num_labels=num_labels, **kwargs)