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