Learning Rate Schedulers in PyTorch

Control optimization dynamics across real-world deep learning pipelines: StepLR decay on retail SKU classifiers, MultiStepLR milestone drops for traffic sign vision, ExponentialLR smooth annealing in voice VAD, CosineAnnealingLR on medical imaging, CosineAnnealingWarmRestarts (SGDR) in satellite segmentation, LambdaLR warmup + cosine decay for LLM fine-tuning, ReduceLROnPlateau on validation fraud loss, OneCycleLR super-convergence in autonomous perception, CyclicLR triangular/exp_range exploration for tabular credit risk, and differential Layer-Wise Learning Rates + scheduler for fine-tuning.

📈 Real-World Context: Why Learning Rate Scheduling Governs Convergence

A static learning rate forces a trade-off between slow early progress or instability (when too large) and getting stuck in suboptimal basins or oscillating around a minimum (when too small). In production PyTorch pipelines, calling optimizer.step() followed by scheduler.step()—or passing validation metrics into ReduceLROnPlateau.step(val_loss)—adapts step sizes across training phases so models converge faster and generalize better.

Each section below pairs a real-world engineering scenario with a runnable PyTorch scheduler snippet, console output, and an interactive SVG curve visualizer that renders automatically on page load.

StepLR & MultiStepLR ExponentialLR & CosineAnnealingLR CosineAnnealingWarmRestarts (SGDR) & LambdaLR ReduceLROnPlateau · OneCycleLR · CyclicLR · Differential LRs
01 StepLR Decay on a Retail SKU Image Classifier
Real-Life Scenario: A retail warehouse vision model classifies product SKUs across 12 epochs using torch.optim.lr_scheduler.StepLR(optimizer, step_size=4, gamma=0.5)—halving the learning rate every 4 epochs so coarse visual features settle early and fine-grained packaging details refine smoothly later.
Python (retail_sku_steplr.py)
import torch
import torch.nn as nn
from torch.optim.lr_scheduler import StepLR

torch.manual_seed(42)
sku_net = nn.Sequential(nn.Linear(32, 64), nn.ReLU(), nn.Linear(64, 12))
optimizer = torch.optim.AdamW(sku_net.parameters(), lr=1e-3)
scheduler = StepLR(optimizer, step_size=4, gamma=0.5)

x_batch = torch.randn(16, 32)
y_batch = torch.randint(0, 12, (16,))
criterion = nn.CrossEntropyLoss()

lr_trace = []
for epoch in range(1, 13):
    optimizer.zero_grad(set_to_none=True)
    loss = criterion(sku_net(x_batch), y_batch)
    loss.backward()
    optimizer.step()

    cur_lr = scheduler.get_last_lr()[0]
    lr_trace.append((epoch, round(cur_lr, 6), round(loss.item(), 4)))
    scheduler.step()

print("StepLR (step_size=4, gamma=0.5) over 12 epochs:")
for ep, lr_val, l_val in lr_trace:
    if ep in (1, 4, 5, 8, 9, 12):
        print(f"  Epoch {ep:02d} | LR = {lr_val:.6f} | Batch Loss = {l_val:.4f}")
Output:
StepLR (step_size=4, gamma=0.5) over 12 epochs:
  Epoch 01 | LR = 0.001000 | Batch Loss = 2.4981
  Epoch 04 | LR = 0.001000 | Batch Loss = 2.3104
  Epoch 05 | LR = 0.000500 | Batch Loss = 2.2148
  Epoch 08 | LR = 0.000500 | Batch Loss = 2.0912
  Epoch 09 | LR = 0.000250 | Batch Loss = 2.0419
  Epoch 12 | LR = 0.000250 | Batch Loss = 1.9873
02 MultiStepLR Milestone Drops for Traffic Sign Recognition
Real-Life Scenario: An autonomous dashcam traffic-sign classifier trains over 15 epochs with MultiStepLR(optimizer, milestones=[6, 11], gamma=0.2), dropping the learning rate by 5× at curated curriculum milestones (epoch 6 after initial convergence and epoch 11 for fine boundary polish) rather than at fixed intervals.
Python (traffic_sign_multisteplr.py)
import torch
import torch.nn as nn
from torch.optim.lr_scheduler import MultiStepLR

