cognithesis.

NOTIX

Species Encyclopedia

241 entries across 8 kingdoms

Kingdom / Phylum / Family / Species

Tensor Topology & Flow

Scope

Operations that rearrange, slice, merge, pad, or route tensors without changing the value of individual elements (except where padding introduces new values). These are the shape, layout, and routing primitives of a graph.

57 entries
I.1ReshapeChanges how a tensor is organized without changing which numbers are in it. Like taking a deck of 52 cards and arranging them into 4 rows of 13 instead of 13 rows of 4.

What it is

Changes how a tensor is organized without changing which numbers are in it. Like taking a deck of 52 cards and arranging them into 4 rows of 13 instead of 13 rows of 4.

Purpose

Different operations expect data in different shapes. Reshape lets you reorganize your data to match what the next operation needs.

Common uses

  • Converting a 2D image (height × width) into a 1D list of pixels before feeding it to a fully-connected layer
  • Rearranging a batch of sequences from (batch, time, features) to (time, batch, features)

What it's NOT

  • Not a mathematical transform – Reshape doesn't calculate anything; it just rearranges
  • Not pooling or downsampling – Reshape keeps all the same values; it doesn't reduce or combine them
  • Not transpose – While both change organization, transpose specifically swaps axes, while reshape can do arbitrary reorganization

Analogy

Imagine you have books on a shelf. Reshape is like taking the same books and putting them on different shelves—same books, different arrangement.

I.1FlattenTakes a multi-dimensional tensor and stretches it out into a single long row (or sometimes a 2D table). Like unrolling a sheet of paper that was folded multiple times.

What it is

Takes a multi-dimensional tensor and stretches it out into a single long row (or sometimes a 2D table). Like unrolling a sheet of paper that was folded multiple times.

Purpose

Many operations (especially older-style neural network layers) expect data as a simple list. Flatten converts complex structures like images or feature maps into that simple format.

Common uses

  • Converting the output of convolutional layers (which produce 3D feature maps) into a 1D vector before classification
  • Preparing batched data where each item needs to become a single vector
  • Simplifying data before feeding it to traditional machine learning algorithms

What it's NOT

  • Not dimensionality reduction – Flatten doesn't remove information or compress data; it just linearizes it
  • Not pooling – Flatten keeps every single value; pooling would combine or select values
  • Not feature extraction – Flatten is purely organizational; it doesn't create new features or select important ones

Analogy

Think of a 3D Rubik's cube. Flatten would be like carefully unfolding it into a long strip of colored squares laid out in a line—same squares, just in a different arrangement.

I.1SqueezeRemoves dimensions that have a size of 1. Like removing empty parentheses in a mathematical expression: (((5))) becomes 5.

What it is

Removes dimensions that have a size of 1. Like removing empty parentheses in a mathematical expression: (((5))) becomes 5.

Purpose

Sometimes operations add "singleton dimensions" (dimensions of size 1) that aren't needed. Squeeze cleans up these extra dimensions to make the data shape simpler.

Common uses

  • Cleaning up after operations that add batch dimensions when you're only processing one item
  • Removing unnecessary dimensions before saving data or passing it to operations that don't expect them
  • Simplifying tensor shapes for easier debugging and understanding

What it's NOT

  • Not data removal – Squeeze doesn't delete any values, just removes organizational overhead
  • Not compression – The same amount of data exists; it's just organized more simply
  • Not reduction – Operations like sum or mean reduce data; squeeze just removes empty dimensions

Analogy

If you have a box containing another box containing another box with a single marble, squeeze removes the nested boxes so you're just holding the marble.

I.1ExpandDimsAdds a new dimension of size 1 to a tensor. The opposite of Squeeze. Like wrapping a single item in brackets: 5 becomes (5).

What it is

Adds a new dimension of size 1 to a tensor. The opposite of Squeeze. Like wrapping a single item in brackets: 5 becomes (5).

Purpose

Some operations expect data to have a specific number of dimensions. ExpandDims lets you add dimensions where needed without changing the actual data.

Common uses

  • Adding a batch dimension when you have a single example but the model expects batched input
  • Making a 1D array into a 2D column vector or row vector
  • Preparing data to broadcast correctly in mathematical operations

What it's NOT

  • Not duplication – ExpandDims doesn't copy data; it just adds organizational structure
  • Not tiling or repeating – It adds a dimension of size 1, not multiple copies
  • Not upsampling – The data stays exactly the same; only the shape changes

Analogy

Like putting a single apple in a basket. The apple is the same, but now it's organized as "a basket of apples" (even though there's only one).

I.2TransposeSwaps or rotates the axes (dimensions) of a tensor. For a 2D matrix, this means swapping rows and columns. For higher dimensions, it can mean any reordering of axes.

What it is

Swaps or rotates the axes (dimensions) of a tensor. For a 2D matrix, this means swapping rows and columns. For higher dimensions, it can mean any reordering of axes.

Purpose

Different operations expect data organized in different orders. Transpose lets you rearrange axes to match what's needed.

Common uses

  • Converting between row-major and column-major matrix storage
  • Reordering batch/sequence/feature dimensions for different model architectures
  • Preparing matrices for matrix multiplication (which often requires one matrix to be transposed)

What it's NOT

  • Not reshape – Transpose specifically reorders axes; reshape can change dimensions entirely
  • Not a rotation (in image sense) – Transpose swaps axes; rotating an image 90° is different
  • Not a flip or reverse – Transpose changes axis order; it doesn't reverse the values along an axis

Analogy

Imagine a spreadsheet. Transpose is like turning it 90 degrees so rows become columns and columns become rows. The same data, just oriented differently.

I.2PermuteAxesA generalization of transpose that can reorder axes in any pattern, not just swapping two. Like shuffling the order of coordinates.

What it is

A generalization of transpose that can reorder axes in any pattern, not just swapping two. Like shuffling the order of coordinates.

Purpose

Complex neural architectures often need data organized in specific axis orders. PermuteAxes provides full flexibility to rearrange dimensions however needed.

Common uses

  • Converting between different data layout conventions (NCHW ↔ NHWC for images)
  • Reordering time/batch/feature dimensions for sequence models
  • Preparing data for operations that expect specific axis orderings

What it's NOT

  • Not sorting – PermuteAxes rearranges which axis is which, not the values within axes
  • Not reshape – The size of each dimension stays the same; only their order changes
  • Not limited to 2D – Unlike simple transpose, works with any number of dimensions

Analogy

Think of a filing cabinet with drawers labeled by year, then month, then category. PermuteAxes would let you reorganize it to category, then year, then month—same files, different organizational structure.

I.3SliceExtracts a continuous rectangular region from a tensor. Like cutting a piece out of a larger sheet of paper.

What it is

Extracts a continuous rectangular region from a tensor. Like cutting a piece out of a larger sheet of paper.

Purpose

Often you only need part of your data—a specific time range, a crop of an image, or a subset of features. Slice lets you extract exactly the region you want.

Common uses

  • Extracting a spatial crop from an image
  • Getting a specific time window from a sequence
  • Selecting a subset of features or channels
  • Implementing operations like padding or cropping

What it's NOT

  • Not filtering – Slice extracts a geometric region, not values meeting a condition
  • Not sampling – Slice takes a continuous block, not scattered positions
  • Not pooling – Slice selects data, doesn't combine or reduce it

Analogy

Like using scissors to cut out a rectangular section from a newspaper. You get that exact section, nothing more, nothing less.

I.3GatherCollects values from specific positions using a list of indices. Like picking specific cards from a deck based on a list of card numbers.

What it is

Collects values from specific positions using a list of indices. Like picking specific cards from a deck based on a list of card numbers.

Purpose

When you need specific elements from specific positions (not a continuous region), Gather lets you select them using index lists.

Common uses

  • Looking up embeddings for specific word IDs in a vocabulary
  • Selecting features based on learned importance scores
  • Implementing attention mechanisms (gathering values based on attention weights)
  • Creating custom rearrangements or selections

What it's NOT

  • Not slice – Gather can select scattered positions; slice only takes continuous regions
  • Not filtering – Gather uses explicit indices, not value-based conditions
  • Not embedding layer – While embeddings use gathering, Gather is the lower-level indexing operation

Analogy

Like a scavenger hunt list that says "get item #5, item #12, and item #3" from a warehouse. You collect exactly those items in that order.

I.3TakeExtracts elements at specific indices along an axis. A simpler, more restricted version of Gather that works along a single axis.

What it is

Extracts elements at specific indices along an axis. A simpler, more restricted version of Gather that works along a single axis.

Purpose

Selecting specific positions along one dimension, like taking certain rows from a table or certain frames from a video.

Common uses

  • Selecting specific samples from a batch
  • Extracting certain time steps from a sequence
  • Picking specific channels from feature maps
  • Implementing sampling strategies

What it's NOT

  • Not Gather – Take is simpler, working along one axis; Gather can index multiple axes
  • Not Slice – Take uses explicit indices, not ranges
  • Not random sampling – Uses provided indices, doesn't generate them randomly

Analogy

Like being given a list of page numbers and pulling just those pages from a book. Simple, direct indexing.

I.3StridedSliceLike Slice, but can skip elements using a "stride" (step size). Extracts every Nth element from a region instead of every element.

What it is

Like Slice, but can skip elements using a "stride" (step size). Extracts every Nth element from a region instead of every element.

Purpose

Efficiently downsample data or extract regularly-spaced samples without needing separate operations.

Common uses

  • Quick downsampling by taking every other pixel
  • Extracting even-indexed or odd-indexed elements
  • Implementing certain types of spatial pooling
  • Selecting regular intervals from sequences

What it's NOT

  • Not pooling – StridedSlice selects existing values; pooling would combine them
  • Not interpolation – This picks existing values at intervals, doesn't create new in-between values
  • Not random sampling – The spacing is regular and deterministic

Analogy

Imagine a ruler with measurements. Regular Slice gives you inches 5 through 10. StridedSlice gives you inches 5, 7, 9 (every other one).

I.4ConcatJoins multiple tensors together along a chosen axis, like stacking blocks side-by-side or end-to-end.

What it is

Joins multiple tensors together along a chosen axis, like stacking blocks side-by-side or end-to-end.

Purpose

Combining information from different sources or different processing paths. Essential for architectures that merge multiple streams of data.

Common uses

  • Combining features from different network branches (like in ResNet skip connections)
  • Merging encoder and decoder features (like in U-Net architectures)
  • Combining embeddings from different sources
  • Building larger tensors from smaller pieces

What it's NOT

  • Not addition or averaging – Concat places tensors side-by-side; it doesn't combine values mathematically
  • Not fusion or blending – The original tensors' values remain distinct and unchanged
  • Not stacking with extra dimension – Concat joins along an existing axis; Stack creates a new axis

Analogy

Like putting books on a shelf next to each other. Each book stays separate, but they're now organized together.

I.4SplitDivides a tensor into multiple pieces along an axis. The opposite of Concat. Like slicing a loaf of bread into separate slices.

What it is

Divides a tensor into multiple pieces along an axis. The opposite of Concat. Like slicing a loaf of bread into separate slices.

Purpose

Separating a tensor into parts that can be processed independently or routed to different operations.

Common uses

  • Dividing a tensor into multiple processing branches
  • Separating different feature types that were concatenated earlier
  • Implementing multi-head attention (splitting into separate heads)
  • Creating separate paths in network architectures

What it's NOT

  • Not chunking by value – Split divides geometrically, not based on content
  • Not clustering or grouping – Divisions are regular along an axis, not based on similarity
  • Not the same as Slice – Split produces multiple outputs; Slice produces one

Analogy

Like cutting a pizza into slices. You started with one whole; now you have several separate pieces.

I.4StackCombines multiple tensors by creating a new dimension. Like taking separate sheets of paper and making them into a booklet.

What it is

Combines multiple tensors by creating a new dimension. Like taking separate sheets of paper and making them into a booklet.

Purpose

When you have multiple related tensors (like frames of video or batch items) and want to organize them together in a new dimension.

Common uses

  • Creating batches from individual examples
  • Combining time steps into a sequence dimension
  • Building RGB images from separate red, green, blue channels
  • Organizing related tensors into a higher-dimensional structure

What it's NOT

  • Not Concat – Stack creates a new axis; Concat joins along an existing axis
  • Not Expand – Stack combines multiple tensors; Expand adds a dimension to one tensor
  • Not Tile – Stack organizes different tensors; Tile repeats the same tensor

Analogy

Like organizing a deck of different trading cards (each a separate card) into a neat stack where you can refer to "the 5th card in the stack."

I.4ChunkDivides a tensor into a specific number of roughly equal pieces along an axis. Like cutting a long rope into several pieces of equal length.

What it is

Divides a tensor into a specific number of roughly equal pieces along an axis. Like cutting a long rope into several pieces of equal length.

Purpose

Partitioning data into a fixed number of groups for parallel processing or distributed computation.

Common uses

  • Distributing work across multiple processors
  • Implementing model parallelism
  • Creating mini-batches of specific sizes
  • Splitting data for multi-GPU training

What it's NOT

  • Not Split – Chunk specifies how many pieces you want; Split specifies the size of each piece
  • Not random partitioning – Chunks are contiguous and deterministic
  • Not filtering – Divides geometrically, not based on values

Analogy

Like dividing a chocolate bar by saying "I want 4 pieces" rather than "I want pieces of size 2 ounces." Chunk figures out the sizes to give you the number you want.

I.4UnstackThe opposite of Stack—takes a tensor and separates it along an axis into multiple individual tensors. Like splitting a deck into individual cards.

What it is

The opposite of Stack—takes a tensor and separates it along an axis into multiple individual tensors. Like splitting a deck into individual cards.

Purpose

Breaking apart batched or stacked data into separate pieces for independent processing.

Common uses

  • Separating batch items for individual processing
  • Extracting frames from a video tensor
  • Splitting RGB channels into separate grayscale images
  • Decomposing stacked representations

What it's NOT

  • Not Split – Unstack removes a dimension; Split keeps all dimensions
  • Not Squeeze – Unstack creates multiple outputs; Squeeze modifies one tensor
  • Not the same as indexing – Produces all slices simultaneously as separate tensors

Analogy

Like taking a deck of cards bound together and separating them into individual cards you can hand to different people.

I.5PadConstantAdds borders around a tensor filled with a specific value (often zero). Like adding margins around text on a page.

What it is

Adds borders around a tensor filled with a specific value (often zero). Like adding margins around text on a page.

Purpose

Many operations need extra space around data (like convolutions near edges). Padding provides that space with controlled values.

Common uses

  • Adding zeros around images before convolution to preserve size
  • Creating boundary regions in spatial data
  • Ensuring tensors have compatible sizes for operations
  • Implementing "same" padding in convolutional networks

What it's NOT

  • Not upsampling or resizing – Padding adds borders with fixed values, doesn't enlarge the content
  • Not duplication or reflection – Constant padding uses one specific value, not copies of existing data
  • Not cropping – This adds space; cropping removes it

Analogy

Like putting a picture in a frame with a wide border. The picture stays the same; you've just added empty space around it.

I.5PadReflectAdds borders by mirroring the existing edge values. Like placing mirrors along the edges of an image.

What it is

Adds borders by mirroring the existing edge values. Like placing mirrors along the edges of an image.

Purpose

When padding with zeros would create artifacts or boundaries, reflection padding provides more natural transitions by mirroring existing content.

Common uses

  • Image processing where edge discontinuities would be problematic
  • Signal processing to avoid boundary effects
  • Convolutional networks when edge behavior matters
  • Creating smoother padding for visual or audio data

What it's NOT

  • Not constant padding – Uses mirrored values, not a fixed constant
  • Not tiling or repeating – Reflects once at the boundary, doesn't repeat patterns
  • Not rotation – Mirrors values, doesn't rotate the content

Analogy

Imagine a pond with trees at the edge. The water reflects the trees. Pad-reflect does this with data—the "reflection" extends beyond the actual content.

I.5CropRemoves borders or extracts a central region from a tensor. The opposite of padding. Like cutting margins off a printed page.

What it is

Removes borders or extracts a central region from a tensor. The opposite of padding. Like cutting margins off a printed page.

Purpose

Removing unnecessary borders, extracting regions of interest, or matching sizes between tensors.

Common uses

  • Removing padding added by earlier operations
  • Extracting the center region of an image
  • Matching spatial dimensions between feature maps
  • Discarding edge regions that may have artifacts

What it's NOT

  • Not downsampling – Crop removes edges, doesn't reduce resolution throughout
  • Not Slice (necessarily) – Crop often refers specifically to removing borders; Slice is more general
  • Not attention-based selection – Crop uses geometric boundaries, not learned importance

Analogy

Like trimming the edges off a photograph to focus on the center, or cutting the crust off bread.

I.5CenterCropExtracts a rectangular region from the center of a tensor, discarding the outer edges. Like taking the middle square from a larger image.

What it is

Extracts a rectangular region from the center of a tensor, discarding the outer edges. Like taking the middle square from a larger image.

Purpose

Focusing on the central content while ensuring consistent output size. Common in vision tasks where the subject is typically centered.

Common uses

  • Preprocessing images for models that expect specific input sizes
  • Data augmentation pipelines
  • Removing edge artifacts while keeping the main content
  • Ensuring uniform sizes across a dataset

What it's NOT

  • Not random crop – Always takes the center, not a random location
  • Not resize – Crops to size, doesn't scale the content
  • Not attention-based – Uses geometric center, not learned focus

Analogy

Like using a circular cookie cutter on square dough—you always get the center circle, edges are discarded.

I.6BooleanMaskUses a true/false pattern to selectively keep or discard elements. Like using a stencil to paint only certain areas.

What it is

Uses a true/false pattern to selectively keep or discard elements. Like using a stencil to paint only certain areas.

Purpose

Selecting elements based on conditions, filtering data, or applying operations only where needed.

Common uses

  • Selecting valid positions in variable-length sequences (masking padding tokens)
  • Implementing attention masks in transformers
  • Filtering data based on conditions
  • Applying operations only to specific regions

What it's NOT

  • Not binary multiplication – While similar, masking has specific semantic meaning about validity
  • Not dropout – Dropout randomly zeros elements; masking uses specific patterns
  • Not slicing – Masking can create irregular patterns; slicing is geometric

Analogy

Like using a cookie cutter on dough. The cutter (mask) determines which parts you keep and which parts you discard.

I.6WhereSelectChooses between two tensors element-by-element based on a condition. Like a fork in the road where each position might go left or right.

What it is

Chooses between two tensors element-by-element based on a condition. Like a fork in the road where each position might go left or right.

Purpose

Conditional data selection, implementing if-then-else logic per element, or blending different data sources.

Common uses

  • Implementing conditional operations in differentiable ways
  • Selecting between two data sources based on learned or fixed conditions
  • Creating piecewise functions
  • Implementing certain types of gating mechanisms

What it's NOT

  • Not filtering – WhereSelect always produces output with the same shape, just with values from different sources
  • Not masking – Masking zeros out values; WhereSelect chooses between alternatives
  • Not a boolean AND/OR – This selects data values, not computing logical operations

Analogy

Like having two ingredients and a recipe that says "for position (i,j), use ingredient A if condition is true, otherwise use ingredient B."

I.6SwitchRouterRoutes data to different processing paths based on conditions or learned decisions. Like a railroad switch that sends trains down different tracks.

What it is

Routes data to different processing paths based on conditions or learned decisions. Like a railroad switch that sends trains down different tracks.

Purpose

Implementing conditional computation where different data takes different paths through the network, or creating mixture-of-experts architectures.

Common uses

  • Mixture-of-experts models (routing to different expert sub-networks)
  • Conditional execution based on input properties
  • Dynamic neural architectures
  • Efficient computation by only processing relevant paths

What it's NOT

  • Not WhereSelect – SwitchRouter determines paths for processing; WhereSelect chooses between already-processed results
  • Not masking – Routes to different computations, doesn't just zero out values
  • Not branching in code – This is a differentiable routing operation within the network

Analogy

Like a post office sorting facility that looks at zip codes and sends packages down different conveyor belts to different destinations.

I.1BroadcastToRepeat existing values along compatible axes to reach a requested shape.

What it is

Repeat existing values along compatible axes to reach a requested shape.

Purpose

Align tensor shapes for elementwise operations.

Common uses

  • Broadcast [1, 3] to [4, 3].
Tensor and behavior contract

Inputs

Tensor X and integer target shape.

Outputs

Tensor Y with the requested shape.

Parameters

  • Target shape.

Shape and rank constraints

  • Aligned input dimensions must equal the target dimension or be one.

Behavioral invariants

  • Repeated output positions reference the corresponding input value.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Broadcast [1, 3] to [4, 3].

Related operations

References

ONNX Expand ↗
I.1TileRepeat a tensor a whole number of times along each axis.

What it is

Repeat a tensor a whole number of times along each axis.

Purpose

Build repeated spatial or sequence patterns.

Common uses

  • Tile [1, 2] three times to obtain [1, 2, 1, 2, 1, 2].
Tensor and behavior contract

Inputs

Tensor X and one integer repeat count per axis.

Outputs

Tensor with dimension i multiplied by repeats[i].

Parameters

  • Repeat counts.

Shape and rank constraints

  • Repeat counts are nonnegative and match the input rank.

Behavioral invariants

  • Each repeated block preserves the original values and order.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Tile [1, 2] three times to obtain [1, 2, 1, 2, 1, 2].

Related operations

References

ONNX Tile ↗
I.2ReverseRead selected tensor axes in the opposite order.

What it is

Read selected tensor axes in the opposite order.

Purpose

Reverse time or spatial ordering without changing values.

Common uses

  • Reverse [1, 2, 3] to [3, 2, 1].
Tensor and behavior contract

Inputs

Tensor X.

Outputs

Tensor of the same shape and element type.

Parameters

  • Axes to reverse.

Shape and rank constraints

  • Axes are unique and within the input rank.

Behavioral invariants

  • Reversing the same axes twice recovers X.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Reverse [1, 2, 3] to [3, 2, 1].

Related operations

I.2RollShift values along an axis and wrap displaced values around its end.

What it is

Shift values along an axis and wrap displaced values around its end.

Purpose

Apply cyclic sequence or spatial shifts.

Common uses

  • Roll [1, 2, 3] by one to obtain [3, 1, 2].
Tensor and behavior contract

Inputs

Tensor X.

Outputs

Tensor of the same shape and element type.

Parameters

  • Integer shifts and axes.

Shape and rank constraints

  • Each shift is paired with a valid axis.

Behavioral invariants

  • The operation preserves all values and is invertible by the opposite shift.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Roll [1, 2, 3] by one to obtain [3, 1, 2].

Related operations

I.3GatherElementsRead one indexed position along an axis for every output location.

What it is

Read one indexed position along an axis for every output location.

