Skip to content
module

functional

134 members
lucid.nn.functional

lucid.nn.functional — the stateless ops the layers are built from.

122 functions across twelve areas: activations, convolution, pooling, normalisation, attention, losses, dropout, linear maps, metrics, sparse (embeddings), sampling and positional encodings.

Every function is pure — weights, biases and running statistics arrive as arguments — so the same call works with or without a Module wrapped around it. Each lucid.nn layer delegates here, which is what keeps the two views from diverging: nn.Linear and F.linear are the same computation and the same autograd node, not parallel implementations.

Device contract: helper tensors an op builds internally (index grids, triangular masks, constants) are created on the input's device, so a call on a Metal tensor stays on Metal end to end. A function that silently returned CPU state would force a round trip on every step of a training loop.

Functions

fnrelu→ Tensor

Apply the rectified linear unit function element-wise.

fnleaky_relu→ Tensor

Leaky rectified linear unit activation.

fnelu→ Tensor

Exponential linear unit activation.

fncelu→ Tensor

Continuously-differentiable Exponential Linear Unit (Barron 2017).

fnselu→ Tensor

Scaled exponential linear unit activation.

fngelu→ Tensor

Gaussian Error Linear Unit activation.

fnsilu→ Tensor

Sigmoid Linear Unit (a.k.a. Swish-1) activation.

fnmish→ Tensor

Mish activation function.

fnhardswish→ Tensor

Hard Swish activation — piecewise linear approximation of silu.

fnhardsigmoid→ Tensor

Hard sigmoid — piecewise linear approximation of sigmoid.

fnsigmoid→ Tensor

Logistic sigmoid activation.

fntanh→ Tensor

Hyperbolic tangent activation.

fnsoftmax→ Tensor

Apply the softmax function along a dimension.

fnlog_softmax→ Tensor

Numerically stable log-softmax along a dimension.

fnsoftplus→ Tensor

Smooth approximation of relu.

fnrelu6→ Tensor

Rectified linear unit clipped at six.

fnsoftmin→ Tensor

Softmin — softmax applied to the negation of the input.

fnglu→ Tensor

Gated Linear Unit (Dauphin et al. 2017).

fnprelu→ Tensor

Parametric Rectified Linear Unit (He et al. 2015).

fnhardshrink→ Tensor

Hard shrinkage operator.

fntanhshrink→ Tensor

Tanh shrinkage activation.

fnsoftshrink→ Tensor

Soft shrinkage operator — proximal operator of λ∥⋅∥1\lambda \|\cdot\|_1.

fncosine_similarity→ Tensor

Cosine similarity between two tensors along a dimension.

fnpairwise_distance→ Tensor

Element-wise LpL_p distance between two equally-shaped tensors.

fnhardtanh→ Tensor

Hardtanh — element-wise clamp to [min_val,max_val][\text{min\_val}, \text{max\_val}].

fnlogsigmoid→ Tensor

Numerically stable log⁡σ(x)\log \sigma(x).

fnsoftsign→ Tensor

Softsign activation.

fnthreshold→ Tensor

Threshold activation — gate elements by a scalar cutoff.

fnrrelu→ Tensor

Randomised leaky ReLU (Xu et al. 2015).

fngumbel_softmax→ Tensor

Gumbel-Softmax — differentiable relaxation of categorical sampling.

fnstraight_through→ Tensor

Straight-through estimator — hard forward, soft backward.

fnsymexp→ Tensor

Inverse of symlog.

fnsymlog→ Tensor

Symmetric logarithm — compress magnitude, keep sign and zero.

fnrelu_→ Tensor

In-place ReLU — input is overwritten with max(0, input).

fnelu_→ Tensor

In-place ELU — overwrites input with ELU(input,α)\text{ELU}(\text{input}, \alpha).

fncelu_→ Tensor

In-place CELU — overwrites input with CELU(input,α)\text{CELU}(\text{input}, \alpha).

fnselu_→ Tensor

In-place SELU — overwrites input with selu(input).

fnleaky_relu_→ Tensor

In-place Leaky ReLU — overwrites input with the leaky-rectified result.

fnhardtanh_→ Tensor

In-place hardtanh — clamps input to [min_val, max_val] in place.

fnthreshold_→ Tensor

In-place threshold — replace entries <= threshold with value.

fnrrelu_→ Tensor

In-place RReLU — randomised leaky ReLU written back into input.

fnlinear→ Tensor

Apply an affine linear transformation y=xW⊤+by = x W^\top + b.

fnbilinear→ Tensor

Bilinear transformation applied to two inputs.

fnfused_linear_relu→ Tensor

