TExcelTAD
Home › Deep Learning: Neural Networks, Architectures & PyTorch › Building Models with nn.Module

Building Models with nn.Module

In layer-by-layer backpropagation you wrote layers as classes with forward and backward, and kept a list of their weights by hand so the optimizer could find them. torch.nn.Module is that idea grown up. You still write forward; autograd writes the backward pass; and the module registers every parameter and every sub-module you assign to it, so one call finds all the weights (model.parameters()), moves them (model.to(device)), saves them (model.state_dict()) or switches the whole tree between training and evaluation (model.train(), model.eval()).

The registration is the part that needs understanding, because when it fails, nothing raises an error: a layer simply is not trained.

How a module finds its parameters

nn.Module overrides __setattr__. When you write self.fc = nn.Linear(4, 3) inside __init__, the assignment is intercepted: a Parameter goes into the module's parameter dictionary, a Module into its child dictionary, and everything else is stored as a normal attribute. named_parameters() then walks the tree of children and yields each parameter with a dotted path (fc.weight). The mechanism fits in forty lines of NumPy, and running it shows the pitfall at the end of this lesson too:

python · try it yourself
import numpy as np

class Param:
    def __init__(self, value):
        self.value = value

class Module:
    def __init__(self):
        object.__setattr__(self, "_params", {})
        object.__setattr__(self, "_children", {})

    def __setattr__(self, name, value):          # the registration trick of nn.Module
        if isinstance(value, Param):
            self._params[name] = value
        elif isinstance(value, Module):
            self._children[name] = value
        object.__setattr__(self, name, value)

    def named_parameters(self, prefix=""):
        for name, p in self._params.items():
            yield prefix + name, p
        for name, child in self._children.items():
            yield from child.named_parameters(prefix + name + ".")

    def __call__(self, x):
        return self.forward(x)

class Linear(Module):
    def __init__(self, n_in, n_out, rng):
        super().__init__()
        bound = 1 / np.sqrt(n_in)
        self.weight = Param(rng.uniform(-bound, bound, (n_out, n_in)))
        self.bias = Param(np.zeros(n_out))
    def forward(self, x):
        return x @ self.weight.value.T + self.bias.value

class MLP(Module):
    def __init__(self, rng):
        super().__init__()
        self.hidden = Linear(64, 32, rng)
        self.out = Linear(32, 10, rng)
        self.extra = [Linear(10, 10, rng)]        # a plain list: invisible to __setattr__
    def forward(self, x):
        return self.out(np.maximum(0, self.hidden(x)))

rng = np.random.default_rng(0)
model = MLP(rng)
for name, p in model.named_parameters():
    print(f"{name:14s} {p.value.shape}")
print("registered parameters:", sum(p.value.size for _, p in model.named_parameters()))
print("hidden in the list:", model.extra[0].weight.value.size + model.extra[0].bias.value.size)
print("output shape:", model(rng.normal(size=(4, 64))).shape)
hidden.weight  (32, 64)
hidden.bias    (32,)
out.weight     (10, 32)
out.bias       (10,)
registered parameters: 2410
hidden in the list: 110
output shape: (4, 10)

The two Linear children were found, with the names hidden.weight … out.bias and 2410 numbers in total. The layer inside a plain Python list was not: its 110 numbers would never be updated, saved or moved. PyTorch behaves exactly the same way, for the same reason.

Two more details of the real class are visible here. __call__ runs forward, and in PyTorch it also runs any hooks (next lesson), so always call model(x), never model.forward(x). And super().__init__() must run before the first assignment, because it creates the dictionaries; forgetting it gives "cannot assign module before Module.init() call".

A model as a subclass

The usual pattern: create the layers in __init__, connect them in forward. print(model) shows the registered children in order, named_parameters() the weights.

python · try it yourself
import torch
from torch import nn

