PyTorch’s functional API provides stateless operations: each output depends entirely on the input arguments. Unlike an nn.Module, a functional call does not store learnable parameters internally. section 8.3.3
Use modules for parameterized layers such as nn.Conv2d and nn.Linear, so their Parameters are registered and managed during training. Use functional operations for parameter-free pooling and activations. section 8.3.3
The functional and module-based styles differ in how they handle state:
- Call a module as layer(input); call a functional operation as F.function(input, other_args). section 8.3.3
- Store module parameters as attributes; pass functional parameters explicitly, such as F.linear(input, weight, bias=None). section 8.3.3
- Let modules register and track parameters automatically; manage functional parameters manually. section 8.3.3
Mixing modules and functional operations
import torch.nn.functional as F class Net(nn.Module): def __init__(self): super().__init__() self.conv1 = nn.Conv2d(3, 16, 3, padding=1) self.fc = nn.Linear(8 * 8 * 8, 2) def forward(self, x): out = F.max_pool2d(torch.tanh(self.conv1(x)), 2) out = out.view(-1, 8 * 8 * 8) return self.fc(out) model = Net() model(img.unsqueeze(0)) section 8.3.3
Table 8.1 Comparing module-based and functional APIs in PyTorch
|
Module-based (
nn.Module
)
|
Functional (
torch.nn.functional
)
|
|---|---|
|
Example:
nn.Linear(in_features, out_features)
|
Example:
F.linear(input, weight, bias=None)
|
|
Has internal state (parameters stored in the module)
|
No internal state (stateless functions)
|
|
Parameters are stored as attributes.
|
Parameters are passed as arguments.
|
|
Parameters are registered and tracked automatically.
|
Parameters must be managed manually.
|
|
Common for layers like
nn.Conv2d,
nn.Linear
|
Common for activations like
F.relu,
F.tanh
|
|
Called via
layer(input)
|
Called via
F.function(input, other_args)
|
Compare module-based and functional calls, including state, parameter storage, registration, and typical uses. section 8.3.3
