Skip to main content

Gen-AI with PyTorch for simulation data

December 10th, 10:00am–12:00pm Pacific Time

Abstract: Over the past two weeks in her Deep learning with PyTorch course, Marie focused on classification problems, including classifying points in two interleaved spirals and images from EuroSAT. This week, we’ll use PyTorch to build a machine-learning model for a custom scientific task: predicting the solution to a partial differential equation (PDE) from a given initial condition. The goal is to train a neural network that serves as a fast surrogate for traditional numerical solvers.

Using PyTorch, we will train a surrogate model on 2D simulation data that we generate ourselves. Along the way, we will build a machine-learning pipeline from scratch: generating synthetic training data through simulations, choosing a model architecture, training it on an HPC cluster, optimizing it to run efficiently on the cluster’s GPUs, and evaluating the quality of its predictions.

We will explore three increasingly challenging types of initial conditions: a single Gaussian peak placed randomly within the domain, multiple randomly placed Gaussian peaks, and 1D linear Gaussian features.

Installation

If running on your own computer, you will need a GPU for training. For inference, a CPU is sufficient. In either case, you would install the following libraries:

uv venv env-simdata --python 3.12   # create a new virtual environment
source env-simdata/bin/activate
uv pip install tqdm torch pillow matplotlib
...
deactivate

Here is the installation on a production cluster (e.g. Fir):

module load python/3.12.4 scipy-stack/2025a
python -m venv env-simdata
source env-simdata/bin/activate
python -m pip install --upgrade --no-index pip
python -m pip install --no-index tqdm torch matplotlib
...
deactivate

Today we’ll be using our training cluster where we have already installed everything into a dedicated virtual Python environment. To load it:

source /project/def-sponsor00/shared/env-simdata/bin/activate

Now, we’ll log in to the training cluster with your username and password.

Numerical problem

The goal of this 2-hour ML course is to train a generative AI model on an ensemble of solutions from a 2D advection solver, and then use the model to predict solutions based on initial conditions.

Consider the following acoustic wave equation with \(c=1\) (speed of sound), written as a system separately for velocity and pressure:

\[ \begin{cases} \partial\vec{v}/\partial t = -\nabla p\\\ \partial p/\partial t = -\nabla\cdot\vec{v} \end{cases} \]

Writing a full 3D solver is straightforward, but to reduce the model training time, we will implement it in 2D. Here is a multi-threaded implementation of this solver in Chapel (save it as acoustic2D.chpl):

use Image, Math, IO, sciplot, Time;
use Random;
config const n = 500, nt = 250, nout = 250; // resolution, max time steps, plotting frequency
const a = 0.1;   // 0.1 - thick front, no post-wave oscillations; 0.5 - narrow front, large oscillations
config const animation = true;
config const model = 1, nruns = 1, firstrun=1;
config const npmax = 1; // maximum number of randomly placed points in model 8

var h = 1.0 / (n-1), coef = -(a/h)**2;

var colour: [1..n, 1..n] 3*int;
var cmap = readColourmap('viridis.csv');   // cmap.domain is {1..256, 1..3}

const mesh = {1..n, 1..n};
const largerMesh = {0..n+1, 0..n+1};
var Vx, Vy, P, tmp: [largerMesh] real;

