File size: 11,346 Bytes
55d72e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
"""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