""" ScGPT feature caches — Load pre-extracted scGPT features from HDF5. ScGPTFeatureCache: per-cell encoder features (for feature_mode="encoder"). ScGPTAttnDeltaCache: per-cell attn@gene_emb features (for feature_mode="attention_delta"). Stores raw per-cell features; computes delta (tgt - src) at lookup time. """ import h5py import numpy as np import torch class ScGPTFeatureCache: """ Loads pre-extracted per-gene scGPT features from HDF5 and provides batch lookup by cell name and gene indices. HDF5 layout: /features (N, G_full, scgpt_dim) float16 /norm_mean (scgpt_dim,) float32 /norm_var (scgpt_dim,) float32 /cell_names (N,) string """ def __init__(self, h5_path: str, target_std: float = 1.0): self.h5_path = h5_path self.target_std = target_std self.h5 = h5py.File(h5_path, "r") self.features = self.h5["features"] # lazy dataset, shape (N, G, D) self.norm_mean = torch.from_numpy(self.h5["norm_mean"][:]).float() # (D,) self.norm_var = torch.from_numpy(self.h5["norm_var"][:]).float() # (D,) # Build cell_name -> row index mapping cell_names = self.h5["cell_names"].asstr()[:] self.name_to_idx = {name: i for i, name in enumerate(cell_names)} def lookup(self, cell_names, gene_indices, device=None) -> torch.Tensor: """ Retrieve pre-extracted features for a batch. Args: cell_names: list of str, cell identifiers from batch gene_indices: (G_sub,) tensor, gene subset indices device: target torch device Returns: (B, G_sub, D) tensor, normalized features """ # Map cell names to HDF5 row indices row_indices = np.array([self.name_to_idx[n] for n in cell_names]) # h5py fancy indexing requires sorted, unique indices unique_indices, inverse = np.unique(row_indices, return_inverse=True) raw = self.features[unique_indices.tolist()] # (U, G_full, D) as numpy # Map back to original batch order (handles duplicates) raw = raw[inverse] # Select gene subset gene_idx_np = gene_indices.cpu().numpy() raw = raw[:, gene_idx_np, :] # (B, G_sub, D) z = torch.from_numpy(raw.astype(np.float32)) # Normalize: (x - mean) / sqrt(var) * target_std eps = 1e-6 z = (z - self.norm_mean) / (self.norm_var.sqrt() + eps) z = z * self.target_std if device is not None: z = z.to(device) return z def close(self): self.h5.close() def __del__(self): try: self.h5.close() except Exception: pass class ScGPTAttnDeltaCache: """ Attention-delta cache: stores per-cell attn@gene_emb features. At lookup time, computes delta = tgt_raw - src_raw, selects gene subset, normalizes. HDF5 layout (same as ScGPTFeatureCache): /features (N, G_full, scgpt_dim) float16 — raw features per cell /norm_mean (scgpt_dim,) float32 — mean of delta features /norm_var (scgpt_dim,) float32 — var of delta features /cell_names (N,) string """ def __init__(self, h5_path: str, target_std: float = 1.0): self.h5_path = h5_path self.target_std = target_std self.h5 = h5py.File(h5_path, "r") self.features = self.h5["features"] # lazy dataset, shape (N, G_full, D) self.norm_mean = torch.from_numpy(self.h5["norm_mean"][:]).float() # (D,) self.norm_var = torch.from_numpy(self.h5["norm_var"][:]).float() # (D,) # Build cell_name -> row index mapping cell_names = self.h5["cell_names"].asstr()[:] self.name_to_idx = {name: i for i, name in enumerate(cell_names)} def _lookup_raw(self, cell_names) -> np.ndarray: """Retrieve raw features for a batch of cells. Returns (B, G_full, D) numpy fp16.""" row_indices = np.array([self.name_to_idx[n] for n in cell_names]) # h5py fancy indexing requires sorted, unique indices unique_indices, inverse = np.unique(row_indices, return_inverse=True) raw = self.features[unique_indices.tolist()] # (U, G_full, D) raw = raw[inverse] # (B, G_full, D) return raw def lookup_delta(self, src_cell_names, tgt_cell_names, gene_indices, device=None): """ Compute normalized attention delta for (src, tgt) cell 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 delta features """ src_raw = self._lookup_raw(src_cell_names) # (B, G_full, D) fp16 tgt_raw = self._lookup_raw(tgt_cell_names) # (B, G_full, D) fp16 # Delta in float32 delta = tgt_raw.astype(np.float32) - src_raw.astype(np.float32) # Select gene subset gene_idx_np = gene_indices.cpu().numpy() delta = delta[:, gene_idx_np, :] # (B, G_sub, D) z = torch.from_numpy(delta) # Normalize: (x - mean) / sqrt(var) * target_std eps = 1e-6 z = (z - self.norm_mean) / (self.norm_var.sqrt() + eps) z = z * self.target_std if device is not None: z = z.to(device) return z def close(self): self.h5.close() def __del__(self): try: self.h5.close() except Exception: pass