Learning-Rate Schedules and Gradient Clipping
The learning rate is the most important hyperparameter, and it should not be constant. Training usually starts with a warmup from a small value, holds a peak, and decays toward zero at the end. Alongside the schedule, gradient clipping caps the size of rare huge gradients so that one bad batch cannot wreck the run. Both are standard in every transformer recipe.
Why warm up?
At initialization the loss surface can be very sharp, Adam's second-moment estimates are still noisy, and the first gradients are large. A full-size step then lands somewhere bad, sometimes irrecoverably. Increasing the learning rate linearly over the first few hundred to few thousand steps lets curvature drop and statistics settle (Curvature).
Why decay?
With a constant rate, SGD keeps bouncing in a noise ball around the minimum, with size proportional to the learning rate (Mini-Batch SGD). Decaying the rate shrinks the ball. Large rates early make fast progress; small rates late refine.
Common schedules
With peak rate , warmup length and total steps :
is linear warmup plus cosine decay, the most common LLM schedule (with often ). Others: step decay (divide by 10 at fixed epochs, classic ResNets), inverse square root (the original transformer), and warmup-stable-decay (constant, then a short final decay), which makes it easy to continue training.
import numpy as np
def cosine(t, T=1000, Tw=100, lr_max=3e-4, lr_min=3e-5):
if t < Tw: return lr_max * t / Tw
return lr_min + 0.5 * (lr_max - lr_min) * (1 + np.cos(np.pi * (t - Tw) / (T - Tw)))
def wsd(t, T=1000, Tw=100, Td=200, lr_max=3e-4, lr_min=3e-5):
if t < Tw: return lr_max * t / Tw
if t < T - Td: return lr_max
return lr_max + (lr_min - lr_max) * (t - (T - Td)) / Td
for t in (0, 50, 100, 300, 550, 800, 900, 1000):
print(f"step {t:4d}: cosine {cosine(t):.2e} warmup-stable-decay {wsd(t):.2e}")step 0: cosine 0.00e+00 warmup-stable-decay 0.00e+00
step 50: cosine 1.50e-04 warmup-stable-decay 1.50e-04
step 100: cosine 3.00e-04 warmup-stable-decay 3.00e-04
step 300: cosine 2.68e-04 warmup-stable-decay 3.00e-04
step 550: cosine 1.65e-04 warmup-stable-decay 3.00e-04
step 800: cosine 6.16e-05 warmup-stable-decay 3.00e-04
step 900: cosine 3.81e-05 warmup-stable-decay 1.65e-04
step 1000: cosine 3.00e-05 warmup-stable-decay 3.00e-05
Gradient clipping
Clipping by global norm rescales the whole gradient when its norm exceeds a threshold :
The direction is unchanged; only the length is capped. Clipping each component separately (clip by value) would change the direction. Typical is 1.0 for transformers. Clipping matters most for RNNs (Vanishing and Exploding Gradients) and for loss spikes in large-scale training.
import numpy as np
def clip_by_norm(grads, c):
total = np.sqrt(sum(np.sum(g**2) for g in grads))
scale = min(1.0, c / (total + 1e-6))
return [g * scale for g in grads], total
grads = [np.array([3.0, 4.0]), np.array([[12.0]])] # global norm 13
clipped, norm = clip_by_norm(grads, 1.0)
print("global norm before:", norm)
print("clipped:", [np.round(g, 4).tolist() for g in clipped])
print("norm after:", round(np.sqrt(sum(np.sum(g**2) for g in clipped)), 4))
v = np.clip(np.array([3.0, 4.0, 12.0]), -1, 1)
print("clip by value instead:", v, "-> direction changed:", not np.allclose(v / np.linalg.norm(v), np.array([3, 4, 12]) / 13))global norm before: 13.0
clipped: [[0.2308, 0.3077], [[0.9231]]]
norm after: 1.0
clip by value instead: [1. 1. 1.] -> direction changed: True
Finding the learning rate
A learning-rate range test trains briefly while increasing exponentially and records the loss; a good peak is somewhat below where the loss starts to rise. For large models, P-style parametrizations let a rate tuned on a small model transfer to a large one.
In software
torch.optim.lr_scheduler.CosineAnnealingLR,LinearLRfor warmup,SequentialLRto chain them;transformers.get_cosine_schedule_with_warmup.torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)returns the pre-clip norm, a useful quantity to log.- With mixed precision and loss scaling, unscale the gradients before clipping.
Go further: Learning-Rate Schedules and Warm-Up compares a constant and a decaying schedule on a real run.
Exercises
Exercise 1: Warmup value
Linear warmup to over 2000 steps. What is the rate at step 500?
Answer
.
Solution
.
Exercise 2: Cosine midpoint
In the cosine phase, what is the rate exactly halfway between the end of warmup and the end of training?
Answer
.
Solution
At the midpoint the cosine argument is , , giving .
Exercise 3: Clipping factor (code)
A gradient has global norm 250 and the threshold is 1. What factor multiplies it, and what happens to a gradient of norm 0.4?
Answer
; the small gradient is untouched.
Solution
for n in (250.0, 0.4):
print(n, min(1.0, 1.0 / n))250.0 0.004
0.4 1.0
Test yourself
Why use learning-rate warmup?
- To save memory
- Early steps face sharp curvature and noisy optimizer statistics, so full-size steps can diverge
- To make training longer
- Warmup is only for SGD
Clipping by global norm…
- changes the gradient's direction
- rescales the whole gradient to at most norm , keeping its direction
- sets large components to
- removes the gradient
Why decay the learning rate late in training?
- To shrink the SGD noise ball around the minimum
- To increase overfitting
- To speed up early training
- Because gradients grow