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.
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:
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
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:
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:
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.
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.
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()unlessretain_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.funcprovides 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.
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
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
Datasetimplements__len__and__getitem__(i); anIterableDatasetyields examples (streams, huge sharded corpora). DataLoaderbatches, shuffles, and loads in parallel worker processes (num_workers), withpin_memory=Truefor faster host-to-GPU copies and acollate_fnto build batches (e.g. padding variable-length sequences).
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
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
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.
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.
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.
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.
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 withTORCH_LOGS=graph_breaks. - Dynamic shapes are supported; mark dynamic dimensions to avoid recompiles.
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).
# 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
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.exportproduces 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
# Keras 3: high-level API running on JAX, PyTorch or TensorFlow backends
import keras
model = keras.Sequential([keras.layers.Dense(128, activation="gelu"), keras.layers.Dense(3)])
model.compile(optimizer=keras.optimizers.AdamW(3e-3),
loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=["accuracy"])
model.fit(X_train, y_train, validation_split=0.2, epochs=10, batch_size=128)
// Rust: Burn (backend-generic: wgpu, CUDA, LibTorch, ndarray) and candle (Hugging Face, inference-focused)
use candle_core::{Device, Tensor, DType};
use candle_nn::{linear, Linear, Module, VarBuilder, VarMap, Optimizer, AdamW, ParamsAdamW};
let dev = Device::cuda_if_available(0)?;
let varmap = VarMap::new();
let vb = VarBuilder::from_varmap(&varmap, DType::F32, &dev);
let l1 = linear(20, 128, vb.pp("l1"))?; let l2 = linear(128, 3, vb.pp("l2"))?;
let mut opt = AdamW::new(varmap.all_vars(), ParamsAdamW { lr: 3e-3, ..Default::default() })?;
let logits = l2.forward(&l1.forward(&xs)?.gelu()?)?;
let loss = candle_nn::loss::cross_entropy(&logits, &ys)?;
opt.backward_step(&loss)?;
# Julia: Flux.jl (and Lux.jl, explicit-parameter style); Zygote/Enzyme for AD; CUDA.jl for GPUs
using Flux
model = Chain(Dense(20 => 128, gelu), Dense(128 => 3))
opt_state = Flux.setup(AdamW(3f-3), model)
for (x, y) in loader
grads = Flux.gradient(m -> Flux.logitcrossentropy(m(x), y), model)
Flux.update!(opt_state, model, grads[1])
end
// Java: Deep Java Library (DJL) — engine-agnostic (PyTorch, ONNX Runtime) training and inference on the JVM
Block block = new SequentialBlock()
.add(Linear.builder().setUnits(128).build()).add(Activation::gelu)
.add(Linear.builder().setUnits(3).build());
try (Model model = Model.newInstance("mlp")) {
model.setBlock(block);
DefaultTrainingConfig cfg = new DefaultTrainingConfig(Loss.softmaxCrossEntropyLoss())
.optOptimizer(Optimizer.adamW().build());
try (Trainer trainer = model.newTrainer(cfg)) {
trainer.initialize(new Shape(128, 20));
EasyTrain.fit(trainer, 10, trainSet, validateSet);
}
}
// C++: LibTorch — the same ATen/autograd engine behind PyTorch
#include <torch/torch.h>
struct Net : torch::nn::Module {
torch::nn::Linear l1{nullptr}, l2{nullptr};
Net() { l1 = register_module("l1", torch::nn::Linear(20, 128));
l2 = register_module("l2", torch::nn::Linear(128, 3)); }
torch::Tensor forward(torch::Tensor x) { return l2(torch::gelu(l1(x))); }
};
auto net = std::make_shared<Net>();
torch::optim::AdamW opt(net->parameters(), torch::optim::AdamWOptions(3e-3));
auto loss = torch::nn::functional::cross_entropy(net->forward(xb), yb);
opt.zero_grad(); loss.backward(); opt.step();
// Go: no mainstream training framework; Go services typically call models over HTTP/gRPC
// or run ONNX models in-process (onnxruntime_go) — training stays in Python.
sess, _ := ort.NewAdvancedSession("model.onnx", []string{"x"}, []string{"logits"},
[]ort.Value{input}, []ort.Value{output}, nil)
_ = sess.Run()
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
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
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
- Add
momentum=0.9(andnesterov=True) to SGD at lr 0.05 and compare with AdamW over 30 epochs. - Implement checkpointing with patience 15 and report the test accuracy of the restored model.
- Wrap the data in a
DatasetandDataLoader(num_workers=2)and measure whether loading becomes faster or slower for this tiny dataset. - 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(),reshapevsview. - Autograd: dynamic graph recorded on the forward pass;
requires_grad,backward(),.gradaccumulation,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.