Fused linear + ReLU forward kernel.

fnfused_linear_gelu→ Tensor

Fused linear + GELU forward kernel.

fnnoisy_linear→ Tensor

A linear layer whose parameters carry learnable noise.

fnscaled_noise→ Tensor

The factorised-noise transform of Fortunato et al. (2017).

fnconv1d→ Tensor

1-D cross-correlation over a 3-D (or unbatched 2-D) input.

fnconv2d→ Tensor

2-D cross-correlation over a 4-D (or unbatched 3-D) input.

fnconv3d→ Tensor

3-D cross-correlation over a 5-D (or unbatched 4-D) input.

fnconv_transpose1d→ Tensor

Transposed 1-D convolution (a.k.a. "fractionally-strided" conv).

fnconv_transpose2d→ Tensor

Transposed 2-D convolution — the standard upsampling primitive.

fnconv_transpose3d→ Tensor

Transposed 3-D convolution — volumetric upsampling.

fnnormalize→ Tensor

Normalize a tensor to unit LpL_p norm along a dimension.

fnbatch_norm→ Tensor

Batch normalization (Ioffe & Szegedy, 2015).

fnlayer_norm→ Tensor

Layer normalization (Ba, Kiros & Hinton, 2016).

fngroup_norm→ Tensor

Group normalization (Wu & He, 2018).

fnrms_norm→ Tensor

Root-mean-square layer normalization (Zhang & Sennrich, 2019).

fninstance_norm→ Tensor

Instance normalization (Ulyanov, Vedaldi & Lempitsky, 2016).

fnlocal_response_norm→ Tensor

Local response normalization (Krizhevsky, Sutskever & Hinton, 2012).

fnmax_pool1d→ Tensor

1-D max pooling over a sliding window.

fnmax_pool2d→ Tensor

2-D max pooling over a sliding window.

fnmax_pool3d→ Tensor

3-D max pooling over a sliding window.

fnavg_pool1d→ Tensor

1-D average pooling over a sliding window.

fnavg_pool2d→ Tensor

2-D average pooling over a sliding window.

fnavg_pool3d→ Tensor

3-D average pooling over a sliding window.

fnadaptive_avg_pool1d→ Tensor

1-D adaptive average pooling — produces a fixed output length.

fnadaptive_avg_pool2d→ Tensor

2-D adaptive average pooling — produces a fixed (H, W).

fnadaptive_avg_pool3d→ Tensor

3-D adaptive average pooling — produces a fixed (D, H, W).

fnadaptive_max_pool2d→ Tensor

2-D adaptive max pooling — fixed-shape (H, W) via per-cell max.

fnadaptive_max_pool1d→ Tensor

1-D adaptive max pooling — produces a fixed output length.

fnadaptive_max_pool3d→ Tensor

3-D adaptive max pooling — produces a fixed (D, H, W).

fnlp_pool1d→ Tensor

1-D power-average pooling — (∑xp)1/p\big(\sum x^p\big)^{1/p}.

fnlp_pool2d→ Tensor

2-D power-average pooling — (∑xp)1/p\big(\sum x^p\big)^{1/p}.

fnlp_pool3d→ Tensor

3-D power-average pooling — (∑xp)1/p\big(\sum x^p\big)^{1/p}.

fnmax_unpool1d→ Tensor

Inverse of max_pool1d via scatter at saved argmax indices.

fnmax_unpool2d→ Tensor

Inverse of max_pool2d via scatter at saved argmax indices.

fnmax_unpool3d→ Tensor

Inverse of max_pool3d via scatter at saved argmax indices.

fnfractional_max_pool2d→ Tensor or (Tensor, Tensor)

Fractional max-pooling over a 2-D input (Graham, 2014).

fnfractional_max_pool3d→ Tensor or (Tensor, Tensor)

Fractional max-pooling over a 3-D input (Graham, 2014).

fndropout→ Tensor

Element-wise Bernoulli dropout — the canonical Srivastava 2014 form.

fndropout1d→ Tensor

Channel-wise dropout for 1-D sequence / feature inputs.

fndropout2d→ Tensor

Channel-wise dropout for 2-D (spatial) feature maps.

fndropout3d→ Tensor

Channel-wise dropout for 3-D (volumetric) feature maps.

fnalpha_dropout→ Tensor

Alpha dropout — variance-preserving dropout for SELU networks.

fnfeature_alpha_dropout→ Tensor

Channel-wise alpha dropout for SELU convolutional networks.

fnrepeat_kv→ Tensor

Repeat each key/value head n_rep times along the head axis.

fnscaled_dot_product_attention→ Tensor

