| """ |
| 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 |
|
|
| |
| _SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) |
| _PROJECT_ROOT = os.path.dirname(_SCRIPT_DIR) |
| sys.path.insert(0, _PROJECT_ROOT) |
|
|
| |
| import _bootstrap_scdfm |
|
|
| 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, |
| 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 |
| valid_mask = hvg_ids >= 0 |
| valid_scgpt_ids = hvg_ids[valid_mask] |
| n_valid = valid_scgpt_ids.shape[0] |
| valid_positions = torch.where(valid_mask)[0] |
|
|
| 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}." |
| ) |
|
|
| |
| expr_valid = expression_batch[:, valid_positions] |
|
|
| |
| 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) |
|
|
| cls_val = torch.zeros(B, 1, device=device) |
| values_in = torch.cat([cls_val, expr_valid], dim=1) |
|
|
| seq_len = n_valid + 1 |
| pad_mask = torch.zeros(B, seq_len, dtype=torch.bool, device=device) |
|
|
| |
| hidden = extractor._forward_to_layer(src, values_in, pad_mask, attn_layer) |
|
|
| |
| attn = extractor._compute_attention(hidden, attn_layer, use_rank_norm) |
|
|
| |
| attn = attn[:, 1:, 1:] |
|
|
| |
| K = min(top_k, n_valid) |
| _, topk_local_idx = attn.abs().topk(K, dim=-1) |
| topk_vals = attn.gather(-1, topk_local_idx) |
|
|
| |
| topk_full_idx = valid_positions[topk_local_idx] |
|
|
| |
| |
| 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) |
|
|
| |
| vp = valid_positions.unsqueeze(0).unsqueeze(-1).expand(B, -1, 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, |
| h5_indices, |
| cell_names, |
| adata, |
| 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)} |
|
|
| |
| 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) |
|
|
| |
| collected_rows = [] |
| delta_top = 30 |
|
|
| 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]] |
|
|
| |
| 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) |
|
|
| |
| 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: |
| |
| |
| delta_row = np.zeros(G_full, dtype=np.float32) |
|
|
| |
| 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] |
|
|
| |
| 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] |
|
|
| |
| 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") |
|
|
| |
| X_sparse = sp.vstack(collected_rows) |
| 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) |
|
|
| |
| 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) |
| explained = pca.explained_variance_[:d].astype(np.float32) |
|
|
| return basis, explained |
|
|
|
|
| def compute_delta_stats( |
| h5_values, |
| h5_indices, |
| 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) |
|
|
| |
| 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) |
| ctrl_idx = h5_indices[ci].astype(np.int32) |
| pert_vals = h5_values[pi].astype(np.float32) |
| pert_idx = h5_indices[pi].astype(np.int32) |
|
|
| |
| for g in range(G_full): |
| |
| 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) |
|
|
| |
| 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: |
| |
| 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) |
|
|
| |
| 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] |
|
|
| |
| 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:]) |
|
|
| |
| 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, 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) |
|
|
| |
| 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") |
|
|
| |
| hvg_gene_names = list(adata.var_names) |
| scgpt_model_dir = os.path.join( |
| os.path.dirname(_REPO_ROOT), |
| 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}") |
|
|
| |
| 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 |
| 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: |
| |
| 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) |
|
|
| |
| 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, |
| ) |
|
|
| val_ds[start:end] = vals.numpy() |
| idx_ds[start:end] = idxs.numpy() |
|
|
| |
| 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) |
| h5.create_dataset("pca_explained_var", data=pca_explained) |
|
|
| |
| 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) |
|
|
| |
| 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() |
|
|