| """ |
| 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"] |
| self.norm_mean = torch.from_numpy(self.h5["norm_mean"][:]).float() |
| self.norm_var = torch.from_numpy(self.h5["norm_var"][:]).float() |
|
|
| |
| 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 |
| """ |
| |
| row_indices = np.array([self.name_to_idx[n] for n in cell_names]) |
|
|
| |
| unique_indices, inverse = np.unique(row_indices, return_inverse=True) |
| raw = self.features[unique_indices.tolist()] |
|
|
| |
| raw = raw[inverse] |
|
|
| |
| gene_idx_np = gene_indices.cpu().numpy() |
| raw = raw[:, gene_idx_np, :] |
|
|
| z = torch.from_numpy(raw.astype(np.float32)) |
|
|
| |
| 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"] |
| self.norm_mean = torch.from_numpy(self.h5["norm_mean"][:]).float() |
| self.norm_var = torch.from_numpy(self.h5["norm_var"][:]).float() |
|
|
| |
| 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]) |
|
|
| |
| unique_indices, inverse = np.unique(row_indices, return_inverse=True) |
| raw = self.features[unique_indices.tolist()] |
| raw = raw[inverse] |
| 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) |
| tgt_raw = self._lookup_raw(tgt_cell_names) |
|
|
| |
| delta = tgt_raw.astype(np.float32) - src_raw.astype(np.float32) |
|
|
| |
| gene_idx_np = gene_indices.cpu().numpy() |
| delta = delta[:, gene_idx_np, :] |
|
|
| z = torch.from_numpy(delta) |
|
|
| |
| 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 |
|
|