sqrt and rsqrt#

A square root turns a variance into a standard deviation and a sum of squares into a norm. Adam divides each step by the square root of a running average of squared gradients, and RMSNorm and LayerNorm multiply by one over the root of a variance, the reciprocal square root. er.sqrt(z) computes the square root of each element and er.rsqrt(x) computes 1 / sqrt(x), for real, integer, bool, and complex inputs. They are also er.elementary.power.sqrt and er.elementary.power.rsqrt.

Each output element is the reference: the exact value, rounded once to the output format. To check another implementation's output, pass it to covers(), which says per element whether a correct implementation could have produced it. How far such an output can be from the reference is the tolerance, and it follows from the steps a correct implementation takes:

  • sqrt is one step. IEEE 754 requires a square root to be correctly rounded. A correct implementation takes one in the compute format and rounds it to the output format, which always gives the reference. So the tolerance is 0, and rounded is the only correct output.

  • rsqrt is two steps. IEEE 754 does not require a correctly rounded reciprocal square root. PyTorch's CPU kernels take the square root, round it, then divide 1 by it and round again. Their result is often one ulp from the reference, so the tolerance is the largest distance the two steps can reach. The reference itself is always accepted. CUDA computes 1 / sqrt(x) with one function instead, which is the algorithm rsqrt_direct.

A complex input gives the principal square root, each part rounded once. Complex inputs explains its tolerance.

Arguments#

Argument

Meaning

Default

z (rsqrt: x)

the input: an array, tensor, or earlier result, 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#

Adam divides each step by sqrt(v) + eps, with v the running average of squared gradients. Here is that square root for a 4096 by 4096 float32 weight:

Code
import torch
import exactref as er

# Seeded, so every run uses the same values
g = torch.Generator().manual_seed(67)
# A second moment: the average of squared gradients of size about 1e-3
v = (torch.randn(4096, 4096, generator=g) * 1e-3) ** 2

# ExactRef's result
r = er.sqrt(v)
# The largest tolerance of the 16,777,216 elements
print("largest tolerance:", max(r.tolerance().scalars()))
# Could a correct implementation produce PyTorch's output?
print("covered:", r.covers(torch.sqrt(v)).all())
Output
largest tolerance: 0.0
covered: True

The tolerance is 0, so PyTorch's output is covered only because it is the reference itself, bit for bit. The same holds in bfloat16, where the root is taken in float32 and rounded again:

Code
# The same second moment in bfloat16
vb = v.bfloat16()
rb = er.sqrt(vb)

print("largest tolerance:", max(rb.tolerance().scalars()))
print("covered:", rb.covers(torch.sqrt(vb)).all())
Output
largest tolerance: 0.0
covered: True

A square root that is not correctly rounded#

The exact root of 2 lies between two float32 values, and the reference is the nearer one. A correctly rounded square root never returns the other, so the default rejects it:

Code
# sqrt(2) in float32, and the float32 value on the other side of the exact root
two = er.asarray([2.0], "float32")
r2 = er.sqrt(two)
other = er.asarray([1.4142136573791504], "float32")

print("reference:", r2.rounded.tolist())
print("the other neighbor, by default:", r2.covers(other).all())
print("the other neighbor, with ulps=1:", r2.covers(other, ulps=1).all())
Output
reference: [1.4142135381698608]
the other neighbor, by default: False
the other neighbor, with ulps=1: True

ulps, an argument of tolerance() and covers(), is how far a library's square root may be from the exact root, in ulps of the compute format. The default, 1/2, is a correctly rounded root.

the exact root the midpoint the value below the value above ulps=1/2 the nearer value only ulps=9/16 both, while the root is within 1/16 of a step of the midpoint ulps=1 both, wherever the root lies

A larger ulps also accepts the neighbor on the far side of the root.

PyTorch's sqrt on an x86 CPU build that uses Intel's MKL is not correctly rounded. PyTorch equivalents gives the ulps that covers it.

rsqrt#

RMSNorm scales each token by one over the root of its mean square. Here is that reciprocal square root in float32 for 4096 tokens of hidden size 4096, the full context of Llama 2 7B:

