File size: 8,734 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 208 209 210 211 212 213 214 215 216 217 218 219 | """
CascadedFlowModel for grn_scalar.
Key changes from grn_svd:
- Latent target: scalar (B, G) or 4-dim (B, G, 4) instead of (B, G, 128)
- Latent encoder: ContinuousValueEncoder (DIM=1, symmetric with expr) or MultiStatsLatentEncoder (DIM=4)
- Latent decoder: ScalarLatentDecoder (symmetric with ExprDecoder, takes backbone+pert concat)
"""
import torch
import torch.nn as nn
from torch import Tensor
from typing import Optional, Tuple
from .layers import MultiStatsLatentEncoder, ScalarLatentDecoder
from .._scdfm_imports import (
GeneadaLN,
ContinuousValueEncoder,
GeneEncoder,
BatchLabelEncoder,
TimestepEmbedder,
ExprDecoder,
DifferentialTransformerBlock,
PerceiverBlock,
DiffPerceiverBlock,
)
class CascadedFlowModel(nn.Module):
"""
Cascaded Flow Model with scalar latent target.
Inputs:
gene_id: (B, G) gene token IDs
cell_1: (B, G) source (control) expression
x_t: (B, G) noised target expression (expr flow)
z_t: (B, G) or (B, G, 4) noised scalar latent (latent flow)
t_expr: (B,) expression flow timestep
t_latent: (B,) latent flow timestep
perturbation_id: (B, 2) perturbation token IDs
Outputs:
pred_v_expr: (B, G) predicted expression velocity
pred_v_latent: (B, G) or (B, G, 4) predicted latent velocity
"""
def __init__(
self,
ntoken: int = 6000,
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,
latent_dim: int = 1,
):
super().__init__()
self.d_model = d_model
self.latent_dim = latent_dim
self.fusion_method = fusion_method
self.perturbation_function = perturbation_function
# === Timestep embedders (separate for expr and latent) ===
self.t_expr_embedder = TimestepEmbedder(d_model)
self.t_latent_embedder = TimestepEmbedder(d_model)
# === Perturbation embedder ===
self.perturbation_embedder = BatchLabelEncoder(ntoken, d_model)
# === Expression stream (reused from scDFM) ===
self.value_encoder_1 = ContinuousValueEncoder(d_model, dropout)
self.value_encoder_2 = ContinuousValueEncoder(d_model, dropout)
self.encoder = GeneEncoder(
ntoken, d_model,
use_perturbation_interaction=use_perturbation_interaction,
mask_path=mask_path,
)
self.use_perturbation_interaction = use_perturbation_interaction
self.fusion_layer = nn.Sequential(
nn.Linear(2 * d_model, d_model),
nn.GELU(),
nn.Linear(d_model, d_model),
nn.LayerNorm(d_model),
)
# === Latent stream encoder (symmetric with expression) ===
if latent_dim == 1:
# Identical to expression encoder: scalar → d_model MLP
self.latent_embedder = ContinuousValueEncoder(d_model, dropout)
else:
# 4-dim → d_model MLP (mirrors ContinuousValueEncoder structure)
self.latent_embedder = MultiStatsLatentEncoder(d_model, dropout)
# === Shared backbone blocks ===
if 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 == "differential_perceiver":
self.blocks = nn.ModuleList([
DiffPerceiverBlock(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"Invalid fusion method: {fusion_method}")
# === Per-layer gene AdaLN + adapter ===
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)
])
# === Expression decoder head (reused from scDFM) ===
self.final_layer = ExprDecoder(d_model, explicit_zero_prob=False, use_batch_labels=True)
# === Latent decoder head (symmetric with ExprDecoder) ===
self.latent_decoder = ScalarLatentDecoder(d_model, latent_dim)
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)
def get_perturbation_emb(
self,
perturbation_id: Optional[Tensor] = None,
perturbation_emb: Optional[Tensor] = None,
cell_1: Optional[Tensor] = None,
) -> Tensor:
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: Tensor, # (B, G)
cell_1: Tensor, # (B, G) source expression
x_t: Tensor, # (B, G) noised expression
z_t: Tensor, # (B, G) or (B, G, 4) noised scalar latent
t_expr: Tensor, # (B,)
t_latent: Tensor, # (B,)
perturbation_id: Optional[Tensor] = None,
) -> Tuple[Tensor, Tensor]:
if t_expr.dim() == 0:
t_expr = t_expr.repeat(cell_1.size(0))
if t_latent.dim() == 0:
t_latent = t_latent.repeat(cell_1.size(0))
# === 1. Expression stream embedding ===
gene_emb = self.encoder(gene_id)
val_emb_1 = self.value_encoder_1(x_t)
val_emb_2 = self.value_encoder_2(cell_1) + gene_emb
expr_tokens = self.fusion_layer(torch.cat([val_emb_1, val_emb_2], dim=-1)) + gene_emb
# === 2. Latent stream embedding (symmetric with expression) ===
# ContinuousValueEncoder handles (B, G) → unsqueeze → (B, G, 1) → MLP → (B, G, d_model)
# MultiStatsLatentEncoder handles (B, G, 4) → MLP → (B, G, d_model)
latent_tokens = self.latent_embedder(z_t)
# === 3. Element-wise addition ===
x = expr_tokens + latent_tokens
# === 4. Conditioning vector ===
t_expr_emb = self.t_expr_embedder(t_expr)
t_latent_emb = self.t_latent_embedder(t_latent)
pert_emb = self.get_perturbation_emb(perturbation_id, cell_1=cell_1)
c = t_expr_emb + t_latent_emb + pert_emb
# === 5. Shared backbone ===
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, val_emb_2, c)
# === 6. Decoder heads (both symmetric, both take backbone+pert concat) ===
x_with_pert = torch.cat([x, pert_emb[:, None, :].expand(-1, x.size(1), -1)], dim=-1)
pred_v_expr = self.final_layer(x_with_pert)["pred"] # (B, G)
pred_v_latent = self.latent_decoder(x_with_pert) # (B, G) or (B, G, 4)
return pred_v_expr, pred_v_latent
|