lfj-code / transfer /code /CCFM /CCFM_Architecture.md
ethan1115's picture
Upload folder using huggingface_hub
0161e74 verified

CCFM (Cascaded Conditioned Flow Matching) 架构文档

一、项目概述

CCFM 是一个级联流匹配框架,融合三个模型的优势来做单细胞扰动预测:

  • scDFM:基础流匹配架构(backbone、数据加载、训练范式)
  • LatentForcing:级联双流思想(latent 流 + 表达流分阶段生成)
  • scGPT:冻结的预训练模型,提供 per-gene 上下文化特征

核心创新

借鉴 LatentForcing 的双流架构,将其从图像域迁移到单细胞域:

LatentForcing (图像) CCFM (单细胞)
像素值 基因表达值
DINO-v2 特征(辅助生成目标) scGPT 上下文特征(辅助生成目标)
类别标签(条件信号) control 表达 + perturbation_id(条件信号)

关键区分:scGPT 特征是从 target(扰动细胞)提取的辅助生成目标,不是条件信号。推理时模型从噪声生成 scGPT 特征(Stage 1),再用生成的特征引导表达值生成(Stage 2)。真正的条件信号是 control 表达和 perturbation_id,它们在推理时始终可获取。

文件结构

CCFM/
├── _bootstrap_scdfm.py                    # Bootstrap scDFM 模块,命名空间隔离
├── config/
│   └── config_cascaded.py                 # CascadedFlowConfig dataclass (tyro CLI)
├── src/
│   ├── __init__.py
│   ├── utils.py                           # Re-exports scDFM utils
│   ├── _scdfm_imports.py                  # scDFM 模块集中导入
│   ├── denoiser.py                        # CascadedDenoiser (训练/推理逻辑)
│   ├── model/
│   │   ├── model.py                       # CascadedFlowModel 双流模型
│   │   └── layers.py                      # LatentEmbedder, LatentDecoder
│   └── data/
│       ├── data.py                        # scDFM 数据加载集成
│       └── scgpt_extractor.py             # FrozenScGPTExtractor
├── scripts/
│   ├── run_cascaded.py                    # 训练/评估入口
│   └── download_scgpt.py                  # 下载 scGPT 预训练模型
├── run.sh                                 # pjsub 模板
└── run_topk30_neg.sh                      # 完整参数化 job 脚本

默认超参数

参数 说明
B 48 batch size
G_full 5000 HVG 总数
G 1000 训练时随机基因子集
d_model 128 隐藏维度
scgpt_dim 512 scGPT 输出特征维度
bottleneck_dim 128 LatentEmbedder 瓶颈维度
nhead 8 注意力头数
nlayers 4 Transformer 层数
dh_depth 2 LatentDecoder block 数
choose_latent_p 0.4 训练 latent 流的概率
latent_weight 1.0 latent loss 权重
gamma 0.5 MMD loss 权重
lr 5e-5 学习率
steps 200000 训练总步数
latent_steps 20 推理 ODE 步数(latent)
expr_steps 20 推理 ODE 步数(表达)
warmup_batches 200 scGPT running stats 预热

二、训练流程 Tensor 数据流

2.1 数据准备

输入:
  source:           (B, G_full=5000)    控制组表达
  target:           (B, G_full=5000)    扰动后表达
  perturbation_id:  (B, 2)              扰动 token ID
  gene_ids:         (G_full=5000,)      全部基因的 vocab ID

随机采样 1000 个基因:
  input_gene_ids = randperm(5000)[:1000]          → (1000,)
  source_sub  = source[:, input_gene_ids]         → (48, 1000)
  target_sub  = target[:, input_gene_ids]         → (48, 1000)
  gene_input  = gene_ids[input_gene_ids].expand   → (48, 1000)

2.2 冻结 scGPT 提取辅助生成目标(类似 LatentForcing 的 DINO 特征提取)

scgpt_extractor.extract(target_sub, gene_indices=input_gene_ids):

  target_sub:        (48, 1000)         输入表达
  hvg_ids:           (1000,)            HVG → scGPT vocab ID 映射
  valid_mask:        (1000,)            bool, 过滤在 scGPT vocab 中的基因
  expr_valid:        (48, G_valid)      有效基因的表达值

  若 G_valid+1 > max_seq_len(1200):
    随机采样 1199 个基因
    seq_len = 1200
  否则:
    seq_len = G_valid + 1

  拼接 CLS token:
    src    = [cls_id | gene_ids]        → (48, seq_len)       long
    values = [0      | expr_valid]      → (48, seq_len)       float

  scGPT frozen forward:
    encoder_out = scgpt._encode(src, values, mask)  → (48, seq_len, 512)

  去掉 CLS, scatter 回固定位置:
    gene_features = encoder_out[:, 1:, :]           → (48, seq_len-1, 512)
    output = zeros(48, 1000, 512)
    output.scatter_(1, idx, gene_features)          → (48, 1000, 512)

  归一化 (running mean/var, warmup 200 batches 后冻结):
    output = (output - running_mean) / sqrt(running_var) * target_std

  z_target:  (48, 1000, 512)

