Sub topic 9
Pretraining: Cross-Entropy Loss and Gradient Descent
This chapter assumes you can read basic Python, multiply matrices, and understand a probability distribution. It also assumes you know what a decoder-only model outputs: a vector of logits (raw scores), one per vocabulary entry, at every position.
The pretraining objective
Pretraining teaches the model to predict the next token. Take a text, convert it to token IDs, and at each position ask the model for a distribution over the next token. The target is the token that actually came next in the text.
For a sequence of tokens t1 ... tN, the model sees t1 ... t(i-1) and is scored on how much probability it gave to t(i). Because the target is simply the next token in the text, no human labeling is needed. The text supervises itself.
Cross-entropy loss
The loss for one position is the negative log of the probability assigned to the correct token:
loss = -log p(correct token)
If the model gives the right token probability 1.0, the loss is 0. If it gives 0.01, the loss is about 4.6. The loss grows sharply as the model becomes confidently wrong. The training loss is the average over all positions in a batch.
To get probabilities, logits are passed through softmax. The code below does this in log space and subtracts the maximum logit first. That avoids overflow when exponentiating large numbers.
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))Each row of logits is one position. The expression log_probs[np.arange(len(targets)), targets] picks, for each row, the log probability of the correct token. The mean of the negatives is the loss.
A model that guesses uniformly over a vocabulary of size V has loss log V. That is a useful sanity check: a freshly initialized model should start near this value.
Gradient descent
The loss is a function of every weight in the model. The gradient is the vector of partial derivatives of the loss with respect to each weight. It points in the direction that increases the loss fastest, so training moves the weights the opposite way:
w = w - learning_rate * gradient
Backpropagation computes all these gradients efficiently by applying the chain rule backward through the layers.
The loop is:
- Sample a batch of text sequences.
- Run the forward pass to get logits.
- Compute the cross-entropy loss.
- Run the backward pass to get gradients.
- Update the weights.
Here is the same idea on a one-parameter problem you can run:
w = 5.0
learning_rate = 0.1
for step in range(5):
loss = (w - 2.0) ** 2
grad = 2 * (w - 2.0)
w = w - learning_rate * grad
print(step, round(loss, 3), round(w, 3))The loss falls each step as w approaches 2.0. Real training does the same thing across billions of weights.
Practical details
- Mini-batches. The gradient is estimated from a small batch, not the full dataset. It is noisy but cheap, so it is called stochastic gradient descent.
- Adam. Large models typically use the Adam optimizer (or a variant). It keeps running averages of the gradient and its square, which gives each weight its own effective step size.
- Learning rate schedule. The rate usually warms up from near zero, then decays. Too high a rate makes the loss spike or diverge. Too low a rate wastes compute.
- Gradient clipping. Capping the gradient norm prevents a single bad batch from wrecking the weights.
Common errors
- Misaligned targets. Targets must be the inputs shifted left by one position. If they are not, the model learns to copy the current token.
- Taking log of softmax directly. Computing
log(softmax(x))in two steps can underflow tolog(0). Use the log-space form shown above. - Reading loss as accuracy. A loss drop from 3.0 to 2.9 can be a real improvement even though the top-1 accuracy barely changes.
- Ignoring validation loss. Track loss on held-out text. If training loss falls while validation loss rises, the model is memorizing.
Exercise
A model assigns probability 0.25 to the correct next token at every position of a batch. What is the average cross-entropy loss, and what perplexity does it correspond to?
Show answer
The loss is -log(0.25), which is about 1.386 (natural log). The perplexity is exp(1.386) = 4, so the model behaves as if it were choosing uniformly among 4 tokens.
Exercise
In the one-parameter gradient descent example, what happens if you set learning_rate to 1.1? Why?
Show answer
The loss grows each step and w diverges. Each update changes w - 2 by a factor of (1 - 2 * 1.1) = -1.2, so the distance from the minimum grows by 20% every step instead of shrinking.