lfj-code / transfer /code /CCFM /plan.md
ethan1115's picture
Upload folder using huggingface_hub
0161e74 verified
# Cascaded Conditioned Flow Matching (CCFM) — 实现计划
## Context
**目标**: 构建一个级联条件流匹配模型,用于单细胞扰动预测。以 scDFM 为底盘,引入 LatentForcing 的级联引导思想,使用 scGPT 提取的 **per-cell-per-gene contextualized features** 作为 latent 引导信号。
**核心概念映射**:
| LatentForcing (图像) | CCFM (单细胞) |
|---|---|
| Pixel patches → tokens | Gene expression → tokens |
| DINO-v2 feature patches → tokens | scGPT per-gene features → tokens |
| `pixel_embed + dino_embed` (element-wise add) | `expr_embed + scgpt_embed` (element-wise add) |
| `c = t_pixel + t_dino + y_emb` (AdaLN) | `c = t_expr + t_latent + pert_emb` (AdaLN) |
| Frozen DINO-v2 on-the-fly | Frozen scGPT on-the-fly |
| Separate pixel/dino decoder heads | Separate expr/latent decoder heads |
**数据集**: Norman (CRISPR) + ComboSciPlex (drug combination)
---
## 0. 项目结构
**工作目录**: `transfer/code/CCFM/`
```
transfer/code/CCFM/
├── plan.md # 本计划文件的副本
├── config/
│ └── config_cascaded.py # CascadedFlowConfig 配置
├── src/
│ ├── model/
│ │ ├── __init__.py
│ │ ├── model.py # CascadedFlowModel 主干网络
│ │ └── layers.py # 新增层: LatentEmbedder, LatentDecoder
│ ├── data/
│ │ ├── __init__.py
│ │ ├── data.py # 数据加载 (基于 scDFM, 新增 latent 支持)
│ │ └── scgpt_extractor.py # 冻结 scGPT 特征提取器封装
│ ├── denoiser.py # CascadedDenoiser (时间采样、损失、生成)
│ └── utils.py # 工具函数
├── scripts/
│ ├── run_cascaded.py # 训练/推理入口
│ └── download_scgpt.py # 下载 scGPT 预训练模型
└── run.sh # pjsub 提交脚本模板
```
所有新代码写在 `transfer/code/CCFM/` 下,通过 import 引用 scDFM 和 scGPT 的现有模块。
---
## 1. 数据准备
### 1.1 下载 scGPT 预训练模型
- 下载 `whole-human` 模型到 `transfer/data/scGPT_pretrained/`
- 包含: `best_model.pt`, `vocab.json`, `args.json`
- 脚本: `scripts/download_scgpt.py`
### 1.2 数据加载 (`src/data/data.py`)
复用 scDFM 的 `Data` 类进行数据加载和 train/test 划分。修改 `PerturbationDataset` 以返回 **raw expression values** (不仅是 gene indices),供 scGPT on-the-fly 提取使用。
关键改动:
-`__init__` 中预计算 scDFM gene names → scGPT vocab ID 的映射表
- `__getitem__` 返回: `src_cell_data`, `tgt_cell_data`, `condition_id`, `src_cell_raw` (供 scGPT), `tgt_cell_raw` (供 scGPT)
### 1.3 scGPT 特征提取器 (`src/data/scgpt_extractor.py`)
**冻结 scGPT 作为 on-the-fly 特征提取器** (类似 LatentForcing 中冻结 DINO-v2):
```python
class FrozenScGPTExtractor(nn.Module):
"""
封装冻结的 scGPT 模型,用于在训练时 on-the-fly 提取 per-gene features。
类似 LatentForcing 的 dinov2_hf.py 中的 RAE 类。
"""
def __init__(self, model_dir, n_hvg_genes, hvg_gene_names, device):
# 1. 加载预训练 scGPT (TransformerModel)
# 2. 冻结所有参数 (requires_grad=False)
# 3. 建立 hvg_gene_names → scGPT vocab ID 映射
# 4. 预计算全局归一化统计量 (running mean/var)
@torch.no_grad()
def extract(self, expression_values, gene_indices=None):
"""
输入: expression_values (B, G) — G=infer_top_gene 的表达值
输出: per_gene_features (B, G, scgpt_d_model) — contextualized 特征
流程:
1. 筛选非零基因,构建 scGPT 输入 (token IDs + values)
2. 运行冻结 scGPT._encode() → (B, seq_len, d_model)
3. 将输出 scatter 回固定的 G 个基因位置
4. 未覆盖的位置用零向量填充
5. 全局归一化 + 方差匹配
"""
```
**关键技术细节**:
- scGPT 的 `_encode()` 返回 `(batch, seq_len, d_model=512)`,其中 seq_len 是变长的(仅包含非零表达的基因 + `<cls>` token)
- 需要用 gene ID 映射将变长输出 **scatter** 回固定的 G 个基因位置
- 基因对齐: scDFM 使用 gene symbol (如 "MAPK1"),scGPT 使用自己的 vocab。在 `__init__` 中建立 `hvg_name → scGPT_vocab_id` 的映射
- 不在 scGPT vocab 中的基因: 用零向量替代
### 1.4 全局归一化与方差匹配 (CRITICAL)
`FrozenScGPTExtractor` 内部实现:
```python
# 方案: 使用 running statistics (类似 BatchNorm 的 running_mean/var)
# 在前 N 个 batch 中收集统计量,之后固定
# Step 1: 标准化到零均值单位方差
z_normalized = (z_raw - running_mean) / (running_std + 1e-6)
# Step 2: 方差匹配 — 缩放到与表达嵌入相近的量级
z_matched = z_normalized * target_std # target_std 默认 1.0
```
这对应 LatentForcing 中 `dinov2_hf.py` 的归一化:
```python
z = (z - latent_mean) / sqrt(latent_var + eps) * match_pixel_norm
```
---
## 2. 网络架构
### 2.1 核心设计 — 严格参照 LatentForcing CoT (`model_cot.py`)
**LatentForcing 的做法 (model_cot.py:398-446)**:
1. **双流嵌入 element-wise 相加** (line 414):
```python
x = pixel_embedder(x_pixel) + dino_embedder(x_dino)
```
2. **条件向量求和通过 AdaLN** (line 409):
```python
c = t_emb_pixel + t_emb_dino + y_emb
```
3. **共享 Transformer backbone**: 所有 block 处理融合后的 tokens
4. **分离解码头** (line 429-441): `dh_blocks_pixel` + `dh_blocks_dino` 分别解码
**CCFM 的对应实现**:
1. `x = expr_embedder(x_t_expr, gene_emb) + latent_embedder(z_t_latent)`
2. `c = t_expr_emb + t_latent_emb + pert_emb`
3. 复用 scDFM 的 DiffPerceiverBlock / PerceiverBlock
4. ExprDecoder (复用) + LatentDecoder (新增)
### 2.2 CascadedFlowModel 架构 (`src/model/model.py`)
```
输入:
- gene_id: (B, G) 基因 token IDs
- cell_1 (source): (B, G) control 细胞表达值
- x_t: (B, G) 加噪后的扰动细胞表达值 (expression flow)
- z_t: (B, G, 512) 加噪后的 scGPT per-gene 特征 (latent flow)
- t_expr: (B,) 表达流的时间步
- t_latent: (B,) 潜变量流的时间步
- perturbation_id: (B, 2) 扰动 token IDs
数据流 (参照 model_cot.py 的 forward):
┌──────────────────────────────────────────────────────┐
│ 1. 表达流嵌入 (复用 scDFM 的 origin 层) │
│ gene_emb = GeneEncoder(gene_id) (B,G,d) │
│ val_emb_1 = ValueEncoder_1(cell_1) + gene_emb │
│ val_emb_2 = ValueEncoder_2(x_t) + gene_emb │
│ expr_tokens = fusion_layer(cat(val_1, val_2)) │
│ → (B, G, d_model) │
├──────────────────────────────────────────────────────┤
│ 2. Latent 流嵌入 (新增, 对应 dino_embedder) │
│ latent_tokens = LatentEmbedder(z_t) │
│ → (B, G, d_model) [bottleneck: 512 → d_model] │
├──────────────────────────────────────────────────────┤
│ 3. Element-wise 相加 (对应 model_cot.py line 414) │
│ x = expr_tokens + latent_tokens │
│ → (B, G, d_model) │
├──────────────────────────────────────────────────────┤
│ 4. 条件向量 (对应 model_cot.py line 409) │
│ c = t_expr_emb + t_latent_emb + pert_emb │
│ → (B, d_model) │
├──────────────────────────────────────────────────────┤
│ 5. 共享 Backbone (复用 scDFM blocks) │
│ for i, block in enumerate(blocks): │
│ x = gene_adaLN[i](gene_emb, x) │
│ x = cat([x, pert_emb.expand], dim=-1) │
│ x = adapter_layer[i](x) │
│ x = block(x, val_emb_2, c) │
│ → (B, G, d_model) │
├──────────────────────────────────────────────────────┤
│ 6a. 表达解码头 (复用 ExprDecoder) │
│ → pred_v_expr: (B, G) │
├──────────────────────────────────────────────────────┤
│ 6b. Latent 解码头 (新增, 对应 dh_blocks_dino) │
│ latent_feats = dh_latent_proj(x) │
│ for block in dh_blocks_latent: │
│ latent_feats = block(latent_feats, c) │
│ pred_v_latent = latent_final_layer(latent_feats) │
│ → (B, G, 512) │
└──────────────────────────────────────────────────────┘
输出: (pred_v_expr, pred_v_latent)
```
### 2.3 新增模块 (`src/model/layers.py`)
```python
class LatentEmbedder(nn.Module):
"""
对应 LatentForcing 的 dino_embedder (BottleneckPatchEmbed)。
将 per-gene scGPT 特征 (B, G, 512) 投影到 (B, G, d_model)。
"""
def __init__(self, scgpt_dim=512, bottleneck_dim=128, d_model=512):
self.proj = nn.Sequential(
nn.Linear(scgpt_dim, bottleneck_dim),
nn.GELU(),
nn.Linear(bottleneck_dim, d_model),
)
def forward(self, z): # z: (B, G, scgpt_dim)
return self.proj(z) # (B, G, d_model)
class LatentDecoder(nn.Module):
"""
对应 LatentForcing 的 final_layer_dino + dh_blocks_dino。
从 backbone 输出 (B, G, d_model) 解码回 (B, G, scgpt_dim)。
"""
def __init__(self, d_model=512, scgpt_dim=512, dh_depth=2):
# 可选: 额外的 decoder head blocks
if dh_depth > 0:
self.dh_blocks = nn.ModuleList([...])
self.final = nn.Sequential(
nn.LayerNorm(d_model),
nn.Linear(d_model, d_model),
nn.GELU(),
nn.Linear(d_model, scgpt_dim),
)
```
### 2.4 复用的现有模块
| 模块 | 来源 | 文件路径 |
|------|------|---------|
| `TimestepEmbedder` | scDFM | `scDFM/src/models/origin/layers.py:157` |
| `ContinuousValueEncoder` | scDFM | `scDFM/src/models/origin/layers.py:26` |
| `GeneEncoder` | scDFM | `scDFM/src/models/origin/layers.py:55` |
| `BatchLabelEncoder` | scDFM | `scDFM/src/models/origin/layers.py:98` |
| `ExprDecoder` | scDFM | `scDFM/src/models/origin/layers.py:116` |
| `GeneadaLN` | scDFM | `scDFM/src/models/origin/layers.py:10` |
| `DiffPerceiverBlock` / `PerceiverBlock` | scDFM | `scDFM/src/models/origin/model.py:55,92` |
| `modulate` | scDFM | `scDFM/src/models/origin/blocks.py` |
| `AffineProbPath` + `CondOTScheduler` | scDFM | `scDFM/src/flow_matching/path/` |
| `make_lognorm_poisson_noise` | scDFM | `scDFM/src/utils/utils.py` |
| `TransformerModel` | scGPT | `scGPT/scgpt/model/model.py` |
| `GeneVocab` | scGPT | `scGPT/scgpt/tokenizer/gene_tokenizer.py` |
| `load_pretrained` | scGPT | `scGPT/scgpt/utils/util.py` |
| `DataCollator` | scGPT | `scGPT/scgpt/data_collator.py` |
---
## 3. 训练逻辑
### 3.1 CascadedDenoiser (`src/denoiser.py`)
封装 `CascadedFlowModel` + `FrozenScGPTExtractor`
### 3.2 级联时间步采样 — 参照 `denoiser_cot.py:121-132`
```python
def sample_t(self, n, device):
"""
dino_first_cascaded 模式 (denoiser_cot.py line 121-132):
- choose_latent_mask=True → 训练 latent 流
t_latent 随机, t_expr=0, loss_weight_expr=0
- choose_latent_mask=False → 训练 expression 流
t_expr 随机, t_latent=1 (clean latent), loss_weight_latent=0
"""
t_latent = torch.rand(n, device=device)
t_expr = torch.rand(n, device=device)
choose_latent_mask = torch.rand(n, device=device) < self.choose_latent_p
t_latent = torch.where(choose_latent_mask, t_latent, torch.ones_like(t_latent))
t_expr = torch.where(choose_latent_mask, torch.zeros_like(t_expr), t_expr)
w_expr = (~choose_latent_mask).float()
w_latent = choose_latent_mask.float()
return t_expr, t_latent, w_expr, w_latent
```
### 3.3 训练步骤
```python
def train_step(self, source, target, perturbation_id, gene_ids):
B = source.shape[0]
# 1. On-the-fly 提取 scGPT per-gene 特征 (冻结)
z_target = self.scgpt_extractor.extract(target) # (B, G, 512)
# 2. 时间采样
t_expr, t_latent, w_expr, w_latent = self.sample_t(B, device)
# 3. Expression path (同 scDFM)
noise_expr = make_noise(source, noise_type)
path_expr = affine_path.sample(t=t_expr, x_0=noise_expr, x_1=target)
# 4. Latent path
noise_latent = torch.randn_like(z_target)
path_latent = affine_path.sample(
t=t_latent.unsqueeze(-1).unsqueeze(-1), # broadcast to (B,1,1)
x_0=noise_latent, x_1=z_target
)
# 5. Model forward
pred_v_expr, pred_v_latent = model(
gene_ids, source, path_expr.x_t, path_latent.x_t,
t_expr, t_latent, perturbation_id
)
# 6. Losses
loss_expr = ((pred_v_expr - path_expr.dx_t)**2
* w_expr[:, None]).mean()
loss_latent = ((pred_v_latent - path_latent.dx_t)**2
* w_latent[:, None, None]).mean()
loss = loss_expr + latent_weight * loss_latent
# Optional MMD (同 scDFM)
if use_mmd_loss:
x1_hat = path_expr.x_t + pred_v_expr * (1 - t_expr).unsqueeze(-1)
loss += gamma * mmd_loss(x1_hat, target)
return loss
```
### 3.4 训练入口 (`scripts/run_cascaded.py`)
基于 scDFM 的 `run.py` 改造:
- 初始化 `FrozenScGPTExtractor` + `CascadedFlowModel`
- 封装进 `CascadedDenoiser`
- 训练循环: 使用 `denoiser.train_step()` 替代 `train_step()`
- 评估: 使用 `denoiser.generate()` + `MetricsEvaluator`
- 其余(optimizer, scheduler, checkpoint)保持不变
---
## 4. 推理逻辑 — 两阶段级联生成
参照 LatentForcing `denoiser_cot.py:224-247`:
```python
@torch.no_grad()
def generate(self, source, perturbation_id, gene_ids,
latent_steps=20, expr_steps=20):
B = source.shape[0]
G = source.shape[1]
# ═══ Stage 1: 生成 Latent (per-gene scGPT features) ═══
# t_latent: 0→1, t_expr=0 (表达流不参与)
z_noise = torch.randn(B, G, scgpt_dim, device=device)
def latent_vf(t, z_t):
t_latent = t.expand(B)
t_expr = torch.zeros(B, device=device)
_, v_latent = model(gene_ids, source, source, z_t,
t_expr, t_latent, perturbation_id)
return v_latent
z_generated = torchdiffeq.odeint(
latent_vf, z_noise,
torch.linspace(0, 1, latent_steps, device=device),
method='rk4'
)[-1] # (B, G, 512)
# ═══ Stage 2: 用生成的 Latent 引导生成表达谱 ═══
# t_expr: 0→1, t_latent=1 (latent "clean")
expr_noise = make_noise(source, noise_type)
def expr_vf(t, x_t):
t_expr = t.expand(B)
t_latent = torch.ones(B, device=device)
v_expr, _ = model(gene_ids, source, x_t, z_generated,
t_expr, t_latent, perturbation_id)
return v_expr
x_generated = torchdiffeq.odeint(
expr_vf, expr_noise,
torch.linspace(0, 1, expr_steps, device=device),
method='rk4'
)[-1] # (B, G)
return torch.clamp(x_generated, min=0)
```
**关键设计** (与 LatentForcing 的 `dino_first_cascaded` 推理完全对应):
- Stage 1: `t_expr=0` → 表达流为纯噪声,模型聚焦 latent 预测
- Stage 2: `t_latent=1` → latent 已解析,`z_generated` 通过 `LatentEmbedder` 投影后与表达 tokens 相加,引导表达生成
- 评估: 复用 scDFM 的 `test()` 函数结构 + `cell-eval MetricsEvaluator`
---
## 5. 配置 (`config/config_cascaded.py`)
```python
@dataclass
class CascadedFlowConfig:
# === 基础 (同 scDFM FlowConfig) ===
model_type: str = 'cascaded'
batch_size: int = 48
d_model: int = 128
nhead: int = 8
nlayers: int = 4
lr: float = 5e-5
steps: int = 200000
eta_min: float = 1e-6
data_name: str = 'norman'
fusion_method: str = 'differential_perceiver'
perturbation_function: str = 'crisper'
noise_type: str = 'Gaussian'
infer_top_gene: int = 1000
n_top_genes: int = 5000
print_every: int = 5000
gamma: float = 0.5
use_mmd_loss: bool = True
split_method: str = 'additive'
fold: int = 1
# === 级联/Latent 特有 ===
scgpt_dim: int = 512 # scGPT embedding 维度
bottleneck_dim: int = 128 # LatentEmbedder 瓶颈维度
latent_weight: float = 1.0 # latent 流损失权重
choose_latent_p: float = 0.4 # 训练 latent 流的概率
target_std: float = 1.0 # 方差匹配目标标准差
dh_depth: int = 2 # latent decoder head 层数
# === scGPT 路径 ===
scgpt_model_dir: str = 'transfer/data/scGPT_pretrained'
# === 推理 ===
latent_steps: int = 20
expr_steps: int = 20
```
---
## 6. 实现顺序
### Step 1: 项目初始化 + 下载 scGPT
- 创建 `transfer/code/CCFM/` 目录结构
- 下载 scGPT `whole-human` 预训练模型
- 验证: 加载 scGPT 模型成功
### Step 2: FrozenScGPTExtractor
- 实现 `src/data/scgpt_extractor.py`
- 处理 scDFM ↔ scGPT 的基因名对齐
- 实现 per-gene feature scatter 和归一化
- 验证: 输入 (48, 1000) expression → 输出 (48, 1000, 512) features
### Step 3: 数据加载
- 实现 `src/data/data.py`,复用 scDFM 的 Data 类
- 验证: DataLoader 正确返回 expression + perturbation_id
### Step 4: CascadedFlowModel
- 实现 `src/model/model.py` 和 `src/model/layers.py`
- 验证: dummy forward pass → (pred_v_expr, pred_v_latent) 形状正确
### Step 5: CascadedDenoiser
- 实现 `src/denoiser.py`
- 验证: `train_step()` 返回 scalar loss, `generate()` 返回正确形状
### Step 6: 训练入口 + 配置
- 实现 `scripts/run_cascaded.py` + `config/config_cascaded.py`
- 编写 `run.sh` (pjsub 脚本)
- 验证: 完整训练循环运行,loss 下降
### Step 7: 端到端验证
- Norman 数据集上训练(先小 step 数)
- 检查 loss_expr 和 loss_latent 分别下降
- 推理并通过 cell-eval 评估
- 与 baseline scDFM 对比
---
## 7. 关键技术决策
| 决策点 | 选择 | 理由 |
|--------|------|------|
| Latent 注入方式 | Element-wise add (token-level) | 严格对标 LatentForcing `model_cot.py:414` |
| 条件注入 | AdaLN (c = sum of all embeddings) | 对标 `model_cot.py:409` |
| scGPT 特征提取 | On-the-fly (冻结) | 存储不可行 (~1TB); 对标 LatentForcing 冻结 DINO-v2 |
| 时间步采样 | dino_first_cascaded | 对标 `denoiser_cot.py:121-132` |
| 方差匹配 | 全局 running statistics + scaling | 对标 `dinov2_hf.py` 的归一化 |
| Backbone | 复用 scDFM 的 DiffPerceiver/Perceiver | 保持底盘一致 |
| 解码头 | 分离: ExprDecoder + LatentDecoder | 对标 `model_cot.py:429-441` 的分离头 |