Results#

Every operation returns an er.Result. This page goes through what it holds and the options of its methods, on one result: a bfloat16 linear layer, 128 tokens of hidden size 4096 through a weight of 1024 outputs.

Code
import torch
import exactref as er

# Seeded, so every run uses the same values
g = torch.Generator().manual_seed(67)
# The layer's input, and its weight scaled as in a trained model
x = torch.randn(128, 4096, generator=g).bfloat16()
w = (torch.randn(1024, 4096, generator=g) / 64).bfloat16()

# ExactRef's result for the layer's product
r = er.matmul(x, w.T)

rounded and guarantee#

r.rounded is the exact answer rounded once to the output format: by default the input format. Operations with several array inputs, such as add, divide, gemm, and convolution, promote inputs of different formats as PyTorch does (bfloat16 with float16 gives float32). Integer and bool inputs give int64 from sum and cumulative_sum, and float32 from divide, reciprocal, logsumexp, and the elementwise functions such as exp and sqrt, as in PyTorch. The operation's dtype= and rounding= arguments choose another format and rounding.

Code
# Row 0's first three elements: the exact product, rounded once to bfloat16
print("rounded:", r.rounded.tolist()[0][:3])
# What rounded satisfies
print("guarantee:", r.guarantee)

# An int8 quantized layer, with its products summed into int32
xq = torch.randint(-128, 128, (128, 4096), generator=g, dtype=torch.int8)
wq = torch.randint(-128, 128, (1024, 4096), generator=g, dtype=torch.int8)
print("int32 guarantee:", er.matmul(xq, wq.T, dtype="int32").guarantee)
Output
rounded: [0.4140625, 2.515625, -0.8046875]
guarantee: correctly_rounded
int32 guarantee: exact

guarantee says what rounded satisfies: "correctly_rounded" for floating-point and complex outputs, and "exact" for integer outputs. When an operation cannot establish its guarantee, it raises ReferenceUnavailableError instead of returning a result.

exact#

Use r.exact when you need the exact value itself rather than its rounding, for example to grade an implementation that is more precise than the output format, or to measure an error exactly. It holds an enclosure of every exact value: r.exact.value(index) is an Enclosure, and the true value lies within radius of midpoint.

enclosure rounding point midpoint format value rounds to this one midpoint +/- radius

An enclosure holds the exact value. When it lies on one side of the point where the rounding changes, every value inside it rounds the same way, which is how ExactRef knows rounded is right.

Code
# The enclosure of element (0, 0)
e = r.exact.value((0, 0))
# The radius is an exact Fraction
print("radius:", repr(e.radius))
# The midpoint as an exact Fraction, then as the nearest float64
print("midpoint:", float(e.midpoint.to_fraction()))
Output
radius: Fraction(0, 1)
midpoint: 0.41482499055564404

A radius of 0 means the midpoint is the exact value, as it is for this layer's sums of products. Transcendental values have a tiny nonzero radius, such as the entries of a matrix exponential, here of a 64 by 64 skew-symmetric matrix as an orthogonal weight parametrization uses:

Code
from fractions import Fraction

# A 64x64 float32 skew-symmetric matrix: s minus its transpose
s = torch.randn(64, 64, generator=g) / 8
m = er.matrix_exp(s - s.T)
# The enclosure of element (0, 0)
e = m.exact.value((0, 0))
# Is its radius above 0 but below 2**-100?
print("tiny nonzero radius:", 0 < e.radius < Fraction(1, 2**100))
Output
tiny nonzero radius: True

A complex element's enclosure is a pair, real part then imaginary part, and r.exact.values() lists every element's enclosure, row-major. Each midpoint has a 128-bit significand, and the radius is at most one unit in its last place. Two rare cases differ, an element whose enclosure contains 0 and an exact value too large or too small to store: ExactArray and Enclosure describes both.

tolerance()#

r.tolerance(compute=None, *, ulps=None, flush_to_zero=False, standard="normal",
            workers=None)

The worst-case |output - rounded| per element over the finite outputs of correct implementations. The options describe which implementations count as correct:

Option

Meaning

Default

compute

the format the implementation rounds to and adds in at the operation's required rounding steps

float32 for inputs narrower than float32, else the input format

ulps

how far each library function, such as exp or log, may be off, in units in the last place of the compute format; at least 1/2. Matrix functions and Fourier transforms read it another way, below

each operation's own, below

flush_to_zero

the implementation flushes values below a format's smallest normal number to zero, as torch.set_flush_denormal(True) does

False

standard

