| """ |
| ScGPTFeatureCache — Load pre-extracted scGPT features from HDF5. |
| |
| Replaces on-the-fly FrozenScGPTExtractor during training when a cache file exists. |
| """ |
|
|
| 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 |
|
|