var watch: stopwatch;
watch.start();
for run in firstrun..#nruns {
  P = 0;
  Vx = 0;
  Vy = 0;
  select model {
    // solutions 1-7 from https://folio.vastcloud.org/meetup20250910.html
    when 1 do
      P = [(i,j) in mesh] exp(coef*(((i-1)*h-0.5)**2+((j-1)*h-0.5)**2));
    when 2 do
      P = [(i,j) in mesh] exp(coef*(((i-1)*h-0.25)**2+((j-1)*h-0.5)**2)) +
      exp(coef*(((i-1)*h-0.75)**2+((j-1)*h-0.5)**2));
    when 3 {
      var sources = [(0.25,0.25), (0.25,0.75), (0.75,0.25), (0.75,0.75)];
      for (i,j) in mesh {
        P[i,j] = 0;
        for src in sources do
          P[i,j] += exp(coef*( ((i-1)*h-src[0])**2 + ((j-1)*h-src[1])**2 ));
      }
    }
    when 4 do
      P = [(i,j) in mesh] exp(coef*(((j-1)*h-0.5)**2));
    when 5 do
      P = [(i,j) in mesh] exp(coef*(((j-1)*h-0.5)**2+0.03*((i-1)*h-0.5)**2));
    when 6 {
      const hw = 50, smooth = 15;
      tmp[n/2-hw..n/2+hw,n/2-hw..n/2+hw] = 1.0;
      forall (i,j) in mesh[4..n-smooth,4..n-smooth] do
        P[i,j] = + reduce tmp[i-smooth..i+smooth,j-smooth..j+smooth];
    }
    when 7 {
      const hw = 80, smooth = 15;
      tmp[n/2-hw..n/2+hw,n/2-10..n/2+10] = 1.0;
      forall (i,j) in mesh[4..n-smooth,4..n-smooth] do
        P[i,j] = + reduce tmp[i-smooth..i+smooth,j-smooth..j+smooth];
    }
    when 8 do {
      // 1-5 randomly placed points
      var rint = new randomStream(int);
      var np = rint.next(min=1, max=npmax);
      var rreal = new randomStream(real);
      var sources: [1..np] (real, real);
      for i in 1..np do
        sources[i] = (0.2 + 0.6*rreal.next(), 0.2 + 0.6*rreal.next());
      //writeln(np, " sources: ", sources);
      for (i,j) in mesh {
        P[i,j] = 0;
        for src in sources do
          P[i,j] += exp(coef*( ((i-1)*h-src[0])**2 + ((j-1)*h-src[1])**2 ));
      }
    }
    when 9 do {
      // two randomly placed points with a line between them
      var rreal = new randomStream(real);
      var points = [(0.2+0.6*rreal.next(), 0.2+0.6*rreal.next()),
                    (0.2+0.6*rreal.next(), 0.2+0.6*rreal.next())];
      var ax = points[1][0] - points[0][0], ay = points[1][1] - points[0][1];
      for (i,j) in mesh {
        var wx = (i-1)*h - points[0][0], wy = (j-1)*h - points[0][1];
        var alength = sqrt(ax*ax + ay*ay), wlength = sqrt(wx*wx + wy*wy);
        var distanceFromTheLine = abs(ax*wy - ay*wx) / alength;
        var dimensionlessCoordinateAlongTheLine = (ax*wx + ay*wy) / (alength*alength);
        // writeln(distanceFromTheLine, "  ", dimensionlessCoordinateAlongTheLine);
        if dimensionlessCoordinateAlongTheLine > 1 then
          P[i,j] = exp(coef*(((i-1)*h-points[1][0])**2+((j-1)*h-points[1][1])**2));
        else if dimensionlessCoordinateAlongTheLine < 0 then
          P[i,j] = exp(coef*(((i-1)*h-points[0][0])**2+((j-1)*h-points[0][1])**2));
        else
          P[i,j] = exp(coef*distanceFromTheLine**2);
      }
    }
  }

  if animation then plotPressure(0,run);

  var dt = h / 1.6;
  for step in 1..nt {
    periodic(P);
    periodic(Vx);
    periodic(Vy);
    forall (i,j) in mesh {
      Vx[i,j] -= dt * (P[i,j]-P[i-1,j]) / h;
      Vy[i,j] -= dt * (P[i,j]-P[i,j-1]) / h;
    }
    forall (i,j) in mesh do
      P[i,j] -= dt * (Vx[i+1,j] - Vx[i,j] + Vy[i,j+1] - Vy[i,j]) / h;
    if step%nout == 0 && animation then plotPressure(step,run);
  }
  writeln("finished run ", run);
}
watch.stop();
writeln('Simulation took ', watch.elapsed(), ' seconds');

proc periodic(A) {
  A[0,1..n] = A[n,1..n]; A[n+1,1..n] = A[1,1..n];
  A[1..n,0] = A[1..n,n]; A[1..n,n+1] = A[1..n,1];
}

proc fourDigits(n: int) {
  var digits: string;
  if n >= 1000 then digits = n:string;
  else if n >= 100 then digits = "0"+n:string;
  else if n >= 10 then digits = "00"+n:string;
  else digits = "000"+n:string;
  return digits;
}

