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 exact value two below the value below the value above two above ulps=1/2 ulps=1 the default ulps=2

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

x

the input: real, integer, bool, or complex

required

dtype

the output format: a floating-point format, or a complex one for a complex input

the input's format; float32 for integers and bools

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 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:

Code
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())
Output
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:

Code
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")
Output
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:

Code
# 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")
Output
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:

Code
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())
Output
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:

hypot=True |z| 1.0000001... rounded to a float most digits lost log of that off by millions er.log |z|**2 - 1 about 2e-7 rounded to a float every digit kept log1p, halved within a few steps

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:

Code
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())
Output
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

exp_algorithm(fused=True)

cos y * e**x and sin y * e**x, each one library call

PyTorch on a Windows CPU

exp_algorithm(products=True)

e**x * cos y and e**x * sin y, with only y = 0 handled apart: e**x overflows past about 88.7 in float32, even where a product would be finite, and an infinite or NaN y gives NaN parts

PyTorch on MPS

log_algorithm(hypot=True)

log(hypot(x, y)) and atan2(y, x)

PyTorch on a macOS CPU and on CUDA

log_algorithm(sqrt_sum=True)

log(sqrt(x*x + y*y)) and atan2(y, x)

PyTorch on MPS

log_algorithm(norm_log1p=True)

0.5 * log1p(x*x + y*y - 1) where x*x + y*y is between 0.5 and 3, else 0.5 * log(x*x + y*y), and atan2(y, x)

PyTorch on a Windows CPU

log1p_algorithm(squares=True)

0.5 * log1p(x*(2 + x) + y*y) below 0.5 in magnitude, else log(hypot(x + 1, y))

PyTorch on a macOS CPU and on CUDA

log1p_algorithm(direct=True)

log(sqrt((1 + x)**2 + y*y))

PyTorch on MPS

log1p_algorithm(norm_log1p=True)

the standard sequence, with the log of log_algorithm(norm_log1p=True)

PyTorch on a Windows CPU

expm1_algorithm(difference=True)

exp(z) - 1 away from zero, with small-argument forms near it

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:

Code
# 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())
Output
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**x rounded 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 unless dtype says 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 (ReferenceUnavailableError if a precision cap is reached first). exp(-inf) is +0 and exp(inf) is inf.

tolerance() bounds an implementation whose exponential is within ulps units 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. x may also be an earlier result, as Result describes. Proof: proofs/exp.md.

A complex x gives e**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 real exp, cos and sin, each within its ulps (default 1), and two rounded products, with glibc's scaling where re passes t (88 in float32, 709 in float64): cos and sin times exp(t) first, then exp(re - t). The Windows CPU kernel's, MSVC's, with e**re cos(im) and e**re sin(im) each one library routine, is exp_algorithm(fused=True), and MPS's exp_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 - 1 rounded once to dtype (default: the input's format), a floating-point format: next to zero, where exp(x) - 1 computed in two steps loses the value, this is still the value itself, rounded. Integer and bool inputs give float32 unless dtype says 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 (ReferenceUnavailableError if a precision cap is reached first). expm1(-inf) is -1 and expm1(inf) is inf.

tolerance() bounds an implementation whose function is within ulps units 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. x may also be an earlier result, as Result describes. Proof: proofs/expm1.md.

A complex x gives each part of e**x - 1 as 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)**2 and exp(re) sin(im); the Windows CPU kernel computes it too, over the C runtime's expm1, which is within 3 units (ulps=3). MPS's kernel is expm1_algorithm(difference=True), which also describes its real kernel, but for a complex x on 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 unless dtype says 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 (ReferenceUnavailableError if a precision cap is reached first). A zero of either sign gives -inf, a negative input NaN, and log(inf) is inf.

tolerance() bounds an implementation whose logarithm is within ulps units 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. x may also be an earlier result, as Result describes. Proof: proofs/log.md.

A complex x gives log|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 takes log1p of |x|**2 - 1 next to the unit circle. The macOS CPU's and CUDA's log(hypot(re, im)), which loses the real part there, is log_algorithm(hypot=True), MPS's is log_algorithm(sqrt_sum=True), and the Windows CPU's, MSVC's, is log_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 to dtype (default: the input's format), a floating-point format: the sum 1 + x is taken exactly, so the value next to zero is the value itself, rounded. Integer and bool inputs give float32 unless dtype says 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 (ReferenceUnavailableError if a precision cap is reached first). log1p(-1) is -inf, an input below -1 gives NaN, and log1p(inf) is inf.

tolerance() bounds an implementation whose function is within ulps units 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. x may also be an earlier result, as Result describes. Proof: proofs/log1p.md.

A complex x gives each part of log(1 + x) as the exact value rounded once, the sum exact. tolerance() bounds PyTorch's corrected form, log(u) * (x / (u - 1)) with u = x + 1, as its Linux CPU kernel computes it. The macOS CPU's and CUDA's form is log1p_algorithm(squares=True), MPS's log1p_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 gradient grad.

grad_x = grad * exp(x), in x's shape and dtype: each element is the exact value rounded once. tolerance() bounds PyTorch's formula computed in the compute format, grad * result with result the 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, which tolerance(compute=dtype) describes. Where x or grad is not finite, the value is that formula's by IEEE rules on exact values: an exact exp(x) is never a zero or an infinity for a finite x, however far it lies outside the format. Integer inputs have no gradient. grad must have x'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 gradient grad.

grad_x = grad * exp(x), in x's shape and dtype: each element is the exact value rounded once, as exp's gradient is. tolerance() bounds PyTorch's formula computed in the compute format, grad * (result + 1) with result as the forward's model gives it: the library function's value, the sum rounded, then the product rounded. Where x or grad is not finite, the value is grad * exp(x) by IEEE rules on exact values. Integer inputs have no gradient. grad must have x'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 gradient grad.

grad_x = grad / x, in x's shape and dtype: the exact quotient rounded once, as divide gives it, ties included, with divide'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 finite grad / x at a negative x, and an infinity or NaN at a zero. Integer inputs have no gradient. grad must have x'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 gradient grad.

grad_x = grad / (1 + x), in x'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 for x below -1, and an infinity at -1 (NaN for a zero grad). Integer inputs have no gradient. grad must have x's shape.

See also#