5.1 Modules and Model Construction

The multilayer perceptron in Section 4.2 had just four parameter arrays, small enough to manage by hand. Real-world architectures are far more intricate. A modern residual network for computer vision stacks dozens or hundreds of layers, and a language model such as Llama 3 8B (Grattafiori et al., 2024), holding 8 billion parameters across 32 identical transformer blocks, spreads its weights over 291 separate arrays. Every single one of those arrays must reach the optimizer, be written into checkpoints, and move onto the GPU. Worse, omitting an array raises no syntax error: it simply sits silently untrained or unsaved.

Deep learning frameworks solve this bookkeeping problem with a single recursive abstraction: the module. A module can represent an individual layer, a group of layers, or an entire model. It owns parameters, owns child modules, and defines a forward computation mapping inputs to outputs. Because modules nest inside other modules, any architecture forms a tree of modules (Figure 5.1.1). Every framework discovers all parameters by traversing this tree, provided each child is properly registered with its parent.

This section is hands-on, and readers who have already built custom modules can skim the basics. Do not skip how registration works and how it fails silently, however, because that bug is notoriously easy to hit. We also show how to write custom forward computations (such as residual connections), how lazy initialization infers shapes on the fly, and how to separate architectural hyperparameters into a compact configuration object. Later sections reuse the same tree traversal for counting parameters (Section 5.2), initializing weights (Section 5.3), saving checkpoints (Section 5.6), and placing models on GPUs (Section 5.7).

Figure 5.1.1:

The module tree of the residual MLP that we build at the end of this section. Each edge carries the name under which the parent registered the child, and the path of names from the root to a parameter is the name of that parameter, here 1.body.0.weight. Blocks 2 to 4 repeat block 1.

from dataclasses import dataclass

5.1.1 The Module Abstraction#

5.1.1.1 Sequential Containers and the Registry#

Every model we have written since Section 2.4 has been a module: d2l.Module subclasses each framework's base module class. The fastest way to assemble a pipeline of layers is a sequential container, which chains its children together one after another. Below we construct an MLP with one hidden layer of 256 ReLU units and 10 outputs, matching Section 4.2, and pass in a minibatch of two examples with 20 features each.

In PyTorch the base class is nn.Module and nn.Sequential chains layers passed as arguments.

net = nn.Sequential(nn.Linear(20, 256), nn.ReLU(), nn.Linear(256, 10))

X = torch.rand(2, 20)
net(X).shape
torch.Size([2, 10])

Under the hood, the container stores its children in an ordered registry mapping names to child modules, and its forward pass iterates through that table in insertion order.

named_children yields (name, module) pairs ('0', '1', '2').

dict(net.named_children())
{'0': Linear(in_features=20, out_features=256, bias=True),
 '1': ReLU(),
 '2': Linear(in_features=256, out_features=10, bias=True)}

Every tree traversal over the model begins at this registry. Gathering parameters for the optimizer, serializing weights to disk, and moving tensors to a GPU all recurse through registered children down to every leaf parameter. As far as those operations are concerned, an unregistered layer might as well not exist.

5.1.1.2 Subclasses of the Module Class#

A sequential container handles linear chains neatly, but many architectures branch, merge, or reuse components. For anything beyond a straight chain, we subclass the framework's base module and implement two methods: a constructor that creates child modules and a forward method that specifies how data flows through them.

In PyTorch the forward method is forward.

Here is the same MLP once more:

class MLP(nn.Module):
    def __init__(self):
        super().__init__()
        self.hidden = nn.Linear(20, 256)
        self.out = nn.Linear(256, 10)

    def forward(self, X):
        return self.out(F.relu(self.hidden(X)))

Instantiating MLP and invoking net(X) dispatches to our custom forward method and maps the 2×202 \times 20 input batch X to an output tensor of shape (2, 10):

net = MLP()
net(X).shape
torch.Size([2, 10])

Two mechanisms do the heavy lifting behind the scenes. First, assigning self.hidden = ... is not plain Python attribute storage: the base module intercepts assignment via __setattr__, notices that the value is a module, and registers it under the attribute name (hidden and out). That automatic registration is all it takes for both layers' parameters to reach the optimizer. Second, we never have to write a backward method: automatic differentiation (Section 1.5) derives the gradients directly from the operations performed during the forward pass.

Always invoke a module as net(X).

Calling forward directly skips the hooks that __call__ runs (Section 5.8).

5.1.2 Module Containers#

5.1.2.1 Writing a Container#

