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
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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
"""
SparseTopkEmbCache β€” Sparse top-K attention delta @ gene_emb features.

Uses precomputed per-cell sparse attention (K=300) to compute delta top-K
weighted gene embeddings at training time. Filters 99.3% noise compared to
dense attention delta.

HDF5 layout (from precompute_sparse_attn.py):
    /attn_values        (N, G_full, K) float16  β€” top-K attention values per row
    /attn_indices       (N, G_full, K) int16    β€” column indices in G_full space
    /cell_names         (N,) string
    /valid_gene_mask    (G_full,) bool
"""

import h5py
import numpy as np
import torch


class SparseTopkEmbCache:
    """
    Sparse top-K attention delta @ gene_emb cache.

    At lookup time:
    1. Read sparse attention for src/tgt cells from HDF5
    2. Scatter to dense, compute delta = tgt - src
    3. Take top-K (default 30) by |delta|
    4. Weighted sum with gene embeddings β†’ (B, G_sub, 512)
    5. Normalize with pre-computed statistics
    """

    def __init__(self, h5_path, gene_emb, top_k=30, target_std=1.0,
                 norm_n_pairs=2000, seed=42):
        """
        Args:
            h5_path: path to sparse attention HDF5 cache
            gene_emb: (G_full, D) CPU tensor of gene embeddings
            top_k: number of top delta entries to keep per gene
            target_std: target standard deviation for normalization
            norm_n_pairs: number of random cell pairs for norm statistics
            seed: random seed for norm sampling
        """
        self.h5_path = h5_path
        self.top_k = top_k
        self.target_std = target_std

        self.h5 = h5py.File(h5_path, "r")
        self.attn_values = self.h5["attn_values"]    # (N, G_full, K)
        self.attn_indices = self.h5["attn_indices"]   # (N, G_full, K)
        self.G_full = self.attn_values.shape[1]
        self.K_sparse = self.attn_values.shape[2]

        cell_names = self.h5["cell_names"].asstr()[:]
        self.name_to_idx = {name: i for i, name in enumerate(cell_names)}

        if "valid_gene_mask" in self.h5:
            self.valid_gene_mask = torch.from_numpy(
                self.h5["valid_gene_mask"][:].astype(bool))
        else:
            self.valid_gene_mask = torch.ones(self.G_full, dtype=torch.bool)

        self.gene_emb = gene_emb  # (G_full, D) CPU tensor
        assert gene_emb.shape[0] == self.G_full, (
            f"gene_emb shape {gene_emb.shape} != G_full {self.G_full}")

        print(f"  SparseTopkEmbCache: {len(self.name_to_idx)} cells, "
              f"G_full={self.G_full}, K_sparse={self.K_sparse}, top_k={top_k}")
        print(f"  gene_emb shape: {gene_emb.shape}, "
              f"valid genes: {self.valid_gene_mask.sum().item()}")

        # Compute normalization statistics
        self._compute_norm_stats(norm_n_pairs, seed)

    def _compute_norm_stats(self, n_pairs, seed):
        """Sample random cell pairs and compute norm statistics for the 512-d output."""
        rng = np.random.RandomState(seed)
        cell_names_list = list(self.name_to_idx.keys())
        n_cells = len(cell_names_list)

        src_idx = rng.randint(0, n_cells, size=n_pairs)
        tgt_idx = rng.randint(0, n_cells, size=n_pairs)

        # Sample gene subset for faster norm estimation
        valid_positions = torch.where(self.valid_gene_mask)[0]
        n_sample_genes = min(500, len(valid_positions))
        sample_perm = rng.choice(len(valid_positions), n_sample_genes, replace=False)
        sample_gene_idx = valid_positions[sample_perm]
        sample_gene_idx = torch.sort(sample_gene_idx)[0]

        D = self.gene_emb.shape[1]
        sum_x = torch.zeros(D, dtype=torch.float64)
        sum_x2 = torch.zeros(D, dtype=torch.float64)
        total_n = 0

        batch_size = 64
        print(f"  Computing norm stats from {n_pairs} cell pairs, "
              f"{n_sample_genes} sampled genes...")
        for i in range(0, n_pairs, batch_size):
            batch_end = min(i + batch_size, n_pairs)
            batch_src = [cell_names_list[j] for j in src_idx[i:batch_end]]
            batch_tgt = [cell_names_list[j] for j in tgt_idx[i:batch_end]]

            feats = self._compute_features(
                batch_src, batch_tgt, sample_gene_idx, torch.device("cpu"))
            flat = feats.reshape(-1, D).double()
            sum_x += flat.sum(dim=0)
            sum_x2 += (flat ** 2).sum(dim=0)
            total_n += flat.shape[0]

        self.norm_mean = (sum_x / total_n).float()
        self.norm_var = (sum_x2 / total_n - (sum_x / total_n) ** 2).float()
        # Clamp variance to avoid division by zero
        self.norm_var = self.norm_var.clamp(min=1e-8)

        print(f"  Norm stats computed: mean [{self.norm_mean.min():.4f}, "
              f"{self.norm_mean.max():.4f}], "
              f"std [{self.norm_var.sqrt().min():.4f}, "
              f"{self.norm_var.sqrt().max():.4f}]")

    def _compute_features(self, src_cell_names, tgt_cell_names, gene_indices, device):
        """
        Compute raw (unnormalized) sparse topk @ gene_emb features.

        Args:
            src_cell_names: list of str, control cell names
            tgt_cell_names: list of str, perturbation cell names
            gene_indices: (G_sub,) tensor or None (all genes)
            device: torch device for computation

        Returns:
            (B, G_sub, D) tensor of raw features
        """
        B = len(src_cell_names)
        D = self.gene_emb.shape[1]

        if gene_indices is not None:
            gene_idx_np = gene_indices.cpu().numpy()
            G_sub = len(gene_idx_np)
        else:
            gene_idx_np = None
            G_sub = self.G_full

        # Step 1: Collect unique cells, read HDF5 once
        seen = {}
        unique_names = []
        for n in src_cell_names + tgt_cell_names:
            if n not in seen:
                seen[n] = len(unique_names)
                unique_names.append(n)

        unique_h5_idx = [self.name_to_idx[n] for n in unique_names]
        sorted_order = np.argsort(unique_h5_idx)
        sorted_h5_idx = [unique_h5_idx[i] for i in sorted_order]

        # Read from HDF5 (sorted for sequential access)
        raw_vals = self.attn_values[sorted_h5_idx]   # (U, G_full, K) float16
        raw_idxs = self.attn_indices[sorted_h5_idx]  # (U, G_full, K) int16

        # Unsort to match unique_names order
        unsort = np.argsort(sorted_order)
        raw_vals = raw_vals[unsort]
        raw_idxs = raw_idxs[unsort]

        # Select gene subset in numpy (before GPU transfer)
        if gene_idx_np is not None:
            raw_vals = raw_vals[:, gene_idx_np, :]  # (U, G_sub, K)
            raw_idxs = raw_idxs[:, gene_idx_np, :]

        # Step 2: Map to src/tgt batch order
        src_map = [seen[n] for n in src_cell_names]
        tgt_map = [seen[n] for n in tgt_cell_names]

        # Step 3: Convert to torch and move to device
        src_vals = torch.from_numpy(raw_vals[src_map].astype(np.float32)).to(device)
        src_idxs = torch.from_numpy(raw_idxs[src_map].astype(np.int64)).to(device)
        tgt_vals = torch.from_numpy(raw_vals[tgt_map].astype(np.float32)).to(device)
        tgt_idxs = torch.from_numpy(raw_idxs[tgt_map].astype(np.int64)).to(device)
        gene_emb_d = self.gene_emb.to(device)

        # Step 4: Process in chunks (100 genes per chunk to limit memory)
        chunk_size = 100
        output = torch.zeros(B, G_sub, D, device=device)

        for c_start in range(0, G_sub, chunk_size):
            c_end = min(c_start + chunk_size, G_sub)
            c_len = c_end - c_start

            sv = src_vals[:, c_start:c_end, :]  # (B, c_len, K)
            si = src_idxs[:, c_start:c_end, :]
            tv = tgt_vals[:, c_start:c_end, :]
            ti = tgt_idxs[:, c_start:c_end, :]

            # Scatter sparse entries to dense attention rows
            src_dense = torch.zeros(B, c_len, self.G_full, device=device)
            tgt_dense = torch.zeros(B, c_len, self.G_full, device=device)
            src_dense.scatter_(-1, si, sv)
            tgt_dense.scatter_(-1, ti, tv)

            # Delta attention
            delta = tgt_dense - src_dense  # (B, c_len, G_full)

            # Top-k by absolute delta value
            _, topk_idx = delta.abs().topk(self.top_k, dim=-1)  # (B, c_len, top_k)
            topk_delta = delta.gather(-1, topk_idx)  # (B, c_len, top_k)

            # Gather gene embeddings at top-k positions
            flat_idx = topk_idx.reshape(-1)  # (B * c_len * top_k,)
            topk_emb = gene_emb_d[flat_idx].reshape(
                B, c_len, self.top_k, D)  # (B, c_len, top_k, D)

            # Weighted sum: delta_values * gene_emb β†’ (B, c_len, D)
            chunk_feat = (topk_delta.unsqueeze(-1) * topk_emb).sum(dim=2)
            output[:, c_start:c_end, :] = chunk_feat

        return output

    def lookup_delta(self, src_cell_names, tgt_cell_names, gene_indices, device=None):
        """
        Compute normalized sparse topk @ gene_emb features for (src, tgt) pairs.

        Args:
            src_cell_names: list of str, control cell identifiers
            tgt_cell_names: list of str, perturbation cell identifiers
            gene_indices: (G_sub,) tensor, gene subset indices
            device: target torch device

        Returns:
            (B, G_sub, D) tensor, normalized features
        """
        if device is None:
            device = torch.device("cpu")

        feats = self._compute_features(
            src_cell_names, tgt_cell_names, gene_indices, device)

        # Normalize: (x - mean) / sqrt(var) * target_std
        eps = 1e-6
        norm_mean = self.norm_mean.to(device)
        norm_var = self.norm_var.to(device)
        feats = (feats - norm_mean) / (norm_var.sqrt() + eps)
        feats = feats * self.target_std

        return feats

    def close(self):
        self.h5.close()

    def __del__(self):
        try:
            self.h5.close()
        except Exception:
            pass


