File size: 7,970 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
"""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)")