File size: 3,693 Bytes
2eb3475 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 | """PBD — Persistence Barycenter Drift across layers (Sprint 1, Idea 2).
For each layer l in L* = {0, 3, 6, 9, 11}:
1. Compute per-head PD-summary (18 scalars) for all 12 heads on the
per-head attention matrix.
2. Approximate the diagram barycenter as the *medoid* head: the one
with minimum mean L2 distance (in PD-summary space) to all other
heads.
3. Record per-layer: mean head-to-medoid distance, max distance,
median distance, and the medoid PD-summary norm.
Across consecutive layer pairs:
4. Layer-pair barycenter drift = L2(medoid_l_summary, medoid_{l+1}_summary).
5. Aggregate: cumulative drift, max drift, max-drift layer index,
late/early drift ratio.
Total: 5 layers * 4 = 20 + 4 inter-layer drifts + 4 aggregate = 28 scalars.
"""
from __future__ import annotations
import numpy as np
from .pd_hdg import _pd_summary_for_attention
LAYERS = (0, 3, 6, 9, 11)
def _columns():
cols = []
for l in LAYERS:
cols.extend([
f"pbd_L{l}_mean_to_medoid",
f"pbd_L{l}_max_to_medoid",
f"pbd_L{l}_med_to_medoid",
f"pbd_L{l}_medoid_pd_norm",
])
for i in range(len(LAYERS) - 1):
cols.append(f"pbd_drift_L{LAYERS[i]}_to_L{LAYERS[i+1]}")
cols.extend([
"pbd_drift_cum",
"pbd_drift_max",
"pbd_drift_argmax_idx",
"pbd_drift_late_over_early",
])
return cols
COLUMNS = _columns()
DIM = len(COLUMNS)
def extract_pbd(model, input_ids, attention_mask, cache, pred_label=None):
"""Return (features (B, DIM), columns)."""
B = input_ids.shape[0]
feats = np.zeros((B, DIM), dtype=np.float32)
medoid_block = 4 * len(LAYERS)
drift_block = medoid_block + (len(LAYERS) - 1)
agg_block = drift_block
for b in range(B):
T_b = int(attention_mask[b].sum().item())
T_b = max(T_b, 3)
medoid_summaries = np.zeros((len(LAYERS), 18), dtype=np.float32)
for li, l in enumerate(LAYERS):
A = cache.attn_weights[l][b].detach().float().cpu().numpy()
T_use = min(T_b, A.shape[-1])
H = A.shape[0]
pd_vec = np.zeros((H, 18), dtype=np.float32)
for h in range(H):
pd_vec[h] = _pd_summary_for_attention(A[h, :T_use, :T_use])
mu = pd_vec.mean(axis=0, keepdims=True)
sd = pd_vec.std(axis=0, keepdims=True) + 1e-6
Z = (pd_vec - mu) / sd
diff = Z[:, None, :] - Z[None, :, :]
D = np.sqrt((diff ** 2).sum(axis=-1))
mean_d = D.mean(axis=1)
m_idx = int(np.argmin(mean_d))
d_to_m = D[m_idx]
d_to_m_others = np.delete(d_to_m, m_idx)
feats[b, li * 4 + 0] = d_to_m_others.mean()
feats[b, li * 4 + 1] = d_to_m_others.max()
feats[b, li * 4 + 2] = float(np.median(d_to_m_others))
feats[b, li * 4 + 3] = float(np.linalg.norm(pd_vec[m_idx]))
medoid_summaries[li] = pd_vec[m_idx]
drifts = np.zeros(len(LAYERS) - 1, dtype=np.float32)
for i in range(len(LAYERS) - 1):
drifts[i] = float(np.linalg.norm(medoid_summaries[i + 1] - medoid_summaries[i]))
feats[b, medoid_block : drift_block] = drifts
feats[b, agg_block + 0] = float(drifts.sum())
feats[b, agg_block + 1] = float(drifts.max() if drifts.size else 0.0)
feats[b, agg_block + 2] = float(np.argmax(drifts)) if drifts.size else 0.0
half = len(drifts) // 2
early = drifts[:half].sum() if half else 0.0
late = drifts[half:].sum() if half else 0.0
feats[b, agg_block + 3] = float(late / (early + 1e-6))
return feats, COLUMNS
|