net = nn.Sequential(nn.Linear(20, 256), nn.ReLU(), nn.Linear(256, 10))
X = torch.rand(2, 20)
net(X).shapeDive into Deep Learning · §5.1
Modules and Model Construction
module trees · child registration · containers · residual blocks · lazy shapes · configs
Motivation & Scale
The Module Tree
The Module Abstraction
When layers form a straight pipeline, a sequential container registers each child by integer index and passes activations through them in insertion order:
torch.Size([2, 10])
{'0': Linear(in_features=20, out_features=256, bias=True),
'1': ReLU(),
'2': Linear(in_features=256, out_features=10, bias=True)}
Subclassing the Base Module
torch.Size([2, 10])
__setattr__: Assigning self.hidden = ... inserts the child into the module’s child registry; always call net(X) to run hooks and builders.Why Registration Matters
Building a Container
__init__ and loops over them in forward:torch.Size([2, 10])
The Plain-List Trap
list (self.layers = [...]) allows forward to run, but net.parameters() is empty (0 parameters instead of 7,946):(torch.Size([2, 10]), 0)
The Silent Training Bug
Outer layers as attributes, middle layers in a plain list: the optimizer accepts the model silently.
class PartlyRegisteredMLP(nn.Module):
def __init__(self):
super().__init__()
self.first = nn.Linear(20, 256)
self.blocks = [nn.Linear(256, 256), nn.Linear(256, 256)] # Plain list
self.last = nn.Linear(256, 10)
def forward(self, X):
X = F.relu(self.first(X))
for block in self.blocks:
X = F.relu(block(X))
return self.last(X)[True, False, False, True]
self.first updates (True), but the optimizer never received self.blocks, so their weights never change (False, False).Registered Collection Containers
nn.ModuleList (or nn.ModuleDict) so all 7{,}946 parameters register in the module tree:(torch.Size([2, 10]), 7946)
Non-Sequential Wiring
A module’s forward method can express arbitrary branching and skip paths, such as a residual block that adds its input directly to a two-layer transformation f(\mathbf{x}):
\mathbf{y} = \mathbf{x} + f(\mathbf{x})
num_hiddens.Forward Is Just Python
No special framework primitive is needed for a skip connection—the forward method simply returns X + self.body(X):
torch.Size([2, 24])
Forward Execution Modes
if/while loops and print debugging work directly.for block in self.blocks:) unroll cleanly, whereas data-dependent branches require symbolic control flow.Deferred Shape Inference
Materializing Shapes Before Training
class TinyMLP(d2l.Module):
def __init__(self):
super().__init__()
self.net = nn.Sequential(nn.LazyLinear(256), nn.ReLU(),
nn.LazyLinear(10))
def init_xavier(module):
if isinstance(module, nn.Linear):
nn.init.xavier_uniform_(module.weight)
model = TinyMLP()
model.apply_init([X], init_xavier)
model.net[0].weight.shapetorch.Size([256, 20])
Dataclass Configurations
@dataclass paired with a build function.Dataclass Configurations
@dataclass
class MLPConfig:
num_inputs: int = 784
num_hiddens: int = 256
num_blocks: int = 4
num_outputs: int = 10
def build(cfg: MLPConfig) -> nn.Module:
blocks = [ResidualBlock(cfg.num_hiddens) for _ in range(cfg.num_blocks)]
return nn.Sequential(nn.Linear(cfg.num_inputs, cfg.num_hiddens),
*blocks, nn.Linear(cfg.num_hiddens, cfg.num_outputs))Analytical vs. Tree-Walk Counts
With explicit widths in MLPConfig(num_inputs=784, num_hiddens=256, num_blocks=4, num_outputs=10), we can compute the exact parameter count on paper and verify it across the module tree:
| Module Component | Shape Formula (W + b) | Parameter Count |
|---|---|---|
Input projection (0) |
784 \times 256 + 256 | 200{,}960 |
4 Residual blocks (1..4) |
4 \times 2 \times (256 \times 256 + 256) | 526{,}336 |
Output head (5) |
256 \times 10 + 10 | 2{,}570 |
| Total network | 10 Linear layers (20 parameter tensors) | 729{,}866 |
num_hiddens=256, num_blocks=4: 729,866 parameters
num_hiddens=512, num_blocks=8: 4,609,546 parameters
Concept Check
Work out both questions from the MLPConfig architecture (d_{\text{in}}=784, K residual blocks of width d, d_{\text{out}}=10):
d = 256) in a plain Python list (in a framework that does not scan lists) while assigning the input and output layers to self.first and self.last. How many parameters does the optimizer receive, and what happens on a GPU?num_hiddens (256 \to 512) and num_blocks (4 \to 8) increase the total parameter count by more than 6\times (729{,}866 \to 4{,}609{,}546)?Answers:
.to(gpu) moves only the outer layers, crashing the first forward pass on a CPU/GPU device mismatch.Key Takeaways
| Concept | Mechanism / Rule | Practical Systems Implication |
|---|---|---|
| Module tree | Recursive hierarchy of layers/blocks; leaves hold parameters | Every parameter is uniquely addressed by its dotted root-to-leaf path |
| Registration | __setattr__ and registered module containers |
Unregistered plain lists hide layers from optimizers, checkpoints, and GPUs |
Custom forward |
Arbitrary Python tensor code (e.g., \mathbf{x} + f(\mathbf{x})); call via net(X) |
Compiled steps forbid branching on tensor values |
| Lazy layers | Infer n_{\text{in}} on the first minibatch; initialize after a dry run | Handy for quick prototypes; explicit widths are preferred for production |
| Config + builder | Serializable @dataclass hyperparameters + build(cfg) factory |
Reconstructing a model requires weights + config + builder code |