AI Logic

Learning Rate Schedulers

WSD (Warmup-Stable-Decay)

Updated:

Graph of WSD and cosine learning rates. The horizontal axis is the number of training tokens (N is the number of model parameters), and the vertical axis is the learning rate relative to the maximum Ī·. After warmup, WSD holds the rate constant at Ī· and lowers it only over a short interval: 40N–44N when stopping at 40N, and 80N–88N when extending to 80N. The two WSD runs share the constant phase. The cosine schedules for comparison, one for 40N and one for 80N, are separate curves from the start for each length

What Is WSD

WSD (Warmup-Stable-Decay) is a learning rate scheduler that splits training into three phases, "warmup," "stable," and "decay," keeping the learning rate constant at its maximum for a long time and lowering it only in a short final phase (about 10% of the total). The MiniCPM paper (Hu et al., 2024) proposed it for pretraining small language models.

Until then, cosine annealing was widely used for language model pretraining. Cosine works best when the step TT at which the learning rate reaches its minimum matches the total number of steps SS, and results get worse if TT is either too short or too long (Figure 4 of the MiniCPM paper, consistent with observations by Kaplan et al. (2020) and Hoffmann et al. (2022)). As a result, the training length had to be decided in advance, and extending training later meant starting over from scratch.

With WSD, the constant phase has the same shape wherever it is stopped, so starting a decay phase from a model partway through it yields a "fully trained model" at any time. To keep training further, training can be resumed at the constant learning rate from the model before decay (the figure at the top).

Theory (How the Learning Rate Is Set)

The WSD procedure is as follows.

  1. Choose the maximum learning rate Ī·\eta and the warmup length WW. During warmup, the learning rate rises linearly from 0 to Ī·\eta (warmup).
  2. During the stable phase, keep the learning rate constant at Ī·\eta. The end of this phase, TT, need not be decided in advance.
  3. When you want to finish training, enter the decay phase from that point TT. Lower the learning rate following a decreasing function ff.
  4. Make the decay phase about 10% of the total.

The MiniCPM paper writes the learning rate at step ss as follows (Eq. (1)). SS is the step at which training ends.

