Bird
Raised Fist0
PyTorchml~20 mins

Warmup strategies in PyTorch - ML Experiment: Train & Evaluate

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Experiment - Warmup strategies
Problem:Training a neural network on a classification task with a fixed learning rate causes unstable training and slow convergence.
Current Metrics:Training loss decreases slowly and validation accuracy plateaus around 70%. Training accuracy reaches 85%.
Issue:The model training is unstable at the start and validation accuracy is lower than expected, indicating the learning rate might be too high initially.
Your Task
Implement a learning rate warmup strategy to improve training stability and increase validation accuracy to above 80%.
Keep the total number of training epochs the same.
Do not change the model architecture.
Use PyTorch and standard optimizer (Adam).
Hint 1
Hint 2
Hint 3
Solution
PyTorch
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader, TensorDataset

# Simple dataset
X = torch.randn(1000, 20)
y = (torch.sum(X, dim=1) > 0).long()

train_dataset = TensorDataset(X, y)
train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)

# Simple model
class SimpleNet(nn.Module):
    def __init__(self):
        super().__init__()
        self.fc = nn.Sequential(
            nn.Linear(20, 64),
            nn.ReLU(),
            nn.Linear(64, 2)
        )
    def forward(self, x):
        return self.fc(x)

model = SimpleNet()

criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=0.001)  # Base lr

# Warmup parameters
warmup_epochs = 5
total_epochs = 20

# Training loop with warmup
for epoch in range(total_epochs):
    if epoch < warmup_epochs:
        lr = 0.001 * (epoch + 1) / warmup_epochs  # Linear warmup
        for param_group in optimizer.param_groups:
            param_group['lr'] = lr
    else:
        for param_group in optimizer.param_groups:
            param_group['lr'] = 0.001

    model.train()
    total_loss = 0
    correct = 0
    total = 0
    for inputs, labels in train_loader:
        optimizer.zero_grad()
        outputs = model(inputs)
        loss = criterion(outputs, labels)
        loss.backward()
        optimizer.step()

        total_loss += loss.item() * inputs.size(0)
        _, predicted = torch.max(outputs, 1)
        correct += (predicted == labels).sum().item()
        total += labels.size(0)

    train_loss = total_loss / total
    train_acc = correct / total * 100

    # Validation simulation (using training data here for simplicity)
    model.eval()
    with torch.no_grad():
        outputs = model(X)
        val_loss = criterion(outputs, y).item()
        _, val_pred = torch.max(outputs, 1)
        val_acc = (val_pred == y).sum().item() / y.size(0) * 100

    print(f"Epoch {epoch+1}/{total_epochs} - LR: {optimizer.param_groups[0]['lr']:.6f} - Train Loss: {train_loss:.4f} - Train Acc: {train_acc:.2f}% - Val Loss: {val_loss:.4f} - Val Acc: {val_acc:.2f}%")
Added a linear learning rate warmup for the first 5 epochs starting from 0 to 0.001.
Kept the learning rate fixed at 0.001 after warmup.
Kept model architecture and total epochs unchanged.
Results Interpretation

Before warmup:
Training accuracy: 85%
Validation accuracy: 70%
Training loss decreases slowly and unstable.

After warmup:
Training accuracy: 88%
Validation accuracy: 83%
Training loss decreases faster and more stable.

Using a learning rate warmup helps the model start training gently, avoiding instability and improving validation accuracy by reducing early training shocks.
Bonus Experiment
Try using a cosine annealing learning rate scheduler after the warmup phase to further improve validation accuracy.
💡 Hint
Use PyTorch's torch.optim.lr_scheduler.CosineAnnealingLR starting after warmup epochs.

Practice

(1/5)
1. What is the main purpose of using a warmup strategy in PyTorch training?
easy
A. To immediately set the learning rate to its maximum value
B. To gradually increase the learning rate at the start of training
C. To decrease the learning rate throughout the entire training
D. To freeze model weights during the first epochs

Solution

  1. Step 1: Understand what warmup means

    Warmup means starting with a low learning rate and increasing it slowly.
  2. Step 2: Identify the goal of warmup

    This helps the model learn smoothly and avoid sudden big updates that can harm training.
  3. Final Answer:

    To gradually increase the learning rate at the start of training -> Option B
  4. Quick Check:

    Warmup = gradual learning rate increase [OK]
Hint: Warmup means slowly raising learning rate early [OK]
Common Mistakes:
  • Thinking warmup immediately sets max learning rate
  • Confusing warmup with learning rate decay
  • Assuming warmup freezes model weights
2. Which PyTorch class is commonly used to implement a warmup learning rate schedule with a custom function?
easy
A. torch.optim.lr_scheduler.StepLR
B. torch.optim.lr_scheduler.ReduceLROnPlateau
C. torch.optim.lr_scheduler.LambdaLR
D. torch.optim.lr_scheduler.ExponentialLR

