Platform Engineering · Lesson 253

PyTorch: Tensors, Autograd, and the Training Loop

PyTorch is NumPy that can run on a GPU and compute its own derivatives. Every model, from a small classifier to an LLM, trains through the same loop: take a batch, run the model forward, compute a loss, call backward() to fill in gradients, and let an optimizer step. Writing that loop correctly is a short checklist, and getting one line wrong produces a model that trains badly without any error. This lesson trains one image classifier, and shows the two lines people forget: zero_grad(), and eval() with no_grad() for validation.

Difficulty: Advanced · Know this first: Lesson 250, Lesson 242

Run it as:

When it breaks, I check

One thing to remember

Where the time goes

This bar adds up minutes for one training run, including what its bugs waste. It is a worked example, not a measurement. The backward and validation hops hold the lines that are easy to forget.

Try it: what happens to the gradient without zero_grad()?

Each batch produces a gradient of about the same size. Choose whether it is cleared each step, and see the size of the update after N steps.

200xgradient used, versus one batch
divergingtraining

Accumulating: each update is the sum of every gradient so far

Check yourself

Three questions. No score is saved anywhere — this is just you against the material.

Basic to master

PyTorch grows in four levels: tensors and autograd, the training loop, training well, and training at scale.

Basic — Tensors and autograd

At the basic level you can compute and differentiate.

  • torch.tensor, .to(device), shapes and dtypes.
  • requires_grad=True, loss.backward(), x.grad.
  • .detach(), .item(), .cpu().numpy().

Where it breaks: keeping loss tensors in a list for logging, which keeps their graphs alive; log loss.item().

Try it: Basic

You append loss to a list each step for plotting, and memory grows. Why?

Now do it: Compute y = (x ** 2).sum() for x with requires_grad and print x.grad after backward().

Intermediate — The training loop

At the intermediate level you write a correct loop.

  • Dataset and DataLoader; nn.Module; a loss; an optimizer.
  • zero_grad, forward, loss, backward, step.
  • model.eval() and torch.no_grad() for validation; model.train() after.

Try it: Intermediate

Which order is correct inside the training loop?

Now do it: Train a two-layer network on a toy dataset and plot the loss.

Advanced — Training well

At the advanced level training is fast and stable.

  • Mixed precision with torch.autocast; gradient clipping; learning-rate schedules.
  • Deliberate gradient accumulation for large effective batches.
  • Seeds and deterministic settings for reproducibility; checkpoints with metadata.

Try it: Advanced

You want an effective batch of 1,024 but only 256 fits in memory. What do you do?

Now do it: Add gradient accumulation to a loop and confirm the loss curve matches a larger batch.

Master — Training at scale

At the master level training spans GPUs and machines.

  • DistributedDataParallel and FSDP; torchrun; sharded checkpoints.
  • torch.compile for speed; profiling with the PyTorch profiler.
  • Experiment tracking and resumable runs on preemptible capacity.

Trade-off: more GPUs shorten the run and add communication overhead and failure points; checkpoint often enough that a lost node costs minutes, not hours.

Try it: Master

A training run on spot instances keeps being preempted. What limits the loss of work?

Now do it: Kill a training script halfway and resume it from its checkpoint.

Go deeper

A complete, correct loop on a small synthetic task that runs on CPU in seconds. Install with pip install torch --index-url https://download.pytorch.org/whl/cpu.

import torch
from torch import nn
from torch.utils.data import DataLoader, TensorDataset

torch.manual_seed(0)
device = "cuda" if torch.cuda.is_available() else "cpu"
X = torch.randn(6000, 20)
y = (X[:, :5].sum(dim=1) > 0).long()                    # a learnable rule
train = DataLoader(TensorDataset(X[:5000], y[:5000]), batch_size=128, shuffle=True)
val = DataLoader(TensorDataset(X[5000:], y[5000:]), batch_size=512)

model = nn.Sequential(nn.Linear(20, 64), nn.ReLU(), nn.Dropout(0.2), nn.Linear(64, 2)).to(device)
opt = torch.optim.AdamW(model.parameters(), lr=1e-3)
loss_fn = nn.CrossEntropyLoss()                          # takes logits

