AI and ML FoundationsVol. 14A · Part XIV
0 / 0

Shelves / AI and ML Foundations

AI·152

PyTorch

The dominant deep learning framework from the inside out: tensors (dtype, device, shape, strides, views), autograd and the dynamic computational graph, nn.Module, parameters and buffers, state dicts, optimisers and learning-rate schedulers, Dataset and DataLoader with workers and collation, a complete idiomatic training and evaluation loop, checkpointing and safe loading, GPUs and the CUDA asynchronous execution model, mixed precision with bfloat16 autocast and gradient scaling, memory accounting and activation checkpointing, torch.compile, distributed training (DDP, FSDP2, tensor and pipeline parallelism, torchrun), profiling with torch.profiler, exporting models, and how JAX, TensorFlow/Keras, Rust (Burn, candle), Julia (Flux/Lux), Java (DJL) and C++ (LibTorch) compare.

30 topics · ~26 min read · 32-question quiz
Updated Suggest a correction

Start here: the framework that writes the backward pass for you

PyTorch gives you three things on top of NumPy: tensors that can live on a GPU, autograd that records operations and computes gradients for you, and building blocks (nn.Module, layers, losses, optimisers, data loaders) for writing models and training loops. Chapter 151's fifty lines of NumPy become:

Python
model = nn.Sequential(nn.Linear(64, 256), nn.ReLU(), nn.Linear(256, 10))
opt = torch.optim.AdamW(model.parameters(), lr=1e-3)
for xb, yb in batches:
    loss = nn.functional.cross_entropy(model(xb), yb)
    opt.zero_grad(); loss.backward(); opt.step()       # backward pass written for you

Tensors share memory more often than you'd think

Text
a: shape (3, 4), strides (4, 1)
a.T: shape (4, 3), strides (1, 4), contiguous = False, shares memory with a = True

A transpose doesn't move any numbers; it changes the strides (how many elements to skip per step along each dimension) of a view onto the same memory. Views are free, but some operations need contiguous memory (.contiguous() copies), and changing a view changes the original.

The optimiser matters as much as the model

The same 19,210-parameter network, 30 epochs of mini-batches of 32:

Text
SGD   lr 0.01:   validation loss 2.087 after 5 epochs, 0.810 after 30   accuracy 92.0%
SGD   lr 0.1:    validation loss 0.507 after 5,        0.172 after 30   accuracy 93.0%
AdamW lr 0.001:  validation loss 0.396 after 5,        0.105 after 30   accuracy 97.8%

