logsumexp#
logsumexp is the logarithm of a sum of exponentials. It adds up
probabilities that are stored as logarithms without leaving the logarithm:
a mixture's likelihood, a partition function, and the normalizer that
log_softmax subtracts are all one. Attention kernels keep each query's
logsumexp for the backward pass.
In ExactRef, er.logsumexp(x, axis=None, *, keepdims=False), also
er.reduction.arithmetic.logsumexp, reduces over the dimensions in axis,
as torch.logsumexp does. Each output element is the reference:
the exact value rounded once. To check another implementation's output
against it, use covers(), as in the example below.
For a row with one finite element the exact value is that element. With
two or more it is never a float and never halfway between two, so ExactRef
computes more and more digits of it until the 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 of
torch.logsumexp, each in the compute format (float32 for inputs
narrower than float32, else the input format): it subtracts the largest
element from each, takes a library exponential of each, adds them up, takes
a library logarithm of the sum, and adds the largest element back.
Where logsumexp rounds, beside softmax and log_softmax, which share its first three steps.
ulps says how close the library's exponential and logarithm are to the
exact ones, in steps of the compute format (default 1). By default the sum
is covered under normal accumulation, the order ordinary kernels add
in (here index order, or 2, 4, 8, or 16 interleaved lanes), and standard="any_order" covers any order. PyTorch's logsumexp adds
with torch.sum, whose order is not normal accumulation, so check it with
standard="any_order".
Arguments#
Argument |
Meaning |
Default |
|---|---|---|
|
the input: real, integer, bool, or complex |
required |
|
the dimensions to reduce over: an int or a tuple of ints |
|
|
keep the reduced dimensions, with size 1 |
|
|
the output format: a floating-point format, or a complex one for a complex input |
the input's format; float32 for integers and bools |
|
the rounding mode of the reference and of a correct implementation's final rounding into the output format |
|
|
what a result past the output format's range becomes: |
each format's own rule |
|
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 |
Example#
The normalizer of a language model's softmax is the logsumexp of each row of logits. Here it is for 8 rows of 50,257 logits in float32, checked against PyTorch's:
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, one element per row
r = er.logsumexp(logits, axis=1)
out = torch.logsumexp(logits, 1)
# Could an implementation that adds in any order produce PyTorch's output?
print("covered:", r.covers(out, standard="any_order").all())
print("rounded:", r.rounded.tolist()[:2])
# The exponentials of these numbers overflow; their logsumexp does not
large = er.asarray([1000.0, 1000.0], "float32")
print("of two 1000s:", er.logsumexp(large).rounded.tolist())
covered: True
rounded: [18.461753845214844, 19.481834411621094]
of two 1000s: 1000.6931762695312
Special values#
An element of -inf adds nothing. A row of only -inf, or of no elements,
gives -inf. A +inf element gives inf, and a NaN gives NaN:
import math
# Rows with -inf, only -inf, +inf, and NaN
rows = er.asarray([[0.0, -math.inf], [-math.inf, -math.inf], [0.0, math.inf], [0.0, math.nan]], "float32")
print("rounded:", er.logsumexp(rows, axis=1).rounded.tolist())
rounded: [0.0, -inf, inf, nan]
Integer and bool inputs give float32, as in PyTorch. The reference is that of the integers themselves, whatever their size, and the tolerance covers an implementation that converts them to float32 first.
Complex inputs#
For complex elements the value is the principal logarithm of the complex sum of exponentials. Its real part is the logarithm of the sum's magnitude, and its imaginary part the sum's angle. Each part of the reference is the exact value rounded once.
A correct implementation subtracts the largest real part, takes the
complex exp of each element, adds the results
in any order, takes the complex log of the sum,
and adds the largest real part back. As for log, the standard sequence is
the C library's on Linux. The normal answer, normal(), is that
sequence with the exponentials added in index order, each library function
correctly rounded, and each step rounded in the compute format.
Two algorithms take the plainer logarithms of
other kernels: er.reduction.arithmetic.logsumexp_algorithm(hypot=True),
PyTorch's on a macOS CPU and on CUDA, and logsumexp_algorithm(sqrt_sum=True),
PyTorch's on MPS:
from exactref.reduction.arithmetic import logsumexp_algorithm
# 64 rows of 1000 complex values
z = torch.complex(torch.randn(64, 1000, generator=g) * 3, torch.randn(64, 1000, generator=g) * 3)
out = torch.logsumexp(z, 1)
# PyTorch on a macOS CPU takes log(hypot(x, y)) for the real part
print("covered by the hypot algorithm:", logsumexp_algorithm(hypot=True).covers(out, z, axis=1).all())
covered by the hypot algorithm: True
Each element of a complex row must be finite, or have a real part of -inf
beside a finite imaginary part, which adds nothing. Any other infinity or
NaN, or a row with no finite element, raises ValueError.
Backward#
r.backward(grad) gives the gradient grad_x = grad * softmax(x) over the
reduced elements (grad * conj(softmax(z)) for complex ones), each element
the exact value rounded once. The tolerance covers PyTorch's formula,
grad * exp(x - result), on the forward's output:
# The logits, and the gradient of each row's logsumexp
xs = logits.clone().requires_grad_()
grad = torch.randn(8, generator=g)
# PyTorch's autograd
torch.logsumexp(xs, 1).backward(grad)
# ExactRef's gradient, held by name
b = er.logsumexp(logits, axis=1).backward(grad)
print("covered:", b["grad_x"].covers(xs.grad, standard="any_order").all())
covered: True
In float16 and bfloat16, PyTorch rounds each step of logsumexp and of its
gradient to the dtype: check them with compute= the dtype.
Full specification#
- logsumexp(x, axis=None, *, keepdims: bool = False, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, workers: int | None = None) Result#
The logarithm of the sum of the exponentials over
axis(None: every dimension; an int or a tuple of ints), keeping the reduced dimensions as 1 withkeepdims.Each output element is the exact
log(sum(exp(x)))of its reduced elements rounded once todtype(default: the input's format), a floating-point format. It is formed asm + log(W)withmthe largest element andWthe sum ofexp(x - m), so no exponential overflows. A single element gives itself; every other finite row gives a transcendental value, rounded from an enclosure refined until the rounding is certain (ReferenceUnavailableErrorif a precision cap is reached first). An element of -inf adds nothing; a row of only -inf, or of no elements, gives -inf; a +inf element gives inf and a NaN gives NaN. Integer and bool inputs give float32 unlessdtypesays otherwise, as PyTorch gives; the reference is that of the integers themselves, and the tolerance covers an implementation that converts them to float32 first.tolerance()bounds PyTorch's method in the compute format: each element less the largest, rounded; a library exponential of each, withinulpsunits in the last place (default 1); their sum, by default normal accumulation (index order, or 2, 4, 8, or 16 lanes) and withstandard="any_order"any order; a library logarithm withinulps; and the largest element added, rounded.xmay also be an earlier result. Proof:proofs/logsumexp.md.
- backward(x, grad, axis=None, *, keepdims: bool = False, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, workers: int | None = None) Result#
Gradient of
logsumexp(x, axis, keepdims=keepdims)for the output gradientgrad.grad_x = grad * softmax(x)over the reduced elements, inx's shape and dtype: each element is the exact value rounded once.tolerance()bounds PyTorch's formula computed in the compute format,grad * exp(x - result)withresultas the forward's model gives it: the difference rounded, a library exponential, and the product rounded. In float16 and bfloat16 PyTorch rounds each of those steps to the dtype: check them withcompute=the dtype. Where the row is not finite the value is that formula's by IEEE rules on exact values. Integer inputs have no gradient.gradmust have the output's shape.xandgradmay also be earlier results.
See also#
softmax and log_softmax, which share its steps.
sum, for the two standards of accumulation.
The proof: logsumexp.md.