Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Learning rate scheduler

In the previous chapter, Adam adjusted the effective step size of each parameter individually. Another hyperparameter related to the step size is the learning rate, which we have still been tuning by hand.

So far, the learning rate has been fixed once training starts: whatever it was at the beginning, it stays the same until the end. But this is not reasonable:

  • Early in training: the parameters are still randomly initialized and the gradient direction is unreliable. If we rush ahead with a large learning rate from the start, we can easily go off course;

  • Late in training: the model is already close to the optimum and needs careful fine-tuning rather than more big steps. Otherwise it swings back and forth around the optimum, or even jumps out of it.

In this chapter, we introduce automatic tuning: a learning rate scheduler changes the learning rate dynamically during training. We will use the scheme most commonly used to train large models: warmup and cosine annealing.

  • Warmup: early in training, the learning rate starts from 0 and gradually climbs to its maximum;

  • Cosine annealing: after warmup, the learning rate falls smoothly from the maximum to the minimum along a cosine curve.

Tensor

Dataset

Abstract class

Character-encoding dataset

Model

Abstract layer

Linear layer

Composite layer

Sequential layer

Embedding layer

Activation functions

Hyperbolic tangent (Tanh)

Loss functions

Abstract class

Cross-entropy loss function

Optimizers

Abstract class

Adaptive moment estimation optimizer

Adaptive moment estimation with weight decay optimizer

Learning rate scheduler (warmup cosine annealing)

To create a learning rate scheduler, we need to provide four initialization parameters:

  • lr (learning rate): the learning rate we have been using all along, which is also the maximum learning rate reached after warmup;

  • total_steps (total steps): the number of steps in the whole training process;

  • warmup_steps (warmup steps): the number of steps in the warmup phase;

  • min_lr (minimum learning rate): the minimum value the learning rate falls to late in training.

Warmup

In the first warmup_steps steps of training, the learning rate climbs linearly from 0 to the maximum lr:

lrt=lr⋅twarmup_stepslr_t = lr \cdot \frac{t}{warmup\_steps}

Where:

  • lrtlr_t: the current learning rate;

  • tt: the current step count (counted from 1, which corresponds to current_step + 1 in the code).

Cosine annealing

After warmup, the learning rate has reached its maximum, and then falls smoothly along a cosine curve from the maximum to the minimum min_lrmin\_lr:

lrt=min_lr+(lr−min_lr)⋅1+cos⁡(π⋅t−warmup_stepstotal_steps−warmup_steps)2lr_t = min\_lr + (lr - min\_lr) \cdot \frac{1 + \cos(\pi \cdot \frac{t - warmup\_steps}{total\_steps - warmup\_steps})}{2}

Where:

  • lrtlr_t: the current learning rate;

  • tt: the current step count (which corresponds to current_step in the code).

The benefit of annealing along a cosine curve is that the step size goes slow, then fast, then slow again. So over the whole training run, the learning rate is like driving a car: a slow start (warmup), acceleration to cruising speed in the middle, and a smooth slowdown as you near the destination (cosine annealing). This is the standard training rhythm of large models such as GPT.


The learning rate scheduler provides only one method:

  • step (step method): computes the new learning rate from the current step count.

Recurrent neural network

Recurrent cell

RNN model

Trainer

Abstract class

RNN trainer

In the trainer, every step first calls the step method step of the learning rate scheduler to get the latest learning rate.

Hyperparameters

Learning rate

With a learning rate scheduler, LEARNING_RATE is in fact used as the maximum learning rate. The scheduler lowers the average learning rate, so we can raise it a little, and set the minimum learning rate to 1/10 of the maximum.

Batch size

Number of epochs

Context size

Embedding size

Modeling

Training

Before training the model, we first create an instance of the learning rate scheduler and pass it to the training method. The initialization parameters here mean:

  • LEARNING_RATE: the maximum learning rate;

  • EPOCHS * len(dataset): the total number of training steps;

  • 100: the number of warmup steps;

  • LEARNING_RATE / 10: the minimum learning rate.

Evaluation

prediction:	32 steps, each (6970, 65)
total loss:	Tensor(64.7635956614507)

Inference

ROMEO:
Hat that, he you!
You spelr gexssigean I'red
ho,
That his whirovellm to waind:
Ye Gosis
The rest patiet,
Pervunded mantlacem! But do stay,
Hath muthood;
I wore not hanted gaing, you knes is not thought be but what you a you geeden Hartion as bearter a Pro

In this chapter, we implemented automatic tuning of the learning rate: warmup lets training start smoothly, and cosine annealing lets it converge finely at the end. With that, the three practical workhorses of model training, the Adam optimizer, gradient clipping, and learning rate scheduling, are all in place. This is also the standard setup for training large models.

Looking back over chapters 11 to 16, we started from digitizing text and implemented an RNN, creating a model that can read text.

But we must point out that the RNN has inherent flaws, limited memory and no parallelism, which keep it from carrying the weight of building a real large language model. In the next part, we take a completely new approach, the attention mechanism, and build a real GPT model step by step.

Exercises

  1. Try changing the initialization parameters of the learning rate scheduler. For example, set the warmup steps to 0 (no warmup) or to a very large number, or set the minimum learning rate to 0 so that the learning rate finally falls to 0. Observe whether training gets faster or slower and whether the results get better or worse.