Code
# The activations, and each token's mean square plus RMSNorm's eps
h = torch.randn(4096, 4096, generator=g)
ms = h.pow(2).mean(dim=-1) + 1e-6

rr = er.rsqrt(ms)
out = torch.rsqrt(ms)
print("covered:", rr.covers(out).all())
# How many of PyTorch's 4096 elements are the reference itself
same = sum(a == b for a, b in zip(rr.rounded.tolist(), out.tolist()))
print("equal to the reference:", same)
Output
covered: True
equal to the reference: 2801

PyTorch's CPU takes the square root and then its reciprocal, so about one answer in three is an ulp from the reference, and every one is inside the tolerance.

In bfloat16 and float16, PyTorch's CPU kernel on ARM rounds both steps in the 16-bit format itself. Check it with compute= set to the dtype. Its x86 kernel, MPS, and CUDA work in float32, the default.

Code
# The same mean squares in bfloat16, as PyTorch's CPU on Apple silicon computes them
msb = ms.bfloat16()
rb = er.rsqrt(msb)
print("with bfloat16 steps:", rb.covers(torch.rsqrt(msb), compute="bfloat16").all())
Output
with bfloat16 steps: True

The bfloat16 kernel of PyTorch's Linux ARM build is the exception. It can be up to 1.70 ulps from the exact value, because it computes some elements with Arm's reciprocal estimate, a hardware approximation accurate to about 8 bits. The algorithm er.elementary.power.rsqrt_estimate() describes that kernel and its gradient. PyTorch equivalents has the details.

A one-step rsqrt#

CUDA computes 1 / sqrt(x) with one device function. NVIDIA documents it as within 2 ulps of the correctly rounded value in float32, and 1 in float64. That is another way of computing it, so it has its own algorithm, er.elementary.power.rsqrt_direct(), whose tolerance is still the distance from rsqrt's reference. Here a value two float32 ulps from the reference is rejected by rsqrt and accepted by rsqrt_direct:

Code
from exactref.elementary.power import rsqrt_direct

# 1 / sqrt(3) in float32, and the float32 value two ulps above it
three = er.asarray([3.0], "float32")
off = er.asarray([0.577350378036499], "float32")

print("reference:", er.rsqrt(three).rounded.tolist())
print("two ulps off, by rsqrt:", er.rsqrt(three).covers(off).all())
# The algorithm's covers() takes the output, then rsqrt's arguments
print("two ulps off, by rsqrt_direct:", rsqrt_direct().covers(off, three).all())
Output
reference: [0.5773502588272095]
two ulps off, by rsqrt: False
two ulps off, by rsqrt_direct: True

Algorithms has its full specification.

Integers#

The square root of an integer tensor is float32, as in PyTorch. The reference is the root of the integer itself. PyTorch first converts the integer to float32, which cannot hold every integer above 2**24, so its answer can differ from the reference. The tolerance allows for that conversion, and normal(), the normal answer, makes it:

Code
# Counts; float32 cannot hold 16785411, which is 4097**2 + 2
counts = torch.tensor([16785411, 4096, 2])

ri = er.sqrt(counts)
print("dtype:", ri.rounded.dtype.name)
print("rounded:", ri.rounded.tolist())
# PyTorch takes the root of 16785412, the nearest float32 value
print("PyTorch:", torch.sqrt(counts).tolist())
print("covered:", ri.covers(torch.sqrt(counts)).all())
print("normal():", ri.normal().tolist())
Output
dtype: float32
rounded: [4097.0, 64.0, 1.4142135381698608]
PyTorch: [4097.00048828125, 64.0, 1.4142135381698608]
covered: True
normal(): [4097.00048828125, 64.0, 1.4142135381698608]

Special values#

Special values follow IEEE arithmetic, as in PyTorch: the root of -0 is -0, the root of a negative value is NaN, and the root of infinity is infinity. may_be() says where a correct implementation may return each:

Code
# +0, -0, a negative value, and infinity, in float32
s = er.sqrt(er.asarray([0.0, -0.0, -1.0, float("inf")], "float32"))

