Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Scientific Machine Learning with PyTorch

Open in Colab

This section uses PyTorch on problems from the rest of the course:

  1. automatic differentiation as a numerical tool, compared with finite differences;

  2. PyTorch’s optimizers, compared with the methods of Optimization Algorithms;

  3. fitting a function with a neural network, with mini-batches and a validation set;

  4. fitting the parameters of an ODE by differentiating through the solver;

  5. solving a boundary value problem with a physics-informed neural network.

At each step we compare with a classical method, because knowing when not to use a neural network is as useful as knowing how to train one.

We work in double precision. Deep learning normally uses single (or lower) precision for speed, but here we want to see errors far below 10-7 (see the section on precision in Linear Algebra in PyTorch).

Run this notebook in Google Colab with a GPU (Runtime → Change runtime type → T4 GPU). The neural networks are trained on the GPU, which is how you would train larger ones.

Automatic differentiation is exact

Take f(x)=sin⁡(3x) e−x2f(x) = \sin(3x)\, e^{-x^2} and compute f′(0.7)f'(0.7) three ways: by hand, by central differences, and with autograd.

Autograd applies the chain rule to the actual sequence of operations that computed yy, so the derivative is exact up to rounding.

PyTorch uses reverse mode automatic differentiation. The forward computation records a graph of operations, and backward() walks it from the output back to the inputs. The gradient of a scalar function of nn variables costs a small multiple of one function evaluation, whatever nn is; a finite difference gradient costs n+1n + 1 evaluations. That is why training networks with millions of parameters is feasible at all.

Second derivatives work the same way. The module torch.func turns a function into a new function that computes its derivatives: grad(f) computes the gradient of a scalar function f, and jacrev(f) and jacfwd(f) compute Jacobians by reverse and forward mode. The Hessian is the Jacobian of the gradient. Here it is for the Rosenbrock function, next to SciPy’s hand-coded one:

A convenient pattern is to write the objective in PyTorch and hand value and gradient to SciPy. With jac=True, minimize expects the function to return both.

PyTorch optimizers

The optimizers in torch.optim are designed for training networks: millions of parameters, gradients that are noisy because they come from mini-batches, and no need for a very accurate minimum. Most are variants of gradient descent with momentum.

Here they are on the Rosenbrock function, a small deterministic problem, with the same budget of 5000 gradient evaluations. LBFGS re-evaluates the function inside its line search, so it takes a closure that recomputes the loss.

Fitting a function: mini-batches and validation

Now a regression problem: 200 noisy samples of f(x)=sin⁡(3x) e−x2/2f(x) = \sin(3x)\, e^{-x^2/2} on [−3,3][-3, 3], with noise of standard deviation 0.1. We hold back a quarter of the data as a validation set, which is never used for training and tells us how well the model does on data it has not seen.

A DataLoader serves the training data in shuffled mini-batches, so each optimizer step uses a stochastic gradient, as in the SGD section of Optimization Algorithms. One pass through the data is an epoch. The DataLoader serves batches from the CPU, and the training loop moves each one to the GPU, which is the usual pattern when a data set does not fit in GPU memory. We train two networks: one plain, and one with weight decay, which adds a penalty λ∥θ∥2\lambda \|\theta\|^2 on the parameters. That is the same idea as ridge regression, applied to a network.

The training error of the plain network falls below the noise variance 0.01: it is starting to fit the noise, and the validation error creeps up as it does. This is overfitting. The usual remedies are to stop training when the validation error is lowest (early stopping) or to regularize, as with weight decay here. None of these choices can be made without held-out data.

For comparison, here is a classical fit: a least squares Chebyshev polynomial, with the degree chosen by the same validation set (compare Interpolation).

A single least squares solve does as well as the networks, at a tiny fraction of the cost. For a smooth function of one variable this is typical, and classical approximation is hard to beat. Networks earn their keep when the input has many dimensions or complicated structure (images, molecules, text), where polynomial bases and grids are hopeless.

Differentiating through a simulation

Because autograd differentiates any sequence of tensor operations, it can differentiate through a whole simulation. Take a damped oscillator

x′′+2ζω x′+ω2x=0,x(0)=1, x′(0)=0,x'' + 2\zeta\omega\, x' + \omega^2 x = 0, \qquad x(0) = 1,\ x'(0) = 0,

observed at 41 times with noise, and fit the frequency ω\omega and damping ratio ζ\zeta. We write RK4 (ODE Solvers) with torch operations, so the loss is a differentiable function of the parameters.

We optimize the logarithms of the parameters, which keeps them positive, starting from a poor guess.

Each gradient cost one forward simulation plus one backward pass through the recorded operations. A finite difference gradient would need an extra simulation per parameter. For models with thousands of parameters (a spatially varying coefficient in a PDE) this difference is huge. It is the idea behind adjoint methods in PDE-constrained optimization and behind neural ODEs.

Two caveats. Backpropagation stores every intermediate value of the simulation, so memory grows with the number of time steps. And autograd differentiates the discretized problem, so the gradient is only as meaningful as the solver is accurate.

Physics-informed neural networks

A physics-informed neural network (PINN) represents the solution of a differential equation as a network uθ(x)u_\theta(x) and trains it to satisfy the equation. For the boundary value problem

−u′′(x)=π2sin⁡(πx),u(0)=u(1)=0,-u''(x) = \pi^2 \sin(\pi x), \qquad u(0) = u(1) = 0,

whose solution is u=sin⁡(πx)u = \sin(\pi x), the loss is the mean squared residual of the equation at a set of collocation points, plus a penalty on the boundary values. The derivatives uθ′′u_\theta'' with respect to the input xx also come from autograd. We use create_graph=True so that the loss can itself be differentiated with respect to the weights.

Now the same problem with the second-order finite difference method: one sparse tridiagonal solve.

The PINN ends up more accurate than finite differences on 256 points, but it took seconds of training against a fraction of a millisecond. Since the finite difference error falls like h2h^2, about five hundred points would match the PINN, still in about a millisecond, and a spectral method (Spectral Methods) would reach machine precision with a few dozen points. The training is also a non-convex optimization problem with no guarantee of success, and the result depends on the network, the collocation points, the penalty weight, and the random initialization.

For forward problems like this one, in low dimensions, classical methods are faster, more accurate, and come with error estimates. PINNs and related methods are worth considering when classical methods are hard, such as inverse problems with scattered measurements, problems in many dimensions, where grids are impossible, or when you need to solve for a whole family of problems.