Sub topic 9
Pretraining: Cross-Entropy Loss and Gradient Descent
This chapter assumes you can read basic Python and NumPy, multiply matrices, and know what a probability distribution is. It also assumes you know a neural network is a function with adjustable numbers called weights. Earlier chapters covered how the decoder-only model turns token IDs into a probability distribution over the next token. Here we cover how it learns to make that distribution good.
The training signal comes free from the text
Pretraining needs no human labels. Any text already contains the answers: the label for each position is the token that comes next. Take the token sequence [the, cat, sat, on]. The model sees the and should predict cat. It sees the cat and should predict sat. It sees the cat sat and should predict on.
A decoder-only model with a causal mask computes all of these predictions in one forward pass. The inputs are tokens[:-1] and the targets are tokens[1:]. This is called teacher forcing: at every position the model is given the true previous tokens, not its own earlier guesses.
Cross-entropy loss
At each position the model outputs one logit per vocabulary entry. Softmax turns the logits into probabilities. The loss at that position is the negative log of the probability the model gave to the true next token:
loss = -log p(correct token)
Averaging over all positions in the batch gives the cross-entropy loss. The behavior is intuitive:
- If the model gives the correct token probability 1.0, the loss is 0.
- If it gives probability 0.5, the loss is about 0.69.
- If it gives probability 0.01, the loss is about 4.6.
The log makes confident wrong answers very expensive, and the loss is never negative.
import numpy as np
def next_token_loss(logits, targets):
# logits: (seq_len, vocab_size), targets: (seq_len,) of token IDs
shifted = logits - logits.max(axis=-1, keepdims=True)
log_probs = shifted - np.log(np.exp(shifted).sum(axis=-1, keepdims=True))
return -log_probs[np.arange(len(targets)), targets].mean()
logits = np.array([[2.0, 0.5, 0.1], [0.2, 1.5, 0.3]])
targets = np.array([0, 1])
print(next_token_loss(logits, targets))This prints about 0.385. The function never builds probabilities and takes a log afterward. It computes log-probabilities directly, after subtracting the row maximum. Subtracting the maximum keeps exp from overflowing. Working in log space avoids log(0) when a probability underflows.
Useful reference points
- Starting loss. A model with random weights spreads probability roughly evenly, so its loss starts near
ln(V), whereVis the vocabulary size. For a 50,000-token vocabulary that is about 10.8. If your first step prints something far from this, suspect a bug. - Perplexity.
exp(loss)is the perplexity. It can be read as the number of equally likely tokens the model is effectively choosing between at each step. - A floor above zero. Text is not fully predictable. After "I went to the" many words are plausible, so even a perfect model has a loss above zero. This floor is the entropy of the text itself.
Gradient descent
The loss is a function of every weight in the model. Backpropagation applies the chain rule backward through the network and gives the gradient: for each weight, how much the loss would change if that weight increased slightly. Gradient descent moves each weight a small step against its gradient:
w = w - learning_rate * gradient
The gradient of the cross-entropy loss with respect to the logits has a simple form: softmax(logits) - one_hot(target). Each wrong token's logit is pushed down in proportion to the probability it was given. The correct token's logit is pushed up in proportion to how much probability it was missing.
The next example trains the smallest possible language model, a table of logits indexed by the previous token (a bigram model). It uses this exact gradient. The same loop structure drives the training of a transformer, with a far bigger function in the middle.
import numpy as np
def softmax(z):
z = z - z.max(axis=-1, keepdims=True)
e = np.exp(z)
return e / e.sum(axis=-1, keepdims=True)
data = np.array([0, 1, 2, 0, 1, 2, 0, 1, 0, 1])
inputs, targets = data[:-1], data[1:]
V = 3
W = np.zeros((V, V)) # row i = logits for the token that follows token i
lr = 0.5
rows = np.arange(len(targets))
for step in range(101):
probs = softmax(W[inputs])
loss = -np.log(probs[rows, targets]).mean()
if step % 25 == 0:
print(step, round(float(loss), 4))
grad_logits = probs.copy()
grad_logits[rows, targets] -= 1 # softmax minus one-hot
grad_logits /= len(targets) # matches the mean in the loss
grad_W = np.zeros_like(W)
np.add.at(grad_W, inputs, grad_logits) # sum gradients for repeated rows
W -= lr * grad_WStep 0 prints 1.0986, which is ln(3), because zero weights give a uniform guess over three tokens. The loss then falls. It cannot reach zero. In this data, token 1 is followed by 2 twice and by 0 once, so no table can predict it perfectly. The lowest achievable loss is about 0.212, the entropy of the data. A transformer faces the same limit on real text.
What changes at LLM scale
The loop above is the whole idea. Real pretraining adds engineering around it.
- Batches. Each step averages the loss over a large batch, often millions of tokens. This gives a less noisy gradient than a single example.
- Optimizer. Plain gradient descent is rarely used. AdamW keeps running averages of each weight's gradient and squared gradient, which scales each weight's step size automatically. It also applies weight decay, a small pull of weights toward zero.
- Learning rate schedule. The rate usually warms up from near zero over the first few thousand steps. It then decays, often along a cosine curve. A rate that is too high at the start can wreck training before the model has learned anything useful.
- Gradient clipping. If the gradient's overall norm exceeds a threshold, it is scaled down. This guards against rare huge updates.
- Mixed precision. Most computation runs in 16-bit or lower-precision numbers for speed and memory. Some quantities, such as the optimizer state, stay in 32-bit.
- Distributed training. The model and the batch are split across thousands of accelerators. Gradients are combined across devices at every step.
- Data. Text is deduplicated, filtered, and mixed from many sources. It is split into sequences up to the context length, with documents separated by a special end-of-text token.
Watching training
Teams track the loss on a held-out validation set that never appears in training. If training loss keeps falling while validation loss rises, the model is overfitting. Occasionally the loss suddenly spikes during a run. Common responses are to restart from an earlier checkpoint, skip the offending batches, or lower the learning rate.
Lower loss generally means better next-token prediction, and it correlates with better performance on downstream tasks. It does not guarantee that the model is truthful, helpful, or safe. The next chapters on post-training address those gaps.
Common errors
| Mistake | Symptom | Fix |
|---|---|---|
| Not shifting targets by one | Loss drops to near zero immediately, because the model copies its input | Use `tokens[1:]` as targets for `tokens[:-1]` |
| Computing `log(softmax(x))` naively | `nan` or `inf` loss | Subtract the max and use log-sum-exp |
| Forgetting the causal mask | Same near-zero loss, and the model is useless at generation time | Mask future positions in attention |
| Averaging loss over padding tokens | Loss values depend on batch composition | Mask padded positions out of the loss |
| Wrong gradient scale | Learning rate seems far too large or small | Divide by the number of positions if the loss uses a mean |
| Comparing loss across tokenizers | A model with a larger vocabulary looks better or worse for no real reason | Compare in bits per byte of raw text |
| Validation text overlapping training text | Validation loss looks suspiciously good | Deduplicate across the splits |
Summary of the working model
Pretraining turns raw text into a supervised problem. Every position has a known target, the cross-entropy loss measures the probability assigned to it, and backpropagation plus an optimizer nudges the weights to raise that probability. Repeated over trillions of tokens, this single objective forces the network to absorb grammar, facts, and patterns of reasoning, because all of them help predict what comes next.
Exercise
A model with a 32,000-token vocabulary has random weights. Roughly what loss should you see at step 0, and what does it mean if you see 0.05 instead?
Show answer
The loss should be near ln(32000), about 10.4, because the predicted distribution is close to uniform. A loss of 0.05 at step 0 almost certainly means a bug, such as targets not shifted by one position or a missing causal mask, so the model can see the answer.
Exercise
In the bigram example, why does the loss never go below about 0.212, no matter how many steps you run?
Show answer
Token 1 is followed by token 2 in two cases and by token 0 in one case, so the next token after 1 is genuinely uncertain. The best possible model predicts probabilities 2/3 and 1/3 there, which leaves an irreducible loss equal to the entropy of the data, about 0.212 averaged over all positions.
Exercise
The gradient of the cross-entropy loss with respect to the logits at one position is softmax(logits) minus the one-hot target vector. If the model assigns probability 0.9 to the correct token, what is the gradient for that token's logit, and what does its sign mean?
Show answer
It is 0.9 - 1 = -0.1. A negative gradient means that increasing this logit would lower the loss, so gradient descent raises it, but only slightly because the model is already mostly right.