softmax and log_softmax#

A softmax turns a row of scores into weights that are positive and add up to 1: each score's exponential over the sum of the row's exponentials. A classifier's last layer takes one, and so does every attention head. log_softmax is its logarithm, which a cross-entropy loss reads. It is computed without forming the weights, so a weight too small for the format still has a finite logarithm.

In ExactRef, er.softmax(x, axis=-1) and er.log_softmax(x, axis=-1) compute them along one dimension, as torch.softmax and torch.log_softmax do. They are also under er.nn.softmax. Each output element is the reference: the exact value rounded once. To check another implementation's output against it, use covers(), as in the examples below.

For finite scores the exact value is never a float and never halfway between two, with two exceptions that ExactRef rounds as fractions. A softmax row whose finite scores are all equal gives each of them one over their count, and a log_softmax row with one finite score gives it 0. Otherwise ExactRef computes the row to more and more digits until every element's rounding is certain. If 16,384 bits were ever not enough, the call would raise ReferenceUnavailableError.

The tolerance says, per element, how far a correct implementation's output can be from the reference. A correct implementation takes the steps below in the compute format (float32 for inputs narrower than float32, else the input format):

reference exp(x_j) / sum(exp(x)), exactly rounded once softmax x_j - largest rounded exp of each within ulps their sum each addition rounded each / sum rounded log_softmax the first three steps log of the sum within ulps shifted - log rounded logsumexp the first three steps log of the sum within ulps log + largest rounded Every step is in the compute format; each result is then rounded to the output.

Where softmax, log_softmax, and logsumexp round. Each reference rounds its exact value once, as softmax's does.

Subtracting the row's largest score first keeps every exponential at 1 or below, so none overflows. ulps says how close the library's exponential and logarithm are to the exact ones, in steps of the compute format (default 1, as for exp and log). Most of the tolerance comes from the sum, because every addition rounds and a row of 50,257 scores has 50,256 of them. By default the tolerance covers normal accumulation, the order ordinary kernels add in: here index order, or 2, 4, 8, or 16 interleaved lanes, which includes PyTorch's CPU kernels on ARM and on x86 with AVX2 or AVX-512. For bfloat16 and float16 inputs it also covers how PyTorch's 16-bit kernels add. softmax's adds whole blocks of 4, 8, or 16 lanes, then the leftover terms in order. log_softmax's, and both backwards', keep two blocks side by side, up to 32 lanes. standard="any_order" covers any order of additions, and is about twice as wide.

Arguments#

Argument

Meaning

Default

x

the scores: a floating-point array

required

axis

the dimension the rows run along

-1, the last

dtype

the output format, a floating-point format: as with torch.softmax's dtype, the input is converted to it first, and the compute format follows it

the input's format

rounding

the rounding mode of the reference and of a correct implementation's final rounding into the output format

er.Rounding.NEAREST_EVEN

overflow

what a result past the output format's range becomes: "ieee", "saturate", or "nan"

each format's own rule

workers

the number of threads the call computes on; no result depends on it

the performance cores on Apple Silicon, else the physical cores, as PyTorch picks

Examples#

A language model's loss reads the log_softmax of its logits over the whole vocabulary. Here it is for 8 rows of 50,257 logits in float32, checked against PyTorch's:

Code
import numpy as np
import torch
import exactref as er

# Seeded, so every run uses the same values
g = torch.Generator().manual_seed(67)
# Logits over a vocabulary of 50,257 tokens
logits = torch.randn(8, 50257, generator=g) * 4

# ExactRef's result
r = er.log_softmax(logits)
out = torch.log_softmax(logits, -1)
# Could a correct implementation produce PyTorch's output?
print("covered:", r.covers(out).all())

# Element (0, 0): its tolerance and PyTorch's error, in float32 steps there
reference = r.rounded.scalars()[0]
step = abs(float(np.spacing(np.float32(reference))))
print("tolerance, in steps:", r.tolerance().scalars()[0] / step)
print("PyTorch's error, in steps:", abs(out[0, 0].item() - reference) / step)
Output
covered: True
tolerance, in steps: 776.0
PyTorch's error, in steps: 9.0

The tolerance is a worst case over every way the 50,256 additions can round, so it is far wider than the error of one run.

