The forward method defines how data moves through a neural network. It tells the model what to do with input to get output.
forward method in PyTorch
def forward(self, x): # define how input x passes through layers x = self.layer1(x) x = self.layer2(x) return x
The forward method is inside a class that inherits from torch.nn.Module.
You do not call forward directly; instead, call the model instance with input.
forward method applies this layer to input x.class SimpleModel(nn.Module): def __init__(self): super().__init__() self.linear = nn.Linear(10, 5) def forward(self, x): return self.linear(x)
forward.def forward(self, x): x = self.conv1(x) x = torch.relu(x) x = self.pool(x) return x
This program defines a small model with two linear layers and a ReLU activation in between. It shows how forward controls data flow. The output is the model's prediction for the input tensor.
import torch import torch.nn as nn class MyModel(nn.Module): def __init__(self): super().__init__() self.linear1 = nn.Linear(4, 3) self.relu = nn.ReLU() self.linear2 = nn.Linear(3, 2) def forward(self, x): x = self.linear1(x) x = self.relu(x) x = self.linear2(x) return x # Create model instance model = MyModel() # Sample input tensor (batch size 1, 4 features) input_tensor = torch.tensor([[1.0, 2.0, 3.0, 4.0]]) # Get model output by calling the model output = model(input_tensor) print("Output:", output)
Always call the model instance (e.g., model(input)) instead of calling forward directly.
The forward method can include any Python code to process data step-by-step.
Use self to access layers defined in __init__.
The forward method defines how input data moves through your model.
It is required when creating custom PyTorch models by subclassing nn.Module.
Call the model instance with input to run forward and get output.
Practice
forward method in a PyTorch model?Solution
Step 1: Understand the role of
Theforwardin PyTorchforwardmethod specifies the computation performed on input data as it passes through the model.Step 2: Differentiate from other methods
Initialization and saving/loading are handled by other methods, notforward.Final Answer:
To define how input data passes through the model layers -> Option AQuick Check:
forwarddefines data flow [OK]
- Confusing forward with initialization
- Thinking forward saves or loads data
- Assuming forward is called manually
forward method inside a PyTorch nn.Module subclass?Solution
Step 1: Check method signature requirements
Theforwardmethod must haveselfas the first argument and input data as the second.Step 2: Validate method name and parameters
def forward(self, x): return x * 2 correctly uses lowercaseforwardand includesselfandx. Others have wrong case, missingself, or missing input.Final Answer:
def forward(self, x): return x * 2 -> Option BQuick Check:
Correct method name and parameters = def forward(self, x): return x * 2 [OK]
- Capitalizing 'Forward' instead of 'forward'
- Omitting 'self' parameter
- Missing input argument in method
model(torch.tensor([2.0]))?
import torch
import torch.nn as nn
class SimpleModel(nn.Module):
def __init__(self):
super().__init__()
self.linear = nn.Linear(1, 1)
self.linear.weight.data.fill_(2.0)
self.linear.bias.data.fill_(1.0)
def forward(self, x):
return self.linear(x)
model = SimpleModel()Solution
Step 1: Calculate linear layer output
The linear layer output is weight * input + bias = 2.0 * 2.0 + 1.0 = 5.0.Step 2: Confirm output tensor
The model returns tensor([5.0]) as output.Final Answer:
tensor([5.0]) -> Option AQuick Check:
Output = 2*2 + 1 = 5 [OK]
- Ignoring bias term
- Using wrong weight value
- Confusing input tensor shape
forward method:
class MyModel(nn.Module):
def __init__(self):
super().__init__()
self.fc = nn.Linear(3, 1)
def forward(self, x):
x = self.fc
return xSolution
Step 1: Analyze the forward method code
The linex = self.fcassigns the layer object to x instead of calling it.Step 2: Identify correct usage
To get output, the layer must be called with input:x = self.fc(x).Final Answer:
The forward method returns the layer object, not the output -> Option DQuick Check:
Layer must be called with input, not assigned [OK]
- Assigning layer instead of calling it
- Forgetting to call super().__init__()
- Ignoring input tensor shape
forward method, with a ReLU activation in between. Which forward method implementation is correct?
class TwoLayerModel(nn.Module):
def __init__(self):
super().__init__()
self.fc1 = nn.Linear(4, 3)
self.fc2 = nn.Linear(3, 2)
self.relu = nn.ReLU()
def forward(self, x):
?Solution
Step 1: Understand the desired layer order
The model should apply fc1, then ReLU, then fc2 in sequence.Step 2: Check each option's order
x = self.fc1(x) x = self.relu(x) x = self.fc2(x) return x correctly applies fc1, then ReLU, then fc2. Others change the order or skip activation between layers.Final Answer:
x = self.fc1(x) x = self.relu(x) x = self.fc2(x) return x -> Option CQuick Check:
Layer1 -> ReLU -> Layer2 sequence = x = self.fc1(x) x = self.relu(x) x = self.fc2(x) return x [OK]
- Applying activation after last layer
- Skipping activation between layers
- Incorrect order of operations
Ready to prove it?
Pass the test and this pattern moves unknown