print("rounded:", s.rounded.tolist())
print("may be NaN:", s.may_be("nan").tolist())
Output
rounded: [0.0, -0.0, nan, inf]
may be NaN: [False, False, True, False]

rsqrt follows 1 / sqrt(x) by the same rules: infinity at +0, -infinity at -0, 0 at infinity, and NaN at a negative value.

Complex inputs#

A complex input gives the principal square root, the one whose real part is not negative. On the negative real axis the sign of the input's zero imaginary part picks the side: sqrt(-4+0j) is 2j, and sqrt(-4-0j) is -2j.

PyTorch's CPU computes it by the method the C libraries share: a hypot, a sum, a square root, and a division, each rounded. No step subtracts, so each part comes out within about two ulps of its own size, however small it is next to the other part. The tolerance allows for those steps, so it is tight for each part. Here are 65,536 complex64 values just off the negative real axis, where the root's real part is about a millionth of its imaginary part:

Code
import math

# A negative real part, and an imaginary part a million times smaller
zc = torch.complex(-torch.rand(65536, generator=g) - 1, torch.randn(65536, generator=g) * 1e-6)

rc = er.sqrt(zc)
print("covered:", rc.covers(torch.sqrt(zc)).all())

def ulp(v):
    """The distance between neighboring float32 values at v's size."""
    return 2.0 ** (math.floor(math.log2(abs(v))) - 23)

# Each part's tolerance, counted in ulps of that part
pairs = zip(rc.tolerance().tolist(), rc.rounded.tolist())
largest = max(max(t.real / ulp(v.real), t.imag / ulp(v.imag)) for t, v in pairs)
print("largest tolerance, in ulps of its own part:", largest)
print("rsqrt covered:", er.rsqrt(zc).covers(torch.rsqrt(zc)).all())
Output
covered: True
largest tolerance, in ulps of its own part: 2.0
rsqrt covered: True

A complex rsqrt is one over that square root, by PyTorch's complex division (divide and reciprocal).

Special values are C99's, as PyTorch's CPU gives them. The square root of zero keeps the sign of its imaginary part, an infinite imaginary part gives infinity in both parts, and rsqrt of zero is inf+nanj:

Code
# Zero, both sides of the negative real axis, and an infinite imaginary part
zs = er.asarray([complex(0.0, -0.0), complex(-4.0, 0.0), complex(-4.0, -0.0), complex(1.0, float("inf"))], "complex128")
print("sqrt:", er.sqrt(zs).rounded.tolist())
print("rsqrt of zero:", er.rsqrt(er.asarray([0j], "complex128")).rounded.tolist())
Output
sqrt: [-0j, 2j, -2j, (inf+infj)]
rsqrt of zero: [(inf+nanj)]

The polar method#

CUDA computes a complex square root through an angle: r = sqrt(hypot(a, b)) and th = atan2(b, a) / 2, then r * cos(th) and r * sin(th). Next to the negative real axis the real part is r times the cosine of an angle near a quarter turn, and that cosine is only as accurate as the angle. So the real part can be far from the exact one, in ulps of its own size, and can even be negative:

sqrt(-3 + 0.000001j) = 0.00000029 + 1.7320508j in complex64: a tiny real part beside a large imaginary one er.sqrt the C libraries' method within 1 ulp of the real part sqrt_polar CUDA's method 0 within about 6 ulps of the imaginary part, 23 million ulps of the real part, reaching below 0 The dot is the exact real part; the dashed band is what each method may return.

How far each method's real part can be from the exact one, for one complex64 input.

That is the method's own error, not a bug in one library, so the method has its own algorithm, er.elementary.power.sqrt_polar(). Here is CUDA's complex64 output for sqrt(-3-0j):

Code
from exactref.elementary.power import sqrt_polar

zp = er.asarray([complex(-3.0, -0.0)], "complex64")
# CUDA's output: the exact real part is 0
cuda = er.asarray([complex(-7.571034643660823e-08, -1.7320507764816284)], "complex64")