for epoch in range(5):
    model.train()
    for xb, yb in train:
        xb, yb = xb.to(device), yb.to(device)
        opt.zero_grad()                                  # fresh gradients
        loss = loss_fn(model(xb), yb)
        loss.backward()
        nn.utils.clip_grad_norm_(model.parameters(), 1.0)
        opt.step()
    model.eval()                                         # dropout off
    correct = 0
    with torch.no_grad():                                # no graphs, less memory
        for xb, yb in val:
            correct += (model(xb.to(device)).argmax(1) == yb.to(device)).sum().item()
    print(f"epoch {epoch}: loss {loss.item():.3f}, val accuracy {correct / 1000:.3f}")

torch.save({"model": model.state_dict(), "epoch": epoch}, "best.pt")

One time it broke

This is a composite of a failure pattern that keeps repeating; the details are illustrative. A refactor removed one line and a week of GPU time.

Timeline

  • Day 1A training script is refactored to add gradient accumulation. The zero_grad() call moves inside an if block that only runs every eighth step, but the step itself runs every batch.
  • Day 1 to 6Runs on a GPU cluster show a loss that falls briefly, then wanders. Several are restarted with lower learning rates.
  • Day 7A gradient-norm plot shows steady growth between optimizer steps. The order is fixed; the next run converges in a day.

What changed after

Gradient norms are logged every step, a smoke test trains a tiny model to a known accuracy in CI, and training loop changes need a reviewer who has written one before.

Python, example by example

PyTorch from tensors to a full training loop: tensors like NumPy arrays that can live on a GPU, autograd that computes gradients for you, and the five lines that train every model. Each example is a whole program: save it under the name in its first line, run it with python3, and you should see exactly the output below it.

Before you start: These examples need torch: make a virtual environment and install them with python3 -m venv .venv && . .venv/bin/activate && pip install torch. Versions differ in small ways, so a number in the last decimal place may not match yours.

1. Tensors

Like NumPy arrays, with a dtype, a shape, and a device (CPU or GPU).

# example_01.py
import torch
t = torch.tensor([[1.0, 2.0], [3.0, 4.0]])
print(t.shape, t.dtype, t.device)
print(t * 2, t @ t, t.mean().item(), sep="\n")
print(torch.zeros(2, 3).shape, torch.arange(5), t.T.tolist())
$ python3 example_01.py
torch.Size([2, 2]) torch.float32 cpu
tensor([[2., 4.],
        [6., 8.]])
tensor([[ 7., 10.],
        [15., 22.]])
2.5
torch.Size([2, 3]) tensor([0, 1, 2, 3, 4]) [[1.0, 3.0], [2.0, 4.0]]

2. Autograd: gradients for free

Mark a tensor with requires_grad, compute, call backward(), and read the gradient.

# example_02.py
import torch
x = torch.tensor(3.0, requires_grad=True)
y = x ** 2 + 2 * x + 1          # dy/dx = 2x + 2 = 8 at x = 3
y.backward()
print(y.item(), x.grad.item())
w = torch.tensor([1.0, -2.0], requires_grad=True)
loss = ((w * torch.tensor([3.0, 4.0])).sum() - 1) ** 2
loss.backward()
print(loss.item(), w.grad.tolist())
$ python3 example_02.py
16.0 8.0
36.0 [-36.0, -48.0]

3. Gradient descent by hand

Step against the gradient, again and again, and the loss falls: what every optimiser does.

# example_03.py
import torch
torch.manual_seed(0)
X = torch.linspace(0, 1, 20).unsqueeze(1)
y = 3 * X + 0.5
w = torch.zeros(1, requires_grad=True)
b = torch.zeros(1, requires_grad=True)
for step in range(301):
    loss = ((X * w + b - y) ** 2).mean()
    loss.backward()
    with torch.no_grad():
        w -= 0.1 * w.grad; b -= 0.1 * b.grad
        w.grad.zero_(); b.grad.zero_()
    if step % 100 == 0:
        print(step, round(loss.item(), 5))
print("w", round(w.item(), 3), "b", round(b.item(), 3))
$ python3 example_03.py
0 4.82895
100 0.02253
200 0.00121
300 7e-05
w 2.974 b 0.514