torch.manual_seed(7)
sign_net = nn.Sequential(nn.Linear(48, 64), nn.GELU(), nn.Linear(64, 8))
optimizer = torch.optim.SGD(sign_net.parameters(), lr=2e-2, momentum=0.9)
scheduler = MultiStepLR(optimizer, milestones=[6, 11], gamma=0.2)

x_signs = torch.randn(24, 48)
y_signs = torch.randint(0, 8, (24,))
loss_fn = nn.CrossEntropyLoss()

snapshots = []
for epoch in range(1, 16):
    optimizer.zero_grad(set_to_none=True)
    loss = loss_fn(sign_net(x_signs), y_signs)
    loss.backward()
    optimizer.step()
    snapshots.append((epoch, scheduler.get_last_lr()[0], loss.item()))
    scheduler.step()

print("MultiStepLR (milestones=[6, 11], gamma=0.2):")
for ep, lr_v, ls_v in snapshots:
    if ep in (1, 6, 7, 11, 12, 15):
        print(f"  Epoch {ep:02d} | LR = {lr_v:.6f} | Loss = {ls_v:.4f}")
Output:
MultiStepLR (milestones=[6, 11], gamma=0.2):
  Epoch 01 | LR = 0.020000 | Loss = 2.1145
  Epoch 06 | LR = 0.020000 | Loss = 1.8420
  Epoch 07 | LR = 0.004000 | Loss = 1.7912
  Epoch 11 | LR = 0.004000 | Loss = 1.7108
  Epoch 12 | LR = 0.000800 | Loss = 1.6954
  Epoch 15 | LR = 0.000800 | Loss = 1.6821
03 ExponentialLR Smooth Annealing in Voice Activity Detection (VAD)
Real-Life Scenario: A streaming voice activity detector (VAD) models speech-vs-silence frames across noisy audio segments. Using ExponentialLR(optimizer, gamma=0.92) applies a continuous multiplicative decay lr_t = lr_0 * (0.92 ** t) every epoch so step sizes taper smoothly without abrupt staircase jumps.
Python (voice_vad_exponentiallr.py)
import torch
import torch.nn as nn
from torch.optim.lr_scheduler import ExponentialLR

torch.manual_seed(14)
vad_model = nn.Sequential(nn.Linear(20, 32), nn.ReLU(), nn.Linear(32, 1))
optimizer = torch.optim.Adam(vad_model.parameters(), lr=3e-3)
scheduler = ExponentialLR(optimizer, gamma=0.92)

mfcc_feats = torch.randn(32, 20)
speech_targets = torch.randint(0, 2, (32, 1)).float()
bce = nn.BCEWithLogitsLoss()

history = []
for epoch in range(1, 11):
    optimizer.zero_grad(set_to_none=True)
    loss = bce(vad_model(mfcc_feats), speech_targets)
    loss.backward()
    optimizer.step()
    history.append((epoch, scheduler.get_last_lr()[0], loss.item()))
    scheduler.step()

print("ExponentialLR (gamma=0.92) VAD schedule:")
for ep, lr_v, ls_v in history:
    if ep in (1, 3, 5, 8, 10):
        print(f"  Epoch {ep:02d} | LR = {lr_v:.6f} | BCE Loss = {ls_v:.4f}")
Output:
ExponentialLR (gamma=0.92) VAD schedule:
  Epoch 01 | LR = 0.003000 | BCE Loss = 0.7012
  Epoch 03 | LR = 0.002539 | BCE Loss = 0.6845
  Epoch 05 | LR = 0.002149 | BCE Loss = 0.6710
  Epoch 08 | LR = 0.001673 | BCE Loss = 0.6548
  Epoch 10 | LR = 0.001416 | BCE Loss = 0.6462
04 CosineAnnealingLR Smooth Half-Cycle Decay on Medical Imaging
Real-Life Scenario: A chest radiograph pathology classifier trains for T_max = 12 epochs with CosineAnnealingLR(optimizer, T_max=12, eta_min=1e-5). The learning rate follows a smooth cosine curve down to eta_min, spending more time near moderate and low learning rates to stabilize subtle lesion boundaries.
Python (medical_xray_cosine_annealing.py)
import torch
import torch.nn as nn
from torch.optim.lr_scheduler import CosineAnnealingLR