"normal" for normal accumulation (index order, or 2 or 4 SIMD-style lanes; for softmax, log_softmax, and logsumexp also the wider orders of PyTorch's kernels); "any_order" for any order of additions that does not overflow

"normal"

workers

the number of threads the bounds are computed on; no result depends on it

the performance cores on Apple Silicon, else the physical cores, as PyTorch picks

Code
# Row 0's first three tolerances, for implementations that add the normal way
print("tolerance:", r.tolerance().tolist()[0][:3])
# The same, for implementations that add in any order
print("any order:", r.tolerance(standard="any_order").tolist()[0][:3])
Output
tolerance: [0.0, 0.0, 0.0]
any order: [0.009765625, 0.015625, 0.01171875]

All three elements have a tolerance of 0: every implementation that adds the normal way in float32 lands exactly on rounded there. The result is a float64 array, rounded upward. For complex outputs it is complex128, one bound per part. inf marks an element with no bound at all, and nan an element whose reference is not finite. Results are kept, so asking again with the same options does not compute them again.

Each operation sets its own default ulps, what a careful library meets:

Operation

Default ulps

exp, expm1, log, and sigmoid, and the operations built on them: softmax, log_softmax, logsumexp, and attention

1: either float next to the exact value

log1p and tanh

1.0001: also the float one full step from an exact value that lies just beside a float

sqrt, rsqrt, std, and the normalizations' square roots

1/2: the square root correctly rounded

matrix_exp and matrix_exp_frechet

1: a multiple of the backward error the tolerance allows

the Fourier transforms

2 for float32 and narrower compute formats, 10 for float64: how far each twiddle factor may be off, in units of the compute format's unit roundoff

The real functions that a complex input's computation calls, such as cos and atan2, also default to 1, except the modulus inside a complex sqrt, at 3/2. flush_to_zero acts on inputs, on results in the compute format, and on outputs: Flushing subnormals to zero gives the rule for each.

finite_range(), may_be(), and covers()#

They take the same options as tolerance():

  • r.finite_range() returns (low, high): the lowest and highest finite output of a correct implementation, as arrays of the output's dtype.

  • r.may_be("+inf"), r.may_be("-inf"), and r.may_be("nan") say where a correct implementation may produce that value. They err on the safe side: they can be True where no correct implementation overflows, but they are never False where one can.

  • r.covers(output) combines them into one verdict per element. output must have the result's dtype and shape.

Reading complicated tolerances shows them on overflow, infinities, NaN, and complex outputs.

normal()#

r.normal(compute=None, *, flush_to_zero=False, workers=None)

The normal answer: what an ordinary implementation computes, to compare with your implementation's output when a check fails. It is the output of normal accumulation in index order, emulated exactly: each product is rounded to the compute format and added in index order, each sum rounded to nearest, ties to even. Where adding the next value would overflow, it starts a new partial sum, and the partial sums are then combined the same way. The result is rounded to the output format as rounded is.

Code
# Row 0's first three elements, as a loop that adds in index order returns them
print("normal:", r.normal().tolist()[0][:3])
Output
normal: [0.4140625, 2.515625, -0.8046875]

It is computed only when you call it, and kept. Each operation's reference page lists the other choices its normal answer makes. These have no normal answer:

  • matrix_exp, matrix_exp_frechet, the Fourier transforms, and their backwards, whose normal() raises NotImplementedError;

  • the named algorithms reciprocal_estimate, rsqrt_direct, rsqrt_estimate, sqrt_polar, var_welford, std_welford, and the softmax, logsumexp, normalization, and elementary function algorithms, which have no normal().

Complex inputs of the other operations have one. For exp, log, tanh, and the other elementary functions, it is PyTorch's Linux CPU sequence, with each library function correctly rounded.

Several outputs#

Some operations return more than one output, held by name:

  • attention returns output and logsumexp;

  • var returns var and mean, and std returns std and mean;

  • batch_norm in training, given running statistics, returns output, running_mean, and running_var;

  • a backward returns a gradient for each input array but a scalar operand and attention's mask, named grad_ plus the input's name, such as grad_A for matmul's A.

r[name] is a result for just that output, which is what covers() and later operations need:

Code
# The layer's gradients for an upstream gradient from the next layer
grad = torch.randn(128, 1024, generator=g).bfloat16()
gb = er.matmul.backward(x, w.T, grad)
# The names of its outputs
print("outputs:", list(gb.rounded))
# One output, read by name from rounded
print("grad_A shape:", gb.rounded.grad_A.shape)
# gb["grad_B"] is a result holding just that output
print("grad_B shape:", gb["grad_B"].rounded.shape)
Output
outputs: ['grad_A', 'grad_B']
grad_A shape: (128, 4096)
grad_B shape: (4096, 1024)

Backward checks these against PyTorch's autograd.

boundaries#

r.boundaries tells you which rounding steps the tolerance allows for: the operation's required rounding steps (boundaries), each one rounding of a value, a sum whose partial sums round, or a library function such as exp. They are listed by name, each an er.Boundary with a kind, a description, and what it applies_to:

Code
# The names of matmul's required rounding steps: it has one
print("boundaries:", list(r.boundaries))
# That boundary, looked up by name
b = r.boundaries["accumulate"]
# What kind of rounding step it is, and what it applies to
print("kind:", b.kind)
print("applies to:", b.applies_to)
print("description:", b.description)
Output
boundaries: ['accumulate']
kind: accumulate
applies to: dot
description: summation of the k products of one output element

Views: reshape and transpose#

r.reshape(shape) and r.transpose(i, j) give a one-output result in another layout, for a later operation that needs it. Moving elements rounds nothing, so rounded, exact, tolerance(), and normal() move with them. A query projection, for example, is split into heads before attention:

Code
# The 1024 outputs per token split into 8 heads of 128, then heads first
heads = r.reshape((128, 8, 128)).transpose(0, 1)
print("heads:", heads.rounded.shape)
Output
heads: (8, 128, 128)

A view has no backward of its own: call backward on the original result, with the gradient reshaped back.

As the next step's input#

You can pass a result in place of an array to any operation, backward, or algorithm. The next result's bounds then cover every value this result allows, since the implementation may have stored any of them: its uncertainty carries into the next step. Chains and any_of explains how.

A result passed this way must have one unnamed output. For a result with named outputs, such as a backward's or var's, pass r[name]: passing the result itself raises TypeError. The tensor-core algorithms are the one exception: they take a float32 A or B only as an array of TF32 values, not as an earlier result.

backward()#

r.backward(grad) runs the operation's backward on the same inputs. See Backward.