Download src/cross_features/ttp.py from zaaabik/paper_extraction: direct link, hf CLI and curl.
- Browser
- Download file 5.62 kB
-
https://huggingface.co/datasets/zaaabik/paper_extraction/resolve/main/src/cross_features/ttp.py
- Command line
-
hf download hf://datasets/zaaabik/paper_extraction/src/cross_features/ttp.py
-
curl -L -o ttp.py https://huggingface.co/datasets/zaaabik/paper_extraction/resolve/main/src/cross_features/ttp.py
5.62 kB
| """TTP — Token-Trajectory Persistence (cross-layer per-token). | |
| For each token t in the active sequence, its hidden-state trajectory | |
| through the encoder is the polyline | |
| v^t = (h_0^t, h_1^t, ..., h_L^t) in R^{(L+1) x D}. | |
| We extract two complementary signal blocks (~21 scalars total): | |
| (A) Cloud-topology block (14 scalars). | |
| Build the T x T distance matrix D_{ij} = mean_l (1 - cos(h_l^i, h_l^j)) | |
| (per-layer cosine distance averaged across all L+1 layers). | |
| Run Ripser up to H1 on D and summarise both diagrams by 7 scalars: | |
| bar count, sum/max persistence, top-2 persistence, entropy, mean | |
| bar midpoint. | |
| (B) Per-token shape block (7 scalars). | |
| For each token compute: | |
| - trajectory length L^t = sum_l ||h_{l+1}^t - h_l^t|| | |
| - step-to-step cosine s_l^t = cos(h_l^t, h_{l+1}^t) (mean over l) | |
| - net displacement N^t = ||h_L^t - h_0^t|| | |
| - curvature k^t = mean_l (1 - cos(h_{l+1}-h_l, h_l-h_{l-1})) | |
| Then aggregate across tokens: mean(L), std(L), mean(s), std(s), | |
| mean(N), mean(k), std(k). | |
| Admissible: pure hidden-state geometry. No W_cls, no logits, no softmax. | |
| Orthogonal axis to ZAP (which uses attention edges, not hidden states). | |
| """ | |
| from __future__ import annotations | |
| import numpy as np | |
| from ripser import ripser | |
| def _pd_stats(pd: np.ndarray) -> np.ndarray: | |
| """7-scalar persistence-diagram summary.""" | |
| if len(pd) == 0: | |
| return np.zeros(7, dtype=np.float32) | |
| finite = pd[np.isfinite(pd[:, 1])] | |
| if len(finite) == 0: | |
| return np.zeros(7, dtype=np.float32) | |
| lengths = finite[:, 1] - finite[:, 0] | |
| if len(lengths) == 0: | |
| return np.zeros(7, dtype=np.float32) | |
| sort_l = np.sort(lengths)[::-1] | |
| n = float(len(lengths)) | |
| s = float(lengths.sum()) | |
| top1 = float(sort_l[0]) if len(sort_l) >= 1 else 0.0 | |
| top2 = float(sort_l[1]) if len(sort_l) >= 2 else 0.0 | |
| p = lengths / max(s, 1e-12) | |
| ent = float(-(p[p > 0] * np.log(p[p > 0])).sum()) | |
| midpoints = (finite[:, 0] + finite[:, 1]) / 2.0 | |
| mid_mean = float(midpoints.mean()) | |
| return np.array([n, s, top1, top2, ent, float(sort_l[-1]) if len(sort_l) else 0.0, mid_mean], | |
| dtype=np.float32) | |
| COLUMNS = ( | |
| # H_0 block | |
| [f"ttp_h0_{s}" for s in ("count", "sum", "max", "top2", "ent", "min", "mid")] | |
| + [f"ttp_h1_{s}" for s in ("count", "sum", "max", "top2", "ent", "min", "mid")] | |
| # Shape block | |
| + ["ttp_len_mean", "ttp_len_std", | |
| "ttp_stepcos_mean", "ttp_stepcos_std", | |
| "ttp_netdisp_mean", | |
| "ttp_curv_mean", "ttp_curv_std"] | |
| ) | |
| DIM = len(COLUMNS) | |
| def extract_ttp(model, input_ids, attention_mask, cache, pred_label=None): | |
| """Return (features (B, DIM), columns). | |
| Reads cache.hidden_states: list of (L+1) tensors each (B, T, D). | |
| """ | |
| B = input_ids.shape[0] | |
| L_total = len(cache.hidden_states) | |
| feats = np.zeros((B, DIM), dtype=np.float32) | |
| for b in range(B): | |
| T_b = int(attention_mask[b].sum().item()) | |
| T_max = cache.hidden_states[0].shape[1] | |
| T = max(min(T_b, T_max), 4) | |
| # Stack: (L+1, T, D) | |
| hs = np.stack( | |
| [cache.hidden_states[l][b, :T].detach().float().cpu().numpy() | |
| for l in range(L_total)], | |
| axis=0, | |
| ) | |
| # (A) Cloud-topology: T x T distance matrix | |
| # per-layer cosine distance, averaged across layers | |
| norms = np.linalg.norm(hs, axis=-1, keepdims=True) # (L+1, T, 1) | |
| unit = hs / np.maximum(norms, 1e-9) # (L+1, T, D) | |
| # per-layer sim: (L+1, T, T) | |
| sim = np.einsum("ltd,lsd->lts", unit, unit) | |
| dist = (1.0 - sim).mean(axis=0) # (T, T) | |
| dist = 0.5 * (dist + dist.T) | |
| np.fill_diagonal(dist, 0.0) | |
| dist = np.clip(dist, 0.0, None) | |
| try: | |
| res = ripser(dist, distance_matrix=True, maxdim=1) | |
| pds = res["dgms"] | |
| except Exception: | |
| pds = [np.zeros((0, 2), dtype=np.float32), | |
| np.zeros((0, 2), dtype=np.float32)] | |
| h0_feats = _pd_stats(pds[0]) | |
| h1_feats = _pd_stats(pds[1]) if len(pds) > 1 else np.zeros(7, dtype=np.float32) | |
| # (B) Per-token shape statistics | |
| # deltas: (L, T, D) | |
| deltas = hs[1:] - hs[:-1] | |
| delta_norms = np.linalg.norm(deltas, axis=-1) # (L, T) | |
| traj_len = delta_norms.sum(axis=0) # (T,) | |
| net_disp = np.linalg.norm(hs[-1] - hs[0], axis=-1) # (T,) | |
| # step-to-step cosine between consecutive hidden states (not deltas) | |
| h_norm = np.linalg.norm(hs, axis=-1, keepdims=True) | |
| h_unit = hs / np.maximum(h_norm, 1e-9) | |
| stepcos = (h_unit[:-1] * h_unit[1:]).sum(axis=-1) # (L, T) | |
| # curvature: angle between consecutive deltas | |
| if deltas.shape[0] >= 2: | |
| d_norm = np.linalg.norm(deltas, axis=-1, keepdims=True) | |
| d_unit = deltas / np.maximum(d_norm, 1e-9) | |
| curv = 1.0 - (d_unit[:-1] * d_unit[1:]).sum(axis=-1) # (L-1, T) | |
| curv_mean = float(curv.mean()) | |
| curv_std = float(curv.std()) | |
| else: | |
| curv_mean = curv_std = 0.0 | |
| shape_feats = np.array([ | |
| float(traj_len.mean()), float(traj_len.std()), | |
| float(stepcos.mean()), float(stepcos.std()), | |
| float(net_disp.mean()), | |
| curv_mean, curv_std, | |
| ], dtype=np.float32) | |
| feats[b, :7] = h0_feats | |
| feats[b, 7:14] = h1_feats | |
| feats[b, 14:] = shape_feats | |
| return feats, COLUMNS | |