Skip to main content

GeneFlowDecoder

z → X 的细胞状态解码器:Gene Transformer + Conditional Rectified Flow (CFM), 把固定的细胞表征 z 解码成 log1p 归一化表达谱 X。

设计目标:接口极简、可复现、单卡可跑 2 万+ 基因面板;z 默认冻结, 不参与反传,也不被优化器更新。

from geneflowdecoder import GeneFlowDecoder

model = GeneFlowDecoder(n_genes=2048, z_dim=256, d=512, depth=8)

model.fit(X_train, z_train,               # X: [N, G] log1p; z: [N, D]
          X_val=X_val, z_val=z_val,       # 可选,开启早停
          epochs=200, batch_size=64)

X_hat = model(z_test)           # 采样(生成式,log1p 空间)
X_hat = model(z_test, steps=8, deterministic=False)

X_rec = model.predict(z_test)  # 确定性还原:NB 均值

快速基线解码器:FastDecoder

当不需要流匹配的迭代积分、只想“z 直接还原 log1p 表达”时(插值、z 空间检索、 基线对比、sanity check),用 FastDecoder:单次 MLP 前向,无 ODE、无时间嵌入、 无梯度检查点,训练与推理都比 flow 模型快 1–2 个数量级。

它与 GeneFlowDecoder 完全独立、互不影响,只是同一个包里的另一条解码路径。 输出尺度一致:log1p 表达谱。

from geneflowdecoder import FastDecoder, FastDecoderConfig
import numpy as np, scipy.sparse as sp

# 一次性转稠密 + 连续内存(稀疏矩阵直接喂会慢)
Xtr = np.ascontiguousarray(
    adata.X.toarray() if sp.isspmatrix(adata.X) else adata.X, dtype=np.float32)
ztr = np.ascontiguousarray(adata.obsm['X_latent'], dtype=np.float32)

cfg = FastDecoderConfig(
    z_dim=ztr.shape[1], n_genes=Xtr.shape[1],
    hidden_dim=256, depth=2,       # 通常 1~2 层就够
    nb_dispersion=False,           # 需要 NB 似然就改 True
)
dec = FastDecoder(cfg, device='cuda' if __import__('torch').cuda.is_available() else 'cpu')

# 训练:z -> log1p(X),默认 MSE(对数域最稳),可选 loss='nb'
dec.fit(ztr, Xtr, epochs=200, batch_size=1024, lr=1e-3, verbose=1)

# 推理:任意 z 秒出 log-normalized 表达(自动分 chunk,不爆显存)
X_hat = dec.predict(some_z)        # numpy [N, G]

FastDecoderConfig

参数 默认 说明
z_dim — 细胞状态 z 的维度
n_genes — 输出基因数 G
hidden_dim 256 MLP 隐层宽度(逐基因独立缩放/偏置另计)
depth 2 MLP 层数
dropout 0.0 dropout,训练样本少时可开
nb_dispersion False 开则多一个逐基因 dispersion 参数,可用 NB NLL 训练
gene_wise_scale True 每个基因独立缩放+偏置,log1p 数据几乎必开
device "auto" "auto" / "cuda" / "cpu"

方法速览

方法 说明
dec.fit(z, X, *, epochs=200, batch_size=256, lr=1e-3, loss='mse', patience=20, verbose=1) 拟合;loss='mse'|'nb';给了早停自动回滚最优权重
dec(z) -> Tensor 前向,返回 log1p 预测 [N, G]
dec.predict(z, *, batch_size=512) -> ndarray 分块推理,返回 numpy
dec.nb_nll(z, X) -> Tensor NB 负对数似然(仅 nb_dispersion=True)
dec.save(path) / FastDecoder.load(path, device="auto") 权重存取

什么时候用哪个

需求 选哪个
只要 z→表达的快速还原 / 基线 / 检索 FastDecoder
想验证“z 里到底有没有表达信息” 先跑 FastDecoder,MSE 都降不动就是 z 或数据的问题
需要生成式采样、流形插值、精细表达分布 GeneFlowDecoder

安装

# 从源码(开发模式)
git clone https://github.com/your-org/geneflowdecoder.git
cd geneflowdecoder
pip install -e .[dev]

