File size: 2,000 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 | """
Scalar latent layers for grn_scalar.
MultiStatsLatentEncoder: (B, G, 4) β (B, G, d_model) β for agg_mode='multi_stats'
ScalarLatentDecoder: (B, G, 2*d_model) β (B, G, latent_dim) β symmetric with ExprDecoder
For agg_mode='signed_l2' (latent_dim=1), the encoder is ContinuousValueEncoder
from scDFM (reused directly in model.py), so no custom encoder class is needed.
"""
import torch.nn as nn
class MultiStatsLatentEncoder(nn.Module):
"""
Encodes 4-dim per-gene statistics to d_model embedding.
Mirrors ContinuousValueEncoder structure: Linear β ReLU β Linear β LN β Dropout.
"""
def __init__(self, d_model: int, dropout: float = 0.1):
super().__init__()
self.linear1 = nn.Linear(4, d_model)
self.activation = nn.ReLU()
self.linear2 = nn.Linear(d_model, d_model)
self.norm = nn.LayerNorm(d_model)
self.dropout = nn.Dropout(p=dropout)
def forward(self, x):
"""x: (B, G, 4) β (B, G, d_model)"""
x = self.activation(self.linear1(x))
x = self.linear2(x)
x = self.norm(x)
return self.dropout(x)
class ScalarLatentDecoder(nn.Module):
"""
Decodes backbone output to scalar (or 4-dim) latent velocity.
Symmetric with ExprDecoder: input is (B, G, 2*d_model) from backbone+pert_emb concat.
"""
def __init__(self, d_model: int, latent_dim: int = 1):
super().__init__()
self.latent_dim = latent_dim
self.fc = nn.Sequential(
nn.Linear(2 * d_model, d_model),
nn.LeakyReLU(),
nn.Linear(d_model, d_model),
nn.LeakyReLU(),
nn.Linear(d_model, latent_dim),
)
def forward(self, x):
"""
x: (B, G, 2*d_model) β backbone output concatenated with pert_emb
Returns: (B, G) if latent_dim=1, else (B, G, latent_dim)
"""
out = self.fc(x)
if self.latent_dim == 1:
return out.squeeze(-1)
return out
|