def _read_sparse_batch(h5_values, h5_indices, name_to_idx,
                       src_cell_names, tgt_cell_names, gene_idx_np=None):
    """
    Shared HDF5 reading logic for sparse caches.

    Returns:
        src_vals, src_idxs, tgt_vals, tgt_idxs: numpy arrays (B, G_sub, K)
    """
    seen = {}
    unique_names = []
    for n in src_cell_names + tgt_cell_names:
        if n not in seen:
            seen[n] = len(unique_names)
            unique_names.append(n)

    unique_h5_idx = [name_to_idx[n] for n in unique_names]
    sorted_order = np.argsort(unique_h5_idx)
    sorted_h5_idx = [unique_h5_idx[i] for i in sorted_order]

    raw_vals = h5_values[sorted_h5_idx]
    raw_idxs = h5_indices[sorted_h5_idx]

    unsort = np.argsort(sorted_order)
    raw_vals = raw_vals[unsort]
    raw_idxs = raw_idxs[unsort]

    if gene_idx_np is not None:
        raw_vals = raw_vals[:, gene_idx_np, :]
        raw_idxs = raw_idxs[:, gene_idx_np, :]

    src_map = [seen[n] for n in src_cell_names]
    tgt_map = [seen[n] for n in tgt_cell_names]
    return raw_vals[src_map], raw_idxs[src_map], raw_vals[tgt_map], raw_idxs[tgt_map]


