Reading complicated tolerances#

How tolerance works covers single numbers: the reference rounded, the exact answer rounded once to the output format, and tolerance(), per element how far from it a correct implementation's output can be, on these inputs. Real checks run over whole tensors and meet overflow, infinities, NaN, several outputs, complex numbers, and kernels that round in their own way. This page shows how to read the result in each case.

A whole tensor at once#

covers() says, per element, whether a correct implementation can produce the output. By default it checks against the normal tolerance, tolerance(), which covers normal accumulation: the order ordinary kernels add in, index order or 2 or 4 SIMD lanes side by side (softmax also allows wider ones). With standard="any_order" it checks against the wider any-order tolerance, for any order of additions at all, as a parallel reduction on a GPU may use. Together they give three verdicts: no worse than normal accumulation can be, correct but worse, and wrong.

covers() returns a bool array with the output's shape, so you can count the verdicts and find the elements behind them. The example below takes the sum from Normal and any-order: three verdicts, which had 96 ones, and makes 26 rows of it with 0 to 200 ones: the kind of large cancellation an 8-lane SIMD kernel handles worst. The 8-lane implementation from that example computes each row:

Code
import exactref as er

# 26 rows of 208 floats: 1e16 and -1e16 padded with zeros, then n ones
# (n = 0, 8, ..., 200), then zeros
rows = [[1e16, 0.0, 0.0, 0.0, -1e16, 0.0, 0.0, 0.0] + [1.0] * n + [0.0] * (200 - n)
        for n in range(0, 201, 8)]

# Adds element i to running sum i % 8, then adds up the 8 sums in order
def eight_lanes(xs):
    lanes = [0.0] * 8
    for i, x in enumerate(xs):
        lanes[i % 8] += x
    total = 0.0
    for lane in lanes:
        total += lane
    return total

# Its output for every row, as one ExactRef array
out = er.asarray([eight_lanes(row) for row in rows])
# ExactRef's result for the sum of each row
r = er.sum(rows, axis=1)
# Per row, whether the output passes the normal tolerance, as Python bools
normal = r.covers(out).scalars()
# Per row, whether it passes the any-order tolerance
any_order = r.covers(out, standard="any_order").scalars()
# Per row, True if the output passes the any-order tolerance only
worse = [a and not n for n, a in zip(normal, any_order)]

# Count the rows with each verdict
print("no worse than normal:", sum(normal))
print("correct but worse:", sum(worse))
print("wrong:", sum(not a for a in any_order))
Output
no worse than normal: 2
correct but worse: 24
wrong: 0

2 rows are no worse than normal accumulation, 24 are correct but worse, and none is wrong. To see why a row landed where it did, read its numbers:

Code
# Row 12, the one with 96 ones
i = 12
# Its output from eight_lanes
print("output:", out.scalars()[i])
# Its exact sum, rounded once
print("rounded:", r.rounded.scalars()[i])
# How far a correct output can be from rounded under normal accumulation
print("tolerance:", r.tolerance().scalars()[i])
Output
output: 72.0
rounded: 96.0
tolerance: 3.330669073877175

Overflow, infinities, and NaN#

The tolerance bounds finite outputs only. Three more methods handle the rest, so a check needs no special cases:

  • finite_range(): the lowest and highest finite output a correct implementation can produce.

  • may_be("+inf"), may_be("-inf"), may_be("nan"): where a correct implementation may produce that value instead.

  • covers(output): uses both.

A sum close to the top of its format's range may overflow in one order of additions and not in another. There the tolerance stays finite, and may_be("+inf") reports the possible infinity:

Code
# ExactRef's result for a float32 sum near the top of float32's range
top = er.sum(er.asarray([3.4028234e38, 2e31, -1e31], "float32"))
# The exact sum, rounded once to float32
print("rounded:", top.rounded.tolist())
# How far a correct finite output can be from rounded
print("tolerance:", top.tolerance().tolist())
# The lowest and highest finite output, (low, high), as plain floats
print("finite range:", [end.tolist() for end in top.finite_range()])
# Whether a correct implementation may return +inf instead
print("may be +inf:", top.may_be("+inf").tolist())
# Does +inf pass the check?
print("+inf covered:", top.covers(er.asarray(float("inf"), "float32")).all())
Output
rounded: 3.4028234663852886e+38
tolerance: 4.056481920730334e+31
finite range: [3.4028230607370965e+38, 3.4028234663852886e+38]
may be +inf: True
+inf covered: True

