All courses

Explain a pretraining run end to end

Describe how a base model is produced: data pipeline, shifted-target objective, AdamW with warmup and cosine decay, gradient clipping, mixed precision, batch size in tokens. Diagnose a loss curve, including spikes and plateaus.

Builds on: Deduplication, memorization and contamination, AdamW and decoupled weight decay, Learning-rate warmup and decay schedules, Gradient clipping and loss spikes, Batch size in tokens and gradient accumulation, Mixed-precision training, Reading pretraining loss curves

▶ Watch this lesson Start the whole course

What the animation says

The factory line

A pretraining run is a factory line: raw text in, base model out. Upstream work happens once: collect text, filter it, remove duplicates and any benchmark questions. Then tokenize with BPE, cut the tokens into rows, and shuffle them. Now the loop. Every step grabs a batch of rows, runs forward and backward, and nudges the weights. It logs the loss and saves checkpoints as it goes. After roughly one pass over the data, the weights that remain are the base model.

One step, precisely

Zoom into one step. Every position predicts the next token. So the targets are the same row, shifted left by one. The loss averages negative log probability of the true next token over all B times T positions. The gradient is clipped: if it's too long, it's scaled down to the threshold. AdamW steps at the scheduled rate, decaying weight matrices only. Matmuls run in bf16; master weights stay in fp32. Your turn: at the word 'cat', tap the token it's scored against.

Planning a 100B-token run

Plan a real run: a hundred billion tokens, rows of 2048, 512 rows per step. That's about one million tokens per step, so roughly 95,400 steps for one pass. Only 32 rows fit in memory, so each step accumulates 16 microbatches. Warmup climbs for 2,000 steps to a peak of three times ten to the minus four, then a cosine glides down to a tenth of that. Halfway down, cosine is zero, so the rate sits at the midpoint: 1.65 times ten to the minus four. The vocabulary has 50,000 tokens. What should the very first logged loss be?

Where the curve starts

Answer: about 10.8. An untrained model spreads its probability evenly, so each token costs the natural log of fifty thousand. So a healthy curve starts near ln V and falls fast. Stuck at ln V means nothing is learning: a zero learning rate, frozen weights, or a bug. Far too low, near zero nats, is bad news. Real language is never that predictable. It means the targets leak into the inputs: labels weren't shifted, or the causal mask lets positions see the future.

Spikes, NaN, val gap, late drop

Later in the run, other shapes appear. A brief spike that recovers is usually harmless; clipping kept those updates small. Repeated or unrecovered spikes: rewind to a checkpoint, skip those batches, lower the peak rate. NaN means something overflowed, like an fp16 activation past 65,504. Rewind and fix that operation. Validation far above training means memorizing, usually heavily duplicated documents. And a slow plateau, then a late drop? That's cosine decay working. Tap the run that needs a rewind.

From raw text to base model, in one run

You've met every ingredient separately: corpus cleaning, shifted targets, AdamW, warmup and cosine decay, clipping, bf16, token batches. How do they fit into **one run** that turns raw text into a base model? And when you look at the loss curve at step 40,000, how do you tell *healthy* from *quietly broken* from *about to blow up*?

A factory line, run about once over the data

**Upstream (once):** collect text, filter, deduplicate, remove benchmark questions, tokenize with BPE, cut into rows of $T{+}1$ tokens, shuffle. **Every step:** take $B\cdot T$ tokens, run forward and backward in bf16, score each position against the *next* token, clip the gradient, let AdamW step at the scheduled learning rate. Log the loss and save checkpoints. After roughly one epoch, the weights you are left with are the base model.

One training step, precisely

Step $s$ of $S$, $B$ rows of $T{+}1$ tokens ($x^{(b)}_t$ is token $t$ of row $b$): $$\mathcal L_s=-\tfrac{1}{BT}\textstyle\sum_{b=1}^{B}\sum_{t=1}^{T}\log p_\theta(x^{(b)}_{t+1}\mid x^{(b)}_{\le t})$$ Gradient $g$ (averaged over microbatches), then clipped: $g\leftarrow g\cdot\min(1,c/\lVert g\rVert)$, where $c$ is the clip threshold. Learning rate, with peak $\eta_{\max}$ and final value $\eta_{\min}$: $\eta_s=\eta_{\max}s/S_w$ for $s\le S_w$ (the $S_w$ warmup steps), else $$\eta_s=\eta_{\min}+\tfrac12(\eta_{\max}-\eta_{\min})\big(1+\cos\pi\tfrac{s-S_w}{S-S_w}\big)$$ AdamW: an Adam step with $\eta_s$, plus $\theta\leftarrow\theta-\eta_s\lambda\theta$ on weight matrices only. Matmuls run in bf16. $\theta$ and Adam's moment estimates stay in fp32.

Planning a 100B-token run

$D=100$B tokens, $T=2048$, $B=512$. - Tokens per step: $512\cdot2048=1{,}048{,}576\approx1$M. - Steps: $S=10^{11}/1.05\times10^{6}\approx95{,}400$, one pass over the data. - Only 32 rows fit in memory at once, so accumulate $512/32=16$ microbatches per step. - Warmup $S_w=2{,}000$, $\eta_{\max}=3\times10^{-4}$, $\eta_{\min}=3\times10^{-5}$. - Halfway through the decay ($s\approx48{,}700$): $\cos(\pi/2)=0$, so $\eta=1.65\times10^{-4}$. - The first logged loss should be $\approx\ln V$. For $V=50{,}000$ that is $10.8$ nats.

Diagnosing the curve: symptom → cause

- Starts near $\ln V$ and falls fast: healthy. - Stuck at $\ln V$: nothing is learning ($\eta=0$, frozen weights, a bug). - Far too low, near 0: the targets leak, from unshifted labels or a broken causal mask. - A brief spike that soon recovers: usually harmless, and clipping kept the bad updates small. Repeated or unrecovered spikes: rewind to a checkpoint, skip those batches, lower $\eta_{\max}$. - NaN: some value overflowed or hit invalid math, e.g. an fp16 activation past its 65,504 maximum. Rewind and fix the unstable operation. - Val ≫ train: the model is memorizing training text, usually heavily duplicated documents. Also check that val comes from the same kind of data. - A slow plateau, then a late drop: cosine decay working.

Remember

A base model is what remains after about one pass of AdamW over a cleaned, deduplicated, tokenized corpus. Each step minimizes shifted-target cross-entropy over $B\cdot T$ tokens, with warmup plus cosine $\eta$, clipped gradients, and bf16 math on fp32 master weights. Read the curve against landmarks: $\ln V$ at the start, a smooth decline, val ≈ train, and a late drop as $\eta$ decays.

On Bytewise this lesson comes in small steps with a check at the end, and the app brings it back right before you would forget it.