4. nn.Module: a model as a class

Layers are modules; a model is a module made of modules. Parameters are found for you.

# example_04.py
import torch
from torch import nn
torch.manual_seed(0)
class MLP(nn.Module):
    def __init__(self):
        super().__init__()
        self.net = nn.Sequential(nn.Linear(4, 8), nn.ReLU(), nn.Linear(8, 2))
    def forward(self, x):
        return self.net(x)
m = MLP()
print(m)
print(sum(p.numel() for p in m.parameters()), "parameters")
print(m(torch.ones(3, 4)).shape)
$ python3 example_04.py
MLP(
  (net): Sequential(
    (0): Linear(in_features=4, out_features=8, bias=True)
    (1): ReLU()
    (2): Linear(in_features=8, out_features=2, bias=True)
  )
)
58 parameters
torch.Size([3, 2])

5. The training loop

Forward, loss, zero the gradients, backward, step: the same five lines train a tiny model or a large one.

# example_05.py
import torch
from torch import nn
torch.manual_seed(0)
X = torch.randn(200, 2)
y = (X[:, 0] + X[:, 1] > 0).long()
model = nn.Sequential(nn.Linear(2, 16), nn.ReLU(), nn.Linear(16, 2))
opt = torch.optim.Adam(model.parameters(), lr=0.05)
loss_fn = nn.CrossEntropyLoss()
for epoch in range(1, 51):
    logits = model(X)
    loss = loss_fn(logits, y)
    opt.zero_grad()
    loss.backward()
    opt.step()
    if epoch % 10 == 0:
        acc = (logits.argmax(1) == y).float().mean().item()
        print(f"epoch {epoch:2d} loss {loss.item():.4f} acc {acc:.3f}")
$ python3 example_05.py
epoch 10 loss 0.1831 acc 0.950
epoch 20 loss 0.0549 acc 1.000
epoch 30 loss 0.0311 acc 1.000
epoch 40 loss 0.0229 acc 1.000
epoch 50 loss 0.0188 acc 1.000

6. Datasets and DataLoaders

A DataLoader serves shuffled mini-batches, so each step sees a slice of the data.

# example_06.py
import torch
from torch.utils.data import TensorDataset, DataLoader
torch.manual_seed(0)
ds = TensorDataset(torch.arange(10.0).unsqueeze(1), torch.arange(10))
dl = DataLoader(ds, batch_size=4, shuffle=True)
for xb, yb in dl:
    print(xb.squeeze(1).tolist(), yb.tolist())
$ python3 example_06.py
[6.0, 7.0, 1.0, 4.0] [6, 7, 1, 4]
[2.0, 0.0, 9.0, 8.0] [2, 0, 9, 8]
[3.0, 5.0] [3, 5]

7. Evaluate without gradients

model.eval() and torch.no_grad() for validation: no gradient bookkeeping, and layers like dropout switch to inference mode.

# example_07.py
import torch
from torch import nn
torch.manual_seed(0)
m = nn.Sequential(nn.Linear(3, 3), nn.Dropout(0.5))
x = torch.ones(1, 3)
m.train(); a = m(x); b = m(x)
print("train mode, same input, different output:", not torch.equal(a, b))
m.eval()
with torch.no_grad():
    c, d = m(x), m(x)
print("eval mode, same output:", torch.equal(c, d), "| grad tracked:", c.requires_grad)
$ python3 example_07.py
train mode, same input, different output: True
eval mode, same output: True | grad tracked: False

8. Save, load, and pick a device

Save the state_dict (the weights), not the whole object; move model and data to the same device.

# example_08.py
import torch
from torch import nn
torch.manual_seed(0)
device = "cuda" if torch.cuda.is_available() else "cpu"
m = nn.Linear(2, 1).to(device)
torch.save(m.state_dict(), "weights.pt")
m2 = nn.Linear(2, 1)
m2.load_state_dict(torch.load("weights.pt", weights_only=True))
x = torch.tensor([[1.0, 2.0]])
print(torch.allclose(m.cpu()(x), m2(x)), sorted(m2.state_dict().keys()))
$ python3 example_08.py
True ['bias', 'weight']

Practice: write the program yourself

