File size: 3,171 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
"""RegFM-specific model layers: RegulatoryHead and VelocityGate."""

import torch
import torch.nn as nn


class RegulatoryHead(nn.Module):
    """
    Predicts gene-gene regulatory interaction matrix R_θ and computes
    regulatory velocity v_reg via attention-like mechanism.

    R_θ = tanh(zero_diag(Q·K^T / √d_r))  ∈ [-1, 1]^{B×G×G}
    v_reg = Linear(R_θ · V)               ∈ R^{B×G}
    """

    def __init__(self, d_model: int, d_r: int = 32):
        super().__init__()
        self.d_r = d_r
        self.scale = d_r ** -0.5
        self.W_q = nn.Linear(d_model, d_r, bias=False)
        self.W_k = nn.Linear(d_model, d_r, bias=False)
        self.W_v = nn.Linear(d_model, d_r, bias=False)
        self.out_proj = nn.Linear(d_r, 1)

    def forward(self, h: torch.Tensor):
        """
        Args:
            h: (B, G, d_model) backbone hidden states
        Returns:
            v_reg: (B, G) regulatory velocity
            R:     (B, G, G) predicted interaction matrix, values in [-1, 1]
        """
        Q = self.W_q(h)                             # (B, G, d_r)
        K = self.W_k(h)                             # (B, G, d_r)
        V = self.W_v(h)                             # (B, G, d_r)

        R = torch.bmm(Q, K.transpose(1, 2))         # (B, G, G)
        R = R * self.scale

        # Zero diagonal: prevent self-loop leakage (v_reg must encode inter-gene interactions)
        R = R - torch.diag_embed(R.diagonal(dim1=1, dim2=2))

        # Tanh: bound to [-1, 1] matching delta_attn range, stabilize training
        R = torch.tanh(R)

        agg = torch.bmm(R, V)                       # (B, G, d_r)
        v_reg = self.out_proj(agg).squeeze(-1)       # (B, G)

        return v_reg, R


class VelocityGate(nn.Module):
    """
    Gated mixing of v_reg and v_int, conditioned on gene state, perturbation, and timestep.

    α = σ(MLP([h; pert_emb; t_emb]))  ∈ (0, 1)^{B×G}
    v = α ⊙ v_reg + (1-α) ⊙ v_int
    """

    def __init__(self, d_model: int, gate_init_bias: float = -3.0):
        super().__init__()
        # Three-way input: h (gene state) + pert_emb (perturbation) + t_emb (timestep)
        self.mlp = nn.Sequential(
            nn.Linear(d_model * 3, d_model),
            nn.SiLU(),
            nn.Linear(d_model, 1),
        )
        # Initialize final layer so sigmoid output ≈ 0.05 at start → v ≈ v_int
        nn.init.zeros_(self.mlp[-1].weight)
        nn.init.constant_(self.mlp[-1].bias, gate_init_bias)

    def forward(
        self, h: torch.Tensor, pert_emb: torch.Tensor, t_emb: torch.Tensor
    ) -> torch.Tensor:
        """
        Args:
            h:        (B, G, d_model) backbone hidden states
            pert_emb: (B, d_model)    perturbation embedding
            t_emb:    (B, d_model)    timestep embedding
        Returns:
            alpha: (B, G) in (0, 1)
        """
        pert_exp = pert_emb.unsqueeze(1).expand_as(h)   # (B, G, d_model)
        t_exp = t_emb.unsqueeze(1).expand_as(h)         # (B, G, d_model)
        x = torch.cat([h, pert_exp, t_exp], dim=-1)     # (B, G, 3*d_model)
        return torch.sigmoid(self.mlp(x).squeeze(-1))    # (B, G)