regdiffusion 0.2.1__tar.gz → 0.2.3__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {regdiffusion-0.2.1 → regdiffusion-0.2.3}/.gitignore +2 -0
- regdiffusion-0.2.3/NEWS.md +43 -0
- {regdiffusion-0.2.1 → regdiffusion-0.2.3}/PKG-INFO +2 -4
- {regdiffusion-0.2.1 → regdiffusion-0.2.3}/README.md +1 -3
- {regdiffusion-0.2.1 → regdiffusion-0.2.3}/pyproject.toml +1 -1
- {regdiffusion-0.2.1 → regdiffusion-0.2.3}/regdiffusion/__init__.py +3 -3
- {regdiffusion-0.2.1 → regdiffusion-0.2.3}/regdiffusion/cli.py +7 -1
- {regdiffusion-0.2.1 → regdiffusion-0.2.3}/regdiffusion/data/beeline.py +9 -9
- {regdiffusion-0.2.1 → regdiffusion-0.2.3}/regdiffusion/data/microglia.py +5 -6
- {regdiffusion-0.2.1 → regdiffusion-0.2.3}/regdiffusion/data/utils.py +1 -1
- {regdiffusion-0.2.1 → regdiffusion-0.2.3}/regdiffusion/evaluator.py +10 -0
- {regdiffusion-0.2.1 → regdiffusion-0.2.3}/regdiffusion/grn.py +37 -37
- {regdiffusion-0.2.1 → regdiffusion-0.2.3}/regdiffusion/logger.py +13 -0
- {regdiffusion-0.2.1 → regdiffusion-0.2.3}/regdiffusion/models/regdiffusion.py +43 -19
- {regdiffusion-0.2.1 → regdiffusion-0.2.3}/regdiffusion/models/regdiffusion_me.py +40 -21
- {regdiffusion-0.2.1 → regdiffusion-0.2.3}/regdiffusion/trainer.py +101 -51
- regdiffusion-0.2.1/NEWS.md +0 -24
- {regdiffusion-0.2.1 → regdiffusion-0.2.3}/.github/workflows/documentation.yml +0 -0
- {regdiffusion-0.2.1 → regdiffusion-0.2.3}/LICENSE +0 -0
- {regdiffusion-0.2.1 → regdiffusion-0.2.3}/docs/.gitignore +0 -0
- {regdiffusion-0.2.1 → regdiffusion-0.2.3}/docs/BUILD.md +0 -0
- {regdiffusion-0.2.1 → regdiffusion-0.2.3}/docs/Makefile +0 -0
- {regdiffusion-0.2.1 → regdiffusion-0.2.3}/docs/REG_PySCENIC.ipynb +0 -0
- {regdiffusion-0.2.1 → regdiffusion-0.2.3}/docs/_static/rd_logo_horizontal.png +0 -0
- {regdiffusion-0.2.1 → regdiffusion-0.2.3}/docs/_static/rd_logo_horizontal@2x.png +0 -0
- {regdiffusion-0.2.1 → regdiffusion-0.2.3}/docs/_static/regdiffusion.png +0 -0
- {regdiffusion-0.2.1 → regdiffusion-0.2.3}/docs/_static/regdiffusion@2x.png +0 -0
- {regdiffusion-0.2.1 → regdiffusion-0.2.3}/docs/_templates/autosummary/class.rst +0 -0
- {regdiffusion-0.2.1 → regdiffusion-0.2.3}/docs/_templates/autosummary/classnoinheritance.rst +0 -0
- {regdiffusion-0.2.1 → regdiffusion-0.2.3}/docs/conf.py +0 -0
- {regdiffusion-0.2.1 → regdiffusion-0.2.3}/docs/data_module.rst +0 -0
- {regdiffusion-0.2.1 → regdiffusion-0.2.3}/docs/downstream_with_pyscenic.md +0 -0
- {regdiffusion-0.2.1 → regdiffusion-0.2.3}/docs/index.rst +0 -0
- {regdiffusion-0.2.1 → regdiffusion-0.2.3}/docs/large_networks.md +0 -0
- {regdiffusion-0.2.1 → regdiffusion-0.2.3}/docs/main_api.rst +0 -0
- {regdiffusion-0.2.1 → regdiffusion-0.2.3}/docs/make.bat +0 -0
- {regdiffusion-0.2.1 → regdiffusion-0.2.3}/docs/models.rst +0 -0
- {regdiffusion-0.2.1 → regdiffusion-0.2.3}/docs/quick_tour.md +0 -0
- {regdiffusion-0.2.1 → regdiffusion-0.2.3}/docs/supplements/googled258341a97f33073.html +0 -0
- {regdiffusion-0.2.1 → regdiffusion-0.2.3}/docs/supplements/rd_hammond_Cx3cr1.html +0 -0
- {regdiffusion-0.2.1 → regdiffusion-0.2.3}/docs/supplements/rd_hammond_Fcrls.html +0 -0
- {regdiffusion-0.2.1 → regdiffusion-0.2.3}/docs/supplements/rd_hammond_Hexb.html +0 -0
- {regdiffusion-0.2.1 → regdiffusion-0.2.3}/docs/supplements/rd_hammond_Mertk.html +0 -0
- {regdiffusion-0.2.1 → regdiffusion-0.2.3}/docs/supplements/rd_hammond_P2ry12.html +0 -0
- {regdiffusion-0.2.1 → regdiffusion-0.2.3}/docs/supplements/rd_hammond_Pros1.html +0 -0
- {regdiffusion-0.2.1 → regdiffusion-0.2.3}/docs/supplements/rd_hammond_Sall1.html +0 -0
- {regdiffusion-0.2.1 → regdiffusion-0.2.3}/docs/supplements/rd_hammond_Siglech.html +0 -0
- {regdiffusion-0.2.1 → regdiffusion-0.2.3}/docs/supplements/rd_hammond_Tmem119.html +0 -0
- {regdiffusion-0.2.1 → regdiffusion-0.2.3}/docs/supplements/rd_hammond_Trem2.html +0 -0
- {regdiffusion-0.2.1 → regdiffusion-0.2.3}/docs/supplements.rst +0 -0
- {regdiffusion-0.2.1 → regdiffusion-0.2.3}/example.ipynb +0 -0
- {regdiffusion-0.2.1 → regdiffusion-0.2.3}/regdiffusion/data/__init__.py +0 -0
- {regdiffusion-0.2.1 → regdiffusion-0.2.3}/regdiffusion/models/__init__.py +0 -0
- {regdiffusion-0.2.1 → regdiffusion-0.2.3}/regdiffusion/plot/__init__.py +0 -0
- {regdiffusion-0.2.1 → regdiffusion-0.2.3}/regdiffusion/plot/pyvis.py +0 -0
- {regdiffusion-0.2.1 → regdiffusion-0.2.3}/regdiffusion/plot/static.py +0 -0
- {regdiffusion-0.2.1 → regdiffusion-0.2.3}/resources/apoe_net.png +0 -0
- {regdiffusion-0.2.1 → regdiffusion-0.2.3}/resources/aucell_mtx.png +0 -0
- {regdiffusion-0.2.1 → regdiffusion-0.2.3}/resources/aucell_umap.png +0 -0
- {regdiffusion-0.2.1 → regdiffusion-0.2.3}/resources/biomarkers.png +0 -0
- {regdiffusion-0.2.1 → regdiffusion-0.2.3}/resources/cellnames.png +0 -0
- {regdiffusion-0.2.1 → regdiffusion-0.2.3}/resources/edgelist.png +0 -0
- {regdiffusion-0.2.1 → regdiffusion-0.2.3}/resources/heatmap.png +0 -0
- {regdiffusion-0.2.1 → regdiffusion-0.2.3}/resources/mecs.png +0 -0
- {regdiffusion-0.2.1 → regdiffusion-0.2.3}/resources/mecs_cluster.png +0 -0
- {regdiffusion-0.2.1 → regdiffusion-0.2.3}/resources/regdiffusion_structure.png +0 -0
- {regdiffusion-0.2.1 → regdiffusion-0.2.3}/resources/regulon_scores.png +0 -0
- {regdiffusion-0.2.1 → regdiffusion-0.2.3}/resources/shinygo.png +0 -0
- {regdiffusion-0.2.1 → regdiffusion-0.2.3}/resources/umap_comparison.png +0 -0
- {regdiffusion-0.2.1 → regdiffusion-0.2.3}/test_scripts/test_beeline_benchmark.py +0 -0
- {regdiffusion-0.2.1 → regdiffusion-0.2.3}/test_scripts/test_beeline_worker.py +0 -0
- {regdiffusion-0.2.1 → regdiffusion-0.2.3}/test_scripts/test_memory_benchmark.py +0 -0
- {regdiffusion-0.2.1 → regdiffusion-0.2.3}/test_scripts/test_sparse_support.py +0 -0
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
# RegDiffusion News / Changelog
|
|
2
|
+
|
|
3
|
+
## 0.2.3 [unreleased]
|
|
4
|
+
|
|
5
|
+
### New Features
|
|
6
|
+
- Added a `seed` argument to `RegDiffusionTrainer` for fully reproducible runs. When set, Python, NumPy, and PyTorch RNGs are seeded and cuDNN is put in deterministic mode. Two runs with the same seed now produce bit-identical adjacency matrices, verified across separate processes and under AMP, `torch.compile`, gradient accumulation, and `train_split < 1.0`. Without a seed (the default), runs remain non-deterministic.
|
|
7
|
+
|
|
8
|
+
### Bug Fixes
|
|
9
|
+
- Fixed `RegDiffusionTrainer.train(n_steps=...)` silently ignoring its argument. Both the normal and gradient-accumulation branches hardcoded `n_steps=None`, so training always ran for the `n_steps` given at initialization.
|
|
10
|
+
- Fixed the L1 sparsity penalty being computed on *signed* adjacency values in the base `RegDiffusion` model. Soft thresholding preserves sign, so the penalty could in principle be reduced by making inhibitory (negative) edges more negative. Both models now share a single `get_sparse_loss()` that takes the mean absolute value over off-diagonal entries. In practice this does not change results — negative entries land in the soft-threshold dead zone, where both the output and its gradient are zero — and BEELINE metrics are unchanged; the penalty is now correct by construction rather than by accident.
|
|
11
|
+
- `RegDiffusionME.get_sampled_sparse_loss()` is renamed to `get_sparse_loss()` and now excludes diagonal samples, matching the base model, whose `get_adj_()` masks the diagonal.
|
|
12
|
+
- Registered the sampled adjacency index tensors (`sampled_adj_row/col_nonparam`) as buffers instead of `nn.Parameter`. These are integer indices, not learnable weights, and they no longer appear in `model.parameters()`. `state_dict` keys are unchanged, so existing checkpoints still load.
|
|
13
|
+
- The sparse loss is no longer computed during the warmup window, where it is discarded.
|
|
14
|
+
- Extended the `tqdm.auto` progress-bar fix from 0.2.2 (which covered `trainer.py`) to the remaining progress bars in `grn.py` and the `data` module, so dataset downloads and edgelist extraction also render properly in notebooks.
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
## 0.2.2
|
|
18
|
+
|
|
19
|
+
- Avoid large progress printing in terminal
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
## 0.2.1
|
|
23
|
+
|
|
24
|
+
### New Features
|
|
25
|
+
- Added sparse matrix support for `RegDiffusionTrainer`. The `exp_array` argument now accepts scipy sparse matrices (e.g. `adata.X`) directly. Normalization statistics are computed in chunks and each sample is normalized on-the-fly during training, so the full dense matrix is never materialized. This enables training on datasets with 1M+ cells without excessive memory usage.
|
|
26
|
+
- Updated CLI (`regdiffusion` command) to handle sparse `adata.X` from H5AD files, including sparse-safe data validation and log-transform via `log1p` on non-zero entries.
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
## 0.2.0
|
|
30
|
+
|
|
31
|
+
### Memory Optimization
|
|
32
|
+
- Removed three `(n_gene, n_gene)` helper matrices (`zeros_nonparam`, `eye_nonparam`, `mask_nonparam`) from `RegDiffusion`, replacing them with inline computations. Saves ~4.8 GB persistent GPU memory for 20K genes with no impact on model accuracy.
|
|
33
|
+
|
|
34
|
+
### New Features
|
|
35
|
+
- Added `RegDiffusionME`, a memory-efficient model variant enabled via `memory_efficient=True` in `RegDiffusionTrainer`. Reduces peak GPU memory by ~45% with no impact on accuracy. Uses a custom autograd function for soft thresholding (boolean masks instead of float32 tensors) and sampled sparse loss (avoids materializing full adjacency matrix for L1 regularization). Benchmarked on all 7 BEELINE datasets with identical AUROC/AUPRR/EPR.
|
|
36
|
+
- Added automatic mixed precision (AMP) support via `use_amp=True` in `RegDiffusionTrainer`. Uses bfloat16 for forward pass and loss computation, reducing memory for autograd-saved activations while keeping model parameters in float32. Requires Ampere or newer GPU.
|
|
37
|
+
|
|
38
|
+
### Bug Fixes
|
|
39
|
+
- Fixed `I_minus_A()` using `self.train` instead of `self.training`, causing dropout to always apply during inference
|
|
40
|
+
- Fixed missing `self` parameter in `GRN.remove_weak_edges()`
|
|
41
|
+
- Fixed `GRN.get_edgelist()` incorrectly passing `self` to `extract_edgelist()`
|
|
42
|
+
- Fixed external logger not being assigned in `RegDiffusionTrainer.__init__()`
|
|
43
|
+
- Fixed `forward()` crash when `n_celltype=None` by adding conditional cell type embedding
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: regdiffusion
|
|
3
|
-
Version: 0.2.
|
|
3
|
+
Version: 0.2.3
|
|
4
4
|
Summary: Gene Regulatory Networks Inference using diffusion model
|
|
5
5
|
Author-email: Hao Zhu <haozhu233@gmail.com>, Donna Slonim <donna.slonim@tufts.edu>
|
|
6
6
|
Maintainer-email: Hao Zhu <haozhu233@gmail.com>
|
|
@@ -23,7 +23,7 @@ Project-URL: Home, https://github.com/TuftsBCB/RegDiffusion
|
|
|
23
23
|
[](https://pepy.tech/project/regdiffusion)
|
|
24
24
|

|
|
25
25
|
|
|
26
|
-
RegDiffusion is a very fast unsupervised regulatory network inference algorithm (just like GENIE3 and GRNBoost2), based on probabilistic diffusion model. It works well on genes and is capable to rapidly (<5min) predict biologically verifiable links from large single cell RNA-seq data with
|
|
26
|
+
RegDiffusion is a very fast unsupervised regulatory network inference algorithm (just like GENIE3 and GRNBoost2), based on probabilistic diffusion model. It works well on genes and is capable to rapidly (<5min) predict biologically verifiable links from large single cell RNA-seq data with 40,000+ genes.
|
|
27
27
|
|
|
28
28
|
```
|
|
29
29
|
Zhu H, Slonim D. From Noise to Knowledge: Diffusion Probabilistic Model-Based Neural Inference of Gene Regulatory Networks. J Comput Biol. 2024 Nov;31(11):1087-1103. doi: 10.1089/cmb.2024.0607. Epub 2024 Oct 10. PMID: 39387266; PMCID: PMC11698671.
|
|
@@ -43,8 +43,6 @@ Check out [this tutorial](https://tuftsbcb.github.io/RegDiffusion/quick_tour.htm
|
|
|
43
43
|
- **Memory-efficient mode**: Set `memory_efficient=True` in `RegDiffusionTrainer` to reduce peak GPU memory by ~45%, making it easier to work with large gene sets on consumer GPUs (You can now fit 20k genes on a 16GB GPU).
|
|
44
44
|
- **Sparse matrix support**: `RegDiffusionTrainer` now accepts scipy sparse matrices directly (e.g., `adata.X`), enabling training on datasets with 1M+ cells without excessive memory usage.
|
|
45
45
|
|
|
46
|
-

|
|
47
|
-
|
|
48
46
|
## Inferred Networks from RegDiffusion
|
|
49
47
|
Here are two examples of inferred networks from regdiffusion. The networks are coherent with existing literature and across datasets.
|
|
50
48
|
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
[](https://pepy.tech/project/regdiffusion)
|
|
5
5
|

|
|
6
6
|
|
|
7
|
-
RegDiffusion is a very fast unsupervised regulatory network inference algorithm (just like GENIE3 and GRNBoost2), based on probabilistic diffusion model. It works well on genes and is capable to rapidly (<5min) predict biologically verifiable links from large single cell RNA-seq data with
|
|
7
|
+
RegDiffusion is a very fast unsupervised regulatory network inference algorithm (just like GENIE3 and GRNBoost2), based on probabilistic diffusion model. It works well on genes and is capable to rapidly (<5min) predict biologically verifiable links from large single cell RNA-seq data with 40,000+ genes.
|
|
8
8
|
|
|
9
9
|
```
|
|
10
10
|
Zhu H, Slonim D. From Noise to Knowledge: Diffusion Probabilistic Model-Based Neural Inference of Gene Regulatory Networks. J Comput Biol. 2024 Nov;31(11):1087-1103. doi: 10.1089/cmb.2024.0607. Epub 2024 Oct 10. PMID: 39387266; PMCID: PMC11698671.
|
|
@@ -24,8 +24,6 @@ Check out [this tutorial](https://tuftsbcb.github.io/RegDiffusion/quick_tour.htm
|
|
|
24
24
|
- **Memory-efficient mode**: Set `memory_efficient=True` in `RegDiffusionTrainer` to reduce peak GPU memory by ~45%, making it easier to work with large gene sets on consumer GPUs (You can now fit 20k genes on a 16GB GPU).
|
|
25
25
|
- **Sparse matrix support**: `RegDiffusionTrainer` now accepts scipy sparse matrices directly (e.g., `adata.X`), enabling training on datasets with 1M+ cells without excessive memory usage.
|
|
26
26
|
|
|
27
|
-

|
|
28
|
-
|
|
29
27
|
## Inferred Networks from RegDiffusion
|
|
30
28
|
Here are two examples of inferred networks from regdiffusion. The networks are coherent with existing literature and across datasets.
|
|
31
29
|
|
|
@@ -13,7 +13,7 @@ maintainers = [
|
|
|
13
13
|
]
|
|
14
14
|
readme = "README.md"
|
|
15
15
|
license = {file = "LICENSE"}
|
|
16
|
-
version = "0.2.
|
|
16
|
+
version = "0.2.3"
|
|
17
17
|
description = "Gene Regulatory Networks Inference using diffusion model"
|
|
18
18
|
|
|
19
19
|
classifiers = ["License :: OSI Approved :: Apache Software License"]
|
|
@@ -6,10 +6,10 @@ from . import models
|
|
|
6
6
|
from . import plot
|
|
7
7
|
|
|
8
8
|
from .logger import LightLogger, load_logger
|
|
9
|
-
from .trainer import RegDiffusionTrainer
|
|
9
|
+
from .trainer import RegDiffusionTrainer, set_seed
|
|
10
10
|
from .grn import GRN, read_hdf5
|
|
11
11
|
from .evaluator import GRNEvaluator
|
|
12
12
|
|
|
13
|
-
__all__ = ['data', 'models', 'plot', 'LightLogger', 'load_logger',
|
|
14
|
-
'RegDiffusionTrainer', 'GRN', 'read_hdf5', 'GRNEvaluator']
|
|
13
|
+
__all__ = ['data', 'models', 'plot', 'LightLogger', 'load_logger',
|
|
14
|
+
'RegDiffusionTrainer', 'set_seed', 'GRN', 'read_hdf5', 'GRNEvaluator']
|
|
15
15
|
|
|
@@ -36,6 +36,12 @@ def main():
|
|
|
36
36
|
default=4,
|
|
37
37
|
help="Number of workers to use for edgelist extraction. Default: 4"
|
|
38
38
|
)
|
|
39
|
+
parser.add_argument(
|
|
40
|
+
"--seed",
|
|
41
|
+
type=int,
|
|
42
|
+
default=None,
|
|
43
|
+
help="Random seed for reproducible results. Default: None"
|
|
44
|
+
)
|
|
39
45
|
|
|
40
46
|
args = parser.parse_args()
|
|
41
47
|
|
|
@@ -65,7 +71,7 @@ def main():
|
|
|
65
71
|
x = np.log(x + 1.0)
|
|
66
72
|
|
|
67
73
|
print("Initializing RegDiffusion trainer and starting training...")
|
|
68
|
-
rd_trainer = RegDiffusionTrainer(x)
|
|
74
|
+
rd_trainer = RegDiffusionTrainer(x, seed=args.seed)
|
|
69
75
|
rd_trainer.train()
|
|
70
76
|
|
|
71
77
|
grn = rd_trainer.get_grn(
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import numpy as np
|
|
2
2
|
import scanpy as sc
|
|
3
3
|
import pandas as pd
|
|
4
|
-
from tqdm import tqdm
|
|
4
|
+
from tqdm.auto import tqdm
|
|
5
5
|
import zipfile
|
|
6
6
|
import os
|
|
7
7
|
from .utils import download_file
|
|
@@ -47,14 +47,14 @@ def load_beeline(data_dir='data', benchmark_data='hESC',
|
|
|
47
47
|
|
|
48
48
|
Args:
|
|
49
49
|
data_dir (str): Parent directory to save and load the data. If the path
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
benchmark_data (str): Benchmark datasets. Choose among "hESC", "hHep",
|
|
53
|
-
|
|
54
|
-
benchmark_setting (str): Benchmark settings. Choose among "500_STRING",
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
50
|
+
does not exist, it will be created. Data will be saved in a
|
|
51
|
+
subdirectory under the provided path.
|
|
52
|
+
benchmark_data (str): Benchmark datasets. Choose among "hESC", "hHep",
|
|
53
|
+
"mDC", "mESC", "mHSC", "mHSC-GM", and "mHSC-L".
|
|
54
|
+
benchmark_setting (str): Benchmark settings. Choose among "500_STRING",
|
|
55
|
+
"1000_STRING", "500_Non-ChIP", "1000_Non-ChIP", "500_ChIP-seq",
|
|
56
|
+
"1000_ChIP-seq", "500_lofgof", and "1000_lofgof". If either of the
|
|
57
|
+
"lofgof" settings is chosen, only "mESC" data is available.
|
|
58
58
|
|
|
59
59
|
Returns:
|
|
60
60
|
tuple: A tuple containing two objects for a single BEELINE benchmark.
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import numpy as np
|
|
2
2
|
import scanpy as sc
|
|
3
3
|
import pandas as pd
|
|
4
|
-
from tqdm import tqdm
|
|
4
|
+
from tqdm.auto import tqdm
|
|
5
5
|
import zipfile
|
|
6
6
|
import os
|
|
7
7
|
from .utils import download_file
|
|
@@ -26,8 +26,8 @@ def load_atlas_microglia(data_dir='data') -> sc.AnnData:
|
|
|
26
26
|
|
|
27
27
|
Args:
|
|
28
28
|
data_dir (str): Parent directory to save and load the data. If the path
|
|
29
|
-
|
|
30
|
-
|
|
29
|
+
does not exist, it will be created. Data will be saved in a
|
|
30
|
+
subdirectory under the provided path.
|
|
31
31
|
"""
|
|
32
32
|
if not os.path.exists(data_dir):
|
|
33
33
|
os.mkdir(data_dir)
|
|
@@ -73,9 +73,8 @@ def load_hammond_microglia(data_dir='data'):
|
|
|
73
73
|
|
|
74
74
|
Args:
|
|
75
75
|
data_dir (str): Parent directory to save and load the data. If the path
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
76
|
+
does not exist, it will be created. Data will be saved in a
|
|
77
|
+
subdirectory under the provided path.
|
|
79
78
|
"""
|
|
80
79
|
if not os.path.exists(data_dir):
|
|
81
80
|
os.mkdir(data_dir)
|
|
@@ -59,6 +59,16 @@ class GRNEvaluator:
|
|
|
59
59
|
self.report_epr = ('EPR' in metrics)
|
|
60
60
|
|
|
61
61
|
def evaluate(self, A):
|
|
62
|
+
"""
|
|
63
|
+
Evaluate a predicted adjacency matrix against the ground truth.
|
|
64
|
+
|
|
65
|
+
Args:
|
|
66
|
+
A (np.ndarray): Predicted adjacency matrix of shape
|
|
67
|
+
(n_gene, n_gene) or (n_tf, n_gene).
|
|
68
|
+
|
|
69
|
+
Returns:
|
|
70
|
+
dict: Dictionary of evaluation metrics (e.g. AUROC, AUPR).
|
|
71
|
+
"""
|
|
62
72
|
if A.shape[0] == A.shape[1]:
|
|
63
73
|
A = A[self.tf_mask, :]
|
|
64
74
|
A = A[:, self.gene_mask]
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import numpy as np
|
|
2
2
|
import pandas as pd
|
|
3
|
-
from tqdm import tqdm
|
|
3
|
+
from tqdm.auto import tqdm
|
|
4
4
|
from datetime import datetime
|
|
5
5
|
from collections import deque, Counter
|
|
6
6
|
from scipy.sparse import csr_matrix
|
|
@@ -10,42 +10,41 @@ import concurrent.futures
|
|
|
10
10
|
from .plot import plot_pyvis
|
|
11
11
|
|
|
12
12
|
class GRN:
|
|
13
|
-
"""
|
|
14
|
-
|
|
13
|
+
"""
|
|
14
|
+
An object to save and analyze a gene regulatory network.
|
|
15
15
|
|
|
16
|
-
A GRN object includes the adjacency matrix between transcriptional factors
|
|
17
|
-
and target genes. In many cases, when TFs are not specified, we have a
|
|
18
|
-
square-shaped adjacency matrix. We
|
|
19
|
-
matrix to hold predicted weights/probabilities for the edges (float).
|
|
16
|
+
A GRN object includes the adjacency matrix between transcriptional factors
|
|
17
|
+
and target genes. In many cases, when TFs are not specified, we have a
|
|
18
|
+
square-shaped adjacency matrix. We expect the adjacency
|
|
19
|
+
matrix to hold predicted weights/probabilities for the edges (float).
|
|
20
20
|
|
|
21
21
|
To create a GRN object, you need at least two things: the adjacency matrix
|
|
22
22
|
and the corresponding gene names. You can further specify the TF names if
|
|
23
|
-
your adjacency matrix is not a square matrix.
|
|
23
|
+
your adjacency matrix is not a square matrix.
|
|
24
24
|
|
|
25
|
-
You can save a GRN object to the HDF5 format using the
|
|
26
|
-
the GRN class. You can load a saved GRN object using the
|
|
27
|
-
function in this package.
|
|
25
|
+
You can save a GRN object to the HDF5 format using the ``.to_hdf5`` method
|
|
26
|
+
in the GRN class. You can load a saved GRN object using the ``read_hdf5``
|
|
27
|
+
function in this package.
|
|
28
28
|
|
|
29
29
|
If your adjacency matrix is very large and space is a concern, you may
|
|
30
|
-
consider
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
30
|
+
consider providing a value for ``top_gene_percentile``. This will calculate
|
|
31
|
+
a cutoff point for the values in the adjacency matrix. Every value whose
|
|
32
|
+
absolute value is below this cutoff point will be set to zero. Later on, we
|
|
33
|
+
can save the data as a sparse matrix to reduce the space requirement.
|
|
34
|
+
|
|
36
35
|
The GRN object comes with many useful methods to analyze and visualize the
|
|
37
|
-
network. Top
|
|
38
|
-
and
|
|
36
|
+
network. Top-level interfaces include ``.extract_local_neighborhood``
|
|
37
|
+
and ``.visualize_local_neighborhood``.
|
|
39
38
|
|
|
40
39
|
Args:
|
|
41
40
|
adj_matrix (np.ndarray): A 2D adjacency matrix to save.
|
|
42
|
-
gene_names (np.ndarray): A 1D numpy array with all the target gene
|
|
43
|
-
|
|
44
|
-
tf_names (np.ndarray, optional): A 1D numpy array with all the TF
|
|
45
|
-
|
|
46
|
-
top_gene_percentile (int): If this value is set, only the top k
|
|
47
|
-
|
|
48
|
-
|
|
41
|
+
gene_names (np.ndarray): A 1D numpy array with all the target gene
|
|
42
|
+
names.
|
|
43
|
+
tf_names (np.ndarray, optional): A 1D numpy array with all the TF
|
|
44
|
+
gene names.
|
|
45
|
+
top_gene_percentile (int): If this value is set, only the top k
|
|
46
|
+
absolute values in the adjacency matrix will be kept. All the
|
|
47
|
+
other values will be set to zero.
|
|
49
48
|
"""
|
|
50
49
|
def __init__(self, adj_matrix: np.ndarray,
|
|
51
50
|
gene_names: np.ndarray,
|
|
@@ -65,8 +64,9 @@ class GRN:
|
|
|
65
64
|
# Here we are estimating the cutoff point for top a% predicted edges
|
|
66
65
|
# To speed up the process, we calculate the 1-a% percentile within
|
|
67
66
|
# 10,000 sampled edges instead of all edges.
|
|
68
|
-
|
|
69
|
-
|
|
67
|
+
rng = np.random.RandomState(0)
|
|
68
|
+
random_row_idx = rng.randint(0, self.n_tfs, 10000)
|
|
69
|
+
random_col_idx = rng.randint(0, self.n_genes, 10000)
|
|
70
70
|
sampled_values = adj_matrix[random_row_idx, random_col_idx]
|
|
71
71
|
self.cutoff_threshold = np.percentile(
|
|
72
72
|
np.abs(sampled_values), 100-top_gene_percentile
|
|
@@ -137,7 +137,7 @@ class GRN:
|
|
|
137
137
|
selected gene. It is slightly faster than the dataframe version.
|
|
138
138
|
|
|
139
139
|
Args:
|
|
140
|
-
|
|
140
|
+
gene (str): A single gene to inspect.
|
|
141
141
|
k (int): Top-k edges to inspect on each node. If k=-1, export all
|
|
142
142
|
"""
|
|
143
143
|
gene_idx = self.gene_indices[gene]
|
|
@@ -162,7 +162,7 @@ class GRN:
|
|
|
162
162
|
The dataframe will have 3 columns: `source`, `target`, `weight`.
|
|
163
163
|
|
|
164
164
|
Args:
|
|
165
|
-
|
|
165
|
+
gene (str): A single gene to inspect.
|
|
166
166
|
k (int): Top-k edges to inspect on each node. If k=-1, export all
|
|
167
167
|
"""
|
|
168
168
|
source_indices = self.extract_node_sources_as_indices(gene, k)
|
|
@@ -182,7 +182,7 @@ class GRN:
|
|
|
182
182
|
selected gene. It is slightly faster than the dataframe version.
|
|
183
183
|
|
|
184
184
|
Args:
|
|
185
|
-
|
|
185
|
+
gene (str): A single gene to inspect.
|
|
186
186
|
k (int): Top-k edges to inspect on each node. If k=-1, export all
|
|
187
187
|
"""
|
|
188
188
|
gene_idx = self.tf_indices[gene]
|
|
@@ -207,7 +207,7 @@ class GRN:
|
|
|
207
207
|
The dataframe will have 3 columns: `source`, `target`, `weight`.
|
|
208
208
|
|
|
209
209
|
Args:
|
|
210
|
-
|
|
210
|
+
gene (str): A single gene to inspect.
|
|
211
211
|
k (int): Top-k edges to inspect on each node. If k=-1, export all
|
|
212
212
|
"""
|
|
213
213
|
target_indices = self.extract_node_targets_as_indices(gene, k)
|
|
@@ -227,7 +227,7 @@ class GRN:
|
|
|
227
227
|
It is slightly faster than the dataframe version.
|
|
228
228
|
|
|
229
229
|
Args:
|
|
230
|
-
|
|
230
|
+
gene (str): A single gene to inspect.
|
|
231
231
|
k (int): Top-k edges to inspect on each node. If k=-1, export all
|
|
232
232
|
"""
|
|
233
233
|
gene_idx = self.gene_indices[gene]
|
|
@@ -261,7 +261,7 @@ class GRN:
|
|
|
261
261
|
The dataframe will have 3 columns: `source`, `target`, `weight`.
|
|
262
262
|
|
|
263
263
|
Args:
|
|
264
|
-
|
|
264
|
+
gene (str): A single gene to inspect.
|
|
265
265
|
k (int): Top-k edges to inspect on each node. If k=-1, export all
|
|
266
266
|
"""
|
|
267
267
|
neighbor_indices = self.extract_node_neighbors_as_indices(gene, k)
|
|
@@ -294,10 +294,10 @@ class GRN:
|
|
|
294
294
|
is defined in a similar way but smaller.
|
|
295
295
|
|
|
296
296
|
Args:
|
|
297
|
-
|
|
297
|
+
gene (str): A single gene to inspect.
|
|
298
298
|
k (int): Top-k edges to inspect on each node. If k=-1, export all
|
|
299
299
|
hops (str): Number of hops to explore. We can either do a "2.5" or
|
|
300
|
-
"1.5" hop
|
|
300
|
+
"1.5" hop traversal around selected genes. Default is "2.5".
|
|
301
301
|
"""
|
|
302
302
|
if isinstance(genes, str):
|
|
303
303
|
genes = [genes]
|
|
@@ -364,7 +364,7 @@ class GRN:
|
|
|
364
364
|
(2-hop) around selected gene(s).
|
|
365
365
|
|
|
366
366
|
Args:
|
|
367
|
-
|
|
367
|
+
gene (str): A single gene to inspect.
|
|
368
368
|
k (int): Top-k edges to inspect on each node. If k=-1, export all.
|
|
369
369
|
hops (str): Number of hops of the neighborhood to explore. Default
|
|
370
370
|
is "2.5".
|
|
@@ -82,6 +82,19 @@ class LightLogger:
|
|
|
82
82
|
self.logging_vars.add(k)
|
|
83
83
|
|
|
84
84
|
def check_early_stopping(self, item: str, k: int = 10):
|
|
85
|
+
"""
|
|
86
|
+
Check if training should stop early based on a monitored metric.
|
|
87
|
+
|
|
88
|
+
Returns True if the minimum value in the last ``k`` steps is greater
|
|
89
|
+
than the historical minimum, indicating no improvement.
|
|
90
|
+
|
|
91
|
+
Args:
|
|
92
|
+
item (str): The metric name to monitor (e.g. 'val_loss').
|
|
93
|
+
k (int): Window size to check for improvement. Default: 10.
|
|
94
|
+
|
|
95
|
+
Returns:
|
|
96
|
+
bool: True if early stopping criteria is met.
|
|
97
|
+
"""
|
|
85
98
|
end_idx = self.mem[self.current_log]['current_step']
|
|
86
99
|
window = []
|
|
87
100
|
start_idx = max(end_idx-k, 0)
|
|
@@ -62,19 +62,19 @@ class RegDiffusion(nn.Module):
|
|
|
62
62
|
From noise to knowledge: probabilistic diffusion-based neural inference
|
|
63
63
|
|
|
64
64
|
Args:
|
|
65
|
-
|
|
66
|
-
time_dim (int): Dimension of time step embedding
|
|
67
|
-
n_celltype (int): Number of expected cell types. If it is not provided,
|
|
68
|
-
|
|
69
|
-
celltype_dim (int): Dimension of cell
|
|
70
|
-
hidden_dims (list[int]): List of
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
adj_dropout (float): A single number between 0 and 1 specifying the
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
init_coef (int): Coefficient to multiply with gene regulation norm
|
|
77
|
-
|
|
65
|
+
n_gene (int): Number of genes.
|
|
66
|
+
time_dim (int): Dimension of time step embedding.
|
|
67
|
+
n_celltype (int): Number of expected cell types. If it is not provided,
|
|
68
|
+
there would be no celltype embedding. Default is None.
|
|
69
|
+
celltype_dim (int): Dimension of cell type embedding. Default: 4.
|
|
70
|
+
hidden_dims (list[int]): List of integers for the dimensions of the
|
|
71
|
+
hidden layers. The first hidden dimension will be used as the size
|
|
72
|
+
for gene embedding. Default: [16, 16, 16].
|
|
73
|
+
adj_dropout (float): A single number between 0 and 1 specifying the
|
|
74
|
+
percentage of values in the adjacency matrix that are dropped
|
|
75
|
+
during training. Default: 0.3.
|
|
76
|
+
init_coef (int): Coefficient to multiply with gene regulation norm
|
|
77
|
+
(1/(n_gene - 1)) to initialize the adjacency matrix. Default: 5.
|
|
78
78
|
"""
|
|
79
79
|
def __init__(
|
|
80
80
|
self, n_gene, time_dim,
|
|
@@ -92,12 +92,16 @@ class RegDiffusion(nn.Module):
|
|
|
92
92
|
|
|
93
93
|
adj_A = torch.ones(n_gene, n_gene) * self.gene_reg_norm * init_coef
|
|
94
94
|
self.adj_A = nn.Parameter(adj_A, requires_grad =True, )
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
95
|
+
# Integer index tensors, not learnable weights. Registered as buffers
|
|
96
|
+
# so they stay out of `parameters()` while keeping their state_dict
|
|
97
|
+
# keys (the `_nonparam` suffix is vestigial, kept for checkpoint
|
|
98
|
+
# compatibility).
|
|
99
|
+
self.register_buffer(
|
|
100
|
+
'sampled_adj_row_nonparam',
|
|
101
|
+
torch.randint(0, n_gene, size=(10000,)))
|
|
102
|
+
self.register_buffer(
|
|
103
|
+
'sampled_adj_col_nonparam',
|
|
104
|
+
torch.randint(0, n_gene, size=(10000,)))
|
|
101
105
|
|
|
102
106
|
self.time_mlp = nn.Sequential(
|
|
103
107
|
SinusoidalPositionEmbeddings(time_dim),
|
|
@@ -144,6 +148,26 @@ class RegDiffusion(nn.Module):
|
|
|
144
148
|
adj = self.get_adj_().detach().cpu().numpy() / self.gene_reg_norm
|
|
145
149
|
return adj.astype(np.float16)
|
|
146
150
|
|
|
151
|
+
def get_sparse_loss(self):
|
|
152
|
+
"""L1 sparsity penalty: mean absolute value of the off-diagonal,
|
|
153
|
+
soft-thresholded adjacency entries.
|
|
154
|
+
|
|
155
|
+
``abs`` is required. Soft thresholding preserves sign, so a plain mean
|
|
156
|
+
of signed values would be *reduced* by making inhibitory (negative)
|
|
157
|
+
edges more negative -- the opposite of a sparsity penalty. In practice
|
|
158
|
+
negative entries do not survive thresholding (they land in the
|
|
159
|
+
``|x| < tau`` dead zone, where the output and its gradient are both
|
|
160
|
+
zero), so this matches the previous signed mean on real runs; it is
|
|
161
|
+
corrected here so the penalty is right by construction rather than by
|
|
162
|
+
accident.
|
|
163
|
+
|
|
164
|
+
The mean is taken over the n*(n-1) off-diagonal entries, since
|
|
165
|
+
``get_adj_`` masks the diagonal to zero, so this agrees with
|
|
166
|
+
``RegDiffusionME.get_sparse_loss``, its sampled approximation.
|
|
167
|
+
"""
|
|
168
|
+
n = self.n_gene
|
|
169
|
+
return self.get_adj_().abs().sum() / (n * (n - 1))
|
|
170
|
+
|
|
147
171
|
@torch.no_grad()
|
|
148
172
|
def get_sampled_adj_(self):
|
|
149
173
|
return self.get_adj_()[
|
|
@@ -45,19 +45,19 @@ class RegDiffusionME(nn.Module):
|
|
|
45
45
|
The model architecture and inference behavior are identical to RegDiffusion.
|
|
46
46
|
|
|
47
47
|
Args:
|
|
48
|
-
|
|
49
|
-
time_dim (int): Dimension of time step embedding
|
|
48
|
+
n_gene (int): Number of genes.
|
|
49
|
+
time_dim (int): Dimension of time step embedding.
|
|
50
50
|
n_celltype (int): Number of expected cell types. If it is not provided,
|
|
51
|
-
|
|
52
|
-
celltype_dim (int): Dimension of cell
|
|
53
|
-
hidden_dims (list[int]): List of
|
|
54
|
-
|
|
55
|
-
|
|
51
|
+
there would be no celltype embedding. Default is None.
|
|
52
|
+
celltype_dim (int): Dimension of cell type embedding. Default: 4.
|
|
53
|
+
hidden_dims (list[int]): List of integers for the dimensions of the
|
|
54
|
+
hidden layers. The first hidden dimension will be used as the size
|
|
55
|
+
for gene embedding. Default: [16, 16, 16].
|
|
56
56
|
adj_dropout (float): A single number between 0 and 1 specifying the
|
|
57
|
-
|
|
58
|
-
|
|
57
|
+
percentage of values in the adjacency matrix that are dropped
|
|
58
|
+
during training. Default: 0.3.
|
|
59
59
|
init_coef (int): Coefficient to multiply with gene regulation norm
|
|
60
|
-
|
|
60
|
+
(1/(n_gene - 1)) to initialize the adjacency matrix. Default: 5.
|
|
61
61
|
"""
|
|
62
62
|
def __init__(
|
|
63
63
|
self, n_gene, time_dim,
|
|
@@ -75,12 +75,16 @@ class RegDiffusionME(nn.Module):
|
|
|
75
75
|
|
|
76
76
|
adj_A = torch.ones(n_gene, n_gene) * self.gene_reg_norm * init_coef
|
|
77
77
|
self.adj_A = nn.Parameter(adj_A, requires_grad =True, )
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
78
|
+
# Integer index tensors, not learnable weights. Registered as buffers
|
|
79
|
+
# so they stay out of `parameters()` while keeping their state_dict
|
|
80
|
+
# keys (the `_nonparam` suffix is vestigial, kept for checkpoint
|
|
81
|
+
# compatibility).
|
|
82
|
+
self.register_buffer(
|
|
83
|
+
'sampled_adj_row_nonparam',
|
|
84
|
+
torch.randint(0, n_gene, size=(10000,)))
|
|
85
|
+
self.register_buffer(
|
|
86
|
+
'sampled_adj_col_nonparam',
|
|
87
|
+
torch.randint(0, n_gene, size=(10000,)))
|
|
84
88
|
|
|
85
89
|
self.time_mlp = nn.Sequential(
|
|
86
90
|
SinusoidalPositionEmbeddings(time_dim),
|
|
@@ -127,19 +131,34 @@ class RegDiffusionME(nn.Module):
|
|
|
127
131
|
adj = self.get_adj_().detach().cpu().numpy() / self.gene_reg_norm
|
|
128
132
|
return adj.astype(np.float16)
|
|
129
133
|
|
|
130
|
-
def
|
|
134
|
+
def get_sparse_loss(self):
|
|
131
135
|
"""Compute mean absolute value of sampled adj entries for sparse loss.
|
|
132
136
|
|
|
137
|
+
Memory-efficient approximation of ``RegDiffusion.get_sparse_loss``.
|
|
133
138
|
Instead of materializing the full (n_gene, n_gene) get_adj_() matrix,
|
|
134
139
|
this samples 10,000 random entries, applies soft thresholding, and
|
|
135
140
|
returns the mean. This avoids creating 3 additional (n,n) tensors
|
|
136
141
|
that the full get_adj_() would require.
|
|
142
|
+
|
|
143
|
+
Diagonal (self-loop) samples are excluded so this matches the base
|
|
144
|
+
model, whose ``get_adj_`` masks the diagonal to zero.
|
|
137
145
|
"""
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
]
|
|
146
|
+
rows = self.sampled_adj_row_nonparam
|
|
147
|
+
cols = self.sampled_adj_col_nonparam
|
|
148
|
+
sampled_vals = self.adj_A[rows, cols]
|
|
141
149
|
sampled_clean = self.soft_thresholding(sampled_vals, self.gene_reg_norm/2)
|
|
142
|
-
|
|
150
|
+
off_diag = (rows != cols).to(sampled_clean.dtype)
|
|
151
|
+
return (sampled_clean.abs() * off_diag).sum() / off_diag.sum()
|
|
152
|
+
|
|
153
|
+
def get_sampled_sparse_loss(self):
|
|
154
|
+
"""
|
|
155
|
+
Deprecated API. Use get_sparse_loss instead.
|
|
156
|
+
"""
|
|
157
|
+
import warnings
|
|
158
|
+
warnings.warn(
|
|
159
|
+
"get_sampled_sparse_loss is deprecated, use get_sparse_loss instead",
|
|
160
|
+
DeprecationWarning)
|
|
161
|
+
return self.get_sparse_loss()
|
|
143
162
|
|
|
144
163
|
@torch.no_grad()
|
|
145
164
|
def get_sampled_adj_(self):
|
|
@@ -6,7 +6,7 @@ import torch.nn.functional as F
|
|
|
6
6
|
from torch.utils.data import DataLoader, Dataset
|
|
7
7
|
from torch.utils.data.dataset import TensorDataset
|
|
8
8
|
from .models import RegDiffusion, RegDiffusionME
|
|
9
|
-
from tqdm import tqdm
|
|
9
|
+
from tqdm.auto import tqdm
|
|
10
10
|
from .logger import LightLogger
|
|
11
11
|
from datetime import datetime
|
|
12
12
|
from .grn import GRN
|
|
@@ -14,6 +14,17 @@ from .evaluator import GRNEvaluator
|
|
|
14
14
|
from .logger import LightLogger
|
|
15
15
|
import matplotlib.pyplot as plt
|
|
16
16
|
import warnings
|
|
17
|
+
import random
|
|
18
|
+
|
|
19
|
+
def set_seed(seed):
|
|
20
|
+
"""Set random seeds for reproducibility across PyTorch, NumPy, and CUDA."""
|
|
21
|
+
random.seed(seed)
|
|
22
|
+
np.random.seed(seed)
|
|
23
|
+
torch.manual_seed(seed)
|
|
24
|
+
if torch.cuda.is_available():
|
|
25
|
+
torch.cuda.manual_seed_all(seed)
|
|
26
|
+
torch.backends.cudnn.deterministic = True
|
|
27
|
+
torch.backends.cudnn.benchmark = False
|
|
17
28
|
|
|
18
29
|
def linear_beta_schedule(timesteps, start_noise, end_noise):
|
|
19
30
|
scale = 1000 / timesteps
|
|
@@ -82,7 +93,7 @@ class RegDiffusionTrainer:
|
|
|
82
93
|
full dense normalized matrix is never materialized.
|
|
83
94
|
cell_types (np.ndarray): (Optional) 1D integer array for cell type. If
|
|
84
95
|
you have labels in your cell type, you need to convert them to
|
|
85
|
-
|
|
96
|
+
integer. Default is None.
|
|
86
97
|
T (int): Total number of diffusion steps. Default: 5,000
|
|
87
98
|
start_noise (float): Minimal noise level (beta) to be added. Default:
|
|
88
99
|
0.0001
|
|
@@ -91,7 +102,7 @@ class RegDiffusionTrainer:
|
|
|
91
102
|
time_dim (int): Dimension size for the time embedding. Default: 64.
|
|
92
103
|
celltype_dim (int): Dimension size for the cell type embedding.
|
|
93
104
|
Default: 4.
|
|
94
|
-
|
|
105
|
+
hidden_dims (list): Dimension sizes for the feature learning layers. We
|
|
95
106
|
use the size of the first layer as the dimension for gene embeddings
|
|
96
107
|
as well. Default: [16, 16, 16].
|
|
97
108
|
init_coef (int): A coefficent to control the value to initialize the
|
|
@@ -119,9 +130,9 @@ class RegDiffusionTrainer:
|
|
|
119
130
|
to run this model on Apple's MPS chips. Default is "cuda" but if
|
|
120
131
|
you only has CPU, it will switch back to CPU.
|
|
121
132
|
compile (boolean): Whether to compile the model before training.
|
|
122
|
-
Compile the model is a good idea on large dataset and
|
|
123
|
-
inference speed when it works. For smaller dataset, eager execution
|
|
124
|
-
|
|
133
|
+
Compile the model is a good idea on large dataset and often improves
|
|
134
|
+
inference speed when it works. For smaller dataset, eager execution
|
|
135
|
+
is often good enough.
|
|
125
136
|
evaluator (GRNEvaluator): (Optional) A defined GRNEvaluator if ground
|
|
126
137
|
truth data is available. Evaluation will be done every 100 steps by
|
|
127
138
|
default but you can change this setting through the eval_on_n_steps
|
|
@@ -136,8 +147,8 @@ class RegDiffusionTrainer:
|
|
|
136
147
|
accumulation. This is useful when number of genes are extremely
|
|
137
148
|
large.
|
|
138
149
|
use_amp (bool): Whether to use automatic mixed precision (bfloat16)
|
|
139
|
-
during training
|
|
140
|
-
|
|
150
|
+
during training at the cost of 2x training time. This is usually
|
|
151
|
+
not recommended unless the last slice of memory is a bottleneck.
|
|
141
152
|
Requires a GPU with bfloat16 support (Ampere or newer).
|
|
142
153
|
Default: False.
|
|
143
154
|
memory_efficient (bool): Whether to use the memory-efficient model
|
|
@@ -145,6 +156,8 @@ class RegDiffusionTrainer:
|
|
|
145
156
|
for soft thresholding (saves boolean masks instead of float32
|
|
146
157
|
tensors) and sampled sparse loss (avoids materializing full
|
|
147
158
|
n_gene x n_gene matrix for L1 regularization). Default: False.
|
|
159
|
+
seed (int): Random seed for full reproducibility. When set, all
|
|
160
|
+
sources of randomness are seeded. Default: None (non-deterministic).
|
|
148
161
|
"""
|
|
149
162
|
def __init__(
|
|
150
163
|
self, exp_array, cell_types=None,
|
|
@@ -159,14 +172,22 @@ class RegDiffusionTrainer:
|
|
|
159
172
|
device='cuda', compile=False,
|
|
160
173
|
evaluator=None, eval_on_n_steps=100, logger=None,
|
|
161
174
|
gradient_accumulation=False, use_amp=False,
|
|
162
|
-
memory_efficient=False
|
|
175
|
+
memory_efficient=False,
|
|
176
|
+
seed=None
|
|
163
177
|
):
|
|
164
178
|
hp = locals()
|
|
165
179
|
del hp['exp_array']
|
|
166
180
|
del hp['cell_types']
|
|
167
181
|
del hp['logger']
|
|
168
182
|
self.hp = hp
|
|
169
|
-
|
|
183
|
+
|
|
184
|
+
# Seed for reproducibility
|
|
185
|
+
if seed is not None:
|
|
186
|
+
set_seed(seed)
|
|
187
|
+
self._sampler_generator = torch.Generator()
|
|
188
|
+
if seed is not None:
|
|
189
|
+
self._sampler_generator.manual_seed(seed)
|
|
190
|
+
|
|
170
191
|
if device == 'mps':
|
|
171
192
|
raise Exception("We noticed unreliable training behavior on",
|
|
172
193
|
"Apple's silicon. Consider using other devices.")
|
|
@@ -239,8 +260,7 @@ class RegDiffusionTrainer:
|
|
|
239
260
|
if name.endswith('adj_A'):
|
|
240
261
|
adj_params.append(param)
|
|
241
262
|
else:
|
|
242
|
-
|
|
243
|
-
non_adj_params.append(param)
|
|
263
|
+
non_adj_params.append(param)
|
|
244
264
|
self.opt = torch.optim.Adam(
|
|
245
265
|
[{'params': non_adj_params}, {'params': adj_params}],
|
|
246
266
|
lr=lr_nn,
|
|
@@ -297,7 +317,8 @@ class RegDiffusionTrainer:
|
|
|
297
317
|
self.train_dataset = TensorDataset(
|
|
298
318
|
x_tensor_train, celltype_tensor_train)
|
|
299
319
|
train_sampler = torch.utils.data.RandomSampler(
|
|
300
|
-
self.train_dataset, replacement=True, num_samples=batch_size
|
|
320
|
+
self.train_dataset, replacement=True, num_samples=batch_size,
|
|
321
|
+
generator=self._sampler_generator)
|
|
301
322
|
self.train_dataloader = DataLoader(
|
|
302
323
|
self.train_dataset,
|
|
303
324
|
sampler=train_sampler,
|
|
@@ -389,7 +410,8 @@ class RegDiffusionTrainer:
|
|
|
389
410
|
cell_min_f32, cell_range_f32, gene_mean, gene_std,
|
|
390
411
|
train_indices)
|
|
391
412
|
train_sampler = torch.utils.data.RandomSampler(
|
|
392
|
-
self.train_dataset, replacement=True, num_samples=batch_size
|
|
413
|
+
self.train_dataset, replacement=True, num_samples=batch_size,
|
|
414
|
+
generator=self._sampler_generator)
|
|
393
415
|
self.train_dataloader = DataLoader(
|
|
394
416
|
self.train_dataset,
|
|
395
417
|
sampler=train_sampler,
|
|
@@ -409,12 +431,17 @@ class RegDiffusionTrainer:
|
|
|
409
431
|
@torch.no_grad()
|
|
410
432
|
def forward_pass(self, x_0, t):
|
|
411
433
|
"""
|
|
412
|
-
Forward diffusion process
|
|
413
|
-
|
|
434
|
+
Forward diffusion process. Adds noise to the input according to the
|
|
435
|
+
diffusion schedule at the given timesteps.
|
|
436
|
+
|
|
414
437
|
Args:
|
|
415
|
-
x_0 (torch.FloatTensor): Torch tensor for expression data. Rows
|
|
416
|
-
|
|
438
|
+
x_0 (torch.FloatTensor): Torch tensor for expression data. Rows
|
|
439
|
+
are cells and columns are genes.
|
|
417
440
|
t (torch.LongTensor): Torch tensor for diffusion time steps.
|
|
441
|
+
|
|
442
|
+
Returns:
|
|
443
|
+
tuple: (x_t, noise) where x_t is the noised input and noise is
|
|
444
|
+
the sampled Gaussian noise that was added.
|
|
418
445
|
"""
|
|
419
446
|
noise = torch.randn_like(x_0)
|
|
420
447
|
mean_coef = self.mean_schedule.gather(dim=-1, index=t)
|
|
@@ -423,10 +450,18 @@ class RegDiffusionTrainer:
|
|
|
423
450
|
return x_t, noise
|
|
424
451
|
|
|
425
452
|
def train(self, n_steps=None):
|
|
453
|
+
"""
|
|
454
|
+
Train the model. Dispatches to gradient accumulation or normal
|
|
455
|
+
training based on the ``gradient_accumulation`` setting.
|
|
456
|
+
|
|
457
|
+
Args:
|
|
458
|
+
n_steps (int): Number of steps to train. If not provided, uses
|
|
459
|
+
the n_steps specified during initialization.
|
|
460
|
+
"""
|
|
426
461
|
if self.hp['gradient_accumulation']:
|
|
427
|
-
self._train_with_gradient_accumulation(n_steps=
|
|
462
|
+
self._train_with_gradient_accumulation(n_steps=n_steps)
|
|
428
463
|
else:
|
|
429
|
-
self._train_normal(n_steps=
|
|
464
|
+
self._train_normal(n_steps=n_steps)
|
|
430
465
|
|
|
431
466
|
|
|
432
467
|
def _train_normal(self, n_steps=None):
|
|
@@ -435,9 +470,9 @@ class RegDiffusionTrainer:
|
|
|
435
470
|
|
|
436
471
|
Args:
|
|
437
472
|
n_steps (int): Number of steps to train. If not provided, it will
|
|
438
|
-
train the model by the n_steps
|
|
473
|
+
train the model by the n_steps specified in class
|
|
439
474
|
initialization. Please read our paper to see how to identify
|
|
440
|
-
the
|
|
475
|
+
the convergence point.
|
|
441
476
|
"""
|
|
442
477
|
start_time = datetime.now()
|
|
443
478
|
eval_steps = self.hp['eval_on_n_steps']
|
|
@@ -445,7 +480,9 @@ class RegDiffusionTrainer:
|
|
|
445
480
|
n_steps = self.hp['n_steps']
|
|
446
481
|
sampled_adj = self.model.get_sampled_adj_()
|
|
447
482
|
with tqdm(range(n_steps)) as pbar:
|
|
448
|
-
for epoch in pbar:
|
|
483
|
+
for epoch in pbar:
|
|
484
|
+
if self.hp['seed'] is not None:
|
|
485
|
+
torch.manual_seed(self.hp['seed'] + epoch)
|
|
449
486
|
epoch_loss = []
|
|
450
487
|
for step, batch in enumerate(self.train_dataloader):
|
|
451
488
|
x_0, ct = batch
|
|
@@ -467,11 +504,13 @@ class RegDiffusionTrainer:
|
|
|
467
504
|
loss_ = F.mse_loss(noise, z, reduction='none')
|
|
468
505
|
loss = loss_.mean()
|
|
469
506
|
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
507
|
+
# Only computed past the warmup window, where it is
|
|
508
|
+
# actually applied.
|
|
509
|
+
if epoch > 10:
|
|
510
|
+
loss_sparse = (
|
|
511
|
+
self.model.get_sparse_loss()
|
|
512
|
+
* self.hp['sparse_loss_coef']
|
|
513
|
+
)
|
|
475
514
|
|
|
476
515
|
if epoch > 10:
|
|
477
516
|
loss = loss + loss_sparse
|
|
@@ -495,6 +534,8 @@ class RegDiffusionTrainer:
|
|
|
495
534
|
for k in eval_result.keys():
|
|
496
535
|
epoch_log[k] = eval_result[k]
|
|
497
536
|
if self.hp['train_split'] < 1:
|
|
537
|
+
if self.hp['seed'] is not None:
|
|
538
|
+
torch.manual_seed(self.hp['seed'] + n_steps + epoch)
|
|
498
539
|
with torch.no_grad():
|
|
499
540
|
val_epoch_loss = []
|
|
500
541
|
for step, batch in enumerate(self.val_dataloader):
|
|
@@ -546,6 +587,8 @@ class RegDiffusionTrainer:
|
|
|
546
587
|
|
|
547
588
|
with tqdm(range(n_steps)) as pbar:
|
|
548
589
|
for step_idx in pbar:
|
|
590
|
+
if self.hp['seed'] is not None:
|
|
591
|
+
torch.manual_seed(self.hp['seed'] + step_idx)
|
|
549
592
|
# Fetch a single batch for the current step
|
|
550
593
|
x_0_batch, ct_batch = next(iter(self.train_dataloader))
|
|
551
594
|
x_0_batch = x_0_batch.to(self.device)
|
|
@@ -588,19 +631,19 @@ class RegDiffusionTrainer:
|
|
|
588
631
|
scaled_loss = loss_sample / batch_size
|
|
589
632
|
scaled_loss.backward()
|
|
590
633
|
|
|
591
|
-
# Handle sparse loss once per effective batch
|
|
592
|
-
|
|
593
|
-
device_type=self.amp_device_type,
|
|
594
|
-
dtype=torch.bfloat16,
|
|
595
|
-
enabled=self.use_amp
|
|
596
|
-
):
|
|
597
|
-
if hasattr(self.model, 'get_sampled_sparse_loss'):
|
|
598
|
-
loss_sparse = self.model.get_sampled_sparse_loss() * self.hp['sparse_loss_coef']
|
|
599
|
-
else:
|
|
600
|
-
adj_m = self.model.get_adj_()
|
|
601
|
-
loss_sparse = adj_m.mean() * self.hp['sparse_loss_coef']
|
|
602
|
-
|
|
634
|
+
# Handle sparse loss once per effective batch. Only computed
|
|
635
|
+
# past the warmup window, where it is actually applied.
|
|
603
636
|
if step_idx > 10:
|
|
637
|
+
with torch.autocast(
|
|
638
|
+
device_type=self.amp_device_type,
|
|
639
|
+
dtype=torch.bfloat16,
|
|
640
|
+
enabled=self.use_amp
|
|
641
|
+
):
|
|
642
|
+
loss_sparse = (
|
|
643
|
+
self.model.get_sparse_loss()
|
|
644
|
+
* self.hp['sparse_loss_coef']
|
|
645
|
+
)
|
|
646
|
+
|
|
604
647
|
loss_sparse.backward()
|
|
605
648
|
|
|
606
649
|
# Perform the optimizer step after accumulating all gradients
|
|
@@ -627,6 +670,8 @@ class RegDiffusionTrainer:
|
|
|
627
670
|
epoch_log[k] = eval_result[k]
|
|
628
671
|
|
|
629
672
|
if self.hp['train_split'] < 1:
|
|
673
|
+
if self.hp['seed'] is not None:
|
|
674
|
+
torch.manual_seed(self.hp['seed'] + n_steps + step_idx)
|
|
630
675
|
with torch.no_grad():
|
|
631
676
|
val_epoch_loss = []
|
|
632
677
|
for step, batch in enumerate(self.val_dataloader):
|
|
@@ -680,28 +725,33 @@ class RegDiffusionTrainer:
|
|
|
680
725
|
|
|
681
726
|
def get_grn(self, gene_names, tf_names=None, top_gene_percentile=None):
|
|
682
727
|
"""
|
|
683
|
-
Obtain a GRN object. You need to provide the
|
|
728
|
+
Obtain a GRN object. You need to provide the gene names.
|
|
684
729
|
|
|
685
730
|
Args:
|
|
686
|
-
gene_names (np.ndarray): An array of names of all genes. The order
|
|
731
|
+
gene_names (np.ndarray): An array of names of all genes. The order
|
|
687
732
|
of genes should be the same as the order used in your expression
|
|
688
733
|
table.
|
|
689
|
-
tf_names (np.ndarray):An array of names of all transcriptional
|
|
690
|
-
factors. The order
|
|
691
|
-
|
|
692
|
-
top_gene_percentile (int): If provided, we will set the value on
|
|
693
|
-
weak links to be zero. It is useful if you want to save the
|
|
694
|
-
regulatory relationship in a GRN object as a sparse matrix.
|
|
695
|
-
|
|
734
|
+
tf_names (np.ndarray): An array of names of all transcriptional
|
|
735
|
+
factors. The order should be the same as the order used in
|
|
736
|
+
your expression table.
|
|
737
|
+
top_gene_percentile (int): If provided, we will set the value on
|
|
738
|
+
weak links to be zero. It is useful if you want to save the
|
|
739
|
+
regulatory relationship in a GRN object as a sparse matrix.
|
|
740
|
+
|
|
741
|
+
Returns:
|
|
742
|
+
GRN: A GRN object containing the inferred regulatory network.
|
|
696
743
|
"""
|
|
697
744
|
adj = self.model.get_adj()
|
|
698
745
|
return GRN(adj, gene_names, tf_names, top_gene_percentile)
|
|
699
746
|
|
|
700
747
|
def get_adj(self):
|
|
701
748
|
"""
|
|
702
|
-
Obtain the adjacency matrix. The values in this adjacency
|
|
749
|
+
Obtain the adjacency matrix. The values in this adjacency matrix have
|
|
703
750
|
been scaled using regulatory norm. You may expect strong links to go
|
|
704
|
-
beyond 5 or 10 in most cases.
|
|
751
|
+
beyond 5 or 10 in most cases.
|
|
752
|
+
|
|
753
|
+
Returns:
|
|
754
|
+
np.ndarray: 2D adjacency matrix of shape (n_gene, n_gene).
|
|
705
755
|
"""
|
|
706
756
|
return self.model.get_adj()
|
|
707
757
|
|
regdiffusion-0.2.1/NEWS.md
DELETED
|
@@ -1,24 +0,0 @@
|
|
|
1
|
-
# RegDiffusion News / Changelog
|
|
2
|
-
|
|
3
|
-
## 0.2.1 [unreleased]
|
|
4
|
-
|
|
5
|
-
### New Features
|
|
6
|
-
- Added sparse matrix support for `RegDiffusionTrainer`. The `exp_array` argument now accepts scipy sparse matrices (e.g. `adata.X`) directly. Normalization statistics are computed in chunks and each sample is normalized on-the-fly during training, so the full dense matrix is never materialized. This enables training on datasets with 1M+ cells without excessive memory usage.
|
|
7
|
-
- Updated CLI (`regdiffusion` command) to handle sparse `adata.X` from H5AD files, including sparse-safe data validation and log-transform via `log1p` on non-zero entries.
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
## 0.2.0
|
|
11
|
-
|
|
12
|
-
### Memory Optimization
|
|
13
|
-
- Removed three `(n_gene, n_gene)` helper matrices (`zeros_nonparam`, `eye_nonparam`, `mask_nonparam`) from `RegDiffusion`, replacing them with inline computations. Saves ~4.8 GB persistent GPU memory for 20K genes with no impact on model accuracy.
|
|
14
|
-
|
|
15
|
-
### New Features
|
|
16
|
-
- Added `RegDiffusionME`, a memory-efficient model variant enabled via `memory_efficient=True` in `RegDiffusionTrainer`. Reduces peak GPU memory by ~45% with no impact on accuracy. Uses a custom autograd function for soft thresholding (boolean masks instead of float32 tensors) and sampled sparse loss (avoids materializing full adjacency matrix for L1 regularization). Benchmarked on all 7 BEELINE datasets with identical AUROC/AUPRR/EPR.
|
|
17
|
-
- Added automatic mixed precision (AMP) support via `use_amp=True` in `RegDiffusionTrainer`. Uses bfloat16 for forward pass and loss computation, reducing memory for autograd-saved activations while keeping model parameters in float32. Requires Ampere or newer GPU.
|
|
18
|
-
|
|
19
|
-
### Bug Fixes
|
|
20
|
-
- Fixed `I_minus_A()` using `self.train` instead of `self.training`, causing dropout to always apply during inference
|
|
21
|
-
- Fixed missing `self` parameter in `GRN.remove_weak_edges()`
|
|
22
|
-
- Fixed `GRN.get_edgelist()` incorrectly passing `self` to `extract_edgelist()`
|
|
23
|
-
- Fixed external logger not being assigned in `RegDiffusionTrainer.__init__()`
|
|
24
|
-
- Fixed `forward()` crash when `n_celltype=None` by adding conditional cell type embedding
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{regdiffusion-0.2.1 → regdiffusion-0.2.3}/docs/_templates/autosummary/classnoinheritance.rst
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|