2.3 级联时间采样

t_latent = rand(48)                         → (48,)
t_expr   = rand(48)                         → (48,)
choose_latent_mask = rand(48) < 0.4         → (48,)  bool

对每个样本二选一:
  若 mask=True  (40%概率): t_latent 保留, t_expr=0, w_expr=0, w_latent=1  → 训练 latent 流
  若 mask=False (60%概率): t_expr 保留, t_latent=1, w_expr=1, w_latent=0  → 训练表达流

输出:
  t_expr:    (48,)    表达流时间步
  t_latent:  (48,)    潜变量流时间步
  w_expr:    (48,)    表达 loss 权重 (0 或 1)
  w_latent:  (48,)    潜变量 loss 权重 (0 或 1)

2.4 Flow Path 采样(线性插值 + 速度)

表达流:
  noise_expr = randn_like(source_sub)                    → (48, 1000)
  path_expr  = AffineProbPath.sample(t_expr, noise_expr, target_sub)
    path_expr.x_t  = (1-t)*noise + t*target              → (48, 1000)    插值后的噪声表达
    path_expr.dx_t = target - noise                       → (48, 1000)    目标速度 (ground truth)

潜变量流:
  noise_latent = randn_like(z_target)                     → (48, 1000, 512)
  展平:
    z_target_flat      = z_target.reshape(48, 512000)     → (48, 512000)
    noise_latent_flat  = noise_latent.reshape(48, 512000) → (48, 512000)
  path_latent_flat = AffineProbPath.sample(t_latent, noise_latent_flat, z_target_flat)
  还原:
    path_latent.x_t  = reshape → (48, 1000, 512)          插值后的噪声 latent
    path_latent.dx_t = reshape → (48, 1000, 512)          目标速度

2.5 模型前向传播 (CascadedFlowModel.forward)

输入:
  gene_input:       (48, 1000)          基因 token ID
  source_sub:       (48, 1000)          源表达
  path_expr.x_t:    (48, 1000)          噪声表达
  path_latent.x_t:  (48, 1000, 512)     噪声 latent
  t_expr:           (48,)
  t_latent:         (48,)
  perturbation_id:  (48, 2)

Step 5a: 表达流 Embedding

gene_emb   = GeneEncoder(gene_input)                        → (48, 1000, 128)
val_emb_1  = ContinuousValueEncoder(x_t)                    → (48, 1000, 128)   encoder_1 = 噪声 target (同 scDFM)
val_emb_2  = ContinuousValueEncoder(source_sub)             → (48, 1000, 128)   encoder_2 = control (同 scDFM)
expr_tokens = fusion_layer(cat[val_emb_1, val_emb_2]) + gene_emb
            = Linear(256→128) → GELU → Linear(128→128) → LN + gene_emb → (48, 1000, 128)

设计说明(与 scDFM 对齐):

  • value_encoder_1 编码噪声 target(x_t),value_encoder_2 编码 control(source),与 scDFM 角色一致
  • gene_emb 只在融合后加一次(去冗余),而非分别加到两个 encoder 的输出上
  • val_emb_2(control 嵌入)传入 backbone 的 DiffPerceiverBlock 作为交叉注意力 KV(稳定参考基线)

Step 5b: 潜变量流 Embedding

latent_tokens = LatentEmbedder(path_latent.x_t)
              = Linear(512→128) → GELU → Linear(128→128)    → (48, 1000, 128)

Step 5c: 双流融合

x = expr_tokens + latent_tokens                              → (48, 1000, 128)

Step 5d: 条件向量

t_expr_emb   = TimestepEmbedder(t_expr)                      → (48, 128)
t_latent_emb = TimestepEmbedder(t_latent)                     → (48, 128)
pert_emb     = GeneEncoder(perturbation_id).mean(dim=1)       → (48, 128)
               # perturbation_id: (48,2) → encoder → (48,2,128) → mean → (48,128)
c = t_expr_emb + t_latent_emb + pert_emb                     → (48, 128)

Step 5e: 共享 Backbone (4 层 DiffPerceiverBlock)

