To perform cosine decay for learning rate scheduling in PyTorch, you can use the built-in torch.optim.lr_scheduler.CosineAnnealingLR or CosineAnnealingWarmRestarts. These classes implement cosine annealing, which reduces the learning rate following a cosine curve from an initial value to zero (or restarts it periodically).
Here's how to use CosineAnnealingLR:
🔁 CosineAnnealingLR (Basic Cosine Decay)
import torch
import torch.nn as nn
import torch.optim as optim
from torch.optim.lr_scheduler import CosineAnnealingLR
# Example model and optimizer
model = nn.Linear(10, 2)
optimizer = optim.SGD(model.parameters(), lr=0.1)
# Define the scheduler
scheduler = CosineAnnealingLR(optimizer, T_max=50, eta_min=0) # T_max is the half period
T_max: Number of epochs/iterations for one full cosine cycle (half period).
eta_min: Minimum learning rate (default is 0).
Then, during training, call scheduler.step() after each epoch:
for epoch in range(100):
# Training loop
...
scheduler.step()
🔁 CosineAnnealingWarmRestarts (Cyclic Cosine Decay with Warm Restarts)
If you want to restart the cosine schedule periodically (e.g., for better convergence), use:
from torch.optim.lr_scheduler import CosineAnnealingWarmRestarts
scheduler = CosineAnnealingWarmRestarts(optimizer, T_0=10, T_mult=2)
T_0: Number of epochs in the first cycle.
T_mult: Multiplication factor for subsequent cycles.
Call scheduler.step() after each epoch (or batch, depending on your use case):
for epoch in range(100):
for batch in dataloader:
...
scheduler.step()
📈 Optional: Visualizing LR Schedule
You can visualize the learning rate changes like this:
import matplotlib.pyplot as plt
lrs = []
model = nn.Linear(10, 2)
optimizer = optim.SGD(model.parameters(), lr=0.1)
scheduler = CosineAnnealingLR(optimizer, T_max=50)
for _ in range(100):
lrs.append(optimizer.param_groups[0]['lr'])
scheduler.step()
plt.plot(lrs)
plt.title("Cosine Annealing Learning Rate")
plt.xlabel("Epoch")
plt.ylabel("Learning Rate")
plt.show()
✅ Summary
| Scheduler | Use Case |
|---|
CosineAnnealingLR | Standard cosine decay over training |
CosineAnnealingWarmRestarts | Cyclic cosine decay with warm restarts |
Let me know if you want to combine cosine decay with warmup, or apply it per iteration instead of per epoch!