rezapop commited on
Commit
0252cb7
·
verified ·
1 Parent(s): a7316b6

IDFF code release v1.0.0 (mirror of GitHub)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +8 -0
  2. .github/workflows/python-app.yml +30 -0
  3. .gitignore +7 -0
  4. 2D_examples/ImageGen.png +3 -0
  5. 2D_examples/idff_2d.py +260 -0
  6. 2D_examples/outputs/8gaussians/config.json +67 -0
  7. 2D_examples/outputs/8gaussians/idff_model.pt +3 -0
  8. 2D_examples/outputs/8gaussians/mmd_results.csv +26 -0
  9. 2D_examples/outputs/8gaussians/mmd_vs_nfe.png +0 -0
  10. 2D_examples/outputs/8gaussians/samples_grid.png +3 -0
  11. 2D_examples/outputs/checkerboard/config.json +67 -0
  12. 2D_examples/outputs/checkerboard/idff_model.pt +3 -0
  13. 2D_examples/outputs/checkerboard/mmd_results.csv +26 -0
  14. 2D_examples/outputs/checkerboard/mmd_vs_nfe.png +0 -0
  15. 2D_examples/outputs/checkerboard/samples_grid.png +3 -0
  16. 2D_examples/outputs/moons/config.json +67 -0
  17. 2D_examples/outputs/moons/idff_model.pt +3 -0
  18. 2D_examples/outputs/moons/mmd_results.csv +26 -0
  19. 2D_examples/outputs/moons/mmd_vs_nfe.png +0 -0
  20. 2D_examples/outputs/moons/samples_grid.png +3 -0
  21. README.md +200 -0
  22. assets/idff_2d.gif +3 -0
  23. assets/idff_lorenz.gif +3 -0
  24. idff/__init__.py +21 -0
  25. idff/core.py +125 -0
  26. idff/datasets.py +103 -0
  27. idff/metrics.py +52 -0
  28. idff/models.py +101 -0
  29. idff/sampling.py +135 -0
  30. requirements.txt +5 -0
  31. scripts/make_gifs.py +176 -0
  32. tests/test_idff.py +259 -0
  33. timeseris_example/MD_simulation.py +202 -0
  34. timeseris_example/attractors.py +229 -0
  35. timeseris_example/data/polyALA_angles.npz +3 -0
  36. timeseris_example/outputs/lorenz/config.json +57 -0
  37. timeseris_example/outputs/lorenz/idff_model.pt +3 -0
  38. timeseris_example/outputs/lorenz/results.csv +13 -0
  39. timeseris_example/outputs/lorenz/rollout.png +3 -0
  40. timeseris_example/outputs/polyALA/config.json +19 -0
  41. timeseris_example/outputs/polyALA/evaluation_results.csv +40 -0
  42. timeseris_example/outputs/polyALA/idff_md.pt +3 -0
  43. timeseris_example/outputs/polyALA/md_samples.png +3 -0
  44. torchcfm/__init__.py +2 -0
  45. torchcfm/conditional_flow_matching.py +606 -0
  46. torchcfm/models/__init__.py +1 -0
  47. torchcfm/models/models.py +53 -0
  48. torchcfm/models/unet/__init__.py +1 -0
  49. torchcfm/models/unet/fp16_util.py +216 -0
  50. torchcfm/models/unet/logger.py +469 -0
.gitattributes CHANGED
@@ -33,3 +33,11 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ 2D_examples/ImageGen.png filter=lfs diff=lfs merge=lfs -text
37
+ 2D_examples/outputs/8gaussians/samples_grid.png filter=lfs diff=lfs merge=lfs -text
38
+ 2D_examples/outputs/checkerboard/samples_grid.png filter=lfs diff=lfs merge=lfs -text
39
+ 2D_examples/outputs/moons/samples_grid.png filter=lfs diff=lfs merge=lfs -text
40
+ assets/idff_2d.gif filter=lfs diff=lfs merge=lfs -text
41
+ assets/idff_lorenz.gif filter=lfs diff=lfs merge=lfs -text
42
+ timeseris_example/outputs/lorenz/rollout.png filter=lfs diff=lfs merge=lfs -text
43
+ timeseris_example/outputs/polyALA/md_samples.png filter=lfs diff=lfs merge=lfs -text
.github/workflows/python-app.yml ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: tests
2
+
3
+ on:
4
+ push:
5
+ branches: [ "main", "master" ]
6
+ pull_request:
7
+ branches: [ "main", "master" ]
8
+
9
+ permissions:
10
+ contents: read
11
+
12
+ jobs:
13
+ test:
14
+ runs-on: ubuntu-latest
15
+ steps:
16
+ - uses: actions/checkout@v4
17
+ - name: Set up Python 3.11
18
+ uses: actions/setup-python@v5
19
+ with:
20
+ python-version: "3.11"
21
+ - name: Install dependencies
22
+ run: |
23
+ python -m pip install --upgrade pip
24
+ pip install torch --index-url https://download.pytorch.org/whl/cpu
25
+ pip install -r requirements.txt
26
+ pip install flake8 pytest
27
+ - name: Lint (syntax errors and undefined names)
28
+ run: flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics
29
+ - name: Run tests
30
+ run: pytest -q
.gitignore ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ __pycache__/
2
+ *.py[cod]
3
+ .pytest_cache/
4
+ .DS_Store
5
+ ._*
6
+ *.egg-info/
7
+ .venv/
2D_examples/ImageGen.png ADDED

Git LFS Details

  • SHA256: de243601185569779b28b6656559fa0da835c75eb8b8d1478b0b2dc5acf5404f
  • Pointer size: 132 Bytes
  • Size of remote file: 5.51 MB
2D_examples/idff_2d.py ADDED
@@ -0,0 +1,260 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """IDFF on 2-D toy distributions.
2
+
3
+ Trains one joint-head network (denoiser + score) with the IDFF objective and compares samplers that
4
+ share it, at several NFE budgets:
5
+
6
+ * CFM (det.) deterministic Euler on v_hat = (x1_hat - x)/(1 - t) (K = 0)
7
+ * Stochastic CFM same diffusion g_t^2 = 2 gamma_t^1 but no score drift (ablation)
8
+ * IDFF K=1 score-Langevin drift + matched diffusion (paper default)
9
+ * IDFF K=2 / K=3 plus contracted curvature terms (K=3 shown for illustration only)
10
+
11
+ Hyper-parameters are selected per NFE budget on a validation sample, and results are reported on
12
+ separate test samples (mean +- std over seeds): gamma_bar for K=1 from {c / NFE} (the paper's
13
+ gamma_bar = O(dt) scaling); alpha_2 for K=2 with the same gamma_bar, where alpha_2 = 0 recovers K=1;
14
+ alpha_3 for K=3 given alpha_2. The sign of alpha_k is free (the deviation bound depends on alpha_k^2).
15
+ Example:
16
+
17
+ python 2D_examples/idff_2d.py --dataset checkerboard
18
+ """
19
+ import argparse
20
+ import csv
21
+ import json
22
+ import sys
23
+ import time
24
+ from pathlib import Path
25
+
26
+ import matplotlib
27
+
28
+ matplotlib.use("Agg")
29
+ import matplotlib.pyplot as plt # noqa: E402
30
+ import numpy as np # noqa: E402
31
+ import torch # noqa: E402
32
+ from scipy.stats import gaussian_kde # noqa: E402
33
+
34
+ ROOT = Path(__file__).resolve().parents[1]
35
+ sys.path.insert(0, str(ROOT))
36
+
37
+ from idff import JointHeadMLP, idff_loss, ot_coupling, sample, sigma_t # noqa: E402
38
+ from idff.datasets import TOY_DATASETS # noqa: E402
39
+ from idff.metrics import mmd_rbf # noqa: E402
40
+
41
+
42
+ def repo_relative(args):
43
+ """Command-line arguments with paths made relative to the repository (for config.json)."""
44
+ out = dict(vars(args))
45
+ for key in ("out", "data"):
46
+ if key in out:
47
+ try:
48
+ out[key] = str(Path(out[key]).resolve().relative_to(ROOT))
49
+ except ValueError:
50
+ pass
51
+ return out
52
+
53
+
54
+ def parse_args():
55
+ p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
56
+ p.add_argument("--dataset", default="checkerboard", choices=list(TOY_DATASETS))
57
+ p.add_argument("--iters", type=int, default=60000,
58
+ help="the score head needs long training: its target -eps/sigma_t is high-variance")
59
+ p.add_argument("--batch", type=int, default=512)
60
+ p.add_argument("--lr", type=float, default=1e-3)
61
+ p.add_argument("--sigma0", type=float, default=0.2)
62
+ p.add_argument("--coupling", default="independent", choices=["independent", "ot"],
63
+ help="'ot' trains OT-IDFF with minibatch optimal-transport pairs (needs POT)")
64
+ p.add_argument("--nfes", type=int, nargs="+", default=[2, 3, 5, 10, 20])
65
+ p.add_argument("--gamma-c-grid", type=float, nargs="+", default=[0.5, 1.0, 2.0, 4.0, 8.0, 16.0, 32.0],
66
+ help="grid for c in gamma_bar = c / NFE")
67
+ p.add_argument("--alpha-grid", type=float, nargs="+",
68
+ default=[-4.0, -2.0, -1.0, -0.5, -0.1, 0.1, 0.5, 1.0, 2.0, 4.0],
69
+ help="alpha_k grid (0 is always added); the sign is free (the bound depends on alpha_k^2)")
70
+ p.add_argument("--n-eval", type=int, default=3000)
71
+ p.add_argument("--seeds", type=int, default=5)
72
+ p.add_argument("--retrain", action="store_true")
73
+ p.add_argument("--out", default=str(Path(__file__).resolve().parent / "outputs"))
74
+ return p.parse_args()
75
+
76
+
77
+ def train(args, out_dir):
78
+ ckpt = out_dir / "idff_model.pt"
79
+ model = JointHeadMLP(2, hidden=256, depth=3, sigma0=args.sigma0)
80
+ if ckpt.exists() and not args.retrain:
81
+ model.load_state_dict(torch.load(ckpt, map_location="cpu", weights_only=True))
82
+ print(f"loaded {ckpt}")
83
+ return model.eval()
84
+ torch.manual_seed(0)
85
+ opt = torch.optim.Adam(model.parameters(), lr=args.lr)
86
+ sched = torch.optim.lr_scheduler.CosineAnnealingLR(opt, args.iters)
87
+ sampler = TOY_DATASETS[args.dataset]
88
+ start = time.time()
89
+ for it in range(1, args.iters + 1):
90
+ x1 = sampler(args.batch)
91
+ x0 = torch.randn_like(x1)
92
+ if args.coupling == "ot":
93
+ x0, x1 = ot_coupling(x0, x1)
94
+ loss, stats = idff_loss(model, x1, x0=x0, sigma0=args.sigma0)
95
+ opt.zero_grad()
96
+ loss.backward()
97
+ torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
98
+ opt.step()
99
+ sched.step()
100
+ if it % 2000 == 0:
101
+ print(f"iter {it:6d} loss {loss.item():.4f} denoiser {stats['denoiser']:.4f} "
102
+ f"score {stats['score']:.4f} ({time.time() - start:.0f}s)")
103
+ torch.save(model.state_dict(), ckpt)
104
+ return model.eval()
105
+
106
+
107
+ @torch.no_grad()
108
+ def score_diagnostic(model, args):
109
+ """Compare the learned score head with the exact marginal score of the training path.
110
+
111
+ With x0 ~ N(0, I), p_t(x) = E_{x1}[N(x; t x1, ((1 - t)^2 + sigma_t^2) I)], evaluated by Monte Carlo.
112
+ """
113
+ ref = TOY_DATASETS[args.dataset](40000)
114
+ rows = []
115
+ for t in [0.25, 0.5, 0.75]:
116
+ var = (1 - t) ** 2 + sigma_t(t, args.sigma0) ** 2
117
+ x = t * TOY_DATASETS[args.dataset](2000) + np.sqrt(var) * torch.randn(2000, 2)
118
+ d = x[:, None] - t * ref[None]
119
+ w = torch.softmax(-(d ** 2).sum(-1) / (2 * var), dim=1)
120
+ true = -(w[..., None] * d).sum(1) / var
121
+ _, s_hat = model(x, torch.full((2000,), t))
122
+ cos = torch.nn.functional.cosine_similarity(s_hat, true, dim=1)
123
+ rel = ((s_hat - true).norm(dim=1) / true.norm(dim=1)).median()
124
+ rows.append((t, cos.mean().item(), rel.item()))
125
+ return rows
126
+
127
+
128
+ METHODS = {
129
+ "CFM (det.)": dict(K=0),
130
+ "Stochastic CFM": dict(K=1, score_drift=False),
131
+ "IDFF K=1": dict(K=1),
132
+ "IDFF K=2": dict(K=2),
133
+ "IDFF K=3": dict(K=3),
134
+ }
135
+
136
+
137
+ def run(model, cfg, nfe, n, seed):
138
+ gen = torch.Generator().manual_seed(seed)
139
+ x0 = torch.randn(n, 2, generator=gen)
140
+ return sample(model, x0, nfe, generator=gen, **cfg)
141
+
142
+
143
+ def config_for(name, nfe, sel):
144
+ """Sampler arguments of method ``name`` at budget ``nfe`` given the selected hyper-parameters."""
145
+ s = sel[nfe]
146
+ cfg = dict(METHODS[name])
147
+ if cfg["K"] >= 1:
148
+ cfg["gamma_bar"] = s["gamma_bar"]
149
+ if cfg["K"] >= 2:
150
+ cfg["alphas"] = {2: s["alpha_2"], 3: s["alpha_3"]}
151
+ return cfg
152
+
153
+
154
+ def select_hyperparameters(model, args):
155
+ """Per NFE budget, on a validation sample (mean MMD over two sampling seeds): gamma_bar for K=1,
156
+ then alpha_2 for K=2 with the same gamma_bar, then alpha_3 for K=3. alpha = 0 is tried first, so
157
+ K=2 falls back to K=1 when the curvature term does not help on validation data."""
158
+ torch.manual_seed(12345)
159
+ val = TOY_DATASETS[args.dataset](args.n_eval)
160
+ alphas = [0.0] + [a for a in args.alpha_grid if a != 0.0]
161
+ sel = {}
162
+ for nfe in args.nfes:
163
+ def score(cfg, nfe=nfe):
164
+ return np.mean([mmd_rbf(run(model, cfg, nfe, args.n_eval, 900 + s), val) for s in range(2)])
165
+
166
+ g = min([c / nfe for c in args.gamma_c_grid], key=lambda g: score(dict(K=1, gamma_bar=g)))
167
+ a2 = min(alphas, key=lambda a: score(dict(K=2, gamma_bar=g, alphas={2: a})))
168
+ a3 = min(alphas, key=lambda a: score(dict(K=3, gamma_bar=g, alphas={2: a2, 3: a})))
169
+ sel[nfe] = {"gamma_bar": g, "alpha_2": a2, "alpha_3": a3}
170
+ return sel
171
+
172
+
173
+ def main():
174
+ args = parse_args()
175
+ out_dir = Path(args.out) / (args.dataset + ("_ot" if args.coupling == "ot" else ""))
176
+ out_dir.mkdir(parents=True, exist_ok=True)
177
+ model = train(args, out_dir)
178
+
179
+ print("\nscore head vs exact marginal score (Fisher's identity):")
180
+ for t, cos, rel in score_diagnostic(model, args):
181
+ print(f" t={t:.2f} mean cosine {cos:.3f} median relative error {rel:.3f}")
182
+
183
+ sel = select_hyperparameters(model, args)
184
+ print("\nselected on validation data:")
185
+ for nfe, s in sel.items():
186
+ print(f" NFE={nfe:3d} gamma_bar={s['gamma_bar']:.3g} alpha_2={s['alpha_2']:g} alpha_3={s['alpha_3']:g}")
187
+
188
+ rows = []
189
+ for name in METHODS:
190
+ for nfe in args.nfes:
191
+ vals = []
192
+ for seed in range(args.seeds):
193
+ torch.manual_seed(1000 + seed)
194
+ test = TOY_DATASETS[args.dataset](args.n_eval)
195
+ vals.append(mmd_rbf(run(model, config_for(name, nfe, sel), nfe, args.n_eval, seed), test))
196
+ rows.append({"method": name, "nfe": nfe, "mmd_mean": float(np.mean(vals)), "mmd_std": float(np.std(vals))})
197
+
198
+ with open(out_dir / "mmd_results.csv", "w", newline="") as fh:
199
+ writer = csv.DictWriter(fh, fieldnames=list(rows[0]))
200
+ writer.writeheader()
201
+ writer.writerows(rows)
202
+ with open(out_dir / "config.json", "w") as fh:
203
+ json.dump({**repo_relative(args), "selected": {str(k): v for k, v in sel.items()}}, fh, indent=2)
204
+
205
+ header = "method".ljust(16) + "".join(f"NFE={n:<14d}" for n in args.nfes)
206
+ print("\nMMD (x1e3, mean +- std over seeds), lower is better\n" + header)
207
+ for name in METHODS:
208
+ line = name.ljust(16)
209
+ for nfe in args.nfes:
210
+ r = next(r for r in rows if r["method"] == name and r["nfe"] == nfe)
211
+ line += f"{1e3 * r['mmd_mean']:6.2f} +- {1e3 * r['mmd_std']:<5.2f} "
212
+ print(line)
213
+
214
+ plot(model, args, rows, out_dir, sel)
215
+ print(f"\nwrote results to {out_dir}")
216
+
217
+
218
+ def plot(model, args, rows, out_dir, sel):
219
+ names = ["CFM (det.)", "Stochastic CFM", "IDFF K=1", "IDFF K=2"]
220
+ budgets = [b for b in [3, 5, 10] if b in args.nfes] or args.nfes[:3]
221
+ true = TOY_DATASETS[args.dataset](5000).numpy()
222
+ lo, hi = true.min() - 1, true.max() + 1
223
+ gx, gy = np.meshgrid(np.linspace(lo, hi, 80), np.linspace(lo, hi, 80))
224
+ grid = np.vstack([gx.ravel(), gy.ravel()])
225
+ z_true = gaussian_kde(true.T)(grid).reshape(gx.shape)
226
+ fig, axs = plt.subplots(len(names), len(budgets), figsize=(3 * len(budgets), 3 * len(names)), squeeze=False)
227
+ for i, name in enumerate(names):
228
+ for j, nfe in enumerate(budgets):
229
+ x = run(model, config_for(name, nfe, sel), nfe, 5000, 0).numpy()
230
+ ax = axs[i, j]
231
+ ax.contourf(gx, gy, gaussian_kde(x.T)(grid).reshape(gx.shape), levels=30, cmap="Reds")
232
+ ax.contour(gx, gy, z_true, levels=6, colors="k", linewidths=0.6, linestyles="dashed")
233
+ mmd = next(r for r in rows if r["method"] == name and r["nfe"] == nfe)["mmd_mean"]
234
+ ax.set_title(f"{name}, NFE={nfe}\nMMD={1e3 * mmd:.2f}e-3", fontsize=9)
235
+ ax.set_xticks([])
236
+ ax.set_yticks([])
237
+ fig.tight_layout()
238
+ fig.savefig(out_dir / "samples_grid.png", dpi=130)
239
+ plt.close(fig)
240
+
241
+ fig, ax = plt.subplots(figsize=(5, 3.6))
242
+ for name in METHODS:
243
+ r = [x for x in rows if x["method"] == name]
244
+ ax.errorbar([x["nfe"] for x in r], [x["mmd_mean"] for x in r], yerr=[x["mmd_std"] for x in r],
245
+ marker="o", capsize=3, label=name, linestyle="--" if name == "IDFF K=3" else "-")
246
+ ax.set_xscale("log")
247
+ ax.set_yscale("log")
248
+ ax.set_xticks(args.nfes)
249
+ ax.set_xticklabels(args.nfes)
250
+ ax.set_xlabel("NFE")
251
+ ax.set_ylabel("MMD (test)")
252
+ ax.set_title(f"{args.dataset}")
253
+ ax.legend(fontsize=8)
254
+ fig.tight_layout()
255
+ fig.savefig(out_dir / "mmd_vs_nfe.png", dpi=130)
256
+ plt.close(fig)
257
+
258
+
259
+ if __name__ == "__main__":
260
+ main()
2D_examples/outputs/8gaussians/config.json ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "dataset": "8gaussians",
3
+ "iters": 60000,
4
+ "batch": 512,
5
+ "lr": 0.001,
6
+ "sigma0": 0.2,
7
+ "coupling": "independent",
8
+ "nfes": [
9
+ 2,
10
+ 3,
11
+ 5,
12
+ 10,
13
+ 20
14
+ ],
15
+ "gamma_c_grid": [
16
+ 0.5,
17
+ 1.0,
18
+ 2.0,
19
+ 4.0,
20
+ 8.0,
21
+ 16.0,
22
+ 32.0
23
+ ],
24
+ "alpha_grid": [
25
+ -4.0,
26
+ -2.0,
27
+ -1.0,
28
+ -0.5,
29
+ -0.1,
30
+ 0.1,
31
+ 0.5,
32
+ 1.0,
33
+ 2.0,
34
+ 4.0
35
+ ],
36
+ "n_eval": 3000,
37
+ "seeds": 5,
38
+ "retrain": false,
39
+ "out": "2D_examples/outputs",
40
+ "selected": {
41
+ "2": {
42
+ "gamma_bar": 0.25,
43
+ "alpha_2": 0.0,
44
+ "alpha_3": 0.0
45
+ },
46
+ "3": {
47
+ "gamma_bar": 2.6666666666666665,
48
+ "alpha_2": -0.5,
49
+ "alpha_3": -1.0
50
+ },
51
+ "5": {
52
+ "gamma_bar": 0.8,
53
+ "alpha_2": -1.0,
54
+ "alpha_3": -4.0
55
+ },
56
+ "10": {
57
+ "gamma_bar": 1.6,
58
+ "alpha_2": -0.5,
59
+ "alpha_3": -4.0
60
+ },
61
+ "20": {
62
+ "gamma_bar": 0.8,
63
+ "alpha_2": -1.0,
64
+ "alpha_3": -1.0
65
+ }
66
+ }
67
+ }
2D_examples/outputs/8gaussians/idff_model.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:969f41be49ca0a053690582566842b975496818eeeee8fab32e985116201597a
3
+ size 547253
2D_examples/outputs/8gaussians/mmd_results.csv ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ method,nfe,mmd_mean,mmd_std
2
+ CFM (det.),2,0.08827868442018214,0.0014740249308344779
3
+ CFM (det.),3,0.0424659072146575,0.0009810335595719967
4
+ CFM (det.),5,0.015201979451496922,0.0006569678599379705
5
+ CFM (det.),10,0.0040618978329832744,0.000340957955402701
6
+ CFM (det.),20,0.0014573786194185868,0.00023822105751385107
7
+ Stochastic CFM,2,0.08827868442018214,0.0014740249308344779
8
+ Stochastic CFM,3,0.02315831109533261,0.0008980638011695121
9
+ Stochastic CFM,5,0.013907063579835502,0.0007509603173326287
10
+ Stochastic CFM,10,0.01856082030546402,0.0005613560839523732
11
+ Stochastic CFM,20,0.010483334864954582,0.0004598238407209597
12
+ IDFF K=1,2,0.08827868442018214,0.0014740249308344779
13
+ IDFF K=1,3,0.012397986278387074,0.0005981308009709111
14
+ IDFF K=1,5,0.0036822221889503738,0.0003590829112280288
15
+ IDFF K=1,10,0.0011825990270721621,0.00014835786463725744
16
+ IDFF K=1,20,0.0007450908311625093,0.0001515723157393066
17
+ IDFF K=2,2,0.08827868442018214,0.0014740249308344779
18
+ IDFF K=2,3,0.012363239203215557,0.0006370963586444877
19
+ IDFF K=2,5,0.0024774969710118443,0.00035616083942766866
20
+ IDFF K=2,10,0.0011324097054436655,0.00018514822443728822
21
+ IDFF K=2,20,0.0006662542188139442,0.00012644574640822932
22
+ IDFF K=3,2,0.08827868442018214,0.0014740249308344779
23
+ IDFF K=3,3,0.010520566650059663,0.0004415496997063861
24
+ IDFF K=3,5,0.0018892526046815571,0.0003234621489433014
25
+ IDFF K=3,10,0.001114295607163185,0.00017315555425689966
26
+ IDFF K=3,20,0.0006655070070097968,0.00012663721965323587
2D_examples/outputs/8gaussians/mmd_vs_nfe.png ADDED
2D_examples/outputs/8gaussians/samples_grid.png ADDED

