NeuralSW / GradientFlow /gradient_flow.py
khai199733's picture
push
b389bd5
Raw History Blame Contribute Delete
4.41 kB
"""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)