Python / PyTorch Fundamentals Interview Questions
What are nn.Sequential and other container modules in PyTorch?
PyTorch provides several container modules that compose layers without requiring a custom nn.Module subclass. They are convenient for simple feedforward architectures but less flexible than full subclassing.
import torch
import torch.nn as nn
# ── nn.Sequential: layers applied in order
model = nn.Sequential(
nn.Linear(784, 256),
nn.ReLU(),
nn.Dropout(0.3),
nn.Linear(256, 128),
nn.ReLU(),
nn.Linear(128, 10),
)
out = model(torch.randn(32, 784)) # (32, 10)
# Named layers in Sequential (for easier access)
model_named = nn.Sequential(
("fc1", nn.Linear(784, 256)),
("relu", nn.ReLU()),
("fc2", nn.Linear(256, 10)),
)
print(model_named.fc1.weight.shape) # torch.Size([256, 784])
# ── nn.ModuleList: list of modules (for dynamic use)
class ResNet(nn.Module):
def __init__(self, n_blocks: int):
super().__init__()
# ModuleList properly registers all contained modules
self.blocks = nn.ModuleList([
nn.Linear(64, 64) for _ in range(n_blocks)
])
def forward(self, x):
for block in self.blocks:
x = torch.relu(block(x)) + x # residual
return x
# ── nn.ModuleDict: dict of modules (for conditional routing)
class MultiHead(nn.Module):
def __init__(self):
super().__init__()
self.heads = nn.ModuleDict({
"sentiment": nn.Linear(128, 2),
"topic": nn.Linear(128, 10),
})
def forward(self, x, task: str):
return self.heads[task](x)| Container | When to use |
|---|---|
| nn.Sequential | Simple feedforward chains; no branching |
| nn.ModuleList | Dynamic or variable-length list of modules in a loop |
| nn.ModuleDict | Named modules selected conditionally (e.g. multi-task) |
| nn.ParameterList | List of nn.Parameter objects (rare) |
| nn.ParameterDict | Dict of nn.Parameter objects (rare) |
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...
