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

ReLU, GELU, SiLU in forward

Function (F.relu(x)). A module is only needed for nn.Sequential or to see it in print(model).

Dropout

Module. F.dropout defaults to training=True, so a function call inside forward must pass training=self.training.

Batch norm

Module. The function F.batch_norm needs you to hold running_mean, running_var and the training flag yourself.

Conv or linear with learnable weights

Module. Use the function when the weights are computed (hypernetworks, weight standardization, torch.func.functional_call style code).

Loss

Either. Module losses (nn.CrossEntropyLoss) fix the options once; functions pass them per call.

Function groups

The reference page organizes the functions as follows (names as listed for 2.15).

Group Functions

Convolution

conv1d, conv2d, conv3d, conv_transpose1d/2d/3d, unfold, fold

Pooling

avg_pool1d/2d/3d, max_pool1d/2d/3d, max_unpool*, lp_pool*, adaptive_avg_pool*, adaptive_max_pool*, fractional_max_pool2d/3d

Attention

scaled_dot_product_attention (see Attention, SDPA, FlexAttention & Transformers)

Non-linear activations

relu, relu6, leaky_relu, prelu, rrelu, elu, selu, celu, gelu, silu, mish, glu, hardtanh, hardswish, hardsigmoid, sigmoid, tanh, softplus, softsign, softmax, softmin, log_softmax, gumbel_softmax, threshold and the in-place _ variants

Normalization

batch_norm, group_norm, instance_norm, layer_norm, rms_norm, local_response_norm, normalize

Linear

linear, bilinear

Dropout

dropout, dropout1d/2d/3d, alpha_dropout, feature_alpha_dropout

Sparse

embedding, embedding_bag, one_hot

Distance

pairwise_distance, cosine_similarity, pdist

Losses

cross_entropy, nll_loss, binary_cross_entropy, binary_cross_entropy_with_logits, mse_loss, l1_loss, smooth_l1_loss, huber_loss, kl_div, ctc_loss, triplet_margin_loss, cosine_embedding_loss, …​, and linear_cross_entropy

Vision

pad, interpolate, upsample and friends, grid_sample, affine_grid, pixel_shuffle, pixel_unshuffle

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 dim to softmax, log_softmax and softmin. For a (batch, classes) tensor, dim=-1 (or 1) normalizes each row; dim=0 normalizes across the batch and silently trains nonsense.

  • Prefer log_softmax over softmax(...).log(): it avoids underflow.

  • The functions F.sigmoid, F.tanh and F.upsample exist in the listing; the reference page does not mark them deprecated. Use torch.sigmoid, torch.tanh and F.interpolate in new code, which is the style the rest of the documentation uses. F.upsample is a thin wrapper kept for compatibility.

  • gumbel_softmax(logits, tau=1, hard=False) draws differentiable samples from a categorical distribution; with hard=True the 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) inside forward without training=self.training keeps dropping at evaluation time.

  • F.softmax without dim, or over the wrong axis.

  • Passing softmax output to F.cross_entropy, which already applies log_softmax internally.

  • F.binary_cross_entropy on raw logits: it expects probabilities in \([0,1]\). Use F.binary_cross_entropy_with_logits instead, which is more stable.

  • F.interpolate with both size and scale_factor, or with align_corners left unset for linear modes.

  • In-place activations (F.relu_, inplace=True) on a tensor that autograd needs later.

  • Using F.batch_norm directly without managing running_mean, running_var and the training flag.