Level 3 In-Depth AI · Programming and Tools
PyTorch
The most widely used deep-learning library. Tensors that run on GPUs, automatic gradients, nn.Module for building models, DataLoader for feeding them, and the five-line training loop at the heart of everything, with a complete digit classifier you can run offline.
- Level
- ●●●●● Intermediate
- Reading
- 11 min
- To learn it well
- 2 hours to read, a weekend to practise
- Builds on
- 19 concepts →
- Quiz
- 5 questions ↓
The full path from zero — 19 concepts before this one
- What Is AI?
- Vectors
- Derivatives and Slopes
- Probability Basics
- Python for AI
- How Machines Learn
- Matrices and Matrix Multiplication
- Partial Derivatives and Gradients
- The Chain Rule
- Supervised, Unsupervised and Reinforcement Learning
- Tensors and Shapes
- Gradient Descent
- NumPy and Array Thinking
- Supervised Learning
- Linear Regression
- The Perceptron
- Logistic Regression
- Neural Networks
- Backpropagation
- PyTorch
Read them roughly in this order. See it on the concept map →
Why it matters
PyTorch is the library most researchers and many companies use to build and train neural networks. Since the early 2020s it has been used for the large majority of new machine-learning papers that release code, and models from Meta's Llama family to most of the open models on Hugging Face are written in it. When you read a model's source code, it will usually be PyTorch.
It gives you four things:
- Tensors: NumPy-style arrays that can live on a GPU.
- Autograd: automatic gradients. You write the forward computation, and
loss.backward()computes the gradient of the loss with respect to every parameter, exactly as the engine in Build an Autograd Engine from Scratch does, but for whole tensors and very fast. - Building blocks: layers, activation functions, loss functions and Optimizers: SGD, Momentum and Adam, ready to combine.
- Data tools for feeding examples to a model in shuffled mini-batches.
Learn the pattern in this chapter and you can read most deep-learning code, from a two-layer classifier to the training script of a GPT.
The intuition
Training a neural network always follows the same loop, whatever the model:
- Take a mini-batch of examples.
- Run them through the model (the forward pass) to get predictions.
- Measure how wrong the predictions are with a loss.
- Compute how each weight affected the loss (the backward pass, Backpropagation).
- Nudge every weight a little to reduce the loss (Gradient Descent).
PyTorch gives each of these steps a standard piece: a DataLoader for step 1, an nn.Module for step 2, a loss function for step 3, loss.backward() for step 4 and an optimizer for step 5. A training script is mostly those pieces wired together.
How it works
Tensors
A tensor in PyTorch is an n-dimensional array, almost identical to a NumPy array: it has a shape, a dtype, and supports indexing, slicing, broadcasting and @ for matrix multiplication. It adds a device, the place where its data lives: cpu, cuda (an NVIDIA GPU) or mps (an Apple-silicon GPU).
import torch
x = torch.tensor([[1.0, 2.0], [3.0, 4.0]])
print(x.shape, x.dtype, x.device) # torch.Size([2, 2]) torch.float32 cpu
x @ x.T # tensor([[ 5., 11.], [11., 25.]])
x.mean(dim=0) # tensor([2., 3.]) PyTorch says dim where NumPy says axis
torch.randn(4, 10) # random normal numbers, shape (4, 10)
t = torch.from_numpy(np_array) # NumPy -> tensor (shares memory)
t.numpy() # tensor -> NumPy (CPU tensors only)
x = x.to("cuda") # move to the GPU, if you have one
Operations between tensors on different devices fail. Moving the model and each batch to the same device is the main thing you have to remember.
Autograd
Mark a tensor with requires_grad=True and PyTorch records every operation on it, building a computation graph. Calling .backward() on a scalar result fills in .grad for every tensor that needs it:
w = torch.tensor(3.0, requires_grad=True)
loss = (w * 2 - 4) ** 2 # (6 - 4)² = 4
loss.backward()
print(loss.item(), w.grad) # 4.0 tensor(8.)
By hand: , so at . In real models you never mark tensors yourself. Layer weights are created with requires_grad=True already. Two habits matter. Gradients accumulate, so you clear them every step. And during evaluation you wrap code in torch.no_grad(), which stops PyTorch from recording a graph and saves memory and time.
Models: nn.Module
Every model, layer and block in PyTorch is a subclass of nn.Module. You create the layers in __init__ and say how data flows through them in forward. Calling model(x) runs forward.
from torch import nn
class MLP(nn.Module):
def __init__(self):
super().__init__()
self.net = nn.Sequential(
nn.Linear(64, 128), nn.ReLU(),
nn.Linear(128, 10),
)
def forward(self, x):
return self.net(x)
nn.Linear(64, 128) is a fully connected layer: it stores a weight matrix of shape (128, 64) and a bias of shape (128,), and computes for a whole batch at once. Given a batch of shape (32, 64) it returns shape (32, 128). nn.ReLU() applies the ReLU activation, . nn.Sequential simply chains modules. Any nn.Module assigned as an attribute is registered automatically, so model.parameters() finds every weight in the whole model, and model.to(device) moves them all.
Other modules you will meet: nn.Conv2d for convolutions, nn.LSTM for recurrent networks, nn.Embedding for embeddings, nn.LayerNorm, nn.Dropout, and nn.MultiheadAttention for Attention.
Loss and optimizer
For classification the standard loss is cross-entropy, nn.CrossEntropyLoss() (see Loss Functions). It takes the model's raw scores, called logits, with shape (batch, classes), and integer labels with shape (batch,). It applies the softmax itself, so do not add a softmax layer to your model. For example, logits [2.0, 0.5, -1.0] with true class 0 give softmax probabilities [0.786, 0.175, 0.039] and a loss of .
An optimizer object holds references to the parameters and applies an update rule. torch.optim.SGD is plain gradient descent. torch.optim.AdamW (Optimizers: SGD, Momentum and Adam) is the usual default for neural networks, typically with a learning rate around 1e-3 for small models and smaller for large ones.
Data: Dataset and DataLoader
A Dataset is anything that can say how many examples it has and return example number i. TensorDataset(X, y) wraps tensors you already have. For images on disk or text files you write a small class with __len__ and __getitem__.
A DataLoader wraps a dataset and serves mini-batches: it shuffles the order each epoch (shuffle=True, for training only), groups examples into batches of batch_size, and can load data in parallel worker processes (num_workers=4) so the GPU is never kept waiting.
Training and evaluation modes
model.train() and model.eval() switch a model between training mode and evaluation mode. Some layers behave differently in each: Dropout and Regularizing Neural Networks randomly zeroes activations only in training, and batch normalisation uses batch statistics in training and stored averages in evaluation. Forgetting model.eval() before measuring accuracy is a classic bug.
Saving and loading
A model's learned numbers live in its state dict, a dictionary from parameter names to tensors. Save that, not the whole object:
torch.save(model.state_dict(), "model.pt")
model = MLP()
model.load_state_dict(torch.load("model.pt"))
During long runs, save a checkpoint every so often that also includes the optimizer's state dict and the epoch number, so you can resume after a crash.
Key idea Every PyTorch training loop is the same five lines inside two
forloops:loss = loss_fn(model(xb), yb),opt.zero_grad(),loss.backward(),opt.step(), repeated over batches and epochs. Everything else is choosing the data, the model and the loss.
In code
A complete program that trains a neural network to recognise handwritten digits. It uses the small digits dataset bundled with scikit-learn (1,797 images of 8 × 8 pixels), so it runs offline in under a minute on any laptop.
import torch
from torch import nn
from torch.utils.data import TensorDataset, DataLoader
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
torch.manual_seed(0)
device = "cuda" if torch.cuda.is_available() else "cpu"
# 1. Data: 1,797 handwritten digits, 8x8 pixels each, as tensors
X, y = load_digits(return_X_y=True)
X_tr, X_te, y_tr, y_te = train_test_split(X / 16.0, y, test_size=0.2, random_state=0)
train_ds = TensorDataset(torch.tensor(X_tr, dtype=torch.float32), torch.tensor(y_tr))
test_ds = TensorDataset(torch.tensor(X_te, dtype=torch.float32), torch.tensor(y_te))
train_dl = DataLoader(train_ds, batch_size=64, shuffle=True)
test_dl = DataLoader(test_ds, batch_size=256)
# 2. Model: a small multilayer perceptron
class MLP(nn.Module):
def __init__(self):
super().__init__()
self.net = nn.Sequential(
nn.Linear(64, 128), nn.ReLU(),
nn.Linear(128, 10), # 10 scores ("logits"), one per digit
)
def forward(self, x):
return self.net(x)
model = MLP().to(device)
loss_fn = nn.CrossEntropyLoss()
opt = torch.optim.AdamW(model.parameters(), lr=1e-3)
def accuracy(dl):
model.eval()
correct = 0
with torch.no_grad(): # no graph needed for evaluation
for xb, yb in dl:
xb, yb = xb.to(device), yb.to(device)
correct += (model(xb).argmax(dim=1) == yb).sum().item()
return correct / len(dl.dataset)
# 3. The training loop
for epoch in range(1, 21):
model.train()
for xb, yb in train_dl:
xb, yb = xb.to(device), yb.to(device)
loss = loss_fn(model(xb), yb) # forward pass + loss
opt.zero_grad() # clear old gradients
loss.backward() # backpropagate
opt.step() # update the weights
if epoch % 5 == 0:
print(f"epoch {epoch:2d} last batch loss {loss.item():.3f} test acc {accuracy(test_dl):.3f}")
# 4. Save and reload
torch.save(model.state_dict(), "digits_mlp.pt")
model2 = MLP().to(device)
model2.load_state_dict(torch.load("digits_mlp.pt"))
print(sum(p.numel() for p in model.parameters()), "parameters")
# epoch 5 last batch loss 0.578 test acc 0.892
# epoch 10 last batch loss 0.248 test acc 0.944
# epoch 15 last batch loss 0.298 test acc 0.953
# epoch 20 last batch loss 0.089 test acc 0.964
# 9610 parameters
That output is from a CPU. With a GPU your numbers may differ slightly. The network has 9,610 parameters: in the first layer and in the second. After 20 passes over the training set it classifies 96.4% of digits it has never seen. The "last batch loss" jumps around because it comes from a single batch of 29 examples. On Apple silicon you can set device = "mps" to use the built-in GPU, although for a model this small the CPU is just as fast.
Next step: MNIST
The classic first deep-learning exercise is MNIST: 70,000 handwritten digits of 28 × 28 pixels (60,000 for training and 10,000 for testing). The companion library torchvision downloads it for you. Only the data part and the first layer change:
from torchvision import datasets, transforms
tfm = transforms.ToTensor() # image -> tensor of shape (1, 28, 28), values 0..1
train_ds = datasets.MNIST("data", train=True, download=True, transform=tfm)
test_ds = datasets.MNIST("data", train=False, download=True, transform=tfm)
train_dl = DataLoader(train_ds, batch_size=64, shuffle=True)
test_dl = DataLoader(test_ds, batch_size=256)
# in MLP.__init__: nn.Flatten(), nn.Linear(28 * 28, 128), nn.ReLU(), nn.Linear(128, 10)
A two-layer MLP like this typically reaches around 97–98% test accuracy on MNIST after a few epochs. A small convolutional network reaches about 99%. Install torchvision with pip install torchvision (it needs network access to download the data the first time).
Common pitfalls
- Forgetting
opt.zero_grad(). Gradients accumulate across steps, so training goes haywire. Some code calls it beforebackward()and some at the start of the loop. Either is fine, as long as it happens once per step. - Device mismatch.
RuntimeError: Expected all tensors to be on the same device. Move the model once and every batch inside the loop. - Softmax before
CrossEntropyLoss. The loss already includes it. Applying it twice still trains, but worse. - Wrong label type or shape.
CrossEntropyLosswants integer class labels of shape(batch,)(dtypetorch.long), not one-hot vectors or floats of shape(batch, 1). - Forgetting
model.eval()andtorch.no_grad()for evaluation. The first gives wrong results with dropout or batch norm. The second wastes memory and can cause out-of-memory errors. - Using
lossinstead ofloss.item()for logging. Keeping the tensor keeps its whole computation graph alive, and memory grows every step. - Not overfitting first. Before a long run, check that the model can drive the loss near zero on one small batch. If it can't, there is a bug. See Training Neural Networks in Practice.
Watch out
torch.loadon a file from an untrusted source can run arbitrary code, because older checkpoint files use Python's pickle format. Recent PyTorch versions default toweights_only=True, which blocks this, but be careful with old code that overrides it. Prefer the safetensors format for sharing weights. The Hugging Face Ecosystem uses it by default.
Where it leads
- Training Neural Networks in Practice covers the practical craft: initialisation, learning-rate choice, regularisation and debugging.
- Convolutional Neural Networks, Recurrent Neural Networks and The Transformer build bigger architectures from the same
nn.Modulepieces, and Build a GPT from Scratch trains a small language model in PyTorch. - Mixed Precision Training (
torch.autocast) andtorch.compilemake training faster. Distributed Training spreads it over many GPUs. - The Hugging Face Ecosystem gives you thousands of pretrained PyTorch models to fine-tune instead of training from scratch.
- Higher-level wrappers such as PyTorch Lightning and fastai remove the boilerplate of the loop, once you understand it.
A bit of history
PyTorch grew out of Torch, a machine-learning library first released in 2002. Its best-known version, Torch7, was programmed in the Lua language and was used at NYU, Facebook and DeepMind in the early 2010s. In 2016 a team at Facebook AI Research, including Adam Paszke, Soumith Chintala, Sam Gross and Gregory Chanan, released PyTorch, which brought Torch's fast tensor code to Python. It borrowed its "define-by-run" autograd from Chainer: the graph is built as ordinary Python runs, so models can use normal if statements and loops and be debugged with normal tools. Researchers preferred this to the static graphs of TensorFlow 1, and by around 2019–2020 PyTorch had become the dominant framework in research papers. Version 1.0 arrived in 2018 and 2.0 in 2023, adding torch.compile. In 2022 PyTorch moved to the independent PyTorch Foundation under the Linux Foundation.
Try it
- Add a second hidden layer,
nn.Linear(128, 64), nn.ReLU(), before the output layer. Does test accuracy improve? How many parameters does the model have now?- Change the optimizer to
torch.optim.SGD(model.parameters(), lr=0.1). How does the speed of learning compare with AdamW?- Record the average training loss per epoch in a list and plot it with Matplotlib (see Visualising Data), along with test accuracy.
Hint for 1: the new parameter count is .
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
PyTorch Tutorials
Official tutorials, from tensors and autograd to Transformers and distributed training.
PyTorch: Learn the Basics
The official step-by-step introduction: tensors, datasets and DataLoaders, building models, autograd, optimisation and saving models.
Dive into Deep Learning
An interactive book with maths, figures and runnable PyTorch code for every chapter. Many universities use it.
Neural Networks: Zero to Hero
A video series that builds backprop, language models and finally GPT from an empty file. Many people consider it the best way to really understand LLMs.
Practical Deep Learning for Coders
Top-down and code-first: you train state-of-the-art models in lesson one, then learn how they work. It suits programmers.
PyTorch documentation
The full API reference for torch, torch.nn, torch.optim and torch.utils.data, with notes on autograd, CUDA and serialisation.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/programming/pytorch.md