Tokenwerk · The LLM textbook

Chapter 19 · IV · Training and evaluating · 7 minutes

Your first training loop

The big moment: the model learns! Draw examples, predict, compute the error backwards, adjust the weights, thousands of times over. Plus a few pro tricks so it doesn't derail along the way.

You already know the loop

Remember chapter 7? Compute a prediction, measure the error, compute the slopes backwards, turn the dials a bit downhill. That is exactly what happens now, just with text examples instead of numbers and with millions of dials instead of one. Only the organization around it is new: which examples come when? How big are the steps? When do we save a checkpoint?

The part that turns slopes into actual changes is called the optimizer. Our simple “learning rate times slope” step already was one. In practice people mostly use AdamW. It is smarter: for every dial it remembers what the slopes looked like recently and adjusts the step size for each dial individually. Like a hiker who remembers where the ground was slippery. On top of that, it pulls all weights a tiny bit toward zero at every step (weight decay), so none of them gets needlessly large.

You can try out below how much such a memory matters. The map shows a loss that depends on only two dials; the point walks downhill as in the gradients chapter. The momentum slider lets it remember its last steps, one of the ingredients of AdamW. Turn the learning rate up until the point flies off, and see where momentum helps and where it hurts.

A batch: many tasks at once

In each step the trainer draws several random starting points from the long chain of tokens: B of them, for example 8. From each starting point it takes a window of T+1 tokens. The first T are the input, the last T the target: the target shift from chapter 14. All windows are the same length, so no padding is needed.

python
starts = rng.integers(0, len(data) - context, size=batch_size)
chunks = np.stack([data[i:i+context+1] for i in starts])
x = torch.from_numpy(chunks[:, :-1].copy()).long().to(device)
y = torch.from_numpy(chunks[:, 1:].copy()).long().to(device)

Obviously the data has to be longer than a window. A good trainer checks that right at the start and says so clearly instead of crashing mysteriously.

Five lines that do it all

python
optimizer.zero_grad(set_to_none=True)
logits = model(x)
loss = F.cross_entropy(logits.reshape(-1, V), y.reshape(-1))
loss.backward()
optimizer.step()

This is the heart of every training run, even for the really big models. Line by line: clear old slopes, compute forward, measure the error, compute backward, adjust the dials. Done. The rest of the trainer is safety gear: warnings for broken numbers, a well-planned learning rate, checkpoints and honest tests.

Learning rate and warmup

A fixed learning rate can be perfectly fine for small models. Our trainer is a bit more refined, in two phases:

Warmup: at the start, the learning rate rises slowly. The starting values are random, and the optimizer also has to gather experience first. Set off carefully instead of sprinting, like warming up before sports.

Cooldown: afterwards the learning rate drops gradually along a smooth curve (a cosine schedule). Big steps at the beginning to make fast progress, small steps toward the end to settle into the valley. Our hiker in the fog gets more careful just before reaching the goal.

Important: this plan is tied to the planned total number of steps. If you continue a run and change the total, you also change the rest of the plan. And the experiment only shows the planned learning rate, not actual learning progress; a pretty curve proves nothing.

The learning rate plan in detail

s is the number of the current step (from 0), SS the planned total, WW the number of warmup steps. During warmup the rate grows in proportion to (s+1)/W(s+1)/W. After that a progress value between 0 and 1 is computed, and the rate follows half a cosine curve from the maximum down to a minimum value.

Big batch, small memory

What if a big batch doesn't fit into memory? Then you compute several small portions (microbatches) forward and backward one after another and collect the slopes before moving the dials once. That is called gradient accumulation. Each portion only counts proportionally, which is why its loss is divided by the number of portions.

python
optimizer.zero_grad(set_to_none=True)
for _ in range(accum_steps):
    x, y = get_batch()
    loss = F.cross_entropy(model(x).reshape(-1, V), y.reshape(-1))
    (loss / accum_steps).backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
optimizer.step()

Example: 2 texts per portion, 4 tokens each, 3 portions: that makes 24 tokens per optimizer step. Memory only ever has to hold one portion at a time.

Emergency brake: gradient clipping

Sometimes a slope is suddenly huge: a cliff in the terrain. A normal step would then catapult the model far away and break a lot. Gradient clipping is the emergency brake: you measure the total length of all slopes together (the gradient norm). If it is bigger than a threshold, here 1.0, everything is shrunk together so the length hits the threshold exactly. The direction stays; only the step gets shorter.

But: clipping is a seatbelt, not a repair. If almost every step has to be braked or NaN values show up, something fundamental is wrong; check the learning rate, data or starting values. And the brake is applied only after all portions have been collected, not after each one.

A concrete run

In step 5 of part VII you train your own model with 2000 steps, 32 texts per batch and 128 tokens per text. A quick calculation: 32 × 128 = 4096 tokens per step, times 2000 steps that is about 8 million processed tokens. TinyStories has 5.5 million tokens, so the model sees each token about one and a half times. With a small text of 100,000 tokens it would be 80 times, and memorizing would become a real topic.

How long that takes depends heavily on your computer. Simply measure how many tokens per second go through. Blanket time estimates would be guesswork.

Checking honestly along the way

Regularly, the trainer measures the error on the validation data: the texts the model never gets to learn from. For that it switches to evaluation mode, computes without gradients and uses its own random number generator so the check doesn't change the course of training.

Because it only checks a few windows, it calls the result an estimated validation loss. For a final evaluation you check the entire validation set using a fixed procedure.

Saving checkpoints and continuing

A trainer should regularly save a checkpoint. The minimum: the state with the best validation result so far. That is exactly what your own train.py in part VII does.

Anyone who trains for a long time wants to be able to continue after a crash. For that, more has to go into the save game: model, configuration, tokenizer, optimizer, step count and the states of the random number generators (RNG). And saving is atomic: first into a helper file, then swapped in one go. If the computer crashes while saving, the old state is still intact. The reference project in the download can do this; on the same hardware a resumed run then continues very much like an uninterrupted one.

Key points

  • Training = five lines in a loop: clear gradients, forward, loss, backward, optimizer step.
  • AdamW adjusts the step size per dial. Warmup and slow cooldown make training more stable.
  • Gradient clipping is the emergency brake, checkpoints are save games, validation is the honest check along the way.