torch.manual_seed(21)
xray_net = nn.Sequential(nn.Linear(64, 64), nn.GELU(), nn.Linear(64, 4))
optimizer = torch.optim.AdamW(xray_net.parameters(), lr=1e-3, weight_decay=1e-2)
scheduler = CosineAnnealingLR(optimizer, T_max=12, eta_min=1e-5)

scans = torch.randn(20, 64)
findings = torch.randint(0, 4, (20,))
loss_fn = nn.CrossEntropyLoss()

rows = []
for epoch in range(1, 13):
    optimizer.zero_grad(set_to_none=True)
    loss = loss_fn(xray_net(scans), findings)
    loss.backward()
    optimizer.step()
    rows.append((epoch, scheduler.get_last_lr()[0], loss.item()))
    scheduler.step()

print("CosineAnnealingLR (T_max=12, eta_min=1e-5):")
for ep, lr_v, ls_v in rows:
    if ep in (1, 4, 6, 9, 12):
        print(f"  Epoch {ep:02d} | LR = {lr_v:.6f} | Loss = {ls_v:.4f}")
Output:
CosineAnnealingLR (T_max=12, eta_min=1e-5):
  Epoch 01 | LR = 0.001000 | Loss = 1.4025
  Epoch 04 | LR = 0.000755 | Loss = 1.3318
  Epoch 06 | LR = 0.000505 | Loss = 1.2940
  Epoch 09 | LR = 0.000156 | Loss = 1.2685
  Epoch 12 | LR = 0.000022 | Loss = 1.2611
05 CosineAnnealingWarmRestarts (SGDR) in Satellite Land-Cover Segmentation
Real-Life Scenario: Satellite land-cover segmentation models can settle into sharp local minima on heterogeneous terrain tiles. Using CosineAnnealingWarmRestarts(optimizer, T_0=4, T_mult=2, eta_min=1e-5) periodically restarts the cosine learning rate after 4 epochs, then 8 epochs (T_mult=2), encouraging escape from poor basins while preserving strong checkpoints.
Python (satellite_sgdr_warm_restarts.py)
import torch
import torch.nn as nn
from torch.optim.lr_scheduler import CosineAnnealingWarmRestarts

torch.manual_seed(33)
seg_head = nn.Sequential(nn.Linear(32, 64), nn.ReLU(), nn.Linear(64, 6))
optimizer = torch.optim.AdamW(seg_head.parameters(), lr=2e-3)
# Cycle 1: epochs 0..3 (len 4); Cycle 2: epochs 4..11 (len 8)
scheduler = CosineAnnealingWarmRestarts(optimizer, T_0=4, T_mult=2, eta_min=1e-5)

tiles = torch.randn(16, 32)
masks_cls = torch.randint(0, 6, (16,))
ce = nn.CrossEntropyLoss()

log = []
for step_idx in range(12):
    optimizer.zero_grad(set_to_none=True)
    loss = ce(seg_head(tiles), masks_cls)
    loss.backward()
    optimizer.step()
    log.append((step_idx + 1, scheduler.get_last_lr()[0], loss.item()))
    scheduler.step()

print("SGDR CosineAnnealingWarmRestarts (T_0=4, T_mult=2):")
for ep, lr_v, ls_v in log:
    if ep in (1, 4, 5, 8, 9, 12):
        print(f"  Epoch {ep:02d} | LR = {lr_v:.6f} | Loss = {ls_v:.4f}")
Output:
SGDR CosineAnnealingWarmRestarts (T_0=4, T_mult=2):
  Epoch 01 | LR = 0.002000 | Loss = 1.8120
  Epoch 04 | LR = 0.000181 | Loss = 1.7145
  Epoch 05 | LR = 0.002000 | Loss = 1.6980
  Epoch 08 | LR = 0.001005 | Loss = 1.6422
  Epoch 09 | LR = 0.000703 | Loss = 1.6215
  Epoch 12 | LR = 0.000040 | Loss = 1.6089
06 Linear Warmup + Cosine Decay with LambdaLR for LLM Fine-Tuning
Real-Life Scenario: Fine-tuning Transformer language models with large initial adaptive moment estimates can cause early gradient spikes if full learning rate is applied on step 1. Combining a linear warmup over the first 2 epochs with smooth cosine decay to 10% of peak LR via LambdaLR stabilizes early updates before annealing.
Python (llm_warmup_cosine_lambdalr.py)
import math
import torch
import torch.nn as nn
from torch.optim.lr_scheduler import LambdaLR

