Coding tutorial · Build it from scratch

PyTorch From First Principles

We build a small neural network and its training loop from raw PyTorch, and look inside every tensor on the way. At the end you can say exactly what happens between loss.backward() and optimizer.step().

PyTorchAutogradTraining loops

What you will build

blog-coding-tutorials/c01-pytorch

scratchnet: a small neural-network training project in raw PyTorch. It has tensor inspection tools, a Linear layer, an MLP, MSE and cross entropy, SGD and AdamW, datasets with collate functions, a full training loop with checkpoints, and debugging hooks. Each piece is tested against the PyTorch code it replaces.

Time
About 3 hours
Hardware
Any laptop CPU. One benchmark needs CUDA or MPS.
You need
Python 3.10+, PyTorch 2.4 or newer, pytest, PyYAML. You should know basic Python and matrix multiplication.
Package
scratchnet
Final repo tree c01-pytorch/
c01-pytorch/
├── README.md  # how to run everything, results table
├── conftest.py  # puts scratchnet on sys.path for pytest
├── scratchnet/
│   ├── autograd_tools.py  # step 6: walk the grad_fn graph
│   ├── broadcasting.py  # step 3: the rule and stride-0 expansion
│   ├── data.py  # step 11: datasets and collate functions
│   ├── debug.py  # step 13: hooks and checks
│   ├── device.py  # step 4: pick_device, synchronize
│   ├── layers.py  # step 7-8: Linear, ReLU, Dropout, Standardize, MLP
│   ├── losses.py  # step 9: MSE, log_softmax, cross entropy
│   ├── matmul.py  # step 5: from loops to bmm
│   ├── optim.py  # step 10: SGD, AdamW, norms, clipping
│   ├── tensors.py  # step 1-2: layout record, strides, manual views
│   └── train.py  # step 12: train_step, evaluate, fit, checkpoints
├── scripts/
│   ├── 01_tensors.py
│   ├── 02_broadcasting.py
│   ├── 03_autograd.py
│   ├── 04_losses.py
│   ├── 05_train.py
│   ├── 06_backward_to_step.py
│   ├── 07_break_it.py
│   ├── 08_linear_manual.py
│   ├── 09_modules.py
│   ├── 10_data.py
│   └── 11_matmul.py
├── benchmarks/
│   ├── dataloader.py
│   ├── matmul.py  # step 5: from loops to bmm
│   ├── optimizers.py
│   └── transfer.py
├── configs/
│   └── spiral_adamw.yaml  # the default run
├── results/  # captured outputs of every script and benchmark
└── tests/
    ├── test_autograd.py
    ├── test_data_train_debug.py
    ├── test_gpu.py
    ├── test_layers_losses.py
    ├── test_optim.py
    └── test_tensors.py

The plan

What exactly happens between loss.backward() and optimizer.step()? Which tensors change, which stay the same, and how would you check?

Those two lines sit inside every framework in this series. Trainer and the distributed and fine-tuning libraries later in the series all wrap them. If you can read those two lines at the level of tensors, the wrappers stop being mysterious.

To answer the question we need the parts underneath it. So we start with one tensor and build upward. A tensor leads to views, views to broadcasting, and broadcasting to matrix multiplication. Then come autograd, a layer, a model, a loss, an optimizer, a data pipeline and a training loop. The last step traces one real training step and prints every piece of state.

The derivations live in the theory posts, so we only point to them. Here we write the code and look at what it does.

Clone the repo once. Every command below runs from its root.

$ git clone https://github.com/srini-anirudh/blog-coding-tutorials.git
$ cd blog-coding-tutorials
$ python -m venv .venv && .venv/bin/pip install -e ".[dev]"
Step 01

Look inside a tensor

Goal Read every piece of metadata a tensor carries, and compute its memory footprint by hand.

Start with the simplest tensor we can make: x = torch.randn(4, 8). It looks like a 4 by 8 table of random numbers. It is really a flat block of memory plus a small record that says how to read that block. Here is every field of the record for x.

What x = torch.randn(4, 8) carries
FieldValueMeaning
shape(4, 8)The size along each dimension.
rank2The number of dimensions. x.dim() returns it.
dimension0 and 1One axis of the tensor. Dimension 0 has size 4. Dimension 1 has size 8.
dtypetorch.float32How to decode the bytes of one element.
devicecpuWhich memory holds the bytes.
storage32 floatsThe flat block itself. It has no shape.
element size4 bytesThe size of one float32.

We collect these in one record, so that a later script can print any tensor the same way.

@dataclass(frozen=True)
class Layout:
    """Everything PyTorch needs to turn a logical index into a memory address."""

    shape: tuple[int, ...]
    stride: tuple[int, ...]
    offset: int
    dtype: torch.dtype
    device: str
    element_size: int
    nbytes: int  # bytes this tensor's elements occupy: numel * element_size
    storage_bytes: int  # bytes of the whole storage it points into
    contiguous: bool


def memory_bytes(t: torch.Tensor) -> int:
    """M = numel(t) * bytes-per-element."""
    return t.numel() * t.element_size()


def describe(t: torch.Tensor) -> Layout:
    """Collect the layout metadata of `t` in one record."""
    return Layout(
        shape=tuple(t.shape),
        stride=tuple(t.stride()),
        offset=t.storage_offset(),
        dtype=t.dtype,
        device=str(t.device),
        element_size=t.element_size(),
        nbytes=memory_bytes(t),
        storage_bytes=t.untyped_storage().nbytes(),
        contiguous=t.is_contiguous(),
    )
Listing 1The whole record. memory_bytes is the formula below, and describe reads each field from the tensor.

Two fields look alike and are not. nbytes is what this tensor’s own elements occupy. storage_bytes is the size of the whole block it points into. They are equal here. Step 2 shows a case where they differ by a factor of 1000.

The memory footprint has a one-line formula.

M = numel(x) × bytes per element = 32 × 4 = 128 bytes

Run the first script. It prints the metadata and repeats the sum for two other dtypes.

$ .venv/bin/python c01-pytorch/scripts/01_tensors.py
== metadata ==
shape=(4, 8) rank=2 dtype=torch.float32 device=cpu
numel=32 element_size=4 B -> 128 B
  as torch.float32    128 B
  as torch.bfloat16    64 B
  as torch.int8        32 B

The shape is the same in all three lines. Only the bytes per element change. This is why half precision matters at scale: the same model in bfloat16 needs half the memory for its weights.

Checkpoint

  • You can name the seven fields above for any tensor.
  • test_memory_footprint passes.
Step 02

Storage, strides and views

Goal Turn a logical index into a memory address by hand, and see why transpose moves no data.

The storage is flat, but a tensor has rows and columns. Two more numbers connect them. The stride of a dimension says how many slots to move in storage when that index goes up by one. The storage offset says which slot holds element zero.

Together they give the one rule that every view in PyTorch follows:

slot = offset + index[0] × stride[0] + index[1] × stride[1] + …

Take m = torch.arange(12).view(3, 4). Its stride is (4, 1). Moving down one row skips 4 slots. Moving right one column skips 1 slot. So m[2, 3] reads slot 0 + 2 × 4 + 3 × 1 = 11.

Now we write the rule as code. storage_indices applies it to every element, in pure Python, because it is a definition and not a fast path.

def contiguous_strides(shape: tuple[int, ...]) -> tuple[int, ...]:
    """Row-major strides: the last dim moves by 1, each earlier dim by the product of later sizes."""
    strides = []
    step = 1
    for size in reversed(shape):
        strides.append(step)
        step *= size
    return tuple(reversed(strides))


def storage_index(index: tuple[int, ...], stride: tuple[int, ...], offset: int) -> int:
    """Where logical element `index` lives in storage: offset + sum_k index[k] * stride[k]."""
    return offset + sum(i * s for i, s in zip(index, stride))


def storage_indices(t: torch.Tensor) -> torch.Tensor:
    """For every logical element of `t`, the storage slot it reads.

    Returns a LongTensor with the same shape as `t`. Pure Python on purpose:
    it is the definition, not a fast path. Use it on small tensors.
    """
    out = torch.empty(t.shape, dtype=torch.long)
    for index in itertools.product(*(range(n) for n in t.shape)):
        out[index] = storage_index(index, t.stride(), t.storage_offset())
    return out
Listing 2Row-major strides, the address rule, and a function that returns the storage slot of every element.

If the rule is right, we can build a transpose without touching any data. We swap two entries of the shape and the same two entries of the stride. Then as_strided makes a new view on the same storage. view_manual does a similar thing: it keeps the storage and computes fresh row-major strides for the new shape.

def transpose_manual(t: torch.Tensor, dim0: int, dim1: int) -> torch.Tensor:
    """Transpose by swapping two entries of shape and stride. No data moves."""
    shape = list(t.shape)
    stride = list(t.stride())
    shape[dim0], shape[dim1] = shape[dim1], shape[dim0]
    stride[dim0], stride[dim1] = stride[dim1], stride[dim0]
    return t.as_strided(shape, stride, t.storage_offset())
def permute_manual(t: torch.Tensor, dims: tuple[int, ...]) -> torch.Tensor:
    """Permute by reordering shape and stride with the same index list."""
    shape = [t.shape[d] for d in dims]
    stride = [t.stride(d) for d in dims]
    return t.as_strided(shape, stride, t.storage_offset())
def view_manual(t: torch.Tensor, shape: tuple[int, ...]) -> torch.Tensor:
    """A `view` for contiguous tensors: same storage, new row-major strides.

    `torch.Tensor.view` handles more cases (it can split or merge dims whose
    strides line up). This version only covers the common one, which is
    exactly the case where a view is always legal.
    """
    if not t.is_contiguous():
        raise RuntimeError("view_manual needs a contiguous tensor; call .contiguous() first")
    if torch.Size(shape).numel() != t.numel():
        raise RuntimeError(f"shape {shape} is invalid for input of size {t.numel()}")
    return t.as_strided(shape, contiguous_strides(shape), t.storage_offset())

The script prints the layout of several views of one storage. Run it again and read the second block.

== views of one storage ==
base.view(3, 4)        shape=[3, 4]     stride=(4, 1)     offset=0  contiguous=True  shares=True
m.t()                  shape=[4, 3]     stride=(1, 4)     offset=0  contiguous=False shares=True
m.t().contiguous()     shape=[4, 3]     stride=(3, 1)     offset=0  contiguous=True  shares=False
m[:, 1:3]              shape=[3, 2]     stride=(4, 1)     offset=1  contiguous=False shares=True
m[1]                   shape=[4]        stride=(1,)       offset=4  contiguous=True  shares=True
m[:, ::2]              shape=[3, 2]     stride=(4, 2)     offset=0  contiguous=False shares=True
base.view(2, 3, 2)     shape=[2, 3, 2]  stride=(6, 2, 1)  offset=0  contiguous=True  shares=True
...permute(2, 0, 1)    shape=[2, 2, 3]  stride=(1, 6, 2)  offset=0  contiguous=False shares=True

Read a few rows. m.t() has stride (1, 4), the swap we predicted, and it still shares storage. m[:, 1:3] has offset 1, because its first element is in slot 1. m[:, ::2] has column stride 2, because it skips every other column. m.t().contiguous() is the only row with shares=False. That call copied the data into a new storage in row-major order.

The next block applies our rule. Since base = torch.arange(12), each value equals its slot, so we can check by eye.

== which storage slot each element reads ==
m.t():
tensor([[ 0,  4,  8],
        [ 1,  5,  9],
        [ 2,  6, 10],
        [ 3,  7, 11]])
m[:, 1:3]:
tensor([[ 1,  2],
        [ 5,  6],
        [ 9, 10]])
shape
stride
offset
contiguous

Figure 1Logical layout is not physical layout. The strip on top is the storage. The grid below is what the view shows. Click any cell in the grid to compute its slot with the address rule. Choose a view to see the cells move while the storage stays still.

The table sums up the operations. Read it by asking one question: does this call move any bytes?

View and copy operations
OperationMoves dataNeeds contiguous inputResult contiguousWhat changes
viewNeverMostly. Strides must line up.If the input wasshape, stride
reshapeOnly when view would failNoDependsshape, stride, sometimes storage
transposeNeverNoUsually nottwo entries of shape and stride
permuteNeverNoUsually notorder of shape and stride
slicingNeverNoDependsshape, stride, offset
contiguousOnly when not already contiguousNoAlwaysstorage, stride
cloneAlwaysNoKeeps the layout when it canstorage

Views have one more cost. A slice keeps its whole storage alive.

== a slice keeps the whole storage alive ==
row.nbytes=4000 B  storage=4.0 MB
row.clone(): storage=4000 B