Purpose

Select per-example or per-position values.

Common uses

  • Choose one class score at each token position.
Tensor and behavior contract

Inputs

Data tensor X and integer index tensor I of equal rank.

Outputs

Tensor with the shape of I.

Parameters

  • Axis.

Shape and rank constraints

  • Every index is valid along the selected axis; other index dimensions fit X.

Behavioral invariants

  • Each output equals the indexed input value.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Choose one class score at each token position.

Related operations

I.3GatherNDRead values or slices using tuples of coordinates across several axes.

What it is

Read values or slices using tuples of coordinates across several axes.

Purpose

Select sparse multidimensional locations.

Common uses

  • Read diagonal coordinates [[0, 0], [1, 1]] from a matrix.
Tensor and behavior contract

Inputs

Data X and integer coordinate tuples I.

Outputs

Shape I[:-1] followed by the unindexed trailing data dimensions.

Parameters

  • Batch dimensions.

Shape and rank constraints

  • Tuple length fits the non-batch data rank and all indices are in bounds.

Behavioral invariants

  • Repeated coordinates select repeated copies of the same value.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Read diagonal coordinates [[0, 0], [1, 1]] from a matrix.

Related operations

I.3ScatterElementsWrite updates at supplied indices along one axis.

What it is

Write updates at supplied indices along one axis.

Purpose

Place sparse updates into a dense tensor.

Common uses

  • Scatter two updates into selected matrix positions.
Tensor and behavior contract

Inputs

Base tensor X, integer indices I, and updates U.

Outputs

Tensor with the shape and element type of X.

Parameters

  • Reduction mode: replace, add, multiply, maximum, or minimum.
  • Axis.

Shape and rank constraints

  • Indices are in bounds and updates match the indexed locations.
  • Replacement mode requires unique destinations.

Behavioral invariants

  • Unaddressed values remain unchanged.

Semantics

Replacement with unique destinations is deterministic; reduction order can affect floating-point rounding.

Examples

  • Scatter two updates into selected matrix positions.

Related operations

I.3ScatterNDWrite updates at supplied coordinate tuples.

What it is

Write updates at supplied coordinate tuples.

Purpose

Place sparse updates into a dense tensor.

Common uses

  • Scatter two updates into selected matrix positions.
Tensor and behavior contract

Inputs

Base tensor X, integer indices I, and updates U.

Outputs

Tensor with the shape and element type of X.

Parameters

  • Reduction mode: replace, add, multiply, maximum, or minimum.

Shape and rank constraints

  • Indices are in bounds and updates match the indexed locations.
  • Replacement mode requires unique destinations.

Behavioral invariants

  • Unaddressed values remain unchanged.

Semantics

Replacement with unique destinations is deterministic; reduction order can affect floating-point rounding.

Examples

  • Scatter two updates into selected matrix positions.

Related operations

I.3SortOrder values along an axis and return their original positions.

What it is

Order values along an axis and return their original positions.

Purpose

Rank values while retaining their index correspondence.

Common uses

  • Sort [3, 1, 2] to values [1, 2, 3] and indices [1, 2, 0].
Tensor and behavior contract

Inputs

Orderable tensor X.

Outputs

Sorted values and a matching integer index tensor.

Parameters

  • Axis, ascending or descending order, stable tie ordering.

Shape and rank constraints

  • The axis is valid and the element type has a declared ordering.

Behavioral invariants

  • Indices form an axiswise permutation; sorted values equal the indexed input.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Sort [3, 1, 2] to values [1, 2, 3] and indices [1, 2, 0].

Related operations

I.3TopKReturn the largest or smallest k values and their positions along an axis.

What it is

Return the largest or smallest k values and their positions along an axis.

Purpose

Choose candidate tokens, experts, or detections.

Common uses

  • Select the five highest token scores.
Tensor and behavior contract

Inputs

Tensor X and integer k.

Outputs

Values and integer indices with the selected axis replaced by k.

Parameters

  • Axis, largest or smallest, sorted output.

Shape and rank constraints

  • 0 <= k <= the axis length.

Behavioral invariants

  • Every returned value matches its returned source index.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Select the five highest token scores.

Related operations

References

ONNX TopK ↗
I.3UniqueFind distinct tensor values or distinct slices along an axis.

What it is

Find distinct tensor values or distinct slices along an axis.

Purpose

Deduplicate IDs or build a compact vocabulary.

Common uses

  • Map [4, 4, 7] to values [4, 7] and inverse indices [0, 0, 1].
Tensor and behavior contract

Inputs

Tensor X.

Outputs

Distinct values plus optional first indices, inverse indices, and counts.

Parameters

  • Optional axis and sorted output.

Shape and rank constraints

  • The equality and ordering rules are declared for the input type.

Behavioral invariants

  • Inverse indices reconstruct the input from the distinct values.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Map [4, 4, 7] to values [4, 7] and inverse indices [0, 0, 1].

Related operations

References

ONNX Unique ↗
I.3NonZeroReturn the coordinates of nonzero elements.

What it is

Return the coordinates of nonzero elements.

Purpose

Convert a dense mask into sparse positions.

Common uses

  • Find the true positions in a padding mask.
Tensor and behavior contract

Inputs

Numeric or boolean tensor X.

Outputs

Integer coordinates of shape [rank(X), number of selected elements].

Parameters

  • None.

Shape and rank constraints

  • The result length depends on the input values.

Behavioral invariants

  • Every returned position identifies a nonzero input element.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Find the true positions in a padding mask.

Related operations

I.6LessThanCompare corresponding values and report whether the left value is < the right value.

What it is

Compare corresponding values and report whether the left value is < the right value.

Purpose

Build a boolean mask for tensor routing.

Common uses

  • Compare [1, 3] < 2.
Tensor and behavior contract

Inputs

Broadcast-compatible orderable tensors A and B.

Outputs

Boolean tensor with the broadcast shape.

Y = A < B

Parameters

  • Broadcast rules.

Shape and rank constraints

  • Inputs use compatible comparable types.

Behavioral invariants

  • Each output is the declared scalar comparison.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Compare [1, 3] < 2.

Related operations

References

ONNX Less ↗
I.6GreaterOrEqualCompare corresponding values and report whether the left value is >= the right value.

What it is

Compare corresponding values and report whether the left value is >= the right value.

Purpose

Build a boolean mask for tensor routing.

Common uses

  • Compare [1, 3] >= 2.
Tensor and behavior contract

Inputs

Broadcast-compatible orderable tensors A and B.

Outputs

Boolean tensor with the broadcast shape.

Y = A >= B

Parameters

  • Broadcast rules.

Shape and rank constraints

  • Inputs use compatible comparable types.

Behavioral invariants

  • Each output is the declared scalar comparison.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Compare [1, 3] >= 2.

Related operations

I.6LessOrEqualCompare corresponding values and report whether the left value is <= the right value.

What it is

Compare corresponding values and report whether the left value is <= the right value.

Purpose

Build a boolean mask for tensor routing.

Common uses

  • Compare [1, 3] <= 2.
Tensor and behavior contract

Inputs

Broadcast-compatible orderable tensors A and B.

Outputs

Boolean tensor with the broadcast shape.

Y = A <= B

Parameters

  • Broadcast rules.

Shape and rank constraints

  • Inputs use compatible comparable types.

Behavioral invariants

  • Each output is the declared scalar comparison.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Compare [1, 3] <= 2.

Related operations

I.6NotEqualCompare corresponding values and report whether the left value is != the right value.

What it is

Compare corresponding values and report whether the left value is != the right value.

Purpose

Build a boolean mask for tensor routing.

Common uses

  • Compare [1, 3] != 2.
Tensor and behavior contract

Inputs

Broadcast-compatible orderable tensors A and B.

Outputs

Boolean tensor with the broadcast shape.

Y = A != B

Parameters

  • Broadcast rules.

Shape and rank constraints

  • Inputs use compatible comparable types.

Behavioral invariants

  • Each output is the declared scalar comparison.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Compare [1, 3] != 2.

Related operations

I.6AndApply boolean and to corresponding mask values.

What it is

Apply boolean and to corresponding mask values.

Purpose

Combine conditions used to route or mask tensor values.

Common uses

  • Apply And to a causal mask and a padding mask.
Tensor and behavior contract

Inputs

Boolean tensor A and broadcast-compatible boolean tensor B.

Outputs

Boolean tensor with the input broadcast shape.

A and B

Parameters

  • Broadcast rules.

Shape and rank constraints

  • Inputs are boolean masks.

Behavioral invariants

  • The result follows the scalar boolean truth table.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Apply And to a causal mask and a padding mask.

Related operations

References

ONNX And ↗
I.6OrApply boolean or to corresponding mask values.

What it is

Apply boolean or to corresponding mask values.

Purpose

Combine conditions used to route or mask tensor values.

Common uses

  • Apply Or to a causal mask and a padding mask.
Tensor and behavior contract

Inputs

Boolean tensor A and broadcast-compatible boolean tensor B.

Outputs

Boolean tensor with the input broadcast shape.

A or B

Parameters

  • Broadcast rules.

Shape and rank constraints

  • Inputs are boolean masks.

Behavioral invariants

  • The result follows the scalar boolean truth table.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Apply Or to a causal mask and a padding mask.

Related operations

References

ONNX Or ↗
I.6XorApply boolean xor to corresponding mask values.

What it is

Apply boolean xor to corresponding mask values.

Purpose

Combine conditions used to route or mask tensor values.

Common uses

  • Apply Xor to a causal mask and a padding mask.
Tensor and behavior contract

Inputs

Boolean tensor A and broadcast-compatible boolean tensor B.

Outputs

Boolean tensor with the input broadcast shape.

A xor B

Parameters

  • Broadcast rules.

Shape and rank constraints

  • Inputs are boolean masks.

Behavioral invariants

  • The result follows the scalar boolean truth table.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Apply Xor to a causal mask and a padding mask.

Related operations

References

ONNX Xor ↗
I.6NotApply boolean not to corresponding mask values.

What it is

Apply boolean not to corresponding mask values.

Purpose

Combine conditions used to route or mask tensor values.

Common uses

  • Invert a valid-token mask.
Tensor and behavior contract

Inputs

Boolean tensor A.

Outputs

Boolean tensor with the input broadcast shape.

not A

Parameters

  • Broadcast rules.

Shape and rank constraints

  • Inputs are boolean masks.

Behavioral invariants

  • The result follows the scalar boolean truth table.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Invert a valid-token mask.

Related operations

References

ONNX Not ↗
I.6IsNaNMark each floating-point value that is not-a-number.

What it is

Mark each floating-point value that is not-a-number.

Purpose

Locate invalid or unbounded numerical results.

Common uses

  • Create a mask for not-a-number values in model outputs.
Tensor and behavior contract

Inputs

Floating-point tensor X.

Outputs

Boolean tensor with the same shape.

Parameters

  • Infinity sign selection for IsInf; none for IsNaN.

Shape and rank constraints

  • The input format supports the tested floating-point category.

Behavioral invariants

  • The input tensor is not changed.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Create a mask for not-a-number values in model outputs.

Related operations

References

ONNX IsNaN ↗
I.6IsInfMark each floating-point value that is infinite.

What it is

Mark each floating-point value that is infinite.

Purpose

Locate invalid or unbounded numerical results.

Common uses

  • Create a mask for infinite values in model outputs.
Tensor and behavior contract

Inputs

Floating-point tensor X.

Outputs

Boolean tensor with the same shape.

Parameters

  • Infinity sign selection for IsInf; none for IsNaN.

Shape and rank constraints

  • The input format supports the tested floating-point category.

Behavioral invariants

  • The input tensor is not changed.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Create a mask for infinite values in model outputs.

Related operations

References

ONNX IsInf ↗
I.6ReduceAllCombine boolean values across axes using logical conjunction.

What it is

Combine boolean values across axes using logical conjunction.

Purpose

Summarize whether all or any positions satisfy a mask.

Common uses

  • Check whether each sequence contains any valid token.
Tensor and behavior contract

Inputs

Boolean tensor X.

Outputs

Boolean reduction result.

Parameters

  • Axes and keep-dimensions flag.

Shape and rank constraints

  • Axes are valid and unique.

Behavioral invariants

  • An empty reduction uses the identity true.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Check whether each sequence contains any valid token.

Related operations

I.6ReduceAnyCombine boolean values across axes using logical disjunction.

What it is

Combine boolean values across axes using logical disjunction.

Purpose

Summarize whether all or any positions satisfy a mask.

Common uses

  • Check whether each sequence contains any valid token.
Tensor and behavior contract

Inputs

Boolean tensor X.

Outputs

Boolean reduction result.

Parameters

  • Axes and keep-dimensions flag.

Shape and rank constraints

  • Axes are valid and unique.

Behavioral invariants

  • An empty reduction uses the identity false.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Check whether each sequence contains any valid token.

Related operations

I.7ConstantIntroduce a declared immutable tensor value into a graph.

What it is

Introduce a declared immutable tensor value into a graph.

Purpose

Provide fixed coefficients, lookup values, or scalar settings.

Common uses

  • Create a scalar zero used by a comparison.
Tensor and behavior contract

Inputs

A serialized tensor literal.

Outputs

Tensor with the literal shape, element type, and values.

Parameters

  • Literal shape, type, and values.

Shape and rank constraints

  • The literal element count equals the product of its dimensions.

Behavioral invariants

  • The same declared literal produces the same output.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Create a scalar zero used by a comparison.

Related operations

I.7FillCreate a tensor whose entries all equal one supplied scalar.

What it is

Create a tensor whose entries all equal one supplied scalar.

Purpose

Construct zeros, ones, masks, and initialized buffers.

Common uses

  • Fill shape [2, 3] with zero; zeros and ones are fixed-value specializations with fill values 0 and 1.
Tensor and behavior contract

Inputs

Integer shape vector and scalar fill value.

Outputs

Filled tensor with the requested shape.

Parameters

  • Element type.

Shape and rank constraints

  • Dimensions are nonnegative integers and the fill input is scalar.

Behavioral invariants

  • Every output element equals the converted fill value.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Fill shape [2, 3] with zero; zeros and ones are fixed-value specializations with fill values 0 and 1.

Related operations

I.7RangeCreate an arithmetic sequence from a start value up to an exclusive limit.

What it is

Create an arithmetic sequence from a start value up to an exclusive limit.

Purpose

Generate position indices or regularly spaced coordinates.

Common uses

  • Range(0, 4, 1) gives [0, 1, 2, 3].
Tensor and behavior contract

Inputs

Scalar start, limit, and step.

Outputs

One-dimensional tensor of generated values.

Parameters

  • Output element type.

Shape and rank constraints

  • Step is nonzero and scalar inputs have compatible types.

Behavioral invariants

  • Adjacent output values differ by step; the limit is excluded.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Range(0, 4, 1) gives [0, 1, 2, 3].

Related operations

References

ONNX Range ↗
I.7OneHotReplace each category index with a vector marking its selected category.

What it is

Replace each category index with a vector marking its selected category.

Purpose

Represent discrete labels or categories as indicator vectors.

Common uses

  • Encode category 2 at depth 4 as [0, 0, 1, 0].
Tensor and behavior contract

Inputs

Integer indices, category depth, and off/on scalar values.

Outputs

Input shape with a category axis inserted.

Parameters

  • Category-axis position.

Shape and rank constraints

  • Depth is positive; out-of-range index handling is declared.

Behavioral invariants

  • A valid index selects exactly one on-value in its output vector.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Encode category 2 at depth 4 as [0, 0, 1, 0].

Related operations

References

ONNX OneHot ↗
I.7ShapeOfRead the dimensions of a tensor as integer graph values.

What it is

Read the dimensions of a tensor as integer graph values.

Purpose

Build shape-dependent tensor transformations.

Common uses

  • Read [2, 8, 16] from a tensor of that shape.
Tensor and behavior contract

Inputs

Tensor X.

Outputs

Integer vector containing the selected dimensions.

Parameters

  • Optional start and end dimension bounds.

Shape and rank constraints

  • Dimension bounds follow the declared rank convention.

Behavioral invariants

  • The output describes shape, not the tensor data values.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Read [2, 8, 16] from a tensor of that shape.

Related operations

References

ONNX Shape ↗
I.7SizeReturn the number of elements in a tensor.

What it is

Return the number of elements in a tensor.

Purpose

Compute graph-visible element counts.

Common uses

  • A tensor of shape [2, 3] has size 6.
Tensor and behavior contract

Inputs

Tensor X.

Outputs

Integer scalar.

Parameters

  • None.

Shape and rank constraints

  • The count is representable in the declared integer output type.

Behavioral invariants

  • The count equals the product of the dimensions, with scalar size one.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • A tensor of shape [2, 3] has size 6.

Related operations

References

ONNX Size ↗
I.7CastConvert each element into a declared numeric representation.

What it is

Convert each element into a declared numeric representation.

Purpose

Change numeric types at graph boundaries.

Common uses

  • Convert float32 activations to float16.
Tensor and behavior contract

Inputs

Numeric tensor X.

Outputs

Tensor of the same shape with the target element type.

Parameters

  • Target type and explicit rounding or saturation policy.

Shape and rank constraints

  • The source-to-target conversion is defined.

Behavioral invariants

  • Shape is preserved; conversion can lose precision.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Convert float32 activations to float16.

Related operations

References

ONNX Cast ↗
I.7BitcastReinterpret the bits of each element as an equal-width numeric type.

What it is

Reinterpret the bits of each element as an equal-width numeric type.

Purpose

Inspect or transform numeric representations without value conversion.

Common uses

  • Interpret the float32 bits of 1.0 as an int32 bit pattern.
Tensor and behavior contract

Inputs

Numeric tensor X.

Outputs

Tensor of the same shape with the target element type.

Parameters

  • Target type and little-endian byte interpretation.

Shape and rank constraints

  • Source and target element widths are equal.

Behavioral invariants

  • Every underlying bit is preserved.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Interpret the float32 bits of 1.0 as an int32 bit pattern.

Related operations

I.8IfExecute one of two graph branches according to a scalar condition.

What it is

Execute one of two graph branches according to a scalar condition.

Purpose

Represent conditional model computation.

Common uses

  • Run an expert branch when its routing condition is true.
Tensor and behavior contract

Inputs

Boolean scalar and values captured by two branch graphs.

Outputs

Outputs of the selected branch.

Parameters

  • Then-branch and else-branch graphs.

Shape and rank constraints

  • Branches return matching output counts and compatible element types and shape unions.

Behavioral invariants

  • Only the selected graph region supplies the outputs.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Run an expert branch when its routing condition is true.

Related operations

References

ONNX If ↗
I.8LoopRepeat a graph body until its condition becomes false or its iteration limit is reached.

What it is

Repeat a graph body until its condition becomes false or its iteration limit is reached.

Purpose

Represent dynamic iteration with explicit carried state.

Common uses

  • Iteratively refine predictions until a stop condition is reached.
Tensor and behavior contract

Inputs

Optional iteration limit, optional initial condition, and carried values.

Outputs

Final carried values and optional stacked per-iteration outputs.

Parameters

  • Body graph.

Shape and rank constraints

  • Body inputs and carried outputs obey a compatible type and state contract.

Behavioral invariants

  • Carried state for iteration t+1 comes from iteration t.

Semantics

State is explicit; determinism and randomness follow the declared body graph.

Examples

  • Iteratively refine predictions until a stop condition is reached.

Related operations

References

ONNX Loop ↗
I.8ScanApply a graph body to successive sequence slices while carrying explicit state.

What it is

Apply a graph body to successive sequence slices while carrying explicit state.

Purpose

Express a general recurrent or sequence-processing graph.

Common uses

  • Apply a recurrent cell to every token and collect its hidden states.
Tensor and behavior contract

Inputs

Initial states and scan-input tensors.

Outputs

Final states and collected per-step outputs.

Parameters

  • Body graph, input/output axes, scan directions.

Shape and rank constraints

  • Scan inputs have matching sequence lengths and compatible body slice types.

Behavioral invariants

  • The scan length and declared directions determine the body-call order.

Semantics

State is explicit; body operations determine parameter use, randomness, and differentiation.

Examples

  • Apply a recurrent cell to every token and collect its hidden states.

Related operations

References

ONNX Scan ↗

Linear Projections & Embeddings

Scope

Operations whose primary effect is a linear map between vector spaces, optionally followed by simple bias addition. This includes dense layers, structured linear transforms, and embedding lookups. Dense-with-bias is represented by the composition MatMul → broadcast Add; its familiar dense names do not define another atomic species.

8 entries
II.1MatMulPure matrix multiplication without bias. Takes two matrices and multiplies them following standard linear algebra rules.

What it is

Pure matrix multiplication without bias. Takes two matrices and multiplies them following standard linear algebra rules.

Purpose

The mathematical foundation of many neural network operations. Used whenever you need to combine or transform features through multiplication.

Common uses

  • Atomic matrix product inside dense-with-bias compositions, attention, and other layers
  • Combining different representations
  • Projecting data into new coordinate systems
  • Implementing mathematical operations that can be expressed as matrix products

What it's NOT

  • Not element-wise multiplication – MatMul combines across dimensions; element-wise multiplies corresponding positions
  • Not bias addition – A dense-with-bias alias connects this product to atomic Add; using a matrix as learned weights does not create a new matrix-product primitive
  • Not convolution – While convolution can be expressed as matrix multiplication, it has different semantics

Analogy

Like a factory production line where raw materials (inputs) go through a transformation machine (weight matrix) to become products (outputs). The machine's configuration determines what comes out.

II.3EmbeddingLookupConverts discrete IDs (like word IDs or categorical values) into continuous vectors by looking them up in a learned table. Each ID gets its own learned vector.

What it is

Converts discrete IDs (like word IDs or categorical values) into continuous vectors by looking them up in a learned table. Each ID gets its own learned vector.

Purpose

Representing discrete items (words, categories, users, items) as continuous vectors that can be used in neural networks. The vectors learn to capture semantic relationships.

Common uses

  • Word embeddings in natural language processing (converting words to vectors)
  • User/item embeddings in recommendation systems
  • Categorical feature representations
  • Any situation where discrete identities need continuous representations

What it's NOT

  • Not one-hot encoding – Embeddings are learned dense vectors; one-hot creates sparse fixed vectors
  • Not feature extraction – Embeddings are learned representations, not extracted features
  • Not compression – While embeddings can be smaller than one-hot, that's not their primary purpose

Analogy

Like a phonebook where you look up a name (ID) and get back a full address and phone number (vector). Each person has their own unique entry, and you learn what information to store for each.

II.3PositionalEmbeddingProvides position-specific vectors that encode where something appears in a sequence. Tells the network "this is the 1st item," "this is the 2nd item," etc.

What it is