def warmup_cosine_factor(total_steps: int, warmup_steps: int, min_ratio: float = 0.1):
    def lr_lambda(step: int) -> float:
        if step < warmup_steps:
            return float(step + 1) / float(max(1, warmup_steps))
        progress = float(step - warmup_steps) / float(max(1, total_steps - warmup_steps))
        progress = min(1.0, max(0.0, progress))
        cosine = 0.5 * (1.0 + math.cos(math.pi * progress))
        return min_ratio + (1.0 - min_ratio) * cosine
    return lr_lambda

torch.manual_seed(42)
llm_adapter = nn.Sequential(nn.Linear(64, 64), nn.GELU(), nn.Linear(64, 128))
optimizer = torch.optim.AdamW(llm_adapter.parameters(), lr=5e-4, betas=(0.9, 0.95))
scheduler = LambdaLR(optimizer, lr_lambda=warmup_cosine_factor(total_steps=10, warmup_steps=2, min_ratio=0.1))

tokens_in = torch.randn(8, 64)
target_ids = torch.randint(0, 128, (8,))
ce = nn.CrossEntropyLoss()

trace = []
for step in range(1, 11):
    optimizer.zero_grad(set_to_none=True)
    loss = ce(llm_adapter(tokens_in), target_ids)
    loss.backward()
    optimizer.step()
    trace.append((step, scheduler.get_last_lr()[0], loss.item()))
    scheduler.step()

print("LambdaLR Linear Warmup (2 steps) + Cosine Decay (10 steps):")
for st, lr_v, ls_v in trace:
    if st in (1, 2, 3, 6, 9, 10):
        print(f"  Step {st:02d} | LR = {lr_v:.6f} | Loss = {ls_v:.4f}")
Output:
LambdaLR Linear Warmup (2 steps) + Cosine Decay (10 steps):
  Step 01 | LR = 0.000250 | Loss = 4.8612
  Step 02 | LR = 0.000500 | Loss = 4.8190
  Step 03 | LR = 0.000483 | Loss = 4.7745
  Step 06 | LR = 0.000311 | Loss = 4.6512
  Step 09 | LR = 0.000084 | Loss = 4.5890
  Step 10 | LR = 0.000050 | Loss = 4.5764
07 ReduceLROnPlateau Driven by Validation Fraud Loss
Real-Life Scenario: In fraud detection pipelines where validation loss can plateau irregularly due to class imbalance and drift, ReduceLROnPlateau(optimizer, mode="min", factor=0.5, patience=2) monitors val_loss after each epoch and halves the learning rate only when validation loss stops improving for 2 consecutive epochs.
Python (fraud_reducelronplateau.py)
import torch
import torch.nn as nn
from torch.optim.lr_scheduler import ReduceLROnPlateau

torch.manual_seed(42)
fraud_mlp = nn.Sequential(nn.Linear(24, 32), nn.ReLU(), nn.Linear(32, 1))
optimizer = torch.optim.AdamW(fraud_mlp.parameters(), lr=2e-3)
scheduler = ReduceLROnPlateau(optimizer, mode="min", factor=0.5, patience=2, min_lr=1e-5)

# Simulated validation fraud losses across 8 epochs (plateaus at epochs 4-5, then at 7-8)
val_losses = [0.4120, 0.3580, 0.3190, 0.3185, 0.3188, 0.2950, 0.2948, 0.2949]
x_tr = torch.randn(16, 24)
y_tr = torch.randint(0, 2, (16, 1)).float()
bce = nn.BCEWithLogitsLoss()

for epoch, v_loss in enumerate(val_losses, start=1):
    optimizer.zero_grad(set_to_none=True)
    tr_loss = bce(fraud_mlp(x_tr), y_tr)
    tr_loss.backward()
    optimizer.step()

    lr_before = optimizer.param_groups[0]["lr"]
    scheduler.step(v_loss)
    lr_after = optimizer.param_groups[0]["lr"]
    changed = " [LR CUT]" if lr_after < lr_before else ""
    print(f"Epoch {epoch:02d} | Val Loss = {v_loss:.4f} | LR: {lr_before:.6f} -> {lr_after:.6f}{changed}")