Write each one from scratch before you open the solution. The output under each solution is what it really prints.

  1. Use autograd to find the derivative of sin(x) * x at x = 1.0, and compare it with cos(1) + sin(1).

    Show a solution
    # task_1.py
    import math, torch
    x = torch.tensor(1.0, requires_grad=True)
    (torch.sin(x) * x).backward()
    print(round(x.grad.item(), 5), round(math.cos(1) + math.sin(1), 5))
    $ python3 task_1.py
    1.38177 1.38177
  2. Build an nn.Sequential with layers 10 -> 32 -> 32 -> 1 and print its parameter count.

    Show a solution
    # task_2.py
    from torch import nn
    m = nn.Sequential(nn.Linear(10, 32), nn.ReLU(), nn.Linear(32, 32), nn.ReLU(), nn.Linear(32, 1))
    print(sum(p.numel() for p in m.parameters()))
    $ python3 task_2.py
    1441
  3. Train nn.Linear(1, 1) with SGD (lr 0.1, 200 steps) on y = 2x - 1 for x in 0..1 (20 points) and print the learned weight and bias rounded to 2.

    Show a solution
    # task_3.py
    import torch
    from torch import nn
    torch.manual_seed(0)
    X = torch.linspace(0, 1, 20).unsqueeze(1); y = 2 * X - 1
    m = nn.Linear(1, 1); opt = torch.optim.SGD(m.parameters(), lr=0.1)
    for _ in range(200):
        loss = ((m(X) - y) ** 2).mean(); opt.zero_grad(); loss.backward(); opt.step()
    print(round(m.weight.item(), 2), round(m.bias.item(), 2))
    $ python3 task_3.py
    1.88 -0.94
  4. Make a DataLoader over 7 items with batch size 3 and no shuffling, and print the batch sizes.

    Show a solution
    # task_4.py
    import torch
    from torch.utils.data import DataLoader, TensorDataset
    dl = DataLoader(TensorDataset(torch.arange(7)), batch_size=3)
    print([len(b[0]) for b in dl])
    $ python3 task_4.py
    [3, 3, 1]

Try it yourself, from scratch

You need Python 3 on Linux, macOS, or WSL on Windows (run wsl --install in PowerShell once); check with python3 --version. The terminal is only for setting Python up and running it and its tools: the Python itself goes in .py files, in part 2 and in "Python, example by example" above.

Before you start: A virtual environment: python3 -m venv ~/py-lab && . ~/py-lab/bin/activate. Then pip install torch --index-url https://download.pytorch.org/whl/cpu for the commands.

1. Terminal: set up and run

Type each one, read what it prints, and compare it with the note above it.

  1. Make a folder for this lesson with its own virtual environment, and install what the lesson needs into it. Every command after this runs inside it; deactivate leaves it, and source .venv/bin/activate brings it back.

    mkdir -p ~/labs/pytorch-tensors-autograd-and-training-loops && cd ~/labs/pytorch-tensors-autograd-and-training-loops
    python3 -m venv .venv || echo "No venv module: on Debian or Ubuntu run  sudo apt install -y python3-venv  and try again"
    source .venv/bin/activate && python --version
    pip install torch --index-url https://download.pytorch.org/whl/cpu
  2. Autograd: the gradient of x squared at 3.

    python -c "import torch; x = torch.tensor(3.0, requires_grad=True); (x ** 2).backward(); print(x.grad)"
  3. backward() adds to .grad: call it twice without zeroing and the gradient doubles.

    python -c "import torch; x = torch.tensor(3.0, requires_grad=True); [(x ** 2).backward() for _ in range(2)]; print(x.grad)"
  4. Which device you have, and which PyTorch build.

    python -c "import torch; print('cuda' if torch.cuda.is_available() else 'cpu', torch.__version__)"
  5. On a machine with an NVIDIA GPU: the driver's view of the GPU and its memory.

    nvidia-smi --query-gpu=name,memory.used,memory.total --format=csv || echo "no NVIDIA GPU here"

2. Python: grad_accum.py

This program trains a one-parameter model by gradient descent twice, once clearing the gradient each step and once forgetting to, so you can watch the second run diverge. Save it as grad_accum.py in the lesson folder, then run it.

