Download models.py from udgamlabs/biocell: direct link, hf CLI and curl.
- Browser
- Download file 18.6 kB
-
https://huggingface.co/udgamlabs/biocell/resolve/main/models.py
- Command line
-
hf download hf://udgamlabs/biocell/models.py
-
curl -L -o models.py https://huggingface.co/udgamlabs/biocell/resolve/main/models.py
18.6 kB
| """Virtual-cell model: core PyTorch architectures. Licence: see LICENSE. | |
| Both architectures share: | |
| 1. MultiViewBioEncoder: maps 1 or 2 perturbed gene priors (STRING + DepMap + GO + optional open text) | |
| into a unified perturbation embedding with an explicit pairwise epistasis interaction block. | |
| 2. CellContextEncoder: encodes the unperturbed cell-line population profile (mean + std across HVGs) | |
| so ONE model generalizes across multiple cell lines and zero-shot to held-out cell lines. | |
| Shootout Candidates (tested head-to-head on Phase 1 A100 val split): | |
| - Candidate A: SetTransitionTransformer (Arc State-style cell-set transformer, trained with | |
| multi-kernel MMD / Energy Distance + Mean-Delta + Cosine Direction loss; 1-step fast inference). | |
| - Candidate B: OTFlowModel (DiT-style AdaLN-Zero residual network trained with exact minibatch | |
| Optimal Transport pairing between control and perturbed cells; 16-step Heun/midpoint ODE). | |
| """ | |
| import math | |
| import numpy as np | |
| import torch | |
| import torch.nn as nn | |
| import torch.nn.functional as F | |
| class PerturbSetEncoder(nn.Module): | |
| """Permutation-invariant encoder for 1-gene or 2-gene perturbations. | |
| Input: | |
| e1: (B, d_prior) first perturbed gene prior | |
| e2: (B, d_prior) second perturbed gene prior (zeros if single-gene) | |
| is_pair: (B, 1) 1.0 for 2-gene combo, 0.0 for single-gene | |
| Outputs: | |
| p_emb: (B, d_model) perturbation conditioning vector | |
| """ | |
| def __init__(self, d_prior, d_model=256, dropout=0.2): | |
| super().__init__() | |
| self.gene_enc = nn.Sequential( | |
| nn.Linear(d_prior, d_model), | |
| nn.LayerNorm(d_model), | |
| nn.SiLU(), | |
| nn.Dropout(dropout), | |
| nn.Linear(d_model, d_model), | |
| nn.LayerNorm(d_model), | |
| ) | |
| # Symmetric pairwise interaction block for epistasis (uses h1*h2 and |h1-h2|, strictly permutation-invariant) | |
| self.pair_enc = nn.Sequential( | |
| nn.Linear(d_model * 3, d_model), | |
| nn.LayerNorm(d_model), | |
| nn.SiLU(), | |
| nn.Dropout(dropout), | |
| nn.Linear(d_model, d_model), | |
| ) | |
| # Zero-init last layer so training starts smoothly near additive superposition | |
| nn.init.zeros_(self.pair_enc[-1].weight) | |
| nn.init.zeros_(self.pair_enc[-1].bias) | |
| def forward(self, e1, e2=None, is_pair=None): | |
| h1 = self.gene_enc(e1) | |
| if e2 is None or is_pair is None: | |
| return h1 | |
| h2 = self.gene_enc(e2) | |
| s = h1 + h2 | |
| prod = h1 * h2 | |
| diff = torch.abs(h1 - h2) | |
| epistasis = self.pair_enc(torch.cat([s, prod, diff], dim=-1)) | |
| return h1 + is_pair * (h2 + epistasis) | |
| class CellContextEncoder(nn.Module): | |
| """Encodes the baseline control population of any cell line (mean + std per gene) into a context vector.""" | |
| def __init__(self, n_genes, d_model=256, dropout=0.1): | |
| super().__init__() | |
| self.net = nn.Sequential( | |
| nn.Linear(n_genes * 2, d_model), | |
| nn.LayerNorm(d_model), | |
| nn.SiLU(), | |
| nn.Dropout(dropout), | |
| nn.Linear(d_model, d_model), | |
| nn.LayerNorm(d_model), | |
| ) | |
| def forward(self, ctx_mean, ctx_std): | |
| return self.net(torch.cat([ctx_mean, ctx_std], dim=-1)) | |
| class AdaLNBlock(nn.Module): | |
| """Residual MLP or Attention block modulated by AdaLN-Zero (DiT-style conditioning).""" | |
| def __init__(self, d_model, d_cond, use_attn=False, n_heads=4, dropout=0.1): | |
| super().__init__() | |
| self.use_attn = use_attn | |
| self.norm1 = nn.LayerNorm(d_model, elementwise_affine=False) | |
| if use_attn: | |
| self.attn = nn.MultiheadAttention(d_model, n_heads, dropout=dropout, batch_first=True) | |
| self.norm2 = nn.LayerNorm(d_model, elementwise_affine=False) | |
| self.mlp = nn.Sequential( | |
| nn.Linear(d_model, d_model * 2), | |
| nn.GELU(), | |
| nn.Dropout(dropout), | |
| nn.Linear(d_model * 2, d_model), | |
| ) | |
| n_mod = 6 if use_attn else 3 | |
| self.ada = nn.Sequential(nn.SiLU(), nn.Linear(d_cond, n_mod * d_model)) | |
| nn.init.zeros_(self.ada[-1].weight) | |
| nn.init.zeros_(self.ada[-1].bias) | |
| def forward(self, x, cond): | |
| # x: (B, M, D) if use_attn else (B, D); cond: (B, d_cond) | |
| mod = self.ada(cond) | |
| if self.use_attn: | |
| mod = mod.unsqueeze(1) # (B, 1, 6*D) | |
| s1, b1, g1, s2, b2, g2 = mod.chunk(6, dim=-1) | |
| h = self.norm1(x) * (1.0 + s1) + b1 | |
| h_attn, _ = self.attn(h, h, h, need_weights=False) | |
| x = x + g1 * h_attn | |
| h2 = self.norm2(x) * (1.0 + s2) + b2 | |
| return x + g2 * self.mlp(h2) | |
| else: | |
| s2, b2, g2 = mod.chunk(3, dim=-1) | |
| h2 = self.norm2(x) * (1.0 + s2) + b2 | |
| return x + g2 * self.mlp(h2) | |
| class SetTransitionTransformer(nn.Module): | |
| """Candidate A: Cell-Set Transition Transformer (State-style). | |
| Takes a set of M unperturbed control cells X0 (B, M, G), cell-line baseline (ctx_mean, ctx_std), | |
| and perturbation priors (e1, e2, is_pair), and outputs the perturbed cell set Y_hat (B, M, G) | |
| as a learned residual delta on top of X0 (clipped to >= 0 at inference). | |
| """ | |
| def __init__(self, n_genes, d_prior, d_model=384, n_layers=4, n_heads=6, dropout=0.15): | |
| super().__init__() | |
| self.pert_enc = PerturbSetEncoder(d_prior, d_model, dropout=dropout) | |
| self.ctx_enc = CellContextEncoder(n_genes, d_model, dropout=dropout) | |
| self.cond_fuse = nn.Sequential( | |
| nn.Linear(d_model * 2, d_model), | |
| nn.LayerNorm(d_model), | |
| nn.SiLU(), | |
| ) | |
| self.cell_in = nn.Sequential( | |
| nn.Linear(n_genes, d_model), | |
| nn.LayerNorm(d_model), | |
| nn.GELU(), | |
| ) | |
| self.blocks = nn.ModuleList([ | |
| AdaLNBlock(d_model, d_model, use_attn=True, n_heads=n_heads, dropout=dropout) | |
| for _ in range(n_layers) | |
| ]) | |
| self.final_norm = nn.LayerNorm(d_model) | |
| # Residual delta decoder (zero-init so initial prediction == control cell) | |
| self.cell_out = nn.Linear(d_model, n_genes) | |
| nn.init.zeros_(self.cell_out.weight) | |
| nn.init.zeros_(self.cell_out.bias) | |
| # Explicit mean-shift skip path (helps fast convergence on bulk delta + PDS) | |
| self.mean_head = nn.Linear(d_model, n_genes) | |
| nn.init.zeros_(self.mean_head.weight) | |
| nn.init.zeros_(self.mean_head.bias) | |
| def forward(self, x0, ctx_mean, ctx_std, e1, e2=None, is_pair=None, clamp_nonneg=False): | |
| # x0: (B, M, G) | |
| p = self.pert_enc(e1, e2, is_pair) | |
| c = self.ctx_enc(ctx_mean, ctx_std) | |
| cond = self.cond_fuse(torch.cat([p, c], dim=-1)) # (B, D) | |
| h = self.cell_in(x0) | |
| for blk in self.blocks: | |
| h = blk(h, cond) | |
| delta_cell = self.cell_out(self.final_norm(h)) # (B, M, G) | |
| delta_mean = self.mean_head(cond).unsqueeze(1) # (B, 1, G) | |
| out = x0 + delta_mean + delta_cell | |
| if clamp_nonneg: | |
| # Smooth lower clamp (Softplus-like exact ReLU with tiny leak prevented) aligned with log1p >= 0 | |
| out = F.relu(out) | |
| return out | |
| def energy_distance_loss(pred, target, eps=1e-6): | |
| """Unbiased sample Energy Distance per batch item: | |
| ED(P, Q) = 2 E||X - Y|| - E||X - X'|| - E||Y - Y'|| | |
| pred, target: (B, M, G). Matches BOTH mean and full cell-to-cell spread/covariance.""" | |
| # Scale by 1/sqrt(G) so loss magnitude is gene-count invariant | |
| scale = 1.0 / math.sqrt(pred.shape[-1]) | |
| p = pred * scale | |
| q = target * scale | |
| d_pq = torch.sqrt(torch.cdist(p, q, p=2).pow(2) + eps).mean(dim=(1, 2)) | |
| d_pp = torch.sqrt(torch.cdist(p, p, p=2).pow(2) + eps).mean(dim=(1, 2)) | |
| d_qq = torch.sqrt(torch.cdist(q, q, p=2).pow(2) + eps).mean(dim=(1, 2)) | |
| return (2.0 * d_pq - d_pp - d_qq).mean() | |
| def set_transition_loss(pred, target, x0_ctrl_mean, w_ed=1.0, w_mae=5.0, w_var=0.5, w_dir=0.25): | |
| """Phase 2 calibrated loss aligned directly with Cell-Eval (DES + PDS + MAE): | |
| - Energy Distance: matches full single-cell distribution (mean + spread + gene-gene correlation) | |
| - Direct L1 (MAE) on predicted vs true mean expression: eliminates Phase 1 MAE overshoot! | |
| - Per-gene std L1: preserves realistic cell-to-cell variance for Mann-Whitney DES test | |
| - Cosine Direction on mean delta (moderate weight 0.25): drives PDS without inflating amplitude | |
| """ | |
| ed = energy_distance_loss(pred, target) | |
| pred_mean = pred.mean(dim=1) | |
| true_mean = target.mean(dim=1) | |
| l_mae = F.l1_loss(pred_mean, true_mean) | |
| l_var = F.l1_loss(pred.std(dim=1, unbiased=False), target.std(dim=1, unbiased=False)) | |
| pred_delta = pred_mean - x0_ctrl_mean | |
| true_delta = true_mean - x0_ctrl_mean | |
| cos = F.cosine_similarity(pred_delta, true_delta, dim=-1, eps=1e-6) | |
| l_dir = (1.0 - cos).mean() | |
| total = w_ed * ed + w_mae * l_mae + w_var * l_var + w_dir * l_dir | |
| return total, { | |
| "ed": float(ed.detach()), "mae": float(l_mae.detach()), | |
| "var": float(l_var.detach()), "dir": float(l_dir.detach()), | |
| } | |
| class OTFlowModel(nn.Module): | |
| """Candidate B: Minibatch Optimal-Transport Conditional Flow Matching in full HVG space. | |
| Uses AdaLN-Zero residual blocks and sinusoidal time embedding.""" | |
| def __init__(self, n_genes, d_prior, d_model=512, n_layers=4, dropout=0.15): | |
| super().__init__() | |
| self.d_model = d_model | |
| self.pert_enc = PerturbSetEncoder(d_prior, d_model, dropout=dropout) | |
| self.ctx_enc = CellContextEncoder(n_genes, d_model, dropout=dropout) | |
| self.time_mlp = nn.Sequential( | |
| nn.Linear(64, d_model), | |
| nn.SiLU(), | |
| nn.Linear(d_model, d_model), | |
| ) | |
| self.cond_fuse = nn.Sequential( | |
| nn.Linear(d_model * 3, d_model), | |
| nn.LayerNorm(d_model), | |
| nn.SiLU(), | |
| ) | |
| self.x_in = nn.Sequential(nn.Linear(n_genes, d_model), nn.LayerNorm(d_model), nn.SiLU()) | |
| self.blocks = nn.ModuleList([ | |
| AdaLNBlock(d_model, d_model, use_attn=False, dropout=dropout) | |
| for _ in range(n_layers) | |
| ]) | |
| self.final_norm = nn.LayerNorm(d_model) | |
| self.v_out = nn.Linear(d_model, n_genes) | |
| nn.init.zeros_(self.v_out.weight) | |
| nn.init.zeros_(self.v_out.bias) | |
| def _temb(t, dim=64): | |
| half = dim // 2 | |
| freqs = torch.exp(torch.arange(half, device=t.device, dtype=t.dtype) * (-math.log(1000.0) / half)) | |
| ang = t[:, None] * freqs[None, :] * 2.0 * math.pi | |
| return torch.cat([ang.sin(), ang.cos()], dim=-1) | |
| def forward(self, xt, t, ctx_mean, ctx_std, e1, e2=None, is_pair=None): | |
| p = self.pert_enc(e1, e2, is_pair) | |
| c = self.ctx_enc(ctx_mean, ctx_std) | |
| te = self.time_mlp(self._temb(t)) | |
| cond = self.cond_fuse(torch.cat([p, c, te], dim=-1)) | |
| h = self.x_in(xt) | |
| for blk in self.blocks: | |
| h = blk(h, cond) | |
| return self.v_out(self.final_norm(h)) | |
| def sample(self, x0, ctx_mean, ctx_std, e1, e2=None, is_pair=None, n_steps=16): | |
| """Midpoint (RK2) ODE integration from t=0 -> 1.""" | |
| x = x0.clone() | |
| dt = 1.0 / n_steps | |
| for i in range(n_steps): | |
| t0 = torch.full((len(x),), i * dt, device=x.device, dtype=x.dtype) | |
| tm = torch.full((len(x),), (i + 0.5) * dt, device=x.device, dtype=x.dtype) | |
| v1 = self.forward(x, t0, ctx_mean, ctx_std, e1, e2, is_pair) | |
| xm = x + 0.5 * dt * v1 | |
| v2 = self.forward(xm, tm, ctx_mean, ctx_std, e1, e2, is_pair) | |
| x = x + dt * v2 | |
| return x | |
| def minibatch_ot_pair(x0, x1): | |
| """Exact linear-sum-assignment Optimal Transport pairing within a perturbation minibatch. | |
| x0, x1: (M, G) tensors -> returns x0_matched, x1 (reordered x0 to minimize total squared transport cost).""" | |
| with torch.no_grad(): | |
| cost = torch.cdist(x0, x1, p=2).pow(2).cpu().numpy() | |
| from scipy.optimize import linear_sum_assignment # training only; inference needs no SciPy | |
| row_ind, col_ind = linear_sum_assignment(cost) | |
| # col_ind[k] is matched to row_ind[k]; return aligned pairs | |
| return x0[row_ind], x1[col_ind] | |
| # ============================================================================== | |
| # UdgamCell-v2.1: Modality-Aware + Zero-Shot-Calibrated SetTransitionTransformer | |
| # ============================================================================== | |
| class PerturbSetEncoderV21(nn.Module): | |
| """Permutation-invariant encoder for 1-gene or 2-gene perturbations with explicit modality | |
| conditioning: modality=0 -> CRISPRi (Turn OFF / knockdown), modality=1 -> CRISPRa (Turn ON / activation).""" | |
| def __init__(self, d_prior, d_model=384, dropout=0.2): | |
| super().__init__() | |
| self.mod_emb = nn.Embedding(2, d_model) | |
| nn.init.normal_(self.mod_emb.weight, std=0.02) | |
| self.gene_enc = nn.Sequential( | |
| nn.Linear(d_prior, d_model), | |
| nn.LayerNorm(d_model), | |
| nn.SiLU(), | |
| nn.Dropout(dropout), | |
| nn.Linear(d_model, d_model), | |
| nn.LayerNorm(d_model), | |
| ) | |
| self.pair_enc = nn.Sequential( | |
| nn.Linear(d_model * 4, d_model), | |
| nn.LayerNorm(d_model), | |
| nn.SiLU(), | |
| nn.Dropout(dropout), | |
| nn.Linear(d_model, d_model), | |
| ) | |
| nn.init.zeros_(self.pair_enc[-1].weight) | |
| nn.init.zeros_(self.pair_enc[-1].bias) | |
| self.mod_fuse = nn.Sequential( | |
| nn.Linear(d_model * 2, d_model), | |
| nn.LayerNorm(d_model), | |
| nn.SiLU(), | |
| ) | |
| def forward(self, e1, e2=None, is_pair=None, modality=None): | |
| B = e1.shape[0] | |
| if modality is None: | |
| modality = torch.zeros(B, dtype=torch.long, device=e1.device) | |
| m = self.mod_emb(modality) | |
| h1 = self.gene_enc(e1) | |
| if e2 is None or is_pair is None: | |
| h = h1 | |
| else: | |
| h2 = self.gene_enc(e2) | |
| s = h1 + h2 | |
| prod = h1 * h2 | |
| diff = torch.abs(h1 - h2) | |
| epistasis = self.pair_enc(torch.cat([s, prod, diff, m], dim=-1)) | |
| h = h1 + is_pair * (h2 + epistasis) | |
| return self.mod_fuse(torch.cat([h, m], dim=-1)) | |
| class BottleneckCellContextEncoder(nn.Module): | |
| """Low-rank L2-normalized cell-context encoder designed for zero-shot cell-line generalization | |
| and user-uploaded control cell populations (.h5ad / .csv).""" | |
| def __init__(self, n_genes, d_model=384, d_bottleneck=64, dropout=0.35): | |
| super().__init__() | |
| self.net = nn.Sequential( | |
| nn.Dropout(dropout), | |
| nn.Linear(n_genes * 2, d_bottleneck), | |
| nn.LayerNorm(d_bottleneck), | |
| nn.SiLU(), | |
| nn.Dropout(dropout), | |
| nn.Linear(d_bottleneck, d_model), | |
| nn.LayerNorm(d_model), | |
| ) | |
| self.null_ctx = nn.Parameter(torch.zeros(1, d_model)) | |
| def forward(self, ctx_mean, ctx_std, ctx_drop_mask=None): | |
| # L2-normalize mean and std separately so sequencing-depth scaling never causes OOD explosions | |
| cm_n = F.normalize(ctx_mean, p=2, dim=-1, eps=1e-6) * math.sqrt(ctx_mean.shape[-1] / 100.0) | |
| cs_n = F.normalize(ctx_std, p=2, dim=-1, eps=1e-6) * math.sqrt(ctx_std.shape[-1] / 100.0) | |
| c = self.net(torch.cat([cm_n, cs_n], dim=-1)) | |
| if ctx_drop_mask is not None: | |
| # ctx_drop_mask: (B, 1) float where 1.0 = drop context to learned null_ctx | |
| c = c * (1.0 - ctx_drop_mask) + self.null_ctx.expand_as(c) * ctx_drop_mask | |
| return c | |
| class SetTransitionTransformerV21(nn.Module): | |
| """UdgamCell-v2.1: Modality-conditioned (CRISPRi / CRISPRa) & zero-shot-calibrated | |
| SetTransitionTransformer with decomposed universal + cell-context-modulated delta heads.""" | |
| def __init__(self, n_genes, d_prior, d_model=384, n_layers=4, n_heads=6, | |
| d_ctx=64, dropout=0.15, ctx_dropout=0.35): | |
| super().__init__() | |
| self.pert_enc = PerturbSetEncoderV21(d_prior, d_model, dropout=dropout) | |
| self.ctx_enc = BottleneckCellContextEncoder(n_genes, d_model, d_bottleneck=d_ctx, dropout=ctx_dropout) | |
| self.cond_fuse = nn.Sequential( | |
| nn.Linear(d_model * 2, d_model), | |
| nn.LayerNorm(d_model), | |
| nn.SiLU(), | |
| ) | |
| self.cell_in = nn.Sequential( | |
| nn.Linear(n_genes, d_model), | |
| nn.LayerNorm(d_model), | |
| nn.GELU(), | |
| ) | |
| self.blocks = nn.ModuleList([ | |
| AdaLNBlock(d_model, d_model, use_attn=True, n_heads=n_heads, dropout=dropout) | |
| for _ in range(n_layers) | |
| ]) | |
| self.final_norm = nn.LayerNorm(d_model) | |
| self.cell_out = nn.Linear(d_model, n_genes) | |
| nn.init.zeros_(self.cell_out.weight) | |
| nn.init.zeros_(self.cell_out.bias) | |
| # Decomposed mean heads: universal perturbation effect + cell-line-specific modulation | |
| self.shared_mean_head = nn.Linear(d_model, n_genes) | |
| nn.init.zeros_(self.shared_mean_head.weight) | |
| nn.init.zeros_(self.shared_mean_head.bias) | |
| self.ctx_mean_head = nn.Linear(d_model, n_genes) | |
| nn.init.zeros_(self.ctx_mean_head.weight) | |
| nn.init.zeros_(self.ctx_mean_head.bias) | |
| def forward(self, x0, ctx_mean, ctx_std, e1, e2=None, is_pair=None, modality=None, | |
| clamp_nonneg=False, ctx_drop_p=0.0, ctx_scale=1.0): | |
| B = x0.shape[0] | |
| p = self.pert_enc(e1, e2, is_pair, modality=modality) | |
| drop_mask = None | |
| if self.training and ctx_drop_p > 0.0: | |
| drop_mask = (torch.rand(B, 1, device=x0.device) < ctx_drop_p).float() | |
| elif ctx_scale <= 0.0: | |
| drop_mask = torch.ones(B, 1, device=x0.device) | |
| c = self.ctx_enc(ctx_mean, ctx_std, ctx_drop_mask=drop_mask) | |
| if not self.training and 0.0 < ctx_scale < 1.0: | |
| c = ctx_scale * c + (1.0 - ctx_scale) * self.ctx_enc.null_ctx.expand_as(c) | |
| cond = self.cond_fuse(torch.cat([p, c], dim=-1)) | |
| h = self.cell_in(x0) | |
| for blk in self.blocks: | |
| h = blk(h, cond) | |
| delta_cell = self.cell_out(self.final_norm(h)) | |
| delta_shared = self.shared_mean_head(p).unsqueeze(1) | |
| delta_ctx = self.ctx_mean_head(cond).unsqueeze(1) | |
| if not self.training and ctx_scale < 1.0: | |
| delta_ctx = delta_ctx * ctx_scale | |
| out = x0 + delta_shared + delta_ctx + delta_cell | |
| if clamp_nonneg: | |
| out = F.relu(out) | |
| return out | |