Tokenwerk · The LLM textbook

Chapter 20 · IV · Training and evaluating · 6 minutes

Reading the loss and finding bugs

The learning curve goes down. Great? Not necessarily. Here you learn to read loss curves like a doctor reads an ECG, and to use targeted tests to find out whether your model is learning, just cramming or cheating.

Four curves, four stories

During training you watch two curves: the error on the training data and the error on the validation data. How they play together tells you a lot:

  • Both stay high: the model hasn't learned much yet. Too little training, wrong learning rate, too small a model, or a bug in the code.
  • Training drops, validation rises: the model is cramming the training texts instead of learning patterns. That is called overfitting, like someone who memorizes old exams and fails on new questions.
  • Both are suspiciously good right from the start: alarm! The model can probably cheat; the answer is hidden somewhere in the input, or test and training data overlap.
  • Both drop: good sign! But not yet proof of good answers. The loss is an average over all tokens. A model can predict filler words like “the” and “and” excellently and still get the one important fact question wrong.

The figure shows schematic example curves, not real measurements. The project writes your real values to metrics.jsonl later.

The most important test: memorize one batch

Sounds paradoxical, but it is gold: take a single small batch and train on it over and over. A working model must manage to memorize these few examples; the loss should drop almost to zero. If it doesn't, there is a bug somewhere in the data path or the optimization. Here overfitting is explicitly what you want.

But beware of fooling yourself: passing the memorization test only shows that the system can learn in principle. It doesn't show that it generalizes. Calling that batch “validation” afterwards would be cheating.

Debugging in the right order

When something doesn't work: don't immediately make the model bigger! Check in this order:

  1. Raw text and tokenizer: does the round trip give back the same text?
  2. Input and target: is the target shifted by exactly one token?
  3. Shapes, number of targets and the peeking test from chapter 16.
  4. Only then: optimizer, learning rate, model size.

That way you avoid burying a data bug under ever larger networks. A target shifted by two instead of one makes learning hard; an unshifted one makes it suspiciously easy. Both show up at step 2.

When NaN shows up

NaN (“not a number”) in the loss isn't a normal state but an emergency. Look for the first spot where a broken number appears. Typical suspects: invalid token IDs, an attention row where everything is forbidden, a division by zero, or a learning rate so large that the weights explode.

python
if not torch.isfinite(loss):
    raise RuntimeError('Non-finite loss; run stopped.')
for name, p in model.named_parameters():
    if p.grad is not None and not torch.isfinite(p.grad).all():
        print('Non-finite gradient:', name)

Important: stop immediately! If you keep training with NaN, you may overwrite the last good checkpoint with garbage.

Good loss, bad texts

Training looks great, but the generated texts are rubbish? First check the input: how does the tokenizer actually split your prompt? A pure text model (a base model) continues text; it doesn't know it is supposed to answer a question. And look at the temperature: if it is too high, unsuitable tokens get drawn too.

Compare fairly: fixed prompts, fixed seed, several attempts. The nicest example out of a hundred attempts is not a quality measurement. And swapping out the worst prompt after every change is fooling yourself.

A bit of a gap is normal

The training loss is almost always lower than the validation loss. Makes sense: the model was optimized on the training data. What is interesting is how big the gap is and how it develops. If it keeps growing, that may be overfitting, or the data differs, or there are duplicates. “Overfitting!” is a hypothesis at first, one you have to check.

Keeping randomness in check

A fixed seed makes experiments more comparable. But on different computers or graphics cards, slightly different numbers can still come out. If two variants do almost equally well, try several seeds. Otherwise you will mistake a random order for a law of nature.

Your measurement log

For every run, write down: which checkpoint, which tokenizer, which data, which configuration, how many tokens were processed, training and validation loss, how validation was done, runtime and a few fixed example texts. For answer models, criteria for content quality come on top.

A simple text file with one line per measurement is completely enough. You don't need a fancy tracking platform before your first model even manages a sentence. That is why the project simply writes its measurements to a local file.

What to do for which finding?

Finding First sensible check
Loss unchanged Are weights learning? Are gradients present?
Almost perfect loss from the start Input/target identical? Future visible?
NaN after a few steps Learning rate, norms, first non-finite operation
Only training improves Data split, amount of data, early stopping
Good losses, bad answers Target distribution, chat format, separate evaluation

Golden rule: only ever change one thing at a time. If you turn three things at once, you won't know afterwards what helped.

Key points

  • Read the training and validation curves together: both high, drifting apart, suspiciously good, or both falling.
  • The memorization test with one batch checks whether the system can learn at all.
  • Hunt for bugs from front to back: data, shift, mask; only then learning rate and size.