Git LFS Details

  • SHA256: a05223ab5c14be46bbf5b4492fd2633ca86439fb1193b17dca1f7282cd648f2f
  • Pointer size: 132 Bytes
  • Size of remote file: 1.02 MB
2D_examples/outputs/checkerboard/config.json ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "dataset": "checkerboard",
3
+ "iters": 60000,
4
+ "batch": 512,
5
+ "lr": 0.001,
6
+ "sigma0": 0.2,
7
+ "coupling": "independent",
8
+ "nfes": [
9
+ 2,
10
+ 3,
11
+ 5,
12
+ 10,
13
+ 20
14
+ ],
15
+ "gamma_c_grid": [
16
+ 0.5,
17
+ 1.0,
18
+ 2.0,
19
+ 4.0,
20
+ 8.0,
21
+ 16.0,
22
+ 32.0
23
+ ],
24
+ "alpha_grid": [
25
+ -4.0,
26
+ -2.0,
27
+ -1.0,
28
+ -0.5,
29
+ -0.1,
30
+ 0.1,
31
+ 0.5,
32
+ 1.0,
33
+ 2.0,
34
+ 4.0
35
+ ],
36
+ "n_eval": 3000,
37
+ "seeds": 5,
38
+ "retrain": false,
39
+ "out": "2D_examples/outputs",
40
+ "selected": {
41
+ "2": {
42
+ "gamma_bar": 0.25,
43
+ "alpha_2": 0.0,
44
+ "alpha_3": 0.0
45
+ },
46
+ "3": {
47
+ "gamma_bar": 5.333333333333333,
48
+ "alpha_2": -2.0,
49
+ "alpha_3": -0.1
50
+ },
51
+ "5": {
52
+ "gamma_bar": 3.2,
53
+ "alpha_2": -2.0,
54
+ "alpha_3": -1.0
55
+ },
56
+ "10": {
57
+ "gamma_bar": 0.8,
58
+ "alpha_2": -2.0,
59
+ "alpha_3": -4.0
60
+ },
61
+ "20": {
62
+ "gamma_bar": 1.6,
63
+ "alpha_2": -2.0,
64
+ "alpha_3": -4.0
65
+ }
66
+ }
67
+ }
2D_examples/outputs/checkerboard/idff_model.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:66d1c2763133bb7f9eeff4fe451acd129198eed1e79b2e8e2b27411fd48ad9fe
3
+ size 547619
2D_examples/outputs/checkerboard/mmd_results.csv ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ method,nfe,mmd_mean,mmd_std
2
+ CFM (det.),2,0.2188572914624701,0.00490916327914265
3
+ CFM (det.),3,0.07052719676172971,0.0025672184262584136
4
+ CFM (det.),5,0.022546077547576166,0.0015034949908499175
5
+ CFM (det.),10,0.005771681778804588,0.0008082264857641433
6
+ CFM (det.),20,0.00185810589663728,0.0004336497652978774
7
+ Stochastic CFM,2,0.2188572914624701,0.00490916327914265
8
+ Stochastic CFM,3,0.005545994919879787,0.0003217477036535606
9
+ Stochastic CFM,5,0.011346294943048757,0.0002807964622559956
10
+ Stochastic CFM,10,0.004263184462992781,0.00015196296352692262
11
+ Stochastic CFM,20,0.011410351401392854,0.000681996901080064
12
+ IDFF K=1,2,0.2188572914624701,0.00490916327914265
13
+ IDFF K=1,3,0.005166943248355144,0.0004286443328964519
14
+ IDFF K=1,5,0.013127750469622635,0.0009708024676790019
15
+ IDFF K=1,10,0.004630318489455843,0.0008313755802861466
16
+ IDFF K=1,20,0.0019207412642658571,0.00045113105322106814
17
+ IDFF K=2,2,0.2188572914624701,0.00490916327914265
18
+ IDFF K=2,3,0.0053014495526616245,0.00031432502413914534
19
+ IDFF K=2,5,0.008471566731020142,0.0005078231336892195
20
+ IDFF K=2,10,0.003940669550593229,0.0007634695077830026
21
+ IDFF K=2,20,0.0016142686218012681,0.00043464216967364753
22
+ IDFF K=3,2,0.2188572914624701,0.00490916327914265
23
+ IDFF K=3,3,0.005288385350304692,0.0003108534892061196
24
+ IDFF K=3,5,0.008154563054282854,0.0004534677194388744
25
+ IDFF K=3,10,0.0034392033576092994,0.0006619511365712285
26
+ IDFF K=3,20,0.0015245175655409227,0.00038807591117552944
2D_examples/outputs/checkerboard/mmd_vs_nfe.png ADDED
2D_examples/outputs/checkerboard/samples_grid.png ADDED

Git LFS Details

  • SHA256: c9fbfe7f216553e224443d8d2ed1a040fc0c151273c2df29085076e7f47a75ad
  • Pointer size: 132 Bytes
  • Size of remote file: 1.02 MB
2D_examples/outputs/moons/config.json ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "dataset": "moons",
3
+ "iters": 60000,
4
+ "batch": 512,
5
+ "lr": 0.001,
6
+ "sigma0": 0.2,
7
+ "coupling": "independent",
8
+ "nfes": [
9
+ 2,
10
+ 3,
11
+ 5,
12
+ 10,
13
+ 20
14
+ ],
15
+ "gamma_c_grid": [
16
+ 0.5,
17
+ 1.0,
18
+ 2.0,
19
+ 4.0,
20
+ 8.0,
21
+ 16.0,
22
+ 32.0
23
+ ],
24
+ "alpha_grid": [
25
+ -4.0,
26
+ -2.0,
27
+ -1.0,
28
+ -0.5,
29
+ -0.1,
30
+ 0.1,
31
+ 0.5,
32
+ 1.0,
33
+ 2.0,
34
+ 4.0
35
+ ],
36
+ "n_eval": 3000,
37
+ "seeds": 5,
38
+ "retrain": false,
39
+ "out": "2D_examples/outputs",
40
+ "selected": {
41
+ "2": {
42
+ "gamma_bar": 0.25,
43
+ "alpha_2": 0.0,
44
+ "alpha_3": 0.0
45
+ },
46
+ "3": {
47
+ "gamma_bar": 2.6666666666666665,
48
+ "alpha_2": -4.0,
49
+ "alpha_3": 1.0
50
+ },
51
+ "5": {
52
+ "gamma_bar": 3.2,
53
+ "alpha_2": -2.0,
54
+ "alpha_3": -1.0
55
+ },
56
+ "10": {
57
+ "gamma_bar": 1.6,
58
+ "alpha_2": -2.0,
59
+ "alpha_3": -4.0
60
+ },
61
+ "20": {
62
+ "gamma_bar": 1.6,
63
+ "alpha_2": -2.0,
64
+ "alpha_3": -4.0
65
+ }
66
+ }
67
+ }
2D_examples/outputs/moons/idff_model.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bbf85577af98bf26c05489a736f77ad524630289a5f24602c8c0827feb84d30e
3
+ size 547253
2D_examples/outputs/moons/mmd_results.csv ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ method,nfe,mmd_mean,mmd_std
2
+ CFM (det.),2,0.22410653579407205,0.006880846596898077
3
+ CFM (det.),3,0.07749838831224833,0.00344215417806067
4
+ CFM (det.),5,0.02514224284439378,0.0017570630054123315
5
+ CFM (det.),10,0.006706524005994185,0.0008233796384715019
6
+ CFM (det.),20,0.0023699601837779416,0.00048571596953232563
7
+ Stochastic CFM,2,0.22410653579407205,0.006880846596898077
8
+ Stochastic CFM,3,0.011972803285579531,0.001692826730553314
9
+ Stochastic CFM,5,0.020956618900112706,0.0012343809499090839
10
+ Stochastic CFM,10,0.014538050884654069,0.0011853329846686581
11
+ Stochastic CFM,20,0.01852075290991318,0.0011641326077654654
12
+ IDFF K=1,2,0.22410653579407205,0.006880846596898077
13
+ IDFF K=1,3,0.01748193841856508,0.001599821822653532
14
+ IDFF K=1,5,0.011726497027321975,0.000935331169924069
15
+ IDFF K=1,10,0.003424801866586147,0.000989061566570685
16
+ IDFF K=1,20,0.0015576914301519197,0.0002964445833506406
17
+ IDFF K=2,2,0.22410653579407205,0.006880846596898077
18
+ IDFF K=2,3,0.009547933922260799,0.0012451935732882766
19
+ IDFF K=2,5,0.0074906257498777605,0.0008030310171046393
20
+ IDFF K=2,10,0.0021999872475188032,0.0006334024334764006
21
+ IDFF K=2,20,0.0011718175166375022,0.000217792740267185
22
+ IDFF K=3,2,0.22410653579407205,0.006880846596898077
23
+ IDFF K=3,3,0.009485082373053389,0.0013233993079878872
24
+ IDFF K=3,5,0.007449597887539444,0.0007582422735597876
25
+ IDFF K=3,10,0.0019417653275533298,0.0005133567380441102
26
+ IDFF K=3,20,0.0011240735688289206,0.00021968238425510887
2D_examples/outputs/moons/mmd_vs_nfe.png ADDED
2D_examples/outputs/moons/samples_grid.png ADDED

Git LFS Details

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

Git LFS Details

  • SHA256: a5a757aef3a62514aba918039c49212c62a5a0ffa774cb20d3f62c736834b2be
  • Pointer size: 131 Bytes
  • Size of remote file: 712 kB
assets/idff_lorenz.gif ADDED

Git LFS Details

  • SHA256: ff1e39e4d7f0122417a2281286b9f22616bcdc5d043da19022b14c43e8b08986
  • Pointer size: 132 Bytes
  • Size of remote file: 3.69 MB
