Bird
Raised Fist0
PyTorchml~12 mins

Weight decay (L2 regularization) in PyTorch - Model Pipeline Trace

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
Model Pipeline - Weight decay (L2 regularization)

This pipeline trains a simple neural network on a small dataset using weight decay, also called L2 regularization. Weight decay helps the model avoid overfitting by gently pushing weights to stay small.

Data Flow - 6 Stages
1Data in
1000 rows x 10 columnsRaw input features and labels1000 rows x 10 columns
Feature vector: [0.5, 1.2, -0.3, ..., 0.7], Label: 1
2Preprocessing
1000 rows x 10 columnsNormalize features to zero mean and unit variance1000 rows x 10 columns
Normalized feature vector: [0.1, -0.2, 0.0, ..., 0.3]
3Feature Engineering
1000 rows x 10 columnsNo additional features added1000 rows x 10 columns
Same normalized features passed forward
4Model Trains
1000 rows x 10 columnsFeedforward neural network with weight decay applied during optimizer step1000 rows x 2 columns (class scores)
Output logits: [1.2, -0.5]
5Metrics Improve
1000 rows x 2 columnsCalculate loss and accuracy on training dataScalar loss and accuracy values
Loss: 0.45, Accuracy: 0.82
6Prediction
1 row x 10 columnsModel predicts class probabilities using softmax1 row x 2 columns (probabilities)
Predicted probabilities: [0.75, 0.25]
Training Trace - Epoch by Epoch
Loss
1.2 |*       
1.0 | *      
0.8 |  *     
0.6 |   *    
0.4 |    *   
    +---------
     1 2 3 4 5
     Epochs
EpochLoss ↓Accuracy ↑Observation
11.200.50Initial loss is high; accuracy is at chance level.
20.850.65Loss decreases and accuracy improves as model learns.
30.650.75Model continues to improve with weight decay controlling complexity.
40.550.80Loss decreases steadily; accuracy rises.
50.480.83Training converges with good accuracy and controlled loss.
Prediction Trace - 4 Layers
Layer 1: Input Layer
Layer 2: Hidden Layer (ReLU)
Layer 3: Output Layer (Linear)
Layer 4: Softmax
Model Quiz - 3 Questions
Test your understanding
What is the main purpose of weight decay in this training pipeline?
ATo add more layers to the neural network
BTo increase the learning rate during training
CTo keep model weights small and prevent overfitting
DTo normalize the input data
Key Insight
Weight decay (L2 regularization) helps the model keep weights small, which reduces overfitting and leads to smoother training with steadily improving accuracy and decreasing loss.

Practice

(1/5)
1. What is the main purpose of weight decay (L2 regularization) in training a PyTorch model?
easy
A. To reduce overfitting by penalizing large weights
B. To increase the learning rate automatically
C. To add more layers to the model
D. To speed up the training process

Solution

  1. Step 1: Understand weight decay concept

    Weight decay adds a penalty to large weights during training to prevent the model from fitting noise in the data.
  2. Step 2: Connect to overfitting reduction

    By keeping weights small, the model generalizes better and avoids overfitting.
  3. Final Answer:

    To reduce overfitting by penalizing large weights -> Option A
  4. Quick Check:

    Weight decay = reduces overfitting [OK]
Hint: Weight decay shrinks weights to avoid overfitting [OK]
Common Mistakes:
  • Confusing weight decay with learning rate changes
  • Thinking weight decay adds layers
  • Assuming weight decay speeds training
2. Which of the following is the correct way to apply weight decay in a PyTorch optimizer?
easy
A. optimizer = torch.optim.SGD(model.parameters(), lr=0.01, wd=0.001)
B. optimizer = torch.optim.SGD(model.parameters(), lr=0.01, decay_weight=0.001)
C. optimizer = torch.optim.SGD(model.parameters(), lr=0.01, weightDecay=0.001)
D. optimizer = torch.optim.SGD(model.parameters(), lr=0.01, weight_decay=0.001)

Solution

  1. Step 1: Recall PyTorch optimizer syntax

    PyTorch optimizers accept a parameter named weight_decay to apply L2 regularization.
  2. Step 2: Identify correct parameter name

    Only optimizer = torch.optim.SGD(model.parameters(), lr=0.01, weight_decay=0.001) uses the exact parameter weight_decay correctly.
  3. Final Answer:

    optimizer = torch.optim.SGD(model.parameters(), lr=0.01, weight_decay=0.001) -> Option D
  4. Quick Check:

    Correct parameter name is weight_decay [OK]