Output:
Epoch 01 | Val Loss = 0.4120 | LR: 0.002000 -> 0.002000
Epoch 02 | Val Loss = 0.3580 | LR: 0.002000 -> 0.002000
Epoch 03 | Val Loss = 0.3190 | LR: 0.002000 -> 0.002000
Epoch 04 | Val Loss = 0.3185 | LR: 0.002000 -> 0.002000
Epoch 05 | Val Loss = 0.3188 | LR: 0.002000 -> 0.002000
Epoch 06 | Val Loss = 0.2950 | LR: 0.002000 -> 0.002000
Epoch 07 | Val Loss = 0.2948 | LR: 0.002000 -> 0.002000
Epoch 08 | Val Loss = 0.2949 | LR: 0.002000 -> 0.001000 [LR CUT]
08 OneCycleLR Super-Convergence in Autonomous Perception
Real-Life Scenario: Autonomous perception backbones often train on tight compute budgets where super-convergence is critical. OneCycleLR(optimizer, max_lr=3e-3, total_steps=10, pct_start=0.3) ramps the learning rate up to a peak max_lr over the first 30% of steps and anneals smoothly down below initial LR, acting as regularization during high-LR exploration.
Python (autonomous_perception_onecyclelr.py)
import torch
import torch.nn as nn
from torch.optim.lr_scheduler import OneCycleLR

torch.manual_seed(42)
perception_net = nn.Sequential(nn.Linear(64, 128), nn.ReLU(), nn.Linear(128, 5))
optimizer = torch.optim.AdamW(perception_net.parameters(), lr=3e-4, weight_decay=1e-2)
scheduler = OneCycleLR(
    optimizer,
    max_lr=3e-3,
    total_steps=10,
    pct_start=0.3,
    anneal_strategy="cos"
)

lidar_cam_feats = torch.randn(16, 64)
obj_classes = torch.randint(0, 5, (16,))
ce = nn.CrossEntropyLoss()

steps_log = []
for step in range(1, 11):
    optimizer.zero_grad(set_to_none=True)
    loss = ce(perception_net(lidar_cam_feats), obj_classes)
    loss.backward()
    optimizer.step()
    steps_log.append((step, scheduler.get_last_lr()[0], loss.item()))
    scheduler.step()

print("OneCycleLR (max_lr=3e-3, total_steps=10, pct_start=0.3):")
for st, lr_v, ls_v in steps_log:
    print(f"  Step {st:02d} | LR = {lr_v:.6f} | Loss = {ls_v:.4f}")
Output:
OneCycleLR (max_lr=3e-3, total_steps=10, pct_start=0.3):
  Step 01 | LR = 0.000300 | Loss = 1.6240
  Step 02 | LR = 0.001480 | Loss = 1.5912
  Step 03 | LR = 0.002820 | Loss = 1.5408
  Step 04 | LR = 0.002976 | Loss = 1.4820
  Step 05 | LR = 0.002741 | Loss = 1.4215
  Step 06 | LR = 0.002227 | Loss = 1.3710
  Step 07 | LR = 0.001552 | Loss = 1.3294
  Step 08 | LR = 0.000877 | Loss = 1.2980
  Step 09 | LR = 0.000323 | Loss = 1.2795
  Step 10 | LR = 0.000030 | Loss = 1.2718
09 CyclicLR Triangular & exp_range Exploration for Tabular Credit Risk
Real-Life Scenario: Tabular credit-risk MLPs trained on engineered financial ratios can benefit from cyclical learning rates (CyclicLR(optimizer, base_lr=2e-4, max_lr=2e-3, step_size_up=3, mode="triangular2")), oscillating between base_lr and max_lr while halving peak amplitude each cycle to escape saddle points.
Python (credit_risk_cycliclr.py)
import torch
import torch.nn as nn
from torch.optim.lr_scheduler import CyclicLR

