Lecture 11: Optimization and Learning Rates

Lecture notes on optimization methods, learning rate schedules, momentum, and adaptive optimizers in deep learning.

1. Introduction to Optimization

Training a deep neural network involves finding model parameters that minimize a loss function. Optimization algorithms update these parameters iteratively using gradients computed through backpropagation.

The basic gradient descent update is

\theta_{t+1} = \theta_t - \eta_t \nabla_\theta L(\theta_t)

where:

The learning rate determines how far the parameters move in the direction opposite to the gradient.

1.1 Challenges in Deep Learning Optimization

Deep neural networks typically have non-convex loss functions. This makes optimization challenging because the loss surface may contain saddle points, flat regions, and regions with very different curvatures.

A learning rate that is too large can cause unstable updates or oscillations. A learning rate that is too small can make training unnecessarily slow.

Choosing an appropriate optimization algorithm and learning rate schedule is therefore important for efficient training.

2. Batch Size and Learning Rate

In deep learning, the batch size determines how many training examples are used to estimate the gradient before updating the model parameters. The choice of batch size affects the stability, computational efficiency, and behavior of the optimization process.

2.1 Full-Batch, Stochastic, and Mini-Batch Gradient Descent

There are three common approaches to computing gradients:

For a mini-batch of size B, the gradient estimate is

g_t = \frac{1}{B}\sum_{i=1}^{B} \nabla_\theta \ell_i(\theta_t)

where \ell_i is the loss for training example i in the mini-batch.

The parameter update becomes

\theta_{t+1} = \theta_t - \eta_t g_t

2.2 How Batch Size Affects Optimization

Smaller batches generally produce noisier gradient estimates. This noise can help the optimizer explore the loss surface, but it can also cause fluctuations during training.

Larger batches generally produce more stable gradient estimates and can take advantage of parallel computation on GPUs. However, they require more memory and may provide fewer parameter updates per epoch.

2.3 Relationship Between Batch Size and Learning Rate

Batch size and learning rate are closely related. When the batch size increases, the gradient estimate often becomes less noisy, which may allow a larger learning rate.

However, increasing the learning rate proportionally with batch size is not always optimal. The appropriate learning rate depends on the model architecture, optimizer, dataset, and training conditions.

In practice, batch size and learning rate should be tuned together rather than independently.

3. Learning Rate Schedules

The learning rate controls the size of each parameter update during optimization. Instead of using a constant learning rate throughout training, we can adjust it over time using a learning rate schedule.

A relatively large learning rate can help the model make faster progress early in training, while a smaller learning rate can help stabilize training and refine the parameters later.

3.1 Exponential Decay

Exponential decay gradually reduces the learning rate by multiplying it by a constant factor:

\eta_t = \eta_0 \gamma^t

where \eta_0 is the initial learning rate and 0 < \gamma < 1 is the decay factor.

This schedule produces a smooth decrease in the learning rate over time.

3.2 Step Decay

Step decay reduces the learning rate at specific intervals rather than continuously.

For example, the learning rate can be halved every K epochs:

\eta_t = \eta_0 \left(\frac{1}{2}\right)^{\lfloor t/K \rfloor}

This allows the optimizer to make larger updates initially and smaller updates later.

3.3 Inverse Time Decay

Inverse time decay decreases the learning rate according to

\eta_t = \frac{\eta_0}{1 + kt}

where k > 0 controls how quickly the learning rate decreases.

Unlike exponential decay, inverse time decay decreases more slowly during later stages of training.

3.4 Cyclical Learning Rates

Cyclical learning rate schedules periodically increase and decrease the learning rate between predefined bounds.

The purpose is to allow the optimizer to explore different regions of the loss surface instead of continuously decreasing the step size.

A larger learning rate can encourage exploration, while a smaller learning rate allows more careful parameter updates.

3.5 Cosine Annealing

Cosine annealing decreases the learning rate following a cosine-shaped curve:

\eta_t = \eta_{\min} + \frac{1}{2}(\eta_{\max}-\eta_{\min})\left(1+\cos\left(\frac{\pi t}{T}\right)\right)

where T is the duration of the schedule, and \eta_{\max} and \eta_{\min} are the maximum and minimum learning rates.

This schedule smoothly decreases the learning rate toward its minimum value.

3.6 Learning Rate Warmup

Learning rate warmup starts training with a small learning rate and gradually increases it to the target value.

A simple linear warmup schedule is

\eta_t = \eta_{\max}\frac{t}{T_w}

for 0 \leq t \leq T_w, where T_w is the number of warmup steps. Warmup can help prevent unstable parameter updates at the beginning of training, particularly when using large batch sizes.

After warmup, another learning rate schedule, such as cosine annealing, is often applied.

3.7 Early Stopping

