Download src/cross_features/aaa.py from zaaabik/paper_extraction: direct link, hf CLI and curl.
- Browser
- Download file 6.86 kB
-
https://huggingface.co/datasets/zaaabik/paper_extraction/resolve/main/src/cross_features/aaa.py
- Command line
-
hf download hf://datasets/zaaabik/paper_extraction/src/cross_features/aaa.py
-
curl -L -o aaa.py https://huggingface.co/datasets/zaaabik/paper_extraction/resolve/main/src/cross_features/aaa.py
6.86 kB
| """AAA — Attention–Activation Alignment (cross attention x hidden states). | |
| For each head u (in layer m) and each token i, the attention-weighted | |
| neighborhood vector is | |
| mu_{u,m,i} = sum_j a_{u,i,j} * h_{m,j} in R^D | |
| and the per-token alignment residual is | |
| q_{u,m,i} = || h_{m,i} - mu_{u,m,i} ||_2. | |
| Large residuals indicate tokens whose own hidden state is far from what | |
| the attention pattern would "predict" by aggregating neighbors. The | |
| intuition: mis-classified examples carry tokens with anomalous | |
| attention-vs-state alignment. | |
| In addition to the residual statistics, we add per-pair similarity: | |
| s_{u,m,i} = cos(h_{m,i}, mu_{u,m,i}) | |
| which captures the direction of alignment rather than magnitude. | |
| The construction is admissible: only attention matrices and hidden | |
| states, no W_cls projection, no logits, no softmax outputs. | |
| Per sample we aggregate: | |
| Block A (per-head residual, 24 scalars): | |
| For each layer in {early=0, mid=L/2, late=L-1} and each head, take | |
| the per-token residual q_{u,m,i}, summarise across active tokens by | |
| (mean, std). Then aggregate across H heads of that layer by | |
| (mean, std, max, min) of the per-head mean-residual --- yielding | |
| 8 scalars per layer x 3 layers = 24 scalars. | |
| Block B (per-head cosine alignment, 12 scalars): | |
| Same 3-layer grid. For each layer, per-head mean cosine across | |
| tokens; aggregate H heads by (mean, std, max, min) = 4 scalars | |
| per layer x 3 layers = 12 scalars. | |
| Block C (depth profile, 6 scalars): | |
| Per-layer head-and-token-averaged residual q_{m} and cosine s_{m}, | |
| summarised across all L layers by (mean, std, late-half mean - early-half mean). | |
| 2 quantities x 3 stats = 6 scalars. | |
| Total: 24 + 12 + 6 = 42 scalars. | |
| """ | |
| from __future__ import annotations | |
| import numpy as np | |
| def _columns(): | |
| cols = [] | |
| # Block A: residual per stratified layer, head-aggregated | |
| for lpos in ("early", "mid", "late"): | |
| for hagg in ("mean", "std", "max", "min"): | |
| for tstat in ("mean", "std"): | |
| cols.append(f"aaa_resid_{lpos}_{hagg}_{tstat}") | |
| # Block B: cosine per stratified layer, head-aggregated | |
| for lpos in ("early", "mid", "late"): | |
| for hagg in ("mean", "std", "max", "min"): | |
| cols.append(f"aaa_cos_{lpos}_{hagg}") | |
| # Block C: depth profile | |
| for q in ("resid", "cos"): | |
| for s in ("mean", "std", "latemearly"): | |
| cols.append(f"aaa_depth_{q}_{s}") | |
| return cols | |
| COLUMNS = _columns() | |
| DIM = len(COLUMNS) | |
| def extract_aaa(model, input_ids, attention_mask, cache, pred_label=None): | |
| """Return (features (B, DIM), columns). | |
| Reads: | |
| cache.attn_weights[l] -> (B, H, T, T) | |
| cache.hidden_states[l] -> (B, T, D) (length L+1; we use indices 1..L+1 | |
| to align with attention output) | |
| """ | |
| B = input_ids.shape[0] | |
| L = len(cache.attn_weights) | |
| # hidden_states has L+1 entries (embeddings + L block outputs). We pair | |
| # each attention layer l with the hidden state that the attention reads, | |
| # which is hidden_states[l] (the input to block l). | |
| feats = np.zeros((B, DIM), dtype=np.float32) | |
| layer_grid = [0, L // 2, L - 1] # early, mid, late | |
| 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 head-and-token-averaged residual and cosine, for depth profile | |
| per_layer_resid_mean = np.zeros(L, dtype=np.float32) | |
| per_layer_cos_mean = np.zeros(L, dtype=np.float32) | |
| block_a = [] # length 3 of length-8 vectors | |
| block_b = [] # length 3 of length-4 vectors | |
| for li, l in enumerate(range(L)): | |
| A_full = cache.attn_weights[l][b].detach().float().cpu().numpy() # (H, T_pad, T_pad) | |
| H_state = cache.hidden_states[l][b].detach().float().cpu().numpy() # (T_pad, D) | |
| A = A_full[:, :T, :T] # (H, T, T) | |
| H_vec = H_state[:T] # (T, D) | |
| # mu_{u, i} = sum_j a_{u,i,j} * h_j -> (H, T, D) | |
| mu = np.einsum("hij,jd->hid", A, H_vec) | |
| diff = H_vec[None, :, :] - mu # (H, T, D) | |
| resid = np.linalg.norm(diff, axis=-1) # (H, T) | |
| # cosine between h_i and mu_{u,i} | |
| h_norm = np.linalg.norm(H_vec, axis=-1, keepdims=True) | |
| mu_norm = np.linalg.norm(mu, axis=-1, keepdims=True) | |
| cos = (H_vec[None, :, :] * mu).sum(axis=-1) / ( | |
| np.maximum(h_norm[None, :, 0] * mu_norm[:, :, 0], 1e-9)) | |
| # cos has shape (H, T) | |
| # depth-profile aggregation (head + token averaged) | |
| per_layer_resid_mean[li] = float(resid.mean()) | |
| per_layer_cos_mean[li] = float(cos.mean()) | |
| # Block A/B contributions if this layer is in the grid | |
| if l in layer_grid: | |
| # per-head stats across tokens | |
| resid_head_mean = resid.mean(axis=1) # (H,) | |
| resid_head_std = resid.std(axis=1) # (H,) | |
| cos_head_mean = cos.mean(axis=1) # (H,) | |
| # Block A: aggregate per-head means by (mean,std,max,min) x (mean,std) | |
| a_vec = np.zeros(8, dtype=np.float32) | |
| idx = 0 | |
| for hagg in (np.mean, np.std, np.max, np.min): | |
| a_vec[idx + 0] = float(hagg(resid_head_mean)) | |
| a_vec[idx + 1] = float(hagg(resid_head_std)) | |
| idx += 2 | |
| block_a.append(a_vec) | |
| # Block B | |
| b_vec = np.array([ | |
| float(cos_head_mean.mean()), | |
| float(cos_head_mean.std()), | |
| float(cos_head_mean.max()), | |
| float(cos_head_mean.min()), | |
| ], dtype=np.float32) | |
| block_b.append(b_vec) | |
| # If layer_grid didn't yield 3 layers (shouldn't happen), pad zeros | |
| while len(block_a) < 3: block_a.append(np.zeros(8, dtype=np.float32)) | |
| while len(block_b) < 3: block_b.append(np.zeros(4, dtype=np.float32)) | |
| # Assemble feature vector | |
| idx = 0 | |
| for a_vec in block_a: | |
| feats[b, idx:idx + 8] = a_vec; idx += 8 | |
| for b_vec in block_b: | |
| feats[b, idx:idx + 4] = b_vec; idx += 4 | |
| # Block C: depth profile (mean, std, late_half_mean - early_half_mean) | |
| half = L // 2 | |
| for arr in (per_layer_resid_mean, per_layer_cos_mean): | |
| feats[b, idx + 0] = float(arr.mean()) | |
| feats[b, idx + 1] = float(arr.std()) | |
| feats[b, idx + 2] = float(arr[half:].mean() - arr[:half].mean()) | |
| idx += 3 | |
| return feats, COLUMNS | |