File size: 22,257 Bytes
9f5e507
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
"""
Precompute per-cell sparse attention matrices (per-row top-K) to HDF5.

Instead of storing attn @ gene_emb (dense 512-dim), this stores the raw sparse
attention values with per-row top-K=300 sparsification. This preserves the
sparse GRN signal and enables consistent gene-pair attention across cells.

Output HDF5 layout:
    /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           β€” True = gene in scGPT vocab
    /pca_basis          (G_full, d) float32      β€” PCA projection basis from delta attn
    /pca_explained_var  (d,) float32             β€” explained variance per component
    /delta_mean         (G_full,) float32        β€” per-gene delta L2 norm mean
    /delta_std          (G_full,) float32         β€” per-gene delta L2 norm std
"""

import sys
import os
import argparse

# Set up paths
_SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
_PROJECT_ROOT = os.path.dirname(_SCRIPT_DIR)
sys.path.insert(0, _PROJECT_ROOT)

# Bootstrap scDFM
import _bootstrap_scdfm  # noqa: F401

import numpy as np
import torch
import h5py
from tqdm import tqdm
from scipy import sparse as sp
from sklearn.decomposition import PCA

from src.data.data import get_data_classes
from src.data.scgpt_extractor import FrozenScGPTExtractor


_REPO_ROOT = os.path.normpath(os.path.join(_PROJECT_ROOT, "..", "..", "transfer", "code"))


def extract_sparse_attn(
    extractor: FrozenScGPTExtractor,
    expression_batch: torch.Tensor,  # (B, G_full)
    top_k: int = 300,
    attn_layer: int = 11,
    use_rank_norm: bool = True,
) -> tuple:
    """
    Extract per-row top-K sparse attention for each cell.

    Returns:
        values: (B, G_full, K) float16 β€” top-K attention values (with sign)
        indices: (B, G_full, K) int16  β€” column indices in G_full space
    """
    B, G_full = expression_batch.shape
    device = expression_batch.device

    hvg_ids = extractor.hvg_to_scgpt_id  # (G_full,)
    valid_mask = hvg_ids >= 0
    valid_scgpt_ids = hvg_ids[valid_mask]  # (G_valid,)
    n_valid = valid_scgpt_ids.shape[0]
    valid_positions = torch.where(valid_mask)[0]  # (G_valid,) indices into G_full

    assert n_valid + 1 <= extractor.max_seq_len, (
        f"n_valid ({n_valid}) + 1 CLS > max_seq_len ({extractor.max_seq_len}). "
        f"Increase max_seq_len to at least {n_valid + 1}."
    )

    # Expression for valid genes
    expr_valid = expression_batch[:, valid_positions]  # (B, G_valid)

    # Build scGPT input: CLS + all valid gene tokens
    cls_ids = torch.full((B, 1), extractor.cls_token_id, dtype=torch.long, device=device)
    gene_ids_expanded = valid_scgpt_ids.unsqueeze(0).expand(B, -1)
    src = torch.cat([cls_ids, gene_ids_expanded], dim=1)  # (B, G_valid + 1)

    cls_val = torch.zeros(B, 1, device=device)
    values_in = torch.cat([cls_val, expr_valid], dim=1)  # (B, G_valid + 1)

    seq_len = n_valid + 1
    pad_mask = torch.zeros(B, seq_len, dtype=torch.bool, device=device)

    # Forward to target layer
    hidden = extractor._forward_to_layer(src, values_in, pad_mask, attn_layer)

    # Compute attention at target layer
    attn = extractor._compute_attention(hidden, attn_layer, use_rank_norm)  # (B, S, S)

    # Remove CLS row/column
    attn = attn[:, 1:, 1:]  # (B, G_valid, G_valid)

    # Per-row top-K in local (valid) space
    K = min(top_k, n_valid)
    _, topk_local_idx = attn.abs().topk(K, dim=-1)  # (B, G_valid, K)
    topk_vals = attn.gather(-1, topk_local_idx)      # (B, G_valid, K) β€” preserve sign

    # Map local indices β†’ G_full space
    topk_full_idx = valid_positions[topk_local_idx]   # (B, G_valid, K)

    # Scatter valid gene rows into (B, G_full, K) output
    # Missing gene rows remain all-zero
    out_values = torch.zeros(B, G_full, K, device=device, dtype=torch.float32)
    out_indices = torch.zeros(B, G_full, K, device=device, dtype=torch.long)

    # valid_positions: (G_valid,) β†’ expand for scatter
    vp = valid_positions.unsqueeze(0).unsqueeze(-1).expand(B, -1, K)  # (B, G_valid, K)
    out_values.scatter_(1, vp, topk_vals)
    out_indices.scatter_(1, vp, topk_full_idx)

    return out_values.half().cpu(), out_indices.short().cpu()


