Skip to content
ImagineWorld

The Pretraining Loop at Scale

node_idnode-book_building-frontier-llm-from-scratch_chapter-17-the-pretraining-loop-at-scale
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num17
chapter_titleThe Pretraining Loop at Scale
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 17 — The Pretraining Loop at Scale

Section titled “Chapter 17 — The Pretraining Loop at Scale”

Part V — Training at Scale

The training loop from Chapter 3 is, mechanically, the same loop used to train a 671-billion-parameter model. What changes at scale is everything around it: how the learning rate is scheduled over trillions of tokens, how large the batch should be, how many tokens to train on at all, and how to checkpoint a run that takes weeks. This chapter covers that surrounding engineering, and devotes a full section to continued pre-training — the most practical way for a small team to build a specialized model without a frontier budget.

Nothing about the loss changes: it is still the shifted cross-entropy of Chapter 4, averaged over every token in every sequence. The optimizer is still AdamW (Chapter 2), typically with betas around (0.9, 0.95), a weight decay near 0.1, and gradient clipping at norm 1.0. What scale forces is discipline about three quantities the toy loop ignored — the learning-rate schedule, the batch size, and the total token budget — because at trillion-token scale a poor choice in any of them wastes weeks of compute.

A constant learning rate trains poorly. The standard schedule has three phases: a short linear warmup from zero (so early, noisy gradients do not destabilize the model), a long decay, and a small floor. Two decay shapes dominate. The classic is a cosine decay to about 10% of the peak. The newer warmup-stable-decay (WSD) holds the rate constant for most of training and decays only at the very end — which has a decisive practical advantage: because the bulk of training runs at a fixed rate, you need not commit to a total step count in advance, and you can branch a decay phase off the stable trunk whenever you stop. Figure 17.1 contrasts the two, and the schedule is a few lines of code.

WSD: stable, then decay (dashed)
learning rate
max ┤ ╱- - - - - - - - - - - - - - - - - - -╲
│ ╱ ‾‾‾‾‾‾───___ ╲
│ ╱ ‾‾‾───___ cosine decay ╲
│╱ ‾‾‾───___ ╲
min ┼─────────────────────────────────────‾‾‾───__╲──
warmup training steps →

Figure 17.1. Two learning-rate schedules. Cosine decays smoothly from the start of the run; warmup-stable-decay (WSD) holds the peak rate for most of training and decays only at the end, so the run length need not be fixed in advance — convenient for continued pre-training.

import math
def lr_at(step, warmup, total, max_lr, min_lr):
if step < warmup:
return max_lr * step / warmup # linear warmup
if step >= total:
return min_lr # floor
ratio = (step - warmup) / (total - warmup)
coeff = 0.5 * (1.0 + math.cos(math.pi * ratio)) # 1 -> 0
return min_lr + coeff * (max_lr - min_lr) # cosine decay

Python — schedule.py: warmup then cosine decay

Two numbers size a pretraining run. The batch size (in tokens) is grown via gradient accumulation and data parallelism (Chapter 19) to a large value — millions of tokens per step — because large-model gradients are otherwise too noisy; there is a “critical batch size” beyond which larger batches stop helping. The token budget is how much data to train on. The Chinchilla scaling result suggested roughly 20 tokens per parameter as compute-optimal, but modern practice deliberately overtrains far past this — Llama 3 and DeepSeek-V3 use trillions of tokens for tens-of-billions of active parameters — because a model that is more expensive to train but cheaper to run is usually the better deal once inference is counted. Table 17.1 summarizes the levers.

QuantityTypical choiceWhy it matters
LR schedulewarmup + cosine or WSDstability early, convergence late
Batch size (tokens)millions/step (via accumulation + DP)tame gradient noise; throughput
Token budgettrillions (overtrained)quality vs. train cost vs. inference cost

Table 17.1 — The three quantities scale adds to the training loop

