Module and parameter registration
Quick answer
An nn.Module organizes operations, submodules, learned parameters and non-learned persistent state. Assign nn.Parameter or a child module to an attribute after super().init() so PyTorch can discover and manage that state. Static examples tested locally with PyTorch 2.10.0+cpu; ByteMind execution is unverified.
Discover registered state
import torchfrom torch import nnclass Scale(nn.Module): def __init__(self): super().__init__() self.weight=nn.Parameter(torch.tensor(2.)) self.register_buffer("offset",torch.tensor(1.)) self.cache=torch.tensor(0.) def forward(self,x): return x*self.weight+self.offsetm=Scale()print(list(dict(m.named_parameters())),list(m.state_dict()),m(torch.tensor(3.)).item())Expected output: ['weight'] ['weight', 'offset'] 7.0. The buffer is serialized but is not a learned parameter; the plain tensor is neither.
How it works
Implement forward(self,x) and call model(x), which also allows module hooks to run. Parameters appear in named_parameters and are offered to optimizers. Ordinary tensors assigned to attributes are not automatically registered as parameters or buffers. register_buffer stores non-parameter tensors that follow device moves and, by default, are included in state_dict. Use ModuleList or ModuleDict for dynamically assembled child modules, and ParameterList for parameter collections. A plain list does not register its contained modules. A state_dict holds parameters and persistent buffers, not an executable architecture; reconstruct the matching model before loading. Frozen parameters may still be registered, but requires_grad=False prevents ordinary gradient accumulation.
Registered containers
from torch import nnclass Model(nn.Module): def __init__(self): super().__init__() self.loose=[nn.Linear(2,3)] self.layers=nn.ModuleList([nn.Linear(2,3)])print(sum(p.numel() for p in Model().parameters()))Expected output: 9. Only the ModuleList child contributes registered weights and biases.
Common mistakes
Create submodules in init, not repeatedly in forward, otherwise an optimizer may never see stable parameters. A persistent buffer is not an optimizer parameter. Use model(x) instead of bypassing the module call with forward directly.
Practice and next steps
Count weights and biases of a two-layer model by hand, then compare with sum(p.numel() for p in model.parameters()).
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Module and parameter registration — knowledge check
Apply module and parameter registration to small examples and debugging scenarios.
What registers a learnable scalar?
Which container registers child modules?
What is included in state_dict by default?
How many parameters in Linear(2,3) with bias?
Where should persistent child layers be created?