def compute_pca_basis(
    h5_values,      # HDF5 dataset (N, G_full, K) float16
    h5_indices,     # HDF5 dataset (N, G_full, K) int16
    cell_names,     # list of cell names
    adata,          # AnnData
    G_full: int,
    n_pairs: int = 1000,
    genes_per_pair: int = 50,
    max_components: int = 64,
    variance_threshold: float = 0.95,
    seed: int = 42,
):
    """
    Compute PCA basis from sampled sparse delta attention rows.

    Returns:
        pca_basis: (G_full, d) float32
        explained_var: (d,) float32
    """
    rng = np.random.RandomState(seed)
    name_to_idx = {name: i for i, name in enumerate(cell_names)}

    # Identify control/perturbation cells
    obs = adata.obs
    if "condition" in obs.columns:
        is_control = obs["condition"] == "control"
    elif "perturbation_covariates" in obs.columns:
        is_control = obs["perturbation_covariates"].str.contains("control", case=False)
    elif "treatment" in obs.columns:
        is_control = obs["treatment"] == "control"
    else:
        raise ValueError("Cannot identify control cells from adata.obs columns")

    ctrl_names = [n for n in obs.index[is_control] if n in name_to_idx]
    pert_names = [n for n in obs.index[~is_control] if n in name_to_idx]
    print(f"PCA basis: {len(ctrl_names)} control, {len(pert_names)} perturbation cells")

    n_pairs = min(n_pairs, len(ctrl_names), len(pert_names))
    ctrl_sample = rng.choice(ctrl_names, n_pairs, replace=True)
    pert_sample = rng.choice(pert_names, n_pairs, replace=True)

    # Collect sparse delta rows
    collected_rows = []
    delta_top = 30  # top entries to keep per row for delta

    for i in tqdm(range(n_pairs), desc="Sampling PCA rows"):
        ci = name_to_idx[ctrl_sample[i]]
        pi = name_to_idx[pert_sample[i]]

        # Load sparse attn for both cells: (G_full, K)
        ctrl_vals = h5_values[ci].astype(np.float32)   # (G_full, K)
        ctrl_idx = h5_indices[ci].astype(np.int32)      # (G_full, K)
        pert_vals = h5_values[pi].astype(np.float32)
        pert_idx = h5_indices[pi].astype(np.int32)

        # Pick random gene rows
        nonzero_rows = np.where(np.abs(ctrl_vals).sum(axis=1) > 0)[0]
        if len(nonzero_rows) < genes_per_pair:
            chosen = nonzero_rows
        else:
            chosen = rng.choice(nonzero_rows, genes_per_pair, replace=False)

        for g in chosen:
            # Merge two sparse vectors, compute delta, keep top-30
            # Build dense delta for this row
            delta_row = np.zeros(G_full, dtype=np.float32)

            # Pert sparse entries
            for k_i in range(pert_idx.shape[1]):
                col = pert_idx[g, k_i]
                if col >= 0:
                    delta_row[col] += pert_vals[g, k_i]

            # Ctrl sparse entries (subtract)
            for k_i in range(ctrl_idx.shape[1]):
                col = ctrl_idx[g, k_i]
                if col >= 0:
                    delta_row[col] -= ctrl_vals[g, k_i]

            # Keep top-30 by absolute value, zero out rest
            if np.count_nonzero(delta_row) > delta_top:
                abs_vals = np.abs(delta_row)
                threshold = np.partition(abs_vals, -delta_top)[-delta_top]
                delta_row[abs_vals < threshold] = 0.0

            if np.any(delta_row != 0):
                collected_rows.append(sp.csr_matrix(delta_row.reshape(1, -1)))

    if not collected_rows:
        raise ValueError("No non-zero delta rows collected for PCA")

    print(f"Collected {len(collected_rows)} sparse delta rows for PCA")

    # Stack into sparse matrix and run PCA
    X_sparse = sp.vstack(collected_rows)  # (n_rows, G_full)
    X_dense = X_sparse.toarray()

    n_components = min(max_components, X_dense.shape[0], G_full)
    pca = PCA(n_components=n_components)
    pca.fit(X_dense)

    # Find number of components for variance threshold
    cumvar = np.cumsum(pca.explained_variance_ratio_)
    d = int(np.searchsorted(cumvar, variance_threshold) + 1)
    d = min(d, max_components)

    print(f"PCA: {d} components explain {cumvar[d-1]*100:.1f}% variance")
    print(f"  Top-5 explained variance ratios: {pca.explained_variance_ratio_[:5]}")

    basis = pca.components_[:d].T.astype(np.float32)      # (G_full, d)
    explained = pca.explained_variance_[:d].astype(np.float32)  # (d,)

    return basis, explained