for i in range(4):
  # GeneadaLN: 用 gene_emb 调制 x
  x = gene_adaLN[i](gene_emb, x)                             → (48, 1000, 128)

  # Adapter: 拼接 pert_emb 后降维
  pert_exp = pert_emb[:, None, :].expand(-1, 1000, -1)        → (48, 1000, 128)
  x = cat[x, pert_exp]                                        → (48, 1000, 256)
  x = adapter_layer[i](x)
    = Linear(256→128) → LeakyReLU → Linear(128→128) → LeakyReLU
                                                               → (48, 1000, 128)

  # DiffPerceiverBlock: attention + MLP, 用 c 做 AdaLN 条件
  x = DiffPerceiverBlock(x, val_emb_2, c)                     → (48, 1000, 128)

Step 5f: 表达 Decoder Head

x_with_pert = cat[x, pert_exp]                                → (48, 1000, 256)
pred_v_expr = ExprDecoder(x_with_pert)["pred"]                → (48, 1000)

Step 5g: Latent Decoder Head

h = dh_proj(x)              # Linear(128→128)                 → (48, 1000, 128)

for j in range(2):           # dh_depth=2
  # AdaLN: c → SiLU → Linear(128→768) → chunk 6
  shift_msa, scale_msa, gate_msa,
  shift_mlp, scale_mlp, gate_mlp = adaLN_modulation(c)        各 (48, 128)

  # Self-Attention with AdaLN
  h_norm = LayerNorm(h) * (1+scale_msa[:,None,:]) + shift_msa[:,None,:]
                                                               → (48, 1000, 128)
  h_attn = MultiheadAttention(h_norm, h_norm, h_norm)          → (48, 1000, 128)
  h = h + gate_msa[:,None,:] * h_attn                          → (48, 1000, 128)

  # MLP with AdaLN
  h_norm = LayerNorm(h) * (1+scale_mlp[:,None,:]) + shift_mlp[:,None,:]
                                                               → (48, 1000, 128)
  h_mlp  = Linear(128→512) → GELU → Linear(512→128)           → (48, 1000, 128)
  h = h + gate_mlp[:,None,:] * h_mlp                           → (48, 1000, 128)

pred_v_latent = final(h)
              = LN → Linear(128→128) → GELU → Linear(128→512) → (48, 1000, 512)

2.6 Loss 计算

loss_expr   = MSE(pred_v_expr - path_expr.dx_t) * w_expr[:, None]
            = ((48,1000) - (48,1000))^2 * (48,1)  → mean → scalar
              只对 w_expr=1 的样本有贡献 (约60%)

loss_latent = MSE(pred_v_latent - path_latent.dx_t) * w_latent[:, None, None]
            = ((48,1000,512) - (48,1000,512))^2 * (48,1,1) → mean → scalar
              只对 w_latent=1 的样本有贡献 (约40%)

loss = loss_expr + latent_weight * loss_latent

可选 MMD loss (对 w_expr>0 的样本):
  x1_hat = x_t + pred_v_expr * (1-t_expr)    # 单步重建 → (N_expr, 1000)
  mmd_loss = mmd2_unbiased_multi_sigma(x1_hat, target_sub)  → scalar
  loss += gamma * mmd_loss

2.7 训练循环

for iteration in range(200000):
    batch → source(48, 5000), target(48, 5000), pert_id(48, 2)
    loss = denoiser.train_step(source, target, pert_id, gene_ids, infer_top_gene=1000)
    optimizer.zero_grad()
    accelerator.backward(loss)
    optimizer.step()
    scheduler.step()  # CosineAnnealing

    if iteration % 5000 == 0:
        save checkpoint + run evaluation

三、推理流程 Tensor 数据流

推理时不调用 scGPT 编码器,模型从噪声自行生成 latent(辅助语义表征)。用全部 5000 个基因,不做子集采样。 条件信号(control 表达 + perturbation_id)在每个 ODE 步中持续提供。

输入:
  source:           (B, 5000)       控制组表达
  perturbation_id:  (B, 2)          扰动 ID
  gene_ids:         (B, 5000)       基因 vocab ID

3.1 Stage 1: 生成 Latent(t_latent: 0→1, t_expr 固定=0)

z_noise = randn(B, 5000, 512)              初始噪声

ODE 求解 (RK4, 20步, t ∈ [0,1]):
  每一步调用 latent_vf(t, z_t):
    t_latent = t.expand(B)                  → (B,)     当前时间步
    t_expr   = zeros(B)                     → (B,)     固定为 0

    model.forward(
      gene_ids,                             (B, 5000)
      source,                               (B, 5000)   源表达
      source,                               (B, 5000)   ← 注意: x_t 用 source (因为 t_expr=0)
      z_t,                                  (B, 5000, 512)  当前 latent 状态
      t_expr=0,                             (B,)
      t_latent=t,                           (B,)
      perturbation_id,                      (B, 2)
    )
    → _, v_latent                           (B, 5000, 512)  latent 速度场

    return v_latent

  z_traj = odeint(latent_vf, z_noise, linspace(0,1,20))
                                            → (20, B, 5000, 512)
  z_generated = z_traj[-1]                  → (B, 5000, 512)  ★ 生成的 latent

