File size: 4,410 Bytes
b389bd5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Sliced-Wasserstein gradient flow of a random point cloud towards the 8-mode
Gaussian ring, using ONLY the amortized neural quantile network trained by
train_quantile_net.py — the target mixture itself is never resampled during
the flow (it is sampled once at the end, purely to plot a visual reference).

At each step, for a batch of random projection directions theta:
  1. project the current particles X onto theta and sort them,
  2. ask the network for the target's quantiles at the matching tau grid,
  3. take the mean squared gap between the two as an estimate of SW^2(X, target),
  4. take a forward-Euler step  X <- X - lr * grad_X SW^2(X, target).
"""
import os
import sys

_THIS_DIR = os.path.dirname(os.path.abspath(__file__))
_ROOT_DIR = os.path.dirname(_THIS_DIR)
_AMORTIZED_DIR = os.path.join(_ROOT_DIR, "Amortized_simulation")
for p in (_ROOT_DIR, _AMORTIZED_DIR):
    if p not in sys.path:
        sys.path.insert(0, p)

import torch
import matplotlib.pyplot as plt
from models import AmortizedPhiFunction
from sw_common import set_seed, random_unit_directions, sample_mixture_gaussian
from target import make_ring_mixture

CHECKPOINT_PATH = os.path.join(_THIS_DIR, "checkpoints", "quantile_net_ring8.pt")


def load_quantile_net(device):
    ckpt = torch.load(CHECKPOINT_PATH, map_location=device)
    model = AmortizedPhiFunction(
        embedding_dim=ckpt["embedding_dim"], num_cosines=ckpt["num_cosines"], d=ckpt["d"]
    ).to(device)
    model.load_state_dict(ckpt["state_dict"])
    model.eval()
    for param in model.parameters():
        param.requires_grad_(False)
    return model, ckpt["d"]


def run_gradient_flow(
    model,
    n_dim,
    device,
    n_particles=500,
    L=200,
    n_iters=2000,
    lr=0.1,
    init_scale=2.0,
    snapshot_iters=(0, 100, 500, 1000, 1999),
):
    X = (init_scale * torch.randn(n_particles, n_dim, device=device)).requires_grad_(True)
    taus = ((torch.arange(n_particles, device=device, dtype=torch.float32) + 0.5) / n_particles).view(-1, 1)

    losses = []
    snapshots = {}
    snapshot_iters = set(snapshot_iters)

    for it in range(n_iters):
        thetas = random_unit_directions(L, n_dim, device)
        proj = thetas @ X.T  # (L, N)
        sorted_proj, _ = torch.sort(proj, dim=1)
        target_quantiles = model(taus, thetas)  # (L, N), network is frozen -> no grad needed here
        loss = ((sorted_proj - target_quantiles) ** 2).mean()

        X.grad = None
        loss.backward()
        with torch.no_grad():
            X -= lr * X.grad

        losses.append(loss.item())
        if it in snapshot_iters:
            snapshots[it] = X.detach().cpu().numpy().copy()
        if it % 100 == 0:
            print(f"Iter {it}, SW^2 loss: {loss.item():.4f}")

    if (n_iters - 1) not in snapshots:
        snapshots[n_iters - 1] = X.detach().cpu().numpy().copy()

    return X.detach(), losses, snapshots


def plot_results(losses, snapshots, reference_sample):
    plt.figure(figsize=(6, 4))
    plt.plot(losses)
    plt.yscale("log")
    plt.xlabel("Iteration")
    plt.ylabel("Sliced quantile-matching loss")
    plt.title("Gradient flow loss")
    plt.tight_layout()
    plt.show()

    sorted_iters = sorted(snapshots)
    fig, axes = plt.subplots(1, len(sorted_iters), figsize=(4 * len(sorted_iters), 4), sharex=True, sharey=True)
    if len(sorted_iters) == 1:
        axes = [axes]
    for ax, it in zip(axes, sorted_iters):
        ax.scatter(reference_sample[:, 0], reference_sample[:, 1], s=5, alpha=0.2, color="black", label="target")
        ax.scatter(snapshots[it][:, 0], snapshots[it][:, 1], s=8, alpha=0.8, color="tab:blue", label="particles")
        ax.set_title(f"iter {it}")
        ax.set_aspect("equal")
    axes[0].legend()
    plt.tight_layout()
    plt.show()


if __name__ == "__main__":
    set_seed(0)
    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    print(f"Using device: {device}")

    model, n_dim = load_quantile_net(device)

    final_X, losses, snapshots = run_gradient_flow(model, n_dim, device)

    # Reference sample of the true mixture, used only for plotting -- not for the flow itself.
    means, covs, weights = make_ring_mixture(n_components=8, radius=5.0, std=0.3, device=device)
    reference_sample = sample_mixture_gaussian(2000, means, covs, weights, n_dim, device).cpu().numpy()

    plot_results(losses, snapshots, reference_sample)