exp, expm1, log, and log1p#
An exponential turns a score into a weight: softmax takes one of every
logit, and attention one of every query-key score. A logarithm goes the
other way, and every likelihood loss takes one. expm1(x) is e**x - 1 and
log1p(x) is log(1 + x). Computed as written, both lose most of their
digits when x is close to zero, so libraries give them functions of their
own. ELU is built on expm1, and softplus on log1p.
In ExactRef, er.exp(x), er.expm1(x), er.log(x), and er.log1p(x)
compute them element by element. They are also under
er.elementary.exp_log. 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.
Apart from exp(0) = 1, expm1(0) = 0, log(1) = 0, and log1p(0) = 0,
the exact value at a finite input is never a float, and never halfway
between two floats. 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 calls one library
function in the compute format (float32 for inputs narrower than
float32, else the input format) and rounds its value to the output format.
A library function is rarely correctly rounded. It promises a value close to
the exact one, and ulps says how close: any value of the compute format
within ulps steps of the exact value. The default, 1, accepts either value
next to it:
The values each ulps accepts around one exact value.
That default is what a careful library meets, and the functions PyTorch's
CPU kernels call meet it. CUDA's and MPS's functions are looser:
PyTorch equivalents gives the ulps
that accepts each. log1p's default is 1.0001. For the inputs closest to
zero, PyTorch's CPU function can return a float a hair more than one step
from the exact value, and the default accepts it, but nothing two steps
away.
Arguments#
Argument |
Meaning |
Default |
|---|---|---|
|
the input: real, integer, bool, or complex |
required |
|
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 |
Examples#
A softmax over a language model's vocabulary takes the exponential of every logit less its row's largest. Here are those exponentials 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 the vocabulary, less each row's largest
logits = torch.randn(8, 50257, generator=g) * 4
shifted = logits - logits.max(dim=-1, keepdim=True).values
# ExactRef's result
r = er.exp(shifted)
out = torch.exp(shifted)
# Could a correct implementation produce PyTorch's output?
print("covered:", r.covers(out).all())
# How many of PyTorch's elements are the reference itself
same = sum(a == b for a, b in zip(r.rounded.scalars(), out.flatten().tolist()))
print("equal to the reference:", same, "of", out.numel())
covered: True
equal to the reference: 364177 of 402056
About one in ten of PyTorch's outputs is not the nearest float. Each of them is the float on the other side of the exact value, which the default accepts.
What ulps accepts#
The exact value of exp(1) lies between two float32 values: the reference,
which is the nearer one, and the float above it. Both are accepted by
default. The floats one step past either are accepted with ulps=2:
import numpy as np
# The reference for exp(1) in float32: the float nearest to e
r1 = er.exp(er.asarray([1.0], "float32"))
nearest = np.float32(r1.rounded.scalars()[0])
print("reference:", float(nearest))
# The float one step below the reference, and one and two steps above it
below = np.nextafter(nearest, np.float32(0))
above = np.nextafter(nearest, np.float32(3))
two_above = np.nextafter(above, np.float32(3))
# Which of them the default and ulps=2 accept
for label, value in (("one below", below), ("one above", above), ("two above", two_above)):
candidate = er.asarray([float(value)], "float32")
print(label + ":", r1.covers(candidate).all(), "by default,", r1.covers(candidate, ulps=2).all(), "with ulps=2")
reference: 2.7182817459106445
one below: False by default, True with ulps=2
one above: True by default, True with ulps=2
two above: False by default, True with ulps=2
expm1 and log1p next to zero#
For a negative x, ELU is expm1(x), and many activations lie close to
zero.
There exp(x) is a float just below 1, and subtracting 1 keeps only the few
digits that were left after the 1. torch.expm1 keeps the value; exp(x) - 1
does not:
# 4096 negative activations within 0.01 of zero
x = -torch.rand(4096, generator=g) / 100
# ExactRef's result, against PyTorch's function and the two-step formula
r = er.expm1(x)
print("torch.expm1 covered:", sum(r.covers(torch.expm1(x)).scalars()), "of 4096")
print("torch.exp(x) - 1 covered:", sum(r.covers(torch.exp(x) - 1).scalars()), "of 4096")
torch.expm1 covered: 4096 of 4096
torch.exp(x) - 1 covered: 64 of 4096
log1p(x) against log(1 + x) is the same story. MPS computes expm1 as
exp(x) - 1 for inputs from 0.1 in magnitude;
er.elementary.exp_log.expm1_algorithm(difference=True) describes that
kernel.
Special values#
An infinity gives the function's limit, an input outside its domain gives
NaN, and expm1 and log1p keep a zero's sign:
import math
# Each function at infinities, -1, zeros of both signs, and NaN
edges = er.asarray([-math.inf, -1.0, -0.0, 0.0, math.inf, math.nan], "float32")
for function in (er.exp, er.expm1, er.log, er.log1p):
print(function.__name__ + ":", function(edges).rounded.tolist())
exp: [0.0, 0.3678794503211975, 1.0, 1.0, inf, nan]
expm1: [-1.0, -0.6321205496788025, -0.0, 0.0, inf, nan]
log: [nan, nan, -inf, -inf, inf, nan]
log1p: [nan, -inf, -0.0, 0.0, inf, nan]
Integer and bool inputs give float32, as in PyTorch. The reference is the
function of the integer itself. PyTorch converts the integer to float32
first, which changes integers above 2**24, so the tolerance also covers an
implementation that does that.
Complex inputs#
For a complex z = x + i y, exp(z) is e**x * (cos y + i sin y) and
log(z) is log|z| + i atan2(y, x). Each part of the reference is the
exact value rounded once.
A correct implementation computes the sequence of PyTorch's Linux CPU
kernel: calls of the C library's real exp, expm1, cos, sin, log,
log1p, hypot, and atan2, each within ulps of the exact value, and
rounded products, sums, and quotients between them. The tolerance covers every
output that sequence can give. The C library's atan2 is itself a little
past 1 step on some inputs, so PyTorch's Linux CPU output for log and
log1p is outside the default on a few inputs in ten thousand, and inside
with ulps=2. The normal answer, normal(), is that sequence with
each library function correctly rounded and each step rounded in the
compute format.
Kernels differ most for log next to the unit circle, where |z| is close
to 1 and log|z| is close to 0:
The real part of log(z) for a z just off the unit circle, by each
sequence.
PyTorch on a macOS CPU and on CUDA takes the first row. Its real part there
is far from the exact value, and er.log says so. Here is that sequence on
4096 points of magnitude 1, with a little noise:
from exactref.elementary.exp_log import log_algorithm
# Points just off the unit circle
angle = torch.rand(4096, generator=g) * 1.5
radius = 1 + torch.randn(4096, generator=g) * 1e-5
z = torch.complex(radius * torch.cos(angle), radius * torch.sin(angle))
# ExactRef's result
r = er.log(z)
# The first row's sequence: log(hypot(x, y)) for the real part
plain = torch.complex(torch.log(torch.hypot(z.real, z.imag)), torch.atan2(z.imag, z.real))
# covers() answers per part: an element is covered when both of its parts are
covered = r.covers(plain).tolist()
print("covered by er.log:", sum(all(parts) for parts in covered), "of 4096")
print("covered by the hypot algorithm:", log_algorithm(hypot=True).covers(plain, z).all())
covered by er.log: 5 of 4096
covered by the hypot algorithm: True
The other kernels' sequences are algorithms too:
Algorithm |
The sequence |
Whose it is |
|---|---|---|
|
|
PyTorch on a Windows CPU |
|
|
PyTorch on MPS |
|
|
PyTorch on a macOS CPU and on CUDA |
|
|
PyTorch on MPS |
|
|
PyTorch on a Windows CPU |
|
|
PyTorch on a macOS CPU and on CUDA |
|
|
PyTorch on MPS |
|
the standard sequence, with the |
PyTorch on a Windows CPU |
|
|
PyTorch on MPS |
Algorithms lists their methods.
Backward#
r.backward(grad) gives the gradient grad_x for an output gradient
grad, each element the exact value rounded once: grad * exp(x) for exp
and expm1, grad / x for log, and grad / (1 + x) for log1p. The
tolerance covers PyTorch's formulas on the forward's output result:
grad * result for exp, grad * (result + 1) for expm1, and the same
quotients for log and log1p. A complex input takes conjugates, as
PyTorch does, such as grad * conj(exp(z)). Here the tolerance checks
autograd's gradient of exp for the softmax rows above:
# The shifted logits, and the gradient of their exponentials
xs = shifted.clone().requires_grad_()
grad = torch.randn(8, 50257, generator=g)
# PyTorch's autograd
torch.exp(xs).backward(grad)
# ExactRef's gradient, held by name
b = er.exp(shifted).backward(grad)
print("covered:", b["grad_x"].covers(xs.grad).all())
covered: True
In float16 and bfloat16, PyTorch rounds expm1's result + 1 and
log1p's x + 1 to the 16-bit dtype before the last step. Check those
gradients with compute= the dtype.
Full specification#
er.exp#
- exp(x, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, workers: int | None = None) Result#
The exponential, elementwise: the exact
e**xrounded once.Each output element is the exact exponential rounded once to
dtype(default: the input's format), a floating-point format. Integer and bool inputs give float32 unlessdtypesays otherwise, as PyTorch gives; the reference is the exponential of the integer itself, and the tolerance covers an implementation that converts it to float32 first.exp(0)is exactly 1; every other finite input gives a transcendental value, which is rounded from an enclosure refined until the rounding is certain (ReferenceUnavailableErrorif a precision cap is reached first).exp(-inf)is +0 andexp(inf)is inf.tolerance()bounds an implementation whose exponential is withinulpsunits in the last place of the exact value in the compute format (default 1), then rounded to the output. It is the exact worst case.xmay also be an earlier result, asResultdescribes. Proof:proofs/exp.md.A complex
xgivese**re * (cos(im) + i sin(im)), each part the exact value rounded once; special values are C's (Annex G).tolerance()bounds the sequence PyTorch's Linux CPU kernel computes: a realexp,cosandsin, each within itsulps(default 1), and two rounded products, with glibc's scaling whererepassest(88 in float32, 709 in float64):cosandsintimesexp(t)first, thenexp(re - t). The Windows CPU kernel's, MSVC's, withe**re cos(im)ande**re sin(im)each one library routine, isexp_algorithm(fused=True), and MPS'sexp_algorithm(products=True).normal()computes the standard sequence with each real library function correctly rounded and each step rounded to nearest, in the compute format.
er.expm1#
- expm1(x, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, workers: int | None = None) Result#
e**x - 1, elementwise: the exact value rounded once.Each output element is the exact
e**x - 1rounded once todtype(default: the input's format), a floating-point format: next to zero, whereexp(x) - 1computed in two steps loses the value, this is still the value itself, rounded. Integer and bool inputs give float32 unlessdtypesays otherwise, as PyTorch gives. A zero gives that zero, with its sign; every other finite input gives a transcendental value, which is rounded from an enclosure refined until the rounding is certain (ReferenceUnavailableErrorif a precision cap is reached first).expm1(-inf)is -1 andexpm1(inf)is inf.tolerance()bounds an implementation whose function is withinulpsunits in the last place of the exact value in the compute format (default 1), then rounded to the output. It is the exact worst case.xmay also be an earlier result, asResultdescribes. Proof:proofs/expm1.md.A complex
xgives each part ofe**x - 1as the exact value rounded once.tolerance()bounds PyTorch's formula as its Linux CPU kernel computes it,expm1(re) cos(im) - 2 sin(im / 2)**2andexp(re) sin(im); the Windows CPU kernel computes it too, over the C runtime'sexpm1, which is within 3 units (ulps=3). MPS's kernel isexpm1_algorithm(difference=True), which also describes its real kernel, but for a complexxon the real axis, where MPS's kernel is up to thousands of units off (a defect in it, which the algorithm rejects).normal()computes the standard sequence with each real library function correctly rounded and each step rounded to nearest, in the compute format.
er.log#
- log(x, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, workers: int | None = None) Result#
The natural logarithm, elementwise: the exact
log(x)rounded once.Each output element is the exact logarithm rounded once to
dtype(default: the input's format), a floating-point format. Integer and bool inputs give float32 unlessdtypesays otherwise, as PyTorch gives; the reference is the logarithm of the integer itself, and the tolerance covers an implementation that converts it to float32 first.log(1)is exactly +0; every other positive finite input gives a transcendental value, which is rounded from an enclosure refined until the rounding is certain (ReferenceUnavailableErrorif a precision cap is reached first). A zero of either sign gives -inf, a negative input NaN, andlog(inf)is inf.tolerance()bounds an implementation whose logarithm is withinulpsunits in the last place of the exact value in the compute format (default 1), then rounded to the output. It is the exact worst case.xmay also be an earlier result, asResultdescribes. Proof:proofs/log.md.A complex
xgiveslog|x| + i atan2(im, re), each part the exact value rounded once, the real part exact next to the unit circle too; special values are C's (Annex G).tolerance()bounds the sequence PyTorch's Linux CPU kernel computes, glibc's, which takeslog1pof|x|**2 - 1next to the unit circle. The macOS CPU's and CUDA'slog(hypot(re, im)), which loses the real part there, islog_algorithm(hypot=True), MPS's islog_algorithm(sqrt_sum=True), and the Windows CPU's, MSVC's, islog_algorithm(norm_log1p=True).normal()computes the standard sequence with each real library function correctly rounded and each step rounded to nearest, in the compute format.
er.log1p#
- log1p(x, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, workers: int | None = None) Result#
log(1 + x), elementwise: the exact value rounded once.Each output element is the exact
log(1 + x)rounded once todtype(default: the input's format), a floating-point format: the sum1 + xis taken exactly, so the value next to zero is the value itself, rounded. Integer and bool inputs give float32 unlessdtypesays otherwise, as PyTorch gives. A zero gives that zero, with its sign; every other finite input above -1 gives a transcendental value, which is rounded from an enclosure refined until the rounding is certain (ReferenceUnavailableErrorif a precision cap is reached first).log1p(-1)is -inf, an input below -1 gives NaN, andlog1p(inf)is inf.tolerance()bounds an implementation whose function is withinulpsunits in the last place of the exact value in the compute format, then rounded to the output. The default is 1.0001: either value of the format next to the exact one, and the one a full step from an exact value that lies just beside a value of the format, as PyTorch's CPU function returns for inputs next to zero. It is the exact worst case.xmay also be an earlier result, asResultdescribes. Proof:proofs/log1p.md.A complex
xgives each part oflog(1 + x)as the exact value rounded once, the sum exact.tolerance()bounds PyTorch's corrected form,log(u) * (x / (u - 1))withu = x + 1, as its Linux CPU kernel computes it. The macOS CPU's and CUDA's form islog1p_algorithm(squares=True), MPS'slog1p_algorithm(direct=True), and the Windows CPU's, that form over MSVC's log,log1p_algorithm(norm_log1p=True).normal()computes the standard sequence with each real library function correctly rounded and each step rounded to nearest, in the compute format.
The backwards#
- backward(x, grad, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, workers: int | None = None) Result#
The gradient of
exp(x)for the output gradientgrad.grad_x = grad * exp(x), inx's shape and dtype: each element is the exact value rounded once.tolerance()bounds PyTorch's formula computed in the compute format,grad * resultwithresultthe exponential as the forward's model gives it: the library function's value, then the product rounded. For float16 and bfloat16 the default holds PyTorch's CPU autograd; CUDA's rounds every step to the dtype, whichtolerance(compute=dtype)describes. Wherexorgradis not finite, the value is that formula's by IEEE rules on exact values: an exactexp(x)is never a zero or an infinity for a finitex, however far it lies outside the format. Integer inputs have no gradient.gradmust havex's shape.
- backward(x, grad, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, workers: int | None = None) Result#
The gradient of
expm1(x)for the output gradientgrad.grad_x = grad * exp(x), inx's shape and dtype: each element is the exact value rounded once, asexp's gradient is.tolerance()bounds PyTorch's formula computed in the compute format,grad * (result + 1)withresultas the forward's model gives it: the library function's value, the sum rounded, then the product rounded. Wherexorgradis not finite, the value isgrad * exp(x)by IEEE rules on exact values. Integer inputs have no gradient.gradmust havex's shape.
- backward(x, grad, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, workers: int | None = None) Result#
The gradient of
log(x)for the output gradientgrad.grad_x = grad / x, inx's shape and dtype: the exact quotient rounded once, asdividegives it, ties included, withdivide's tolerance (one rounded division in the compute format). Where the derivative does not exist the value is that formula's by IEEE rules on exact values, as PyTorch computes it: the finitegrad / xat a negativex, and an infinity or NaN at a zero. Integer inputs have no gradient.gradmust havex's shape.
- backward(x, grad, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, workers: int | None = None) Result#
The gradient of
log1p(x)for the output gradientgrad.grad_x = grad / (1 + x), inx's shape and dtype: the exact quotient rounded once, ties included.tolerance()bounds PyTorch's formula computed in the compute format,grad / (x + 1): the sum rounded, then the division rounded. Where the derivative does not exist the value is that formula's by IEEE rules on exact values: the finite quotient forxbelow -1, and an infinity at -1 (NaN for a zerograd). Integer inputs have no gradient.gradmust havex's shape.
See also#
softmax and log_softmax and logsumexp, which call these functions inside.
divide and reciprocal:
log's gradient is a rounded division.PyTorch equivalents, with the
ulpsfor each device.