Python / PyTorch Fundamentals Interview Questions
What optimizers does PyTorch provide and how do you configure them?
Optimizers update model parameters based on computed gradients. PyTorch provides all major optimizers in torch.optim. Choosing and configuring the right optimizer significantly affects training speed and final performance.
| Optimizer | Key feature | Typical use |
|---|---|---|
| SGD | Simple, supports momentum and weight decay | Computer vision with lr scheduling |
| Adam | Adaptive lr per param; momentum + RMSProp | Default for NLP, general purpose |
| AdamW | Adam with decoupled weight decay | Transformers, fine-tuning (recommended over Adam) |
| RMSprop | Adaptive lr without momentum | RNNs |
| Adagrad | Accumulates squared gradients; rare today | Sparse features |
| LBFGS | Second-order quasi-Newton; very slow | Small networks, physics-informed NNs |
import torch, torch.nn as nn, torch.optim as optim
model = nn.Linear(128, 10)
# ── SGD with momentum and weight decay
opt_sgd = optim.SGD(
model.parameters(),
lr=0.1,
momentum=0.9, # Nesterov-style acceleration
weight_decay=1e-4, # L2 regularisation
nesterov=True,
)
# ── Adam
opt_adam = optim.Adam(
model.parameters(),
lr=1e-3,
betas=(0.9, 0.999), # (β1, β2) — momentum terms
eps=1e-8,
weight_decay=0, # Adam + L2 is suboptimal — use AdamW!
)
# ── AdamW (preferred for transformers)
opt_adamw = optim.AdamW(
model.parameters(),
lr=1e-3,
weight_decay=0.01, # decoupled from gradient update
)
# ── Per-layer learning rates
opt_layerwise = optim.Adam([
{"params": model.weight, "lr": 1e-4}, # slower for weight
{"params": model.bias, "lr": 1e-3}, # faster for bias
])
# ── Standard training step
opt = optim.AdamW(model.parameters(), lr=1e-3)
for x, y in [(torch.randn(32,128), torch.randint(0,10,(32,)))]:
opt.zero_grad() # 1. clear old gradients
loss = nn.CrossEntropyLoss()(model(x), y) # 2. forward
loss.backward() # 3. backward
opt.step() # 4. update parameters
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...