class MLP(nn.Module):
    def __init__(self, n_in, n_hidden, n_out, p_drop=0.1):
        super().__init__()                       # must come first: sets up the registries
        self.hidden = nn.Linear(n_in, n_hidden)
        self.act = nn.ReLU()
        self.drop = nn.Dropout(p_drop)
        self.out = nn.Linear(n_hidden, n_out)

    def forward(self, x):
        return self.out(self.drop(self.act(self.hidden(x))))

torch.manual_seed(0)
model = MLP(64, 32, 10)
print(model)
for name, p in model.named_parameters():
    print(f"{name:14s} {str(tuple(p.shape)):9s} {p.numel():5d}")
total = sum(p.numel() for p in model.parameters())
trainable = sum(p.numel() for p in model.parameters() if p.requires_grad)
print("total", total, "trainable", trainable, "| by hand:", 64 * 32 + 32 + 32 * 10 + 10)
x = torch.randn(4, 64)
print("output", tuple(model(x).shape), "| model(x) calls forward through __call__")
print("state_dict keys:", list(model.state_dict().keys()))
MLP(
  (hidden): Linear(in_features=64, out_features=32, bias=True)
  (act): ReLU()
  (drop): Dropout(p=0.1, inplace=False)
  (out): Linear(in_features=32, out_features=10, bias=True)
)
hidden.weight  (32, 64)   2048
hidden.bias    (32,)        32
out.weight     (10, 32)    320
out.bias       (10,)        10
total 2410 trainable 2410 | by hand: 2410
output (4, 10) | model(x) calls forward through __call__
state_dict keys: ['hidden.weight', 'hidden.bias', 'out.weight', 'out.bias']

The same 2410 parameters as the NumPy version: a Linear(n_in, n_out) holds an n_out by n_in weight (output first, which is why its forward computes x @ W.T + b) and n_out biases. Counting p.numel() over parameters() is the standard parameter count; restricting it to p.requires_grad counts what is actually trained, which differs once layers are frozen. The state_dict is an ordered dictionary from those dotted names to tensors; it is what you save and load. ReLU and Dropout have no parameters, so they add no keys, but they are still children: they show up in print(model) and they receive the train()/eval() switch.

Containers: Sequential, ModuleList, ModuleDict

Container Use it for forward
nn.Sequential(a, b, c) a straight pipeline, each output feeds the next built in: c(b(a(x)))
nn.ModuleList([...]) a list of layers you loop over yourself (variable depth, skip connections) you write it
nn.ModuleDict({...}) layers chosen by name (one head per task, per language) you write it

All three register their contents, so their parameters are found with names such as blocks.0.weight or heads.digit.bias. The next example builds each one, then the broken version with a plain list.

python · try it yourself
import torch
from torch import nn

torch.manual_seed(0)
seq = nn.Sequential(nn.Linear(64, 32), nn.ReLU(), nn.Dropout(0.5), nn.Linear(32, 10))
print("Sequential keys:", list(seq.state_dict().keys()))
print("seq[0] is", seq[0])

class Deep(nn.Module):
    def __init__(self, sizes, heads):
        super().__init__()
        self.blocks = nn.ModuleList(nn.Linear(a, b) for a, b in zip(sizes[:-1], sizes[1:]))
        self.heads = nn.ModuleDict({name: nn.Linear(sizes[-1], k) for name, k in heads.items()})
    def forward(self, x, task):
        for block in self.blocks:
            x = torch.relu(block(x))
        return self.heads[task](x)

deep = Deep([64, 48, 32, 16], {"digit": 10, "parity": 2})
x = torch.randn(4, 64)
print("digit head", tuple(deep(x, "digit").shape), "parity head", tuple(deep(x, "parity").shape))
print("Deep parameters:", sum(p.numel() for p in deep.parameters()))
print("names:", [n for n, _ in deep.named_parameters()][:4], "...")

class Broken(nn.Module):
    def __init__(self, sizes):
        super().__init__()
        self.blocks = [nn.Linear(a, b) for a, b in zip(sizes[:-1], sizes[1:])]   # plain list!
    def forward(self, x):
        for block in self.blocks:
            x = torch.relu(block(x))
        return x