The reference is the largest float32 value. An implementation that adds 2e31 first overflows to infinity, and that is correct too:

+inf finite range largest finite value overflows past here may_be("+inf")

Near the top of the range, the finite range ends at the largest finite value, and may_be("+inf") says a correct implementation may overflow instead.

A NaN tolerance means the reference itself is not finite, so there is no distance to measure:

Code
# ExactRef's result for a float32 sum of about 6e38, beyond float32's range
inf = er.sum(er.asarray([3e38, 3e38], "float32"))
# The reference is +inf, so the tolerance is NaN
print("rounded:", inf.rounded.tolist())
print("tolerance:", inf.tolerance().tolist())
# The lowest and highest finite output
print("finite range:", [end.tolist() for end in inf.finite_range()])
# Whether a correct implementation may return +inf
print("may be +inf:", inf.may_be("+inf").tolist())
Output
rounded: inf
tolerance: nan
finite range: [nan, nan]
may be +inf: True

Here no finite output can occur, so the range is empty (both ends NaN) and only +inf passes. But a reference can be infinite while correct implementations still return finite values:

Code
# ExactRef's result for a float32 sum whose exact value rounds to +inf
near = er.sum(er.asarray([3.4028234e38, 6e30, 6e30], "float32"))
# The reference is +inf, so the tolerance is NaN
print("rounded:", near.rounded.tolist())
print("tolerance:", near.tolerance().tolist())
# What a loop that adds in index order returns
print("normal:", near.normal().tolist())
# The lowest and highest finite output that can still occur
print("finite range:", [end.tolist() for end in near.finite_range()])
# Does the largest finite float32 value pass the check?
print("largest finite covered:",
      near.covers(er.asarray(3.4028234663852886e+38, "float32")).all())
Output
rounded: inf
tolerance: nan
normal: 3.4028234663852886e+38
finite range: [3.4028230607370965e+38, 3.4028234663852886e+38]
largest finite covered: True

The exact sum is just past the point where float32 rounds to infinity. Added in index order, each 6e30 is less than half the spacing of float32 values up there, so both are lost and the loop returns the largest finite value. finite_range() keeps those finite outputs, so covers() accepts them.

Some final roundings cannot overflow: rounding toward zero, rounding toward -inf for a positive result or toward +inf for a negative one, and overflow="saturate", as a kernel that clamps its output does. They give the largest finite value instead. The reference is then that value, and the tolerance is measured from it:

Code
# Three float16 values whose exact sum, 70001, is past float16's largest, 65504
x16 = er.asarray([40000.0, 30000.0, 1.0], "float16")
# ExactRef's result for their sum, with the final rounding toward zero
capped = er.sum(x16, rounding=er.Rounding.TOWARD_ZERO)
# The reference and its tolerance
print("rounded:", capped.rounded.tolist())
print("tolerance:", capped.tolerance().tolist())
Output
rounded: 65504.0
tolerance: 0.0

Infinite and NaN inputs follow IEEE rules on the exact sum:

Code
# ExactRef's result for the float32 sum of +inf and -inf
special = er.sum(er.asarray([float("inf"), float("-inf")], "float32"))
# NaN, as IEEE arithmetic gives for inf + (-inf)
print("rounded:", special.rounded.tolist())
# Whether a correct implementation may return NaN, and +inf
print("may be NaN:", special.may_be("nan").tolist())
print("may be +inf:", special.may_be("+inf").tolist())
Output
rounded: nan
may be NaN: True
may be +inf: False

An infinite tolerance means no bound at all: every finite value is in the finite range, and may_be() is True for +inf, -inf, and NaN. An operation called on plain arrays rarely gives one, as where an attention logit may overflow. It can appear in a chain, where you pass an earlier result in place of an array, and the next result's bounds cover every value the earlier result allows, since the implementation may have stored any of them. If the next operation applies exp, as attention does, and the earlier step may have stored +inf, exp can turn that back into a finite value:

Code
# The sum from above, as the one row of a 1x3 array
first = er.sum(er.asarray([[3.4028234e38, 2e31, -1e31]], "float32"), axis=1)
# A correct implementation of it may store +inf
print("first may be +inf:", first.may_be("+inf").tolist())

