| """ |
| 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 |
|
|