nn.Module helps keep your model code neat and easy to manage. It groups all parts of your model together so you can build, train, and save it smoothly.
Why nn.Module organizes model code in PyTorch
Introduction
Syntax
PyTorch
import torch.nn as nn class MyModel(nn.Module): def __init__(self): super(MyModel, self).__init__() # define layers here def forward(self, x): # define forward pass here return x
Always call super().__init__() to initialize the base class.
Define your layers in __init__ and the data flow in forward.
Examples
PyTorch
class SimpleNN(nn.Module): def __init__(self): super(SimpleNN, self).__init__() self.linear = nn.Linear(10, 5) def forward(self, x): return self.linear(x)
PyTorch
class TwoLayerNN(nn.Module): def __init__(self): super(TwoLayerNN, self).__init__() self.layer1 = nn.Linear(10, 20) self.layer2 = nn.Linear(20, 5) def forward(self, x): x = self.layer1(x) x = nn.functional.relu(x) x = self.layer2(x) return x
Sample Model
This code defines a simple model using nn.Module, then runs a sample input through it to get the output.
PyTorch
import torch import torch.nn as nn class SimpleModel(nn.Module): def __init__(self): super(SimpleModel, self).__init__() self.linear = nn.Linear(3, 1) def forward(self, x): return self.linear(x) model = SimpleModel() # Create a sample input tensor input_tensor = torch.tensor([[1.0, 2.0, 3.0]]) # Get model output output = model(input_tensor) print(f"Input: {input_tensor}") print(f"Output: {output}")
Important Notes
nn.Module tracks all layers automatically, so you don't have to manage them yourself.
It also helps with moving your model to GPU or CPU easily.
Using nn.Module makes saving and loading models straightforward.
Summary
nn.Module organizes your model code by grouping layers and logic.
It makes training, saving, and reusing models easier.
Always define layers in __init__ and data flow in forward.
Practice
1. Why do we use
nn.Module to organize model code in PyTorch?easy
Solution
Step 1: Understand the role of nn.Module
nn.Module helps organize layers and the forward pass logic in one place.Step 2: Recognize benefits for training and reuse
This organization makes training, saving, and reusing models easier and cleaner.Final Answer:
It groups layers and logic to simplify training and reuse. -> Option DQuick Check:
nn.Module groups layers and logic = C [OK]
Hint: Remember: nn.Module bundles layers and logic together [OK]
Common Mistakes:
- Thinking nn.Module writes training loops automatically
- Believing nn.Module replaces all Python functions
- Assuming nn.Module only helps with saving models
2. Which part of a PyTorch
nn.Module subclass should you use to define layers?easy
Solution
Step 1: Identify where layers are defined
Layers must be created once when the model is built, so they go in__init__.Step 2: Understand the role of
forwardforwarddefines how data moves through layers, not layer creation.Final Answer:
Inside the __init__ method -> Option CQuick Check:
Define layers in __init__ = A [OK]
Hint: Layers go in __init__, data flow in forward [OK]
Common Mistakes:
- Defining layers inside forward method
- Placing layers outside the class
- Using a non-existent train method for layers
3. Given this PyTorch model code, what will
print(model(torch.ones(1, 3))) output?
import torch
import torch.nn as nn
class SimpleModel(nn.Module):
def __init__(self):
super().__init__()
self.linear = nn.Linear(3, 2)
def forward(self, x):
return self.linear(x) + 1
model = SimpleModel()medium
Solution
Step 1: Analyze the model structure
The model has a linear layer from 3 inputs to 2 outputs, then adds 1 to output.Step 2: Understand the input and output shapes
Input shape is (1,3), so output shape is (1,2). The output is linear(x) + 1.Final Answer:
A tensor of shape (1, 2) with values equal to linear output plus 1 -> Option BQuick Check:
Output shape (1,2) and adds 1 = B [OK]
Hint: Check layer shapes and operations in forward [OK]
Common Mistakes:
- Confusing input and output shapes
- Expecting an error due to missing forward
- Assuming output is zeros without computation
4. What is wrong with this PyTorch model code?
import torch.nn as nn
class BadModel(nn.Module):
def __init__(self):
self.linear = nn.Linear(4, 2)
def forward(self, x):
return self.linear(x)medium
Solution
Step 1: Check __init__ method correctness
In nn.Module subclasses, you must call super().__init__() to initialize the base class.Step 2: Verify other parts
forward returns output correctly; layers are defined in __init__; input size 4 is valid.Final Answer:
Missing call to super().__init__() in __init__ -> Option AQuick Check:
Always call super().__init__() in __init__ = D [OK]
Hint: Always call super().__init__() in your model's __init__ [OK]
Common Mistakes:
- Forgetting super().__init__() call
- Defining layers inside forward method
- Misunderstanding nn.Linear input size
5. You want to create a PyTorch model that has two linear layers and applies ReLU between them. How should you organize this using
nn.Module?hard
Solution
Step 1: Organize layers in __init__
Both linear layers should be created once in __init__ to register parameters properly.Step 2: Define data flow in forward
Apply the first linear layer, then ReLU, then second linear layer inside forward.Final Answer:
Define both linear layers in __init__ and apply ReLU in forward. -> Option AQuick Check:
Layers in __init__, logic in forward = A [OK]
Hint: Layers in __init__, operations in forward [OK]
Common Mistakes:
- Defining layers inside forward causing re-creation
- Not using ReLU between layers
- Defining layers outside the class
Recommended
Ready to prove it?
Pass the test and this pattern moves unknown
10 questions ~5 mineasy hard