Most teams will never pretrain from scratch — nor should they. Continued pre-training (also called continual or domain-adaptive pretraining) takes an existing open-weight base model and trains it further with the same next-token objective on new data: a domain (medicine, law, finance), a language, or a longer context window. It is the highest-leverage technique in this book for a small team, because it inherits the trillions of tokens of general capability already baked into the base model and adds specialization for a tiny fraction of the cost.

Three practical points make the difference between success and a ruined model:

  • Use a smaller learning rate. The model is already well-trained; a from-scratch peak rate would erase what it knows. Warm up briefly and decay from a fraction of the original peak. WSD schedules are popular here precisely because you can take a checkpoint, run a short stable phase on new data, and decay — without re-planning a full run.

  • Mix in replay data. Training only on the new domain causes catastrophic forgetting — the model loses general ability as it specializes. Blending a meaningful fraction of general data (often 10–30%) with the domain data preserves broad competence while still shifting the model toward the target.

  • Watch both losses. Track loss on the new domain and on a held-out general set. The goal is the domain loss falling while the general loss stays roughly flat; a rising general loss means too high a rate or too little replay.

Done well, continued pre-training turns a generic frontier base model into a credibly specialized one — a medical or legal or low-resource-language model — using a single node for days rather than a cluster for months. It is followed by the alignment of Part VI to make the specialized model usable.

Continued vs. fine-tuning Continued pre-training and fine-tuning differ in objective and intent. Continued pre-training uses the unsupervised next-token objective on raw domain text to inject knowledge; supervised fine-tuning (Chapter 22) uses labeled instruction–response pairs to shape behavior. A common pipeline does both in order: continue pretraining on domain documents, then fine-tune on domain instructions.

A run that lasts weeks must survive interruption — preempted nodes, failed GPUs, crashes. Checkpointing saves not just the model weights but the optimizer state, the learning-rate-schedule step, the data-loader position, and the random seeds, so training resumes exactly where it stopped. Save on a fixed cadence and keep several recent checkpoints (loss spikes, Chapter 21, sometimes require rolling back). The reproducibility discipline of Chapter 3 — seed everything, log the seed — scales up to a hard requirement: without it, a divergence at step 400,000 is unreproducible and therefore undebuggable.

Code reference — karpathy/nanoGPT (train.py: LR decay, checkpointing, resume)

nanoGPT’s train.py implements the cosine schedule, periodic checkpointing, and exact resume around the loop of Chapter 10 — the minimal version of everything in this chapter, readable in one sitting.

The loop is now scaled in principle. But a single GPU cannot hold a frontier model, and BF16 is no longer the cheapest precision available. The next two chapters supply the two technologies that make a large run actually affordable: FP8 arithmetic, and distributing the model across thousands of GPUs.

17.6 Worked Example: One Real Training Step

Section titled “17.6 Worked Example: One Real Training Step”

The loop of this chapter, written as a single production-grade step, combines gradient accumulation (a large effective batch on limited memory), mixed precision, gradient clipping (Chapter 21), and the optimizer update. This is the inner body that runs hundreds of thousands of times:

optimizer.zero_grad(set_to_none=True)
for micro in range(grad_accum_steps): # accumulate to a big batch
x, y = next(data_iter)
with torch.autocast("cuda", dtype=torch.bfloat16):
logits = model(x)
loss = F.cross_entropy(logits.flatten(0, 1), y.flatten())
loss = loss / grad_accum_steps # scale for accumulation
loss.backward() # grads accumulate in .grad
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
for g in optimizer.param_groups:
g["lr"] = get_lr(step) # cosine schedule
optimizer.step() # one update per big batch

Python — a complete accumulated, mixed-precision training step

17.7 Gradient Accumulation and Effective Batch Size

Section titled “17.7 Gradient Accumulation and Effective Batch Size”

