Large Language Models often require careful tuning of learning rates. How do you adapt learning rates during training to ensure stable convergence and efficient learning for LLMs?
LLM training adapts learning rates across steps (rather than epochs) using linear warmup followed by cosine or Warmup-Stable-Decay (WSD) schedules, paired with AdamW for per-parameter adaptive scaling and decoupled weight decay. Warmup prevents early divergence before Adam's second-moment estimates stabilize and before residual/LayerNorm gradients settle, while decaying toward ~10% of peak learning rate and clipping global gradient norms ensures smooth convergence.
Study Card: Adapting Learning Rates for LLMs
Direct Answer
Because LLM pre-training typically performs a single pass (or fixed token budget) over trillions of tokens, learning rates are scheduled over optimizer steps / tokens rather than epochs, combining four complementary mechanisms:
- Linear Warmup: Ramps the learning rate from over the first ~0.5%–2% of steps (e.g., 500–2,000 steps). Warmup does not primarily help escape local minima; instead, it prevents early training spikes and loss divergence while Adam’s running second-moment estimates are uncalibrated and early attention/LayerNorm gradients are large.
- Decay Schedules (Cosine & WSD):
- Cosine Decay: Smoothly decays from to a non-zero floor matched to the exact total step horizon (Chinchilla scaling showed mismatched horizons hurt final perplexity).
- Warmup-Stable-Decay (WSD): Holds constant during the main compute phase and runs a short cooldown decay at the end, enabling flexible checkpoint branching without fixing upfront.
- Adaptive Per-Parameter Updates (AdamW) & Gradient Clipping: AdamW scales updates per parameter by with decoupled weight decay:
Global gradient norm clipping (max_norm=1.0) catches sudden gradient spikes from noisy pre-training batches.
4. Width & Batch-Size Scaling (P): Maximal Update Parametrization (P) adjusts layer-wise initialization and learning-rate scaling so optimal tuned on a small proxy model transfers cleanly to billion-parameter models.
Key Terms
- Linear Warmup: Gradually increasing over initial steps to stabilize Adam’s second-moment variance estimates and early residual updates.
- Cosine & WSD Schedules: Step-based decay curves bringing learning rate down to ~10% of peak (or near zero in WSD cooldown) for sharp final convergence.
- AdamW: Adaptive optimizer separating weight decay from gradient-normalized moment updates.
- Global Gradient Clipping: Rescaling the gradient vector whenever (commonly ) to prevent training spikes.
- Maximal Update Parametrization (P): Scaling rules enabling zero-shot learning-rate transfer from small proxy models to full-scale LLMs.
Example
When pre-training a 7B Transformer over 200,000 steps with batch size 4M tokens, an engineer might warm up linearly over 2,000 steps to using AdamW (, weight decay ) and clip_grad_norm_(1.0), then cosine-decay down to . During downstream supervised fine-tuning (SFT), a much smaller peak learning rate (e.g., to , or higher for LoRA adapters) is used to prevent catastrophic forgetting.
Code Implementation
import torch
import torch.nn as nn
torch.manual_seed(0)
# 1. Self-contained PyTorch AdamW + Linear Warmup + Cosine Decay + Gradient Clipping
model = nn.TransformerEncoderLayer(d_model=64, nhead=4, batch_first=True)
lm_head = nn.Linear(64, 100)
embed = nn.Embedding(100, 64)
params = list(embed.parameters()) + list(model.parameters()) + list(lm_head.parameters())
peak_lr, min_lr = 3e-4, 3e-5
warmup_steps, total_steps = 4, 12
optimizer = torch.optim.AdamW(params, lr=peak_lr, betas=(0.9, 0.95), weight_decay=0.1)
warmup = torch.optim.lr_scheduler.LinearLR(
optimizer, start_factor=1e-2, end_factor=1.0, total_iters=warmup_steps
)
cosine = torch.optim.lr_scheduler.CosineAnnealingLR(
optimizer, T_max=total_steps - warmup_steps, eta_min=min_lr
)
scheduler = torch.optim.lr_scheduler.SequentialLR(
optimizer, schedulers=[warmup, cosine], milestones=[warmup_steps]
)
criterion = nn.CrossEntropyLoss()
for step in range(total_steps):
x = torch.randint(0, 100, (8, 16))
logits = lm_head(model(embed(x)))
loss = criterion(logits[:, :-1].reshape(-1, 100), x[:, 1:].reshape(-1))
optimizer.zero_grad()
loss.backward()
torch.nn.utils.clip_grad_norm_(params, max_norm=1.0)
optimizer.step()
scheduler.step()
print(f"Step {step+1:2d} | LR: {optimizer.param_groups[0]['lr']:.6f} | Loss: {loss.item():.4f}")
# 2. Modern Hugging Face Trainer configuration (requires train_dataset)
# from transformers import TrainingArguments
# training_args = TrainingArguments(
# output_dir="./results",
# max_steps=10000,
# per_device_train_batch_size=16,
# learning_rate=2e-5,
# lr_scheduler_type="cosine",
# warmup_ratio=0.05,
# optim="adamw_torch",
# max_grad_norm=1.0,
# bf16=True,
# )
Related Concepts
- Differential / Layer-wise Learning Rates: Assigning smaller learning rates to lower pre-trained backbone layers than to newly initialized heads during fine-tuning.
- Batch-Size Scaling Laws: Adjusting learning rate with global batch size (roughly square-root scaling for AdamW up to the critical batch size).
- Mixed-Precision Training (
bf16/fp16): Interacts closely with learning-rate stability (bf16preservesfp32exponent range and avoids loss-scaling underflow). - 8-bit / Fused Optimizers: Memory-efficient optimizer implementations (such as
adamw_torch_fusedorbitsandbytes) for large models.