◆ AI All-in-One

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
↗ Plan a path here

Read first

NumPy and Array ThinkingTensors and ShapesBackpropagation

This leads to

Training Neural Networks in PracticeBuild a GPT from ScratchThe Hugging Face Ecosystem
The full path from zero — 19 concepts before this one
  1. What Is AI?
  2. Vectors
  3. Derivatives and Slopes
  4. Probability Basics
  5. Python for AI
  6. How Machines Learn
  7. Matrices and Matrix Multiplication
  8. Partial Derivatives and Gradients
  9. The Chain Rule
  10. Supervised, Unsupervised and Reinforcement Learning
  11. Tensors and Shapes
  12. Gradient Descent
  13. NumPy and Array Thinking
  14. Supervised Learning
  15. Linear Regression
  16. The Perceptron
  17. Logistic Regression
  18. Neural Networks
  19. Backpropagation
  20. 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:

  1. Tensors: NumPy-style arrays that can live on a GPU.
  2. 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.
  3. Building blocks: layers, activation functions, loss functions and Optimizers: SGD, Momentum and Adam, ready to combine.
  4. 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:

  1. Take a mini-batch of examples.
  2. Run them through the model (the forward pass) to get predictions.
  3. Measure how wrong the predictions are with a loss.
  4. Compute how each weight affected the loss (the backward pass, Backpropagation).
  5. 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.

xb (64, 64) Linear 64→128 + ReLU hidden (64, 128) Linear 128→10 logits (64, 10) forward pass: model(xb) yb (64,) labels CrossEntropy loss_fn(logits, yb) loss one number loss.backward() every weight gets a .grad opt.step() w ← w − η·grad (AdamW) new weights opt.zero_grad() clears the .grad values before the next backward() repeat for every batch, for every epoch
Fig. 1 The PyTorch training loop with tensor shapes for the digit classifier in this chapter. A batch of 64 images, each 64 pixels, flows forward through two linear layers to 10 scores per image. The loss compares them with the 64 true labels and gives one number. backward() fills in the gradient of every weight, and opt.step() updates them.

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: L=(2w−4)2L = (2w - 4)^2, so dLdw=2(2w−4)⋅2=8\frac{dL}{dw} = 2(2w - 4) \cdot 2 = 8 at w=3w = 3. 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 xW⊤+b\mathbf{x}\mathbf{W}^\top + \mathbf{b} for a whole batch at once. Given a batch of shape (32, 64) it returns shape (32, 128). nn.ReLU() applies the ReLU activation, max⁡(0,x)\max(0, x). 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 −ln⁡0.786≈0.241-\ln 0.786 \approx 0.241.

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.

Dataset 1,437 examples (x, y) 0 1 2 3 4 5 6 7 8 9 10 11 … DataLoader shuffle=True, batch_size=64 1 7 10 0 6 11 4 5 2 8 9 3 1. shuffle the order (new each epoch) Batches 2. cut and stack batch 1 xb (64, 64), yb (64,) batch 2 xb (64, 64), yb (64,) batch 23 xb (29, 64), yb (29,) ⋮ for xb, yb in train_dl: one pass over all 23 batches = one epoch
Fig. 2 From dataset to batches. The Dataset holds every example. Each epoch, the DataLoader shuffles the order, cuts it into batches of 64 and stacks each batch into tensors, ready for the model. 1,437 training examples make 23 batches per epoch, the last one smaller.

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 for loops: 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: 64×128+12864 \times 128 + 128 in the first layer and 128×10+10128 \times 10 + 10 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 before backward() 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. CrossEntropyLoss wants integer class labels of shape (batch,) (dtype torch.long), not one-hot vectors or floats of shape (batch, 1).
  • Forgetting model.eval() and torch.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 loss instead of loss.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.load on a file from an untrusted source can run arbitrary code, because older checkpoint files use Python's pickle format. Recent PyTorch versions default to weights_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

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

  1. 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?
  2. Change the optimizer to torch.optim.SGD(model.parameters(), lr=0.1). How does the speed of learning compare with AdamW?
  3. 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 64⋅128+128+128⋅64+64+64⋅10+1064 \cdot 128 + 128 + 128 \cdot 64 + 64 + 64 \cdot 10 + 10.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. Your model is on the GPU, and training crashes with "Expected all tensors to be on the same device". What is the fix?

  2. You add nn.Softmax() as the last layer of your classifier and train with nn.CrossEntropyLoss(). What happens?

  3. Your model uses dropout. You measure test accuracy without calling model.eval(). What goes wrong?

  4. During a long training run, memory grows a little every step. You log losses.append(loss) each step. What is the likely cause?

  5. nn.Linear(64, 128) receives a batch of shape (32, 64). What is the output shape, and how many parameters does the layer have?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Docs

PyTorch Tutorials

PyTorch · Beginner · Free

Official tutorials, from tensors and autograd to Transformers and distributed training.

Tutorial

PyTorch: Learn the Basics

PyTorch · Beginner · Free

The official step-by-step introduction: tensors, datasets and DataLoaders, building models, autograd, optimisation and saving models.

Book

Dive into Deep Learning

Zhang, Lipton, Li & Smola · Intermediate · Free

An interactive book with maths, figures and runnable PyTorch code for every chapter. Many universities use it.

Video

Neural Networks: Zero to Hero

Andrej Karpathy · Intermediate · Free

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.

Course

Practical Deep Learning for Coders

Jeremy Howard (fast.ai) · Beginner · Free

Top-down and code-first: you train state-of-the-art models in lesson one, then learn how they work. It suits programmers.

Docs

PyTorch documentation

PyTorch · Intermediate · Free

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