tanh#
The hyperbolic tangent squashes any number into the range from -1 to 1. It is the activation of an LSTM's cell, and the GELU of GPT-2 and BERT is computed through it.
In ExactRef, er.tanh(x), also er.elementary.hyperbolic.tanh, 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.
At a finite input other than 0, 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. Far above zero,
tanh(x) is closer to 1 than any float below 1 is, and still below 1. The
reference there is 1 when rounding to nearest, and the float just below 1
when rounding toward zero. Far below zero it is the same at -1.
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.
ulps says how close that function is to the exact value: any value of the
compute format within ulps steps of it, as
the diagram on the exp page shows. The default is 1.0001: either
value next to the exact one, and a little more. For some inputs next to
zero, PyTorch's CPU function returns a float a hair more than one step from
the exact value. 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#
GPT-2's GELU is 0.5 * h * (1 + tanh(u)), with
u = sqrt(2 / pi) * (h + 0.044715 * h**3). Here is that tanh for one MLP
layer, 512 tokens by 3072 features in float32, checked against PyTorch's:
import math
import torch
import exactref as er
# Seeded, so every run uses the same values
g = torch.Generator().manual_seed(67)
# The MLP's hidden activations, and the argument of GELU's tanh
h = torch.randn(512, 3072, generator=g)
u = math.sqrt(2 / math.pi) * (h + 0.044715 * h**3)
# ExactRef's result
r = er.tanh(u)
out = torch.tanh(u)
# 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: 1568556 of 1572864
Far from zero#
tanh(20) differs from 1 by about 8e-18, far less than a float32 step. The
reference depends on the rounding mode, and a library function may return 1
or the float below it:
# tanh(20) in float32
far = er.asarray([20.0], "float32")
# The float32 value just below 1
below_one = 0.9999999403953552
# The reference, rounding to nearest and toward zero
print("to nearest:", er.tanh(far).rounded.tolist())
print("toward zero:", er.tanh(far, rounding=er.Rounding.TOWARD_ZERO).rounded.tolist())
# Both outputs a library function may return
print("1 covered:", er.tanh(far).covers(er.asarray([1.0], "float32")).all())
print("the float below 1 covered:", er.tanh(far).covers(er.asarray([below_one], "float32")).all())
to nearest: [1.0]
toward zero: [0.9999999403953552]
1 covered: True
the float below 1 covered: True
Special values#
tanh(inf) is 1, tanh(-inf) is -1, a zero keeps its sign, and NaN gives
NaN. Integer and bool inputs give float32, as in PyTorch.
Complex inputs#
For a complex z = x + i y,
tanh(z) = (sinh 2x + i sin 2y) / (cosh 2x + cos 2y). Each part of the
reference is the exact value rounded once.
A correct implementation computes the sequence of the C library on Linux,
which PyTorch's Linux CPU kernel calls: real sinh, cosh, sin, and
cos, each within ulps of the exact value, and rounded products, sums,
and quotients between them. That library's sinh and cosh are a little
past 1 step on some inputs, so PyTorch's Linux CPU output is outside the
default on about two inputs in a 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. The other kernels' sequences are algorithms of
er.elementary.hyperbolic.tanh_algorithm:
Algorithm |
The sequence |
Whose it is |
|---|---|---|
|
|
PyTorch on a macOS CPU |
|
Kahan's form, as |
PyTorch on a Windows CPU |
|
Kahan's form, from |
PyTorch on CUDA |
|
|
PyTorch on MPS |
from exactref.elementary.hyperbolic import tanh_algorithm
# 4096 complex values
z = torch.complex(torch.randn(4096, generator=g), torch.randn(4096, generator=g))
out = torch.tanh(z)
# PyTorch on a macOS CPU computes the double-angle sequence
algorithm = tanh_algorithm(double_angle=True)
print("covered by the double-angle algorithm:", algorithm.covers(out, z).all())
covered by the double-angle algorithm: True
Algorithms lists the methods.
Backward#
r.backward(grad) gives the gradient grad_x = grad * (1 - tanh(x)**2), the
exact value rounded once. The tolerance covers PyTorch's formula,
grad * (1 - result * result) on the forward's output. Some builds compute
1 - result * result with one rounding, a fused multiply-add, and
some with two, and the tolerance covers both. Here it checks autograd's
gradient for the GELU above:
# GELU's tanh argument, and the gradient of its tanh
us = u.clone().requires_grad_()
grad = torch.randn(512, 3072, generator=g)
# PyTorch's autograd
torch.tanh(us).backward(grad)
# ExactRef's gradient, held by name
b = er.tanh(u).backward(grad)
print("covered:", b["grad_x"].covers(us.grad).all())
covered: True
Full specification#
er.tanh#
- tanh(x, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, workers: int | None = None) Result#
The hyperbolic tangent, elementwise: the exact
tanh(x)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 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). Far from zero the value is within less than any precision of 1 or -1 and is still rounded as the value just inside.tanh(inf)is 1 andtanh(-inf)is -1.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/tanh.md.A complex
xgives each part oftanh(x)as the exact value rounded once; far from the imaginary axis the real part is within less than any precision of 1 or -1, on either side of it.tolerance()bounds glibc's sequence, which PyTorch's Linux CPU kernel calls. The macOS CPU's istanh_algorithm(double_angle=True), CUDA'stanh_algorithm(kahan=True), MPS'stanh_algorithm(quotient=True), and the Windows CPU's, MSVC's,tanh_algorithm(sinh_beta=True).normal()computes the standard sequence with each real library function correctly rounded and each step rounded to nearest, in the compute format.
er.tanh.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
tanh(x)for the output gradientgrad.grad_x = grad * (1 - tanh(x)**2), inx'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)withresultas the forward's model gives it: the productresult * resultrounded or fused into the difference (builds differ), and the last product rounded. Wherexorgradis not finite, the value is that formula's by IEEE rules on exact values: the factor is +0 at an infinitex. Integer inputs have no gradient.gradmust havex's shape.
See also#
PyTorch equivalents, with the
ulpsfor each device.The proof: tanh.md.