File size: 10,335 Bytes
0252cb7 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 | ---
license: other
tags:
- code
- generative-modeling
- flow-matching
- diffusion
- time-series
---
> Hugging Face mirror of the GitHub code release
> [`v1.0.0`](https://github.com/MrRezaeiUofT/Implicit_Dynamical_Flow_Fusion_for_Genereative_Modeling/releases/tag/v1.0.0).
> The paper and the trained checkpoints are in [rezapop/IDFF](https://huggingface.co/rezapop/IDFF).
<h1 align="center">Implicit Dynamical Flow Fusion (IDFF) for Generative Modeling</h1>
<p align="center">
<a href="https://arxiv.org/abs/2409.14599">
<img src="https://img.shields.io/badge/arXiv-Paper-red?logo=arxiv" alt="arXiv">
</a>
</p>
Reference implementation of **IDFF** (TMLR). IDFF trains one network with two heads, a denoiser
$\hat{\mathbf x}_1(\mathbf x_t,t)$ and a score $\hat s_t(\mathbf x_t,t)$, and samples with a
conditional-flow-matching (CFM) drift augmented by a score-Langevin term and a matched diffusion:
$$
d\mathbf x_t=\Big[\hat{\mathbf v}_t+\gamma_t^1\,\hat s_t+\sum_{k=2}^{K}\gamma_t^k\,(\nabla_{\mathbf x}^{k-1}\hat s_t)[\mathbf u_t]^{k-1}\Big]dt+g_t\,d\mathbf w_t,
\qquad \hat{\mathbf v}_t=\frac{\hat{\mathbf x}_1-\mathbf x_t}{1-t},\quad g_t^2=2\gamma_t^1 .
$$
* **K = 1 (default).** With the exact score, the score-Langevin pair leaves the CFM marginals
$p_t$ unchanged in continuous time; the benefit is robustness to coarse discretisation, i.e. fewer
network function evaluations (NFE).
* **K ≥ 2 (optional).** Curvature terms along the flow direction $\mathbf u_t=\hat{\mathbf v}_t/\|\hat{\mathbf v}_t\|$,
computed from the same score head with forward-mode JVPs (no extra networks), with
$\gamma_t^k=\alpha_k\gamma_t^1\Delta t^{k-1}$.
<p align="center">
<img src="2D_examples/ImageGen.png" alt="IDFF image generation example" width="90%"/>
</p>
## Repository layout
```
idff/ reference implementation
core.py probability path, schedules, IDFF loss, time-series training pairs, OT coupling
models.py joint-head MLP (denoiser + score), optional sequence-position embedding
sampling.py Euler-Maruyama sampler (Algorithm 1) and autoregressive sampler (Algorithm 4)
datasets.py, metrics.py
2D_examples/idff_2d.py 2-D toy distributions: CFM, Stochastic CFM and IDFF K=1/2/3 across NFE budgets
timeseris_example/
MD_simulation.py polyALA molecular-dynamics surrogate (46 dihedral angles)
attractors.py Lorenz attractor
data/polyALA_angles.npz
tests/test_idff.py unit tests and numerical checks of the theory
scripts/make_gifs.py renders the animations in assets/ from the trained example models
torchcfm/ vendored torchcfm (Tong et al., MIT); used for the optional OT coupling
```
## Installation
```bash
pip install -r requirements.txt # torch, numpy, scipy, matplotlib (+ pot for OT coupling)
pytest -q # ~15 s on a laptop CPU
```
Everything below runs on a CPU; a GPU is not required for the 2-D and time-series examples.
## Usage
```python
import torch
from idff import JointHeadMLP, idff_loss, sample
model = JointHeadMLP(dim=2, sigma0=0.2)
opt = torch.optim.Adam(model.parameters(), lr=1e-3)
for _ in range(60000):
x1 = my_data_sampler(512) # (batch, dim)
loss, _ = idff_loss(model, x1, sigma0=0.2) # denoiser + score-matching terms
opt.zero_grad(); loss.backward(); opt.step()
nfe = 5
x = sample(model, torch.randn(1000, 2), nfe=nfe, K=1, gamma_bar=8.0 / nfe) # IDFF, K = 1
x_cfm = sample(model, torch.randn(1000, 2), nfe=nfe, K=0) # deterministic CFM
```
Key arguments of `sample`: `K` (0 = deterministic CFM), `gamma_bar` and `schedule` (Langevin
amplitude $\gamma_t^1$, default Beta(2,2) $4\bar\gamma t(1-t)$), `alphas` ($\alpha_k$ for $k\ge2$),
`diffusion_scale` ($g_t^2/\gamma_t^1$, default 2), and `score_drift` (set to `False` for the
noise-only ablation).
## Examples and results
All numbers below were produced by the scripts in this repository (CPU, a few minutes each).
Every compared sampler uses the **same trained network**, so differences come from the sampler only.
### 2-D toy distributions
```bash
python 2D_examples/idff_2d.py --dataset checkerboard # also: 8gaussians, moons; --coupling ot for OT-IDFF
```
<p align="center">
<img src="assets/idff_2d.gif" alt="CFM vs IDFF K=1 and K=2 sampling at NFE=5 on 8 Gaussians" width="90%"/>
</p>
<p align="center"><em>Sampling 8 Gaussians with 5 network evaluations from the same noise and the same trained
network: deterministic CFM (blue), IDFF K=1 (red) and IDFF K=2 (purple), with the hyper-parameters selected
on validation data. Frames between sampler steps are interpolated for display.</em></p>
Hyper-parameters are selected per NFE budget on a separate validation sample: $\bar\gamma$ for K=1
(from $c/\mathrm{NFE}$), then $\alpha_2$ for K=2 with the same $\bar\gamma$ ($\alpha_2=0$, i.e. K=1, is
always a candidate). From the same trained network, IDFF K=1 reaches the target distribution in far
fewer steps than deterministic CFM, noise alone (Stochastic CFM) helps only at the smallest budgets,
and the curvature correction (K=2) further improves on K=1 at most budgets. Per-budget test results
for 8gaussians, checkerboard and moons are written to `2D_examples/outputs/<dataset>/` (CSV and plots).
At NFE = 2 all samplers coincide: $\gamma_t^1$ vanishes at $t=0$ and the coefficients are switched
off on the final step, so IDFF needs at least three steps to differ from CFM. With the paper's
default $\alpha_2\approx0.05$ the K = 2 term is about 1% of the K = 1 Langevin term and changes nothing
visible; the selected values are larger and mostly negative ($\alpha_2\in[-4,-0.5]$, see each
`config.json`). The deviation bound depends on $\alpha_k^2$, so the theory does not fix the sign.
### Molecular dynamics (polyALA)
```bash
python timeseris_example/MD_simulation.py --nfes 3 5 10 --sweep
```
Free autoregressive rollouts (5 trajectories x 3 seeds) compared with the simulated trajectory;
MAE/RMSE use the wrapped angular difference (degrees).
| sampler | NFE=3 MAE / CC | NFE=5 MAE / CC | NFE=10 MAE / CC |
|---|---|---|---|
| CFM (det.) | 2.99 / 99.8% | 2.61 / 99.8% | 2.34 / 99.9% |
| IDFF K=1 ($\gamma_{\rm rel}=1$) | 3.93 / 99.7% | 3.92 / 99.7% | 3.63 / 99.7% |
| IDFF K=2 ($\gamma_{\rm rel}=1$, $\alpha_2=0.05$) | 3.93 / 99.7% | 3.92 / 99.7% | 3.63 / 99.7% |
On this task the deterministic sampler is already very accurate, and adding the Langevin pair does
not improve it at any amplitude in the sweep, nor does K = 2 for any $\alpha_2$ tried, positive or
negative (`evaluation_results.csv`). This example has a single trajectory and no validation split, so
its settings are fixed a priori rather than selected.
### Lorenz attractor
```bash
python timeseris_example/attractors.py --system lorenz
```
<p align="center">
<img src="assets/idff_lorenz.gif" alt="CFM, IDFF K=1 and IDFF K=2 rollouts on the Lorenz attractor" width="95%"/>
</p>
<p align="center"><em>Autoregressive rollouts over a whole 2000-step held-out Lorenz trajectory at 5 NFE per frame:
CFM (blue), IDFF K=1 (red) and IDFF K=2 (purple), all from one trained network, the same first frame and the
same noise, against the simulated trajectory (grey).</em></p>
Held-out 2000-step trajectories, test metrics averaged over 10 sampling seeds; $\bar\gamma$ and
$\alpha_2$ are chosen per budget on validation trajectories by how well long rollouts reproduce the
attractor's state distribution. CFM has the lowest one-step and 20-step errors at every budget, while
the long IDFF K=1 rollouts reproduce the attractor's state distribution more closely on average at 5
and 10 NFE. On this system the curvature correction does not help: validation selects $\alpha_2=0$
(i.e. K=1) at 3 and 10 NFE, and the value selected at 5 NFE does slightly worse than K=1 on the test
trajectories. See `timeseris_example/outputs/lorenz/results.csv`.
## Implementation notes
* **Training objective** (`idff_loss`): $\beta(t)^2\|\hat{\mathbf x}_1-\mathbf x_1\|^2+\sigma_t^2\|\hat s_t+\boldsymbol\epsilon/\sigma_t\|^2$
with $\sigma_t=\sigma_0\sqrt{t(1-t)}$ and $\beta(t)=(1-t+10^{-2})^{-1}$. By Fisher's identity the score
head converges to $\nabla\log p_t$; `tests/test_idff.py` checks this against the closed-form score on
Gaussian data. The target $-\boldsymbol\epsilon/\sigma_t$ has high variance, so the score head needs
long training (60k iterations in the 2-D example).
* **Sampler time grid.** Step $i$ uses $t_i=i/\mathrm{NFE}$, so exactly NFE network evaluations are made
(K = 2 adds one JVP per step). The final step uses $\gamma=0$; that pure CFM Euler step from
$t=1-\Delta t$ equals the denoiser read-out $\hat{\mathbf x}_1$.
* **Hyper-parameter selection.** Every example selects $\bar\gamma$ (K=1) and then $\alpha_2$ (K=2,
same $\bar\gamma$) per NFE budget on validation data only; test data are never used for tuning. The
sign of $\alpha_k$ is free, and $\alpha_2=0$ is always a candidate.
* **Scale of $\bar\gamma$.** The paper's $\bar\gamma\in[0.1,0.3]$ refers to a unit-variance base $N(0,I)$.
In the time-series models the base is the previous frame plus $N(0,\sigma_0^2 I)$, so $p_t$ has width
$\sim\sigma_0$; the scripts set $\bar\gamma=\gamma_{\rm rel}\,\sigma_0^2$ to keep the Langevin step stable.
* **Velocity field.** $\hat{\mathbf v}_t=(\hat{\mathbf x}_1-\mathbf x_t)/(1-t)$ is the exact marginal
field when $\sigma_0\to0$; for $\sigma_0>0$ it differs from it by $O(\sigma_0^2)$.
* **Smooth activations.** The networks use SiLU written as $x\,\sigma(x)$, which supports the nested
forward-mode JVPs needed for K ≥ 3 (PyTorch's fused SiLU kernel does not).
* The score head output is divided by the local noise scale of $p_t$ (a fixed preconditioner); this
does not change what the head is trained to represent.
* The image-generation experiments of the paper (ScoreSDE / DiT backbones) are not included here.
## Citation
```
@misc{rezaei2025implicitdynamicalflowfusion,
title={Implicit Dynamical Flow Fusion (IDFF) for Generative Modeling},
author={Mohammad R. Rezaei and Milos R. Popovic and Milad Lankarany and Rahul G. Krishnan},
year={2025},
eprint={2409.14599},
archivePrefix={arXiv},
primaryClass={cs.LG},
url={https://arxiv.org/abs/2409.14599},
}
```
|