One 4000-byte row holds a 4 MB block in memory. If you keep small pieces of big tensors, such as a few rows of a batch in a list, call clone() first. Otherwise each piece keeps the big block alive.

Checkpoint

  • You can predict the stride of a transposed tensor before printing it.
  • You can explain why t.view(12) fails after a transpose.
  • The five tests above pass.
Step 03

Broadcasting

Goal Write the broadcasting rule yourself, see that it copies nothing, and catch the bug it can hide.

Later tutorials add a vector to every token and a per-head vector to every position. We do not want Python loops for that. Broadcasting lets two tensors of different shapes combine, as if the smaller one had been repeated. The rule is short:

  1. Line the shapes up from the right.
  2. Treat a missing dimension as size 1.
  3. In each column, the sizes must be equal, or one of them must be 1.
  4. A size-1 dimension is stretched to match.
def broadcast_shape(a: tuple[int, ...], b: tuple[int, ...]) -> tuple[int, ...]:
    """The result shape of `a op b`, or ValueError when the shapes do not broadcast."""
    rank = max(len(a), len(b))
    # Left-pad the shorter shape with 1s so both have the same rank.
    a_pad = (1,) * (rank - len(a)) + tuple(a)
    b_pad = (1,) * (rank - len(b)) + tuple(b)
    out = []
    for dim, (x, y) in enumerate(zip(a_pad, b_pad)):
        if x == y or y == 1:
            out.append(x)
        elif x == 1:
            out.append(y)
        else:
            raise ValueError(f"dim {dim - rank}: sizes {x} and {y} do not broadcast (shapes {a} and {b})")
    return tuple(out)
Listing 3The rule as code. The shorter shape is left-padded with 1s, then each column is checked.

Stretching costs no memory, and Step 2 tells us why. If a dimension has stride 0, then moving along it never moves in storage. Every index reads the same element. So an expanded tensor is one more view.

def expand_to(t: torch.Tensor, shape: tuple[int, ...]) -> torch.Tensor:
    """Broadcast `t` to `shape` by setting stride 0 on every stretched dim."""
    rank = len(shape)
    src_shape = (1,) * (rank - t.dim()) + tuple(t.shape)
    src_stride = (0,) * (rank - t.dim()) + tuple(t.stride())
    stride = []
    for size, src_size, src_st in zip(shape, src_shape, src_stride):
        if src_size == size:
            stride.append(src_st)
        elif src_size == 1:
            stride.append(0)  # every index along this dim reads the same element
        else:
            raise ValueError(f"cannot expand {tuple(t.shape)} to {shape}")
    return t.as_strided(shape, stride, t.storage_offset())
Listing 4Expansion by stride. Stretched dimensions get stride 0, so as_strided returns a view of the same few numbers.

The script tries the two shapes that attention needs.

$ .venv/bin/python c01-pytorch/scripts/02_broadcasting.py
== [B, N, D] + [D]: a bias added to every token ==
broadcast_shape: (2, 5, 8)
bias expanded: (2, 5, 8) stride (0, 0, 1)

== [B, H, N, D] + [1, H, 1, D]: one vector per head ==
broadcast_shape: (2, 4, 5, 8)
per_head expanded: (2, 4, 5, 8) stride (0, 8, 0, 1)
batch 0 token 3 and batch 1 token 0 both get the head-2 vector: True

== a mismatch is an error ==
ValueError: dim -1: sizes 8 and 5 do not broadcast (shapes (2, 5, 8) and (5,))

== the silent bug: [B, 1] - [B] ==
pred (4, 1) - target (4,) -> (4, 4)
loss on [B, B]: 1.0290   correct loss: 0.6618
Shapes in this step (B = 2, H = 4, N = 5, D = 8)
TensorShapeMeaning
x[B, N, D]One D-number vector per token and batch element.
bias[D]One vector. It is added to every token.
q[B, H, N, D]One vector per batch element, head and token.
per_head[1, H, 1, D]One vector per head. It is shared across batch and tokens.
per_head, expanded[B, H, N, D], stride (0, 8, 0, 1)Still 4 × 8 = 32 numbers in memory.

Figure 2The broadcasting rule, column by column. Pick a preset or type your own shapes. Blue columns match. In an orange column the size-1 side stretches, with stride 0. A red column is an error. For rank-2 results the figure also draws the expanded tensor, which is where the silent bug shows up.

Checkpoint

  • You can say the result shape of [B, H, N, D] + [1, H, 1, D] without running it.
  • You print the shape of a difference before you average it.
Step 04

CPU and GPU tensors

Goal Know where a tensor lives, what a copy costs, and how to time GPU code without fooling yourself.

So far the storage has been in host memory, the RAM the CPU uses. A discrete GPU has its own memory. A tensor lives in one or the other, and x.device tells you which. x.to(device) returns a new tensor on that device, with a new storage. x.cuda() is short for x.to("cuda"). If the tensor is already there, no copy happens.

We pick the device in one place, with a helper that every script uses.

def pick_device(prefer: str | None = None) -> torch.device:
    """Return the best available device: cuda > mps > cpu.

    `prefer` forces a device by name (for example "cpu" in tests).
    """
    if prefer is not None:
        return torch.device(prefer)
    if torch.cuda.is_available():
        return torch.device("cuda")
    if torch.backends.mps.is_available():
        return torch.device("mps")
    return torch.device("cpu")


def synchronize(device: torch.device | str) -> None:
    """Block until all queued work on `device` has finished."""
    device = torch.device(device)
    if device.type == "cuda":
        torch.cuda.synchronize(device)
    elif device.type == "mps":
        torch.mps.synchronize()
    # CPU ops run eagerly, so there is nothing to wait for.
Listing 5Device choice and synchronisation. The second function is the one people forget.

The second function exists because GPU work is queued. When torch.mm(a, b) returns on a GPU, Python has only put a command in a queue. The multiply has not finished. If you read the clock at that point, you measure the time to queue the work.

The matmul benchmark measures this mistake directly. It needs a device with a real queue, so this one is from the Apple M5 GPU.

        a, b = torch.randn(4096, 4096, device=accel), torch.randn(4096, 4096, device=accel)
        torch.mm(a, b)
        synchronize(accel)
        t0 = time.perf_counter()
        c = torch.mm(a, b)
        t_issue = time.perf_counter() - t0
        synchronize(accel)
        t_real = time.perf_counter() - t0
Listing 6Timing the same call twice: once when it returns, and once after synchronize.
timing a 4096 x 4096 matmul on mps with and without synchronize():
  without sync: 0.285 ms   with sync: 53.572 ms

The clock read before the sync says 0.285 ms. The real time is 53.6 ms, which is 188 times longer. Figure 3 shows the two timelines.

Figure 3Python and the device run on separate timelines. Both bars are drawn to scale, using the real timings on an Apple M5 GPU. The top panel is one 4096 by 4096 matmul. The bottom panel is one 64 MB non_blocking copy.

Anything that needs the value forces the same wait. .item(), .cpu() and print(x) all block until the device catches up. This is why GradNormMonitor in Step 13 stores a tensor and not a float.

Pinned memory and asynchronous copies

On a discrete GPU, a copy is done by a DMA engine, a hardware unit that reads RAM directly. It needs the source pages to stay in place. The operating system can normally move or swap ordinary pages, which are called pageable. pin_memory() makes a copy of the tensor in pages that are locked in place. Without it, the driver first copies your data to a pinned buffer of its own.

With a pinned source, x.to(device, non_blocking=True) can return at once while the copy runs in the background. The CPU can use that time to prepare the next batch. The benchmark times all three directions and shows what non_blocking returns.

def time_copy(fn, device, reps: int) -> float:
    """Median seconds per call. synchronize() before and after: copies are queued, not finished."""
    fn()
    synchronize(device)  # warm-up: first use allocates and caches device memory
    times = []
    for _ in range(reps):
        synchronize(device)
        t0 = time.perf_counter()
        fn()
        synchronize(device)
        times.append(time.perf_counter() - t0)
    return statistics.median(times)
    x = torch.randn(16 * 2**20).pin_memory()
    x.to(device)
    synchronize(device)
    t0 = time.perf_counter()
    y = x.to(device, non_blocking=True)
    t_issue = time.perf_counter() - t0
    synchronize(device)
    t_done = time.perf_counter() - t0
Tensors in the transfer benchmark, for size S in MB
TensorShapeWhere it lives
host[S × 220 / 4]Host memory, pageable. Float32, so 4 bytes each.
pinnedsameHost memory, page-locked. A separate copy of host.
devsameDevice memory.
$ .venv/bin/python c01-pytorch/benchmarks/transfer.py --device mps
device=mps  torch=2.15.0
 size_MB  H2D_pageable  H2D_pinned      D2H   (GB/s)
  0.0625          0.19        0.18     0.09
       1          1.58        3.70     1.61
       4          7.22       10.68     9.66
      16          8.90       13.99     7.78
      64          8.20       11.57     5.01
     256         15.23       21.71    14.01

what non_blocking=True returns (64 MB, pinned source):
  call returned after 0.092 ms, copy finished after 5.433 ms

Here is the same benchmark on CUDA. It is one run on an NVIDIA H100 80GB HBM3.

$ .venv/bin/python c01-pytorch/benchmarks/transfer.py --device cuda
device=cuda  torch=2.15.0+cu132
 size_MB  H2D_pageable  H2D_pinned      D2H   (GB/s)
  0.0625          1.77        3.11     1.00
       1          6.85       11.61     1.39
       4         10.88       13.46     1.51
      16         12.82       14.02     1.54
      64         12.04       14.20     1.37
     256         11.73       14.25     1.35

what non_blocking=True returns (64 MB, pinned source):
  call returned after 0.036 ms, copy finished after 4.741 ms

The repo also has six tests that need a real GPU. They cover .cuda() against .to(), a pinned non_blocking copy, a real device mismatch, our AdamW against PyTorch’s on CUDA, and resuming from a checkpoint on CUDA. All six passed in one run on the H100.

$ .venv/bin/python -m pytest c01-pytorch -m gpu
......                                                                   [100%]
6 passed, 50 deselected in 9.00s

Checkpoint

  • Every timing you write calls synchronize(device) before it reads the clock.
  • benchmarks/transfer.py prints a table on your accelerator. On a CPU-only machine it prints no accelerator found; nothing to transfer to.
Step 05

Matrix multiplication

Goal Write matmul from its definition, add the batch dimension, and measure what a real kernel buys you.

Almost all the compute in a neural network is matrix multiplication. Linear layers use it now. Attention uses it in Build Attention From Scratch. Its shape rule is worth learning early. The inner dimension K must match, and it disappears:

[B, M, K] @ [B, K, N] → [B, M, N]

We start from the definition, with three loops. Then we remove one loop with broadcasting from Step 3. Then we add a batch dimension.

