zaaabik's picture
Add files using upload-large-folder tool
2eb3475 verified
Raw History Blame Contribute Delete
4.53 kB
"""KCS — Key-Concept Similarity (Phase 1, idx 5).
For each layer l, find the top-K = 32 MLP neurons by |pre-activation| at
[CLS], i.e. ``cache.mlp_pre_act[l][:, 0, :]``. Each selected neuron j
corresponds to a value vector v_{l, j} = W_down[l][:, j] (the j-th
column of the MLP down-projection); its logit-space contribution is
W_cls @ v_{l, j}.
Build a (32 L) × (32 L) similarity matrix
A[(l1, j1), (l2, j2)] = cos(W_cls @ v_{l1, j1}, W_cls @ v_{l2, j2})
and summarise:
* top-10 eigenvalues of the normalised Laplacian of |A| (10)
* Ripser persistence on (1 - A) treated as distance (18)
* 5 global scalars: mean, std, max, min, median of |A| (5)
Output dim = 33.
References: Geva et al. EMNLP 2021/2022; Voita et al. ACL 2024.
"""
from __future__ import annotations
import numpy as np
import torch
from .persistence_summary import ripser_summary_from_distance, column_names as pcol
K = 32
L = 12
def _columns():
cols = [f"kcs_lap_eig{i}" for i in range(10)]
cols.extend(pcol("kcs_pers"))
cols.extend(["kcs_A_mean", "kcs_A_std", "kcs_A_max", "kcs_A_min", "kcs_A_median"])
return cols
COLUMNS = _columns()
DIM = len(COLUMNS)
def _mlp_w_down(model) -> list:
"""Return per-layer W_down weight tensors (D, 4D), one per encoder layer."""
if hasattr(model, "roberta"):
layers = model.roberta.encoder.layer
elif hasattr(model, "electra"):
layers = model.electra.encoder.layer
else:
layers = model.encoder.layer
return [l.output.dense.weight.detach() for l in layers]
def _classifier_out_proj(model) -> torch.Tensor:
cls = model.classifier
for attr in ("out_proj", "dense", "fc", "linear"):
if hasattr(cls, attr):
sub = getattr(cls, attr)
if isinstance(sub, torch.nn.Linear):
return sub.weight.detach()
if isinstance(cls, torch.nn.Linear):
return cls.weight.detach()
raise RuntimeError("Could not locate classifier out_proj weight")
def _normalised_laplacian_eigs(A: np.ndarray, k: int = 10) -> np.ndarray:
n = A.shape[0]
A = np.abs(A)
np.fill_diagonal(A, 0.0)
d = A.sum(axis=1)
d_safe = np.where(d > 0, d, 1.0)
D_inv_sqrt = 1.0 / np.sqrt(d_safe)
L_norm = np.eye(n) - (D_inv_sqrt[:, None] * A * D_inv_sqrt[None, :])
try:
ev = np.linalg.eigvalsh(0.5 * (L_norm + L_norm.T))
except np.linalg.LinAlgError:
return np.zeros(k, dtype=np.float32)
ev = np.sort(ev)[::-1]
out = np.zeros(k, dtype=np.float32)
out[:min(k, ev.size)] = ev[:min(k, ev.size)]
return out
def extract_kcs(model, input_ids, attention_mask, cache, pred_label=None):
"""Return (features (B, 33), columns)."""
B = input_ids.shape[0]
feats = np.zeros((B, DIM), dtype=np.float32)
W_cls = _classifier_out_proj(model).float() # (C, D)
W_down = _mlp_w_down(model) # list of (D, 4D)
# Per-layer pre-activation magnitudes at [CLS]
# cache.mlp_pre_act[l] shape (B, T, 4D)
pre_cls = [cache.mlp_pre_act[l][:, 0, :].float() for l in range(L)] # list of (B, 4D)
for b in range(B):
# Per-layer top-K indices into 4D for THIS sample
top_idx = []
for l in range(L):
mag = pre_cls[l][b].abs()
k_eff = min(K, mag.shape[0])
_, idx = torch.topk(mag, k_eff)
top_idx.append(idx.cpu().numpy())
# Project the selected neurons' value-vectors through W_cls
proj = [] # (n_l × C)
node_layer = []
for l in range(L):
idx = top_idx[l]
V = W_down[l][:, idx].float() # (D, k)
P = (W_cls @ V).T # (k, C)
proj.append(P)
node_layer.extend([l] * idx.size)
Proj = torch.cat(proj, dim=0) # (sum_k, C)
Pn = torch.nn.functional.normalize(Proj, dim=-1)
A = (Pn @ Pn.T).cpu().numpy() # (n, n)
eigs = _normalised_laplacian_eigs(A, k=10)
feats[b, 0:10] = eigs
D = 1.0 - A
np.fill_diagonal(D, 0.0)
pers, _ = ripser_summary_from_distance(D, maxdim=1, prefix="kcs_pers")
feats[b, 10 : 28] = pers
off = A.copy()
np.fill_diagonal(off, 0.0)
v = off[np.triu_indices_from(off, k=1)]
feats[b, 28:33] = [
float(v.mean()), float(v.std()), float(v.max()),
float(v.min()), float(np.median(v)),
]
return feats, COLUMNS