Provides position-specific vectors that encode where something appears in a sequence. Tells the network "this is the 1st item," "this is the 2nd item," etc.

Purpose

Many neural architectures (especially transformers) process all positions simultaneously and lose track of order. Positional embeddings restore that order information.

Common uses

  • Transformer models (like BERT, GPT) that need position information
  • Any architecture that processes sequences in parallel
  • Time-series models that need temporal position information
  • Grid-based models that need spatial position information

What it's NOT

  • Not timestamp encoding – Encodes relative position, not absolute time
  • Not content-based – Position embeddings depend only on position, not on what's there
  • Not the same as RNN hidden states – This is explicit position info; RNNs implicitly track position

Analogy

Like seat numbers in a theater. Seat B-12 is B-12 regardless of who sits there. Positional embeddings give each position its own "seat number" vector.

II.2LowRankProjectionApproximates a large weight matrix using two smaller matrices multiplied together. Reduces parameters while maintaining expressiveness for many tasks.

What it is

Approximates a large weight matrix using two smaller matrices multiplied together. Reduces parameters while maintaining expressiveness for many tasks.

Purpose

Compressing models by exploiting the fact that many weight matrices have low intrinsic dimensionality. Fewer parameters, faster computation.

Common uses

  • Compressing large language models
  • Adapter layers in transfer learning (LoRA)
  • Reducing parameters in attention mechanisms
  • Memory-efficient fine-tuning

What it's NOT

  • Not pruning – Restructures the matrix, doesn't zero out weights
  • Not quantization – Uses full precision but fewer total values
  • Not always lossless – Trades some capacity for efficiency

Analogy

Like summarizing a detailed map with simpler directions. Instead of storing every street, you store major routes (low rank) and can still get most places.

II.3MultiHotEmbeddingLike regular embedding lookup, but for cases where each position has multiple active IDs simultaneously. Averages or sums the embeddings for all active IDs.

What it is

Like regular embedding lookup, but for cases where each position has multiple active IDs simultaneously. Averages or sums the embeddings for all active IDs.

Purpose

Representing cases where multiple discrete features are active at once, like multiple tags on a document or multiple ingredients in a recipe.

Common uses

  • Multi-label classification (document with multiple categories)
  • Recommendation systems (user with multiple interests)
  • Items with multiple attributes
  • Feature combinations in categorical data

What it's NOT

  • Not one-hot embedding – Multiple positions can be active, not just one
  • Not multi-output embedding – Still produces one vector, just from multiple inputs
  • Not attention – Simple averaging/summing, not weighted by learned attention

Analogy

Like describing a meal by averaging the flavor profiles of all its ingredients, rather than just picking the main ingredient.

II.1EinsumCombine tensors according to named multiplication and summation indices.

What it is

Combine tensors according to named multiplication and summation indices.

Purpose

Describe explicit tensor contractions and their compositions.

Common uses

  • Use ij,jk->ik for a matrix product.
Tensor and behavior contract

Inputs

One or more numeric tensors and a contraction equation.

Outputs

Tensor whose axes are specified by the equation.

Y[output indices] = sum(contracted indices, product(operands))

Parameters

  • Subscript equation and ellipsis broadcasting.

Shape and rank constraints

  • Repeated and contracted labels obey compatible dimension sizes.

Behavioral invariants

  • The equation determines both reduced indices and output ordering.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Use ij,jk->ik for a matrix product.

Related operations

References

ONNX Einsum ↗
II.1BilinearCombine two feature vectors through a learned three-axis weight tensor and optional bias.

What it is

Combine two feature vectors through a learned three-axis weight tensor and optional bias.

Purpose

Model pairwise feature interactions.

Common uses

  • Score a relation between two entity embeddings.
Tensor and behavior contract

Inputs

X[..., I], Z[..., J], W[O, I, J], and optional b[O].

Outputs

Y[..., O].

Y[..., o] = sum(i,j, X[..., i] * W[o,i,j] * Z[..., j]) + b[o]

Parameters

  • Output width and optional bias.

Shape and rank constraints

  • Leading input dimensions agree and feature widths match W.

Behavioral invariants

  • The map is bilinear in X and Z before optional bias addition.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Score a relation between two entity embeddings.

Related operations

II.3EmbeddingBagLook up a bag of embedding rows and combine them without retaining every row.

What it is

Look up a bag of embedding rows and combine them without retaining every row.

Purpose

Build compact representations for sets or bags of IDs.

Common uses

  • Average the word embeddings in each document.
Tensor and behavior contract

Inputs

Integer IDs, learned embedding table [V, D], bag offsets, and optional sample weights.

Outputs

One D-dimensional vector per bag.

Parameters

  • Sum, mean, or maximum reduction; padding ID.

Shape and rank constraints

  • IDs are valid table rows and offsets define valid bags.

Behavioral invariants

  • Output count equals the number of bags.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Average the word embeddings in each document.

Related operations

Local Spatial & Signal Neighborhoods

Scope

Operations that compute over local neighborhoods in space, time, or other structured domains. This includes convolutions, pooling, up/down-sampling, and classical signal transforms when applied locally.

38 entries
III.1Conv2DSlides a small pattern-detector (kernel) across a 2D image, computing how much the kernel matches each local region. Like checking every spot in an image for a specific feature.

What it is

Slides a small pattern-detector (kernel) across a 2D image, computing how much the kernel matches each local region. Like checking every spot in an image for a specific feature.

Purpose

Detecting local patterns (edges, textures, shapes) while being invariant to exactly where they appear. The foundation of computer vision.

Common uses

  • Building convolutional neural networks for image classification
  • Detecting edges, corners, and textures in images
  • Creating feature maps that capture visual patterns
  • Any task involving spatial data (images, video, maps)

What it's NOT

  • Not fully-connected – Convolution only looks at local neighborhoods, not all inputs
  • Not pooling – Convolution uses learned patterns; pooling uses fixed operations (max, average)
  • Not template matching – While similar in spirit, convolution is differentiable and learns optimal patterns

Analogy

Like checking every 3×3 square in a puzzle to see if it matches certain patterns you're looking for (vertical edge, horizontal edge, corner, etc.). You slide your pattern-checker across the whole puzzle.

III.1DepthwiseConv2DConvolution where each channel is processed separately, rather than mixing all channels together. Like having independent filters for red, green, and blue in an RGB image.

What it is

Convolution where each channel is processed separately, rather than mixing all channels together. Like having independent filters for red, green, and blue in an RGB image.

Purpose

Efficiency—reduces computation while often maintaining performance. First step in separable convolutions.

Common uses

  • Mobile and efficient neural network architectures (MobileNet)
  • First stage of depthwise-separable convolutions
  • Situations where channel-mixing and spatial-filtering should be separate
  • Resource-constrained environments

What it's NOT

  • Not regular convolution – Doesn't mix channels, processes each independently
  • Not channel-wise pooling – Still uses learned kernels, not fixed pooling operations
  • Not pointwise convolution – Depthwise has spatial kernels; pointwise is 1×1

Analogy

Imagine processing a color photo. Regular convolution uses all three color channels together. Depthwise convolution processes red, green, and blue separately with their own filters.

III.1PointwiseConv2DA 1×1 convolution that mixes channels at each spatial position without looking at neighbors. Like remixing colors at each pixel independently.

What it is

A 1×1 convolution that mixes channels at each spatial position without looking at neighbors. Like remixing colors at each pixel independently.

Purpose

Changing the number of channels, learning optimal channel combinations, reducing or expanding dimensionality.

Common uses

  • Changing feature map depth (reducing 256 channels to 64, etc.)
  • Second stage of depthwise-separable convolutions
  • Bottleneck layers in efficient architectures
  • Learning optimal combinations of features

What it's NOT

  • Not spatial convolution – Pointwise only mixes channels, doesn't look at spatial neighbors
  • Not just dimension reduction – While it can reduce dimensions, it learns how to do so optimally
  • Not a dense-with-bias composition – Works on spatial feature maps, although both use weighted combinations

Analogy

Like having multiple paint colors at each spot and mixing them according to learned recipes—each location gets its own custom color mix, but the mixing doesn't consider neighboring spots.

III.2MaxPool2DDivides an image into rectangular regions and keeps only the maximum value from each region. Like summarizing each neighborhood by its strongest signal.

What it is

Divides an image into rectangular regions and keeps only the maximum value from each region. Like summarizing each neighborhood by its strongest signal.

Purpose

Reducing spatial size while keeping the most prominent features. Creates invariance to small shifts and reduces computational cost.

Common uses

  • Downsampling feature maps in convolutional networks
  • Building hierarchical feature representations
  • Creating translation invariance
  • Reducing computational cost and memory

What it's NOT

  • Not average pooling – Takes maximum, not average
  • Not convolution – Uses a fixed operation (max), doesn't learn patterns
  • Not dropout – Deterministically selects maximum, doesn't randomly drop

Analogy

Like surveying a neighborhood by dividing it into blocks and asking "what's the tallest building in each block?" You get a coarser but still informative map.

III.2AvgPool2DDivides an image into regions and computes the average value in each region. Like summarizing each neighborhood by its typical value.

What it is

Divides an image into regions and computes the average value in each region. Like summarizing each neighborhood by its typical value.

Purpose

Reducing spatial size while smoothly blending information. Less sensitive to outliers than max pooling.

Common uses

  • Downsampling feature maps with smooth transitions
  • Global average pooling (reducing entire feature maps to single values)
  • Creating smoother feature hierarchies than max pooling
  • Situations where average activation is more meaningful than maximum

What it's NOT

  • Not max pooling – Uses average, not maximum
  • Not Gaussian smoothing – Simple average, not weighted by distance
  • Not interpolation – Reduces size, doesn't estimate intermediate values

Analogy

Instead of finding the tallest building per neighborhood block, you compute the average building height. Gives a smoother representation.

III.2GlobalAveragePoolingReduces each feature map to a single number by averaging all spatial positions. Collapses all spatial dimensions into one global summary per channel.

What it is

Reduces each feature map to a single number by averaging all spatial positions. Collapses all spatial dimensions into one global summary per channel.

Purpose

Converting spatial feature maps into fixed-size vectors for classification, while maintaining translation invariance.

Common uses

  • Final layer before classification (alternative to flattening + dense)
  • Reducing spatial feature maps to global descriptors
  • Enforcing translation invariance for entire objects
  • Reducing parameters compared to fully-connected layers

What it's NOT

  • Not flatten – Averages across space; flatten keeps all spatial positions
  • Not attention-based pooling – Uses uniform averaging, not learned importance
  • Not max pooling – Uses average of all positions, not maximum

Analogy

Like describing a photograph by the average color in the whole image. You lose spatial detail but get a summary that doesn't depend on exact positioning.

III.1Conv1DConvolution along a single dimension, typically time. Slides a pattern-detector across a sequence looking for local patterns.

What it is

Convolution along a single dimension, typically time. Slides a pattern-detector across a sequence looking for local patterns.

Purpose

Detecting local patterns in sequences like audio, time series, or text. The 1D equivalent of image convolution.

Common uses

  • Audio processing and speech recognition
  • Time series analysis
  • Text processing (character or word level)
  • Any sequential data with local structure

What it's NOT

  • Not 2D convolution – Only one spatial/temporal dimension
  • Not RNN – Parallel processing, not sequential; no hidden state
  • Not fully-connected – Only looks at local windows

Analogy

Like reading a book with a sliding window that looks at 5 words at a time, detecting patterns like "very good" or "not bad" as it slides along.

III.1Conv3DConvolution across three dimensions—typically height, width, and depth/time. Detects patterns in 3D volumes or video.

What it is

Convolution across three dimensions—typically height, width, and depth/time. Detects patterns in 3D volumes or video.

Purpose

Processing volumetric data like medical scans, video sequences, or 3D shapes.

Common uses

  • Video action recognition
  • Medical image analysis (CT/MRI scans)
  • 3D object recognition
  • Spatio-temporal pattern detection

What it's NOT

  • Not just stacked 2D convolutions – True 3D kernels capture volumetric patterns
  • Not significantly different in concept – Same idea as 2D, just higher dimensional
  • Not memory-free – Much more expensive than 2D due to extra dimension

Analogy

Like checking every cube in a 3D puzzle to see if it matches certain 3D patterns, rather than just checking flat patterns on surfaces.

III.3NearestNeighborUpsample2DMakes an image larger by repeating each pixel multiple times. The simplest upsampling method.

What it is

Makes an image larger by repeating each pixel multiple times. The simplest upsampling method.

Purpose

Increasing spatial resolution when you need quick, simple upsampling without interpolation artifacts.

Common uses

  • Quick resizing in image generators
  • Upsampling in decoder networks
  • Pixelated, blocky upscaling (sometimes desired aesthetic)
  • First step before refinement layers

What it's NOT

  • Not bilinear/bicubic – Doesn't interpolate, just repeats pixels
  • Not deconvolution – Doesn't learn, just duplicates
  • Not anti-aliased – Creates blocky results, not smooth

Analogy

Like zooming in on a pixel art image—each original pixel becomes a block of identical pixels.

III.3BilinearResize2DResizes images using linear interpolation between pixels. Creates smooth transitions when enlarging or shrinking.

What it is

Resizes images using linear interpolation between pixels. Creates smooth transitions when enlarging or shrinking.

Purpose

Changing image size while maintaining smooth appearance, avoiding the blockiness of nearest-neighbor.

Common uses

  • Preprocessing images to standard sizes
  • Smooth upsampling in generators
  • Matching feature map sizes
  • Creating image pyramids

What it's NOT

  • Not nearest-neighbor – Interpolates, doesn't repeat
  • Not bicubic – Uses linear (not cubic) interpolation
  • Not learned – Fixed mathematical interpolation, not trainable

Analogy

Like stretching a rubber sheet with a photo on it—the image smoothly expands, with new pixels created by blending neighboring ones.

III.1ConvTranspose2DAlso called "deconvolution." Reverses the spatial transformation of convolution, often used to upsample feature maps.

What it is

Also called "deconvolution." Reverses the spatial transformation of convolution, often used to upsample feature maps.

Purpose

Learned upsampling that can restore spatial resolution while learning what patterns to generate.

Common uses

  • Decoder networks in autoencoders
  • Image generation and super-resolution
  • Semantic segmentation (upsampling to pixel-level predictions)
  • Any architecture needing learned upsampling

What it's NOT

  • Not truly inverse convolution – Approximates it but doesn't perfectly invert
  • Not simple resizing – Uses learned kernels, not fixed interpolation
  • Not artifact-free – Can create checkerboard patterns if not carefully designed

Analogy

Like having a compression algorithm that not only decompresses but learns what kind of details to add back in based on training.

III.1ConvTranspose1DApply the transposed linear mapping of a 1-dimensional convolution.

What it is

Apply the transposed linear mapping of a 1-dimensional convolution.

Purpose

Learn an increase in spatial resolution.

Common uses

  • Expand a signal in a decoder.
Tensor and behavior contract

Inputs

Features [N, C_in, spatial...] and learned convolution weights.

Outputs

Features [N, C_out, expanded spatial...].

Parameters

  • Kernel size, stride, dilation, groups, padding, output padding, optional bias.

Shape and rank constraints

  • Input spatial rank is 1; channels and groups match the weights.

Behavioral invariants

  • The operation is a convolution transpose, not a general inverse convolution.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Expand a signal in a decoder.

Related operations

III.1ConvTranspose3DApply the transposed linear mapping of a 3-dimensional convolution.

What it is

Apply the transposed linear mapping of a 3-dimensional convolution.

Purpose

Learn an increase in spatial resolution.

Common uses

  • Expand a volume in a decoder.
Tensor and behavior contract

Inputs

Features [N, C_in, spatial...] and learned convolution weights.

Outputs

Features [N, C_out, expanded spatial...].

Parameters

  • Kernel size, stride, dilation, groups, padding, output padding, optional bias.

Shape and rank constraints

  • Input spatial rank is 3; channels and groups match the weights.

Behavioral invariants

  • The operation is a convolution transpose, not a general inverse convolution.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Expand a volume in a decoder.

Related operations

III.1DeformConv2DMove convolution sampling points using explicit offsets before combining their values.

What it is

Move convolution sampling points using explicit offsets before combining their values.

Purpose

Adapt local image features to changing object geometry.

Common uses

  • Follow a curved object boundary with learned offsets.
Tensor and behavior contract

Inputs

Image X[N,C,H,W], weights, offsets, and optional modulation mask and bias.

Outputs

Convolved feature map.

Parameters

  • Stride, dilation, padding, weight groups, offset groups.

Shape and rank constraints

  • Offset channels and spatial shape match the kernel sampling grid and group counts.

Behavioral invariants

  • Zero offsets and unit modulation recover the corresponding ordinary convolution.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Follow a curved object boundary with learned offsets.

Related operations

III.2MaxPooling1DCompute the maximum in each sliding 1-dimensional window.

What it is

Compute the maximum in each sliding 1-dimensional window.

Purpose

Reduce spatial resolution while retaining local summaries.

Common uses

  • Pool a temporal signal.
Tensor and behavior contract

Inputs

Features [N,C,spatial...].

Outputs

Pooled features and optional maximum indices.

Parameters

  • Window size, stride, padding, dilation where supported, ceil mode.

Shape and rank constraints

  • The spatial rank is 1; window and stride components are positive.

Behavioral invariants

  • Each output summarizes only its declared input window.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Pool a temporal signal.

Related operations

III.2MaxPooling3DCompute the maximum in each sliding 3-dimensional window.

What it is

Compute the maximum in each sliding 3-dimensional window.

Purpose

Reduce spatial resolution while retaining local summaries.

Common uses

  • Pool a 3D feature volume.
Tensor and behavior contract

Inputs

Features [N,C,spatial...].

Outputs

Pooled features and optional maximum indices.

Parameters

  • Window size, stride, padding, dilation where supported, ceil mode.

Shape and rank constraints

  • The spatial rank is 3; window and stride components are positive.

Behavioral invariants

  • Each output summarizes only its declared input window.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Pool a 3D feature volume.

Related operations

III.2AveragePooling1DCompute the average in each sliding 1-dimensional window.

What it is

Compute the average in each sliding 1-dimensional window.

Purpose

Reduce spatial resolution while retaining local summaries.

Common uses

  • Pool a temporal signal.
Tensor and behavior contract

Inputs

Features [N,C,spatial...].

Outputs

Pooled features.

Parameters

  • Window size, stride, padding, dilation where supported, ceil mode.

Shape and rank constraints

  • The spatial rank is 1; window and stride components are positive.

Behavioral invariants

  • Each output summarizes only its declared input window.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Pool a temporal signal.

Related operations

III.2AveragePooling3DCompute the average in each sliding 3-dimensional window.

What it is

Compute the average in each sliding 3-dimensional window.

Purpose

Reduce spatial resolution while retaining local summaries.

Common uses

  • Pool a 3D feature volume.
Tensor and behavior contract

Inputs

Features [N,C,spatial...].

Outputs

Pooled features.

Parameters

  • Window size, stride, padding, dilation where supported, ceil mode.

Shape and rank constraints

  • The spatial rank is 3; window and stride components are positive.

Behavioral invariants

  • Each output summarizes only its declared input window.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Pool a 3D feature volume.

Related operations

III.2AdaptiveMaxPoolingChoose pooling windows from a target spatial shape and take each window's maximum.

What it is

Choose pooling windows from a target spatial shape and take each window's maximum.

Purpose

Produce a fixed-size spatial summary from variable input sizes.

Common uses

  • Convert variable-size image features to a 7 by 7 grid.
Tensor and behavior contract

Inputs

Features [N,C,spatial...].

Outputs

Features [N,C,target spatial...].

Parameters

  • Target spatial shape.

Shape and rank constraints

  • Target dimensions are positive and spatial rank is declared.

Behavioral invariants

  • Every output bin uses the declared adaptive partition of input positions.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Convert variable-size image features to a 7 by 7 grid.

Related operations

III.2AdaptiveAveragePoolingChoose pooling windows from a target spatial shape and take each window's average.

What it is

Choose pooling windows from a target spatial shape and take each window's average.

Purpose

Produce a fixed-size spatial summary from variable input sizes.

Common uses

  • Convert variable-size image features to a 7 by 7 grid.
Tensor and behavior contract

Inputs

Features [N,C,spatial...].

Outputs

Features [N,C,target spatial...].

Parameters

  • Target spatial shape.

Shape and rank constraints

  • Target dimensions are positive and spatial rank is declared.

Behavioral invariants

  • Every output bin uses the declared adaptive partition of input positions.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Convert variable-size image features to a 7 by 7 grid.

Related operations

III.2ReduceProductMultiply values along selected axes.

What it is

Multiply values along selected axes.

Purpose

Compute products of factors or probabilities.

Common uses

  • Reduce feature vectors along their final axis.
Tensor and behavior contract

Inputs

Numeric tensor X.

Outputs

Reduction result with selected axes removed or retained as size one.

product(X)

Parameters

  • Reduction axes and keep-dimensions flag.

Shape and rank constraints

  • Axes are valid and unique; the input type supports the declared reduction.

Behavioral invariants

  • Only declared axes are reduced.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Reduce feature vectors along their final axis.

Related operations

III.2ReduceL1Sum the absolute values along selected axes.

What it is

Sum the absolute values along selected axes.

Purpose

Measure vector magnitude or absolute error.

Common uses

  • Reduce feature vectors along their final axis.
Tensor and behavior contract

Inputs

Numeric tensor X.

Outputs

Reduction result with selected axes removed or retained as size one.

sum(abs(X))

Parameters

  • Reduction axes and keep-dimensions flag.

Shape and rank constraints

  • Axes are valid and unique; the input type supports the declared reduction.

Behavioral invariants

  • Only declared axes are reduced.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Reduce feature vectors along their final axis.

Related operations

III.2ReduceL2Take the square root of the sum of squared values along selected axes.

What it is

Take the square root of the sum of squared values along selected axes.

Purpose

Measure Euclidean magnitude.

Common uses

  • Reduce feature vectors along their final axis.
Tensor and behavior contract

Inputs

Numeric tensor X.

Outputs

Reduction result with selected axes removed or retained as size one.

sqrt(sum(abs(X)^2))

Parameters

  • Reduction axes and keep-dimensions flag.

Shape and rank constraints

  • Axes are valid and unique; the input type supports the declared reduction.

Behavioral invariants

  • Only declared axes are reduced.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Reduce feature vectors along their final axis.

Related operations

III.2ReduceLogSumExpCombine log-space values with a stable logarithm of a sum of exponentials.

What it is

Combine log-space values with a stable logarithm of a sum of exponentials.

Purpose

Normalize log probabilities without avoidable numerical overflow.

Common uses

  • Reduce feature vectors along their final axis.
Tensor and behavior contract

Inputs

Numeric tensor X.

