Python / PyTorch Fundamentals Interview Questions
How do you initialise weights in a PyTorch model?
PyTorch uses sensible default initialisations (Kaiming uniform for Linear and Conv layers), but custom initialisation is often needed to match a paper or improve convergence. The torch.nn.init module provides all standard schemes.
import torch, torch.nn as nn
# Default initialisation:
# nn.Linear → Kaiming uniform (He init) for weight, uniform for bias
# nn.Conv2d → Kaiming uniform
# nn.Embedding → Normal(0, 1)
# Custom initialisation using apply()
def init_weights(module):
if isinstance(module, nn.Linear):
nn.init.xavier_uniform_(module.weight) # Xavier/Glorot
nn.init.zeros_(module.bias)
elif isinstance(module, nn.Conv2d):
nn.init.kaiming_normal_(module.weight,
mode="fan_out",
nonlinearity="relu") # He init
if module.bias is not None:
nn.init.zeros_(module.bias)
elif isinstance(module, nn.Embedding):
nn.init.normal_(module.weight, mean=0.0, std=0.02) # GPT-style
model = nn.Sequential(
nn.Linear(128, 64), nn.ReLU(),
nn.Linear(64, 10)
)
model.apply(init_weights) # recursively applies to all sub-modules
# Direct initialisation with torch.no_grad()
with torch.no_grad():
model[0].weight.fill_(0.01)
model[0].bias.zero_()| Scheme | API | Best for |
|---|---|---|
| Xavier / Glorot uniform | nn.init.xavier_uniform_() | Sigmoid / Tanh activations |
| Xavier / Glorot normal | nn.init.xavier_normal_() | Sigmoid / Tanh activations |
| Kaiming / He uniform | nn.init.kaiming_uniform_() | ReLU (PyTorch default) |
| Kaiming / He normal | nn.init.kaiming_normal_() | ReLU (often better than uniform) |
| Normal | nn.init.normal_(mean, std) | Embeddings (std=0.02 GPT-style) |
| Zeros / Ones | nn.init.zeros_() / ones_() | Biases, gates |
| Orthogonal | nn.init.orthogonal_() | RNNs |
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...
