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
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.
Six moves, repeated millions of times
The loss and the update, precisely
One step on one prediction
The loop in PyTorch
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
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.
Bytewise
All courses