File size: 10,844 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 | """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()
|