Skip to content
E
Educatum

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?

Curated by Educatum AI teamLast updated:
Large Language Models (LLMs)
Direct Answer

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:

  1. Linear Warmup: Ramps the learning rate from 0→ηmax⁡0 \to \eta_{\max} 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 vtv_t are uncalibrated and early attention/LayerNorm gradients are large.
  2. Decay Schedules (Cosine & WSD):
    • Cosine Decay: Smoothly decays ηt\eta_t from ηmax⁡\eta_{\max} to a non-zero floor ηmin⁡≈0.1 ηmax⁡\eta_{\min} \approx 0.1\,\eta_{\max} matched to the exact total step horizon TT (Chinchilla scaling showed mismatched horizons hurt final perplexity).
    • Warmup-Stable-Decay (WSD): Holds ηmax⁡\eta_{\max} constant during the main compute phase and runs a short cooldown decay at the end, enabling flexible checkpoint branching without fixing TT upfront.
  3. Adaptive Per-Parameter Updates (AdamW) & Gradient Clipping: AdamW scales updates per parameter by m^t/(v^t+ϵ)\hat{m}_t / (\sqrt{\hat{v}_t} + \epsilon) with decoupled weight decay:
θt+1=θt−ηtλθt−ηtm^tv^t+ϵ\theta_{t+1} = \theta_t - \eta_t \lambda \theta_t - \eta_t \frac{\hat{m}_t}{\sqrt{\hat{v}_t} + \epsilon}

Global gradient norm clipping (max_norm=1.0) catches sudden gradient spikes from noisy pre-training batches. 4. Width & Batch-Size Scaling (μ\muP): Maximal Update Parametrization (μ\muP) adjusts layer-wise initialization and learning-rate scaling so optimal ηmax⁡\eta_{\max} tuned on a small proxy model transfers cleanly to billion-parameter models.

Key Terms

  • Linear Warmup: Gradually increasing ηt\eta_t 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 L2L_2 weight decay from gradient-normalized moment updates.
  • Global Gradient Clipping: Rescaling the gradient vector whenever ∥∇L∥2>c\|\nabla \mathcal{L}\|_2 > c (commonly c=1.0c = 1.0) to prevent training spikes.
  • Maximal Update Parametrization (μ\muP): 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 ηmax⁡=3×10−4\eta_{\max} = 3 \times 10^{-4} using AdamW (β1=0.9,β2=0.95\beta_1=0.9, \beta_2=0.95, weight decay 0.10.1) and clip_grad_norm_(1.0), then cosine-decay down to ηmin⁡=3×10−5\eta_{\min} = 3 \times 10^{-5}. During downstream supervised fine-tuning (SFT), a much smaller peak learning rate (e.g., 1×10−51\times 10^{-5} to 2×10−52\times 10^{-5}, or higher 1×10−41\times 10^{-4} 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,
# )
  • 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 (bf16 preserves fp32 exponent range and avoids loss-scaling underflow).
  • 8-bit / Fused Optimizers: Memory-efficient optimizer implementations (such as adamw_torch_fused or bitsandbytes) for large models.
View all →

Try keywords like RoPE, FlashAttention, DPO, or Blind 75.