class SparsePCADeltaCache:
    """
    Sparse PCA delta cache: topk filtering + PCA projection.

    Same topk30 filtering as SparseTopkEmbCache, but projects through
    precomputed PCA basis (d-dim) instead of gene_emb (512-dim):
        1. scatter sparse K=300 β†’ dense delta (G_full)
        2. topk(top_k) by |delta|
        3. delta_vals @ pca_basis[topk_idx] β†’ (d,)
    """

    def __init__(self, h5_path, top_k=30, target_std=1.0,
                 norm_n_pairs=2000, seed=42):
        self.h5_path = h5_path
        self.top_k = top_k
        self.target_std = target_std

        self.h5 = h5py.File(h5_path, "r")
        self.attn_values = self.h5["attn_values"]
        self.attn_indices = self.h5["attn_indices"]
        self.G_full = self.attn_values.shape[1]
        self.K_sparse = self.attn_values.shape[2]

        cell_names = self.h5["cell_names"].asstr()[:]
        self.name_to_idx = {name: i for i, name in enumerate(cell_names)}

        if "valid_gene_mask" in self.h5:
            self.valid_gene_mask = torch.from_numpy(
                self.h5["valid_gene_mask"][:].astype(bool))
        else:
            self.valid_gene_mask = torch.ones(self.G_full, dtype=torch.bool)

        # Load PCA basis
        self.pca_basis = torch.from_numpy(self.h5["pca_basis"][:]).float()  # (G_full, d)
        self.pca_dim = self.pca_basis.shape[1]

        print(f"  SparsePCADeltaCache: {len(self.name_to_idx)} cells, "
              f"G_full={self.G_full}, K_sparse={self.K_sparse}, "
              f"top_k={top_k}, PCA dim={self.pca_dim}")

        self._compute_norm_stats(norm_n_pairs, seed)

    def _compute_norm_stats(self, n_pairs, seed):
        """Sample random cell pairs and compute norm statistics for PCA-d output."""
        rng = np.random.RandomState(seed)
        cell_names_list = list(self.name_to_idx.keys())
        n_cells = len(cell_names_list)

        src_idx = rng.randint(0, n_cells, size=n_pairs)
        tgt_idx = rng.randint(0, n_cells, size=n_pairs)

        valid_positions = torch.where(self.valid_gene_mask)[0]
        n_sample_genes = min(500, len(valid_positions))
        sample_perm = rng.choice(len(valid_positions), n_sample_genes, replace=False)
        sample_gene_idx = valid_positions[sample_perm]
        sample_gene_idx = torch.sort(sample_gene_idx)[0]

        D = self.pca_dim
        sum_x = torch.zeros(D, dtype=torch.float64)
        sum_x2 = torch.zeros(D, dtype=torch.float64)
        total_n = 0

        batch_size = 64
        print(f"  Computing PCA norm stats from {n_pairs} cell pairs, "
              f"{n_sample_genes} sampled genes...")
        for i in range(0, n_pairs, batch_size):
            batch_end = min(i + batch_size, n_pairs)
            batch_src = [cell_names_list[j] for j in src_idx[i:batch_end]]
            batch_tgt = [cell_names_list[j] for j in tgt_idx[i:batch_end]]

            feats = self._compute_features(
                batch_src, batch_tgt, sample_gene_idx, torch.device("cpu"))
            flat = feats.reshape(-1, D).double()
            sum_x += flat.sum(dim=0)
            sum_x2 += (flat ** 2).sum(dim=0)
            total_n += flat.shape[0]

        self.norm_mean = (sum_x / total_n).float()
        self.norm_var = (sum_x2 / total_n - (sum_x / total_n) ** 2).float()
        self.norm_var = self.norm_var.clamp(min=1e-8)

        print(f"  Norm stats computed: mean [{self.norm_mean.min():.4f}, "
              f"{self.norm_mean.max():.4f}], "
              f"std [{self.norm_var.sqrt().min():.4f}, "
              f"{self.norm_var.sqrt().max():.4f}]")

    def _compute_features(self, src_cell_names, tgt_cell_names, gene_indices, device):
        """
        Compute topk-filtered PCA-projected delta features.

        Flow per chunk:
        1. scatter sparse K=300 β†’ dense (B, chunk, G_full)
        2. delta = tgt_dense - src_dense
        3. topk(top_k) by |delta|
        4. delta_vals @ pca_basis[topk_idx] β†’ (B, chunk, pca_dim)

        Returns: (B, G_sub, pca_dim) tensor
        """
        B = len(src_cell_names)
        D = self.pca_dim

        gene_idx_np = gene_indices.cpu().numpy() if gene_indices is not None else None
        G_sub = len(gene_idx_np) if gene_idx_np is not None else self.G_full

        sv_np, si_np, tv_np, ti_np = _read_sparse_batch(
            self.attn_values, self.attn_indices, self.name_to_idx,
            src_cell_names, tgt_cell_names, gene_idx_np)

        src_vals = torch.from_numpy(sv_np.astype(np.float32)).to(device)
        src_idxs = torch.from_numpy(si_np.astype(np.int64)).to(device)
        tgt_vals = torch.from_numpy(tv_np.astype(np.float32)).to(device)
        tgt_idxs = torch.from_numpy(ti_np.astype(np.int64)).to(device)
        pca_d = self.pca_basis.to(device)  # (G_full, d)

        chunk_size = 100
        output = torch.zeros(B, G_sub, D, device=device)

        for c_start in range(0, G_sub, chunk_size):
            c_end = min(c_start + chunk_size, G_sub)
            c_len = c_end - c_start

            sv = src_vals[:, c_start:c_end, :]  # (B, c_len, K)
            si = src_idxs[:, c_start:c_end, :]
            tv = tgt_vals[:, c_start:c_end, :]
            ti = tgt_idxs[:, c_start:c_end, :]

            # Scatter sparse β†’ dense
            src_dense = torch.zeros(B, c_len, self.G_full, device=device)
            tgt_dense = torch.zeros(B, c_len, self.G_full, device=device)
            src_dense.scatter_(-1, si, sv)
            tgt_dense.scatter_(-1, ti, tv)

            # Delta + topk
            delta = tgt_dense - src_dense  # (B, c_len, G_full)
            _, topk_idx = delta.abs().topk(self.top_k, dim=-1)  # (B, c_len, top_k)
            topk_delta = delta.gather(-1, topk_idx)  # (B, c_len, top_k)

            # Gather PCA basis at topk positions & weighted sum
            flat_idx = topk_idx.reshape(-1)
            topk_pca = pca_d[flat_idx].reshape(
                B, c_len, self.top_k, D)  # (B, c_len, top_k, d)
            chunk_feat = (topk_delta.unsqueeze(-1) * topk_pca).sum(dim=2)
            output[:, c_start:c_end, :] = chunk_feat

        return output

    def lookup_delta(self, src_cell_names, tgt_cell_names, gene_indices, device=None):
        """
        Compute normalized PCA-projected delta features for (src, tgt) pairs.

        Returns: (B, G_sub, pca_dim) tensor, normalized features
        """
        if device is None:
            device = torch.device("cpu")

        feats = self._compute_features(
            src_cell_names, tgt_cell_names, gene_indices, device)

        eps = 1e-6
        norm_mean = self.norm_mean.to(device)
        norm_var = self.norm_var.to(device)
        feats = (feats - norm_mean) / (norm_var.sqrt() + eps)
        feats = feats * self.target_std

        return feats

    def close(self):
        self.h5.close()

    def __del__(self):
        try:
            self.h5.close()
        except Exception:
            pass