# The 2x2 identity matrix, as a 1x1x2x2 array
eye = er.asarray([[[[1.0, 0.0], [0.0, 1.0]]]], "float32")
# Keys: eye times first. Passing the result itself, reshaped to 1x1x1x1,
# carries its possible +inf into the keys.
key = er.multiply(eye, first.reshape((1, 1, 1, 1)))
# One query and two values
query = er.asarray([[[[1.0, 2.0]]]], "float32")
value = er.asarray([[[[1.0, 1.0], [2.0, 2.0]]]], "float32")
# ExactRef's result for attention, which applies exp to the scores
a = er.scaled_dot_product_attention(query, key, value)
# Attention has two outputs, read by name: output and logsumexp (see Several
# outputs below). The reference and tolerance of output:
print("output:", a.rounded.output.tolist())
print("tolerance:", a.tolerance().output.tolist())
Output
first may be +inf: [True]
output: [[[[2.0, 2.0]]]]
tolerance: [[[[inf, inf]]]]

Several outputs#

Attention returns two outputs, named as in PyTorch: output and logsumexp. rounded, tolerance(), and the other methods hold both, by name, and r["output"] is a result for just one of them:

Code
# Two queries, three keys, and three values, each with 2 features
q = er.asarray([[[1.0, 0.5], [0.25, -1.0]]], "float32")
k = er.asarray([[[1.0, 0.0], [0.0, 1.0], [1.0, 1.0]]], "float32")
v = er.asarray([[[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]]], "float32")
# Per query, the keys it keeps (True): keys 0 and 2 for the first query
mask = er.asarray([[[True, False, True], [False, False, False]]], "bool")
# ExactRef's result for attention with that mask
a = er.scaled_dot_product_attention(q, k, v, attn_mask=mask)
# The names of its outputs
print("outputs:", list(a.rounded))
# Each output, read by name
print("output:", a.rounded.output.tolist())
print("logsumexp:", a.rounded.logsumexp.tolist())
print("logsumexp tolerance:", a.tolerance().logsumexp.tolist())
Output
outputs: ['output', 'logsumexp']
output: [[[3.3499159812927246, 4.349915981292725], [0.0, 0.0]]]
logsumexp: [[1.592574954032898, -inf]]
logsumexp tolerance: [[5.960464477539062e-07, nan]]

The mask keeps no key for the second query, so that row's output is 0 and its logsumexp is -inf (the log of an empty sum), which has a NaN tolerance like every non-finite reference. logsumexp is in float32 for outputs narrower than float32, as fused kernels return it.

covers() on a itself takes a dict of outputs by name, as in a.covers({"output": out}), and returns a verdict for each by name. To check one output on its own, use a["output"]. Here is PyTorch's attention under a padding mask, for a batch of four sequences of different lengths, 8 heads, 512 positions, and head dimension 64:

Code
import torch

# Seeded, so every run uses the same values
g = torch.Generator().manual_seed(67)
# Queries, keys, and values: (batch, heads, positions, head dimension)
q, k, v = (torch.randn(4, 8, 512, 64, generator=g) for _ in range(3))

# The padding mask: each sequence keeps its first n positions as keys
keep = torch.zeros(4, 1, 1, 512, dtype=torch.bool)
for b, n in enumerate([512, 300, 77, 1]):
    keep[b, :, :, :n] = True

# ExactRef's result, and PyTorch's output, for the same masked attention
a = er.scaled_dot_product_attention(q, k, v, attn_mask=keep)
out = torch.nn.functional.scaled_dot_product_attention(q, k, v, attn_mask=keep)
# a["output"] is a result for that output alone, which covers() can check
print("covered:", a["output"].covers(out).all())
Output
covered: True

Gradients work the same way, with names such as grad_A and grad_query; Backward checks them against PyTorch's autograd.

Complex outputs#

Complex outputs come from signal-processing and physics code, where one part of an element can overflow while the other stays finite. Each part of a complex element is bounded on its own. tolerance() returns complex128: its real part bounds the real part of the difference, its imaginary part the imaginary part. may_be() and covers() add a last axis of 2, real then imaginary, the layout of torch.view_as_real:

