Download scripts/metrics.py from Cross-Mergeability/crossarch-1b-diagnostics: direct link, hf CLI and curl.
- Browser
- Download file 4.7 kB
-
https://huggingface.co/datasets/Cross-Mergeability/crossarch-1b-diagnostics/resolve/main/scripts/metrics.py
- Command line
-
hf download hf://datasets/Cross-Mergeability/crossarch-1b-diagnostics/scripts/metrics.py
-
curl -L -o metrics.py https://huggingface.co/datasets/Cross-Mergeability/crossarch-1b-diagnostics/resolve/main/scripts/metrics.py
4.7 kB
| """Representation-level diagnostics, computed on GPU (the CPU on this box is saturated). | |
| All metrics take paired sentence-embedding matrices X (n x d1), Y (n x d2): row i of each is | |
| the SGPT-pooled representation of the SAME parallel sentence. d1 need not equal d2 -- none of | |
| these metrics requires a shared parameter space, which is why they are defined across | |
| architectures while weight-space operators are not. No padding or truncation is ever applied. | |
| """ | |
| import numpy as np, torch | |
| torch.set_num_threads(8) | |
| _DEV = "cuda" if torch.cuda.is_available() else "cpu" | |
| def _t(X): | |
| if isinstance(X, torch.Tensor): | |
| return X.to(_DEV, torch.float64) | |
| return torch.as_tensor(np.asarray(X), dtype=torch.float64, device=_DEV) | |
| def _c(X): | |
| return X - X.mean(0, keepdim=True) | |
| def linear_cka(X, Y): | |
| """Linear CKA (Kornblith et al. 2019), feature-space form.""" | |
| X, Y = _c(_t(X)), _c(_t(Y)) | |
| num = (X.T @ Y).pow(2).sum() | |
| den = (X.T @ X).pow(2).sum().sqrt() * (Y.T @ Y).pow(2).sum().sqrt() | |
| return float(num / den) if den > 0 else float("nan") | |
| def procrustes_score(X, Y): | |
| """Orthogonal-Procrustes alignability in [0,1]; R is (d2,d1) so rectangular cases are native.""" | |
| X, Y = _c(_t(X)), _c(_t(Y)) | |
| X = X / X.norm(); Y = Y / Y.norm() | |
| U, _, Vh = torch.linalg.svd(Y.T @ X, full_matrices=False) | |
| R = U @ Vh | |
| return float(1.0 - (X - Y @ R).pow(2).sum() / X.pow(2).sum()) | |
| def svcca(X, Y, var_keep=0.99, max_k=64): | |
| """SVCCA (Raghu et al. 2017): SVD-truncate both sides, then mean canonical correlation.""" | |
| def prep(A): | |
| A = _c(_t(A)) | |
| U, s, _ = torch.linalg.svd(A, full_matrices=False) | |
| cum = torch.cumsum(s ** 2, 0) / (s ** 2).sum().clamp(min=1e-30) | |
| k = int(torch.searchsorted(cum, torch.tensor(var_keep, dtype=cum.dtype, device=cum.device)) + 1) | |
| k = max(2, min(k, max_k, A.shape[0] - 1, A.shape[1])) | |
| return U[:, :k] * s[:k] | |
| qa, _ = torch.linalg.qr(prep(X)); qb, _ = torch.linalg.qr(prep(Y)) | |
| sv = torch.linalg.svdvals(qa.T @ qb) | |
| return float(sv.clamp(0, 1).mean()) | |
| def retrieval_p_at_1(X, Y, seed=0, train_frac=0.5, ridge=1e-2): | |
| """Ridge map X->Y fit on a train split; cosine P@1 on the held-out split. Chance = 1/n_test.""" | |
| X, Y = _t(X), _t(Y) | |
| n = X.shape[0] | |
| perm = torch.from_numpy(np.random.default_rng(seed).permutation(n)).to(_DEV) | |
| ntr = int(train_frac * n) | |
| tr, te = perm[:ntr], perm[ntr:] | |
| mx, my = X[tr].mean(0), Y[tr].mean(0) | |
| Xtr, Ytr = X[tr] - mx, Y[tr] - my | |
| G = Xtr.T @ Xtr | |
| A = G + ridge * torch.trace(G) / G.shape[0] * torch.eye(G.shape[0], dtype=G.dtype, device=_DEV) | |
| W = torch.linalg.solve(A, Xtr.T @ Ytr) | |
| P = torch.nn.functional.normalize((X[te] - mx) @ W, dim=1) | |
| T = torch.nn.functional.normalize(Y[te] - my, dim=1) | |
| hits = (P @ T.T).argmax(1) == torch.arange(len(te), device=_DEV) | |
| return float(hits.double().mean()), float(1.0 / len(te)) | |
| def shuffled_control(Y, seed): | |
| """One permutation of side B, drawn once per pair and reused everywhere (paper 3.4).""" | |
| Y = _t(Y) | |
| return Y[torch.from_numpy(np.random.default_rng(seed).permutation(Y.shape[0])).to(_DEV)] | |
| def jackknife_cka(X, Y, n_blocks=50, seed=0, z=1.96): | |
| """Delete-a-group jackknife CI on linear CKA (the repo's default estimator, on GPU).""" | |
| X, Y = _t(X), _t(Y) | |
| n = X.shape[0] | |
| idx = torch.from_numpy(np.random.default_rng(seed).permutation(n)).to(_DEV) | |
| blocks = [idx[i::n_blocks] for i in range(n_blocks)] | |
| blocks = [b for b in blocks if len(b) > 0] | |
| full = linear_cka(X, Y) | |
| keep = torch.ones(n, dtype=torch.bool, device=_DEV) | |
| vals = [] | |
| for b in blocks: | |
| keep[:] = True; keep[b] = False | |
| vals.append(linear_cka(X[keep], Y[keep])) | |
| v = np.asarray(vals, float); k = len(v) | |
| ps = k * full - (k - 1) * v | |
| mean, se = ps.mean(), ps.std(ddof=1) / np.sqrt(k) | |
| return dict(cka=full, cka_debiased=float(mean), cka_se=float(se), | |
| cka_ci_low=float(mean - z * se), cka_ci_high=float(mean + z * se)) | |
| def all_rep_metrics(X, Y, pair_seed, with_ci=True): | |
| """Full representation-level family for one pair, matched and shuffled.""" | |
| X, Y = _t(X), _t(Y) | |
| Ys = shuffled_control(Y, pair_seed) | |
| p1, chance = retrieval_p_at_1(X, Y, seed=pair_seed) | |
| p1s, _ = retrieval_p_at_1(X, Ys, seed=pair_seed) | |
| out = dict(cka=linear_cka(X, Y), cka_shuf=linear_cka(X, Ys), | |
| procrustes=procrustes_score(X, Y), procrustes_shuf=procrustes_score(X, Ys), | |
| svcca=svcca(X, Y), svcca_shuf=svcca(X, Ys), | |
| p_at_1=p1, p_at_1_shuf=p1s, p_at_1_chance=chance) | |
| if with_ci: | |
| out.update(jackknife_cka(X, Y, seed=pair_seed)) | |
| return out | |