idff/__init__.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Implicit Dynamical Flow Fusion (IDFF): reference implementation of the TMLR paper."""
2
+ from .core import (gamma_schedule, idff_loss, ot_coupling, sample_conditional_path, sequence_training_pairs,
3
+ sigma_t)
4
+ from .models import JointHeadMLP
5
+ from .sampling import contracted_score_derivative, sample, sample_next, sample_sequence
6
+
7
+ __version__ = "1.0.0"
8
+
9
+ __all__ = [
10
+ "gamma_schedule",
11
+ "idff_loss",
12
+ "ot_coupling",
13
+ "sample_conditional_path",
14
+ "sequence_training_pairs",
15
+ "sigma_t",
16
+ "JointHeadMLP",
17
+ "contracted_score_derivative",
18
+ "sample",
19
+ "sample_next",
20
+ "sample_sequence",
21
+ ]
idff/core.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Probability path, coefficient schedules and the IDFF training objective.
2
+
3
+ Equation and section references are to the TMLR paper "Implicit Dynamical Flow Fusion (IDFF) for
4
+ Generative Modeling".
5
+ """
6
+ import math
7
+
8
+ import torch
9
+
10
+
11
+ def pad_like(t, x):
12
+ """Reshape a scalar or (batch,) time tensor so that it broadcasts against ``x``."""
13
+ if not torch.is_tensor(t):
14
+ t = torch.tensor(t, dtype=x.dtype, device=x.device)
15
+ if t.dim() == 0:
16
+ return t
17
+ return t.reshape(-1, *([1] * (x.dim() - 1)))
18
+
19
+
20
+ def sigma_t(t, sigma0):
21
+ """Standard deviation of the conditional path, sigma_t = sigma0 * sqrt(t (1 - t)) (Eq. ppath)."""
22
+ if torch.is_tensor(t):
23
+ return sigma0 * torch.sqrt((t * (1.0 - t)).clamp_min(0.0))
24
+ return sigma0 * math.sqrt(max(t * (1.0 - t), 0.0))
25
+
26
+
27
+ def sample_conditional_path(x0, x1, t, sigma0):
28
+ """Draw x_t = t x1 + (1 - t) x0 + sigma_t eps with eps ~ N(0, I) (Eq. ppath).
29
+
30
+ Returns ``(x_t, eps, sigma_t)`` with ``sigma_t`` broadcastable against ``x1``.
31
+ """
32
+ eps = torch.randn_like(x1)
33
+ tt = pad_like(t, x1)
34
+ st = sigma_t(tt, sigma0)
35
+ xt = tt * x1 + (1.0 - tt) * x0 + st * eps
36
+ return xt, eps, st
37
+
38
+
39
+ def gamma_schedule(t, gamma_bar, shape="beta22"):
40
+ """Langevin amplitude gamma_t^1 >= 0, vanishing at t = 0 and t = 1.
41
+
42
+ Shapes follow the schedule ablation of the paper (Appendix, "Schedule shape ablation"):
43
+ ``beta22`` 4 gamma_bar t (1 - t) (default, Beta(2,2))
44
+ ``triangular`` gamma_bar min(t, 1 - t)
45
+ ``sine`` gamma_bar sin(pi t)
46
+ ``beta33`` 16 gamma_bar t^2 (1 - t)^2 (peak normalised to gamma_bar)
47
+ """
48
+ if shape == "beta22":
49
+ return 4.0 * gamma_bar * t * (1.0 - t)
50
+ if shape == "triangular":
51
+ return gamma_bar * min(t, 1.0 - t)
52
+ if shape == "sine":
53
+ return gamma_bar * math.sin(math.pi * t)
54
+ if shape == "beta33":
55
+ return 16.0 * gamma_bar * (t * (1.0 - t)) ** 2
56
+ raise ValueError(f"unknown schedule shape: {shape!r}")
57
+
58
+
59
+ def idff_loss(model, x1, x0=None, t=None, sigma0=0.2, beta_eps=1e-2, model_kwargs=None):
60
+ """IDFF training objective (Eq. idff_loss).
61
+
62
+ beta(t)^2 ||x1_hat(x_t, t) - x1||^2 + lambda_1(t)^2 ||s_hat(x_t, t) + eps / sigma_t||^2,
63
+
64
+ with beta(t) = 1 / (1 - t + beta_eps) and lambda_1(t) = sigma_t. The score term regresses the
65
+ score head onto the conditional score grad log p_t(x_t | x0, x1) = -eps / sigma_t; by Fisher's
66
+ identity its minimiser is the marginal score grad log p_t(x_t). Because lambda_1 = sigma_t, the
67
+ term is evaluated in the algebraically identical, numerically stable form ||sigma_t s_hat + eps||^2.
68
+
69
+ Args:
70
+ model: callable ``model(x_t, t, **model_kwargs) -> (x1_hat, s_hat)``.
71
+ x1: data batch.
72
+ x0: base samples; defaults to N(0, I) (independent coupling).
73
+ t: times in [0, 1], shape (batch,); defaults to U(0, 1).
74
+ sigma0: path bandwidth; must be > 0, otherwise the score head receives no signal.
75
+
76
+ Returns:
77
+ ``(loss, stats)`` where ``stats`` holds the two terms as floats.
78
+ """
79
+ if sigma0 <= 0:
80
+ raise ValueError("sigma0 must be > 0: with sigma0 = 0 the score target -eps/sigma_t is undefined")
81
+ if x0 is None:
82
+ x0 = torch.randn_like(x1)
83
+ if t is None:
84
+ t = torch.rand(x1.shape[0], device=x1.device, dtype=x1.dtype)
85
+ xt, eps, st = sample_conditional_path(x0, x1, t, sigma0)
86
+ x1_hat, s_hat = model(xt, t, **(model_kwargs or {}))
87
+ beta = 1.0 / (1.0 - pad_like(t, x1) + beta_eps)
88
+ denoiser = ((beta * (x1_hat - x1)) ** 2).flatten(1).mean(1).mean()
89
+ score = ((st * s_hat + eps) ** 2).flatten(1).mean(1).mean()
90
+ return denoiser + score, {"denoiser": denoiser.item(), "score": score.item()}
91
+
92
+
93
+ def ot_coupling(x0, x1):
94
+ """Re-pair a minibatch with the exact optimal-transport plan (squared Euclidean cost).
95
+
96
+ This is the minibatch-OT coupling of OT-CFM (Tong et al.), used by the OT-IDFF variant. The score
97
+ head remains valid under any coupling (Fisher's identity does not need independence). Requires POT.
98
+ """
99
+ from torchcfm.optimal_transport import OTPlanSampler
100
+
101
+ return OTPlanSampler(method="exact").sample_plan(x0, x1)
102
+
103
+
104
+ def sequence_training_pairs(data, batch_size, sigma0, generator=None):
105
+ """Draw a training batch for the time-series model (Algorithm 3, IDFF Training (Time-Series)).
106
+
107
+ For position n = 0 the base sample is x0 ~ N(0, I). For n > 0 it is the previous frame,
108
+ x0 ~ N(x^{n-1}, sigma0^2 I), matching the Markovian initialisation used at sampling time.
109
+
110
+ Args:
111
+ data: tensor of shape (num_sequences, length, dim).
112
+
113
+ Returns:
114
+ ``(x0, x1, n)`` with ``n`` the (batch,) long tensor of positions.
115
+ """
116
+ num_seq, length = data.shape[0], data.shape[1]
117
+ dev = data.device
118
+ seq = torch.randint(num_seq, (batch_size,), device=dev, generator=generator)
119
+ n = torch.randint(length, (batch_size,), device=dev, generator=generator)
120
+ x1 = data[seq, n]
121
+ prev = data[seq, (n - 1).clamp_min(0)]
122
+ noise = torch.randn(x1.shape, device=dev, dtype=x1.dtype, generator=generator)
123
+ first = (n == 0).reshape(-1, *([1] * (x1.dim() - 1)))
124
+ x0 = torch.where(first, noise, prev + sigma0 * noise)
125
+ return x0, x1, n
idff/datasets.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Datasets used by the examples: 2-D toy distributions, 3-D chaotic attractors and the polyALA MD data."""
2
+ import math
3
+ import pickle
4
+ from pathlib import Path
5
+
6
+ import numpy as np
7
+ import torch
8
+
9
+
10
+ # ----------------------------------------------------------------------------------------------
11
+ # 2-D toy distributions
12
+ # ----------------------------------------------------------------------------------------------
13
+ def eight_gaussians(n, scale=5.0, std=0.1 ** 0.25, generator=None):
14
+ """Mixture of 8 Gaussians on a circle of radius ``scale`` (same law as the original torchcfm helper)."""
15
+ angles = torch.arange(8) * (2 * math.pi / 8)
16
+ centers = scale * torch.stack([torch.cos(angles), torch.sin(angles)], dim=1)
17
+ idx = torch.randint(8, (n,), generator=generator)
18
+ return centers[idx] + std * torch.randn(n, 2, generator=generator)
19
+
20
+
21
+ def checkerboard(n, generator=None):
22
+ """Checkerboard on [-4, 4]^2 (same law as the original torchcfm helper)."""
23
+ x1 = torch.rand(n, generator=generator) * 4 - 2
24
+ x2_ = torch.rand(n, generator=generator) - torch.randint(0, 2, (n,), generator=generator) * 2
25
+ x2 = x2_ + torch.floor(x1) % 2
26
+ return torch.stack([x1, x2], dim=1) * 2
27
+
28
+
29
+ def moons(n, noise=0.2, generator=None):
30
+ """Two interleaving half circles, scaled as x * 3 - 1 like the original torchcfm helper."""
31
+ n_out = n // 2
32
+ n_in = n - n_out
33
+ a = torch.rand(n_out, generator=generator) * math.pi
34
+ b = torch.rand(n_in, generator=generator) * math.pi
35
+ outer = torch.stack([torch.cos(a), torch.sin(a)], dim=1)
36
+ inner = torch.stack([1 - torch.cos(b), 0.5 - torch.sin(b)], dim=1)
37
+ x = torch.cat([outer, inner], dim=0)
38
+ x = x + noise * torch.randn(x.shape, generator=generator)
39
+ return x[torch.randperm(n, generator=generator)] * 3 - 1
40
+
41
+
42
+ TOY_DATASETS = {"8gaussians": eight_gaussians, "checkerboard": checkerboard, "moons": moons}
43
+
44
+
45
+ # ----------------------------------------------------------------------------------------------
46
+ # 3-D chaotic attractors (Appendix "3D Attractors")
47
+ # ----------------------------------------------------------------------------------------------
48
+ def _lorenz(state, sigma=10.0, rho=28.0, beta=8.0 / 3.0):
49
+ x, y, z = state[..., 0], state[..., 1], state[..., 2]
50
+ return np.stack([sigma * (y - x), x * (rho - z) - y, x * y - beta * z], axis=-1)
51
+
52
+
53
+ def _rossler(state, a=0.2, b=0.2, c=5.7):
54
+ x, y, z = state[..., 0], state[..., 1], state[..., 2]
55
+ return np.stack([-y - z, x + a * y, b + z * (x - c)], axis=-1)
56
+
57
+
58
+ def attractor_trajectories(system, num_traj, length, dt=None, stride=None, burn_in=2000, seed=0):
59
+ """Simulate ``num_traj`` trajectories of ``length`` frames with RK4.
60
+
61
+ ``system`` is ``"lorenz"`` (sigma=10, rho=28, beta=8/3) or ``"rossler"`` (a=b=0.2, c=5.7), the
62
+ parameters used in the paper. Returns an array of shape (num_traj, length, 3).
63
+ """
64
+ f = {"lorenz": _lorenz, "rossler": _rossler}[system]
65
+ dt = dt if dt is not None else {"lorenz": 0.01, "rossler": 0.05}[system]
66
+ stride = stride if stride is not None else {"lorenz": 2, "rossler": 2}[system]
67
+ rng = np.random.default_rng(seed)
68
+ state = rng.normal(size=(num_traj, 3)) + (np.array([0.0, 0.0, 25.0]) if system == "lorenz" else 0.0)
69
+
70
+ def step(s):
71
+ k1 = f(s)
72
+ k2 = f(s + 0.5 * dt * k1)
73
+ k3 = f(s + 0.5 * dt * k2)
74
+ k4 = f(s + dt * k3)
75
+ return s + dt / 6.0 * (k1 + 2 * k2 + 2 * k3 + k4)
76
+
77
+ for _ in range(burn_in):
78
+ state = step(state)
79
+ out = np.empty((num_traj, length, 3))
80
+ for i in range(length):
81
+ out[:, i] = state
82
+ for _ in range(stride):
83
+ state = step(state)
84
+ return out
85
+
86
+
87
+ # ----------------------------------------------------------------------------------------------
88
+ # polyALA molecular dynamics (Sec. "Surrogate Models for Molecular Dynamics")
89
+ # ----------------------------------------------------------------------------------------------
90
+ def load_polyala_angles(path):
91
+ """Load the polyALA dihedral-angle trajectory, shape (frames, 46), in degrees.
92
+
93
+ Accepts the compact ``.npz`` shipped with the repository (key ``angles``) or the original
94
+ simulation pickle (``data['angles'][1]`` reshaped to (sim_length, -1), as in the original script).
95
+ """
96
+ path = Path(path)
97
+ if not path.exists():
98
+ raise FileNotFoundError(f"MD dataset not found: {path}")
99
+ if path.suffix == ".npz":
100
+ return np.load(path)["angles"].astype(np.float64)
101
+ with open(path, "rb") as fh:
102
+ data = pickle.load(fh) # trusted local simulation output
103
+ return np.asarray(data["angles"][1]).reshape(data["sim_length"], -1).astype(np.float64)
idff/metrics.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Evaluation metrics used by the examples."""
2
+ import numpy as np
3
+ import torch
4
+
5
+
6
+ def mmd_rbf(x, y, bandwidth=1.0):
7
+ """Biased (V-statistic) squared MMD between samples x and y with a Gaussian RBF kernel."""
8
+ x = torch.as_tensor(x, dtype=torch.float64)
9
+ y = torch.as_tensor(y, dtype=torch.float64)
10
+
11
+ def k(a, b):
12
+ return torch.exp(-torch.cdist(a, b) ** 2 / (2 * bandwidth ** 2))
13
+
14
+ return (k(x, x).mean() + k(y, y).mean() - 2 * k(x, y).mean()).item()
15
+
16
+
17
+ def wrap_degrees(d):
18
+ """Map angle differences to (-180, 180]."""
19
+ return (np.asarray(d) + 180.0) % 360.0 - 180.0
20
+
21
+
22
+ def trajectory_metrics(generated, true, angles=False):
23
+ """MAE, RMSE and correlation coefficient between generated and true trajectories.
24
+
25
+ Args:
26
+ generated: array (length, num_samples, dim).
27
+ true: array (length, dim).
28
+ angles: if True, errors use the wrapped angular difference (degrees).
29
+
30
+ Metrics are computed per (sample, dimension) series and averaged, as in the paper's MD table.
31
+ """
32
+ generated = np.asarray(generated)
33
+ true = np.asarray(true)
34
+ err = generated - true[:, None, :]
35
+ if angles:
36
+ err = wrap_degrees(err)
37
+ mae = np.abs(err).mean(axis=0)
38
+ rmse = np.sqrt((err ** 2).mean(axis=0))
39
+ cc = np.full(mae.shape, np.nan)
40
+ for s in range(generated.shape[1]):
41
+ for j in range(generated.shape[2]):
42
+ g, r = generated[:, s, j], true[:, j]
43
+ if g.std() > 0 and r.std() > 0:
44
+ cc[s, j] = np.corrcoef(g, r)[0, 1]
45
+ out = {"MAE": float(mae.mean()), "MAE_std": float(mae.mean(1).std()),
46
+ "RMSE": float(rmse.mean()), "RMSE_std": float(rmse.mean(1).std()),
47
+ "CC": float("nan"), "CC_std": float("nan")}
48
+ if np.isfinite(cc).any():
49
+ per_sample = np.array([np.nanmean(row) if np.isfinite(row).any() else np.nan for row in cc])
50
+ out["CC"] = float(np.nanmean(cc))
51
+ out["CC_std"] = float(np.nanstd(per_sample))
52
+ return out
idff/models.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Joint-head networks for IDFF.
2
+
3
+ A single trunk feeds two linear heads: the denoiser x1_hat(x_t, t) and the score s_hat(x_t, t)
4
+ (paper, Sec. "Sample-Based Vector Field Learning"). SiLU activations keep the score smooth, so the
5
+ Jacobian used by the K >= 2 correction is well defined (ReLU networks are not suitable for K >= 2).
6
+ """
7
+ import math
8
+
9
+ import torch
10
+ from torch import nn
11
+
12
+
13
+ class SiLU(nn.Module):
14
+ """SiLU written as x * sigmoid(x).
15
+
16
+ Mathematically identical to ``torch.nn.SiLU``, but built from primitives that support nested
17
+ forward-mode differentiation, which the K >= 3 contracted derivatives require (the fused
18
+ ``aten::silu`` kernel does not support forward-over-forward AD).
19
+ """
20
+
21
+ def forward(self, x):
22
+ return x * torch.sigmoid(x)
23
+
24
+
25
+ class TimeFeatures(nn.Module):
26
+ """Fourier features of the flow time t: [t, sin(2 pi k t), cos(2 pi k t)] for k = 1..n_freq."""
27
+
28
+ def __init__(self, n_freq=4):
29
+ super().__init__()
30
+ self.register_buffer("freqs", 2.0 * math.pi * torch.arange(1, n_freq + 1).float())
31
+ self.out_dim = 1 + 2 * n_freq
32
+
33
+ def forward(self, t):
34
+ ang = t[:, None] * self.freqs[None]
35
+ return torch.cat([t[:, None], torch.sin(ang), torch.cos(ang)], dim=-1)
36
+
37
+
38
+ class JointHeadMLP(nn.Module):
39
+ """MLP with a shared trunk and two heads, returning ``(x1_hat, s_hat)``.
40
+
41
+ Args:
42
+ dim: data dimension.
43
+ hidden, depth: trunk width and number of hidden layers.
44
+ sigma0: path bandwidth used in training (needed for the score preconditioner).
45
+ base_std: std of the base distribution x0 around its mean (1 for N(0, I)).
46
+ num_positions: if given, adds a learned embedding of the sequence position n
47
+ (dual-time indexing for time series: t is the flow time, n the sequence position).
48
+ base_std_first: base std at position n = 0 when ``num_positions`` is set (x0 ~ N(0, I) there).
49
+ residual: if True, x1_hat = x_t + head(x_t, t); convenient for time series where
50
+ consecutive frames are close. It changes only the parameterisation, not the objective.
51
+ score_floor: floor of the score preconditioner.
52
+
53
+ The score head is preconditioned as s_hat = h_s / c(t) with
54
+ c(t) = sqrt(b^2 (1 - t)^2 + sigma_t^2 + floor^2), the local noise scale of p_t. This rescales
55
+ the head output only; the head is still trained to the marginal score by the IDFF objective.
56
+ """
57
+
58
+ def __init__(self, dim, hidden=256, depth=3, sigma0=0.2, base_std=1.0, num_positions=None,
59
+ base_std_first=1.0, residual=False, n_freq=4, pos_dim=64, score_floor=1e-2):
60
+ super().__init__()
61
+ self.dim = dim
62
+ self.sigma0 = float(sigma0)
63
+ self.base_std = float(base_std)
64
+ self.base_std_first = float(base_std_first)
65
+ self.residual = residual
66
+ self.score_floor = float(score_floor)
67
+ self.time = TimeFeatures(n_freq)
68
+ in_dim = dim + self.time.out_dim
69
+ self.pos = None
70
+ if num_positions is not None:
71
+ self.pos = nn.Embedding(num_positions, pos_dim)
72
+ in_dim += pos_dim
73
+ layers = [nn.Linear(in_dim, hidden), SiLU()]
74
+ for _ in range(depth - 1):
75
+ layers += [nn.Linear(hidden, hidden), SiLU()]
76
+ self.trunk = nn.Sequential(*layers)
77
+ self.head_x1 = nn.Linear(hidden, dim)
78
+ self.head_score = nn.Linear(hidden, dim)
79
+
80
+ def forward(self, x, t, n=None):
81
+ batch = x.shape[0]
82
+ if not torch.is_tensor(t):
83
+ t = torch.tensor(float(t), device=x.device, dtype=x.dtype)
84
+ t = t.to(dtype=x.dtype).reshape(-1)
85
+ if t.numel() == 1:
86
+ t = t.expand(batch)
87
+ feats = [x.reshape(batch, -1), self.time(t)]
88
+ if self.pos is not None:
89
+ if n is None:
90
+ raise ValueError("this model was built with num_positions; pass the sequence position n")
91
+ feats.append(self.pos(n.long()))
92
+ h = self.trunk(torch.cat(feats, dim=-1))
93
+ x1_hat = self.head_x1(h)
94
+ if self.residual:
95
+ x1_hat = x.reshape(batch, -1) + x1_hat
96
+ b = torch.full_like(t, self.base_std)
97
+ if self.pos is not None:
98
+ b = torch.where(n.reshape(-1) == 0, torch.full_like(t, self.base_std_first), b)
99
+ var = (b * (1.0 - t)) ** 2 + self.sigma0 ** 2 * t * (1.0 - t) + self.score_floor ** 2
100
+ s_hat = self.head_score(h) / torch.sqrt(var)[:, None]
101
+ return x1_hat.reshape_as(x), s_hat.reshape_as(x)
idff/sampling.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """IDFF samplers: Algorithm 1 (static data) and Algorithm 4 (time series) of the paper."""
2
+ import math
3
+
4
+ import torch
5
+ from torch.func import jvp
6
+
7
+ from .core import gamma_schedule
8
+
9
+
10
+ def contracted_score_derivative(score_fn, x, u, order):
11
+ """Return (grad_x^order s)(x)[u]^order, i.e. the contracted term m^(order + 1) of Eq. momentum_contraction.
12
+
13
+ ``order = 1`` gives the Hessian-vector product (grad_x s) u used at K = 2. Higher orders are
14
+ obtained by nesting forward-mode JVPs, so no tensor of order > 1 is ever formed.
15
+ """
16
+ f = score_fn
17
+ for _ in range(order):
18
+ f = _directional_derivative(f, u)
19
+ return f(x)
20
+
21
+
22
+ def _directional_derivative(f, u):
23
+ def g(y):
24
+ return jvp(f, (y,), (u,))[1]
25
+ return g
26
+
27
+
28
+ def _unit(v):
29
+ norm = v.reshape(v.shape[0], -1).norm(dim=1).clamp_min(1e-12)
30
+ return v / norm.reshape(-1, *([1] * (v.dim() - 1)))
31
+
32
+
33
+ @torch.no_grad()
34
+ def sample(model, x0, nfe, K=1, gamma_bar=0.2, alphas=None, schedule="beta22", diffusion_scale=2.0,
35
+ score_drift=True, model_kwargs=None, generator=None, return_trajectory=False):
36
+ """Integrate the IDFF SDE (Eq. idff_sde) with Euler-Maruyama (Algorithm 1).
37
+
38
+ dx = [gamma_t^0 v_hat + gamma_t^1 m^(1) + sum_{k=2..K} gamma_t^k m^(k)] dt + g_t dW,
39
+
40
+ with v_hat = (x1_hat - x) / (1 - t), m^(1) = s_hat, m^(k) = (grad^{k-1} s_hat)[u]^{k-1},
41
+ u = v_hat / ||v_hat||, gamma_t^0 = 1 (the paper's default), gamma_t^1 from ``schedule``,
42
+ gamma_t^k = alpha_k gamma_t^1 dt^(k-1) for k >= 2, and g_t^2 = diffusion_scale * gamma_t^1.
43
+
44
+ The defaults (K = 1, diffusion_scale = 2, score_drift = True) are the configuration whose
45
+ continuous-time marginals equal the CFM marginals exactly (Theorem first_order_preservation).
46
+ Other settings reproduce the ablations: ``K=0`` or ``gamma_bar=0`` is the deterministic CFM
47
+ sampler, ``score_drift=False`` is "Stochastic CFM" (noise without the score drift), and
48
+ ``diffusion_scale=0`` is the score drift without diffusion compensation.
49
+
50
+ Time grid: step i uses t_i = i / nfe, so exactly ``nfe`` network evaluations are made (K >= 2
51
+ adds one JVP per step and order). The coefficients are set to zero on the final step, as the
52
+ paper prescribes, so the last update is a pure CFM Euler step from t = 1 - dt; that step equals
53
+ the denoiser read-out x1_hat(x, 1 - dt), which is what is returned.
54
+
55
+ Args:
56
+ model: ``model(x, t, **model_kwargs) -> (x1_hat, s_hat)``.
57
+ x0: initial samples (N(0, I) for static data).
58
+ nfe: number of network evaluations (= Euler-Maruyama steps).
59
+ alphas: dict {k: alpha_k} for k >= 2; defaults to 0.05 for every order.
60
+ generator: optional torch.Generator for the Brownian increments.
61
+ return_trajectory: also return the stacked iterates, shape (nfe + 1, *x0.shape).
62
+ """
63
+ if nfe < 1:
64
+ raise ValueError("nfe must be >= 1")
65
+ alphas = alphas or {}
66
+ model_kwargs = model_kwargs or {}
67
+ dt = 1.0 / nfe
68
+ x = x0.clone()
69
+ traj = [x] if return_trajectory else None
70
+ for i in range(nfe):
71
+ t = i * dt
72
+ tb = torch.full((x.shape[0],), t, device=x.device, dtype=x.dtype)
73
+ x1_hat, s_hat = model(x, tb, **model_kwargs)
74
+ if i == nfe - 1:
75
+ x = x1_hat
76
+ else:
77
+ v = (x1_hat - x) / (1.0 - t)
78
+ g1 = gamma_schedule(t, gamma_bar, schedule) if K >= 1 else 0.0
79
+ drift = v
80
+ if g1 > 0 and score_drift:
81
+ drift = drift + g1 * s_hat
82
+ if K >= 2 and g1 > 0:
83
+ u = _unit(v)
84
+
85
+ def score_fn(y, tb=tb):
86
+ return model(y, tb, **model_kwargs)[1]
87
+
88
+ for k in range(2, K + 1):
89
+ gk = alphas.get(k, 0.05) * g1 * dt ** (k - 1)
90
+ drift = drift + gk * contracted_score_derivative(score_fn, x, u, k - 1)
91
+ x = x + drift * dt
92
+ if g1 > 0 and diffusion_scale > 0:
93
+ noise = torch.randn(x.shape, device=x.device, dtype=x.dtype, generator=generator)
94
+ x = x + math.sqrt(diffusion_scale * g1 * dt) * noise
95
+ if return_trajectory:
96
+ traj.append(x)
97
+ if return_trajectory:
98
+ return x, torch.stack(traj)
99
+ return x
100
+
101
+
102
+ @torch.no_grad()
103
+ def sample_next(model, prev, n, nfe, sigma0, generator=None, **sampler_kwargs):
104
+ """Sample frame n given frame n-1 (one step of Algorithm 4): x0^n ~ N(prev, sigma0^2 I)."""
105
+ noise = torch.randn(prev.shape, device=prev.device, dtype=prev.dtype, generator=generator)
106
+ x0 = prev + sigma0 * noise
107
+ nb = torch.full((prev.shape[0],), n, device=prev.device, dtype=torch.long)
108
+ return sample(model, x0, nfe, model_kwargs={"n": nb}, generator=generator, **sampler_kwargs)
109
+
110
+
111
+ @torch.no_grad()
112
+ def sample_sequence(model, length, num_samples, dim, nfe, sigma0, first_frame=None, device="cpu",
113
+ generator=None, **sampler_kwargs):
114
+ """Autoregressive time-series sampling (Algorithm 4, IDFF Sampling (Time-Series)).
115
+
116
+ Position 0 starts from N(0, I) unless ``first_frame`` is given (shape (dim,) shared by all
117
+ samples, or (num_samples, dim) one per sample), in which case the rollout is conditioned on it and
118
+ continues from position 1. Each later position starts from the previous generated frame,
119
+ x0^n ~ N(x1^{n-1}, sigma0^2 I).
120
+
121
+ Returns:
122
+ tensor of shape (length, num_samples, dim).
123
+ """
124
+ frames = []
125
+ if first_frame is None:
126
+ x0 = torch.randn((num_samples, dim), device=device, generator=generator)
127
+ nb = torch.zeros(num_samples, device=device, dtype=torch.long)
128
+ prev = sample(model, x0, nfe, model_kwargs={"n": nb}, generator=generator, **sampler_kwargs)
129
+ else:
130
+ prev = first_frame.to(device).expand(num_samples, dim).clone()
131
+ frames.append(prev)
132
+ for n in range(1, length):
133
+ prev = sample_next(model, prev, n, nfe, sigma0, generator=generator, **sampler_kwargs)
134
+ frames.append(prev)
135
+ return torch.stack(frames)
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ torch>=2.1
2
+ numpy
3
+ scipy
4
+ matplotlib
5
+ pot # optional: minibatch-OT coupling (OT-IDFF) via torchcfm.optimal_transport
scripts/make_gifs.py ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Render the README animations from the trained example models.
2
+
3
+ python scripts/make_gifs.py
4
+
5
+ Requires the checkpoints written by ``2D_examples/idff_2d.py --dataset 8gaussians`` and
6
+ ``timeseris_example/attractors.py --system lorenz``. Outputs ``assets/idff_2d.gif`` and
7
+ ``assets/idff_lorenz.gif``.
8
+
9
+ 2-D animation: CFM (deterministic), IDFF K=1 and IDFF K=2 at NFE = 5 share one trained network
10
+ and start from the same noise; frames between two sampler
11
+ steps are straight-line interpolations for display only.
12
+ """
13
+ import json
14
+ import sys
15
+ from pathlib import Path
16
+
17
+ import matplotlib
18
+
19
+ matplotlib.use("Agg")
20
+ import matplotlib.pyplot as plt # noqa: E402
21
+ import numpy as np # noqa: E402
22
+ import torch # noqa: E402
23
+ from matplotlib.animation import FuncAnimation, PillowWriter # noqa: E402
24
+
25
+ ROOT = Path(__file__).resolve().parents[1]
26
+ sys.path.insert(0, str(ROOT))
27
+
28
+ from idff import JointHeadMLP, sample, sample_sequence # noqa: E402
29
+ from idff.datasets import TOY_DATASETS, attractor_trajectories # noqa: E402
30
+
31
+ ASSETS = ROOT / "assets"
32
+
33
+
34
+ def load(path, **kwargs):
35
+ model = JointHeadMLP(**kwargs)
36
+ model.load_state_dict(torch.load(path, map_location="cpu", weights_only=True))
37
+ return model.eval()
38
+
39
+
40
+ COLORS = {"CFM (det.)": "tab:blue", "IDFF K=1": "tab:red", "IDFF K=2": "tab:purple"}
41
+
42
+
43
+ def gif_2d(dataset="8gaussians", nfes=(5,), n=1500, n_frames=40, hold=14):
44
+ """Rows: NFE budgets. Columns: CFM, IDFF K=1, IDFF K=2 (alpha_2 as selected by 2D_examples/idff_2d.py).
45
+
46
+ NFE = 2 is not shown: gamma_t^1 vanishes at t = 0 and the coefficients are switched off on the final
47
+ step, so with two steps every sampler coincides with CFM. Test MMDs are in the README table.
48
+ """
49
+ out = ROOT / "2D_examples" / "outputs" / dataset
50
+ cfg = json.loads((out / "config.json").read_text())
51
+ model = load(out / "idff_model.pt", dim=2, hidden=256, depth=3, sigma0=cfg["sigma0"])
52
+ torch.manual_seed(3)
53
+ data = TOY_DATASETS[dataset](4000).numpy()
54
+ grid = []
55
+ for nfe in nfes:
56
+ sel = cfg["selected"][str(nfe)] # chosen per budget on validation data by idff_2d.py
57
+ gamma, a2 = sel["gamma_bar"], sel["alpha_2"]
58
+ row = []
59
+ for label, kw in [("CFM (det.)", dict(K=0)),
60
+ ("IDFF K=1", dict(K=1, gamma_bar=gamma)),
61
+ ("IDFF K=2", dict(K=2, gamma_bar=gamma, alphas={2: a2}))]:
62
+ x0 = torch.randn(n, 2, generator=torch.Generator().manual_seed(0))
63
+ _, traj = sample(model, x0, nfe, generator=torch.Generator().manual_seed(100),
64
+ return_trajectory=True, **kw)
65
+ row.append((label if label != "IDFF K=2" else f"IDFF K=2 (alpha_2={a2:g})", traj.numpy()))
66
+ grid.append((nfe, row))
67
+
68
+ taus = np.concatenate([np.linspace(0, 1, n_frames), np.ones(hold)])
69
+ fig, axs = plt.subplots(len(nfes), 3, figsize=(9.6, 3.35 * len(nfes) + 0.35), squeeze=False)
70
+ lim = np.abs(data).max() + 1.0
71
+ scats = []
72
+ for r, (nfe, row) in enumerate(grid):
73
+ for c, (label, traj) in enumerate(row):
74
+ ax = axs[r, c]
75
+ ax.scatter(data[:, 0], data[:, 1], s=1, c="0.82", rasterized=True)
76
+ sc = ax.scatter(traj[0, :, 0], traj[0, :, 1], s=1.5, c=COLORS[label.split(" (alpha")[0]], alpha=0.6)
77
+ ax.set_xlim(-lim, lim)
78
+ ax.set_ylim(-lim, lim)
79
+ ax.set_xticks([])
80
+ ax.set_yticks([])
81
+ ax.set_title(f"{label}\nNFE={nfe}", fontsize=9)
82
+ scats.append((sc, traj, nfe))
83
+ title = fig.suptitle("", fontsize=11)
84
+ fig.tight_layout(rect=(0, 0, 1, 0.965))
85
+
86
+ def update(k):
87
+ tau = taus[k]
88
+ for sc, traj, nfe in scats:
89
+ s = tau * nfe
90
+ i = min(int(np.floor(s)), nfe - 1)
91
+ a = s - i
92
+ sc.set_offsets((1 - a) * traj[i] + a * traj[i + 1])
93
+ title.set_text(f"{dataset}: sampling from noise to data t = {tau:.2f} (grey: data)")
94
+ return [s for s, _, _ in scats] + [title]
95
+
96
+ anim = FuncAnimation(fig, update, frames=len(taus), blit=False)
97
+ path = ASSETS / "idff_2d.gif"
98
+ anim.save(path, writer=PillowWriter(fps=12), dpi=65)
99
+ plt.close(fig)
100
+ return path
101
+
102
+
103
+ def gif_lorenz(nfe=5, n_frames=100):
104
+ """CFM, IDFF K=1 and IDFF K=2 rollouts over a whole held-out Lorenz trajectory, all sharing one
105
+ trained network, started from the same first frame with the same noise seed. gamma_bar and alpha_2
106
+ are those selected per budget on the validation trajectories by timeseris_example/attractors.py."""
107
+ systems = ["lorenz"]
108
+ panels = []
109
+ for system in systems:
110
+ out = ROOT / "timeseris_example" / "outputs" / system
111
+ cfg = json.loads((out / "config.json").read_text())
112
+ n_train, n_val, n_test = cfg["n_train"], cfg["n_val"], cfg["n_test"]
113
+ raw = attractor_trajectories(system, n_train + n_val + n_test, cfg["length"], seed=0)
114
+ train = raw[:n_train]
115
+ mean, std = train.reshape(-1, 3).mean(0), train.reshape(-1, 3).std(0)
116
+ true = raw[n_train + n_val] # first held-out test trajectory
117
+ model = load(out / "idff_model.pt", dim=3, hidden=128, depth=2, sigma0=cfg["sigma0"],
118
+ base_std=cfg["sigma0"], num_positions=cfg["length"], residual=True)
119
+ first = torch.tensor((true[0] - mean) / std, dtype=torch.float32)
120
+ sel = cfg["selected"][str(nfe)] # chosen per budget on validation trajectories
121
+ g = sel["gamma_bar"]
122
+ for label, kw in [("CFM (det.)", dict(K=0)),
123
+ ("IDFF K=1", dict(K=1, gamma_bar=g)),
124
+ ("IDFF K=2", dict(K=2, gamma_bar=g, alphas={2: sel["alpha_2"]}))]:
125
+ gen = sample_sequence(model, cfg["length"], 1, 3, nfe, cfg["sigma0"], first_frame=first,
126
+ generator=torch.Generator().manual_seed(0), **kw)
127
+ gen = gen[:, 0].numpy() * std + mean
128
+ name = label if label != "IDFF K=2" else f"IDFF K=2 (alpha_2={sel['alpha_2']:g})"
129
+ panels.append((system, label, name, true, gen))
130
+ length = len(panels[0][3])
131
+
132
+ fig = plt.figure(figsize=(11.4, 3.9))
133
+ axes, lines = [], []
134
+ for j, (system, label, name, true, gen) in enumerate(panels):
135
+ color = COLORS[label]
136
+ ax = fig.add_subplot(1, 3, j + 1, projection="3d")
137
+ ax.plot(*true.T, c="0.6", lw=0.5, alpha=0.6)
138
+ (line,) = ax.plot([], [], [], c=color, lw=0.9)
139
+ (head,) = ax.plot([], [], [], "o", c=color, ms=3)
140
+ lo, hi = np.minimum(true.min(0), gen.min(0)), np.maximum(true.max(0), gen.max(0))
141
+ ax.set_xlim(lo[0], hi[0])
142
+ ax.set_ylim(lo[1], hi[1])
143
+ ax.set_zlim(lo[2], hi[2])
144
+ ax.set_xticklabels([])
145
+ ax.set_yticklabels([])
146
+ ax.set_zticklabels([])
147
+ ax.set_title(f"{name}\nNFE={nfe}", fontsize=9)
148
+ axes.append(ax)
149
+ lines.append((line, head, gen))
150
+ title = fig.suptitle("", fontsize=10)
151
+ fig.tight_layout(rect=(0, 0, 1, 0.86))
152
+ steps = np.linspace(2, length, n_frames).astype(int)
153
+
154
+ def update(k):
155
+ m = steps[min(k, len(steps) - 1)]
156
+ for ax, (line, head, gen) in zip(axes, lines):
157
+ line.set_data(gen[:m, 0], gen[:m, 1])
158
+ line.set_3d_properties(gen[:m, 2])
159
+ head.set_data(gen[m - 1:m, 0], gen[m - 1:m, 1])
160
+ head.set_3d_properties(gen[m - 1:m, 2])
161
+ ax.view_init(elev=22, azim=-65 + 0.3 * k)
162
+ title.set_text(f"Lorenz: autoregressive rollout from a held-out first frame, step {m}/{length} "
163
+ "(grey: simulated trajectory)")
164
+ return [x for ln in lines for x in ln[:2]]
165
+
166
+ anim = FuncAnimation(fig, update, frames=n_frames + 12, blit=False)
167
+ path = ASSETS / "idff_lorenz.gif"
168
+ anim.save(path, writer=PillowWriter(fps=12), dpi=62)
169
+ plt.close(fig)
170
+ return path
171
+
172
+
173
+ if __name__ == "__main__":
174
+ ASSETS.mkdir(exist_ok=True)
175
+ for p in (gif_2d(), gif_lorenz()):
176
+ print(f"wrote {p} ({p.stat().st_size / 1e6:.2f} MB)")
tests/test_idff.py ADDED
@@ -0,0 +1,259 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for the IDFF reference implementation.
2
+
3
+ Besides unit tests, two tests check the paper's theory numerically on Gaussian data, where every
4
+ quantity is available in closed form:
5
+ * Theorem first_order_preservation: the K = 1 sampler with g_t^2 = 2 gamma_t^1 and the exact score
6
+ reproduces the CFM marginals, while mismatched diffusion does not.
7
+ * Fisher's identity: the score head trained with the IDFF objective converges to the marginal score.
8
+ """
9
+ import math
10
+ import sys
11
+ from pathlib import Path
12
+
13
+ import numpy as np
14
+ import pytest
15
+ import torch
16
+
17
+ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
18
+
19
+ from idff import (JointHeadMLP, contracted_score_derivative, gamma_schedule, idff_loss, # noqa: E402
20
+ sample, sample_next, sample_sequence, sequence_training_pairs, sigma_t)
21
+ from idff.datasets import TOY_DATASETS, attractor_trajectories # noqa: E402
22
+ from idff.metrics import mmd_rbf, trajectory_metrics, wrap_degrees # noqa: E402
23
+
24
+ M = torch.tensor([1.0, -2.0]) # data mean for the Gaussian tests
25
+ S = 0.5 # data std
26
+
27
+
28
+ class GaussianOracle(torch.nn.Module):
29
+ """Exact (x1_hat, s_hat) for x0 ~ N(0, I), x1 ~ N(M, S^2 I), x_t = t x1 + (1 - t) x0 + sigma_t eps."""
30
+
31
+ def __init__(self, sigma0=0.0):
32
+ super().__init__()
33
+ self.sigma0 = sigma0
34
+
35
+ def variance(self, t):
36
+ return t ** 2 * S ** 2 + (1 - t) ** 2 + self.sigma0 ** 2 * t * (1 - t)
37
+
38
+ def forward(self, x, t):
39
+ t = t.reshape(-1, 1)
40
+ var = self.variance(t)
41
+ x1_hat = M + (t * S ** 2 / var) * (x - t * M)
42
+ score = -(x - t * M) / var
43
+ return x1_hat, score
44
+
45
+
46
+ # --------------------------------------------------------------------------------------------
47
+ # Unit tests
48
+ # --------------------------------------------------------------------------------------------
49
+ def test_sigma_and_schedules_vanish_at_endpoints():
50
+ assert sigma_t(0.0, 0.3) == 0.0 and sigma_t(1.0, 0.3) == 0.0
51
+ assert math.isclose(sigma_t(0.5, 0.2), 0.1)
52
+ for shape in ["beta22", "triangular", "sine", "beta33"]:
53
+ assert gamma_schedule(0.0, 0.7, shape) == pytest.approx(0.0, abs=1e-12)
54
+ assert gamma_schedule(1.0, 0.7, shape) == pytest.approx(0.0, abs=1e-12)
55
+ assert gamma_schedule(0.5, 0.7, shape) > 0
56
+ assert gamma_schedule(0.5, 0.7, "beta22") == pytest.approx(0.7)
57
+
58
+
59
+ def test_loss_matches_manual_computation():
60
+ torch.manual_seed(0)
61
+ model = JointHeadMLP(2, hidden=16, depth=2, sigma0=0.3)
62
+ x1, x0, t = torch.randn(64, 2), torch.randn(64, 2), torch.rand(64)
63
+ torch.manual_seed(1)
64
+ loss, stats = idff_loss(model, x1, x0=x0, t=t, sigma0=0.3)
65
+ torch.manual_seed(1)
66
+ eps = torch.randn_like(x1)
67
+ st = 0.3 * torch.sqrt(t * (1 - t))[:, None]
68
+ xt = t[:, None] * x1 + (1 - t[:, None]) * x0 + st * eps
69
+ x1_hat, s_hat = model(xt, t)
70
+ beta = 1 / (1 - t[:, None] + 1e-2)
71
+ manual = ((beta * (x1_hat - x1)) ** 2).mean() + (st ** 2 * (s_hat + eps / st) ** 2).mean()
72
+ assert loss.item() == pytest.approx(manual.item(), rel=1e-5)
73
+ with pytest.raises(ValueError):
74
+ idff_loss(model, x1, sigma0=0.0)
75
+
76
+
77
+ def test_contracted_derivatives_match_closed_form():
78
+ torch.manual_seed(0)
79
+ a = torch.randn(3, 3)
80
+
81
+ def score(y): # linear part plus elementwise cubic: derivatives known in closed form
82
+ return y @ a.T + 0.3 * y ** 3
83
+
84
+ x, u = torch.randn(5, 3), torch.randn(5, 3)
85
+ m2 = contracted_score_derivative(score, x, u, 1)
86
+ m3 = contracted_score_derivative(score, x, u, 2)
87
+ m4 = contracted_score_derivative(score, x, u, 3)
88
+ torch.testing.assert_close(m2, u @ a.T + 0.9 * x ** 2 * u)
89
+ torch.testing.assert_close(m3, 1.8 * x * u ** 2)
90
+ torch.testing.assert_close(m4, 1.8 * u ** 3)
91
+
92
+
93
+ def test_network_evaluation_count_and_determinism():
94
+ class Counting(torch.nn.Module):
95
+ def __init__(self):
96
+ super().__init__()
97
+ self.calls = 0
98
+ self.net = JointHeadMLP(2, hidden=16, depth=2)
99
+
100
+ def forward(self, x, t):
101
+ self.calls += 1
102
+ return self.net(x, t)
103
+
104
+ model = Counting()
105
+ x0 = torch.randn(8, 2)
106
+ for nfe in [1, 2, 5]:
107
+ model.calls = 0
108
+ sample(model, x0, nfe, K=1)
109
+ assert model.calls == nfe
110
+ model.calls = 0
111
+ sample(model, x0, 6, K=2)
112
+ assert model.calls == 6 + 4 # one JVP on every step with gamma_t^1 > 0 (all but the first and last)
113
+ a = sample(model, x0, 5, K=0, generator=torch.Generator().manual_seed(0))
114
+ b = sample(model, x0, 5, K=0, generator=torch.Generator().manual_seed(1))
115
+ torch.testing.assert_close(a, b)
116
+
117
+
118
+ def test_sequence_training_pairs():
119
+ data = torch.arange(2 * 5 * 3, dtype=torch.float32).reshape(2, 5, 3)
120
+ torch.manual_seed(0)
121
+ x0, x1, n = sequence_training_pairs(data, 512, sigma0=1e-3)
122
+ for i in range(len(n)):
123
+ k = n[i].item()
124
+ seq = [s for s in range(2) if torch.equal(x1[i], data[s, k])]
125
+ assert len(seq) == 1 # x1 is a data frame at position n
126
+ if k > 0: # x0 ~ N(x^{n-1}, sigma0^2 I) for the same sequence
127
+ assert (x0[i] - data[seq[0], k - 1]).abs().max() < 0.01
128
+ assert x0[n == 0].std() > 0.5 # position 0 starts from N(0, I)
129
+
130
+
131
+ def test_ot_coupling_shortens_pairs():
132
+ pytest.importorskip("ot")
133
+ from idff import ot_coupling
134
+
135
+ torch.manual_seed(0)
136
+ x0, x1 = torch.randn(256, 2), TOY_DATASETS["8gaussians"](256)
137
+ p0, p1 = ot_coupling(x0, x1)
138
+ assert p0.shape == x0.shape and p1.shape == x1.shape
139
+ assert ((p1 - p0) ** 2).sum(1).mean() < 0.6 * ((x1 - x0) ** 2).sum(1).mean()
140
+ # N(0, I) -> N(m, I): W2^2 = |m|^2 = 18, while independent pairing costs |m|^2 + 2d = 22
141
+ x0, x1 = torch.randn(512, 2), torch.randn(512, 2) + 3.0
142
+ p0, p1 = ot_coupling(x0, x1)
143
+ assert abs(((p1 - p0) ** 2).sum(1).mean().item() - 18.0) < 2.0
144
+
145
+
146
+ def test_metrics():
147
+ assert wrap_degrees(350.0) == pytest.approx(-10.0)
148
+ true = np.stack([np.linspace(0, 10, 50), np.linspace(0, -5, 50)], 1)
149
+ m = trajectory_metrics(true[:, None, :], true)
150
+ assert m["MAE"] == 0 and m["RMSE"] == 0 and m["CC"] == pytest.approx(1.0)
151
+ m = trajectory_metrics(np.full((3, 1, 1), 179.0), np.full((3, 1), -179.0), angles=True)
152
+ assert m["MAE"] == pytest.approx(2.0)
153
+ x = torch.randn(300, 2)
154
+ assert mmd_rbf(x, x) == pytest.approx(0.0, abs=1e-12)
155
+ assert mmd_rbf(x, x + 3.0) > 0.1
156
+
157
+
158
+ # --------------------------------------------------------------------------------------------
159
+ # Theory checks on Gaussian data
160
+ # --------------------------------------------------------------------------------------------
161
+ @pytest.mark.parametrize("gamma_bar", [0.0, 1.0])
162
+ def test_k1_sampler_preserves_marginals_with_exact_score(gamma_bar):
163
+ """Theorem first_order_preservation: Langevin drift + matched diffusion leaves p_t unchanged.
164
+
165
+ With sigma0 = 0 the velocity (x1_hat - x)/(1 - t) is the exact marginal field, so the only
166
+ errors are Euler-Maruyama discretisation and Monte-Carlo noise.
167
+ """
168
+ torch.manual_seed(0)
169
+ oracle = GaussianOracle(sigma0=0.0)
170
+ nfe, n = 400, 40000
171
+ x, traj = sample(oracle, torch.randn(n, 2), nfe, K=1, gamma_bar=gamma_bar, return_trajectory=True)
172
+ torch.testing.assert_close(x.mean(0), M, atol=0.02, rtol=0)
173
+ assert x.var(0).sub(S ** 2).abs().max() < 0.03 * S ** 2
174
+ mid = traj[nfe // 2] # t = 0.5
175
+ var_mid = oracle.variance(torch.tensor(0.5)).item()
176
+ torch.testing.assert_close(mid.mean(0), 0.5 * M, atol=0.02, rtol=0)
177
+ assert mid.var(0).sub(var_mid).abs().max() < 0.03 * var_mid
178
+
179
+
180
+ def test_mismatched_diffusion_breaks_preservation():
181
+ """The cancellation needs g_t^2 = 2 gamma_t^1: dropping the noise shrinks the variance, and noise
182
+ without the score drift inflates it."""
183
+ torch.manual_seed(0)
184
+ oracle = GaussianOracle(sigma0=0.0)
185
+ x0 = torch.randn(40000, 2)
186
+ no_noise = sample(oracle, x0, 400, K=1, gamma_bar=1.0, diffusion_scale=0.0)
187
+ noise_only = sample(oracle, x0, 400, K=1, gamma_bar=1.0, score_drift=False)
188
+ assert no_noise.var(0).max() < 0.85 * S ** 2
189
+ assert noise_only.var(0).min() > 1.15 * S ** 2
190
+
191
+
192
+ def test_score_head_learns_marginal_score():
193
+ """Fisher's identity: regressing on -eps/sigma_t yields grad log p_t (and the denoiser E[x1 | x_t])."""
194
+ torch.manual_seed(0)
195
+ sigma0 = 0.5
196
+ model = JointHeadMLP(2, hidden=128, depth=3, sigma0=sigma0)
197
+ opt = torch.optim.Adam(model.parameters(), lr=2e-3)
198
+ for _ in range(3000):
199
+ x1 = M + S * torch.randn(1024, 2)
200
+ loss, _ = idff_loss(model, x1, sigma0=sigma0)
201
+ opt.zero_grad()
202
+ loss.backward()
203
+ opt.step()
204
+ oracle = GaussianOracle(sigma0=sigma0)
205
+ for t in [0.2, 0.5, 0.8]:
206
+ st = sigma0 * math.sqrt(t * (1 - t))
207
+ xt = t * (M + S * torch.randn(4000, 2)) + (1 - t) * torch.randn(4000, 2) + st * torch.randn(4000, 2)
208
+ tb = torch.full((4000,), t)
209
+ with torch.no_grad():
210
+ x1_hat, s_hat = model(xt, tb)
211
+ x1_true, s_true = oracle(xt, tb)
212
+ rel_score = ((s_hat - s_true).norm(dim=1) / s_true.norm(dim=1)).median()
213
+ rel_x1 = ((x1_hat - x1_true).norm(dim=1) / x1_true.norm(dim=1)).median()
214
+ assert rel_score < 0.15, (t, rel_score)
215
+ assert rel_x1 < 0.05, (t, rel_x1)
216
+
217
+
218
+ # --------------------------------------------------------------------------------------------
219
+ # End-to-end smoke tests
220
+ # --------------------------------------------------------------------------------------------
221
+ @pytest.mark.parametrize("name", list(TOY_DATASETS))
222
+ def test_static_training_and_sampling_smoke(name):
223
+ torch.manual_seed(0)
224
+ model = JointHeadMLP(2, hidden=64, depth=2, sigma0=0.2)
225
+ opt = torch.optim.Adam(model.parameters(), lr=1e-3)
226
+ losses = []
227
+ for _ in range(200):
228
+ loss, _ = idff_loss(model, TOY_DATASETS[name](256), sigma0=0.2)
229
+ opt.zero_grad()
230
+ loss.backward()
231
+ opt.step()
232
+ losses.append(loss.item())
233
+ assert np.mean(losses[-20:]) < np.mean(losses[:20])
234
+ for K in [0, 1, 2, 3]:
235
+ out = sample(model, torch.randn(128, 2), 5, K=K, gamma_bar=0.5, alphas={2: 1.0, 3: 1.0})
236
+ assert out.shape == (128, 2) and torch.isfinite(out).all()
237
+
238
+
239
+ def test_sequence_training_and_sampling_smoke():
240
+ torch.manual_seed(0)
241
+ raw = attractor_trajectories("lorenz", num_traj=4, length=30, burn_in=200, seed=0)
242
+ data = torch.tensor((raw - raw.mean((0, 1))) / raw.std((0, 1)), dtype=torch.float32)
243
+ model = JointHeadMLP(3, hidden=64, depth=2, sigma0=0.05, base_std=0.05, num_positions=30, residual=True)
244
+ opt = torch.optim.Adam(model.parameters(), lr=1e-3)
245
+ for _ in range(100):
246
+ x0, x1, n = sequence_training_pairs(data, 128, sigma0=0.05)
247
+ loss, _ = idff_loss(model, x1, x0=x0, sigma0=0.05, model_kwargs={"n": n})
248
+ opt.zero_grad()
249
+ loss.backward()
250
+ opt.step()
251
+ for K in [0, 1, 2]:
252
+ traj = sample_sequence(model, 30, 4, 3, nfe=3, sigma0=0.05, K=K)
253
+ assert traj.shape == (30, 4, 3) and torch.isfinite(traj).all()
254
+ cond = sample_sequence(model, 30, 4, 3, nfe=3, sigma0=0.05, first_frame=data[0, 0], K=K)
255
+ torch.testing.assert_close(cond[0], data[0, 0].expand(4, 3))
256
+ per_sample = sample_sequence(model, 30, 4, 3, nfe=3, sigma0=0.05, first_frame=data[:, 0], K=K)
257
+ torch.testing.assert_close(per_sample[0], data[:, 0])
258
+ nxt = sample_next(model, data[:, 3], 4, nfe=3, sigma0=0.05)
259
+ assert nxt.shape == (4, 3)
timeseris_example/MD_simulation.py ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """IDFF surrogate model for polyALA molecular dynamics (paper, Sec. "Surrogate Models for Molecular Dynamics").
2
+
3
+ The data are the 46 backbone dihedral angles (23 phi/psi pairs) of a 200-frame polyALA trajectory.
4
+ A single joint-head network with dual-time indexing (flow time t, sequence position n) is trained
5
+ with the IDFF objective (Algorithm 3) and sampled autoregressively (Algorithm 4): position 0 starts
6
+ from N(0, I), every later position from x0^n ~ N(x1^{n-1}, sigma0^2 I).
7
+
8
+ Generated trajectories are compared with the true one by MAE / RMSE (wrapped angular error, degrees)
9
+ and the correlation coefficient, for the deterministic CFM sampler and IDFF with K = 1 and K = 2,
10
+ all sharing the same trained network.
11
+
12
+ Scale of the Langevin amplitude: the paper's gamma_bar in [0.1, 0.3] refers to a unit-variance base
13
+ N(0, I). Here the base is the previous frame plus N(0, sigma0^2 I) noise, so p_t has width ~sigma0
14
+ and its score a Lipschitz constant ~1/sigma0^2; Euler-Maruyama on the Langevin term is only stable
15
+ when gamma_t dt / sigma0^2 is small. We therefore set gamma_bar = gamma_rel * sigma0^2 (gamma_rel = 1
16
+ by default, chosen a priori, not tuned on the evaluation trajectory). ``--sweep`` reports the
17
+ sensitivity to gamma_rel and alpha_2. Example:
18
+
19
+ python timeseris_example/MD_simulation.py --nfes 3 5 10
20
+ """
21
+ import argparse
22
+ import csv
23
+ import json
24
+ import sys
25
+ import time
26
+ from pathlib import Path
27
+
28
+ import matplotlib
29
+
30
+ matplotlib.use("Agg")
31
+ import matplotlib.pyplot as plt # noqa: E402
32
+ import numpy as np # noqa: E402
33
+ import torch # noqa: E402
34
+
35
+ HERE = Path(__file__).resolve().parent
36
+ sys.path.insert(0, str(HERE.parent))
37
+
38
+ from idff import JointHeadMLP, idff_loss, sample_sequence, sequence_training_pairs # noqa: E402
39
+ from idff.datasets import load_polyala_angles # noqa: E402
40
+ from idff.metrics import trajectory_metrics, wrap_degrees # noqa: E402
41
+
42
+
43
+ def repo_relative(args):
44
+ """Command-line arguments with paths made relative to the repository (for config.json)."""
45
+ out = dict(vars(args))
46
+ for key in ("out", "data"):
47
+ if key in out:
48
+ try:
49
+ out[key] = str(Path(out[key]).resolve().relative_to(HERE.parent))
50
+ except ValueError:
51
+ pass
52
+ return out
53
+
54
+
55
+ def parse_args():
56
+ p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
57
+ p.add_argument("--data", default=str(HERE / "data" / "polyALA_angles.npz"),
58
+ help="polyALA_angles.npz (shipped) or the original polyALA_dataset.p")
59
+ p.add_argument("--iters", type=int, default=20000)
60
+ p.add_argument("--batch", type=int, default=256)
61
+ p.add_argument("--lr", type=float, default=1e-3)
62
+ p.add_argument("--sigma0", type=float, default=0.1, help="path bandwidth and Markov-init noise (standardised units)")
63
+ p.add_argument("--nfes", type=int, nargs="+", default=[3, 5, 10])
64
+ p.add_argument("--gamma-rel", type=float, default=1.0,
65
+ help="Langevin amplitude relative to the base variance: gamma_bar = gamma_rel * sigma0^2")
66
+ p.add_argument("--alpha2", type=float, default=0.05, help="second-order scale (paper: ~0.05)")
67
+ p.add_argument("--num-traj", type=int, default=5)
68
+ p.add_argument("--seeds", type=int, default=3)
69
+ p.add_argument("--sweep", action="store_true", help="also report a gamma_bar / alpha_2 sensitivity sweep")
70
+ p.add_argument("--retrain", action="store_true")
71
+ p.add_argument("--out", default=str(HERE / "outputs" / "polyALA"))
72
+ return p.parse_args()
73
+
74
+
75
+ def prepare(path):
76
+ """Unwrap each angle in time (period 360) so consecutive frames are close, then standardise."""
77
+ raw = load_polyala_angles(path)
78
+ unwrapped = np.unwrap(raw, period=360.0, axis=0)
79
+ mean, std = unwrapped.mean(0), unwrapped.std(0) + 1e-6
80
+ data = torch.tensor((unwrapped - mean) / std, dtype=torch.float32)[None] # (1, frames, 46)
81
+ return raw, unwrapped, data, mean, std
82
+
83
+
84
+ def train(args, data, out_dir):
85
+ length, dim = data.shape[1], data.shape[2]
86
+ model = JointHeadMLP(dim, hidden=256, depth=3, sigma0=args.sigma0, base_std=args.sigma0,
87
+ num_positions=length, residual=True)
88
+ ckpt = out_dir / "idff_md.pt"
89
+ if ckpt.exists() and not args.retrain:
90
+ model.load_state_dict(torch.load(ckpt, map_location="cpu", weights_only=True))
91
+ print(f"loaded {ckpt}")
92
+ return model.eval()
93
+ torch.manual_seed(0)
94
+ opt = torch.optim.Adam(model.parameters(), lr=args.lr)
95
+ sched = torch.optim.lr_scheduler.CosineAnnealingLR(opt, args.iters)
96
+ start = time.time()
97
+ for it in range(1, args.iters + 1):
98
+ x0, x1, n = sequence_training_pairs(data, args.batch, args.sigma0)
99
+ loss, stats = idff_loss(model, x1, x0=x0, sigma0=args.sigma0, model_kwargs={"n": n})
100
+ opt.zero_grad()
101
+ loss.backward()
102
+ torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
103
+ opt.step()
104
+ sched.step()
105
+ if it % 2000 == 0:
106
+ print(f"iter {it:6d} loss {loss.item():.4f} denoiser {stats['denoiser']:.4f} "
107
+ f"score {stats['score']:.4f} ({time.time() - start:.0f}s)")
108
+ torch.save(model.state_dict(), ckpt)
109
+ return model.eval()
110
+
111
+
112
+ def generate(model, data, args, nfe, seed, **cfg):
113
+ gen = torch.Generator().manual_seed(seed)
114
+ traj = sample_sequence(model, data.shape[1], args.num_traj, data.shape[2], nfe, args.sigma0,
115
+ generator=gen, **cfg)
116
+ return traj.numpy() # (frames, num_traj, 46), standardised
117
+
118
+
119
+ def evaluate(model, data, unwrapped, mean, std, args, nfe, cfg):
120
+ """Mean of each metric over sampling seeds; each seed rolls out ``num_traj`` trajectories."""
121
+ per_seed = []
122
+ for seed in range(args.seeds):
123
+ gen = generate(model, data, args, nfe, seed, **cfg) * std + mean # degrees (unwrapped)
124
+ per_seed.append(trajectory_metrics(gen, unwrapped, angles=True))
125
+ keys = ["MAE", "RMSE", "CC"]
126
+ return {k: float(np.mean([m[k] for m in per_seed])) for k in keys} | \
127
+ {k + "_seed_std": float(np.std([m[k] for m in per_seed])) for k in keys}
128
+
129
+
130
+ def main():
131
+ args = parse_args()
132
+ out_dir = Path(args.out)
133
+ out_dir.mkdir(parents=True, exist_ok=True)
134
+ raw, unwrapped, data, mean, std = prepare(args.data)
135
+ print(f"polyALA: {data.shape[1]} frames x {data.shape[2]} dihedral angles")
136
+ model = train(args, data, out_dir)
137
+
138
+ gamma_bar = args.gamma_rel * args.sigma0 ** 2
139
+ methods = {
140
+ "CFM (det.)": dict(K=0),
141
+ "IDFF K=1": dict(K=1, gamma_bar=gamma_bar),
142
+ "IDFF K=2": dict(K=2, gamma_bar=gamma_bar, alphas={2: args.alpha2}),
143
+ }
144
+ rows = []
145
+ for nfe in args.nfes:
146
+ for name, cfg in methods.items():
147
+ m = evaluate(model, data, unwrapped, mean, std, args, nfe, cfg)
148
+ rows.append({"method": name, "nfe": nfe, "gamma_rel": args.gamma_rel if "gamma_bar" in cfg else 0.0,
149
+ "alpha2": cfg.get("alphas", {}).get(2, ""), **m})
150
+ print(f"NFE={nfe:3d} {name:12s} MAE {m['MAE']:6.2f} RMSE {m['RMSE']:6.2f} CC {100 * m['CC']:5.1f}%")
151
+
152
+ if args.sweep:
153
+ print("\nsensitivity (NFE = max of --nfes):")
154
+ nfe = max(args.nfes)
155
+ for rel in [0.1, 0.3, 1.0, 3.0, 10.0]:
156
+ g = rel * args.sigma0 ** 2
157
+ for name, cfg in [("IDFF K=1", dict(K=1, gamma_bar=g))] + \
158
+ [("IDFF K=2", dict(K=2, gamma_bar=g, alphas={2: a})) for a in [-5.0, -1.0, 0.05, 1.0, 5.0]]:
159
+ m = evaluate(model, data, unwrapped, mean, std, args, nfe, cfg)
160
+ rows.append({"method": name + " (sweep)", "nfe": nfe, "gamma_rel": rel,
161
+ "alpha2": cfg.get("alphas", {}).get(2, ""), **m})
162
+ print(f" gamma_rel={rel:<5} {name} alpha2={cfg.get('alphas', {}).get(2, '-')!s:<5} "
163
+ f"MAE {m['MAE']:6.2f} RMSE {m['RMSE']:6.2f} CC {100 * m['CC']:5.1f}%")
164
+
165
+ with open(out_dir / "evaluation_results.csv", "w", newline="") as fh:
166
+ writer = csv.DictWriter(fh, fieldnames=list(rows[0]))
167
+ writer.writeheader()
168
+ writer.writerows(rows)
169
+ with open(out_dir / "config.json", "w") as fh:
170
+ json.dump(repo_relative(args), fh, indent=2)
171
+ plot(model, data, raw, mean, std, args, out_dir)
172
+ print(f"\nwrote results to {out_dir}")
173
+
174
+
175
+ def plot(model, data, raw, mean, std, args, out_dir, angle=10):
176
+ """Figure in the style of the paper's MD figure: true vs generated (phi, psi) and one angle over time."""
177
+ nfe = max(args.nfes)
178
+ gen = generate(model, data, args, nfe, 0, K=1, gamma_bar=args.gamma_rel * args.sigma0 ** 2) * std + mean
179
+ gen_w = wrap_degrees(gen)
180
+ fig, axs = plt.subplots(1, 3, figsize=(13, 3.8))
181
+ axs[0].scatter(raw[:, 0::2].ravel(), raw[:, 1::2].ravel(), s=2, c="k", alpha=0.3)
182
+ axs[0].set_title("(A) true (phi, psi)")
183
+ axs[1].scatter(gen_w[:, :, 0::2].ravel(), gen_w[:, :, 1::2].ravel(), s=2, c="tab:red", alpha=0.3)
184
+ axs[1].set_title(f"(B) IDFF K=1, NFE={nfe}")
185
+ for ax in axs[:2]:
186
+ ax.set_xlim(-180, 180)
187
+ ax.set_ylim(-180, 180)
188
+ ax.set_xlabel("phi")
189
+ ax.set_ylabel("psi")
190
+ for k in range(gen_w.shape[1]):
191
+ axs[2].plot(gen_w[:, k, angle], c="tab:red", alpha=0.5, lw=1)
192
+ axs[2].plot(raw[:, angle], c="k", lw=1.5, label="true")
193
+ axs[2].set_title(f"(C) angle {angle}: true (black) vs generated (red)")
194
+ axs[2].set_xlabel("frame")
195
+ axs[2].set_ylabel("degrees")
196
+ fig.tight_layout()
197
+ fig.savefig(out_dir / "md_samples.png", dpi=130)
198
+ plt.close(fig)
199
+
200
+
201
+ if __name__ == "__main__":
202
+ main()
timeseris_example/attractors.py ADDED
@@ -0,0 +1,229 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """IDFF on chaotic 3-D attractors (paper, Appendix "3D Attractors").
2
+
3
+ Lorenz (sigma=10, rho=28, beta=8/3) and Rossler (a=b=0.2, c=5.7) trajectories are simulated with RK4.
4
+ An MLP with two hidden layers of width 128, two heads (denoiser, score) and embeddings of the flow time
5
+ t and the sequence position n is trained with the IDFF objective (Algorithm 3) and sampled
6
+ autoregressively (Algorithm 4).
7
+
8
+ Evaluation on held-out test trajectories; hyper-parameters are chosen per NFE budget on separate
9
+ validation trajectories (by default by rollout MMD, the long-run statistic the README animation shows):
10
+ * one-step-ahead MAE: sample x_n given the true x_{n-1};
11
+ * free rollout from the true first frame: MAE over the first 20 steps and the MMD between the
12
+ generated and true state distributions (long-run attractor statistics).
13
+
14
+ Example:
15
+
16
+ python timeseris_example/attractors.py --system lorenz
17
+ """
18
+ import argparse
19
+ import csv
20
+ import json
21
+ import sys
22
+ import time
23
+ from pathlib import Path
24
+
25
+ import matplotlib
26
+
27
+ matplotlib.use("Agg")
28
+ import matplotlib.pyplot as plt # noqa: E402
29
+ import numpy as np # noqa: E402
30
+ import torch # noqa: E402
31
+
32
+ HERE = Path(__file__).resolve().parent
33
+ sys.path.insert(0, str(HERE.parent))
34
+
35
+ from idff import JointHeadMLP, idff_loss, sample_next, sample_sequence, sequence_training_pairs # noqa: E402
36
+ from idff.datasets import attractor_trajectories # noqa: E402
37
+ from idff.metrics import mmd_rbf # noqa: E402
38
+
39
+
40
+ def repo_relative(args):
41
+ """Command-line arguments with paths made relative to the repository (for config.json)."""
42
+ out = dict(vars(args))
43
+ for key in ("out", "data"):
44
+ if key in out:
45
+ try:
46
+ out[key] = str(Path(out[key]).resolve().relative_to(HERE.parent))
47
+ except ValueError:
48
+ pass
49
+ return out
50
+
51
+
52
+ def parse_args():
53
+ p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
54
+ p.add_argument("--system", default="lorenz", choices=["lorenz", "rossler"])
55
+ p.add_argument("--length", type=int, default=2000, help="trajectory length (the paper uses 2000)")
56
+ p.add_argument("--n-train", type=int, default=32)
57
+ p.add_argument("--n-val", type=int, default=4)
58
+ p.add_argument("--n-test", type=int, default=8)
59
+ p.add_argument("--iters", type=int, default=20000)
60
+ p.add_argument("--batch", type=int, default=512)
61
+ p.add_argument("--lr", type=float, default=1e-3)
62
+ p.add_argument("--sigma0", type=float, default=0.05)
63
+ p.add_argument("--nfes", type=int, nargs="+", default=[2, 3, 5, 10])
64
+ p.add_argument("--gamma-rel-grid", type=float, nargs="+", default=[0.1, 0.3, 1.0, 3.0, 10.0],
65
+ help="gamma_bar = gamma_rel * sigma0^2 (see the MD example for why the base variance sets the scale)")
66
+ p.add_argument("--alpha-grid", type=float, nargs="+",
67
+ default=[-1000.0, -100.0, -10.0, -1.0, 1.0, 10.0, 100.0, 1000.0],
68
+ help="alpha_2 grid (0 is always added). It is wide because gamma_bar is small here; the sign "
69
+ "is free (the deviation bound depends on alpha_k^2)")
70
+ p.add_argument("--seeds", type=int, default=10, help="sampling seeds for the test rollout metrics")
71
+ p.add_argument("--select-by", default="rollout_mmd", choices=["rollout_mmd", "one_step_mae"],
72
+ help="validation criterion for gamma_bar and alpha_2")
73
+ p.add_argument("--select-seeds", type=int, default=3, help="sampling seeds for the validation criterion")
74
+ p.add_argument("--retrain", action="store_true")
75
+ p.add_argument("--out", default=str(HERE / "outputs"))
76
+ return p.parse_args()
77
+
78
+
79
+ def make_data(args):
80
+ total = args.n_train + args.n_val + args.n_test
81
+ raw = attractor_trajectories(args.system, total, args.length, seed=0)
82
+ train, val, test = np.split(raw, [args.n_train, args.n_train + args.n_val])
83
+ mean, std = train.reshape(-1, 3).mean(0), train.reshape(-1, 3).std(0)
84
+
85
+ def norm(a):
86
+ return torch.tensor((a - mean) / std, dtype=torch.float32)
87
+
88
+ return norm(train), norm(val), norm(test), mean, std
89
+
90
+
91
+ def train(args, data, out_dir):
92
+ model = JointHeadMLP(3, hidden=128, depth=2, sigma0=args.sigma0, base_std=args.sigma0,
93
+ num_positions=args.length, residual=True)
94
+ ckpt = out_dir / "idff_model.pt"
95
+ if ckpt.exists() and not args.retrain:
96
+ model.load_state_dict(torch.load(ckpt, map_location="cpu", weights_only=True))
97
+ print(f"loaded {ckpt}")
98
+ return model.eval()
99
+ torch.manual_seed(0)
100
+ opt = torch.optim.Adam(model.parameters(), lr=args.lr)
101
+ sched = torch.optim.lr_scheduler.CosineAnnealingLR(opt, args.iters)
102
+ start = time.time()
103
+ for it in range(1, args.iters + 1):
104
+ x0, x1, n = sequence_training_pairs(data, args.batch, args.sigma0)
105
+ loss, stats = idff_loss(model, x1, x0=x0, sigma0=args.sigma0, model_kwargs={"n": n})
106
+ opt.zero_grad()
107
+ loss.backward()
108
+ torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
109
+ opt.step()
110
+ sched.step()
111
+ if it % 4000 == 0:
112
+ print(f"iter {it:6d} loss {loss.item():.4f} denoiser {stats['denoiser']:.4f} "
113
+ f"score {stats['score']:.4f} ({time.time() - start:.0f}s)")
114
+ torch.save(model.state_dict(), ckpt)
115
+ return model.eval()
116
+
117
+
118
+ def one_step_mae(model, data, nfe, sigma0, std, cfg, seed=0, stride=1):
119
+ """Mean absolute one-step-ahead error in original units, over all trajectories and every
120
+ ``stride``-th position."""
121
+ gen = torch.Generator().manual_seed(seed)
122
+ errs = []
123
+ for n in range(1, data.shape[1], stride):
124
+ pred = sample_next(model, data[:, n - 1], n, nfe, sigma0, generator=gen, **cfg)
125
+ errs.append(((pred - data[:, n]).abs() * torch.tensor(std, dtype=torch.float32)).mean().item())
126
+ return float(np.mean(errs))
127
+
128
+
129
+ def rollout(model, data, nfe, sigma0, cfg, seed=0):
130
+ """Roll out every trajectory in one batch, each conditioned on its own true first frame."""
131
+ gen = torch.Generator().manual_seed(seed)
132
+ traj = sample_sequence(model, data.shape[1], data.shape[0], 3, nfe, sigma0, first_frame=data[:, 0],
133
+ generator=gen, **cfg)
134
+ return traj.transpose(0, 1) # (num_traj, length, 3)
135
+
136
+
137
+ def rollout_metrics(model, data, nfe, sigma0, std, cfg, seeds=3, seed0=0):
138
+ """20-step MAE (original units) and state-distribution MMD, averaged over sampling seeds.
139
+
140
+ Chaotic rollouts decorrelate quickly, so single-seed long-horizon numbers are noisy.
141
+ """
142
+ scale = torch.tensor(std, dtype=torch.float32)
143
+ shorts, mmds = [], []
144
+ for seed in range(seed0, seed0 + seeds):
145
+ gen = rollout(model, data, nfe, sigma0, cfg, seed=seed)
146
+ shorts.append(((gen[:, 1:21] - data[:, 1:21]).abs() * scale).mean().item())
147
+ idx = torch.randperm(gen.shape[0] * gen.shape[1], generator=torch.Generator().manual_seed(seed))[:4000]
148
+ mmds.append(mmd_rbf(gen.reshape(-1, 3)[idx], data.reshape(-1, 3)[idx]))
149
+ if seed == seed0:
150
+ first = gen
151
+ return float(np.mean(shorts)), float(np.mean(mmds)), float(np.std(mmds)), first
152
+
153
+
154
+ def select(model, val, args, std):
155
+ """Per NFE budget, on the validation trajectories: gamma_bar for K=1, then alpha_2 for K=2 with the
156
+ same gamma_bar (alpha_2 = 0, tried first, recovers K=1). The criterion is the rollout MMD (mean over
157
+ ``--select-seeds`` sampling seeds that differ from the test seeds) or the one-step-ahead MAE."""
158
+ grid = [r * args.sigma0 ** 2 for r in args.gamma_rel_grid]
159
+ alphas = [0.0] + [a for a in args.alpha_grid if a != 0.0]
160
+ sel = {}
161
+ for nfe in args.nfes:
162
+ if nfe <= 2: # gamma_t^1 = 0 at t = 0 and on the final step: every sampler coincides with CFM
163
+ sel[nfe] = {"gamma_bar": grid[0], "alpha_2": 0.0}
164
+ continue
165
+
166
+ def err(cfg, nfe=nfe):
167
+ if args.select_by == "one_step_mae":
168
+ return one_step_mae(model, val, nfe, args.sigma0, std, cfg, stride=4)
169
+ return rollout_metrics(model, val, nfe, args.sigma0, std, cfg, seeds=args.select_seeds, seed0=100)[1]
170
+
171
+ g = min(grid, key=lambda g: err(dict(K=1, gamma_bar=g)))
172
+ a2 = min(alphas, key=lambda a: err(dict(K=2, gamma_bar=g, alphas={2: a})))
173
+ sel[nfe] = {"gamma_bar": g, "alpha_2": a2}
174
+ return sel
175
+
176
+
177
+ def main():
178
+ args = parse_args()
179
+ out_dir = Path(args.out) / args.system
180
+ out_dir.mkdir(parents=True, exist_ok=True)
181
+ train_d, val_d, test_d, mean, std = make_data(args)
182
+ print(f"{args.system}: train {tuple(train_d.shape)}, val {tuple(val_d.shape)}, test {tuple(test_d.shape)}")
183
+ model = train(args, train_d, out_dir)
184
+ sel = select(model, val_d, args, std)
185
+ print("selected on validation trajectories:")
186
+ for nfe, s in sel.items():
187
+ print(f" NFE={nfe:3d} gamma_rel={s['gamma_bar'] / args.sigma0 ** 2:g} alpha_2={s['alpha_2']:g}")
188
+
189
+ def methods(nfe):
190
+ s = sel[nfe]
191
+ return {"CFM (det.)": dict(K=0), "IDFF K=1": dict(K=1, gamma_bar=s["gamma_bar"]),
192
+ "IDFF K=2": dict(K=2, gamma_bar=s["gamma_bar"], alphas={2: s["alpha_2"]})}
193
+
194
+ rows, rolls = [], {}
195
+ print(f"\n{'NFE':>4} {'method':12s} {'1-step MAE':>11s} {'20-step MAE':>12s} {'rollout MMD (mean +- std)':>26s}")
196
+ for nfe in args.nfes:
197
+ for name, cfg in methods(nfe).items():
198
+ mae1 = one_step_mae(model, test_d, nfe, args.sigma0, std, cfg)
199
+ short, mmd, mmd_sd, gen = rollout_metrics(model, test_d, nfe, args.sigma0, std, cfg, seeds=args.seeds)
200
+ rolls[(name, nfe)] = gen
201
+ rows.append({"method": name, "nfe": nfe, "one_step_mae": mae1, "rollout20_mae": short,
202
+ "rollout_mmd": mmd, "rollout_mmd_std": mmd_sd})
203
+ print(f"{nfe:>4} {name:12s} {mae1:11.4f} {short:12.4f} {mmd:9.5f} +- {mmd_sd:.5f}")
204
+
205
+ with open(out_dir / "results.csv", "w", newline="") as fh:
206
+ writer = csv.DictWriter(fh, fieldnames=list(rows[0]))
207
+ writer.writeheader()
208
+ writer.writerows(rows)
209
+ with open(out_dir / "config.json", "w") as fh:
210
+ json.dump({**repo_relative(args), "selected": {str(k): v for k, v in sel.items()}}, fh, indent=2)
211
+
212
+ nfe = max(args.nfes)
213
+ true = test_d[0].numpy() * std + mean
214
+ fig = plt.figure(figsize=(14, 4.5))
215
+ for j, name in enumerate(["CFM (det.)", "IDFF K=1", "IDFF K=2"]):
216
+ ax = fig.add_subplot(1, 3, j + 1, projection="3d")
217
+ g = rolls[(name, nfe)][0].numpy() * std + mean
218
+ ax.plot(*true.T, c="k", lw=0.6, alpha=0.6, label="true")
219
+ ax.plot(*g.T, c="tab:red", lw=0.6, alpha=0.8, label="generated")
220
+ ax.set_title(f"{args.system}: {name}, NFE={nfe}")
221
+ ax.legend(fontsize=7)
222
+ fig.tight_layout()
223
+ fig.savefig(out_dir / "rollout.png", dpi=130)
224
+ plt.close(fig)
225
+ print(f"\nwrote results to {out_dir}")
226
+
227
+
228
+ if __name__ == "__main__":
229
+ main()
timeseris_example/data/polyALA_angles.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9cd407fc8218f4344e605112ea7e8f5a3d3ccd4e57b8ab7c18db4b5a67ba1ef0
3
+ size 34215
timeseris_example/outputs/lorenz/config.json ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "system": "lorenz",
3
+ "length": 2000,
4
+ "n_train": 32,
5
+ "n_val": 4,
6
+ "n_test": 8,
7
+ "iters": 20000,
8
+ "batch": 512,
9
+ "lr": 0.001,
10
+ "sigma0": 0.05,
11
+ "nfes": [
12
+ 2,
13
+ 3,
14
+ 5,
15
+ 10
16
+ ],
17
+ "gamma_rel_grid": [
18
+ 0.1,
19
+ 0.3,
20
+ 1.0,
21
+ 3.0,
22
+ 10.0
23
+ ],
24
+ "alpha_grid": [
25
+ -1000.0,
26
+ -100.0,
27
+ -10.0,
28
+ -1.0,
29
+ 1.0,
30
+ 10.0,
31
+ 100.0,
32
+ 1000.0
33
+ ],
34
+ "seeds": 10,
35
+ "select_by": "rollout_mmd",
36
+ "select_seeds": 3,
37
+ "retrain": false,
38
+ "out": "timeseris_example/outputs",
39
+ "selected": {
40
+ "2": {
41
+ "gamma_bar": 0.00025000000000000006,
42
+ "alpha_2": 0.0
43
+ },
44
+ "3": {
45
+ "gamma_bar": 0.0007500000000000001,
46
+ "alpha_2": 0.0
47
+ },
48
+ "5": {
49
+ "gamma_bar": 0.00025000000000000006,
50
+ "alpha_2": -10.0
51
+ },
52
+ "10": {
53
+ "gamma_bar": 0.0007500000000000001,
54
+ "alpha_2": 0.0
55
+ }
56
+ }
57
+ }
timeseris_example/outputs/lorenz/idff_model.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1a34994890468bfc838d84ffb1d37f7e37b1001914e994f3805526e554a4a3ab
3
+ size 624757
timeseris_example/outputs/lorenz/results.csv ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ method,nfe,one_step_mae,rollout20_mae,rollout_mmd,rollout_mmd_std
2
+ CFM (det.),2,0.5046711948706306,2.970464992523193,0.013119068704618774,0.009917949236038632
3
+ IDFF K=1,2,0.5046711948706306,2.970464992523193,0.013119068704618774,0.009917949236038632
4
+ IDFF K=2,2,0.5046711948706306,2.970464992523193,0.013119068704618774,0.009917949236038632
5
+ CFM (det.),3,0.39490651294939394,2.1065974593162538,0.005244532301044491,0.00389900752757173
6
+ IDFF K=1,3,0.4134999921674905,2.163750243186951,0.005251220724828009,0.003239456811503962
7
+ IDFF K=2,3,0.4134999921674905,2.163750243186951,0.005251220724828009,0.003239456811503962
8
+ CFM (det.),5,0.3209775646010776,1.3495140194892883,0.0037345989312153214,0.00353533620336635
9
+ IDFF K=1,5,0.3336806403451588,1.472440481185913,0.00202500827088391,0.0007522051552088028
10
+ IDFF K=2,5,0.3329388130420801,1.484570050239563,0.002992447405168791,0.00305111604551931
11
+ CFM (det.),10,0.3021115019671496,1.169181227684021,0.005124361358398932,0.004687339883902047
12
+ IDFF K=1,10,0.3502505819922152,1.3118240892887116,0.0037427483634526414,0.005020263076036552
13
+ IDFF K=2,10,0.3502505819922152,1.3118240892887116,0.0037427483634526414,0.005020263076036552
timeseris_example/outputs/lorenz/rollout.png ADDED