Hint: Use exact parameter name 'weight_decay' in optimizer [OK]
Common Mistakes:
  • Using wrong parameter names like decay_weight or wd
  • Capitalizing parameter names incorrectly
  • Confusing weight decay with learning rate
3. Consider this PyTorch code snippet:
import torch
model = torch.nn.Linear(2, 1)
optimizer = torch.optim.SGD(model.parameters(), lr=0.1, weight_decay=0.01)
initial_weight = model.weight.data.clone()
optimizer.zero_grad()
output = model(torch.tensor([[1.0, 2.0]]))
loss = output.sum()
loss.backward()
optimizer.step()
updated_weight = model.weight.data
print((initial_weight - updated_weight).abs().sum().item())

What does the printed value represent?
medium
A. The total change in weights after one optimization step including weight decay
B. The learning rate value
C. The loss value before backward pass
D. The sum of model outputs

Solution

  1. Step 1: Understand code flow

    The code runs one optimizer step with weight decay, then measures how much weights changed.
  2. Step 2: Interpret printed value

    The printed value is the sum of absolute differences between initial and updated weights, showing total weight change including weight decay effect.
  3. Final Answer:

    The total change in weights after one optimization step including weight decay -> Option A
  4. Quick Check:

    Weight change sum = printed value [OK]
Hint: Weight decay affects weight updates, so weight change includes it [OK]
Common Mistakes:
  • Thinking printed value is loss or learning rate
  • Ignoring weight decay effect on weights
  • Confusing output sum with weight change
4. You wrote this PyTorch optimizer code:
optimizer = torch.optim.Adam(model.parameters(), lr=0.001, weight_decay=0.1)

But your model is overfitting badly. What is a likely mistake?
medium
A. Weight decay value is too high, causing poor training
B. Weight decay should be set to zero to reduce overfitting
C. Weight decay is applied to biases by default, so overfitting remains
D. Learning rate is too low to affect weight decay

Solution

  1. Step 1: Recall weight decay behavior in PyTorch

    By default, weight decay is applied to all parameters, including biases and batch norm weights, unless explicitly excluded.
  2. Step 2: Understand overfitting cause

    If weight decay is applied to all parameters including biases, it may not reduce overfitting effectively because biases are not regularized properly.
  3. Final Answer:

    Weight decay is applied to biases by default, so overfitting remains -> Option C
  4. Quick Check:

    Biases often excluded from weight decay for better regularization [OK]
Hint: Check if weight decay excludes biases to reduce overfitting [OK]
Common Mistakes:
  • Assuming weight decay does not apply to biases
  • Setting weight decay to zero to fix overfitting
  • Blaming learning rate for weight decay issues
5. You want to apply weight decay only to the weights of a PyTorch model's linear layers but not to biases. Which code snippet correctly sets this up?
hard
A. optimizer = torch.optim.Adam(model.parameters(), lr=0.001, weight_decay=0.01)
B. params = [ {'params': [p for n, p in model.named_parameters() if 'weight' in n], 'weight_decay': 0.01}, {'params': [p for n, p in model.named_parameters() if 'bias' in n], 'weight_decay': 0.0} ] optimizer = torch.optim.Adam(params, lr=0.001)
C. optimizer = torch.optim.Adam(model.parameters(), lr=0.001, weight_decay=0.0)
D. params = [ {'params': model.parameters(), 'weight_decay': 0.01} ] optimizer = torch.optim.Adam(params, lr=0.001)

Solution

  1. Step 1: Understand selective weight decay

    To apply weight decay only to weights, separate parameters into groups with and without weight decay.
  2. Step 2: Check code correctness

    params = [ {'params': [p for n, p in model.named_parameters() if 'weight' in n], 'weight_decay': 0.01}, {'params': [p for n, p in model.named_parameters() if 'bias' in n], 'weight_decay': 0.0} ] optimizer = torch.optim.Adam(params, lr=0.001) creates two groups: weights with weight_decay=0.01 and biases with weight_decay=0.0, correctly excluding biases.
  3. Final Answer:

    Code snippet that separates weights and biases with different weight_decay values -> Option B
  4. Quick Check:

    Separate params for weight decay control [OK]
Hint: Group parameters by name to apply weight decay selectively [OK]
Common Mistakes:
  • Applying weight decay to all parameters blindly
  • Not separating biases from weights
  • Using wrong parameter names in filtering