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.1
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| geneflowdecoder-0.2.1.tar.gz | 20.6 kB | Without provenance | Details for geneflowdecoder-0.2.1.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| geneflowdecoder-0.2.1-py3-none-any.whl | Python 3 | none | any | Details for geneflowdecoder-0.2.1-py3-none-any.whl |
Total release size: 37.5 kB
Release files / geneflowdecoder-0.2.1.tar.gz
| Download URL | geneflowdecoder-0.2.1.tar.gz |
|---|---|
| Size | 20.6 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
12d5ad29fbeaa859bc4f461f478397e548a265937c3ed8cfa5d6d5f90f717d74
|
|
BLAKE2b-256 checksum How to use checksums |
23a40519c17d906918fc28d2fbdc093c0ae6805dd5dc703d60a2b1b3b64a00cf
|
| 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.1-py3-none-any.whl
| Download URL | geneflowdecoder-0.2.1-py3-none-any.whl |
|---|---|
| Size | 17.0 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
a0cd72ae6e97b6f3c16a8c08f6575dd466f87dbe935f32c6cec2e40ae84b86fa
|
|
BLAKE2b-256 checksum How to use checksums |
af0be20a3d5a142c1797965af807633c958a3a997bad9ca652b7889844bad07e
|
| 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.1
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.