Foundations to Frontier
Tests
C. Programming, Tools and HPC › C3 Deep Learning Frameworks

PyTorch Lightning

PyTorch Lightning separates the science (model, loss, optimizer) from the engineering (the training loop, devices, precision, logging, checkpointing, early stopping, distributed training). You write a LightningModule with training_step, validation_step and configure_optimizers; the Trainer runs the loop and calls your hooks and callbacks in a fixed order. This topic covers the LightningModule and LightningDataModule, the Trainer's main flags (max_epochs, accumulate_grad_batches, gradient_clip_val, precision, devices, fast_dev_run, overfit_batches), callbacks (EarlyStopping, ModelCheckpoint), loggers and reproducibility. In the exercises you build a mini Trainer with hooks, accumulation, clipping and both callbacks in NumPy, then study how early-stopping patience and checkpoint selection affect test error on a model that overfits.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

Let someone else run the kitchen

A recipe says what to cook; running a busy kitchen (timing, ovens, cleaning, writing down what worked) is a different job. Training neural networks is similar: the “recipe” is your model and its loss, but the loop around it (going through the data many times, saving the best version, stopping when it stops improving, using several GPUs) is the same boilerplate every time. PyTorch Lightning is a ready-made kitchen manager: you write the recipe, it runs the loop.

EarlyStopping and ModelCheckpoint on an overfitting model
10.10.011101001000trainvalidation (monitored)test (clean, unseen)
stopped after epoch 19 of 3000 (1% of the budget)
best checkpoint: epoch 9, test MSE 0.0669
oracle (best test) epoch 52: 0.0280
last epoch, no callbacks: 0.0829
Small patience stops in the first wiggle of the validation curve (momentum makes it oscillate early). Larger patience finds the same best checkpoint and only costs extra epochs, as long as ModelCheckpoint restores the best weights rather than the last ones. The grey region is training that never happened.
Why engineers care

Research code that hand-rolls its loop tends to accumulate subtle bugs (validation in training mode, wrong accumulation, missing seeds) and is hard to scale from a laptop to a GPU cluster. A standard trainer makes experiments comparable, reproducible and portable, which matters when a model feeds a flight or robotics pipeline that others must review.

📝 Quick check (Level 0)
0/3 answered
  1. 1. What does Lightning take over from you?
  2. 2. Why stop training early?
  3. 3. In the demo, what keeps falling while validation error rises?

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

A LightningModule

import lightning as L
import torch
from torch import nn

class Regressor(L.LightningModule):
    def __init__(self, lr=1e-3):
        super().__init__()
        self.save_hyperparameters()                  # stored in checkpoints and logs
        self.net = nn.Sequential(nn.Linear(8, 64), nn.ReLU(), nn.Linear(64, 1))

    def training_step(self, batch, batch_idx):
        x, y = batch
        loss = nn.functional.mse_loss(self.net(x), y)
        self.log("train_loss", loss)
        return loss                                  # Lightning calls backward() and step()

    def validation_step(self, batch, batch_idx):
        x, y = batch
        self.log("val_loss", nn.functional.mse_loss(self.net(x), y))

    def configure_optimizers(self):
        return torch.optim.Adam(self.parameters(), lr=self.hparams.lr)

trainer = L.Trainer(max_epochs=100, callbacks=[
    L.pytorch.callbacks.EarlyStopping(monitor="val_loss", patience=10),
    L.pytorch.callbacks.ModelCheckpoint(monitor="val_loss", save_top_k=1)])
trainer.fit(Regressor(), train_loader, val_loader)

There’s no zero_grad, backward, step, model.eval(), torch.no_grad() or .to(device) in your code: the Trainer does all of them, in the right order.

📝 Quick check (Level 1)
0/3 answered
  1. 1. Which method defines the optimizer?
  2. 2. What should training_step return?
  3. 3. Who switches the model to eval mode for validation?

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 35 minUndergraduate students and practising engineers.

The loop the Trainer runs

For each epoch: on_train_epoch_start → for each batch, training_step → (every k batches with accumulate_grad_batches=k) gradient clipping (gradient_clip_val), optimizer.step(), zero_grad() → on_train_epoch_end → validation loop under eval() and no_grad() → on_validation_epoch_end → callbacks such as EarlyStopping and ModelCheckpoint read the logged metrics. trainer.global_step counts optimizer steps, not batches.

Trainer flags worth knowing

  • precision="bf16-mixed" / "16-mixed": mixed precision.
  • devices, accelerator, strategy="ddp": same code from CPU to a multi-GPU cluster (C6).
  • fast_dev_run=True: one training and one validation batch, to catch crashes in seconds.
  • overfit_batches=1: the “can it overfit one batch?” sanity check (C3.1).
  • deterministic=True with L.seed_everything(42, workers=True): reproducibility (C2.4).
  • limit_train_batches, val_check_interval, log_every_n_steps.

Data and callbacks

A LightningDataModule bundles prepare_data (download once), setup(stage) (splits), and train/val/test_dataloader, so a dataset travels with its preprocessing. Callbacks are objects with hook methods (on_validation_end, …) for anything not part of the model: early stopping, checkpointing, learning-rate monitoring, EMA of weights, custom plots. Loggers (TensorBoard, CSV, Weights & Biases, MLflow) receive everything passed to self.log.