print("reference:", er.sqrt(zp).rounded.tolist())
print("CUDA's output, by sqrt:", er.sqrt(zp).covers(cuda).all())
# The algorithm's covers() takes the output, then sqrt's arguments
print("CUDA's output, by sqrt_polar:", sqrt_polar().covers(cuda, zp).all())
Output
reference: [-1.7320507764816284j]
CUDA's output, by sqrt: False
CUDA's output, by sqrt_polar: True

Algorithms has its full specification.

Backward#

er.sqrt.backward(z, grad) returns grad_z = grad / (2 * sqrt(z)), and er.rsqrt.backward(x, grad) returns grad_x = -grad / (2 * x * sqrt(x)), each the exact value rounded once. They are named outputs, and gb["grad_z"] reads one as a result of its own.

PyTorch computes the square root's gradient as grad / (2 * result), with result the forward's output. The tolerance allows for those steps in the compute format: the root rounded, its doubling, which is exact, and the division rounded. Here the gradient checks PyTorch's autograd for the standard deviations LayerNorm takes, sqrt(var + eps), of the 4096 tokens above:

Code
# Each token's variance plus LayerNorm's eps, and the gradient of its root
var = h.var(dim=-1, correction=0) + 1e-5
gs = torch.randn(4096, generator=g)

# PyTorch's autograd, on a copy that records gradients
var_ = var.clone().requires_grad_()
torch.sqrt(var_).backward(gs)

# ExactRef's gradient, held by name
gb = er.sqrt.backward(var, gs)
print("outputs:", list(gb.rounded))
print("grad_z covered:", gb["grad_z"].covers(var_.grad).all())
Output
outputs: ['grad_z']
grad_z covered: True

In bfloat16 and float16, PyTorch divides by the forward's stored output, which is already rounded to the 16-bit format. That is a rounding in the dtype, not in float32, so check it with compute= set to the dtype:

Code
# The same in bfloat16
varb, gsb = var.bfloat16(), gs.bfloat16()
varb_ = varb.clone().requires_grad_()
torch.sqrt(varb_).backward(gsb)

bb = er.sqrt.backward(varb, gsb)["grad_z"]
print("with float32 steps:", bb.covers(varb_.grad).all())
print("with bfloat16 steps:", bb.covers(varb_.grad, compute="bfloat16").all())
Output
with float32 steps: False
with bfloat16 steps: True

Where z is zero the derivative does not exist. The gradient there is what PyTorch's formula gives by IEEE rules, with the root of -0 being -0:

Code
# grad = 1, at z = +0 and z = -0
zb = er.sqrt.backward(er.asarray([0.0, -0.0], "float32"), er.asarray([1.0, 1.0], "float32"))
print("grad_z:", zb["grad_z"].rounded.tolist())
Output
grad_z: [inf, -inf]

PyTorch computes rsqrt's gradient as (-0.5 * grad) * result**3, and the tolerance allows for those steps the same way. Here it checks the RMSNorm example above:

Code
# The gradient of the reciprocal square roots
gr = torch.randn(4096, generator=g)
ms_ = ms.clone().requires_grad_()
torch.rsqrt(ms_).backward(gr)

rg = er.rsqrt.backward(ms, gr)
print("outputs:", list(rg.rounded))
print("grad_x covered:", rg["grad_x"].covers(ms_.grad).all())
Output
outputs: ['grad_x']
grad_x covered: True

Integer inputs have no gradient.

For a complex input the gradients are grad / (2 * conj(sqrt(z))) and -grad / (2 * conj(x) * conj(sqrt(x))), each part rounded once. PyTorch computes them as grad / (2 * result.conj()) and -0.5 * grad * result.pow(3).conj(), and the tolerance allows for those steps as a complex division or complex products on the forward's result:

Code
# The gradient of the complex square root's output
gz = torch.randn(65536, dtype=torch.complex64, generator=g)
zc_ = zc.clone().requires_grad_()
torch.sqrt(zc_).backward(gz)

print("grad_z covered:", er.sqrt.backward(zc, gz)["grad_z"].covers(zc_.grad).all())
Output
grad_z covered: True

Full specification#

er.sqrt#

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

The square root, elementwise: the exact root rounded once.

