lfj-code / GRN /grn_ccfm /src /data /sparse_topk_cache.py
ethan1115's picture
Upload folder using huggingface_hub
9f5e507 verified
"""
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