Section 17.3 set a token budget of millions of tokens per optimizer step, but a single GPU holds only a few thousand tokens of activations at a time. The bridge is gradient accumulation: split the step’s batch into microbatches, run forward and backward on each, let the gradients pile up in the .grad buffers, and call the optimizer only once at the end. The effective batch is the product of three numbers — microbatch size, accumulation steps, and the data-parallel world size:

accum_steps = 16 # microbatches per optimizer step
optimizer.zero_grad(set_to_none=True)
for _ in range(accum_steps):
x, y = next(loader)
logits = model(x)
loss = F.cross_entropy(logits.view(-1, V), y.view(-1))
(loss / accum_steps).backward() # scale so grads average, not sum
norm = torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
optimizer.step()

Python — train/accumulate.py: gradient accumulation

The single subtlety is the division by accum_steps. Backward adds into the gradient buffers, so without scaling you would accumulate a sum over microbatches and your effective learning rate would silently grow with the accumulation count. Dividing the loss makes the accumulated gradient the mean, exactly what a single large batch would have produced.

17.8 Worked Example: One Optimizer Step, End to End

Section titled “17.8 Worked Example: One Optimizer Step, End to End”

Assemble the pieces — the cosine schedule of Section 17.2, mixed precision from Chapter 18, accumulation, clipping, and the step — into the loop that actually trains a frontier model:

lr = get_lr(step) # cosine warmup+decay (17.2)
for g in optimizer.param_groups:
g["lr"] = lr
optimizer.zero_grad(set_to_none=True)
for _ in range(accum_steps):
x, y = next(loader)
with torch.autocast("cuda", dtype=torch.bfloat16):
loss = F.cross_entropy(model(x).view(-1, V), y.view(-1))
(loss / accum_steps).backward()
grad_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
optimizer.step()

Python — train/step.py: the real per-step body

Now put numbers on it. With a microbatch of 4 sequences of 4,096 tokens, 16 accumulation steps, and 64 data-parallel ranks, one optimizer step consumes 4 × 4096 × 16 × 64 ≈ 16.8 million tokens. To train on 14.6 trillion tokens you therefore need about 870,000 steps; at a peak learning rate of 2.8×10⁻⁴ with 2,000 warmup steps, the schedule spends its first 0.2% of the run climbing to peak and the remaining 99.8% cosine-decaying toward zero. Every large run is, at bottom, this loop repeated a million times.

Effective batch is a product, not a setting There is no single “batch size” knob at scale. What the optimizer sees is microbatch × accumulation × data-parallel ranks. You can trade any factor against the others to fit memory while holding the token-per-step budget — and the loss curve only cares about the product.

17.9 AdamW and the Cost of Optimizer State

Section titled “17.9 AdamW and the Cost of Optimizer State”

Almost every large language model is trained with AdamW, an optimizer that adapts the step size per parameter using running estimates of the gradient’s first and second moments. Its update is worth knowing not only because it is ubiquitous but because its memory footprint is one of the largest single costs of training:

m = beta1 * m + (1 - beta1) * g # first moment (mean)
v = beta2 * v + (1 - beta2) * g * g # second moment (variance)
m_hat = m / (1 - beta1 ** t) # bias correction
v_hat = v / (1 - beta2 ** t)
w = w - lr * (m_hat / (v_hat.sqrt() + eps) + wd * w) # decoupled wd

Python — optim/adamw.py: the update behind nearly every LLM

The two moment tensors, m and v, are the same shape as the parameters and are kept in FP32 for stability (Section 18.7). The arithmetic of this is sobering: a 7-billion-parameter model stores its weights in about 14 GB at BF16, but its optimizer state is 7 billion × 4 bytes × 2 = 56 GB — four times the weights themselves. Add the FP32 master copy and gradients and the optimizer dwarfs the model. This is precisely the memory that ZeRO and FSDP (Chapter 19) shard across data-parallel ranks; understanding why optimizer state is so large is understanding why that sharding is not optional at scale.

17.10 Reproducibility: Seeds, Determinism, and Why It Is Hard

