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 |
More Related questions...