Other kernels#

Along the last dimension, PyTorch's CPU kernel does not divide each exponential by the sum. It computes one over the sum once per row and multiplies by it, which rounds twice per element. The named algorithm softmax_algorithm(reciprocal=True) describes those steps:

Code
from exactref.nn.softmax import softmax_algorithm

# PyTorch's softmax over the vocabulary, against the reciprocal algorithm
out = torch.softmax(logits, -1)
print("covered by the reciprocal algorithm:", softmax_algorithm(reciprocal=True).covers(out, logits).all())
Output
covered by the reciprocal algorithm: True

The other kernels' steps are algorithms too:

Algorithm

What differs

Whose it is

softmax_algorithm(reciprocal=True)

each exponential times a rounded 1 / sum

PyTorch's CPU kernel along the last dimension, and MPS

softmax_algorithm(stored_exp=True)

an exponential may be rounded to the output's 16-bit format before it is added or divided

PyTorch's CPU kernel along another dimension, for float16 and bfloat16

softmax_algorithm(products=True)

the backward as grad * result - result * S

PyTorch on CUDA

log_softmax_algorithm(stored_sum=True)

the sum and its logarithm are rounded to the output's 16-bit format first

PyTorch's CPU kernel along the last dimension, for float16 and bfloat16

Kernels that add a row in an order of their own, such as a GPU's tree or a CPU thread's share of a column, need standard="any_order". PyTorch equivalents gives the arguments for each of PyTorch's kernels.

Scores far apart#

Where one score is far above the others, its weight is closer to 1 than any float below 1, and still below 1. The others' weights are far below the smallest float, and still above 0. The reference rounds those exact values, so it depends on the rounding mode:

Code
# Two scores 1000 apart
far = er.asarray([[0.0, -1000.0]], "float32")

print("to nearest:", er.softmax(far).rounded.tolist())
print("toward zero:", er.softmax(far, rounding=er.Rounding.TOWARD_ZERO).rounded.tolist())
print("log_softmax:", er.log_softmax(far).rounded.tolist())
Output
to nearest: [[1.0, 0.0]]
toward zero: [[0.9999999403953552, 0.0]]
log_softmax: [[-0.0, -1000.0]]

Special values#

A score of -inf gets the weight 0 (-inf from log_softmax) and takes no part in the sum. A row with a NaN or a +inf score, or with no finite score, is NaN throughout, as in PyTorch:

Code
import math

# Rows with -inf, with +inf, and with only -inf
rows = er.asarray([[2.0, -math.inf, 2.0], [2.0, math.inf, 1.0], [-math.inf, -math.inf, -math.inf]], "float32")
print("softmax:", er.softmax(rows).rounded.tolist())
print("log_softmax:", er.log_softmax(rows).rounded.tolist())
Output
softmax: [[0.5, 0.0, 0.5], [nan, nan, nan], [nan, nan, nan]]
log_softmax: [[-0.6931471824645996, -inf, -0.6931471824645996], [nan, nan, nan], [nan, nan, nan]]

Integer and bool inputs raise TypeError, as in PyTorch.

Backward#

r.backward(grad) gives the gradient grad_x for an output gradient grad, each element the exact value rounded once. With P the row's softmax, softmax's is P_j * (grad_j - sum(grad * P)) and log_softmax's is grad_j - P_j * sum(grad). The tolerance covers PyTorch's CPU formulas on the forward's output: (grad - S) * result with S the row's sum of grad * result, and grad - exp(result) * sum(grad). Here it checks autograd's gradient of a cross-entropy loss over the logits above:

Code
import torch.nn.functional as F

# Each row's target token, and the loss on copies of the logits that record gradients
targets = torch.randint(0, 50257, (8,), generator=g)
xs = logits.clone().requires_grad_()
F.nll_loss(torch.log_softmax(xs, -1), targets).backward()

# The loss's gradient with respect to log_softmax's output
grad = -F.one_hot(targets, 50257).float() / 8
b = er.log_softmax(logits).backward(grad)
print("covered:", b["grad_x"].covers(xs.grad).all())
Output
covered: True

Full specification#

er.softmax#

