Topic 21 of 62 · Generalizing and measuring it
Overfitting vs underfitting
EasyTraining loss keeps falling while validation loss starts rising. What does this tell you, and what do you check before changing the model?
1 · Start with the intuition
Training loss measures how well the model fits the examples it updates on; validation loss estimates how well that fit transfers to held-out data. When training loss drops while validation loss climbs, the model is memorizing patterns specific to the training set (or noise in its labels) that do not hold on the validation split. Before reaching for heavier regularization or an earlier checkpoint, first verify that the two curves are actually measuring the same quantity under the same mask, tokenization, and evaluation mode.
2 · How the mechanism works
Mechanism step 1 of 3 · no question to answer
Verify the comparison
Confirm that train and validation losses use identical token masks, normalization (per-token vs per-sequence), and model.eval() settings.
Next, we will look at: Inspect slices & examples. Move on when this operation makes sense.
Visualizing the behavior
The gap opens when validation stops improving
Illustrative- training loss
- validation loss
Classical bias–variance trade-off
Illustrative- bias²
- variance
- total
3 · The governing equation
Empirical training loss: L_train(θ) = (1 / N_train) Σᵢ ℓ(fθ(xᵢ), yᵢ) Held-out validation loss: L_val(θ) = (1 / N_val) Σⱼ ℓ(fθ(xⱼ), yⱼ) Generalization gap: Δ = L_val(θ) − L_train(θ) (computed with identical loss definition ℓ)
Notation: ℓ must be evaluated without training-only regularizers (such as L2 penalty terms or active dropout) when comparing the two numbers directly.
In multi-epoch fine-tuning (such as SFT on a small dataset), validation token loss often reaches a minimum after 1–2 epochs and rises on later epochs as the model sharpens its probabilities on repeated training prefixes. However, a rising validation loss does not always mean downstream task accuracy is worse—calibration can worsen (driving NLL up) while greedy accuracy still improves slightly—so always pair validation loss with task-level evaluations.
4 · Put concrete numbers on it
Illustrative scenario5 · Common misconception to avoid
Comparing training loss logged with dropout active and per-microbatch averaging against a validation loss computed in eval mode with per-token averaging—or tuning hyperparameters fifty times on the validation set and treating the best validation score as an unbiased estimate.
In practice · implementation & engineering rule of thumb
Always log a "train-eval" metric—evaluating a fixed subset of training examples in model.eval() mode with the exact validation loss function—to confirm your train and validation curves are computed identically.
@torch.no_grad()
def evaluate(model, loader):
model.eval()
total_nll, total_toks = 0.0, 0
for batch in loader:
logits = model(batch["input_ids"]).logits
total_nll += F.cross_entropy(logits.view(-1, V), batch["labels"].view(-1), ignore_index=-100, reduction="sum").item()
total_toks += (batch["labels"] != -100).sum().item()
return total_nll / max(1, total_toks)Go one level deeper
Follow-ups that often come after a correct first answer.
- The decomposition itself
- For squared loss: E[(y − f̂(x))²] = Bias[f̂(x)]² + Var[f̂(x)] + σ². The expectation is over training sets and noise, and σ² is irreducible noise. It is exact for squared error; for other losses it is an analogy.
- Early stopping is regularization
- Picking the checkpoint with the best validation loss limits how far the weights move from initialization. The chosen epoch is itself fitted on validation data, so report final performance on a separate test set.
6 · Self-check & interview synthesis
Explain it in your own words first
Before revealing the reference answer, try answering the opening question aloud in four beats: what it is → how the math works → what trade-off it makes → a concrete number or failure mode.
Follow-up question interviewers often ask next
MediumWhy is validation loss sometimes lower than training loss during the first epoch?
Show follow-up reasoning
Three common reasons: (1) training loss is averaged over the epoch as weights are still improving, whereas validation loss is evaluated at the end of the epoch; (2) dropout or data augmentation is active during training and disabled during validation; or (3) the validation split happens to contain shorter or cleaner examples.