Python / PyTorch Fundamentals Interview Questions
What built-in layers does PyTorch's nn module provide and how do you use the most common ones?
PyTorch's torch.nn module contains all the standard neural network building blocks. Understanding what each layer does mathematically helps you choose the right component and configure it correctly.
| Layer | Formula / purpose | Key parameters |
|---|---|---|
| nn.Linear | y = xW^T + b — fully connected | in_features, out_features, bias=True |
| nn.Conv2d | 2D cross-correlation — feature extraction | in_channels, out_channels, kernel_size, stride, padding |
| nn.BatchNorm1d/2d | Normalise over batch; learnable γ, β | num_features, eps, momentum |
| nn.Dropout | Zero random neurons with prob p during train | p (dropout probability) |
| nn.Embedding | Learnable lookup table for integer tokens | num_embeddings, embedding_dim |
| nn.LSTM | Long Short-Term Memory recurrent layer | input_size, hidden_size, num_layers |
| nn.MultiheadAttention | Scaled dot-product attention | embed_dim, num_heads |
| nn.LayerNorm | Normalise over feature dims per sample | normalized_shape |
import torch, torch.nn as nn
# nn.Linear
fc = nn.Linear(128, 64) # (batch, 128) → (batch, 64)
print(fc.weight.shape) # (64, 128) — transposed internally
print(fc.bias.shape) # (64,)
# nn.Conv2d
conv = nn.Conv2d(
in_channels=3,
out_channels=32,
kernel_size=3,
stride=1,
padding=1, # "same" padding preserves H, W
)
x_img = torch.randn(8, 3, 32, 32) # (batch, C, H, W)
print(conv(x_img).shape) # (8, 32, 32, 32)
# nn.BatchNorm2d
bn = nn.BatchNorm2d(32) # num_features = channels
# In train mode: normalises over (N, H, W) per channel
# In eval mode: uses running mean/var from training
# nn.Embedding
emb = nn.Embedding(num_embeddings=10000, embedding_dim=128)
tokens = torch.tensor([5, 23, 100]) # integer token ids
print(emb(tokens).shape) # (3, 128)
# nn.Dropout — active only in train mode
drop = nn.Dropout(p=0.5)
x = torch.ones(4, 8)
print(drop(x)) # ~half zeros (train), all ones after model.eval()
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...