def compute_delta_stats(
    h5_values,      # HDF5 dataset (N, G_full, K)
    h5_indices,     # HDF5 dataset (N, G_full, K)
    cell_names,
    adata,
    G_full: int,
    n_pairs: int = 2000,
    seed: int = 42,
):
    """
    Compute per-gene delta L2 norm statistics from sparse attention.

    Returns:
        delta_mean: (G_full,) float32 β€” mean of per-gene delta L2 norm
        delta_std:  (G_full,) float32 β€” std of per-gene delta L2 norm
    """
    rng = np.random.RandomState(seed)
    name_to_idx = {name: i for i, name in enumerate(cell_names)}

    obs = adata.obs
    if "condition" in obs.columns:
        is_control = obs["condition"] == "control"
    elif "perturbation_covariates" in obs.columns:
        is_control = obs["perturbation_covariates"].str.contains("control", case=False)
    elif "treatment" in obs.columns:
        is_control = obs["treatment"] == "control"
    else:
        raise ValueError("Cannot identify control cells from adata.obs columns")

    ctrl_names = [n for n in obs.index[is_control] if n in name_to_idx]
    pert_names = [n for n in obs.index[~is_control] if n in name_to_idx]
    print(f"Delta stats: {len(ctrl_names)} control, {len(pert_names)} perturbation cells")

    n_pairs = min(n_pairs, len(ctrl_names), len(pert_names))
    ctrl_sample = rng.choice(ctrl_names, n_pairs, replace=True)
    pert_sample = rng.choice(pert_names, n_pairs, replace=True)

    # Accumulate per-gene L2 norms
    running_sum = np.zeros(G_full, dtype=np.float64)
    running_sq = np.zeros(G_full, dtype=np.float64)

    for i in tqdm(range(n_pairs), desc="Computing delta stats"):
        ci = name_to_idx[ctrl_sample[i]]
        pi = name_to_idx[pert_sample[i]]

        ctrl_vals = h5_values[ci].astype(np.float32)   # (G_full, K)
        ctrl_idx = h5_indices[ci].astype(np.int32)
        pert_vals = h5_values[pi].astype(np.float32)
        pert_idx = h5_indices[pi].astype(np.int32)

        # Compute per-gene delta L2 norm
        for g in range(G_full):
            # Build dense delta for this gene's attention row
            delta = {}

            for k_i in range(pert_idx.shape[1]):
                col = int(pert_idx[g, k_i])
                if col >= 0:
                    delta[col] = delta.get(col, 0.0) + float(pert_vals[g, k_i])

            for k_i in range(ctrl_idx.shape[1]):
                col = int(ctrl_idx[g, k_i])
                if col >= 0:
                    delta[col] = delta.get(col, 0.0) - float(ctrl_vals[g, k_i])

            if delta:
                l2 = np.sqrt(sum(v ** 2 for v in delta.values()))
                running_sum[g] += l2
                running_sq[g] += l2 ** 2

    mean = (running_sum / n_pairs).astype(np.float32)
    std = np.sqrt(np.maximum(running_sq / n_pairs - (running_sum / n_pairs) ** 2, 1e-8)).astype(np.float32)

    print(f"Delta stats from {n_pairs} pairs:")
    print(f"  mean L2 range: [{mean.min():.6f}, {mean.max():.6f}]")
    print(f"  std L2 range:  [{std.min():.6f}, {std.max():.6f}]")

    return mean, std