A sequential container has just two responsibilities: register each child module as it is added, and pass the input through them in order. Implementing a minimal version ourselves clarifies exactly how registration works—and where it can go wrong.

class MySequential(nn.Module):
    def __init__(self, *args):
        super().__init__()
        for idx, module in enumerate(args):
            self.add_module(str(idx), module)

    def forward(self, X):
        for module in self.children():
            X = module(X)
        return X

add_module registers each child by string index, and children() iterates over the registry in insertion order.

Our custom MySequential behaves just like the built-in container:

net = MySequential(nn.Linear(20, 256), nn.ReLU(), nn.Linear(256, 10))
net(X).shape
torch.Size([2, 10])

5.1.2.2 Layers in a Plain List#

What happens if we store layers in an ordinary Python list, as anyone unfamiliar with module registration naturally would? The forward pass can still loop over the list, but a plain list is not a module. Does the framework still discover the layers inside it?

class PlainListMLP(nn.Module):
    def __init__(self):
        super().__init__()
        self.layers = [nn.Linear(20, 256), nn.ReLU(), nn.Linear(256, 10)]

    def forward(self, X):
        for layer in self.layers:
            X = layer(X)
        return X

net = PlainListMLP()
net(X).shape, sum(p.numel() for p in net.parameters())
(torch.Size([2, 10]), 0)

The forward pass succeeds, yet net.parameters() is empty because __setattr__ treats a plain Python list as an ordinary attribute rather than a module container. Worse than a completely empty model (which torch.optim.SGD rejects) is a partly registered model whose outer layers are attributes and inner layers sit in a plain list. We take one SGD step and check which weights move:

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)

To see which layers actually move during training, we snapshot all four weight matrices of PartlyRegisteredMLP in before, run a single backward pass on net(X).sum() followed by one SGD step, and compare each layer's weights against before:

net = PartlyRegisteredMLP()
layers = [net.first, *net.blocks, net.last]
before = [layer.weight.clone() for layer in layers]
optimizer = torch.optim.SGD(net.parameters(), lr=0.1)
net(X).sum().backward()
optimizer.step()
[not torch.equal(b, layer.weight) for b, layer in zip(before, layers)]
[True, False, False, True]

Only the outer weights updated, without a single warning or error. Backpropagation flowed through self.blocks to reach self.first, but the optimizer never saw the middle layers. Wrapping the list in nn.ModuleList (or nn.ModuleDict for dictionaries) registers every child properly:

class ModuleListMLP(PlainListMLP):
    def __init__(self):
        super().__init__()
        self.layers = nn.ModuleList(self.layers)

net = ModuleListMLP()
net(X).shape, sum(p.numel() for p in net.parameters())
(torch.Size([2, 10]), 7946)

All 7,946 parameters are now registered. Use nn.Sequential for straight chains, and nn.ModuleList or nn.ModuleDict whenever your forward method loops or indexes over children manually.

5.1.3 Forward Computation#

Because a module's forward method is just Python, it can invoke arbitrary tensor operations, loops, conditionals, and skip paths. We use this flexibility to implement a residual connection, and then see what constraints arise when a framework compiles the training step.

5.1.3.1 Residual Connections#

The simplest widely used architecture that is not a straight chain is a residual connection, which adds a block's input directly to its output (He et al., 2016). Writing ff for the block's body (here two fully connected layers with a ReLU between them), the block computes

y=x+f(x).(5.1.1)\mathbf{y} = \mathbf{x} + f(\mathbf{x}). \tag{5.1.1}

Whenever f(x)=0f(\mathbf{x}) = \mathbf{0}, the block reduces to the identity map, allowing signals to pass cleanly through deep stacks while each block learns only a refinement f(x)f(\mathbf{x}) rather than rebuilding the representation from scratch. The ResNet architectures of Section 7.4 rely on this pattern. No framework needs a special built-in layer for residual connections: in a custom module, it is simply one line, X + self.body(X):

class ResidualBlock(nn.Module):
    def __init__(self, num_hiddens):
        super().__init__()
        self.body = nn.Sequential(
            nn.Linear(num_hiddens, num_hiddens), nn.ReLU(),
            nn.Linear(num_hiddens, num_hiddens))

    def forward(self, X):
        return X + self.body(X)
Figure 5.1.2:

A residual block. The input splits into the body, Linear, ReLU, Linear, and an identity path, and the two rejoin by addition.

Figure 5.1.2 depicts the wiring. Adding x\mathbf{x} and f(x)f(\mathbf{x}) requires their shapes to match, so a residual block takes a single hidden width num_hiddens.

