Backprop a deep tanh chain with gradient checkpointing

HardAutogradPro

Why it matters Fine-tuning large language models on one GPU usually depends on activation checkpointing.

Gradient checkpointing saves memory by storing only some activations and recomputing the rest during the backward pass.

Write checkpointed_backward(x, Ws, k). The network is h_0 = x (shape (n, d)) and h_{l+1} = tanh(h_l @ Ws[l]) for l = 0..L-1, with loss = sum(h_L). In the forward pass keep only checkpoints h_l for l = 0, k, 2k, ... (l < L). In the backward pass, process segments from last to first: recompute that segment's activations from its checkpoint, then backprop through it. Return (dx, dWs, peak) where dx = d loss / d x, dWs is the list of gradients for each W, and peak = number of checkpoints + length of the longest segment (the most activations held at once).

Signaturedef checkpointed_backward(x, Ws, k)

Example

one layer, x = [[0]], Ws = [[[1]]], k = 1 gives dx [[1.0]], dWs [[[0.0]]] and peak 2.

Understand the idea

Backprop normally keeps every layer's activation in memory, which is what runs out first on big models. Checkpointing keeps only every k-th activation. When the backward pass needs the ones in between, it recomputes them from the nearest saved one. You trade a second forward pass for much less memory, like writing down only every tenth page number and re-counting from there when needed.

Tiny example: 5 layers, k = 2. Checkpoints at layers 0, 2, 4: 3 stored. Segments are [0, 2), [2, 4), [4, 5), longest 2. Peak is 3 + 2 = 5 activations instead of 6.

Rule: memory is about L / k + k, smallest when k is near sqrt(L). The gradients are identical to normal backprop.

PyTorch's checkpoint utility and the gradient_checkpointing flag in Hugging Face models do exactly this per transformer block.

Shapes and data flow

h_l (n, d); W_l (d, d); checkpoints at l = 0, k, 2k, ...
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: examplecheckpointed_backward([[0.0]], [[[1.0]]], 1)
  • Sample 2: five layers k=2R(checkpointed_backward(X, WS, 2))