Cosine decay is a popular learning rate scheduling technique used in training deep learning models. It gradually reduces the learning rate following a cosine function, which often leads to better convergence compared to other methods like step decay. In PyTorch, you can implement cosine decay using the torch.optim.lr_scheduler.CosineAnnealingLR scheduler, which is built into the library, or you can create a custom scheduler if needed.
Below, I'll explain how to use the built-in CosineAnnealingLR scheduler and provide an example of a custom implementation for more flexibility.
1. Using torch.optim.lr_scheduler.CosineAnnealingLR
The CosineAnnealingLR scheduler in PyTorch adjusts the learning rate according to a cosine decay schedule over a specified number of epochs (T_max). The learning rate starts at its initial value, decreases following a cosine function, and reaches a minimum value (default is 0) at the end of the cycle.
Syntax:
torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max, eta_min=0, last_epoch=-1, verbose=False)
optimizer: The optimizer for which the learning rate is scheduled.
T_max: The maximum number of iterations (epochs) for one complete cosine cycle.
eta_min: The minimum learning rate (default is 0).
last_epoch: The index of the last epoch (useful for resuming training; default is -1).
verbose: If True, prints a message to stdout for each update.
Example:
import torch
import torch.nn as nn
import torch.optim as optim
from torch.optim.lr_scheduler import CosineAnnealingLR
# Define a simple model
model = nn.Linear(10, 1)
optimizer = optim.SGD(model.parameters(), lr=0.1)
# Define the cosine annealing scheduler
scheduler = CosineAnnealingLR(optimizer, T_max=50, eta_min=0)
# Training loop (example)
num_epochs = 100
for epoch in range(num_epochs):
# Simulate a training step
optimizer.zero_grad()
output = model(torch.randn(1, 10))
loss = output.sum()
loss.backward()
optimizer.step()
# Update the learning rate
scheduler.step()
# Print the current learning rate
current_lr = optimizer.param_groups[0]['lr']
print(f"Epoch {epoch+1}, Learning Rate: {current_lr:.6f}")
Explanation of the Example:
- The learning rate starts at 0.1 and decreases following a cosine function over 50 epochs (
T_max=50).
- After 50 epochs, the learning rate reaches
eta_min=0, and the cycle restarts (i.e., the learning rate jumps back to 0.1 and starts decaying again).
- If you want the learning rate to decay over the entire training period (e.g., 100 epochs), set
T_max=100.
2. Custom Cosine Decay Implementation
If you need more flexibility (e.g., decay over a specific number of steps, warm-up periods, or a non-zero minimum learning rate without restarting), you can implement a custom cosine decay scheduler. Below is an example of a custom cosine decay scheduler in PyTorch.
Custom Cosine Decay Scheduler:
import torch
import torch.nn as nn
import torch.optim as optim
import math
class CustomCosineDecayScheduler:
def __init__(self, optimizer, max_steps, min_lr=0, warmup_steps=0):
self.optimizer = optimizer
self.max_steps = max_steps
self.min_lr = min_lr
self.warmup_steps = warmup_steps
self.step_count = 0
self.initial_lr = optimizer.param_groups[0]['lr']
def step(self):
self.step_count += 1
if self.step_count <= self.warmup_steps:
# Linear warm-up
lr = self.initial_lr * self.step_count / self.warmup_steps
else:
# Cosine decay
decay_steps = self.max_steps - self.warmup_steps
step = self.step_count - self.warmup_steps
cosine_decay = 0.5 * (1 + math.cos(math.pi * step / decay_steps))
lr = self.min_lr + (self.initial_lr - self.min_lr) * cosine_decay
# Update the learning rate in the optimizer
for param_group in self.optimizer.param_groups:
param_group['lr'] = lr
return lr
# Example usage
model = nn.Linear(10, 1)
optimizer = optim.SGD(model.parameters(), lr=0.1)
# Define the custom scheduler
scheduler = CustomCosineDecayScheduler(optimizer, max_steps=100, min_lr=1e-6, warmup_steps=10)
# Training loop (example)
num_steps = 100
for step in range(num_steps):
# Simulate a training step
optimizer.zero_grad()
output = model(torch.randn(1, 10))
loss = output.sum()
loss.backward()
optimizer.step()
# Update the learning rate
current_lr = scheduler.step()
# Print the current learning rate
print(f"Step {step+1}, Learning Rate: {current_lr:.6f}")
Explanation of the Custom Scheduler:
- Warm-up: During the first
warmup_steps, the learning rate linearly increases from 0 to the initial learning rate (initial_lr).
- Cosine Decay: After the warm-up period, the learning rate decays following a cosine function over the remaining steps (
max_steps - warmup_steps).
- Minimum Learning Rate: The learning rate never goes below
min_lr, unlike the default behavior of CosineAnnealingLR, which resets the cycle.
- Flexibility: This custom scheduler allows you to control the total number of steps, warm-up period, and minimum learning rate without restarting the cycle.
3. Cosine Decay with Restarts (CosineAnnealingWarmRestarts)
If you want cosine decay with periodic restarts (i.e., the learning rate decreases following a cosine function, then jumps back to the initial value and repeats), you can use PyTorch's CosineAnnealingWarmRestarts scheduler. This is useful for training models with cyclical learning rates.
Syntax:
torch.optim.lr_scheduler.CosineAnnealingWarmRestarts(optimizer, T_0, T_mult=1, eta_min=0, last_epoch=-1, verbose=False)
T_0: The number of epochs for the first cycle.
T_mult: A factor by which the cycle length increases after each restart (default is 1, meaning no increase).
eta_min: The minimum learning rate (default is 0).
Example:
import torch
import torch.nn as nn
import torch.optim as optim
from torch.optim.lr_scheduler import CosineAnnealingWarmRestarts
# Define a simple model
model = nn.Linear(10, 1)
optimizer = optim.SGD(model.parameters(), lr=0.1)
# Define the cosine annealing with warm restarts scheduler
scheduler = CosineAnnealingWarmRestarts(optimizer, T_0=10, T_mult=2, eta_min=1e-6)
# Training loop (example)
num_epochs = 50
for epoch in range(num_epochs):
# Simulate a training step
optimizer.zero_grad()
output = model(torch.randn(1, 10))
loss = output.sum()
loss.backward()
optimizer.step()
# Update the learning rate
scheduler.step()
# Print the current learning rate
current_lr = optimizer.param_groups[0]['lr']
print(f"Epoch {epoch+1}, Learning Rate: {current_lr:.6f}")
Explanation of the Example:
- The learning rate starts at 0.1 and decays to
eta_min=1e-6 over 10 epochs (T_0=10).
- After the first cycle, the cycle length doubles (
T_mult=2), so the next cycle takes 20 epochs, then 40 epochs, and so on.
- This approach is useful for training models with cyclical learning rates, which can help escape local minima and improve convergence.
4. Choosing the Right Scheduler
- Use
CosineAnnealingLR if you want a simple cosine decay over a fixed number of epochs without restarts.
- Use
CosineAnnealingWarmRestarts if you want cosine decay with periodic restarts (cyclical learning rates).
- Use a custom scheduler if you need more control, such as warm-up periods, non-zero minimum learning rates, or decay over a specific number of steps rather than epochs.
5. Visualizing the Learning Rate Schedule
To better understand how the learning rate changes over time, you can plot it. Here's an example using Matplotlib:
import torch
import torch.nn as nn
import torch.optim as optim
from torch.optim.lr_scheduler import CosineAnnealingLR
import matplotlib.pyplot as plt
# Define a simple model and optimizer
model = nn.Linear(10, 1)
optimizer = optim.SGD(model.parameters(), lr=0.1)
# Define the scheduler
scheduler = CosineAnnealingLR(optimizer, T_max=50, eta_min=1e-6)
# Collect learning rates over time
lrs = []
num_epochs = 100
for epoch in range(num_epochs):
optimizer.step() # Simulate an optimization step
lrs.append(optimizer.param_groups[0]['lr'])
scheduler.step()
# Plot the learning rate schedule
plt.plot(range(num_epochs), lrs)
plt.xlabel("Epoch")
plt.ylabel("Learning Rate")
plt.title("Cosine Decay Learning Rate Schedule")
plt.show()
This will generate a plot showing how the learning rate changes over time, which can help you tune the hyperparameters of the scheduler.
Summary
- PyTorch provides built-in schedulers like
CosineAnnealingLR and CosineAnnealingWarmRestarts for cosine decay.
- For more flexibility, you can implement a custom scheduler to include features like warm-up, non-zero minimum learning rates, or step-based decay.
- Always visualize the learning rate schedule to ensure it behaves as expected for your training setup.