Download src/extract_topological_features.py from zaaabik/paper_extraction: direct link, hf CLI and curl.
- Browser
- Download file 5.73 kB
-
https://huggingface.co/datasets/zaaabik/paper_extraction/resolve/main/src/extract_topological_features.py
- Command line
-
hf download hf://datasets/zaaabik/paper_extraction/src/extract_topological_features.py
-
curl -L -o extract_topological_features.py https://huggingface.co/datasets/zaaabik/paper_extraction/resolve/main/src/extract_topological_features.py
5.73 kB
| """Single-attention topological features (ripser / template / graph). | |
| v1: load precomputed .npy from paper/drive_folder/ and flatten to (N, F). | |
| v2 (TODO): recompute from raw attention dumps using ripser + networkx. | |
| """ | |
| from __future__ import annotations | |
| from pathlib import Path | |
| from typing import Dict, List, Tuple | |
| import numpy as np | |
| def _load_and_flatten(path: str, sample_axis_last: bool, expected_n: int) -> np.ndarray: | |
| """The shipped .npy files have N on different axes depending on the feature type. | |
| Observed shapes (paper/drive_folder/): | |
| ripser (12, 12, N, 14) | |
| template (12, 12, 7, N) | |
| graph (12, 12, 9, N, 6) | |
| We locate the axis with size == expected_n and move it to the front. | |
| """ | |
| arr = np.load(path) | |
| n_axes = [i for i, s in enumerate(arr.shape) if s == expected_n] | |
| if not n_axes: | |
| raise ValueError(f"Unexpected shape {arr.shape} for {path}; expected N={expected_n}") | |
| moved = np.moveaxis(arr, n_axes[0], 0) | |
| return moved.reshape(moved.shape[0], -1).astype(np.float32) | |
| def load_existing_features( | |
| cfg_files: Dict[str, str], split: str, n_samples: int | |
| ) -> Tuple[np.ndarray, List[str]]: | |
| """Return (N, F_total) feature matrix concatenating ripser+template+graph.""" | |
| groups = [ | |
| (f"ripser_{split}", "ripser"), | |
| (f"template_{split}", "template"), | |
| (f"graph_{split}", "graph"), | |
| ] | |
| arrays, names = [], [] | |
| for key, label in groups: | |
| path = cfg_files.get(key) | |
| if not path or not Path(path).exists(): | |
| continue | |
| flat = _load_and_flatten(path, sample_axis_last=True, expected_n=n_samples) | |
| arrays.append(flat) | |
| names.extend([f"{label}_{i}" for i in range(flat.shape[1])]) | |
| if not arrays: | |
| return np.zeros((n_samples, 0), dtype=np.float32), [] | |
| return np.concatenate(arrays, axis=1), names | |
| def load_recomputed_features( | |
| recomputed_dir: str | Path, split: str, n_samples: int | |
| ) -> Tuple[np.ndarray, List[str]]: | |
| """Load features that were produced by ``scripts/07_recompute_topology.py``. | |
| Expected files under ``recomputed_dir``: | |
| - ``{split}_ripser.npy`` — (L, H, N, 14) | |
| - ``{split}_template.npy`` — (L, H, 7, N) | |
| - ``{split}_s_w_e_v_c_b0b1_m_k_lists_array_6.npy`` — (L, H, 9, N, 6) | |
| """ | |
| rd = Path(recomputed_dir) | |
| mapping = { | |
| f"ripser_{split}": ("ripser", rd / f"{split}_ripser.npy"), | |
| f"template_{split}": ("template", rd / f"{split}_template.npy"), | |
| f"graph_{split}": ("graph", rd / f"{split}_s_w_e_v_c_b0b1_m_k_lists_array_6.npy"), | |
| } | |
| cfg_files = {key: str(path) for key, (_, path) in mapping.items()} | |
| return load_existing_features(cfg_files, split=split, n_samples=n_samples) | |
| def _process_one_sample(args): | |
| """Worker: load one sample's attention .npz and compute its features.""" | |
| idx, attn_dir_str = args | |
| from .topology_features import extract_all_features # local import for spawn-safety | |
| from pathlib import Path as _Path | |
| with np.load(_Path(attn_dir_str) / f"{idx:06d}.npz") as data: | |
| attn = data["attn"].astype(np.float32) | |
| return idx, extract_all_features(attn) | |
| def recompute_from_attention( | |
| attn_dir: Path, indices: List[int], n_workers: int = 1 | |
| ) -> Tuple[np.ndarray, np.ndarray, np.ndarray]: | |
| """Recompute the three SingleAttention feature families from on-disk attention dumps. | |
| For each sample idx in ``indices``, loads ``attn_dir/{idx:06d}.npz`` (shape | |
| (L, H, T, T)) and computes graph/ripser/template features per (layer, head). | |
| Returns three arrays matching the schema of paper/drive_folder/*.npy: | |
| - graph : (L, H, N_graph=9, N, N_thresholds=6) | |
| - ripser : (L, H, N, N_ripser=14) | |
| - template : (L, H, N_template=7, N) | |
| Use ``n_workers > 1`` to parallelize across samples via multiprocessing | |
| (networkx is pure-Python so this is CPU-bound and benefits from many cores). | |
| Graph and Ripser features are validated against the precomputed arrays by | |
| 06_parity_test.py (max abs error ≈ 1 unit for graph counts due to float16 | |
| storage; ≈ 1e-3 for Ripser longest deaths). Template features use a | |
| best-effort definition (max abs error ≈ 0.1; see topology_features.py). | |
| """ | |
| from .topology_features import ( | |
| extract_all_features, THRESHOLDS, N_RIPSER, N_TEMPLATE, N_GRAPH, | |
| ) | |
| from tqdm import tqdm | |
| N = len(indices) | |
| probe = np.load(attn_dir / f"{indices[0]:06d}.npz")["attn"] | |
| L, H = probe.shape[:2] | |
| graph_arr = np.zeros((L, H, N_GRAPH, N, len(THRESHOLDS)), dtype=np.float32) | |
| ripser_arr = np.zeros((L, H, N, N_RIPSER), dtype=np.float32) | |
| template_arr = np.zeros((L, H, N_TEMPLATE, N), dtype=np.float32) | |
| pos_of = {idx: n for n, idx in enumerate(indices)} | |
| args = [(idx, str(attn_dir)) for idx in indices] | |
| if n_workers <= 1: | |
| for n, idx in enumerate(tqdm(indices, desc="recompute features")): | |
| _, feats = _process_one_sample(args[n]) | |
| graph_arr[:, :, :, n, :] = feats["graph"] | |
| ripser_arr[:, :, n, :] = feats["ripser"] | |
| template_arr[:, :, :, n] = feats["template"] | |
| return graph_arr, ripser_arr, template_arr | |
| from multiprocessing import Pool | |
| with Pool(processes=n_workers) as pool: | |
| for idx, feats in tqdm( | |
| pool.imap_unordered(_process_one_sample, args, chunksize=4), | |
| total=N, desc=f"recompute features [{n_workers}w]", | |
| ): | |
| n = pos_of[idx] | |
| graph_arr[:, :, :, n, :] = feats["graph"] | |
| ripser_arr[:, :, n, :] = feats["ripser"] | |
| template_arr[:, :, :, n] = feats["template"] | |
| return graph_arr, ripser_arr, template_arr | |