TExcelTAD
Home › Math for Deep Learning & LLMs › Learning-Rate Schedules and Gradient Clipping

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 ηmax⁡\eta_{\max}, warmup length TwT_w and total steps TT:

ηt={ηmax⁡tTwt<Twηmin⁡+12(ηmax⁡−ηmin⁡)(1+cos⁡(πt−TwT−Tw))t≥Tw\eta_t = \begin{cases} \eta_{\max}\frac{t}{T_w} & t < T_w \\ \eta_{\min} + \frac{1}{2}(\eta_{\max} - \eta_{\min})\left(1 + \cos\left(\pi\frac{t - T_w}{T - T_w}\right)\right) & t \ge T_w \end{cases}

is linear warmup plus cosine decay, the most common LLM schedule (with ηmin⁡\eta_{\min} often 0.1ηmax⁡0.1\eta_{\max}). Others: step decay (divide by 10 at fixed epochs, classic ResNets), inverse square root η∝1/t\eta \propto 1/\sqrt{t} (the original transformer), and warmup-stable-decay (constant, then a short final decay), which makes it easy to continue training.

python · try it yourself
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 cc:

g←g⋅min⁡(1,c∥g∥)\mathbf{g} \leftarrow \mathbf{g}\cdot\min\left(1, \frac{c}{\lVert\mathbf{g}\rVert}\right)

The direction is unchanged; only the length is capped. Clipping each component separately (clip by value) would change the direction. Typical cc is 1.0 for transformers. Clipping matters most for RNNs (Vanishing and Exploding Gradients) and for loss spikes in large-scale training.

python · try it yourself
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 η\eta exponentially and records the loss; a good peak is somewhat below where the loss starts to rise. For large models, μ\muP-style parametrizations let a rate tuned on a small model transfer to a large one.

In software

  • torch.optim.lr_scheduler.CosineAnnealingLR, LinearLR for warmup, SequentialLR to 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 ηmax⁡=6×10−4\eta_{\max} = 6 \times 10^{-4} over 2000 steps. What is the rate at step 500?

Answer

1.5×10−41.5 \times 10^{-4}.

Solution

6×10−4⋅500/2000=1.5×10−46 \times 10^{-4} \cdot 500/2000 = 1.5 \times 10^{-4}.

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

(ηmax⁡+ηmin⁡)/2(\eta_{\max} + \eta_{\min})/2.

Solution

At the midpoint the cosine argument is π/2\pi/2, cos⁡=0\cos = 0, giving ηmin⁡+12(ηmax⁡−ηmin⁡)\eta_{\min} + \frac{1}{2}(\eta_{\max} - \eta_{\min}).

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

0.0040.004; the small gradient is untouched.

Solution
python · try it yourself
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?

  1. To save memory
  2. Early steps face sharp curvature and noisy optimizer statistics, so full-size steps can diverge
  3. To make training longer
  4. Warmup is only for SGD

Clipping by global norm…

  1. changes the gradient's direction
  2. rescales the whole gradient to at most norm cc, keeping its direction
  3. sets large components to cc
  4. removes the gradient

Why decay the learning rate late in training?

  1. To shrink the SGD noise ball around the minimum
  2. To increase overfitting
  3. To speed up early training
  4. Because gradients grow