proc plotPressure(step,run) {
  // var output: [largerMesh] real;
  var output = P;
  for (i,j) in output.domain {
    if output[i,j] < 0.0 then output[i,j] = 0.0;
    //if output[i,j] > 0.10 then output[i,j] = 1.0;
  }
  var smin = min reduce(output);
  var smax = max reduce(output);
  // writeln(smin, "  ", smax);
  for i in 1..n {
    for j in 1..n {
      var idx = ((output[j,n-i+1]-smin)/(smax-smin)*255):int + 1; //scale to 1..256
      colour[i,j] = ((cmap[idx,1]*255):int, (cmap[idx,2]*255):int, (cmap[idx,3]*255):int);
    }
  }
  var pixels = colorToPixel(colour);   // array of pixels
  var filename = "r" + fourDigits(run) + "s" + fourDigits(step)+".png";
  // writeln("writing ", filename);
  writeImage(filename, imageType.png, pixels);
}

You will also need sciplot.chpl (below) that reads a colour map from the CSV file:

use IO;
use List;

proc readColourmap(filename: string) {
  var reader = open(filename, ioMode.r).reader();
  var line: string;
  if (!reader.readLine(line)) then   // skip the header
    halt("ERROR: file appears to be empty");
  var dataRows : list(string); // a list of lines from the file
  while (reader.readLine(line)) do   // read all lines into the list
    dataRows.pushBack(line);
  var cmap: [1..dataRows.size, 1..3] real;
  for (i, row) in zip(1..dataRows.size, dataRows) {
    var c1 = row.find(','):int;    // position of the 1st comma in the line
    var c2 = row.rfind(','):int;   // position of the 2nd comma in the line
    cmap[i,1] = row[0..c1-1]:real;
    cmap[i,2] = row[c1+1..c2-1]:real;
    cmap[i,3] = row[c2+1..]:real;
  }
  reader.close();
  return cmap;
}

To compile and run it:

module load chapel-multicore
chpl --fast acoustic2D.chpl
wget https://raw.githubusercontent.com/razoumov/simdata/refs/heads/main/viridis.csv
srun --time=0:10:0 --mem-per-cpu=3600 ./acoustic2D --nt=500 --nout=50
CautionNaming scheme

The above run produces images r0001s{0000,0050,0100,0150,0200,0250,0300,0350,0400,0450,0500}.png. In this naming scheme r0001 stands for run 1, s0000 for time step 0 (initial condition), and so on.

To view these images, download them to your laptop:

laptop
scp sfucuda:simdata/r0001s{0000,0050,0100,0150,0200,0250,0300,0350,0400,0450,0500}.png .

For a single point source:

For two point sources:

Some representative solutions

Here are several example solutions (models 1-7; omitted from the code for brevity). We begin with solutions for point sources at a fixed time, with initial conditions shown on the left and the corresponding solutions on the right:

Since advection proceeds in the direction of the pressure gradient, a 1D initial pulse produces a flat 1D wave moving horizontally:

Here we combine 0D (point-source) and 1D (line) features:

The plan is to feed hundreds or thousands of these runs – the initial conditions and their respective time-dependent solutions – to a deep neural network, to train it to produce a surrogate solution from an arbitrary initial condition.

NoteVery large 2D solution

On the instructor’s laptop, demo a \(4001^2\) solution clip with 10_000 time steps:
open $(fd large.mkv ~/training)

Levels of difficulty

We will build our neural networks in order of increasing solution complexity:

   1\(^\text{st}\) level: single point source placed randomly into the 2D domain,
   2\(^\text{nd}\) level: 1-5 randomly placed point sources, and
   3\(^\text{rd}\) level: 1-5 point sources or a single linear source, all randomly placed.

Prepare training and testing data

Quick reminder to set our environment with:

source /project/def-sponsor00/shared/env-jax/bin/activate
module load chapel-multicore

We will run models 8-9 to generate synthetic data for training a generative AI model for all three levels of difficulty. To run, for example, model 8 once and save every frame for movie creation, we can use the following commands:

chpl --fast acoustic2D.chpl
srun --time=0:10:0 --mem-per-cpu=3600 ./acoustic2D --model=8 --nout=1

to produce 251 frames that can be merged into a movie.

We start with model 8 with a single source. For each run we use --nout=250 --nt=250, i.e. there are two output files per each run: the initial condition + timestep 250.

