AlgoViz

From a training corpus to a checkpoint

hard 6 min

Language-model pretraining repeatedly predicts held-out target tokens from their prefixes.

Video lesson · Chapter 1 of 4

One missed word moves a checkpoint

0:00 / 3:54

Theory

Read or listen first. About 2 min.

What it is

Language-model pretraining repeatedly predicts held-out target tokens from their prefixes. The training loop shifts inputs and targets, masks padding or other excluded positions, measures the negative log-probability of the targets and backpropagates gradients. An optimizer uses those gradients and its running state to update the weights. Validation measures performance on data withheld from those updates.

Why it exists

Inspect both curves. A falling training loss with a rising held-out loss can signal overfitting or distribution mismatch. A sudden change after resume can indicate missing optimizer state, learning-rate position or data ordering. Continued pretraining adapts next-token statistics on a domain corpus, supervised tuning teaches desired responses, and retrieval supplies changeable source facts at request time.

Learn from a missed next token

Packed examples → Loss and gradient (input and targets). Loss and gradient → Optimizer step (gradients). Optimizer step → Held-out stream (checkpoint). Optimizer step → Loss and gradient (updated weights)
Packed examples → Loss and gradient (input and targets). Loss and gradient → Optimizer step (gradients). Optimizer step → Held-out stream (checkpoint). Optimizer step → Loss and gradient (updated weights)

Inside this chapter

Chapter sources
Cross-entropy and perplexity
Cross-entropy averages negative log probability across the evaluated target tokens. Exponentiating the mean natural-log loss gives perplexity. Tokenizers, masking rules and evaluation distributions affect comparisons.

Cross-entropy is the average surprise the model feels at the actual next tokens. Perplexity exponentiates it back into an intuitive count of effective choices. Both depend on the tokenizer, because splitting text into more, easier pieces lowers per-token loss without the model getting better, so compare perplexities only across models that share a tokenizer and evaluation set. A suspiciously low loss often means the mask lets the model see its targets or the data repeats.

Example. If the model assigns the true next token probability 0.25, that target contributes about 1.386 nats. A single such target has perplexity four.

Probability of the true token, loss and perplexity

p(true token)Loss = -ln p (nats)Perplexity = e^loss
0.50.6932
0.251.3864
0.12.30310
0.014.605100
For a single target, perplexity is 1 / p: the model is as unsure as a uniform choice among that many options.
Gradient accumulation and schedules
Accumulate gradients over microbatches when the full effective batch will not fit. Scale or normalize them consistently and update the optimizer and schedule at the intended step. Evaluation batches must not update the weights.

Accumulation lets a small device emulate a large batch by summing gradients from several forward and backward passes before updating. Scale each microbatch loss so the sum equals the mean over the effective batch; with variable-length sequences, decide whether to average per token or per example and do it consistently. Two common bugs: stepping the scheduler every microbatch, which runs the schedule four times too fast, and forgetting to zero gradients, which silently doubles them.

Example. Accumulating four eight-example microbatches gives 32 examples per optimizer step on one worker when every example is counted equally.

Another example. A fine-tuning job that fit batch 32 on a larger GPU moves to a smaller one: batch 8 with accumulation 4 keeps the same effective batch, learning rate and schedule length.

Four microbatches, one optimiser step
  1. 1Microbatch 1 of 48 examples, loss divided by 4
  2. 2Backward, keep gradsgradients add up in place
  3. 3Microbatches 2 to 4same, 32 examples total
  4. 4Optimiser stepone update from summed grads
  5. 5Scheduler step, zeroadvance learning rate, clear grads
Repeat: back to Microbatch 1 of 4

The learning-rate schedule counts optimiser steps, not microbatches.

Reproducible checkpoints
A resumable checkpoint includes the weights, optimizer state, scheduler, training step and enough random/data state to resume the intended sampling. A compact inference export can omit several of those pieces.

Adaptive optimisers keep running averages of gradients for every parameter, and those averages shape the next updates. Restarting with fresh optimiser state is like resetting momentum, which often shows up as a loss spike. Forgetting the data cursor means the resumed run repeats or skips data. Save everything needed to continue, and verify by resuming from a checkpoint and comparing the next few losses with the original run.

Example. Resuming with weights alone and a fresh optimizer can change the subsequent loss even on the same stream of tokens.

Resumable training checkpoint

  • Model weights
  • Optimiser state such as moments
  • Scheduler position and step count
  • Random generator states
  • Data loader cursor and mixture state

Inference export

  • Model weights only, often in a serving format
  • Tokenizer and config
  • No optimiser or scheduler state
  • Cannot continue training identically
