Python / PyTorch Fundamentals Interview Questions
What optimizers does PyTorch provide and what is the difference between SGD, Adam, and AdamW?
Optimizers update model parameters based on computed gradients. PyTorch's torch.optim module provides many algorithms; understanding their differences helps you choose the right one and tune hyperparameters effectively.
| Optimizer | Key idea | Typical lr | Best for |
|---|---|---|---|
| SGD | Plain gradient descent, optional momentum | 0.01–0.1 | Image classification (with momentum + schedule) |
| SGD + momentum | Accumulates velocity to smooth updates | 0.01–0.1 | Often best final generalisation |
| Adam | Adaptive per-parameter learning rates + momentum | 1e-3 | Fast convergence, good default |
| AdamW | Adam with decoupled weight decay | 1e-3 to 5e-5 | Fine-tuning transformers, modern default |
| RMSprop | Adaptive lr based on recent gradient magnitude | 1e-3 | RNNs (historically popular) |
import torch
import torch.nn as nn
import torch.optim as optim
model = nn.Linear(10, 1)
# ── SGD with momentum
opt_sgd = optim.SGD(
model.parameters(),
lr=0.01,
momentum=0.9, # accelerates in consistent gradient directions
weight_decay=1e-4, # L2 regularisation
)
# ── Adam — adaptive learning rate per parameter
opt_adam = optim.Adam(
model.parameters(),
lr=1e-3,
betas=(0.9, 0.999), # momentum decay rates
eps=1e-8,
)
# ── AdamW — decoupled weight decay (recommended for fine-tuning)
opt_adamw = optim.AdamW(
model.parameters(),
lr=2e-5, # typical for fine-tuning pretrained models
weight_decay=0.01,
)
# ── Standard training step
x, y = torch.randn(16, 10), torch.randn(16, 1)
loss_fn = nn.MSELoss()
opt_adamw.zero_grad() # 1. clear old gradients
pred = model(x) # 2. forward pass
loss = loss_fn(pred, y) # 3. compute loss
loss.backward() # 4. backpropagate
opt_adamw.step() # 5. update parameters
# ── Different learning rates per parameter group
optimizer = optim.AdamW([
{"params": model.weight, "lr": 1e-3},
{"params": model.bias, "lr": 1e-4},
])
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