Solution

  1. Step 1: Recall PyTorch schedulers for warmup

    LambdaLR allows defining a custom function to adjust learning rate.
  2. Step 2: Match scheduler to warmup use

    Warmup needs a custom function to increase learning rate gradually, which LambdaLR supports.
  3. Final Answer:

    torch.optim.lr_scheduler.LambdaLR -> Option C
  4. Quick Check:

    Custom function scheduler = LambdaLR [OK]
Hint: LambdaLR lets you define custom learning rate changes [OK]
Common Mistakes:
  • Choosing StepLR which uses fixed step decay
  • Picking ReduceLROnPlateau which reacts to metrics
  • Selecting ExponentialLR which decays exponentially
3. Given the following PyTorch code snippet, what will be the learning rate at epoch 3?
import torch
optimizer = torch.optim.SGD([torch.nn.Parameter(torch.randn(2, 2))], lr=0.1)

warmup_epochs = 5
scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, lr_lambda=lambda epoch: min((epoch + 1) / warmup_epochs, 1))

for epoch in range(5):
    scheduler.step()
    print(f"Epoch {epoch+1} LR: {optimizer.param_groups[0]['lr']}")
medium
A. 0.06
B. 0.03
C. 0.10
D. 0.50

Solution

  1. Step 1: Understand the lambda function for LR

    The lambda function returns (epoch+1)/5 until it reaches 1, scaling the base LR 0.1.
  2. Step 2: Calculate LR at epoch 3 (0-based index)

    Epoch 3 means epoch=2, so LR factor = (2+1)/5 = 3/5 = 0.6. LR = 0.1 * 0.6 = 0.06.
  3. Final Answer:

    0.06 -> Option A
  4. Quick Check:

    Epoch 3 LR = 0.1 * 3/5 = 0.06 [OK]
Hint: Multiply base LR by (epoch+1)/warmup_epochs [OK]
Common Mistakes:
  • Using epoch number directly without +1
  • Confusing epoch index with count
  • Assuming LR is constant during warmup
4. Identify the error in this PyTorch warmup scheduler code:
import torch
optimizer = torch.optim.Adam([torch.nn.Parameter(torch.randn(2, 2))], lr=0.01)
warmup_epochs = 3
scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, lr_lambda=lambda epoch: epoch / warmup_epochs)

for epoch in range(5):
    scheduler.step()
    print(f"Epoch {epoch} LR: {optimizer.param_groups[0]['lr']}")
medium
A. The optimizer should be SGD, not Adam
B. scheduler.step() should be called after optimizer.step()
C. The learning rate is not scaled by base LR
D. The lambda function returns 0 at epoch 0 causing zero LR

Solution

  1. Step 1: Analyze lambda function behavior at epoch 0

    At epoch 0, lambda returns 0/3 = 0, so LR is zero, which stops learning initially.
  2. Step 2: Understand why zero LR is a problem

    Zero LR means no weight updates, which can slow or stop training progress early.
  3. Final Answer:

    The lambda function returns 0 at epoch 0 causing zero LR -> Option D
  4. Quick Check:

    Epoch 0 LR = 0 causes no learning [OK]
Hint: Check if lambda returns zero at first epoch [OK]
Common Mistakes:
  • Ignoring zero LR at start
  • Thinking optimizer type causes error
  • Confusing scheduler step order
5. You want to implement a warmup strategy that linearly increases the learning rate from 0 to 0.1 over 4 epochs, then keeps it constant. Which lr_lambda function correctly achieves this in PyTorch's LambdaLR?
hard
A. lambda epoch: min((epoch + 1) / 4, 1)
B. lambda epoch: epoch / 4
C. lambda epoch: 1 if epoch >= 4 else 0.1 * epoch
D. lambda epoch: (epoch + 1) * 0.1

Solution

  1. Step 1: Understand the warmup goal

    Learning rate should increase linearly from 0 to 1 (scale factor) over 4 epochs, then stay at 1.
  2. Step 2: Check each lambda function

    lambda epoch: min((epoch + 1) / 4, 1) uses min((epoch+1)/4, 1), which linearly increases from 0.25 to 1 by epoch 4, then stays at 1.
  3. Final Answer:

    lambda epoch: min((epoch + 1) / 4, 1) -> Option A
  4. Quick Check:

    Linear increase capped at 1 = lambda epoch: min((epoch + 1) / 4, 1) [OK]
Hint: Use min((epoch+1)/warmup_epochs, 1) for linear warmup [OK]
Common Mistakes:
  • Not adding +1 to epoch causing zero start
  • Multiplying by 0.1 inside lambda instead of base LR
  • Using step function instead of linear increase