Skip to main content
The clorch.nn.functional namespace — conventionally aliased as F — contains the stateless counterpart to every module in clorch.nn. Unlike modules, functional operations hold no parameters of their own: weights and biases must be supplied by the caller on every invocation. This makes the functional API ideal for custom architectures where you want explicit control over how parameters flow, or for operations that genuinely have no learnable state (activations, pooling, dropout).

Core Operations

Linear

Applies a linear transformation xW^T + b. Pass nil as the bias to omit it.

Convolution

All spatial parameters accept either a scalar (applied uniformly) or a sequence (one value per spatial dimension).

Batch Normalization

Applies batch normalization over a mini-batch of inputs. Requires pre-computed running statistics.

Pooling


Normalization

Both functions accept optional weight and bias tensors so you can wire in your own learnable scale/shift parameters.

Activations

Functional activations take a tensor as their first argument. See the Activations page for the full list.

Regularization

Dropout

Always pass :training? true during training and :training? false (or omit it) during inference. The module form nn/dropout handles mode-switching automatically via nn/train; the functional form does not.

Interpolation and Padding

Interpolation

Resize spatial tensors to a target size or by a scale factor.

Padding

The padding argument is a vector ordered [left right top bottom ...] — reversed from the spatial dimensions, following PyTorch convention.

Pixel Shuffle

Rearranges elements in a tensor of shape [N C*r^2 H W] into [N C H*r W*r], and vice versa. Used in sub-pixel convolution super-resolution models.

Loss Functions

Loss functions live in F/ alongside other stateless operations. See the Loss Functions page for full coverage.

Scaled Dot-Product Attention

F/scaled-dot-product-attention wraps LibTorch’s fused SDPA dispatcher. On CUDA it automatically selects Flash Attention, memory-efficient attention, or the math kernel based on dtype, tensor shape, and hardware support.
:causal? true is equivalent to passing a causal mask, but it is handled entirely inside LibTorch’s C++ layer, avoiding the cost of materializing a large boolean matrix on the JVM side.

When to Use Functional vs Modules

Choose the stateful module form when:
  • The layer has learnable parameters (weights, biases, scale, shift).
  • You want automatic parameter registration — nn/parameters, nn/state-dict, and nn/to work out of the box.
  • You need training/eval mode switching (dropout, batchnorm).
  • You are composing layers inside defmodel or nn/sequential.
Most real models mix both styles: defmodel fields hold the learnable modules while the forward body calls F/relu, F/dropout, and F/softmax directly — no sub-module instantiation required.