WSD(T;s)={sW η,s<WĪ·,W<s<Tf(sāˆ’T) η,T<s<S\mathrm{WSD}(T; s) = \begin{cases} \dfrac{s}{W}\,\eta, & s < W \\[4pt] \eta, & W < s < T \\[4pt] f(s - T)\,\eta, & T < s < S \end{cases}

ff is a decreasing function with 0<f(sāˆ’T)≤10 < f(s - T) \le 1; its shape is not fixed. The paper writes the setting that keeps the stable phase until TT and continues the decay phase for DD as WSD(T,D)\mathrm{WSD}(T, D); for example, WSD(40N,4N)\mathrm{WSD}(40N, 4N) means "constant until 40N40N tokens, then lowered over 4N4N tokens" (NN is the number of model parameters).

MiniCPM (2.4B and 1.2B) used the following settings in its main training.

ItemSetting
OptimizerAdam
Maximum learning rate0.01
Batch sizeAbout 3.93 million tokens
Stable phaseAbout 1 trillion tokens
Decay functionExponential (the paper's formula is f(sāˆ’T)=0.5(sāˆ’S)/Tf(s - T) = 0.5^{(s - S)/T}, where this TT is 5000 steps = 20 billion tokens; the learning rate halves every 5000 steps)

Warmup is considered to have little effect on the results as long as it is long enough, and the paper omits it in the rest of its discussion. The key to WSD is separating the "constant phase" from the "short decay phase."

Why It Works

The MiniCPM paper attributed cosine's best performance at T=ST = S to two factors.

  • A long period at a high learning rate: Training for a long time with a large learning rate allows wide exploration of parameter space
  • A period of fully lowering the learning rate: Lowering the learning rate thoroughly at the end lets training descend to the bottom of the valley it has reached

WSD separates these two clearly into distinct phases. It explores widely in the stable phase and descends to the bottom in the decay phase.

The paper's analysis (Section 4.4) also shows different behavior in the two phases. For MiniCPM-2.4B, in the stable phase the weights were updated substantially while the loss barely fell, whereas in the decay phase the weight changes were small but the loss fell quickly. For a 0.2B model, entering the decay phase aligned the gradient directions of consecutive steps (the cosine between gradients was almost always positive), the gradient magnitude shrank, and the curvature of the loss grew by an order of magnitude. The paper interprets this as a sign of approaching a local optimum.

As an analogy, the stable phase is time spent striding across wide mountains in search of a low valley, and the decay phase is time spent taking small steps down to the bottom of the valley found. The search can be extended as long as desired, and the descent takes only a short time at the end.

Experimental Results

Experiments with a 0.036B (36 million parameter) model in the MiniCPM paper (Figures 5 and 6) confirmed the following.

ObservationDetails
Loss drops sharply in the decay phaseOnce the learning rate starts falling, the loss drops quickly, reaching a loss equal to or lower than cosine (T=ST = S) with the same number of tokens
Decay over 10% of the total is enoughDecaying from three intermediate models at 40N, 60N, and 80N, a decay of 10% of all tokens gave the best results, and 2.5% was not enough
Training can be extendedContinuing at the high learning rate from the model before decay and decaying later reaches the same loss as a longer cosine
A small model can catch up with a larger oneTraining the 0.036B model longer reached the same loss as a 0.17B model trained on 40N tokens, using about 4 times the training compute (with about one fifth the inference compute per pass)

Because a "fully trained model" can be produced from intermediate models any number of times, experiments measuring scaling laws (the relationship between model size, data amount, and loss) also become cheaper. Previously, trying mm model sizes and mm data amounts required about O(m2)O(m^2) training runs, but with WSD the results for multiple data amounts can be extracted from one run, so the paper states that about O(m)O(m) runs suffice.

The data used in the decay phase can also be chosen carefully. The paper experimented with mixing high-quality data (such as instruction-following data) into the decay phase (Table 1). For an intermediate MiniCPM-2.4B model, mixing in high-quality data (A-2) instead of using only pretraining data in the decay phase (A-1) raised MMLU from 44.6 to 50.9 and GSM8K from 27.7 to 42.3 after the same additional training.

Practical Considerations

Evaluating a model from the stable phase as-is does not reveal its true capability. The learning rate is still high, so the loss has not fully come down. To check the performance of an intermediate model, run a short decay phase from that model before evaluating.

PyTorch's torch.optim.lr_scheduler has no dedicated WSD class. Write the three-phase formula with LambdaLR, or use get_wsd_schedule from Hugging Face Transformers (the decay shape can be chosen from linear, cosine, and 1-sqrt; the default is cosine).

Also note the following points.

  • To extend training, resume from the model before decay: Instead of raising the learning rate again on a model that has finished decaying, resume at the constant learning rate from the model (and optimizer state) saved just before decay. Save the model periodically during the stable phase.
  • Do not make the decay phase too short: In the paper, 10% of the total was enough and 2.5% was not.
  • Choose a maximum learning rate at which training does not break down even in the constant phase: Because the learning rate stays at its maximum for a long time, choose it while watching that the loss does not spike. MiniCPM used Tensor Programs to keep the learning rate largely independent of model size, and chose 0.01 from small-model experiments (confirming that 0.01 was also best at 2.1B).

Comparison with Other Learning Rate Schedulers

WSD and the schedulers it is often compared with are lined up from the same viewpoint.

SchedulerHow the learning rate decreasesWhat must be fixed in advanceSuited for
Step decayDrops in steps at set timesWhen to drop and by how muchReproducing tasks with established settings
Cosine annealingDecreases smoothly along a cosineTotal steps, maximum, minimumMany tasks with a fixed total number of steps
Polynomial decayDecreases toward 0 along a polynomialTotal steps and degreeSemantic segmentation and similar
One CycleRises once, then drops sharplyTotal steps, maximumFast convergence in short training
WSDHolds constant, then decreases in a short final phaseMaximum and decay length (when to start decaying can be decided later)Pretraining large language models and similar

In the four schedulers other than WSD, the learning rate is tied to the overall training length, so changing the length changes the whole curve. Apart from the decay phase, WSD does not depend on the length.

Guidelines for choosing:

  • If the training length is undecided or may be extended later, use WSD: Training can be finished at any time by decaying from partway through the constant phase.
  • To compare several settings of different lengths, use WSD: From one run, multiple results can be extracted by changing when decay starts.
  • If the training length is fixed and you train only once, cosine annealing is also fine: In the paper's experiments, WSD reached a loss equal to or slightly lower than cosine of the same length, which is not a large difference.

PyTorch example

Show code
python
import math
import torch
import torch.nn as nn

model = nn.Sequential(nn.Embedding(1000, 64), nn.Flatten(), nn.Linear(64 * 16, 1000))   # dummy language model
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.01)    # Ī· = 0.01 (peak learning rate)

warmup, stable_end, decay = 100, 9000, 1000                  # W, T, decay length (10% of total)

def wsd(step, decay_type="exp"):
    """Return the multiplier on Ī· (MiniCPM Eq. (1))"""
    if step < warmup:                                        # warmup: s / W
        return step / warmup
    if step < stable_end:                                    # stable: 1 (stays at Ī·)
        return 1.0
    p = min(step - stable_end, decay) / decay                # progress through the decay phase, 0 to 1
    if decay_type == "linear":
        return 1.0 - p                                       # linearly down to 0
    return 0.5 ** (p * 5)                                    # exponential: halves every 1/5 of the decay (1/32 at the end)

# PyTorch has no dedicated WSD class, so use LambdaLR. Call step() every step (mini-batch)
scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, lr_lambda=wsd)

