LucasLoading's picture
Upload 30 files
6f2ed01 verified
Raw
History Blame Contribute Delete
6.95 kB
# -*- coding: utf-8 -*-
"""Per-layer family centroids -- the single input both ISS and KTS consume.
Protocol 7.4-7.6 and 8.2 describe one preparation, then branch. Keeping it in
one place means ISS and KTS cannot silently disagree about what a fact's
representation under a condition family IS, which would make the joint
interpretation table (protocol 12) meaningless.
z = transport(h) raw: identity; jlens: y = B h
zbar = z - mu_r - mu_t + mu relation and family main effects removed
zt = L2(PCA-whiten(zbar)) one transform per (model, layer)
v = L2(mean of zt within a family) -> [F, T, D], plus a mask
"""
import os, json
import numpy as np
import torch
import mcommon as mc
def l2n(X, eps=1e-12):
return X / X.norm(dim=-1, keepdim=True).clamp_min(eps)
def whiten(Z, dim, shrinkage, eps):
"""PCA whitening fitted once on the pooled matrix (protocol 7.5).
Fitting per condition family is forbidden: it would absorb exactly the
cross-condition differences these metrics exist to detect.
"""
mu = Z.mean(0, keepdim=True)
Zc = Z - mu
n, d = Zc.shape
k = min(dim, d)
# d <= 5120 while n ~ 39k, so the d x d covariance route is far cheaper
# than an SVD of the tall matrix and numerically equivalent.
C = (Zc.T @ Zc).double() / max(n - 1, 1)
evals, evecs = torch.linalg.eigh(C)
evals = evals.flip(0)[:k].clamp_min(0).float()
evecs = evecs.flip(1)[:, :k].float()
lam = shrinkage * float(evals.mean())
return (Zc @ evecs) / torch.sqrt(evals + lam + eps)
class StateLoader:
"""Streams (layer -> family centroids) for one model."""
def __init__(self, model, transport="raw", coverage=None, device="auto",
shuffle_seed=None):
C = mc.cfg()
self.C = C
self.model = model
self.transport = transport
# Protocol 18.1: with fact identity destroyed, ISS must collapse,
# KTS-ID must fall to chance and KTS-Geo to ~0. If they do not, the
# metric is measuring something other than the fact.
self.shuffle_seed = shuffle_seed
self.mode = coverage or C["headline_coverage"]
self.dev = ("cuda" if torch.cuda.is_available() else "cpu") \
if device == "auto" else device
self.hdir = mc.out("hidden", model)
self.meta = json.load(open(os.path.join(self.hdir, "index.json")))
if not self.meta.get("complete"):
raise SystemExit(f"{model}: hidden states incomplete; run extract_hidden.py")
self.families = C["main_families"]
fam_id = {t: i for i, t in enumerate(self.families)}
self.keep_facts = mc.eval_fact_set(self.mode)
self.fidx = {f: i for i, f in enumerate(self.keep_facts)}
self.rel_of = mc.fact_relation()
self.sel = np.array([i for i, f in enumerate(self.meta["fact_ids"])
if f in self.fidx], dtype=np.int64)
self.fact_idx = torch.tensor(
[self.fidx[self.meta["fact_ids"][i]] for i in self.sel], device=self.dev)
self.fam_idx = torch.tensor(
[fam_id[self.meta["families"][i]] for i in self.sel], device=self.dev)
self.by_rel = {}
for f in self.keep_facts:
self.by_rel.setdefault(self.rel_of[f], []).append(self.fidx[f])
rel_pos = {r: i for i, r in enumerate(self.by_rel)}
self.rel_idx = torch.tensor(
[rel_pos[self.rel_of[self.meta["fact_ids"][i]]] for i in self.sel],
device=self.dev)
self.n_rel = len(self.by_rel)
self.window = self.meta["window"]
self.late = set(self.meta["late_window"])
self.B = None
if transport == "jlens":
self.B = {}
for l in self.window:
p = mc.out("jlens", model, f"L{l:03d}", "B.npy")
if not os.path.exists(p):
raise SystemExit(
f"{model} L{l}: no J-Lens factor at {p}. Run src/jlens.py "
"first, or use --transport raw for the ablation.")
self.B[l] = torch.from_numpy(np.load(p)).to(self.dev).float()
@property
def n_facts(self):
return len(self.keep_facts)
def centroids(self, layer):
"""-> V [F, T, D] (zero where absent), mask [F, T]."""
icfg = self.C["iss"]
eps = float(icfg["eps"])
H = np.load(os.path.join(self.hdir, f"L{layer:03d}.npy"), mmap_mode="r")
Z = torch.from_numpy(np.ascontiguousarray(H[self.sel])).to(self.dev).float()
if self.B is not None:
Z = Z @ self.B[layer].T # y = B h (J-Lens spec 6.4)
# ---- protocol 7.4 double residualisation
mu = Z.mean(0, keepdim=True)
D = Z.shape[1]
mu_r = torch.zeros(self.n_rel, D, device=self.dev)
cr = torch.zeros(self.n_rel, device=self.dev)
mu_r.index_add_(0, self.rel_idx, Z)
cr.index_add_(0, self.rel_idx, torch.ones_like(self.rel_idx, dtype=torch.float))
mu_r /= cr.clamp_min(1).unsqueeze(-1)
mu_t = torch.zeros(len(self.families), D, device=self.dev)
ct = torch.zeros(len(self.families), device=self.dev)
mu_t.index_add_(0, self.fam_idx, Z)
ct.index_add_(0, self.fam_idx, torch.ones_like(self.fam_idx, dtype=torch.float))
mu_t /= ct.clamp_min(1).unsqueeze(-1)
Z = Z - mu_r[self.rel_idx] - mu_t[self.fam_idx] + mu
Z = l2n(whiten(Z, icfg["pca_dim"], icfg["shrinkage"], eps))
# ---- protocol 7.6 family centroid: average inside the family FIRST, so
# paraphrase (10,053 queries) cannot outweigh anchor (2,592) in one fact
F, T, Dn = self.n_facts, len(self.families), Z.shape[1]
V = torch.zeros(F, T, Dn, device=self.dev)
cnt = torch.zeros(F, T, device=self.dev)
flat = self.fact_idx * T + self.fam_idx
V.view(-1, Dn).index_add_(0, flat, Z)
cnt.view(-1).index_add_(0, flat, torch.ones_like(flat, dtype=torch.float))
mask = cnt > 0
V = V / cnt.clamp_min(1).unsqueeze(-1)
V = l2n(V) * mask.unsqueeze(-1)
if self.shuffle_seed is not None:
# Permute the fact axis INDEPENDENTLY per family, and permute within
# a relation so the shuffled control keeps the same relation
# composition -- otherwise a drop could just mean facts got matched
# against a different relation, which is not the null being tested.
g = torch.Generator().manual_seed(self.shuffle_seed + 1000 * layer)
for t in range(T):
for members in self.by_rel.values():
idx = torch.tensor(members)
perm = idx[torch.randperm(len(members), generator=g)]
V[idx, t] = V[perm.to(V.device), t].clone()
mask[idx, t] = mask[perm.to(mask.device), t].clone()
return V, mask