block = ResidualBlock(24)
block(torch.randn(2, 24)).shape
torch.Size([2, 24])

A forward method can also depend on values that are neither inputs nor trainable parameters. A scalar constant can live as an ordinary Python attribute, whereas a tensor tracked from data (such as running input statistics) must be saved in checkpoints and moved across devices alongside the model without being updated by the optimizer. We cover how to register such non-trainable buffers in Section 5.2.1.2.

5.1.3.2 Eager and Compiled Execution#

So far our forward passes have executed like regular Python, running one operation at a time. To eliminate Python overhead and fuse operations, however, frameworks can trace a computation once and replay the compiled graph on future calls. That speedup comes with a trade-off: compiled execution restricts data-dependent Python control flow inside the forward pass.

Both Gluon Block and PyTorch nn.Module run eagerly by default, executing Python statement by statement, so data-dependent control flow works just like NumPy (we cover graph compilation in Chapter 13).

5.1.4 Lazy Initialization#

5.1.4.1 Shapes from Data#

Many layer libraries let a layer specify only its output dimension at construction and infer its input width from the first minibatch.

Before the first forward pass, nn.LazyLinear(256) holds an UninitializedParameter without a shape:

net = nn.Sequential(nn.LazyLinear(256), nn.ReLU(), nn.LazyLinear(10))
net[0].weight
<UninitializedParameter>

Passing the first minibatch X through the network cascades shapes from layer to layer and materializes every weight tensor:

net(X)
net[0].weight.shape
torch.Size([256, 20])

5.1.4.2 Initialization after a Dry Run#

Lazy layers free us from manually propagating input dimensions from layer to layer, which quickly becomes error-prone in deep models. The trade-off is that parameters do not exist until data flows through the network: before that first pass, we cannot inspect parameter counts or run shape-dependent initializers such as Xavier initialization (Section 4.4.2.1). A lazy model therefore needs its initializer either recorded up front or applied after a dry run (a single forward pass on a dummy minibatch whose output is discarded) that materializes every shape.

d2l.Module.apply_init runs one forward pass without tracking gradients to materialize lazy shapes, then applies an initializer callback across the module tree via self.apply:

@d2l.add_to_class(d2l.Module)
def apply_init(self, inputs, init=None):
    """Run a dry pass to fix lazy shapes, then apply `init`."""
    with torch.no_grad():
        self(*inputs)
    if init is not None:
        self.apply(init)

nn.Module.apply(fn) calls fn on every module of the tree, children before their parents: one more task that is a walk over the tree. Here is apply_init with Xavier's uniform initializer:

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.shape
torch.Size([256, 20])

When should we use lazy layers versus explicit dimensions? For rapid prototyping on unfamiliar datasets, lazy layers are handy. For production models whose parameters we want to count, initialize programmatically, or instantiate from a configuration file without dummy data, declaring explicit input and output widths is cleaner, and that is the convention we adopt for the rest of this chapter.

5.1.5 Models from a Config#

5.1.5.1 Configs and Builders#

Can we reconstruct a trained model from its saved weight tensors alone? Not entirely. A trained model consists of both numerical arrays and the code that interprets them. Every width and depth we wrote earlier was hardcoded directly into constructor calls; a weights file reflects those choices only indirectly (tensor shapes reveal layer widths, but nothing in the arrays reveals a parameter-free choice such as ReLU vs. tanh).

Architectural hyperparameters that vary across experiments therefore belong in a dedicated configuration object (config) that can be logged alongside metrics and saved next to checkpoints, while the topology itself (what each block computes and how blocks wire together) lives in code. Below, a Python dataclass captures four architectural fields, and a build factory function turns any config into a complete module tree:

@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))

A single config completely specifies an instance of the architecture: an input projection from num_inputs to num_hiddens, num_blocks residual blocks, and an output head. Notice that blocks starts as a temporary Python list, which is completely safe here because unpacking it into the sequential container registers every block immediately. Because every layer specifies both its input and output widths, we can inspect and count parameters right away without a dry run.

net = build(MLPConfig())
[(name, tuple(p.shape)) for name, p in net.named_parameters()][:4]
[('0.weight', (256, 784)),
 ('0.bias', (256,)),
 ('1.body.0.weight', (256, 256)),
 ('1.body.0.bias', (256,))]

The resulting model maps a minibatch of 784-dimensional vectors (such as flattened Fashion-MNIST images) to 10 output logits:

net(torch.rand(2, 784)).shape
torch.Size([2, 10])