🐍 Exercise 1: a mini Lightning Trainer
Implement LightningModule (log, hooks), an SGD optimizer, Callback, EarlyStopping (patience, min_delta, mode), ModelCheckpoint (best score, path and a copy of the weights, plus last), an ArrayLoader, and a Trainer with hook order, gradient accumulation, global-norm gradient clipping, validation averaging, callback_metrics, should_stop and fast_dev_run. Train a linear regression and check every behaviour.
📝 Quick check (Level 2)
0/3 answered
  1. 1. 10 batches per epoch, accumulate_grad_batches = 4. Optimizer steps per epoch?
  2. 2. fast_dev_run=True is for…
  3. 3. EarlyStopping decides based on…

Level 3: Advanced

★★★★☆ Advanced⏱ 30 minGraduate level, with full derivations and proofs.

Early stopping as regularization

With gradient descent from small weights, a flexible model first fits the large, smooth structure and only later the small, noisy details (B4.3). Stopping early therefore limits effective capacity much like an L2 penalty: for linear least squares, k steps of gradient descent with step size η behave approximately like ridge regression with λ ≈ 1/(kη). The validation loss estimates where the trade-off is best.

Choosing patience and checkpoints

  • Patience too small stops at the first noise wiggle (momentum makes the early curve oscillate).
  • Patience large costs epochs but, with ModelCheckpoint restoring the best weights, does not hurt the selected model.
  • min_delta ignores improvements smaller than the noise in the validation estimate.
  • The best validation score is optimistically biased: it was selected as a minimum over noisy values. Report final numbers on a separate test set.
  • Resuming: trainer.fit(model, ckpt_path="last.ckpt") restores optimizer state, epoch and callbacks, not just weights.
📝 Quick check (Level 3)
0/3 answered
  1. 1. With ModelCheckpoint(monitor='val_loss') and large patience, the selected model is…
  2. 2. Why is the best validation loss optimistic?
  3. 3. Early stopping of gradient descent on least squares resembles…

Level 4: Expert

★★★★★ Expert⏱ 35 minResearchers: original papers and open problems.

Early stopping, measured

Exercise 1. The mini Trainer recovers w = (2.001, −0.998), b = 0.498. 30 epochs of 10 batches give 300 global steps; with accumulation 4 there are 3 steps per epoch; gradient norms never exceed the clip value; fast_dev_run makes exactly 1 step and 1 validation. On a scripted validation curve 5, 4, 3, 3.5, 3.2, 3.1, 3.3, 2.9, 3.0, …: patience 3 stops at epoch 5; patience 5 lets the 2.9 at epoch 7 reset the counter and runs all 12 epochs; patience 5 with min_delta 0.15 ignores that 0.1 improvement and stops at epoch 7.

Exercise 2: patience and checkpoints on an overfitting model. A degree-20 Legendre model is trained by full-batch gradient descent with momentum (lr 0.05, μ 0.9) on 30 noisy samples of sin(3x) (σ = 0.3), with 30 validation samples, for 3000 epochs. The training MSE falls to 0.013 (below the noise variance 0.09: the model fits the noise). Test MSE against the clean function:

Selection Epoch (0-based) Test MSE
oracle (best test) 18 0.0404
best validation (patience ≥ 10) 21 0.0434
patience 1 or 3 4 0.357
last epoch, no callbacks 2999 0.513

Patience 10, 30, 100 and 300 all select epoch 21 and run 32, 52, 122 and 322 epochs. The best validation MSE (0.1296) is lower than the expected loss of that model on fresh noisy data (0.0434 + 0.09 = 0.1334), a small selection bias with 30 validation points.

🐍 Exercise 2 (research): patience, checkpoints and overfitting
Train an overfitting polynomial model, record train/validation/test curves, apply Lightning's early-stopping rule for a sweep of patience values, and compare the test error of the selected checkpoint with the oracle epoch and with training to the end; quantify the optimism of the best validation score.

Lightning in AI, robotics and aerospace

  • Surrogate models for simulations, trained the same way on a laptop and on an HPC GPU node by changing only Trainer flags.
  • Perception models for robots and satellites with mixed precision and multi-GPU training.
  • Reproducible ablations: a config system (Hydra, C2.5) plus Lightning’s seed and checkpoint conventions make each run reconstructible.
  • Fabric, Lightning’s lighter layer, for custom loops (reinforcement learning) that still want device and precision handling.

References

  1. W. Falcon and the PyTorch Lightning team (2019). PyTorch Lightning. github.com/Lightning-AI/pytorch-lightning; documentation at lightning.ai/docs.
  2. L. Prechelt (1998). “Early stopping: but when?” In Neural Networks: Tricks of the Trade, Springer LNCS 1524.
  3. Y. Yao, L. Rosasco, A. Caponnetto (2007). “On early stopping in gradient descent learning.” Constructive Approximation, 26.
  4. I. Goodfellow, Y. Bengio, A. Courville (2016). Deep Learning, §7.8 (early stopping). MIT Press.
  5. G. C. Cawley, N. L. C. Talbot (2010). “On over-fitting in model selection and subsequent selection bias in performance evaluation.” JMLR, 11.