Announcements¶
- Please evaluate the course. We need to decide if we want to keep offering this course. |
Task:
- Unsupervised learning:
- Training data: $\mathcal{D}^\text{(tr)} = \{(x_i^\text{(tr)})\}_{i=1}^{N^\text{(tr)}}$ sampled from $p(x)$.
- Goal: Output new samples from $p(x)$ (Implicit generative model)
Introduction¶
In this lecture we will study Conditional Flow Matching (CFM), a new approach to generative modeling that offers several advantages over Generative Adversarial Networks (GANs), Variational Autoencoders (VAEs), and Diffusion Models.
CFM belongs to a broader family of continuous normalizing flows, which learns a diffeomorphic mapping between a simple proposal distribution, typically a Gaussian distribution $\mathcal{N}(0, I)$, and the complex target data distribution $p(x)$.
This mapping is parameterized by a continuous-time vector field, $v_\theta(t, x)$, where $\theta$ represents the learnable parameters of the model.
By leveraging ordinary differential equations (ODEs), CFM provides a flexible and efficient means of modeling complex data distributions, thereby facilitating the generation of high-quality samples.
Theoretical Background¶
A diffeomorphic mapping, denoted as $\mathcal{V}_{\theta}: \mathcal{M} \to \mathcal{N}$, is a type of smooth and invertible mapping between two manifolds, $\mathcal{M}$ and $\mathcal{N}$.
Formally, a diffeomorphic mapping satisfies the following properties:
- Smoothness: The mapping $\mathcal{V}_{\theta}$ is continuously differentiable, i.e., $\mathcal{V}_{\theta} \in C(\mathcal{M})$.
- Invertibility: The mapping induced by $\mathcal{V}_{\theta}$ has a smooth inverse.
- Bijectivity: The mapping induced by $\mathcal{V}_{\theta}$ establishes a one-to-one correspondence between points in $\mathcal{M}$ and $\mathcal{N}$.
The Continuous Normalizing Flow Framework¶
In the context of continuous normalizing flows, the diffeomorphic mapping is typically represented as the solution to an ordinary differential equation (ODE), which describes the evolution of the input data under a continuous-time transformation.
The ODE is often specified as: $$\frac{dx(t)}{dt} = \frac{\mathcal{V}_{\theta}(t,x(t)}{dt} = v_{\theta}(t, x(t)),$$ where
- $x(t)$ represents the input data at time $t$, and $\theta$ denotes the learnable parameters of the model. The solution to this ODE defines a trajectory that starts at the initial condition $x(0)$ (typically the target) and ends at the final state $x(T)$ (typically Gaussian), where $T$ represents the total evolution time (usually $T=1$).
- $v_\theta(t, x(t))$ is a learned vector field parameterized by a neural network with parameters $\theta$
The diffeomorphic property ensures that the transformation preserves the topological structure of the input data, while allowing for complex and non-linear transformations to be applied. This enables continuous normalizing flows, such as Conditional Flow Matching (CFM), to model complex data distributions.
Conditional Flow Matching Objective¶
The key insight of Conditional Flow Matching is that we can directly learn the vector field $v_\theta$ by minimizing:
$$\mathcal{L}(\theta) = \mathbb{E}_{x_0 \sim p_0, x_1 \sim p_1, t \sim \mathcal{U}[0,1]} \left[ \| v_\theta(t, x_t) - u_t(x_t|x_0,x_1) \|^2 \right]$$
where:
- $p_0$ is our target data distribution
- $p_1$ is our proposal distribution (e.g., Gaussian)
- $x_t = (1-t)x_0 + tx_1$ is a linear interpolation between data and noise
- $u_t(x_t|x_0,x_1) = x_1 - x_0$ is the conditional vector field (the "ground truth" direction)
This objective is much simpler to optimize than alternatives like score matching or the ELBO, making CFM particularly easy to optimize.
Implementation¶
We will now implement Conditional Flow Matching for a simple 2D example: transforming samples from a Gaussian distribution to the classic "Two Moons" dataset.
Setting Up ODE Solver¶
For sampling, we need to solve an ODE. We will use the torchdiffeq package, which provides several ODE solvers:
# We will be using torchdiffeq
try:
from torchdiffeq import odeint
except ImportError:
print("Error: torchdiffeq library not found.")
print("Please install it using: pip install torchdiffeq")
# You might want to exit or raise an error here if torchdiffeq is essential
# For this example, we'll let it potentially fail later if sampling is called.
exit(-1)
Configuration¶
These are the hyperparameters and task parameters for our model and training process:
# *** Hyperparameters & Task Parameters ***
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(f"Using device: {device}")
# Data parameters
N_SAMPLES = 5000 # Number of training samples
NOISE = 0.05 # Noise level for the two moons dataset
DATA_DIM = 2 # Dimensionality of the data
# Model parameters
HIDDEN_DIM = 128 # Size of hidden layers
N_LAYERS = 4 # Number of hidden layers
# Training parameters
BATCH_SIZE = 512
LEARNING_RATE = 1e-3
N_EPOCHS = 5000
PRINT_INTERVAL = 500 # Print loss every N epochs
# Sampling parameters
N_SAMPLES_GENERATE = 2000
ODE_SOLVER = 'dopri5' # Recommended adaptive-step solver from Lipman et al. (2022) paper
ODE_TOL = 1e-5 # ODE solver tolerance
Data Generation¶
For this example, we will our "two moons" dataset as our target distribution:
# *** Data Generation ***
def generate_two_moons(n_samples, noise):
"""
Generates the two moons dataset.
Args:
n_samples: Number of samples to generate
noise: Standard deviation of Gaussian noise added to the data
Returns:
torch.Tensor of shape [n_samples, 2] containing the data points
"""
X, _ = make_moons(n_samples=n_samples, noise=noise)
return torch.tensor(X, dtype=torch.float32)
Neural Network Architecture¶
Now, let's define our neural network that will learn the vector field. We'll use a simple MLP with SiLU (Swish) activation functions:
# *** Model Definition ***
class VectorFieldNet(nn.Module):
"""
A simple MLP to approximate the vector field v(t, x).
Input: time t (scalar) and position x (vector)
Output: velocity vector (same dim as x)
"""
def __init__(self, input_dim, hidden_dim, output_dim, n_layers):
super().__init__()
# Input layer: Takes concatenated time and position
layers = [nn.Linear(input_dim + 1, hidden_dim), nn.SiLU()] # SiLU activation
# Hidden layers
for _ in range(n_layers):
layers.extend([nn.Linear(hidden_dim, hidden_dim), nn.SiLU()])
# Output layer
layers.append(nn.Linear(hidden_dim, output_dim))
self.net = nn.Sequential(*layers)
def forward(self, t, x):
# Ensure t is broadcastable to the batch dimension of x
if isinstance(t, (float, int)) or t.ndim == 0:
# Make t a tensor of shape [batch_size, 1]
t_vec = torch.ones(x.shape[0], 1, device=x.device, dtype=x.dtype) * t
elif t.ndim == 1 and t.shape[0] == x.shape[0]:
# Make t a tensor of shape [batch_size, 1]
t_vec = t.unsqueeze(-1)
else:
raise ValueError(f"Incorrect shape for t: {t.shape}, expected scalar or [batch_size]")
# Concatenate time embedding with input x
tx = torch.cat([t_vec, x], dim=1)
return self.net(tx)
The Conditional Flow Matching Loss¶
Now we implement the core of our method: the conditional flow matching loss. This is where the mathematical foundation we discussed earlier is translated into code:
# **** Flow Matching Loss ****
def conditional_flow_matching_loss(model, x0, x1):
"""
Calculates the conditional flow matching loss.
Args:
model: The neural network approximating the vector field.
x0: Samples from the data distribution (e.g., two moons). Shape [batch_size, data_dim].
x1: Samples from the proposal distribution (e.g., Gaussian). Shape [batch_size, data_dim].
Returns:
loss: The mean squared error loss.
"""
batch_size = x0.shape[0]
data_dim = x0.shape[1]
# 1. Sample time t uniformly from [0, 1]
t = torch.rand(batch_size, 1, device=x0.device)
# 2. Calculate the conditional path x_t
# x_t = sigma_t * x0 + mu_t * x1
mu_t = t
sigma_t = 1.0 - t
x_t = mu_t * x1 + sigma_t * x0
# 3. Calculate the conditional vector field u_t
# u_t = d/dt x_t = x1 - x0
u_t = x1 - x0
# 4. Get the model's prediction for the vector field at (t, x_t)
v_pred_t = model(t.squeeze(-1), x_t) # Pass t as [batch_size]
# 5. Calculate the loss: MSE between predicted and target vector fields
loss = torch.mean((v_pred_t - u_t)**2)
return loss
Understanding the CFM Loss¶
The core idea of Conditional Flow Matching:
- We sample a random time point $t \in [0, 1]$
- We compute the interpolated point $x_t = (1-t)x_0 + tx_1$
- We compute the "ground truth" vector field $u_t = x_1 - x_0$
- We predict the vector field $v_\theta(t, x_t)$ using our model
- We minimize the mean squared error between $v_\theta(t, x_t)$ and $u_t$
Note that the "ground truth" vector field $u_t = x_1 - x_0$ is simply the direction from $x_0$ to $x_1$, which is the direction we want our model to learn.
Training Loop¶
Here is the implementation of the training function:
# --- Training Function ---
def train_flow_matching(model, dataloader, optimizer, n_epochs, device, data_dim):
"""
Trains the flow matching model.
Args:
model: The neural network model
dataloader: DataLoader providing batches of training data
optimizer: The optimizer for parameter updates
n_epochs: Number of training epochs
device: Device to use for computation
data_dim: Dimensionality of the data
"""
model.train()
start_time = time.time()
print("Starting training...")
for epoch in range(n_epochs):
epoch_loss = 0.0
for batch_x0 in dataloader:
batch_x0 = batch_x0[0].to(device) # Dataloader wraps tensors in a list
batch_size = batch_x0.shape[0]
# Sample x1 from the proposal distribution (Standard Gaussian)
x1 = torch.randn(batch_size, data_dim, device=device)
# Zero gradients
optimizer.zero_grad()
# Calculate loss
loss = conditional_flow_matching_loss(model, batch_x0, x1)
# Backpropagate and update weights
loss.backward()
optimizer.step()
epoch_loss += loss.item() * batch_x0.size(0) # Scale by batch size
avg_epoch_loss = epoch_loss / len(dataloader.dataset)
if (epoch + 1) % PRINT_INTERVAL == 0 or epoch == 0:
elapsed_time = time.time() - start_time
print(f"Epoch [{epoch+1}/{n_epochs}], Loss: {avg_epoch_loss:.6f}, Time: {elapsed_time:.2f}s")
print("Training finished.")
total_time = time.time() - start_time
print(f"Total Training Time: {total_time:.2f}s")
Sampling via ODE Solving¶
Once we have trained our model, we can generate new samples by solving the ODE from $t=1$ to $t=0$:
# --- Sampling Function ---
@torch.no_grad()
def sample_ode(model, n_samples, data_dim, device, solver=ODE_SOLVER, rtol=ODE_TOL, atol=ODE_TOL):
"""
Generates samples by solving the ODE dx/dt = v(t, x) from t=1 to t=0.
Starts with samples x1 from the proposal distribution (Gaussian).
Args:
model: The trained neural network model
n_samples: Number of samples to generate
data_dim: Dimensionality of the data
device: Device to use for computation
solver: ODE solver method to use
rtol, atol: Relative and absolute tolerances for the ODE solver
Returns:
Generated samples as numpy array
"""
if odeint is None:
print("Error: torchdiffeq is required for sampling but not installed.")
return None
model.eval() # Set model to evaluation mode
# Initial samples from the proposal distribution (Gaussian) at t=1
x1 = torch.randn(n_samples, data_dim, device=device)
# Time points for integration: from t=1 to t=0
t_span = torch.tensor([1.0, 0.0], device=device)
# Define the ODE function for the solver
def ode_func(t, x):
# Ensure t is a scalar for the model call within odeint
t_scalar = t.item() if isinstance(t, torch.Tensor) else t
return model(t_scalar, x)
print(f"Starting ODE sampling with solver: {solver}...")
start_time = time.time()
# Solve the ODE: dx/dt = v(t, x)
# The shape will be [time_points, batch_size, data_dim]
x0_pred_traj = odeint(
ode_func,
x1, # Initial state at t=1
t_span, # Time points to evaluate (from 1 to 0)
method=solver,
rtol=rtol,
atol=atol
)
# Extract the samples at t=0 (the last time point)
x0_pred = x0_pred_traj[-1] # Shape: [batch_size, data_dim]
sampling_time = time.time() - start_time
print(f"Sampling finished. Time: {sampling_time:.2f}s")
return x0_pred.cpu().numpy() # Return as numpy array on CPU
Understanding the Sampling Process¶
Sampling works by:
- Starting with random Gaussian noise samples $x_1 \sim \mathcal{N}(0, I)$
- Solving the ODE $\frac{dx(t)}{dt} = v_\theta(t, x(t))$ from $t=1$ to $t=0$
- The solution at $t=0$ gives us samples from the learned data distribution
This is the reverse of the training process, where we learned to map from the data distribution to noise.
Visualization¶
Le'ts visualize to compare the real and generated data:
# --- Visualization ---
def plot_results(x_real, x_generated):
"""
Plots the real and generated data distributions.
Args:
x_real: Real data samples
x_generated: Generated data samples
"""
plt.figure(figsize=(12, 6))
plt.subplot(1, 2, 1)
plt.scatter(x_real[:, 0], x_real[:, 1], alpha=0.5, label='Real Data (Two Moons)')
plt.title('Real Data Distribution')
plt.xlabel('X1')
plt.ylabel('X2')
plt.legend()
plt.axis('equal')
plt.grid(True, linestyle='--', alpha=0.6)
plt.subplot(1, 2, 2)
if x_generated is not None:
plt.scatter(x_generated[:, 0], x_generated[:, 1], alpha=0.5, color='red',
label='Generated Samples')
plt.title('Generated Data Distribution')
plt.xlabel('X1')
plt.ylabel('X2')
plt.legend()
plt.axis('equal') # Ensure aspect ratio is equal for visual comparison
plt.grid(True, linestyle='--', alpha=0.6)
else:
plt.text(0.5, 0.5, 'Sampling failed (torchdiffeq missing?)',
horizontalalignment='center', verticalalignment='center',
transform=plt.gca().transAxes)
plt.title('Generated Data Distribution (Failed)')
plt.suptitle('Flow Matching: Two Moons Example')
plt.tight_layout(rect=[0, 0.03, 1, 0.95]) # Adjust layout to prevent title overlap
plt.show()
Summary of Flow Matching¶
Conditional Flow Matching (CFM) offers several advantages over other generative methods:
- Simplicity: The loss function is straightforward and doesn't require complex approximations.
- Stability: Training is typically more stable than GANs (but typically less stable than diffusion models).
- Quality: The samples generated are of high quality, comparable to diffusion models.
- Speed: Sampling can be faster than diffusion models, especially with adaptive ODE solvers.
Challenges
- Tong et al. (2023) argue that flow matching should use optimal transport loss rather than just match the vector field gradients
- This is the same issue as with VAEs when we sampled $\epsilon$ noises.
(Figure from Tong et al. (2023))
References¶
- Lipman, Y., Chen, R. T. Q., Ben-Hamu, H., Nickel, M., & Le, M. (2023). Flow Matching for Generative Modeling, ICLR 2023.
- Albergo, M. S., & Vanden-Eijnden, E. (2022). Building Normalizing Flows with Stochastic Interpolants.
- Tong, A., Fatras, K., Malkin, N., Huguet, G., Zhang, Y., Rector-Brooks, J., Wolf, G., & Bengio, Y. (2023). Improving and Generalizing Flow-Based Generative Models with Minibatch Optimal Transport, JMLR 2024.
#Complete code
"""
PyTorch implementation of Conditional Flow Matching for the Two Moons dataset.
This simple code demonstrates how to train a simple neural network to learn the
vector field that transports samples from a simple distribution (Gaussian)
to a complex one (Two Moons) using the Conditional Flow Matching objective.
It also includes code for sampling from the learned model using an ODE solver.
"""
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import TensorDataset, DataLoader
import numpy as np
from sklearn.datasets import make_moons
import matplotlib.pyplot as plt
import time
# Try importing torchdiffeq, provide instructions if missing
try:
from torchdiffeq import odeint
except ImportError:
print("Error: torchdiffeq library not found.")
print("Please install it using: pip install torchdiffeq")
# You might want to exit or raise an error here if torchdiffeq is essential
# For this example, we'll let it potentially fail later if sampling is called.
odeint = None # Set to None if not available
# *** Configuration ***
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(f"Using device: {device}")
# Data parameters
N_SAMPLES = 5000
NOISE = 0.05
DATA_DIM = 2
# Model parameters
HIDDEN_DIM = 128
N_LAYERS = 4 # Number of hidden layers
# Training parameters
BATCH_SIZE = 512
LEARNING_RATE = 1e-3
N_EPOCHS = 5000
PRINT_INTERVAL = 500 # Print loss every N epochs
# Sampling parameters
N_SAMPLES_GENERATE = 2000
ODE_SOLVER = 'dopri5' # Recommended solver
ODE_TOL = 1e-5 # ODE solver tolerance
# *** Data Generation ***
def generate_two_moons(n_samples, noise):
"""Generates the two moons dataset."""
X, _ = make_moons(n_samples=n_samples, noise=noise)
return torch.tensor(X, dtype=torch.float32)
# *** Model Definition ***
class VectorFieldNet(nn.Module):
"""
A simple MLP to approximate the vector field v(t, x).
Input: time t (scalar) and position x (vector)
Output: velocity vector (same dim as x)
"""
def __init__(self, input_dim, hidden_dim, output_dim, n_layers):
super().__init__()
# Input layer: Takes concatenated time and position
layers = [nn.Linear(input_dim + 1, hidden_dim), nn.SiLU()] # SiLU activation
# Hidden layers
for _ in range(n_layers):
layers.extend([nn.Linear(hidden_dim, hidden_dim), nn.SiLU()])
# Output layer
layers.append(nn.Linear(hidden_dim, output_dim))
self.net = nn.Sequential(*layers)
def forward(self, t, x):
# Ensure t is broadcastable to the batch dimension of x
if isinstance(t, (float, int)) or t.ndim == 0:
# Make t a tensor of shape [batch_size, 1]
t_vec = torch.ones(x.shape[0], 1, device=x.device, dtype=x.dtype) * t
elif t.ndim == 1 and t.shape[0] == x.shape[0]:
# Make t a tensor of shape [batch_size, 1]
t_vec = t.unsqueeze(-1)
else:
raise ValueError(f"Incorrect shape for t: {t.shape}, expected scalar or [batch_size]")
# Concatenate time embedding with input x
tx = torch.cat([t_vec, x], dim=1)
return self.net(tx)
# *** Flow Matching Loss ***
def conditional_flow_matching_loss(model, x0, x1):
"""
Calculates the conditional flow matching loss.
Args:
model: The neural network approximating the vector field.
x0: Samples from the data distribution (e.g., two moons). Shape [batch_size, data_dim].
x1: Samples from the proposal distribution (e.g., Gaussian). Shape [batch_size, data_dim].
Returns:
loss: The mean squared error loss.
"""
batch_size = x0.shape[0]
data_dim = x0.shape[1]
# 1. Sample time t uniformly from [0, 1]
t = torch.rand(batch_size, 1, device=x0.device)
# 2. Calculate the conditional path x_t
# x_t = sigma_t * x1 + mu_t * x0
# For standard CFM: mu_t = t, sigma_t = 1 - t (linear interpolation)
mu_t = t
sigma_t = 1.0 - t
x_t = mu_t * x1 + sigma_t * x0
# 3. Calculate the conditional vector field u_t
# u_t = d/dt x_t = x1 - x0
u_t = x1 - x0
# 4. Get the model's prediction for the vector field at (t, x_t)
# Pass t as a vector matching the batch size
v_pred_t = model(t.squeeze(-1), x_t) # Pass t as [batch_size]
# 5. Calculate the loss: MSE between predicted and target vector fields
loss = torch.mean((v_pred_t - u_t)**2)
return loss
# --- Training Function ---
def train_flow_matching(model, dataloader, optimizer, n_epochs, device, data_dim):
"""Trains the flow matching model."""
model.train()
start_time = time.time()
print("Starting training...")
for epoch in range(n_epochs):
epoch_loss = 0.0
for batch_x0 in dataloader:
batch_x0 = batch_x0[0].to(device) # Dataloader wraps tensors in a list
batch_size = batch_x0.shape[0]
# Sample x1 from the target distribution (Standard Gaussian)
batch_x1 = torch.randn(batch_size, data_dim, device=device)
# Zero gradients
optimizer.zero_grad()
# Calculate loss
loss = conditional_flow_matching_loss(model, batch_x0, batch_x1)
# Backpropagate and update weights
loss.backward()
optimizer.step()
epoch_loss += loss.item() * batch_x0.size(0) # Accumulate loss scaled by batch size
avg_epoch_loss = epoch_loss / len(dataloader.dataset)
if (epoch + 1) % PRINT_INTERVAL == 0 or epoch == 0:
elapsed_time = time.time() - start_time
print(f"Epoch [{epoch+1}/{n_epochs}], Loss: {avg_epoch_loss:.6f}, Time: {elapsed_time:.2f}s")
print("Training finished.")
total_time = time.time() - start_time
print(f"Total Training Time: {total_time:.2f}s")
Using device: cpu
# --- Sampling Function ---
@torch.no_grad()
def sample_ode(model, n_samples, data_dim, device, solver=ODE_SOLVER, rtol=ODE_TOL, atol=ODE_TOL):
"""
Generates samples by solving the ODE dx/dt = v(t, x) from t=1 to t=0.
Starts with samples x1 from the proposal distribution (Gaussian).
"""
if odeint is None:
print("Error: torchdiffeq is required for sampling but not installed.")
exit(-1)
model.eval() # Set model to evaluation mode
# Initial samples from the proposal distribution (Gaussian) at t=1
x1 = torch.randn(n_samples, data_dim, device=device)
# Time points for integration: from t=1 to t=0
t_span = torch.tensor([1.0, 0.0], device=device)
# Define the ODE function for the solver
# The solver expects func(t, y), where y is the state (our x)
# We need to wrap our model which takes (t, x)
def ode_func(t, x):
# Ensure t is a scalar for the model call within odeint
# Note: odeint typically passes t as a scalar tensor.
# If it passes a batch of times, model needs adjustment or check torchdiffeq docs.
# Assuming scalar t here based on common usage.
t_scalar = t.item() if isinstance(t, torch.Tensor) else t
return model(t_scalar, x)
print(f"Starting ODE sampling with solver: {solver}...")
start_time = time.time()
# Solve the ODE: odeint returns solutions at specified t_span points
# We only need the solution at the final time point (t=0)
# The shape will be [time_points, batch_size, data_dim]
x0_pred_traj = odeint(
ode_func,
x1, # Initial state at t=1
t_span, # Time points to evaluate (from 1 to 0)
method=solver,
rtol=rtol,
atol=atol
)
# Extract the samples at t=0 (the last time point)
x0_pred = x0_pred_traj[-1] # Shape: [batch_size, data_dim]
sampling_time = time.time() - start_time
print(f"Sampling finished. Time: {sampling_time:.2f}s")
return x0_pred.cpu().numpy() # Return as numpy array on CPU
def plot_results(x_real, x_generated):
"""
Plots the real and generated data distributions.
Args:
x_real: Real data samples
x_generated: Generated data samples
"""
plt.figure(figsize=(12, 6))
plt.subplot(1, 2, 1)
plt.scatter(x_real[:, 0], x_real[:, 1], alpha=0.5, label='Real Data (Two Moons)')
plt.title('Real Data Distribution')
plt.xlabel('X1')
plt.ylabel('X2')
plt.legend()
plt.axis('equal')
plt.grid(True, linestyle='--', alpha=0.6)
plt.subplot(1, 2, 2)
if x_generated is not None:
plt.scatter(x_generated[:, 0], x_generated[:, 1], alpha=0.5, color='red',
label='Generated Samples')
plt.title('Generated Data Distribution')
plt.xlabel('X1')
plt.ylabel('X2')
plt.legend()
plt.axis('equal') # Ensure aspect ratio is equal for visual comparison
plt.grid(True, linestyle='--', alpha=0.6)
else:
plt.text(0.5, 0.5, 'Sampling failed (torchdiffeq missing?)',
horizontalalignment='center', verticalalignment='center',
transform=plt.gca().transAxes)
plt.title('Generated Data Distribution (Failed)')
plt.suptitle('Flow Matching: Two Moons Example')
plt.tight_layout(rect=[0, 0.03, 1, 0.95]) # Adjust layout to prevent title overlap
plt.show()
def plot_vector_field_at_multiple_times(model, device, times=[0.0, 0.33, 0.67, 1.0], grid_size=20, margin=1.5):
"""
Visualizes the vector field at multiple time steps to show how it evolves.
Args:
model: The trained neural network model
device: Device to use for computation
times: List of time points at which to visualize the vector field
grid_size: Number of points along each axis of the grid
margin: Margin to add around the [-1,1]×[-1,1] region
"""
model.eval()
# Create a grid of points
x = np.linspace(-margin, margin, grid_size)
y = np.linspace(-margin, margin, grid_size)
X, Y = np.meshgrid(x, y)
# Reshape the grid for input to the model
xy = np.stack([X.flatten(), Y.flatten()], axis=1)
xy_tensor = torch.tensor(xy, dtype=torch.float32, device=device)
# Create the figure with larger size
fig = plt.figure(figsize=(24, 8)) # Significantly increased figure size
# Add a suptitle with larger font size
fig.suptitle('Evolution of the Vector Field Over Time', fontsize=18)
# Create subfigures with proper spacing
axes = []
for i, t in enumerate(times):
# Create subplot with specific position to allow for the suptitle
ax = fig.add_subplot(1, len(times), i+1)
axes.append(ax)
# Compute the vector field at the grid points for this time step
with torch.no_grad():
vectors = model(t, xy_tensor).cpu().numpy()
# Get the x and y components of the vectors
U = vectors[:, 0].reshape(grid_size, grid_size)
V = vectors[:, 1].reshape(grid_size, grid_size)
# Compute the vector magnitudes for color mapping
magnitude = np.sqrt(U**2 + V**2)
# Plot vectors with color mapping based on magnitude
# Using -U, -V as specified to correct the direction
q = ax.quiver(X, Y, -U, -V, magnitude, cmap='viridis', pivot='mid', scale=25)
# Add title and labels with larger font sizes
ax.set_title(f't={t:.2f}', fontsize=16)
ax.set_xlabel('X1', fontsize=14)
ax.set_ylabel('X2', fontsize=14)
ax.tick_params(axis='both', labelsize=12)
ax.grid(True, linestyle='--', alpha=0.3)
ax.axis('equal')
# Add a colorbar with larger font
cbar_ax = fig.add_axes([0.92, 0.15, 0.02, 0.7]) # [left, bottom, width, height]
cbar = fig.colorbar(q, cax=cbar_ax)
cbar.ax.tick_params(labelsize=12)
cbar.set_label('Vector Magnitude', fontsize=14)
# Adjust the spacing between subplots
plt.subplots_adjust(left=0.05, right=0.9, top=0.85, bottom=0.1, wspace=0.3)
plt.show()
# --- Main Execution ---
if __name__ == "__main__":
# 1. Generate Data
print("Generating two moons data...")
x_data = generate_two_moons(N_SAMPLES, NOISE)
dataset = TensorDataset(x_data)
dataloader = DataLoader(dataset, batch_size=BATCH_SIZE, shuffle=True)
print(f"Data shape: {x_data.shape}")
# 2. Initialize Model and Optimizer
print("Initializing model and optimizer...")
model = VectorFieldNet(input_dim=DATA_DIM, hidden_dim=HIDDEN_DIM, output_dim=DATA_DIM, n_layers=N_LAYERS).to(device)
optimizer = optim.Adam(model.parameters(), lr=LEARNING_RATE)
print(f"Model parameters: {sum(p.numel() for p in model.parameters() if p.requires_grad):,}")
# 3. Train the Model
train_flow_matching(model, dataloader, optimizer, N_EPOCHS, device, DATA_DIM)
# 4. Generate Samples
print("\nGenerating samples from the trained model...")
generated_samples = sample_ode(model, N_SAMPLES_GENERATE, DATA_DIM, device)
# 5. Visualize Results
print("Plotting results...")
plot_results(x_data.cpu().numpy(), generated_samples)
# 6. Visualize Vector Field
print("Plotting vector field at t=[0.0, 0.33, 0.67, 1.0]")
plot_vector_field_at_multiple_times(model, device, times=[0.0, 0.33, 0.67, 1.0])
Generating two moons data... Data shape: torch.Size([5000, 2]) Initializing model and optimizer... Model parameters: 66,818 Starting training... Epoch [1/5000], Loss: 1.596811, Time: 0.04s Epoch [500/5000], Loss: 0.922143, Time: 11.08s Epoch [1000/5000], Loss: 0.962374, Time: 22.25s Epoch [1500/5000], Loss: 0.937087, Time: 33.57s Epoch [2000/5000], Loss: 0.929066, Time: 44.97s Epoch [2500/5000], Loss: 0.936958, Time: 56.38s Epoch [3000/5000], Loss: 0.947778, Time: 67.96s Epoch [3500/5000], Loss: 0.940112, Time: 79.12s Epoch [4000/5000], Loss: 0.961403, Time: 90.28s Epoch [4500/5000], Loss: 0.955766, Time: 101.13s Epoch [5000/5000], Loss: 0.939210, Time: 112.13s Training finished. Total Training Time: 112.13s Generating samples from the trained model... Starting ODE sampling with solver: dopri5... Sampling finished. Time: 0.08s Plotting results...
Plotting vector field at t=[0.0, 0.33, 0.67, 1.0]