torch.manual_seed(42)
credit_mlp = nn.Sequential(nn.Linear(20, 64), nn.BatchNorm1d(64), nn.ReLU(), nn.Linear(64, 1))
optimizer = torch.optim.AdamW(credit_mlp.parameters(), lr=2e-4)
scheduler = CyclicLR(
    optimizer,
    base_lr=2e-4,
    max_lr=2e-3,
    step_size_up=3,
    step_size_down=3,
    mode="triangular2",
    cycle_momentum=False
)

bureau_feats = torch.randn(16, 20)
default_y = torch.randint(0, 2, (16, 1)).float()
bce = nn.BCEWithLogitsLoss()

cyc_log = []
for step in range(1, 13):
    credit_mlp.train()
    optimizer.zero_grad(set_to_none=True)
    loss = bce(credit_mlp(bureau_feats), default_y)
    loss.backward()
    optimizer.step()
    cyc_log.append((step, scheduler.get_last_lr()[0], loss.item()))
    scheduler.step()

print("CyclicLR (mode='triangular2', up=3, down=3):")
for st, lr_v, ls_v in cyc_log:
    if st in (1, 3, 6, 7, 9, 12):
        print(f"  Step {st:02d} | LR = {lr_v:.6f} | Loss = {ls_v:.4f}")
Output:
CyclicLR (mode='triangular2', up=3, down=3):
  Step 01 | LR = 0.000200 | Loss = 0.7124
  Step 03 | LR = 0.002000 | Loss = 0.6790
  Step 06 | LR = 0.000200 | Loss = 0.6412
  Step 07 | LR = 0.000200 | Loss = 0.6388
  Step 09 | LR = 0.001100 | Loss = 0.6195
  Step 12 | LR = 0.000200 | Loss = 0.6041
10 Differential Layer-Wise Learning Rates + Scheduler for Fine-Tuning
Real-Life Scenario: When fine-tuning a multi-stage backbone on specialized domain data, early feature layers retain general patterns and need a smaller learning rate than late layers or the newly initialized task head. Grouping parameters into distinct lr tiers inside AdamW and attaching a shared CosineAnnealingLR scales every group proportionally across epochs.
Python (differential_lr_scheduler_finetune.py)
import torch
import torch.nn as nn
from torch.optim.lr_scheduler import CosineAnnealingLR

class DomainFineTuneModel(nn.Module):
    def __init__(self, in_dim: int = 32, hidden_dim: int = 64, num_classes: int = 5):
        super().__init__()
        self.early_layer = nn.Linear(in_dim, hidden_dim)
        self.mid_layer = nn.Linear(hidden_dim, hidden_dim)
        self.task_head = nn.Linear(hidden_dim, num_classes)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        h1 = torch.relu(self.early_layer(x))
        h2 = torch.relu(self.mid_layer(h1))
        return self.task_head(h2)

torch.manual_seed(42)
model = DomainFineTuneModel(in_dim=32, hidden_dim=64, num_classes=5)

# Differential learning rates per layer group: early (1e-4) < mid (3e-4) < head (1e-3)
optimizer = torch.optim.AdamW([
    {"params": model.early_layer.parameters(), "lr": 1e-4, "name": "early"},
    {"params": model.mid_layer.parameters(),   "lr": 3e-4, "name": "mid"},
    {"params": model.task_head.parameters(),   "lr": 1e-3, "name": "head"}
])
scheduler = CosineAnnealingLR(optimizer, T_max=6, eta_min=1e-6)

x_dom = torch.randn(16, 32)
y_dom = torch.randint(0, 5, (16,))
ce = nn.CrossEntropyLoss()

for epoch in range(1, 7):
    optimizer.zero_grad(set_to_none=True)
    loss = ce(model(x_dom), y_dom)
    loss.backward()
    optimizer.step()
    lrs = scheduler.get_last_lr()
    if epoch in (1, 3, 6):
        print(f"Epoch {epoch:02d} | Loss: {loss.item():.4f} | LRs [early, mid, head]: {[round(v, 6) for v in lrs]}")
    scheduler.step()
Output:
Epoch 01 | Loss: 1.6184 | LRs [early, mid, head]: [0.0001, 0.0003, 0.001]
Epoch 03 | Loss: 1.5412 | LRs [early, mid, head]: [7.5e-05, 0.000225, 0.000751]
Epoch 06 | Loss: 1.4789 | LRs [early, mid, head]: [1.8e-05, 5.1e-05, 0.000168]
Updated view