regdiffusion 0.1.1__tar.gz → 0.2.1__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/NEWS.md +24 -0
- {regdiffusion-0.1.1 → regdiffusion-0.2.1}/PKG-INFO +9 -5
- {regdiffusion-0.1.1 → regdiffusion-0.2.1}/README.md +8 -4
- regdiffusion-0.2.1/docs/BUILD.md +66 -0
- {regdiffusion-0.1.1 → regdiffusion-0.2.1}/docs/index.rst +1 -0
- regdiffusion-0.2.1/docs/large_networks.md +102 -0
- {regdiffusion-0.1.1 → regdiffusion-0.2.1}/pyproject.toml +1 -1
- {regdiffusion-0.1.1 → regdiffusion-0.2.1}/regdiffusion/cli.py +16 -5
- {regdiffusion-0.1.1 → regdiffusion-0.2.1}/regdiffusion/grn.py +203 -4
- regdiffusion-0.2.1/regdiffusion/models/__init__.py +2 -0
- {regdiffusion-0.1.1 → regdiffusion-0.2.1}/regdiffusion/models/regdiffusion.py +20 -18
- regdiffusion-0.2.1/regdiffusion/models/regdiffusion_me.py +172 -0
- regdiffusion-0.2.1/regdiffusion/plot/__init__.py +15 -0
- regdiffusion-0.2.1/regdiffusion/plot/pyvis.py +108 -0
- regdiffusion-0.2.1/regdiffusion/plot/static.py +334 -0
- {regdiffusion-0.1.1 → regdiffusion-0.2.1}/regdiffusion/trainer.py +285 -97
- regdiffusion-0.2.1/test_scripts/test_beeline_benchmark.py +135 -0
- regdiffusion-0.2.1/test_scripts/test_beeline_worker.py +38 -0
- regdiffusion-0.2.1/test_scripts/test_memory_benchmark.py +129 -0
- regdiffusion-0.2.1/test_scripts/test_sparse_support.py +110 -0
- regdiffusion-0.1.1/regdiffusion/models/__init__.py +0 -1
- regdiffusion-0.1.1/regdiffusion/plot/__init__.py +0 -1
- regdiffusion-0.1.1/regdiffusion/plot/pyvis.py +0 -60
- {regdiffusion-0.1.1 → regdiffusion-0.2.1}/.github/workflows/documentation.yml +0 -0
- {regdiffusion-0.1.1 → regdiffusion-0.2.1}/.gitignore +0 -0
- {regdiffusion-0.1.1 → regdiffusion-0.2.1}/LICENSE +0 -0
- {regdiffusion-0.1.1 → regdiffusion-0.2.1}/docs/.gitignore +0 -0
- {regdiffusion-0.1.1 → regdiffusion-0.2.1}/docs/Makefile +0 -0
- {regdiffusion-0.1.1 → regdiffusion-0.2.1}/docs/REG_PySCENIC.ipynb +0 -0
- {regdiffusion-0.1.1 → regdiffusion-0.2.1}/docs/_static/rd_logo_horizontal.png +0 -0
- {regdiffusion-0.1.1 → regdiffusion-0.2.1}/docs/_static/rd_logo_horizontal@2x.png +0 -0
- {regdiffusion-0.1.1 → regdiffusion-0.2.1}/docs/_static/regdiffusion.png +0 -0
- {regdiffusion-0.1.1 → regdiffusion-0.2.1}/docs/_static/regdiffusion@2x.png +0 -0
- {regdiffusion-0.1.1 → regdiffusion-0.2.1}/docs/_templates/autosummary/class.rst +0 -0
- {regdiffusion-0.1.1 → regdiffusion-0.2.1}/docs/_templates/autosummary/classnoinheritance.rst +0 -0
- {regdiffusion-0.1.1 → regdiffusion-0.2.1}/docs/conf.py +0 -0
- {regdiffusion-0.1.1 → regdiffusion-0.2.1}/docs/data_module.rst +0 -0
- {regdiffusion-0.1.1 → regdiffusion-0.2.1}/docs/downstream_with_pyscenic.md +0 -0
- {regdiffusion-0.1.1 → regdiffusion-0.2.1}/docs/main_api.rst +0 -0
- {regdiffusion-0.1.1 → regdiffusion-0.2.1}/docs/make.bat +0 -0
- {regdiffusion-0.1.1 → regdiffusion-0.2.1}/docs/models.rst +0 -0
- {regdiffusion-0.1.1 → regdiffusion-0.2.1}/docs/quick_tour.md +0 -0
- {regdiffusion-0.1.1 → regdiffusion-0.2.1}/docs/supplements/googled258341a97f33073.html +0 -0
- {regdiffusion-0.1.1 → regdiffusion-0.2.1}/docs/supplements/rd_hammond_Cx3cr1.html +0 -0
- {regdiffusion-0.1.1 → regdiffusion-0.2.1}/docs/supplements/rd_hammond_Fcrls.html +0 -0
- {regdiffusion-0.1.1 → regdiffusion-0.2.1}/docs/supplements/rd_hammond_Hexb.html +0 -0
- {regdiffusion-0.1.1 → regdiffusion-0.2.1}/docs/supplements/rd_hammond_Mertk.html +0 -0
- {regdiffusion-0.1.1 → regdiffusion-0.2.1}/docs/supplements/rd_hammond_P2ry12.html +0 -0
- {regdiffusion-0.1.1 → regdiffusion-0.2.1}/docs/supplements/rd_hammond_Pros1.html +0 -0
- {regdiffusion-0.1.1 → regdiffusion-0.2.1}/docs/supplements/rd_hammond_Sall1.html +0 -0
- {regdiffusion-0.1.1 → regdiffusion-0.2.1}/docs/supplements/rd_hammond_Siglech.html +0 -0
- {regdiffusion-0.1.1 → regdiffusion-0.2.1}/docs/supplements/rd_hammond_Tmem119.html +0 -0
- {regdiffusion-0.1.1 → regdiffusion-0.2.1}/docs/supplements/rd_hammond_Trem2.html +0 -0
- {regdiffusion-0.1.1 → regdiffusion-0.2.1}/docs/supplements.rst +0 -0
- {regdiffusion-0.1.1 → regdiffusion-0.2.1}/example.ipynb +0 -0
- {regdiffusion-0.1.1 → regdiffusion-0.2.1}/regdiffusion/__init__.py +0 -0
- {regdiffusion-0.1.1 → regdiffusion-0.2.1}/regdiffusion/data/__init__.py +0 -0
- {regdiffusion-0.1.1 → regdiffusion-0.2.1}/regdiffusion/data/beeline.py +0 -0
- {regdiffusion-0.1.1 → regdiffusion-0.2.1}/regdiffusion/data/microglia.py +0 -0
- {regdiffusion-0.1.1 → regdiffusion-0.2.1}/regdiffusion/data/utils.py +0 -0
- {regdiffusion-0.1.1 → regdiffusion-0.2.1}/regdiffusion/evaluator.py +0 -0
- {regdiffusion-0.1.1 → regdiffusion-0.2.1}/regdiffusion/logger.py +0 -0
- {regdiffusion-0.1.1 → regdiffusion-0.2.1}/resources/apoe_net.png +0 -0
- {regdiffusion-0.1.1 → regdiffusion-0.2.1}/resources/aucell_mtx.png +0 -0
- {regdiffusion-0.1.1 → regdiffusion-0.2.1}/resources/aucell_umap.png +0 -0
- {regdiffusion-0.1.1 → regdiffusion-0.2.1}/resources/biomarkers.png +0 -0
- {regdiffusion-0.1.1 → regdiffusion-0.2.1}/resources/cellnames.png +0 -0
- {regdiffusion-0.1.1 → regdiffusion-0.2.1}/resources/edgelist.png +0 -0
- {regdiffusion-0.1.1 → regdiffusion-0.2.1}/resources/heatmap.png +0 -0
- {regdiffusion-0.1.1 → regdiffusion-0.2.1}/resources/mecs.png +0 -0
- {regdiffusion-0.1.1 → regdiffusion-0.2.1}/resources/mecs_cluster.png +0 -0
- {regdiffusion-0.1.1 → regdiffusion-0.2.1}/resources/regdiffusion_structure.png +0 -0
- {regdiffusion-0.1.1 → regdiffusion-0.2.1}/resources/regulon_scores.png +0 -0
- {regdiffusion-0.1.1 → regdiffusion-0.2.1}/resources/shinygo.png +0 -0
- {regdiffusion-0.1.1 → regdiffusion-0.2.1}/resources/umap_comparison.png +0 -0
|
@@ -0,0 +1,24 @@
|
|
|
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
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: regdiffusion
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.2.1
|
|
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>
|
|
@@ -29,8 +29,6 @@ RegDiffusion is a very fast unsupervised regulatory network inference algorithm
|
|
|
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.
|
|
30
30
|
```
|
|
31
31
|
|
|
32
|
-

|
|
33
|
-
|
|
34
32
|
## Installation
|
|
35
33
|
|
|
36
34
|
RegDiffusion is on pypi.
|
|
@@ -39,7 +37,13 @@ RegDiffusion is on pypi.
|
|
|
39
37
|
pip install regdiffusion
|
|
40
38
|
```
|
|
41
39
|
|
|
42
|
-
Check out
|
|
40
|
+
Check out [this tutorial](https://tuftsbcb.github.io/RegDiffusion/quick_tour.html) for a quick tour of how to use RegDiffusion! If you would like to integrate results from RegDiffusion into the SCENIC pipeline, checkout [this tutorial](https://tuftsbcb.github.io/RegDiffusion/downstream_with_pyscenic.html).
|
|
41
|
+
|
|
42
|
+
## New in v0.2
|
|
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
|
+
- **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
|
+
|
|
46
|
+

|
|
43
47
|
|
|
44
48
|
## Inferred Networks from RegDiffusion
|
|
45
49
|
Here are two examples of inferred networks from regdiffusion. The networks are coherent with existing literature and across datasets.
|
|
@@ -75,7 +79,7 @@ options:
|
|
|
75
79
|
|
|
76
80
|
## Citation
|
|
77
81
|
|
|
78
|
-
If you find our package useful, consider
|
|
82
|
+
If you find our package useful, consider citing our paper! =)
|
|
79
83
|
|
|
80
84
|
```
|
|
81
85
|
@article{zhu2024noise,
|
|
@@ -10,8 +10,6 @@ RegDiffusion is a very fast unsupervised regulatory network inference algorithm
|
|
|
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.
|
|
11
11
|
```
|
|
12
12
|
|
|
13
|
-