Outputs

Reduction result with selected axes removed or retained as size one.

log(sum(exp(X)))

Parameters

  • Reduction axes and keep-dimensions flag.

Shape and rank constraints

  • Axes are valid and unique; the input type supports the declared reduction.

Behavioral invariants

  • Only declared axes are reduced.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Reduce feature vectors along their final axis.

Related operations

III.2ReduceVarianceMeasure average squared deviation from the mean.

What it is

Measure average squared deviation from the mean.

Purpose

Summarize the distribution of activation or error values.

Common uses

  • Measure the dispersion or middle value of a feature channel.
Tensor and behavior contract

Inputs

Real-valued tensor X and quantiles where applicable.

Outputs

Statistical reduction values.

sum((X - mean(X))^2) / (count - correction)

Parameters

  • Axes, keep-dimensions, degrees-of-freedom correction.

Shape and rank constraints

  • Reduction axes are valid and sample count exceeds the variance correction.

Behavioral invariants

  • The declared interpolation or correction rule is part of the operation contract.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Measure the dispersion or middle value of a feature channel.

Related operations

III.2ReduceStandardDeviationMeasure spread in the same units as the input.

What it is

Measure spread in the same units as the input.

Purpose

Summarize the distribution of activation or error values.

Common uses

  • Measure the dispersion or middle value of a feature channel.
Tensor and behavior contract

Inputs

Real-valued tensor X and quantiles where applicable.

Outputs

Statistical reduction values.

sqrt(variance(X))

Parameters

  • Axes, keep-dimensions, degrees-of-freedom correction.

Shape and rank constraints

  • Reduction axes are valid and sample count exceeds the variance correction.

Behavioral invariants

  • The declared interpolation or correction rule is part of the operation contract.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Measure the dispersion or middle value of a feature channel.

Related operations

III.2ReduceMedianChoose the middle ordered value along an axis.

What it is

Choose the middle ordered value along an axis.

Purpose

Summarize the distribution of activation or error values.

Common uses

  • Measure the dispersion or middle value of a feature channel.
Tensor and behavior contract

Inputs

Real-valued tensor X and quantiles where applicable.

Outputs

Statistical reduction values.

lower middle value of sorted(X)

Parameters

  • Axis, keep-dimensions, explicit lower-middle rule for even counts.

Shape and rank constraints

  • The reduced axis is valid and nonempty; an even-length axis selects the lower middle value.

Behavioral invariants

  • The declared interpolation or correction rule is part of the operation contract.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Measure the dispersion or middle value of a feature channel.

Related operations

III.2ReduceQuantileFind values at declared fractions of the ordered input.

What it is

Find values at declared fractions of the ordered input.

Purpose

Summarize the distribution of activation or error values.

Common uses

  • Measure the dispersion or middle value of a feature channel.
Tensor and behavior contract

Inputs

Real-valued tensor X and quantiles where applicable.

Outputs

Statistical reduction values.

quantile(X, q)

Parameters

  • Quantiles, axis, keep-dimensions, interpolation rule.

Shape and rank constraints

  • The reduced axis is valid and nonempty; each quantile lies in [0,1].

Behavioral invariants

  • The declared interpolation or correction rule is part of the operation contract.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Measure the dispersion or middle value of a feature channel.

Related operations

III.2CountNonZeroCount values that differ from zero along selected axes.

What it is

Count values that differ from zero along selected axes.

Purpose

Measure sparsity or active positions.

Common uses

  • Count active neurons per example.
Tensor and behavior contract

Inputs

Numeric or boolean tensor X.

Outputs

Integer counts.

Parameters

  • Axes and keep-dimensions flag.

Shape and rank constraints

  • Axes are valid and counts fit the output integer type.

Behavioral invariants

  • Each count is between zero and the number of reduced elements.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Count active neurons per example.

Related operations

III.3SpaceToDepthMove regularly spaced spatial blocks into channels without changing values.

What it is

Move regularly spaced spatial blocks into channels without changing values.

Purpose

Trade spatial resolution for channel capacity.

Common uses

  • Move a 2 by 2 pixel block into four channels.
Tensor and behavior contract

Inputs

Image X[N,C,H,W].

Outputs

Tensor [N,C*b*b,H/b,W/b].

Parameters

  • Positive integer block size b.

Shape and rank constraints

  • H and W are divisible by b.

Behavioral invariants

  • Element count and values are preserved; the declared layout reverses PixelShuffle.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Move a 2 by 2 pixel block into four channels.

Related operations

III.3MaxUnpoolPlace pooled values at the recorded positions of their maximum-pooling winners.

What it is

Place pooled values at the recorded positions of their maximum-pooling winners.

Purpose

Restore a sparse spatial layout in a decoder.

Common uses

  • Restore selected image features using stored MaxPool indices.
Tensor and behavior contract

Inputs

Pooled values and matching integer pooling indices.

Outputs

Larger tensor with selected positions filled and other positions zero.

Parameters

  • Output shape, pooling kernel, stride, and padding.

Shape and rank constraints

  • Indices belong to the declared output shape and correspond to the matching pooling convention.

Behavioral invariants

  • This operation cannot reconstruct values discarded by pooling.

Semantics

Overlapping repeated output indices require an explicitly declared collision policy.

Examples

  • Restore selected image features using stored MaxPool indices.

Related operations

III.3GridSampleRead an image or volume at supplied fractional coordinates using a declared interpolation rule.

What it is

Read an image or volume at supplied fractional coordinates using a declared interpolation rule.

Purpose

Warp spatial features or apply a learned geometric transform.

Common uses

  • Warp image features using an optical-flow grid.
Tensor and behavior contract

Inputs

X[N,C,spatial...] and grid[N,output spatial...,spatial rank].

Outputs

Y[N,C,output spatial...].

Parameters

  • Interpolation mode, padding mode, align-corners convention.

Shape and rank constraints

  • Grid rank matches spatial rank and its coordinates use the declared normalization.

Behavioral invariants

  • Sampling preserves the batch and channel axes.

Semantics

Forward sampling is defined by its coordinates; parallel backward accumulation can be order-dependent.

Examples

  • Warp image features using an optical-flow grid.

Related operations

III.3RoiAlignSample aligned feature regions into fixed-size grids without rounding their boundaries.

What it is

Sample aligned feature regions into fixed-size grids without rounding their boundaries.

Purpose

Extract object-region features for detection and segmentation.

Common uses

  • Extract a 7 by 7 feature grid for each proposed object.
Tensor and behavior contract

Inputs

Feature map [N,C,H,W], regions [R,4], and region batch indices [R].

Outputs

Region features [R,C,H_out,W_out].

Parameters

  • Output size, spatial scale, samples per bin, coordinate convention, average or maximum mode.

Shape and rank constraints

  • Regions and batch indices follow the declared image coordinate convention.

Behavioral invariants

  • Fractional region coordinates are retained during bilinear sampling.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Extract a 7 by 7 feature grid for each proposed object.

Related operations

III.3AffineGridConstruct normalized sampling coordinates by applying an affine map to a regular grid.

What it is

Construct normalized sampling coordinates by applying an affine map to a regular grid.

Purpose

Prepare an image or volume warp.

Common uses

  • Generate a rotation grid before GridSample.
Tensor and behavior contract

Inputs

Affine matrices [N,2,3] or [N,3,4] and requested output size.

Outputs

Coordinate grid [N,output spatial...,2 or 3].

Parameters

  • Output size and align-corners convention.

Shape and rank constraints

  • The matrix width is one greater than the declared spatial rank.

Behavioral invariants

  • An identity affine map produces the matching identity sampling grid.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Generate a rotation grid before GridSample.

Related operations

III.4InverseSTFTReconstruct a signal from overlapping short-time Fourier frames using inverse transforms and overlap-add.

What it is

Reconstruct a signal from overlapping short-time Fourier frames using inverse transforms and overlap-add.

Purpose

Turn a processed spectrogram back into a waveform.

Common uses

  • Synthesize audio after modifying a spectrogram.
Tensor and behavior contract

Inputs

Complex frequency frames and a synthesis window.

Outputs

Real or complex reconstructed time signal.

Parameters

  • FFT size, hop length, window length, centering, normalization, output length.

Shape and rank constraints

  • Window and hop settings permit nonzero overlap-add normalization.

Behavioral invariants

  • Compatible unchanged STFT frames reconstruct the original signal within numerical precision.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Synthesize audio after modifying a spectrogram.

Related operations

III.4HannWindowGenerate a raised-cosine taper for a finite signal window.

What it is

Generate a raised-cosine taper for a finite signal window.

Purpose

Reduce boundary discontinuities during windowed spectral analysis.

Common uses

  • Multiply an audio frame by the window before STFT.
Tensor and behavior contract

Inputs

Integer window length N.

Outputs

One-dimensional real window of length N.

w[n] = 0.5 - 0.5*cos(2*pi*n/D)

Parameters

  • Periodic or symmetric mode and output type.

Shape and rank constraints

  • The small-length convention is declared; D is N for periodic windows and N-1 for symmetric windows.

Behavioral invariants

  • Coefficients depend only on their index and the declared window settings.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Multiply an audio frame by the window before STFT.

Related operations

III.4HammingWindowGenerate a cosine taper with a nonzero boundary coefficient.

What it is

Generate a cosine taper with a nonzero boundary coefficient.

Purpose

Reduce boundary discontinuities during windowed spectral analysis.

Common uses

  • Multiply an audio frame by the window before STFT.
Tensor and behavior contract

Inputs

Integer window length N.

Outputs

One-dimensional real window of length N.

w[n] = 0.54 - 0.46*cos(2*pi*n/D)

Parameters

  • Periodic or symmetric mode and output type.

Shape and rank constraints

  • The small-length convention is declared; D is N for periodic windows and N-1 for symmetric windows.

Behavioral invariants

  • Coefficients depend only on their index and the declared window settings.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Multiply an audio frame by the window before STFT.

Related operations

III.4BlackmanWindowGenerate a two-cosine taper for spectral analysis.

What it is

Generate a two-cosine taper for spectral analysis.

Purpose

Reduce boundary discontinuities during windowed spectral analysis.

Common uses

  • Multiply an audio frame by the window before STFT.
Tensor and behavior contract

Inputs

Integer window length N.

Outputs

One-dimensional real window of length N.

w[n] = 0.42 - 0.5*cos(2*pi*n/D) + 0.08*cos(4*pi*n/D)

Parameters

  • Periodic or symmetric mode and output type.

Shape and rank constraints

  • The small-length convention is declared; D is N for periodic windows and N-1 for symmetric windows.

Behavioral invariants

  • Coefficients depend only on their index and the declared window settings.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Multiply an audio frame by the window before STFT.

Related operations

Context & Sequence Modeling

Scope

Operations that explicitly model context, order, or temporal structure across positions. This includes attention mechanisms, sequence/state-space models, recurrent units, and explicit memory/cache operations.

12 entries
IV.1ScaledDotProductAttentionComputes how much each position should "pay attention to" every other position, then aggregates information based on those attention weights. The core mechanism of transformers.

What it is

Computes how much each position should "pay attention to" every other position, then aggregates information based on those attention weights. The core mechanism of transformers.

Purpose

Allowing each position to gather information from relevant positions anywhere in the sequence, with relevance determined by learned queries and keys.

Common uses

  • Core building block of transformer architectures
  • Implementing flexible, learned patterns of information flow
  • Capturing long-range dependencies in sequences
  • Enabling models to focus on relevant context

What it's NOT

  • Not convolution – Attention can connect any positions; convolution only looks locally
  • Not RNN – Processes all positions in parallel, doesn't maintain hidden state
  • Not simple weighted average – The weights are computed based on learned queries and keys

Analogy

Like a room full of people where each person decides who they want to listen to based on relevance, then hears a blend of what those relevant people are saying. Everyone can potentially listen to anyone.

IV.1MultiHeadAttentionRuns multiple independent attention mechanisms in parallel (heads), then combines their results. Like having multiple simultaneous conversations about different aspects of the data.

What it is

Runs multiple independent attention mechanisms in parallel (heads), then combines their results. Like having multiple simultaneous conversations about different aspects of the data.

Purpose

Allowing the model to attend to different types of information simultaneously (syntax, semantics, long-range, short-range, etc.).

Common uses

  • Transformer models (BERT, GPT, ViT, etc.)
  • Any architecture needing rich contextual understanding
  • Models that benefit from capturing multiple relationship types
  • Modern sequence-to-sequence architectures

What it's NOT

  • Not just multiple attention layers stacked – The heads run in parallel at the same layer, not sequentially
  • Not ensemble of models – The heads are trained jointly as one model
  • Not necessarily more attention on the same things – Different heads can learn different patterns

Analogy

Like having a team review a document where each person focuses on different aspects simultaneously—one checks grammar, one checks facts, one checks flow—then they combine their insights.

IV.1GroupedQueryAttention (GQA)A variant of multi-head attention where multiple query heads share the same key and value heads, reducing computational cost while maintaining most of the benefit.

What it is

A variant of multi-head attention where multiple query heads share the same key and value heads, reducing computational cost while maintaining most of the benefit.

Purpose

Achieving better efficiency than full multi-head attention while retaining more representational power than multi-query attention.

Common uses

  • Large language models where memory and computation are expensive
  • Situations balancing quality and efficiency
  • Production deployments of transformer models
  • Models that need many query perspectives but can share keys/values

What it's NOT

  • Not regular multi-head attention – Shares keys/values across query groups
  • Not multi-query attention – Has multiple key/value groups, not just one
  • Not a training trick – This is an architectural choice affecting the model permanently

Analogy

Like a library where instead of each student having their own complete card catalog (expensive), small groups of students share a card catalog (efficient) but still look up different things (expressive).

IV.1MultiQueryAttention (MQA)All query heads share a single set of keys and values. The most extreme sharing variant, maximizing efficiency.

What it is

All query heads share a single set of keys and values. The most extreme sharing variant, maximizing efficiency.

Purpose

Minimizing memory and computation in attention mechanisms, especially important for autoregressive generation where keys/values accumulate.

Common uses

  • Fast inference in large language models
  • Memory-constrained deployments
  • Autoregressive generation where KV cache size is critical
  • Mobile or edge deployments of transformers

What it's NOT

  • Not regular multi-head attention – All heads share one set of keys/values
  • Not removing heads – Still has multiple query heads, just shared keys/values
  • Not equivalent in quality – Trades some quality for substantial efficiency gains

Analogy

Like all students in a class sharing one textbook (the keys/values) but each can ask their own questions about it (multiple queries).

IV.3LSTMCellA recurrent unit with special gates that control what information to remember, forget, and output. Processes sequences one step at a time while maintaining a memory cell.

What it is

A recurrent unit with special gates that control what information to remember, forget, and output. Processes sequences one step at a time while maintaining a memory cell.

Purpose

Capturing sequential dependencies while avoiding the vanishing gradient problem that affects simple RNNs. Selective memory allows learning very long-term patterns.

Common uses

  • Processing text sequences before transformers became dominant
  • Time series prediction and forecasting
  • Speech recognition and generation
  • Any sequential task requiring memory of distant past

What it's NOT

  • Not attention – LSTM has fixed-size memory and processes sequentially; attention can look anywhere in parallel
  • Not stateless – LSTM carries hidden state forward through the sequence
  • Not a simple RNN – Has specialized gating mechanisms that simple RNNs lack

Analogy

Like taking notes while reading a book. You have a memory (cell state) where you decide what to write down (input gate), what old notes to erase (forget gate), and what to tell someone asking about the book (output gate).

IV.3GRUCellA simpler alternative to LSTM with fewer gates (just reset and update gates), but still capable of learning long-term dependencies.

What it is

A simpler alternative to LSTM with fewer gates (just reset and update gates), but still capable of learning long-term dependencies.

Purpose

Providing the benefits of LSTM with fewer parameters and simpler computation, often matching LSTM performance with less overhead.

Common uses

  • Same applications as LSTM but where simplicity is valued
  • Situations where LSTM's full complexity isn't needed
  • Resource-constrained environments
  • Faster training than LSTM due to fewer parameters

What it's NOT

  • Not LSTM – Has different and simpler gating mechanism
  • Not better than LSTM universally – Sometimes matches, sometimes worse, depends on task
  • Not attention – Still sequential processing with fixed memory

Analogy

Like a simpler note-taking system: instead of separate "what to forget" and "what to remember" decisions, you make combined decisions about updating your notes.

IV.2LinearStateSpaceLayerModels sequences using state-space equations from control theory. Maintains a hidden state that evolves according to linear dynamics.

What it is

Models sequences using state-space equations from control theory. Maintains a hidden state that evolves according to linear dynamics.

Purpose

Efficiently modeling long sequences by using structured state transitions, often more efficient than attention for very long contexts.

Common uses

  • Long-range sequence modeling
  • Efficient alternatives to transformers for long contexts
  • Time series with linear dynamics
  • Models needing theoretical connections to control systems

What it's NOT

  • Not attention – Uses structured state evolution, not learned queries/keys
  • Not RNN – Linear dynamics, not nonlinear gated updates
  • Not convolutional – Maintains state, not just local windows

Analogy

Like a cruise control system that maintains speed based on current state and inputs, following predictable linear rules.

IV.3VanillaRNNThe simplest recurrent network. Maintains hidden state and updates it at each time step using a simple linear transformation plus nonlinearity.

What it is

The simplest recurrent network. Maintains hidden state and updates it at each time step using a simple linear transformation plus nonlinearity.

Purpose

The foundational recurrent architecture. Mostly historical now, but helps understand more complex RNNs.

Common uses

  • Teaching and understanding recurrent networks
  • Simple sequence tasks where LSTM is overkill
  • Theoretical analysis of recurrent dynamics
  • Rarely used in modern production systems

What it's NOT

  • Not LSTM or GRU – Lacks gating mechanisms
  • Not practical for long sequences – Suffers badly from vanishing/exploding gradients
  • Not attention – Sequential processing with hidden state

Analogy

Like passing a message through a line of people where each person slightly changes the message before passing it on—by the end, the original message (gradient) may be completely garbled.

IV.1MultiHeadLatentAttentionCompress shared key-value information into a learned latent vector before attention.

What it is

Compress shared key-value information into a learned latent vector before attention.

Purpose

Reduce attention cache storage while retaining multiple query heads.

Common uses

  • Cache compressed key-value state during autoregressive decoding.
Tensor and behavior contract

Inputs

Token features, learned down/up projections, positional components, and optional cached latents.

Outputs

Attended token representations and updated latent cache.

Parameters

  • Head counts, latent ranks, positional dimensions, causal rule.

Shape and rank constraints

  • Projection dimensions and positional query-key components are compatible.

Behavioral invariants

  • The latent representation is shared through the declared compression maps.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Cache compressed key-value state during autoregressive decoding.

Related operations

References

DeepSeek-V2 ↗
IV.5CumulativeSumReturn the running sum at every position of an axis.

What it is

Return the running sum at every position of an axis.

Purpose

Accumulate sequence context without discarding intermediate prefixes.

Common uses

  • Turn [1, 2, 3] into running totals [1, 3, 6].
Tensor and behavior contract

Inputs

Numeric tensor X.

Outputs

Tensor with the same shape as X.

Y[t] = sum(X[0:t+1])

Parameters

  • Axis; the declared operation uses an inclusive forward prefix.

Shape and rank constraints

  • The axis is valid.

Behavioral invariants

  • Each output includes exactly the input prefix ending at that position.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Turn [1, 2, 3] into running totals [1, 3, 6].

Related operations

References

ONNX CumSum ↗
IV.5CumulativeProductReturn the running product at every position of an axis.

What it is

Return the running product at every position of an axis.

Purpose

Accumulate sequence context without discarding intermediate prefixes.

Common uses

  • Compute running sequence factors or normalizers.
Tensor and behavior contract

Inputs

Numeric tensor X.

Outputs

Tensor with the same shape as X.

Y[t] = product(X[0:t+1])

Parameters

  • Axis; the declared operation uses an inclusive forward prefix.

Shape and rank constraints

  • The axis is valid.

Behavioral invariants

  • Each output includes exactly the input prefix ending at that position.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Compute running sequence factors or normalizers.

Related operations

IV.5CumulativeLogSumExpReturn a stable running log-sum-exp at every position of an axis.

What it is

Return a stable running log-sum-exp at every position of an axis.

Purpose

Accumulate sequence context without discarding intermediate prefixes.

Common uses

  • Compute running sequence factors or normalizers.
Tensor and behavior contract

Inputs

Numeric tensor X.

Outputs

Tensor with the same shape as X.

Y[t] = log(sum(exp(X[0:t+1])))

Parameters

  • Axis; the declared operation uses an inclusive forward prefix.

Shape and rank constraints

  • The axis is valid. Log-sum-exp requires a floating-point input.

Behavioral invariants

  • Each output includes exactly the input prefix ending at that position.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Compute running sequence factors or normalizers.

Related operations

Normalization & Calibration

Scope

Operations that normalize, scale, or calibrate activations or probabilities without changing the underlying topology. This includes feature-wise normalization, magnitude scaling, and probability calibration transforms.

13 entries
V.1LayerNormNormalizes each example independently across its features, subtracting the mean and dividing by standard deviation, then applying learned scale and shift.

What it is

Normalizes each example independently across its features, subtracting the mean and dividing by standard deviation, then applying learned scale and shift.

Purpose

Stabilizing training by ensuring features have consistent scale within each example. Essential for transformer architectures.