# 或构建 wheel 后安装
python -m build
pip install dist/geneflowdecoder-0.1.0-py3-none-any.whl

依赖:torch >= 2.1、numpy >= 1.24。没有 GPU 也能在 CPU 上跑(只是慢)。


API

GeneFlowDecoder(...)

参数 默认 说明
n_genes — 基因数,即输出维度 G
z_dim — 细胞状态 z 的维度
d 768 Transformer 宽度
depth 16 Transformer 层数
n_heads 12 注意力头数
chunk_size 2048 基因轴分块,控制显存峰值
gradient_checkpoint True 激活检查点,省显存
cfg FlowConfig() flow / loss 超参
freeze_z True z 全程 detach,只读条件
device "auto" "auto" / "cuda" / "cpu"

model.fit(X, z, *, X_val=None, z_val=None, epochs=200, batch_size=64, lr=2e-4, weight_decay=0.02, patience=20, num_workers=0, verbose=1) -> self

  • X / X_val:[N, G] log1p 表达,numpy 或 torch 都行
  • z / z_val:[N, z_dim];freeze_z=True 时绝不会被修改或反传
  • 给了验证集 → 早停 + 自动回滚最优权重

model(z, *, steps=4, method="midpoint", deterministic=False) -> Tensor

Flow 采样,steps=4 通常够用。

model.predict(z) -> Tensor

确定性输出 E[X] 的 log1p(NB mean)。转伪计数:(log_mu.exp() - 1).clamp(min=0)。

model.save(path) / GeneFlowDecoder.load(path, device="auto")


FlowConfig

from geneflowdecoder import FlowConfig

cfg = FlowConfig(
    sigma_min=1e-4,     # t 的截断,防 t≈0 数值爆炸
    nb_weight=1.0,      # NB 似然辅助损失权重
    corr_weight=0.1,    # cell-wise Pearson 相关性正则
)
model = GeneFlowDecoder(n_genes=G, z_dim=D, cfg=cfg)

发布

python -m build          # 生成 sdist + wheel 到 dist/
twine check dist/*       # 校验元数据
twine upload dist/*      # 发布到 PyPI(需账号 token)

目录结构

geneflowdecoder/
├── pyproject.toml
├── README.md
├── LICENSE
├── src/geneflowdecoder/
│   ├── __init__.py        # 公开 API
│   ├── _core.py           # GeneFlowDecoder:flow 模型 + fit/forward/predict
│   ├── _fastdec.py        # FastDecoder:确定性 MLP 解码器
│   └── _version.py
└── tests/
    ├── test_api.py
    └── test_fastdec.py    # FastDecoder 形状契约与收敛测试

License

MIT

Metadata

Release files for geneflowdecoder 0.2.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for geneflowdecoder 0.2.2
File Size Uploaded Provenance Actions
geneflowdecoder-0.2.2.tar.gz 23.3 kB Without provenance Details for geneflowdecoder-0.2.2.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for geneflowdecoder 0.2.2
File Interpreter ABI Platform Actions
geneflowdecoder-0.2.2-py3-none-any.whl Python 3 none any Details for geneflowdecoder-0.2.2-py3-none-any.whl

Total release size: 43.8 kB

Release files / geneflowdecoder-0.2.2.tar.gz

Download URL geneflowdecoder-0.2.2.tar.gz
Size 23.3 kB
Tags Source
SHA-256 checksum
How to use checksums
b17bb4bcb6182430e5f1b342050fd4b746230a94b3096a57f53799c0fc179c1e
BLAKE2b-256 checksum
How to use checksums
9605f2334626b4a270dcb97e8f192f94a6ef1b0b4715b86c3c1b50e152e73bef
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.10.18

Release files / geneflowdecoder-0.2.2-py3-none-any.whl

Download URL geneflowdecoder-0.2.2-py3-none-any.whl
Size 20.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
2b645c857a65a21702e1fdf3bc147f3903a97b51ab83b378f414f9eecfedd17c
BLAKE2b-256 checksum
How to use checksums
85c5604488917016d21231f9b01b3ff0b75fadce5cc5db764722d8cfe1ebd5b2
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.10.18

Security for geneflowdecoder 0.2.2

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page