diff --git a/.gitattributes b/.gitattributes index a6344aac8c09253b3b630fb776ae94478aa0275b..7c17083b38d4d045292740e995e85ed13e97f0ae 100644 --- a/.gitattributes +++ b/.gitattributes @@ -33,3 +33,11 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text *.zip filter=lfs diff=lfs merge=lfs -text *.zst filter=lfs diff=lfs merge=lfs -text *tfevents* filter=lfs diff=lfs merge=lfs -text +2D_examples/ImageGen.png filter=lfs diff=lfs merge=lfs -text +2D_examples/outputs/8gaussians/samples_grid.png filter=lfs diff=lfs merge=lfs -text +2D_examples/outputs/checkerboard/samples_grid.png filter=lfs diff=lfs merge=lfs -text +2D_examples/outputs/moons/samples_grid.png filter=lfs diff=lfs merge=lfs -text +assets/idff_2d.gif filter=lfs diff=lfs merge=lfs -text +assets/idff_lorenz.gif filter=lfs diff=lfs merge=lfs -text +timeseris_example/outputs/lorenz/rollout.png filter=lfs diff=lfs merge=lfs -text +timeseris_example/outputs/polyALA/md_samples.png filter=lfs diff=lfs merge=lfs -text diff --git a/.github/workflows/python-app.yml b/.github/workflows/python-app.yml new file mode 100644 index 0000000000000000000000000000000000000000..2e835f5a997e923f086bf0750406454759c077b4 --- /dev/null +++ b/.github/workflows/python-app.yml @@ -0,0 +1,30 @@ +name: tests + +on: + push: + branches: [ "main", "master" ] + pull_request: + branches: [ "main", "master" ] + +permissions: + contents: read + +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Set up Python 3.11 + uses: actions/setup-python@v5 + with: + python-version: "3.11" + - name: Install dependencies + run: | + python -m pip install --upgrade pip + pip install torch --index-url https://download.pytorch.org/whl/cpu + pip install -r requirements.txt + pip install flake8 pytest + - name: Lint (syntax errors and undefined names) + run: flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics + - name: Run tests + run: pytest -q diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..044f2dc0e09c332740d44c9abdeda58f31fc92bd --- /dev/null +++ b/.gitignore @@ -0,0 +1,7 @@ +__pycache__/ +*.py[cod] +.pytest_cache/ +.DS_Store +._* +*.egg-info/ +.venv/ diff --git a/2D_examples/ImageGen.png b/2D_examples/ImageGen.png new file mode 100644 index 0000000000000000000000000000000000000000..3712dc2b63d650e007ed64501dba451e7fef7642 --- /dev/null +++ b/2D_examples/ImageGen.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:de243601185569779b28b6656559fa0da835c75eb8b8d1478b0b2dc5acf5404f +size 5514069 diff --git a/2D_examples/idff_2d.py b/2D_examples/idff_2d.py new file mode 100644 index 0000000000000000000000000000000000000000..ba741325c31dc4e9ab4872c815864ab1f193556f --- /dev/null +++ b/2D_examples/idff_2d.py @@ -0,0 +1,260 @@ +"""IDFF on 2-D toy distributions. + +Trains one joint-head network (denoiser + score) with the IDFF objective and compares samplers that +share it, at several NFE budgets: + +* CFM (det.) deterministic Euler on v_hat = (x1_hat - x)/(1 - t) (K = 0) +* Stochastic CFM same diffusion g_t^2 = 2 gamma_t^1 but no score drift (ablation) +* IDFF K=1 score-Langevin drift + matched diffusion (paper default) +* IDFF K=2 / K=3 plus contracted curvature terms (K=3 shown for illustration only) + +Hyper-parameters are selected per NFE budget on a validation sample, and results are reported on +separate test samples (mean +- std over seeds): gamma_bar for K=1 from {c / NFE} (the paper's +gamma_bar = O(dt) scaling); alpha_2 for K=2 with the same gamma_bar, where alpha_2 = 0 recovers K=1; +alpha_3 for K=3 given alpha_2. The sign of alpha_k is free (the deviation bound depends on alpha_k^2). +Example: + + python 2D_examples/idff_2d.py --dataset checkerboard +""" +import argparse +import csv +import json +import sys +import time +from pathlib import Path + +import matplotlib + +matplotlib.use("Agg") +import matplotlib.pyplot as plt # noqa: E402 +import numpy as np # noqa: E402 +import torch # noqa: E402 +from scipy.stats import gaussian_kde # noqa: E402 + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) + +from idff import JointHeadMLP, idff_loss, ot_coupling, sample, sigma_t # noqa: E402 +from idff.datasets import TOY_DATASETS # noqa: E402 +from idff.metrics import mmd_rbf # noqa: E402 + + +def repo_relative(args): + """Command-line arguments with paths made relative to the repository (for config.json).""" + out = dict(vars(args)) + for key in ("out", "data"): + if key in out: + try: + out[key] = str(Path(out[key]).resolve().relative_to(ROOT)) + except ValueError: + pass + return out + + +def parse_args(): + p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + p.add_argument("--dataset", default="checkerboard", choices=list(TOY_DATASETS)) + p.add_argument("--iters", type=int, default=60000, + help="the score head needs long training: its target -eps/sigma_t is high-variance") + p.add_argument("--batch", type=int, default=512) + p.add_argument("--lr", type=float, default=1e-3) + p.add_argument("--sigma0", type=float, default=0.2) + p.add_argument("--coupling", default="independent", choices=["independent", "ot"], + help="'ot' trains OT-IDFF with minibatch optimal-transport pairs (needs POT)") + p.add_argument("--nfes", type=int, nargs="+", default=[2, 3, 5, 10, 20]) + p.add_argument("--gamma-c-grid", type=float, nargs="+", default=[0.5, 1.0, 2.0, 4.0, 8.0, 16.0, 32.0], + help="grid for c in gamma_bar = c / NFE") + p.add_argument("--alpha-grid", type=float, nargs="+", + default=[-4.0, -2.0, -1.0, -0.5, -0.1, 0.1, 0.5, 1.0, 2.0, 4.0], + help="alpha_k grid (0 is always added); the sign is free (the bound depends on alpha_k^2)") + p.add_argument("--n-eval", type=int, default=3000) + p.add_argument("--seeds", type=int, default=5) + p.add_argument("--retrain", action="store_true") + p.add_argument("--out", default=str(Path(__file__).resolve().parent / "outputs")) + return p.parse_args() + + +def train(args, out_dir): + ckpt = out_dir / "idff_model.pt" + model = JointHeadMLP(2, hidden=256, depth=3, sigma0=args.sigma0) + if ckpt.exists() and not args.retrain: + model.load_state_dict(torch.load(ckpt, map_location="cpu", weights_only=True)) + print(f"loaded {ckpt}") + return model.eval() + torch.manual_seed(0) + opt = torch.optim.Adam(model.parameters(), lr=args.lr) + sched = torch.optim.lr_scheduler.CosineAnnealingLR(opt, args.iters) + sampler = TOY_DATASETS[args.dataset] + start = time.time() + for it in range(1, args.iters + 1): + x1 = sampler(args.batch) + x0 = torch.randn_like(x1) + if args.coupling == "ot": + x0, x1 = ot_coupling(x0, x1) + loss, stats = idff_loss(model, x1, x0=x0, sigma0=args.sigma0) + opt.zero_grad() + loss.backward() + torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) + opt.step() + sched.step() + if it % 2000 == 0: + print(f"iter {it:6d} loss {loss.item():.4f} denoiser {stats['denoiser']:.4f} " + f"score {stats['score']:.4f} ({time.time() - start:.0f}s)") + torch.save(model.state_dict(), ckpt) + return model.eval() + + +@torch.no_grad() +def score_diagnostic(model, args): + """Compare the learned score head with the exact marginal score of the training path. + + 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. + """ + ref = TOY_DATASETS[args.dataset](40000) + rows = [] + for t in [0.25, 0.5, 0.75]: + var = (1 - t) ** 2 + sigma_t(t, args.sigma0) ** 2 + x = t * TOY_DATASETS[args.dataset](2000) + np.sqrt(var) * torch.randn(2000, 2) + d = x[:, None] - t * ref[None] + w = torch.softmax(-(d ** 2).sum(-1) / (2 * var), dim=1) + true = -(w[..., None] * d).sum(1) / var + _, s_hat = model(x, torch.full((2000,), t)) + cos = torch.nn.functional.cosine_similarity(s_hat, true, dim=1) + rel = ((s_hat - true).norm(dim=1) / true.norm(dim=1)).median() + rows.append((t, cos.mean().item(), rel.item())) + return rows + + +METHODS = { + "CFM (det.)": dict(K=0), + "Stochastic CFM": dict(K=1, score_drift=False), + "IDFF K=1": dict(K=1), + "IDFF K=2": dict(K=2), + "IDFF K=3": dict(K=3), +} + + +def run(model, cfg, nfe, n, seed): + gen = torch.Generator().manual_seed(seed) + x0 = torch.randn(n, 2, generator=gen) + return sample(model, x0, nfe, generator=gen, **cfg) + + +def config_for(name, nfe, sel): + """Sampler arguments of method ``name`` at budget ``nfe`` given the selected hyper-parameters.""" + s = sel[nfe] + cfg = dict(METHODS[name]) + if cfg["K"] >= 1: + cfg["gamma_bar"] = s["gamma_bar"] + if cfg["K"] >= 2: + cfg["alphas"] = {2: s["alpha_2"], 3: s["alpha_3"]} + return cfg + + +def select_hyperparameters(model, args): + """Per NFE budget, on a validation sample (mean MMD over two sampling seeds): gamma_bar for K=1, + then alpha_2 for K=2 with the same gamma_bar, then alpha_3 for K=3. alpha = 0 is tried first, so + K=2 falls back to K=1 when the curvature term does not help on validation data.""" + torch.manual_seed(12345) + val = TOY_DATASETS[args.dataset](args.n_eval) + alphas = [0.0] + [a for a in args.alpha_grid if a != 0.0] + sel = {} + for nfe in args.nfes: + def score(cfg, nfe=nfe): + return np.mean([mmd_rbf(run(model, cfg, nfe, args.n_eval, 900 + s), val) for s in range(2)]) + + g = min([c / nfe for c in args.gamma_c_grid], key=lambda g: score(dict(K=1, gamma_bar=g))) + a2 = min(alphas, key=lambda a: score(dict(K=2, gamma_bar=g, alphas={2: a}))) + a3 = min(alphas, key=lambda a: score(dict(K=3, gamma_bar=g, alphas={2: a2, 3: a}))) + sel[nfe] = {"gamma_bar": g, "alpha_2": a2, "alpha_3": a3} + return sel + + +def main(): + args = parse_args() + out_dir = Path(args.out) / (args.dataset + ("_ot" if args.coupling == "ot" else "")) + out_dir.mkdir(parents=True, exist_ok=True) + model = train(args, out_dir) + + print("\nscore head vs exact marginal score (Fisher's identity):") + for t, cos, rel in score_diagnostic(model, args): + print(f" t={t:.2f} mean cosine {cos:.3f} median relative error {rel:.3f}") + + sel = select_hyperparameters(model, args) + print("\nselected on validation data:") + for nfe, s in sel.items(): + print(f" NFE={nfe:3d} gamma_bar={s['gamma_bar']:.3g} alpha_2={s['alpha_2']:g} alpha_3={s['alpha_3']:g}") + + rows = [] + for name in METHODS: + for nfe in args.nfes: + vals = [] + for seed in range(args.seeds): + torch.manual_seed(1000 + seed) + test = TOY_DATASETS[args.dataset](args.n_eval) + vals.append(mmd_rbf(run(model, config_for(name, nfe, sel), nfe, args.n_eval, seed), test)) + rows.append({"method": name, "nfe": nfe, "mmd_mean": float(np.mean(vals)), "mmd_std": float(np.std(vals))}) + + with open(out_dir / "mmd_results.csv", "w", newline="") as fh: + writer = csv.DictWriter(fh, fieldnames=list(rows[0])) + writer.writeheader() + writer.writerows(rows) + with open(out_dir / "config.json", "w") as fh: + json.dump({**repo_relative(args), "selected": {str(k): v for k, v in sel.items()}}, fh, indent=2) + + header = "method".ljust(16) + "".join(f"NFE={n:<14d}" for n in args.nfes) + print("\nMMD (x1e3, mean +- std over seeds), lower is better\n" + header) + for name in METHODS: + line = name.ljust(16) + for nfe in args.nfes: + r = next(r for r in rows if r["method"] == name and r["nfe"] == nfe) + line += f"{1e3 * r['mmd_mean']:6.2f} +- {1e3 * r['mmd_std']:<5.2f} " + print(line) + + plot(model, args, rows, out_dir, sel) + print(f"\nwrote results to {out_dir}") + + +def plot(model, args, rows, out_dir, sel): + names = ["CFM (det.)", "Stochastic CFM", "IDFF K=1", "IDFF K=2"] + budgets = [b for b in [3, 5, 10] if b in args.nfes] or args.nfes[:3] + true = TOY_DATASETS[args.dataset](5000).numpy() + lo, hi = true.min() - 1, true.max() + 1 + gx, gy = np.meshgrid(np.linspace(lo, hi, 80), np.linspace(lo, hi, 80)) + grid = np.vstack([gx.ravel(), gy.ravel()]) + z_true = gaussian_kde(true.T)(grid).reshape(gx.shape) + fig, axs = plt.subplots(len(names), len(budgets), figsize=(3 * len(budgets), 3 * len(names)), squeeze=False) + for i, name in enumerate(names): + for j, nfe in enumerate(budgets): + x = run(model, config_for(name, nfe, sel), nfe, 5000, 0).numpy() + ax = axs[i, j] + ax.contourf(gx, gy, gaussian_kde(x.T)(grid).reshape(gx.shape), levels=30, cmap="Reds") + ax.contour(gx, gy, z_true, levels=6, colors="k", linewidths=0.6, linestyles="dashed") + mmd = next(r for r in rows if r["method"] == name and r["nfe"] == nfe)["mmd_mean"] + ax.set_title(f"{name}, NFE={nfe}\nMMD={1e3 * mmd:.2f}e-3", fontsize=9) + ax.set_xticks([]) + ax.set_yticks([]) + fig.tight_layout() + fig.savefig(out_dir / "samples_grid.png", dpi=130) + plt.close(fig) + + fig, ax = plt.subplots(figsize=(5, 3.6)) + for name in METHODS: + r = [x for x in rows if x["method"] == name] + ax.errorbar([x["nfe"] for x in r], [x["mmd_mean"] for x in r], yerr=[x["mmd_std"] for x in r], + marker="o", capsize=3, label=name, linestyle="--" if name == "IDFF K=3" else "-") + ax.set_xscale("log") + ax.set_yscale("log") + ax.set_xticks(args.nfes) + ax.set_xticklabels(args.nfes) + ax.set_xlabel("NFE") + ax.set_ylabel("MMD (test)") + ax.set_title(f"{args.dataset}") + ax.legend(fontsize=8) + fig.tight_layout() + fig.savefig(out_dir / "mmd_vs_nfe.png", dpi=130) + plt.close(fig) + + +if __name__ == "__main__": + main() diff --git a/2D_examples/outputs/8gaussians/config.json b/2D_examples/outputs/8gaussians/config.json new file mode 100644 index 0000000000000000000000000000000000000000..dca7d05028a09e78b736fd022151215ec43ef7a5 --- /dev/null +++ b/2D_examples/outputs/8gaussians/config.json @@ -0,0 +1,67 @@ +{ + "dataset": "8gaussians", + "iters": 60000, + "batch": 512, + "lr": 0.001, + "sigma0": 0.2, + "coupling": "independent", + "nfes": [ + 2, + 3, + 5, + 10, + 20 + ], + "gamma_c_grid": [ + 0.5, + 1.0, + 2.0, + 4.0, + 8.0, + 16.0, + 32.0 + ], + "alpha_grid": [ + -4.0, + -2.0, + -1.0, + -0.5, + -0.1, + 0.1, + 0.5, + 1.0, + 2.0, + 4.0 + ], + "n_eval": 3000, + "seeds": 5, + "retrain": false, + "out": "2D_examples/outputs", + "selected": { + "2": { + "gamma_bar": 0.25, + "alpha_2": 0.0, + "alpha_3": 0.0 + }, + "3": { + "gamma_bar": 2.6666666666666665, + "alpha_2": -0.5, + "alpha_3": -1.0 + }, + "5": { + "gamma_bar": 0.8, + "alpha_2": -1.0, + "alpha_3": -4.0 + }, + "10": { + "gamma_bar": 1.6, + "alpha_2": -0.5, + "alpha_3": -4.0 + }, + "20": { + "gamma_bar": 0.8, + "alpha_2": -1.0, + "alpha_3": -1.0 + } + } +} \ No newline at end of file diff --git a/2D_examples/outputs/8gaussians/idff_model.pt b/2D_examples/outputs/8gaussians/idff_model.pt new file mode 100644 index 0000000000000000000000000000000000000000..420bd31fc740408358828f72f43e85b1a6bcb925 --- /dev/null +++ b/2D_examples/outputs/8gaussians/idff_model.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:969f41be49ca0a053690582566842b975496818eeeee8fab32e985116201597a +size 547253 diff --git a/2D_examples/outputs/8gaussians/mmd_results.csv b/2D_examples/outputs/8gaussians/mmd_results.csv new file mode 100644 index 0000000000000000000000000000000000000000..a9d0c13c5e446000354d9ea7e5b22d8906df4a48 --- /dev/null +++ b/2D_examples/outputs/8gaussians/mmd_results.csv @@ -0,0 +1,26 @@ +method,nfe,mmd_mean,mmd_std +CFM (det.),2,0.08827868442018214,0.0014740249308344779 +CFM (det.),3,0.0424659072146575,0.0009810335595719967 +CFM (det.),5,0.015201979451496922,0.0006569678599379705 +CFM (det.),10,0.0040618978329832744,0.000340957955402701 +CFM (det.),20,0.0014573786194185868,0.00023822105751385107 +Stochastic CFM,2,0.08827868442018214,0.0014740249308344779 +Stochastic CFM,3,0.02315831109533261,0.0008980638011695121 +Stochastic CFM,5,0.013907063579835502,0.0007509603173326287 +Stochastic CFM,10,0.01856082030546402,0.0005613560839523732 +Stochastic CFM,20,0.010483334864954582,0.0004598238407209597 +IDFF K=1,2,0.08827868442018214,0.0014740249308344779 +IDFF K=1,3,0.012397986278387074,0.0005981308009709111 +IDFF K=1,5,0.0036822221889503738,0.0003590829112280288 +IDFF K=1,10,0.0011825990270721621,0.00014835786463725744 +IDFF K=1,20,0.0007450908311625093,0.0001515723157393066 +IDFF K=2,2,0.08827868442018214,0.0014740249308344779 +IDFF K=2,3,0.012363239203215557,0.0006370963586444877 +IDFF K=2,5,0.0024774969710118443,0.00035616083942766866 +IDFF K=2,10,0.0011324097054436655,0.00018514822443728822 +IDFF K=2,20,0.0006662542188139442,0.00012644574640822932 +IDFF K=3,2,0.08827868442018214,0.0014740249308344779 +IDFF K=3,3,0.010520566650059663,0.0004415496997063861 +IDFF K=3,5,0.0018892526046815571,0.0003234621489433014 +IDFF K=3,10,0.001114295607163185,0.00017315555425689966 +IDFF K=3,20,0.0006655070070097968,0.00012663721965323587 diff --git a/2D_examples/outputs/8gaussians/mmd_vs_nfe.png b/2D_examples/outputs/8gaussians/mmd_vs_nfe.png new file mode 100644 index 0000000000000000000000000000000000000000..09d67a26b8cdea62e706d0e42ced4dfb982eee28 Binary files /dev/null and b/2D_examples/outputs/8gaussians/mmd_vs_nfe.png differ diff --git a/2D_examples/outputs/8gaussians/samples_grid.png b/2D_examples/outputs/8gaussians/samples_grid.png new file mode 100644 index 0000000000000000000000000000000000000000..cd9f1ddccc1f0b2d950c570555eb2e61a028783d --- /dev/null +++ b/2D_examples/outputs/8gaussians/samples_grid.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a05223ab5c14be46bbf5b4492fd2633ca86439fb1193b17dca1f7282cd648f2f +size 1024983 diff --git a/2D_examples/outputs/checkerboard/config.json b/2D_examples/outputs/checkerboard/config.json new file mode 100644 index 0000000000000000000000000000000000000000..270fc2163b35dfee6e47d1bda643f7883afefdc4 --- /dev/null +++ b/2D_examples/outputs/checkerboard/config.json @@ -0,0 +1,67 @@ +{ + "dataset": "checkerboard", + "iters": 60000, + "batch": 512, + "lr": 0.001, + "sigma0": 0.2, + "coupling": "independent", + "nfes": [ + 2, + 3, + 5, + 10, + 20 + ], + "gamma_c_grid": [ + 0.5, + 1.0, + 2.0, + 4.0, + 8.0, + 16.0, + 32.0 + ], + "alpha_grid": [ + -4.0, + -2.0, + -1.0, + -0.5, + -0.1, + 0.1, + 0.5, + 1.0, + 2.0, + 4.0 + ], + "n_eval": 3000, + "seeds": 5, + "retrain": false, + "out": "2D_examples/outputs", + "selected": { + "2": { + "gamma_bar": 0.25, + "alpha_2": 0.0, + "alpha_3": 0.0 + }, + "3": { + "gamma_bar": 5.333333333333333, + "alpha_2": -2.0, + "alpha_3": -0.1 + }, + "5": { + "gamma_bar": 3.2, + "alpha_2": -2.0, + "alpha_3": -1.0 + }, + "10": { + "gamma_bar": 0.8, + "alpha_2": -2.0, + "alpha_3": -4.0 + }, + "20": { + "gamma_bar": 1.6, + "alpha_2": -2.0, + "alpha_3": -4.0 + } + } +} \ No newline at end of file diff --git a/2D_examples/outputs/checkerboard/idff_model.pt b/2D_examples/outputs/checkerboard/idff_model.pt new file mode 100644 index 0000000000000000000000000000000000000000..3c08d56e162d17ada81903e5ae4b0e0c612d1bb2 --- /dev/null +++ b/2D_examples/outputs/checkerboard/idff_model.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:66d1c2763133bb7f9eeff4fe451acd129198eed1e79b2e8e2b27411fd48ad9fe +size 547619 diff --git a/2D_examples/outputs/checkerboard/mmd_results.csv b/2D_examples/outputs/checkerboard/mmd_results.csv new file mode 100644 index 0000000000000000000000000000000000000000..ca3e1278ae3e69762c171eaef0bbc62c07321b8b --- /dev/null +++ b/2D_examples/outputs/checkerboard/mmd_results.csv @@ -0,0 +1,26 @@ +method,nfe,mmd_mean,mmd_std +CFM (det.),2,0.2188572914624701,0.00490916327914265 +CFM (det.),3,0.07052719676172971,0.0025672184262584136 +CFM (det.),5,0.022546077547576166,0.0015034949908499175 +CFM (det.),10,0.005771681778804588,0.0008082264857641433 +CFM (det.),20,0.00185810589663728,0.0004336497652978774 +Stochastic CFM,2,0.2188572914624701,0.00490916327914265 +Stochastic CFM,3,0.005545994919879787,0.0003217477036535606 +Stochastic CFM,5,0.011346294943048757,0.0002807964622559956 +Stochastic CFM,10,0.004263184462992781,0.00015196296352692262 +Stochastic CFM,20,0.011410351401392854,0.000681996901080064 +IDFF K=1,2,0.2188572914624701,0.00490916327914265 +IDFF K=1,3,0.005166943248355144,0.0004286443328964519 +IDFF K=1,5,0.013127750469622635,0.0009708024676790019 +IDFF K=1,10,0.004630318489455843,0.0008313755802861466 +IDFF K=1,20,0.0019207412642658571,0.00045113105322106814 +IDFF K=2,2,0.2188572914624701,0.00490916327914265 +IDFF K=2,3,0.0053014495526616245,0.00031432502413914534 +IDFF K=2,5,0.008471566731020142,0.0005078231336892195 +IDFF K=2,10,0.003940669550593229,0.0007634695077830026 +IDFF K=2,20,0.0016142686218012681,0.00043464216967364753 +IDFF K=3,2,0.2188572914624701,0.00490916327914265 +IDFF K=3,3,0.005288385350304692,0.0003108534892061196 +IDFF K=3,5,0.008154563054282854,0.0004534677194388744 +IDFF K=3,10,0.0034392033576092994,0.0006619511365712285 +IDFF K=3,20,0.0015245175655409227,0.00038807591117552944 diff --git a/2D_examples/outputs/checkerboard/mmd_vs_nfe.png b/2D_examples/outputs/checkerboard/mmd_vs_nfe.png new file mode 100644 index 0000000000000000000000000000000000000000..95957491d83534ef19fb46ebca11cc5ebcbf2b29 Binary files /dev/null and b/2D_examples/outputs/checkerboard/mmd_vs_nfe.png differ diff --git a/2D_examples/outputs/checkerboard/samples_grid.png b/2D_examples/outputs/checkerboard/samples_grid.png new file mode 100644 index 0000000000000000000000000000000000000000..9f060b22090f0d54fdd47ea50fd68d0391a0b187 --- /dev/null +++ b/2D_examples/outputs/checkerboard/samples_grid.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c9fbfe7f216553e224443d8d2ed1a040fc0c151273c2df29085076e7f47a75ad +size 1016885 diff --git a/2D_examples/outputs/moons/config.json b/2D_examples/outputs/moons/config.json new file mode 100644 index 0000000000000000000000000000000000000000..b451f7468a2a0b01bb391e40bc743ce8ec2160cd --- /dev/null +++ b/2D_examples/outputs/moons/config.json @@ -0,0 +1,67 @@ +{ + "dataset": "moons", + "iters": 60000, + "batch": 512, + "lr": 0.001, + "sigma0": 0.2, + "coupling": "independent", + "nfes": [ + 2, + 3, + 5, + 10, + 20 + ], + "gamma_c_grid": [ + 0.5, + 1.0, + 2.0, + 4.0, + 8.0, + 16.0, + 32.0 + ], + "alpha_grid": [ + -4.0, + -2.0, + -1.0, + -0.5, + -0.1, + 0.1, + 0.5, + 1.0, + 2.0, + 4.0 + ], + "n_eval": 3000, + "seeds": 5, + "retrain": false, + "out": "2D_examples/outputs", + "selected": { + "2": { + "gamma_bar": 0.25, + "alpha_2": 0.0, + "alpha_3": 0.0 + }, + "3": { + "gamma_bar": 2.6666666666666665, + "alpha_2": -4.0, + "alpha_3": 1.0 + }, + "5": { + "gamma_bar": 3.2, + "alpha_2": -2.0, + "alpha_3": -1.0 + }, + "10": { + "gamma_bar": 1.6, + "alpha_2": -2.0, + "alpha_3": -4.0 + }, + "20": { + "gamma_bar": 1.6, + "alpha_2": -2.0, + "alpha_3": -4.0 + } + } +} \ No newline at end of file diff --git a/2D_examples/outputs/moons/idff_model.pt b/2D_examples/outputs/moons/idff_model.pt new file mode 100644 index 0000000000000000000000000000000000000000..1962eda0c883153dede3e3b48834ce36b3efaf9f --- /dev/null +++ b/2D_examples/outputs/moons/idff_model.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bbf85577af98bf26c05489a736f77ad524630289a5f24602c8c0827feb84d30e +size 547253 diff --git a/2D_examples/outputs/moons/mmd_results.csv b/2D_examples/outputs/moons/mmd_results.csv new file mode 100644 index 0000000000000000000000000000000000000000..b6e29ac7bfc2c2515f1a2ae1755aacb3df415bb7 --- /dev/null +++ b/2D_examples/outputs/moons/mmd_results.csv @@ -0,0 +1,26 @@ +method,nfe,mmd_mean,mmd_std +CFM (det.),2,0.22410653579407205,0.006880846596898077 +CFM (det.),3,0.07749838831224833,0.00344215417806067 +CFM (det.),5,0.02514224284439378,0.0017570630054123315 +CFM (det.),10,0.006706524005994185,0.0008233796384715019 +CFM (det.),20,0.0023699601837779416,0.00048571596953232563 +Stochastic CFM,2,0.22410653579407205,0.006880846596898077 +Stochastic CFM,3,0.011972803285579531,0.001692826730553314 +Stochastic CFM,5,0.020956618900112706,0.0012343809499090839 +Stochastic CFM,10,0.014538050884654069,0.0011853329846686581 +Stochastic CFM,20,0.01852075290991318,0.0011641326077654654 +IDFF K=1,2,0.22410653579407205,0.006880846596898077 +IDFF K=1,3,0.01748193841856508,0.001599821822653532 +IDFF K=1,5,0.011726497027321975,0.000935331169924069 +IDFF K=1,10,0.003424801866586147,0.000989061566570685 +IDFF K=1,20,0.0015576914301519197,0.0002964445833506406 +IDFF K=2,2,0.22410653579407205,0.006880846596898077 +IDFF K=2,3,0.009547933922260799,0.0012451935732882766 +IDFF K=2,5,0.0074906257498777605,0.0008030310171046393 +IDFF K=2,10,0.0021999872475188032,0.0006334024334764006 +IDFF K=2,20,0.0011718175166375022,0.000217792740267185 +IDFF K=3,2,0.22410653579407205,0.006880846596898077 +IDFF K=3,3,0.009485082373053389,0.0013233993079878872 +IDFF K=3,5,0.007449597887539444,0.0007582422735597876 +IDFF K=3,10,0.0019417653275533298,0.0005133567380441102 +IDFF K=3,20,0.0011240735688289206,0.00021968238425510887 diff --git a/2D_examples/outputs/moons/mmd_vs_nfe.png b/2D_examples/outputs/moons/mmd_vs_nfe.png new file mode 100644 index 0000000000000000000000000000000000000000..ac8b8c875036ccd6b293533e289a767e481cd364 Binary files /dev/null and b/2D_examples/outputs/moons/mmd_vs_nfe.png differ diff --git a/2D_examples/outputs/moons/samples_grid.png b/2D_examples/outputs/moons/samples_grid.png new file mode 100644 index 0000000000000000000000000000000000000000..7c23485f6fe5db14f7c6fefad18df8941fecbedf --- /dev/null +++ b/2D_examples/outputs/moons/samples_grid.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:80491a5e9b82da91acbef7828fa73ef8c25f62477716fcec28eec3cfdfd652ae +size 587308 diff --git a/README.md b/README.md new file mode 100644 index 0000000000000000000000000000000000000000..4c0c30ed6dab9faf8b7ec11198bb45f42bb7ad26 --- /dev/null +++ b/README.md @@ -0,0 +1,200 @@ +--- +license: other +tags: +- code +- generative-modeling +- flow-matching +- diffusion +- time-series +--- + +> Hugging Face mirror of the GitHub code release +> [`v1.0.0`](https://github.com/MrRezaeiUofT/Implicit_Dynamical_Flow_Fusion_for_Genereative_Modeling/releases/tag/v1.0.0). +> The paper and the trained checkpoints are in [rezapop/IDFF](https://huggingface.co/rezapop/IDFF). + +
+
+
+
+
+
+
+
+
Sampling 8 Gaussians with 5 network evaluations from the same noise and the same trained +network: deterministic CFM (blue), IDFF K=1 (red) and IDFF K=2 (purple), with the hyper-parameters selected +on validation data. Frames between sampler steps are interpolated for display.
+ +Hyper-parameters are selected per NFE budget on a separate validation sample: $\bar\gamma$ for K=1 +(from $c/\mathrm{NFE}$), then $\alpha_2$ for K=2 with the same $\bar\gamma$ ($\alpha_2=0$, i.e. K=1, is +always a candidate). From the same trained network, IDFF K=1 reaches the target distribution in far +fewer steps than deterministic CFM, noise alone (Stochastic CFM) helps only at the smallest budgets, +and the curvature correction (K=2) further improves on K=1 at most budgets. Per-budget test results +for 8gaussians, checkerboard and moons are written to `2D_examples/outputs/
+
+
Autoregressive rollouts over a whole 2000-step held-out Lorenz trajectory at 5 NFE per frame: +CFM (blue), IDFF K=1 (red) and IDFF K=2 (purple), all from one trained network, the same first frame and the +same noise, against the simulated trajectory (grey).
+ +Held-out 2000-step trajectories, test metrics averaged over 10 sampling seeds; $\bar\gamma$ and +$\alpha_2$ are chosen per budget on validation trajectories by how well long rollouts reproduce the +attractor's state distribution. CFM has the lowest one-step and 20-step errors at every budget, while +the long IDFF K=1 rollouts reproduce the attractor's state distribution more closely on average at 5 +and 10 NFE. On this system the curvature correction does not help: validation selects $\alpha_2=0$ +(i.e. K=1) at 3 and 10 NFE, and the value selected at 5 NFE does slightly worse than K=1 on the test +trajectories. See `timeseris_example/outputs/lorenz/results.csv`. + +## Implementation notes + +* **Training objective** (`idff_loss`): $\beta(t)^2\|\hat{\mathbf x}_1-\mathbf x_1\|^2+\sigma_t^2\|\hat s_t+\boldsymbol\epsilon/\sigma_t\|^2$ + with $\sigma_t=\sigma_0\sqrt{t(1-t)}$ and $\beta(t)=(1-t+10^{-2})^{-1}$. By Fisher's identity the score + head converges to $\nabla\log p_t$; `tests/test_idff.py` checks this against the closed-form score on + Gaussian data. The target $-\boldsymbol\epsilon/\sigma_t$ has high variance, so the score head needs + long training (60k iterations in the 2-D example). +* **Sampler time grid.** Step $i$ uses $t_i=i/\mathrm{NFE}$, so exactly NFE network evaluations are made + (K = 2 adds one JVP per step). The final step uses $\gamma=0$; that pure CFM Euler step from + $t=1-\Delta t$ equals the denoiser read-out $\hat{\mathbf x}_1$. +* **Hyper-parameter selection.** Every example selects $\bar\gamma$ (K=1) and then $\alpha_2$ (K=2, + same $\bar\gamma$) per NFE budget on validation data only; test data are never used for tuning. The + sign of $\alpha_k$ is free, and $\alpha_2=0$ is always a candidate. +* **Scale of $\bar\gamma$.** The paper's $\bar\gamma\in[0.1,0.3]$ refers to a unit-variance base $N(0,I)$. + In the time-series models the base is the previous frame plus $N(0,\sigma_0^2 I)$, so $p_t$ has width + $\sim\sigma_0$; the scripts set $\bar\gamma=\gamma_{\rm rel}\,\sigma_0^2$ to keep the Langevin step stable. +* **Velocity field.** $\hat{\mathbf v}_t=(\hat{\mathbf x}_1-\mathbf x_t)/(1-t)$ is the exact marginal + field when $\sigma_0\to0$; for $\sigma_0>0$ it differs from it by $O(\sigma_0^2)$. +* **Smooth activations.** The networks use SiLU written as $x\,\sigma(x)$, which supports the nested + forward-mode JVPs needed for K ≥ 3 (PyTorch's fused SiLU kernel does not). +* The score head output is divided by the local noise scale of $p_t$ (a fixed preconditioner); this + does not change what the head is trained to represent. +* The image-generation experiments of the paper (ScoreSDE / DiT backbones) are not included here. + +## Citation + +``` +@misc{rezaei2025implicitdynamicalflowfusion, + title={Implicit Dynamical Flow Fusion (IDFF) for Generative Modeling}, + author={Mohammad R. Rezaei and Milos R. Popovic and Milad Lankarany and Rahul G. Krishnan}, + year={2025}, + eprint={2409.14599}, + archivePrefix={arXiv}, + primaryClass={cs.LG}, + url={https://arxiv.org/abs/2409.14599}, +} +``` diff --git a/assets/idff_2d.gif b/assets/idff_2d.gif new file mode 100644 index 0000000000000000000000000000000000000000..454ba249a8bdc6b13349398d4b4f1edac429961e --- /dev/null +++ b/assets/idff_2d.gif @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a5a757aef3a62514aba918039c49212c62a5a0ffa774cb20d3f62c736834b2be +size 712475 diff --git a/assets/idff_lorenz.gif b/assets/idff_lorenz.gif new file mode 100644 index 0000000000000000000000000000000000000000..3d8e78266d9e9d280ca29f8ad29fc3d8ecb31d96 --- /dev/null +++ b/assets/idff_lorenz.gif @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ff1e39e4d7f0122417a2281286b9f22616bcdc5d043da19022b14c43e8b08986 +size 3693971 diff --git a/idff/__init__.py b/idff/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6339bc93ad4c8e2885489b241c274b5ad4031f25 --- /dev/null +++ b/idff/__init__.py @@ -0,0 +1,21 @@ +"""Implicit Dynamical Flow Fusion (IDFF): reference implementation of the TMLR paper.""" +from .core import (gamma_schedule, idff_loss, ot_coupling, sample_conditional_path, sequence_training_pairs, + sigma_t) +from .models import JointHeadMLP +from .sampling import contracted_score_derivative, sample, sample_next, sample_sequence + +__version__ = "1.0.0" + +__all__ = [ + "gamma_schedule", + "idff_loss", + "ot_coupling", + "sample_conditional_path", + "sequence_training_pairs", + "sigma_t", + "JointHeadMLP", + "contracted_score_derivative", + "sample", + "sample_next", + "sample_sequence", +] diff --git a/idff/core.py b/idff/core.py new file mode 100644 index 0000000000000000000000000000000000000000..7b285fa65e0db1abff646cc60e087bf36236899d --- /dev/null +++ b/idff/core.py @@ -0,0 +1,125 @@ +"""Probability path, coefficient schedules and the IDFF training objective. + +Equation and section references are to the TMLR paper "Implicit Dynamical Flow Fusion (IDFF) for +Generative Modeling". +""" +import math + +import torch + + +def pad_like(t, x): + """Reshape a scalar or (batch,) time tensor so that it broadcasts against ``x``.""" + if not torch.is_tensor(t): + t = torch.tensor(t, dtype=x.dtype, device=x.device) + if t.dim() == 0: + return t + return t.reshape(-1, *([1] * (x.dim() - 1))) + + +def sigma_t(t, sigma0): + """Standard deviation of the conditional path, sigma_t = sigma0 * sqrt(t (1 - t)) (Eq. ppath).""" + if torch.is_tensor(t): + return sigma0 * torch.sqrt((t * (1.0 - t)).clamp_min(0.0)) + return sigma0 * math.sqrt(max(t * (1.0 - t), 0.0)) + + +def sample_conditional_path(x0, x1, t, sigma0): + """Draw x_t = t x1 + (1 - t) x0 + sigma_t eps with eps ~ N(0, I) (Eq. ppath). + + Returns ``(x_t, eps, sigma_t)`` with ``sigma_t`` broadcastable against ``x1``. + """ + eps = torch.randn_like(x1) + tt = pad_like(t, x1) + st = sigma_t(tt, sigma0) + xt = tt * x1 + (1.0 - tt) * x0 + st * eps + return xt, eps, st + + +def gamma_schedule(t, gamma_bar, shape="beta22"): + """Langevin amplitude gamma_t^1 >= 0, vanishing at t = 0 and t = 1. + + Shapes follow the schedule ablation of the paper (Appendix, "Schedule shape ablation"): + ``beta22`` 4 gamma_bar t (1 - t) (default, Beta(2,2)) + ``triangular`` gamma_bar min(t, 1 - t) + ``sine`` gamma_bar sin(pi t) + ``beta33`` 16 gamma_bar t^2 (1 - t)^2 (peak normalised to gamma_bar) + """ + if shape == "beta22": + return 4.0 * gamma_bar * t * (1.0 - t) + if shape == "triangular": + return gamma_bar * min(t, 1.0 - t) + if shape == "sine": + return gamma_bar * math.sin(math.pi * t) + if shape == "beta33": + return 16.0 * gamma_bar * (t * (1.0 - t)) ** 2 + raise ValueError(f"unknown schedule shape: {shape!r}") + + +def idff_loss(model, x1, x0=None, t=None, sigma0=0.2, beta_eps=1e-2, model_kwargs=None): + """IDFF training objective (Eq. idff_loss). + + beta(t)^2 ||x1_hat(x_t, t) - x1||^2 + lambda_1(t)^2 ||s_hat(x_t, t) + eps / sigma_t||^2, + + with beta(t) = 1 / (1 - t + beta_eps) and lambda_1(t) = sigma_t. The score term regresses the + score head onto the conditional score grad log p_t(x_t | x0, x1) = -eps / sigma_t; by Fisher's + identity its minimiser is the marginal score grad log p_t(x_t). Because lambda_1 = sigma_t, the + term is evaluated in the algebraically identical, numerically stable form ||sigma_t s_hat + eps||^2. + + Args: + model: callable ``model(x_t, t, **model_kwargs) -> (x1_hat, s_hat)``. + x1: data batch. + x0: base samples; defaults to N(0, I) (independent coupling). + t: times in [0, 1], shape (batch,); defaults to U(0, 1). + sigma0: path bandwidth; must be > 0, otherwise the score head receives no signal. + + Returns: + ``(loss, stats)`` where ``stats`` holds the two terms as floats. + """ + if sigma0 <= 0: + raise ValueError("sigma0 must be > 0: with sigma0 = 0 the score target -eps/sigma_t is undefined") + if x0 is None: + x0 = torch.randn_like(x1) + if t is None: + t = torch.rand(x1.shape[0], device=x1.device, dtype=x1.dtype) + xt, eps, st = sample_conditional_path(x0, x1, t, sigma0) + x1_hat, s_hat = model(xt, t, **(model_kwargs or {})) + beta = 1.0 / (1.0 - pad_like(t, x1) + beta_eps) + denoiser = ((beta * (x1_hat - x1)) ** 2).flatten(1).mean(1).mean() + score = ((st * s_hat + eps) ** 2).flatten(1).mean(1).mean() + return denoiser + score, {"denoiser": denoiser.item(), "score": score.item()} + + +def ot_coupling(x0, x1): + """Re-pair a minibatch with the exact optimal-transport plan (squared Euclidean cost). + + This is the minibatch-OT coupling of OT-CFM (Tong et al.), used by the OT-IDFF variant. The score + head remains valid under any coupling (Fisher's identity does not need independence). Requires POT. + """ + from torchcfm.optimal_transport import OTPlanSampler + + return OTPlanSampler(method="exact").sample_plan(x0, x1) + + +def sequence_training_pairs(data, batch_size, sigma0, generator=None): + """Draw a training batch for the time-series model (Algorithm 3, IDFF Training (Time-Series)). + + For position n = 0 the base sample is x0 ~ N(0, I). For n > 0 it is the previous frame, + x0 ~ N(x^{n-1}, sigma0^2 I), matching the Markovian initialisation used at sampling time. + + Args: + data: tensor of shape (num_sequences, length, dim). + + Returns: + ``(x0, x1, n)`` with ``n`` the (batch,) long tensor of positions. + """ + num_seq, length = data.shape[0], data.shape[1] + dev = data.device + seq = torch.randint(num_seq, (batch_size,), device=dev, generator=generator) + n = torch.randint(length, (batch_size,), device=dev, generator=generator) + x1 = data[seq, n] + prev = data[seq, (n - 1).clamp_min(0)] + noise = torch.randn(x1.shape, device=dev, dtype=x1.dtype, generator=generator) + first = (n == 0).reshape(-1, *([1] * (x1.dim() - 1))) + x0 = torch.where(first, noise, prev + sigma0 * noise) + return x0, x1, n diff --git a/idff/datasets.py b/idff/datasets.py new file mode 100644 index 0000000000000000000000000000000000000000..24b5fbe0edf875df65d05e9d0de16adcb35ee589 --- /dev/null +++ b/idff/datasets.py @@ -0,0 +1,103 @@ +"""Datasets used by the examples: 2-D toy distributions, 3-D chaotic attractors and the polyALA MD data.""" +import math +import pickle +from pathlib import Path + +import numpy as np +import torch + + +# ---------------------------------------------------------------------------------------------- +# 2-D toy distributions +# ---------------------------------------------------------------------------------------------- +def eight_gaussians(n, scale=5.0, std=0.1 ** 0.25, generator=None): + """Mixture of 8 Gaussians on a circle of radius ``scale`` (same law as the original torchcfm helper).""" + angles = torch.arange(8) * (2 * math.pi / 8) + centers = scale * torch.stack([torch.cos(angles), torch.sin(angles)], dim=1) + idx = torch.randint(8, (n,), generator=generator) + return centers[idx] + std * torch.randn(n, 2, generator=generator) + + +def checkerboard(n, generator=None): + """Checkerboard on [-4, 4]^2 (same law as the original torchcfm helper).""" + x1 = torch.rand(n, generator=generator) * 4 - 2 + x2_ = torch.rand(n, generator=generator) - torch.randint(0, 2, (n,), generator=generator) * 2 + x2 = x2_ + torch.floor(x1) % 2 + return torch.stack([x1, x2], dim=1) * 2 + + +def moons(n, noise=0.2, generator=None): + """Two interleaving half circles, scaled as x * 3 - 1 like the original torchcfm helper.""" + n_out = n // 2 + n_in = n - n_out + a = torch.rand(n_out, generator=generator) * math.pi + b = torch.rand(n_in, generator=generator) * math.pi + outer = torch.stack([torch.cos(a), torch.sin(a)], dim=1) + inner = torch.stack([1 - torch.cos(b), 0.5 - torch.sin(b)], dim=1) + x = torch.cat([outer, inner], dim=0) + x = x + noise * torch.randn(x.shape, generator=generator) + return x[torch.randperm(n, generator=generator)] * 3 - 1 + + +TOY_DATASETS = {"8gaussians": eight_gaussians, "checkerboard": checkerboard, "moons": moons} + + +# ---------------------------------------------------------------------------------------------- +# 3-D chaotic attractors (Appendix "3D Attractors") +# ---------------------------------------------------------------------------------------------- +def _lorenz(state, sigma=10.0, rho=28.0, beta=8.0 / 3.0): + x, y, z = state[..., 0], state[..., 1], state[..., 2] + return np.stack([sigma * (y - x), x * (rho - z) - y, x * y - beta * z], axis=-1) + + +def _rossler(state, a=0.2, b=0.2, c=5.7): + x, y, z = state[..., 0], state[..., 1], state[..., 2] + return np.stack([-y - z, x + a * y, b + z * (x - c)], axis=-1) + + +def attractor_trajectories(system, num_traj, length, dt=None, stride=None, burn_in=2000, seed=0): + """Simulate ``num_traj`` trajectories of ``length`` frames with RK4. + + ``system`` is ``"lorenz"`` (sigma=10, rho=28, beta=8/3) or ``"rossler"`` (a=b=0.2, c=5.7), the + parameters used in the paper. Returns an array of shape (num_traj, length, 3). + """ + f = {"lorenz": _lorenz, "rossler": _rossler}[system] + dt = dt if dt is not None else {"lorenz": 0.01, "rossler": 0.05}[system] + stride = stride if stride is not None else {"lorenz": 2, "rossler": 2}[system] + rng = np.random.default_rng(seed) + state = rng.normal(size=(num_traj, 3)) + (np.array([0.0, 0.0, 25.0]) if system == "lorenz" else 0.0) + + def step(s): + k1 = f(s) + k2 = f(s + 0.5 * dt * k1) + k3 = f(s + 0.5 * dt * k2) + k4 = f(s + dt * k3) + return s + dt / 6.0 * (k1 + 2 * k2 + 2 * k3 + k4) + + for _ in range(burn_in): + state = step(state) + out = np.empty((num_traj, length, 3)) + for i in range(length): + out[:, i] = state + for _ in range(stride): + state = step(state) + return out + + +# ---------------------------------------------------------------------------------------------- +# polyALA molecular dynamics (Sec. "Surrogate Models for Molecular Dynamics") +# ---------------------------------------------------------------------------------------------- +def load_polyala_angles(path): + """Load the polyALA dihedral-angle trajectory, shape (frames, 46), in degrees. + + Accepts the compact ``.npz`` shipped with the repository (key ``angles``) or the original + simulation pickle (``data['angles'][1]`` reshaped to (sim_length, -1), as in the original script). + """ + path = Path(path) + if not path.exists(): + raise FileNotFoundError(f"MD dataset not found: {path}") + if path.suffix == ".npz": + return np.load(path)["angles"].astype(np.float64) + with open(path, "rb") as fh: + data = pickle.load(fh) # trusted local simulation output + return np.asarray(data["angles"][1]).reshape(data["sim_length"], -1).astype(np.float64) diff --git a/idff/metrics.py b/idff/metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..77db17f1e1585afd81f461e0098f5a3dd2181c6f --- /dev/null +++ b/idff/metrics.py @@ -0,0 +1,52 @@ +"""Evaluation metrics used by the examples.""" +import numpy as np +import torch + + +def mmd_rbf(x, y, bandwidth=1.0): + """Biased (V-statistic) squared MMD between samples x and y with a Gaussian RBF kernel.""" + x = torch.as_tensor(x, dtype=torch.float64) + y = torch.as_tensor(y, dtype=torch.float64) + + def k(a, b): + return torch.exp(-torch.cdist(a, b) ** 2 / (2 * bandwidth ** 2)) + + return (k(x, x).mean() + k(y, y).mean() - 2 * k(x, y).mean()).item() + + +def wrap_degrees(d): + """Map angle differences to (-180, 180].""" + return (np.asarray(d) + 180.0) % 360.0 - 180.0 + + +def trajectory_metrics(generated, true, angles=False): + """MAE, RMSE and correlation coefficient between generated and true trajectories. + + Args: + generated: array (length, num_samples, dim). + true: array (length, dim). + angles: if True, errors use the wrapped angular difference (degrees). + + Metrics are computed per (sample, dimension) series and averaged, as in the paper's MD table. + """ + generated = np.asarray(generated) + true = np.asarray(true) + err = generated - true[:, None, :] + if angles: + err = wrap_degrees(err) + mae = np.abs(err).mean(axis=0) + rmse = np.sqrt((err ** 2).mean(axis=0)) + cc = np.full(mae.shape, np.nan) + for s in range(generated.shape[1]): + for j in range(generated.shape[2]): + g, r = generated[:, s, j], true[:, j] + if g.std() > 0 and r.std() > 0: + cc[s, j] = np.corrcoef(g, r)[0, 1] + out = {"MAE": float(mae.mean()), "MAE_std": float(mae.mean(1).std()), + "RMSE": float(rmse.mean()), "RMSE_std": float(rmse.mean(1).std()), + "CC": float("nan"), "CC_std": float("nan")} + if np.isfinite(cc).any(): + per_sample = np.array([np.nanmean(row) if np.isfinite(row).any() else np.nan for row in cc]) + out["CC"] = float(np.nanmean(cc)) + out["CC_std"] = float(np.nanstd(per_sample)) + return out diff --git a/idff/models.py b/idff/models.py new file mode 100644 index 0000000000000000000000000000000000000000..32ec49745100cc2dddf4d692079a4be379c100f0 --- /dev/null +++ b/idff/models.py @@ -0,0 +1,101 @@ +"""Joint-head networks for IDFF. + +A single trunk feeds two linear heads: the denoiser x1_hat(x_t, t) and the score s_hat(x_t, t) +(paper, Sec. "Sample-Based Vector Field Learning"). SiLU activations keep the score smooth, so the +Jacobian used by the K >= 2 correction is well defined (ReLU networks are not suitable for K >= 2). +""" +import math + +import torch +from torch import nn + + +class SiLU(nn.Module): + """SiLU written as x * sigmoid(x). + + Mathematically identical to ``torch.nn.SiLU``, but built from primitives that support nested + forward-mode differentiation, which the K >= 3 contracted derivatives require (the fused + ``aten::silu`` kernel does not support forward-over-forward AD). + """ + + def forward(self, x): + return x * torch.sigmoid(x) + + +class TimeFeatures(nn.Module): + """Fourier features of the flow time t: [t, sin(2 pi k t), cos(2 pi k t)] for k = 1..n_freq.""" + + def __init__(self, n_freq=4): + super().__init__() + self.register_buffer("freqs", 2.0 * math.pi * torch.arange(1, n_freq + 1).float()) + self.out_dim = 1 + 2 * n_freq + + def forward(self, t): + ang = t[:, None] * self.freqs[None] + return torch.cat([t[:, None], torch.sin(ang), torch.cos(ang)], dim=-1) + + +class JointHeadMLP(nn.Module): + """MLP with a shared trunk and two heads, returning ``(x1_hat, s_hat)``. + + Args: + dim: data dimension. + hidden, depth: trunk width and number of hidden layers. + sigma0: path bandwidth used in training (needed for the score preconditioner). + base_std: std of the base distribution x0 around its mean (1 for N(0, I)). + num_positions: if given, adds a learned embedding of the sequence position n + (dual-time indexing for time series: t is the flow time, n the sequence position). + base_std_first: base std at position n = 0 when ``num_positions`` is set (x0 ~ N(0, I) there). + residual: if True, x1_hat = x_t + head(x_t, t); convenient for time series where + consecutive frames are close. It changes only the parameterisation, not the objective. + score_floor: floor of the score preconditioner. + + The score head is preconditioned as s_hat = h_s / c(t) with + c(t) = sqrt(b^2 (1 - t)^2 + sigma_t^2 + floor^2), the local noise scale of p_t. This rescales + the head output only; the head is still trained to the marginal score by the IDFF objective. + """ + + def __init__(self, dim, hidden=256, depth=3, sigma0=0.2, base_std=1.0, num_positions=None, + base_std_first=1.0, residual=False, n_freq=4, pos_dim=64, score_floor=1e-2): + super().__init__() + self.dim = dim + self.sigma0 = float(sigma0) + self.base_std = float(base_std) + self.base_std_first = float(base_std_first) + self.residual = residual + self.score_floor = float(score_floor) + self.time = TimeFeatures(n_freq) + in_dim = dim + self.time.out_dim + self.pos = None + if num_positions is not None: + self.pos = nn.Embedding(num_positions, pos_dim) + in_dim += pos_dim + layers = [nn.Linear(in_dim, hidden), SiLU()] + for _ in range(depth - 1): + layers += [nn.Linear(hidden, hidden), SiLU()] + self.trunk = nn.Sequential(*layers) + self.head_x1 = nn.Linear(hidden, dim) + self.head_score = nn.Linear(hidden, dim) + + def forward(self, x, t, n=None): + batch = x.shape[0] + if not torch.is_tensor(t): + t = torch.tensor(float(t), device=x.device, dtype=x.dtype) + t = t.to(dtype=x.dtype).reshape(-1) + if t.numel() == 1: + t = t.expand(batch) + feats = [x.reshape(batch, -1), self.time(t)] + if self.pos is not None: + if n is None: + raise ValueError("this model was built with num_positions; pass the sequence position n") + feats.append(self.pos(n.long())) + h = self.trunk(torch.cat(feats, dim=-1)) + x1_hat = self.head_x1(h) + if self.residual: + x1_hat = x.reshape(batch, -1) + x1_hat + b = torch.full_like(t, self.base_std) + if self.pos is not None: + b = torch.where(n.reshape(-1) == 0, torch.full_like(t, self.base_std_first), b) + var = (b * (1.0 - t)) ** 2 + self.sigma0 ** 2 * t * (1.0 - t) + self.score_floor ** 2 + s_hat = self.head_score(h) / torch.sqrt(var)[:, None] + return x1_hat.reshape_as(x), s_hat.reshape_as(x) diff --git a/idff/sampling.py b/idff/sampling.py new file mode 100644 index 0000000000000000000000000000000000000000..9061594b61600512b926bee5e24d7fe4299548ab --- /dev/null +++ b/idff/sampling.py @@ -0,0 +1,135 @@ +"""IDFF samplers: Algorithm 1 (static data) and Algorithm 4 (time series) of the paper.""" +import math + +import torch +from torch.func import jvp + +from .core import gamma_schedule + + +def contracted_score_derivative(score_fn, x, u, order): + """Return (grad_x^order s)(x)[u]^order, i.e. the contracted term m^(order + 1) of Eq. momentum_contraction. + + ``order = 1`` gives the Hessian-vector product (grad_x s) u used at K = 2. Higher orders are + obtained by nesting forward-mode JVPs, so no tensor of order > 1 is ever formed. + """ + f = score_fn + for _ in range(order): + f = _directional_derivative(f, u) + return f(x) + + +def _directional_derivative(f, u): + def g(y): + return jvp(f, (y,), (u,))[1] + return g + + +def _unit(v): + norm = v.reshape(v.shape[0], -1).norm(dim=1).clamp_min(1e-12) + return v / norm.reshape(-1, *([1] * (v.dim() - 1))) + + +@torch.no_grad() +def sample(model, x0, nfe, K=1, gamma_bar=0.2, alphas=None, schedule="beta22", diffusion_scale=2.0, + score_drift=True, model_kwargs=None, generator=None, return_trajectory=False): + """Integrate the IDFF SDE (Eq. idff_sde) with Euler-Maruyama (Algorithm 1). + + dx = [gamma_t^0 v_hat + gamma_t^1 m^(1) + sum_{k=2..K} gamma_t^k m^(k)] dt + g_t dW, + + with v_hat = (x1_hat - x) / (1 - t), m^(1) = s_hat, m^(k) = (grad^{k-1} s_hat)[u]^{k-1}, + u = v_hat / ||v_hat||, gamma_t^0 = 1 (the paper's default), gamma_t^1 from ``schedule``, + gamma_t^k = alpha_k gamma_t^1 dt^(k-1) for k >= 2, and g_t^2 = diffusion_scale * gamma_t^1. + + The defaults (K = 1, diffusion_scale = 2, score_drift = True) are the configuration whose + continuous-time marginals equal the CFM marginals exactly (Theorem first_order_preservation). + Other settings reproduce the ablations: ``K=0`` or ``gamma_bar=0`` is the deterministic CFM + sampler, ``score_drift=False`` is "Stochastic CFM" (noise without the score drift), and + ``diffusion_scale=0`` is the score drift without diffusion compensation. + + Time grid: step i uses t_i = i / nfe, so exactly ``nfe`` network evaluations are made (K >= 2 + adds one JVP per step and order). The coefficients are set to zero on the final step, as the + paper prescribes, so the last update is a pure CFM Euler step from t = 1 - dt; that step equals + the denoiser read-out x1_hat(x, 1 - dt), which is what is returned. + + Args: + model: ``model(x, t, **model_kwargs) -> (x1_hat, s_hat)``. + x0: initial samples (N(0, I) for static data). + nfe: number of network evaluations (= Euler-Maruyama steps). + alphas: dict {k: alpha_k} for k >= 2; defaults to 0.05 for every order. + generator: optional torch.Generator for the Brownian increments. + return_trajectory: also return the stacked iterates, shape (nfe + 1, *x0.shape). + """ + if nfe < 1: + raise ValueError("nfe must be >= 1") + alphas = alphas or {} + model_kwargs = model_kwargs or {} + dt = 1.0 / nfe + x = x0.clone() + traj = [x] if return_trajectory else None + for i in range(nfe): + t = i * dt + tb = torch.full((x.shape[0],), t, device=x.device, dtype=x.dtype) + x1_hat, s_hat = model(x, tb, **model_kwargs) + if i == nfe - 1: + x = x1_hat + else: + v = (x1_hat - x) / (1.0 - t) + g1 = gamma_schedule(t, gamma_bar, schedule) if K >= 1 else 0.0 + drift = v + if g1 > 0 and score_drift: + drift = drift + g1 * s_hat + if K >= 2 and g1 > 0: + u = _unit(v) + + def score_fn(y, tb=tb): + return model(y, tb, **model_kwargs)[1] + + for k in range(2, K + 1): + gk = alphas.get(k, 0.05) * g1 * dt ** (k - 1) + drift = drift + gk * contracted_score_derivative(score_fn, x, u, k - 1) + x = x + drift * dt + if g1 > 0 and diffusion_scale > 0: + noise = torch.randn(x.shape, device=x.device, dtype=x.dtype, generator=generator) + x = x + math.sqrt(diffusion_scale * g1 * dt) * noise + if return_trajectory: + traj.append(x) + if return_trajectory: + return x, torch.stack(traj) + return x + + +@torch.no_grad() +def sample_next(model, prev, n, nfe, sigma0, generator=None, **sampler_kwargs): + """Sample frame n given frame n-1 (one step of Algorithm 4): x0^n ~ N(prev, sigma0^2 I).""" + noise = torch.randn(prev.shape, device=prev.device, dtype=prev.dtype, generator=generator) + x0 = prev + sigma0 * noise + nb = torch.full((prev.shape[0],), n, device=prev.device, dtype=torch.long) + return sample(model, x0, nfe, model_kwargs={"n": nb}, generator=generator, **sampler_kwargs) + + +@torch.no_grad() +def sample_sequence(model, length, num_samples, dim, nfe, sigma0, first_frame=None, device="cpu", + generator=None, **sampler_kwargs): + """Autoregressive time-series sampling (Algorithm 4, IDFF Sampling (Time-Series)). + + Position 0 starts from N(0, I) unless ``first_frame`` is given (shape (dim,) shared by all + samples, or (num_samples, dim) one per sample), in which case the rollout is conditioned on it and + continues from position 1. Each later position starts from the previous generated frame, + x0^n ~ N(x1^{n-1}, sigma0^2 I). + + Returns: + tensor of shape (length, num_samples, dim). + """ + frames = [] + if first_frame is None: + x0 = torch.randn((num_samples, dim), device=device, generator=generator) + nb = torch.zeros(num_samples, device=device, dtype=torch.long) + prev = sample(model, x0, nfe, model_kwargs={"n": nb}, generator=generator, **sampler_kwargs) + else: + prev = first_frame.to(device).expand(num_samples, dim).clone() + frames.append(prev) + for n in range(1, length): + prev = sample_next(model, prev, n, nfe, sigma0, generator=generator, **sampler_kwargs) + frames.append(prev) + return torch.stack(frames) diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..3c64e733b0b8138ded9b19d264fb0edaba65b42b --- /dev/null +++ b/requirements.txt @@ -0,0 +1,5 @@ +torch>=2.1 +numpy +scipy +matplotlib +pot # optional: minibatch-OT coupling (OT-IDFF) via torchcfm.optimal_transport diff --git a/scripts/make_gifs.py b/scripts/make_gifs.py new file mode 100644 index 0000000000000000000000000000000000000000..49bd89958833921691118495f0d485590bbfa927 --- /dev/null +++ b/scripts/make_gifs.py @@ -0,0 +1,176 @@ +"""Render the README animations from the trained example models. + + python scripts/make_gifs.py + +Requires the checkpoints written by ``2D_examples/idff_2d.py --dataset 8gaussians`` and +``timeseris_example/attractors.py --system lorenz``. Outputs ``assets/idff_2d.gif`` and +``assets/idff_lorenz.gif``. + +2-D animation: CFM (deterministic), IDFF K=1 and IDFF K=2 at NFE = 5 share one trained network +and start from the same noise; frames between two sampler +steps are straight-line interpolations for display only. +""" +import json +import sys +from pathlib import Path + +import matplotlib + +matplotlib.use("Agg") +import matplotlib.pyplot as plt # noqa: E402 +import numpy as np # noqa: E402 +import torch # noqa: E402 +from matplotlib.animation import FuncAnimation, PillowWriter # noqa: E402 + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) + +from idff import JointHeadMLP, sample, sample_sequence # noqa: E402 +from idff.datasets import TOY_DATASETS, attractor_trajectories # noqa: E402 + +ASSETS = ROOT / "assets" + + +def load(path, **kwargs): + model = JointHeadMLP(**kwargs) + model.load_state_dict(torch.load(path, map_location="cpu", weights_only=True)) + return model.eval() + + +COLORS = {"CFM (det.)": "tab:blue", "IDFF K=1": "tab:red", "IDFF K=2": "tab:purple"} + + +def gif_2d(dataset="8gaussians", nfes=(5,), n=1500, n_frames=40, hold=14): + """Rows: NFE budgets. Columns: CFM, IDFF K=1, IDFF K=2 (alpha_2 as selected by 2D_examples/idff_2d.py). + + NFE = 2 is not shown: gamma_t^1 vanishes at t = 0 and the coefficients are switched off on the final + step, so with two steps every sampler coincides with CFM. Test MMDs are in the README table. + """ + out = ROOT / "2D_examples" / "outputs" / dataset + cfg = json.loads((out / "config.json").read_text()) + model = load(out / "idff_model.pt", dim=2, hidden=256, depth=3, sigma0=cfg["sigma0"]) + torch.manual_seed(3) + data = TOY_DATASETS[dataset](4000).numpy() + grid = [] + for nfe in nfes: + sel = cfg["selected"][str(nfe)] # chosen per budget on validation data by idff_2d.py + gamma, a2 = sel["gamma_bar"], sel["alpha_2"] + row = [] + for label, kw in [("CFM (det.)", dict(K=0)), + ("IDFF K=1", dict(K=1, gamma_bar=gamma)), + ("IDFF K=2", dict(K=2, gamma_bar=gamma, alphas={2: a2}))]: + x0 = torch.randn(n, 2, generator=torch.Generator().manual_seed(0)) + _, traj = sample(model, x0, nfe, generator=torch.Generator().manual_seed(100), + return_trajectory=True, **kw) + row.append((label if label != "IDFF K=2" else f"IDFF K=2 (alpha_2={a2:g})", traj.numpy())) + grid.append((nfe, row)) + + taus = np.concatenate([np.linspace(0, 1, n_frames), np.ones(hold)]) + fig, axs = plt.subplots(len(nfes), 3, figsize=(9.6, 3.35 * len(nfes) + 0.35), squeeze=False) + lim = np.abs(data).max() + 1.0 + scats = [] + for r, (nfe, row) in enumerate(grid): + for c, (label, traj) in enumerate(row): + ax = axs[r, c] + ax.scatter(data[:, 0], data[:, 1], s=1, c="0.82", rasterized=True) + sc = ax.scatter(traj[0, :, 0], traj[0, :, 1], s=1.5, c=COLORS[label.split(" (alpha")[0]], alpha=0.6) + ax.set_xlim(-lim, lim) + ax.set_ylim(-lim, lim) + ax.set_xticks([]) + ax.set_yticks([]) + ax.set_title(f"{label}\nNFE={nfe}", fontsize=9) + scats.append((sc, traj, nfe)) + title = fig.suptitle("", fontsize=11) + fig.tight_layout(rect=(0, 0, 1, 0.965)) + + def update(k): + tau = taus[k] + for sc, traj, nfe in scats: + s = tau * nfe + i = min(int(np.floor(s)), nfe - 1) + a = s - i + sc.set_offsets((1 - a) * traj[i] + a * traj[i + 1]) + title.set_text(f"{dataset}: sampling from noise to data t = {tau:.2f} (grey: data)") + return [s for s, _, _ in scats] + [title] + + anim = FuncAnimation(fig, update, frames=len(taus), blit=False) + path = ASSETS / "idff_2d.gif" + anim.save(path, writer=PillowWriter(fps=12), dpi=65) + plt.close(fig) + return path + + +def gif_lorenz(nfe=5, n_frames=100): + """CFM, IDFF K=1 and IDFF K=2 rollouts over a whole held-out Lorenz trajectory, all sharing one + trained network, started from the same first frame with the same noise seed. gamma_bar and alpha_2 + are those selected per budget on the validation trajectories by timeseris_example/attractors.py.""" + systems = ["lorenz"] + panels = [] + for system in systems: + out = ROOT / "timeseris_example" / "outputs" / system + cfg = json.loads((out / "config.json").read_text()) + n_train, n_val, n_test = cfg["n_train"], cfg["n_val"], cfg["n_test"] + raw = attractor_trajectories(system, n_train + n_val + n_test, cfg["length"], seed=0) + train = raw[:n_train] + mean, std = train.reshape(-1, 3).mean(0), train.reshape(-1, 3).std(0) + true = raw[n_train + n_val] # first held-out test trajectory + model = load(out / "idff_model.pt", dim=3, hidden=128, depth=2, sigma0=cfg["sigma0"], + base_std=cfg["sigma0"], num_positions=cfg["length"], residual=True) + first = torch.tensor((true[0] - mean) / std, dtype=torch.float32) + sel = cfg["selected"][str(nfe)] # chosen per budget on validation trajectories + g = sel["gamma_bar"] + for label, kw in [("CFM (det.)", dict(K=0)), + ("IDFF K=1", dict(K=1, gamma_bar=g)), + ("IDFF K=2", dict(K=2, gamma_bar=g, alphas={2: sel["alpha_2"]}))]: + gen = sample_sequence(model, cfg["length"], 1, 3, nfe, cfg["sigma0"], first_frame=first, + generator=torch.Generator().manual_seed(0), **kw) + gen = gen[:, 0].numpy() * std + mean + name = label if label != "IDFF K=2" else f"IDFF K=2 (alpha_2={sel['alpha_2']:g})" + panels.append((system, label, name, true, gen)) + length = len(panels[0][3]) + + fig = plt.figure(figsize=(11.4, 3.9)) + axes, lines = [], [] + for j, (system, label, name, true, gen) in enumerate(panels): + color = COLORS[label] + ax = fig.add_subplot(1, 3, j + 1, projection="3d") + ax.plot(*true.T, c="0.6", lw=0.5, alpha=0.6) + (line,) = ax.plot([], [], [], c=color, lw=0.9) + (head,) = ax.plot([], [], [], "o", c=color, ms=3) + lo, hi = np.minimum(true.min(0), gen.min(0)), np.maximum(true.max(0), gen.max(0)) + ax.set_xlim(lo[0], hi[0]) + ax.set_ylim(lo[1], hi[1]) + ax.set_zlim(lo[2], hi[2]) + ax.set_xticklabels([]) + ax.set_yticklabels([]) + ax.set_zticklabels([]) + ax.set_title(f"{name}\nNFE={nfe}", fontsize=9) + axes.append(ax) + lines.append((line, head, gen)) + title = fig.suptitle("", fontsize=10) + fig.tight_layout(rect=(0, 0, 1, 0.86)) + steps = np.linspace(2, length, n_frames).astype(int) + + def update(k): + m = steps[min(k, len(steps) - 1)] + for ax, (line, head, gen) in zip(axes, lines): + line.set_data(gen[:m, 0], gen[:m, 1]) + line.set_3d_properties(gen[:m, 2]) + head.set_data(gen[m - 1:m, 0], gen[m - 1:m, 1]) + head.set_3d_properties(gen[m - 1:m, 2]) + ax.view_init(elev=22, azim=-65 + 0.3 * k) + title.set_text(f"Lorenz: autoregressive rollout from a held-out first frame, step {m}/{length} " + "(grey: simulated trajectory)") + return [x for ln in lines for x in ln[:2]] + + anim = FuncAnimation(fig, update, frames=n_frames + 12, blit=False) + path = ASSETS / "idff_lorenz.gif" + anim.save(path, writer=PillowWriter(fps=12), dpi=62) + plt.close(fig) + return path + + +if __name__ == "__main__": + ASSETS.mkdir(exist_ok=True) + for p in (gif_2d(), gif_lorenz()): + print(f"wrote {p} ({p.stat().st_size / 1e6:.2f} MB)") diff --git a/tests/test_idff.py b/tests/test_idff.py new file mode 100644 index 0000000000000000000000000000000000000000..663d37944a0e85f9189d0432a2a70f9174d40df8 --- /dev/null +++ b/tests/test_idff.py @@ -0,0 +1,259 @@ +"""Tests for the IDFF reference implementation. + +Besides unit tests, two tests check the paper's theory numerically on Gaussian data, where every +quantity is available in closed form: +* Theorem first_order_preservation: the K = 1 sampler with g_t^2 = 2 gamma_t^1 and the exact score + reproduces the CFM marginals, while mismatched diffusion does not. +* Fisher's identity: the score head trained with the IDFF objective converges to the marginal score. +""" +import math +import sys +from pathlib import Path + +import numpy as np +import pytest +import torch + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from idff import (JointHeadMLP, contracted_score_derivative, gamma_schedule, idff_loss, # noqa: E402 + sample, sample_next, sample_sequence, sequence_training_pairs, sigma_t) +from idff.datasets import TOY_DATASETS, attractor_trajectories # noqa: E402 +from idff.metrics import mmd_rbf, trajectory_metrics, wrap_degrees # noqa: E402 + +M = torch.tensor([1.0, -2.0]) # data mean for the Gaussian tests +S = 0.5 # data std + + +class GaussianOracle(torch.nn.Module): + """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.""" + + def __init__(self, sigma0=0.0): + super().__init__() + self.sigma0 = sigma0 + + def variance(self, t): + return t ** 2 * S ** 2 + (1 - t) ** 2 + self.sigma0 ** 2 * t * (1 - t) + + def forward(self, x, t): + t = t.reshape(-1, 1) + var = self.variance(t) + x1_hat = M + (t * S ** 2 / var) * (x - t * M) + score = -(x - t * M) / var + return x1_hat, score + + +# -------------------------------------------------------------------------------------------- +# Unit tests +# -------------------------------------------------------------------------------------------- +def test_sigma_and_schedules_vanish_at_endpoints(): + assert sigma_t(0.0, 0.3) == 0.0 and sigma_t(1.0, 0.3) == 0.0 + assert math.isclose(sigma_t(0.5, 0.2), 0.1) + for shape in ["beta22", "triangular", "sine", "beta33"]: + assert gamma_schedule(0.0, 0.7, shape) == pytest.approx(0.0, abs=1e-12) + assert gamma_schedule(1.0, 0.7, shape) == pytest.approx(0.0, abs=1e-12) + assert gamma_schedule(0.5, 0.7, shape) > 0 + assert gamma_schedule(0.5, 0.7, "beta22") == pytest.approx(0.7) + + +def test_loss_matches_manual_computation(): + torch.manual_seed(0) + model = JointHeadMLP(2, hidden=16, depth=2, sigma0=0.3) + x1, x0, t = torch.randn(64, 2), torch.randn(64, 2), torch.rand(64) + torch.manual_seed(1) + loss, stats = idff_loss(model, x1, x0=x0, t=t, sigma0=0.3) + torch.manual_seed(1) + eps = torch.randn_like(x1) + st = 0.3 * torch.sqrt(t * (1 - t))[:, None] + xt = t[:, None] * x1 + (1 - t[:, None]) * x0 + st * eps + x1_hat, s_hat = model(xt, t) + beta = 1 / (1 - t[:, None] + 1e-2) + manual = ((beta * (x1_hat - x1)) ** 2).mean() + (st ** 2 * (s_hat + eps / st) ** 2).mean() + assert loss.item() == pytest.approx(manual.item(), rel=1e-5) + with pytest.raises(ValueError): + idff_loss(model, x1, sigma0=0.0) + + +def test_contracted_derivatives_match_closed_form(): + torch.manual_seed(0) + a = torch.randn(3, 3) + + def score(y): # linear part plus elementwise cubic: derivatives known in closed form + return y @ a.T + 0.3 * y ** 3 + + x, u = torch.randn(5, 3), torch.randn(5, 3) + m2 = contracted_score_derivative(score, x, u, 1) + m3 = contracted_score_derivative(score, x, u, 2) + m4 = contracted_score_derivative(score, x, u, 3) + torch.testing.assert_close(m2, u @ a.T + 0.9 * x ** 2 * u) + torch.testing.assert_close(m3, 1.8 * x * u ** 2) + torch.testing.assert_close(m4, 1.8 * u ** 3) + + +def test_network_evaluation_count_and_determinism(): + class Counting(torch.nn.Module): + def __init__(self): + super().__init__() + self.calls = 0 + self.net = JointHeadMLP(2, hidden=16, depth=2) + + def forward(self, x, t): + self.calls += 1 + return self.net(x, t) + + model = Counting() + x0 = torch.randn(8, 2) + for nfe in [1, 2, 5]: + model.calls = 0 + sample(model, x0, nfe, K=1) + assert model.calls == nfe + model.calls = 0 + sample(model, x0, 6, K=2) + assert model.calls == 6 + 4 # one JVP on every step with gamma_t^1 > 0 (all but the first and last) + a = sample(model, x0, 5, K=0, generator=torch.Generator().manual_seed(0)) + b = sample(model, x0, 5, K=0, generator=torch.Generator().manual_seed(1)) + torch.testing.assert_close(a, b) + + +def test_sequence_training_pairs(): + data = torch.arange(2 * 5 * 3, dtype=torch.float32).reshape(2, 5, 3) + torch.manual_seed(0) + x0, x1, n = sequence_training_pairs(data, 512, sigma0=1e-3) + for i in range(len(n)): + k = n[i].item() + seq = [s for s in range(2) if torch.equal(x1[i], data[s, k])] + assert len(seq) == 1 # x1 is a data frame at position n + if k > 0: # x0 ~ N(x^{n-1}, sigma0^2 I) for the same sequence + assert (x0[i] - data[seq[0], k - 1]).abs().max() < 0.01 + assert x0[n == 0].std() > 0.5 # position 0 starts from N(0, I) + + +def test_ot_coupling_shortens_pairs(): + pytest.importorskip("ot") + from idff import ot_coupling + + torch.manual_seed(0) + x0, x1 = torch.randn(256, 2), TOY_DATASETS["8gaussians"](256) + p0, p1 = ot_coupling(x0, x1) + assert p0.shape == x0.shape and p1.shape == x1.shape + assert ((p1 - p0) ** 2).sum(1).mean() < 0.6 * ((x1 - x0) ** 2).sum(1).mean() + # N(0, I) -> N(m, I): W2^2 = |m|^2 = 18, while independent pairing costs |m|^2 + 2d = 22 + x0, x1 = torch.randn(512, 2), torch.randn(512, 2) + 3.0 + p0, p1 = ot_coupling(x0, x1) + assert abs(((p1 - p0) ** 2).sum(1).mean().item() - 18.0) < 2.0 + + +def test_metrics(): + assert wrap_degrees(350.0) == pytest.approx(-10.0) + true = np.stack([np.linspace(0, 10, 50), np.linspace(0, -5, 50)], 1) + m = trajectory_metrics(true[:, None, :], true) + assert m["MAE"] == 0 and m["RMSE"] == 0 and m["CC"] == pytest.approx(1.0) + m = trajectory_metrics(np.full((3, 1, 1), 179.0), np.full((3, 1), -179.0), angles=True) + assert m["MAE"] == pytest.approx(2.0) + x = torch.randn(300, 2) + assert mmd_rbf(x, x) == pytest.approx(0.0, abs=1e-12) + assert mmd_rbf(x, x + 3.0) > 0.1 + + +# -------------------------------------------------------------------------------------------- +# Theory checks on Gaussian data +# -------------------------------------------------------------------------------------------- +@pytest.mark.parametrize("gamma_bar", [0.0, 1.0]) +def test_k1_sampler_preserves_marginals_with_exact_score(gamma_bar): + """Theorem first_order_preservation: Langevin drift + matched diffusion leaves p_t unchanged. + + With sigma0 = 0 the velocity (x1_hat - x)/(1 - t) is the exact marginal field, so the only + errors are Euler-Maruyama discretisation and Monte-Carlo noise. + """ + torch.manual_seed(0) + oracle = GaussianOracle(sigma0=0.0) + nfe, n = 400, 40000 + x, traj = sample(oracle, torch.randn(n, 2), nfe, K=1, gamma_bar=gamma_bar, return_trajectory=True) + torch.testing.assert_close(x.mean(0), M, atol=0.02, rtol=0) + assert x.var(0).sub(S ** 2).abs().max() < 0.03 * S ** 2 + mid = traj[nfe // 2] # t = 0.5 + var_mid = oracle.variance(torch.tensor(0.5)).item() + torch.testing.assert_close(mid.mean(0), 0.5 * M, atol=0.02, rtol=0) + assert mid.var(0).sub(var_mid).abs().max() < 0.03 * var_mid + + +def test_mismatched_diffusion_breaks_preservation(): + """The cancellation needs g_t^2 = 2 gamma_t^1: dropping the noise shrinks the variance, and noise + without the score drift inflates it.""" + torch.manual_seed(0) + oracle = GaussianOracle(sigma0=0.0) + x0 = torch.randn(40000, 2) + no_noise = sample(oracle, x0, 400, K=1, gamma_bar=1.0, diffusion_scale=0.0) + noise_only = sample(oracle, x0, 400, K=1, gamma_bar=1.0, score_drift=False) + assert no_noise.var(0).max() < 0.85 * S ** 2 + assert noise_only.var(0).min() > 1.15 * S ** 2 + + +def test_score_head_learns_marginal_score(): + """Fisher's identity: regressing on -eps/sigma_t yields grad log p_t (and the denoiser E[x1 | x_t]).""" + torch.manual_seed(0) + sigma0 = 0.5 + model = JointHeadMLP(2, hidden=128, depth=3, sigma0=sigma0) + opt = torch.optim.Adam(model.parameters(), lr=2e-3) + for _ in range(3000): + x1 = M + S * torch.randn(1024, 2) + loss, _ = idff_loss(model, x1, sigma0=sigma0) + opt.zero_grad() + loss.backward() + opt.step() + oracle = GaussianOracle(sigma0=sigma0) + for t in [0.2, 0.5, 0.8]: + st = sigma0 * math.sqrt(t * (1 - t)) + xt = t * (M + S * torch.randn(4000, 2)) + (1 - t) * torch.randn(4000, 2) + st * torch.randn(4000, 2) + tb = torch.full((4000,), t) + with torch.no_grad(): + x1_hat, s_hat = model(xt, tb) + x1_true, s_true = oracle(xt, tb) + rel_score = ((s_hat - s_true).norm(dim=1) / s_true.norm(dim=1)).median() + rel_x1 = ((x1_hat - x1_true).norm(dim=1) / x1_true.norm(dim=1)).median() + assert rel_score < 0.15, (t, rel_score) + assert rel_x1 < 0.05, (t, rel_x1) + + +# -------------------------------------------------------------------------------------------- +# End-to-end smoke tests +# -------------------------------------------------------------------------------------------- +@pytest.mark.parametrize("name", list(TOY_DATASETS)) +def test_static_training_and_sampling_smoke(name): + torch.manual_seed(0) + model = JointHeadMLP(2, hidden=64, depth=2, sigma0=0.2) + opt = torch.optim.Adam(model.parameters(), lr=1e-3) + losses = [] + for _ in range(200): + loss, _ = idff_loss(model, TOY_DATASETS[name](256), sigma0=0.2) + opt.zero_grad() + loss.backward() + opt.step() + losses.append(loss.item()) + assert np.mean(losses[-20:]) < np.mean(losses[:20]) + for K in [0, 1, 2, 3]: + out = sample(model, torch.randn(128, 2), 5, K=K, gamma_bar=0.5, alphas={2: 1.0, 3: 1.0}) + assert out.shape == (128, 2) and torch.isfinite(out).all() + + +def test_sequence_training_and_sampling_smoke(): + torch.manual_seed(0) + raw = attractor_trajectories("lorenz", num_traj=4, length=30, burn_in=200, seed=0) + data = torch.tensor((raw - raw.mean((0, 1))) / raw.std((0, 1)), dtype=torch.float32) + model = JointHeadMLP(3, hidden=64, depth=2, sigma0=0.05, base_std=0.05, num_positions=30, residual=True) + opt = torch.optim.Adam(model.parameters(), lr=1e-3) + for _ in range(100): + x0, x1, n = sequence_training_pairs(data, 128, sigma0=0.05) + loss, _ = idff_loss(model, x1, x0=x0, sigma0=0.05, model_kwargs={"n": n}) + opt.zero_grad() + loss.backward() + opt.step() + for K in [0, 1, 2]: + traj = sample_sequence(model, 30, 4, 3, nfe=3, sigma0=0.05, K=K) + assert traj.shape == (30, 4, 3) and torch.isfinite(traj).all() + cond = sample_sequence(model, 30, 4, 3, nfe=3, sigma0=0.05, first_frame=data[0, 0], K=K) + torch.testing.assert_close(cond[0], data[0, 0].expand(4, 3)) + per_sample = sample_sequence(model, 30, 4, 3, nfe=3, sigma0=0.05, first_frame=data[:, 0], K=K) + torch.testing.assert_close(per_sample[0], data[:, 0]) + nxt = sample_next(model, data[:, 3], 4, nfe=3, sigma0=0.05) + assert nxt.shape == (4, 3) diff --git a/timeseris_example/MD_simulation.py b/timeseris_example/MD_simulation.py new file mode 100644 index 0000000000000000000000000000000000000000..3ffa067d3b5ef88a179178b3f9c7d3b1b04cc479 --- /dev/null +++ b/timeseris_example/MD_simulation.py @@ -0,0 +1,202 @@ +"""IDFF surrogate model for polyALA molecular dynamics (paper, Sec. "Surrogate Models for Molecular Dynamics"). + +The data are the 46 backbone dihedral angles (23 phi/psi pairs) of a 200-frame polyALA trajectory. +A single joint-head network with dual-time indexing (flow time t, sequence position n) is trained +with the IDFF objective (Algorithm 3) and sampled autoregressively (Algorithm 4): position 0 starts +from N(0, I), every later position from x0^n ~ N(x1^{n-1}, sigma0^2 I). + +Generated trajectories are compared with the true one by MAE / RMSE (wrapped angular error, degrees) +and the correlation coefficient, for the deterministic CFM sampler and IDFF with K = 1 and K = 2, +all sharing the same trained network. + +Scale of the Langevin amplitude: the paper's gamma_bar in [0.1, 0.3] refers to a unit-variance base +N(0, I). Here the base is the previous frame plus N(0, sigma0^2 I) noise, so p_t has width ~sigma0 +and its score a Lipschitz constant ~1/sigma0^2; Euler-Maruyama on the Langevin term is only stable +when gamma_t dt / sigma0^2 is small. We therefore set gamma_bar = gamma_rel * sigma0^2 (gamma_rel = 1 +by default, chosen a priori, not tuned on the evaluation trajectory). ``--sweep`` reports the +sensitivity to gamma_rel and alpha_2. Example: + + python timeseris_example/MD_simulation.py --nfes 3 5 10 +""" +import argparse +import csv +import json +import sys +import time +from pathlib import Path + +import matplotlib + +matplotlib.use("Agg") +import matplotlib.pyplot as plt # noqa: E402 +import numpy as np # noqa: E402 +import torch # noqa: E402 + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent)) + +from idff import JointHeadMLP, idff_loss, sample_sequence, sequence_training_pairs # noqa: E402 +from idff.datasets import load_polyala_angles # noqa: E402 +from idff.metrics import trajectory_metrics, wrap_degrees # noqa: E402 + + +def repo_relative(args): + """Command-line arguments with paths made relative to the repository (for config.json).""" + out = dict(vars(args)) + for key in ("out", "data"): + if key in out: + try: + out[key] = str(Path(out[key]).resolve().relative_to(HERE.parent)) + except ValueError: + pass + return out + + +def parse_args(): + p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + p.add_argument("--data", default=str(HERE / "data" / "polyALA_angles.npz"), + help="polyALA_angles.npz (shipped) or the original polyALA_dataset.p") + p.add_argument("--iters", type=int, default=20000) + p.add_argument("--batch", type=int, default=256) + p.add_argument("--lr", type=float, default=1e-3) + p.add_argument("--sigma0", type=float, default=0.1, help="path bandwidth and Markov-init noise (standardised units)") + p.add_argument("--nfes", type=int, nargs="+", default=[3, 5, 10]) + p.add_argument("--gamma-rel", type=float, default=1.0, + help="Langevin amplitude relative to the base variance: gamma_bar = gamma_rel * sigma0^2") + p.add_argument("--alpha2", type=float, default=0.05, help="second-order scale (paper: ~0.05)") + p.add_argument("--num-traj", type=int, default=5) + p.add_argument("--seeds", type=int, default=3) + p.add_argument("--sweep", action="store_true", help="also report a gamma_bar / alpha_2 sensitivity sweep") + p.add_argument("--retrain", action="store_true") + p.add_argument("--out", default=str(HERE / "outputs" / "polyALA")) + return p.parse_args() + + +def prepare(path): + """Unwrap each angle in time (period 360) so consecutive frames are close, then standardise.""" + raw = load_polyala_angles(path) + unwrapped = np.unwrap(raw, period=360.0, axis=0) + mean, std = unwrapped.mean(0), unwrapped.std(0) + 1e-6 + data = torch.tensor((unwrapped - mean) / std, dtype=torch.float32)[None] # (1, frames, 46) + return raw, unwrapped, data, mean, std + + +def train(args, data, out_dir): + length, dim = data.shape[1], data.shape[2] + model = JointHeadMLP(dim, hidden=256, depth=3, sigma0=args.sigma0, base_std=args.sigma0, + num_positions=length, residual=True) + ckpt = out_dir / "idff_md.pt" + if ckpt.exists() and not args.retrain: + model.load_state_dict(torch.load(ckpt, map_location="cpu", weights_only=True)) + print(f"loaded {ckpt}") + return model.eval() + torch.manual_seed(0) + opt = torch.optim.Adam(model.parameters(), lr=args.lr) + sched = torch.optim.lr_scheduler.CosineAnnealingLR(opt, args.iters) + start = time.time() + for it in range(1, args.iters + 1): + x0, x1, n = sequence_training_pairs(data, args.batch, args.sigma0) + loss, stats = idff_loss(model, x1, x0=x0, sigma0=args.sigma0, model_kwargs={"n": n}) + opt.zero_grad() + loss.backward() + torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) + opt.step() + sched.step() + if it % 2000 == 0: + print(f"iter {it:6d} loss {loss.item():.4f} denoiser {stats['denoiser']:.4f} " + f"score {stats['score']:.4f} ({time.time() - start:.0f}s)") + torch.save(model.state_dict(), ckpt) + return model.eval() + + +def generate(model, data, args, nfe, seed, **cfg): + gen = torch.Generator().manual_seed(seed) + traj = sample_sequence(model, data.shape[1], args.num_traj, data.shape[2], nfe, args.sigma0, + generator=gen, **cfg) + return traj.numpy() # (frames, num_traj, 46), standardised + + +def evaluate(model, data, unwrapped, mean, std, args, nfe, cfg): + """Mean of each metric over sampling seeds; each seed rolls out ``num_traj`` trajectories.""" + per_seed = [] + for seed in range(args.seeds): + gen = generate(model, data, args, nfe, seed, **cfg) * std + mean # degrees (unwrapped) + per_seed.append(trajectory_metrics(gen, unwrapped, angles=True)) + keys = ["MAE", "RMSE", "CC"] + return {k: float(np.mean([m[k] for m in per_seed])) for k in keys} | \ + {k + "_seed_std": float(np.std([m[k] for m in per_seed])) for k in keys} + + +def main(): + args = parse_args() + out_dir = Path(args.out) + out_dir.mkdir(parents=True, exist_ok=True) + raw, unwrapped, data, mean, std = prepare(args.data) + print(f"polyALA: {data.shape[1]} frames x {data.shape[2]} dihedral angles") + model = train(args, data, out_dir) + + gamma_bar = args.gamma_rel * args.sigma0 ** 2 + methods = { + "CFM (det.)": dict(K=0), + "IDFF K=1": dict(K=1, gamma_bar=gamma_bar), + "IDFF K=2": dict(K=2, gamma_bar=gamma_bar, alphas={2: args.alpha2}), + } + rows = [] + for nfe in args.nfes: + for name, cfg in methods.items(): + m = evaluate(model, data, unwrapped, mean, std, args, nfe, cfg) + rows.append({"method": name, "nfe": nfe, "gamma_rel": args.gamma_rel if "gamma_bar" in cfg else 0.0, + "alpha2": cfg.get("alphas", {}).get(2, ""), **m}) + print(f"NFE={nfe:3d} {name:12s} MAE {m['MAE']:6.2f} RMSE {m['RMSE']:6.2f} CC {100 * m['CC']:5.1f}%") + + if args.sweep: + print("\nsensitivity (NFE = max of --nfes):") + nfe = max(args.nfes) + for rel in [0.1, 0.3, 1.0, 3.0, 10.0]: + g = rel * args.sigma0 ** 2 + for name, cfg in [("IDFF K=1", dict(K=1, gamma_bar=g))] + \ + [("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]]: + m = evaluate(model, data, unwrapped, mean, std, args, nfe, cfg) + rows.append({"method": name + " (sweep)", "nfe": nfe, "gamma_rel": rel, + "alpha2": cfg.get("alphas", {}).get(2, ""), **m}) + print(f" gamma_rel={rel:<5} {name} alpha2={cfg.get('alphas', {}).get(2, '-')!s:<5} " + f"MAE {m['MAE']:6.2f} RMSE {m['RMSE']:6.2f} CC {100 * m['CC']:5.1f}%") + + with open(out_dir / "evaluation_results.csv", "w", newline="") as fh: + writer = csv.DictWriter(fh, fieldnames=list(rows[0])) + writer.writeheader() + writer.writerows(rows) + with open(out_dir / "config.json", "w") as fh: + json.dump(repo_relative(args), fh, indent=2) + plot(model, data, raw, mean, std, args, out_dir) + print(f"\nwrote results to {out_dir}") + + +def plot(model, data, raw, mean, std, args, out_dir, angle=10): + """Figure in the style of the paper's MD figure: true vs generated (phi, psi) and one angle over time.""" + nfe = max(args.nfes) + gen = generate(model, data, args, nfe, 0, K=1, gamma_bar=args.gamma_rel * args.sigma0 ** 2) * std + mean + gen_w = wrap_degrees(gen) + fig, axs = plt.subplots(1, 3, figsize=(13, 3.8)) + axs[0].scatter(raw[:, 0::2].ravel(), raw[:, 1::2].ravel(), s=2, c="k", alpha=0.3) + axs[0].set_title("(A) true (phi, psi)") + axs[1].scatter(gen_w[:, :, 0::2].ravel(), gen_w[:, :, 1::2].ravel(), s=2, c="tab:red", alpha=0.3) + axs[1].set_title(f"(B) IDFF K=1, NFE={nfe}") + for ax in axs[:2]: + ax.set_xlim(-180, 180) + ax.set_ylim(-180, 180) + ax.set_xlabel("phi") + ax.set_ylabel("psi") + for k in range(gen_w.shape[1]): + axs[2].plot(gen_w[:, k, angle], c="tab:red", alpha=0.5, lw=1) + axs[2].plot(raw[:, angle], c="k", lw=1.5, label="true") + axs[2].set_title(f"(C) angle {angle}: true (black) vs generated (red)") + axs[2].set_xlabel("frame") + axs[2].set_ylabel("degrees") + fig.tight_layout() + fig.savefig(out_dir / "md_samples.png", dpi=130) + plt.close(fig) + + +if __name__ == "__main__": + main() diff --git a/timeseris_example/attractors.py b/timeseris_example/attractors.py new file mode 100644 index 0000000000000000000000000000000000000000..b3c5d98bc11635cbe6caabbd86e8edda0a981f4b --- /dev/null +++ b/timeseris_example/attractors.py @@ -0,0 +1,229 @@ +"""IDFF on chaotic 3-D attractors (paper, Appendix "3D Attractors"). + +Lorenz (sigma=10, rho=28, beta=8/3) and Rossler (a=b=0.2, c=5.7) trajectories are simulated with RK4. +An MLP with two hidden layers of width 128, two heads (denoiser, score) and embeddings of the flow time +t and the sequence position n is trained with the IDFF objective (Algorithm 3) and sampled +autoregressively (Algorithm 4). + +Evaluation on held-out test trajectories; hyper-parameters are chosen per NFE budget on separate +validation trajectories (by default by rollout MMD, the long-run statistic the README animation shows): +* one-step-ahead MAE: sample x_n given the true x_{n-1}; +* free rollout from the true first frame: MAE over the first 20 steps and the MMD between the + generated and true state distributions (long-run attractor statistics). + +Example: + + python timeseris_example/attractors.py --system lorenz +""" +import argparse +import csv +import json +import sys +import time +from pathlib import Path + +import matplotlib + +matplotlib.use("Agg") +import matplotlib.pyplot as plt # noqa: E402 +import numpy as np # noqa: E402 +import torch # noqa: E402 + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent)) + +from idff import JointHeadMLP, idff_loss, sample_next, sample_sequence, sequence_training_pairs # noqa: E402 +from idff.datasets import attractor_trajectories # noqa: E402 +from idff.metrics import mmd_rbf # noqa: E402 + + +def repo_relative(args): + """Command-line arguments with paths made relative to the repository (for config.json).""" + out = dict(vars(args)) + for key in ("out", "data"): + if key in out: + try: + out[key] = str(Path(out[key]).resolve().relative_to(HERE.parent)) + except ValueError: + pass + return out + + +def parse_args(): + p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + p.add_argument("--system", default="lorenz", choices=["lorenz", "rossler"]) + p.add_argument("--length", type=int, default=2000, help="trajectory length (the paper uses 2000)") + p.add_argument("--n-train", type=int, default=32) + p.add_argument("--n-val", type=int, default=4) + p.add_argument("--n-test", type=int, default=8) + p.add_argument("--iters", type=int, default=20000) + p.add_argument("--batch", type=int, default=512) + p.add_argument("--lr", type=float, default=1e-3) + p.add_argument("--sigma0", type=float, default=0.05) + p.add_argument("--nfes", type=int, nargs="+", default=[2, 3, 5, 10]) + p.add_argument("--gamma-rel-grid", type=float, nargs="+", default=[0.1, 0.3, 1.0, 3.0, 10.0], + help="gamma_bar = gamma_rel * sigma0^2 (see the MD example for why the base variance sets the scale)") + p.add_argument("--alpha-grid", type=float, nargs="+", + default=[-1000.0, -100.0, -10.0, -1.0, 1.0, 10.0, 100.0, 1000.0], + help="alpha_2 grid (0 is always added). It is wide because gamma_bar is small here; the sign " + "is free (the deviation bound depends on alpha_k^2)") + p.add_argument("--seeds", type=int, default=10, help="sampling seeds for the test rollout metrics") + p.add_argument("--select-by", default="rollout_mmd", choices=["rollout_mmd", "one_step_mae"], + help="validation criterion for gamma_bar and alpha_2") + p.add_argument("--select-seeds", type=int, default=3, help="sampling seeds for the validation criterion") + p.add_argument("--retrain", action="store_true") + p.add_argument("--out", default=str(HERE / "outputs")) + return p.parse_args() + + +def make_data(args): + total = args.n_train + args.n_val + args.n_test + raw = attractor_trajectories(args.system, total, args.length, seed=0) + train, val, test = np.split(raw, [args.n_train, args.n_train + args.n_val]) + mean, std = train.reshape(-1, 3).mean(0), train.reshape(-1, 3).std(0) + + def norm(a): + return torch.tensor((a - mean) / std, dtype=torch.float32) + + return norm(train), norm(val), norm(test), mean, std + + +def train(args, data, out_dir): + model = JointHeadMLP(3, hidden=128, depth=2, sigma0=args.sigma0, base_std=args.sigma0, + num_positions=args.length, residual=True) + ckpt = out_dir / "idff_model.pt" + if ckpt.exists() and not args.retrain: + model.load_state_dict(torch.load(ckpt, map_location="cpu", weights_only=True)) + print(f"loaded {ckpt}") + return model.eval() + torch.manual_seed(0) + opt = torch.optim.Adam(model.parameters(), lr=args.lr) + sched = torch.optim.lr_scheduler.CosineAnnealingLR(opt, args.iters) + start = time.time() + for it in range(1, args.iters + 1): + x0, x1, n = sequence_training_pairs(data, args.batch, args.sigma0) + loss, stats = idff_loss(model, x1, x0=x0, sigma0=args.sigma0, model_kwargs={"n": n}) + opt.zero_grad() + loss.backward() + torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) + opt.step() + sched.step() + if it % 4000 == 0: + print(f"iter {it:6d} loss {loss.item():.4f} denoiser {stats['denoiser']:.4f} " + f"score {stats['score']:.4f} ({time.time() - start:.0f}s)") + torch.save(model.state_dict(), ckpt) + return model.eval() + + +def one_step_mae(model, data, nfe, sigma0, std, cfg, seed=0, stride=1): + """Mean absolute one-step-ahead error in original units, over all trajectories and every + ``stride``-th position.""" + gen = torch.Generator().manual_seed(seed) + errs = [] + for n in range(1, data.shape[1], stride): + pred = sample_next(model, data[:, n - 1], n, nfe, sigma0, generator=gen, **cfg) + errs.append(((pred - data[:, n]).abs() * torch.tensor(std, dtype=torch.float32)).mean().item()) + return float(np.mean(errs)) + + +def rollout(model, data, nfe, sigma0, cfg, seed=0): + """Roll out every trajectory in one batch, each conditioned on its own true first frame.""" + gen = torch.Generator().manual_seed(seed) + traj = sample_sequence(model, data.shape[1], data.shape[0], 3, nfe, sigma0, first_frame=data[:, 0], + generator=gen, **cfg) + return traj.transpose(0, 1) # (num_traj, length, 3) + + +def rollout_metrics(model, data, nfe, sigma0, std, cfg, seeds=3, seed0=0): + """20-step MAE (original units) and state-distribution MMD, averaged over sampling seeds. + + Chaotic rollouts decorrelate quickly, so single-seed long-horizon numbers are noisy. + """ + scale = torch.tensor(std, dtype=torch.float32) + shorts, mmds = [], [] + for seed in range(seed0, seed0 + seeds): + gen = rollout(model, data, nfe, sigma0, cfg, seed=seed) + shorts.append(((gen[:, 1:21] - data[:, 1:21]).abs() * scale).mean().item()) + idx = torch.randperm(gen.shape[0] * gen.shape[1], generator=torch.Generator().manual_seed(seed))[:4000] + mmds.append(mmd_rbf(gen.reshape(-1, 3)[idx], data.reshape(-1, 3)[idx])) + if seed == seed0: + first = gen + return float(np.mean(shorts)), float(np.mean(mmds)), float(np.std(mmds)), first + + +def select(model, val, args, std): + """Per NFE budget, on the validation trajectories: gamma_bar for K=1, then alpha_2 for K=2 with the + same gamma_bar (alpha_2 = 0, tried first, recovers K=1). The criterion is the rollout MMD (mean over + ``--select-seeds`` sampling seeds that differ from the test seeds) or the one-step-ahead MAE.""" + grid = [r * args.sigma0 ** 2 for r in args.gamma_rel_grid] + alphas = [0.0] + [a for a in args.alpha_grid if a != 0.0] + sel = {} + for nfe in args.nfes: + if nfe <= 2: # gamma_t^1 = 0 at t = 0 and on the final step: every sampler coincides with CFM + sel[nfe] = {"gamma_bar": grid[0], "alpha_2": 0.0} + continue + + def err(cfg, nfe=nfe): + if args.select_by == "one_step_mae": + return one_step_mae(model, val, nfe, args.sigma0, std, cfg, stride=4) + return rollout_metrics(model, val, nfe, args.sigma0, std, cfg, seeds=args.select_seeds, seed0=100)[1] + + g = min(grid, key=lambda g: err(dict(K=1, gamma_bar=g))) + a2 = min(alphas, key=lambda a: err(dict(K=2, gamma_bar=g, alphas={2: a}))) + sel[nfe] = {"gamma_bar": g, "alpha_2": a2} + return sel + + +def main(): + args = parse_args() + out_dir = Path(args.out) / args.system + out_dir.mkdir(parents=True, exist_ok=True) + train_d, val_d, test_d, mean, std = make_data(args) + print(f"{args.system}: train {tuple(train_d.shape)}, val {tuple(val_d.shape)}, test {tuple(test_d.shape)}") + model = train(args, train_d, out_dir) + sel = select(model, val_d, args, std) + print("selected on validation trajectories:") + for nfe, s in sel.items(): + print(f" NFE={nfe:3d} gamma_rel={s['gamma_bar'] / args.sigma0 ** 2:g} alpha_2={s['alpha_2']:g}") + + def methods(nfe): + s = sel[nfe] + return {"CFM (det.)": dict(K=0), "IDFF K=1": dict(K=1, gamma_bar=s["gamma_bar"]), + "IDFF K=2": dict(K=2, gamma_bar=s["gamma_bar"], alphas={2: s["alpha_2"]})} + + rows, rolls = [], {} + print(f"\n{'NFE':>4} {'method':12s} {'1-step MAE':>11s} {'20-step MAE':>12s} {'rollout MMD (mean +- std)':>26s}") + for nfe in args.nfes: + for name, cfg in methods(nfe).items(): + mae1 = one_step_mae(model, test_d, nfe, args.sigma0, std, cfg) + short, mmd, mmd_sd, gen = rollout_metrics(model, test_d, nfe, args.sigma0, std, cfg, seeds=args.seeds) + rolls[(name, nfe)] = gen + rows.append({"method": name, "nfe": nfe, "one_step_mae": mae1, "rollout20_mae": short, + "rollout_mmd": mmd, "rollout_mmd_std": mmd_sd}) + print(f"{nfe:>4} {name:12s} {mae1:11.4f} {short:12.4f} {mmd:9.5f} +- {mmd_sd:.5f}") + + with open(out_dir / "results.csv", "w", newline="") as fh: + writer = csv.DictWriter(fh, fieldnames=list(rows[0])) + writer.writeheader() + writer.writerows(rows) + with open(out_dir / "config.json", "w") as fh: + json.dump({**repo_relative(args), "selected": {str(k): v for k, v in sel.items()}}, fh, indent=2) + + nfe = max(args.nfes) + true = test_d[0].numpy() * std + mean + fig = plt.figure(figsize=(14, 4.5)) + for j, name in enumerate(["CFM (det.)", "IDFF K=1", "IDFF K=2"]): + ax = fig.add_subplot(1, 3, j + 1, projection="3d") + g = rolls[(name, nfe)][0].numpy() * std + mean + ax.plot(*true.T, c="k", lw=0.6, alpha=0.6, label="true") + ax.plot(*g.T, c="tab:red", lw=0.6, alpha=0.8, label="generated") + ax.set_title(f"{args.system}: {name}, NFE={nfe}") + ax.legend(fontsize=7) + fig.tight_layout() + fig.savefig(out_dir / "rollout.png", dpi=130) + plt.close(fig) + print(f"\nwrote results to {out_dir}") + + +if __name__ == "__main__": + main() diff --git a/timeseris_example/data/polyALA_angles.npz b/timeseris_example/data/polyALA_angles.npz new file mode 100644 index 0000000000000000000000000000000000000000..8d1129edd1cbcd3b3a69afb6b59423ffaddadef6 --- /dev/null +++ b/timeseris_example/data/polyALA_angles.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9cd407fc8218f4344e605112ea7e8f5a3d3ccd4e57b8ab7c18db4b5a67ba1ef0 +size 34215 diff --git a/timeseris_example/outputs/lorenz/config.json b/timeseris_example/outputs/lorenz/config.json new file mode 100644 index 0000000000000000000000000000000000000000..8d8e6879aec4b6c6c69ff0fb1b7f1d00fbabed76 --- /dev/null +++ b/timeseris_example/outputs/lorenz/config.json @@ -0,0 +1,57 @@ +{ + "system": "lorenz", + "length": 2000, + "n_train": 32, + "n_val": 4, + "n_test": 8, + "iters": 20000, + "batch": 512, + "lr": 0.001, + "sigma0": 0.05, + "nfes": [ + 2, + 3, + 5, + 10 + ], + "gamma_rel_grid": [ + 0.1, + 0.3, + 1.0, + 3.0, + 10.0 + ], + "alpha_grid": [ + -1000.0, + -100.0, + -10.0, + -1.0, + 1.0, + 10.0, + 100.0, + 1000.0 + ], + "seeds": 10, + "select_by": "rollout_mmd", + "select_seeds": 3, + "retrain": false, + "out": "timeseris_example/outputs", + "selected": { + "2": { + "gamma_bar": 0.00025000000000000006, + "alpha_2": 0.0 + }, + "3": { + "gamma_bar": 0.0007500000000000001, + "alpha_2": 0.0 + }, + "5": { + "gamma_bar": 0.00025000000000000006, + "alpha_2": -10.0 + }, + "10": { + "gamma_bar": 0.0007500000000000001, + "alpha_2": 0.0 + } + } +} \ No newline at end of file diff --git a/timeseris_example/outputs/lorenz/idff_model.pt b/timeseris_example/outputs/lorenz/idff_model.pt new file mode 100644 index 0000000000000000000000000000000000000000..8445fc10a056d0ed82957677e170d26bde9ff197 --- /dev/null +++ b/timeseris_example/outputs/lorenz/idff_model.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1a34994890468bfc838d84ffb1d37f7e37b1001914e994f3805526e554a4a3ab +size 624757 diff --git a/timeseris_example/outputs/lorenz/results.csv b/timeseris_example/outputs/lorenz/results.csv new file mode 100644 index 0000000000000000000000000000000000000000..e2735be76b40aef3d0165d8f8c8cab598f1c8329 --- /dev/null +++ b/timeseris_example/outputs/lorenz/results.csv @@ -0,0 +1,13 @@ +method,nfe,one_step_mae,rollout20_mae,rollout_mmd,rollout_mmd_std +CFM (det.),2,0.5046711948706306,2.970464992523193,0.013119068704618774,0.009917949236038632 +IDFF K=1,2,0.5046711948706306,2.970464992523193,0.013119068704618774,0.009917949236038632 +IDFF K=2,2,0.5046711948706306,2.970464992523193,0.013119068704618774,0.009917949236038632 +CFM (det.),3,0.39490651294939394,2.1065974593162538,0.005244532301044491,0.00389900752757173 +IDFF K=1,3,0.4134999921674905,2.163750243186951,0.005251220724828009,0.003239456811503962 +IDFF K=2,3,0.4134999921674905,2.163750243186951,0.005251220724828009,0.003239456811503962 +CFM (det.),5,0.3209775646010776,1.3495140194892883,0.0037345989312153214,0.00353533620336635 +IDFF K=1,5,0.3336806403451588,1.472440481185913,0.00202500827088391,0.0007522051552088028 +IDFF K=2,5,0.3329388130420801,1.484570050239563,0.002992447405168791,0.00305111604551931 +CFM (det.),10,0.3021115019671496,1.169181227684021,0.005124361358398932,0.004687339883902047 +IDFF K=1,10,0.3502505819922152,1.3118240892887116,0.0037427483634526414,0.005020263076036552 +IDFF K=2,10,0.3502505819922152,1.3118240892887116,0.0037427483634526414,0.005020263076036552 diff --git a/timeseris_example/outputs/lorenz/rollout.png b/timeseris_example/outputs/lorenz/rollout.png new file mode 100644 index 0000000000000000000000000000000000000000..0ab41a6774d43e4010500c9353b09bcdeeb81a50 --- /dev/null +++ b/timeseris_example/outputs/lorenz/rollout.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a359364c41ce556902a39370e49c433f244733df2f694850e2af8d5d3bdce638 +size 546910 diff --git a/timeseris_example/outputs/polyALA/config.json b/timeseris_example/outputs/polyALA/config.json new file mode 100644 index 0000000000000000000000000000000000000000..bdc41032d2070505b02df2b1d5bd842c47fb7dda --- /dev/null +++ b/timeseris_example/outputs/polyALA/config.json @@ -0,0 +1,19 @@ +{ + "data": "timeseris_example/data/polyALA_angles.npz", + "iters": 20000, + "batch": 256, + "lr": 0.001, + "sigma0": 0.1, + "nfes": [ + 3, + 5, + 10 + ], + "gamma_rel": 1.0, + "alpha2": 0.05, + "num_traj": 5, + "seeds": 3, + "sweep": true, + "retrain": false, + "out": "timeseris_example/outputs/polyALA" +} \ No newline at end of file diff --git a/timeseris_example/outputs/polyALA/evaluation_results.csv b/timeseris_example/outputs/polyALA/evaluation_results.csv new file mode 100644 index 0000000000000000000000000000000000000000..9d9499cc7eaec91d63e085fa6777fc17cddc3fb0 --- /dev/null +++ b/timeseris_example/outputs/polyALA/evaluation_results.csv @@ -0,0 +1,40 @@ +method,nfe,gamma_rel,alpha2,MAE,RMSE,CC,MAE_seed_std,RMSE_seed_std,CC_seed_std +CFM (det.),3,0.0,,2.9922401767075617,4.155066000812517,0.9978891292225894,0.31496997083863243,0.5177781690175595,0.00018535222011378807 +IDFF K=1,3,1.0,,3.9276713578107185,5.350654676136595,0.9966403078454028,0.6455303157859048,0.9737780357648421,0.0005396718572639132 +IDFF K=2,3,1.0,0.05,3.9273660952308442,5.350164205578271,0.9966404569051882,0.6452164712290651,0.973095082673879,0.0005391411282792847 +CFM (det.),5,0.0,,2.6118116313896222,3.649404712513005,0.9983524237576468,0.1636659245691367,0.2965550594561423,7.984906844305301e-05 +IDFF K=1,5,1.0,,3.916477027762792,5.464339336591634,0.9965412388478644,0.43580179825493714,0.733190721641211,0.0005028230577794873 +IDFF K=2,5,1.0,0.05,3.916338106692932,5.464288320381553,0.9965408149190714,0.43543860528082085,0.7327343574291173,0.0005029380871925646 +CFM (det.),10,0.0,,2.339762608007314,3.280161720437835,0.9987191174913775,0.04284794495472016,0.06781351612737008,2.7027454805517246e-05 +IDFF K=1,10,1.0,,3.6311263349798804,5.1716461633838415,0.996922951704656,0.5250965149041412,0.9247040605568756,0.0006962228989955795 +IDFF K=2,10,1.0,0.05,3.6311846407688293,5.171681859327962,0.996922551846415,0.5248725401122517,0.9243230661841134,0.0006963234461285235 +IDFF K=1 (sweep),10,0.1,,2.6879184781623082,3.8335534845981853,0.9983853872648671,0.3821271525978309,0.6493292469691564,0.0003206207323959128 +IDFF K=2 (sweep),10,0.1,-5.0,2.6884027237714947,3.8359898994286215,0.998386770142095,0.38459391515038666,0.6539447738825922,0.0003224262094807928 +IDFF K=2 (sweep),10,0.1,-1.0,2.687932440823337,3.833952124165439,0.99838575359131,0.3826134243353551,0.6502616790433675,0.00032098612648573215 +IDFF K=2 (sweep),10,0.1,0.05,2.6879182716266263,3.8335336862133325,0.9983853679340845,0.3821030425361508,0.6492825490464281,0.0003206018078964179 +IDFF K=2 (sweep),10,0.1,1.0,2.6879476584214306,3.8331991605654543,0.99838497504257,0.38163922107171344,0.6483896498941699,0.00032025142568402733 +IDFF K=2 (sweep),10,0.1,5.0,2.6885058781509734,3.832244238330153,0.9983828566493026,0.3796619574653882,0.644578159673287,0.0003187500960379704 +IDFF K=1 (sweep),10,0.3,,2.9272957929000927,4.164683317686751,0.9980622673809153,0.4446130009360982,0.7605947322762708,0.00042017238987658313 +IDFF K=2 (sweep),10,0.3,-5.0,2.9292651664544436,4.171681781571837,0.9980654860779906,0.45265134333748663,0.7742250118457833,0.0004228984493766659 +IDFF K=2 (sweep),10,0.3,-1.0,2.9271187864353188,4.165485005700865,0.9980635699760465,0.4462324290966084,0.7633895429805821,0.00042074719304405683 +IDFF K=2 (sweep),10,0.3,0.05,2.9273131976428375,4.164652632290722,0.9980621924947886,0.44453194734410334,0.7604525331810816,0.00042014189569559014 +IDFF K=2 (sweep),10,0.3,1.0,2.927786587103954,4.164203009381241,0.9980606103877235,0.44301419541340586,0.7577638141729802,0.0004195805087601121 +IDFF K=2 (sweep),10,0.3,5.0,2.9329938499053387,4.16567109425354,0.998050205976469,0.43648971456311236,0.7460964465238891,0.00041705084834158093 +IDFF K=1 (sweep),10,1.0,,3.6311263349798804,5.1716461633838415,0.996922951704656,0.5250965149041412,0.9247040605568756,0.0006962228989955795 +IDFF K=2 (sweep),10,1.0,-5.0,3.6475163964434754,5.189859391725872,0.9969319765551895,0.5484801679272854,0.9601051345911288,0.0006856372298810682 +IDFF K=2 (sweep),10,1.0,-1.0,3.6309627593122418,5.171906215508305,0.996929564757315,0.5296725346581149,0.9322456272134577,0.0006942032898193387 +IDFF K=2 (sweep),10,1.0,0.05,3.6311846407688293,5.171681859327962,0.996922551846415,0.5248725401122517,0.9243230661841134,0.0006963234461285235 +IDFF K=2 (sweep),10,1.0,1.0,3.6332281701053835,5.173238130299825,0.9969136867025843,0.5205305462134877,0.9169991451387031,0.0006981871877827594 +IDFF K=2 (sweep),10,1.0,5.0,3.661241178939767,5.200242248584531,0.9968465153541702,0.5030676931283106,0.8852448227352774,0.0007052845638891795 +IDFF K=1 (sweep),10,3.0,,5.281976525195554,7.602697547750491,0.9932302331179151,0.6274062514275708,1.1138994229536192,0.0013595718961097567 +IDFF K=2 (sweep),10,3.0,-5.0,5.887492088417011,8.08663030792043,0.9926436326897995,0.7283366266533818,1.17745201730117,0.0011862905239823692 +IDFF K=2 (sweep),10,3.0,-1.0,5.327354834626896,7.627806938563121,0.9932253363591407,0.6430596677695429,1.129077512307308,0.001331932647267951 +IDFF K=2 (sweep),10,3.0,0.05,5.280299484064513,7.601936447492572,0.9932296475367406,0.6266846574223109,1.1131337817765459,0.001360897830327774 +IDFF K=2 (sweep),10,3.0,1.0,5.257205580150825,7.594546093369105,0.9932062855521142,0.6137237561819945,1.0985993971520605,0.001385080440871407 +IDFF K=2 (sweep),10,3.0,5.0,5.278074274651343,7.661614799375243,0.9929231456165505,0.5739513342466118,1.0433944542483913,0.0014704773371371927 +IDFF K=1 (sweep),10,10.0,,67.41158247504073,79.9155399717963,0.31689136135475077,3.1532989951075443,3.567632910122242,0.10015263875163914 +IDFF K=2 (sweep),10,10.0,-5.0,75.85843675667384,89.06746227275288,0.1577573385496486,2.9828389492612253,3.1356857692180222,0.06585600406958056 +IDFF K=2 (sweep),10,10.0,-1.0,75.50231033726324,88.39049203137763,0.09926679637740615,0.3762112058837424,0.6004679659482175,0.07231126134139261 +IDFF K=2 (sweep),10,10.0,0.05,71.4424623697763,84.10156668319955,0.20103752590061297,5.214554799984109,5.846294691060069,0.14995549668143493 +IDFF K=2 (sweep),10,10.0,1.0,67.27718624342712,79.64379335385955,0.30868282262257635,4.158869029541596,4.998679193014867,0.14813485954777644 +IDFF K=2 (sweep),10,10.0,5.0,54.33118738070104,67.24698177986338,0.4194601369724329,10.762887206772902,11.138546685311526,0.19349604666049583 diff --git a/timeseris_example/outputs/polyALA/idff_md.pt b/timeseris_example/outputs/polyALA/idff_md.pt new file mode 100644 index 0000000000000000000000000000000000000000..c5d87dc647bd4b107c5eff1352f30c9efc6c6c47 --- /dev/null +++ b/timeseris_example/outputs/polyALA/idff_md.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9f3fbeb6f773815fa31c9fa0895e9e4b24f1a01600f165582578e3b8bd20adf6 +size 799167 diff --git a/timeseris_example/outputs/polyALA/md_samples.png b/timeseris_example/outputs/polyALA/md_samples.png new file mode 100644 index 0000000000000000000000000000000000000000..35418961dff01f8ce7e49eedffae4cd84859bd99 --- /dev/null +++ b/timeseris_example/outputs/polyALA/md_samples.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:36857c4c4cf94cebd7fbc495afa990ab453251e0a45fd2d74836c63f23367fe1 +size 230707 diff --git a/torchcfm/__init__.py b/torchcfm/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..52be33ad3e54e5f1ed161c0d86f1a4da15686379 --- /dev/null +++ b/torchcfm/__init__.py @@ -0,0 +1,2 @@ +from .conditional_flow_matching import * +from .version import __version__ diff --git a/torchcfm/conditional_flow_matching.py b/torchcfm/conditional_flow_matching.py new file mode 100644 index 0000000000000000000000000000000000000000..fd788ac70987c93a2e17a88a97f25ebc23b3f8c4 --- /dev/null +++ b/torchcfm/conditional_flow_matching.py @@ -0,0 +1,606 @@ +"""Implements Conditional Flow Matcher Losses.""" + +import math +import warnings +from typing import Union + +import torch + +from .optimal_transport import OTPlanSampler + + +def pad_t_like_x(t, x): + """Function to reshape the time vector t by the number of dimensions of x. + + Parameters + ---------- + x : Tensor, shape (bs, *dim) + represents the source minibatch + t : FloatTensor, shape (bs) + + Returns + ------- + t : Tensor, shape (bs, number of x dimensions) + + Example + ------- + x: Tensor (bs, C, W, H) + t: Vector (bs) + pad_t_like_x(t, x): Tensor (bs, 1, 1, 1) + """ + if isinstance(t, (float, int)): + return t + return t.reshape(-1, *([1] * (x.dim() - 1))) + + +class ConditionalFlowMatcher: + """Base class for conditional flow matching methods. This class implements the independent + conditional flow matching methods from [1] and serves as a parent class for all other flow + matching methods. + + It implements: + - Drawing data from gaussian probability path N(t * x1 + (1 - t) * x0, sigma) function + - conditional flow matching ut(x1|x0) = x1 - x0 + - score function $\nabla log p_t(x|x0, x1)$ + """ + + def __init__(self, sigma: Union[float, int] = 0.0): + r"""Initialize the ConditionalFlowMatcher class. It requires the hyper-parameter $\sigma$. + + Parameters + ---------- + sigma : Union[float, int] + """ + self.sigma = sigma + + def compute_mu_t(self, x0, x1, t): + """ + Compute the mean of the probability path N(t * x1 + (1 - t) * x0, sigma), see (Eq.14) [1]. + + Parameters + ---------- + x0 : Tensor, shape (bs, *dim) + represents the source minibatch + x1 : Tensor, shape (bs, *dim) + represents the target minibatch + t : FloatTensor, shape (bs) + + Returns + ------- + mean mu_t: t * x1 + (1 - t) * x0 + + References + ---------- + [1] Improving and Generalizing Flow-Based Generative Models with minibatch optimal transport, Preprint, Tong et al. + """ + t = pad_t_like_x(t, x0) + return t * x1 + (1 - t) * x0 + + def compute_sigma_t(self, t): + """ + Compute the standard deviation of the probability path N(t * x1 + (1 - t) * x0, sigma), see (Eq.14) [1]. + + Parameters + ---------- + t : FloatTensor, shape (bs) + + Returns + ------- + standard deviation sigma + + References + ---------- + [1] Improving and Generalizing Flow-Based Generative Models with minibatch optimal transport, Preprint, Tong et al. + """ + del t + return self.sigma + + def sample_xt(self, x0, x1, t, epsilon): + """ + Draw a sample from the probability path N(t * x1 + (1 - t) * x0, sigma), see (Eq.14) [1]. + + Parameters + ---------- + x0 : Tensor, shape (bs, *dim) + represents the source minibatch + x1 : Tensor, shape (bs, *dim) + represents the target minibatch + t : FloatTensor, shape (bs) + epsilon : Tensor, shape (bs, *dim) + noise sample from N(0, 1) + + Returns + ------- + xt : Tensor, shape (bs, *dim) + + References + ---------- + [1] Improving and Generalizing Flow-Based Generative Models with minibatch optimal transport, Preprint, Tong et al. + """ + mu_t = self.compute_mu_t(x0, x1, t) + sigma_t = self.compute_sigma_t(t) + sigma_t = pad_t_like_x(sigma_t, x0) + return mu_t + sigma_t * epsilon + + def compute_conditional_flow(self, x0, x1, t, xt): + """ + Compute the conditional vector field ut(x1|x0) = x1 - x0, see Eq.(15) [1]. + + Parameters + ---------- + x0 : Tensor, shape (bs, *dim) + represents the source minibatch + x1 : Tensor, shape (bs, *dim) + represents the target minibatch + t : FloatTensor, shape (bs) + xt : Tensor, shape (bs, *dim) + represents the samples drawn from probability path pt + + Returns + ------- + ut : conditional vector field ut(x1|x0) = x1 - x0 + + References + ---------- + [1] Improving and Generalizing Flow-Based Generative Models with minibatch optimal transport, Preprint, Tong et al. + """ + del t, xt + return x1 - x0 + + def sample_noise_like(self, x): + return torch.randn_like(x) + + def sample_location_and_conditional_flow(self, x0, x1, t=None, return_noise=False): + """ + Compute the sample xt (drawn from N(t * x1 + (1 - t) * x0, sigma)) + and the conditional vector field ut(x1|x0) = x1 - x0, see Eq.(15) [1]. + + Parameters + ---------- + x0 : Tensor, shape (bs, *dim) + represents the source minibatch + x1 : Tensor, shape (bs, *dim) + represents the target minibatch + (optionally) t : Tensor, shape (bs) + represents the time levels + if None, drawn from uniform [0,1] + return_noise : bool + return the noise sample epsilon + + + Returns + ------- + t : FloatTensor, shape (bs) + xt : Tensor, shape (bs, *dim) + represents the samples drawn from probability path pt + ut : conditional vector field ut(x1|x0) = x1 - x0 + (optionally) eps: Tensor, shape (bs, *dim) such that xt = mu_t + sigma_t * epsilon + + References + ---------- + [1] Improving and Generalizing Flow-Based Generative Models with minibatch optimal transport, Preprint, Tong et al. + """ + if t is None: + t = torch.rand(x0.shape[0]).type_as(x0) + assert len(t) == x0.shape[0], "t has to have batch size dimension" + + eps = self.sample_noise_like(x0) + xt = self.sample_xt(x0, x1, t, eps) + ut = self.compute_conditional_flow(x0, x1, t, xt) + if return_noise: + return t, xt, ut, eps + else: + return t, xt, ut + + def compute_lambda(self, t): + """Compute the lambda function, see Eq.(23) [3]. + + Parameters + ---------- + t : FloatTensor, shape (bs) + + Returns + ------- + lambda : score weighting function + + References + ---------- + [4] Simulation-free Schrodinger bridges via score and flow matching, Preprint, Tong et al. + """ + sigma_t = self.compute_sigma_t(t) + return 2 * sigma_t / (self.sigma**2 + 1e-8) + + +class ExactOptimalTransportConditionalFlowMatcher(ConditionalFlowMatcher): + """Child class for optimal transport conditional flow matching method. This class implements + the OT-CFM methods from [1] and inherits the ConditionalFlowMatcher parent class. + + It overrides the sample_location_and_conditional_flow. + """ + + def __init__(self, sigma: Union[float, int] = 0.0): + r"""Initialize the ConditionalFlowMatcher class. It requires the hyper-parameter $\sigma$. + + Parameters + ---------- + sigma : Union[float, int] + ot_sampler: exact OT method to draw couplings (x0, x1) (see Eq.(17) [1]). + """ + super().__init__(sigma) + self.ot_sampler = OTPlanSampler(method="exact") + def compute_sigma_t(self, t): + + return self.sigma * torch.sqrt(t* (1 - t)) + + def sample_location_and_conditional_flow(self, x0, x1, t=None, return_noise=False): + r""" + Compute the sample xt (drawn from N(t * x1 + (1 - t) * x0, sigma)) + and the conditional vector field ut(x1|x0) = x1 - x0, see Eq.(15) [1] + with respect to the minibatch OT plan $\Pi$. + + Parameters + ---------- + x0 : Tensor, shape (bs, *dim) + represents the source minibatch + x1 : Tensor, shape (bs, *dim) + represents the target minibatch + (optionally) t : Tensor, shape (bs) + represents the time levels + if None, drawn from uniform [0,1] + return_noise : bool + return the noise sample epsilon + + Returns + ------- + t : FloatTensor, shape (bs) + xt : Tensor, shape (bs, *dim) + represents the samples drawn from probability path pt + ut : conditional vector field ut(x1|x0) = x1 - x0 + (optionally) epsilon : Tensor, shape (bs, *dim) such that xt = mu_t + sigma_t * epsilon + + References + ---------- + [1] Improving and Generalizing Flow-Based Generative Models with minibatch optimal transport, Preprint, Tong et al. + """ + x0, x1 = self.ot_sampler.sample_plan(x0, x1) + return super().sample_location_and_conditional_flow(x0, x1, t, return_noise) + + def guided_sample_location_and_conditional_flow( + self, x0, x1, y0=None, y1=None, t=None, return_noise=False + ): + r""" + Compute the sample xt (drawn from N(t * x1 + (1 - t) * x0, sigma)) + and the conditional vector field ut(x1|x0) = x1 - x0, see Eq.(15) [1] + with respect to the minibatch OT plan $\Pi$. + + Parameters + ---------- + x0 : Tensor, shape (bs, *dim) + represents the source minibatch + x1 : Tensor, shape (bs, *dim) + represents the target minibatch + y0 : Tensor, shape (bs) (default: None) + represents the source label minibatch + y1 : Tensor, shape (bs) (default: None) + represents the target label minibatch + (optionally) t : Tensor, shape (bs) + represents the time levels + if None, drawn from uniform [0,1] + return_noise : bool + return the noise sample epsilon + + Returns + ------- + t : FloatTensor, shape (bs) + xt : Tensor, shape (bs, *dim) + represents the samples drawn from probability path pt + ut : conditional vector field ut(x1|x0) = x1 - x0 + (optionally) epsilon : Tensor, shape (bs, *dim) such that xt = mu_t + sigma_t * epsilon + + References + ---------- + [1] Improving and Generalizing Flow-Based Generative Models with minibatch optimal transport, Preprint, Tong et al. + """ + x0, x1, y0, y1 = self.ot_sampler.sample_plan_with_labels(x0, x1, y0, y1) + if return_noise: + t, xt, ut, eps = super().sample_location_and_conditional_flow(x0, x1, t, return_noise) + return t, xt, ut, y0, y1, eps + else: + t, xt, ut = super().sample_location_and_conditional_flow(x0, x1, t, return_noise) + return t, xt, ut, y0, y1 + + +class TargetConditionalFlowMatcher(ConditionalFlowMatcher): + """Lipman et al. 2023 style target OT conditional flow matching. This class inherits the + ConditionalFlowMatcher and override the compute_mu_t, compute_sigma_t and + compute_conditional_flow functions in order to compute [2]'s flow matching. + + [2] Flow Matching for Generative Modelling, ICLR, Lipman et al. + """ + + def compute_mu_t(self, x0, x1, t): + """Compute the mean of the probability path tx1, see (Eq.20) [2]. + + Parameters + ---------- + x0 : Tensor, shape (bs, *dim) + represents the source minibatch + x1 : Tensor, shape (bs, *dim) + represents the target minibatch + t : FloatTensor, shape (bs) + + Returns + ------- + mean mu_t: t * x1 + + References + ---------- + [2] Flow Matching for Generative Modelling, ICLR, Lipman et al. + """ + del x0 + t = pad_t_like_x(t, x1) + return t * x1 + + def compute_sigma_t(self, t): + """ + Compute the standard deviation of the probability path N(t x1, 1 - (1 - sigma) t), see (Eq.20) [2]. + + Parameters + ---------- + t : FloatTensor, shape (bs) + + Returns + ------- + standard deviation sigma 1 - (1 - sigma) t + + References + ---------- + [2] Flow Matching for Generative Modelling, ICLR, Lipman et al. + """ + return 1 - (1 - self.sigma) * t + + def compute_conditional_flow(self, x0, x1, t, xt): + """ + Compute the conditional vector field ut(x1|x0) = (x1 - (1 - sigma) t)/(1 - (1 - sigma)t), see Eq.(21) [2]. + + Parameters + ---------- + x0 : Tensor, shape (bs, *dim) + represents the source minibatch + x1 : Tensor, shape (bs, *dim) + represents the target minibatch + t : FloatTensor, shape (bs) + xt : Tensor, shape (bs, *dim) + represents the samples drawn from probability path pt + + Returns + ------- + ut : conditional vector field ut(x1|x0) = (x1 - (1 - sigma) t)/(1 - (1 - sigma)t) + + References + ---------- + [1] Flow Matching for Generative Modelling, ICLR, Lipman et al. + """ + del x0 + t = pad_t_like_x(t, x1) + return (x1 - (1 - self.sigma) * xt) / (1 - (1 - self.sigma) * t) + + +class SchrodingerBridgeConditionalFlowMatcher(ConditionalFlowMatcher): + """Child class for Schrödinger bridge conditional flow matching method. This class implements + the SB-CFM methods from [1] and inherits the ConditionalFlowMatcher parent class. + + It overrides the compute_sigma_t, compute_conditional_flow and + sample_location_and_conditional_flow functions. + """ + + def __init__(self, sigma: Union[float, int] = 1.0, ot_method="exact"): + r"""Initialize the SchrodingerBridgeConditionalFlowMatcher class. It requires the hyper- + parameter $\sigma$ and the entropic OT map. + + Parameters + ---------- + sigma : Union[float, int] + ot_sampler: exact OT method to draw couplings (x0, x1) (see Eq.(17) [1]). + we use exact as the default as we found this to perform better + (more accurate and faster) in practice for reasonable batch sizes. + We note that as batchsize --> infinity the correct choice is the + sinkhorn method theoretically. + """ + if sigma <= 0: + raise ValueError(f"Sigma must be strictly positive, got {sigma}.") + elif sigma < 1e-3: + warnings.warn("Small sigma values may lead to numerical instability.") + super().__init__(sigma) + self.ot_method = ot_method + self.ot_sampler = OTPlanSampler(method=ot_method, reg=2 * self.sigma**2) + + def compute_sigma_t(self, t): + """ + Compute the standard deviation of the probability path N(t * x1 + (1 - t) * x0, sqrt(t * (1 - t))*sigma^2), + see (Eq.20) [1]. + + Parameters + ---------- + t : FloatTensor, shape (bs) + + Returns + ------- + standard deviation sigma + + References + ---------- + [1] Improving and Generalizing Flow-Based Generative Models with minibatch optimal transport, Preprint, Tong et al. + """ + return self.sigma * torch.sqrt(t * (1 - t)) + + def compute_conditional_flow(self, x0, x1, t, xt): + """Compute the conditional vector field. + + ut(x1|x0) = (1 - 2 * t) / (2 * t * (1 - t)) * (xt - mu_t) + x1 - x0, + see Eq.(21) [1]. + + Parameters + ---------- + x0 : Tensor, shape (bs, *dim) + represents the source minibatch + x1 : Tensor, shape (bs, *dim) + represents the target minibatch + t : FloatTensor, shape (bs) + xt : Tensor, shape (bs, *dim) + represents the samples drawn from probability path pt + + Returns + ------- + ut : conditional vector field + ut(x1|x0) = (1 - 2 * t) / (2 * t * (1 - t)) * (xt - mu_t) + x1 - x0 + + References + ---------- + [1] Improving and Generalizing Flow-Based Generative Models + with minibatch optimal transport, Preprint, Tong et al. + """ + t = pad_t_like_x(t, x0) + mu_t = self.compute_mu_t(x0, x1, t) + sigma_t_prime_over_sigma_t = (1 - 2 * t) / (2 * t * (1 - t) + 1e-8) + ut = sigma_t_prime_over_sigma_t * (xt - mu_t) + x1 - x0 + return ut + + def sample_location_and_conditional_flow(self, x0, x1, t=None, return_noise=False): + """ + Compute the sample xt (drawn from N(t * x1 + (1 - t) * x0, sqrt(t * (1 - t))*sigma^2 )) + and the conditional vector field ut(x1|x0) = (1 - 2 * t) / (2 * t * (1 - t)) * (xt - mu_t) + x1 - x0, + (see Eq.(15) [1]) with respect to the minibatch entropic OT plan. + + Parameters + ---------- + x0 : Tensor, shape (bs, *dim) + represents the source minibatch + x1 : Tensor, shape (bs, *dim) + represents the target minibatch + (optionally) t : Tensor, shape (bs) + represents the time levels + if None, drawn from uniform [0,1] + return_noise: bool + return the noise sample epsilon + + + Returns + ------- + t : FloatTensor, shape (bs) + xt : Tensor, shape (bs, *dim) + represents the samples drawn from probability path pt + ut : conditional vector field ut(x1|x0) = x1 - x0 + (optionally) epsilon : Tensor, shape (bs, *dim) such that xt = mu_t + sigma_t * epsilon + + References + ---------- + [1] Improving and Generalizing Flow-Based Generative Models with minibatch optimal transport, Preprint, Tong et al. + """ + x0, x1 = self.ot_sampler.sample_plan(x0, x1) + return super().sample_location_and_conditional_flow(x0, x1, t, return_noise) + + def guided_sample_location_and_conditional_flow( + self, x0, x1, y0=None, y1=None, t=None, return_noise=False + ): + r""" + Compute the sample xt (drawn from N(t * x1 + (1 - t) * x0, sigma)) + and the conditional vector field ut(x1|x0) = x1 - x0, see Eq.(15) [1] + with respect to the minibatch entropic OT plan $\Pi$. + + Parameters + ---------- + x0 : Tensor, shape (bs, *dim) + represents the source minibatch + x1 : Tensor, shape (bs, *dim) + represents the target minibatch + y0 : Tensor, shape (bs) (default: None) + represents the source label minibatch + y1 : Tensor, shape (bs) (default: None) + represents the target label minibatch + (optionally) t : Tensor, shape (bs) + represents the time levels + if None, drawn from uniform [0,1] + return_noise : bool + return the noise sample epsilon + + Returns + ------- + t : FloatTensor, shape (bs) + xt : Tensor, shape (bs, *dim) + represents the samples drawn from probability path pt + ut : conditional vector field ut(x1|x0) = x1 - x0 + (optionally) epsilon : Tensor, shape (bs, *dim) such that xt = mu_t + sigma_t * epsilon + + References + ---------- + [1] Improving and Generalizing Flow-Based Generative Models with minibatch optimal transport, Preprint, Tong et al. + """ + x0, x1, y0, y1 = self.ot_sampler.sample_plan_with_labels(x0, x1, y0, y1) + if return_noise: + t, xt, ut, eps = super().sample_location_and_conditional_flow(x0, x1, t, return_noise) + return t, xt, ut, y0, y1, eps + else: + t, xt, ut = super().sample_location_and_conditional_flow(x0, x1, t, return_noise) + return t, xt, ut, y0, y1 + + +class VariancePreservingConditionalFlowMatcher(ConditionalFlowMatcher): + """Albergo et al. 2023 trigonometric interpolants class. This class inherits the + ConditionalFlowMatcher and override the compute_mu_t and compute_conditional_flow functions in + order to compute [3]'s trigonometric interpolants. + + [3] Stochastic Interpolants: A Unifying Framework for Flows and Diffusions, Albergo et al. + """ + + def compute_mu_t(self, x0, x1, t): + r"""Compute the mean of the probability path (Eq.5) from [3]. + + Parameters + ---------- + x0 : Tensor, shape (bs, *dim) + represents the source minibatch + x1 : Tensor, shape (bs, *dim) + represents the target minibatch + t : FloatTensor, shape (bs) + + Returns + ------- + mean mu_t: cos(pi t/2)x0 + sin(pi t/2)x1 + + References + ---------- + [3] Stochastic Interpolants: A Unifying Framework for Flows and Diffusions, Albergo et al. + """ + t = pad_t_like_x(t, x0) + return torch.cos(math.pi / 2 * t) * x0 + torch.sin(math.pi / 2 * t) * x1 + + def compute_conditional_flow(self, x0, x1, t, xt): + r"""Compute the conditional vector field similar to [3]. + + ut(x1|x0) = pi/2 (cos(pi*t/2) x1 - sin(pi*t/2) x0), + see Eq.(21) [3]. + + Parameters + ---------- + x0 : Tensor, shape (bs, *dim) + represents the source minibatch + x1 : Tensor, shape (bs, *dim) + represents the target minibatch + t : FloatTensor, shape (bs) + xt : Tensor, shape (bs, *dim) + represents the samples drawn from probability path pt + + Returns + ------- + ut : conditional vector field + ut(x1|x0) = pi/2 (cos(pi*t/2) x1 - sin(\pi*t/2) x0) + + References + ---------- + [3] Stochastic Interpolants: A Unifying Framework for Flows and Diffusions, Albergo et al. + """ + del xt + t = pad_t_like_x(t, x0) + return math.pi / 2 * (torch.cos(math.pi / 2 * t) * x1 - torch.sin(math.pi / 2 * t) * x0) + diff --git a/torchcfm/models/__init__.py b/torchcfm/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..da4e87fd2094f6b3449a4387ce6bd348098756af --- /dev/null +++ b/torchcfm/models/__init__.py @@ -0,0 +1 @@ +from .models import MLP diff --git a/torchcfm/models/models.py b/torchcfm/models/models.py new file mode 100644 index 0000000000000000000000000000000000000000..edf49e46a4de2a075329644d7dba960363cb5a60 --- /dev/null +++ b/torchcfm/models/models.py @@ -0,0 +1,53 @@ +import torch +import torch.nn as nn + +class MLP(torch.nn.Module): + def __init__(self, dim, out_dim=None, w=64, time_varying=False): + super().__init__() + self.time_varying = time_varying + if out_dim is None: + out_dim = dim + self.net = torch.nn.Sequential( + torch.nn.Linear(dim + (1 if time_varying else 0), w), + torch.nn.SELU(), + torch.nn.Linear(w, w), + torch.nn.SELU(), + torch.nn.Linear(w, w), + torch.nn.SELU(), + torch.nn.Linear(w, out_dim), + ) + + def forward(self, x): + return self.net(x) + +class MLP_Embedding(torch.nn.Module): + def __init__(self, dim, out_dim=None, w=64, time_embed=100,time_varying=False): + super().__init__() + self.time_varying = time_varying + self.time_index_embedding = nn.Embedding(time_embed, w) + if out_dim is None: + out_dim = dim + self.net = torch.nn.Sequential( + torch.nn.Linear(dim + (1+w if time_varying else w), w), + torch.nn.SELU(), + torch.nn.Linear(w, w), + torch.nn.SELU(), + torch.nn.Linear(w, w), + torch.nn.SELU(), + torch.nn.Linear(w, out_dim), + ) + + def forward(self, x,ti): + embedded_tensor = self.time_index_embedding(ti.to(torch.long)) + return self.net(torch.cat([x,embedded_tensor.squeeze()],dim=-1)) + + +class GradModel(torch.nn.Module): + def __init__(self, action): + super().__init__() + self.action = action + + def forward(self, x): + x = x.requires_grad_(True) + grad = torch.autograd.grad(torch.sum(self.action(x)), x, create_graph=True)[0] + return grad[:, :-1] diff --git a/torchcfm/models/unet/__init__.py b/torchcfm/models/unet/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..50e6e57eba88881b473f6b6edb77be29b7b3c937 --- /dev/null +++ b/torchcfm/models/unet/__init__.py @@ -0,0 +1 @@ +from .unet import UNetModelWrapper as UNetModel diff --git a/torchcfm/models/unet/fp16_util.py b/torchcfm/models/unet/fp16_util.py new file mode 100644 index 0000000000000000000000000000000000000000..93e1dee76cae3028dda290ab39a63359e655e176 --- /dev/null +++ b/torchcfm/models/unet/fp16_util.py @@ -0,0 +1,216 @@ +"""Helpers to train with 16-bit precision.""" + +import numpy as np +import torch as th +import torch.nn as nn +from torch._utils import _flatten_dense_tensors, _unflatten_dense_tensors + +from . import logger + +INITIAL_LOG_LOSS_SCALE = 20.0 + + +def convert_module_to_f16(l): + """Convert primitive modules to float16.""" + if isinstance(l, (nn.Conv1d, nn.Conv2d, nn.Conv3d)): + l.weight.data = l.weight.data.half() + if l.bias is not None: + l.bias.data = l.bias.data.half() + + +def convert_module_to_f32(l): + """Convert primitive modules to float32, undoing convert_module_to_f16().""" + if isinstance(l, (nn.Conv1d, nn.Conv2d, nn.Conv3d)): + l.weight.data = l.weight.data.float() + if l.bias is not None: + l.bias.data = l.bias.data.float() + + +def make_master_params(param_groups_and_shapes): + """Copy model parameters into a (differently-shaped) list of full-precision parameters.""" + master_params = [] + for param_group, shape in param_groups_and_shapes: + master_param = nn.Parameter( + _flatten_dense_tensors([param.detach().float() for (_, param) in param_group]).view( + shape + ) + ) + master_param.requires_grad = True + master_params.append(master_param) + return master_params + + +def model_grads_to_master_grads(param_groups_and_shapes, master_params): + """Copy the gradients from the model parameters into the master parameters from + make_master_params().""" + for master_param, (param_group, shape) in zip(master_params, param_groups_and_shapes): + master_param.grad = _flatten_dense_tensors( + [param_grad_or_zeros(param) for (_, param) in param_group] + ).view(shape) + + +def master_params_to_model_params(param_groups_and_shapes, master_params): + """Copy the master parameter data back into the model parameters.""" + # Without copying to a list, if a generator is passed, this will + # silently not copy any parameters. + for master_param, (param_group, _) in zip(master_params, param_groups_and_shapes): + for (_, param), unflat_master_param in zip( + param_group, unflatten_master_params(param_group, master_param.view(-1)) + ): + param.detach().copy_(unflat_master_param) + + +def unflatten_master_params(param_group, master_param): + return _unflatten_dense_tensors(master_param, [param for (_, param) in param_group]) + + +def get_param_groups_and_shapes(named_model_params): + named_model_params = list(named_model_params) + scalar_vector_named_params = ( + [(n, p) for (n, p) in named_model_params if p.ndim <= 1], + (-1), + ) + matrix_named_params = ( + [(n, p) for (n, p) in named_model_params if p.ndim > 1], + (1, -1), + ) + return [scalar_vector_named_params, matrix_named_params] + + +def master_params_to_state_dict(model, param_groups_and_shapes, master_params, use_fp16): + if use_fp16: + state_dict = model.state_dict() + for master_param, (param_group, _) in zip(master_params, param_groups_and_shapes): + for (name, _), unflat_master_param in zip( + param_group, unflatten_master_params(param_group, master_param.view(-1)) + ): + assert name in state_dict + state_dict[name] = unflat_master_param + else: + state_dict = model.state_dict() + for i, (name, _value) in enumerate(model.named_parameters()): + assert name in state_dict + state_dict[name] = master_params[i] + return state_dict + + +def state_dict_to_master_params(model, state_dict, use_fp16): + if use_fp16: + named_model_params = [(name, state_dict[name]) for name, _ in model.named_parameters()] + param_groups_and_shapes = get_param_groups_and_shapes(named_model_params) + master_params = make_master_params(param_groups_and_shapes) + else: + master_params = [state_dict[name] for name, _ in model.named_parameters()] + return master_params + + +def zero_master_grads(master_params): + for param in master_params: + param.grad = None + + +def zero_grad(model_params): + for param in model_params: + # Taken from https://pytorch.org/docs/stable/_modules/torch/optim/optimizer.html#Optimizer.add_param_group + if param.grad is not None: + param.grad.detach_() + param.grad.zero_() + + +def param_grad_or_zeros(param): + if param.grad is not None: + return param.grad.data.detach() + else: + return th.zeros_like(param) + + +class MixedPrecisionTrainer: + def __init__( + self, + *, + model, + use_fp16=False, + fp16_scale_growth=1e-3, + initial_lg_loss_scale=INITIAL_LOG_LOSS_SCALE, + ): + self.model = model + self.use_fp16 = use_fp16 + self.fp16_scale_growth = fp16_scale_growth + + self.model_params = list(self.model.parameters()) + self.master_params = self.model_params + self.param_groups_and_shapes = None + self.lg_loss_scale = initial_lg_loss_scale + + if self.use_fp16: + self.param_groups_and_shapes = get_param_groups_and_shapes( + self.model.named_parameters() + ) + self.master_params = make_master_params(self.param_groups_and_shapes) + self.model.convert_to_fp16() + + def zero_grad(self): + zero_grad(self.model_params) + + def backward(self, loss: th.Tensor): + if self.use_fp16: + loss_scale = 2**self.lg_loss_scale + (loss * loss_scale).backward() + else: + loss.backward() + + def optimize(self, opt: th.optim.Optimizer): + if self.use_fp16: + return self._optimize_fp16(opt) + else: + return self._optimize_normal(opt) + + def _optimize_fp16(self, opt: th.optim.Optimizer): + logger.logkv_mean("lg_loss_scale", self.lg_loss_scale) + model_grads_to_master_grads(self.param_groups_and_shapes, self.master_params) + grad_norm, param_norm = self._compute_norms(grad_scale=2**self.lg_loss_scale) + if check_overflow(grad_norm): + self.lg_loss_scale -= 1 + logger.log(f"Found NaN, decreased lg_loss_scale to {self.lg_loss_scale}") + zero_master_grads(self.master_params) + return False + + logger.logkv_mean("grad_norm", grad_norm) + logger.logkv_mean("param_norm", param_norm) + + for p in self.master_params: + p.grad.mul_(1.0 / (2**self.lg_loss_scale)) + opt.step() + zero_master_grads(self.master_params) + master_params_to_model_params(self.param_groups_and_shapes, self.master_params) + self.lg_loss_scale += self.fp16_scale_growth + return True + + def _optimize_normal(self, opt: th.optim.Optimizer): + grad_norm, param_norm = self._compute_norms() + logger.logkv_mean("grad_norm", grad_norm) + logger.logkv_mean("param_norm", param_norm) + opt.step() + return True + + def _compute_norms(self, grad_scale=1.0): + grad_norm = 0.0 + param_norm = 0.0 + for p in self.master_params: + with th.no_grad(): + param_norm += th.norm(p, p=2, dtype=th.float32).item() ** 2 + if p.grad is not None: + grad_norm += th.norm(p.grad, p=2, dtype=th.float32).item() ** 2 + return np.sqrt(grad_norm) / grad_scale, np.sqrt(param_norm) + + def master_params_to_state_dict(self, master_params): + return master_params_to_state_dict( + self.model, self.param_groups_and_shapes, master_params, self.use_fp16 + ) + + def state_dict_to_master_params(self, state_dict): + return state_dict_to_master_params(self.model, state_dict, self.use_fp16) + + +def check_overflow(value): + return (value == float("inf")) or (value == -float("inf")) or (value != value) diff --git a/torchcfm/models/unet/logger.py b/torchcfm/models/unet/logger.py new file mode 100644 index 0000000000000000000000000000000000000000..9c6e456ed8a7e643ae0f5a891299cdfd16d29926 --- /dev/null +++ b/torchcfm/models/unet/logger.py @@ -0,0 +1,469 @@ +"""Logger copied from OpenAI baselines to avoid extra RL-based dependencies: + +https://github.com/openai/baselines/blob/ea25b9e8b234e6ee1bca43083f8f3cf974143998/baselines/logger.py +""" + +import datetime +import json +import os +import os.path as osp +import shutil +import sys +import tempfile +import time +import warnings +from collections import defaultdict +from contextlib import contextmanager + +DEBUG = 10 +INFO = 20 +WARN = 30 +ERROR = 40 + +DISABLED = 50 + + +class KVWriter: + def writekvs(self, kvs): + raise NotImplementedError + + +class SeqWriter: + def writeseq(self, seq): + raise NotImplementedError + + +class HumanOutputFormat(KVWriter, SeqWriter): + def __init__(self, filename_or_file): + if isinstance(filename_or_file, str): + self.file = open(filename_or_file, "w") + self.own_file = True + else: + assert hasattr(filename_or_file, "read"), ( + "expected file or str, got %s" % filename_or_file + ) + self.file = filename_or_file + self.own_file = False + + def writekvs(self, kvs): + # Create strings for printing + key2str = {} + for key, val in sorted(kvs.items()): + if hasattr(val, "__float__"): + valstr = "%-8.3g" % val + else: + valstr = str(val) + key2str[self._truncate(key)] = self._truncate(valstr) + + # Find max widths + if len(key2str) == 0: + print("WARNING: tried to write empty key-value dict") + return + else: + keywidth = max(map(len, key2str.keys())) + valwidth = max(map(len, key2str.values())) + + # Write out the data + dashes = "-" * (keywidth + valwidth + 7) + lines = [dashes] + for key, val in sorted(key2str.items(), key=lambda kv: kv[0].lower()): + lines.append( + "| %s%s | %s%s |" + % (key, " " * (keywidth - len(key)), val, " " * (valwidth - len(val))) + ) + lines.append(dashes) + self.file.write("\n".join(lines) + "\n") + + # Flush the output to the file + self.file.flush() + + def _truncate(self, s): + maxlen = 30 + return s[: maxlen - 3] + "..." if len(s) > maxlen else s + + def writeseq(self, seq): + seq = list(seq) + for i, elem in enumerate(seq): + self.file.write(elem) + if i < len(seq) - 1: # add space unless this is the last one + self.file.write(" ") + self.file.write("\n") + self.file.flush() + + def close(self): + if self.own_file: + self.file.close() + + +class JSONOutputFormat(KVWriter): + def __init__(self, filename): + self.file = open(filename, "w") + + def writekvs(self, kvs): + for k, v in sorted(kvs.items()): + if hasattr(v, "dtype"): + kvs[k] = float(v) + self.file.write(json.dumps(kvs) + "\n") + self.file.flush() + + def close(self): + self.file.close() + + +class CSVOutputFormat(KVWriter): + def __init__(self, filename): + self.file = open(filename, "w+t") + self.keys = [] + self.sep = "," + + def writekvs(self, kvs): + # Add our current row to the history + extra_keys = list(kvs.keys() - self.keys) + extra_keys.sort() + if extra_keys: + self.keys.extend(extra_keys) + self.file.seek(0) + lines = self.file.readlines() + self.file.seek(0) + for i, k in enumerate(self.keys): + if i > 0: + self.file.write(",") + self.file.write(k) + self.file.write("\n") + for line in lines[1:]: + self.file.write(line[:-1]) + self.file.write(self.sep * len(extra_keys)) + self.file.write("\n") + for i, k in enumerate(self.keys): + if i > 0: + self.file.write(",") + v = kvs.get(k) + if v is not None: + self.file.write(str(v)) + self.file.write("\n") + self.file.flush() + + def close(self): + self.file.close() + + +class TensorBoardOutputFormat(KVWriter): + """Dumps key/value pairs into TensorBoard's numeric format.""" + + def __init__(self, dir): + os.makedirs(dir, exist_ok=True) + self.dir = dir + self.step = 1 + prefix = "events" + path = osp.join(osp.abspath(dir), prefix) + import tensorflow as tf + from tensorflow.core.util import event_pb2 + from tensorflow.python import pywrap_tensorflow + from tensorflow.python.util import compat + + self.tf = tf + self.event_pb2 = event_pb2 + self.pywrap_tensorflow = pywrap_tensorflow + self.writer = pywrap_tensorflow.EventsWriter(compat.as_bytes(path)) + + def writekvs(self, kvs): + def summary_val(k, v): + kwargs = {"tag": k, "simple_value": float(v)} + return self.tf.Summary.Value(**kwargs) + + summary = self.tf.Summary(value=[summary_val(k, v) for k, v in kvs.items()]) + event = self.event_pb2.Event(wall_time=time.time(), summary=summary) + event.step = self.step # is there any reason why you'd want to specify the step? + self.writer.WriteEvent(event) + self.writer.Flush() + self.step += 1 + + def close(self): + if self.writer: + self.writer.Close() + self.writer = None + + +def make_output_format(format, ev_dir, log_suffix=""): + os.makedirs(ev_dir, exist_ok=True) + if format == "stdout": + return HumanOutputFormat(sys.stdout) + elif format == "log": + return HumanOutputFormat(osp.join(ev_dir, "log%s.txt" % log_suffix)) + elif format == "json": + return JSONOutputFormat(osp.join(ev_dir, "progress%s.json" % log_suffix)) + elif format == "csv": + return CSVOutputFormat(osp.join(ev_dir, "progress%s.csv" % log_suffix)) + elif format == "tensorboard": + return TensorBoardOutputFormat(osp.join(ev_dir, "tb%s" % log_suffix)) + else: + raise ValueError(f"Unknown format specified: {format}") + + +# ================================================================ +# API +# ================================================================ + + +def logkv(key, val): + """Log a value of some diagnostic Call this once for each diagnostic quantity, each iteration + If called many times, last value will be used.""" + get_current().logkv(key, val) + + +def logkv_mean(key, val): + """The same as logkv(), but if called many times, values averaged.""" + get_current().logkv_mean(key, val) + + +def logkvs(d): + """Log a dictionary of key-value pairs.""" + for k, v in d.items(): + logkv(k, v) + + +def dumpkvs(): + """Write all of the diagnostics from the current iteration.""" + return get_current().dumpkvs() + + +def getkvs(): + return get_current().name2val + + +def log(*args, level=INFO): + """Write the sequence of args, with no separators, to the console and output files (if you've + configured an output file).""" + get_current().log(*args, level=level) + + +def debug(*args): + log(*args, level=DEBUG) + + +def info(*args): + log(*args, level=INFO) + + +def warn(*args): + log(*args, level=WARN) + + +def error(*args): + log(*args, level=ERROR) + + +def set_level(level): + """Set logging threshold on current logger.""" + get_current().set_level(level) + + +def set_comm(comm): + get_current().set_comm(comm) + + +def get_dir(): + """Get directory that log files are being written to. + + will be None if there is no output directory (i.e., if you didn't call start) + """ + return get_current().get_dir() + + +record_tabular = logkv +dump_tabular = dumpkvs + + +@contextmanager +def profile_kv(scopename): + logkey = "wait_" + scopename + tstart = time.time() + try: + yield + finally: + get_current().name2val[logkey] += time.time() - tstart + + +def profile(n): + """ + Usage: + @profile("my_func") + def my_func(): code + """ + + def decorator_with_name(func): + def func_wrapper(*args, **kwargs): + with profile_kv(n): + return func(*args, **kwargs) + + return func_wrapper + + return decorator_with_name + + +# ================================================================ +# Backend +# ================================================================ + + +def get_current(): + if Logger.CURRENT is None: + _configure_default_logger() + + return Logger.CURRENT + + +class Logger: + DEFAULT = None # A logger with no output files. (See right below class definition) + # So that you can still log to the terminal without setting up any output files + CURRENT = None # Current logger being used by the free functions above + + def __init__(self, dir, output_formats, comm=None): + self.name2val = defaultdict(float) # values this iteration + self.name2cnt = defaultdict(int) + self.level = INFO + self.dir = dir + self.output_formats = output_formats + self.comm = comm + + # Logging API, forwarded + # ---------------------------------------- + def logkv(self, key, val): + self.name2val[key] = val + + def logkv_mean(self, key, val): + oldval, cnt = self.name2val[key], self.name2cnt[key] + self.name2val[key] = oldval * cnt / (cnt + 1) + val / (cnt + 1) + self.name2cnt[key] = cnt + 1 + + def dumpkvs(self): + if self.comm is None: + d = self.name2val + else: + d = mpi_weighted_mean( + self.comm, + {name: (val, self.name2cnt.get(name, 1)) for (name, val) in self.name2val.items()}, + ) + if self.comm.rank != 0: + d["dummy"] = 1 # so we don't get a warning about empty dict + out = d.copy() # Return the dict for unit testing purposes + for fmt in self.output_formats: + if isinstance(fmt, KVWriter): + fmt.writekvs(d) + self.name2val.clear() + self.name2cnt.clear() + return out + + def log(self, *args, level=INFO): + if self.level <= level: + self._do_log(args) + + # Configuration + # ---------------------------------------- + def set_level(self, level): + self.level = level + + def set_comm(self, comm): + self.comm = comm + + def get_dir(self): + return self.dir + + def close(self): + for fmt in self.output_formats: + fmt.close() + + # Misc + # ---------------------------------------- + def _do_log(self, args): + for fmt in self.output_formats: + if isinstance(fmt, SeqWriter): + fmt.writeseq(map(str, args)) + + +def get_rank_without_mpi_import(): + # check environment variables here instead of importing mpi4py + # to avoid calling MPI_Init() when this module is imported + for varname in ["PMI_RANK", "OMPI_COMM_WORLD_RANK"]: + if varname in os.environ: + return int(os.environ[varname]) + return 0 + + +def mpi_weighted_mean(comm, local_name2valcount): + """ + Copied from: https://github.com/openai/baselines/blob/ea25b9e8b234e6ee1bca43083f8f3cf974143998/baselines/common/mpi_util.py#L110 + Perform a weighted average over dicts that are each on a different node + Input: local_name2valcount: dict mapping key -> (value, count) + Returns: key -> mean + """ + all_name2valcount = comm.gather(local_name2valcount) + if comm.rank == 0: + name2sum = defaultdict(float) + name2count = defaultdict(float) + for n2vc in all_name2valcount: + for name, (val, count) in n2vc.items(): + try: + val = float(val) + except ValueError: + if comm.rank == 0: + warnings.warn(f"WARNING: tried to compute mean on non-float {name}={val}") + else: + name2sum[name] += val * count + name2count[name] += count + return {name: name2sum[name] / name2count[name] for name in name2sum} + else: + return {} + + +def configure(dir=None, format_strs=None, comm=None, log_suffix=""): + """If comm is provided, average all numerical stats across that comm.""" + if dir is None: + dir = os.getenv("OPENAI_LOGDIR") + if dir is None: + dir = osp.join( + tempfile.gettempdir(), + datetime.datetime.now().strftime("openai-%Y-%m-%d-%H-%M-%S-%f"), + ) + assert isinstance(dir, str) + dir = os.path.expanduser(dir) + os.makedirs(os.path.expanduser(dir), exist_ok=True) + + rank = get_rank_without_mpi_import() + if rank > 0: + log_suffix = log_suffix + "-rank%03i" % rank + + if format_strs is None: + if rank == 0: + format_strs = os.getenv("OPENAI_LOG_FORMAT", "stdout,log,csv").split(",") + else: + format_strs = os.getenv("OPENAI_LOG_FORMAT_MPI", "log").split(",") + format_strs = filter(None, format_strs) + output_formats = [make_output_format(f, dir, log_suffix) for f in format_strs] + + Logger.CURRENT = Logger(dir=dir, output_formats=output_formats, comm=comm) + if output_formats: + log("Logging to %s" % dir) + + +def _configure_default_logger(): + configure() + Logger.DEFAULT = Logger.CURRENT + + +def reset(): + if Logger.CURRENT is not Logger.DEFAULT: + Logger.CURRENT.close() + Logger.CURRENT = Logger.DEFAULT + log("Reset logger") + + +@contextmanager +def scoped_configure(dir=None, format_strs=None, comm=None): + prevlogger = Logger.CURRENT + configure(dir=dir, format_strs=format_strs, comm=comm) + try: + yield + finally: + Logger.CURRENT.close() + Logger.CURRENT = prevlogger diff --git a/torchcfm/models/unet/nn.py b/torchcfm/models/unet/nn.py new file mode 100644 index 0000000000000000000000000000000000000000..5e454703472e201d61f314786909af4a55f137e6 --- /dev/null +++ b/torchcfm/models/unet/nn.py @@ -0,0 +1,153 @@ +"""Various utilities for neural networks.""" + +import math + +import torch as th +import torch.nn as nn + + +# PyTorch 1.7 has SiLU, but we support PyTorch 1.5. +class SiLU(nn.Module): + def forward(self, x): + return x * th.sigmoid(x) + + +class GroupNorm32(nn.GroupNorm): + def forward(self, x): + return super().forward(x.float()).type(x.dtype) + + +def conv_nd(dims, *args, **kwargs): + """Create a 1D, 2D, or 3D convolution module.""" + if dims == 1: + return nn.Conv1d(*args, **kwargs) + elif dims == 2: + return nn.Conv2d(*args, **kwargs) + elif dims == 3: + return nn.Conv3d(*args, **kwargs) + raise ValueError(f"unsupported dimensions: {dims}") + + +def linear(*args, **kwargs): + """Create a linear module.""" + return nn.Linear(*args, **kwargs) + + +def avg_pool_nd(dims, *args, **kwargs): + """Create a 1D, 2D, or 3D average pooling module.""" + if dims == 1: + return nn.AvgPool1d(*args, **kwargs) + elif dims == 2: + return nn.AvgPool2d(*args, **kwargs) + elif dims == 3: + return nn.AvgPool3d(*args, **kwargs) + raise ValueError(f"unsupported dimensions: {dims}") + + +def update_ema(target_params, source_params, rate=0.99): + """Update target parameters to be closer to those of source parameters using an exponential + moving average. + + :param target_params: the target parameter sequence. + :param source_params: the source parameter sequence. + :param rate: the EMA rate (closer to 1 means slower). + """ + for targ, src in zip(target_params, source_params): + targ.detach().mul_(rate).add_(src, alpha=1 - rate) + + +def zero_module(module): + """Zero out the parameters of a module and return it.""" + for p in module.parameters(): + p.detach().zero_() + return module + + +def scale_module(module, scale): + """Scale the parameters of a module and return it.""" + for p in module.parameters(): + p.detach().mul_(scale) + return module + + +def mean_flat(tensor): + """Take the mean over all non-batch dimensions.""" + return tensor.mean(dim=list(range(1, len(tensor.shape)))) + + +def normalization(channels): + """Make a standard normalization layer. + + :param channels: number of input channels. + :return: an nn.Module for normalization. + """ + return GroupNorm32(32, channels) + + +def timestep_embedding(timesteps, dim, max_period=10000): + """Create sinusoidal timestep embeddings. + + :param timesteps: a 1-D Tensor of N indices, one per batch element. These may be fractional. + :param dim: the dimension of the output. + :param max_period: controls the minimum frequency of the embeddings. + :return: an [N x dim] Tensor of positional embeddings. + """ + half = dim // 2 + freqs = th.exp( + -math.log(max_period) + * th.arange(start=0, end=half, dtype=th.float32, device=timesteps.device) + / half + ) + args = timesteps[:, None].float() * freqs[None] + embedding = th.cat([th.cos(args), th.sin(args)], dim=-1) + if dim % 2: + embedding = th.cat([embedding, th.zeros_like(embedding[:, :1])], dim=-1) + return embedding + + +def checkpoint(func, inputs, params, flag): + """Evaluate a function without caching intermediate activations, allowing for reduced memory at + the expense of extra compute in the backward pass. + + :param func: the function to evaluate. + :param inputs: the argument sequence to pass to `func`. + :param params: a sequence of parameters `func` depends on but does not + explicitly take as arguments. + :param flag: if False, disable gradient checkpointing. + """ + if flag: + args = tuple(inputs) + tuple(params) + return CheckpointFunction.apply(func, len(inputs), *args) + else: + return func(*inputs) + + +class CheckpointFunction(th.autograd.Function): + @staticmethod + def forward(ctx, run_function, length, *args): + ctx.run_function = run_function + ctx.input_tensors = list(args[:length]) + ctx.input_params = list(args[length:]) + with th.no_grad(): + output_tensors = ctx.run_function(*ctx.input_tensors) + return output_tensors + + @staticmethod + def backward(ctx, *output_grads): + ctx.input_tensors = [x.detach().requires_grad_(True) for x in ctx.input_tensors] + with th.enable_grad(): + # Fixes a bug where the first op in run_function modifies the + # Tensor storage in place, which is not allowed for detach()'d + # Tensors. + shallow_copies = [x.view_as(x) for x in ctx.input_tensors] + output_tensors = ctx.run_function(*shallow_copies) + input_grads = th.autograd.grad( + output_tensors, + ctx.input_tensors + ctx.input_params, + output_grads, + allow_unused=True, + ) + del ctx.input_tensors + del ctx.input_params + del output_tensors + return (None, None) + input_grads diff --git a/torchcfm/models/unet/unet.py b/torchcfm/models/unet/unet.py new file mode 100644 index 0000000000000000000000000000000000000000..8c8a63dc68c055310a0fa10613784ef27a2cfa9b --- /dev/null +++ b/torchcfm/models/unet/unet.py @@ -0,0 +1,925 @@ +"""From https://raw.githubusercontent.com/openai/guided-diffusion/main/guided_diffusion/unet.py.""" +import math +from abc import abstractmethod + +import numpy as np +import torch as th +import torch.nn as nn +import torch.nn.functional as F + +from .fp16_util import convert_module_to_f16, convert_module_to_f32 +from .nn import ( + avg_pool_nd, + checkpoint, + conv_nd, + linear, + normalization, + timestep_embedding, + zero_module, +) + + +class AttentionPool2d(nn.Module): + """Adapted from CLIP: https://github.com/openai/CLIP/blob/main/clip/model.py.""" + + def __init__( + self, + spacial_dim: int, + embed_dim: int, + num_heads_channels: int, + output_dim: int = None, + ): + super().__init__() + self.positional_embedding = nn.Parameter( + th.randn(embed_dim, spacial_dim**2 + 1) / embed_dim**0.5 + ) + self.qkv_proj = conv_nd(1, embed_dim, 3 * embed_dim, 1) + self.c_proj = conv_nd(1, embed_dim, output_dim or embed_dim, 1) + self.num_heads = embed_dim // num_heads_channels + self.attention = QKVAttention(self.num_heads) + + def forward(self, x): + b, c, *_spatial = x.shape + x = x.reshape(b, c, -1) # NC(HW) + x = th.cat([x.mean(dim=-1, keepdim=True), x], dim=-1) # NC(HW+1) + x = x + self.positional_embedding[None, :, :].to(x.dtype) # NC(HW+1) + x = self.qkv_proj(x) + x = self.attention(x) + x = self.c_proj(x) + return x[:, :, 0] + + +class TimestepBlock(nn.Module): + """Any module where forward() takes timestep embeddings as a second argument.""" + + @abstractmethod + def forward(self, x, emb): + """Apply the module to `x` given `emb` timestep embeddings.""" + + +class TimestepEmbedSequential(nn.Sequential, TimestepBlock): + """A sequential module that passes timestep embeddings to the children that support it as an + extra input.""" + + def forward(self, x, emb): + for layer in self: + if isinstance(layer, TimestepBlock): + x = layer(x, emb) + else: + x = layer(x) + return x + + +class Upsample(nn.Module): + """An upsampling layer with an optional convolution. + + :param channels: channels in the inputs and outputs. + :param use_conv: a bool determining if a convolution is applied. + :param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then upsampling occurs in the + inner-two dimensions. + """ + + def __init__(self, channels, use_conv, dims=2, out_channels=None): + super().__init__() + self.channels = channels + self.out_channels = out_channels or channels + self.use_conv = use_conv + self.dims = dims + if use_conv: + self.conv = conv_nd(dims, self.channels, self.out_channels, 3, padding=1) + + def forward(self, x): + assert x.shape[1] == self.channels + if self.dims == 3: + x = F.interpolate(x, (x.shape[2], x.shape[3] * 2, x.shape[4] * 2), mode="nearest") + else: + x = F.interpolate(x, scale_factor=2, mode="nearest") + if self.use_conv: + x = self.conv(x) + return x + + +class Downsample(nn.Module): + """A downsampling layer with an optional convolution. + + :param channels: channels in the inputs and outputs. + :param use_conv: a bool determining if a convolution is applied. + :param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then downsampling occurs in the + inner-two dimensions. + """ + + def __init__(self, channels, use_conv, dims=2, out_channels=None): + super().__init__() + self.channels = channels + self.out_channels = out_channels or channels + self.use_conv = use_conv + self.dims = dims + stride = 2 if dims != 3 else (1, 2, 2) + if use_conv: + self.op = conv_nd(dims, self.channels, self.out_channels, 3, stride=stride, padding=1) + else: + assert self.channels == self.out_channels + self.op = avg_pool_nd(dims, kernel_size=stride, stride=stride) + + def forward(self, x): + assert x.shape[1] == self.channels + return self.op(x) + + +class ResBlock(TimestepBlock): + """A residual block that can optionally change the number of channels. + + :param channels: the number of input channels. + :param emb_channels: the number of timestep embedding channels. + :param dropout: the rate of dropout. + :param out_channels: if specified, the number of out channels. + :param use_conv: if True and out_channels is specified, use a spatial convolution instead of a + smaller 1x1 convolution to change the channels in the skip connection. + :param dims: determines if the signal is 1D, 2D, or 3D. + :param use_checkpoint: if True, use gradient checkpointing on this module. + :param up: if True, use this block for upsampling. + :param down: if True, use this block for downsampling. + """ + + def __init__( + self, + channels, + emb_channels, + dropout, + out_channels=None, + use_conv=False, + use_scale_shift_norm=False, + dims=2, + use_checkpoint=False, + up=False, + down=False, + ): + super().__init__() + self.channels = channels + self.emb_channels = emb_channels + self.dropout = dropout + self.out_channels = out_channels or channels + self.use_conv = use_conv + self.use_checkpoint = use_checkpoint + self.use_scale_shift_norm = use_scale_shift_norm + + self.in_layers = nn.Sequential( + normalization(channels), + nn.SiLU(), + conv_nd(dims, channels, self.out_channels, 3, padding=1), + ) + + self.updown = up or down + + if up: + self.h_upd = Upsample(channels, False, dims) + self.x_upd = Upsample(channels, False, dims) + elif down: + self.h_upd = Downsample(channels, False, dims) + self.x_upd = Downsample(channels, False, dims) + else: + self.h_upd = self.x_upd = nn.Identity() + + self.emb_layers = nn.Sequential( + nn.SiLU(), + linear( + emb_channels, + 2 * self.out_channels if use_scale_shift_norm else self.out_channels, + ), + ) + self.out_layers = nn.Sequential( + normalization(self.out_channels), + nn.SiLU(), + nn.Dropout(p=dropout), + zero_module(conv_nd(dims, self.out_channels, self.out_channels, 3, padding=1)), + ) + + if self.out_channels == channels: + self.skip_connection = nn.Identity() + elif use_conv: + self.skip_connection = conv_nd(dims, channels, self.out_channels, 3, padding=1) + else: + self.skip_connection = conv_nd(dims, channels, self.out_channels, 1) + + def forward(self, x, emb): + """Apply the block to a Tensor, conditioned on a timestep embedding. + + :param x: an [N x C x ...] Tensor of features. + :param emb: an [N x emb_channels] Tensor of timestep embeddings. + :return: an [N x C x ...] Tensor of outputs. + """ + return checkpoint(self._forward, (x, emb), self.parameters(), self.use_checkpoint) + + def _forward(self, x, emb): + if self.updown: + in_rest, in_conv = self.in_layers[:-1], self.in_layers[-1] + h = in_rest(x) + h = self.h_upd(h) + x = self.x_upd(x) + h = in_conv(h) + else: + h = self.in_layers(x) + emb_out = self.emb_layers(emb).type(h.dtype) + while len(emb_out.shape) < len(h.shape): + emb_out = emb_out[..., None] + if self.use_scale_shift_norm: + out_norm, out_rest = self.out_layers[0], self.out_layers[1:] + scale, shift = th.chunk(emb_out, 2, dim=1) + h = out_norm(h) * (1 + scale) + shift + h = out_rest(h) + else: + h = h + emb_out + h = self.out_layers(h) + return self.skip_connection(x) + h + + +class AttentionBlock(nn.Module): + """An attention block that allows spatial positions to attend to each other. + + Originally ported from here, but adapted to the N-d case. + https://github.com/hojonathanho/diffusion/blob/1e0dceb3b3495bbe19116a5e1b3596cd0706c543/diffusion_tf/models/unet.py#L66. + """ + + def __init__( + self, + channels, + num_heads=1, + num_head_channels=-1, + use_checkpoint=False, + use_new_attention_order=False, + ): + super().__init__() + self.channels = channels + if num_head_channels == -1: + self.num_heads = num_heads + else: + assert ( + channels % num_head_channels == 0 + ), f"q,k,v channels {channels} is not divisible by num_head_channels {num_head_channels}" + self.num_heads = channels // num_head_channels + self.use_checkpoint = use_checkpoint + self.norm = normalization(channels) + self.qkv = conv_nd(1, channels, channels * 3, 1) + if use_new_attention_order: + # split qkv before split heads + self.attention = QKVAttention(self.num_heads) + else: + # split heads before split qkv + self.attention = QKVAttentionLegacy(self.num_heads) + + self.proj_out = zero_module(conv_nd(1, channels, channels, 1)) + + def forward(self, x): + return checkpoint(self._forward, (x,), self.parameters(), True) + + def _forward(self, x): + b, c, *spatial = x.shape + x = x.reshape(b, c, -1) + qkv = self.qkv(self.norm(x)) + h = self.attention(qkv) + h = self.proj_out(h) + return (x + h).reshape(b, c, *spatial) + + +def count_flops_attn(model, _x, y): + """A counter for the `thop` package to count the operations in an attention operation. + + Meant to be used like: + macs, params = thop.profile( + model, + inputs=(inputs, timestamps), + custom_ops={QKVAttention: QKVAttention.count_flops}, + ) + """ + b, c, *spatial = y[0].shape + num_spatial = int(np.prod(spatial)) + # We perform two matmuls with the same number of ops. + # The first computes the weight matrix, the second computes + # the combination of the value vectors. + matmul_ops = 2 * b * (num_spatial**2) * c + model.total_ops += th.DoubleTensor([matmul_ops]) + + +class QKVAttentionLegacy(nn.Module): + """A module which performs QKV attention. + + Matches legacy QKVAttention + input/output heads shaping + """ + + def __init__(self, n_heads): + super().__init__() + self.n_heads = n_heads + + def forward(self, qkv): + """Apply QKV attention. + + :param qkv: an [N x (H * 3 * C) x T] tensor of Qs, Ks, and Vs. + :return: an [N x (H * C) x T] tensor after attention. + """ + bs, width, length = qkv.shape + assert width % (3 * self.n_heads) == 0 + ch = width // (3 * self.n_heads) + q, k, v = qkv.reshape(bs * self.n_heads, ch * 3, length).split(ch, dim=1) + scale = 1 / math.sqrt(math.sqrt(ch)) + weight = th.einsum( + "bct,bcs->bts", q * scale, k * scale + ) # More stable with f16 than dividing afterwards + weight = th.softmax(weight.float(), dim=-1).type(weight.dtype) + a = th.einsum("bts,bcs->bct", weight, v) + return a.reshape(bs, -1, length) + + @staticmethod + def count_flops(model, _x, y): + return count_flops_attn(model, _x, y) + + +class QKVAttention(nn.Module): + """A module which performs QKV attention and splits in a different order.""" + + def __init__(self, n_heads): + super().__init__() + self.n_heads = n_heads + + def forward(self, qkv): + """Apply QKV attention. + + :param qkv: an [N x (3 * H * C) x T] tensor of Qs, Ks, and Vs. + :return: an [N x (H * C) x T] tensor after attention. + """ + bs, width, length = qkv.shape + assert width % (3 * self.n_heads) == 0 + ch = width // (3 * self.n_heads) + q, k, v = qkv.chunk(3, dim=1) + scale = 1 / math.sqrt(math.sqrt(ch)) + weight = th.einsum( + "bct,bcs->bts", + (q * scale).view(bs * self.n_heads, ch, length), + (k * scale).view(bs * self.n_heads, ch, length), + ) # More stable with f16 than dividing afterwards + weight = th.softmax(weight.float(), dim=-1).type(weight.dtype) + a = th.einsum("bts,bcs->bct", weight, v.reshape(bs * self.n_heads, ch, length)) + return a.reshape(bs, -1, length) + + @staticmethod + def count_flops(model, _x, y): + return count_flops_attn(model, _x, y) + + +class UNetModel(nn.Module): + """The full UNet model with attention and timestep embedding. + + :param in_channels: channels in the input Tensor. + :param model_channels: base channel count for the model. + :param out_channels: channels in the output Tensor. + :param num_res_blocks: number of residual blocks per downsample. + :param attention_resolutions: a collection of downsample rates at which + attention will take place. May be a set, list, or tuple. + For example, if this contains 4, then at 4x downsampling, attention + will be used. + :param dropout: the dropout probability. + :param channel_mult: channel multiplier for each level of the UNet. + :param conv_resample: if True, use learned convolutions for upsampling and + downsampling. + :param dims: determines if the signal is 1D, 2D, or 3D. + :param num_classes: if specified (as an int), then this model will be + class-conditional with `num_classes` classes. + :param use_checkpoint: use gradient checkpointing to reduce memory usage. + :param num_heads: the number of attention heads in each attention layer. + :param num_heads_channels: if specified, ignore num_heads and instead use + a fixed channel width per attention head. + :param num_heads_upsample: works with num_heads to set a different number + of heads for upsampling. Deprecated. + :param use_scale_shift_norm: use a FiLM-like conditioning mechanism. + :param resblock_updown: use residual blocks for up/downsampling. + :param use_new_attention_order: use a different attention pattern for potentially + increased efficiency. + """ + + def __init__( + self, + image_size, + in_channels, + model_channels, + out_channels, + num_res_blocks, + attention_resolutions, + dropout=0, + channel_mult=(1, 2, 4, 8), + conv_resample=True, + dims=2, + num_classes=None, + use_checkpoint=False, + use_fp16=False, + num_heads=1, + num_head_channels=-1, + num_heads_upsample=-1, + use_scale_shift_norm=False, + resblock_updown=False, + use_new_attention_order=False, + ): + super().__init__() + + if num_heads_upsample == -1: + num_heads_upsample = num_heads + + self.image_size = image_size + self.in_channels = in_channels + self.model_channels = model_channels + self.out_channels = out_channels + self.num_res_blocks = num_res_blocks + self.attention_resolutions = attention_resolutions + self.dropout = dropout + self.channel_mult = channel_mult + self.conv_resample = conv_resample + self.num_classes = num_classes + self.use_checkpoint = use_checkpoint + self.dtype = th.float16 if use_fp16 else th.float32 + self.num_heads = num_heads + self.num_head_channels = num_head_channels + self.num_heads_upsample = num_heads_upsample + + time_embed_dim = model_channels * 4 + self.time_embed = nn.Sequential( + linear(model_channels, time_embed_dim), + nn.SiLU(), + linear(time_embed_dim, time_embed_dim), + ) + + if self.num_classes is not None: + self.label_emb = nn.Embedding(num_classes, time_embed_dim) + + ch = input_ch = int(channel_mult[0] * model_channels) + self.input_blocks = nn.ModuleList( + [TimestepEmbedSequential(conv_nd(dims, in_channels, ch, 3, padding=1))] + ) + self._feature_size = ch + input_block_chans = [ch] + ds = 1 + for level, mult in enumerate(channel_mult): + for _ in range(num_res_blocks): + layers = [ + ResBlock( + ch, + time_embed_dim, + dropout, + out_channels=int(mult * model_channels), + dims=dims, + use_checkpoint=use_checkpoint, + use_scale_shift_norm=use_scale_shift_norm, + ) + ] + ch = int(mult * model_channels) + if ds in attention_resolutions: + layers.append( + AttentionBlock( + ch, + use_checkpoint=use_checkpoint, + num_heads=num_heads, + num_head_channels=num_head_channels, + use_new_attention_order=use_new_attention_order, + ) + ) + self.input_blocks.append(TimestepEmbedSequential(*layers)) + self._feature_size += ch + input_block_chans.append(ch) + if level != len(channel_mult) - 1: + out_ch = ch + self.input_blocks.append( + TimestepEmbedSequential( + ResBlock( + ch, + time_embed_dim, + dropout, + out_channels=out_ch, + dims=dims, + use_checkpoint=use_checkpoint, + use_scale_shift_norm=use_scale_shift_norm, + down=True, + ) + if resblock_updown + else Downsample(ch, conv_resample, dims=dims, out_channels=out_ch) + ) + ) + ch = out_ch + input_block_chans.append(ch) + ds *= 2 + self._feature_size += ch + + self.middle_block = TimestepEmbedSequential( + ResBlock( + ch, + time_embed_dim, + dropout, + dims=dims, + use_checkpoint=use_checkpoint, + use_scale_shift_norm=use_scale_shift_norm, + ), + AttentionBlock( + ch, + use_checkpoint=use_checkpoint, + num_heads=num_heads, + num_head_channels=num_head_channels, + use_new_attention_order=use_new_attention_order, + ), + ResBlock( + ch, + time_embed_dim, + dropout, + dims=dims, + use_checkpoint=use_checkpoint, + use_scale_shift_norm=use_scale_shift_norm, + ), + ) + self._feature_size += ch + + self.output_blocks = nn.ModuleList([]) + for level, mult in list(enumerate(channel_mult))[::-1]: + for i in range(num_res_blocks + 1): + ich = input_block_chans.pop() + layers = [ + ResBlock( + ch + ich, + time_embed_dim, + dropout, + out_channels=int(model_channels * mult), + dims=dims, + use_checkpoint=use_checkpoint, + use_scale_shift_norm=use_scale_shift_norm, + ) + ] + ch = int(model_channels * mult) + if ds in attention_resolutions: + layers.append( + AttentionBlock( + ch, + use_checkpoint=use_checkpoint, + num_heads=num_heads_upsample, + num_head_channels=num_head_channels, + use_new_attention_order=use_new_attention_order, + ) + ) + if level and i == num_res_blocks: + out_ch = ch + layers.append( + ResBlock( + ch, + time_embed_dim, + dropout, + out_channels=out_ch, + dims=dims, + use_checkpoint=use_checkpoint, + use_scale_shift_norm=use_scale_shift_norm, + up=True, + ) + if resblock_updown + else Upsample(ch, conv_resample, dims=dims, out_channels=out_ch) + ) + ds //= 2 + self.output_blocks.append(TimestepEmbedSequential(*layers)) + self._feature_size += ch + + self.out = nn.Sequential( + normalization(ch), + nn.SiLU(), + zero_module(conv_nd(dims, input_ch, out_channels, 3, padding=1)), + ) + + def convert_to_fp16(self): + """Convert the torso of the model to float16.""" + self.input_blocks.apply(convert_module_to_f16) + self.middle_block.apply(convert_module_to_f16) + self.output_blocks.apply(convert_module_to_f16) + + def convert_to_fp32(self): + """Convert the torso of the model to float32.""" + self.input_blocks.apply(convert_module_to_f32) + self.middle_block.apply(convert_module_to_f32) + self.output_blocks.apply(convert_module_to_f32) + + def forward(self, t, x, y=None): + """Apply the model to an input batch. + + :param x: an [N x C x ...] Tensor of inputs. + :param timesteps: a 1-D batch of timesteps. + :param y: an [N] Tensor of labels, if class-conditional. + :return: an [N x C x ...] Tensor of outputs. + """ + timesteps = t + assert (y is not None) == ( + self.num_classes is not None + ), "must specify y if and only if the model is class-conditional" + while timesteps.dim() > 1: + print(timesteps.shape) + timesteps = timesteps[:, 0] + if timesteps.dim() == 0: + timesteps = timesteps.repeat(x.shape[0]) + + hs = [] + emb = self.time_embed(timestep_embedding(timesteps, self.model_channels)) + + if self.num_classes is not None: + assert y.shape == (x.shape[0],) + emb = emb + self.label_emb(y) + + h = x.type(self.dtype) + for module in self.input_blocks: + h = module(h, emb) + hs.append(h) + h = self.middle_block(h, emb) + for module in self.output_blocks: + h = th.cat([h, hs.pop()], dim=1) + h = module(h, emb) + h = h.type(x.dtype) + return self.out(h) + + +class SuperResModel(UNetModel): + """A UNetModel that performs super-resolution. + + Expects an extra kwarg `low_res` to condition on a low-resolution image. + """ + + def __init__(self, image_size, in_channels, *args, **kwargs): + super().__init__(image_size, in_channels * 2, *args, **kwargs) + + def forward(self, x, timesteps, low_res=None, **kwargs): + _, _, new_height, new_width = x.shape + upsampled = F.interpolate(low_res, (new_height, new_width), mode="bilinear") + x = th.cat([x, upsampled], dim=1) + return super().forward(x, timesteps, **kwargs) + + +class EncoderUNetModel(nn.Module): + """The half UNet model with attention and timestep embedding. + + For usage, see UNet. + """ + + def __init__( + self, + image_size, + in_channels, + model_channels, + out_channels, + num_res_blocks, + attention_resolutions, + dropout=0, + channel_mult=(1, 2, 4, 8), + conv_resample=True, + dims=2, + use_checkpoint=False, + use_fp16=False, + num_heads=1, + num_head_channels=-1, + num_heads_upsample=-1, + use_scale_shift_norm=False, + resblock_updown=False, + use_new_attention_order=False, + pool="adaptive", + ): + super().__init__() + + if num_heads_upsample == -1: + num_heads_upsample = num_heads + + self.in_channels = in_channels + self.model_channels = model_channels + self.out_channels = out_channels + self.num_res_blocks = num_res_blocks + self.attention_resolutions = attention_resolutions + self.dropout = dropout + self.channel_mult = channel_mult + self.conv_resample = conv_resample + self.use_checkpoint = use_checkpoint + self.dtype = th.float16 if use_fp16 else th.float32 + self.num_heads = num_heads + self.num_head_channels = num_head_channels + self.num_heads_upsample = num_heads_upsample + + time_embed_dim = model_channels * 4 + self.time_embed = nn.Sequential( + linear(model_channels, time_embed_dim), + nn.SiLU(), + linear(time_embed_dim, time_embed_dim), + ) + + ch = int(channel_mult[0] * model_channels) + self.input_blocks = nn.ModuleList( + [TimestepEmbedSequential(conv_nd(dims, in_channels, ch, 3, padding=1))] + ) + self._feature_size = ch + input_block_chans = [ch] + ds = 1 + for level, mult in enumerate(channel_mult): + for _ in range(num_res_blocks): + layers = [ + ResBlock( + ch, + time_embed_dim, + dropout, + out_channels=int(mult * model_channels), + dims=dims, + use_checkpoint=use_checkpoint, + use_scale_shift_norm=use_scale_shift_norm, + ) + ] + ch = int(mult * model_channels) + if ds in attention_resolutions: + layers.append( + AttentionBlock( + ch, + use_checkpoint=use_checkpoint, + num_heads=num_heads, + num_head_channels=num_head_channels, + use_new_attention_order=use_new_attention_order, + ) + ) + self.input_blocks.append(TimestepEmbedSequential(*layers)) + self._feature_size += ch + input_block_chans.append(ch) + if level != len(channel_mult) - 1: + out_ch = ch + self.input_blocks.append( + TimestepEmbedSequential( + ResBlock( + ch, + time_embed_dim, + dropout, + out_channels=out_ch, + dims=dims, + use_checkpoint=use_checkpoint, + use_scale_shift_norm=use_scale_shift_norm, + down=True, + ) + if resblock_updown + else Downsample(ch, conv_resample, dims=dims, out_channels=out_ch) + ) + ) + ch = out_ch + input_block_chans.append(ch) + ds *= 2 + self._feature_size += ch + + self.middle_block = TimestepEmbedSequential( + ResBlock( + ch, + time_embed_dim, + dropout, + dims=dims, + use_checkpoint=use_checkpoint, + use_scale_shift_norm=use_scale_shift_norm, + ), + AttentionBlock( + ch, + use_checkpoint=use_checkpoint, + num_heads=num_heads, + num_head_channels=num_head_channels, + use_new_attention_order=use_new_attention_order, + ), + ResBlock( + ch, + time_embed_dim, + dropout, + dims=dims, + use_checkpoint=use_checkpoint, + use_scale_shift_norm=use_scale_shift_norm, + ), + ) + self._feature_size += ch + self.pool = pool + if pool == "adaptive": + self.out = nn.Sequential( + normalization(ch), + nn.SiLU(), + nn.AdaptiveAvgPool2d((1, 1)), + zero_module(conv_nd(dims, ch, out_channels, 1)), + nn.Flatten(), + ) + elif pool == "attention": + assert num_head_channels != -1 + self.out = nn.Sequential( + normalization(ch), + nn.SiLU(), + AttentionPool2d((image_size // ds), ch, num_head_channels, out_channels), + ) + elif pool == "spatial": + self.out = nn.Sequential( + nn.Linear(self._feature_size, 2048), + nn.ReLU(), + nn.Linear(2048, self.out_channels), + ) + elif pool == "spatial_v2": + self.out = nn.Sequential( + nn.Linear(self._feature_size, 2048), + normalization(2048), + nn.SiLU(), + nn.Linear(2048, self.out_channels), + ) + else: + raise NotImplementedError(f"Unexpected {pool} pooling") + + def convert_to_fp16(self): + """Convert the torso of the model to float16.""" + self.input_blocks.apply(convert_module_to_f16) + self.middle_block.apply(convert_module_to_f16) + + def convert_to_fp32(self): + """Convert the torso of the model to float32.""" + self.input_blocks.apply(convert_module_to_f32) + self.middle_block.apply(convert_module_to_f32) + + def forward(self, x, timesteps): + """Apply the model to an input batch. + + :param x: an [N x C x ...] Tensor of inputs. + :param timesteps: a 1-D batch of timesteps. + :return: an [N x K] Tensor of outputs. + """ + emb = self.time_embed(timestep_embedding(timesteps, self.model_channels)) + + results = [] + h = x.type(self.dtype) + for module in self.input_blocks: + h = module(h, emb) + if self.pool.startswith("spatial"): + results.append(h.type(x.dtype).mean(dim=(2, 3))) + h = self.middle_block(h, emb) + if self.pool.startswith("spatial"): + results.append(h.type(x.dtype).mean(dim=(2, 3))) + h = th.cat(results, axis=-1) + return self.out(h) + else: + h = h.type(x.dtype) + return self.out(h) + + +NUM_CLASSES = 1000 + + +class UNetModelWrapper(UNetModel): + def __init__( + self, + dim, + num_channels, + num_res_blocks, + channel_mult=None, + learn_sigma=False, + class_cond=False, + num_classes=NUM_CLASSES, + use_checkpoint=False, + attention_resolutions="16", + num_heads=1, + num_head_channels=-1, + num_heads_upsample=-1, + use_scale_shift_norm=False, + dropout=0, + resblock_updown=False, + use_fp16=False, + use_new_attention_order=False, + ): + """Dim (tuple): (C, H, W)""" + image_size = dim[-1] + if channel_mult is None: + if image_size == 512: + channel_mult = (0.5, 1, 1, 2, 2, 4, 4) + elif image_size == 256: + channel_mult = (1, 1, 2, 2, 4, 4) + elif image_size == 128: + channel_mult = (1, 1, 2, 3, 4) + elif image_size == 64: + channel_mult = (1, 2, 3, 4) + elif image_size == 32: + channel_mult = (1, 2, 2, 2) + elif image_size == 28: + channel_mult = (1, 2, 2) + else: + raise ValueError(f"unsupported image size: {image_size}") + else: + channel_mult = list(channel_mult) + + attention_ds = [] + for res in attention_resolutions.split(","): + attention_ds.append(image_size // int(res)) + + return super().__init__( + image_size=image_size, + in_channels=dim[0], + model_channels=num_channels, + out_channels=(dim[0] if not learn_sigma else dim[0] * 2), + num_res_blocks=num_res_blocks, + attention_resolutions=tuple(attention_ds), + dropout=dropout, + channel_mult=channel_mult, + num_classes=(num_classes if class_cond else None), + use_checkpoint=use_checkpoint, + use_fp16=use_fp16, + num_heads=num_heads, + num_head_channels=num_head_channels, + num_heads_upsample=num_heads_upsample, + use_scale_shift_norm=use_scale_shift_norm, + resblock_updown=resblock_updown, + use_new_attention_order=use_new_attention_order, + ) + + def forward(self, t, x, y=None, *args, **kwargs): + return super().forward(t, x, y=y) \ No newline at end of file diff --git a/torchcfm/optimal_transport.py b/torchcfm/optimal_transport.py new file mode 100644 index 0000000000000000000000000000000000000000..cea5e362a8a5b78df05eb64c85d2120370641318 --- /dev/null +++ b/torchcfm/optimal_transport.py @@ -0,0 +1,263 @@ +import math +import warnings +from functools import partial +from typing import Optional + +import numpy as np +import ot as pot +import torch + + +class OTPlanSampler: + """OTPlanSampler implements sampling coordinates according to an OT plan (wrt squared Euclidean + cost) with different implementations of the plan calculation.""" + + def __init__( + self, + method: str, + reg: float = 0.05, + reg_m: float = 1.0, + normalize_cost: bool = False, + warn: bool = True, + ) -> None: + """Initialize the OTPlanSampler class. + + Parameters + ---------- + method: str + choose which optimal transport solver you would like to use. + Currently supported are ["exact", "sinkhorn", "unbalanced", + "partial"] OT solvers. + reg: float, optional + regularization parameter to use for Sinkhorn-based iterative solvers. + reg_m: float, optional + regularization weight for unbalanced Sinkhorn-knopp solver. + normalize_cost: bool, optional + normalizes the cost matrix so that the maximum cost is 1. Helps + stabilize Sinkhorn-based solvers. Should not be used in the vast + majority of cases. + warn: bool, optional + if True, raises a warning if the algorithm does not converge + """ + # ot_fn should take (a, b, M) as arguments where a, b are marginals and + # M is a cost matrix + if method == "exact": + self.ot_fn = pot.emd + elif method == "sinkhorn": + self.ot_fn = partial(pot.sinkhorn, reg=reg) + elif method == "unbalanced": + self.ot_fn = partial(pot.unbalanced.sinkhorn_knopp_unbalanced, reg=reg, reg_m=reg_m) + elif method == "partial": + self.ot_fn = partial(pot.partial.entropic_partial_wasserstein, reg=reg) + else: + raise ValueError(f"Unknown method: {method}") + self.reg = reg + self.reg_m = reg_m + self.normalize_cost = normalize_cost + self.warn = warn + + def get_map(self, x0, x1): + """Compute the OT plan (wrt squared Euclidean cost) between a source and a target + minibatch. + + Parameters + ---------- + x0 : Tensor, shape (bs, *dim) + represents the source minibatch + x1 : Tensor, shape (bs, *dim) + represents the source minibatch + + Returns + ------- + p : numpy array, shape (bs, bs) + represents the OT plan between minibatches + """ + a, b = pot.unif(x0.shape[0]), pot.unif(x1.shape[0]) + if x0.dim() > 2: + x0 = x0.reshape(x0.shape[0], -1) + if x1.dim() > 2: + x1 = x1.reshape(x1.shape[0], -1) + x1 = x1.reshape(x1.shape[0], -1) + M = torch.cdist(x0, x1) ** 2 + if self.normalize_cost: + M = M / M.max() # should not be normalized when using minibatches + p = self.ot_fn(a, b, M.detach().cpu().numpy()) + if not np.all(np.isfinite(p)): + print("ERROR: p is not finite") + print(p) + print("Cost mean, max", M.mean(), M.max()) + print(x0, x1) + if np.abs(p.sum()) < 1e-8: + if self.warn: + warnings.warn("Numerical errors in OT plan, reverting to uniform plan.") + p = np.ones_like(p) / p.size + return p + + def sample_map(self, pi, batch_size, replace=True): + r"""Draw source and target samples from pi $(x,z) \sim \pi$ + + Parameters + ---------- + pi : numpy array, shape (bs, bs) + represents the source minibatch + batch_size : int + represents the OT plan between minibatches + replace : bool + represents sampling or without replacement from the OT plan + + Returns + ------- + (i_s, i_j) : tuple of numpy arrays, shape (bs, bs) + represents the indices of source and target data samples from $\pi$ + """ + p = pi.flatten() + p = p / p.sum() + choices = np.random.choice( + pi.shape[0] * pi.shape[1], p=p, size=batch_size, replace=replace + ) + return np.divmod(choices, pi.shape[1]) + + def sample_plan(self, x0, x1, replace=True): + r"""Compute the OT plan $\pi$ (wrt squared Euclidean cost) between a source and a target + minibatch and draw source and target samples from pi $(x,z) \sim \pi$ + + Parameters + ---------- + x0 : Tensor, shape (bs, *dim) + represents the source minibatch + x1 : Tensor, shape (bs, *dim) + represents the source minibatch + replace : bool + represents sampling or without replacement from the OT plan + + Returns + ------- + x0[i] : Tensor, shape (bs, *dim) + represents the source minibatch drawn from $\pi$ + x1[j] : Tensor, shape (bs, *dim) + represents the source minibatch drawn from $\pi$ + """ + pi = self.get_map(x0, x1) + i, j = self.sample_map(pi, x0.shape[0], replace=replace) + return x0[i], x1[j] + + def sample_plan_with_labels(self, x0, x1, y0=None, y1=None, replace=True): + r"""Compute the OT plan $\pi$ (wrt squared Euclidean cost) between a source and a target + minibatch and draw source and target labeled samples from pi $(x,z) \sim \pi$ + + Parameters + ---------- + x0 : Tensor, shape (bs, *dim) + represents the source minibatch + x1 : Tensor, shape (bs, *dim) + represents the target minibatch + y0 : Tensor, shape (bs) + represents the source label minibatch + y1 : Tensor, shape (bs) + represents the target label minibatch + replace : bool + represents sampling or without replacement from the OT plan + + Returns + ------- + x0[i] : Tensor, shape (bs, *dim) + represents the source minibatch drawn from $\pi$ + x1[j] : Tensor, shape (bs, *dim) + represents the target minibatch drawn from $\pi$ + y0[i] : Tensor, shape (bs, *dim) + represents the source label minibatch drawn from $\pi$ + y1[j] : Tensor, shape (bs, *dim) + represents the target label minibatch drawn from $\pi$ + """ + pi = self.get_map(x0, x1) + i, j = self.sample_map(pi, x0.shape[0], replace=replace) + return ( + x0[i], + x1[j], + y0[i] if y0 is not None else None, + y1[j] if y1 is not None else None, + ) + + def sample_trajectory(self, X): + """Compute the OT trajectories between different sample populations moving from the source + to the target distribution. + + Parameters + ---------- + X : Tensor, (bs, times, *dim) + different populations of samples moving from the source to the target distribution. + + Returns + ------- + to_return : Tensor, (bs, times, *dim) + represents the OT sampled trajectories over time. + """ + times = X.shape[1] + pis = [] + for t in range(times - 1): + pis.append(self.get_map(X[:, t], X[:, t + 1])) + + indices = [np.arange(X.shape[0])] + for pi in pis: + j = [] + for i in indices[-1]: + j.append(np.random.choice(pi.shape[1], p=pi[i] / pi[i].sum())) + indices.append(np.array(j)) + + to_return = [] + for t in range(times): + to_return.append(X[:, t][indices[t]]) + to_return = np.stack(to_return, axis=1) + return to_return + + +def wasserstein( + x0: torch.Tensor, + x1: torch.Tensor, + method: Optional[str] = None, + reg: float = 0.05, + power: int = 2, + **kwargs, +) -> float: + """Compute the Wasserstein (1 or 2) distance (wrt Euclidean cost) between a source and a target + distributions. + + Parameters + ---------- + x0 : Tensor, shape (bs, *dim) + represents the source minibatch + x1 : Tensor, shape (bs, *dim) + represents the source minibatch + method : str (default : None) + Use exact Wasserstein or an entropic regularization + reg : float (default : 0.05) + Entropic regularization coefficients + power : int (default : 2) + power of the Wasserstein distance (1 or 2) + Returns + ------- + ret : float + Wasserstein distance + """ + assert power == 1 or power == 2 + # ot_fn should take (a, b, M) as arguments where a, b are marginals and + # M is a cost matrix + if method == "exact" or method is None: + ot_fn = pot.emd2 + elif method == "sinkhorn": + ot_fn = partial(pot.sinkhorn2, reg=reg) + else: + raise ValueError(f"Unknown method: {method}") + + a, b = pot.unif(x0.shape[0]), pot.unif(x1.shape[0]) + if x0.dim() > 2: + x0 = x0.reshape(x0.shape[0], -1) + if x1.dim() > 2: + x1 = x1.reshape(x1.shape[0], -1) + M = torch.cdist(x0, x1) + if power == 2: + M = M**2 + ret = ot_fn(a, b, M.detach().cpu().numpy(), numItermax=int(1e7)) + if power == 2: + ret = math.sqrt(ret) + return ret diff --git a/torchcfm/utils.py b/torchcfm/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..47a1fe0455347a991513d66abfa648683d78643d --- /dev/null +++ b/torchcfm/utils.py @@ -0,0 +1,185 @@ +import math + +import matplotlib.pyplot as plt +import numpy as np +import torch +import torchdyn +from torchdyn.datasets import generate_moons +rng = np.random.RandomState() +# Implement some helper functions + + +def eight_normal_sample(n, dim, scale=1, var=1): + m = torch.distributions.multivariate_normal.MultivariateNormal( + torch.zeros(dim), math.sqrt(var) * torch.eye(dim) + ) + centers = [ + (1, 0), + (-1, 0), + (0, 1), + (0, -1), + (1.0 / np.sqrt(2), 1.0 / np.sqrt(2)), + (1.0 / np.sqrt(2), -1.0 / np.sqrt(2)), + (-1.0 / np.sqrt(2), 1.0 / np.sqrt(2)), + (-1.0 / np.sqrt(2), -1.0 / np.sqrt(2)), + ] + centers = torch.tensor(centers) * scale + noise = m.sample((n,)) + multi = torch.multinomial(torch.ones(8), n, replacement=True) + data = [] + for i in range(n): + data.append(centers[multi[i]] + noise[i]) + data = torch.stack(data) + return data + + +def pinwheel(n): + radial_std = 0.3 + tangential_std = 0.1 + num_classes = 5 + num_per_class = n // 5 + rate = 0.25 + rads = np.linspace(0, 2 * np.pi, num_classes, endpoint=False) + + features = rng.randn(num_classes * num_per_class, 2) \ + * np.array([radial_std, tangential_std]) + features[:, 0] += 1. + labels = np.repeat(np.arange(num_classes), num_per_class) + + angles = rads[labels] + rate * np.exp(features[:, 0]) + rotations = np.stack([np.cos(angles), -np.sin(angles), np.sin(angles), np.cos(angles)]) + rotations = np.reshape(rotations.T, (-1, 2, 2)) + + return torch.tensor(2 * rng.permutation(np.einsum("ti,tij->tj", features, rotations))) +def spirals_2d(n): + n = int(n) # Ensure n is an integer + half_n = n // 2 + + theta = np.sqrt(np.random.rand(half_n, 1)) * 540 * (2 * np.pi) / 360 # Angle in radians + d1x = -np.cos(theta) * theta + np.random.rand(half_n, 1) * 0.5 + d1y = np.sin(theta) * theta + np.random.rand(half_n, 1) * 0.5 + + # Stack spiral and mirrored spiral + x = np.vstack(( + np.hstack((d1x, d1y)), + np.hstack((-d1x, -d1y)) + )) / 3 + + # Add Gaussian noise + x += np.random.randn(*x.shape) * 0.1 + + return torch.tensor(x, dtype=torch.float32) + + +def checkerboard(n): + x1 = np.random.rand(n) * 4 - 2 + x2_ = np.random.rand(n) - np.random.randint(0, 2, n) * 2 + x2 = x2_ + (np.floor(x1) % 2) + return torch.tensor(np.concatenate([x1[:, None], x2[:, None]], 1) * 2) + +def sample_moons(n): + x0, _ = generate_moons(n, noise=0.2) + return x0 * 3 - 1 + + +def sample_8gaussians(n): + return eight_normal_sample(n, 2, scale=5, var=0.1).float() + +def sample_pinwheel(n): + return pinwheel(n ).float() + +def sample_spirals(n): + return spirals_2d(n ).float() + +def sample_checkerboard(n): + return checkerboard(n ).float() + +class torch_wrapper(torch.nn.Module): + """Wraps model to torchdyn compatible format.""" + + def __init__(self, model): + super().__init__() + self.model = model + + def forward(self, t, x, *args, **kwargs): + return self.model(torch.cat([x, t.repeat(x.shape[0])[:, None]], 1)) + + + +def plot_trajectories(traj,true): + """Plot trajectories of some selected samples.""" + n = traj.shape[1] + plt.figure(figsize=(6, 6)) + plt.scatter(traj[0, :n, 0], traj[0, :n, 1], s=10, alpha=0.2, c="g") + x=traj[:, :n, 0] + y=traj[:, :n, 1] + # plt.quiver(x[:-1], y[:-1], x[1:] - x[:-1], y[1:] - y[:-1], scale_units='xy', angles='xy', scale=1, color='b',width=0.01, headwidth=5) + # plt.scatter(traj[:-1, :n, 0], traj[:-1, :n, 1], s=0.2, alpha=0.5, c="olive") + plt.scatter(traj[-1, :n, 0], traj[-1, :n, 1], s=4, alpha=1, c="black") + # plt.scatter(true[:, 0], true[:, 1], s=4, alpha=1, c="g") + # plt.legend(["Prior sample z(S)", "Flow", "z(0)"]) + plt.xlim(-5,5) + plt.ylim(-5, 5) + plt.xticks([]) + plt.yticks([]) +def plot_trajectories_m(traj, true, moment_traj, finals): + """Plot trajectories of some selected samples with arrows representing moment_traj.""" + n = traj.shape[1] + + plt.scatter(finals[:, 0], finals[:, 1], s=.8, alpha=.3, c="black") + plt.scatter(traj[0, :n, 0], traj[0, :n, 1], s=10, alpha=1, c="g") + x = traj[:, :n, 0] + y = traj[:, :n, 1] + plt.quiver(x[:-1], y[:-1], x[1:] - x[:-1], y[1:] - y[:-1], scale_units='xy', angles='xy', scale=1, color='b',width=0.01, headwidth=2, alpha=.5) + for i in range(n): + for j in range(traj.shape[0]): + plt.arrow(x[j, i], y[j, i], moment_traj[j, i, 0],moment_traj[j, i, 1], color='r', alpha=0.8, width=0.01, head_width=0.2) + + # plt.scatter(true[:, 0], true[:, 1], s=4, alpha=.1, c="g") + # plt.legend(["Prior samples", "IDFF", "IDFF momentum term"]) + # plt.xlim(-5, 5) + # plt.ylim(-5, 5) + plt.xticks([]) + plt.yticks([]) + + + +def plt_flow_samples(prior_sample, npts=100, memory=100, kde_enable=True, title="", device="cpu"): + z = prior_sample.to(device) + zk = [] + inds = torch.arange(0, z.shape[0]).to(torch.int64) + for ii in torch.split(inds, int(memory ** 2)): + zk.append(z[ii]) + zk = torch.cat(zk, 0).cpu().numpy() + x_min, x_max = prior_sample[:, 0].min(), prior_sample[:, 0].max() + y_min, y_max = prior_sample[:, 1].min(), prior_sample[:, 1].max() + xx, yy = np.meshgrid(np.linspace(x_min, x_max, npts), + np.linspace(y_min, y_max, npts)) + grid_points = np.c_[xx.ravel(), yy.ravel()] + + # ax.hist2d(zk[:, 0], zk[:, 1], range=[[LOW, HIGH], [LOW, HIGH]], bins=npts) + + if kde_enable: + # Fit a kernel density estimator to the data + from sklearn.neighbors import KernelDensity + + kde = KernelDensity(bandwidth=0.2) + kde.fit(zk) + + # Compute the log density values for the grid points + log_density = kde.score_samples(grid_points) + + # Reshape the log density values to match the grid shape + density = np.exp(log_density) + density = density.reshape(xx.shape) + plt.imshow(density.T, # ,extent=(-2, 3, -2, 3), + # interpolation='nearest', + origin='lower') + else: + # hist, x_edges, y_edges = np.histogram2d(zk[:, 0], zk[:, 1], range=[[LOW, HIGH], [LOW, HIGH]], bins=(npts, npts)) + # ax.imshow(hist, cmap='copper', + # interpolation='nearest', + # origin='lower') + # copper_color = (0.5, 0.3, 0.1) + burnt_orange = "#cc5500" + plt.scatter(zk[:, 0], zk[:, 1], c='k', s=.05, alpha=.02) diff --git a/torchcfm/version.py b/torchcfm/version.py new file mode 100644 index 0000000000000000000000000000000000000000..382021f30ff6ce35872aa0de4ebe2a43f50c21d7 --- /dev/null +++ b/torchcfm/version.py @@ -0,0 +1 @@ +__version__ = "1.0.6"