from dataclasses import dataclass5.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).
1.body.0.weight. Blocks 2 to 4 repeat block 1.
from dataclasses import dataclass
import tensorflow as tffrom dataclasses import dataclass
from mxnet import autograd, gluon, init, np as mnp, npx
from mxnet.gluon import nn
npx.set_np()from dataclasses import dataclass5.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.
In Keras the base class is tf.keras.layers.Layer (with training methods on tf.keras.Model) and tf.keras.Sequential chains a list of layers.
In Flax NNX the base class is nnx.Module, nnx.Sequential chains its arguments, and layers allocate parameters at construction using rngs.
In Gluon the base class is nn.Block, nn.Sequential adds layers via add, and initialize() prepares parameters before the first call (Section 5.1.4).
net = nn.Sequential(nn.Linear(20, 256), nn.ReLU(), nn.Linear(256, 10))
X = torch.rand(2, 20)
net(X).shapetorch.Size([2, 10])
net = tf.keras.Sequential([tf.keras.layers.Dense(256, activation='relu'),
tf.keras.layers.Dense(10)])
X = tf.random.uniform((2, 20))
net(X).shapeTensorShape([2, 10])
rngs = nnx.Rngs(d2l.get_key())
net = nnx.Sequential(nnx.Linear(20, 256, rngs=rngs), nnx.relu,
nnx.Linear(256, 10, rngs=rngs))
X = jax.random.uniform(d2l.get_key(), (2, 20))
net(X).shape(2, 10)
net = nn.Sequential()
net.add(nn.Dense(256, activation='relu', in_units=20))
net.add(nn.Dense(10, in_units=256))
net.initialize()
X = mnp.random.uniform(size=(2, 20))
net(X).shape(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').
Keras stores children in net.layers with auto-generated names.
nnx.state(net, nnx.Param) lists every parameter by its path through layers.
Printing the block displays its children keyed by index (0, 1).
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)}
net.layers[<Dense name=dense, built=True>, <Dense name=dense_1, built=True>]
[(path, value.shape)
for path, value in nnx.state(net, nnx.Param).flat_state()][(('layers', 0, 'bias'), (256,)),
(('layers', 0, 'kernel'), (20, 256)),
(('layers', 2, 'bias'), (10,)),
(('layers', 2, 'kernel'), (256, 10))]
netSequential(
(0): Dense(20 -> 256, Activation(relu))
(1): Dense(256 -> 10, linear)
)
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.
In Keras the forward method is call.
In Flax NNX the forward method is __call__.
In Gluon 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)))class MLP(tf.keras.Model):
def __init__(self):
super().__init__()
self.hidden = tf.keras.layers.Dense(256, activation='relu')
self.out = tf.keras.layers.Dense(10)
def call(self, X):
return self.out(self.hidden(X))class MLP(nnx.Module):
def __init__(self, rngs):
self.hidden = nnx.Linear(20, 256, rngs=rngs)
self.out = nnx.Linear(256, 10, rngs=rngs)
def __call__(self, X):
return self.out(nnx.relu(self.hidden(X)))class MLP(nn.Block):
def __init__(self):
super().__init__()
self.hidden = nn.Dense(256, activation='relu', in_units=20)
self.out = nn.Dense(10, in_units=256)
def forward(self, X):
return self.out(self.hidden(X))Instantiating MLP and invoking net(X) dispatches to our custom forward method and maps the \(2 \times 20\) input batch X to an output tensor of shape (2, 10):
In JAX, the constructor takes an explicit nnx.Rngs.
In MXNet, net.initialize() creates the parameters first.
net = MLP()
net(X).shapetorch.Size([2, 10])
net = MLP()
net(X).shapeTensorShape([2, 10])
net = MLP(nnx.Rngs(d2l.get_key()))
net(X).shape(2, 10)
net = MLP()
net.initialize()
net(X).shape(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).
Calling call directly skips __call__, which builds deferred variables on the first call (Section 5.1.4).
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 Xclass MySequential(tf.keras.Model):
def __init__(self, *args):
super().__init__()
self.modules = args
def call(self, X):
for module in self.modules:
X = module(X)
return Xclass MySequential(nnx.Module):
def __init__(self, *modules):
self.modules = nnx.List(modules)
def __call__(self, X):
for module in self.modules:
X = module(X)
return Xclass MySequential(nn.Block):
def __init__(self):
super().__init__()
self._layers = [] # The registry holds weak references
def add(self, block):
self._layers.append(block)
self.register_child(block)
def forward(self, X):
for block in self._layers:
X = block(X)
return Xadd_module registers each child by string index, and children() iterates over the registry in insertion order.
Keras’s __setattr__ automatically scans inside Python lists, tuples, and dicts, tracking every layer in self.modules.
nnx.List wraps a sequence of modules as a graph-tracked container under modules.
register_child adds a block to the registry (which stores weak references, so self._layers keeps the blocks alive).
Our custom MySequential behaves just like the built-in container:
net = MySequential(nn.Linear(20, 256), nn.ReLU(), nn.Linear(256, 10))
net(X).shapetorch.Size([2, 10])
net = MySequential(tf.keras.layers.Dense(256, activation='relu'),
tf.keras.layers.Dense(10))
net(X).shapeTensorShape([2, 10])
rngs = nnx.Rngs(d2l.get_key())
net = MySequential(nnx.Linear(20, 256, rngs=rngs), nnx.relu,
nnx.Linear(256, 10, rngs=rngs))
net(X).shape(2, 10)
net = MySequential()
net.add(nn.Dense(256, activation='relu', in_units=20))
net.add(nn.Dense(10, in_units=256))
net.initialize()
net(X).shape(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?
In Keras the plain list is the ordinary way to hold a stack of layers, because the attribute scan looks inside lists:
The block below keeps its layers in a plain list. net.initialize() walks the registry and cannot reach them, so we initialize each layer by hand to get a forward pass at all:
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)
class ListMLP(tf.keras.Model):
def __init__(self):
super().__init__()
self.blocks = [tf.keras.layers.Dense(256, activation='relu'),
tf.keras.layers.Dense(10)]
def call(self, X):
for block in self.blocks:
X = block(X)
return X
net = ListMLP()
net(X).shape, sum(int(tf.size(v)) for v in net.trainable_variables)(TensorShape([2, 10]), 7946)
class PlainListMLP(nnx.Module):
def __init__(self, rngs):
self.layers = [nnx.Linear(20, 256, rngs=rngs),
nnx.Linear(256, 10, rngs=rngs)] # Plain list
def __call__(self, X):
return self.layers[1](nnx.relu(self.layers[0](X)))
try:
net = PlainListMLP(nnx.Rngs(d2l.get_key()))
except ValueError as e:
print(str(e).split(' of Pytree')[0]) # The rest lists the repairsFound data on value of type '<class 'list'>' assigned to static attribute 'layers'
class PlainListMLP(nn.Block):
def __init__(self):
super().__init__()
self.layers = [nn.Dense(256, activation='relu', in_units=20),
nn.Dense(10, in_units=256)]
for layer in self.layers:
layer.initialize() # By hand: net.initialize() cannot see them
def forward(self, X):
for layer in self.layers:
X = layer(X)
return X
net = PlainListMLP()
net(X).shape, len(net.collect_params())UserWarning: "PlainListMLP.layers" is an unregistered container with Blocks.
Note that Blocks inside the list, tuple or dict will not be registered
automatically. Make sure to register them using register_child() or switching to
nn.Sequential/nn.HybridSequential instead.
((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:
Because Keras scans inside Python lists assigned to attributes, all 7,946 parameters (\(20 \cdot 256 + 256 + 256 \cdot 10 + 10\)) are tracked automatically. Instead, the structural bug Keras forbids is attaching a new layer after the model has already been built:
NNX immediately raises a ValueError at construction when a plain Python list holds modules, naming nnx.List as the fix so a partly registered model can never be constructed silently:
The forward pass succeeds, yet collect_params() is empty. While a completely empty parameter dict makes Trainer fail immediately, a partly registered model (where outer layers are attributes and inner layers sit in a plain list) fails silently during training. We take one SGD step on such a model 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)class PartlyRegisteredMLP(nn.Block):
def __init__(self):
super().__init__()
self.first = nn.Dense(256, activation='relu', in_units=20)
self.blocks = [nn.Dense(256, activation='relu', in_units=256)
for _ in range(2)] # Plain list
for block in self.blocks:
block.initialize() # By hand, as before
self.last = nn.Dense(10, in_units=256)
def forward(self, X):
X = self.first(X)
for block in self.blocks:
X = 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:
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]
net = PartlyRegisteredMLP()
net.initialize()
layers = [net.first, *net.blocks, net.last]
before = [layer.weight.data().copy() for layer in layers]
trainer = gluon.Trainer(net.collect_params(), 'sgd', {'learning_rate': 0.1})
with autograd.record():
loss = net(X).sum()
loss.backward()
trainer.step(batch_size=1)
[bool((b != layer.weight.data()).any()) for b, layer in zip(before, layers)]UserWarning: "PartlyRegisteredMLP.blocks" is an unregistered container with
Blocks. Note that Blocks inside the list, tuple or dict will not be registered
automatically. Make sure to register them using register_child() or switching to
nn.Sequential/nn.HybridSequential instead.
UserWarning: "PartlyRegisteredMLP.blocks" is an unregistered container with
Blocks. Note that Blocks inside the list, tuple or dict will not be registered
automatically. Make sure to register them using register_child() or switching to
nn.Sequential/nn.HybridSequential instead.
[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:
Only the outer weights updated. Backpropagation flowed through self.blocks to reach self.first, but Trainer never received the list’s parameters (though collect_params() does print a warning). Registering each child via register_child fixes the bug:
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)
try:
net.head = tf.keras.layers.Dense(2) # net is built: too late
except ValueError as e:
print(str(e)[:70].rsplit(' ', 1)[0], '...')You cannot add new elements of state (variables or sub-layers) to a ...
class ListMLP(PlainListMLP):
def __init__(self, rngs):
self.layers = nnx.List([nnx.Linear(20, 256, rngs=rngs),
nnx.Linear(256, 10, rngs=rngs)])
net = ListMLP(nnx.Rngs(d2l.get_key()))
state = nnx.state(net, nnx.Param)
net(X).shape, sum(x.size for _, x in state.flat_state())((2, 10), 7946)
class RegisteredListMLP(PlainListMLP):
def __init__(self):
super().__init__()
for layer in self.layers:
self.register_child(layer)
net = RegisteredListMLP()
net(X).shape, sum(p.data().size for p in net.collect_params().values())((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.
Keras requires all layers to be attached in __init__ or build; any layer reachable from an attribute (including inside lists or dicts) is tracked automatically.
With nnx.List (or nnx.Dict for mappings), all 7,946 parameters are registered cleanly.
All 7,946 parameters are now registered. In Gluon, register children via attribute assignment, nn.Sequential, or register_child.
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 \(f\) for the block’s body (here two fully connected layers with a ReLU between them), the block computes
\[\mathbf{y} = \mathbf{x} + f(\mathbf{x}). \tag{5.1.1}\]
Whenever \(f(\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(\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)class ResidualBlock(tf.keras.layers.Layer):
def __init__(self, num_hiddens, **kwargs):
super().__init__(**kwargs)
self.body = tf.keras.Sequential([
tf.keras.layers.Dense(num_hiddens, activation='relu'),
tf.keras.layers.Dense(num_hiddens)])
def call(self, X):
return X + self.body(X)class ResidualBlock(nnx.Module):
def __init__(self, num_hiddens, *, rngs):
self.body = nnx.Sequential(
nnx.Linear(num_hiddens, num_hiddens, rngs=rngs), nnx.relu,
nnx.Linear(num_hiddens, num_hiddens, rngs=rngs))
def __call__(self, X):
return X + self.body(X)class ResidualBlock(nn.Block):
def __init__(self, num_hiddens):
super().__init__()
self.body = nn.Sequential()
self.body.add(nn.Dense(num_hiddens, activation='relu',
in_units=num_hiddens),
nn.Dense(num_hiddens, in_units=num_hiddens))
def forward(self, X):
return X + self.body(X)Figure 5.1.2 depicts the wiring. Adding \(\mathbf{x}\) and \(f(\mathbf{x})\) requires their shapes to match, so a residual block takes a single hidden width num_hiddens.
Keras infers input widths when the layer is built, so the constraint falls on the caller: an input with other than num_hiddens columns makes the addition fail.
block = ResidualBlock(24)
block(torch.randn(2, 24)).shapetorch.Size([2, 24])
block = ResidualBlock(24)
block(tf.random.normal((2, 24))).shapeTensorShape([2, 24])
block = ResidualBlock(24, rngs=nnx.Rngs(d2l.get_key()))
X24 = jax.random.normal(d2l.get_key(), (2, 24))
block(X24).shape(2, 24)
block = ResidualBlock(24)
block.initialize()
block(mnp.random.normal(size=(2, 24))).shape(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).
Direct calls run eagerly, but d2l.Trainer compiles training steps with tf.function by tracing call once on symbolic tensors without concrete values. Because Keras does not apply AutoGraph inside Layer.call, a Python while loop conditioned on tensor values fails during tracing:
Direct calls run eagerly, but d2l.Trainer compiles training steps with nnx.jit by tracing __call__ once on abstract tracers that carry shapes and dtypes but no values. Branching on a tracer in a Python while loop raises an error:
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).
class HalvingNet(tf.keras.Model):
def __init__(self):
super().__init__()
self.proj = tf.keras.layers.Dense(24)
def call(self, X):
X = self.proj(X)
while tf.reduce_sum(tf.abs(X)) > 1: # Depends on the values of X
X = X / 2
return tf.reduce_sum(X)
net = HalvingNet()
print(net(X))
try:
tf.function(net)(X)
except tf.errors.OperatorNotAllowedInGraphError as e:
print(type(e).__name__)tf.Tensor(-0.08005211, shape=(), dtype=float32)
OperatorNotAllowedInGraphError
class HalvingNet(nnx.Module):
def __init__(self, rngs):
self.proj = nnx.Linear(20, 24, rngs=rngs)
def __call__(self, X):
X = self.proj(X)
while jnp.abs(X).sum() > 1: # Depends on the values of X
X = X / 2
return X.sum()
net = HalvingNet(nnx.Rngs(d2l.get_key()))
print(net(X))
try:
nnx.jit(lambda net, X: net(X))(net, X)
except jax.errors.TracerBoolConversionError as e:
print(type(e).__name__)-0.2457959
TracerBoolConversionError
Eager execution runs the data-dependent loop, whereas tracing rejects converting a symbolic tensor or tracer into a Python bool (requiring tf.while_loop or jax.lax.while_loop). Loops over static model structure, such as iterating over self.modules, unroll cleanly at trace time.
Eager execution runs the data-dependent loop, whereas tracing rejects converting a symbolic tensor or tracer into a Python bool (requiring tf.while_loop or jax.lax.while_loop). Loops over static model structure, such as iterating over self.modules, unroll cleanly at trace time.
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:
Before the first call, Dense(256) has not allocated any variables at all:
NNX layers require explicit input and output widths and allocate their parameters immediately in __init__.
Before the first forward pass, nn.Dense(256) creates parameter placeholders with unknown input dimension -1:
net = nn.Sequential(nn.LazyLinear(256), nn.ReLU(), nn.LazyLinear(10))
net[0].weight<UninitializedParameter>
net = tf.keras.Sequential([tf.keras.layers.Dense(256, activation='relu'),
tf.keras.layers.Dense(10)])
net.weights[]
net = nn.Sequential()
net.add(nn.Dense(256, activation='relu'))
net.add(nn.Dense(10))
{name: p.shape for name, p in net.collect_params().items()}{'0.weight': (256, -1),
'0.bias': (256,),
'1.weight': (10, -1),
'1.bias': (10,)}
Passing the first minibatch X through the network cascades shapes from layer to layer and materializes every weight tensor:
Passing the first minibatch X through the network cascades shapes from layer to layer and materializes every weight tensor:
Passing the first minibatch X through the network cascades shapes from layer to layer and materializes every weight tensor:
net(X)
net[0].weight.shapetorch.Size([256, 20])
net(X)
[w.shape for w in net.weights][TensorShape([20, 256]),
TensorShape([256]),
TensorShape([256, 10]),
TensorShape([10])]
rngs = nnx.Rngs(d2l.get_key())
net = nnx.Sequential(nnx.Linear(20, 256, rngs=rngs), nnx.relu,
nnx.Linear(256, 10, rngs=rngs))
[(path, value.shape)
for path, value in nnx.state(net, nnx.Param).flat_state()][(('layers', 0, 'bias'), (256,)),
(('layers', 0, 'kernel'), (20, 256)),
(('layers', 2, 'bias'), (10,)),
(('layers', 2, 'kernel'), (256, 10))]
net.initialize()
net(X)
{name: p.shape for name, p in net.collect_params().items()}{'0.weight': (256, 20),
'0.bias': (256,),
'1.weight': (10, 256),
'1.bias': (10,)}
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:
Keras layers take kernel_initializer at construction and apply it when build runs (either on the first data call or via net.build((None, 20))).
nnx.Linear takes kernel_init and draws weights immediately in the constructor.
net.initialize(init.Xavier()) records the initializer upfront and applies it automatically on the first forward pass.
@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.shapetorch.Size([256, 20])
net = tf.keras.Sequential([
tf.keras.layers.Dense(
256, activation='relu',
kernel_initializer=tf.keras.initializers.GlorotUniform()),
tf.keras.layers.Dense(10)])
net.build((None, 20))
net.layers[0].kernel.shapeTensorShape([20, 256])
class TinyMLP(d2l.Module):
def __init__(self, rngs):
super().__init__()
self.net = nnx.Sequential(
nnx.Linear(20, 256,
kernel_init=nnx.initializers.xavier_uniform(),
rngs=rngs), nnx.relu,
nnx.Linear(256, 10, rngs=rngs))
model = TinyMLP(nnx.Rngs(d2l.get_key()))
[(path, value.shape)
for path, value in nnx.state(model, nnx.Param).flat_state()][(('net', 'layers', 0, 'bias'), (256,)),
(('net', 'layers', 0, 'kernel'), (20, 256)),
(('net', 'layers', 2, 'bias'), (10,)),
(('net', 'layers', 2, 'kernel'), (256, 10))]
net = nn.Sequential()
net.add(nn.Dense(256, activation='relu'))
net.add(nn.Dense(10))
net.initialize(init.Xavier())
net(X)
net[0].weight.data().shape(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))@dataclass
class MLPConfig:
num_inputs: int = 784
num_hiddens: int = 256
num_blocks: int = 4
num_outputs: int = 10
def build(cfg: MLPConfig) -> tf.keras.Model:
blocks = [ResidualBlock(cfg.num_hiddens) for _ in range(cfg.num_blocks)]
return tf.keras.Sequential([tf.keras.Input((cfg.num_inputs,)),
tf.keras.layers.Dense(cfg.num_hiddens),
*blocks,
tf.keras.layers.Dense(cfg.num_outputs)])@dataclass
class MLPConfig:
num_inputs: int = 784
num_hiddens: int = 256
num_blocks: int = 4
num_outputs: int = 10
def build(cfg: MLPConfig, rngs=None) -> nnx.Module:
rngs = nnx.Rngs(d2l.get_key()) if rngs is None else rngs
blocks = [ResidualBlock(cfg.num_hiddens, rngs=rngs)
for _ in range(cfg.num_blocks)]
return nnx.Sequential(
nnx.Linear(cfg.num_inputs, cfg.num_hiddens, rngs=rngs), *blocks,
nnx.Linear(cfg.num_hiddens, cfg.num_outputs, rngs=rngs))@dataclass
class MLPConfig:
num_inputs: int = 784
num_hiddens: int = 256
num_blocks: int = 4
num_outputs: int = 10
def build(cfg: MLPConfig) -> nn.Block:
net = nn.Sequential()
net.add(nn.Dense(cfg.num_hiddens, in_units=cfg.num_inputs))
for _ in range(cfg.num_blocks):
net.add(ResidualBlock(cfg.num_hiddens))
net.add(nn.Dense(cfg.num_outputs, in_units=cfg.num_hiddens))
return netA 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,))]
net = build(MLPConfig())
[(w.path, tuple(w.shape)) for w in net.weights][:4][('sequential_8/dense_24/kernel', (784, 256)),
('sequential_8/dense_24/bias', (256,)),
('sequential_8/residual_block_1/sequential_4/dense_16/kernel', (256, 256)),
('sequential_8/residual_block_1/sequential_4/dense_16/bias', (256,))]
net = build(MLPConfig())
[(path, value.shape)
for path, value in nnx.state(net, nnx.Param).flat_state()][:4][(('layers', 0, 'bias'), (256,)),
(('layers', 0, 'kernel'), (784, 256)),
(('layers', 1, 'body', 'layers', 0, 'bias'), (256,)),
(('layers', 1, 'body', 'layers', 0, 'kernel'), (256, 256))]
net = build(MLPConfig())
net.initialize()
[(name, p.shape) for name, p in net.collect_params().items()][: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)).shapetorch.Size([2, 10])
net(tf.random.uniform((2, 784))).shapeTensorShape([2, 10])
net(jax.random.uniform(d2l.get_key(), (2, 784))).shape(2, 10)
net(mnp.random.uniform(size=(2, 784))).shape(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 \cdot 256 + 256 = 200{,}960\) parameters, each residual block contains two dense layers totaling \(2 \cdot (256 \cdot 256 + 256) = 131{,}584\) parameters, and the output layer adds \(256 \cdot 10 + 10 = 2{,}570\), giving
\[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
for cfg in (MLPConfig(), MLPConfig(num_hiddens=512, num_blocks=8)):
print(f'num_hiddens={cfg.num_hiddens}, num_blocks={cfg.num_blocks}: '
f'{build(cfg).count_params():,} parameters')num_hiddens=256, num_blocks=4: 729,866 parameters
num_hiddens=512, num_blocks=8: 4,609,546 parameters
for cfg in (MLPConfig(), MLPConfig(num_hiddens=512, num_blocks=8)):
n = sum(x.size for _, x in nnx.state(build(cfg), nnx.Param).flat_state())
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
for cfg in (MLPConfig(), MLPConfig(num_hiddens=512, num_blocks=8)):
net = build(cfg)
net.initialize()
n = sum(p.data().size for p in net.collect_params().values())
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
[code] Unregistered modules. The plain list in
PlainListMLPkeeps its layers out ofnet.parameters(),net.to(device), andnet.state_dict(). Predict, then verify, what three further operations do to the model.- Call
net.apply(init_xavier)and check whether the weight ofnet.layers[0]changes. - Add
nn.Dropout(0.5)after thenn.ReLU()in the list, callnet.eval(), and pass the same input through the model twice. - The method
load_state_dictis the inverse ofstate_dict: it copies a dictionary of saved tensors into a model. Callnet.load_state_dict(ModuleListMLP().state_dict()). - Which of these failures are silent and which raise an error? Explain all three from the same missing registration.
- Call
Widening a residual block.
ResidualBlockrequires its input and output widths to agree. Suppose a block maps width \(d\) to a larger width \(d'\), so its body ends in a \(d'\)-wide layer and the skip path must also produce width \(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.[code] A module from scratch. ● In plain Python and NumPy, without any framework base class, write a
Parameterclass that wraps an array and a minimalModuleclass whose__setattr__registers every assignedParameterorModule. GiveModuleaparameters()method that recurses into the registered children. Write aLinearsubclass ofModulethat holds a weight and a bias, build a two-layer MLP from two instances of it, and verify thatparameters()returns all four arrays. Then store the two layers in a plain list, check whatparameters()returns, and extendModuleso that the list version finds all four arrays as well.Adapted from CMU 10-714, Homework 2, Question 2.
[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.
[code] Unregistered modules. Keras tracks a layer that the constructor assigns to an attribute, but not a
Denselayer created insidecall. Such a model runs without complaint. Write one, checklen(net.trainable_variables)after calling it, explain what an optimizer would train, and explain what happens to the layer’s weights between two calls.Widening a residual block.
ResidualBlockrequires its input and output widths to agree. Suppose a block maps width \(d\) to a larger width \(d'\), so its body ends in a \(d'\)-wide layer and the skip path must also produce width \(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.[code] A module from scratch. ● In plain Python and NumPy, without any framework base class, write a
Parameterclass that wraps an array and a minimalModuleclass whose__setattr__registers every assignedParameterorModule. GiveModuleaparameters()method that recurses into the registered children. Write aLinearsubclass ofModulethat holds a weight and a bias, build a two-layer MLP from two instances of it, and verify thatparameters()returns all four arrays. Then store the two layers in a plain list, check whatparameters()returns, and extendModuleso that the list version finds all four arrays as well.Adapted from CMU 10-714, Homework 2, Question 2.
[code] Lazy input width. Build a
tf.keras.Sequentialholdingtf.keras.layers.Dense(256, activation='relu')andtf.keras.layers.Dense(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.
[code] Unregistered containers. NNX rejects a plain Python list that holds modules and names
nnx.Listandnnx.dataas repairs.- Rewrite
ListMLPtwice: once with its two layers in annnx.Dictkeyed'hidden'and'out', and once with the plain list wrapped innnx.data. Verify that all 7,946 parameters appear innnx.state(net, nnx.Param)in both versions. - Compare the parameter paths of the two versions with those of
ListMLP. A checkpoint stores the state as a mapping from paths to arrays. Which of the two rewrites could restore a checkpoint saved fromListMLP, and why?
- Rewrite
Widening a residual block.
ResidualBlockrequires its input and output widths to agree. Suppose a block maps width \(d\) to a larger width \(d'\), so its body ends in a \(d'\)-wide layer and the skip path must also produce width \(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.[code] A module from scratch. ● In plain Python and NumPy, without any framework base class, write a
Parameterclass that wraps an array and a minimalModuleclass whose__setattr__registers every assignedParameterorModule. GiveModuleaparameters()method that recurses into the registered children. Write aLinearsubclass ofModulethat holds a weight and a bias, build a two-layer MLP from two instances of it, and verify thatparameters()returns all four arrays. Then store the two layers in a plain list, check whatparameters()returns, and extendModuleso that the list version finds all four arrays as well.Adapted from CMU 10-714, Homework 2, Question 2.
[code] Shared children. Reusing one child module at several sites turns the module tree of Figure 5.1.1 into a graph. Build a small network that uses the same child at two sites. Predict, then verify: does the shared child’s parameter set appear once or twice in
nnx.state(net, nnx.Param)? The functionnnx.split(net)separates a module into a static graph definition and its state, andnnx.mergerebuilds a module from the two. After such a round trip, are the two sites still one object, checked withis?
[code] Unregistered modules. The plain list in
PlainListMLPkeeps its layers out ofcollect_params(),initialize(), andsave_parameters, andcollect_params()warns about it. Predict, then verify, what two further operations do to the model.- Pass a batch through a fresh
PlainListMLP, callnet.cast('float64'), check the dtype ofnet.layers[0].weight.data(), and pass afloat64batch through the model. - The method
load_parametersis the inverse ofsave_parameters: it reads a saved parameter file into a model. Run one forward pass through aRegisteredListMLP, save it withsave_parameters, and load the file into a freshPlainListMLPwithload_parameters. - Which of these failures are silent and which raise an error? Explain both from the same missing registration.
- Pass a batch through a fresh
Widening a residual block.
ResidualBlockrequires its input and output widths to agree. Suppose a block maps width \(d\) to a larger width \(d'\), so its body ends in a \(d'\)-wide layer and the skip path must also produce width \(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.[code] A module from scratch. ● In plain Python and NumPy, without any framework base class, write a
Parameterclass that wraps an array and a minimalModuleclass whose__setattr__registers every assignedParameterorModule. GiveModuleaparameters()method that recurses into the registered children. Write aLinearsubclass ofModulethat holds a weight and a bias, build a two-layer MLP from two instances of it, and verify thatparameters()returns all four arrays. Then store the two layers in a plain list, check whatparameters()returns, and extendModuleso that the list version finds all four arrays as well.Adapted from CMU 10-714, Homework 2, Question 2.
[code] Lazy input width. Build an
nn.Sequentialholdingnn.Dense(256, activation='relu')andnn.Dense(10), callinitialize(), 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.