Data mixtures and a learning-rate schedule
Track the sampling weight of each corpus, deduplicate across the training and validation boundary and keep a domain holdout. A warmup and subsequent learning-rate decay change update sizes across steps. Save the scheduler, optimizer and random state when resuming.

Warmup avoids large, noisy updates while optimiser statistics are still unreliable; decay lets the model settle as training ends. The data mixture decides what the model spends those updates on, and it is defined by tokens sampled, not files: long textbooks dominate a token-weighted mix even when they are few files. Track validation loss per domain beside the aggregate, because a mixture change can improve one domain while another quietly regresses.

Example. If textbooks form 10% of files but 45% of tokens, sampling files uniformly and sampling tokens uniformly produce different mixtures. Plot domain validation loss beside aggregate loss before changing the mix.

Another example. Textbooks are 10% of files but 45% of tokens. Sampling files uniformly gives them about 10% of training batches by count; sampling tokens uniformly gives them close to half the tokens seen.

Linear warmup, then cosine decay

ηt={ηmax⁡ tTwt<Twηmin⁡+12(ηmax⁡−ηmin⁡)(1+cos⁡(π t−TwT−Tw))t≥Tw\eta_t=\begin{cases}\eta_{\max}\,\dfrac{t}{T_w} & t<T_w\\[6pt] \eta_{\min}+\tfrac12(\eta_{\max}-\eta_{\min})\Big(1+\cos\big(\pi\,\tfrac{t-T_w}{T-T_w}\big)\Big) & t\ge T_w\end{cases}
T_w warmup steps, T total steps. Resuming must restore t, or the rate jumps back to the start.
Training compute estimate
For a dense transformer, training compute is roughly six floating-point operations per parameter per training token: about two for the forward pass and four for the backward pass.

The estimate lets you turn a budget into a plan: divide by the sustained throughput of your hardware to get time. Real throughput is usually well below peak, so measure utilisation on a short run before committing. The same approximation underlies the scaling-law trade-off between a bigger model and more tokens for a fixed compute budget.

Example. A 1-billion-parameter model trained on 20 billion tokens needs about 6 x 10^9 x 2 x 10^10 = 1.2 x 10^20 operations.

The 6ND rule of thumb

C≈6 N DN=109,  D=2×1010  ⇒  C≈1.2×1020 FLOPsC \approx 6\,N\,D \qquad N=10^9,\; D=2\times10^{10} \;\Rightarrow\; C\approx 1.2\times10^{20}\ \text{FLOPs}
N parameters, D training tokens. It ignores attention's length-dependent term, so it underestimates at very long sequence lengths.

How it works

Step through the idea, or press Play.

Step 1 of 4

Packed examples. Shift and mask the target

Understand it

Worked example

Learn from a missed next token

  1. 1

    Shift and mask the target

    Two real target tokens remain after padding positions are excluded. The dataset manifest fixes the sampling mix.

  2. 2

    The rare target receives p = 0.25

    Compute target loss and differentiate through the model. Inspect the mask before interpreting a strangely low loss.

  3. 3

    Accumulate four microbatches

    Update weights and the schedule once per effective batch. Persist the step and optimizer state.

  4. 4

    Compare the new checkpoint

    Evaluate on untouched data under the same masking rule. Record both training and validation loss against tokens processed.

Next-token loss

L=−1N∑t=1Nlog⁡p(yt∣x≤t),PPL=eLL=-\frac{1}{N}\sum_{t=1}^{N}\log p(y_t\mid x_{\leq t}),\quad \mathrm{PPL}=e^L
Average over unmasked target positions. Use the same tokenizer when comparing perplexity.

Follow the handoffs

Inspect both curves. A falling training loss with a rising held-out loss can signal overfitting or distribution mismatch. A sudden change after resume can indicate missing optimizer state, learning-rate position or data ordering. Continued pretraining adapts next-token statistics on a domain corpus, supervised tuning teaches desired responses, and retrieval supplies changeable source facts at request time.

Shift, mask and score one packed example

PositionInput tokenTarget tokenMaskp(target)Loss
1<bos>ferro10.50.693
2ferrofluid10.251.386
3fluid<pad>0excluded
4<pad><pad>0excluded
Illustrative values. Mean over the two unmasked targets is 1.040 nats, so perplexity is e^1.040, about 2.83.

Summary

The whole topic in one minute.

Contaminated examples cannot estimate behavior on genuinely unseen data. Rebuild the split and reevaluate.

Inspect both curves. A falling training loss with a rising held-out loss can signal overfitting or distribution mismatch. A sudden change after resume can indicate missing optimizer state, learning-rate position or data ordering. Continued pretraining adapts next-token statistics on a domain corpus, supervised tuning teaches desired responses, and retrieval supplies changeable source facts at request time.

Sources