Section titled “17.10 Reproducibility: Seeds, Determinism, and Why It Is Hard”

Reproducing a training run exactly — the same loss curve, the same final weights — is harder than it sounds, and the difficulty is instructive. It requires three things to align: a fixed random seed for initialization and data shuffling, deterministic kernels, and an identical data order across the run:

torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
torch.use_deterministic_algorithms(True) # slower, reproducible

Python — repro/seed.py: pinning randomness for reproducibility

The catch is the trade-off in that last line. Several high-performance GPU kernels are deliberately non-deterministic — they sum partial results in whatever order finishes first, which is faster but not bit-reproducible. Forcing determinism can cost real throughput, so production runs often accept approximate reproducibility (same seed, same data order, statistically identical curves) rather than paying for the exact kind. Knowing the distinction matters when debugging: if two “identical” runs diverge, the cause is usually a non-deterministic kernel or a subtly different data order, not a bug in the model.

Optimizer state is the hidden memory giant AdamW’s two moment tensors, kept in FP32, can quadruple a model’s memory footprint. That single fact explains why optimizer-state sharding (ZeRO/FSDP) is the first tool reached for when a model will not fit.

17.11 Activation Checkpointing: Trading Compute for Memory

Section titled “17.11 Activation Checkpointing: Trading Compute for Memory”

The optimizer-state accounting of Section 17.9 left out a cost that can exceed even the weights: activations. The forward pass must retain its intermediate results so the backward pass can compute gradients, and for a deep model with a long sequence this storage is enormous. Activation checkpointing trades it back for compute — store only a few checkpoints, and recompute the discarded activations during the backward pass:

from torch.utils.checkpoint import checkpoint
def forward(self, x):
for block in self.blocks:
x = checkpoint(block, x, use_reentrant=False)
return x # block internals recomputed, not stored

Python — train/checkpoint.py: recompute activations in backward

The trade is quantifiable and usually worth it: storing a checkpoint only at each block boundary, rather than every internal activation, cuts activation memory dramatically at the cost of roughly one extra forward pass during backward — about 33% more compute. For the long sequences and large batches that frontier training demands, this is what makes a step fit at all. It is also the memory that Appendix D’s “16 bytes per parameter” pointedly does not count, which is why a real run’s memory ceiling is set as much by activations and sequence length as by the parameter count itself.

Memory you can buy back with compute Activations can dominate training memory, but unlike weights they are recomputable. Checkpointing stores a few and regenerates the rest in backward — about a third more compute for a large memory saving, often the difference between fitting and not.

17.12 Effective Batch Size and the Linear Scaling Rule

Section titled “17.12 Effective Batch Size and the Linear Scaling Rule”

Batch size and learning rate are not independent knobs — change one and you should change the other. The reason is gradient noise: a larger batch averages over more examples, producing a less noisy estimate of the true gradient, which in turn can support a larger, more confident step. The practical heuristic that captures this is the linear scaling rule: scale the learning rate in proportion to the batch size. Double the effective batch (Section 17.8), and double the learning rate.

The rule holds within a useful range but not forever. At small to moderate batch sizes it tracks well, and it is why the two appear together in any tuning table (Appendix C). As the batch grows very large, the linearity breaks down — the gradient is already near-noiseless, so further enlarging it stops justifying a proportionally larger step, and a longer warmup (Section 17.2) becomes necessary to reach the high learning rate without diverging early. This interaction matters acutely in distributed training, where adding data-parallel workers (Chapter 19) increases the effective batch size automatically: scale out to more GPUs and the effective batch grows, so the learning rate must rise to match, or the larger batch is wasted on too-timid steps. Batch size and learning rate are best thought of as a single coupled decision, tuned together rather than in isolation.

Bigger batches earn bigger steps A larger batch gives a less noisy gradient that supports a proportionally larger learning rate — the linear scaling rule. It breaks at extreme batch sizes and couples directly to data parallelism, where scaling out grows the batch and so must grow the learning rate.