def verify_coverage(
    h5_values,
    h5_indices,
    cell_names,
    adata,
    G_full: int,
    n_pairs: int = 100,
    delta_top: int = 30,
    seed: int = 123,
):
    """
    Verify that K=300 sparse attn covers the true delta top-30 entries.
    """
    rng = np.random.RandomState(seed)
    name_to_idx = {name: i for i, name in enumerate(cell_names)}

    obs = adata.obs
    if "condition" in obs.columns:
        is_control = obs["condition"] == "control"
    elif "perturbation_covariates" in obs.columns:
        is_control = obs["perturbation_covariates"].str.contains("control", case=False)
    elif "treatment" in obs.columns:
        is_control = obs["treatment"] == "control"
    else:
        raise ValueError("Cannot identify control cells from adata.obs columns")

    ctrl_names = [n for n in obs.index[is_control] if n in name_to_idx]
    pert_names = [n for n in obs.index[~is_control] if n in name_to_idx]

    n_pairs = min(n_pairs, len(ctrl_names), len(pert_names))
    ctrl_sample = rng.choice(ctrl_names, n_pairs, replace=False)
    pert_sample = rng.choice(pert_names, n_pairs, replace=False)

    coverages = []

    for i in tqdm(range(n_pairs), desc="Verifying coverage"):
        ci = name_to_idx[ctrl_sample[i]]
        pi = name_to_idx[pert_sample[i]]

        ctrl_vals = h5_values[ci].astype(np.float32)
        ctrl_idx = h5_indices[ci].astype(np.int32)
        pert_vals = h5_values[pi].astype(np.float32)
        pert_idx = h5_indices[pi].astype(np.int32)

        # Sample some gene rows to check
        nonzero_rows = np.where(np.abs(ctrl_vals).sum(axis=1) > 0)[0]
        if len(nonzero_rows) == 0:
            continue
        check_genes = rng.choice(nonzero_rows, min(20, len(nonzero_rows)), replace=False)

        for g in check_genes:
            # Columns covered by union of ctrl and pert sparse entries
            covered_cols = set()
            for k_i in range(ctrl_idx.shape[1]):
                col = int(ctrl_idx[g, k_i])
                if col >= 0:
                    covered_cols.add(col)
            for k_i in range(pert_idx.shape[1]):
                col = int(pert_idx[g, k_i])
                if col >= 0:
                    covered_cols.add(col)

            # Compute full dense delta for this row
            delta = np.zeros(G_full, dtype=np.float32)
            for k_i in range(pert_idx.shape[1]):
                col = int(pert_idx[g, k_i])
                if col >= 0:
                    delta[col] += pert_vals[g, k_i]
            for k_i in range(ctrl_idx.shape[1]):
                col = int(ctrl_idx[g, k_i])
                if col >= 0:
                    delta[col] -= ctrl_vals[g, k_i]

            # Find true top-30 delta entries
            abs_delta = np.abs(delta)
            if np.count_nonzero(abs_delta) < delta_top:
                continue
            top_cols = set(np.argpartition(abs_delta, -delta_top)[-delta_top:])

            # Coverage = fraction of top-30 delta cols that are in covered_cols
            hits = len(top_cols & covered_cols)
            coverages.append(hits / delta_top)

    if coverages:
        coverages = np.array(coverages)
        print(f"\n=== Coverage Verification ===")
        print(f"Pairs checked: {n_pairs}, gene rows checked: {len(coverages)}")
        print(f"Delta top-{delta_top} coverage by K=300 sparse attn:")
        print(f"  Mean:   {coverages.mean():.4f}")
        print(f"  Median: {np.median(coverages):.4f}")
        print(f"  Min:    {coverages.min():.4f}")
        print(f"  P5:     {np.percentile(coverages, 5):.4f}")
        print(f"  P25:    {np.percentile(coverages, 25):.4f}")
    else:
        print("WARNING: No valid gene rows found for coverage check")


