File size: 4,245 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
"""
Data loading for grn_dense4.

Uses SparseRawDeltaCache to get dense (B, G_sub, G_sub) delta attention,
then computes per-row statistics [mean, std, max, min] → (B, G_sub, 4)
in the DataLoader worker to minimize CPU→GPU transfer.
"""

import sys
import os

import torch
from torch.utils.data import Dataset

_SCDFM_ROOT = os.path.normpath(
    os.path.join(os.path.dirname(__file__), "..", "..", "..", "..", "transfer", "code", "scDFM")
)

_cached_classes = {}


def get_data_classes():
    """Lazily import scDFM data classes with proper module isolation."""
    if _cached_classes:
        return (
            _cached_classes["Data"],
            _cached_classes["PerturbationDataset"],
            _cached_classes["TrainSampler"],
            _cached_classes["TestDataset"],
        )

    saved = {}
    for key in list(sys.modules.keys()):
        if key == "src" or key.startswith("src."):
            saved[key] = sys.modules.pop(key)

    for d in ["src", "src/data_process", "src/utils", "src/tokenizer"]:
        init_path = os.path.join(_SCDFM_ROOT, d, "__init__.py")
        if not os.path.exists(init_path):
            os.makedirs(os.path.dirname(init_path), exist_ok=True)
            with open(init_path, "w") as f:
                f.write("# Auto-created by CCFM\n")

    sys.path.insert(0, _SCDFM_ROOT)
    try:
        from src.data_process.data import Data, PerturbationDataset, TrainSampler, TestDataset
        _cached_classes["Data"] = Data
        _cached_classes["PerturbationDataset"] = PerturbationDataset
        _cached_classes["TrainSampler"] = TrainSampler
        _cached_classes["TestDataset"] = TestDataset
    finally:
        for key in list(sys.modules.keys()):
            if (key == "src" or key.startswith("src.")) and not key.startswith("scdfm_"):
                del sys.modules[key]
        for key, mod in saved.items():
            sys.modules[key] = mod
        if _SCDFM_ROOT in sys.path:
            sys.path.remove(_SCDFM_ROOT)

    return Data, PerturbationDataset, TrainSampler, TestDataset


class GRNDatasetWrapper(Dataset):
    """
    Wraps scDFM PerturbationDataset to produce per-row statistics from dense delta.

    Worker computes: dense delta (B, G_sub, G_sub) → [mean, std, max, min] → (B, G_sub, 4)
    Only the 4-dim stats are sent to GPU, not the full G_sub×G_sub matrix.
    """

    def __init__(self, base_dataset, sparse_cache, gene_ids_cpu, infer_top_gene):
        self.base = base_dataset
        self.sparse_cache = sparse_cache
        self.gene_ids = gene_ids_cpu
        self.infer_top_gene = infer_top_gene

    def __len__(self):
        return len(self.base)

    def __getitem__(self, idx):
        batch = self.base[idx]

        # 1. Random gene subset
        G_full = batch["src_cell_data"].shape[-1]
        input_gene_ids = torch.randperm(G_full)[:self.infer_top_gene]

        # 2. Dense delta from sparse cache (in worker process)
        src_names = batch["src_cell_id"]
        tgt_names = batch["tgt_cell_id"]
        if src_names and isinstance(src_names[0], (tuple, list)):
            src_names = [n[0] for n in src_names]
            tgt_names = [n[0] for n in tgt_names]
        z_dense = self.sparse_cache.lookup_delta(
            src_names, tgt_names, input_gene_ids, device=torch.device("cpu")
        )  # (B, G_sub, G_sub)

        # 3. Per-row statistics: (B, G_sub, G_sub) → (B, G_sub, 4)
        z_stats = torch.stack([
            z_dense.mean(dim=-1),              # mean of each gene's attention changes
            z_dense.std(dim=-1),               # spread of attention changes
            z_dense.max(dim=-1).values,        # strongest positive change
            z_dense.min(dim=-1).values,        # strongest negative change
        ], dim=-1)  # (B, G_sub, 4)

        # 4. Subset expression data
        return {
            "src_cell_data": batch["src_cell_data"][:, input_gene_ids],
            "tgt_cell_data": batch["tgt_cell_data"][:, input_gene_ids],
            "condition_id": batch["condition_id"],
            "z_stats": z_stats,                                            # (B, G_sub, 4)
            "gene_ids_sub": self.gene_ids[input_gene_ids],
            "input_gene_ids": input_gene_ids,
        }