softmax(x, axis=-1, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, workers: int | None = None) -> Result#

The softmax along axis: each element's exponential over the sum of its row's.

Each output element is the exact exp(x_j) / sum(exp(x)) over its row (the elements along axis) rounded once to dtype (default: the input's format), a floating-point format. A row whose finite elements are all equal gives 1 / count exactly; every other value is transcendental and is rounded from the row's enclosures, refined until the rounding is certain (ReferenceUnavailableError if a precision cap is reached first). An element of -inf gives +0. A row with a NaN or a +inf element, or with no finite element, is NaN, as PyTorch gives. Integer and bool inputs raise, as in PyTorch.

tolerance() bounds this method in the compute format (with dtype, the input is converted to it first and the compute format is that format's): each element less the row's largest, rounded; a library exponential of each, within ulps units in the last place (default 1); their sum, by default normal accumulation (index order, or 2, 4, 8, or 16 lanes, and for bfloat16 and float16 the shapes PyTorch's kernels for them add in) and with standard="any_order" any order; and each exponential divided by the sum, rounded. PyTorch's CPU kernel for the last dimension multiplies by a rounded reciprocal instead: softmax_algorithm(reciprocal=True). x may also be an earlier result. Proof: proofs/softmax.md.

er.log_softmax#

log_softmax(x, axis=-1, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, workers: int | None = None) -> Result#

The logarithm of the softmax along axis: each element less its row's logsumexp.

Each output element is the exact x_j - log(sum(exp(x))) over its row (the elements along axis) rounded once to dtype (default: the input's format), a floating-point format. A row with one finite element gives 0 there; every other value is transcendental and is rounded from the row's enclosures, refined until the rounding is certain (ReferenceUnavailableError if a precision cap is reached first). An element of -inf gives -inf. A row with a NaN or a +inf element, or with no finite element, is NaN, as PyTorch gives. Integer and bool inputs raise, as in PyTorch.

tolerance() bounds PyTorch's method in the compute format (with dtype, the input is converted to it first and the compute format is that format's): each element less the row's largest, rounded; a library exponential of each, within ulps units in the last place (default 1); their sum, by default normal accumulation and with standard="any_order" any order; a library logarithm of the sum within ulps; and each shifted element less that logarithm, rounded. PyTorch's CPU kernel for the last dimension in float16 or bfloat16 (the output's format) rounds the sum and its logarithm to that format first: log_softmax_algorithm(stored_sum=True). x may also be an earlier result. Proof: proofs/log_softmax.md.

The backwards#

backward(x, grad, axis=-1, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, workers: int | None = None) -> Result#

Gradient of softmax(x, axis) for the output gradient grad.

grad_x = P_j * (grad_j - sum(grad * P)) over each row, with P the row's softmax, in x's shape and dtype: each element is the exact value rounded once, an exact zero included. tolerance() bounds PyTorch's CPU formula computed in the compute format on the forward's result, (grad - S) * result with S the row's sum of grad * result (a sum of products, bounded as the forward's sum is: by default index order, or 2, 4, 8, or 16 lanes, and for bfloat16 and float16 the shapes PyTorch's kernels for them add in), the difference rounded and the product rounded. CUDA's formula, grad * result - result * S, is softmax_algorithm(products=True). Integer inputs have no gradient. grad must have x's shape. x and grad may also be earlier results.

backward(x, grad, axis=-1, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, workers: int | None = None) -> Result#

Gradient of log_softmax(x, axis) for the output gradient grad.

grad_x = grad_j - P_j * sum(grad) over each row, with P the row's softmax, in x's shape and dtype: each element is the exact value rounded once; where the row's finite elements are all equal or the gradients sum to zero it is rational and rounded exactly, ties included. tolerance() bounds PyTorch's formula computed in the compute format on the forward's result, grad - exp(result) * G with G the row's sum of grad (bounded as the forward's sum is: by default index order, or 2, 4, 8, or 16 lanes, and for bfloat16 and float16 the shapes PyTorch's kernels for them add in), a library exponential within ulps, and the product fused into the difference or rounded first. Where the row is not finite the value is that formula's by IEEE rules on exact values. Integer inputs have no gradient. grad must have x's shape. x and grad may also be earlier results.

See also#