LLM Pretraining: Optimization Loops, Cosine Schedules & Stability
How do learning rate schedules, gradient clipping, and AdamW optimization integrate into a production pretraining loop that trains billions of parameters without loss spikes or divergence?
How this lesson unfolds.
Begin with How does the AdamW training loop drive next-token prediction loss from 10.9 down to coherent English emergence?. Follow the visual diagrams to build an intuitive, mathematically grounded mental model of autoregressive pretraining loop & optimization dynamics.
How does complete autoregressive pretraining execution loop operate mathematically within the overall Autoregressive Pretraining Loop & Optimization Dynamics?
An automated deep learning engine running at 100 iterations per second: load batch, zero gradients, compute forward pass, calculate loss, backpropagate error, clip gradient spikes, take optimizer step, update learning rate, and repeat a billion times.
- $$\mathbf{y} = f(\mathbf{X} \mathbf{W} + \mathbf{b})$$
- Learning goalAssemble the seven-step pretraining execution loop and optimize memory throughput with set_to_none=True.
- Helpful foundationsMatrix multiplication and tensor broadcasting · Decoupled Weight Decay Regularization (Loshchilov & Hutter, ICLR 2019) · Language Models are Unsupervised Multitask Learners (Radford et al., OpenAI 2019)
- Common trapCalling optimizer.zero_grad() with default set_to_none=False; setting gradients to None instead of zero deallocates tensor memory and gives a 5–10% speedup.
- Next connectionExplore how learning rate evolves across time in Bridge AdamW and Cosine Annealing Journey.
More context & mechanics
The pretraining step executes seven synchronous operations:
- Zero gradients: `optimizer.zero_grad(set_to_none=True)`
- Forward pass: Z = model(X)
- Loss: L = F.cross\_entropy(Z.view(-1, V), Y.view(-1))
- Backprop: `loss.backward()`
- Gradient clipping: \|g\|₂ ≤ M
- Optimizer step: `optimizer.step()`
- Scheduler step: `scheduler.step()`
The standard execution loop running on thousands of H100 GPUs across supercomputing clusters training foundation models (LLaMA-3, Claude, DeepSeek).
Evolved from basic mini-batch SGD into highly synchronized CUDA execution pipelines optimized by Nvidia (Megatron-LM) and Microsoft (DeepSpeed).
Zero → Forward → Loss → Backward → Clip → Step → Anneal.
How does bridge adamw and cosine annealing journey operate mathematically within the overall Autoregressive Pretraining Loop & Optimization Dynamics?
Like warming up an airplane engine on the runway before takeoff, climbing to cruising altitude, and then gliding gently down to landing. You don't hit the engine with full throttle on cold ice, and you don't slam into the runway at 500 mph.
- $$\mathbf{y} = f(\mathbf{X} \mathbf{W} + \mathbf{b})$$
- Learning goalDerive the mathematical formulation of linear warmup combined with cosine decay and implement a custom PyTorch scheduler.
- Helpful foundationsMatrix multiplication and tensor broadcasting · Decoupled Weight Decay Regularization (Loshchilov & Hutter, ICLR 2019) · Language Models are Unsupervised Multitask Learners (Radford et al., OpenAI 2019)
- Common trapSkipping warmup with AdamW; during the first few hundred steps, second-moment estimates v_t are uncalibrated and cause destructive exploding updates.
- Next connectionAnalyze multi-epoch loss dynamics in Multi-Epoch Loss Trajectory Convergence.
More context & mechanics
Cosine learning rate schedule with linear warmup combines two phases:
- Linear Warmup (t ≤ T_(warm)):
α_t = α_(max) · (t) / (T_(warm))
- Cosine Annealing (T_(warm) < t ≤ T_(max)):
α_t = α_(min) + 1/2(α_(max) - α_(min))(1 + cos(π (t - T_(warm)) / (T_(max) - T_(warm))))
Standard schedule in all modern transformer training runs (LLaMA, GPT-3, PaLM), typically setting T_(warm) = 2000 steps and α_(min) = 0.1 · α_(max).
Cosine annealing was introduced by Loshchilov & Hutter (2016) in SGDR, while linear warmup was popularized by Goyal et al. (2017) to stabilize large-batch ImageNet training.
Warm up to build stable moments; glide down with cosine to settle into sharp basins.
How does multi epoch loss trajectory convergence operate mathematically within the overall Autoregressive Pretraining Loop & Optimization Dynamics?
Tracing the path of learning over multiple passes across the book: epoch 1 grasps basic vocabulary, epoch 2 learns grammar and sentence structure, and epoch 3 refines deep factual relationships and stylistic nuance.
- $$\mathbf{y} = f(\mathbf{X} \mathbf{W} + \mathbf{b})$$
- Learning goalAnalyze multi-epoch loss curves and verify power-law scaling properties during pretraining.
- Helpful foundationsMatrix multiplication and tensor broadcasting · Decoupled Weight Decay Regularization (Loshchilov & Hutter, ICLR 2019) · Language Models are Unsupervised Multitask Learners (Radford et al., OpenAI 2019)
- Common trapTraining for too many epochs on small data; after 3–4 epochs on the same tokens, transformers begin memorizing exact strings and validation loss degrades.
- Next connectionLearn how to detect and eliminate sudden training blow-ups in Gradient Norm Monitoring and Loss Spikes.
More context & mechanics
Loss convergence across epochs exhibits logarithmic decay governed by the Chinchilla scaling law:
L(N, D) = E + (A) / (N^(α)) + (B) / (D^(β))
where N is parameter count, D is token count, and E is irreducible entropy. As D increases across epochs, marginal loss reduction scales as a power-law.
Used by AI research laboratories to predict the exact compute budget (FLOPs) required to achieve a target validation loss.
Established by Kaplan et al. (2020) at OpenAI and refined by Hoffmann et al. (2022) at DeepMind in the landmark Chinchilla paper.
Learning follows power laws: each subsequent decimal point of loss requires exponential data and compute.
How does gradient norm monitoring and loss spikes operate mathematically within the overall Autoregressive Pretraining Loop & Optimization Dynamics?
A surge protector on a sensitive electronic circuit. If a lightning bolt (a corrupted text document with weird unicode) sends a massive electrical spike through the network, the fuse clips the voltage so the computer doesn't catch fire.
- $$\mathbf{y} = f(\mathbf{X} \mathbf{W} + \mathbf{b})$$
- Learning goalCalculate global L2 gradient norm across multi-layer models and implement gradient clipping via torch.nn.utils.clip_grad_norm_.
- Helpful foundationsMatrix multiplication and tensor broadcasting · Decoupled Weight Decay Regularization (Loshchilov & Hutter, ICLR 2019) · Language Models are Unsupervised Multitask Learners (Radford et al., OpenAI 2019)
- Common trapClipping each layer gradient independently; independent clipping changes the relative gradient direction between layers. Always clip the global norm.
- Next connectionReview the full architectural blueprint in Complete Multi-Epoch Pretraining Macro Blueprint.
More context & mechanics
Global gradient clipping computes the total L2 norm across all P parameter tensors:
\|g\|₂ = √(∑_(i=1)^P \|∇_(wᵢ) L\|²)
If \|g\|₂ > M (typically M = 1.0), all gradients are rescaled in-place:
g arrow g · (M) / (\|g\|₂)
This preserves the exact update direction while bounding maximum parameter displacement.
Universal requirement in large-scale distributed pretraining. Without gradient clipping, a single corrupt token batch can destroy weeks of training progress.
Introduced by Razvan Pascanu, Tomas Mikolov, and Yoshua Bengio (2013) in 'On the Difficulty of Training Recurrent Neural Networks' to solve exploding gradients.
Preserve the angle; cap the magnitude: gradient clipping keeps training on the rails.
How does complete multi epoch pretraining macro blueprint operate mathematically within the overall Autoregressive Pretraining Loop & Optimization Dynamics?
The master architectural schematic of a modern AI pretraining facility: data loaders feeding tokens, GPU forward-backward loops executing with mixed precision, gradient clipping safeguarding stability, and checkpoint writers securing model weights.
- $$\mathbf{y} = f(\mathbf{X} \mathbf{W} + \mathbf{b})$$
- Learning goalAudit the full multi-epoch pretraining architecture and trace the lifecycle of a training step from disk to parameter update.
- Helpful foundationsMatrix multiplication and tensor broadcasting · Decoupled Weight Decay Regularization (Loshchilov & Hutter, ICLR 2019) · Language Models are Unsupervised Multitask Learners (Radford et al., OpenAI 2019)
- Common trapNeglecting system-level monitoring (GPU temperature, memory allocation, PCIe bandwidth); hardware faults cause 80% of unexpected training stalls at scale.
- Next connectionProceed to Chapter 29 to master inference temperature and nucleus sampling decoding strategies.
More context & mechanics
The complete pretraining system orchestrates:
- Dynamic data streaming and token batching
- Mixed precision forward pass (bfloat16)
- Cross-entropy loss computation
- Backward automatic differentiation
- Global gradient norm monitoring and clipping
- AdamW parameter updates with decoupled decay
- Cosine learning rate modulation
- Periodic validation and checkpoint serialization
The blueprint underlying production training frameworks including Megatron-LM, Torchtitan, and DeepSpeed ZeRO-3.
Represents the culmination of a decade of deep learning systems engineering, turning neural network training from a delicate art into a predictable science.
Reliability at scale is an engineering discipline: automate safety, monitor norms, and log everything.
How do data loaders, forward evaluation, loss computation, backpropagation, and learning rate warmup orchestrate model pretraining?
Think of training an athlete for the Olympics. You don't ask them to sprint at maximum speed on day 1 (that would pull a hamstring). You start with a gentle warm-up: jogging slowly for 15 minutes as heart rate rises (learning rate warmup). Then, they run structured drills in small workout sets with recovery periods (mini-batches). After each set, the coach reviews performance, corrects their posture (backprop gradients), prevents dangerous form overshoots (gradient clipping), and updates their muscle memory (optimizer step). Pretraining an LLM follows this exact disciplined workout schedule.
- Learning goalConstruct an end-to-end LLM pretraining loop incorporating mixed precision, gradient clipping, and cosine learning rate schedules.
- Helpful foundationsCross-entropy loss · AdamW optimizer · SGDR: Stochastic Gradient Descent with Warm Restarts (Loshchilov & Hutter, 2016)
- Common trapBelieving `optimizer.zero_grad()` must zero tensors; setting `set_to_none=True` deallocates gradient buffers, boosting GPU memory bandwidth by ~10%.
- Next connectionWhen training runs for 3 months on thousands of servers, hardware failures are inevitable. How do we save and resume state? We examine model checkpointing.
More context & mechanics
The standard LLM pretraining loop structure:
```python
for step in range(total_steps):
# 1. Fetch batch from streaming token dataset: (B, T)
x, y = get_batch('train') # y is x shifted right by 1
# 2. Forward pass with mixed precision (BF16)
with torch.cuda.amp.autocast(dtype=torch.bfloat16):
logits = model(x)
loss = F.cross_entropy(logits.view(-1, logits.size(-1)), y.view(-1))
# 3. Backward pass: accumulate parameter gradients
optimizer.zero_grad(set_to_none=True)
loss.backward()
# 4. Gradient norm clipping to prevent exploding steps
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
# 5. Dynamic learning rate schedule (Linear Warmup + Cosine Decay)
lr = get_lr_cosine_schedule(step, warmup_steps, total_steps, max_lr, min_lr)
for param_group in optimizer.param_groups:
param_group['lr'] = lr
# 6. Optimizer update and state advancement
optimizer.step()
```
This exact loop runs across clusters of 16,000+ NVIDIA H100 GPUs using Megatron-LM or PyTorch FSDP (Fully Sharded Data Parallel) to train frontier AI models.
Mini-batch gradient descent was formalized in the 1980s. The standard linear-warmup cosine-decay schedule was popularized by Ilya Loshchilov and Frank Hutter in SGDR (2016).
- Batch, Forward, Backward, Clip, Warmup, Step.
- Set gradients to None to save GPU memory.
How does The Pretraining Optimization Loop: AdamW, Weight Decay & Learning Rate Warmup operate mathematically at scale?
Two synchronized training dynamics charts:
- Learning goalMaster the algebraic and geometric derivation of The Pretraining Optimization Loop: AdamW, Weight Decay & Learning Rate Warmup.
- Helpful foundationsFoundations of Build Llm From Scratch · Coordinate Invariance & Geometric Projections · Radford et al. (2019), Language Models are Unsupervised Multitask Learners, OpenAI
- Common trapAssuming The Pretraining Optimization Loop: AdamW, Weight Decay & Learning Rate Warmup is an arbitrary computational trick rather than an invariant spatial law.
- Next connectionConnects upstream foundational lemmas to modern high-dimensional computational systems.
More context & mechanics
An optimization training dynamics diagram in square 1:1 format on dark slate (#0f172a) with clean coordinate curves.
Top section: Title in white sans-serif: "Pretraining Optimization: AdamW & Cosine Decay". Subtitle in muted cyan: "The standard modern optimization regime for training Large Language Models."
Middle section: Two synchronized training dynamics charts:
Top Chart: Learning Rate Schedule η_t across training steps:
- Linear Warmup (Steps 0 to 2,000): η rises linearly from 0 to η_(max) = 6 × 10^(-4) (prevents early gradient shock).
- Cosine Decay (Steps 2,000 to 100,000): η smoothly decays along a half-cosine curve down to η_(min) = 0.1 × η_(max).
Bottom Chart: AdamW Parameter Update Equation:
"m_t = β₁ m_(t-1) + (1 - β₁) g_t (Momentum)"
"v_t = β₂ v_(t-1) + (1 - β₂) g_t² (Variance)"
"θ_(t+1) = θ_t - η_t ((m̂_t) / (√(v̂_t) + ε) + λ θ_t) (Decoupled Weight Decay)".
Bottom section: Loss stability: "Decoupled weight decay λ θ_t stabilizes pretraining without corrupting adaptive moment statistics."
Sharp vector curves, highlighted warmup and decay zones, elegant dark theme.
Every transformation preserves structural invariants while mapping coordinate spaces. When operating in high dimensions, numerical precision and computational efficiency require adhering strictly to canonical mathematical laws.
Formal derivation and peer-reviewed analysis:
Radford et al. (2019), Language Models are Unsupervised Multitask Learners, OpenAI
"The Pretraining Optimization Loop: AdamW, Weight Decay & Learning Rate Warmup: Invariance, symmetry, and structure govern mathematical truth across continuous and discrete domains."