sigmoid#

The logistic function, 1 / (1 + e**-x), turns any number into one between 0 and 1. It gives a binary classifier its probability and an LSTM its gates, and SiLU multiplies x by it.

In ExactRef, er.sigmoid(x), also er.elementary.logistic.sigmoid, computes it element by element. 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.

sigmoid(0) is exactly 1/2. At any other finite input the exact value is never a float and never halfway between two, so ExactRef computes more and more digits of it until the rounding is certain, as for exp and log.

The tolerance says, per element, how far a correct implementation's output can be from the reference. PyTorch computes 1 / (1 + exp(-x)) on every device, in three steps in the compute format (float32 for inputs narrower than float32, else the input format), and a correct implementation is one that takes those steps:

reference 1 / (1 + e**-x), exactly rounded once tolerance exp(-x) within ulps 1 + that rounded 1 / the sum rounded to the output rounded The first three steps are in the compute format.

Where sigmoid rounds: once for the reference, and at every step for a correct implementation.

ulps says how close the library's exponential is to the exact one, in steps of the compute format. Its default is 1, as for exp. The tolerance is exactly as far as the three steps can get from the reference.

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#

An LSTM layer of hidden size 1024 takes the sigmoid of its input, forget, and output gates. Here are those gates for 256 sequences, 256 by 3072 values 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)
# The three gates' pre-activations
gates = torch.randn(256, 3072, generator=g) * 2

# ExactRef's result
r = er.sigmoid(gates)
out = torch.sigmoid(gates)
# 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: 532220 of 786432

A third of PyTorch's answers are not the nearest float, because the three steps round three times, and every one of them is inside the tolerance.

Where the exponential overflows#

Below about -88.7 in float32, exp(-x) is past the largest float, so the three steps give exactly 0. The exact value is a tiny positive number, which the reference keeps. PyTorch returns 0, and the tolerance covers it:

Code
# Inputs on either side of where exp(-x) overflows in float32
x = torch.tensor([-88.0, -89.0, -100.0])
r = er.sigmoid(x)

print("reference:", r.rounded.tolist())
print("PyTorch:", torch.sigmoid(x).tolist())
print("covered:", r.covers(torch.sigmoid(x)).tolist())
Output
reference: [6.054601485195952e-39, 2.2273639090442967e-39, 3.783505853677006e-44]
PyTorch: [6.054601485195952e-39, 0.0, 0.0]
covered: [True, True, True]

Special values#

sigmoid(-inf) is 0, sigmoid(inf) is 1, and NaN gives NaN. Integer and bool inputs give float32, as in PyTorch.

Complex inputs#

For a complex z, each part of the reference is the exact value of 1 / (1 + e**-z) rounded once. A correct implementation takes the steps PyTorch's Linux and macOS CPU kernels take: the complex exp of -z, a sum with 1, and a complex reciprocal by Smith's method. CUDA and MPS take the reciprocal in other ways, and each is an algorithm of er.elementary.logistic.sigmoid_algorithm:

Algorithm

The reciprocal of c + i d

Whose it is

sigmoid_algorithm(scaled=True)

(c, -d) / (c*c + d*d)

PyTorch on CUDA

sigmoid_algorithm(divided=True)

Smith's method with a division

PyTorch on MPS

PyTorch on a Windows CPU takes the same steps as on Linux, with the complex exp of exp_algorithm(fused=True): sigmoid_algorithm(fused=True) describes it. On MPS the complex exp is that of exp_algorithm(products=True). Where the real part of z is below about -88.72 in float32 and the imaginary part is not 0, both parts of e**-z are infinite and MPS returns NaN, which sigmoid_algorithm(divided=True) accepts. Where the imaginary part is 0, MPS returns 0.

The normal answer, normal(), takes the Linux CPU kernel's steps, with each library function correctly rounded and each step rounded in the compute format.

Backward#

r.backward(grad) gives the gradient grad_x = grad * s * (1 - s) with s = sigmoid(x), the exact value rounded once. The tolerance covers PyTorch's formula, (grad * (1 - result)) * result on the forward's output. Here it checks autograd's gradient for the LSTM gates above:

Code
# The gates, and the gradient of their sigmoids
xs = gates.clone().requires_grad_()
grad = torch.randn(256, 3072, generator=g)

# PyTorch's autograd
torch.sigmoid(xs).backward(grad)

# ExactRef's gradient, held by name
b = er.sigmoid(gates).backward(grad)
print("covered:", b["grad_x"].covers(xs.grad).all())
Output
covered: True

In float16 on a CPU, and in float16 and bfloat16 on CUDA, PyTorch rounds each of the formula's three operations to the 16-bit dtype: check those gradients with compute= the dtype.

Full specification#

er.sigmoid#

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

The logistic function 1 / (1 + e**-x), elementwise: the exact value rounded once.

Each output element is the exact value 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. sigmoid(0) is exactly 1/2; 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). sigmoid(-inf) is +0 and sigmoid(inf) is 1.

tolerance() bounds an implementation that takes three steps, each in the compute format: an exponential exp(-x) within ulps units in the last place of the exact value (default 1), the sum 1 + exp(-x) rounded, and its reciprocal rounded; then the rounding to the output. Where the exponential passes the format's largest value the result is 0, though the exact value is not. It is the exact worst case. x may also be an earlier result, as Result describes. Proof: proofs/sigmoid.md.

A complex x gives each part of 1 / (1 + e**-x) as the exact value rounded once. tolerance() bounds the sequence PyTorch's Linux and macOS CPU kernels compute: the complex exp of -x, a sum, and a complex reciprocal by Smith's method. CUDA's reciprocal is sigmoid_algorithm(scaled=True), MPS's sigmoid_algorithm(divided=True), and the Windows CPU's, the same steps over MSVC's exp, sigmoid_algorithm(fused=True). normal() computes the standard sequence with each real library function correctly rounded and each step rounded to nearest, in the compute format.

er.sigmoid.backward#

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 sigmoid(x) for the output gradient grad.

grad_x = grad * s * (1 - s) with s = sigmoid(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 * (1 - result)) * result with result as the forward's model gives it, each of the three operations rounded. Where x or grad is not finite, the value is that formula's by IEEE rules on exact values: the factor is +0 at an infinite x. Integer inputs have no gradient. grad must have x's shape.

See also#