Custom models
Define a trainable neural network with layers and custom computation.
PyTorch · Class
torch.nn.Module is the base class for PyTorch neural-network modules. Subclass it to define models or reusable components, compose child modules, and manage registered parameters and module-wide conversions.
Subclass nn.Module to define a callable neural-network component. Initialize child modules and state in __init__, implement forward for the computation, and assign child modules as attributes so PyTorch registers them for parameter discovery and operations such as device or dtype conversion.
class torch.nn.Module(*args, **kwargs)| Name | Type | Description |
|---|---|---|
*args | object | Positional arguments accepted by the base constructor. |
**kwargs | object | Keyword arguments accepted by the base constructor. |
A Module instance; subclasses provide the model behavior through forward.
import torch
from torch import nn
class MLP(nn.Module):
def __init__(self, width=8):
super().__init__()
self.layers = nn.Sequential(
nn.Linear(4, width),
nn.ReLU(),
nn.Linear(width, 2),
)
def forward(self, x):
return self.layers(x)
model = MLP()
print(model(torch.randn(3, 4)).shape)Subclass nn.Module, register layers as attributes, and implement forward so the instance can be called with input tensors.
Define a trainable neural network with layers and custom computation.
Package a reusable operation together with its parameters and submodules.
Build hierarchical architectures from smaller neural-network modules.
nn.Module is PyTorch’s base class for neural-network modules. A custom model subclasses it, initializes child modules, and defines forward for the computation.
Follow-up: How does composition work? A Module can contain other Modules, producing a nested module tree.
Assigning child modules as attributes registers them with the parent. This lets PyTorch discover the submodules and apply operations such as to() to their parameters.
Follow-up: Why prefer nn.Sequential or ModuleList over a plain Python list? Registered containers ensure contained modules participate in the module hierarchy.
The documented class declaration is torch.nn.Module(*args, **kwargs). In practice, subclasses call super().__init__() before assigning their child modules.
Follow-up: What belongs in forward? The input-to-output computation; initialization and layer construction belong in __init__.
torch.nn.Parametertorch.nn.Sequentialtorch.nn.ModuleListtorch.nn.ModuleDict