Modules and Model Construction

Dive into Deep Learning · §5.1

Modules and Model Construction
module trees · child registration · containers · residual blocks · lazy shapes · configs

Why Models Need a Recursive Bookkeeping Abstraction

Motivation & Scale

  • Hundreds of distributed weight tensors: Llama 3 8B stacks 32 transformer blocks of 9 parameter arrays each plus 3 outer arrays, totaling 32 \times 9 + 3 = 291 distinct tensors.
  • All-or-nothing lifecycle: Every tensor must be discovered by the optimizer, serialized into checkpoints, initialized, and transferred to GPU memory.
  • Silent failure hazard: Omitting a weight array from the module registry raises no error during a CPU forward pass—those weights simply stay frozen at initialization.

A Model Is a Tree of Modules Addressed by Path

The Module Tree

  • Modules all the way down: Every layer, composite block, and complete network is a module that owns parameters, registers child modules, and defines a forward pass.
  • Hierarchical paths: Each edge carries the attribute or index name under which the parent registered the child, so every leaf parameter is uniquely named by its path from the root (e.g., block 1, layer 0, weight).

Sequential Containers Chain Registered Children

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:

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])
{'0': Linear(in_features=20, out_features=256, bias=True),
 '1': ReLU(),
 '2': Linear(in_features=256, out_features=10, bias=True)}

Custom Module Subclasses Register Attributes

Subclassing the Base Module

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)))
net = MLP()
net(X).shape
torch.Size([2, 10])
  • Automatic registration via __setattr__: Assigning self.hidden = ... inserts the child into the module’s child registry; always call net(X) to run hooks and builders.

Every Whole-Model Operation Walks the Module Registry

Why Registration Matters

  • Five recursive tree walks: Optimizer setup, checkpointing, device transfer, initialization, and mode/hook toggling all walk registered children.
  • Consequence of an unregistered layer: Its weights never update, are omitted from checkpoints, stay behind when the model moves to the GPU, and keep training-mode Dropout/BatchNorm during evaluation.

Inside a Sequential Container: Registration + Loop

Building a Container

  • A sequential container only registers children in __init__ and loops over them in forward:
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
net = MySequential(nn.Linear(20, 256), nn.ReLU(), nn.Linear(256, 10))
net(X).shape
torch.Size([2, 10])

Pitfall: Plain Python Lists Hide Layers from PyTorch

The Plain-List Trap

  • Storing layers inside an ordinary Python list (self.layers = [...]) allows forward to run, but net.parameters() is empty (0 parameters instead of 7,946):
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)

A Partly Registered Model Silently Freezes Inner Layers

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]
  • Gradients flow, weights stay frozen: self.first updates (True), but the optimizer never received self.blocks, so their weights never change (False, False).

Fixing List Registration with Module Containers

Registered Collection Containers

  • Wrap dynamic collections of layers in nn.ModuleList (or nn.ModuleDict) so all 7{,}946 parameters register in the module tree:
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)

Custom Forward Passes: The Residual Connection

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

  • Identity baseline: When f(\mathbf{x}) = \mathbf{0}, the block acts as the identity map \mathbf{y} = \mathbf{x}, letting deep stacks learn incremental refinements.
  • Shape invariant: Elementwise addition requires \mathbf{x} and f(\mathbf{x}) to share the exact same feature width num_hiddens.

Implementing a Reusable ResidualBlock Module

Forward Is Just Python

No special framework primitive is needed for a skip connection—the forward method simply returns 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)
block = ResidualBlock(24)
block(torch.randn(2, 24)).shape
torch.Size([2, 24])

Eager Execution vs. Graph Tracing

Forward Execution Modes

  • Eager execution (default): Runs line-by-line on concrete values so data-dependent if/while loops and print debugging work directly.
  • Compiled graph tracing: Static loops over registered modules (for block in self.blocks:) unroll cleanly, whereas data-dependent branches require symbolic control flow.

Lazy Layers Infer Input Shapes on the First Batch

Deferred Shape Inference

  • Lazy layers specify only their output width at construction and materialize weight matrices on the first forward pass:
net = nn.Sequential(nn.LazyLinear(256), nn.ReLU(), nn.LazyLinear(10))
net[0].weight
<UninitializedParameter>
net(X)
net[0].weight.shape
torch.Size([256, 20])

Initializing Lazy Models After a Dry Run

Materializing Shapes Before Training

  • Because variance-scaling initializers depend on n_{\text{in}} and n_{\text{out}}, lazy layers must run a dummy forward pass (dry run) before custom initialization:
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])

Separating Architecture Configs from Builder Code

Dataclass Configurations

  • Production code factors hyperparameters into a serializable @dataclass paired with a build function.

Building a Model from a Config

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))
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,))]

Exact Parameter Accounting From the Config

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: Module Trees & Parameter Scaling

Concept Check

Work out both questions from the MLPConfig architecture (d_{\text{in}}=784, K residual blocks of width d, d_{\text{out}}=10):

  1. Suppose a programmer stores the 4 residual blocks (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?
  2. Why does doubling both 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:

  1. Only 200{,}960 + 2{,}570 = 203{,}530 parameters reach the optimizer; the 526{,}336 block parameters remain frozen. Calling .to(gpu) moves only the outer layers, crashing the first forward pass on a CPU/GPU device mismatch.
  2. Each residual block’s weights scale quadratically with width (2 d^2) and linearly with depth (K), multiplying block parameters by 2^2 \times 2 = 8\times (526{,}336 \to 4{,}202{,}496).

Summary: Modules and Model Construction

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