"""Cross-barcode (PairedAttention) features via Prim-MST RTD approximation. Port of `RTD_simplified_summ_only` from paper/drive_folder/cross_barcodes_approximation.ipynb, generalized over the 144 (layer, head) pairs and across samples, with a batched GPU implementation that processes all pairs of a sample in parallel. Public API: - ``rtd_simplified(a1, a2, q)`` — single-pair convenience wrapper. - ``rtd_simplified_batched(A1, A2, q)`` — vectorized over P pairs at once. - ``compute_cross_barcode_features(...)`` — runs the pipeline over a dataset. Private: - ``_prim_mst_sum_loop(adj)`` — original per-matrix reference (slow, single). - ``_prim_mst_sum(adj)`` — batched implementation; accepts (n,n) or (B,n,n). - ``_rtd_simplified_loop(a1,a2,q)`` — original notebook-faithful single-pair reference. """ from __future__ import annotations from pathlib import Path from typing import List, Tuple import numpy as np import torch from tqdm import tqdm # --------------------------------------------------------------------------- # Reference implementations (kept for tests) # --------------------------------------------------------------------------- def _prim_mst_sum_loop(adj: torch.Tensor) -> torch.Tensor: """Reference single-matrix Prim-MST sum (loop form). Faithful re-implementation of paper/drive_folder/cross_barcodes_approximation.ipynb `prim_algo_simplified`. """ n = adj.shape[0] infty = adj.max().item() + 10.0 dst = torch.full((n,), infty, device=adj.device, dtype=adj.dtype) anc = -torch.ones(n, device=adj.device, dtype=torch.long) visited = torch.zeros(n, device=adj.device, dtype=torch.bool) s = torch.zeros((), device=adj.device, dtype=adj.dtype) v = 0 for _ in range(n - 1): visited[v] = True improved = dst > adj[v] anc = torch.where(improved, torch.full_like(anc, v), anc) dst = torch.minimum(dst, adj[v]) dst = torch.where(visited, torch.full_like(dst, infty), dst) v = int(torch.argmin(dst).item()) s = s + adj[v, anc[v]] return s def _rtd_simplified_loop(a1: torch.Tensor, a2: torch.Tensor, q: float = 0.9) -> torch.Tensor: """Reference single-pair RTD (loop form).""" r1 = a1 / torch.quantile(a1, q) r2 = a2 / torch.quantile(a2, q) rmin = torch.minimum(r1, r2) return (_prim_mst_sum_loop(r1) - _prim_mst_sum_loop(rmin)) + ( _prim_mst_sum_loop(r2) - _prim_mst_sum_loop(rmin) ) # --------------------------------------------------------------------------- # Batched implementation (production path) # --------------------------------------------------------------------------- def _prim_mst_sum(adj: torch.Tensor) -> torch.Tensor: """Sum of MST edge weights for a batch of dense weighted adjacency matrices. Accepts either (n, n) or (B, n, n). Equivalent to running Prim's algorithm independently on each matrix in the batch, but with the inner ``argmin`` loop running once across the whole batch in a single GPU kernel per step. Returns: () if input was (n, n); (B,) if input was (B, n, n). """ squeeze_out = False if adj.ndim == 2: adj = adj.unsqueeze(0) squeeze_out = True B, n, _ = adj.shape device, dtype = adj.device, adj.dtype infty = float(adj.amax().item() + 10.0) dst = torch.full((B, n), infty, device=device, dtype=dtype) anc = torch.full((B, n), -1, device=device, dtype=torch.long) visited = torch.zeros((B, n), device=device, dtype=torch.bool) s = torch.zeros(B, device=device, dtype=dtype) v = torch.zeros(B, device=device, dtype=torch.long) # all start at vertex 0 batch_idx = torch.arange(B, device=device) for _ in range(n - 1): visited[batch_idx, v] = True row = adj[batch_idx, v] # (B, n) improved = dst > row # (B, n) anc = torch.where(improved, v.unsqueeze(1).expand_as(anc), anc) dst = torch.minimum(dst, row) dst = torch.where(visited, torch.full_like(dst, infty), dst) v = dst.argmin(dim=1) # (B,) s = s + adj[batch_idx, v, anc[batch_idx, v]] return s.squeeze(0) if squeeze_out else s def rtd_simplified_batched(a1: torch.Tensor, a2: torch.Tensor, q: float = 0.9) -> torch.Tensor: """Batched sum-of-MST RTD estimator. Args: a1, a2: shape (P, n, n) — P pairs of n×n attention matrices. Returns: rtd: shape (P,) RTD scores. """ P = a1.shape[0] a1_flat = a1.reshape(P, -1) a2_flat = a2.reshape(P, -1) q1 = torch.quantile(a1_flat, q, dim=1).view(P, 1, 1) q2 = torch.quantile(a2_flat, q, dim=1).view(P, 1, 1) r1 = a1 / q1 r2 = a2 / q2 rmin = torch.minimum(r1, r2) stacked = torch.cat([r1, r2, rmin], dim=0) # (3P, n, n) s = _prim_mst_sum(stacked).view(3, P) r1_sum, r2_sum, rmin_sum = s[0], s[1], s[2] return (r1_sum - rmin_sum) + (r2_sum - rmin_sum) def rtd_simplified(a1: torch.Tensor, a2: torch.Tensor, q: float = 0.9) -> torch.Tensor: """Single-pair RTD — thin wrapper over the batched path.""" return rtd_simplified_batched(a1.unsqueeze(0), a2.unsqueeze(0), q=q).squeeze(0) # --------------------------------------------------------------------------- # Pair selection strategies # --------------------------------------------------------------------------- def _pairs_all_144() -> List[Tuple[int, int, int, int]]: """144 pairs: last-layer heads (11, j) crossed with last-head layers (k, 11).""" pairs = [] for j in range(12): for k in range(12): pairs.append((11, j, k, 11)) return pairs def _pairs_last_layer() -> List[Tuple[int, int, int, int]]: """Cross-barcodes **inside the last layer** — every unordered pair of heads (hi, hj) within layer 11, excluding the diagonal hi == hj (RTD is symmetric and zero on identical matrices). 12 choose 2 = 66 pairs. """ return _pairs_last_n_layers(1) def _pairs_last_n_layers(n: int) -> List[Tuple[int, int, int, int]]: """All unique unordered pairs among the (layer, head) attention matrices drawn from the last ``n`` layers — that is, layers in [12 - n, 11]. With L=12 layers and H=12 heads, this yields ``C(n*H, 2)`` pairs: n=1 → 66, n=2 → 276, n=3 → 630, n=4 → 1128, n=12 → 10296. """ L, H = 12, 12 layers = list(range(L - n, L)) attentions = [(layer, head) for layer in layers for head in range(H)] out = [] for i in range(len(attentions)): for j in range(i + 1, len(attentions)): li, hi = attentions[i] lj, hj = attentions[j] out.append((li, hi, lj, hj)) return out def _pairs_stratified(layer_indices: List[int]) -> List[Tuple[int, int, int, int]]: """All unordered (layer, head) pairs among heads at the given layer indices. With H=12 heads per layer, len(layer_indices)=k gives C(k*H, 2) pairs. k=3 → 630, k=4 → 1128. """ H = 12 attentions = [(layer, head) for layer in layer_indices for head in range(H)] out = [] for i in range(len(attentions)): for j in range(i + 1, len(attentions)): li, hi = attentions[i] lj, hj = attentions[j] out.append((li, hi, lj, hj)) return out def _resolve_pairs(strategy: str) -> List[Tuple[int, int, int, int]]: if strategy == "all_144": return _pairs_all_144() if strategy == "last_layer": return _pairs_last_n_layers(1) if strategy == "last_2_layers": return _pairs_last_n_layers(2) if strategy == "last_3_layers": return _pairs_last_n_layers(3) if strategy == "last_4_layers": return _pairs_last_n_layers(4) if strategy == "all_pairs": return _pairs_last_n_layers(12) # all C(144, 2) = 10,296 pairs # Stratified depth-spanning strategies (start / middle / end) if strategy == "stratified_3": return _pairs_stratified([1, 6, 11]) # early / mid / late, 36 heads → 630 pairs if strategy == "stratified_4": return _pairs_stratified([0, 4, 8, 11]) # 48 heads → 1128 pairs if strategy == "stratified_6": return _pairs_stratified([0, 2, 5, 7, 9, 11]) # 72 heads → 2556 pairs # Paper's i–k–j strategy (Kostenok et al. §III.A): for fixed pivot layer k, # pair (A_{i,k}, A_{k,j}) — i.e. heads at layer-i ↔ heads at layer-j with # head index = k or j respectively. We interpret this as "fix pivot # layer k, pair layer-i head k vs layer-j head h_pivot for every (i, j) in # the layer grid". The paper's tensor shape (12,12,144) suggests # 12 × 12 = 144 unique (i, j) ordered pairs per pivot k. if strategy == "paper_ikj_k11": return _pairs_paper_ikj(k_layers=[11]) # 144 ordered pairs → 78 unordered if strategy == "paper_ikj_k6": return _pairs_paper_ikj(k_layers=[6]) if strategy == "paper_ikj_multi": return _pairs_paper_ikj(k_layers=[3, 6, 9, 11]) # 4 pivots → ~300 unique pairs raise ValueError(f"unknown pairs_strategy: {strategy}") def _pairs_paper_ikj(k_layers: List[int]) -> List[Tuple[int, int, int, int]]: """Paper's i-k-j cross-barcode pairing: for each pivot layer k and each layer pair (i, j), generate (layer_i head_k, layer_j head_k). All 12 × 12 ordered (i, j) for a fixed k → 144 directed pairs. We keep only unordered (i < j) for symmetry → 78 per pivot. Multi-pivot stacks. """ L = 12 seen = set() out = [] for k in k_layers: for i in range(L): for j in range(L): if i == j: continue # treat k as the shared head index for both matrices a, b = (i, k), (j, k) if (a, b) in seen or (b, a) in seen: continue seen.add((a, b)) out.append((i, k, j, k)) return out # --------------------------------------------------------------------------- # Driver # --------------------------------------------------------------------------- def compute_cross_barcode_features( attn_dir: Path, indices: List[int], *, device: torch.device, pairs_strategy: str = "last_layer", quantile: float = 0.9, ) -> Tuple[np.ndarray, List[str]]: pairs = _resolve_pairs(pairs_strategy) feature_names = [f"cb_L{li}H{hi}_L{lj}H{hj}" for li, hi, lj, hj in pairs] P = len(pairs) pairs_t = torch.tensor(pairs, device=device, dtype=torch.long) li, hi, lj, hj = pairs_t[:, 0], pairs_t[:, 1], pairs_t[:, 2], pairs_t[:, 3] out = np.zeros((len(indices), P), dtype=np.float32) for n, idx in enumerate(tqdm(indices, desc="cross-barcode")): path = attn_dir / f"{idx:06d}.npz" with np.load(path) as data: attn = data["attn"].astype(np.float32) # (L, H, T, T) attn_t = torch.from_numpy(attn).to(device) A1 = attn_t[li, hi] # (P, T, T) A2 = attn_t[lj, hj] # (P, T, T) out[n] = rtd_simplified_batched(A1, A2, q=quantile).detach().cpu().numpy() return out, feature_names