module load chapel-multicore
chpl --fast acoustic2D.chpl
mkdir -p data/{training,single,multi,line}
/bin/rm data/training/*
srun --unbuffered --time=0:10:0 --mem-per-cpu=3600 ./acoustic2D --model=8 --nout=250 --nt=250 --nruns=100
mv r????s????.png data/training

This will give us 100 pairs of files to train the model.

We also need test images:

# srun --unbuffered --time=0:10:0 --mem-per-cpu=3600 ./acoustic2D --model=8 --nt=0 --nruns=5   # just the initial conditions
srun --unbuffered --time=0:10:0 --mem-per-cpu=3600 ./acoustic2D --model=8 --nout=250 --nt=250 --nruns=5   # 2 files per run
mv r????s????.png data/single

Neural net types: early experiments

As a first approach, we could try a standard dense (fully connected) network that maps an input image to its corresponding solution image at t=250 through several hidden layers. However, this architecture tends to perform poorly on generative tasks: flattening a 2D spatial field into a 1D vector discards the problem’s geometric and physical structure, forcing the network to learn spatial relationships from scratch.

An improvement wold be to use a convolutional neural network (CNN). In this approach, convolutional filters are applied to local patches of pixels, with the results feeding into neurons in the next layer. Each neuron therefore receives input from a small region of the previous layer, which reduces the number of parameters compared to a fully connected network and enables the model to recognize features even when they are spatially shifted in the input (translation invariance) or when we change grid resolution. By stacking layers with different filters, the network can learn increasingly complex features.

CNNs are great for processing images (these contain a lot of redundant spatial information!) and detecting patterns, and they work ideally for classification tasks. In short, convolutional layers extract high-level features (detecting patterns and objects) while reducing the spatial resolution – we would call this an encoder network.

To make convolutional layers work for an image-to-image generative neural network, you might to add a decoder part in which you reconstruct the spatial information (where these objects are), forming what is formally called a Convolutional Autoencoder (CAE) network. Unfortunately, a CAE works very slowly to generate a PDE solution, as spatial information gets almost lost in the convolutional layers and, as a result, propagates very slowly into the output layer (reconstructed solution).

To speed up convergence, a U-Net introduces skip connections that pass low-level pixel data from the input image (or encoder) to the decoder. For example, you can convolve one of the encoder layers with one of the decoder layers.

In my experiments, none of these networks performed well. I won’t bore you with details, just will show you a typical solution with a convolutional autoencoder:

Initial condition (left), exact solution (center), neural network prediction (right) after 370 epochs

While this network can accurately position the circle around the initial dot (easy to verify with other initial conditions), it fails to reproduce the solution. You can also see this in the training loss evolution: it essentially plateaus at a high value. I tested variants with different spatial downsampling, and even removing downsampling entirely, but that did not help.

Similarly, U-Nets also struggle with PDEs. While U-Nets are great at identifying and locating patterns, and learning low-frequency shapes, they can’t quite capture high-frequency gradients in a PDE solution. You could try a smoother activation function, increase the depth of the network, play with individual layers, but so far I have not found a good solution for this problem with UNet-type networks.

Temporal dimension

From a temporal standpoint, we chose one of the most demanding problems for model convergence:

A neural operator is a mapping between discretized function spaces
This course Mapping from Mapping to Convergence difficulty Comment
✓ initial conditions solution at a later, fixed time very difficult: large gap between the initial conditions and the solution
✓ initial conditions solution for all time steps difficult
solution at one time step solution at the next time step easiest: small evolution
solution at all previous time steps solution for all remaining time steps ? auto-regressive neural net: apply an FNO to the output of the previous FNO

We will design the neural network to train on multiple time steps and return solutions at multiple time steps for arbitrary initial conditions (line 2). First, though, we’ll train it on a single time step t=250 (line 1), then extend it to produce time-dependent solutions across many time steps.

Fourier Neural Operator (FNO)

What we need is a neural operator: a network designed to learn mappings between function spaces across 2D grids at different resolutions, while capturing both local and global modes.

Specifically, we’ll use a Fourier neural operator (FNO), which represents 2D arrays in Fourier space at each layer. Fourier Neural Operator (FNOs) were pioneered by Li et al. in 2020 – see the diagram below copied from their original paper.

  • P “lifts” the original initial condition to a higher dimension channel space
  • Q projects back to the the target dimension
  • multiple stacks of spectral convolution (Fourier layers)
  • each Fourier layer:
    1. the Fourier transform \(\cal{F}\)
    2. a linear transform \(\cal{R}\) to keep just the lower Fourier modes, i.e. truncate higher-mode oscillations
    3. the inverse Fourier transform \(\cal{F}^{−1}\)
    4. a local linear transform \(\cal{W}\) for a local skip connection

In a nutshell, since we apply convolutions in the Fourier (spectral) space, we automatically get multiscale properties, i.e. the ability to reconstruct shapes of different sizes from the training set solutions. This is ideal for physics-informed ML and for solving PDEs.

Another appealing property of FNOs is their ability to generate solutions at higher spatial resolution than those used during training, effectively enabling super-resolution of numerical solutions.

Now let’s take a look at our network architecture in detail.

In the file fourierModule.py, we define a class SpectralConv2d for our basic spectral convolution layer:

abc

  • the matrix multiplication jnp.einsum() inside SpectralConv2d performs a frequency-domain linear transformation, which is the mathematical equivalent of a convolution in the spatial domain
  • we matrix-multiply the input frequencies and the learnable weights across the input (i) and output (o) channels
  • since we perform a Fourier transform on real-valued data, the output in the frequency domain has some redundancies (symmetries) ⇨ we need to consider only two quadrants in the 2D frequency domain
  • the notation “bixy,ioxy->boxy” describes mapping of input/output dimensions for the complex matrix multiplication at every frequency coordinate: b = batch size, i = number of input channels, o = number of output channels, x and y = 2D frequency coordinates
  • self.weights1 and self.weights2 are learnable weights for positive and negative frequencies in both spatial dimensions
class SpectralConv2d(nn.Module):   # spectral convolution layer = the FNO core
    ...

We stack four of these spectral convolution layers in our network, each with a parallel skip connection:

class FNO2d(nn.Module):   # high-level network architecture
    ...

We also define the loss function:

class RelativeL2Loss(nn.Module):
    def forward(self, pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
        batch_size = pred.shape[0]
        pred_flat = pred.reshape(batch_size, -1)
        target_flat = target.reshape(batch_size, -1)
        diff_norm = torch.norm(pred_flat - target_flat, p=2, dim=1)
        target_norm = torch.norm(target_flat, p=2, dim=1) + 1e-8
        return torch.mean(diff_norm / target_norm)

Training

We start by loading all the necessary libraries:

import os, argparse, sys
from pathlib import Path
from glob import glob
import numpy as np
from PIL import Image
import torch
import torch.nn as nn
from torch.utils.data import TensorDataset, DataLoader
from tqdm import tqdm
from fourierModule import FNO2d

Our training script will read two command-line arguments to set the training directory and the output checkpoint file (into which we’ll be saving our weights from training):

parser = argparse.ArgumentParser(description="Process required arguments")
parser.add_argument("-m", "--model", type=Path, required=True, help="Path to converged model")
parser.add_argument("-d", "--dir", type=Path, required=True, help="Training directory")
args = parser.parse_args()

dir = args.dir
checkpointFile = args.model

With the training data in place, we start by loading it:

# compute the number of timesteps (excluding the ICc) that will train the model
initialConditions = sorted(glob(os.path.join(dir, "r*s0000.png")))
runs = [os.path.basename(ic)[1:5] for ic in initialConditions]
timeSteps = sorted(glob(os.path.join(dir, "r0001s*.png")))[1:]   # exclude the initial conditions
steps = [os.path.basename(ts)[6:10] for ts in timeSteps]

nruns, nsteps = len(runs), len(steps)
nx, ny = np.asarray(Image.open(initialConditions[0]).convert("L"), dtype=np.float32).shape   # image spatial dimensions

# define arrays to hold the training data
xdata = np.zeros((nruns, 1, nx, ny), dtype=np.float32)        # initial conditions
ydata = np.zeros((nruns, nsteps, nx, ny), dtype=np.float32)

# load the data
for r, run in enumerate(tqdm(runs, desc="Loading training data")):
    initial = os.path.join(dir, f"r{run}s0000.png")
    xdata[r, 0] = np.asarray(Image.open(initial).convert("L"), dtype=np.float32) / 255.0
    for s, step in enumerate(steps):
        timestep = os.path.join(dir, f"r{run}s{step}.png")
        ydata[r, s] = np.asarray(Image.open(timestep).convert("L"), dtype=np.float32) / 255.0

# convert the data to PyTorch tensors
xdata, ydata = torch.from_numpy(xdata), torch.from_numpy(ydata)

Next, we set up our device in this order: CUDA (if available), Apple’s Silicon GPU (if available), then CPU:

device = torch.device("cuda" if torch.cuda.is_available()
                      else "mps" if torch.backends.mps.is_available()
                      else "cpu")
print("Using device:", device)

Next, we set the model parameters and define the model:

batch_size = 4
epochs = 50
lr = 1e-3
modes = 24
width = 32

dataset = TensorDataset(xdata, ydata)
loader = DataLoader(dataset, batch_size=batch_size, shuffle=True)

model = FNO2d(out_steps=nsteps, modes1=modes, modes2=modes, width=width).to(device)
optimizer = torch.optim.AdamW(model.parameters(), lr=lr, weight_decay=1e-4)
scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=epochs, eta_min=1e-5)
criterion = RelativeL2Loss()

Finally, we train it:

model.train()   # put nn.Module into training mode
for epoch in range(1, epochs + 1):
    print(epoch)
    total_loss = 0.0
    for bx, by in loader:
        bx, by = bx.to(device), by.to(device)
        optimizer.zero_grad()
        pred = model(bx)
        loss = criterion(pred, by)
        loss.backward()
        optimizer.step()
        total_loss += loss.item() * bx.size(0)
    scheduler.step()
    avg_loss = total_loss / len(dataset)
    if epoch == 1 or epoch % 10 == 0 or epoch == epochs:
        print(f"Epoch [{epoch:03d}/{epochs:03d}] - Rel L2 Loss: {avg_loss:.6f}")

The last step is to save the computed weights and biases:

torch.save(model.state_dict(), checkpointFile)
print("Saved model weights to", checkpointFile)

Since we have only two vGPUs and more attendees than available vGPUs, it would be a good idea to reduce the number of epochs to let’s say epochs = 10 so that nobody sits on a GPU for too long.

Let’s run this script:

# laptop
# source ~/env-simdata/bin/activate
python train.py -m data/b01.pt -d data/training
# sfucuda
# module load python/3.12.4 scipy-stack/2025a
# source /project/def-sponsor00/shared/env-simdata/bin/activate
srun --unbuffered --time=0:15:0 --mem=7200 --gpus-per-node=1 python train.py -m data/b01.pt -d data/training

Modify the script to save a checkpoint after every second epoch in uniquely named files so the checkpoints don’t overwrite one another.

Inference

With the model weights saved, how can we infer a solution from a given initial condition?

Let’s start a new script infer.py and load the required libraries:

import os, argparse, sys
from pathlib import Path
from glob import glob
import numpy as np
from PIL import Image
import matplotlib as mpl
import torch
from fourierModule import FNO2d

This script will also take two command-line arguments: the converged model (checkpoint file) and the directory with input initial states. It will iterate over all initial states in this directory and run inference on each one.

parser = argparse.ArgumentParser(description="Process required arguments")
parser.add_argument("-m", "--model", type=Path, required=True, help="Path to converged model")
parser.add_argument("-d", "--dir", type=Path, required=True, help="Test directory")
args = parser.parse_args()

checkpointFile = args.model
dir = args.dir

As usual, we should set the device:

device = torch.device("cuda" if torch.cuda.is_available()
                      else "mps" if torch.backends.mps.is_available()
                      else "cpu")
print("Using device:", device)

Next we load the model/checkpoint and look up its parameters:

state_dict = torch.load(checkpointFile, map_location=device, weights_only=True)

# Recreate the model with the same hyperparameters used when training; predict all 50 steps at once
modes = state_dict["conv_layers.0.weights1"].shape[2]   # 24
width = state_dict["lift.bias"].shape[0]                # 32
nsteps = state_dict["proj2.bias"].shape[0]              # 1 - the number of timesteps to infer
model = FNO2d(out_steps=nsteps, modes1=modes, modes2=modes, width=width).to(device) # num_layers=4
model.load_state_dict(state_dict)   # load the saved weights (map_location handles CPU/GPU differences safely)

We then scan the initial states and load the colourmap for plotting:

initialConditions = sorted(glob(os.path.join(dir, "r*s0000.png")))
runs = [os.path.basename(ic)[1:5] for ic in initialConditions]

cmap = mpl.colormaps["viridis"]

Finally, we run inference, saving the last timestep for each initial condition:

model.eval()   # put nn.Module into evaluation/inference mode
for run in runs:
    testImageFile = os.path.join(dir, f"r{run}s0000.png")
    testImage = np.asarray(Image.open(testImageFile).convert("L"), dtype=np.float32) / 255.0
    testTensor = torch.from_numpy(testImage).unsqueeze(0).unsqueeze(0).to(device)  # (1, 1, nx, ny)
    with torch.no_grad():
        predictedSteps = model(testTensor).squeeze(0).cpu().numpy()
    print("Predicted output shape:", predictedSteps.shape)  # (51, 500, 500)
    idx = nsteps - 1
    frame = np.clip(predictedSteps[idx] * 255.0, 0, 255).astype(np.uint8)
    rgb = (cmap(frame / 255.0)[..., :3] * 255).astype(np.uint8)
    Image.fromarray(rgb, mode="RGB").save(os.path.join(dir, f"pred{run}.png"))

Let’s compute inference!

# laptop
# source ~/env-simdata/bin/activate
python infer.py -m data/b01.pt -d data/single
# sfucuda
# module load python/3.12.4 scipy-stack/2025a
# source /project/def-sponsor00/shared/env-simdata/bin/activate
srun --time=0:5:0 --mem=7200 --gpus-per-node=1 python infer.py -m data/b01.pt -d data/single

Here is an example of a converging solution for a single source:

Solution after (left to right) 2, 4, 6, and 10 epochs.

Run inference on five randomly generated initial states, each with a single point source.

Multi-point-source model

What happens if we try to run inference on an initial state with multiple sources (difficulty level 2)? Let’s try it!

srun --unbuffered --time=0:10:0 --mem-per-cpu=3600 ./acoustic2D --model=8 --npmax=5 --nout=250 --nt=250 --nruns=5
mv r????s????.png data/multi

srun --unbuffered --time=0:5:0 --mem=3600 --gpus-per-node=1 python infer.py -m data/b01.pt -d data/multi

Download these images to your laptop and open them (the exact commands will likely be different for you, depending on your setup and OS):

# laptop
scp sfucuda:simdata/data/multi/pred????.png .
open pred????.png

Applying the same model (50 epochs) to initial states with (left to right) 1, 2, and 5 sources.

The solution get progressively worse for more sources. For multiple point sources, we actually need to train a new model that can adapt to a variable number of sources.

Let’s add 100 new runs with a a random number (1..5) of sources to our previous training dataset, labelling them runs 0101..0200, and then train the new model:

srun --unbuffered --time=0:10:0 --mem-per-cpu=3600 ./acoustic2D --model=8 --npmax=5 --nout=250 --nt=250 --firstrun=101 --nruns=100
mv r????s????.png data/training

>>> set epochs = 300
srun --unbuffered --time=0:30:0 --mem=7200 --gpus-per-node=1 python train.py -m data/b03.pt -d data/training

Compared with the previous single-source model, convergence is slower. After 50 epochs, the loss drops to 0.037365, which is reasonable given the more complex initial states and solutions. After 100 epochs the loss is down to 0.012957 (saved as data/b02.pt), and to 0.006608 after 300 epochs (saved as data/b03.pt).

We now run inference on the new model:

srun --unbuffered --time=0:5:0 --mem=3600 --gpus-per-node=1 python infer.py -m data/b03.pt -d data/multi
# laptop
scp sfucuda:simdata/data/multi/pred????.png .
open pred????.png

Inferred solution after 300 trailing epochs with with (left to right) 1, 2, and 5 sources.

The solution is now more consistent regardless of the number of sources, but there is still a little bit of degradation when going to multiple sources even after 300 epochs.

Let’s train on a larger dataset with 1000 runs and a maximum of five point sources:

mkdir -p data/large
srun --unbuffered --time=0:10:0 --mem-per-cpu=3600 ./acoustic2D --model=8 --npmax=5 --nout=250 --nt=250 --nruns=1000
mv r????s????.png data/large

>>> set epochs = 50
srun --unbuffered --time=1:0:0 --mem=7200 --gpus-per-node=1 python train.py -m data/b04.pt -d data/large
# Epoch [050/050] - Rel L2 Loss: 0.021039, 34m

srun --unbuffered --time=0:5:0 --mem=3600 --gpus-per-node=1 python infer.py -m data/b04.pt -d data/multi

Inferred solutions: training on 200 runs after 300 epochs (left), 1000 runs after 50 epochs (right).

More training data can help the neural network converge more reliably by exposing it to a wider range of examples and reducing overfitting.

Multi-shape model

Our point-source model has never seen an extended source. How will it perform on line sources (difficulty level 3)? Let’s check!

# generate test solutions
srun --unbuffered --time=0:5:0 --mem-per-cpu=3600 ./acoustic2D --model=9 --nout=250 --nt=250 --nruns=5
mv r????s????.png data/line

srun --unbuffered --time=0:5:0 --mem=3600 --gpus-per-node=1 python infer.py -m data/b04.pt -d data/line

The exact solution (top) and the solution inferred by the point-source model b04.pt (bottom).

This is not bad for a model that wasn’t trained on line sources! A model trained on both point and line sources would perform even better.

Train a model on a combination of point and line sources. You can add line sources to the training dataset with:

srun --unbuffered --time=0:10:0 --mem-per-cpu=3600 ./acoustic2D --model=9 --nout=250 --nt=250 --firstrun=1001 --nruns=1000
mv r????s????.png data/large

Time-dependent model

Now that we have trained a neural network to infer the solution at a fixed later timestep t=250, can we use our existing model b04.pt to predict the solutions for all earlier timesteps t=1..249? After all, doesn’t the model already compute those steps on its way to t=250?

The answer to both questions is no. The model doesn’t know how the travelling wave evolves over time, and it has no concept of time. To infer a time-dependent solution, we need to train the model on a time-dependent dataset. Fortunately, we already have code for that!

Recall this block inside train.py:

# compute the number of timesteps (excluding the ICc) that will train the model
initialConditions = sorted(glob(os.path.join(dir, "r*s0000.png")))
runs = [os.path.basename(ic)[1:5] for ic in initialConditions]
timeSteps = sorted(glob(os.path.join(dir, "r0001s*.png")))[1:]   # exclude the initial conditions
steps = [os.path.basename(ts)[6:10] for ts in timeSteps]

nruns, nsteps = len(runs), len(steps)
nx, ny = np.asarray(Image.open(initialConditions[0]).convert("L"), dtype=np.float32).shape   # image spatial dimensions

# define arrays to hold the training data
xdata = np.zeros((nruns, 1, nx, ny), dtype=np.float32)        # initial conditions
ydata = np.zeros((nruns, nsteps, nx, ny), dtype=np.float32)

In all previous runs, the script set nsteps to 1 based on the number of files per run in the training dataset. With intermediate time frames, it sets nsteps accordingly and fills the PyTorch tensor ydata with the corresponding data.

During inference, nsteps is set automatically from the shape of the bias array in the checkpoint file:

nsteps = state_dict["proj2.bias"].shape[0]

In infer.py, the array predictedSteps has shape (nsteps, 500, 500). The only change needed is to save all nsteps frames instead of just the final frame at idx = nsteps - 1.

For simplicity, focus on just line sources (--model=9), run each model to t=250, store every 10th timestep (--nout=10), and start with 100 runs. That should generate (1+25)*100=2600 training files. Train the net and use it to compute time-dependent solutions.

GPU thread / memory utilization

For your past jobs on production clusters, we encourage you to use our Metrix portal which is currently available for Rorqual, Narval and Nibi. The support for Fir will hopefully come very soon.

However, you can also monitor running jobs in real time via command line. The two tools useful for this are NVIDIA’s nvidia-smi and nvtop, and you can use them from the login node via these handy shortcuts:

function job-nvidia-smi() {
    srun --overlap --jobid=$(squeue -u $USER | awk 'NR==2 {print $1}') --pty watch -n 1 nvidia-smi   # replace current output every 1s
}
function job-nvtop() {
    srun --overlap --jobid=$(squeue -u $USER | awk 'NR==2 {print $1}') --pty nvtop   # the first job from the list
}
Note

nvidia-smi and nvtop do not have access to real-time GPU utilization inside a MIG, although they show memory usage per slice. They show GPU utilization only if you schedule a full GPU.

Typical output from nvtop on a full GPU