Early stopping is another practical strategy for controlling training.

Instead of choosing a fixed number of training epochs, we monitor performance on a validation dataset and stop training when validation performance no longer improves.

Early stopping can reduce unnecessary computation and help prevent overfitting. Unlike learning rate decay, it determines when training should stop rather than changing the step size.

3.8 Learning Rate Schedulers in PyTorch

PyTorch provides built-in learning rate schedulers that automatically adjust the learning rate during training. Instead of manually updating the learning rate, we can define a schedule and apply it throughout the training process.

One useful option is torch.optim.lr_scheduler.LambdaLR, which allows us to specify a custom function that determines the learning rate multiplier.

For example, suppose we want to reduce the learning rate by half every 10 epochs:

import torch

optimizer = torch.optim.SGD(model.parameters(), lr=0.1)

scheduler = torch.optim.lr_scheduler.LambdaLR(
    optimizer,
    lr_lambda=lambda epoch: 0.5 ** (epoch // 10)
)

for epoch in range(30):
    model.train()

    for inputs, targets in train_loader:
        optimizer.zero_grad()
        outputs = model(inputs)
        loss = criterion(outputs, targets)
        loss.backward()
        optimizer.step()

    scheduler.step()
    print(f"Epoch {epoch + 1}: LR = {scheduler.get_last_lr()[0]:.5f}")

In this example, the learning rate starts at 0.1 and decreases by a factor of 0.5 every 10 epochs. The scheduler.step() method is called after the training updates for each epoch.

PyTorch also provides other schedulers, such as StepLR, ExponentialLR, and CosineAnnealingLR.

An important practical consideration is that the scheduler’s state should be saved along with the model and optimizer when training needs to be resumed:

torch.save({
    'model_state_dict': model.state_dict(),
    'optimizer_state_dict': optimizer.state_dict(),
    'scheduler_state_dict': scheduler.state_dict()
}, 'checkpoint.pth')

Saving these states allows training to resume with the correct parameters, optimizer history, and learning rate schedule.

4. Momentum and Stochastic Gradient Descent

4.1 Limitations of Standard SGD

Stochastic Gradient Descent (SGD) updates model parameters in the opposite direction of the gradient:

\theta_{t+1} = \theta_t - \eta \nabla L(\theta_t)

Although SGD is simple and widely used, it can be inefficient when the loss surface has different curvatures in different directions.

For example, consider a narrow valley in the loss landscape. The gradient may point toward the opposite side of the valley rather than along the valley toward the minimum. As a result, SGD can oscillate from one side to the other, slowing down convergence.

4.2 Momentum

Momentum improves SGD by incorporating information from previous gradient updates. Instead of relying only on the current gradient, it maintains a running average of past gradients.

A common formulation is:

v_t = \mu v_{t-1} + g_t \theta_{t+1} = \theta_t - \eta v_t

where:

Momentum reduces oscillations by combining gradient information across iterations. In a narrow valley, gradient components pointing across the valley tend to cancel, while components pointing along the valley accumulate.

This allows the optimizer to move more efficiently toward the minimum.

4.3 Momentum in PyTorch

PyTorch supports momentum through the SGD optimizer:

import torch

optimizer = torch.optim.SGD(
    model.parameters(),
    lr=0.01,
    momentum=0.9
)

The momentum parameter controls how strongly previous gradient updates influence the current update.

PyTorch also provides a dampening parameter, which modifies the contribution of new gradients to the momentum buffer.

4.4 Nesterov Momentum

Nesterov Accelerated Gradient (NAG) is an extension of classical momentum that uses a look-ahead strategy to improve the direction of parameter updates.

In classical momentum, the optimizer combines the current gradient with accumulated information from previous iterations. However, the gradient is evaluated at the current parameter position.

Nesterov momentum instead considers where the previous momentum would move the parameters before evaluating the gradient. This allows the optimizer to anticipate the effect of momentum and make a correction earlier.

Using the parameter-displacement formulation, the update can be written as:

v_t = \mu v_{t-1} + \eta \nabla_\theta L(\theta_t - \mu v_{t-1}) \theta_{t+1} = \theta_t - v_t

where:

The main difference between classical momentum and Nesterov momentum is the location at which the gradient is evaluated.

This look-ahead correction can reduce overshooting and improve convergence in some optimization problems.

PyTorch supports Nesterov momentum through the SGD optimizer:

import torch

optimizer = torch.optim.SGD(
    model.parameters(),
    lr=0.01,
    momentum=0.9,
    nesterov=True
)

Note that PyTorch uses an algebraically related implementation of Nesterov momentum rather than explicitly evaluating the gradient at a separate look-ahead position.

4.5 Gradient Clipping

Gradient clipping is a technique used to prevent excessively large gradients from causing unstable parameter updates during neural network training.

Deep neural networks can sometimes experience exploding gradients, especially when gradients are propagated through many layers or time steps. Large gradients may cause the optimizer to take excessively large steps, leading to unstable training.

One common approach is gradient norm clipping, which rescales the gradient vector when its norm exceeds a predefined threshold.

Let g represent the gradient vector and c represent the maximum allowed norm.

The clipped gradient is defined as:

g_{\text{clipped}} = \begin{cases} g, & \|g\|_2 \leq c \\ \frac{c}{\|g\|_2}g, & \|g\|_2 > c \end{cases}

This operation preserves the direction of the gradient while reducing its magnitude when necessary.

For example, suppose the gradient vector is:

g = (6,8)

Its L2 norm is:

\|g\|_2 = \sqrt{6^2+8^2}=10

If the clipping threshold is c=5, the gradient becomes:

g_{\text{clipped}} = \frac{5}{10}(6,8)=(3,4)

The direction remains unchanged, but the norm is reduced from 10 to 5.

In PyTorch, gradient clipping can be implemented using torch.nn.utils.clip_grad_norm_():

import torch

optimizer.zero_grad()

outputs = model(inputs)
loss = criterion(outputs, targets)

loss.backward()

torch.nn.utils.clip_grad_norm_(
    model.parameters(),
    max_norm=1.0
)

optimizer.step()

Gradient clipping should be applied after loss.backward() and before optimizer.step(), so that the gradients are limited before the optimizer updates the parameters.

Unlike learning rate scheduling, gradient clipping does not directly change the learning rate. Instead, it limits the magnitude of unusually large gradients to improve training stability.

5. Adaptive Optimization Methods

5.1 Why Adaptive Learning Rates?

Standard SGD uses the same learning rate for all model parameters. However, different parameters may have gradients of different magnitudes.

Adaptive optimization methods address this problem by adjusting the effective learning rate for each parameter based on its gradient history.

These methods can improve training efficiency and reduce the need for manually tuning a single learning rate.

5.2 AdaGrad

AdaGrad adapts the learning rate using the accumulated squared gradients.

Let g_t be the gradient at iteration t. The accumulated squared gradient is

G_t = G_{t-1} + g_t^2

The parameter update is

\theta_{t+1} = \theta_t - \frac{\eta}{\sqrt{G_t}+\epsilon}g_t

All operations involving G_t are performed element-wise.

AdaGrad gives smaller effective learning rates to parameters with large accumulated gradients.

However, because G_t continuously increases, the effective learning rate may become too small during long training runs.

5.3 RMSProp

RMSProp addresses AdaGrad’s continuously decreasing learning rates by using an exponential moving average of squared gradients.

s_t = \beta s_{t-1} + (1-\beta)g_t^2

The parameter update is

\theta_{t+1} = \theta_t - \frac{\eta}{\sqrt{s_t}+\epsilon}g_t

Here, \beta controls how much information from previous gradients is retained.

Unlike AdaGrad, RMSProp gives more weight to recent gradients rather than accumulating all past squared gradients equally.

5.4 Adam Optimizer

Adam stands for Adaptive Moment Estimation. It combines ideas from momentum and adaptive learning rates.

Adam maintains two moving averages:

m_t = \beta_1 m_{t-1} + (1-\beta_1)g_t v_t = \beta_2 v_{t-1} + (1-\beta_2)g_t^2

Because both moving averages are initialized at zero, Adam applies bias correction:

\hat{m}_t = \frac{m_t}{1-\beta_1^t} \hat{v}_t = \frac{v_t}{1-\beta_2^t}

The parameter update is

\theta_{t+1} = \theta_t - \eta \frac{\hat{m}_t}{\sqrt{\hat{v}_t}+\epsilon}

Common default values are:

Adam uses momentum-like gradient averaging while also scaling updates based on recent squared gradients.

5.5 SGD with Momentum vs. Adam

SGD with momentum uses accumulated gradient information to reduce oscillations and accelerate optimization.

Adam additionally adapts the effective learning rate for each parameter using estimates of the first and second moments.

Adam often makes rapid progress early in training and can work well with limited learning-rate tuning. However, SGD with momentum can sometimes achieve better generalization, depending on the model and task.

Neither optimizer is universally better.

5.6 Adam in PyTorch

PyTorch provides Adam through torch.optim.Adam.

import torch

optimizer = torch.optim.Adam(
    model.parameters(),
    lr=0.001,
    betas=(0.9, 0.999),
    eps=1e-8
)

The lr parameter specifies the base learning rate, while betas controls the exponential moving averages of the gradient and squared gradient.

Adam is widely used in deep learning because it combines adaptive parameter updates with momentum-like behavior.