Neural networks and PyTorch

Tensors, autograd, nn.Module and the training loop, built up from a hand-written autograd engine.

Beginner about 10 h

The picture

  1. 01

    Tensors

    shapes, devices

  2. 02

    Autograd

    record, backprop

  3. 03

    nn.Module

    layers

  4. 04

    Loss + optimiser

    AdamW

  5. 05

    Training loop

    eval, checkpoint

A tiny autograd engine

Understanding autograd removes the mystery from loss.backward(). A value remembers how it was computed, and backward walks the graph applying the chain rule.

class Value:
    def __init__(self, data, children=()):
        self.data, self.grad = data, 0.0
        self._prev, self._backward = set(children), lambda: None

    def __add__(self, o):
        o = o if isinstance(o, Value) else Value(o)
        out = Value(self.data + o.data, (self, o))
        def _bw():
            self.grad += out.grad
            o.grad += out.grad
        out._backward = _bw
        return out

    def __mul__(self, o):
        o = o if isinstance(o, Value) else Value(o)
        out = Value(self.data * o.data, (self, o))
        def _bw():
            self.grad += o.data * out.grad
            o.grad += self.data * out.grad
        out._backward = _bw
        return out

    def backward(self):
        order, seen = [], set()
        def topo(v):
            if v not in seen:
                seen.add(v)
                for c in v._prev:
                    topo(c)
                order.append(v)
        topo(self)
        self.grad = 1.0
        for v in reversed(order):
            v._backward()

a, b = Value(2.0), Value(-3.0)
c = a * b + a
c.backward()
print(a.grad, b.grad)   # dc/da = b + 1 = -2, dc/db = a = 2

The PyTorch training loop

import torch, torch.nn as nn, torch.nn.functional as F

class MLP(nn.Module):
    def __init__(self, d_in, d_hidden, d_out):
        super().__init__()
        self.net = nn.Sequential(nn.Linear(d_in, d_hidden), nn.GELU(), nn.Linear(d_hidden, d_out))
    def forward(self, x):
        return self.net(x)

model = MLP(20, 64, 3).to(device)
opt = torch.optim.AdamW(model.parameters(), lr=3e-3, weight_decay=0.01)

for step in range(1000):
    model.train()
    xb, yb = next(train_batches)                  # your DataLoader
    loss = F.cross_entropy(model(xb.to(device)), yb.to(device))
    opt.zero_grad(set_to_none=True)
    loss.backward()
    torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
    opt.step()

    if step % 100 == 0:
        model.eval()
        with torch.no_grad():
            xv, yv = val_batch
            vloss = F.cross_entropy(model(xv.to(device)), yv.to(device))
        print(step, loss.item(), vloss.item())

The habits that save days

  1. Overfit one batch. If the model cannot drive loss to about zero on 8 examples, you have a bug, not a modelling problem.
  2. Check the initial loss. For KK classes it should be about ln⁡K\ln K. If it is far off, initialisation or the loss is wrong.
  3. Inspect shapes and gradients with a quick for n,p in model.named_parameters(): print(n, p.grad.norm()).
  4. Fix seeds and log everything (loss, grad norm, learning rate).

Common mistakes

  • Forgetting model.eval() and torch.no_grad() during validation.
  • Accumulating gradients by forgetting zero_grad.
  • Moving the model to the GPU but not the batch.

Exercises

  1. Extend Value with tanh and train a 2-layer scalar MLP on four points.
  2. Compare your gradients to PyTorch's to six decimal places.

You are done when you can…

  • Write a training loop from memory with eval mode, no_grad and gradient clipping
  • Implement a scalar autograd engine and check it against PyTorch
  • Overfit a single batch on purpose to prove the pipeline works