def main():
    parser = argparse.ArgumentParser(description="Precompute sparse attention matrices")
    parser.add_argument("--data-name", type=str, default="norman")
    parser.add_argument("--n-top-genes", type=int, default=5000)
    parser.add_argument("--fold", type=int, default=1)
    parser.add_argument("--split-method", type=str, default="additive")
    parser.add_argument("--topk", type=int, default=30)
    parser.add_argument("--use-negative-edge", action="store_true", default=True)
    parser.add_argument("--scgpt-model-dir", type=str,
                        default="transfer/data/scGPT_pretrained")
    parser.add_argument("--max-seq-len", type=int, default=5000,
                        help="scGPT max_seq_len, must be >= n_valid_genes + 1")
    parser.add_argument("--attn-layer", type=int, default=11)
    parser.add_argument("--attn-use-rank-norm", action="store_true", default=True)
    parser.add_argument("--batch-size", type=int, default=2,
                        help="Batch size for extraction (rank norm is memory-intensive)")
    parser.add_argument("--top-k", type=int, default=300,
                        help="Per-row top-K for sparse attention")
    parser.add_argument("--n-pca-pairs", type=int, default=1000,
                        help="Number of (ctrl, pert) pairs for PCA basis")
    parser.add_argument("--max-pca-components", type=int, default=64)
    parser.add_argument("--output", type=str,
                        default="cache/norman_attn_L11_sparse.h5")
    parser.add_argument("--device", type=str, default="cuda")
    args = parser.parse_args()

    device = torch.device(args.device if torch.cuda.is_available() else "cpu")
    print(f"Device: {device}")

    # === Data loading (reuse from precompute_attn_features.py) ===
    Data, PerturbationDataset, TrainSampler, TestDataset = get_data_classes()

    scdfm_data_path = os.path.join(_REPO_ROOT, "scDFM", "data")
    data_manager = Data(scdfm_data_path)
    data_manager.load_data(args.data_name)

    # Convert var_names if needed
    if "gene_name" in data_manager.adata.var.columns and data_manager.adata.var_names[0].startswith("ENSG"):
        data_manager.adata.var_names = data_manager.adata.var["gene_name"].values
        data_manager.adata.var_names_make_unique()
        print(f"Converted var_names to gene symbols, sample: {list(data_manager.adata.var_names[:5])}")

    data_manager.process_data(
        n_top_genes=args.n_top_genes,
        split_method=args.split_method,
        fold=args.fold,
        use_negative_edge=args.use_negative_edge,
        k=args.topk,
    )

    adata = data_manager.adata
    N = adata.n_obs
    G_full = adata.n_vars
    print(f"Dataset: {N} cells Γ— {G_full} genes")

    # === Build extractor ===
    hvg_gene_names = list(adata.var_names)
    scgpt_model_dir = os.path.join(
        os.path.dirname(_REPO_ROOT),  # transfer/
        args.scgpt_model_dir.replace("transfer/", ""),
    )
    extractor = FrozenScGPTExtractor(
        model_dir=scgpt_model_dir,
        hvg_gene_names=hvg_gene_names,
        device=device,
        max_seq_len=args.max_seq_len,
        target_std=1.0,
        warmup_batches=0,
    )
    extractor = extractor.to(device)
    extractor.eval()

    n_valid = (extractor.hvg_to_scgpt_id >= 0).sum().item()
    valid_gene_mask = (extractor.hvg_to_scgpt_id >= 0).cpu().numpy()
    K = args.top_k
    print(f"Valid genes in scGPT vocab: {n_valid}/{G_full}")
    print(f"Sequence length: {n_valid + 1} (with CLS), max_seq_len: {args.max_seq_len}")
    print(f"Top-K: {K}")

    # === Create output HDF5 ===
    output_path = os.path.join(_PROJECT_ROOT, args.output)
    os.makedirs(os.path.dirname(output_path), exist_ok=True)

    cell_names = list(adata.obs_names)

    X = adata.X
    is_sparse = hasattr(X, "toarray")

    est_gb = N * G_full * K * 4 / 1e9  # float16 + int16 = 4 bytes per entry
    print(f"Output: {output_path}")
    print(f"Estimated size: {est_gb:.1f} GB (float16 values + int16 indices)")
    print(f"Batch size: {args.batch_size}, total batches: {(N + args.batch_size - 1) // args.batch_size}")

    with h5py.File(output_path, "w") as h5:
        # Pre-allocate datasets
        val_ds = h5.create_dataset(
            "attn_values", shape=(N, G_full, K), dtype="float16",
            chunks=(1, G_full, K),
        )
        idx_ds = h5.create_dataset(
            "attn_indices", shape=(N, G_full, K), dtype="int16",
            chunks=(1, G_full, K),
        )
        h5.create_dataset("cell_names", data=np.array(cell_names, dtype="S"))
        h5.create_dataset("valid_gene_mask", data=valid_gene_mask)

        # === Step 1: Batch extraction ===
        batch_size = args.batch_size
        for start in tqdm(range(0, N, batch_size), desc="Extracting sparse attn"):
            end = min(start + batch_size, N)

            if is_sparse:
                expr_np = X[start:end].toarray()
            else:
                expr_np = X[start:end]

            expr = torch.from_numpy(expr_np.astype(np.float32)).to(device)

            with torch.no_grad():
                vals, idxs = extract_sparse_attn(
                    extractor, expr,
                    top_k=K,
                    attn_layer=args.attn_layer,
                    use_rank_norm=args.attn_use_rank_norm,
                )  # (B, G_full, K) each

            val_ds[start:end] = vals.numpy()
            idx_ds[start:end] = idxs.numpy()

        # === Step 2: PCA basis ===
        print("\nComputing PCA basis...")
        pca_basis, pca_explained = compute_pca_basis(
            val_ds, idx_ds, cell_names, adata, G_full,
            n_pairs=args.n_pca_pairs,
            max_components=args.max_pca_components,
        )
        d = pca_basis.shape[1]
        h5.create_dataset("pca_basis", data=pca_basis)             # (G_full, d)
        h5.create_dataset("pca_explained_var", data=pca_explained)  # (d,)

        # === Step 3: Delta stats ===
        print("\nComputing delta statistics...")
        delta_mean, delta_std = compute_delta_stats(
            val_ds, idx_ds, cell_names, adata, G_full,
        )
        h5.create_dataset("delta_mean", data=delta_mean)
        h5.create_dataset("delta_std", data=delta_std)

    # === Step 4: Verify coverage ===
    print("\nVerifying coverage...")
    with h5py.File(output_path, "r") as h5:
        verify_coverage(
            h5["attn_values"], h5["attn_indices"],
            cell_names, adata, G_full,
        )

    print(f"\nDone! Output saved to {output_path}")
    print(f"  attn_values:  ({N}, {G_full}, {K}) float16")
    print(f"  attn_indices: ({N}, {G_full}, {K}) int16")
    print(f"  pca_basis:    ({G_full}, {d}) float32")
    print(f"  delta_mean/std: ({G_full},) float32")


if __name__ == "__main__":
    main()