All courses

The LLM training loop

Write the loop: sample a batch of token windows, forward, cross-entropy loss, backward, optimizer step, zero gradients. Explain what each line does to the parameters.

Builds on: Shifted targets and parallel training, Backpropagation as reverse-mode autodiff, Stochastic minibatch gradients, The decoder-only transformer, end to end

▶ Watch this lesson Start the whole course

What the animation says

Six moves, every step

Training a language model is one short loop, run millions of times. Each pass makes six moves, always in this order. Sample: grab a batch of random windows of text. Forward: the model turns them into logits, a score for every vocabulary token at every position. Loss: measure how little probability went to the true next tokens. Backward computes a gradient for every parameter. Step nudges the parameters. Zero clears the gradients. Exactly one of these six moves changes the weights. Tap it.

Score one prediction

Each window holds T plus one tokens. The inputs are the first T, and the targets are the same tokens shifted by one. The loss averages over every position in the batch. Zoom into one: three-token vocabulary, logits two, one, zero. The true token is the middle one. Softmax gives about point six six five, point two four five, point zero nine. The loss is minus log of point two four five: about one point four one. Backward gives the gradient on the logits: probabilities minus the one-hot target. Treat the logits as parameters and subtract that gradient, learning rate one. Which logits go up?

The step lands

Only the true token's logit went up, from one to about one point seven five. The others dropped, to one point three four and minus point zero nine. Its probability climbs from point two four five to point five five one. The loss falls from one point four one to point six. Notice the split. Backward computed the gradient, at about twice the cost of the forward pass, and changed nothing. The step applied it: theta minus learning rate times gradient. Fancier optimizers change only that one line.

The loop in PyTorch

Here's the whole loop. A tiny stand-in model replaces the transformer, and the loop doesn't change. The data counts zero to forty-nine, over and over, so the next token is always one more. These three lines sample: window starts, inputs, and targets shifted by one. Then forward, and cross-entropy averaged over every position. Backward fills the gradients. Step changes the weights. Zero grad clears the gradients. The loss falls from about four toward zero. Now move zero grad up, between backward and step. What happens?

Where zero_grad may go

The weights never move. Zero grad wiped the gradients, so step had nothing to apply. The loss sits near four. The rule: zero grad goes before backward or after step, never between them. Why clear at all? Because backward doesn't overwrite the gradient buffer. It adds into it. Watch one weight with no zero grad. Batch one writes point four. Batch two computes point two five, and the buffer now holds point six five. Step uses that stale sum. No error, no warning. Training just quietly goes wrong.

What actually runs at each training step?

You already have the pieces. A forward pass gives logits for all $T$ positions, cross-entropy scores them, backprop gives gradients, and gradient descent moves parameters. So what is the loop that turns a pile of text into trained weights? What runs each step, in what order, and which line actually changes $\theta$? Get the order wrong and training breaks silently, with no error message.

Six moves, repeated millions of times

1. **Sample**: grab $B$ random windows of $T{+}1$ consecutive tokens. Inputs are the first $T$, targets the last $T$. 2. **Forward**: compute logits `[B, T, V]`. 3. **Loss**: average $-\log$ prob of each true next token over all $BT$ positions. 4. **Backward**: fill a gradient buffer for every parameter. Weights are untouched. 5. **Step**: nudge each parameter against its gradient. 6. **Zero**: clear the buffers, because backward *adds* into them.

The loss and the update, precisely

$$\mathcal{L}_{\text{batch}}=-\frac{1}{BT}\sum_{b=1}^{B}\sum_{t=1}^{T}\log p_\theta\big(x^{(b)}_{t+1}\mid x^{(b)}_{\le t}\big)$$ $$\theta\leftarrow\theta-\eta\,\nabla_\theta\mathcal{L}_{\text{batch}}$$ - Window $b$ holds tokens $x^{(b)}_1,\dots,x^{(b)}_{T+1}$. - $\eta$ is the learning rate. - The backward pass computes $\nabla_\theta\mathcal{L}_{\text{batch}}$, costing about 2× the forward pass. - The step applies the update. This is plain minibatch SGD. Fancier optimizers change only the update line.

One step on one prediction

Take $V=3$, logits $z=[2,1,0]$, and true next token = id 1 (ids start at 0, so it is the middle entry). - $p=\text{softmax}(z)\approx[0.665,\,0.245,\,0.090]$, so the loss is $-\ln 0.245=1.41$. - Gradient w.r.t. logits: $p-\text{onehot}=[0.665,\,-0.755,\,0.090]$. - Treat $z$ as the parameters and take a step with $\eta=1$: $z\to[1.335,\,1.755,\,-0.090]$. - Now $p_1=5.78/10.50=0.551$, so the loss is $0.60$. The step raised the true token's logit and lowered the others.

The loop in PyTorch

**Order rule:** `zero_grad()` goes before `backward()` or after `step()`, never between them. Between them it would wipe the gradients before `step()` uses them, so $\theta$ never moves. Skip it entirely and the bug is silent. After two batches, a weight's `.grad` holds $g_1+g_2$, not $g_2$. Each comment gives the move number from the six-move card. Only move 5 changes $\theta$. A stand-in model replaces the transformer, and the loop is identical for a real one. The data cycles 0, 1, …, 49, 0, 1, …, so the next token is always the current one plus 1. The model can learn this, and the printed loss falls from about 4 toward 0.
import torch, torch.nn as nn, torch.nn.functional as F
V, d, T, B, eta = 50, 16, 8, 4, 0.5
data = torch.arange(10_000) % V    # 0,1,…,49,0,1,…: next = current+1
model = nn.Sequential(nn.Embedding(V, d), nn.Linear(d, V))  # stand-in
opt = torch.optim.SGD(model.parameters(), lr=eta)
for step in range(301):
    i = torch.randint(0, len(data) - T, (B,))      # 1 sample: window starts
    x = torch.stack([data[j:j+T] for j in i])      # 1 inputs  [B, T]
    y = torch.stack([data[j+1:j+T+1] for j in i])  # 1 targets [B, T], shifted
    z = model(x)                                   # 2 forward: logits [B, T, V]
    loss = F.cross_entropy(z.reshape(-1, V), y.reshape(-1))  # 3 mean over B*T
    loss.backward()     # 4 backward: fills .grad only, weights untouched
    opt.step()          # 5 step: the only line that changes θ
    opt.zero_grad()     # 6 zero: clear .grad (backward adds into it)
    if step % 100 == 0: print(step, round(loss.item(), 2))

Remember this

Each step: sample $B$ windows → forward → mean cross-entropy over $BT$ predictions → backward (fills gradients only) → step (the only line that changes $\theta$) → zero gradients (backward accumulates). Repeat.

On Bytewise this lesson comes in small steps with a check at the end, and the app brings it back right before you would forget it.