Git LFS Details

  • SHA256: a359364c41ce556902a39370e49c433f244733df2f694850e2af8d5d3bdce638
  • Pointer size: 131 Bytes
  • Size of remote file: 547 kB
timeseris_example/outputs/polyALA/config.json ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "data": "timeseris_example/data/polyALA_angles.npz",
3
+ "iters": 20000,
4
+ "batch": 256,
5
+ "lr": 0.001,
6
+ "sigma0": 0.1,
7
+ "nfes": [
8
+ 3,
9
+ 5,
10
+ 10
11
+ ],
12
+ "gamma_rel": 1.0,
13
+ "alpha2": 0.05,
14
+ "num_traj": 5,
15
+ "seeds": 3,
16
+ "sweep": true,
17
+ "retrain": false,
18
+ "out": "timeseris_example/outputs/polyALA"
19
+ }
timeseris_example/outputs/polyALA/evaluation_results.csv ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ method,nfe,gamma_rel,alpha2,MAE,RMSE,CC,MAE_seed_std,RMSE_seed_std,CC_seed_std
2
+ CFM (det.),3,0.0,,2.9922401767075617,4.155066000812517,0.9978891292225894,0.31496997083863243,0.5177781690175595,0.00018535222011378807
3
+ IDFF K=1,3,1.0,,3.9276713578107185,5.350654676136595,0.9966403078454028,0.6455303157859048,0.9737780357648421,0.0005396718572639132
4
+ IDFF K=2,3,1.0,0.05,3.9273660952308442,5.350164205578271,0.9966404569051882,0.6452164712290651,0.973095082673879,0.0005391411282792847
5
+ CFM (det.),5,0.0,,2.6118116313896222,3.649404712513005,0.9983524237576468,0.1636659245691367,0.2965550594561423,7.984906844305301e-05
6
+ IDFF K=1,5,1.0,,3.916477027762792,5.464339336591634,0.9965412388478644,0.43580179825493714,0.733190721641211,0.0005028230577794873
7
+ IDFF K=2,5,1.0,0.05,3.916338106692932,5.464288320381553,0.9965408149190714,0.43543860528082085,0.7327343574291173,0.0005029380871925646
8
+ CFM (det.),10,0.0,,2.339762608007314,3.280161720437835,0.9987191174913775,0.04284794495472016,0.06781351612737008,2.7027454805517246e-05
9
+ IDFF K=1,10,1.0,,3.6311263349798804,5.1716461633838415,0.996922951704656,0.5250965149041412,0.9247040605568756,0.0006962228989955795
10
+ IDFF K=2,10,1.0,0.05,3.6311846407688293,5.171681859327962,0.996922551846415,0.5248725401122517,0.9243230661841134,0.0006963234461285235
11
+ IDFF K=1 (sweep),10,0.1,,2.6879184781623082,3.8335534845981853,0.9983853872648671,0.3821271525978309,0.6493292469691564,0.0003206207323959128
12
+ IDFF K=2 (sweep),10,0.1,-5.0,2.6884027237714947,3.8359898994286215,0.998386770142095,0.38459391515038666,0.6539447738825922,0.0003224262094807928
13
+ IDFF K=2 (sweep),10,0.1,-1.0,2.687932440823337,3.833952124165439,0.99838575359131,0.3826134243353551,0.6502616790433675,0.00032098612648573215
14
+ IDFF K=2 (sweep),10,0.1,0.05,2.6879182716266263,3.8335336862133325,0.9983853679340845,0.3821030425361508,0.6492825490464281,0.0003206018078964179
15
+ IDFF K=2 (sweep),10,0.1,1.0,2.6879476584214306,3.8331991605654543,0.99838497504257,0.38163922107171344,0.6483896498941699,0.00032025142568402733
16
+ IDFF K=2 (sweep),10,0.1,5.0,2.6885058781509734,3.832244238330153,0.9983828566493026,0.3796619574653882,0.644578159673287,0.0003187500960379704
17
+ IDFF K=1 (sweep),10,0.3,,2.9272957929000927,4.164683317686751,0.9980622673809153,0.4446130009360982,0.7605947322762708,0.00042017238987658313
18
+ IDFF K=2 (sweep),10,0.3,-5.0,2.9292651664544436,4.171681781571837,0.9980654860779906,0.45265134333748663,0.7742250118457833,0.0004228984493766659
19
+ IDFF K=2 (sweep),10,0.3,-1.0,2.9271187864353188,4.165485005700865,0.9980635699760465,0.4462324290966084,0.7633895429805821,0.00042074719304405683
20
+ IDFF K=2 (sweep),10,0.3,0.05,2.9273131976428375,4.164652632290722,0.9980621924947886,0.44453194734410334,0.7604525331810816,0.00042014189569559014
21
+ IDFF K=2 (sweep),10,0.3,1.0,2.927786587103954,4.164203009381241,0.9980606103877235,0.44301419541340586,0.7577638141729802,0.0004195805087601121
22
+ IDFF K=2 (sweep),10,0.3,5.0,2.9329938499053387,4.16567109425354,0.998050205976469,0.43648971456311236,0.7460964465238891,0.00041705084834158093
23
+ IDFF K=1 (sweep),10,1.0,,3.6311263349798804,5.1716461633838415,0.996922951704656,0.5250965149041412,0.9247040605568756,0.0006962228989955795
24
+ IDFF K=2 (sweep),10,1.0,-5.0,3.6475163964434754,5.189859391725872,0.9969319765551895,0.5484801679272854,0.9601051345911288,0.0006856372298810682
25
+ IDFF K=2 (sweep),10,1.0,-1.0,3.6309627593122418,5.171906215508305,0.996929564757315,0.5296725346581149,0.9322456272134577,0.0006942032898193387
26
+ IDFF K=2 (sweep),10,1.0,0.05,3.6311846407688293,5.171681859327962,0.996922551846415,0.5248725401122517,0.9243230661841134,0.0006963234461285235
27
+ IDFF K=2 (sweep),10,1.0,1.0,3.6332281701053835,5.173238130299825,0.9969136867025843,0.5205305462134877,0.9169991451387031,0.0006981871877827594
28
+ IDFF K=2 (sweep),10,1.0,5.0,3.661241178939767,5.200242248584531,0.9968465153541702,0.5030676931283106,0.8852448227352774,0.0007052845638891795
29
+ IDFF K=1 (sweep),10,3.0,,5.281976525195554,7.602697547750491,0.9932302331179151,0.6274062514275708,1.1138994229536192,0.0013595718961097567
30
+ IDFF K=2 (sweep),10,3.0,-5.0,5.887492088417011,8.08663030792043,0.9926436326897995,0.7283366266533818,1.17745201730117,0.0011862905239823692
31
+ IDFF K=2 (sweep),10,3.0,-1.0,5.327354834626896,7.627806938563121,0.9932253363591407,0.6430596677695429,1.129077512307308,0.001331932647267951
32
+ IDFF K=2 (sweep),10,3.0,0.05,5.280299484064513,7.601936447492572,0.9932296475367406,0.6266846574223109,1.1131337817765459,0.001360897830327774
33
+ IDFF K=2 (sweep),10,3.0,1.0,5.257205580150825,7.594546093369105,0.9932062855521142,0.6137237561819945,1.0985993971520605,0.001385080440871407
34
+ IDFF K=2 (sweep),10,3.0,5.0,5.278074274651343,7.661614799375243,0.9929231456165505,0.5739513342466118,1.0433944542483913,0.0014704773371371927
35
+ IDFF K=1 (sweep),10,10.0,,67.41158247504073,79.9155399717963,0.31689136135475077,3.1532989951075443,3.567632910122242,0.10015263875163914
36
+ IDFF K=2 (sweep),10,10.0,-5.0,75.85843675667384,89.06746227275288,0.1577573385496486,2.9828389492612253,3.1356857692180222,0.06585600406958056
37
+ IDFF K=2 (sweep),10,10.0,-1.0,75.50231033726324,88.39049203137763,0.09926679637740615,0.3762112058837424,0.6004679659482175,0.07231126134139261
38
+ IDFF K=2 (sweep),10,10.0,0.05,71.4424623697763,84.10156668319955,0.20103752590061297,5.214554799984109,5.846294691060069,0.14995549668143493
39
+ IDFF K=2 (sweep),10,10.0,1.0,67.27718624342712,79.64379335385955,0.30868282262257635,4.158869029541596,4.998679193014867,0.14813485954777644
40
+ IDFF K=2 (sweep),10,10.0,5.0,54.33118738070104,67.24698177986338,0.4194601369724329,10.762887206772902,11.138546685311526,0.19349604666049583
timeseris_example/outputs/polyALA/idff_md.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9f3fbeb6f773815fa31c9fa0895e9e4b24f1a01600f165582578e3b8bd20adf6
3
+ size 799167
timeseris_example/outputs/polyALA/md_samples.png ADDED