|
|
14
|
-
|
|
15
13
|
## Installation
|
|
16
14
|
|
|
17
15
|
RegDiffusion is on pypi.
|
|
@@ -20,7 +18,13 @@ RegDiffusion is on pypi.
|
|
|
20
18
|
pip install regdiffusion
|
|
21
19
|
```
|
|
22
20
|
|
|
23
|
-
Check out
|
|
21
|
+
Check out [this tutorial](https://tuftsbcb.github.io/RegDiffusion/quick_tour.html) for a quick tour of how to use RegDiffusion! If you would like to integrate results from RegDiffusion into the SCENIC pipeline, checkout [this tutorial](https://tuftsbcb.github.io/RegDiffusion/downstream_with_pyscenic.html).
|
|
22
|
+
|
|
23
|
+
## New in v0.2
|
|
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
|
+
- **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
|
+
|
|
27
|
+

|
|
24
28
|
|
|
25
29
|
## Inferred Networks from RegDiffusion
|
|
26
30
|
Here are two examples of inferred networks from regdiffusion. The networks are coherent with existing literature and across datasets.
|
|
@@ -56,7 +60,7 @@ options:
|
|
|
56
60
|
|
|
57
61
|
## Citation
|
|
58
62
|
|
|
59
|
-
If you find our package useful, consider
|
|
63
|
+
If you find our package useful, consider citing our paper! =)
|
|
60
64
|
|
|
61
65
|
```
|
|
62
66
|
@article{zhu2024noise,
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
# Building Sphinx Documentation
|
|
2
|
+
|
|
3
|
+
## Quick Start
|
|
4
|
+
|
|
5
|
+
To rebuild the documentation, navigate to the `docs/` directory and run:
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
cd docs
|
|
9
|
+
make html
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
The built HTML documentation will be available in `docs/_build/html/`. Open `docs/_build/html/index.html` in your browser to view it.
|
|
13
|
+
|
|
14
|
+
## Common Commands
|
|
15
|
+
|
|
16
|
+
### Build HTML Documentation
|
|
17
|
+
```bash
|
|
18
|
+
make html
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
### Clean Build Directory
|
|
22
|
+
If you encounter issues, clean the build directory first:
|
|
23
|
+
```bash
|
|
24
|
+
make clean
|
|
25
|
+
make html
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
### View Available Build Targets
|
|
29
|
+
```bash
|
|
30
|
+
make help
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
### Other Build Formats
|
|
34
|
+
- `make latexpdf` - Build PDF documentation
|
|
35
|
+
- `make epub` - Build EPUB format
|
|
36
|
+
- `make linkcheck` - Check all external links
|
|
37
|
+
|
|
38
|
+
## Troubleshooting
|
|
39
|
+
|
|
40
|
+
### If `make` command is not found:
|
|
41
|
+
Use the Python module directly:
|
|
42
|
+
```bash
|
|
43
|
+
python -m sphinx -b html . _build/html
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
### If dependencies are missing:
|
|
47
|
+
Install required packages:
|
|
48
|
+
```bash
|
|
49
|
+
pip install sphinx sphinx-book-theme sphinx-copybutton myst-parser sphinxext-napoleon
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
### If autodoc fails to import modules:
|
|
53
|
+
Make sure you're in the correct conda environment and the package is installed:
|
|
54
|
+
```bash
|
|
55
|
+
pip install -e ..
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
## File Structure
|
|
59
|
+
|
|
60
|
+
- `conf.py` - Sphinx configuration file
|
|
61
|
+
- `index.rst` - Main documentation entry point
|
|
62
|
+
- `*.rst` - ReStructuredText source files
|
|
63
|
+
- `*.md` - Markdown files (via myst-parser)
|
|
64
|
+
- `_build/` - Build output directory (generated)
|
|
65
|
+
- `_static/` - Static assets (images, CSS, etc.)
|
|
66
|
+
- `_templates/` - Custom templates
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
# Working with Large Gene Networks
|
|
2
|
+
|
|
3
|
+
RegDiffusion can infer GRNs among 10,000+ genes within minutes on a modern GPU. However, as the number of genes grows, GPU memory becomes the primary bottleneck. This guide covers practical strategies to reduce memory usage and scale to larger networks.
|
|
4
|
+
|
|
5
|
+
## Why Memory Grows Quickly
|
|
6
|
+
|
|
7
|
+
The core of RegDiffusion is a dense adjacency matrix of shape `(n_gene, n_gene)`. For a network with `n` genes, the memory cost scales quadratically. Beyond the adjacency matrix itself, PyTorch's autograd retains multiple `(n_gene, n_gene)` intermediate tensors during each training step for the backward pass — these are the dominant memory cost.
|
|
8
|
+
|
|
9
|
+
## Strategy 1: Memory-Efficient Mode (Recommended)
|
|
10
|
+
|
|
11
|
+
The most effective way to reduce memory is to enable the memory-efficient model variant. This cuts peak GPU memory by approximately **45%** with no impact on accuracy and no slowdown.
|
|
12
|
+
|
|
13
|
+
```python
|
|
14
|
+
trainer = rd.RegDiffusionTrainer(
|
|
15
|
+
exp_array,
|
|
16
|
+
memory_efficient=True,
|
|
17
|
+
device='cuda'
|
|
18
|
+
)
|
|
19
|
+
trainer.train()
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
**What it does:**
|
|
23
|
+
- Uses a custom autograd function for soft thresholding that saves boolean masks (1 byte per entry) instead of float32 tensors (4 bytes per entry), reducing autograd memory by ~8x for these operations
|
|
24
|
+
- Computes sparse regularization loss from random samples of the adjacency matrix instead of materializing the full `(n_gene, n_gene)` matrix, eliminating 3 large intermediate tensors
|
|
25
|
+
|
|
26
|
+
**Impact on accuracy:** Minimal. We benchmarked RegDiffusion and RegDiffusionME on all 7 BEELINE datasets (1000_STRING, 10 repeats each). The ME version tends to be slightly lower but the results are statistically indistinguishable:
|
|
27
|
+
|
|
28
|
+
| Dataset | RegDiffusion AUROC | RegDiffusionME AUROC | RegDiffusion EPR | RegDiffusionME EPR |
|
|
29
|
+
|---------|-------------------|---------------------|-----------------|-------------------|
|
|
30
|
+
| hESC | 0.6531 +/- 0.0009 | 0.6526 +/- 0.0009 | 5.35 +/- 0.06 | 5.35 +/- 0.05 |
|
|
31
|
+
| hHep | 0.6542 +/- 0.0004 | 0.6534 +/- 0.0007 | 3.49 +/- 0.04 | 3.48 +/- 0.04 |
|
|
32
|
+
| mDC | 0.5739 +/- 0.0010 | 0.5734 +/- 0.0011 | 2.25 +/- 0.05 | 2.25 +/- 0.05 |
|
|
33
|
+
| mESC | 0.6127 +/- 0.0005 | 0.6124 +/- 0.0007 | 4.20 +/- 0.05 | 4.20 +/- 0.04 |
|
|
34
|
+
| mHSC-E | 0.7115 +/- 0.0021 | 0.7109 +/- 0.0025 | 8.37 +/- 0.15 | 8.33 +/- 0.15 |
|
|
35
|
+
| mHSC-GM | 0.7424 +/- 0.0023 | 0.7411 +/- 0.0022 | 9.17 +/- 0.09 | 9.12 +/- 0.08 |
|
|
36
|
+
| mHSC-L | 0.6924 +/- 0.0048 | 0.6921 +/- 0.0057 | 7.35 +/- 0.16 | 7.35 +/- 0.18 |
|
|
37
|
+
|
|
38
|
+
## GPU Memory Benchmark
|
|
39
|
+
|
|
40
|
+
We measured peak GPU memory during training with synthetic data (200 cells, 20 training steps) across different gene counts:
|
|
41
|
+
|
|
42
|
+
| Genes | Default | ME | ME Savings | ME + AMP |
|
|
43
|
+
|-------|---------|------|-----------|----------|
|
|
44
|
+
| 5,000 | 2.1 GB | 1.2 GB | 41% | 1.1 GB |
|
|
45
|
+
| 10,000 | 7.3 GB | 4.0 GB | 45% | 3.8 GB |
|
|
46
|
+
| 15,000 | 15.7 GB | 8.5 GB | 46% | 8.1 GB |
|
|
47
|
+
| 20,000 | 27.3 GB | 14.6 GB | 47% | 14.1 GB |
|
|
48
|
+
| 25,000 | 42.1 GB | 22.4 GB | 47% | 21.8 GB |
|
|
49
|
+
| 30,000 | 60.2 GB | 31.8 GB | 47% | 31.1 GB |
|
|
50
|
+
|
|
51
|
+
The memory-efficient mode also runs slightly faster than default (about 15% faster), since fewer intermediate tensors need to be allocated and freed.
|
|
52
|
+
|
|
53
|
+
## Strategy 2: Mixed Precision Training
|
|
54
|
+
|
|
55
|
+
Automatic mixed precision (AMP) provides a modest additional memory reduction (about 5%) on top of memory-efficient mode. It runs the forward pass in bfloat16. However, AMP increases training time by roughly 2x due to dtype casting overhead, so it is only recommended if you need the last few percent of memory savings.
|
|
56
|
+
|
|
57
|
+
```python
|
|
58
|
+
trainer = rd.RegDiffusionTrainer(
|
|
59
|
+
exp_array,
|
|
60
|
+
memory_efficient=True,
|
|
61
|
+
use_amp=True,
|
|
62
|
+
device='cuda'
|
|
63
|
+
)
|
|
64
|
+
trainer.train()
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
**Requirements:** A GPU with bfloat16 support (NVIDIA Ampere architecture or newer, e.g., A100, RTX 3090, RTX 4090).
|
|
68
|
+
|
|
69
|
+
## Strategy 3: Gene Filtering
|
|
70
|
+
|
|
71
|
+
Reducing the number of genes is always effective since memory scales quadratically. RegDiffusion does not require heavy gene filtering, but removing clearly uninformative genes can save substantial memory with minimal impact on results.
|
|
72
|
+
|
|
73
|
+
**Remove non-expressed genes:** Genes with zero total counts across all cells carry no information and should always be removed.
|
|
74
|
+
|
|
75
|
+
```python
|
|
76
|
+
import scanpy as sc
|
|
77
|
+
|
|
78
|
+
# Remove genes expressed in fewer than 10 cells
|
|
79
|
+
sc.pp.filter_genes(adata, min_cells=10)
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
**Consider highly variable gene selection:** If your dataset has 25,000+ genes and you are memory constrained, selecting the top 15,000-20,000 highly variable genes is a reasonable compromise.
|
|
83
|
+
|
|
84
|
+
```python
|
|
85
|
+
sc.pp.highly_variable_genes(adata, n_top_genes=15000)
|
|
86
|
+
adata = adata[:, adata.var.highly_variable]
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
## Running on CPU
|
|
90
|
+
|
|
91
|
+
If you don't have access to a GPU with enough memory, RegDiffusion also runs on CPU. It will be slower (but still much faster than GRNBoost2) but has no memory constraint from GPU VRAM.
|
|
92
|
+
|
|
93
|
+
```python
|
|
94
|
+
trainer = rd.RegDiffusionTrainer(
|
|
95
|
+
exp_array,
|
|
96
|
+
device='cpu',
|
|
97
|
+
n_steps=1000
|
|
98
|
+
)
|
|
99
|
+
trainer.train()
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
For reference, inference on a 15,000-gene network takes roughly 3 hours on a mid-range 12-core CPU versus under 5 minutes on an A100 GPU.
|
|
@@ -13,7 +13,7 @@ maintainers = [
|
|
|
13
13
|
]
|
|
14
14
|
readme = "README.md"
|
|
15
15
|
license = {file = "LICENSE"}
|
|
16
|
-
version = "0.
|
|
16
|
+
version = "0.2.1"
|
|
17
17
|
description = "Gene Regulatory Networks Inference using diffusion model"
|
|
18
18
|
|
|
19
19
|
classifiers = ["License :: OSI Approved :: Apache Software License"]
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import argparse
|
|
2
2
|
import os
|
|
3
3
|
import numpy as np
|
|
4
|
+
import scipy.sparse as sp
|
|
4
5
|
import scanpy as sc
|
|
5
6
|
from .trainer import RegDiffusionTrainer
|
|
6
7
|
|
|
@@ -47,11 +48,21 @@ def main():
|
|
|
47
48
|
|
|
48
49
|
print("Applying log transformation on the dataset...")
|
|
49
50
|
x = adata.X
|
|
50
|
-
if (x
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
51
|
+
if sp.issparse(x):
|
|
52
|
+
if (x < 0).nnz > 0:
|
|
53
|
+
raise ValueError("Negative values spotted in the data. Please only provide count data in this CLI tool. ")
|
|
54
|
+
residual = x.copy()
|
|
55
|
+
residual.data = residual.data - residual.data.astype(int)
|
|
56
|
+
if abs(residual.sum()) > 1:
|
|
57
|
+
raise ValueError("Data might have been log transformed. Please only provide count data in this CLI tool. ")
|
|
58
|
+
x = x.copy()
|
|
59
|
+
x.data = np.log1p(x.data) # log(0+1)=0 stays sparse
|
|
60
|
+
else:
|
|
61
|
+
if (x < 0).sum() > 0:
|
|
62
|
+
raise ValueError("Negative values spotted in the data. Please only provide count data in this CLI tool. ")
|
|
63
|
+
if (x - x.astype(int)).sum() > 1:
|
|
64
|
+
raise ValueError("Data might have been log transformed. Please only provide count data in this CLI tool. ")
|
|
65
|
+
x = np.log(x + 1.0)
|
|
55
66
|
|
|
56
67
|
print("Initializing RegDiffusion trainer and starting training...")
|
|
57
68
|
rd_trainer = RegDiffusionTrainer(x)
|
|
@@ -88,10 +88,17 @@ class GRN:
|
|
|
88
88
|
|
|
89
89
|
self.calculated_neighbors = {}
|
|
90
90
|
|
|
91
|
-
def remove_weak_edges(threshold=None):
|
|
92
|
-
|
|
91
|
+
def remove_weak_edges(self, threshold=None):
|
|
92
|
+
"""
|
|
93
|
+
Remove edges with absolute weight below the threshold.
|
|
94
|
+
|
|
95
|
+
Args:
|
|
96
|
+
threshold (float): Edges with absolute weight below this value
|
|
97
|
+
will be set to zero.
|
|
98
|
+
"""
|
|
99
|
+
if threshold is not None and threshold > self.cutoff_threshold:
|
|
93
100
|
self.cutoff_threshold = threshold
|
|
94
|
-
|
|
101
|
+
self.adj_matrix[np.abs(self.adj_matrix) < threshold] = 0
|
|
95
102
|
|
|
96
103
|
def extract_edgelist(self, k: int = 20, workers: int = 2) -> pd.DataFrame:
|
|
97
104
|
"""
|
|
@@ -119,7 +126,9 @@ class GRN:
|
|
|
119
126
|
"""
|
|
120
127
|
Deprecated API. Use extract_edgelist instead.
|
|
121
128
|
"""
|
|
122
|
-
|
|
129
|
+
import warnings
|
|
130
|
+
warnings.warn("get_edgelist is deprecated, use extract_edgelist instead", DeprecationWarning)
|
|
131
|
+
return self.extract_edgelist(k, workers)
|
|
123
132
|
|
|
124
133
|
|
|
125
134
|
def extract_node_sources_as_indices(self, gene: str, k: int = 20) -> Dict:
|
|
@@ -439,6 +448,196 @@ class GRN:
|
|
|
439
448
|
def __str__(self):
|
|
440
449
|
return self.__repr__()
|
|
441
450
|
|
|
451
|
+
def compute_network_statistics(self) -> Dict:
|
|
452
|
+
"""
|
|
453
|
+
Compute comprehensive network statistics.
|
|
454
|
+
"""
|
|
455
|
+
adj = np.abs(self.adj_matrix)
|
|
456
|
+
|
|
457
|
+
# Basic statistics
|
|
458
|
+
n_edges = np.sum(adj > self.cutoff_threshold)
|
|
459
|
+
density = n_edges / (self.n_tfs * self.n_genes)
|
|
460
|
+
|
|
461
|
+
# Degree statistics
|
|
462
|
+
in_degrees = adj.sum(axis=0)
|
|
463
|
+
out_degrees = adj.sum(axis=1)
|
|
464
|
+
|
|
465
|
+
stats = {
|
|
466
|
+
'n_tfs': self.n_tfs,
|
|
467
|
+
'n_genes': self.n_genes,
|
|
468
|
+
'n_edges': int(n_edges),
|
|
469
|
+
'density': float(density),
|
|
470
|
+
'mean_in_degree': float(in_degrees.mean()),
|
|
471
|
+
'std_in_degree': float(in_degrees.std()),
|
|
472
|
+
'max_in_degree': float(in_degrees.max()),
|
|
473
|
+
'mean_out_degree': float(out_degrees.mean()),
|
|
474
|
+
'std_out_degree': float(out_degrees.std()),
|
|
475
|
+
'max_out_degree': float(out_degrees.max()),
|
|
476
|
+
'mean_edge_weight': float(adj[adj > 0].mean()) if n_edges > 0 else 0,
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
return stats
|
|
480
|
+
|
|
481
|
+
def find_hub_genes(self, top_k: int = 10, direction: str = 'out') -> pd.DataFrame:
|
|
482
|
+
"""
|
|
483
|
+
Find hub genes based on degree centrality.
|
|
484
|
+
|
|
485
|
+
Args:
|
|
486
|
+
top_k: Number of top hub genes to return
|
|
487
|
+
direction: 'in' (most regulated), 'out' (most regulating), or 'both'
|
|
488
|
+
"""
|
|
489
|
+
adj = np.abs(self.adj_matrix)
|
|
490
|
+
results = []
|
|
491
|
+
|
|
492
|
+
if direction in ['out', 'both']:
|
|
493
|
+
out_degrees = adj.sum(axis=1)
|
|
494
|
+
top_out_idx = np.argsort(out_degrees)[-top_k:][::-1]
|
|
495
|
+
for idx in top_out_idx:
|
|
496
|
+
results.append({
|
|
497
|
+
'gene': self.tf_names[idx],
|
|
498
|
+
'out_degree': out_degrees[idx],
|
|
499
|
+
'type': 'regulator'
|
|
500
|
+
})
|
|
501
|
+
|
|
502
|
+
if direction in ['in', 'both']:
|
|
503
|
+
in_degrees = adj.sum(axis=0)
|
|
504
|
+
top_in_idx = np.argsort(in_degrees)[-top_k:][::-1]
|
|
505
|
+
for idx in top_in_idx:
|
|
506
|
+
results.append({
|
|
507
|
+
'gene': self.gene_names[idx],
|
|
508
|
+
'in_degree': in_degrees[idx],
|
|
509
|
+
'type': 'target'
|
|
510
|
+
})
|
|
511
|
+
|
|
512
|
+
return pd.DataFrame(results)
|
|
513
|
+
|
|
514
|
+
def find_regulatory_paths(
|
|
515
|
+
self, source: str, target: str, max_hops: int = 3, top_k_per_hop: int = 10
|
|
516
|
+
) -> List[List[str]]:
|
|
517
|
+
"""
|
|
518
|
+
Find regulatory paths between two genes using BFS.
|
|
519
|
+
"""
|
|
520
|
+
from collections import deque
|
|
521
|
+
|
|
522
|
+
if source not in self.tf_indices or target not in self.gene_indices:
|
|
523
|
+
return []
|
|
524
|
+
|
|
525
|
+
paths = []
|
|
526
|
+
queue = deque([[source]])
|
|
527
|
+
visited = {source}
|
|
528
|
+
|
|
529
|
+
while queue and len(paths) < 100: # Limit search
|
|
530
|
+
path = queue.popleft()
|
|
531
|
+
if len(path) > max_hops + 1:
|
|
532
|
+
break
|
|
533
|
+
|
|
534
|
+
current = path[-1]
|
|
535
|
+
if current == target and len(path) > 1:
|
|
536
|
+
paths.append(path)
|
|
537
|
+
continue
|
|
538
|
+
|
|
539
|
+
# Get top-k neighbors
|
|
540
|
+
if current in self.tf_indices:
|
|
541
|
+
targets = self.extract_node_targets_as_indices(current, top_k_per_hop)
|
|
542
|
+
for idx in targets['gene_indices']:
|
|
543
|
+
neighbor = self.gene_names[idx]
|
|
544
|
+
if neighbor not in visited or neighbor == target:
|
|
545
|
+
visited.add(neighbor)
|
|
546
|
+
queue.append(path + [neighbor])
|
|
547
|
+
|
|
548
|
+
return paths
|
|
549
|
+
|
|
550
|
+
def to_networkx(self, threshold: float = None) -> 'nx.DiGraph':
|
|
551
|
+
"""
|
|
552
|
+
Convert GRN to NetworkX DiGraph for advanced graph analysis.
|
|
553
|
+
"""
|
|
554
|
+
import networkx as nx
|
|
555
|
+
|
|
556
|
+
G = nx.DiGraph()
|
|
557
|
+
G.add_nodes_from(self.gene_names)
|
|
558
|
+
|
|
559
|
+
adj = self.adj_matrix
|
|
560
|
+
threshold = threshold or self.cutoff_threshold
|
|
561
|
+
|
|
562
|
+
for i in range(self.n_tfs):
|
|
563
|
+
for j in range(self.n_genes):
|
|
564
|
+
if abs(adj[i, j]) > threshold:
|
|
565
|
+
G.add_edge(
|
|
566
|
+
self.tf_names[i],
|
|
567
|
+
self.gene_names[j],
|
|
568
|
+
weight=float(adj[i, j])
|
|
569
|
+
)
|
|
570
|
+
|
|
571
|
+
return G
|
|
572
|
+
|
|
573
|
+
def compute_centrality(self, method: str = 'pagerank') -> pd.DataFrame:
|
|
574
|
+
"""
|
|
575
|
+
Compute centrality measures for all genes.
|
|
576
|
+
|
|
577
|
+
Args:
|
|
578
|
+
method: 'pagerank', 'betweenness', 'eigenvector', or 'all'
|
|
579
|
+
"""
|
|
580
|
+
import networkx as nx
|
|
581
|
+
G = self.to_networkx()
|
|
582
|
+
|
|
583
|
+
results = {'gene': list(G.nodes())}
|
|
584
|
+
|
|
585
|
+
if method in ['pagerank', 'all']:
|
|
586
|
+
pr = nx.pagerank(G, weight='weight')
|
|
587
|
+
results['pagerank'] = [pr.get(g, 0) for g in results['gene']]
|
|
588
|
+
|
|
589
|
+
if method in ['betweenness', 'all']:
|
|
590
|
+
bc = nx.betweenness_centrality(G, weight='weight')
|
|
591
|
+
results['betweenness'] = [bc.get(g, 0) for g in results['gene']]
|
|
592
|
+
|
|
593
|
+
if method in ['eigenvector', 'all']:
|
|
594
|
+
try:
|
|
595
|
+
ec = nx.eigenvector_centrality(G, weight='weight', max_iter=1000)
|
|
596
|
+
results['eigenvector'] = [ec.get(g, 0) for g in results['gene']]
|
|
597
|
+
except nx.PowerIterationFailedConvergence:
|
|
598
|
+
results['eigenvector'] = [0] * len(results['gene'])
|
|
599
|
+
|
|
600
|
+
return pd.DataFrame(results).sort_values(
|
|
601
|
+
by=list(results.keys())[1], ascending=False
|
|
602
|
+
)
|
|
603
|
+
|
|
604
|
+
def to_csv(self, file_path: str, k: int = -1, workers: int = 4):
|
|
605
|
+
"""Export edgelist to CSV."""
|
|
606
|
+
edgelist = self.extract_edgelist(k=k, workers=workers)
|
|
607
|
+
edgelist.to_csv(file_path, index=False)
|
|
608
|
+
|
|
609
|
+
def to_gml(self, file_path: str, threshold: float = None):
|
|
610
|
+
"""Export to GML format for Cytoscape/Gephi."""
|
|
611
|
+
import networkx as nx
|
|
612
|
+
G = self.to_networkx(threshold)
|
|
613
|
+
nx.write_gml(G, file_path)
|
|
614
|
+
|
|
615
|
+
def to_graphml(self, file_path: str, threshold: float = None):
|
|
616
|
+
"""Export to GraphML format."""
|
|
617
|
+
import networkx as nx
|
|
618
|
+
G = self.to_networkx(threshold)
|
|
619
|
+
nx.write_graphml(G, file_path)
|
|
620
|
+
|
|
621
|
+
def to_cytoscape_json(self, file_path: str, k: int = 100):
|
|
622
|
+
"""Export to Cytoscape JSON format."""
|
|
623
|
+
import json
|
|
624
|
+
|
|
625
|
+
edgelist = self.extract_edgelist(k=k)
|
|
626
|
+
nodes = set(edgelist['source']) | set(edgelist['target'])
|
|
627
|
+
|
|
628
|
+
cytoscape_data = {
|
|
629
|
+
"elements": {
|
|
630
|
+
"nodes": [{"data": {"id": n, "label": n}} for n in nodes],
|
|
631
|
+
"edges": [
|
|
632
|
+
{"data": {"source": row['source'], "target": row['target'], "weight": row['weight']}}
|
|
633
|
+
for _, row in edgelist.iterrows()
|
|
634
|
+
]
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
with open(file_path, 'w') as f:
|
|
639
|
+
json.dump(cytoscape_data, f, indent=2)
|
|
640
|
+
|
|
442
641
|
def read_hdf5(file_path: str):
|
|
443
642
|
"""
|
|
444
643
|
Read HDF5 file as a GRN object. See the documentation for GRN for details.
|
|
@@ -87,6 +87,8 @@ class RegDiffusion(nn.Module):
|
|
|
87
87
|
self.gene_dim = hidden_dims[0]
|
|
88
88
|
self.adj_dropout=adj_dropout
|
|
89
89
|
self.gene_reg_norm = 1/(n_gene-1)
|
|
90
|
+
self.celltype_dim = celltype_dim
|
|
91
|
+
self.n_celltype = n_celltype
|
|
90
92
|
|
|
91
93
|
adj_A = torch.ones(n_gene, n_gene) * self.gene_reg_norm * init_coef
|
|
92
94
|
self.adj_A = nn.Parameter(adj_A, requires_grad =True, )
|
|
@@ -119,30 +121,24 @@ class RegDiffusion(nn.Module):
|
|
|
119
121
|
|
|
120
122
|
self.final = nn.Linear(hidden_dims[-1]-1, 1)
|
|
121
123
|
|
|
122
|
-
self.zeros_nonparam = nn.Parameter(
|
|
123
|
-
torch.zeros(n_gene, n_gene), requires_grad=False)
|
|
124
|
-
self.eye_nonparam = nn.Parameter(
|
|
125
|
-
torch.eye(n_gene), requires_grad=False)
|
|
126
|
-
self.mask_nonparam = nn.Parameter(
|
|
127
|
-
1 - torch.eye(n_gene), requires_grad=False)
|
|
128
|
-
|
|
129
124
|
def soft_thresholding(self, x, tau):
|
|
130
|
-
return torch.sign(x) * torch.
|
|
131
|
-
self.zeros_nonparam, torch.abs(x) - tau)
|
|
125
|
+
return torch.sign(x) * F.relu(torch.abs(x) - tau)
|
|
132
126
|
|
|
133
127
|
def I_minus_A(self):
|
|
134
|
-
|
|
135
|
-
if self.
|
|
128
|
+
eye = torch.eye(self.n_gene, device=self.adj_A.device)
|
|
129
|
+
if self.training:
|
|
136
130
|
A_dropout = (torch.rand_like(self.adj_A)>self.adj_dropout).float()
|
|
137
131
|
A_dropout /= (1-self.adj_dropout)
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
132
|
+
A_dropout.fill_diagonal_(0)
|
|
133
|
+
mask = A_dropout
|
|
134
|
+
else:
|
|
135
|
+
mask = 1 - eye
|
|
136
|
+
clean_A = self.soft_thresholding(self.adj_A, self.gene_reg_norm/2) * mask
|
|
137
|
+
return eye - clean_A
|
|
142
138
|
|
|
143
139
|
def get_adj_(self):
|
|
144
|
-
|
|
145
|
-
|
|
140
|
+
mask = 1 - torch.eye(self.n_gene, device=self.adj_A.device)
|
|
141
|
+
return self.soft_thresholding(self.adj_A, self.gene_reg_norm/2) * mask
|
|
146
142
|
|
|
147
143
|
def get_adj(self):
|
|
148
144
|
adj = self.get_adj_().detach().cpu().numpy() / self.gene_reg_norm
|
|
@@ -159,7 +155,13 @@ class RegDiffusion(nn.Module):
|
|
|
159
155
|
|
|
160
156
|
def forward(self, x, t, ct):
|
|
161
157
|
h_time = self.time_mlp(t)
|
|
162
|
-
|
|
158
|
+
if self.n_celltype is not None:
|
|
159
|
+
h_celltype = self.celltype_emb(ct)
|
|
160
|
+
else:
|
|
161
|
+
# Create zero tensor for cell type embedding when not using cell types
|
|
162
|
+
h_celltype = torch.zeros(
|
|
163
|
+
x.shape[0], self.celltype_dim, device=x.device, dtype=x.dtype
|
|
164
|
+
)
|
|
163
165
|
original = x.unsqueeze(-1)
|
|
164
166
|
h_x = self.gene_emb(x)
|
|
165
167
|
for i, block in enumerate(self.blocks):
|