broken = Broken([64, 48, 32, 16])
print("Broken parameters:", sum(p.numel() for p in broken.parameters()), "| state_dict:", list(broken.state_dict().keys()))
try:
    torch.optim.SGD(broken.parameters(), lr=0.1)
except ValueError as e:
    print("ValueError:", e)
broken.double()
print("after .double(): first layer dtype", broken.blocks[0].weight.dtype)
Sequential keys: ['0.weight', '0.bias', '3.weight', '3.bias']
seq[0] is Linear(in_features=64, out_features=32, bias=True)
digit head (4, 10) parity head (4, 2)
Deep parameters: 5420
names: ['blocks.0.weight', 'blocks.0.bias', 'blocks.1.weight', 'blocks.1.bias'] ...
Broken parameters: 0 | state_dict: []
ValueError: optimizer got an empty parameter list
after .double(): first layer dtype torch.float32

What the output shows, line by line:

  • Sequential names its children by position, so the keys are 0.weight and 3.weight (positions 1 and 2 are the parameter-free ReLU and Dropout). Inserting a layer later shifts the numbers and old checkpoints no longer load by name. Pass an OrderedDict of names to Sequential if checkpoints must survive edits.
  • ModuleList and ModuleDict register their contents: 5420 parameters, that is 64*48 + 48, 48*32 + 32 and 32*16 + 16 for the three blocks plus both heads (170 and 34). The forward pass picks a head by name; the other head's parameters receive no gradient in that step.
  • The plain list registers nothing. Broken reports 0 parameters and an empty state_dict. Here the optimizer at least refuses an empty list; in a model that also has some registered layers, the listed layers are silently left out of training, saving and .to(): after broken.double() the hidden layer is still float32, and after .to("cuda") it would still be on the CPU.

The training flag and apply

python · try it yourself
import torch
from torch import nn

torch.manual_seed(0)
seq = nn.Sequential(nn.Linear(64, 32), nn.ReLU(), nn.Dropout(0.5), nn.Linear(32, 10))
x = torch.randn(4, 64)
seq.eval()
print("eval flags:", seq.training, [m.training for m in seq])
with torch.no_grad():
    a, b = seq(x), seq(x)
print("eval: two calls equal", torch.equal(a, b))
seq.train()
with torch.no_grad():
    a, b = seq(x), seq(x)
print("train: two calls equal", torch.equal(a, b))

def init(m):
    if isinstance(m, nn.Linear):
        nn.init.zeros_(m.bias)
seq.apply(init)
print("biases zero:", all(seq[i].bias.abs().sum().item() == 0 for i in (0, 3)))
print("children:", [type(m).__name__ for m in seq.children()])
eval flags: False [False, False, False, False]
eval: two calls equal True
train: two calls equal False
biases zero: True
children: ['Linear', 'ReLU', 'Dropout', 'Linear']

model.eval() sets training = False on the module and, recursively, on every child; model.train() sets it back. Layers read the flag: dropout is active only in training mode, so two calls in eval mode agree and two calls in train mode do not. Batch normalisation switches between batch statistics and running averages the same way. The flag has nothing to do with gradients: eval() does not stop autograd (that is torch.no_grad()), and no_grad() does not turn dropout off. Validation needs both.

model.apply(fn) calls fn on every module in the tree, the usual way to apply a custom initialisation; children() yields the direct children, modules() the whole tree including the module itself.

Composing modules

Modules nest: a block is a module, a model is a module made of blocks, and a bigger model can hold that model as a child. Each level only knows its direct children, and the dotted names follow the nesting (encoder.blocks.2.attn.weight). A typical structure:

python
class Block(nn.Module):
    def __init__(self, d, p_drop):
        super().__init__()
        self.fc = nn.Linear(d, d)
        self.drop = nn.Dropout(p_drop)
    def forward(self, x):
        return x + self.drop(torch.relu(self.fc(x)))      # residual: x plus a correction