Code
# ExactRef's result for a complex128 sum whose real part is infinite
z = er.sum(er.asarray([complex("inf+1j"), 1 + 1j], "complex128"))
# The exact sum, rounded once
print("rounded:", z.rounded.tolist())
# One bound per part, as one complex number
print("tolerance:", z.tolerance().tolist())
# Per part, real then imaginary: may a correct implementation return +inf?
print("may be +inf:", z.may_be("+inf").tolist())
# Per part: is inf+2.5j correct?
print("inf+2.5j covered:",
      z.covers(er.asarray(complex("inf+2.5j"), "complex128")).tolist())
Output
rounded: (inf+2j)
tolerance: (nan+4.440892098500626e-16j)
may be +inf: [True, False]
inf+2.5j covered: [True, False]

The real part is infinite, so it has a NaN tolerance, but the imaginary part is still checked: 2.5 is too far from 2.

Kernels that round more than the operation requires#

The tolerance of an operation covers implementations that round only where the operation requires: at the steps where every correct implementation has to round, such as each partial sum or the final rounding to the output format. Some kernels round in more places. FlashAttention, for example, computes each weight exp(score - row maximum) without normalizing it, rounds the weights to bfloat16 for the product with V, and normalizes by the row sum at the end. Here is that arithmetic emulated in PyTorch, for causal attention with 8 heads, 1024 positions, and head dimension 64:

Code
# Queries, keys, and values: (batch, heads, positions, head dimension)
q, k, v = (torch.randn(1, 8, 1024, 64, generator=g) for _ in range(3))

# The scores q times k transposed, scaled by 1/sqrt(64)
scores = (q @ k.transpose(-2, -1)) / 8.0
# True above the diagonal: the later keys each query must not see
causal = torch.ones(1024, 1024, dtype=torch.bool).triu(1)
# Remove those keys: a score of -inf gets weight 0
scores = scores.masked_fill(causal, float("-inf"))

# The unnormalized weights and their row sums, in float32
weights = torch.exp(scores - scores.amax(-1, keepdim=True))
row_sums = weights.sum(-1, keepdim=True)
# The weights rounded to bfloat16 for the product with v, then divided by the sums
out = (weights.bfloat16().float() @ v) / row_sums

# ExactRef's result for causal attention on the same inputs
r = er.scaled_dot_product_attention(q, k, v, is_causal=True)
# Does the operation's own tolerance cover the kernel's output?
print("covered:", r["output"].covers(out).all())
Output
covered: False

The operation's own tolerance does not allow for the extra rounding. The matching algorithm, one specific way of computing the operation with its own bounds, does:

Code
# An algorithm that also rounds the weights to bfloat16 before multiplying by v
flash = er.nn.attention.AttentionAlgorithm(weights="bfloat16")
# Does its tolerance cover the kernel's output? covers() takes outputs by name.
print("flash covered:",
      flash.covers({"output": out}, q, k, v, is_causal=True).output.all())

# The largest tolerance of any output element: the operation's own, then flash's
print("largest tolerance:", max(r.tolerance().output.scalars()))
print("largest flash tolerance:",
      max(flash.tolerance(q, k, v, is_causal=True).output.scalars()))
Output
flash covered: True
largest tolerance: 4.172325134277344e-05
largest flash tolerance: 0.013547182083129883

A kernel that rounds the normalized weights instead, as PyTorch's math path does when it materializes them, is a different computation that no tolerance allows for (Guarantees and limits).

Finer than the output format#

When the implementation you check is more precise than the output format, or when you want to measure an error exactly, use r.exact. It holds an enclosure of each exact value: a midpoint and a radius, with the exact value no further than the radius from the midpoint. A careful library that takes float32 inputs but adds in float64, for example, is far better than any float32 output can show:

Code
import random
from fractions import Fraction

# Seeded, so every run uses the same values
rng = random.Random(67)
# A float32 row of 4096 activations and a column of weights
xs = torch.tensor([rng.gauss(0, 1) for _ in range(4096)])
ws = torch.tensor([rng.gauss(0, 1) for _ in range(4096)]) / 64

# ExactRef's result for their dot product, and the enclosure of the exact value
d = er.matmul(xs, ws)
e = d.exact.value()
# A radius of 0: the midpoint is the exact dot product
print("radius:", repr(e.radius))

# The implementation: the same dot product added in float64, as Python floats
total = 0.0
for a, b in zip(xs.tolist(), ws.tolist()):
    total += a * b