Common uses

  • Transformer models (normalization within each token's features)
  • Recurrent networks
  • Any architecture where batch size is small or variable
  • Situations where normalization should be independent per example

What it's NOT

  • Not batch normalization – Normalizes per example across features, not across batch per feature
  • Not just standardization – Includes learned scale/shift parameters after normalization
  • Not L2 normalization – Uses mean and std for normalization, not vector magnitude

Analogy

Like grading students on a curve, but doing it separately for each student's different subjects. Each student gets their own mean/std, ensuring fair comparison across their subjects.

V.1BatchNormNormalizes each feature across the batch, subtracting the batch mean and dividing by batch standard deviation, with learned scale and shift.

What it is

Normalizes each feature across the batch, subtracting the batch mean and dividing by batch standard deviation, with learned scale and shift.

Purpose

Accelerating training by reducing internal covariate shift. Makes networks less sensitive to initialization and learning rates.

Common uses

  • Convolutional neural networks for computer vision
  • Deep networks where training stability is important
  • After convolutional or dense layers (typically before activation)
  • Any architecture with large, fixed batch sizes

What it's NOT

  • Not layer norm – Normalizes across batch per feature, not per example across features
  • Not dropout – BatchNorm normalizes, doesn't randomly zero elements
  • Not guaranteed to help every architecture – Works great for CNNs, less effective for transformers

Analogy

Like ensuring all thermometers in a room show similar distributions—you normalize each thermometer's reading against what all other thermometers at that location are showing.

V.1RMSNormSimpler than LayerNorm—normalizes by root-mean-square without centering (no mean subtraction), with learned scale.

What it is

Simpler than LayerNorm—normalizes by root-mean-square without centering (no mean subtraction), with learned scale.

Purpose

Providing normalization benefits with less computation than LayerNorm. Often performs similarly with lower cost.

Common uses

  • Large language models where efficiency matters (GPT-3, LLaMA)
  • Transformer architectures seeking computational savings
  • Situations where centering isn't critical
  • Modern architectures optimizing for speed

What it's NOT

  • Not LayerNorm – Doesn't subtract mean, only normalizes by RMS
  • Not just scaling – Normalizes by learned magnitude, not just multiplies
  • Not batch-dependent – Like LayerNorm, operates per example

Analogy

Like ensuring vector lengths are consistent without worrying about where they point. You rescale each vector to have a standard magnitude.

V.1GroupNormDivides channels into groups and normalizes within each group. Hybrid between LayerNorm and BatchNorm.

What it is

Divides channels into groups and normalizes within each group. Hybrid between LayerNorm and BatchNorm.

Purpose

Providing normalization that works well with small batches, avoiding batch dependence while being more flexible than layer norm.

Common uses

  • Object detection and segmentation where batch sizes are small
  • Situations where batch statistics are unreliable
  • Architectures needing normalization flexibility
  • Transfer learning where test batches differ from training

What it's NOT

  • Not batch norm – Doesn't use batch statistics
  • Not layer norm – Normalizes within groups of channels, not all channels
  • Not instance normalization – Groups can have multiple channels; instance norm is per-channel

Analogy

Like organizing a large class into small discussion groups and grading on a curve within each group, rather than across the whole class (batch) or per individual (layer).

V.2L2NormalizeScales each vector to have unit length (magnitude of 1) without changing its direction.

What it is

Scales each vector to have unit length (magnitude of 1) without changing its direction.

Purpose

Making comparisons based on direction rather than magnitude. Essential for similarity metrics and certain loss functions.

Common uses

  • Face recognition (comparing face embeddings by angle, not magnitude)
  • Metric learning and similarity-based tasks
  • Before cosine similarity computations
  • Creating unit-norm embeddings

What it's NOT

  • Not LayerNorm – Only normalizes magnitude, doesn't center or use standard deviation
  • Not softmax – Doesn't convert to probabilities, just ensures unit length
  • Not whitening – Doesn't decorrelate features

Analogy

Like normalizing all arrows to be the same length while keeping them pointing in their original directions. Only the direction matters, not how long they were.

V.2ClipByValueConstrains values to be within a specified range, setting anything too small to the minimum and anything too large to the maximum.

What it is

Constrains values to be within a specified range, setting anything too small to the minimum and anything too large to the maximum.

Purpose

Preventing extreme values that could destabilize training or cause numerical issues.

Common uses

  • Clipping gradients during training to prevent explosions
  • Constraining outputs to valid ranges
  • Implementing certain activation functions
  • Avoiding numerical overflow/underflow

What it's NOT

  • Not normalization – Doesn't rescale the whole distribution, just clips extremes
  • Not gradient clipping by norm – Clips values independently, not based on vector magnitude
  • Not ReLU – Clips on both ends, ReLU only zeros negatives

Analogy

Like speed limits and minimum speeds on a highway. You're free to go any speed between the limits, but if you exceed them, you're brought back to the limit.

V.3SoftmaxConverts a vector of numbers into probabilities that sum to 1. Larger inputs get larger probabilities, exponentially.

What it is

Converts a vector of numbers into probabilities that sum to 1. Larger inputs get larger probabilities, exponentially.

Purpose

Converting raw scores (logits) into probabilities for multi-class classification. Making decisions interpretable.

Common uses

  • Final layer of multi-class classifiers
  • Attention weight computation
  • Any situation needing probability distributions
  • Making categorical decisions

What it's NOT

  • Not sigmoid – Sigmoid is independent per element; softmax ensures outputs sum to 1
  • Not normalization – While it normalizes, it's specifically for creating probability distributions
  • Not argmax – Softmax is differentiable; argmax isn't
  • Not LogSoftmax – Softmax outputs probabilities; LogSoftmax outputs log-probabilities

Analogy

Like dividing a pie where bigger scores get bigger slices, but done exponentially so the biggest score dominates, and all slices sum to the whole pie.

V.2TemperatureScaleDivides logits by a temperature parameter before softmax. Higher temperature makes probabilities more uniform; lower makes them more peaked.

What it is

Divides logits by a temperature parameter before softmax. Higher temperature makes probabilities more uniform; lower makes them more peaked.

Purpose

Controlling the "confidence" or "sharpness" of probability distributions, useful in distillation and sampling.

Common uses

  • Knowledge distillation (teacher with high temperature provides "soft" targets)
  • Text generation (controlling randomness of sampling)
  • Calibrating overconfident models
  • Softmax with controllable entropy

What it's NOT

  • Not general normalization – Specifically for logits before softmax
  • Not learned – Temperature is a hyperparameter, not trained
  • Not probability calibration – Related but different; this is about distribution shape

Analogy

Like adjusting the thermostat on decision-making: high temperature makes you more exploratory and uncertain, low temperature makes you more decisive and confident.

V.3LogSoftmaxComputes log of probabilities directly without computing probabilities first. Numerically stable way to get log-probabilities.

What it is

Computes log of probabilities directly without computing probabilities first. Numerically stable way to get log-probabilities.

Purpose

Used with negative log-likelihood loss. More numerically stable than softmax followed by log.

Common uses

  • With NLL loss for classification
  • When you need log-probabilities not probabilities
  • Information theory applications
  • More stable than log(softmax(x))

What it's NOT

  • Not softmax – Outputs log-probabilities, not probabilities
  • Not just for stability – Required by certain loss functions
  • Not interchangeable with softmax – Different output scale and interpretation

Analogy

Like measuring earthquakes on a logarithmic scale (Richter) rather than linear scale—more stable and meaningful for extreme values.

V.1LocalResponseNormDivide each activation by an energy measure of nearby channels.

What it is

Divide each activation by an energy measure of nearby channels.

Purpose

Control competition between neighboring feature channels.

Common uses

  • Normalize nearby convolutional feature channels.
Tensor and behavior contract

Inputs

Features [N,C,spatial...].

Outputs

Tensor with the same shape.

Parameters

  • Channel window size, alpha, beta, positive bias k.

Shape and rank constraints

  • Window size and denominator settings produce a defined normalization.

Behavioral invariants

  • Normalization neighborhoods extend across channels at fixed spatial positions.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Normalize nearby convolutional feature channels.

Related operations

References

ONNX LRN ↗
V.2L1NormalizeDivide each vector by its absolute-value sum with an explicit minimum denominator.

What it is

Divide each vector by its absolute-value sum with an explicit minimum denominator.

Purpose

Rescale feature vectors to unit L1 magnitude.

Common uses

  • Normalize a nonnegative feature vector before comparison.
Tensor and behavior contract

Inputs

Real-valued tensor X.

Outputs

Tensor with the same shape.

Y = X / max(sum(abs(X), axes), epsilon)

Parameters

  • Axes and positive epsilon.

Shape and rank constraints

  • Axes are valid and epsilon is positive.

Behavioral invariants

  • Vectors above the epsilon threshold have absolute-value sum one.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Normalize a nonnegative feature vector before comparison.

Related operations

V.3EntmaxMap logits to probabilities with a tunable degree of exact sparsity.

What it is

Map logits to probabilities with a tunable degree of exact sparsity.

Purpose

Make probability selections that can exclude low-scoring alternatives.

Common uses

  • Assign probability only to a small set of relevant tokens.
Tensor and behavior contract

Inputs

Real logits X.

Outputs

Nonnegative probabilities with the same shape.

argmax over simplex p of dot(p,X) + TsallisEntropy_alpha(p)

Parameters

  • Normalization axis and alpha in (1,2].

Shape and rank constraints

  • The normalized axis is nonempty.

Behavioral invariants

  • Probabilities sum to one; alpha=2 yields Sparsemax and the alpha->1 limit yields Softmax.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Assign probability only to a small set of relevant tokens.

Related operations

V.3HardmaxMark the largest logit with one and all other logits with zero.

What it is

Mark the largest logit with one and all other logits with zero.

Purpose

Make a deterministic categorical selection.

Common uses

  • Select the highest-scoring category.
Tensor and behavior contract

Inputs

Real logits X.

Outputs

One-hot tensor with the same shape.

Parameters

  • Axis and first-index tie rule.

Shape and rank constraints

  • The selected axis is nonempty.

Behavioral invariants

  • Every vector has exactly one entry equal to one.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Select the highest-scoring category.

Related operations

Pointwise Nonlinear Transforms

Scope

Operations that apply a nonlinear scalar function to each element of a tensor, possibly with simple per-channel or per-element parameters. These are the classical “activations,” but classified more precisely.

54 entries
VI.1ReLUKeeps positive values unchanged, sets negative values to zero. The most popular activation function.

What it is

Keeps positive values unchanged, sets negative values to zero. The most popular activation function.

Purpose

Introducing nonlinearity while being computationally simple and avoiding vanishing gradients for positive activations.

Common uses

  • Default activation in most neural networks
  • After convolutional and dense layers
  • Hidden layers in most modern architectures
  • Anywhere simple, effective nonlinearity is needed

What it's NOT

  • Not linear – Despite its simple form, it's nonlinear because of the kink at zero
  • Not differentiable at zero – Has a discontinuous derivative, though this rarely matters in practice
  • Not bounded – Can output arbitrarily large values, unlike sigmoid/tanh

Analogy

Like a valve that only flows one direction. Positive pressure opens it fully; negative pressure closes it completely.

VI.1LeakyReLULike ReLU but allows small negative values through (typically 0.01x the input). Negative inputs don't go to zero, just get reduced.

What it is

Like ReLU but allows small negative values through (typically 0.01x the input). Negative inputs don't go to zero, just get reduced.

Purpose

Addressing the "dying ReLU" problem where neurons can get stuck outputting zero. Small negative slope keeps gradients alive.

Common uses

  • Situations where dying neurons are problematic
  • GANs and other adversarial architectures
  • Deeper networks where gradient flow is critical
  • When small negative activations are semantically useful

What it's NOT

  • Not ReLU – Has non-zero slope for negatives
  • Not PReLU – Uses fixed slope (not learned)
  • Not ELU – Uses linear slope for negatives, not exponential

Analogy

Like a valve that fully opens for positive pressure but allows a tiny trickle even for negative pressure, never fully closing.

VI.1PReLULike LeakyReLU but the negative slope is learned rather than fixed. The network decides how much negative input to let through.

What it is

Like LeakyReLU but the negative slope is learned rather than fixed. The network decides how much negative input to let through.

Purpose

Automatically learning the optimal negative slope for each neuron, rather than using a fixed small value.

Common uses

  • When you want the benefits of LeakyReLU but with learned parameters
  • Architectures where activation function tuning is important
  • Situations where optimal negative slope isn't known
  • Networks where extra parameters are acceptable

What it's NOT

  • Not LeakyReLU – Slope is learned, not fixed
  • Not ReLU – Has learnable negative slope
  • Not adding significant computation – Just one extra parameter per activation

Analogy

Like a valve where the trickle rate for negative pressure is learned from experience rather than being a fixed setting.

VI.2SigmoidSmoothly maps any real number to a value between 0 and 1. Creates an S-shaped curve.

What it is

Smoothly maps any real number to a value between 0 and 1. Creates an S-shaped curve.

Purpose

Converting arbitrary values to probabilities or gate values. Squashing outputs into a bounded range.

Common uses

  • Binary classification (final layer)
  • Gate mechanisms in LSTMs and GRUs
  • Attention weights
  • Anywhere you need outputs between 0 and 1

What it's NOT

  • Not softmax – Sigmoid is independent per element; softmax creates probabilities that sum to 1
  • Not tanh – Outputs 0-1, not -1 to 1
  • Not ideal for hidden layers – Suffers from vanishing gradients; ReLU usually better

Analogy

Like a dimmer switch that can be anywhere from completely off (0) to completely on (1), with smooth adjustment in between.

VI.2TanhMaps any real number to a value between -1 and 1. Like sigmoid but centered at zero.

What it is

Maps any real number to a value between -1 and 1. Like sigmoid but centered at zero.

Purpose

Similar to sigmoid but zero-centered, which often helps with training. Stronger gradients than sigmoid.

Common uses

  • RNN hidden states before LSTMs became standard
  • Situations where zero-centered activations help
  • Gate mechanisms
  • Hidden layers when sigmoid-like behavior is wanted

What it's NOT

  • Not sigmoid – Outputs -1 to 1, not 0 to 1
  • Not commonly used anymore – Largely replaced by ReLU in modern architectures
  • Not immune to vanishing gradients – Better than sigmoid, but still has the issue

Analogy

Like a dimmer that goes from full reverse (-1) through off (0) to full forward (1).

VI.3GELUGaussian Error Linear Unit—weights inputs by their value in a Gaussian cumulative distribution. Smooth approximation to ReLU that never fully zeros inputs.

What it is

Gaussian Error Linear Unit—weights inputs by their value in a Gaussian cumulative distribution. Smooth approximation to ReLU that never fully zeros inputs.

Purpose

Providing smooth, probabilistically-motivated nonlinearity. Better properties than ReLU in some cases, especially for transformers.

Common uses

  • Transformer models (BERT, GPT, ViT)
  • Modern language models
  • Situations where smoothness matters
  • Architectures where stochasticity-inspired design helps

What it's NOT

  • Not ReLU – Smooth curve, not a sharp corner; never completely zeros inputs
  • Not computationally free – More expensive than ReLU (though fast approximations exist)
  • Not universally better – Architecture-dependent; great for transformers, may not beat ReLU everywhere

Analogy

Like a gate that opens more as the input gets more positive, but uses a smooth probability curve instead of a hard cutoff.

VI.3SiLU (Swish)Multiplies the input by its sigmoid. Self-gated activation that can be negative, unlike ReLU.

What it is

Multiplies the input by its sigmoid. Self-gated activation that can be negative, unlike ReLU.

Purpose

Providing smooth, self-gating nonlinearity. Can outperform ReLU, especially in deeper networks.

Common uses

  • Efficient neural network architectures (EfficientNet, mobile models)
  • Situations where smooth activation helps
  • Deeper networks where gradient flow is important
  • Modern computer vision architectures

What it's NOT

  • Not ReLU – Smooth, not piecewise linear; can be negative
  • Not just sigmoid – Multiplies input by its sigmoid, doesn't just squash
  • Not computationally free – Requires sigmoid computation

Analogy

Like a gate that uses its own input signal to decide how much to open—the stronger the positive input, the more it amplifies itself.

VI.3SoftplusSmooth approximation to ReLU. The curve approaches zero for negative inputs and becomes linear for positive inputs, but without sharp corners.

What it is

Smooth approximation to ReLU. The curve approaches zero for negative inputs and becomes linear for positive inputs, but without sharp corners.

Purpose

Providing ReLU-like behavior with everywhere-differentiable smooth curve. Used when mathematical smoothness is desired.

Common uses

  • Variational autoencoders (modeling positive quantities smoothly)
  • Situations requiring strict differentiability
  • Probabilistic models
  • When ReLU's non-differentiability at zero is problematic

What it's NOT

  • Not ReLU – Smooth everywhere, not piecewise linear
  • Not commonly used for general networks – ReLU usually preferred for its simplicity
  • Not bounded above – Like ReLU, can grow arbitrarily large

Analogy

Like a smoothed version of the one-way valve (ReLU)—instead of a sharp transition, it smoothly curves from closed to open.

VI.1ELUExponential Linear Unit. Like ReLU for positive values, but uses a smooth exponential curve for negative values instead of zeroing them.

What it is

Exponential Linear Unit. Like ReLU for positive values, but uses a smooth exponential curve for negative values instead of zeroing them.

Purpose

Addressing ReLU's dead neuron problem while maintaining differentiability and having negative values that can push mean activations toward zero.

Common uses

  • When negative activations are desired
  • Networks where dying neurons are problematic
  • Situations where smooth activation helps
  • Alternative to ReLU/LeakyReLU with different properties

What it's NOT

  • Not ReLU – Has smooth exponential for negatives
  • Not LeakyReLU – Exponential curve, not linear slope
  • Not computationally free – Exponential is more expensive than ReLU

Analogy

Like a valve that fully opens for positive pressure, but for negative pressure, closes exponentially smoothly rather than linearly or abruptly.

VI.2HardSigmoidPiecewise linear approximation to sigmoid. Faster to compute, outputs 0 for very negative, 1 for very positive, linear in between.

What it is

Piecewise linear approximation to sigmoid. Faster to compute, outputs 0 for very negative, 1 for very positive, linear in between.

Purpose

Providing sigmoid-like behavior with much faster computation, especially useful on mobile or embedded devices.

Common uses

  • Mobile neural networks
  • Embedded and edge devices
  • Approximating sigmoid in models where speed matters
  • MobileNet-style architectures

What it's NOT

  • Not smooth sigmoid – Piecewise linear, not smooth curve
  • Not identical behavior – Approximation that trades accuracy for speed
  • Not mathematically equivalent – Different derivatives

Analogy

Like a dimmer switch with only a few settings (0%, 50%, 100%) instead of smooth continuous adjustment—simpler mechanism, faster to operate.

VI.3MishSelf-regularized nonlinearity: x × tanh(softplus(x)). Smooth, non-monotonic activation function.

What it is

Self-regularized nonlinearity: x × tanh(softplus(x)). Smooth, non-monotonic activation function.

Purpose

Providing smooth nonlinearity that can outperform ReLU on some tasks, especially in deeper networks.

Common uses

  • Modern computer vision architectures
  • Tasks where smooth activations help
  • Deeper networks benefiting from better gradient flow
  • Research exploring activation alternatives

What it's NOT

  • Not ReLU – Smooth, unbounded on both sides
  • Not SiLU – Uses tanh(softplus(x)) instead of sigmoid(x)
  • Not universally better – Architecture and task dependent

Analogy

Like a sophisticated suspension system that smoothly handles both compression and extension, adapting to terrain changes.

VI.1CELUKeep positive values and use a smooth exponential branch for negative values.

What it is

Keep positive values and use a smooth exponential branch for negative values.

Purpose

Smooth negative responses in a feature map.

Common uses

  • Smooth negative responses in a feature map.
Tensor and behavior contract

Inputs

Real-valued tensor X.

Outputs

Tensor with the same shape.

max(0,x) + min(0,alpha*(exp(x/alpha)-1))

Parameters

  • Positive alpha.

Shape and rank constraints

  • alpha > 0.

Behavioral invariants

  • The declared scalar function is applied independently to every element.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Smooth negative responses in a feature map.

Related operations

References

ONNX Celu ↗
VI.1ReLU6Clip each value to the interval from zero to six.

What it is

Clip each value to the interval from zero to six.

Purpose

Map [-2, 3, 8] to [0, 3, 6].

Common uses

  • Map [-2, 3, 8] to [0, 3, 6].
Tensor and behavior contract

Inputs

Real-valued tensor X.

Outputs

Tensor with the same shape.

min(max(x,0),6)

Parameters

  • Fixed bounds zero and six.

Shape and rank constraints

  • Real-valued input.

Behavioral invariants

  • The declared scalar function is applied independently to every element.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Map [-2, 3, 8] to [0, 3, 6].

Related operations

VI.1HardTanhClip each value between declared lower and upper bounds.

What it is

Clip each value between declared lower and upper bounds.

Purpose

Clip gate inputs into [-1,1].

Common uses

  • Clip gate inputs into [-1,1].
Tensor and behavior contract

Inputs

Real-valued tensor X.

Outputs

Tensor with the same shape.

min(max(x,min_value),max_value)

Parameters

  • Lower and upper bounds.

Shape and rank constraints

  • Lower bound is less than upper bound.

Behavioral invariants

  • The declared scalar function is applied independently to every element.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Clip gate inputs into [-1,1].

Related operations

VI.1ThresholdKeep values above a threshold and replace the others with one declared value.

What it is

Keep values above a threshold and replace the others with one declared value.

Purpose

Replace values at or below zero with zero.

Common uses

  • Replace values at or below zero with zero.
Tensor and behavior contract

Inputs

Real-valued tensor X.

Outputs

Tensor with the same shape.

x if x > threshold else value

Parameters

  • Threshold and replacement value.

Shape and rank constraints

  • Threshold and replacement are compatible scalars.

Behavioral invariants

  • The declared scalar function is applied independently to every element.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Replace values at or below zero with zero.

Related operations

VI.2LogSigmoidCompute the logarithm of sigmoid without unstable intermediate probabilities.

What it is

Compute the logarithm of sigmoid without unstable intermediate probabilities.

Purpose

Compute stable binary log probabilities.

Common uses

  • Compute stable binary log probabilities.
Tensor and behavior contract

Inputs

Real-valued tensor X.

Outputs

Tensor with the same shape.

-softplus(-x)

Parameters

  • None.

Shape and rank constraints

  • Real-valued input.

Behavioral invariants

  • The declared scalar function is applied independently to every element.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Compute stable binary log probabilities.

Related operations

VI.2SoftsignCompress values smoothly toward minus one or one.

What it is

Compress values smoothly toward minus one or one.

Purpose

Bound recurrent feature responses.

Common uses

  • Bound recurrent feature responses.
Tensor and behavior contract

Inputs

Real-valued tensor X.

Outputs

Tensor with the same shape.

x / (1 + abs(x))

Parameters

  • None.

Shape and rank constraints

  • Real-valued input.

Behavioral invariants

  • The declared scalar function is applied independently to every element.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Bound recurrent feature responses.

Related operations

VI.3HardSwishMultiply each input by a clipped linear approximation of a sigmoid gate.

What it is

Multiply each input by a clipped linear approximation of a sigmoid gate.

Purpose

Use a simple gated activation in mobile networks.

Common uses

  • Use a simple gated activation in mobile networks.
Tensor and behavior contract

Inputs

Real-valued tensor X.

Outputs

Tensor with the same shape.

x * min(max(x+3,0),6) / 6

Parameters

  • Fixed gate breakpoints -3 and 3.

Shape and rank constraints

  • Real-valued input.

Behavioral invariants

  • The declared scalar function is applied independently to every element.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Use a simple gated activation in mobile networks.

Related operations

VI.3SoftshrinkSet small values to zero and move larger values toward zero by a fixed amount.

What it is

Set small values to zero and move larger values toward zero by a fixed amount.

Purpose

Apply soft thresholding to sparse features.

Common uses

  • Apply soft thresholding to sparse features.
Tensor and behavior contract

Inputs

Real-valued tensor X.

Outputs

Tensor with the same shape.

x-lambda if x>lambda; x+lambda if x<-lambda; 0 otherwise

Parameters

  • Nonnegative lambda.

Shape and rank constraints

  • lambda >= 0.

Behavioral invariants

  • The declared scalar function is applied independently to every element.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Apply soft thresholding to sparse features.

Related operations

VI.3HardShrinkKeep values outside a threshold interval and set values inside it to zero.

What it is

Keep values outside a threshold interval and set values inside it to zero.

Purpose

Remove small feature responses.

Common uses

  • Remove small feature responses.
Tensor and behavior contract

Inputs

Real-valued tensor X.

Outputs

Tensor with the same shape.

x if abs(x)>lambda else 0

Parameters

  • Nonnegative lambda.

Shape and rank constraints

  • lambda >= 0.

Behavioral invariants

  • The declared scalar function is applied independently to every element.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Remove small feature responses.

Related operations

VI.3TanhShrinkSubtract a bounded tanh response from each input value.

What it is

Subtract a bounded tanh response from each input value.

Purpose

Suppress responses near zero while retaining large values.

Common uses

  • Suppress responses near zero while retaining large values.
Tensor and behavior contract

Inputs

Real-valued tensor X.

Outputs

Tensor with the same shape.

x - tanh(x)

Parameters

  • None.

Shape and rank constraints

  • Real-valued input.

Behavioral invariants

  • The declared scalar function is applied independently to every element.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Suppress responses near zero while retaining large values.

Related operations

VI.4RsqrtTake the reciprocal of the square root of each value.

What it is

Take the reciprocal of the square root of each value.

Purpose

Compute inverse normalization scales.

Common uses

  • Compute inverse normalization scales.
Tensor and behavior contract

Inputs

Real-valued tensor X.

Outputs

Tensor with the same shape.

1 / sqrt(x)

Parameters

  • None.

Shape and rank constraints

  • Positive inputs give finite real outputs.

Behavioral invariants

  • The declared scalar function is applied independently to every element.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Compute inverse normalization scales.

Related operations

VI.4SquareMultiply each scalar by itself.

What it is

Multiply each scalar by itself.

Purpose

Build squared-error or variance expressions.

Common uses

  • Build squared-error or variance expressions.
Tensor and behavior contract

Inputs

Real-valued tensor X.

Outputs

Tensor with the same shape.

x*x

Parameters

  • None.

Shape and rank constraints

  • A declared numeric type and overflow policy.

Behavioral invariants

  • The declared scalar function is applied independently to every element.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Build squared-error or variance expressions.

Related operations

VI.4Expm1Compute the exponential minus one with accuracy near zero.

What it is

Compute the exponential minus one with accuracy near zero.

Purpose

Evaluate small exponential increments.

Common uses

  • Evaluate small exponential increments.
Tensor and behavior contract

Inputs

Real-valued tensor X.

Outputs

Tensor with the same shape.

exp(x)-1

Parameters

  • None.

Shape and rank constraints

  • Real-valued input; overflow behavior follows the declared numeric format.

Behavioral invariants

  • The declared scalar function is applied independently to every element.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Evaluate small exponential increments.

Related operations

VI.4Exp2Raise two to the power of each input value.

What it is

Raise two to the power of each input value.

Purpose

Convert base-two log values into ordinary values.

Common uses

  • Convert base-two log values into ordinary values.
Tensor and behavior contract

Inputs

Real-valued tensor X.

Outputs

Tensor with the same shape.

2^x

Parameters

  • None.

Shape and rank constraints

  • Real-valued input; overflow behavior follows the declared numeric format.

Behavioral invariants

  • The declared scalar function is applied independently to every element.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Convert base-two log values into ordinary values.

Related operations

VI.4Log2Take the base-two logarithm of each value.

What it is

Take the base-two logarithm of each value.

Purpose

Measure magnitudes in powers of two.

Common uses

  • Measure magnitudes in powers of two.
Tensor and behavior contract

Inputs

Real-valued tensor X.

Outputs

Tensor with the same shape.

log2(x)

Parameters

  • None.

Shape and rank constraints

  • Positive inputs give finite real outputs.

Behavioral invariants

  • The declared scalar function is applied independently to every element.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Measure magnitudes in powers of two.

Related operations

VI.4Log10Take the base-ten logarithm of each value.

What it is

Take the base-ten logarithm of each value.

Purpose

Convert positive magnitudes to a decimal logarithmic scale.

Common uses

  • Convert positive magnitudes to a decimal logarithmic scale.
Tensor and behavior contract

Inputs

Real-valued tensor X.

Outputs

Tensor with the same shape.

log10(x)

Parameters

  • None.

Shape and rank constraints

  • Positive inputs give finite real outputs.

Behavioral invariants

  • The declared scalar function is applied independently to every element.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Convert positive magnitudes to a decimal logarithmic scale.

Related operations

VI.4CeilRound each value upward to the nearest integer value.

What it is

Round each value upward to the nearest integer value.

Purpose

Round an output-size estimate upward.

Common uses

  • Round an output-size estimate upward.
Tensor and behavior contract

Inputs

Real-valued tensor X.

Outputs

Tensor with the same shape.

ceil(x)

Parameters

  • None.

Shape and rank constraints

  • Real-valued input with declared nonfinite-value behavior.

Behavioral invariants

  • The declared scalar function is applied independently to every element.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Round an output-size estimate upward.

Related operations

References

ONNX Ceil ↗
VI.4FloorRound each value downward to the nearest integer value.

What it is

Round each value downward to the nearest integer value.

Purpose

Convert continuous positions to lower grid indices.

Common uses

  • Convert continuous positions to lower grid indices.
Tensor and behavior contract

Inputs

Real-valued tensor X.

Outputs

Tensor with the same shape.

floor(x)

Parameters

  • None.

Shape and rank constraints

  • Real-valued input with declared nonfinite-value behavior.

Behavioral invariants

  • The declared scalar function is applied independently to every element.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Convert continuous positions to lower grid indices.

Related operations

References

ONNX Floor ↗
VI.4RoundRound each value to its nearest integer, choosing the even integer at a tie.

What it is

Round each value to its nearest integer, choosing the even integer at a tie.

Purpose

Map [1.5, 2.5] to [2, 2].

Common uses

  • Map [1.5, 2.5] to [2, 2].
Tensor and behavior contract

Inputs

Real-valued tensor X.

Outputs

Tensor with the same shape.

round_to_nearest_even(x)

Parameters

  • Ties-to-even rule.

Shape and rank constraints

  • Real-valued input with declared nonfinite-value behavior.

Behavioral invariants

  • The declared scalar function is applied independently to every element.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Map [1.5, 2.5] to [2, 2].

Related operations

References

ONNX Round ↗
VI.4TruncDiscard each value's fractional part by rounding toward zero.

What it is

Discard each value's fractional part by rounding toward zero.

Purpose

Map [-1.8, 1.8] to [-1, 1].

Common uses

  • Map [-1.8, 1.8] to [-1, 1].
Tensor and behavior contract

Inputs

Real-valued tensor X.

Outputs

Tensor with the same shape.

trunc(x)

Parameters

  • None.

Shape and rank constraints

  • Real-valued input with declared nonfinite-value behavior.

Behavioral invariants

  • The declared scalar function is applied independently to every element.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Map [-1.8, 1.8] to [-1, 1].

Related operations

VI.4FracReturn the signed fractional part left after truncating toward zero.

What it is

Return the signed fractional part left after truncating toward zero.

Purpose

Map [-1.8, 1.8] to approximately [-0.8, 0.8].

Common uses

  • Map [-1.8, 1.8] to approximately [-0.8, 0.8].
Tensor and behavior contract

Inputs

Real-valued tensor X.

Outputs

Tensor with the same shape.

x - trunc(x)

Parameters

  • None.

Shape and rank constraints

  • Finite real-valued input.

Behavioral invariants

  • The declared scalar function is applied independently to every element.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Map [-1.8, 1.8] to approximately [-0.8, 0.8].

Related operations

VI.4SinCompute the sine of each angle measured in radians.

What it is

Compute the sine of each angle measured in radians.

Purpose

Construct periodic position features.

Common uses

  • Construct periodic position features.
Tensor and behavior contract

Inputs

Real-valued tensor X.

Outputs

Tensor with the same shape.

sin(x)

Parameters

  • Radian angle convention.

Shape and rank constraints

  • Finite real-valued angles.

Behavioral invariants

  • The declared scalar function is applied independently to every element.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Construct periodic position features.

Related operations

References

ONNX Sin ↗
VI.4CosCompute the cosine of each angle measured in radians.

What it is

Compute the cosine of each angle measured in radians.

Purpose

Construct periodic position features.

Common uses

  • Construct periodic position features.
Tensor and behavior contract

Inputs

Real-valued tensor X.

Outputs

Tensor with the same shape.

cos(x)

Parameters

  • Radian angle convention.

Shape and rank constraints

  • Finite real-valued angles.

Behavioral invariants

  • The declared scalar function is applied independently to every element.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Construct periodic position features.

Related operations

References

ONNX Cos ↗
VI.4TanCompute the tangent of each angle measured in radians.

What it is

Compute the tangent of each angle measured in radians.

Purpose

Apply an angular scalar transform.

Common uses

  • Apply an angular scalar transform.
Tensor and behavior contract

Inputs

Real-valued tensor X.

Outputs

Tensor with the same shape.

tan(x)

Parameters

  • Radian angle convention.

Shape and rank constraints

  • Finite angles away from odd multiples of pi/2 for finite outputs.

Behavioral invariants

  • The declared scalar function is applied independently to every element.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Apply an angular scalar transform.

Related operations

References

ONNX Tan ↗
VI.4AsinReturn the principal angle whose sine equals each input.

What it is

Return the principal angle whose sine equals each input.

Purpose

Recover angles from sine-valued coordinates.

Common uses

  • Recover angles from sine-valued coordinates.
Tensor and behavior contract

Inputs

Real-valued tensor X.

Outputs

Tensor with the same shape.

asin(x)

Parameters

  • Radian output convention.

Shape and rank constraints

  • Real input lies in [-1,1].

Behavioral invariants

  • The declared scalar function is applied independently to every element.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Recover angles from sine-valued coordinates.

Related operations

References

ONNX Asin ↗
VI.4AcosReturn the principal angle whose cosine equals each input.

What it is

Return the principal angle whose cosine equals each input.

Purpose

Convert normalized dot products into angular distances.

Common uses

  • Convert normalized dot products into angular distances.
Tensor and behavior contract

Inputs

Real-valued tensor X.

Outputs

Tensor with the same shape.

acos(x)

Parameters

  • Radian output convention.

Shape and rank constraints

  • Real input lies in [-1,1].

Behavioral invariants

  • The declared scalar function is applied independently to every element.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Convert normalized dot products into angular distances.

Related operations

References

ONNX Acos ↗
VI.4AtanReturn the principal angle whose tangent equals each input.

What it is

Return the principal angle whose tangent equals each input.

Purpose

Map real ratios into bounded angles.

Common uses

  • Map real ratios into bounded angles.
Tensor and behavior contract

Inputs

Real-valued tensor X.

Outputs

Tensor with the same shape.

atan(x)

Parameters

  • Radian output convention.

Shape and rank constraints

  • Real-valued input.

Behavioral invariants

  • The declared scalar function is applied independently to every element.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Map real ratios into bounded angles.

Related operations

References

ONNX Atan ↗
VI.4SinhApply the hyperbolic sine to each scalar.

What it is

Apply the hyperbolic sine to each scalar.

Purpose

Transform features in hyperbolic models.

Common uses

  • Transform features in hyperbolic models.
Tensor and behavior contract

Inputs

Real-valued tensor X.

Outputs

Tensor with the same shape.

(exp(x)-exp(-x))/2

Parameters

  • None.

Shape and rank constraints

  • Real-valued input; overflow follows the numeric format.

Behavioral invariants

  • The declared scalar function is applied independently to every element.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Transform features in hyperbolic models.

Related operations

References

ONNX Sinh ↗
VI.4CoshApply the hyperbolic cosine to each scalar.

What it is

Apply the hyperbolic cosine to each scalar.

Purpose

Compute hyperbolic distance expressions.

Common uses

  • Compute hyperbolic distance expressions.
Tensor and behavior contract

Inputs

Real-valued tensor X.

Outputs

Tensor with the same shape.

(exp(x)+exp(-x))/2

Parameters

  • None.

Shape and rank constraints

  • Real-valued input; overflow follows the numeric format.

Behavioral invariants

  • The declared scalar function is applied independently to every element.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Compute hyperbolic distance expressions.

Related operations

References

ONNX Cosh ↗
VI.4AsinhApply the inverse hyperbolic sine to each scalar.

What it is

Apply the inverse hyperbolic sine to each scalar.

Purpose

Compress signed magnitudes with logarithmic tails.

Common uses

  • Compress signed magnitudes with logarithmic tails.
Tensor and behavior contract

Inputs

Real-valued tensor X.

Outputs

Tensor with the same shape.

asinh(x)

Parameters

  • None.

Shape and rank constraints

  • Real-valued input.

Behavioral invariants

  • The declared scalar function is applied independently to every element.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Compress signed magnitudes with logarithmic tails.

Related operations

References

ONNX Asinh ↗
VI.4AcoshApply the principal inverse hyperbolic cosine.

What it is

Apply the principal inverse hyperbolic cosine.

Purpose

Recover a hyperbolic distance from its cosine.

Common uses

  • Recover a hyperbolic distance from its cosine.
Tensor and behavior contract

Inputs

Real-valued tensor X.

Outputs

Tensor with the same shape.

acosh(x)

Parameters

  • None.

Shape and rank constraints

  • Real input is at least one.

Behavioral invariants

  • The declared scalar function is applied independently to every element.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Recover a hyperbolic distance from its cosine.

Related operations

References

ONNX Acosh ↗
VI.4AtanhApply the inverse hyperbolic tangent.

What it is

Apply the inverse hyperbolic tangent.

Purpose

Recover unconstrained values from bounded tanh outputs.

Common uses

  • Recover unconstrained values from bounded tanh outputs.
Tensor and behavior contract

Inputs

Real-valued tensor X.

Outputs

Tensor with the same shape.

atanh(x)

Parameters

  • None.

Shape and rank constraints

  • Inputs strictly between -1 and 1 give finite real outputs.

Behavioral invariants

  • The declared scalar function is applied independently to every element.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Recover unconstrained values from bounded tanh outputs.

Related operations

References

ONNX Atanh ↗
VI.4ErfEvaluate the Gaussian error function at each scalar.

What it is

Evaluate the Gaussian error function at each scalar.

Purpose

Build Gaussian probability and GELU expressions.

Common uses

  • Build Gaussian probability and GELU expressions.
Tensor and behavior contract

Inputs

Real-valued tensor X.

Outputs

Tensor with the same shape.

erf(x)

Parameters

  • None.

Shape and rank constraints

  • Real-valued input.

Behavioral invariants

  • The declared scalar function is applied independently to every element.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Build Gaussian probability and GELU expressions.

Related operations

References

ONNX Erf ↗
VI.4ErfcEvaluate the complementary Gaussian error function accurately in its tails.

What it is

Evaluate the complementary Gaussian error function accurately in its tails.

Purpose

Compute small Gaussian tail probabilities.

Common uses

  • Compute small Gaussian tail probabilities.
Tensor and behavior contract

Inputs

Real-valued tensor X.

Outputs

Tensor with the same shape.

1 - erf(x)

Parameters

  • None.

Shape and rank constraints

  • Real-valued input.

Behavioral invariants

  • The declared scalar function is applied independently to every element.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Compute small Gaussian tail probabilities.

Related operations

VI.4FloorDivideDivide values and round each quotient toward negative infinity.

What it is

Divide values and round each quotient toward negative infinity.

Purpose

Apply the declared scalar map to tensor values.

Common uses

  • FloorDivide(-3,2) gives -2.
Tensor and behavior contract

Inputs

Two broadcast-compatible real tensors.

Outputs

Tensor with the broadcast shape.

floor(A/B)

Parameters

  • Remainder convention for Mod; otherwise the declared numeric policy.

Shape and rank constraints

  • Divisors are nonzero and inputs broadcast.

Behavioral invariants

  • The output shape follows broadcasting.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • FloorDivide(-3,2) gives -2.

Related operations

VI.4ModReturn the remainder under a declared floor-division or truncation convention.

What it is

Return the remainder under a declared floor-division or truncation convention.

Purpose

Apply the declared scalar map to tensor values.

Common uses

  • Under floor division, Mod(-3,2) gives 1.
Tensor and behavior contract

Inputs

Two broadcast-compatible real tensors.

Outputs

Tensor with the broadcast shape.

A - B*floor(A/B), or A - B*trunc(A/B)

Parameters

  • Remainder convention for Mod; otherwise the declared numeric policy.

Shape and rank constraints

  • Divisors are nonzero and the remainder convention is explicit.

Behavioral invariants

  • The output shape follows broadcasting.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Under floor division, Mod(-3,2) gives 1.

Related operations

References

ONNX Mod ↗
VI.4MinimumChoose the smaller value at each pair of corresponding positions.

What it is

Choose the smaller value at each pair of corresponding positions.

Purpose

Apply the declared scalar map to tensor values.

Common uses

  • Minimum([1,4],[2,3]) gives [1,3].
Tensor and behavior contract

Inputs

Two broadcast-compatible real tensors.

Outputs

Tensor with the broadcast shape.

min(A,B)

Parameters

  • Remainder convention for Mod; otherwise the declared numeric policy.

Shape and rank constraints

  • Inputs broadcast and NaN behavior is declared.

Behavioral invariants

  • The output shape follows broadcasting.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Minimum([1,4],[2,3]) gives [1,3].

Related operations

References

ONNX Min ↗
VI.4MaximumChoose the larger value at each pair of corresponding positions.

What it is

Choose the larger value at each pair of corresponding positions.

Purpose

Apply the declared scalar map to tensor values.

Common uses

  • Maximum([1,4],[2,3]) gives [2,4].
Tensor and behavior contract

Inputs

Two broadcast-compatible real tensors.

Outputs

Tensor with the broadcast shape.

max(A,B)

Parameters

  • Remainder convention for Mod; otherwise the declared numeric policy.

Shape and rank constraints

  • Inputs broadcast and NaN behavior is declared.

Behavioral invariants

  • The output shape follows broadcasting.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Maximum([1,4],[2,3]) gives [2,4].

Related operations

References

ONNX Max ↗
VI.4Atan2Compute an angle from its signed vertical and horizontal coordinates.

What it is

Compute an angle from its signed vertical and horizontal coordinates.

Purpose

Apply the declared scalar map to tensor values.

Common uses

  • Atan2(1,0) gives pi/2.
Tensor and behavior contract

Inputs

Two broadcast-compatible real tensors.

Outputs

Tensor with the broadcast shape.

atan2(Y,X)

Parameters

  • Remainder convention for Mod; otherwise the declared numeric policy.

Shape and rank constraints

  • Inputs broadcast and signed-zero and origin behavior are declared.

Behavioral invariants

  • The output shape follows broadcasting.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Atan2(1,0) gives pi/2.

Related operations

VI.4ComplexConstructCombine real and imaginary parts into complex scalar values.

What it is

Combine real and imaginary parts into complex scalar values.

Purpose

Represent or transform complex-valued model and signal features.

Common uses

  • Construct or inspect a complex Fourier coefficient.
Tensor and behavior contract

Inputs

Real tensors A and B of matching shape and precision.

Outputs

Complex tensor with the same shape.

A + i*B

Parameters

  • Component precision.

Shape and rank constraints

  • Real and complex component formats are compatible.

Behavioral invariants

  • Each scalar is transformed independently and shape is preserved.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Construct or inspect a complex Fourier coefficient.

Related operations

VI.4RealRead the real component of each complex value.

What it is

Read the real component of each complex value.

Purpose

Represent or transform complex-valued model and signal features.

Common uses

  • Construct or inspect a complex Fourier coefficient.
Tensor and behavior contract

Inputs

Complex tensor X.

Outputs

Real tensor with the same shape and component precision.

real(X)

Parameters

  • Component precision.

Shape and rank constraints

  • Real and complex component formats are compatible.

Behavioral invariants

  • Each scalar is transformed independently and shape is preserved.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Construct or inspect a complex Fourier coefficient.

Related operations

VI.4ImagRead the imaginary component of each complex value.

What it is

Read the imaginary component of each complex value.

Purpose

Represent or transform complex-valued model and signal features.

Common uses

  • Construct or inspect a complex Fourier coefficient.
Tensor and behavior contract

Inputs

Complex tensor X.

Outputs

Real tensor with the same shape and component precision.

imag(X)

Parameters

  • Component precision.

Shape and rank constraints

  • Real and complex component formats are compatible.

Behavioral invariants

  • Each scalar is transformed independently and shape is preserved.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Construct or inspect a complex Fourier coefficient.

Related operations

VI.4ConjugateNegate the imaginary component of each complex value.

What it is

Negate the imaginary component of each complex value.

Purpose

Represent or transform complex-valued model and signal features.

Common uses

  • Construct or inspect a complex Fourier coefficient.
Tensor and behavior contract

Inputs

Complex tensor X.

Outputs

Complex tensor with the same shape.

conj(a+i*b) = a-i*b

Parameters

  • Component precision.

Shape and rank constraints

  • Real and complex component formats are compatible.

Behavioral invariants

  • Each scalar is transformed independently and shape is preserved.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Construct or inspect a complex Fourier coefficient.

Related operations

Stochastic & Robustness Operators

Scope

Operations that introduce stochastic behavior or modify data to improve robustness, regularization, or invariance. This includes noise injection, drop mechanisms, and data augmentation operators expressed at the operation level.

13 entries
VII.2DropoutRandomly sets a fraction of activations to zero during training. Each forward pass drops different random elements.

What it is

Randomly sets a fraction of activations to zero during training. Each forward pass drops different random elements.

Purpose

Preventing overfitting by forcing the network to not rely on any single neuron. Creates ensemble-like effect from one network.

Common uses

  • Regularizing fully-connected layers
  • Preventing co-adaptation of neurons
  • Most neural networks as standard regularization
  • After dense layers, before final classification

What it's NOT

  • Not data augmentation – Applied to internal activations, not input data
  • Not pruning – Temporary and random during training, not permanent removal
  • Not BatchNorm – Dropout zeros elements randomly; BatchNorm normalizes
  • Not active during inference – Usually disabled during testing

Analogy

Like practicing a team sport where random players are benched each game. The team learns not to rely on any one player, making everyone important.

VII.2Dropout2DDrops entire feature maps (channels) instead of individual elements. Spatial dropout for convolutional networks.

What it is

Drops entire feature maps (channels) instead of individual elements. Spatial dropout for convolutional networks.

Purpose

Preventing co-adaptation of feature maps. More appropriate than regular dropout for convolutional layers.

Common uses

  • Regularizing convolutional networks
  • After convolutional layers where spatial structure matters
  • Preventing channel co-adaptation
  • Vision architectures

What it's NOT

  • Not regular dropout – Drops whole channels, not individual pixels
  • Not spatial dropout on individual features – Operates on entire feature maps
  • Not stochastic depth – Drops channels, not layers

Analogy

Like turning off entire color channels in an image (all red, all green, etc.) rather than random individual pixels.

VII.2StochasticDepthRandomly skips entire layers during training, using residual connections. Randomly drops computational paths.

What it is

Randomly skips entire layers during training, using residual connections. Randomly drops computational paths.

Purpose

Regularizing very deep networks, reducing training time, and improving gradient flow.

Common uses

  • Very deep residual networks
  • Efficient training of large models
  • Preventing over-reliance on specific layers
  • Models with many residual blocks

What it's NOT

  • Not dropout – Drops entire layers, not activations
  • Not pruning – Temporary during training, not permanent removal
  • Not active at test time – All layers used during inference

Analogy

Like practicing a relay race where team members randomly sit out—forces the team to work with different combinations, making everyone essential.

VII.2TokenDropRandomly removes some tokens from a sequence during training. Reduces sequence length dynamically.

What it is

Randomly removes some tokens from a sequence during training. Reduces sequence length dynamically.

Purpose

Speeding up transformer training, regularization, and forcing models to handle missing information.

Common uses

  • Efficient transformer training
  • Vision transformers (dropping image patches)
  • Regularizing sequence models
  • Reducing computational cost in long sequences

What it's NOT

  • Not attention masking – Physically removes tokens, doesn't just mask
  • Not random token replacement – Removes entirely, doesn't substitute
  • Not dropout – Removes entire tokens, not individual features

Analogy

Like speed-reading where you skip some words but still understand the passage—forces the model to be robust to missing information.

VII.1UniformRandomDraw independent values uniformly between declared bounds.

What it is

Draw independent values uniformly between declared bounds.

Purpose

Supply explicit random samples to a neural computation.

Common uses

  • Draw perturbations in [0,1).
Tensor and behavior contract

Inputs

Requested shape and scalar bounds.

Outputs

Real tensor of the requested shape.

Parameters

  • Lower bound, exclusive upper bound, output type, RNG state.

Shape and rank constraints

  • Lower bound is less than upper bound.

Behavioral invariants

  • The output follows the declared distribution and shape contract.

Semantics

Stochastic; reproducibility requires the same explicitly specified random generator, state, and sampling algorithm.

Examples

  • Draw perturbations in [0,1).

Related operations

VII.1NormalRandomDraw independent values from a normal distribution.

What it is

Draw independent values from a normal distribution.

Purpose

Supply explicit random samples to a neural computation.

Common uses

  • Draw standard-normal latent noise.
Tensor and behavior contract

Inputs

Requested shape, mean, and standard deviation.

Outputs

Real tensor of the requested shape.

Parameters

  • Mean, nonnegative standard deviation, output type, RNG state.

Shape and rank constraints

  • Standard deviation is nonnegative.

Behavioral invariants

  • The output follows the declared distribution and shape contract.

Semantics

Stochastic; reproducibility requires the same explicitly specified random generator, state, and sampling algorithm.

Examples

  • Draw standard-normal latent noise.

Related operations

VII.1BernoulliSampleDraw zero or one independently according to supplied probabilities.

What it is

Draw zero or one independently according to supplied probabilities.

Purpose

Supply explicit random samples to a neural computation.

Common uses

  • Sample a keep mask for dropout.
Tensor and behavior contract

Inputs

Probability tensor P.

Outputs

Zero-one tensor with the same shape.

Parameters

  • Output type and RNG state.

Shape and rank constraints

  • Every probability lies in [0,1].

Behavioral invariants

  • The output follows the declared distribution and shape contract.

Semantics

Stochastic; reproducibility requires the same explicitly specified random generator, state, and sampling algorithm.

Examples

  • Sample a keep mask for dropout.

Related operations

VII.1MultinomialSampleDraw category indices according to a supplied distribution or nonnegative category weights.

What it is

Draw category indices according to a supplied distribution or nonnegative category weights.

Purpose

Supply explicit random samples to a neural computation.

Common uses

  • Sample token IDs from predicted probabilities.
Tensor and behavior contract

Inputs

A category-weight vector or batch of vectors.

Outputs

Integer category indices.

Parameters

  • Sample count, replacement flag, RNG state.

Shape and rank constraints

  • Weights are nonnegative and finite with a positive sum; sampling without replacement cannot exceed positive-weight categories.

Behavioral invariants

  • The output follows the declared distribution and shape contract.

Semantics

Stochastic; reproducibility requires the same explicitly specified random generator, state, and sampling algorithm.

Examples

  • Sample token IDs from predicted probabilities.

Related operations

VII.1PoissonSampleDraw nonnegative integer counts with a supplied expected rate.

What it is

Draw nonnegative integer counts with a supplied expected rate.

Purpose

Supply explicit random samples to a neural computation.

Common uses

  • Simulate random event counts.
Tensor and behavior contract

Inputs

Nonnegative rate tensor.

Outputs

Count-valued tensor with the same shape.

Parameters

  • RNG state and output representation.

Shape and rank constraints

  • Rates are finite and nonnegative.

Behavioral invariants

  • The output follows the declared distribution and shape contract.

Semantics

Stochastic; reproducibility requires the same explicitly specified random generator, state, and sampling algorithm.

Examples

  • Simulate random event counts.

Related operations

VII.2AlphaDropoutRandomly replace activations with a negative saturation value and rescale to preserve self-normalizing statistics.

What it is

Randomly replace activations with a negative saturation value and rescale to preserve self-normalizing statistics.

Purpose

Regularize self-normalizing networks.

Common uses

  • Regularize a network using SELU activations.
Tensor and behavior contract

Inputs

Real tensor X and explicit random state.

Outputs

Tensor with the same shape.

Parameters

  • Drop probability, training flag, SELU saturation constants.

Shape and rank constraints

  • Drop probability is in [0,1); the rescaling rule is explicit.

Behavioral invariants

  • Evaluation mode is identity; training preserves the intended zero-mean unit-variance fixed point.

Semantics

Stochastic during training; the evaluation mapping is deterministic identity.

Examples

  • Regularize a network using SELU activations.

Related operations

VII.2DropBlockDrop contiguous blocks of a feature map instead of isolated elements.

What it is

Drop contiguous blocks of a feature map instead of isolated elements.

Purpose

Prevent nearby convolutional features from bypassing dropout.

Common uses

  • Suppress square regions of a convolutional feature map.
Tensor and behavior contract

Inputs

Spatial features and explicit random state.

Outputs

Features with a sampled block mask and declared rescaling.

Parameters

  • Block size, drop rate, training flag.

Shape and rank constraints

  • Blocks fit the declared spatial domain and the kept-value rescaling is defined.

Behavioral invariants

  • Training masks cover contiguous spatial regions; evaluation is identity.

Semantics

Stochastic during training; explicit random state controls block selection.

Examples

  • Suppress square regions of a convolutional feature map.

Related operations

References

DropBlock ↗
VII.3CutMixReplace an image region with a region from another example and mix their targets by the replaced area.

What it is

Replace an image region with a region from another example and mix their targets by the replaced area.

Purpose

Train classifiers using spatially mixed examples.

Common uses

  • Paste a patch from one training image into another.
Tensor and behavior contract

Inputs

Image batch, matching targets, and explicit random state.

Outputs

Mixed images and area-weighted mixed targets.

Parameters

  • Mixing distribution, sampled rectangle, pairing permutation.

Shape and rank constraints

  • Paired images and targets are compatible; target weights use the actual clipped patch area.

Behavioral invariants

  • The two target weights sum to one.

Semantics

Stochastic augmentation; pairing and patch sampling use explicit random state.

Examples

  • Paste a patch from one training image into another.

Related operations

References

CutMix ↗
VII.3RandomErasingReplace a sampled image rectangle with declared constant or random values.

What it is

Replace a sampled image rectangle with declared constant or random values.

Purpose

Teach robustness to missing or occluded image regions.

Common uses

  • Simulate an occluded object during training.
Tensor and behavior contract

Inputs

Image tensor and explicit random state.

Outputs

Image of the same shape with a possible erased region.

Parameters

  • Application probability, area range, aspect-ratio range, fill rule.

Shape and rank constraints

  • Area and aspect-ratio bounds are positive and the selected rectangle fits the image.

Behavioral invariants

  • Pixels outside the selected region are unchanged.

Semantics

Stochastic augmentation; fill sampling and region selection use explicit random state.

Examples

  • Simulate an occluded object during training.

Related operations

Learning Mechanics & Quantization

Scope

Operations that define objectives, learning rules, gradient transforms, schedules, and quantization/compression mechanics. This kingdom captures how models are trained and how parameters and representations are discretized or compressed.

46 entries
VIII.1CrossEntropyLogitsCompares predicted probabilities (from logits) to true labels, measuring how "surprised" the model would be by the true answer.

What it is

Compares predicted probabilities (from logits) to true labels, measuring how "surprised" the model would be by the true answer.

Purpose

The standard loss for classification. Encourages the model to assign high probability to correct classes.

Common uses

  • Training classifiers (image classification, text classification, etc.)
  • Any multi-class prediction task
  • Language modeling
  • Most supervised learning with categorical outputs

What it's NOT

  • Not mean squared error – Cross-entropy is for probabilities/categories; MSE is for continuous values
  • Not just softmax – Includes both softmax and logarithmic loss computation
  • Not only for neural networks – Used across machine learning for probabilistic classification

Analogy

Like a penalty for being surprised. If you confidently predict rain (high probability) and it rains, small penalty. If you say "no chance of rain" and it pours, huge penalty.

VIII.1MeanSquaredErrorAverages the squared differences between predictions and targets. Penalizes larger errors more than smaller ones.

What it is

Averages the squared differences between predictions and targets. Penalizes larger errors more than smaller ones.

Purpose

Standard loss for regression tasks. Measures how far predictions are from true values.

Common uses

  • Regression (predicting continuous values like prices, temperatures)
  • Image reconstruction tasks
  • Denoising autoencoders
  • Any task where you want to minimize distance to true values

What it's NOT

  • Not cross-entropy – For continuous values, not categories/probabilities
  • Not mean absolute error – Squares errors, doesn't just take absolute value
  • Not robust to outliers – Squared term makes it very sensitive to large errors

Analogy

Like measuring how far your darts land from the bullseye, but giving extra penalty for really bad throws (squaring the distance).

VIII.1KLDivergenceMeasures how one probability distribution differs from another. Asymmetric measure of distribution mismatch.

What it is

Measures how one probability distribution differs from another. Asymmetric measure of distribution mismatch.

Purpose

Comparing learned distributions to target distributions, especially in variational inference and generative models.

Common uses

  • Variational autoencoders (matching latent distribution to prior)
  • Distillation (student matching teacher's soft predictions)
  • Information theory applications
  • Generative models

What it's NOT

  • Not a distance metric – Asymmetric (KL(P||Q) ≠ KL(Q||P)) and doesn't satisfy triangle inequality
  • Not cross-entropy – Related but different; cross-entropy includes entropy term
  • Not symmetric – Order matters; measuring P against Q differs from Q against P

Analogy

Like measuring how much extra information you'd need to describe one distribution using another distribution's coding scheme. The "surprise" of using the wrong distribution.

VIII.2SGDStochastic Gradient Descent—updates parameters by moving them in the direction opposite to the gradient, scaled by learning rate.

What it is

Stochastic Gradient Descent—updates parameters by moving them in the direction opposite to the gradient, scaled by learning rate.

Purpose

The fundamental optimization algorithm. Adjusts weights to reduce loss.

Common uses

  • Training neural networks (though often with momentum)
  • Baseline optimization algorithm
  • Situations where simplicity is valued
  • Often augmented with momentum for better performance

What it's NOT

  • Not an architecture – It's how you train, not what you train
  • Not guaranteed to find global optimum – Can get stuck in local minima
  • Not using all data at once – "Stochastic" means it uses batches/samples

Analogy

Like hiking downhill in fog. You can only see your immediate slope (gradient), so you take steps downhill. Learning rate determines step size.

VIII.2AdamAdaptive optimizer that maintains running averages of gradient and squared gradient, automatically adjusting learning rate per parameter.

What it is

Adaptive optimizer that maintains running averages of gradient and squared gradient, automatically adjusting learning rate per parameter.

Purpose

Providing fast convergence with less learning rate tuning than SGD. Adapts to each parameter's behavior.

Common uses

  • Default optimizer for many modern architectures
  • Training transformers and language models
  • Situations where automatic learning rate adaptation helps
  • When you want good performance without extensive tuning

What it's NOT

  • Not always better than SGD – Can generalize worse on some vision tasks
  • Not parameter-free – Still has hyperparameters (learning rate, betas, epsilon)
  • Not the same as AdaGrad or RMSProp – Combines ideas from both but with bias correction

Analogy

Like hiking with a smart walking stick that remembers how steep recent slopes were and adjusts your stride accordingly for each leg independently.

VIII.2AdamWAdam with decoupled weight decay. Separates weight decay from the adaptive learning rate.

What it is

Adam with decoupled weight decay. Separates weight decay from the adaptive learning rate.

Purpose

Fixing a subtle issue in original Adam where weight decay interacted incorrectly with adaptive learning rates.

Common uses

  • Training large transformers (BERT, GPT, etc.)
  • Modern deep learning where better regularization helps
  • Situations where original Adam's weight decay behavior was problematic
  • Current best-practice for many tasks

What it's NOT

  • Not hugely different from Adam – Same core algorithm, different weight decay implementation
  • Not always necessary – Difference matters more for some tasks than others
  • Not a replacement for all regularization – Still might need dropout, etc.

Analogy

Like Adam's smart walking stick, but also has a separate mechanism that ensures you don't carry unnecessary weight (weight decay) independent of terrain adaptation.

VIII.3GradientClipByNormIf gradient magnitude exceeds a threshold, scale it down to the threshold while preserving direction.

What it is

If gradient magnitude exceeds a threshold, scale it down to the threshold while preserving direction.

Purpose

Preventing exploding gradients that would destabilize training, especially in recurrent networks.

Common uses

  • Training RNNs and LSTMs
  • Any architecture prone to gradient explosion
  • Reinforcement learning
  • Situations where gradients can become extreme

What it's NOT

  • Not gradient clipping by value – Clips based on total magnitude, not individual elements
  • Not normalization – Only clips when exceeding threshold, doesn't rescale all gradients
  • Not a replacement for good architecture – Band-aid for gradient problems, not a full solution

Analogy

Like a speed limiter on a car. You can accelerate or brake normally, but if you'd go over the speed limit, the limiter caps your speed.

VIII.3GradientClipByValueClips each element of the gradient independently to be within a range, like [-1, 1].

What it is

Clips each element of the gradient independently to be within a range, like [-1, 1].

Purpose

Preventing individual gradient elements from becoming extreme and destabilizing updates.

Common uses

  • Alternative to norm-based clipping
  • When element-wise extremes are the problem
  • Some reinforcement learning algorithms
  • Situations where norm clipping isn't enough

What it's NOT

  • Not gradient clipping by norm – Clips each element independently, not the overall magnitude
  • Not the common choice – Norm-based clipping usually preferred
  • Not preserving gradient direction – Can change direction by clipping elements differently

Analogy

Like limiting individual ingredients in a recipe rather than limiting total amount. Each ingredient has its own cap.

VIII.4UniformAffineQuantizeMaps floating-point values to a discrete set of levels (like 256 levels for 8-bit), using a uniform spacing and learned zero-point/scale.

What it is

Maps floating-point values to a discrete set of levels (like 256 levels for 8-bit), using a uniform spacing and learned zero-point/scale.

Purpose

Reducing model size and computation by using lower-precision arithmetic while maintaining accuracy.

Common uses

  • Deploying models on mobile or edge devices
  • Reducing memory footprint
  • Speeding up inference with integer arithmetic
  • Model compression for production

What it's NOT

  • Not pruning – Reduces precision, doesn't remove weights
  • Not lossless – Trading accuracy for efficiency
  • Not only for deployment – Can train with quantization too (quantization-aware training)

Analogy

Like converting a high-resolution photo to one with only 256 colors. Takes less space, loads faster, but loses some detail.

VIII.1BinaryCrossEntropyLoss function for binary classification. Measures how well predicted probabilities match true binary labels (0 or 1).

What it is

Loss function for binary classification. Measures how well predicted probabilities match true binary labels (0 or 1).

Purpose

Training binary classifiers. Penalizes confident wrong predictions more than uncertain ones.

Common uses

  • Binary classification (spam/not spam, cat/dog, etc.)
  • Multi-label classification (each label is independent binary)
  • Sigmoid output layers
  • Any yes/no decision tasks

What it's NOT

  • Not categorical cross-entropy – For two classes, not many
  • Not MSE – Designed for probabilities, not continuous values
  • Not hinge loss – Probabilistic interpretation, not margin-based

Analogy

Like scoring a true/false test where you're heavily penalized for being confidently wrong.

VIII.1HingeLossMargin-based loss from SVM theory. Encourages correct class score to be higher than others by at least a margin.

What it is

Margin-based loss from SVM theory. Encourages correct class score to be higher than others by at least a margin.

Purpose

Training models to not just classify correctly, but with confident margins.

Common uses

  • Support vector machines
  • Ranking problems
  • Face verification (triplet loss is related)
  • When margin interpretation is meaningful

What it's NOT

  • Not cross-entropy – Margin-based, not probabilistic
  • Not MSE – Encourages margins, not close values
  • Not only for SVMs – Can be used with neural networks

Analogy

Like a high jump where clearing the bar by any amount counts the same—you just need to beat the threshold by the required margin.

VIII.1ContrastiveLossPulls similar examples together and pushes dissimilar examples apart in embedding space.

What it is

Pulls similar examples together and pushes dissimilar examples apart in embedding space.

Purpose

Learning representations where semantic similarity corresponds to geometric proximity.

Common uses

  • Face recognition (learning face embeddings)
  • Similarity learning
  • Metric learning
  • Self-supervised learning

What it's NOT

  • Not classification loss – Learns embeddings, not class probabilities
  • Not triplet loss – Uses pairs, not triplets
  • Not contrastive learning framework – This is the loss; frameworks use it

Analogy

Like organizing magnets where similar ones attract and dissimilar ones repel, naturally clustering related items.

VIII.2SGDWithMomentumSGD that maintains a velocity term, like a ball rolling downhill that builds up speed. Combines current gradient with previous momentum.

What it is

SGD that maintains a velocity term, like a ball rolling downhill that builds up speed. Combines current gradient with previous momentum.

Purpose

Accelerating convergence and dampening oscillations. Usually much better than plain SGD.

Common uses

  • Default variant of SGD in most frameworks
  • Training convolutional networks for vision
  • When SGD-family optimizers are preferred
  • Often better generalization than Adam on vision tasks

What it's NOT

  • Not vanilla SGD – Includes momentum term
  • Not Adam – Doesn't adapt learning rate per parameter
  • Not Nesterov momentum – Standard momentum, not lookahead variant

Analogy

Like pushing a heavy cart—once it gets moving, it's easier to keep going and harder to change direction suddenly.

VIII.2AdaGradAdapts learning rate per parameter based on historical gradients. Parameters with large gradients get smaller learning rates.

What it is

Adapts learning rate per parameter based on historical gradients. Parameters with large gradients get smaller learning rates.

Purpose

Automatically adjusting learning rates for features that appear rarely vs. frequently.

Common uses

  • Sparse data and NLP (before Adam became dominant)
  • When different features have vastly different scales
  • Online learning scenarios
  • Less common now but historically important

What it's NOT

  • Not Adam – Simpler, doesn't use momentum
  • Not RMSProp – Accumulates all history, not recent window
  • Not the best choice usually – Adam/RMSProp often better

Analogy

Like adjusting your pace based on total distance covered—the more you've walked, the more cautiously you step.

VIII.2RMSPropLike AdaGrad but uses exponential moving average of squared gradients, preventing learning rates from decreasing too much.

What it is

Like AdaGrad but uses exponential moving average of squared gradients, preventing learning rates from decreasing too much.

Purpose

Adaptive learning rates that don't decay too aggressively, fixing AdaGrad's main weakness.

Common uses

  • Alternative to Adam
  • When Adam's bias correction isn't needed
  • RNN training (historically)
  • Situations where simpler than Adam is preferred

What it's NOT

  • Not AdaGrad – Uses moving average, not full history
  • Not Adam – Lacks momentum and bias correction
  • Not outdated – Still useful in some contexts

Analogy

Like AdaGrad but with a fading memory—recent terrain matters more than distant past.

VIII.3GradientNoiseInjectionAdds random noise to gradients during training. Deliberate perturbation of gradient signals.

What it is

Adds random noise to gradients during training. Deliberate perturbation of gradient signals.

Purpose

Regularization, escaping sharp minima, and improving generalization.

Common uses

  • Improving generalization
  • Escaping local minima
  • Reinforcement learning (policy gradient methods)
  • Researching optimization dynamics

What it's NOT

  • Not dropout – Adds noise to gradients, not activations
  • Not data augmentation – Perturbs learning signal, not data
  • Not common practice – Specialized technique, not standard

Analogy

Like adding small random jiggles while descending a hill to avoid getting stuck in small divots.

VIII.4SymmetricQuantizeQuantization where the zero-point is fixed (usually at 0), and positive/negative ranges are symmetric.

What it is

Quantization where the zero-point is fixed (usually at 0), and positive/negative ranges are symmetric.

Purpose

Simpler quantization scheme when symmetric ranges suffice. Often used for weights.

Common uses

  • Weight quantization (weights often roughly symmetric)
  • When zero-point doesn't need calibration
  • Simpler hardware implementations
  • Post-training quantization

What it's NOT

  • Not affine quantization – No learnable zero-point offset
  • Not the only choice – Affine can be better for activations
  • Not lossless – Still approximates original values

Analogy

Like a thermometer centered at zero where positive and negative sides have equal range, simpler than one with an arbitrary zero point.

VIII.4WeightPruningMaskBinary mask that zeros out selected weights permanently. Explicit representation of which weights are "pruned."

What it is

Binary mask that zeros out selected weights permanently. Explicit representation of which weights are "pruned."

Purpose

Creating sparse networks by removing less important weights, reducing model size and computation.

Common uses

  • Model compression
  • Efficient inference
  • Discovering minimal network structures
  • Reducing overfitting through structured regularization

What it's NOT

  • Not dropout – Permanent pruning, not temporary
  • Not quantization – Removes weights, doesn't reduce precision
  • Not automatic – Requires strategy for choosing what to prune

Analogy

Like editing a document by permanently deleting unnecessary words rather than just hiding them—smaller final document.

VIII.1NegativeLogLikelihoodScore the log probability assigned to the target class.

What it is

Score the log probability assigned to the target class.

Purpose

Define an explicit training objective.

Common uses

  • Train a classifier whose output already contains log probabilities.
Tensor and behavior contract

Inputs

Log probabilities [N,C,...] and integer class targets.

Outputs

Per-target losses or a reduced scalar.

loss = -log_probability[target]

Parameters

  • Class weights, ignored target index, reduction.

Shape and rank constraints

  • Targets are valid classes or the ignored index.

Behavioral invariants

  • The declared reduction and weighting determine the final objective scale.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Train a classifier whose output already contains log probabilities.

Related operations

VIII.1CosineEmbeddingLossEncourage paired vectors to align or remain sufficiently different.

What it is

Encourage paired vectors to align or remain sufficiently different.

Purpose

Define an explicit training objective.

Common uses

  • Train embeddings from matching and nonmatching pairs.
Tensor and behavior contract

Inputs

Paired vectors [N,D] and labels +1 or -1.

Outputs

One loss per pair or a reduced scalar.

positive: 1-cos(x,z); negative: max(0,cos(x,z)-margin)

Parameters

  • Cosine margin and reduction.

Shape and rank constraints

  • Pairs have equal feature width and labels are +1 or -1.

Behavioral invariants

  • The declared reduction and weighting determine the final objective scale.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Train embeddings from matching and nonmatching pairs.

Related operations

VIII.1MarginRankingLossPenalize pairs whose scores violate a required ordering margin.

What it is

Penalize pairs whose scores violate a required ordering margin.

Purpose

Define an explicit training objective.

Common uses

  • Rank a relevant item above an irrelevant one.
Tensor and behavior contract

Inputs

Scores X1, X2 and ordering labels Y in {-1,+1}.

Outputs

Elementwise ranking losses or a reduced scalar.

max(0,-Y*(X1-X2)+margin)

Parameters

  • Nonnegative margin and reduction.

Shape and rank constraints

  • Inputs have compatible shapes and labels use the declared sign convention.

Behavioral invariants

  • The declared reduction and weighting determine the final objective scale.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Rank a relevant item above an irrelevant one.

Related operations

VIII.1HuberLossUse squared error for small mistakes and a linear penalty for large mistakes.

What it is

Use squared error for small mistakes and a linear penalty for large mistakes.

Purpose

Define an explicit training objective.

Common uses

  • Train regression with occasional outliers.
Tensor and behavior contract

Inputs

Real predictions and matching targets.

Outputs

Elementwise losses or a reduced scalar.

0.5*e^2 if abs(e)<=delta; delta*(abs(e)-0.5*delta) otherwise

Parameters

  • Positive delta and reduction.

Shape and rank constraints

  • Prediction and target shapes agree or use an explicitly declared broadcasting rule.

Behavioral invariants

  • The declared reduction and weighting determine the final objective scale.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Train regression with occasional outliers.

Related operations

VIII.1SmoothL1LossUse a beta-scaled quadratic region and a unit-slope linear region for regression errors.

What it is

Use a beta-scaled quadratic region and a unit-slope linear region for regression errors.

Purpose

Define an explicit training objective.

Common uses

  • Regress object bounding boxes with robust errors.
Tensor and behavior contract

Inputs

Real predictions and matching targets.

Outputs

Elementwise losses or a reduced scalar.

0.5*e^2/beta if abs(e)<beta; abs(e)-0.5*beta otherwise

Parameters

  • Nonnegative beta and reduction.

Shape and rank constraints

  • beta=0 is the absolute-error limit.

Behavioral invariants

  • The declared reduction and weighting determine the final objective scale.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Regress object bounding boxes with robust errors.

Related operations

VIII.1PoissonNLLLossScore observed counts under a predicted Poisson rate.

What it is

Score observed counts under a predicted Poisson rate.

Purpose

Define an explicit training objective.

Common uses

  • Predict event or photon counts.
Tensor and behavior contract

Inputs

Predicted log-rate or rate and nonnegative observed counts.

Outputs

Elementwise likelihood losses or a reduced scalar.

exp(log_rate)-target*log_rate, plus the declared factorial term

Parameters

  • Log-input flag, optional full factorial term, epsilon, reduction.

Shape and rank constraints

  • Non-log rates are nonnegative; count observations are nonnegative.

Behavioral invariants

  • The declared reduction and weighting determine the final objective scale.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Predict event or photon counts.

Related operations

VIII.1GaussianNLLLossScore observations under a Gaussian prediction with an explicit variance.

What it is

Score observations under a Gaussian prediction with an explicit variance.

Purpose

Define an explicit training objective.

Common uses

  • Train a regressor that predicts uncertainty.
Tensor and behavior contract

Inputs

Predicted mean, target, and variance tensors.

Outputs

Elementwise likelihood losses or a reduced scalar.

0.5*(log(var)+(target-mean)^2/var), with declared variance floor and constant

Parameters

  • Positive variance floor, optional normalization constant, reduction.

Shape and rank constraints

  • Variance is nonnegative and its broadcasting pattern is declared.

Behavioral invariants

  • The declared reduction and weighting determine the final objective scale.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Train a regressor that predicts uncertainty.

Related operations

VIII.1CTCLossSum the probabilities of valid blank-and-repeat alignments between sequence outputs and labels.

What it is

Sum the probabilities of valid blank-and-repeat alignments between sequence outputs and labels.

Purpose

Define an explicit training objective.

Common uses

  • Train speech recognition without frame-by-frame label alignment.
Tensor and behavior contract

Inputs

Log probabilities [T,N,C], target labels, input lengths, and target lengths.

Outputs

Per-sequence losses or a reduced scalar.

-log(sum over valid alignments a of product_t P(a_t at t))

Parameters

  • Blank class, reduction, zero-infinity policy.

Shape and rank constraints

  • Targets exclude the blank label and lengths fit their sequence storage.

Behavioral invariants

  • The declared reduction and weighting determine the final objective scale.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Train speech recognition without frame-by-frame label alignment.

Related operations

VIII.1DiceLossPenalize poor overlap between a soft segmentation prediction and its target.

What it is

Penalize poor overlap between a soft segmentation prediction and its target.

Purpose

Define an explicit training objective.

Common uses

  • Train segmentation when foreground pixels are rare.
Tensor and behavior contract

Inputs

Nonnegative segmentation probabilities P and compatible target mask T.

Outputs

Per-region losses or a reduced scalar.

1 - (2*sum(P*T)+epsilon)/(sum(P^2)+sum(T^2)+epsilon)

Parameters

  • Reduction axes, positive smoothing epsilon, squared-sum denominator.

Shape and rank constraints

  • Predictions and targets share the declared spatial and class layout.

Behavioral invariants

  • The declared reduction and weighting determine the final objective scale.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Train segmentation when foreground pixels are rare.

Related operations

References

V-Net ↗
VIII.1FocalLossDownweight easy classification examples so difficult examples matter more.

What it is

Downweight easy classification examples so difficult examples matter more.

Purpose

Define an explicit training objective.

Common uses

  • Train an object detector with many easy background examples.
Tensor and behavior contract

Inputs

Class probabilities or logits and matching class targets.

Outputs

Elementwise losses or a reduced scalar.

-alpha_t*(1-p_t)^gamma*log(p_t)

Parameters

  • Nonnegative focusing gamma, class weight alpha, binary or categorical mode, reduction.

Shape and rank constraints

  • The probability/logit interpretation and target layout are explicit.

Behavioral invariants

  • The declared reduction and weighting determine the final objective scale.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Train an object detector with many easy background examples.

Related operations

VIII.2NAdamUse Adam moments with a Nesterov-style momentum correction.

What it is

Use Adam moments with a Nesterov-style momentum correction.

Purpose

Update learned model parameters during training.

Common uses

  • Apply one NAdam update after a backward pass.
Tensor and behavior contract

Inputs

Parameters, matching gradients, persistent optimizer state, and step counter.

Outputs

Updated parameters and optimizer state.

Parameters

  • Learning rate, beta1, beta2, epsilon, momentum decay, weight decay.

Shape and rank constraints

  • Parameter, gradient, and state shapes agree.

Behavioral invariants

  • State updates follow the declared optimizer rule; optimizer state is separate from model activations.

Semantics

Stateful; identical state and inputs define the same mathematical update, subject to declared numeric rounding.

Examples

  • Apply one NAdam update after a backward pass.

Related operations

VIII.2RAdamRectify Adam's adaptive update using the estimated variance of its early second-moment history.

What it is

Rectify Adam's adaptive update using the estimated variance of its early second-moment history.

Purpose

Update learned model parameters during training.

Common uses

  • Apply one RAdam update after a backward pass.
Tensor and behavior contract

Inputs

Parameters, matching gradients, persistent optimizer state, and step counter.

Outputs

Updated parameters and optimizer state.

Parameters

  • Learning rate, beta1, beta2, epsilon, weight decay.

Shape and rank constraints

  • Parameter, gradient, and state shapes agree.

Behavioral invariants

  • State updates follow the declared optimizer rule; optimizer state is separate from model activations.

Semantics

Stateful; identical state and inputs define the same mathematical update, subject to declared numeric rounding.

Examples

  • Apply one RAdam update after a backward pass.

Related operations

VIII.2AdadeltaAdapt updates using running squared-gradient and squared-update averages.

What it is

Adapt updates using running squared-gradient and squared-update averages.

Purpose

Update learned model parameters during training.

Common uses

  • Apply one Adadelta update after a backward pass.
Tensor and behavior contract

Inputs

Parameters, matching gradients, persistent optimizer state, and step counter.

Outputs

Updated parameters and optimizer state.

Parameters

  • Decay rho, positive epsilon, learning-rate multiplier, weight decay.

Shape and rank constraints

  • Parameter, gradient, and state shapes agree.

Behavioral invariants

  • State updates follow the declared optimizer rule; optimizer state is separate from model activations.

Semantics

Stateful; identical state and inputs define the same mathematical update, subject to declared numeric rounding.

Examples

  • Apply one Adadelta update after a backward pass.

Related operations

VIII.2ASGDApply stochastic gradient updates while maintaining averaged parameter iterates.

What it is

Apply stochastic gradient updates while maintaining averaged parameter iterates.

Purpose

Update learned model parameters during training.

Common uses

  • Apply one ASGD update after a backward pass.
Tensor and behavior contract

Inputs

Parameters, matching gradients, persistent optimizer state, and step counter.

Outputs

Updated parameters and optimizer state.

Parameters

  • Learning rate, decay lambda, decay exponent alpha, averaging start t0, weight decay.

Shape and rank constraints

  • Parameter, gradient, and state shapes agree.

Behavioral invariants

  • State updates follow the declared optimizer rule; optimizer state is separate from model activations.

Semantics

Stateful; identical state and inputs define the same mathematical update, subject to declared numeric rounding.

Examples

  • Apply one ASGD update after a backward pass.

Related operations

VIII.2RpropAdjust each parameter's step size according to changes in gradient sign.

What it is

Adjust each parameter's step size according to changes in gradient sign.

Purpose

Update learned model parameters during training.

Common uses

  • Apply one Rprop update after a backward pass.
Tensor and behavior contract

Inputs

Parameters, matching gradients, persistent optimizer state, and step counter.

Outputs

Updated parameters and optimizer state.

Parameters

  • Initial step size, increase/decrease factors, minimum and maximum step sizes.

Shape and rank constraints

  • Parameter, gradient, and state shapes agree.

Behavioral invariants

  • State updates follow the declared optimizer rule; optimizer state is separate from model activations.

Semantics

Stateful; identical state and inputs define the same mathematical update, subject to declared numeric rounding.

Examples

  • Apply one Rprop update after a backward pass.

Related operations

VIII.2MuonForm momentum for a matrix gradient and approximately orthogonalize the update before applying it.

What it is

Form momentum for a matrix gradient and approximately orthogonalize the update before applying it.

Purpose

Update learned model parameters during training.

Common uses

  • Apply one Muon update after a backward pass.
Tensor and behavior contract

Inputs

Parameters, matching gradients, persistent optimizer state, and step counter.

Outputs

Updated parameters and optimizer state.

Parameters

  • Learning rate, momentum, Nesterov flag, orthogonalization iterations, weight decay.

Shape and rank constraints

  • Parameter, gradient, and state shapes agree.
  • The orthogonalized parameter is a matrix; vector parameters use a separately declared optimizer.

Behavioral invariants

  • State updates follow the declared optimizer rule; optimizer state is separate from model activations.

Semantics

Stateful; identical state and inputs define the same mathematical update, subject to declared numeric rounding.

Examples

  • Apply one Muon update after a backward pass.

Related operations

VIII.2LBFGSApproximate an inverse Hessian from a limited history of parameter and gradient differences.

What it is

Approximate an inverse Hessian from a limited history of parameter and gradient differences.

Purpose

Optimize an objective using curvature information without storing a full Hessian.

Common uses

  • Fit a small full-batch model with a smooth objective.
Tensor and behavior contract

Inputs

Parameters, differentiable objective/gradient evaluator, and limited update history.

Outputs

Updated parameters, objective value, and history.

Parameters

  • Learning rate, history size, iteration/evaluation limits, tolerances, line-search rule.

Shape and rank constraints

  • The objective evaluator is valid at every trial point and parameters admit a common flattened representation.

Behavioral invariants

  • History length remains within the declared bound.

Semantics

Stateful; the same objective and state determine the update, including any declared line search.

Examples

  • Fit a small full-batch model with a smooth objective.

Related operations

VIII.2ExponentialMovingAverageBlend current parameters into a persistent exponentially weighted parameter average.

What it is

Blend current parameters into a persistent exponentially weighted parameter average.

Purpose

Maintain a smoothed model for evaluation or teacher targets.

Common uses

  • Maintain teacher weights during self-supervised training.
Tensor and behavior contract

Inputs

Current parameters W and matching average M.

Outputs

Updated average M.

M_next = beta*M + (1-beta)*W

Parameters

  • Decay beta in [0,1), initialization rule, update interval.

Shape and rank constraints

  • Current and average parameter structures agree.

Behavioral invariants

  • The averaging state is separate from the trainable model parameters.

Semantics

Stateful and deterministic for an explicit parameter sequence.

Examples

  • Maintain teacher weights during self-supervised training.

Related operations

VIII.3StopGradientReturn the same forward values while preventing derivatives from crossing this graph edge.

What it is

Return the same forward values while preventing derivatives from crossing this graph edge.

Purpose

Freeze a target or detach an auxiliary computation during training.

Common uses

  • Detach a teacher target before computing a student loss.
Tensor and behavior contract

Inputs

Tensor X and an automatic-differentiation graph edge.

Outputs

Tensor with identical values, shape, and type.

forward(X)=X; derivative=0

Parameters

  • None.

Shape and rank constraints

  • The differentiation rule is attached to this graph edge rather than inferred from values.

Behavioral invariants

  • Forward values are unchanged and the derivative through this edge is zero.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Detach a teacher target before computing a student loss.

Related operations

VIII.3GradientReverseKeep forward values unchanged but multiply their backward gradients by a negative coefficient.

What it is

Keep forward values unchanged but multiply their backward gradients by a negative coefficient.

Purpose

Train features that confuse an adversarial classifier.

Common uses

  • Learn domain-invariant features with an adversarial domain head.
Tensor and behavior contract

Inputs

Tensor X and its graph edge.

Outputs

Tensor with identical forward values.

forward(X)=X; backward(g)=-lambda*g

Parameters

  • Nonnegative reversal strength lambda.

Shape and rank constraints

  • lambda is a declared scalar and the custom backward rule is explicit.

Behavioral invariants

  • Forward is identity and backward multiplies the incoming gradient by -lambda.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Learn domain-invariant features with an adversarial domain head.

Related operations

VIII.3GradientScaleMultiply an explicitly supplied gradient tensor by a scalar factor.

What it is

Multiply an explicitly supplied gradient tensor by a scalar factor.

Purpose

Scale, unscale, or weight a training gradient.

Common uses

  • Unscale mixed-precision gradients before clipping.
Tensor and behavior contract

Inputs

Gradient tensor G and scalar factor s.

Outputs

Gradient tensor with the shape of G.

G_out=s*G

Parameters

  • Scale factor.

Shape and rank constraints

  • s is a compatible scalar; finite-result requirements are declared.

Behavioral invariants

  • Gradient shape is unchanged.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Unscale mixed-precision gradients before clipping.

Related operations

VIII.3GradientAccumulateAdd a new gradient contribution into an explicit accumulation buffer.

What it is

Add a new gradient contribution into an explicit accumulation buffer.

Purpose

Combine microbatch gradients before one optimizer update.

Common uses

  • Accumulate four microbatches before stepping AdamW.
Tensor and behavior contract

Inputs

Gradient buffer A and shape-compatible contribution G.

Outputs

Updated accumulation buffer.

A_next=A+weight*G

Parameters

  • Contribution weight and explicit reset boundary.

Shape and rank constraints

  • Buffer and contribution shapes and types agree.

Behavioral invariants

  • Each contribution is added once before the declared optimizer boundary.

Semantics

Stateful; floating-point accumulation order is part of the declared numerical policy.

Examples

  • Accumulate four microbatches before stepping AdamW.

Related operations

VIII.4DequantizeConvert integer codes back into approximate real values using an affine scale and zero point.

What it is

Convert integer codes back into approximate real values using an affine scale and zero point.

Purpose

Interpret quantized weights or activations.

Common uses

  • Decode int8 activations before a floating-point consumer.
Tensor and behavior contract

Inputs

Integer codes Q, positive scale S, and zero point Z.

Outputs

Real tensor with the shape of Q.

X_hat=(Q-Z)*S

Parameters

  • Quantization axis or block shape and output type.

Shape and rank constraints

  • Scale and zero-point shapes match the declared granularity.

Behavioral invariants

  • The declared quantization grid maps each code to one real reconstruction value.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Decode int8 activations before a floating-point consumer.

Related operations

VIII.4DynamicQuantizeCompute affine integer-grid settings from an input tensor and quantize it with those settings.

What it is

Compute affine integer-grid settings from an input tensor and quantize it with those settings.

Purpose

Quantize activations whose useful range changes at runtime.

Common uses

  • Quantize a batch of activations using its observed range.
Tensor and behavior contract

Inputs

Real tensor X.

Outputs

Quantized codes, positive scale, and integer zero point.

Parameters

  • Integer code range, range-estimation rule, rounding and saturation policies.

Shape and rank constraints

  • The range-estimation rule declares a nonzero scale for constant tensors.

Behavioral invariants

  • Returned scale and zero point describe the grid used for every output code.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Quantize a batch of activations using its observed range.

Related operations

VIII.4FakeQuantizeQuantize and dequantize values while keeping a floating-point forward result.

What it is

Quantize and dequantize values while keeping a floating-point forward result.

Purpose

Simulate quantization error during training.

Common uses

  • Train a model to tolerate int8 activation quantization.
Tensor and behavior contract

Inputs

Real tensor X, scale, and zero point.

Outputs

Floating-point reconstruction tensor with the shape of X.

Y=(clamp(round(X/S)+Z,qmin,qmax)-Z)*S

Parameters

  • Integer code range, granularity, rounding, clipping, explicit backward estimator.

Shape and rank constraints

  • Scale is positive and the estimator is explicitly defined.

Behavioral invariants

  • Forward values lie on the declared reconstructed quantization grid.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Train a model to tolerate int8 activation quantization.

Related operations

VIII.4VectorQuantizeReplace each feature vector by its nearest declared codebook vector.

What it is

Replace each feature vector by its nearest declared codebook vector.

Purpose

Represent continuous features with discrete latent codes.

Common uses

  • Encode audio features with a discrete latent code.
Tensor and behavior contract

Inputs

Features [...,D] and codebook [K,D].

Outputs

Code indices [...] and selected vectors [...,D].

index=argmin_k distance(X,codebook[k]); Y=codebook[index]

Parameters

  • Distance metric, deterministic tie rule, optional explicitly declared training estimator.

Shape and rank constraints

  • Feature widths match, K is positive, and the metric and tie rule are fixed.

Behavioral invariants

  • Every selected vector is an entry in the supplied codebook.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Encode audio features with a discrete latent code.

Related operations

VIII.4CodebookQuantizeMap each scaled scalar value to the nearest entry of a declared nonuniform codebook.

What it is

Map each scaled scalar value to the nearest entry of a declared nonuniform codebook.

Purpose

Compress values using reconstruction levels that need not be evenly spaced.

Common uses

  • NF4 quantization is a specialization using its fixed codebook for normalized weight blocks.
Tensor and behavior contract

Inputs

Real tensor X, scalar codebook [K], and declared block scales.

Outputs

Code indices and the required scale metadata.

Q=argmin_k abs(X/scale-codebook[k])

Parameters

  • Codebook values, block shape, nearest-level tie rule, saturation.

Shape and rank constraints

  • K is positive, scales are positive, and every input belongs to a declared scale block.

Behavioral invariants

  • Dequantization reconstructs the selected codebook value times its block scale.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • NF4 quantization is a specialization using its fixed codebook for normalized weight blocks.

Related operations

References

QLoRA ↗
VIII.4LowBitUnpackExtract fixed-width integer codes from packed storage words.

What it is

Extract fixed-width integer codes from packed storage words.

Purpose

Recover quantized codes before their numerical interpretation.

Common uses

  • Extract two 4-bit codes from each byte.
Tensor and behavior contract

Inputs

Packed words and logical output element count.

Outputs

Integer codes in logical element order.

code[i]=(word >> bit_offset[i]) & ((1<<bits)-1)

Parameters

  • Bits per code, low-to-high bit order, signed-code interpretation.

Shape and rank constraints

  • Storage has enough bits for the logical count; padding bits are excluded.

Behavioral invariants

  • Unpacking the matching LowBitPacking representation recovers its original codes.

Semantics

Deterministic for the same inputs and declared parameters.

Examples

  • Extract two 4-bit codes from each byte.

Related operations

About the encyclopedia

This encyclopedia catalogs every species in the Neural Operation Taxonomy IndeX (NOTIX). Each entry explains what the operation does, why you'd use it, and what it's not—all in language accessible to someone learning these concepts for the first time.

Core taxonomic model
8 kingdoms / 241 encyclopedia entriesTaxonomy first, implementation later.Josh Morgan