class Net(nn.Module):
    def __init__(self, n_in, d, depth, n_out, p_drop=0.1):
        super().__init__()
        self.inp = nn.Linear(n_in, d)
        self.blocks = nn.Sequential(*[Block(d, p_drop) for _ in range(depth)])
        self.head = nn.Linear(d, n_out)
    def forward(self, x):
        return self.head(self.blocks(torch.relu(self.inp(x))))

Keep configuration (sizes, depth, dropout rate) as constructor arguments and save them next to the state_dict: a state dict holds tensors, not the architecture, and loading needs a model built with the same shapes. load_state_dict(sd) is strict by default and reports missing and unexpected keys, which catches renamed layers immediately; strict=False is for deliberate partial loading, such as a new classification head on a pretrained body.

Pitfalls

  • Layers in a plain list or dict. Use nn.ModuleList / nn.ModuleDict. A quick check after building any model: compare sum(p.numel() for p in model.parameters()) with what you expect.
  • A tensor that should be trained, stored as a plain attribute. self.scale = torch.ones(3) is not a parameter; wrap it in nn.Parameter (next lesson).
  • Calling model.forward(x). It skips hooks; call model(x).
  • Reusing one layer object twice (nn.Sequential(layer, nn.ReLU(), layer)) shares its weights. Sometimes intended (weight tying), usually a bug.
  • Forgetting model.train() after validation. Dropout stays off for the rest of training. Put model.train() at the start of every epoch.
  • Changing a Sequential and loading an old checkpoint. Position-based names shift; name the children.

Practice

  1. How many parameters does nn.Sequential(nn.Linear(10, 20), nn.ReLU(), nn.Linear(20, 20), nn.ReLU(), nn.Linear(20, 3)) have, and what are its state_dict keys?
Answer

10*20 + 20 = 220, 20*20 + 20 = 420, 20*3 + 3 = 63: 703 in total. Keys 0.weight, 0.bias, 2.weight, 2.bias, 4.weight, 4.bias (the ReLUs at positions 1 and 3 have none).

  1. A model has self.layers = [nn.Linear(8, 8) for _ in range(4)] and self.head = nn.Linear(8, 2). Training runs without errors and the loss goes down a little. What is wrong, and what does len(model.state_dict()) return?
Answer

Only the head is registered, so only its 18 parameters are trained; the four hidden layers keep their random weights and act as a fixed random feature map, which is why the loss still decreases a little. state_dict has 2 entries (head.weight, head.bias). Use nn.ModuleList.

  1. Write a forward for a ModuleDict of three heads that returns all three outputs at once as a dictionary.
Answer
python
def forward(self, x):
    h = self.body(x)
    return {name: head(h) for name, head in self.heads.items()}

The body runs once and every head reads its output; the loss is usually a weighted sum of the per-head losses.

Test yourself

How does nn.Module find the parameters of the layers you create in __init__?

  1. It inspects the source code of forward
  2. Its __setattr__ registers every assigned Parameter and Module
  3. You must call register_parameter for each layer
  4. The optimizer searches the object's attributes

What happens to layers stored in a plain Python list attribute?

  1. They are trained normally
  2. They are not registered: no training, no saving in state_dict, not moved by .to()
  3. PyTorch raises an error at construction
  4. They are converted to a ModuleList automatically

What does model.eval() change?

  1. It disables gradient computation
  2. It sets training = False on every submodule, so dropout and batch norm switch to inference behaviour
  3. It freezes all parameters
  4. It moves the model to the CPU

Why are the state_dict keys of nn.Sequential(nn.Linear(4, 8), nn.ReLU(), nn.Linear(8, 2)) called 0.weight and 2.weight?

  1. Sequential names children by position, and the ReLU at position 1 has no parameters
  2. Index 1 is reserved
  3. Biases take position 1
  4. Keys are sorted alphabetically