Normalising and the training loop

Every quantity on a similar scale, with statistics from the training set only; then batch, forward, loss, backward, step, with a validation loss each epoch.

Outcome: Standardise inputs and outputs with statistics from the training set only, and undo the scaling to report results in physical units; pick per-channel statistics for fields and a log scale for wide-range quantities, and let size enter through Re; write a PyTorch training loop with a DataLoader, Adam, MSE, a schedule and a validation pass under model.eval() and torch.no_grad(); save the trained weights with their scaling and make runs repeatable where the platform allows.

Builds on Loss, gradients and autograd, From runs to arrays, Train, validation and test

Raw engineering inputs come in very different units and sizes: an angle of attack of a few degrees, a sweep of 20 to 36 degrees, a Reynolds number of millions, a pressure of 10510^5 Pa. A freshly initialised network assumes inputs of order one (LeCun et al. 1998). Large inputs can push its neurons into the flat parts of their activations, and the gradients of different weights can end up with very different sizes, so no single learning rate suits them all. The remedy is to rescale each input.

x~=x−μσ\tilde{x} = \frac{x - \mu}{\sigma}
(4-5)
μ\mu and σ\sigma: the mean and standard deviation of that input over the training runs. x~\tilde{x} then has mean 0 and standard deviation 1 on them.

This is standardising, the usual default.

For design variables with fixed bounds, min-max scaling onto [−1,1][-1, 1] or [0,1][0, 1] is natural. For positive quantities that span decades (Reynolds number, viscosity, a heat flux), their logarithm is standardised instead.

On the aircraft, min-max scaling takes the angle of attack as (α−3)/5(\alpha - 3)/5 and the sweep as (Λ−28)/8(\Lambda - 28)/8, which map the training box (α\alpha -2° to 8°, Λ\Lambda 20° to 36°) onto [−1,1][-1, 1]; the site’s in-browser neural field uses it. The course’s listings standardise instead.

The statistics are computed on the training runs only, then applied unchanged to validation, test and new designs. Statistics from all the data let the held-out runs shape the model, a small leak (see train, validation and test).

Outputs and units

Outputs are scaled too: the model trains on standardised targets, and predictions are converted back to physical units before any error is reported. With several channels (pressure, three velocity components, temperature), each has its own mean and standard deviation, computed over all points of the training runs. The loss adds up the channels’ errors, so the scaling also decides how much each counts. Equal weights are a sensible start; a channel that matters more to the design is weighted explicitly in the loss, with the weight chosen on the validation runs.

Non-dimensional quantities such as CpC_p (see physical fields) already do much of this. They scale each run by its own reference values, such as the free-stream speed or the inlet pressure, which is valid because those are known inputs of the run.

A run must not be scaled by statistics of its own output field (its mean or maximum CpC_p): at prediction time that field is the unknown.

When runs differ in size, speed or fluid, each run’s coordinates are divided by its reference length LL, and the model receives a standardised log⁡10Re\log_{10}\mathrm{Re} built on that same length (and MM for a compressible flow) in place of size and speed; without it, a body and a larger copy of it would look the same to the model. By dynamic similarity (physical fields) nothing relevant is lost. A model whose inputs and outputs are all dimensionless also gives the same answer whatever units the data were written in; Villar et al. 2023 build that property into the model itself.

Example 4-4 standardises the two design inputs of the download.

Example 4-4. Standardising the aircraft’s inputs with training statistics only, with scikit-learn
import numpy as np
from sklearn.preprocessing import StandardScaler
from aircraft import load_runs

# The aircraft runs: alpha and sweep of each run.
d = load_runs()
X = np.column_stack([d["alpha"], d["sweep"]])
train = d["split"] == 0  # 36 training runs
val = d["split"] == 1    # 8 validation runs

# Statistics from the training runs only.
scaler = StandardScaler().fit(X[train])1
Xn_tr = scaler.transform(X[train])
Xn_val = scaler.transform(X[val])2
print(scaler.mean_.round(2), scaler.scale_.round(2))
# The validation runs are not exactly mean 0, std 1.
print(Xn_val.mean(0).round(2), Xn_val.std(0).round(2))
# Back to physical units: scaler.inverse_transform(Xn_tr)
  1. fit computes μ\mu and σ\sigma of Equation 4-5 per column, from the 36 training runs only.
  2. transform applies those same statistics to the validation runs; they are never refitted on them.

Example 4-4 prints [ 3.21 28.42] [2.75 4.82], the means and standard deviations of α\alpha and Λ\Lambda over the training runs, then [-0.42 -0.49] [1.21 0.58] for the validation runs. Those are not 0 and 1, and need not be: the eight runs played no part in the statistics, as a new design would not.

The training loop

For each minibatch of training data the loop does five things: run the model forward, compute the loss, clear the old gradients, run backpropagation, and let the optimiser update the weights. After each epoch (one pass over the training data) it switches to evaluation mode and computes the loss on the validation runs, which are never used to update the weights.