Scaled dot-product attention — the core of every Transformer block.

fnmse_loss→ Tensor

Mean-squared-error (L2) loss between input and target.

fnl1_loss→ Tensor

Mean-absolute-error (L1) loss between input and target.

fnsmooth_l1_loss→ Tensor

Smooth L1 loss — a quadratic-near-zero, linear-far-from-zero hybrid.

fnhuber_loss→ Tensor

Huber loss — robust regression with a tunable transition point.

fncross_entropy→ Tensor

Cross-entropy loss for multi-class classification.

fnnll_loss→ Tensor

Negative log-likelihood loss for multi-class classification.

fnbinary_cross_entropy→ Tensor

Binary cross-entropy between predicted probabilities and targets.

fnbinary_cross_entropy_with_logits→ Tensor

Binary cross-entropy from raw logits (numerically stable).

fnkl_div→ Tensor

Kullback-Leibler divergence between two distributions.

fntriplet_margin_loss→ Tensor

Triplet margin loss for metric learning.

fntriplet_margin_with_distance_loss→ Tensor

Triplet margin loss with a user-supplied distance function.

fncosine_embedding_loss→ Tensor

Cosine embedding loss for pairwise similarity learning.

fnmargin_ranking_loss→ Tensor

Pairwise ranking hinge loss.

fnhinge_embedding_loss→ Tensor

Hinge embedding loss.

fnpoisson_nll_loss→ Tensor

Poisson negative log-likelihood loss for count regression.

fngaussian_nll_loss→ Tensor

Gaussian negative log-likelihood for heteroscedastic regression.

fnctc_loss→ Tensor

Connectionist Temporal Classification (CTC) loss.

fnmulti_margin_loss→ Tensor

Multi-class hinge (margin) loss — Crammer-Singer SVM objective.

fnmultilabel_margin_loss→ Tensor

Multi-label hinge loss for set-valued targets.

fnsoft_margin_loss→ Tensor

Logistic (softplus) loss for binary classification with ±1 labels.

fnmultilabel_soft_margin_loss→ Tensor

Per-class logistic loss averaged over labels (multi-label BCE).

fnembedding→ Tensor

Look up rows of an embedding table by integer indices.

fnnearest_codebook→ Tensor

Index of the closest codebook entry for each row of x.

fnone_hot→ Tensor

One-hot encode an integer class index tensor.

fntwo_hot→ Tensor

Encode continuous scalars as a distribution over two adjacent bins.

fnvector_quantize→ Tensor

Snap x to its nearest codebook entries, straight-through.

fnapply_rotary_emb→ tuple[Tensor, Tensor]

Apply Rotary Position Embedding (RoPE) to query and key tensors.

fnsinusoidal_embedding→ Tensor

Build the 1-D sinusoidal positional encoding table from "Attention Is All You Need".

fnsinusoidal_embedding_2d→ Tensor

Build the 2-D sinusoidal positional encoding from DETR (Carion et al., 2020).

fnupsample→ Tensor

Resample input to size or by scale_factor (deprecated).

fnupsample_nearest→ Tensor

Resample input by nearest neighbours (deprecated).

fnupsample_bilinear→ Tensor

Resample a 4-D input bilinearly, with aligned corners (deprecated).

fninterpolate→ Tensor

Resample an N-D tensor to a target spatial size or scale factor.

fngrid_sample→ Tensor

Sample an input feature map at flow-field coordinates.

fnaffine_grid→ Tensor

Generate a sampling grid from a batch of affine transform matrices.

fnpad→ Tensor

Pad an N-D tensor along an arbitrary set of trailing dimensions.

fnunfold→ Tensor

Extract sliding local blocks (im2col) from a 4-D or unbatched 3-D tensor.

fnfold→ Tensor

Combine an array of sliding local blocks back into an image (col2im).

fnembedding_bag→ Tensor

Aggregate embeddings into per-bag pooled vectors.

fnpixel_shuffle→ Tensor

Sub-pixel upsampling: rearrange channels into spatial resolution.

fnpixel_unshuffle→ Tensor

Inverse of pixel_shuffle: pack spatial blocks into channels.

fnmulti_head_attention_forward→ (Tensor, Tensor or None)

Stateless functional multi-head attention forward pass.

fnchannel_shuffle→ Tensor

Group-then-transpose channel rearrangement (ShuffleNet).

fnpdist→ Tensor

Pairwise LpL_p distances between rows of a 2-D tensor.

fnaccuracy→ Tensor

Compute the mean classification accuracy in [0, 1].

fncorrect_count→ Tensor

Count of correct top-1 predictions as an int64 0-d Tensor.