# Its error, exactly: the exact value of total minus the exact dot product
print("float64 error:", float(Fraction(total) - e.midpoint.to_fraction()))
# The error of the best float32 answer, for comparison
print("float32 error:", float(d.rounded.value().to_fraction() - e.midpoint.to_fraction()))
Output
radius: Fraction(0, 1)
float64 error: -1.875940808943044e-15
float32 error: -1.320531005621602e-08

Flushing subnormals to zero#

Subnormals are the tiny values below a format's smallest normal number. Some hardware modes, and torch.set_flush_denormal(True), flush them to zero, which matters for data with tiny values, such as small gradients late in training. Say so with flush_to_zero=True. On one product:

Code
# ExactRef's result for a float32 product of about 1e-40, a float32 subnormal
t = er.multiply(er.asarray([1e-30], "float32"), er.asarray([1e-10], "float32"))
# The reference and its tolerance
print("rounded:", t.rounded.tolist())
print("tolerance:", t.tolerance().tolist())

# The output of an implementation that flushes the product to zero
zero = er.asarray([0.0], "float32")
# Is it correct by default? And with flush_to_zero=True?
print("zero covered:", t.covers(zero).all())
print("zero covered, flushing:", t.covers(zero, flush_to_zero=True).all())
# The tolerance with flushing: 2**-126, the smallest normal float32
print("flushing tolerance:", t.tolerance(flush_to_zero=True).tolist())
Output
rounded: [9.99994610111476e-41]
tolerance: [0.0]
zero covered: False
zero covered, flushing: True
flushing tolerance: [1.1754943508222875e-38]

A flush can happen wherever a value moves into a float format. Each place has its own threshold:

Where

A value may become zero when it is below

an input is read

the smallest normal number of the input's own format, or of the compute format if that is larger

a result is rounded to the compute format

the compute format's smallest normal number

the output is rounded

the output format's smallest normal number

The thresholds differ when the formats do. float32 data computed in float64 has its subnormal values read as zero, though float64 holds them as normal numbers. A float64 result below 2**-126 becomes zero when it is stored as float32. An operand promoted to a wider format, such as float32 data added to float64 data, is read by its own format's threshold.

As an input's or the output's format, a format with less precision than float32 counts as float32, since implementations hold bfloat16, float16, and 8-bit values in float32. So bfloat16 values flush below 2**-126. float16 and 8-bit values are never that small, so they flush only where the compute format is itself that narrow, as with compute="float16".

normal() with flush_to_zero=True gives the answer of an implementation that tests each value before rounding it, as ARM CPUs do. An x86 CPU tests after the rounding, so it keeps a value just below the smallest normal number that rounds up to it. Some builds compute part of a large array on threads that do not flush. The bounds allow all of these.

Matrix exponential#

matrix_exp has no rounding step that every algorithm shares: Taylor and Pade methods of any degree, with any number of squarings, all compute it. So its tolerance is a backward error instead: a correct result is exp(A + dA) for a small dA. Guarantees and limits gives the bound on dA, the matrices it was measured on, and the implementations known to exceed it. Here it is for a 64 by 64 skew-symmetric matrix, as an orthogonal weight parametrization uses:

Code
# A 64x64 float64 skew-symmetric matrix: s minus its transpose
s = torch.randn(64, 64, generator=g, dtype=torch.float64) / 8
m = er.matrix_exp(s - s.T)
# Row 0's first two entries of the exact exponential, rounded once to float64
print("rounded:", m.rounded.tolist()[0][:2])
# The largest tolerance of any entry, from the backward error
print("largest tolerance:", max(m.tolerance().scalars()))

# Asking for the normal answer raises an error
try:
    m.normal()
except NotImplementedError as error:
    print(f"{type(error).__name__}: {error}")
Output
rounded: [0.2153948564738674, 0.004926118263893915]
largest tolerance: 4.0947800705737336e-13
NotImplementedError: matrix_exp has no normal answer

There is no single ordinary algorithm to emulate, so there is no normal answer.

Where to go next#

  • Algorithms: kernels that round in more places than the operation requires, such as fused attention and tensor cores.

  • Chains and any_of: checking a computation of several steps.

  • Backward: the same checks on gradients.

  • Guarantees and limits: what a tolerance covers and what it does not.