Evaluation, Checkpoints, and Scale
This chapter presents language metrics, multi-layer evaluation, and reproducible checkpoints.
After training, it is necessary to quantify performance, compare configurations fairly, and preserve the state needed to resume experiments. These practices connect research, reproducibility, and operations.
13.1 Evaluation Metrics: Perplexity and Loss
Unlike binary classification tasks, where “accuracy” is a clear metric, generative models require metrics that evaluate the probability of the generated sequences.
13.1.1 Cross-Entropy Loss
The fundamental loss function during training is the cross-entropy loss. It measures the difference between the probability distribution predicted by the model and the true distribution (the correct next token).
13.1.2 Perplexity (PPL)
Perplexity is the gold-standard metric for evaluating autoregressive language models. Intuitively, it measures how “surprised” the model is when it sees new data. * Mathematical definition: Perplexity is the exponentiation of the mean cross-entropy loss.
* Interpretation: * A low PPL indicates that the model assigns high probability to the correct next token. * A PPL of 1 would be a perfect model (absolute certainty). * A PPL equal to the vocabulary size indicates that the model is guessing at random.
Implementation Example (PyTorch)
import torch
import torch.nn.functional as F
def calculate_perplexity(logits, targets):
"""
Computes perplexity given the model logits and the target tokens.
Args:
logits: Raw model output [batch_size, seq_len, vocab_size]
targets: True tokens [batch_size, seq_len]
Returns:
float: Perplexity value
"""
# Reshape for compatibility with cross_entropy
# [batch_size * seq_len, vocab_size]
logits_flat = logits.view(-1, logits.size(-1))
targets_flat = targets.view(-1)
# Compute the cross-entropy loss
loss = F.cross_entropy(logits_flat, targets_flat)
# Compute perplexity
perplexity = torch.exp(loss)
return perplexity.item()
13.1.3 Evaluation Flow

13.2 Saving Checkpoints (Persistence)
Training LLMs is computationally expensive and prone to hardware failures. Saving checkpoints serves not only to save the final model, but to allow training to be resumed and to enable the analysis of overfitting.
13.2.1 What to Save?
A robust checkpoint should contain more than just the model weights (state_dict).
- Model weights: Learned parameters.
- Optimizer state: Moments and variance (essential for AdamW).
- Scheduler state: Current learning rate.
- Metadata: Epoch number, current step, and loss value.
Saving Strategy
import os
def save_checkpoint(model, optimizer, scheduler, epoch, loss, path="checkpoints"):
if not os.path.exists(path):
os.makedirs(path)
checkpoint = {
'epoch': epoch,
'model_state_dict': model.state_dict(),
'optimizer_state_dict': optimizer.state_dict(),
'scheduler_state_dict': scheduler.state_dict(),
'loss': loss,
}
file_name = f"{path}/checkpoint_epoch_{epoch}.pt"
torch.save(checkpoint, file_name)
print(f"Checkpoint saved to: {file_name}")
# Usage example in the training loop
# save_checkpoint(model, optimizer, scheduler, current_epoch, current_loss)
13.3 Chapter Conclusion
Perplexity and loss help track token modeling, but must be complemented by tasks, human review, and system tests. Checkpoints preserve progress and make comparisons and resumptions more reliable.
13.4 Multi-Layer Evaluation
Perplexity compares token prediction under the same tokenizer and corpus, but does not by itself measure usefulness, safety, or factuality. A complete evaluation combines intrinsic metrics, automatic tasks, human review, and tests of the integrated system. Compare models with the same data preparation so as not to attribute to the model a difference caused by tokenization.
Set aside a test set before tuning hyperparameters. Use validation during development and consult the test set only for final decisions. Document the checkpoint version, prompt, generation parameters, dependencies, and seed; without this, an isolated score is not reproducible.
A checkpoint is not just the model
To resume training faithfully, also save the optimizer and scheduler state, the mixed-precision scaler, the global step, and the random states. For inference, weights, configuration, and a compatible tokenizer are the minimum necessary.
13.5 An Evaluation Pyramid
Cheap, frequent evaluations should sit at the base; expensive, contextualized evaluations at the top. During training, loss and perplexity detect regressions quickly. Afterward, automatic tasks measure specific capabilities. Human samples assess usefulness, clarity, and criteria that are hard to encode. Finally, system tests verify retrieval, tools, permissions, latency, and failures in production.

No layer replaces the others. A lower perplexity may not improve instruction following; a human preference may favor style without detecting a factual error; a benchmark may be contaminated by the training data.
13.5.1 Uncertainty and Intervals
A mean without variability can lead to fragile conclusions. For accuracy on examples, use confidence intervals or bootstrap. When comparing two models, evaluate them on the same items and examine the distribution of the differences. Small gains may disappear with another seed, prompt, or sample.
13.5.2 Evaluating Open-Ended Generation
Texts can have several valid answers. Metrics based on lexical overlap penalize correct paraphrases, while model-based evaluators may introduce a preference for style, order, or verbosity. Define rubrics with observable criteria and calibrate automatic evaluators against human judgments.
| Dimension | Operational question |
|---|---|
| Correctness | Can the claims be verified? |
| Relevance | Does the answer meet the request without digressions? |
| Robustness | Do small rephrasings preserve the result? |
| Safety | Do adversarial inputs get through the controls? |
| Efficiency | Do latency and memory meet the budget? |
13.6 Checkpoint Strategy
Saving at a fixed interval simplifies resumption but can consume excessive storage. A practical policy keeps the best validation checkpoint, the most recent one, and a few spaced milestones. Write first to a temporary file and finalize with an atomic operation to reduce the risk of corruption.
Test the restoration
A checkpoint is only trustworthy after it has been loaded. Automate a test that restores the state, runs a known batch, and confirms the global step, learning rate, and expected output within tolerance.