5.1.5.2 Counting Parameters#

A config also lets us calculate a model's exact parameter count on paper before allocating any memory. The input projection has 784⋅256+256=200,960784 \cdot 256 + 256 = 200{,}960 parameters, each residual block contains two dense layers totaling 2⋅(256⋅256+256)=131,5842 \cdot (256 \cdot 256 + 256) = 131{,}584 parameters, and the output layer adds 256⋅10+10=2,570256 \cdot 10 + 10 = 2{,}570, giving

200,960+4⋅131,584+2,570=729,866(5.1.2)200{,}960 + 4 \cdot 131{,}584 + 2{,}570 = 729{,}866 \tag{5.1.2}

parameters in all—dominated by the residual blocks. Scaling the model up now takes changing two config fields rather than editing model code, and walking the parameter tree verifies our calculation:

for cfg in (MLPConfig(), MLPConfig(num_hiddens=512, num_blocks=8)):
    n = sum(p.numel() for p in build(cfg).parameters())
    print(f'num_hiddens={cfg.num_hiddens}, num_blocks={cfg.num_blocks}: '
          f'{n:,} parameters')
num_hiddens=256, num_blocks=4: 729,866 parameters
num_hiddens=512, num_blocks=8: 4,609,546 parameters

Doubling the hidden width quadruples the parameter count inside each block, and doubling the number of blocks doubles that total, so the larger config contains more than six times as many parameters. Real-world foundation models follow the exact same pattern: our 8B language model is specified by a compact config (e.g., 32 blocks, hidden width 4,096) paired with builder code that materializes the module tree.

Keep in mind that a config stores hyperparameters, not implementation code. Restoring a model from a checkpoint requires all three pieces: the weights, the config, and the matching build function and block definitions. In Section 5.6, we save the weights and config together, while version control takes care of the code.

So far we have only located and counted parameters without inspecting what lives inside them. In Section 5.2, we open up the tensors a model owns, account for how much memory training consumes, and see how to share or freeze weights.

5.1.6 Summary#

Three core ideas anchor model construction. First, every neural network is a tree of modules, with each parameter uniquely addressed by its path from the root. Second, optimizers, checkpoints, and device transfers all operate by walking registered children, so hiding layers inside an unregistered container silently excludes them from training and saving. Third, factoring variable dimensions into a lightweight config paired with a build function makes architectures easy to log, scale, and reproduce. On top of these fundamentals, custom forward methods give us full Python flexibility (subject to tracing constraints under compiled execution), while lazy layers offer convenience for quick experiments at the cost of deferring shape creation until a dry run.

5.1.7 Exercises#

  1. [code] Unregistered modules. The plain list in PlainListMLP keeps its layers out of net.parameters(), net.to(device), and net.state_dict(). Predict, then verify, what three further operations do to the model.
    1. Call net.apply(init_xavier) and check whether the weight of net.layers[0] changes.
    2. Add nn.Dropout(0.5) after the nn.ReLU() in the list, call net.eval(), and pass the same input through the model twice.
    3. The method load_state_dict is the inverse of state_dict: it copies a dictionary of saved tensors into a model. Call net.load_state_dict(ModuleListMLP().state_dict()).
    4. Which of these failures are silent and which raise an error? Explain all three from the same missing registration.
  1. Widening a residual block. ResidualBlock requires its input and output widths to agree. Suppose a block maps width dd to a larger width d′d', so its body ends in a d′d'-wide layer and the skip path must also produce width d′d'. Give one way to build that skip path with parameters and one without. For each, count the extra parameters and state which output coordinates still receive the identity path.

  2. [code] A module from scratch. ● In plain Python and NumPy, without any framework base class, write a Parameter class that wraps an array and a minimal Module class whose __setattr__ registers every assigned Parameter or Module. Give Module a parameters() method that recurses into the registered children. Write a Linear subclass of Module that holds a weight and a bias, build a two-layer MLP from two instances of it, and verify that parameters() returns all four arrays. Then store the two layers in a plain list, check what parameters() returns, and extend Module so that the list version finds all four arrays as well.

    Adapted from CMU 10-714, Homework 2, Question 2.

  1. [code] Lazy input width. Build net = nn.Sequential(nn.LazyLinear(256), nn.ReLU(), nn.LazyLinear(10)) and pass a batch with 20 features through it, then a batch with 30 features. Explain the outcome from what the first forward pass did to each layer. Then describe a model that accepts inputs of either width while sharing every layer after the first.

Discussions