torch.nn.functional
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
torch.nn.functional (conventionally imported as F) holds the stateless versions of the layers and losses in torch.nn. A module such as nn.Conv2d owns its weights and remembers whether it is in training mode; the matching function F.conv2d(input, weight, bias, ...) owns nothing, so you pass every tensor and flag explicitly. This page explains when each style is the right one, tours the function groups listed in the 2.15 reference, and collects the argument mistakes that cause silent bugs. Modules are described in nn.Module, and the layers whose functional forms appear below in Linear, Convolution & Pooling Layers and Embeddings, Normalization, Dropout & Activations.
Examples were run on Python 3.13 with PyTorch 2.15 (CPU) on 2026-10-31.
Modules or functions?
Use a module when the layer has parameters or buffers, or behaves differently in training and evaluation, so that model.parameters(), state_dict(), .to(device) and model.eval() work without extra code. Use a function for operations without state: activations, softmax, pad, interpolate, normalize, scaled_dot_product_attention, losses computed on the fly. The two are equivalent where both exist; the module simply stores the arguments and calls the function.
| Situation | Recommendation |
|---|---|
|
Function ( |
Dropout |
Module. |
Batch norm |
Module. The function |
Conv or linear with learnable weights |
Module. Use the function when the weights are computed (hypernetworks, weight standardization, |
Loss |
Either. Module losses ( |
Function groups
The reference page organizes the functions as follows (names as listed for 2.15).
| Group | Functions |
|---|---|
Convolution |
|
Pooling |
|
Attention |
|
Non-linear activations |
|
Normalization |
|
Linear |
|
Dropout |
|
Sparse |
|
Distance |
|
Losses |
|
Vision |
|
linear_cross_entropy and its module nn.LinearCrossEntropyLoss are recent additions that fuse the final projection with the loss; see Loss Functions.
Activations and softmax
import torch
import torch.nn.functional as F
x = torch.randn(4, 10)
a = F.relu(x)
b = F.gelu(x, approximate="tanh") # the default is the exact version
c = F.silu(x)
p = F.softmax(x, dim=-1) # always pass dim
lp = F.log_softmax(x, dim=-1) # numerically stable log of softmax
print(p.sum(-1), lp.exp().sum(-1))
# In-place variants mutate the input and can break autograd if the value is needed later
y = x.clone().requires_grad_()
z = F.relu(y) # prefer this over F.relu_(y)
Rules that avoid bugs:
-
Always give
dimtosoftmax,log_softmaxandsoftmin. For a(batch, classes)tensor,dim=-1(or1) normalizes each row;dim=0normalizes across the batch and silently trains nonsense. -
Prefer
log_softmaxoversoftmax(...).log(): it avoids underflow. -
The functions
F.sigmoid,F.tanhandF.upsampleexist in the listing; the reference page does not mark them deprecated. Usetorch.sigmoid,torch.tanhandF.interpolatein new code, which is the style the rest of the documentation uses.F.upsampleis a thin wrapper kept for compatibility. -
gumbel_softmax(logits, tau=1, hard=False)draws differentiable samples from a categorical distribution; withhard=Truethe forward pass is one-hot and the backward pass uses the soft sample (straight-through).
Losses
The loss functions take a reduction argument (mean, sum or none; the old size_average and reduce arguments are deprecated). Details of each loss, shapes and which ones expect logits are on Loss Functions. The functional form is convenient when the class weights or label smoothing change per call.
import torch
import torch.nn.functional as F
logits = torch.randn(6, 4, requires_grad=True)
target = torch.tensor([0, 3, 1, 1, 2, 0])
loss = F.cross_entropy(logits, target, label_smoothing=0.1)
per_sample = F.cross_entropy(logits, target, reduction="none") # shape (6,)
loss.backward()
# Same result as log_softmax followed by nll_loss
ref = F.nll_loss(F.log_softmax(logits, dim=-1), target)
Vision utilities
F.pad(input, pad, mode='constant', value=None) takes the padding as a flat tuple that starts from the last dimension: for a 4D tensor (left, right, top, bottom). F.interpolate(input, size=None, scale_factor=None, mode='nearest', align_corners=None, ...) resizes images and sequences; give exactly one of size and scale_factor, and set align_corners explicitly for the linear modes. F.grid_sample and F.affine_grid implement spatial transformers and warping. F.pixel_shuffle rearranges channels into spatial resolution for sub-pixel convolution (super-resolution).
import torch
import torch.nn.functional as F
img = torch.rand(1, 3, 32, 32)
padded = F.pad(img, (2, 2, 4, 4), mode="reflect") # W by 2+2, H by 4+4
up = F.interpolate(img, scale_factor=2, mode="bilinear", align_corners=False)
down = F.adaptive_avg_pool2d(img, output_size=(8, 8))
print(padded.shape, up.shape, down.shape)
labels = torch.tensor([2, 0, 1])
onehot = F.one_hot(labels, num_classes=3) # int64, shape (3, 3)
unit = F.normalize(torch.randn(5, 16), p=2, dim=1) # rows with L2 norm 1
sim = F.cosine_similarity(unit[:, None], unit[None, :], dim=-1) # (5, 5)
print(onehot.dtype, sim.diag())
F.one_hot returns int64; cast to float with .float() before using it as a soft target for losses that expect probabilities. F.normalize clamps the norm with eps=1e-12 to avoid division by zero.
Functional layers with explicit weights
Passing weights explicitly makes the functional API the basis for techniques where the parameters are not fixed module attributes: weight sharing across layers, per-sample parameters, meta-learning and the transformations in torch.func (see Higher-Order Gradients & torch.func).
import torch
import torch.nn.functional as F
from torch import nn
class StandardizedConv2d(nn.Conv2d):
"""Convolution whose weights are standardized per output channel on every call."""
def forward(self, x):
w = self.weight
w = (w - w.mean(dim=(1, 2, 3), keepdim=True)) / (w.std(dim=(1, 2, 3), keepdim=True) + 1e-5)
return F.conv2d(x, w, self.bias, self.stride, self.padding, self.dilation, self.groups)
layer = StandardizedConv2d(3, 8, kernel_size=3, padding=1)
print(layer(torch.randn(2, 3, 16, 16)).shape) # torch.Size([2, 8, 16, 16])
Common mistakes
-
F.dropout(x, p=0.5)insideforwardwithouttraining=self.trainingkeeps dropping at evaluation time. -
F.softmaxwithoutdim, or over the wrong axis. -
Passing softmax output to
F.cross_entropy, which already applieslog_softmaxinternally. -
F.binary_cross_entropyon raw logits: it expects probabilities in \([0,1]\). UseF.binary_cross_entropy_with_logitsinstead, which is more stable. -
F.interpolatewith bothsizeandscale_factor, or withalign_cornersleft unset for linear modes. -
In-place activations (
F.relu_,inplace=True) on a tensor that autograd needs later. -
Using
F.batch_normdirectly without managingrunning_mean,running_varand the training flag.