File size: 7,619 Bytes
9f5e507
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
"""
SparseRawDeltaCache β€” Reconstructs raw Ξ”_attn (B, G_sub, G_sub) from sparse attention cache.

No scGPT forward required. No normalization needed (rank-normed values in [0,1], delta in [-1,1]).

Multi-process safe: each DataLoader worker lazily opens its own HDF5 handle (PID-based detection).

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 os
import h5py
import numpy as np
import torch


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 SparseRawDeltaCache:
    """
    Reconstructs raw Ξ”_attn (B, G_sub, G_sub) from sparse attention cache.

    Multi-process safe: HDF5 handles are lazily opened per-process (PID-tracked).
    Safe for use in DataLoader workers with persistent_workers=True.

    Lookup flow:
    1. Read src/tgt sparse attention: (G_full, K=300) values + indices
    2. Select gene subset rows
    3. Scatter to dense: (B, G_sub, G_full) β€” chunked to avoid OOM
    4. Select columns: (B, G_sub, G_sub)
    5. Delta = tgt_dense - src_dense -> (B, G_sub, G_sub)
    """

    def __init__(self, h5_path, delta_top_k=None):
        self.h5_path = h5_path
        self.delta_top_k = delta_top_k

        # Read metadata only, then close β€” safe for fork
        with h5py.File(h5_path, "r") as h5:
            self.G_full = h5["attn_values"].shape[1]
            self.K_sparse = h5["attn_values"].shape[2]
            cell_names = h5["cell_names"].asstr()[:]
            self.name_to_idx = {name: i for i, name in enumerate(cell_names)}
            if "valid_gene_mask" in h5:
                self.valid_gene_mask = h5["valid_gene_mask"][:].astype(bool)
            else:
                self.valid_gene_mask = np.ones(self.G_full, dtype=bool)

        # Per-process HDF5 handle (lazily opened)
        self._h5 = None
        self._attn_values = None
        self._attn_indices = None
        self._pid = None

        print(f"  SparseRawDeltaCache: {len(self.name_to_idx)} cells, "
              f"G_full={self.G_full}, K_sparse={self.K_sparse}")
        print(f"  valid genes: {self.valid_gene_mask.sum()}/{self.G_full}")

    def _ensure_h5_open(self):
        """Ensure current process has its own HDF5 file handle."""
        pid = os.getpid()
        if self._h5 is None or self._pid != pid:
            # PID changed (fork) or first access β€” close stale handle, open new one
            if self._h5 is not None:
                try:
                    self._h5.close()
                except Exception:
                    pass
            self._h5 = h5py.File(self.h5_path, "r")
            self._attn_values = self._h5["attn_values"]
            self._attn_indices = self._h5["attn_indices"]
            self._pid = pid

    def get_missing_gene_mask(self, gene_indices=None):
        """
        Return missing gene mask (True = missing/invalid).
        Pure numpy operation β€” no HDF5 I/O needed.

        Args:
            gene_indices: (G_sub,) tensor or None (all genes)

        Returns:
            (G_sub,) or (G_full,) bool tensor β€” True where gene is missing
        """
        mask = torch.from_numpy(~self.valid_gene_mask)  # True = missing
        if gene_indices is not None:
            return mask[gene_indices.cpu()]
        return mask

    def lookup_delta(self, src_cell_names, tgt_cell_names, gene_indices, device=None):
        """
        Reconstruct raw Ξ”_attn (B, G_sub, G_sub) from sparse cache.

        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, G_sub) tensor β€” raw delta attention, values in [-1, 1]
        """
        self._ensure_h5_open()

        if device is None:
            device = torch.device("cpu")

        B = len(src_cell_names)
        gene_idx_np = gene_indices.cpu().numpy()
        G_sub = len(gene_idx_np)

        # Read sparse data from HDF5 (uses per-process handle)
        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)  # (B, G_sub, K)
        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)

        # Process in chunks (100 rows per chunk) to limit memory
        chunk_size = 100
        output = torch.zeros(B, G_sub, G_sub, device=device)

        for c_start in range(0, G_sub, chunk_size):
            c_end = min(c_start + chunk_size, G_sub)

            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, :]
            c_len = c_end - c_start

            # Scatter sparse entries to dense attention rows: (B, c_len, G_full)
            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)

            # Select columns for gene subset + compute delta
            delta = tgt_dense[:, :, gene_idx_np] - src_dense[:, :, gene_idx_np]  # (B, c_len, G_sub)

            # Per-row top-K sparsification on delta
            if self.delta_top_k is not None and self.delta_top_k < delta.size(-1):
                _, topk_idx = delta.abs().topk(self.delta_top_k, dim=-1)
                sparse_delta = torch.zeros_like(delta)
                sparse_delta.scatter_(-1, topk_idx, delta.gather(-1, topk_idx))
                delta = sparse_delta

            output[:, c_start:c_end, :] = delta

        return output  # (B, G_sub, G_sub), values in [-1, 1]

    def close(self):
        if self._h5 is not None:
            try:
                self._h5.close()
            except Exception:
                pass
            self._h5 = None
            self._attn_values = None
            self._attn_indices = None

    def __del__(self):
        self.close()