30 Mins

3. Neural Network Modules (nn.Module)

The Architecture of nn.Module

At the core of PyTorch's flexibility is the nn.Module class. Every neural network architecture must inherit from this base class. By doing so, your custom model gains access to automatic tracking of trainable parameters, the ability to transition between devices (CPU/GPU), and seamless integration with optimization algorithms.

When you subclass nn.Module, the convention is to define your layers in the __init__ constructor and define the flow of data through those layers in the forward method. The forward method is automatically called when you invoke the model instance as a function, which is critical for PyTorch's dynamic computation graph creation.

Initialization in __init__ involves defining layers as class members. You register them by assigning them to self. By using built-in modules like nn.Linear, PyTorch automatically manages the weight and bias matrices for you. Note that you should always call super().__init__() first to ensure the base class is properly set up.

The forward method is where the 'functional' logic resides. You apply the layers defined in the constructor sequentially or in complex branching patterns. PyTorch keeps track of these operations internally to compute gradients via backpropagation during training.

Operator Note: Always use torch.nn.Module rather than nn.Sequential if you require custom logic like residual connections or conditional branching in your forward pass.
Python 3
import torch
import torch.nn as nn

class SimpleNet(nn.Module):
    def __init__(self, input_dim, hidden_dim, output_dim):
        super(SimpleNet, self).__init__()
        # Initializing layers
        self.fc1 = nn.Linear(input_dim, hidden_dim)
        self.relu = nn.ReLU()
        self.fc2 = nn.Linear(hidden_dim, output_dim)
        self.sigmoid = nn.Sigmoid()

    def forward(self, x):
        # Defining the forward pass flow
        x = self.fc1(x)
        x = self.relu(x)
        x = self.fc2(x)
        return self.sigmoid(x)

# Instantiate and run dummy data
model = SimpleNet(10, 5, 1)
dummy_input = torch.randn(1, 10)
output = model(dummy_input)
print(f'Output tensor shape: {output.shape}')

Parameter Management and Serialization

After defining a model, you often need to inspect or modify its parameters directly. The .parameters() generator yields all weight and bias tensors registered within the module. This is the primary method optimizers use to update weights during gradient descent.

Beyond live parameters, PyTorch provides state_dict() and load_state_dict(). A state_dict is a Python dictionary object that maps each layer to its parameter tensor. This is the standard way to save and load model weights to disk, ensuring that your model's configuration is persistent across different sessions.

Operator Note: Never manually modify parameters in place unless you are performing gradient-free inference or specific initialization tweaks; it may interfere with the autograd graph if not handled via torch.no_grad().
Python 3
model = SimpleNet(10, 5, 1)

# Accessing parameters
for name, param in model.named_parameters():
    print(f'Layer: {name} | Size: {param.size()}')

# Exporting the state dictionary
sd = model.state_dict()
print(f'Keys in state_dict: {list(sd.keys())}')

# Manually saving weights is common for checkpoints
torch.save(model.state_dict(), 'checkpoint.pth')

Knowledge Check

Ready to test your understanding of 3. Neural Network Modules (nn.Module)?

Back