File size: 8,308 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
205
206
207
"""
RegFMModel: scDFM backbone + RegulatoryHead + VelocityGate.

Parameter names for backbone components match ori_scDFM exactly,
enabling direct weight loading from scDFM baseline checkpoints.
"""

import torch
import torch.nn as nn

from src._scdfm_imports import (
    GeneEncoder,
    ContinuousValueEncoder,
    GeneadaLN,
    BatchLabelEncoder,
    TimestepEmbedder,
    ExprDecoder,
    DiffPerceiverBlock,
    DifferentialTransformerBlock,
    PerceiverBlock,
)
from src.model.layers import RegulatoryHead, VelocityGate


class RegFMModel(nn.Module):
    """
    Regulatory Flow Matching model.

    Forward returns:
        v:  (B, G)   — final velocity = α·v_reg + (1-α)·v_int
        R:  (B, G, G) — predicted interaction matrix (for L_reg supervision)
    """

    def __init__(
        self,
        ntoken: int = 512,
        d_model: int = 128,
        nhead: int = 8,
        d_hid: int = 512,
        nlayers: int = 4,
        dropout: float = 0.1,
        fusion_method: str = "differential_perceiver",
        perturbation_function: str = "crisper",
        use_perturbation_interaction: bool = True,
        mask_path: str = None,
        # RegFM-specific
        d_r: int = 32,
        gate_init_bias: float = -3.0,
    ):
        super().__init__()
        self.perturbation_function = perturbation_function
        self._gate_init_bias = gate_init_bias

        # === Backbone (parameter names match ori_scDFM for warm start) ===
        self.encoder = GeneEncoder(
            ntoken, d_model,
            use_perturbation_interaction=use_perturbation_interaction,
            mask_path=mask_path,
        )
        self.value_encoder_1 = ContinuousValueEncoder(d_model, dropout)
        self.value_encoder_2 = ContinuousValueEncoder(d_model, dropout)
        self.fusion_layer = nn.Sequential(
            nn.Linear(2 * d_model, d_model),
            nn.GELU(),
            nn.Linear(d_model, d_model),
            nn.LayerNorm(d_model),
        )
        self.t_embedder = TimestepEmbedder(d_model)
        self.perturbation_embedder = BatchLabelEncoder(ntoken, d_model)

        # Transformer blocks
        if fusion_method == "differential_perceiver":
            self.blocks = nn.ModuleList(
                [DiffPerceiverBlock(d_model, nhead, i, mlp_ratio=4.0) for i in range(nlayers)]
            )
        elif fusion_method == "differential_transformer":
            self.blocks = nn.ModuleList(
                [DifferentialTransformerBlock(d_model, nhead, i, mlp_ratio=4.0) for i in range(nlayers)]
            )
        elif fusion_method == "perceiver":
            self.blocks = nn.ModuleList(
                [PerceiverBlock(d_model, d_model, heads=nhead, mlp_ratio=4.0, dropout=0.1) for _ in range(nlayers)]
            )
        else:
            raise ValueError(f"Unknown fusion_method: {fusion_method}")

        self.gene_adaLN = nn.ModuleList(
            [GeneadaLN(d_model, dropout) for _ in range(nlayers)]
        )
        self.adapter_layer = nn.ModuleList([
            nn.Sequential(
                nn.Linear(2 * d_model, d_model),
                nn.LeakyReLU(),
                nn.Dropout(dropout),
                nn.Linear(d_model, d_model),
                nn.LeakyReLU(),
            )
            for _ in range(nlayers)
        ])

        # predict_p auxiliary head (kept for compatibility)
        self.p_mask_embed = nn.Parameter(torch.randn(d_model))
        self.p_head = nn.Sequential(nn.LayerNorm(d_model), nn.Linear(d_model, d_model))

        # === v_int head (ExprDecoder, same as scDFM's self.final_layer) ===
        self.final_layer = ExprDecoder(d_model, explicit_zero_prob=False, use_batch_labels=True)

        # === RegFM additions ===
        self.reg_head = RegulatoryHead(d_model, d_r)
        self.velocity_gate = VelocityGate(d_model, gate_init_bias)

        self.initialize_weights()

    def initialize_weights(self):
        def _basic_init(module):
            if isinstance(module, nn.Linear):
                torch.nn.init.xavier_uniform_(module.weight)
                if module.bias is not None:
                    nn.init.constant_(module.bias, 0)
        self.apply(_basic_init)
        # Re-apply gate bias after global init
        nn.init.zeros_(self.velocity_gate.mlp[-1].weight)
        nn.init.constant_(self.velocity_gate.mlp[-1].bias, self._gate_init_bias)

    def get_perturbation_emb(self, perturbation_id=None, perturbation_emb=None,
                             cell_1=None, use_mask: bool = False):
        """Identical to scDFM model.get_perturbation_emb for compatibility."""
        if use_mask:
            B = cell_1.size(0)
            return self.p_mask_embed[None, :].expand(B, -1).to(cell_1.device, dtype=cell_1.dtype)

        assert perturbation_emb is None or perturbation_id is None
        if perturbation_id is not None:
            if self.perturbation_function == "crisper":
                perturbation_emb = self.encoder(perturbation_id)
            else:
                perturbation_emb = self.perturbation_embedder(perturbation_id)
            perturbation_emb = perturbation_emb.mean(1)
        elif perturbation_emb is not None:
            perturbation_emb = perturbation_emb.to(cell_1.device, dtype=cell_1.dtype)
            if perturbation_emb.dim() == 1:
                perturbation_emb = perturbation_emb.unsqueeze(0)
            if perturbation_emb.size(0) == 1:
                perturbation_emb = perturbation_emb.expand(cell_1.shape[0], -1).contiguous()
            perturbation_emb = self.perturbation_embedder.enc_norm(perturbation_emb)
        return perturbation_emb

    def forward(self, gene_id, cell_1, t, cell_2,
                perturbation_id=None, gene_id_all=None,
                perturbation_emb=None, mode="predict_y"):
        """
        Args:
            gene_id:          (B, G) vocab-encoded gene IDs
            cell_1:           (B, G) noised target expression x_t
            t:                (B,) or scalar — flow timestep
            cell_2:           (B, G) source/control expression
            perturbation_id:  (B, 2) perturbation condition IDs
            gene_id_all:      unused (kept for API compatibility)
            perturbation_emb: optional precomputed perturbation embedding
            mode:             "predict_y" (default) or "predict_p"
        Returns:
            if mode == "predict_y": (v, R)
                v: (B, G) — gated velocity: α·v_reg + (1-α)·v_int
                R: (B, G, G) — predicted interaction matrix
            if mode == "predict_p": (B, d_model)
        """
        if t.dim() == 0:
            t = t.repeat(cell_1.size(0))

        # --- Backbone (identical to scDFM) ---
        gene_emb = self.encoder(gene_id)                        # (B, G, d_model)
        value_emb_1 = self.value_encoder_1(cell_1) + gene_emb   # x_t encoding
        value_emb_2 = self.value_encoder_2(cell_2) + gene_emb   # source encoding

        value_emb = torch.cat([value_emb_1, value_emb_2], dim=-1)
        value_emb = self.fusion_layer(value_emb)                # (B, G, d_model)

        t_emb = self.t_embedder(t)                              # (B, d_model)
        pert_emb = self.get_perturbation_emb(perturbation_id, perturbation_emb, cell_1)

        x = value_emb
        for i, block in enumerate(self.blocks):
            x = self.gene_adaLN[i](gene_emb, x)
            pert_exp = pert_emb[:, None, :].expand(-1, x.size(1), -1)
            x = torch.cat([x, pert_exp], dim=-1)
            x = self.adapter_layer[i](x)
            x = block(x, value_emb_2, t_emb)

        h = x  # backbone output: (B, G, d_model)

        # --- predict_p mode (auxiliary task, unchanged) ---
        if mode == "predict_p":
            return self.p_head(h.mean(dim=1))

        # --- v_int: intrinsic velocity (same as scDFM) ---
        x_dec = torch.cat([h, pert_emb[:, None, :].expand(-1, h.size(1), -1)], dim=-1)
        v_int = self.final_layer(x_dec)["pred"]      # (B, G)

        # --- v_reg, R: regulatory velocity (RegFM) ---
        v_reg, R = self.reg_head(h)                   # (B, G), (B, G, G)

        # --- Gated mixing ---
        alpha = self.velocity_gate(h, pert_emb, t_emb)  # (B, G)
        v = alpha * v_reg + (1.0 - alpha) * v_int        # (B, G)

        return v, R