def mm_loops(a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
    """[M, K] @ [K, N] -> [M, N] with explicit loops: out[i, j] = sum_k a[i, k] * b[k, j]."""
    m, k = a.shape
    k2, n = b.shape
    if k != k2:
        raise ValueError(f"inner dims differ: {tuple(a.shape)} @ {tuple(b.shape)}")
    out = torch.zeros(m, n, dtype=a.dtype)
    for i in range(m):
        for j in range(n):
            acc = 0.0
            for p in range(k):
                acc += a[i, p].item() * b[p, j].item()
            out[i, j] = acc
    return out


def mm_rows(a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
    """[M, K] @ [K, N] -> [M, N], one row at a time: row i of the output is a[i] @ b."""
    return torch.stack([(a[i, :, None] * b).sum(dim=0) for i in range(a.shape[0])])


def bmm_loop(a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
    """[B, M, K] @ [B, K, N] -> [B, M, N]: an independent matmul per batch element."""
    return torch.stack([a[i] @ b[i] for i in range(a.shape[0])])
Listing 7Matmul from its definition. mm_rows computes one output row at a time with broadcasting. bmm_loop adds the batch dimension.

The line in mm_rows is worth reading slowly. a[i, :, None] has shape [K, 1]. b has shape [K, N]. Their product broadcasts to [K, N], where row p of b is scaled by a[i, p]. Summing over dimension 0 gives one output row, of shape [N].

Figure 4One output cell is one row of A dotted with one column of B. The integers are for illustration. The last frames add the batch dimension, which is an independent matmul per batch element.

torch.matmul adds one more idea on top of torch.bmm: the leading dimensions broadcast. The last two dimensions never do. They follow the matmul rule. We can write that with the tools we already have.

def matmul_manual(a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
    """[..., M, K] @ [..., K, N] -> [..., M, N], for inputs of rank 2 or more.

    This is what torch.matmul adds on top of torch.bmm: the leading dims broadcast.
    The last two dims never do. They follow the matmul rule instead.
    """
    batch = broadcast_shape(tuple(a.shape[:-2]), tuple(b.shape[:-2]))
    m, k = a.shape[-2:]
    k2, n = b.shape[-2:]
    a_flat = a.expand(*batch, m, k).reshape(-1, m, k)  # [prod(batch), M, K]
    b_flat = b.expand(*batch, k2, n).reshape(-1, k2, n)  # [prod(batch), K, N]
    return bmm_loop(a_flat, b_flat).reshape(*batch, m, n)
Listing 8Matmul with broadcast leading dimensions: expand both inputs, flatten the batch, multiply, and restore the shape.
Which call takes which shapes
CallInput shapesOutputNotes
torch.mm[M, K], [K, N][M, N]Exactly two dimensions.
torch.bmm[B, M, K], [B, K, N][B, M, N]Exactly three dimensions, same B.
torch.matmul, @[..., M, K], [..., K, N][..., M, N]Leading dimensions broadcast.
Attention, in Build Attention From Scratch[B, H, N, d], [B, H, d, N][B, H, N, N]One score per pair of tokens, per head.
$ .venv/bin/python c01-pytorch/scripts/11_matmul.py
== [M, K] @ [K, N] -> [M, N] ==
a (4, 6) b (6, 3) -> (4, 3)  flops: 144
mm_loops  matches torch.mm: True
mm_rows   matches torch.mm: True

== [B, M, K] @ [B, K, N] -> [B, M, N]: one independent matmul per batch element ==
ba (2, 4, 6) bb (2, 6, 3) -> (2, 4, 3)
bmm_loop matches torch.bmm: True
row 1 of the batch is ba[1] @ bb[1]: True

== matmul broadcasts the leading dims; bmm does not ==
(2, 4, 6) @ (6, 3) -> (2, 4, 3)  matches torch.matmul: True
(2, 1, 4, 6) @ (5, 6, 3) -> (2, 5, 4, 3)  matches torch.matmul: True
torch.bmm(ba, bb[0]) -> batch2 must be a 3D tensor

== the attention shape: [B, H, N, d] @ [B, H, d, N] -> [B, H, N, N] ==
q @ k.transpose(-2, -1): (2, 4, 5, 5)

Now the bottleneck. We run all versions and report milliseconds and GFLOP/s, billions of floating-point operations per second. A multiply and an add count as two.

$ .venv/bin/python c01-pytorch/benchmarks/matmul.py
torch 2.15.0+cu132, 8 CPU threads
impl                       n         ms   GFLOP/s
mm_loops (python)         32    164.411    0.0004
mm_rows (broadcast)      256     10.695       3.1
torch.mm cpu x8 thr      256      0.180     186.2
torch.mm cpu x8 thr     1024      7.963     269.7
torch.mm cpu x8 thr     2048     27.051     635.1

That machine has no accelerator we can use. For the GPU rows we use the earlier run on the Apple M5.

impl                       n         ms   GFLOP/s
mm_loops (python)         32     93.214    0.0007
mm_rows (broadcast)      256     13.007       2.6
torch.mm cpu x2 thr      256      0.192     175.0
torch.mm cpu x2 thr     1024      3.152     681.3
torch.mm cpu x2 thr     2048     34.960     491.4
torch.mm mps             256      0.400      83.9
torch.mm mps            1024      1.106    1942.1
torch.mm mps            2048      6.047    2841.3
torch.mm mps            4096    217.726     631.2

Here is the same benchmark on CUDA, one run on an NVIDIA H100 80GB HBM3. The CPU rows come from that machine’s own host CPU. It is a different machine from the EPYC server above, so compare its CPU rows only with its GPU rows.

impl                       n         ms   GFLOP/s
mm_loops (python)         32    161.564    0.0004
mm_rows (broadcast)      256     10.953       3.1
torch.mm cpu x8 thr      256      0.079     426.4
torch.mm cpu x8 thr     1024      2.898     741.0
torch.mm cpu x8 thr     2048     22.676     757.6
torch.mm cuda            256      0.049     686.9
torch.mm cuda           1024      0.085   25228.3
torch.mm cuda           2048      0.369   46606.3
torch.mm cuda           4096      2.695   51000.9

On the H100 the GPU wins at every size we ran, even n = 256: 0.049 ms against 0.079 ms on its host CPU. At n = 2048 it takes 0.369 ms against 22.7 ms. At n = 4096 it reaches 51,001 GFLOP/s, about 51 TFLOP/s, in float32 with the default precision. These are single runs.

Checkpoint

  • You can write the output shape of any @ before running it.
  • The matmul tests pass.
Step 06

Autograd

Goal See the graph that PyTorch records, walk it yourself, and learn when gradients add up and when the graph disappears.

Set requires_grad=True on a tensor and PyTorch starts recording. Each operation on it creates a backward node, and the output tensor points to that node through grad_fn. The maths is in the theory post. Here we inspect the objects.

Derivation inWhat autograd actually does
x = torch.tensor([1.0, 2.0, 3.0], requires_grad=True)
w = torch.tensor([0.5, -1.0, 2.0], requires_grad=True)
y = x * w  # MulBackward0
z = y.sum()  # SumBackward0
for name, t in [("x", x), ("w", w), ("y", y), ("z", z)]:
    print(f"{name}: is_leaf={t.is_leaf!s:<5} requires_grad={t.requires_grad!s:<5} grad_fn={type(t.grad_fn).__name__}")
print("z.grad_fn.next_functions:", [type(fn).__name__ for fn, _ in z.grad_fn.next_functions])
print("y.grad_fn.next_functions:", [type(fn).__name__ for fn, _ in y.grad_fn.next_functions])
print(format_graph(z))

y.retain_grad()  # non-leaf grads are freed by default; ask to keep this one
z.backward()
print("x.grad =", x.grad.tolist(), " (dz/dx = w)")
print("w.grad =", w.grad.tolist(), " (dz/dw = x)")
print("y.grad =", y.grad.tolist())
Listing 9Three operations and one backward pass. We print the state of each tensor before the backward pass.

format_graph prints the recorded graph. It is a short recursion over next_functions, the list of inputs each node holds.

def walk_graph(t: torch.Tensor) -> list[Node]:
    """Depth-first list of the backward nodes reachable from `t.grad_fn`.

    A node reached twice (for example a weight used in two places) is listed
    once, at the first depth it is seen.
    """
    if t.grad_fn is None:
        return []
    seen: set[int] = set()
    nodes: list[Node] = []

    def visit(fn, depth: int) -> None:
        if fn is None or id(fn) in seen:
            return
        seen.add(id(fn))
        leaf = getattr(fn, "variable", None)  # only AccumulateGrad has .variable
        nodes.append(Node(depth, type(fn).__name__, tuple(leaf.shape) if leaf is not None else None))
        for next_fn, _ in fn.next_functions:
            visit(next_fn, depth + 1)

    visit(t.grad_fn, 0)
    return nodes
Listing 10A depth-first walk of the backward graph. Only AccumulateGrad nodes have a .variable: the leaf tensor they write into.
$ .venv/bin/python c01-pytorch/scripts/03_autograd.py
== a three-op graph ==
x: is_leaf=True  requires_grad=True  grad_fn=NoneType
w: is_leaf=True  requires_grad=True  grad_fn=NoneType
y: is_leaf=False requires_grad=True  grad_fn=MulBackward0
z: is_leaf=False requires_grad=True  grad_fn=SumBackward0
z.grad_fn.next_functions: ['MulBackward0']
y.grad_fn.next_functions: ['AccumulateGrad', 'AccumulateGrad']
SumBackward0
  MulBackward0
    AccumulateGrad  -> .grad of leaf [3]
    AccumulateGrad  -> .grad of leaf [3]
x.grad = [0.5, -1.0, 2.0]  (dz/dx = w)
w.grad = [1.0, 2.0, 3.0]  (dz/dw = x)
y.grad = [1.0, 1.0, 1.0]
The tensors of the graph, with values
TensorShapeValueKindgrad_fn
x[3][1, 2, 3]LeafNone
w[3][0.5, -1, 2]LeafNone
y = x * w[3][0.5, -2, 6]Non-leafMulBackward0
z = y.sum()[]4.5Non-leafSumBackward0

A leaf is a tensor you created, not the result of a recorded operation. Weights are leaves. By default, backward() fills .grad only on leaves. y.grad exists here only because we asked for it with y.retain_grad().

The nodes run in the reverse order of the forward pass. SumBackward0 sends a gradient of 1 to each element of y. MulBackward0 multiplies by the other input, so x receives w and w receives x. Then the two AccumulateGrad nodes write into .grad.

Figure 5The forward pass builds the graph. The backward pass walks it from the root and writes .grad on the leaves. Values are the printed values from the script above.

Gradients accumulate

AccumulateGrad means what it says. It adds to .grad. It does not overwrite.

w = torch.tensor(2.0, requires_grad=True)
for i in range(3):
    (3 * w).backward()
    print(f"after backward #{i + 1}: w.grad = {w.grad.item()}")
w.grad = None
print("after w.grad = None:", w.grad)
== gradients accumulate ==
after backward #1: w.grad = 3.0
after backward #2: w.grad = 6.0
after backward #3: w.grad = 9.0
after w.grad = None: None

This is why every training step starts with zero_grad. It is also useful on purpose: gradient accumulation over several small batches is exactly this behaviour. Step 13 shows what happens when you forget to clear them.

The graph is freed, unless you ask

Backward nodes hold tensors they saved for the backward pass. To save memory, backward() frees those tensors as it goes. A second call then has nothing to work with.

a = torch.tensor(1.5, requires_grad=True)
b = a.exp()
b.backward()
try:
    b.backward()
except RuntimeError as err:
    print("second backward ->", str(err).split(".")[0])
a.grad = None
b = a.exp()
b.backward(retain_graph=True)
b.backward()
print(f"with retain_graph=True: a.grad = {a.grad.item():.4f} = 2 * e^1.5")

print("\n== detach and no_grad ==")
x = torch.randn(3, requires_grad=True)
print("x.detach().requires_grad:", x.detach().requires_grad)
with torch.no_grad():
    y = x * 2
print("under no_grad: y.requires_grad =", y.requires_grad, " y.grad_fn =", y.grad_fn)
detach and no_grad both stop recording, at different scopes
ToolScopeShares storageTypical use
x.detach()One tensorYes, writes reach xKeep a value without its graph. Treat a term as a constant.
torch.no_grad()Every operation in the blockNot applicableEvaluation, and the optimizer update.

Checkpoint

  • You can draw the graph of (x * w).sum() with its node names.
  • You can say which tensors get a .grad by default, and why.
Step 07

A Linear layer by hand

Goal Build y = xW + b from two parameters, and match nn.Linear exactly.

We now have what a layer needs: a matmul, broadcasting and gradients. A linear layer is two tensors and one line of algebra.

y = x W + b

We start with the two tensors and no class at all. nn.Parameter marks a tensor as something to train. The rest is the matmul from Step 5 and the broadcast from Step 3.

W = nn.Parameter(torch.randn(3, 2))  # [in, out]
b = nn.Parameter(torch.zeros(2))  # [out]
x = torch.randn(256, 3)  # [B, in]
y = x @ W + b
print("x", list(x.shape), "@ W", list(W.shape), "+ b", list(b.shape), "-> y", list(y.shape))
Listing 11A linear layer with no class around it. The highlighted line is all of it.
$ .venv/bin/python c01-pytorch/scripts/08_linear_manual.py
== y = x W + b with bare parameters ==
x [256, 3] @ W [3, 2] + b [2] -> y [256, 2]
Shapes of the layer
TensorShapeMeaning
x[..., in_features]Input. Any number of leading dimensions.
W[in_features, out_features]The weight. Row i says how input i feeds each output.
b[out_features]The bias. It broadcasts over all leading dimensions of x.
y[..., out_features]Output.

Now we wrap those two tensors in a class. nn.Parameter is a tensor with requires_grad=True that a module registers when you assign it to an attribute. That single behaviour is why the next step works.

class Linear(nn.Module):
    """y = x W + b.

    Shapes: x [..., in_features], W [in_features, out_features],
    b [out_features], y [..., out_features].
    `nn.Linear` stores its weight transposed, as [out_features, in_features].
    """

    def __init__(self, in_features: int, out_features: int, bias: bool = True) -> None:
        super().__init__()
        # Same scale as nn.Linear: U(-1/sqrt(in), 1/sqrt(in)) keeps the output
        # variance roughly independent of the fan-in.
        bound = 1.0 / math.sqrt(in_features)
        self.weight = nn.Parameter(torch.empty(in_features, out_features).uniform_(-bound, bound))
        self.bias = nn.Parameter(torch.empty(out_features).uniform_(-bound, bound)) if bias else None

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        y = x @ self.weight
        if self.bias is not None:
            y = y + self.bias  # [out] broadcasts over every leading dim of x
        return y

    def extra_repr(self) -> str:
        n_in, n_out = self.weight.shape
        return f"in_features={n_in}, out_features={n_out}, bias={self.bias is not None}"
Listing 12The layer. forward is the algebra, with the matmul and the broadcast from earlier steps.

Read forward with the earlier steps in mind. x @ self.weight is the matmul from Step 5. y + self.bias is the [B, N, D] + [D] broadcast from Step 3. The initial values come from a uniform range of plus or minus 1 / sqrt(in_features), the same range nn.Linear uses. It keeps the output variance roughly independent of the input width.

There is one trap when you compare with PyTorch. We store W as [in, out], which matches the algebra. nn.Linear stores its weight transposed, as [out, in]. The test copies our weight across with a transpose, then requires equal outputs.

def test_linear_matches_nn_linear():
    torch.manual_seed(0)
    ours = Linear(6, 4)
    ref = nn.Linear(6, 4)
    with torch.no_grad():
        ref.weight.copy_(ours.weight.t())  # nn.Linear stores [out, in]
        ref.bias.copy_(ours.bias)
    x = torch.randn(2, 5, 6)
    torch.testing.assert_close(ours(x), ref(x))
Listing 13Comparing with the trusted implementation. The transpose on the highlighted line is the only difference.

Autograd sees the layer as ordinary tensor operations, so we can print its graph. This is the Linear layer plus .pow(2).mean() as a loss.

== the graph of a Linear layer and a loss ==
MeanBackward0
  PowBackward0
    AddBackward0
      MmBackward0
        AccumulateGrad  -> .grad of leaf [3, 2]
      AccumulateGrad  -> .grad of leaf [2]

Read it from the bottom. The weight [3, 2] enters MmBackward0, the matmul. Its result and the bias [2] enter AddBackward0. Then come the square and the mean. The two leaves are the only tensors that will get a .grad.

Checkpoint

  • Linear(6, 4) matches nn.Linear(6, 4) once the weight is transposed.
  • gradcheck passes.
Step 08

nn.Module and an MLP

Goal Understand what nn.Module keeps track of, by building an MLP that uses all of it.

We borrow one thing from PyTorch: nn.Module. It is bookkeeping. When you assign an attribute, it looks at the type and files it in the right place. That filing is what lets .parameters(), .to(device) and .state_dict() work on a whole tree of layers.

A stack of linear layers alone is still one linear map, so we need a nonlinearity between them. We also add two small modules that show the other things nn.Module handles: dropout depends on the training mode, and Standardize holds buffers.

Theory inWhy neural networks need nonlinearity
class ReLU(nn.Module):
    def forward(self, x: torch.Tensor) -> torch.Tensor:
        return x.clamp_min(0.0)


class Dropout(nn.Module):
    """Zero each element with probability p in training mode; identity in eval mode."""

    def __init__(self, p: float = 0.1) -> None:
        super().__init__()
        self.p = p

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        if not self.training or self.p == 0.0:
            return x
        keep = (torch.rand_like(x) >= self.p).to(x.dtype)
        # Scale by 1/(1-p) so the expected activation is the same in both modes.
        return x * keep / (1.0 - self.p)


class Standardize(nn.Module):
    """(x - mean) / std with fixed statistics.

    mean and std are buffers: saved in state_dict and moved by .to(device),
    but not returned by .parameters(), so the optimizer never touches them.
    """

    def __init__(self, mean: torch.Tensor, std: torch.Tensor) -> None:
        super().__init__()
        self.register_buffer("mean", mean.clone())
        self.register_buffer("std", std.clone())

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        return (x - self.mean) / self.std
Listing 14Three small modules. Dropout reads self.training. Standardize registers its statistics as buffers.
class MLP(nn.Module):
    """Standardize -> [Linear -> ReLU -> Dropout] x depth -> Linear.

    Shapes: x [B, in_dim] -> logits [B, out_dim].
    """

    def __init__(
        self,
        in_dim: int,
        hidden: int,
        out_dim: int,
        depth: int = 2,
        dropout: float = 0.0,
        mean: torch.Tensor | None = None,
        std: torch.Tensor | None = None,
    ) -> None:
        super().__init__()
        mean = torch.zeros(in_dim) if mean is None else mean
        std = torch.ones(in_dim) if std is None else std
        self.norm = Standardize(mean, std)
        dims = [in_dim] + [hidden] * depth
        # ModuleList registers each block, so its parameters are found by .parameters().
        self.blocks = nn.ModuleList(
            nn.Sequential(Linear(d_in, d_out), ReLU(), Dropout(dropout)) for d_in, d_out in zip(dims[:-1], dims[1:])
        )
        self.head = Linear(hidden, out_dim)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        h = self.norm(x)
        for block in self.blocks:
            h = block(h)
        return self.head(h)
Listing 15The MLP. nn.ModuleList registers the blocks. A plain Python list would hide them from .parameters().

Now ask the module tree what it found. named_parameters() walks the tree and gives each parameter a dotted name. state_dict() holds the parameters plus the buffers.

$ .venv/bin/python c01-pytorch/scripts/09_modules.py
MLP(
  (norm): Standardize()
  (blocks): ModuleList(
    (0): Sequential(
      (0): Linear(in_features=2, out_features=16, bias=True)
      (1): ReLU()
      (2): Dropout()
    )
    (1): Sequential(
      (0): Linear(in_features=16, out_features=16, bias=True)
      (1): ReLU()
      (2): Dropout()
    )
  )
  (head): Linear(in_features=16, out_features=3, bias=True)
)

== submodules ==
['norm', 'blocks', 'head']

== parameters ==
blocks.0.0.weight  [2, 16]    32
blocks.0.0.bias    [16]       16
blocks.1.0.weight  [16, 16]  256
blocks.1.0.bias    [16]       16
head.weight        [16, 3]    48
head.bias          [3]         3
count_parameters: 371

== buffers: saved and moved, but never optimized ==
norm.mean          [0.0, 0.0]
norm.std           [1.0, 1.0]
norm.mean returned by .parameters(): False

== state_dict: parameters and buffers together ==
['norm.mean', 'norm.std', 'blocks.0.0.weight', 'blocks.0.0.bias', 'blocks.1.0.weight', 'blocks.1.0.bias', 'head.weight', 'head.bias']

Check the sum by hand: (2 × 16 + 16) + (16 × 16 + 16) + (16 × 3 + 3) = 371. The buffers appear in state_dict but are not returned by .parameters(), so the optimizer never sees them.

What nn.Module does with each kind of attribute
KindExampleIn parameters()In state_dict()Moved by .to()Updated by the optimizer
Parameterself.weightYesYesYesYes
Bufferself.meanNoYesYesNo
Submoduleself.headIts parametersIts entries, prefixedYesIts parameters
Plain tensorself.t = torch.ones(2)NoNoNoNo
Python list of modulesself.layers = [Linear(2, 2)]NoNoNoNo

Read down the columns. A buffer is state that must be saved and moved, but never trained. The last two rows are bugs. Nothing warns you about them. The model runs, and those tensors never learn.

train() and eval() do one thing: they set self.training on every module in the tree. They do not turn gradients on or off. That is what no_grad is for. Dropout reads the flag. In training mode it zeros elements and scales the rest by 1 / (1 - p), so the expected activation is the same in both modes.

== train() and eval() set one flag on every submodule ==
new model: model.training = True  head.training = True
after eval(): model.training = False  head.training = False
after train(): model.training = True  head.training = True

== the flag only matters to layers that read it: Dropout(0.5) ==
train mode: [2.0, 0.0, 0.0, 0.0, 0.0, 2.0, 2.0, 2.0]
eval mode:  [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]

Checkpoint

  • MLP(2, 16, 3) has 371 parameters and 2 buffers. You can compute the 371 by hand.
  • state_dict holds 8 entries: 6 parameters and 2 buffers.
Step 09

Loss functions

Goal Build cross entropy from log_softmax and gather, make it stable, and match F.cross_entropy exactly.

A loss turns the model’s output into one number. That number is the root of the graph, the place where backward() starts. MSE comes first, because it is one line plus the shape check that Step 3 taught us to want.

def mse_loss(pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
    """mean((pred - target)^2) over every element. Shapes must match exactly."""
    if pred.shape != target.shape:
        # F.mse_loss only warns here; a silent broadcast of [B, 1] against [B]
        # gives a [B, B] difference and a wrong loss that still trains.
        raise ValueError(f"pred {tuple(pred.shape)} and target {tuple(target.shape)} differ")
    return ((pred - target) ** 2).mean()
Listing 16MSE, with a check that fails on the silent broadcast from Step 3.

Cross entropy is the loss for choosing one of C classes. The model outputs a score per class, called a logit. Softmax turns scores into probabilities. The loss is the negative log probability of the right class. The direct way to write that overflows.

def log_softmax_naive(logits: torch.Tensor, dim: int = -1) -> torch.Tensor:
    """log(exp(z) / sum exp(z)). Correct on paper, overflows for logits above ~88 in float32."""
    e = logits.exp()
    return (e / e.sum(dim, keepdim=True)).log()


def log_softmax(logits: torch.Tensor, dim: int = -1) -> torch.Tensor:
    """log_softmax(z) = (z - m) - log(sum exp(z - m)), with m = max(z).

    Subtracting the max changes nothing mathematically (it cancels between
    numerator and denominator) but keeps every exp() argument <= 0.
    """
    m = logits.amax(dim, keepdim=True).detach()  # a constant shift; no gradient needed
    shifted = logits - m
    return shifted - shifted.exp().sum(dim, keepdim=True).log()
Listing 17Two versions of log softmax. Both are correct on paper. Only the second survives large logits.

The stable version uses one trick. Subtract the row maximum m first. The numerator and the denominator of softmax both get divided by exp(m), so the result does not change. But now every exp() argument is zero or negative, so it cannot overflow.

With log_softmax in hand, cross entropy is a lookup. gather picks one element from each row, at the column the target names.

def cross_entropy(logits: torch.Tensor, target: torch.Tensor, ignore_index: int = -100) -> torch.Tensor:
    """Mean negative log-likelihood of the target class.

    Shapes: logits [N, C] or [B, T, C]; target [N] or [B, T] of class ids.
    Positions whose target equals `ignore_index` contribute nothing and are
    not counted in the mean, like F.cross_entropy.
    """
    num_classes = logits.shape[-1]
    logp = log_softmax(logits.reshape(-1, num_classes), dim=-1)  # [N, C]
    target = target.reshape(-1)  # [N]
    valid = target != ignore_index
    # gather needs a real class id at every position, so park ignored ones on class 0.
    safe = torch.where(valid, target, torch.zeros_like(target))
    picked = logp.gather(dim=1, index=safe[:, None]).squeeze(1)  # [N]: log p(target)
    nll = -picked * valid
    # 0/0 = NaN when every position is ignored, which is also what F.cross_entropy returns.
    return nll.sum() / valid.sum()
Listing 18Cross entropy as log_softmax plus gather. ignore_index is what later tutorials use to skip padding.
Shapes in cross entropy (N = 4, C = 3)
TensorShapeMeaning
logits[N, C]A score per class. [B, T, C] is flattened to this.
target[N]The right class id per row. Integers, not one-hot.
logp[N, C]Log probabilities. Each row sums to 1 after exp.
safe[:, None][N, 1]The index for gather. It must have the same rank as logp.
picked[N]log p(target) for each row.
loss[]A scalar, the root of the graph.
$ .venv/bin/python c01-pytorch/scripts/04_losses.py
logits [N=4, C=3]:
 tensor([[ 2.0000,  1.0000,  0.1000],
        [ 0.5000,  2.5000, -1.0000],
        [ 1.2000,  0.2000,  3.0000],
        [ 0.0000,  0.0000,  0.0000]])
row max m [4, 1]: tensor([2.0000, 2.5000, 3.0000, 0.0000])
logsumexp [4, 1]: tensor([2.4170, 2.6532, 3.2038, 1.0986])
log_softmax [4, 3]:
 tensor([[-0.4170, -1.4170, -2.3170],
        [-2.1532, -0.1532, -3.6532],
        [-2.0038, -3.0038, -0.2038],
        [-1.0986, -1.0986, -1.0986]])
gather(1, target[:, None]) [4, 1]: tensor([-0.4170, -0.1532, -3.0038, -1.0986])
ours  : 1.1681665182113647
torch : 1.1681665182113647

Figure 6Cross entropy, tensor by tensor, on the logits and targets from the script. The numbers match the printed output. The third row is a confident wrong answer, and it costs more than the other three rows together.

Look at two rows in the output. The third row has its largest logit on class 2 but its target is class 1, so it contributes 3.0038. The fourth row has all-zero logits, so its probability is one third and it contributes ln 3 = 1.0986. That is the loss of a model that has learned nothing. For three classes, expect a first loss near 1.1. The 8-example batch in Step 14 has a loss of 1.1375. With the same initial weights, 200 shuffled batches of 64 averaged 1.107. That is what a good initial state looks like.

ignore_index needs care. Ignored rows must add nothing to the sum, and they must also leave the count. Dividing by valid.sum() does both, so padding does not shrink the loss.

== ignore_index, for padded positions ==
ours  : 0.5562735199928284
torch : 0.5562735199928284

Checkpoint

  • ours and torch print the same digits in every block.
  • You know that a useless three-class model starts near a loss of 1.1, and you check for it.
Step 10

Optimizers

Goal Write SGD and AdamW as the update rules they are, and match torch.optim to the last printed digit.

An optimizer is less than its name suggests. It holds references to parameters and some state per parameter. step() reads each p.grad and changes p in place. The simplest possible version is the four highlighted lines in this training loop:

for step in range(201):
    loss = ((x @ W + b - target) ** 2).mean()
    loss.backward()
    with torch.no_grad():  # the update is not part of the model
        for p in (W, b):
            p -= lr * p.grad
            p.grad = None  # backward adds to .grad, so clear it before the next one
    if step % 50 == 0:
        print(f"step {step:>3}: loss {loss.item():.6f}")
Listing 19Vanilla SGD on the bare W and b from Step 7, fitting a known target. There is no optimizer class yet.
== vanilla SGD on a known target ==
without no_grad -> a leaf Variable that requires grad is being used in an in-place operation.
step   0: loss 15.499691
step  50: loss 0.000610
step 100: loss 0.000000
step 150: loss 0.000000
step 200: loss 0.000000
recovered W:
 tensor([[ 1.0000, -2.0000],
        [ 0.5000,  0.0000],
        [-1.0000,  3.0000]])
true W:
 tensor([[ 1.0000, -2.0000],
        [ 0.5000,  0.0000],
        [-1.0000,  3.0000]])
recovered b: tensor([ 0.5000, -0.5000])  true b: tensor([ 0.5000, -0.5000])
largest error: W 1.19e-06  b 3.58e-07

The loop recovers the true W and b with an error near 1e-06. The first output line shows what happens without no_grad: PyTorch refuses an in-place write to a leaf that requires a gradient.

no_grad is required. The update must not be recorded, or the next backward pass would try to differentiate through it. Everything else in an optimizer class is state and bookkeeping. Here is the shared part.

class ManualOptimizer:
    """The shared part: a parameter list, per-parameter state and zero_grad."""

    def __init__(self, params: Iterable[torch.nn.Parameter]) -> None:
        self.params = [p for p in params if p.requires_grad]
        self.state: dict[torch.Tensor, dict[str, torch.Tensor | int]] = {}

    def zero_grad(self, set_to_none: bool = True) -> None:
        for p in self.params:
            if set_to_none:
                # Dropping the tensor frees memory, and the next backward
                # writes a fresh gradient instead of adding to zeros.
                p.grad = None
            elif p.grad is not None:
                p.grad.zero_()
Listing 20The base class. Setting a gradient to None frees its memory, and the next backward writes a fresh tensor.

SGD adds optional momentum and weight decay on top of the two-line update.

class SGD(ManualOptimizer):
    """p <- p - lr * g, with optional momentum and (coupled) weight decay."""

    def __init__(self, params, lr: float, momentum: float = 0.0, weight_decay: float = 0.0) -> None:
        super().__init__(params)
        self.lr, self.momentum, self.weight_decay = lr, momentum, weight_decay

    @torch.no_grad()  # the update itself must not be recorded in the autograd graph
    def step(self) -> None:
        for p in self.params:
            if p.grad is None:
                continue
            g = p.grad
            if self.weight_decay:
                g = g.add(p, alpha=self.weight_decay)  # L2 penalty folded into the gradient
            if self.momentum:
                state = self.state.setdefault(p, {})
                if "momentum_buffer" not in state:
                    state["momentum_buffer"] = g.clone()
                else:
                    state["momentum_buffer"].mul_(self.momentum).add_(g)
                g = state["momentum_buffer"]
            p.add_(g, alpha=-self.lr)
Listing 21SGD. p.add_(g, alpha=-lr) is p -= lr * g. Momentum needs one extra tensor per parameter.

AdamW keeps two running averages per parameter. The first is of the gradient. The second is of its square. The update divides one by the square root of the other, so each element gets its own step size. The theory post derives why.

Derivation inWhat an optimizer actually does
class AdamW(ManualOptimizer):
    """Adam with decoupled weight decay (Loshchilov and Hutter, 2019).

    m <- b1 m + (1 - b1) g          first moment (a running mean of g)
    v <- b2 v + (1 - b2) g^2        second moment (a running mean of g^2)
    p <- p (1 - lr wd)              decay applied to p, not mixed into g
    p <- p - lr * m_hat / (sqrt(v_hat) + eps)
    """

    def __init__(
        self,
        params,
        lr: float = 1e-3,
        betas: tuple[float, float] = (0.9, 0.999),
        eps: float = 1e-8,
        weight_decay: float = 1e-2,
    ) -> None:
        super().__init__(params)
        self.lr, self.betas, self.eps, self.weight_decay = lr, betas, eps, weight_decay

    @torch.no_grad()
    def step(self) -> None:
        beta1, beta2 = self.betas
        for p in self.params:
            if p.grad is None:
                continue
            g = p.grad
            state = self.state.setdefault(p, {})
            if not state:
                state["step"] = 0
                state["exp_avg"] = torch.zeros_like(p)  # m: same shape as p
                state["exp_avg_sq"] = torch.zeros_like(p)  # v: same shape as p
            state["step"] += 1
            t = state["step"]
            m, v = state["exp_avg"], state["exp_avg_sq"]

            p.mul_(1 - self.lr * self.weight_decay)
            m.lerp_(g, 1 - beta1)  # m + (1 - b1)(g - m) == b1 m + (1 - b1) g
            v.mul_(beta2).addcmul_(g, g, value=1 - beta2)

            # Both moments start at zero, so early averages are biased toward
            # zero. Dividing by (1 - beta^t) removes that bias.
            bias1 = 1 - beta1**t
            bias2 = 1 - beta2**t
            denom = (v.sqrt() / math.sqrt(bias2)).add_(self.eps)
            p.addcdiv_(m, denom, value=-self.lr / bias1)
Listing 22AdamW. Weight decay acts on p directly, and is not mixed into the gradient. The two bias terms correct for the averages starting at zero.
AdamW state for a parameter of shape [16, 3]
TensorShapeMeaning
p[16, 3]The parameter. Changed in place.
p.grad[16, 3]Written by backward, read by step.
state["exp_avg"], m[16, 3]Running mean of g.
state["exp_avg_sq"], v[16, 3]Running mean of g squared.
state["step"], tscalarThe step count, used for the bias correction.

Now the check. We train the same model with the same seed four times, with our optimizers and with PyTorch’s.

$ .venv/bin/python c01-pytorch/scripts/05_train.py --compare
optimizer         lr train_loss  val_loss  val_acc  time_s
manual-sgd       0.1     0.0018    0.0420    0.997    1.85
sgd              0.1     0.0018    0.0420    0.997    5.03
manual-adamw    0.01     0.0015    0.0286    0.998    1.51
adamw           0.01     0.0015    0.0286    0.998    1.58
max |train_loss(manual-sgd) - train_loss(sgd)| over 60 epochs: 0.00e+00
max |train_loss(manual-adamw) - train_loss(adamw)| over 60 epochs: 0.00e+00

The largest gap in epoch loss over 60 epochs is exactly zero, for both pairs. Our optimizers follow the same trajectory as PyTorch’s, to every digit that gets averaged into that loss.

The time column needs a warning. Torch SGD looks slow: 5.03 s against 1.85 s here, and 1.7 to 3.1 times manual SGD in four reruns. That is not the price of SGD. It looks like a one-time cost, and --compare always runs torch SGD first.

We checked by running the four optimizers in three different orders, twice each. Whichever torch optimizer ran first in the process took 3.0 to 7.2 s. Later torch optimizers took 1.3 to 2.1 s, close to ours at 1.3 to 2.7 s. We did not trace where the one-time cost comes from.

How much does readable code cost? torch.optim.AdamW has three implementations: a for-loop, a foreach version that batches operations, and a fused kernel. We time one step on 6.3 million parameters.

$ .venv/bin/python c01-pytorch/benchmarks/optimizers.py
torch 2.15.0+cu132, 8 CPU threads
6.30 M parameters in 48 tensors
impl                  cpu ms
scratchnet.AdamW        5.37
torch for-loop          7.59
torch foreach          18.12
torch fused             2.35
6.30 M parameters in 48 tensors
impl                  cpu ms    mps ms
scratchnet.AdamW       11.73      8.58
torch for-loop          8.34     11.20
torch foreach          10.00     10.94
torch fused             4.38      5.51
torch 2.15.0+cu132, 8 CPU threads
6.30 M parameters in 48 tensors
impl                  cpu ms   cuda ms
scratchnet.AdamW        4.11      3.24
torch for-loop          4.34      3.78
torch foreach          10.51      0.55
torch fused             0.96      0.23

The last block is one run on an NVIDIA H100 80GB HBM3. Its cpu ms column is that machine’s host CPU, not the EPYC server above. On CUDA, foreach goes from slowest to second fastest, at 0.55 ms. Fused takes 0.23 ms. Ours takes 3.24 ms and the for-loop 3.78 ms.

Checkpoint

  • The two max |train_loss(...)| lines print 0.00e+00.
  • You can write the AdamW update for one element on paper. Step 14 checks it.
Step 11

Dataset and DataLoader

Goal Write a dataset and two collate functions, then measure what workers and prefetching really change.

A Dataset answers two questions: how many examples are there, and what is example i? We use interleaved spirals in 2D. They are small, they are exact, and no linear model can separate them. So if we reach high accuracy, the hidden layers are doing real work.

class SpiralDataset(Dataset):
    """K interleaved spiral arms in 2D. A linear model cannot separate them.

    Example i: {"x": FloatTensor [2], "y": LongTensor [] (class id)}.
    """

    def __init__(self, points_per_class: int = 300, num_classes: int = 3, noise: float = 0.25, seed: int = 0) -> None:
        g = torch.Generator().manual_seed(seed)
        xs, ys = [], []
        for k in range(num_classes):
            r = torch.linspace(0.05, 1.0, points_per_class)
            # Each arm sweeps 7 radians (just over one turn), rotated 2pi/K from the previous arm.
            theta = torch.linspace(0, 7, points_per_class) + k * 2 * math.pi / num_classes
            theta = theta + noise * torch.randn(points_per_class, generator=g)
            xs.append(torch.stack([r * torch.sin(theta), r * torch.cos(theta)], dim=1))
            ys.append(torch.full((points_per_class,), k, dtype=torch.long))
        self.x = torch.cat(xs)  # [N, 2]
        self.y = torch.cat(ys)  # [N]
        self.num_classes = num_classes

    def __len__(self) -> int:
        return self.x.shape[0]

    def __getitem__(self, i: int) -> dict[str, torch.Tensor]:
        return {"x": self.x[i], "y": self.y[i]}
Listing 23The dataset. A dataset is only __len__ and __getitem__. All the data lives in two tensors.

A DataLoader does four jobs for each batch. It picks indices, with shuffling if you ask. Workers fetch those examples. A collate function turns a list of examples into one batch. Optionally, the batch is pinned. We will write each job ourselves.

Collate is the part you write most often. For equal-shape examples it is one torch.stack.

def collate_dicts(batch: list[dict[str, torch.Tensor]]) -> dict[str, torch.Tensor]:
    """[{"x": [2], "y": []}, ...] of length B -> {"x": [B, 2], "y": [B]}.

    This is what the default collate does for dicts of equal-shape tensors,
    written out so the step is visible.
    """
    return {key: torch.stack([example[key] for example in batch]) for key in batch[0]}
Listing 24What the default collate does for dicts of equal-shape tensors, written out so the step is visible.

Language data does not have equal shapes. Every sequence has its own length, so torch.stack fails. We pad to the longest sequence in the batch and return a mask that says which positions are real.

def pad_collate(batch: list[dict[str, torch.Tensor]], pad_id: int = 0) -> dict[str, torch.Tensor]:
    """Right-pad ragged sequences to the longest in the batch.

    Returns input_ids [B, T_max], attention_mask [B, T_max] (1 = real token),
    lengths [B], label [B]. torch.stack would fail here: shapes differ.
    """
    lengths = torch.tensor([len(ex["input_ids"]) for ex in batch])
    t_max = int(lengths.max())
    input_ids = torch.full((len(batch), t_max), pad_id, dtype=torch.long)
    for row, ex in enumerate(batch):
        input_ids[row, : len(ex["input_ids"])] = ex["input_ids"]
    # [T_max] < [B, 1] broadcasts to [B, T_max]: position t is real when t < length.
    attention_mask = (torch.arange(t_max)[None, :] < lengths[:, None]).long()
    labels = torch.stack([ex["label"] for ex in batch])
    return {"input_ids": input_ids, "attention_mask": attention_mask, "lengths": lengths, "label": labels}
Listing 25Padding collate. The highlighted lines build the mask with the broadcasting rule from Step 3.

Figure 7pad_collate on the first four examples of VarLenDataset(n=8). These are the tensors that scripts/10_data.py prints. The mask comes from one broadcast comparison.
Shapes through the data pipeline
TensorShapeMeaning
Spiral example, x[2]One 2D point.
Spiral example, y[]A class id, as a scalar long.
Spiral batch, x[B, 2]After collate_dicts.
Spiral batch, y[B]After collate_dicts.
input_ids[B, T_max]Token ids, right-padded with 0.
attention_mask[B, T_max]1 at real tokens, 0 at padding.
lengths[B]The real length of each row.

Collate was one job. Here are the other three, in SimpleDataLoader. It covers batching, shuffling, workers, prefetching and pinning, in about 90 lines.

    def _index_batches(self) -> Iterator[list[int]]:
        n = len(self.dataset)
        order = torch.randperm(n, generator=self.generator) if self.shuffle else torch.arange(n)
        for start in range(0, len(self) * self.batch_size, self.batch_size):
            yield order[start : start + self.batch_size].tolist()
    def _finish(self, batch: dict[str, torch.Tensor]) -> dict[str, torch.Tensor]:
        # Pinned pages cannot be swapped out, so the GPU can copy from them without a staging buffer.
        return {k: v.pin_memory() for k, v in batch.items()} if self.pin_memory else batch

    def __iter__(self) -> Iterator[dict[str, torch.Tensor]]:
        if self.num_workers == 0:
            for indices in self._index_batches():
                yield self._finish(self.collate_fn([self.dataset[i] for i in indices]))
        else:
            yield from self._iter_workers()
def _worker_loop(dataset: Dataset, collate_fn: Callable, tasks: mp.Queue, results: mp.Queue) -> None:
    """One worker process: take (batch_id, indices), build that batch, send it back."""
    torch.set_num_threads(1)  # N workers with M threads each would oversubscribe the cores
    while (task := tasks.get()) is not None:
        batch_id, indices = task
        try:
            results.put((batch_id, collate_fn([dataset[i] for i in indices]), None))
        except Exception:
            results.put((batch_id, None, traceback.format_exc()))
    def _iter_workers(self) -> Iterator[dict[str, torch.Tensor]]:
        results: mp.Queue = mp.Queue()
        queues = [mp.Queue() for _ in range(self.num_workers)]
        workers = [mp.Process(target=_worker_loop, args=(self.dataset, self.collate_fn, q, results), daemon=True)
                   for q in queues]
        for w in workers:
            w.start()

        todo = enumerate(self._index_batches())
        turn = itertools.cycle(queues)  # hand out work round robin

        def send_next() -> int:
            task = next(todo, None)
            if task is None:
                return 0
            next(turn).put(task)
            return 1

        in_flight = sum(send_next() for _ in range(self.num_workers * self.prefetch_factor))
        ready: dict[int, dict[str, torch.Tensor]] = {}
        next_id = 0
        try:
            while in_flight:
                while next_id not in ready:
                    batch_id, batch, error = results.get()
                    if error is not None:
                        raise RuntimeError(f"worker failed on batch {batch_id}:\n{error}")
                    ready[batch_id] = batch
                yield self._finish(ready.pop(next_id))
                next_id += 1
                in_flight += send_next() - 1
        finally:
            # Also runs when the caller breaks out of the loop early.
            for q in queues:
                q.put(None)
            for w in workers:
                w.join(timeout=5)
                if w.is_alive():
                    w.terminate()

The first three tabs are short. _index_batches makes one order per epoch and cuts it into lists of indices. Shuffling changes only that order. __iter__ fetches and collates in the main process when there are no workers. _worker_loop does the same job in a separate process: it takes a batch id and its indices, and sends the batch back.

_iter_workers holds two ideas. Workers finish in any order, so finished batches wait in the ready dict until their turn. That keeps the batch order fixed. And in_flight starts at num_workers * prefetch_factor and stays at that level, because a new task goes out only when a batch comes back. So that bound is the prefetch. It is also what stops workers from filling all of memory.

Pinning is the one line in _finish. Note a limit: our workers start fresh every epoch. PyTorch’s loader also watches for workers that die and seeds each worker, so random augmentation differs between them.

$ .venv/bin/python c01-pytorch/scripts/10_data.py
== a Dataset answers two questions ==
len(ds): 30
ds[0]: {'x': ([2], torch.float32), 'y': ([], torch.int64)}

== batching: a list of examples -> one dict of stacked tensors ==
collate_dicts of 3: {'x': [3, 2], 'y': [3]}

== shuffle: only the index order changes ==
indices, no shuffle: [0, 1, 2, 3]
indices, epoch 1   : [14, 13, 23, 27]
indices, epoch 2   : [0, 3, 2, 20]

== ours against torch.utils.data.DataLoader ==
num_workers=0: 8 batches, same batches as torch: True
num_workers=2: 8 batches, same batches as torch: True

== ragged sequences need their own collate ==
lengths: [6, 9, 7, 2]
default collate -> stack expects each tensor to be equal size, but got [6] at entry 0 and [9] at entry 1
pad_collate: {'input_ids': [4, 9], 'attention_mask': [4, 9], 'lengths': [4], 'label': [4]}
input_ids:
 tensor([[10,  5, 14,  2,  4,  8,  0,  0,  0],
        [17, 16,  2, 12, 19,  7, 11, 19, 10],
        [11, 15,  2, 11, 16, 15, 10,  0,  0],
        [18, 15,  0,  0,  0,  0,  0,  0,  0]])
attention_mask:
 tensor([[1, 1, 1, 1, 1, 1, 0, 0, 0],
        [1, 1, 1, 1, 1, 1, 1, 1, 1],
        [1, 1, 1, 1, 1, 1, 1, 0, 0],
        [1, 1, 0, 0, 0, 0, 0, 0, 0]])

Now we measure workers. Our spirals are too cheap to need any, so SlowDataset burns 2 ms of CPU per example. That stands in for decoding an image or tokenizing text.

$ .venv/bin/python c01-pytorch/benchmarks/dataloader.py
600 examples, 2 ms of CPU work each, batch 32
config                              epoch 1 s  epoch 2 s  ex/s (ep 2)
num_workers=0                            1.22       1.21          496
num_workers=2                            0.75       0.75          795
num_workers=2 persistent                 0.71       0.65          922
num_workers=4                            0.54       0.55         1089
num_workers=4 persistent                 0.46       0.34         1778
num_workers=4 persistent prefetch=4       0.50       0.34         1750
SimpleDataLoader num_workers=0           1.21       1.21          498
SimpleDataLoader num_workers=4           0.41       0.40         1508

The benchmark adds a pin_memory row only when CUDA is present. On the H100 machine, in one run, four persistent workers gave 1813 examples per second without pinning and 1771 with it. That is no difference. This benchmark pins each batch but never copies it to the GPU, so it shows only that pinning did not slow the loader down.

num_workers=4 persistent                 0.50       0.33         1813
num_workers=4 persistent prefetch=4       0.43       0.33         1804
num_workers=4 persistent pin_memory       0.70       0.34         1771
DataLoader options and what they do
OptionWhat it doesWhen to change itWhat we measured
batch_sizeExamples per collate callSet by memory and the optimizer64 in our training run
shuffleA random sampler, reseeded through generatorOn for training, off for evaluationSeeded by epoch, so a resumed run sees the same batches
collate_fnList of examples to one batchVariable shapes, or a custom batch formatThe default fails on ragged sequences
num_workersFetches in separate processesWhen __getitem__ does real work496 with none, 1778 with 4 persistent
persistent_workersKeeps workers between epochsAlmost always, with workers795 to 922 ex/s at 2 workers, 1089 to 1778 at 4
prefetch_factorBatches queued per workerWhen data arrives in bursts1778 to 1750 ex/s, no real change
pin_memoryPins each batch in a background threadWith CUDA and non_blocking=True1771 against 1813 ex/s without it, one run: no difference here

Checkpoint

  • collate_dicts gives x [B, 2] and y [B] with dtype long.
  • attention_mask.sum(1) equals lengths.
  • Your scripts that use workers have an if __name__ == "__main__" guard. On macOS and Windows, workers start by importing the file again, so the guard is required.
Step 12

The full training loop

Goal Join all the pieces into one loop, explain each line, and train the spiral model to high accuracy.

One training step is five lines. Everything else in train.py is plumbing around them.

def train_step(model, batch, optimizer, max_grad_norm: float | None = None) -> dict[str, float]:
    optimizer.zero_grad(set_to_none=True)  # 1. forget the previous step's gradients
    logits = model(batch["x"])  # 2. forward: [B, 2] -> [B, C], records the graph
    loss = cross_entropy(logits, batch["y"])  # 3. scalar loss at the root of the graph
    loss.backward()  # 4. walk the graph backwards, write p.grad for every leaf
    if max_grad_norm is not None:
        norm = manual_optim.clip_grad_norm(model.parameters(), max_grad_norm)
    else:
        norm = manual_optim.grad_norm(model.parameters())
    optimizer.step()  # 5. read p.grad, update p in place
    return {"loss": loss.item(), "grad_norm": norm.item()}
Listing 26One training step. The numbered comments are the whole algorithm.

Here is what each line does to the state of the program.

State after each line of train_step
LineGraphp.gradpOptimizer state
zero_gradNoneNone, gradients droppedOldOld
model(x)Recorded, node by nodeNoneOldOld
cross_entropyGrows to the loss, the rootNoneOldOld
loss.backward()Walked, then freedWrittenOldOld
clip or normFreedRead, maybe scaledOldOld
optimizer.step()FreedReadNewNew

Notice where p changes: in one row only. The forward pass, the loss and the backward pass do not change any weights. Only step() does.

Next come the parts that surround the step. to_device moves a batch, and evaluate measures the model without recording a graph.

def to_device(batch: dict[str, torch.Tensor], device: torch.device) -> dict[str, torch.Tensor]:
    # non_blocking only overlaps the copy with compute when the source is pinned.
    return {k: v.to(device, non_blocking=True) for k, v in batch.items()}
@torch.no_grad()
def evaluate(model, loader, device: torch.device) -> dict[str, float]:
    model.eval()  # dropout off; a model with batch norm would also switch to running stats
    total_loss, correct, n = 0.0, 0, 0
    for batch in loader:
        batch = to_device(batch, device)
        logits = model(batch["x"])
        total_loss += cross_entropy(logits, batch["y"]).item() * len(batch["y"])
        correct += (logits.argmax(-1) == batch["y"]).sum().item()
        n += len(batch["y"])
    model.train()
    return {"val_loss": total_loss / n, "val_acc": correct / n}
def build(cfg: TrainConfig):
    """Data, model and optimizer, all seeded from cfg.seed."""
    torch.manual_seed(cfg.seed)
    train_ds = SpiralDataset(cfg.points_per_class, seed=cfg.seed)
    val_ds = SpiralDataset(cfg.points_per_class, seed=cfg.seed + 1)  # same spirals, fresh noise
    device = torch.device(cfg.device)
    # Input statistics come from the training split only, and live in buffers.
    model = MLP(2, cfg.hidden, train_ds.num_classes, cfg.depth, cfg.dropout,
                mean=train_ds.x.mean(0), std=train_ds.x.std(0)).to(device)
    optimizer = build_optimizer(cfg, model.parameters())
    shuffle_gen = torch.Generator()
    train_loader = DataLoader(train_ds, batch_size=cfg.batch_size, shuffle=True, collate_fn=collate_dicts,
                              num_workers=cfg.num_workers, generator=shuffle_gen,
                              pin_memory=device.type == "cuda")  # the loader only pins for CUDA
    val_loader = DataLoader(val_ds, batch_size=512, collate_fn=collate_dicts)
    return model, optimizer, train_loader, val_loader, shuffle_gen

evaluate uses both tools from earlier steps. @torch.no_grad() stops recording, which saves memory. model.eval() turns dropout off, which changes the answer. They do different jobs, and you need both.

Finally, fit runs the epochs, and saves and resumes checkpoints.

def fit(
    cfg: TrainConfig,
    resume_from: str | Path | None = None,
    save_to: str | Path | None = None,
    on_epoch_end: Callable[[int, torch.nn.Module, dict], None] | None = None,
):
    """Train for cfg.epochs epochs (counting any already done in `resume_from`).

    Returns (model, history), where history has one dict per epoch.
    """
    model, optimizer, train_loader, val_loader, shuffle_gen = build(cfg)
    device = torch.device(cfg.device)
    start = 0
    if resume_from is not None:
        ckpt = torch.load(resume_from, map_location=device, weights_only=False)
        model.load_state_dict(ckpt["model"])
        optimizer.load_state_dict(ckpt["optimizer"])
        torch.set_rng_state(ckpt["rng"].cpu())  # map_location moved it, but this state must live on the CPU
        start = ckpt["epoch"] + 1

    history = []
    model.train()
    for epoch in range(start, cfg.epochs):
        # Seeding the shuffle by epoch makes a resumed run see the same batches.
        shuffle_gen.manual_seed(cfg.seed * 10_000 + epoch)
        losses, norms = [], []
        for batch in train_loader:
            stats = train_step(model, to_device(batch, device), optimizer, cfg.max_grad_norm)
            losses.append(stats["loss"])
            norms.append(stats["grad_norm"])
        row = {"epoch": epoch, "train_loss": sum(losses) / len(losses), "grad_norm": max(norms),
               **evaluate(model, val_loader, device)}
        history.append(row)
        if on_epoch_end is not None:
            on_epoch_end(epoch, model, row)
        if save_to is not None:
            save_checkpoint(save_to, model, optimizer, epoch, cfg)
    return model, history
Listing 27The outer loop. Reseeding the shuffle by epoch makes a resumed run see the same batches as an uninterrupted one.

A checkpoint holds the model, the optimizer and the random state. Without the optimizer state, AdamW would restart with empty averages, and the resumed run would differ from the original. The test checks this: it trains 2 epochs, resumes to 4, and compares with 4 uninterrupted epochs.

# Default run for scripts/05_train.py --config. Every key is a TrainConfig field.
optimizer: adamw
lr: 0.01
weight_decay: 0.0
epochs: 60
batch_size: 64
hidden: 64
depth: 2
dropout: 0.0
max_grad_norm: null
points_per_class: 300
num_workers: 0
seed: 0
device: cpu
Listing 28The default run. Every key is a TrainConfig field.
$ .venv/bin/python c01-pytorch/scripts/05_train.py --config c01-pytorch/configs/spiral_adamw.yaml
epoch   0  train_loss 1.0318  val_loss 0.9422  val_acc 0.479  max_grad_norm 0.622
epoch  10  train_loss 0.1007  val_loss 0.1439  val_acc 0.976  max_grad_norm 1.287
epoch  20  train_loss 0.0591  val_loss 0.0403  val_acc 0.997  max_grad_norm 0.995
epoch  30  train_loss 0.0073  val_loss 0.0312  val_acc 0.997  max_grad_norm 0.150
epoch  40  train_loss 0.0036  val_loss 0.0294  val_acc 0.998  max_grad_norm 0.087
epoch  50  train_loss 0.0023  val_loss 0.0293  val_acc 0.998  max_grad_norm 0.067
epoch  59  train_loss 0.0015  val_loss 0.0286  val_acc 0.998  max_grad_norm 0.043
60 epochs in 5.79 s on cpu

Validation accuracy reaches 0.998 in a few seconds. The validation set uses the same spirals with fresh noise. Now drag through the run and watch the regions form.

train loss
val loss
val accuracy
max grad norm

Figure 8The real run. Regions show the predicted class on a 48 by 48 grid, saved at eight epochs. Dots are a third of the training points. The numbers come from the run’s saved history on an AMD EPYC 7R13 CPU. Switch the optimizer to compare AdamW at lr 0.01 with SGD and momentum at lr 0.1.

The training curve is not smooth. AdamW’s epoch loss jumps from 0.038 at epoch 18 to 0.224 at epoch 19, and back to 0.059 at epoch 20. At this learning rate that is ordinary. It is also why we look at the whole curve, and not only the last row.

Here is the same run on CUDA, one run on an NVIDIA H100 80GB HBM3.

$ .venv/bin/python c01-pytorch/scripts/05_train.py --optimizer adamw --device cuda
epoch   0  train_loss 1.0318  val_loss 0.9422  val_acc 0.479  max_grad_norm 0.622
epoch  10  train_loss 0.1007  val_loss 0.1439  val_acc 0.976  max_grad_norm 1.287
epoch  20  train_loss 0.0591  val_loss 0.0403  val_acc 0.997  max_grad_norm 0.995
epoch  30  train_loss 0.0073  val_loss 0.0312  val_acc 0.997  max_grad_norm 0.150
epoch  40  train_loss 0.0036  val_loss 0.0294  val_acc 0.998  max_grad_norm 0.087
epoch  50  train_loss 0.0023  val_loss 0.0293  val_acc 0.998  max_grad_norm 0.067
epoch  59  train_loss 0.0015  val_loss 0.0286  val_acc 0.998  max_grad_norm 0.043
60 epochs in 4.91 s on cuda

Every printed loss and accuracy matches the CPU run above. The final train loss is 0.0015 and the validation accuracy 0.998 on both. The time is 4.91 s on the GPU against 5.79 s on the EPYC CPU. Those are different machines, so the GPU is at most a little faster here.

Here is the same model on the Apple M5 GPU, cut to 20 epochs.

epoch   0  train_loss 1.0318  val_loss 0.9422  val_acc 0.479  max_grad_norm 0.622
epoch  10  train_loss 0.1007  val_loss 0.1439  val_acc 0.976  max_grad_norm 1.287
epoch  19  train_loss 0.2243  val_loss 0.0894  val_acc 0.980  max_grad_norm 6.156
20 epochs in 17.59 s on mps

Checkpoint

  • Validation accuracy on the spirals passes 0.99.
  • You can say which line of train_step changes the weights.
  • A resumed run matches an uninterrupted one.
Step 13

Debugging

Goal Break the loop in five ways, and find each bug with hooks and checks, without editing the model.

A training bug rarely raises an error. Usually the loss just looks wrong. So we need ways to look inside a running model without editing it. PyTorch gives us hooks: functions that run at fixed points. A forward hook runs after a module’s forward and sees its output. A post-accumulate-grad hook runs during backward, right after a parameter’s .grad has been written.

We build three tools on these two hooks. Each one removes its hooks on exit, so it is safe to use in a with block.

class ActivationStats(HookSet):
    """Record mean, std and fraction of zeros of every matching module's output."""

    def __init__(self, model: nn.Module, types: tuple[type, ...]) -> None:
        super().__init__()
        self.stats: dict[str, ActStat] = {}
        for name, module in model.named_modules():
            if isinstance(module, types):
                self.handles.append(module.register_forward_hook(self._make_hook(name)))

    def _make_hook(self, name: str):
        def hook(module: nn.Module, inputs: tuple, output: torch.Tensor) -> None:
            out = output.detach().float()
            self.stats[name] = ActStat(out.mean().item(), out.std().item(), (out == 0).float().mean().item())

        return hook
class GradNormMonitor(HookSet):
    """Record each parameter's gradient norm the moment backward finishes writing it."""

    def __init__(self, model: nn.Module) -> None:
        super().__init__()
        self.record = GradRecord()
        for name, p in model.named_parameters():
            if p.requires_grad:
                self.handles.append(p.register_post_accumulate_grad_hook(self._make_hook(name)))

    def _make_hook(self, name: str):
        def hook(p: torch.Tensor) -> None:
            self.record.order.append(name)
            # Keep a tensor, not .item(): .item() would force a GPU sync inside backward.
            self.record.norms[name] = p.grad.detach().norm()

        return hook
class NaNDetector(HookSet):
    """Raise at the first module whose forward output, or parameter whose grad, is not finite."""

    def __init__(self, model: nn.Module) -> None:
        super().__init__()
        for name, module in model.named_modules():
            self.handles.append(module.register_forward_hook(self._forward_hook(name or "<root>")))
        for name, p in model.named_parameters():
            if p.requires_grad:
                self.handles.append(p.register_post_accumulate_grad_hook(self._grad_hook(name)))

    @staticmethod
    def _forward_hook(name: str):
        def hook(module: nn.Module, inputs: tuple, output) -> None:
            if torch.is_tensor(output) and not torch.isfinite(output).all():
                finite_in = all(torch.isfinite(x).all() for x in inputs if torch.is_tensor(x))
                where = "first appears in" if finite_in else "passes through"
                raise FloatingPointError(f"non-finite output {where} {name} ({type(module).__name__})")

        return hook

    @staticmethod
    def _grad_hook(name: str):
        def hook(p: torch.Tensor) -> None:
            if not torch.isfinite(p.grad).all():
                raise FloatingPointError(f"non-finite gradient for parameter {name}")

        return hook
def check_same_device(model: nn.Module, **tensors: torch.Tensor) -> None:
    """Fail early, with names, instead of deep inside a matmul."""
    devices = {p.device for p in model.parameters()}
    if len(devices) != 1:
        raise RuntimeError(f"model parameters are split across devices: {devices}")
    (model_device,) = devices
    for name, t in tensors.items():
        if t.device != model_device:
            raise RuntimeError(f"{name} is on {t.device} but the model is on {model_device}; call .to(device)")
What the tools record
ValueShapeToolWhat it tells you
Parameter normscalar per parameterparam_normsWeights growing without limit.
Gradient normscalar per parameterGradNormMonitorExploding or vanishing gradients, and the layer they start in.
Activation mean, std, zerosscalars per moduleActivationStatsDead units and collapsing signals.
Finite checkraises an errorNaNDetectorThe first module or gradient that went bad.

The first row needs no class. It is one line, read whenever you want it.

def param_norms(model: nn.Module) -> dict[str, float]:
    return {name: p.detach().norm().item() for name, p in model.named_parameters()}
Listing 29The parameter norm, for each named parameter. The other three tools are the hooks above.
$ .venv/bin/python c01-pytorch/scripts/07_break_it.py

Break 1: a learning rate of 10

    with NaNDetector(model), GradNormMonitor(model) as mon:
        try:
            for epoch in range(3):
                for x, y in batches(ds, seed=epoch):
                    opt.zero_grad()
                    loss = cross_entropy(model(x), y)
                    loss.backward()
                    worst = max(mon.record.norms, key=lambda n: mon.record.norms[n])
                    if step % 3 == 0:
                        print(f"step {step:>2}: loss {loss.item():>10.4g}  largest grad norm "
                              f"{mon.record.norms[worst].item():>9.3g} ({worst})")
                    opt.step()
                    mon.reset()
                    step += 1
Listing 30The loop from Step 12, wrapped in two debugging tools. The model and the update code are unchanged.

Break 2: forgetting zero_grad

Break 3: evaluating in training mode

Break 4: a shape mismatch

Break 5: a device mismatch

From symptom to first check
BugWhat you seeRaises an errorFirst checkFix
Learning rate too highLoss explodes, then may look normalOnly with a detectorGradient norm per layer, dead ReLUsLower the learning rate
Missing zero_gradLoss stays high, gradient norm stays highNoGradient norm over timeClear gradients each step
Missing eval()Accuracy lower and not repeatableNoTwo passes on one batchCall model.eval()
Silent broadcastLoss wrong but fallingNo, a warning in F.mse_lossShape of pred - targetMake the shapes match
Shape mismatchError at a matmulYesInner dimensions in the messageFix the input or the layer
Device mismatchError at an operationYescheck_same_device.to(device)

Read the third column. The bugs that raise an error are the cheap ones. The costly ones run to the end and report a number.

Checkpoint

  • You have run all five scenarios and read each log.
  • You can say why a finite loss does not prove a healthy model.
Step 14

From backward to step

Goal Answer the question we started with, on one real step, with every piece of state printed.

Now we have every part we need. This script runs one training step of a small MLP on 8 spiral points. It stops after each line and prints what changed. We follow one parameter closely: head.weight, of shape [16, 3].

$ .venv/bin/python c01-pytorch/scripts/06_backward_to_step.py
== 0. before anything ==
head.weight.grad: None | optimizer state entries: 0

== 1. forward ==
logits [8, 3]  loss 1.1375  graph nodes 26  leaves 6
  blocks.0.1 (ReLU) output: mean 0.164  std 0.233  zeros 56%
  blocks.1.1 (ReLU) output: mean 0.070  std 0.094  zeros 50%
still no gradients: True

== 2. loss.backward() ==
order in which .grad was written:
  0: head.bias          grad [3]      norm 0.8355
  1: head.weight        grad [16, 3]  norm 0.3892
  2: blocks.1.0.bias    grad [16]     norm 0.4576
  3: blocks.1.0.weight  grad [16, 16] norm 0.5178
  4: blocks.0.0.bias    grad [16]     norm 0.1988
  5: blocks.0.0.weight  grad [2, 16]  norm 0.0359
a second loss.backward() fails: the graph's saved tensors were freed

== 3. between backward and step ==
global grad norm 1.1695  (clip, unscale or all-reduce would happen here)
optimizer state entries: 0 (state is created lazily on the first step)

== 4. optimizer.step() ==
state keys for head.weight: {'step': 1.0, 'exp_avg': [16, 3], 'exp_avg_sq': [16, 3]}
param bytes 1484  optimizer state bytes 2968  ratio 2.0
head.weight[10, 0]: before -0.087641  grad -0.196497  after -0.077632  by hand -0.077632
|update| where grad != 0: mean 0.01000 (first step ~ lr = 0.01)  | entries with grad == 0: 24 of 48, moved by 2.5e-05

== 5. optimizer.zero_grad() ==
head.weight.grad: None | state survives: 1 step(s) recorded

Figure 9One real training step, tensor by tensor. Each heatmap is a real [16, 3] tensor saved by the script. Blue is positive and orange is negative. Each heatmap has its own colour scale, so compare patterns and not shades between panels. The outlined cell is element [10, 0], the one with the largest gradient. The batch is the first 8 examples of the dataset, unshuffled.

Walk through the output with the figure.

After the forward pass, the loss exists and the graph has 26 nodes, 6 of which are leaves. There is one leaf for each parameter tensor. Every .grad is still None. No weight has changed.

During loss.backward(), autograd walks those nodes from the loss down. The order is real, and our hook recorded it: head first, then blocks.1, then blocks.0. The graph is then freed, so a second backward() fails. Weights have still not changed.

Between the two lines, the gradients sit in .grad. Nothing is running. The optimizer has no state yet, because it creates state on the first step. This gap is where other tools do their work. Gradient clipping scales .grad here. Mixed precision unscales it here. In training across several machines, the gradients have already been averaged by now. Manual accumulation skips the step here. All of these are edits to the same tensors.

During optimizer.step(), AdamW allocates exp_avg and exp_avg_sq for each parameter, reads .grad, and writes to p in place. It never looks at the graph or the loss. It only sees p, p.grad and its own state.

The script also proves the update by hand, for the element with the largest gradient. On the first step, the bias correction cancels the (1 - beta) factors, so the update reduces to almost exactly lr × sign(g).

lr, wd, (b1, b2), eps = 1e-2, 0.01, (0.9, 0.999), 1e-8
i, j = divmod(g.abs().argmax().item(), g.shape[1])
p0, g0 = w_before[i, j].item(), g[i, j].item()
m = (1 - b1) * g0
v = (1 - b2) * g0 * g0
p_hand = p0 * (1 - lr * wd) - lr * (m / (1 - b1)) / ((v / (1 - b2)) ** 0.5 + eps)
print(f"head.weight[{i}, {j}]: before {p0:.6f}  grad {g0:.6f}  after {w[i, j].item():.6f}  by hand {p_hand:.6f}")
Listing 31The AdamW formula for one element at step 1, computed in plain Python. It must match what opt.step() did.
The tracked element, head.weight[10, 0]
QuantityValueSource
Before-0.087641Saved before the step
Gradient-0.196497Written by loss.backward()
After-0.077632Written by opt.step()
By hand-0.077632The formula above

After zero_grad, .grad is None again. The optimizer state survives, with one step recorded. The weights keep their new values. The loop is ready to run again.

So here is the answer. loss.backward() walks the recorded graph from the loss to the leaves and writes one gradient tensor per parameter. It changes no weights. optimizer.step() reads those gradient tensors and its own state, and changes the weights in place. It knows nothing of the graph. Between the two lines there is only data in .grad, waiting, and you can read or edit it.

Checkpoint

  • The after and by hand values print the same six decimals.
  • You can list what is alive at each of the five stages: graph, .grad, optimizer state.

Our code against PyTorch

Rows are the pieces we built. Columns are the file, the trusted implementation it was checked against, the evidence, and what the PyTorch version adds. Read the last column to see what you would lose by shipping the teaching version. The pattern is that the core rule is short everywhere, and PyTorch adds speed, edge cases and integration.

Each scratchnet piece and its check
PieceOur fileChecked againstResultWhat PyTorch adds
Strides and viewstensors.pytorch.empty().stride(), transpose, permute, viewEqualview that can split or merge dimensions on some non-contiguous inputs
Broadcastingbroadcasting.pytorch.broadcast_shapes, expandEqualApplied inside every operation
Matmulmatmul.pytorch.mm, bmm, matmulClose, about a million times slower per operation for the loopsTuned kernels, GPU support
Linearlayers.pynn.Linear, gradcheckClose after a transposeKaiming-style init code, a stored [out, in] layout
MSElosses.pyF.mse_lossClose. Ours rejects shape mismatchesReduction options
Cross entropylosses.pyF.cross_entropyValue and gradient closeClass weights, label smoothing, soft targets
SGDoptim.pytorch.optim.SGDLargest epoch-loss gap 0.0Nesterov, parameter groups, fused and foreach paths
AdamWoptim.pytorch.optim.AdamWLargest epoch-loss gap 0.0Fused kernel at about half the time, AMSGrad, parameter groups
Gradient clippingoptim.pyclip_grad_norm_CloseOther norms, error on non-finite
Collatedata.pyThe default collateSame shapes. Ours also padsNested structures, NumPy, more types
DataLoaderdata.pytorch.utils.data.DataLoaderSame batches, at 0 and 2 workersPersistent workers, per-worker seeds, detection of dead workers, samplers

Run everything

Here is the final folder, and the commands that produced the numbers in this post.

c01-pytorch/ final tree
c01-pytorch/
├── README.md  # how to run everything, results table
├── conftest.py  # puts scratchnet on sys.path for pytest
├── scratchnet/
│   ├── autograd_tools.py  # step 6: walk the grad_fn graph
│   ├── broadcasting.py  # step 3: the rule and stride-0 expansion
│   ├── data.py  # step 11: datasets and collate functions
│   ├── debug.py  # step 13: hooks and checks
│   ├── device.py  # step 4: pick_device, synchronize
│   ├── layers.py  # step 7-8: Linear, ReLU, Dropout, Standardize, MLP
│   ├── losses.py  # step 9: MSE, log_softmax, cross entropy
│   ├── matmul.py  # step 5: from loops to bmm
│   ├── optim.py  # step 10: SGD, AdamW, norms, clipping
│   ├── tensors.py  # step 1-2: layout record, strides, manual views
│   └── train.py  # step 12: train_step, evaluate, fit, checkpoints
├── scripts/
│   ├── 01_tensors.py
│   ├── 02_broadcasting.py
│   ├── 03_autograd.py
│   ├── 04_losses.py
│   ├── 05_train.py
│   ├── 06_backward_to_step.py
│   ├── 07_break_it.py
│   ├── 08_linear_manual.py
│   ├── 09_modules.py
│   ├── 10_data.py
│   └── 11_matmul.py
├── benchmarks/
│   ├── dataloader.py
│   ├── matmul.py  # step 5: from loops to bmm
│   ├── optimizers.py
│   └── transfer.py
├── configs/
│   └── spiral_adamw.yaml  # the default run
├── results/  # captured outputs of every script and benchmark
└── tests/
    ├── test_autograd.py
    ├── test_data_train_debug.py
    ├── test_gpu.py
    ├── test_layers_losses.py
    ├── test_optim.py
    └── test_tensors.py
$ .venv/bin/python -m pytest c01-pytorch -m "not slow and not gpu"
$ .venv/bin/python c01-pytorch/scripts/01_tensors.py
$ .venv/bin/python c01-pytorch/scripts/02_broadcasting.py
$ .venv/bin/python c01-pytorch/scripts/11_matmul.py
$ .venv/bin/python c01-pytorch/scripts/03_autograd.py
$ .venv/bin/python c01-pytorch/scripts/08_linear_manual.py
$ .venv/bin/python c01-pytorch/scripts/09_modules.py
$ .venv/bin/python c01-pytorch/scripts/04_losses.py
$ .venv/bin/python c01-pytorch/scripts/10_data.py
$ .venv/bin/python c01-pytorch/scripts/05_train.py --config c01-pytorch/configs/spiral_adamw.yaml --export c01-pytorch/results/run_adamw.json
$ .venv/bin/python c01-pytorch/scripts/05_train.py --optimizer sgd --export c01-pytorch/results/run_sgd.json
$ .venv/bin/python c01-pytorch/scripts/05_train.py --compare
$ .venv/bin/python c01-pytorch/scripts/07_break_it.py
$ .venv/bin/python c01-pytorch/scripts/06_backward_to_step.py c01-pytorch/results/head_weight_trace.json
$ .venv/bin/python c01-pytorch/benchmarks/transfer.py
$ .venv/bin/python c01-pytorch/benchmarks/matmul.py
$ .venv/bin/python c01-pytorch/benchmarks/optimizers.py
$ .venv/bin/python c01-pytorch/benchmarks/dataloader.py
$ .venv/bin/python -m pytest c01-pytorch -m gpu
# On the CUDA machine:
$ .venv/bin/python c01-pytorch/benchmarks/transfer.py --device cuda
$ .venv/bin/python c01-pytorch/scripts/05_train.py --optimizer adamw --device cuda
$ .venv/bin/python c01-pytorch/scripts/07_break_it.py device
# On the Apple M5 only:
$ .venv/bin/python c01-pytorch/benchmarks/transfer.py --device mps
$ .venv/bin/python c01-pytorch/scripts/05_train.py --device mps --epochs 20

Three checks use short extra loops that are not in the repo: the every-step trace at lr=10 in Step 13, the first-use timing in Step 10, and the 200 shuffled batches in Step 14. Each one takes a few lines on top of the code above. The reruns we quote are repeats of these commands, on the same AMD EPYC 7R13.

On the AMD EPYC server, all 50 offline tests passed. The six gpu tests need CUDA. They passed in one run on an NVIDIA H100 80GB HBM3. The transfer benchmark needs CUDA or MPS. On a CPU-only machine it prints a message and exits. Captured outputs of every run are in results/.

Key insights and nuances

Exercises

  1. Complete view_manualHard PyTorch’s view also works on some non-contiguous tensors, when the dimensions you split or merge have strides that line up. Extend view_manual to cover those cases. Write a test that compares it with Tensor.view on random slices and permutes, including the error cases.
    Hint

    Group old and new dimensions into chunks with equal products. A chunk of old dimensions can be merged only if each stride equals the next stride times the next size.

  2. Measure a real GPUEasy Run benchmarks/transfer.py, matmul.py and optimizers.py on your own CUDA machine, a few times each. Compare them with the single H100 run here. At what size does pinned memory start to matter? Where does the GPU stop winning at matmul? Then run the six GPU-only tests.
  3. Compare Adam with L2 and AdamWMedium Add an AdamL2 class that adds wd * p to the gradient, as our SGD does. Match it against torch.optim.Adam. Then train the spiral model with both at a high weight decay and compare the parameter norms.
    Hint

    Use param_norms from debug.py at each epoch. The theory post on optimizers says what to expect.

  4. Add BatchNormMedium Write a BatchNorm1d module with running statistics as buffers. Match nn.BatchNorm1d in both modes. Then repeat Break 3 and see how much worse a forgotten eval() becomes.
  5. Find dead units automaticallyMedium Extend ActivationStats to count units that are zero for every example in a batch. Run it on the lr=10 scenario. At which step does the first layer stop being useful? Can a warmup schedule keep the units alive?
    Hint

    For an output of shape [B, D], use (out == 0).all(dim=0).

Continue reading

References

Grouped by topic. Every entry links to its primary source.

Tensors and PyTorch

Autograd

Regularisation and optimizers

Code