Each output element is the exact square root 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 root of the integer itself, and the tolerance covers an implementation that converts it to float32 first. Special values follow IEEE 754: sqrt(-0) is -0, the root of a negative value is NaN, and sqrt(inf) is inf.

tolerance() bounds an implementation whose square root is within ulps units in the last place of the exact root in the compute format (default 1/2: correctly rounded, as IEEE 754 requires), then rounded to the output. It is the exact worst case, and 0 where the compute format is the output format: a correctly rounding square root has no freedom. tolerance(ulps=1) accepts either value next to the exact root. z may also be an earlier result, as Result describes. Proof: proofs/sqrt.md.

A complex z gives the principal square root, each part the exact value rounded once: the real part is never negative, and on the negative real axis the imaginary part has the sign of z's (sqrt(-4+0j) is 2j and sqrt(-4-0j) is -2j). Special values are C99's. tolerance() bounds the method the C libraries share: a hypot within 3/2 ulps, a sum, a square root and a division, each rounded in the compute format. Each part is bounded in units of its own last place, however small it is beside the other. An implementation by the polar method, as CUDA's is, is sqrt_polar.

er.rsqrt#

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

The reciprocal square root 1 / sqrt(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. Special values follow IEEE 754 for 1 / sqrt(x): rsqrt(+0) is inf, rsqrt(-0) is -inf, rsqrt(inf) is 0, and the value at a negative x is NaN.

tolerance() bounds PyTorch's CPU method, two steps in the compute format: a square root within ulps units in the last place (default 1/2: correctly rounded), then its reciprocal, rounded, then the rounding to the output. It is the exact worst case, and the correctly rounded 1 / sqrt(x) is always inside it. An implementation that computes 1 / sqrt(x) with one function, as CUDA does, is rsqrt_direct. x may also be an earlier result, as Result describes. Proof: proofs/rsqrt.md.

A complex x gives 1 / sqrt(x) with the principal square root, each part the exact value rounded once. Where x is zero or a part is not finite the value is the complex reciprocal's of the square root's: rsqrt(0j) is inf+nanj. tolerance() bounds PyTorch's CPU method: the complex square root as sqrt bounds it, then the division of 1 by it by Smith's method, each step rounded in the compute format.

er.sqrt.backward#

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

The gradient of sqrt(z) for the output gradient grad.

grad_z = grad / (2 * sqrt(z)), in z's shape and dtype: each element is the exact value rounded once. tolerance() bounds PyTorch's formula computed in the compute format, grad / (2 * result) with result the square root as the forward's model gives it: the root rounded, doubled (exact), and the division rounded. PyTorch divides by the forward's stored output, which is rounded to the dtype: for a dtype narrower than the compute format, check it with tolerance(compute=dtype). Where z is zero the derivative does not exist, and the value is that formula's by IEEE rules on exact values, with sqrt(-0) = -0: an infinity of grad's sign at +0 and of the other sign at -0, and NaN where grad is zero. Integer inputs have no gradient. grad must have z's shape.

For a complex z the gradient is grad / (2 * conj(sqrt(z))), each part the exact value rounded once, and tolerance() bounds that division by Smith's method on the forward's result, as divide bounds a quotient whose divisor is an earlier result. Where z is zero or a part is not finite, the value is that formula's by IEEE rules on exact values.

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

grad_x = -grad / (2 * x * sqrt(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, (-0.5 * grad) * result**3 with result as the forward's model gives it and the cube as two rounded products. PyTorch cubes the forward's stored output, which is rounded to the dtype: for a dtype narrower than the compute format, check it with tolerance(compute=dtype). Where x is zero the derivative does not exist, and the value is that formula's by IEEE rules on exact values, with rsqrt(-0) = -inf: an infinity of the sign opposite to grad's at +0 and of grad's sign at -0, and NaN where grad is zero. Integer inputs have no gradient. grad must have x's shape.

For a complex x the gradient is -grad / (2 * conj(x) * conj(sqrt(x))), each part the exact value rounded once, and tolerance() bounds PyTorch's formula (-0.5 * grad) * conj((result * result) * result) as complex products of this library on the forward's result.

See also#