model.train()
for step in range(stable_end + decay):
    tokens = torch.randint(0, 1000, (8, 16))
    target = torch.randint(0, 1000, (8,))
    optimizer.zero_grad()
    loss = criterion(model(tokens), target)
    loss.backward()
    optimizer.step()
    scheduler.step()
    if step == stable_end - 1:
        # Saving the model just before decay lets you extend training later at the constant learning rate
        ckpt = {"model": model.state_dict(), "optimizer": optimizer.state_dict(), "scheduler": scheduler.state_dict()}

# With Hugging Face Transformers:
# from transformers import get_wsd_schedule
# scheduler = get_wsd_schedule(optimizer, num_warmup_steps=100, num_decay_steps=1000,
#                              num_training_steps=10000, decay_type="linear", min_lr_ratio=0.0)

FAQ

Q. What shape should be used to lower the rate in the decay phase?
A.

In the MiniCPM paper's formula, any decreasing function works, and the shape is not fixed. MiniCPM's main training used an exponential shape (halving every fixed number of steps). Hugging Face Transformers' get_wsd_schedule offers linear, cosine, and 1āˆ’āˆš shapes.

Q. How long should the decay phase be?
A.

In the MiniCPM paper's experiments, a decay of 10% of all tokens gave the best results, and 2.5% was not enough. Starting with about 10% of the total is a good rule of thumb.

Q. Can it be used outside language models, such as for image classification?
A.

In terms of the formula, it can be used for any training. However, the MiniCPM paper verified its effect on language model pretraining. For other tasks with a fixed training length, it is safer to choose by comparing it with cosine annealing and others.

References

  1. S. Hu et al., "MiniCPM: Unveiling the Potential of Small Language Models with Scalable Training Strategies," arXiv:2404.06395, 2024.
  2. J. Kaplan et al., "Scaling Laws for Neural Language Models," arXiv:2001.08361, 2020.
  3. J. Hoffmann et al., "Training Compute-Optimal Large Language Models," arXiv:2203.15556, 2022.
  4. Hugging Face Transformers Documentation, "Optimization" (get_wsd_schedule).
  5. PyTorch Documentation, "LambdaLR."