3.2 Stage 2: 用生成的 Latent 引导表达生成(t_expr: 0→1, t_latent 固定=1)

expr_noise = randn_like(source)             → (B, 5000)  高斯噪声 (或 Poisson)

ODE 求解 (RK4, 20步, t ∈ [0,1]):
  每一步调用 expr_vf(t, x_t):
    t_expr   = t.expand(B)                  → (B,)     当前时间步
    t_latent = ones(B)                      → (B,)     固定为 1 (latent 已完成)

    model.forward(
      gene_ids,                             (B, 5000)
      source,                               (B, 5000)
      x_t,                                  (B, 5000)   ← 当前噪声表达
      z_generated,                          (B, 5000, 512)  ★ Stage 1 的结果 (固定)
      t_expr=t,                             (B,)
      t_latent=1,                           (B,)
      perturbation_id,                      (B, 2)
    )
    → v_expr, _                             (B, 5000)  表达速度场

    return v_expr

  x_traj = odeint(expr_vf, expr_noise, linspace(0,1,20))
                                            → (20, B, 5000)
  x_generated = clamp(x_traj[-1], min=0)   → (B, 5000)  ★ 最终预测表达

3.3 评估流程

对每个扰动条件:
  source = 随机采样 128 个控制细胞              → (128, 5000)
  按 batch_size 调用 generate:
    pred = denoiser.generate(source, pert_id, gene_ids)  → (128, 5000)

汇总:
  pred_adata = AnnData(X=所有预测表达, obs=扰动标签)
  real_adata = AnnData(X=所有真实表达, obs=扰动标签)
  MetricsEvaluator(pred_adata, real_adata) → results.csv, agg_results.csv

四、训练 vs 推理 对比总结

维度 训练 推理
基因数 随机采样 G=1000 全量 G=5000
scGPT 特征(辅助生成目标) 冻结提取 target 特征 z_target 作为 latent 流的生成目标 不使用,模型从噪声自行生成 latent(Stage 1)
时间步 级联采样:40% 训练 latent, 60% 训练表达 两阶段串行:先 latent(0→1), 再表达(0→1)
流采样 单步:x_t = (1-t)*noise + t*target ODE 积分:RK4, 20 步
Loss MSE(velocity) + MMD
输出 scalar loss (B, G_full) 表达矩阵
条件信号 control + pert_id(真条件);scGPT 特征是生成目标 control + pert_id(每步输入);latent 由 Stage1 生成
时间步 t_exprt_latent 随机,互斥激活 Stage1: t_expr=0, t_latent∈[0,1]; Stage2: t_latent=1, t_expr∈[0,1]

五、模型架构总览图

                        ┌──────────────────────────────────────────────┐
                        │           CascadedFlowModel                  │
                        │                                              │
  gene_id (B,G) ───────→│  GeneEncoder ──→ gene_emb (B,G,d)           │
                        │       │                                      │
  x_t (B,G) ──────────→│  ValEnc1 ──→ val_emb_1 (B,G,d)  噪声target  │
  source (B,G) ────────→│  ValEnc2 ──→ val_emb_2 (B,G,d)  control     │
                        │       │                                      │
                        │  fusion_layer(cat[val_emb_1, val_emb_2])     │
                        │       + gene_emb (融合后加一次)                │
                        │       ↓                                      │
                        │  expr_tokens (B,G,d)                         │
                        │       │                                      │
  z_t (B,G,512) ──────→│  LatentEmbedder(512→128→d)                   │
                        │       ↓                                      │
                        │  latent_tokens (B,G,d)                       │
                        │       │                                      │
                        │  x = expr_tokens + latent_tokens  (B,G,d)   │
                        │                                              │
  t_expr (B,) ────────→│  TimestepEmb ──┐                             │
  t_latent (B,) ──────→│  TimestepEmb ──┼→ c = sum (B,d)             │
  pert_id (B,2) ──────→│  PertEmb ──────┘                             │
                        │                                              │
                        │  ┌─ 4x DiffPerceiverBlock ──────────────┐    │
                        │  │  gene_adaLN(gene_emb, x)             │    │
                        │  │  cat[x, pert_emb] → adapter → x      │    │
                        │  │  DiffPerceiverBlock(x, val_emb_2, c)  │    │
                        │  └──────────────────────────────────────┘    │
                        │       │                                      │
                        │       ├──→ ExprDecoder(cat[x, pert]) ──→ pred_v_expr (B,G)
                        │       │                                      │
                        │       └──→ LatentDecoder(x, c)               │
                        │              dh_proj → 2x AdaLN Block        │
                        │              → final proj ──→ pred_v_latent (B,G,512)
                        └──────────────────────────────────────────────┘