# grad_accum.py
data = [(x, 3.0 * x) for x in [1.0, 2.0, 3.0, 4.0]]     # learn w = 3

def train(zero_grad, steps=12, lr=0.02):
    w, grad, history = 0.0, 0.0, []
    for step in range(steps):
        if zero_grad:
            grad = 0.0
        for x, y in data:                                  # loss = mean (w x - y)^2
            grad += 2 * (w * x - y) * x / len(data)        # backward() adds
        w -= lr * grad
        loss = sum((w * x - y) ** 2 for x, y in data) / len(data)
        history.append(loss)
    return w, history

for zero in (True, False):
    w, h = train(zero)
    shown = ", ".join(f"{l:.3g}" for l in h[::3])
    print(f"zero_grad={'yes' if zero else 'no '}  final w={w:10.3f}  loss every 3 steps: {shown}")

Run it, and you should see this output:

$ python3 grad_accum.py
zero_grad=yes  final w=     2.958  loss every 3 steps: 33.1, 3.89, 0.458, 0.0539
zero_grad=no   final w=     0.521  loss every 3 steps: 33.1, 46.6, 20, 58.7

3. What to notice

4. Advanced: a test that keeps the program honest

A program you keep needs a test, so you know at once when a change alters what it does. This one uses unittest, which comes with Python: it runs grad_accum.py and checks that it exits cleanly and prints exactly the output above. Save it as test_grad_accum.py next to the program.

# test_grad_accum.py: checks that grad_accum.py still prints exactly what this lesson shows.
# Run it with:  python3 -m unittest -v test_grad_accum
import subprocess
import sys
import unittest
from pathlib import Path

HERE = Path(__file__).resolve().parent
EXPECTED = r"""
zero_grad=yes  final w=     2.958  loss every 3 steps: 33.1, 3.89, 0.458, 0.0539
zero_grad=no   final w=     0.521  loss every 3 steps: 33.1, 46.6, 20, 58.7
""".strip("\n")


class TestGradAccum(unittest.TestCase):
    def run_program(self):
        return subprocess.run([sys.executable, str(HERE / "grad_accum.py")], cwd=HERE,
                              capture_output=True, text=True, timeout=60)

    def test_exits_cleanly(self):
        result = self.run_program()
        self.assertEqual(result.returncode, 0, result.stderr)

    def test_prints_the_expected_output(self):
        result = self.run_program()
        self.assertEqual(result.stdout.rstrip(), EXPECTED)


if __name__ == "__main__":
    unittest.main()

Run it: you should see both tests end in ok, then OK. Then change one value in the program, run it again, and read how the failure shows you the difference. pytest runs the same file unchanged, if you prefer it.

python3 -m unittest -v test_grad_accum

5. Learn the basics behind it

New to a feature used above? These W3Schools pages explain each one from zero, with examples you can run in the browser.

If you remember nothing else

Design exercise

Fine-tune an image classifier for defect detection on 30,000 labelled product photos, on one GPU with 24 GB.

Clarifying questions to ask

What batch size fits, and how do you get a larger effective batch? How do you know training is healthy in the first ten minutes? How is validation done? What gets saved, and how often?

Rough sizing

Say 224 by 224 images, a pretrained ResNet-50, 5% defects, 15 epochs, and a run that may be preempted.

Shape of the answer

A pretrained backbone with a new head; mixed precision; batch 64 with accumulation of 4; AdamW with a cosine schedule and gradient clipping; a weighted loss or sampler for the 5% class; loss and gradient norms logged every 50 steps; eval() and no_grad() validation each epoch reporting recall on defects; checkpoints of model, optimizer, scheduler, and epoch every epoch, best kept by validation recall.

Trade-offs to name

Larger effective batches stabilise training and change how the learning rate should be set. Validating every epoch costs time and catches problems early; more frequent checkpoints cost disk and save work on preemption.

Saved on this device, in this browser.
Next in this series · Lesson 254
Hugging Face Transformers and Tokenizers

The Hugging Face Hub holds hundreds of thousands of open models, and the transformers library loads almost any of them with two lines: a tokenizer that turns text into token IDs, and a model that turns IDs into predictions.

Go to Lesson 254 →

Or browse the full course from the Lessons index.