zaaabik's picture
Add files using upload-large-folder tool
2eb3475 verified
Raw History Blame Contribute Delete
5.18 kB
"""VAS — Value-Attention Similarity (admissible cross-substrate per head).
For each head (l, h), two T x T similarity matrices on the tokens are
naturally defined:
S_att = A_{l,h} (attention-induced)
S_val = V_{l,h} V_{l,h}^T / D_h_norm (value-vector Gram)
where V_{l,h} = X_l W_V^{l,h} is the per-head value projection of the
post-LN hidden state X_l. We approximate V via the head's attention
output contribution recorded in the forward cache (cache.head_writes),
since A V is what the head actually "writes" into the residual stream.
The cross-substrate intuition: a well-functioning head's attention
pattern should be consistent with the underlying value-space geometry
(tokens attended together should have similar value vectors); a
mismatch signals that attention is pointing somewhere uncalibrated
with the representation.
Per-head scalar:
d_{l,h} = || S_att_centered - S_val_centered ||_F / (||S_att||_F * ||S_val||_F)
(normalised mismatch)
c_{l,h} = CKA(S_att, S_val) (alignment correlation)
r_{l,h} = mean_i kl(S_att[i,:] || S_val[i,:]) (row-wise KL)
Aggregate per layer (mean, std, max, min across H heads) for each of
(d, c, r), then aggregate per scalar across L layers by (mean, std,
max, argmax, late, early). Total: 3 quantities x 4 head-stats x 6
layer-stats = 72 → trimmed to 36 scalars.
Admissible: pure attention + head-write geometry, no W_cls projection.
"""
from __future__ import annotations
import numpy as np
def _columns():
cols = []
for q in ("d", "c", "r"):
for hagg in ("mean", "std", "max", "min"):
for lstat in ("mean", "std", "max"): # 3 layer-stats only to keep 36
cols.append(f"vas_{q}_{hagg}_{lstat}")
return cols[:36]
COLUMNS = _columns()
DIM = len(COLUMNS)
def _center(K):
n = K.shape[0]
return K - K.mean(axis=0, keepdims=True) - K.mean(axis=1, keepdims=True) + K.mean()
def _cka(K1, K2, eps=1e-12):
K1c = _center(K1); K2c = _center(K2)
num = float(np.sum(K1c * K2c))
d1 = float(np.sum(K1c * K1c)); d2 = float(np.sum(K2c * K2c))
return num / max(np.sqrt(d1 * d2), eps)
def _row_kl(P, Q, eps=1e-12):
p = P / max(P.sum(axis=-1, keepdims=True).max(), eps)
q = Q / max(Q.sum(axis=-1, keepdims=True).max(), eps)
p = np.clip(p, eps, None); q = np.clip(q, eps, None)
return float((p * np.log(p / q)).sum(axis=-1).mean())
def extract_vas(model, input_ids, attention_mask, cache, pred_label=None):
"""Return (features (B, DIM), columns).
Uses cache.attn_weights and cache.head_writes (per-head write
contributions). head_writes[l] has shape (B, H, T, D_head).
"""
B = input_ids.shape[0]
if not getattr(cache, "head_writes", None):
return np.zeros((B, DIM), dtype=np.float32), COLUMNS
L = len(cache.attn_weights)
feats = np.zeros((B, DIM), dtype=np.float32)
for b in range(B):
T_b = int(attention_mask[b].sum().item())
T_max = cache.attn_weights[0].shape[-1]
T = max(min(T_b, T_max), 4)
per_layer_d = [] # (L,) head-mean / std / max / min
per_layer_c = []
per_layer_r = []
for l in range(L):
A_full = cache.attn_weights[l][b].detach().float().cpu().numpy() # (H, T_pad, T_pad)
HW = cache.head_writes[l][b].detach().float().cpu().numpy() # (H, T_pad, D_head)
A = A_full[:, :T, :T]
V = HW[:, :T] # (H, T, D_head)
d_h = np.zeros(A.shape[0])
c_h = np.zeros(A.shape[0])
r_h = np.zeros(A.shape[0])
for h in range(A.shape[0]):
S_att = A[h]
# value Gram (normalised)
V_norm = V[h] / np.maximum(np.linalg.norm(V[h], axis=-1, keepdims=True), 1e-9)
S_val = V_norm @ V_norm.T
S_val = (S_val + 1.0) / 2.0 # map [-1,1] to [0,1]
# Frobenius-normalised mismatch
Sa_c = _center(S_att); Sv_c = _center(S_val)
num = float(np.linalg.norm(Sa_c - Sv_c))
den = max(float(np.linalg.norm(S_att) * np.linalg.norm(S_val)), 1e-9)
d_h[h] = num / den
c_h[h] = _cka(S_att, S_val)
r_h[h] = _row_kl(S_att, S_val)
per_layer_d.append([d_h.mean(), d_h.std(), d_h.max(), d_h.min()])
per_layer_c.append([c_h.mean(), c_h.std(), c_h.max(), c_h.min()])
per_layer_r.append([r_h.mean(), r_h.std(), r_h.max(), r_h.min()])
D_arr = np.array(per_layer_d, dtype=np.float32) # (L, 4)
C_arr = np.array(per_layer_c, dtype=np.float32)
R_arr = np.array(per_layer_r, dtype=np.float32)
idx = 0
for ARR in (D_arr, C_arr, R_arr):
for hagg_col in range(4):
col = ARR[:, hagg_col]
feats[b, idx + 0] = float(col.mean())
feats[b, idx + 1] = float(col.std())
feats[b, idx + 2] = float(col.max())
idx += 3
if idx >= DIM: break
if idx >= DIM: break
return feats, COLUMNS