Plain SGD at a small learning rate barely moved; AdamW (which adapts each parameter's step size) reached a better model in the same time with its default-ish learning rate. AdamW is the usual starting point; SGD with momentum and a tuned schedule can match it but needs more care.

Watch the validation loss, not just the training loss

AdamW at lr 3×10⁻³ for 150 epochs:

Text
training loss → 0.0002 (memorised)
validation loss lowest 0.070 at epoch 87, then rising to 0.079

After epoch 87 the model kept improving on training data and got slightly worse on new data. Early stopping keeps the weights from the best validation epoch. Dropout (0.5) gave the same test accuracy here (97.5% both), a reminder that regularisers help most when data is scarce relative to model size.

The classic bug: forgetting model.eval()

With dropout in the model and model.train() still on, two forward passes over the same input gave different logits (identical top predictions this time, but not reliably). Layers like dropout and batch normalisation behave differently in training and evaluation; always switch with model.eval() and wrap inference in torch.no_grad().

How deep to go in PyTorch

Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.

Level What you can do
L1 Create tensors, build an nn.Sequential model and run a training loop
L2 Write custom modules, datasets and loaders, with validation, checkpointing and early stopping
L3 Explain autograd's graph, views and strides, devices, modes and optimiser internals
L4 Debug shape, device, gradient and mode bugs; profile and speed up training
L5 Design training pipelines with mixed precision, compilation, distributed training and reproducibility
L6 Build training infrastructure and custom kernels for large-scale training

Why PyTorch

PyTorch (Meta, 2016; governed by the PyTorch Foundation under the Linux Foundation since 2022) won research and most production deep learning through:

  • Eager execution: operations run immediately, like NumPy; ordinary Python control flow, print debugging and pdb work.
  • Dynamic graphs: autograd records the operations actually executed each step, so models can branch and loop on data.
  • A huge ecosystem: Hugging Face Transformers, torchvision/torchaudio, Lightning, vLLM and SGLang (chapter 166), DeepSpeed, PyTorch Geometric.
  • Compilation without giving up eagerness: torch.compile (2.0+) captures graphs and generates fused kernels.

As of autumn 2026 the current release line is PyTorch 2.14 (September 2026). Exact APIs evolve; the concepts here are stable.

Tensors

A torch.Tensor is an n-dimensional array with a dtype, a device (cpu, cuda, mps, xpu…), a shape, strides and, optionally, gradient tracking. Like NumPy arrays (chapter 144), many operations return views sharing storage.

Python
import torch

x = torch.arange(12, dtype=torch.float32).reshape(3, 4)
x.shape, x.dtype, x.device, x.stride()       # (torch.Size([3, 4]), torch.float32, device(type='cpu'), (4, 1))
x.T.stride(), x.T.is_contiguous()            # ((1, 4), False): a view with swapped strides
y = x[:, 1]                                  # view; y.storage is x's storage
x.view(4, 3)                                 # requires compatible strides; reshape() copies if needed
x.unsqueeze(0).shape                         # torch.Size([1, 3, 4]): add a batch dimension

a = torch.randn(32, 128, 64)                 # batch of 32 matrices
b = torch.randn(64, 10)
(a @ b).shape                                # broadcasting matmul → [32, 128, 10]
torch.einsum("bij,jk->bik", a, b).shape      # same, explicit

torch.from_numpy(x.numpy()).data_ptr() == x.data_ptr()   # True: zero-copy interop on CPU
dtype Bits Use
float32 32 Default; master weights
bfloat16 16 (8-bit exponent) Training and inference on modern GPUs/TPUs; same range as fp32, less precision
float16 16 (5-bit exponent) Inference; training needs loss scaling
float8 (e4m3, e5m2) 8 Hopper/Blackwell-class training and inference with scaling
int8, int4 (packed) 8, 4 Quantised inference (chapter 165)
int64 64 Indices, token ids

Device transfers are explicit: x.to("cuda"), x.cuda(), x.cpu(). Operations require operands on the same device.

Autograd

Set requires_grad=True on leaf tensors (parameters do this automatically). Each operation on them records a node in a graph; loss.backward() traverses it in reverse and accumulates gradients into .grad of leaves: exactly the Value engine of chapter 146, on tensors.

Python
w = torch.randn(3, requires_grad=True)
x = torch.tensor([1.0, 2.0, 3.0])
loss = ((w * x).sum() - 1.0) ** 2
loss.grad_fn                                  # <PowBackward0 ...>: the recorded graph
loss.backward()
w.grad                                        # 2·(w·x − 1)·x
w.grad.zero_()                                # gradients accumulate: reset (optimizer.zero_grad does this)

with torch.no_grad():                         # inference / manual updates: don't record
    w -= 0.1 * w.grad
with torch.inference_mode():                  # stricter, faster for pure inference
    y = w * 2

# Higher-order and functional gradients
z = torch.tensor(2.0, requires_grad=True)
(g,) = torch.autograd.grad(z ** 3, z, create_graph=True)   # 12
(h,) = torch.autograd.grad(g, z)                            # 12 (second derivative 6z)

Key behaviours:

  • The graph is freed after backward() unless retain_graph=True.
  • .detach() returns a tensor cut from the graph (shares data).
  • In-place operations on tensors needed for backward raise errors: autograd tracks version counters.
  • torch.func provides JAX-style transforms: grad, vmap (vectorise over a batch dimension), jacrev, jacfwd, functional_call.

Modules, parameters and buffers

nn.Module is the building block: it registers parameters (learnable nn.Parameter tensors), buffers (state that isn't learned, e.g. BatchNorm running statistics), and submodules, and defines forward.

Python
import torch.nn as nn
import torch.nn.functional as F

class MLP(nn.Module):
    def __init__(self, d_in: int, d_hidden: int, d_out: int, p_drop: float = 0.1):
        super().__init__()
        self.net = nn.Sequential(
            nn.Linear(d_in, d_hidden), nn.GELU(), nn.Dropout(p_drop),
            nn.Linear(d_hidden, d_hidden), nn.GELU(), nn.Dropout(p_drop),
            nn.Linear(d_hidden, d_out),
        )

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        return self.net(x)                        # returns logits

model = MLP(20, 128, 3)
sum(p.numel() for p in model.parameters())        # 19,587 parameters
[n for n, _ in model.named_parameters()][:2]      # ['net.0.weight', 'net.0.bias']
model.train(); model.eval()                       # toggles dropout / batchnorm behaviour
  • model.state_dict(): an ordered dict of parameter and buffer tensors: what you save.
  • model.to(device, dtype), model.requires_grad_(False) (freeze), model.apply(init_fn).
  • Common layers: nn.Linear, nn.Embedding, nn.Conv2d, nn.LayerNorm, nn.RMSNorm, nn.MultiheadAttention, F.scaled_dot_product_attention (fused, FlashAttention-style kernels), nn.LSTM, nn.TransformerEncoderLayer.
  • Losses take logits: F.cross_entropy(logits, targets) applies log-softmax internally (chapter 147's stability trick); F.binary_cross_entropy_with_logits.

Optimisers and schedulers

Python
decay, no_decay = [], []
for name, p in model.named_parameters():
    (no_decay if p.ndim < 2 else decay).append(p)        # no decay on biases and norm weights
optimizer = torch.optim.AdamW([{"params": decay, "weight_decay": 0.05},
                               {"params": no_decay, "weight_decay": 0.0}],
                              lr=3e-4, betas=(0.9, 0.95))

total_steps, warmup = 10_000, 500
scheduler = torch.optim.lr_scheduler.SequentialLR(
    optimizer,
    schedulers=[torch.optim.lr_scheduler.LinearLR(optimizer, start_factor=0.01, total_iters=warmup),
                torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=total_steps - warmup, eta_min=3e-5)],
    milestones=[warmup],
)

The optimiser holds references to parameters plus its own state (Adam's m, v), saved via optimizer.state_dict().

Datasets and DataLoaders

  • A map-style Dataset implements __len__ and __getitem__(i); an IterableDataset yields examples (streams, huge sharded corpora).
  • DataLoader batches, shuffles, and loads in parallel worker processes (num_workers), with pin_memory=True for faster host-to-GPU copies and a collate_fn to build batches (e.g. padding variable-length sequences).
Python
from torch.utils.data import Dataset, DataLoader

class TabularDataset(Dataset):
    def __init__(self, X, y):
        self.X = torch.as_tensor(X, dtype=torch.float32)
        self.y = torch.as_tensor(y, dtype=torch.long)
    def __len__(self): return len(self.y)
    def __getitem__(self, i): return self.X[i], self.y[i]

def pad_collate(batch, pad_id=0):
    """For variable-length token sequences: pad to the longest in the batch and build a mask."""
    seqs, labels = zip(*batch)
    L = max(len(s) for s in seqs)
    ids = torch.full((len(seqs), L), pad_id, dtype=torch.long)
    for i, s in enumerate(seqs): ids[i, :len(s)] = torch.as_tensor(s)
    return ids, ids.ne(pad_id), torch.as_tensor(labels)

g = torch.Generator().manual_seed(0)
X = torch.randn(5000, 20); true_w = torch.randn(20, 3)
y = (X @ true_w + 0.5 * torch.randn(5000, 3)).argmax(1)
train_ds, val_ds = torch.utils.data.random_split(TabularDataset(X, y), [4000, 1000], generator=g)
train_dl = DataLoader(train_ds, batch_size=128, shuffle=True, num_workers=0, drop_last=True)
val_dl = DataLoader(val_ds, batch_size=512)

Data loading is a frequent bottleneck: profile it (GPU utilisation dips between steps), increase workers, pre-tokenise and store in efficient formats (memory-mapped arrays, WebDataset/MosaicML Streaming shards, Arrow).

The training loop

Python
def train(model, train_dl, val_dl, epochs=10, lr=3e-3, device="cpu"):
    model.to(device)
    opt = torch.optim.AdamW(model.parameters(), lr=lr, weight_decay=0.01)
    sched = torch.optim.lr_scheduler.OneCycleLR(opt, max_lr=lr, total_steps=epochs * len(train_dl))
    for epoch in range(epochs):
        model.train()
        for xb, yb in train_dl:
            xb, yb = xb.to(device, non_blocking=True), yb.to(device, non_blocking=True)
            logits = model(xb)                                   # 1. forward
            loss = F.cross_entropy(logits, yb)                   # 2. loss
            opt.zero_grad(set_to_none=True)                      # 3. clear old gradients
            loss.backward()                                      # 4. backward
            torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)   # 5. clip
            opt.step(); sched.step()                             # 6. update
        val_loss, val_acc = evaluate(model, val_dl, device)
        print(f"epoch {epoch}  train_loss {loss.item():.3f}  val_loss {val_loss:.3f}  val_acc {val_acc:.3f}")
    return model

@torch.no_grad()
def evaluate(model, dl, device):
    model.eval()
    total, correct, loss_sum = 0, 0, 0.0
    for xb, yb in dl:
        xb, yb = xb.to(device), yb.to(device)
        logits = model(xb)
        loss_sum += F.cross_entropy(logits, yb, reduction="sum").item()
        correct += (logits.argmax(1) == yb).sum().item(); total += len(yb)
    return loss_sum / total, correct / total

torch.manual_seed(0)
model = train(MLP(20, 128, 3), train_dl, val_dl, epochs=10)   # val_acc reaches ≈ 0.94
batch .to(device) model(x) cross_entropy zero_grad backward() clip norm opt.step() sched.step() evaluation: model.eval() · torch.no_grad() / inference_mode() · no optimiser
The PyTorch training step. Each iteration moves a batch to the device, runs the forward pass to get logits, computes the loss, clears old gradients, backpropagates to fill each parameter's grad, optionally clips, and lets the optimiser and scheduler update parameters and the learning rate. Evaluation runs under no_grad with the model in eval mode.

Higher-level wrappers remove the boilerplate: PyTorch Lightning, Hugging Face Accelerate and Trainer, torchtune (LLM fine-tuning recipes), TorchTitan (large-scale pre-training reference). Learning the raw loop first makes them transparent.

Checkpoints

Save everything needed to resume exactly: model, optimiser, scheduler, step, RNG states, config.

Python
def save_checkpoint(path, model, opt, sched, step):
    torch.save({"model": model.state_dict(), "optimizer": opt.state_dict(),
                "scheduler": sched.state_dict(), "step": step,
                "rng": torch.get_rng_state()}, path)

def load_checkpoint(path, model, opt=None, sched=None, map_location="cpu"):
    ckpt = torch.load(path, map_location=map_location, weights_only=True)   # safe: no arbitrary unpickling
    model.load_state_dict(ckpt["model"])
    if opt: opt.load_state_dict(ckpt["optimizer"])
    if sched: sched.load_state_dict(ckpt["scheduler"])
    torch.set_rng_state(ckpt["rng"])
    return ckpt["step"]

For large distributed models use torch.distributed.checkpoint (DCP), which saves sharded state in parallel and can reshard on load. Save periodically and asynchronously; keep the best and the latest few.

GPUs

The execution model

  • A GPU has thousands of cores and high-bandwidth memory (HBM); it excels at large, parallel, regular work (matmuls) and is starved by small operations and data transfers.
  • CUDA operations are asynchronous: Python enqueues kernels on a stream and returns immediately. Calls that need a result on the host (.item(), .cpu(), print(tensor), .tolist()) synchronise and stall the pipeline: avoid them in the hot loop.
  • Time GPU code with torch.cuda.synchronize() or CUDA events, not plain wall-clock timers around asynchronous calls.
  • Prefer large batched operations; fuse small ones (torch.compile); keep data on the device.
Python
device = ("cuda" if torch.cuda.is_available()
          else "mps" if torch.backends.mps.is_available() else "cpu")
torch.backends.cuda.matmul.allow_tf32 = True           # TF32 tensor cores for fp32 matmuls on Ampere+
torch.set_float32_matmul_precision("high")             # equivalent, newer API

Memory accounting

Training memory ≈ weights + gradients + optimiser state + activations (+ temporary buffers).

For a 7-billion-parameter model with AdamW in mixed precision: weights (bf16) 14 GB + gradients 14 GB + fp32 master weights 28 GB + Adam m, v (fp32) 56 GB ≈ 112 GB before activations: far beyond one GPU's memory, hence sharding (FSDP/ZeRO), parameter-efficient fine-tuning (LoRA, chapter 163), and quantisation (QLoRA). Inference needs only weights + the KV cache (chapter 166).

Activation checkpointing (gradient checkpointing) stores only some activations in the forward pass and recomputes the rest during backward: trades about 30% more compute for large memory savings.

Python
from torch.utils.checkpoint import checkpoint
class Block(nn.Module):
    def __init__(self, d): super().__init__(); self.ff = nn.Sequential(nn.Linear(d, 4 * d), nn.GELU(), nn.Linear(4 * d, d))
    def forward(self, x): return x + checkpoint(self.ff, x, use_reentrant=False)

torch.cuda.max_memory_allocated() if torch.cuda.is_available() else None   # peak memory tracking

Mixed precision

Run most operations in 16-bit for speed and memory while keeping numerically sensitive ones (reductions, softmax, losses) and master weights in fp32.

  • bfloat16 (preferred on Ampere and newer, TPUs): same exponent range as fp32, so no loss scaling needed.
  • float16: smaller range; small gradients underflow to zero, so use a GradScaler that multiplies the loss by a large factor before backward and unscales before the step, skipping steps with inf/NaN.
  • FP8 training (Hopper/Blackwell) uses per-tensor or block scaling via libraries such as Transformer Engine or torchao.
Python
use_cuda = torch.cuda.is_available()
opt = torch.optim.AdamW(model.parameters(), lr=3e-4)
scaler = torch.amp.GradScaler("cuda", enabled=use_cuda)       # only needed for float16
for xb, yb in train_dl:
    with torch.autocast(device_type="cuda" if use_cuda else "cpu", dtype=torch.bfloat16):
        loss = F.cross_entropy(model(xb), yb)                 # matmuls in bf16, loss in fp32
    opt.zero_grad(set_to_none=True)
    scaler.scale(loss).backward()                             # no-op scaling when disabled
    scaler.unscale_(opt)
    torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
    scaler.step(opt); scaler.update()
    break

torch.compile

torch.compile(model) uses TorchDynamo to capture Python bytecode into FX graphs (falling back to eager at unsupported code: "graph breaks"), AOTAutograd to trace the backward graph ahead of time, and TorchInductor to generate fused Triton (GPU) or C++/OpenMP (CPU) kernels.

  • Typical speed-ups 1.3–2× for training, more for some inference workloads; the first call pays compilation time.
  • Modes: "default", "reduce-overhead" (CUDA graphs to cut launch overhead for small batches), "max-autotune" (searches kernel configurations).
  • Avoid graph breaks (data-dependent Python control flow, .item(), unsupported libraries) in the hot path; inspect with TORCH_LOGS=graph_breaks.
  • Dynamic shapes are supported; mark dynamic dimensions to avoid recompiles.
Python
compiled = torch.compile(model, mode="default")
out = compiled(torch.randn(64, 20))        # first call compiles; later calls run fused kernels

Distributed training

Strategy What is split When
DDP (DistributedDataParallel) Data: each GPU has a full model replica and a different batch; gradients all-reduced each step Model fits on one GPU
FSDP / FSDP2 (fully_shard), ZeRO (DeepSpeed) Parameters, gradients and optimiser state sharded across data-parallel ranks; gathered just-in-time per layer Model + optimiser too big for one GPU
Tensor parallelism Individual matmuls split across GPUs (column/row parallel), within a node over fast links Very large layers; inference of big models
Pipeline parallelism Layers split into stages on different GPUs; micro-batches flow through Very deep models across nodes
Sequence / context parallelism Long sequences split across GPUs (ring attention) Long-context training
Expert parallelism Mixture-of-experts experts placed on different GPUs MoE models (chapter 156)

Large-scale training combines these ("3D/4D/5D parallelism") on a DeviceMesh. Communication uses NCCL collectives: all-reduce, all-gather, reduce-scatter (chapter 166 covers the same ideas for inference).

DDPFSDP / ZeRO-3 W fullW fullW fullW full optoptoptopt batch 0batch 1batch 2batch 3 all-reduce gradients W ¼W ¼W ¼W ¼ opt ¼opt ¼opt ¼opt ¼ batch 0batch 1batch 2batch 3 all-gather layer → compute → free reduce-scatter gradients memory per GPU: DDP = full model state · FSDP ≈ 1/N of it (+ one gathered layer)
Data parallelism versus fully sharded data parallelism. With DDP every GPU holds the full model and optimiser state and processes its own batch; gradients are averaged with all-reduce. With FSDP each GPU holds only a shard of parameters, gradients and optimiser state; full layers are all-gathered just before use and gradients are reduce-scattered back to their owners, cutting memory per GPU roughly by the number of GPUs.
Python
# train_ddp.py — launched with: torchrun --nproc_per_node=8 train_ddp.py
import os, torch, torch.distributed as dist
from torch.nn.parallel import DistributedDataParallel as DDP
from torch.utils.data.distributed import DistributedSampler

def main():
    dist.init_process_group("nccl")
    local_rank = int(os.environ["LOCAL_RANK"]); torch.cuda.set_device(local_rank)
    model = DDP(MLP(20, 128, 3).cuda(), device_ids=[local_rank])
    sampler = DistributedSampler(train_ds, shuffle=True)        # each rank sees a different shard
    dl = DataLoader(train_ds, batch_size=128, sampler=sampler, num_workers=4, pin_memory=True)
    opt = torch.optim.AdamW(model.parameters(), lr=3e-3)
    for epoch in range(10):
        sampler.set_epoch(epoch)                                 # reshuffle differently each epoch
        for xb, yb in dl:
            loss = F.cross_entropy(model(xb.cuda()), yb.cuda())
            opt.zero_grad(); loss.backward(); opt.step()         # backward overlaps all-reduce
    if dist.get_rank() == 0: torch.save(model.module.state_dict(), "model.pt")
    dist.destroy_process_group()

# FSDP2: shard each block, then the root
# from torch.distributed.fsdp import fully_shard
# for block in model.layers: fully_shard(block)
# fully_shard(model)

Profiling

Python
from torch.profiler import profile, record_function, ProfilerActivity
activities = [ProfilerActivity.CPU] + ([ProfilerActivity.CUDA] if torch.cuda.is_available() else [])
with profile(activities=activities, record_shapes=True, profile_memory=True) as prof:
    with record_function("train_step"):
        loss = F.cross_entropy(model(X[:512]), y[:512]); loss.backward()
print(prof.key_averages().table(sort_by="self_cpu_time_total", row_limit=8))
prof.export_chrome_trace("trace.json")          # open in Perfetto / chrome://tracing

What to look for: GPU idle gaps (data loading or host syncs), many tiny kernels (fuse/compile), memory peaks (activation checkpointing, smaller micro-batches), communication not overlapped with compute (distributed). Also useful: torch.cuda.memory._record_memory_history() for memory snapshots, NVIDIA Nsight Systems for whole-system timelines, and MFU (model FLOPs utilisation: achieved FLOPs / hardware peak) as the headline efficiency metric for large training runs (40–60% is good).

Exporting and deployment paths

  • torch.export produces a clean, ahead-of-time graph (ExportedProgram) for deployment and compilers.
  • AOTInductor compiles an exported model to a shared library callable from C++.
  • ONNX export (torch.onnx.export(..., dynamo=True)) for ONNX Runtime, TensorRT and cross-language serving (Java, Go, C#, Rust).
  • ExecuTorch for mobile and edge devices.
  • LLM serving typically loads Hugging Face/safetensors weights into vLLM, SGLang or TensorRT-LLM (chapter 166, 179).

Other frameworks and languages

# JAX (Google): functional — pure functions + transformations (grad, jit, vmap, pmap/shard_map)
import jax, jax.numpy as jnp
def loss_fn(params, x, y):
    logits = x @ params["W"] + params["b"]
    return -jnp.mean(jax.nn.log_softmax(logits)[jnp.arange(len(y)), y])
grad_fn = jax.jit(jax.grad(loss_fn))              # compiled with XLA
params = jax.tree.map(lambda p, g: p - 0.1 * g, params, grad_fn(params, x, y))
# Flax NNX / Equinox for modules, Optax for optimisers; strong on TPUs, used for many frontier models

Lab: training loops, optimisers and modes in PyTorch

PyTorch 2.14.1 (CPU, 2 threads) on the lab machine. Digits scaled to [0, 1], split 1,000 train / 400 validation / 397 test with a seeded permutation; model Linear(64, 256) → ReLU → [Dropout] → Linear(256, 10) (19,210 parameters); mini-batches of 32.

Experiment 1: views and strides

Text
a = arange(12).reshape(3, 4):  strides (4, 1)
a.T:                           strides (1, 4), is_contiguous False, same data_ptr True

view requires compatible strides and fails on a transposed tensor; reshape falls back to copying when it must. In-place operations on views (v.add_(1)) modify the original, and autograd raises an error if an in-place change destroys a value it needed for the backward pass.

Experiment 2: optimisers

Optimiser Val loss, epoch 5 Val loss, epoch 30 Val accuracy
SGD, lr 0.01 2.087 0.810 92.0%
SGD, lr 0.1 0.507 0.172 93.0%
AdamW, lr 1e-3 0.396 0.105 97.8%

The lr 0.1 and AdamW runs each took about a second of wall time; the first run in the script (SGD 0.01) included PyTorch's one-time start-up costs, so its time isn't comparable. Adding momentum 0.9 to SGD usually closes much of the gap; try it.

Experiment 3: overfitting and early stopping

Run (AdamW 3e-3, 150 epochs) Final train loss Best val loss (epoch) Final val loss Test accuracy
no dropout 0.0002 0.070 (87) 0.079 97.5%
dropout 0.5 0.0005 — 0.078 97.5%

A checkpoint-on-best-validation loop (save model.state_dict() when validation loss improves; reload at the end) implements early stopping. With 400 validation images, validation loss itself is noisy; using a patience of 10–20 epochs avoids stopping on a random dip.

Experiment 4: modes

Text
model with Dropout(0.5) left in train mode:
  two passes over 5 test images → same argmax this time; logits identical? False

The predictions happened to agree on these five images, which is exactly why the bug survives: evaluation looks "mostly fine" while being noisy and slightly wrong. Batch-norm layers in train mode are worse: they normalise with the current batch's statistics, so a batch of one at inference produces garbage.

Try it yourself

  1. Add momentum=0.9 (and nesterov=True) to SGD at lr 0.05 and compare with AdamW over 30 epochs.
  2. Implement checkpointing with patience 15 and report the test accuracy of the restored model.
  3. Wrap the data in a Dataset and DataLoader(num_workers=2) and measure whether loading becomes faster or slower for this tiny dataset.
  4. Try torch.compile(model) and measure the time per epoch after the first (compile) epoch.

Revision sheet: PyTorch

Key ideas

  • Tensors: dtype, device, shape, strides; views vs copies; .contiguous(), reshape vs view.
  • Autograd: dynamic graph recorded on the forward pass; requires_grad, backward(), .grad accumulation, no_grad, detach.
  • Modules: nn.Module, parameters and buffers, state_dict, train()/eval() modes.
  • Training loop: forward → loss → zero_grad → backward → step; validation each epoch; checkpointing; early stopping; LR schedulers.
  • Data: Dataset, DataLoader (batching, shuffling, workers, pinned memory).
  • Speed: GPU placement, mixed precision (torch.autocast, bf16), torch.compile, profiling (torch.profiler).
  • Scale: DDP and FSDP for distributed training; gradient accumulation; activation checkpointing.

Numbers to remember

  • Lab: AdamW 1e-3 reached 97.8% validation accuracy in 30 epochs where SGD 0.01 reached 92.0%.
  • Lab: validation loss bottomed at epoch 87 while training loss kept falling to 0.0002.

Pitfalls

  • Forgetting zero_grad() (gradients accumulate).
  • Evaluating in train mode; forgetting no_grad (memory blow-up).
  • Tensors on different devices; dtype mismatches.
  • In-place ops breaking autograd; modifying views unintentionally.
  • Saving whole model objects instead of state_dicts.
  • Data loading as the hidden bottleneck.

Glossary

  • Stride: elements to skip per step along a dimension.
  • Buffer: non-trained state in a module (e.g. batch-norm running mean).
  • state_dict: mapping of parameter and buffer names to tensors.
  • Autocast: automatic mixed precision context.
  • DDP / FSDP: data-parallel / fully sharded data-parallel training.