The loop on the aircraft

Example 4-5 trains the MLP of Example 4-1 to predict the lift coefficient CLC_L of the aircraft from α\alpha and Λ\Lambda, on the 36 training runs of the download, and checks it on the 8 validation runs.

Example 4-5. The training loop, with a validation loss after each epoch, in PyTorch
# Add to aircraft.py: the course's scaling of alpha and sweep.
def scale_designs(d, train):
    """alpha and sweep of every run, standardised with the
    training runs' mean and std; also returns those two."""
    X = np.column_stack([d["alpha"], d["sweep"]])
    mu, sd = X[train].mean(0), X[train].std(0)1
    return (X - mu) / sd, mu, sd

# Then, in a script:
import torch
from torch import nn
from torch.utils.data import DataLoader, TensorDataset
from aircraft import MLP, load_runs, scale_designs, split_runs

torch.manual_seed(0)
# The aircraft's CL against alpha and sweep: 36 training
# and 8 validation runs.
d = load_runs()
tr, va, _, _ = split_runs(d)
# Normalise with the training runs' statistics.
Xn, mu, sd = scale_designs(d, tr)
y = d["CL"][:, None]
ym, ys = y[tr].mean(), y[tr].std()
T = lambda a: torch.tensor(a, dtype=torch.float32)
X_tr, y_tr = T(Xn[tr]), T((y[tr] - ym) / ys)
X_val, y_val = T(Xn[va]), T((y[va] - ym) / ys)

data = TensorDataset(X_tr, y_tr)
loader = DataLoader(data, batch_size=8, shuffle=True)2
model = MLP()
loss_fn = nn.MSELoss()
opt = torch.optim.Adam(model.parameters(), lr=3e-3)
epochs = 300
sched = torch.optim.lr_scheduler.CosineAnnealingLR(
    opt, T_max=epochs)3

for epoch in range(epochs):
    model.train()
    total = 0.0
    for xb, yb in loader:
        # Forward pass and loss on one minibatch.
        loss = loss_fn(model(xb), yb)
        # Clear old gradients, backpropagate, update.
        opt.zero_grad()
        loss.backward()
        opt.step()
        total += loss.item() * len(xb)4
    # The epoch's mean training loss.
    train_loss = total / len(data)
    # Lower the learning rate.
    sched.step()
    # Validation: evaluation mode, no gradients needed.
    model.eval()
    with torch.no_grad():5
        val_loss = loss_fn(model(X_val), y_val).item()
    if epoch % 100 == 0 or epoch == epochs - 1:
        print(f"epoch {epoch:3d} train {train_loss:.1e}"
              f" val {val_loss:.1e}")

# Validation RMSE back in units of CL.
print(f"val RMSE {ys * val_loss ** 0.5:.4f} in CL")
# The trained surrogate: weights and scaling, in one file.
torch.save({"model": model.state_dict(),6
            "mu": mu.tolist(), "sd": sd.tolist(),
            "ym": float(ym), "ys": float(ys)}, "cl_mlp.pt")
  1. The statistics of Equation 4-5, from the training runs only. scale_designs returns them with the scaled inputs, so that they can be saved; later listings scale α\alpha and Λ\Lambda with it. CLC_L is scaled the same way, below.
  2. shuffle=True deals the 36 training runs into batches of 8 in a new order every epoch.
  3. T_max=epochs: the cosine runs over the whole training, because the scheduler steps once per epoch, below.
  4. The batch loss is a mean, so it is weighted by the batch size: the last batch holds 4 runs, not 8, and the epoch’s mean stays exact.
  5. Evaluation mode, and no record for autograd: the validation runs never update the weights.
  6. The weights and the normalisation statistics go into one file: a model without its scaling cannot be used.

Example 4-5 prints the two losses, in normalised units, every 100 epochs, from epoch 0 train 7.6e-01 val 6.7e-01 to epoch 299 train 3.2e-06 val 1.0e-05, then val RMSE 0.0007 in CL: on the validation runs the network is off by less than a thousandth in CLC_L. The lift of this solver is a smooth function of the two inputs, which makes it an easy target.

A Dataset returns one example by index, and TensorDataset wraps arrays already in memory. A DataLoader shuffles the examples and groups them into batches. For data on disk, a small Dataset class loads one run at a time.

model.train() and model.eval() switch the few layers that behave differently while training, such as dropout (see the next lesson); this small model has none, so here the calls change nothing. torch.no_grad() stops autograd recording during validation, which saves memory and time. The scheduler lowers the learning rate as training proceeds, here along a cosine.

model.state_dict() holds every weight; saved with the normalisation statistics, as in the last lines of Example 4-5, it is a checkpoint from which the model can be used again.

Once trained, the surrogate is that file of weights and its scaling statistics, and each answer costs one forward pass, usually a small fraction of the solver’s time.