Download set5/code/probes12.py from LamTNguyen/repa-representation-probing: direct link, hf CLI and curl.
- Browser
- Download file 14.2 kB
-
https://huggingface.co/datasets/LamTNguyen/repa-representation-probing/resolve/main/set5/code/probes12.py
- Command line
-
hf download hf://datasets/LamTNguyen/repa-representation-probing/set5/code/probes12.py
-
curl -L -o probes12.py https://huggingface.co/datasets/LamTNguyen/repa-representation-probing/resolve/main/set5/code/probes12.py
14.2 kB
| """Linear probes and training-free measures. | |
| Regression probes (latent reconstruction, NYU depth) are ridge regressions solved in closed form | |
| from sufficient statistics accumulated per data fold, so dense features never touch the disk. | |
| Features are z-scored with training statistics before the ridge penalty is applied. | |
| Seeds: seed j holds out fold j of the training split (10 folds). The held-out fold selects the | |
| regularisation strength; the probe is fit on the other 9 folds and scored on the fixed test split. | |
| So the std over seeds reflects sensitivity to the training subset (and SGD order for the classifier). | |
| """ | |
| from __future__ import annotations | |
| import math | |
| import numpy as np | |
| import torch | |
| import torch.nn.functional as F | |
| RIDGE_ALPHAS = [1e-8, 1e-7, 1e-6, 1e-5, 1e-4, 1e-3, 1e-2, 1e-1, 1.0] # smoke run hit the 1e-6 edge | |
| LOGREG_LAMBDAS = [1e-5, 1e-4, 1e-3, 1e-2] | |
| # Dtype of the per-batch products in the sufficient statistics (always summed across batches in float64). | |
| # Features are first centred on a fixed per-layer reference vector in float64 (see _Centre), which is what | |
| # removes the catastrophic cancellation; the product dtype only matters at the 1e-6 level. | |
| ACC_DTYPE = torch.float32 | |
| class _Centre: | |
| """Fixed per-layer reference vector (mean of the first batch seen), subtracted in float64. | |
| SiT blocks carry a few 'massive activation' channels whose mean is orders of magnitude larger than | |
| their spread (worst at block 4 of the REPA checkpoints). v1 of this file accumulated raw float32 | |
| products and centred afterwards via E[x^2] - mu^2, which cancelled catastrophically there (depth RMSE | |
| 5.5 and latent R^2 down to -7000 at block 4). Centring on a reference first keeps every product O(spread). | |
| """ | |
| def __init__(self, n_layers): | |
| self.ref = [None] * n_layers | |
| def __call__(self, li, x): | |
| x = x.double() | |
| if self.ref[li] is None: | |
| self.ref[li] = x.reshape(-1, x.shape[-1]).mean(0) | |
| return x - self.ref[li] | |
| # ----------------------------------------------------------------------------- ridge from sufficient stats | |
| class RidgeStats: | |
| """Per-fold accumulators of M = Xb'WXb, V = Xb'Wy, C = y'Wy (per output), N = sum of weights, | |
| for each layer. Xb = [X - ref, 1]. W is identity for token-level targets, A'diag(mask)A for depth. | |
| Weights returned by solve() act on centred features: predict with RidgeStats.predict(x, W, ref).""" | |
| def __init__(self, n_layers, dim, n_out, n_folds=10, device="cuda"): | |
| d1 = dim + 1 | |
| self.M = torch.zeros(n_folds, n_layers, d1, d1, dtype=torch.float64, device=device) | |
| self.V = torch.zeros(n_folds, n_layers, d1, n_out, dtype=torch.float64, device=device) | |
| self.C = torch.zeros(n_folds, n_out, dtype=torch.float64, device=device) | |
| self.N = torch.zeros(n_folds, dtype=torch.float64, device=device) | |
| self.n_folds, self.dim, self.n_out = n_folds, dim, n_out | |
| self.centre = _Centre(n_layers) | |
| def _aug(x): # [..., D] -> [..., D+1] | |
| return torch.cat([x, torch.ones_like(x[..., :1])], dim=-1) | |
| def predict(x, W, ref): | |
| """x: [..., D] raw features; W: [D+1, k] from solve(); ref: [D] centring vector. float64 result.""" | |
| return RidgeStats._aug(x.double() - ref) @ W.to(x.device, torch.float64) | |
| def add_tokens(self, feats, y, fold): | |
| """feats: list over layers of [B, T, D]; y: [B, T, k]; fold: [B] (per image).""" | |
| for f in fold.unique().tolist(): | |
| sel = fold == f | |
| yf = y[sel].reshape(-1, self.n_out).to(ACC_DTYPE) | |
| self.C[f] += (yf.double() ** 2).sum(0) | |
| self.N[f] += yf.shape[0] | |
| for li, x in enumerate(feats): | |
| xb = self._aug(self.centre(li, x[sel].reshape(-1, x.shape[-1]))).to(ACC_DTYPE) | |
| self.M[f, li] += (xb.T @ xb).double() | |
| self.V[f, li] += (xb.T @ yf).double() | |
| def add_weighted(self, feats, G, b, c, n, fold): | |
| """Depth: per image, loss = sum_p m_p (A Xb w - y)_p^2 = w'Xb'G Xb w - 2 w'Xb'b + c. | |
| G: [B, T, T]; b: [B, T]; c, n: [B].""" | |
| for f in fold.unique().tolist(): | |
| sel = fold == f | |
| self.C[f, 0] += c[sel].double().sum() | |
| self.N[f] += n[sel].double().sum() | |
| Gs, bs = G[sel].to(ACC_DTYPE), b[sel].to(ACC_DTYPE) | |
| for li, x in enumerate(feats): | |
| xb = self._aug(self.centre(li, x[sel])).to(ACC_DTYPE) # [b, T, D+1] | |
| GX = torch.bmm(Gs, xb) # [b, T, D+1] | |
| self.M[f, li] += torch.einsum("btd,bte->de", xb, GX).double() | |
| self.V[f, li, :, 0] += torch.einsum("btd,bt->d", xb, bs).double() | |
| def _sum(self, folds): | |
| idx = torch.tensor(folds, device=self.M.device) | |
| return self.M[idx].sum(0), self.V[idx].sum(0), self.C[idx].sum(0), self.N[idx].sum(0) | |
| def solve(self, layer, train_folds, alphas): | |
| """Return list of weight matrices [D+1, k] (original feature space), one per alpha.""" | |
| M, V, C, N = self._sum(train_folds) | |
| M, V = M[layer].cpu(), V[layer].cpu() | |
| N = float(N) | |
| d = self.dim | |
| mu = M[d, :d] / N | |
| var = (torch.diagonal(M)[:d] / N - mu ** 2).clamp_min(0) | |
| sd = var.sqrt() + 1e-6 * var.sqrt().mean() + 1e-12 | |
| T = torch.zeros(d + 1, d + 1, dtype=torch.float64) | |
| T[:d, :d] = torch.diag(1.0 / sd) | |
| T[d, :d] = -mu / sd | |
| T[d, d] = 1.0 | |
| Mt = T.T @ M @ T | |
| Vt = T.T @ V | |
| S = Mt[:d, :d] | |
| S = 0.5 * (S + S.T) | |
| evals, Q = torch.linalg.eigh(S) | |
| evals = evals.clamp_min(0) | |
| QtV = Q.T @ Vt[:d] | |
| bias = Vt[d] / N # centred features => bias decouples | |
| out = [] | |
| for a in alphas: | |
| w = Q @ (QtV / (evals + a * N)[:, None]) | |
| wt = torch.cat([w, bias[None]], 0) | |
| out.append(T @ wt) | |
| return out | |
| def loss(self, layer, folds, W): | |
| """Mean squared error (per output and per unit weight) of weights W on the given folds.""" | |
| M, V, C, N = self._sum(folds) | |
| M, V, C = M[layer].cpu(), V[layer].cpu(), C.cpu() | |
| tot = C.sum() - 2 * (W * V).sum() + torch.einsum("dk,de,ek->", W, M, W) | |
| return float(tot / (float(N) * self.n_out)) | |
| def fit_seed(self, layer, seed): | |
| """Hold out fold `seed`, pick alpha on it, return (W fitted on the other folds, alpha, val curve).""" | |
| train = [f for f in range(self.n_folds) if f != seed] | |
| Ws = self.solve(layer, train, RIDGE_ALPHAS) | |
| vals = [self.loss(layer, [seed], W) for W in Ws] | |
| k = int(np.argmin(vals)) | |
| return Ws[k], RIDGE_ALPHAS[k], vals | |
| # ----------------------------------------------------------------------------- latent test accumulator | |
| class R2Acc: | |
| def __init__(self, n_out): | |
| self.sse = torch.zeros(n_out, dtype=torch.float64) | |
| self.sy = torch.zeros(n_out, dtype=torch.float64) | |
| self.syy = torch.zeros(n_out, dtype=torch.float64) | |
| self.n = 0 | |
| def add(self, pred, y): | |
| pred, y = pred.double().cpu(), y.double().cpu() | |
| self.sse += ((pred - y) ** 2).sum(0) | |
| self.sy += y.sum(0) | |
| self.syy += (y ** 2).sum(0) | |
| self.n += y.shape[0] | |
| def result(self): | |
| sst = self.syy - self.sy ** 2 / self.n | |
| r2 = 1 - self.sse / sst | |
| return dict(r2=float(r2.mean()), r2_vw=float(1 - self.sse.sum() / sst.sum())) | |
| # ----------------------------------------------------------------------------- depth helpers | |
| DEPTH_MIN, DEPTH_MAX = 1e-3, 10.0 | |
| EIGEN_ROWS = (45, 471) # Eigen crop rows; its columns (41:601) cover the whole 480-wide centre crop | |
| def upsample_matrix(src=16, dst=480, device="cuda"): | |
| """A[p, t]: bilinear (align_corners=False) weight of token t at label pixel p.""" | |
| eye = torch.eye(src * src, device=device).reshape(src * src, 1, src, src) | |
| up = F.interpolate(eye, size=(dst, dst), mode="bilinear", align_corners=False) | |
| return up.reshape(src * src, dst * dst).T.contiguous() # [dst*dst, src*src] | |
| def depth_mask(depth): # [B, 480, 480] | |
| m = (depth > DEPTH_MIN) & (depth <= DEPTH_MAX) | |
| rows = torch.zeros_like(m) | |
| rows[:, EIGEN_ROWS[0]:EIGEN_ROWS[1], :] = True | |
| return m & rows | |
| def depth_design(depth, A): | |
| """Per-image G = A'diag(m)A, b = A'(m*log d), c = sum m (log d)^2, n = sum m.""" | |
| m = depth_mask(depth).reshape(depth.shape[0], -1).float() | |
| logd = torch.log(depth.clamp_min(DEPTH_MIN)).reshape(depth.shape[0], -1) | |
| G = torch.stack([(A * mi[:, None]).T @ A for mi in m]) | |
| b = (m * logd) @ A | |
| c = (m * logd ** 2).sum(1) | |
| n = m.sum(1) | |
| return G, b, c, n | |
| def depth_metrics(pred_tok_log, depth): | |
| """pred_tok_log: [B, 256] log-depth per token; depth: [B, 480, 480]. Per-image metrics.""" | |
| B = depth.shape[0] | |
| p = F.interpolate(pred_tok_log.reshape(B, 1, 16, 16).float(), size=depth.shape[-2:], mode="bilinear", align_corners=False)[:, 0] | |
| pd = p.exp().clamp(DEPTH_MIN, DEPTH_MAX) | |
| m = depth_mask(depth) | |
| out = [] | |
| for i in range(B): | |
| g, q = depth[i][m[i]], pd[i][m[i]] | |
| ratio = torch.maximum(q / g, g / q) | |
| out.append(dict(rmse=float(((q - g) ** 2).mean().sqrt()), | |
| delta1=float((ratio < 1.25).float().mean()), | |
| absrel=float(((q - g).abs() / g).mean()), | |
| rmse_log=float(((q.log() - g.log()) ** 2).mean().sqrt()))) | |
| return out | |
| # ----------------------------------------------------------------------------- classification | |
| def train_logreg(Xtr, ytr, Xva, yva, Xte, yte, seed, n_classes=1000, epochs=60, bs=1024, lr=1e-3, | |
| lambdas=LOGREG_LAMBDAS): | |
| """Multinomial logistic regression, one head per (layer, lambda), trained jointly (independent losses). | |
| X*: [L, N, D] on GPU. Returns per layer dict(best_lambda, val_acc, test_acc, val_curve).""" | |
| L, N, D = Xtr.shape | |
| mu = Xtr.mean(1, keepdim=True) | |
| sd = Xtr.std(1, keepdim=True) + 1e-6 | |
| norm = lambda X: (X - mu) / sd # noqa: E731 | |
| Xtr_n, Xva_n, Xte_n = norm(Xtr), norm(Xva), norm(Xte) | |
| nl = len(lambdas) | |
| H = L * nl | |
| lam = torch.tensor(lambdas, device=Xtr.device).repeat(L) # head h -> lambdas[h % nl] | |
| W = torch.zeros(H, D, n_classes, device=Xtr.device, requires_grad=True) | |
| b = torch.zeros(H, 1, n_classes, device=Xtr.device, requires_grad=True) | |
| opt = torch.optim.Adam([W, b], lr=lr) | |
| g = torch.Generator(device="cpu").manual_seed(seed) | |
| steps_per_epoch = math.ceil(N / bs) | |
| total = epochs * steps_per_epoch | |
| sched = torch.optim.lr_scheduler.LambdaLR(opt, lambda s: 0.5 * (1 + math.cos(math.pi * min(s, total) / total))) | |
| for ep in range(epochs): | |
| perm = torch.randperm(N, generator=g).to(Xtr.device) | |
| for i in range(steps_per_epoch): | |
| idx = perm[i * bs:(i + 1) * bs] | |
| xb = Xtr_n[:, idx].repeat_interleave(nl, dim=0) # [H, B, D] | |
| yb = ytr[idx] | |
| logits = torch.baddbmm(b, xb, W) # [H, B, C] | |
| ce = F.cross_entropy(logits.reshape(-1, n_classes), yb.repeat(H), reduction="none").reshape(H, -1).mean(1) | |
| loss = ce.sum() + (lam * (W ** 2).sum((1, 2))).sum() | |
| opt.zero_grad(set_to_none=True) | |
| loss.backward() | |
| opt.step() | |
| sched.step() | |
| def acc(Xn, y): | |
| correct = torch.zeros(H, device=Xn.device) | |
| for i in range(0, Xn.shape[1], 2048): | |
| xb = Xn[:, i:i + 2048].repeat_interleave(nl, dim=0) | |
| pred = torch.baddbmm(b, xb, W).argmax(-1) | |
| correct += (pred == y[i:i + 2048][None]).float().sum(1) | |
| return (correct / Xn.shape[1]).reshape(L, nl).cpu().numpy() | |
| va, te = acc(Xva_n, yva), acc(Xte_n, yte) | |
| res = [] | |
| for l in range(L): | |
| k = int(np.argmax(va[l])) | |
| res.append(dict(best_lambda=lambdas[k], val_acc=float(va[l, k]), test_acc=float(te[l, k]), | |
| val_curve=[float(v) for v in va[l]])) | |
| return res | |
| # ----------------------------------------------------------------------------- training-free measures | |
| def hsic_unbiased(K, L): | |
| m = K.shape[0] | |
| Kt = K.clone().fill_diagonal_(0) | |
| Lt = L.clone().fill_diagonal_(0) | |
| v = (Kt * Lt.T).sum() + Kt.sum() * Lt.sum() / ((m - 1) * (m - 2)) - 2 * (Kt @ Lt).sum() / (m - 2) | |
| return v / (m * (m - 3)) | |
| def cknna(A, B, topk=10): | |
| """CKNNA (Huh et al. 2024, unbiased, k=10) between row-aligned feature sets; features L2-normalised.""" | |
| A = F.normalize(A.double(), dim=-1) | |
| B = F.normalize(B.double(), dim=-1) | |
| n = A.shape[0] | |
| K, L = A @ A.T, B @ B.T | |
| def sim(K, L): | |
| Kh = K.clone().fill_diagonal_(float("-inf")) | |
| Lh = L.clone().fill_diagonal_(float("-inf")) | |
| mk = torch.zeros(n, n, device=K.device, dtype=K.dtype).scatter_(1, Kh.topk(topk, dim=1).indices, 1) | |
| ml = torch.zeros(n, n, device=K.device, dtype=K.dtype).scatter_(1, Lh.topk(topk, dim=1).indices, 1) | |
| mask = mk * ml | |
| return hsic_unbiased(mask * K, mask * L) | |
| return float(sim(K, L) / (torch.sqrt(sim(K, K) * sim(L, L)) + 1e-12)) | |
| class CovAcc: | |
| """Covariance from running sums of reference-centred features (same cancellation fix as RidgeStats).""" | |
| def __init__(self, dim, device="cuda"): | |
| self.s = torch.zeros(dim, dtype=torch.float64, device=device) | |
| self.ss = torch.zeros(dim, dim, dtype=torch.float64, device=device) | |
| self.n = 0 | |
| self.centre = _Centre(1) | |
| def add(self, x): # [N, D] | |
| x = self.centre(0, x) | |
| self.s += x.sum(0) | |
| xa = x.to(ACC_DTYPE) | |
| self.ss += (xa.T @ xa).double() | |
| self.n += x.shape[0] | |
| def participation_ratio(self): | |
| mu = self.s / self.n | |
| C = self.ss / self.n - torch.outer(mu, mu) | |
| ev = torch.linalg.eigvalsh(0.5 * (C + C.T).cpu()).clamp_min(0) | |
| return float(ev.sum() ** 2 / (ev ** 2).sum()) | |
| def participation_ratio(X): | |
| c = CovAcc(X.shape[1], device=X.device) | |
| c.add(X) | |
| return c.participation_ratio() | |