Git LFS Details

  • SHA256: 36857c4c4cf94cebd7fbc495afa990ab453251e0a45fd2d74836c63f23367fe1
  • Pointer size: 131 Bytes
  • Size of remote file: 231 kB
torchcfm/__init__.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ from .conditional_flow_matching import *
2
+ from .version import __version__
torchcfm/conditional_flow_matching.py ADDED
@@ -0,0 +1,606 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Implements Conditional Flow Matcher Losses."""
2
+
3
+ import math
4
+ import warnings
5
+ from typing import Union
6
+
7
+ import torch
8
+
9
+ from .optimal_transport import OTPlanSampler
10
+
11
+
12
+ def pad_t_like_x(t, x):
13
+ """Function to reshape the time vector t by the number of dimensions of x.
14
+
15
+ Parameters
16
+ ----------
17
+ x : Tensor, shape (bs, *dim)
18
+ represents the source minibatch
19
+ t : FloatTensor, shape (bs)
20
+
21
+ Returns
22
+ -------
23
+ t : Tensor, shape (bs, number of x dimensions)
24
+
25
+ Example
26
+ -------
27
+ x: Tensor (bs, C, W, H)
28
+ t: Vector (bs)
29
+ pad_t_like_x(t, x): Tensor (bs, 1, 1, 1)
30
+ """
31
+ if isinstance(t, (float, int)):
32
+ return t
33
+ return t.reshape(-1, *([1] * (x.dim() - 1)))
34
+
35
+
36
+ class ConditionalFlowMatcher:
37
+ """Base class for conditional flow matching methods. This class implements the independent
38
+ conditional flow matching methods from [1] and serves as a parent class for all other flow
39
+ matching methods.
40
+
41
+ It implements:
42
+ - Drawing data from gaussian probability path N(t * x1 + (1 - t) * x0, sigma) function
43
+ - conditional flow matching ut(x1|x0) = x1 - x0
44
+ - score function $\nabla log p_t(x|x0, x1)$
45
+ """
46
+
47
+ def __init__(self, sigma: Union[float, int] = 0.0):
48
+ r"""Initialize the ConditionalFlowMatcher class. It requires the hyper-parameter $\sigma$.
49
+
50
+ Parameters
51
+ ----------
52
+ sigma : Union[float, int]
53
+ """
54
+ self.sigma = sigma
55
+
56
+ def compute_mu_t(self, x0, x1, t):
57
+ """
58
+ Compute the mean of the probability path N(t * x1 + (1 - t) * x0, sigma), see (Eq.14) [1].
59
+
60
+ Parameters
61
+ ----------
62
+ x0 : Tensor, shape (bs, *dim)
63
+ represents the source minibatch
64
+ x1 : Tensor, shape (bs, *dim)
65
+ represents the target minibatch
66
+ t : FloatTensor, shape (bs)
67
+
68
+ Returns
69
+ -------
70
+ mean mu_t: t * x1 + (1 - t) * x0
71
+
72
+ References
73
+ ----------
74
+ [1] Improving and Generalizing Flow-Based Generative Models with minibatch optimal transport, Preprint, Tong et al.
75
+ """
76
+ t = pad_t_like_x(t, x0)
77
+ return t * x1 + (1 - t) * x0
78
+
79
+ def compute_sigma_t(self, t):
80
+ """
81
+ Compute the standard deviation of the probability path N(t * x1 + (1 - t) * x0, sigma), see (Eq.14) [1].
82
+
83
+ Parameters
84
+ ----------
85
+ t : FloatTensor, shape (bs)
86
+
87
+ Returns
88
+ -------
89
+ standard deviation sigma
90
+
91
+ References
92
+ ----------
93
+ [1] Improving and Generalizing Flow-Based Generative Models with minibatch optimal transport, Preprint, Tong et al.
94
+ """
95
+ del t
96
+ return self.sigma
97
+
98
+ def sample_xt(self, x0, x1, t, epsilon):
99
+ """
100
+ Draw a sample from the probability path N(t * x1 + (1 - t) * x0, sigma), see (Eq.14) [1].
101
+
102
+ Parameters
103
+ ----------
104
+ x0 : Tensor, shape (bs, *dim)
105
+ represents the source minibatch
106
+ x1 : Tensor, shape (bs, *dim)
107
+ represents the target minibatch
108
+ t : FloatTensor, shape (bs)
109
+ epsilon : Tensor, shape (bs, *dim)
110
+ noise sample from N(0, 1)
111
+
112
+ Returns
113
+ -------
114
+ xt : Tensor, shape (bs, *dim)
115
+
116
+ References
117
+ ----------
118
+ [1] Improving and Generalizing Flow-Based Generative Models with minibatch optimal transport, Preprint, Tong et al.
119
+ """
120
+ mu_t = self.compute_mu_t(x0, x1, t)
121
+ sigma_t = self.compute_sigma_t(t)
122
+ sigma_t = pad_t_like_x(sigma_t, x0)
123
+ return mu_t + sigma_t * epsilon
124
+
125
+ def compute_conditional_flow(self, x0, x1, t, xt):
126
+ """
127
+ Compute the conditional vector field ut(x1|x0) = x1 - x0, see Eq.(15) [1].
128
+
129
+ Parameters
130
+ ----------
131
+ x0 : Tensor, shape (bs, *dim)
132
+ represents the source minibatch
133
+ x1 : Tensor, shape (bs, *dim)
134
+ represents the target minibatch
135
+ t : FloatTensor, shape (bs)
136
+ xt : Tensor, shape (bs, *dim)
137
+ represents the samples drawn from probability path pt
138
+
139
+ Returns
140
+ -------
141
+ ut : conditional vector field ut(x1|x0) = x1 - x0
142
+
143
+ References
144
+ ----------
145
+ [1] Improving and Generalizing Flow-Based Generative Models with minibatch optimal transport, Preprint, Tong et al.
146
+ """
147
+ del t, xt
148
+ return x1 - x0
149
+
150
+ def sample_noise_like(self, x):
151
+ return torch.randn_like(x)
152
+
153
+ def sample_location_and_conditional_flow(self, x0, x1, t=None, return_noise=False):
154
+ """
155
+ Compute the sample xt (drawn from N(t * x1 + (1 - t) * x0, sigma))
156
+ and the conditional vector field ut(x1|x0) = x1 - x0, see Eq.(15) [1].
157
+
158
+ Parameters
159
+ ----------
160
+ x0 : Tensor, shape (bs, *dim)
161
+ represents the source minibatch
162
+ x1 : Tensor, shape (bs, *dim)
163
+ represents the target minibatch
164
+ (optionally) t : Tensor, shape (bs)
165
+ represents the time levels
166
+ if None, drawn from uniform [0,1]
167
+ return_noise : bool
168
+ return the noise sample epsilon
169
+
170
+
171
+ Returns
172
+ -------
173
+ t : FloatTensor, shape (bs)
174
+ xt : Tensor, shape (bs, *dim)
175
+ represents the samples drawn from probability path pt
176
+ ut : conditional vector field ut(x1|x0) = x1 - x0
177
+ (optionally) eps: Tensor, shape (bs, *dim) such that xt = mu_t + sigma_t * epsilon
178
+
179
+ References
180
+ ----------
181
+ [1] Improving and Generalizing Flow-Based Generative Models with minibatch optimal transport, Preprint, Tong et al.
182
+ """
183
+ if t is None:
184
+ t = torch.rand(x0.shape[0]).type_as(x0)
185
+ assert len(t) == x0.shape[0], "t has to have batch size dimension"
186
+
187
+ eps = self.sample_noise_like(x0)
188
+ xt = self.sample_xt(x0, x1, t, eps)
189
+ ut = self.compute_conditional_flow(x0, x1, t, xt)
190
+ if return_noise:
191
+ return t, xt, ut, eps
192
+ else:
193
+ return t, xt, ut
194
+
195
+ def compute_lambda(self, t):
196
+ """Compute the lambda function, see Eq.(23) [3].
197
+
198
+ Parameters
199
+ ----------
200
+ t : FloatTensor, shape (bs)
201
+
202
+ Returns
203
+ -------
204
+ lambda : score weighting function
205
+
206
+ References
207
+ ----------
208
+ [4] Simulation-free Schrodinger bridges via score and flow matching, Preprint, Tong et al.
209
+ """
210
+ sigma_t = self.compute_sigma_t(t)
211
+ return 2 * sigma_t / (self.sigma**2 + 1e-8)
212
+
213
+
214
+ class ExactOptimalTransportConditionalFlowMatcher(ConditionalFlowMatcher):
215
+ """Child class for optimal transport conditional flow matching method. This class implements
216
+ the OT-CFM methods from [1] and inherits the ConditionalFlowMatcher parent class.
217
+
218
+ It overrides the sample_location_and_conditional_flow.
219
+ """
220
+
221
+ def __init__(self, sigma: Union[float, int] = 0.0):
222
+ r"""Initialize the ConditionalFlowMatcher class. It requires the hyper-parameter $\sigma$.
223
+
224
+ Parameters
225
+ ----------
226
+ sigma : Union[float, int]
227
+ ot_sampler: exact OT method to draw couplings (x0, x1) (see Eq.(17) [1]).
228
+ """
229
+ super().__init__(sigma)
230
+ self.ot_sampler = OTPlanSampler(method="exact")
231
+ def compute_sigma_t(self, t):
232
+
233
+ return self.sigma * torch.sqrt(t* (1 - t))
234
+
235
+ def sample_location_and_conditional_flow(self, x0, x1, t=None, return_noise=False):
236
+ r"""
237
+ Compute the sample xt (drawn from N(t * x1 + (1 - t) * x0, sigma))
238
+ and the conditional vector field ut(x1|x0) = x1 - x0, see Eq.(15) [1]
239
+ with respect to the minibatch OT plan $\Pi$.
240
+
241
+ Parameters
242
+ ----------
243
+ x0 : Tensor, shape (bs, *dim)
244
+ represents the source minibatch
245
+ x1 : Tensor, shape (bs, *dim)
246
+ represents the target minibatch
247
+ (optionally) t : Tensor, shape (bs)
248
+ represents the time levels
249
+ if None, drawn from uniform [0,1]
250
+ return_noise : bool
251
+ return the noise sample epsilon
252
+
253
+ Returns
254
+ -------
255
+ t : FloatTensor, shape (bs)
256
+ xt : Tensor, shape (bs, *dim)
257
+ represents the samples drawn from probability path pt
258
+ ut : conditional vector field ut(x1|x0) = x1 - x0
259
+ (optionally) epsilon : Tensor, shape (bs, *dim) such that xt = mu_t + sigma_t * epsilon
260
+
261
+ References
262
+ ----------
263
+ [1] Improving and Generalizing Flow-Based Generative Models with minibatch optimal transport, Preprint, Tong et al.
264
+ """
265
+ x0, x1 = self.ot_sampler.sample_plan(x0, x1)
266
+ return super().sample_location_and_conditional_flow(x0, x1, t, return_noise)
267
+
268
+ def guided_sample_location_and_conditional_flow(
269
+ self, x0, x1, y0=None, y1=None, t=None, return_noise=False
270
+ ):
271
+ r"""
272
+ Compute the sample xt (drawn from N(t * x1 + (1 - t) * x0, sigma))
273
+ and the conditional vector field ut(x1|x0) = x1 - x0, see Eq.(15) [1]
274
+ with respect to the minibatch OT plan $\Pi$.
275
+
276
+ Parameters
277
+ ----------
278
+ x0 : Tensor, shape (bs, *dim)
279
+ represents the source minibatch
280
+ x1 : Tensor, shape (bs, *dim)
281
+ represents the target minibatch
282
+ y0 : Tensor, shape (bs) (default: None)
283
+ represents the source label minibatch
284
+ y1 : Tensor, shape (bs) (default: None)
285
+ represents the target label minibatch
286
+ (optionally) t : Tensor, shape (bs)
287
+ represents the time levels
288
+ if None, drawn from uniform [0,1]
289
+ return_noise : bool
290
+ return the noise sample epsilon
291
+
292
+ Returns
293
+ -------
294
+ t : FloatTensor, shape (bs)
295
+ xt : Tensor, shape (bs, *dim)
296
+ represents the samples drawn from probability path pt
297
+ ut : conditional vector field ut(x1|x0) = x1 - x0
298
+ (optionally) epsilon : Tensor, shape (bs, *dim) such that xt = mu_t + sigma_t * epsilon
299
+
300
+ References
301
+ ----------
302
+ [1] Improving and Generalizing Flow-Based Generative Models with minibatch optimal transport, Preprint, Tong et al.
303
+ """
304
+ x0, x1, y0, y1 = self.ot_sampler.sample_plan_with_labels(x0, x1, y0, y1)
305
+ if return_noise:
306
+ t, xt, ut, eps = super().sample_location_and_conditional_flow(x0, x1, t, return_noise)
307
+ return t, xt, ut, y0, y1, eps
308
+ else:
309
+ t, xt, ut = super().sample_location_and_conditional_flow(x0, x1, t, return_noise)
310
+ return t, xt, ut, y0, y1
311
+
312
+
313
+ class TargetConditionalFlowMatcher(ConditionalFlowMatcher):
314
+ """Lipman et al. 2023 style target OT conditional flow matching. This class inherits the
315
+ ConditionalFlowMatcher and override the compute_mu_t, compute_sigma_t and
316
+ compute_conditional_flow functions in order to compute [2]'s flow matching.
317
+
318
+ [2] Flow Matching for Generative Modelling, ICLR, Lipman et al.
319
+ """
320
+
321
+ def compute_mu_t(self, x0, x1, t):
322
+ """Compute the mean of the probability path tx1, see (Eq.20) [2].
323
+
324
+ Parameters
325
+ ----------
326
+ x0 : Tensor, shape (bs, *dim)
327
+ represents the source minibatch
328
+ x1 : Tensor, shape (bs, *dim)
329
+ represents the target minibatch
330
+ t : FloatTensor, shape (bs)
331
+
332
+ Returns
333
+ -------
334
+ mean mu_t: t * x1
335
+
336
+ References
337
+ ----------
338
+ [2] Flow Matching for Generative Modelling, ICLR, Lipman et al.
339
+ """
340
+ del x0
341
+ t = pad_t_like_x(t, x1)
342
+ return t * x1
343
+
344
+ def compute_sigma_t(self, t):
345
+ """
346
+ Compute the standard deviation of the probability path N(t x1, 1 - (1 - sigma) t), see (Eq.20) [2].
347
+
348
+ Parameters
349
+ ----------
350
+ t : FloatTensor, shape (bs)
351
+
352
+ Returns
353
+ -------
354
+ standard deviation sigma 1 - (1 - sigma) t
355
+
356
+ References
357
+ ----------
358
+ [2] Flow Matching for Generative Modelling, ICLR, Lipman et al.
359
+ """
360
+ return 1 - (1 - self.sigma) * t
361
+
362
+ def compute_conditional_flow(self, x0, x1, t, xt):
363
+ """
364
+ Compute the conditional vector field ut(x1|x0) = (x1 - (1 - sigma) t)/(1 - (1 - sigma)t), see Eq.(21) [2].
365
+
366
+ Parameters
367
+ ----------
368
+ x0 : Tensor, shape (bs, *dim)
369
+ represents the source minibatch
370
+ x1 : Tensor, shape (bs, *dim)
371
+ represents the target minibatch
372
+ t : FloatTensor, shape (bs)
373
+ xt : Tensor, shape (bs, *dim)
374
+ represents the samples drawn from probability path pt
375
+
376
+ Returns
377
+ -------
378
+ ut : conditional vector field ut(x1|x0) = (x1 - (1 - sigma) t)/(1 - (1 - sigma)t)
379
+
380
+ References
381
+ ----------
382
+ [1] Flow Matching for Generative Modelling, ICLR, Lipman et al.
383
+ """
384
+ del x0
385
+ t = pad_t_like_x(t, x1)
386
+ return (x1 - (1 - self.sigma) * xt) / (1 - (1 - self.sigma) * t)
387
+
388
+
389
+ class SchrodingerBridgeConditionalFlowMatcher(ConditionalFlowMatcher):
390
+ """Child class for Schrödinger bridge conditional flow matching method. This class implements
391
+ the SB-CFM methods from [1] and inherits the ConditionalFlowMatcher parent class.
392
+
393
+ It overrides the compute_sigma_t, compute_conditional_flow and
394
+ sample_location_and_conditional_flow functions.
395
+ """
396
+
397
+ def __init__(self, sigma: Union[float, int] = 1.0, ot_method="exact"):
398
+ r"""Initialize the SchrodingerBridgeConditionalFlowMatcher class. It requires the hyper-
399
+ parameter $\sigma$ and the entropic OT map.
400
+
401
+ Parameters
402
+ ----------
403
+ sigma : Union[float, int]
404
+ ot_sampler: exact OT method to draw couplings (x0, x1) (see Eq.(17) [1]).
405
+ we use exact as the default as we found this to perform better
406
+ (more accurate and faster) in practice for reasonable batch sizes.
407
+ We note that as batchsize --> infinity the correct choice is the
408
+ sinkhorn method theoretically.
409
+ """
410
+ if sigma <= 0:
411
+ raise ValueError(f"Sigma must be strictly positive, got {sigma}.")
412
+ elif sigma < 1e-3:
413
+ warnings.warn("Small sigma values may lead to numerical instability.")
414
+ super().__init__(sigma)
415
+ self.ot_method = ot_method
416
+ self.ot_sampler = OTPlanSampler(method=ot_method, reg=2 * self.sigma**2)
417
+
418
+ def compute_sigma_t(self, t):
419
+ """
420
+ Compute the standard deviation of the probability path N(t * x1 + (1 - t) * x0, sqrt(t * (1 - t))*sigma^2),
421
+ see (Eq.20) [1].
422
+
423
+ Parameters
424
+ ----------
425
+ t : FloatTensor, shape (bs)
426
+
427
+ Returns
428
+ -------
429
+ standard deviation sigma
430
+
431
+ References
432
+ ----------
433
+ [1] Improving and Generalizing Flow-Based Generative Models with minibatch optimal transport, Preprint, Tong et al.
434
+ """
435
+ return self.sigma * torch.sqrt(t * (1 - t))
436
+
437
+ def compute_conditional_flow(self, x0, x1, t, xt):
438
+ """Compute the conditional vector field.
439
+
440
+ ut(x1|x0) = (1 - 2 * t) / (2 * t * (1 - t)) * (xt - mu_t) + x1 - x0,
441
+ see Eq.(21) [1].
442
+
443
+ Parameters
444
+ ----------
445
+ x0 : Tensor, shape (bs, *dim)
446
+ represents the source minibatch
447
+ x1 : Tensor, shape (bs, *dim)
448
+ represents the target minibatch
449
+ t : FloatTensor, shape (bs)
450
+ xt : Tensor, shape (bs, *dim)
451
+ represents the samples drawn from probability path pt
452
+
453
+ Returns
454
+ -------
455
+ ut : conditional vector field
456
+ ut(x1|x0) = (1 - 2 * t) / (2 * t * (1 - t)) * (xt - mu_t) + x1 - x0
457
+
458
+ References
459
+ ----------
460
+ [1] Improving and Generalizing Flow-Based Generative Models
461
+ with minibatch optimal transport, Preprint, Tong et al.
462
+ """
463
+ t = pad_t_like_x(t, x0)
464
+ mu_t = self.compute_mu_t(x0, x1, t)
465
+ sigma_t_prime_over_sigma_t = (1 - 2 * t) / (2 * t * (1 - t) + 1e-8)
466
+ ut = sigma_t_prime_over_sigma_t * (xt - mu_t) + x1 - x0
467
+ return ut
468
+
469
+ def sample_location_and_conditional_flow(self, x0, x1, t=None, return_noise=False):
470
+ """
471
+ Compute the sample xt (drawn from N(t * x1 + (1 - t) * x0, sqrt(t * (1 - t))*sigma^2 ))
472
+ and the conditional vector field ut(x1|x0) = (1 - 2 * t) / (2 * t * (1 - t)) * (xt - mu_t) + x1 - x0,
473
+ (see Eq.(15) [1]) with respect to the minibatch entropic OT plan.
474
+
475
+ Parameters
476
+ ----------
477
+ x0 : Tensor, shape (bs, *dim)
478
+ represents the source minibatch
479
+ x1 : Tensor, shape (bs, *dim)
480
+ represents the target minibatch
481
+ (optionally) t : Tensor, shape (bs)
482
+ represents the time levels
483
+ if None, drawn from uniform [0,1]
484
+ return_noise: bool
485
+ return the noise sample epsilon
486
+
487
+
488
+ Returns
489
+ -------
490
+ t : FloatTensor, shape (bs)
491
+ xt : Tensor, shape (bs, *dim)
492
+ represents the samples drawn from probability path pt
493
+ ut : conditional vector field ut(x1|x0) = x1 - x0
494
+ (optionally) epsilon : Tensor, shape (bs, *dim) such that xt = mu_t + sigma_t * epsilon
495
+
496
+ References
497
+ ----------
498
+ [1] Improving and Generalizing Flow-Based Generative Models with minibatch optimal transport, Preprint, Tong et al.
499
+ """
500
+ x0, x1 = self.ot_sampler.sample_plan(x0, x1)
501
+ return super().sample_location_and_conditional_flow(x0, x1, t, return_noise)
502
+
503
+ def guided_sample_location_and_conditional_flow(
504
+ self, x0, x1, y0=None, y1=None, t=None, return_noise=False
505
+ ):
506
+ r"""
507
+ Compute the sample xt (drawn from N(t * x1 + (1 - t) * x0, sigma))
508
+ and the conditional vector field ut(x1|x0) = x1 - x0, see Eq.(15) [1]
509
+ with respect to the minibatch entropic OT plan $\Pi$.
510
+
511
+ Parameters
512
+ ----------
513
+ x0 : Tensor, shape (bs, *dim)
514
+ represents the source minibatch
515
+ x1 : Tensor, shape (bs, *dim)
516
+ represents the target minibatch
517
+ y0 : Tensor, shape (bs) (default: None)
518
+ represents the source label minibatch
519
+ y1 : Tensor, shape (bs) (default: None)
520
+ represents the target label minibatch
521
+ (optionally) t : Tensor, shape (bs)
522
+ represents the time levels
523
+ if None, drawn from uniform [0,1]
524
+ return_noise : bool
525
+ return the noise sample epsilon
526
+
527
+ Returns
528
+ -------
529
+ t : FloatTensor, shape (bs)
530
+ xt : Tensor, shape (bs, *dim)
531
+ represents the samples drawn from probability path pt
532
+ ut : conditional vector field ut(x1|x0) = x1 - x0
533
+ (optionally) epsilon : Tensor, shape (bs, *dim) such that xt = mu_t + sigma_t * epsilon
534
+
535
+ References
536
+ ----------
537
+ [1] Improving and Generalizing Flow-Based Generative Models with minibatch optimal transport, Preprint, Tong et al.
538
+ """
539
+ x0, x1, y0, y1 = self.ot_sampler.sample_plan_with_labels(x0, x1, y0, y1)
540
+ if return_noise:
541
+ t, xt, ut, eps = super().sample_location_and_conditional_flow(x0, x1, t, return_noise)
542
+ return t, xt, ut, y0, y1, eps
543
+ else:
544
+ t, xt, ut = super().sample_location_and_conditional_flow(x0, x1, t, return_noise)
545
+ return t, xt, ut, y0, y1
546
+
547
+
548
+ class VariancePreservingConditionalFlowMatcher(ConditionalFlowMatcher):
549
+ """Albergo et al. 2023 trigonometric interpolants class. This class inherits the
550
+ ConditionalFlowMatcher and override the compute_mu_t and compute_conditional_flow functions in
551
+ order to compute [3]'s trigonometric interpolants.
552
+
553
+ [3] Stochastic Interpolants: A Unifying Framework for Flows and Diffusions, Albergo et al.
554
+ """
555
+
556
+ def compute_mu_t(self, x0, x1, t):
557
+ r"""Compute the mean of the probability path (Eq.5) from [3].
558
+
559
+ Parameters
560
+ ----------
561
+ x0 : Tensor, shape (bs, *dim)
562
+ represents the source minibatch
563
+ x1 : Tensor, shape (bs, *dim)
564
+ represents the target minibatch
565
+ t : FloatTensor, shape (bs)
566
+
567
+ Returns
568
+ -------
569
+ mean mu_t: cos(pi t/2)x0 + sin(pi t/2)x1
570
+
571
+ References
572
+ ----------
573
+ [3] Stochastic Interpolants: A Unifying Framework for Flows and Diffusions, Albergo et al.
574
+ """
575
+ t = pad_t_like_x(t, x0)
576
+ return torch.cos(math.pi / 2 * t) * x0 + torch.sin(math.pi / 2 * t) * x1
577
+
578
+ def compute_conditional_flow(self, x0, x1, t, xt):
579
+ r"""Compute the conditional vector field similar to [3].
580
+
581
+ ut(x1|x0) = pi/2 (cos(pi*t/2) x1 - sin(pi*t/2) x0),
582
+ see Eq.(21) [3].
583
+
584
+ Parameters
585
+ ----------
586
+ x0 : Tensor, shape (bs, *dim)
587
+ represents the source minibatch
588
+ x1 : Tensor, shape (bs, *dim)
589
+ represents the target minibatch
590
+ t : FloatTensor, shape (bs)
591
+ xt : Tensor, shape (bs, *dim)
592
+ represents the samples drawn from probability path pt
593
+
594
+ Returns
595
+ -------
596
+ ut : conditional vector field
597
+ ut(x1|x0) = pi/2 (cos(pi*t/2) x1 - sin(\pi*t/2) x0)
598
+
599
+ References
600
+ ----------
601
+ [3] Stochastic Interpolants: A Unifying Framework for Flows and Diffusions, Albergo et al.
602
+ """
603
+ del xt
604
+ t = pad_t_like_x(t, x0)
605
+ return math.pi / 2 * (torch.cos(math.pi / 2 * t) * x1 - torch.sin(math.pi / 2 * t) * x0)
606
+
torchcfm/models/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .models import MLP
torchcfm/models/models.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+
4
+ class MLP(torch.nn.Module):
5
+ def __init__(self, dim, out_dim=None, w=64, time_varying=False):
6
+ super().__init__()
7
+ self.time_varying = time_varying
8
+ if out_dim is None:
9
+ out_dim = dim
10
+ self.net = torch.nn.Sequential(
11
+ torch.nn.Linear(dim + (1 if time_varying else 0), w),
12
+ torch.nn.SELU(),
13
+ torch.nn.Linear(w, w),
14
+ torch.nn.SELU(),
15
+ torch.nn.Linear(w, w),
16
+ torch.nn.SELU(),
17
+ torch.nn.Linear(w, out_dim),
18
+ )
19
+
20
+ def forward(self, x):
21
+ return self.net(x)
22
+
23
+ class MLP_Embedding(torch.nn.Module):
24
+ def __init__(self, dim, out_dim=None, w=64, time_embed=100,time_varying=False):
25
+ super().__init__()
26
+ self.time_varying = time_varying
27
+ self.time_index_embedding = nn.Embedding(time_embed, w)
28
+ if out_dim is None:
29
+ out_dim = dim
30
+ self.net = torch.nn.Sequential(
31
+ torch.nn.Linear(dim + (1+w if time_varying else w), w),
32
+ torch.nn.SELU(),
33
+ torch.nn.Linear(w, w),
34
+ torch.nn.SELU(),
35
+ torch.nn.Linear(w, w),
36
+ torch.nn.SELU(),
37
+ torch.nn.Linear(w, out_dim),
38
+ )
39
+
40
+ def forward(self, x,ti):
41
+ embedded_tensor = self.time_index_embedding(ti.to(torch.long))
42
+ return self.net(torch.cat([x,embedded_tensor.squeeze()],dim=-1))
43
+
44
+
45
+ class GradModel(torch.nn.Module):
46
+ def __init__(self, action):
47
+ super().__init__()
48
+ self.action = action
49
+
50
+ def forward(self, x):
51
+ x = x.requires_grad_(True)
52
+ grad = torch.autograd.grad(torch.sum(self.action(x)), x, create_graph=True)[0]
53
+ return grad[:, :-1]
torchcfm/models/unet/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .unet import UNetModelWrapper as UNetModel
torchcfm/models/unet/fp16_util.py ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Helpers to train with 16-bit precision."""
2
+
3
+ import numpy as np
4
+ import torch as th
5
+ import torch.nn as nn
6
+ from torch._utils import _flatten_dense_tensors, _unflatten_dense_tensors
7
+
8
+ from . import logger
9
+
10
+ INITIAL_LOG_LOSS_SCALE = 20.0
11
+
12
+
13
+ def convert_module_to_f16(l):
14
+ """Convert primitive modules to float16."""
15
+ if isinstance(l, (nn.Conv1d, nn.Conv2d, nn.Conv3d)):
16
+ l.weight.data = l.weight.data.half()
17
+ if l.bias is not None:
18
+ l.bias.data = l.bias.data.half()
19
+
20
+
21
+ def convert_module_to_f32(l):
22
+ """Convert primitive modules to float32, undoing convert_module_to_f16()."""
23
+ if isinstance(l, (nn.Conv1d, nn.Conv2d, nn.Conv3d)):
24
+ l.weight.data = l.weight.data.float()
25
+ if l.bias is not None:
26
+ l.bias.data = l.bias.data.float()
27
+
28
+
29
+ def make_master_params(param_groups_and_shapes):
30
+ """Copy model parameters into a (differently-shaped) list of full-precision parameters."""
31
+ master_params = []
32
+ for param_group, shape in param_groups_and_shapes:
33
+ master_param = nn.Parameter(
34
+ _flatten_dense_tensors([param.detach().float() for (_, param) in param_group]).view(
35
+ shape
36
+ )
37
+ )
38
+ master_param.requires_grad = True
39
+ master_params.append(master_param)
40
+ return master_params
41
+
42
+
43
+ def model_grads_to_master_grads(param_groups_and_shapes, master_params):
44
+ """Copy the gradients from the model parameters into the master parameters from
45
+ make_master_params()."""
46
+ for master_param, (param_group, shape) in zip(master_params, param_groups_and_shapes):
47
+ master_param.grad = _flatten_dense_tensors(
48
+ [param_grad_or_zeros(param) for (_, param) in param_group]
49
+ ).view(shape)
50
+
51
+
52
+ def master_params_to_model_params(param_groups_and_shapes, master_params):
53
+ """Copy the master parameter data back into the model parameters."""
54
+ # Without copying to a list, if a generator is passed, this will
55
+ # silently not copy any parameters.
56
+ for master_param, (param_group, _) in zip(master_params, param_groups_and_shapes):
57
+ for (_, param), unflat_master_param in zip(
58
+ param_group, unflatten_master_params(param_group, master_param.view(-1))
59
+ ):
60
+ param.detach().copy_(unflat_master_param)
61
+
62
+
63
+ def unflatten_master_params(param_group, master_param):
64
+ return _unflatten_dense_tensors(master_param, [param for (_, param) in param_group])
65
+
66
+
67
+ def get_param_groups_and_shapes(named_model_params):
68
+ named_model_params = list(named_model_params)
69
+ scalar_vector_named_params = (
70
+ [(n, p) for (n, p) in named_model_params if p.ndim <= 1],
71
+ (-1),
72
+ )
73
+ matrix_named_params = (
74
+ [(n, p) for (n, p) in named_model_params if p.ndim > 1],
75
+ (1, -1),
76
+ )
77
+ return [scalar_vector_named_params, matrix_named_params]
78
+
79
+
80
+ def master_params_to_state_dict(model, param_groups_and_shapes, master_params, use_fp16):
81
+ if use_fp16:
82
+ state_dict = model.state_dict()
83
+ for master_param, (param_group, _) in zip(master_params, param_groups_and_shapes):
84
+ for (name, _), unflat_master_param in zip(
85
+ param_group, unflatten_master_params(param_group, master_param.view(-1))
86
+ ):
87
+ assert name in state_dict
88
+ state_dict[name] = unflat_master_param
89
+ else:
90
+ state_dict = model.state_dict()
91
+ for i, (name, _value) in enumerate(model.named_parameters()):
92
+ assert name in state_dict
93
+ state_dict[name] = master_params[i]
94
+ return state_dict
95
+
96
+
97
+ def state_dict_to_master_params(model, state_dict, use_fp16):
98
+ if use_fp16:
99
+ named_model_params = [(name, state_dict[name]) for name, _ in model.named_parameters()]
100
+ param_groups_and_shapes = get_param_groups_and_shapes(named_model_params)
101
+ master_params = make_master_params(param_groups_and_shapes)
102
+ else:
103
+ master_params = [state_dict[name] for name, _ in model.named_parameters()]
104
+ return master_params
105
+
106
+
107
+ def zero_master_grads(master_params):
108
+ for param in master_params:
109
+ param.grad = None
110
+
111
+
112
+ def zero_grad(model_params):
113
+ for param in model_params:
114
+ # Taken from https://pytorch.org/docs/stable/_modules/torch/optim/optimizer.html#Optimizer.add_param_group
115
+ if param.grad is not None:
116
+ param.grad.detach_()
117
+ param.grad.zero_()
118
+
119
+
120
+ def param_grad_or_zeros(param):
121
+ if param.grad is not None:
122
+ return param.grad.data.detach()
123
+ else:
124
+ return th.zeros_like(param)
125
+
126
+
127
+ class MixedPrecisionTrainer:
128
+ def __init__(
129
+ self,
130
+ *,
131
+ model,
132
+ use_fp16=False,
133
+ fp16_scale_growth=1e-3,
134
+ initial_lg_loss_scale=INITIAL_LOG_LOSS_SCALE,
135
+ ):
136
+ self.model = model
137
+ self.use_fp16 = use_fp16
138
+ self.fp16_scale_growth = fp16_scale_growth
139
+
140
+ self.model_params = list(self.model.parameters())
141
+ self.master_params = self.model_params
142
+ self.param_groups_and_shapes = None
143
+ self.lg_loss_scale = initial_lg_loss_scale
144
+
145
+ if self.use_fp16:
146
+ self.param_groups_and_shapes = get_param_groups_and_shapes(
147
+ self.model.named_parameters()
148
+ )
149
+ self.master_params = make_master_params(self.param_groups_and_shapes)
150
+ self.model.convert_to_fp16()
151
+
152
+ def zero_grad(self):
153
+ zero_grad(self.model_params)
154
+
155
+ def backward(self, loss: th.Tensor):
156
+ if self.use_fp16:
157
+ loss_scale = 2**self.lg_loss_scale
158
+ (loss * loss_scale).backward()
159
+ else:
160
+ loss.backward()
161
+
162
+ def optimize(self, opt: th.optim.Optimizer):
163
+ if self.use_fp16:
164
+ return self._optimize_fp16(opt)
165
+ else:
166
+ return self._optimize_normal(opt)
167
+
168
+ def _optimize_fp16(self, opt: th.optim.Optimizer):
169
+ logger.logkv_mean("lg_loss_scale", self.lg_loss_scale)
170
+ model_grads_to_master_grads(self.param_groups_and_shapes, self.master_params)
171
+ grad_norm, param_norm = self._compute_norms(grad_scale=2**self.lg_loss_scale)
172
+ if check_overflow(grad_norm):
173
+ self.lg_loss_scale -= 1
174
+ logger.log(f"Found NaN, decreased lg_loss_scale to {self.lg_loss_scale}")
175
+ zero_master_grads(self.master_params)
176
+ return False
177
+
178
+ logger.logkv_mean("grad_norm", grad_norm)
179
+ logger.logkv_mean("param_norm", param_norm)
180
+
181
+ for p in self.master_params:
182
+ p.grad.mul_(1.0 / (2**self.lg_loss_scale))
183
+ opt.step()
184
+ zero_master_grads(self.master_params)
185
+ master_params_to_model_params(self.param_groups_and_shapes, self.master_params)
186
+ self.lg_loss_scale += self.fp16_scale_growth
187
+ return True
188
+
189
+ def _optimize_normal(self, opt: th.optim.Optimizer):
190
+ grad_norm, param_norm = self._compute_norms()
191
+ logger.logkv_mean("grad_norm", grad_norm)
192
+ logger.logkv_mean("param_norm", param_norm)
193
+ opt.step()
194
+ return True
195
+
196
+ def _compute_norms(self, grad_scale=1.0):
197
+ grad_norm = 0.0
198
+ param_norm = 0.0
199
+ for p in self.master_params:
200
+ with th.no_grad():
201
+ param_norm += th.norm(p, p=2, dtype=th.float32).item() ** 2
202
+ if p.grad is not None:
203
+ grad_norm += th.norm(p.grad, p=2, dtype=th.float32).item() ** 2
204
+ return np.sqrt(grad_norm) / grad_scale, np.sqrt(param_norm)
205
+
206
+ def master_params_to_state_dict(self, master_params):
207
+ return master_params_to_state_dict(
208
+ self.model, self.param_groups_and_shapes, master_params, self.use_fp16
209
+ )
210
+
211
+ def state_dict_to_master_params(self, state_dict):
212
+ return state_dict_to_master_params(self.model, state_dict, self.use_fp16)
213
+
214
+
215
+ def check_overflow(value):
216
+ return (value == float("inf")) or (value == -float("inf")) or (value != value)
torchcfm/models/unet/logger.py ADDED
@@ -0,0 +1,469 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Logger copied from OpenAI baselines to avoid extra RL-based dependencies:
2
+
3
+ https://github.com/openai/baselines/blob/ea25b9e8b234e6ee1bca43083f8f3cf974143998/baselines/logger.py
4
+ """
5
+
6
+ import datetime
7
+ import json
8
+ import os
9
+ import os.path as osp
10
+ import shutil
11
+ import sys
12
+ import tempfile
13
+ import time
14
+ import warnings
15
+ from collections import defaultdict
16
+ from contextlib import contextmanager
17
+
18
+ DEBUG = 10
19
+ INFO = 20
20
+ WARN = 30
21
+ ERROR = 40
22
+
23
+ DISABLED = 50
24
+
25
+
26
+ class KVWriter:
27
+ def writekvs(self, kvs):
28
+ raise NotImplementedError
29
+
30
+
31
+ class SeqWriter:
32
+ def writeseq(self, seq):
33
+ raise NotImplementedError
34
+
35
+
36
+ class HumanOutputFormat(KVWriter, SeqWriter):
37
+ def __init__(self, filename_or_file):
38
+ if isinstance(filename_or_file, str):
39
+ self.file = open(filename_or_file, "w")
40
+ self.own_file = True
41
+ else:
42
+ assert hasattr(filename_or_file, "read"), (
43
+ "expected file or str, got %s" % filename_or_file
44
+ )
45
+ self.file = filename_or_file
46
+ self.own_file = False
47
+
48
+ def writekvs(self, kvs):
49
+ # Create strings for printing
50
+ key2str = {}
51
+ for key, val in sorted(kvs.items()):
52
+ if hasattr(val, "__float__"):
53
+ valstr = "%-8.3g" % val
54
+ else:
55
+ valstr = str(val)
56
+ key2str[self._truncate(key)] = self._truncate(valstr)
57
+
58
+ # Find max widths
59
+ if len(key2str) == 0:
60
+ print("WARNING: tried to write empty key-value dict")
61
+ return
62
+ else:
63
+ keywidth = max(map(len, key2str.keys()))
64
+ valwidth = max(map(len, key2str.values()))
65
+
66
+ # Write out the data
67
+ dashes = "-" * (keywidth + valwidth + 7)
68
+ lines = [dashes]
69
+ for key, val in sorted(key2str.items(), key=lambda kv: kv[0].lower()):
70
+ lines.append(
71
+ "| %s%s | %s%s |"
72
+ % (key, " " * (keywidth - len(key)), val, " " * (valwidth - len(val)))
73
+ )
74
+ lines.append(dashes)
75
+ self.file.write("\n".join(lines) + "\n")
76
+
77
+ # Flush the output to the file
78
+ self.file.flush()
79
+
80
+ def _truncate(self, s):
81
+ maxlen = 30
82
+ return s[: maxlen - 3] + "..." if len(s) > maxlen else s
83
+
84
+ def writeseq(self, seq):
85
+ seq = list(seq)
86
+ for i, elem in enumerate(seq):
87
+ self.file.write(elem)
88
+ if i < len(seq) - 1: # add space unless this is the last one
89
+ self.file.write(" ")
90
+ self.file.write("\n")
91
+ self.file.flush()
92
+
93
+ def close(self):
94
+ if self.own_file:
95
+ self.file.close()
96
+
97
+
98
+ class JSONOutputFormat(KVWriter):
99
+ def __init__(self, filename):
100
+ self.file = open(filename, "w")
101
+
102
+ def writekvs(self, kvs):
103
+ for k, v in sorted(kvs.items()):
104
+ if hasattr(v, "dtype"):
105
+ kvs[k] = float(v)
106
+ self.file.write(json.dumps(kvs) + "\n")
107
+ self.file.flush()
108
+
109
+ def close(self):
110
+ self.file.close()
111
+
112
+
113
+ class CSVOutputFormat(KVWriter):
114
+ def __init__(self, filename):
115
+ self.file = open(filename, "w+t")
116
+ self.keys = []
117
+ self.sep = ","
118
+
119
+ def writekvs(self, kvs):
120
+ # Add our current row to the history
121
+ extra_keys = list(kvs.keys() - self.keys)
122
+ extra_keys.sort()
123
+ if extra_keys:
124
+ self.keys.extend(extra_keys)
125
+ self.file.seek(0)
126
+ lines = self.file.readlines()
127
+ self.file.seek(0)
128
+ for i, k in enumerate(self.keys):
129
+ if i > 0:
130
+ self.file.write(",")
131
+ self.file.write(k)
132
+ self.file.write("\n")
133
+ for line in lines[1:]:
134
+ self.file.write(line[:-1])
135
+ self.file.write(self.sep * len(extra_keys))
136
+ self.file.write("\n")
137
+ for i, k in enumerate(self.keys):
138
+ if i > 0:
139
+ self.file.write(",")
140
+ v = kvs.get(k)
141
+ if v is not None:
142
+ self.file.write(str(v))
143
+ self.file.write("\n")
144
+ self.file.flush()
145
+
146
+ def close(self):
147
+ self.file.close()
148
+
149
+
150
+ class TensorBoardOutputFormat(KVWriter):
151
+ """Dumps key/value pairs into TensorBoard's numeric format."""
152
+
153
+ def __init__(self, dir):
154
+ os.makedirs(dir, exist_ok=True)
155
+ self.dir = dir
156
+ self.step = 1
157
+ prefix = "events"
158
+ path = osp.join(osp.abspath(dir), prefix)
159
+ import tensorflow as tf
160
+ from tensorflow.core.util import event_pb2
161
+ from tensorflow.python import pywrap_tensorflow
162
+ from tensorflow.python.util import compat
163
+
164
+ self.tf = tf
165
+ self.event_pb2 = event_pb2
166
+ self.pywrap_tensorflow = pywrap_tensorflow
167
+ self.writer = pywrap_tensorflow.EventsWriter(compat.as_bytes(path))
168
+
169
+ def writekvs(self, kvs):
170
+ def summary_val(k, v):
171
+ kwargs = {"tag": k, "simple_value": float(v)}
172
+ return self.tf.Summary.Value(**kwargs)
173
+
174
+ summary = self.tf.Summary(value=[summary_val(k, v) for k, v in kvs.items()])
175
+ event = self.event_pb2.Event(wall_time=time.time(), summary=summary)
176
+ event.step = self.step # is there any reason why you'd want to specify the step?
177
+ self.writer.WriteEvent(event)
178
+ self.writer.Flush()
179
+ self.step += 1
180
+
181
+ def close(self):
182
+ if self.writer:
183
+ self.writer.Close()
184
+ self.writer = None
185
+
186
+
187
+ def make_output_format(format, ev_dir, log_suffix=""):
188
+ os.makedirs(ev_dir, exist_ok=True)
189
+ if format == "stdout":
190
+ return HumanOutputFormat(sys.stdout)
191
+ elif format == "log":
192
+ return HumanOutputFormat(osp.join(ev_dir, "log%s.txt" % log_suffix))
193
+ elif format == "json":
194
+ return JSONOutputFormat(osp.join(ev_dir, "progress%s.json" % log_suffix))
195
+ elif format == "csv":
196
+ return CSVOutputFormat(osp.join(ev_dir, "progress%s.csv" % log_suffix))
197
+ elif format == "tensorboard":
198
+ return TensorBoardOutputFormat(osp.join(ev_dir, "tb%s" % log_suffix))
199
+ else:
200
+ raise ValueError(f"Unknown format specified: {format}")
201
+
202
+
203
+ # ================================================================
204
+ # API
205
+ # ================================================================
206
+
207
+
208
+ def logkv(key, val):
209
+ """Log a value of some diagnostic Call this once for each diagnostic quantity, each iteration
210
+ If called many times, last value will be used."""
211
+ get_current().logkv(key, val)
212
+
213
+
214
+ def logkv_mean(key, val):
215
+ """The same as logkv(), but if called many times, values averaged."""
216
+ get_current().logkv_mean(key, val)
217
+
218
+
219
+ def logkvs(d):
220
+ """Log a dictionary of key-value pairs."""
221
+ for k, v in d.items():
222
+ logkv(k, v)
223
+
224
+
225
+ def dumpkvs():
226
+ """Write all of the diagnostics from the current iteration."""
227
+ return get_current().dumpkvs()
228
+
229
+
230
+ def getkvs():
231
+ return get_current().name2val
232
+
233
+
234
+ def log(*args, level=INFO):
235
+ """Write the sequence of args, with no separators, to the console and output files (if you've
236
+ configured an output file)."""
237
+ get_current().log(*args, level=level)
238
+
239
+
240
+ def debug(*args):
241
+ log(*args, level=DEBUG)
242
+
243
+
244
+ def info(*args):
245
+ log(*args, level=INFO)
246
+
247
+
248
+ def warn(*args):
249
+ log(*args, level=WARN)
250
+
251
+
252
+ def error(*args):
253
+ log(*args, level=ERROR)
254
+
255
+
256
+ def set_level(level):
257
+ """Set logging threshold on current logger."""
258
+ get_current().set_level(level)
259
+
260
+
261
+ def set_comm(comm):
262
+ get_current().set_comm(comm)
263
+
264
+
265
+ def get_dir():
266
+ """Get directory that log files are being written to.
267
+
268
+ will be None if there is no output directory (i.e., if you didn't call start)
269
+ """
270
+ return get_current().get_dir()
271
+
272
+
273
+ record_tabular = logkv
274
+ dump_tabular = dumpkvs
275
+
276
+
277
+ @contextmanager
278
+ def profile_kv(scopename):
279
+ logkey = "wait_" + scopename
280
+ tstart = time.time()
281
+ try:
282
+ yield
283
+ finally:
284
+ get_current().name2val[logkey] += time.time() - tstart
285
+
286
+
287
+ def profile(n):
288
+ """
289
+ Usage:
290
+ @profile("my_func")
291
+ def my_func(): code
292
+ """
293
+
294
+ def decorator_with_name(func):
295
+ def func_wrapper(*args, **kwargs):
296
+ with profile_kv(n):
297
+ return func(*args, **kwargs)
298
+
299
+ return func_wrapper
300
+
301
+ return decorator_with_name
302
+
303
+
304
+ # ================================================================
305
+ # Backend
306
+ # ================================================================
307
+
308
+
309
+ def get_current():
310
+ if Logger.CURRENT is None:
311
+ _configure_default_logger()
312
+
313
+ return Logger.CURRENT
314
+
315
+
316
+ class Logger:
317
+ DEFAULT = None # A logger with no output files. (See right below class definition)
318
+ # So that you can still log to the terminal without setting up any output files
319
+ CURRENT = None # Current logger being used by the free functions above
320
+
321
+ def __init__(self, dir, output_formats, comm=None):
322
+ self.name2val = defaultdict(float) # values this iteration
323
+ self.name2cnt = defaultdict(int)
324
+ self.level = INFO
325
+ self.dir = dir
326
+ self.output_formats = output_formats
327
+ self.comm = comm
328
+
329
+ # Logging API, forwarded
330
+ # ----------------------------------------
331
+ def logkv(self, key, val):
332
+ self.name2val[key] = val
333
+
334
+ def logkv_mean(self, key, val):
335
+ oldval, cnt = self.name2val[key], self.name2cnt[key]
336
+ self.name2val[key] = oldval * cnt / (cnt + 1) + val / (cnt + 1)
337
+ self.name2cnt[key] = cnt + 1
338
+
339
+ def dumpkvs(self):
340
+ if self.comm is None:
341
+ d = self.name2val
342
+ else:
343
+ d = mpi_weighted_mean(
344
+ self.comm,
345
+ {name: (val, self.name2cnt.get(name, 1)) for (name, val) in self.name2val.items()},
346
+ )
347
+ if self.comm.rank != 0:
348
+ d["dummy"] = 1 # so we don't get a warning about empty dict
349
+ out = d.copy() # Return the dict for unit testing purposes
350
+ for fmt in self.output_formats:
351
+ if isinstance(fmt, KVWriter):
352
+ fmt.writekvs(d)
353
+ self.name2val.clear()
354
+ self.name2cnt.clear()
355
+ return out
356
+
357
+ def log(self, *args, level=INFO):
358
+ if self.level <= level:
359
+ self._do_log(args)
360
+
361
+ # Configuration
362
+ # ----------------------------------------
363
+ def set_level(self, level):
364
+ self.level = level
365
+
366
+ def set_comm(self, comm):
367
+ self.comm = comm
368
+
369
+ def get_dir(self):
370
+ return self.dir
371
+
372
+ def close(self):
373
+ for fmt in self.output_formats:
374
+ fmt.close()
375
+
376
+ # Misc
377
+ # ----------------------------------------
378
+ def _do_log(self, args):
379
+ for fmt in self.output_formats:
380
+ if isinstance(fmt, SeqWriter):
381
+ fmt.writeseq(map(str, args))
382
+
383
+
384
+ def get_rank_without_mpi_import():
385
+ # check environment variables here instead of importing mpi4py
386
+ # to avoid calling MPI_Init() when this module is imported
387
+ for varname in ["PMI_RANK", "OMPI_COMM_WORLD_RANK"]:
388
+ if varname in os.environ:
389
+ return int(os.environ[varname])
390
+ return 0
391
+
392
+
393
+ def mpi_weighted_mean(comm, local_name2valcount):
394
+ """
395
+ Copied from: https://github.com/openai/baselines/blob/ea25b9e8b234e6ee1bca43083f8f3cf974143998/baselines/common/mpi_util.py#L110
396
+ Perform a weighted average over dicts that are each on a different node
397
+ Input: local_name2valcount: dict mapping key -> (value, count)
398
+ Returns: key -> mean
399
+ """
400
+ all_name2valcount = comm.gather(local_name2valcount)
401
+ if comm.rank == 0:
402
+ name2sum = defaultdict(float)
403
+ name2count = defaultdict(float)
404
+ for n2vc in all_name2valcount:
405
+ for name, (val, count) in n2vc.items():
406
+ try:
407
+ val = float(val)
408
+ except ValueError:
409
+ if comm.rank == 0:
410
+ warnings.warn(f"WARNING: tried to compute mean on non-float {name}={val}")
411
+ else:
412
+ name2sum[name] += val * count
413
+ name2count[name] += count
414
+ return {name: name2sum[name] / name2count[name] for name in name2sum}
415
+ else:
416
+ return {}
417
+
418
+
419
+ def configure(dir=None, format_strs=None, comm=None, log_suffix=""):
420
+ """If comm is provided, average all numerical stats across that comm."""
421
+ if dir is None:
422
+ dir = os.getenv("OPENAI_LOGDIR")
423
+ if dir is None:
424
+ dir = osp.join(
425
+ tempfile.gettempdir(),
426
+ datetime.datetime.now().strftime("openai-%Y-%m-%d-%H-%M-%S-%f"),
427
+ )
428
+ assert isinstance(dir, str)
429
+ dir = os.path.expanduser(dir)
430
+ os.makedirs(os.path.expanduser(dir), exist_ok=True)
431
+
432
+ rank = get_rank_without_mpi_import()
433
+ if rank > 0:
434
+ log_suffix = log_suffix + "-rank%03i" % rank
435
+
436
+ if format_strs is None:
437
+ if rank == 0:
438
+ format_strs = os.getenv("OPENAI_LOG_FORMAT", "stdout,log,csv").split(",")
439
+ else:
440
+ format_strs = os.getenv("OPENAI_LOG_FORMAT_MPI", "log").split(",")
441
+ format_strs = filter(None, format_strs)
442
+ output_formats = [make_output_format(f, dir, log_suffix) for f in format_strs]
443
+
444
+ Logger.CURRENT = Logger(dir=dir, output_formats=output_formats, comm=comm)
445
+ if output_formats:
446
+ log("Logging to %s" % dir)
447
+
448
+
449
+ def _configure_default_logger():
450
+ configure()
451
+ Logger.DEFAULT = Logger.CURRENT
452
+
453
+
454
+ def reset():
455
+ if Logger.CURRENT is not Logger.DEFAULT:
456
+ Logger.CURRENT.close()
457
+ Logger.CURRENT = Logger.DEFAULT
458
+ log("Reset logger")
459
+
460
+
461
+ @contextmanager
462
+ def scoped_configure(dir=None, format_strs=None, comm=None):
463
+ prevlogger = Logger.CURRENT
464
+ configure(dir=dir, format_strs=format_strs, comm=comm)
465
+ try:
466
+ yield
467
+ finally:
468
+ Logger.CURRENT.close()
469
+ Logger.CURRENT = prevlogger