File size: 11,181 Bytes
0252cb7 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 | """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()
|