Result#
A result holds everything ExactRef works out for one call: the exact answer rounded to the output format, enclosures (intervals guaranteed to contain the exact answer), and the bounds that say which outputs a correct implementation can produce.
Every operation returns an er.Result. Results
walks through it with examples; this page lists every method.
At a glance#
Attribute or method |
What it gives |
|---|---|
|
the exact answer, rounded once to the output format |
|
enclosures guaranteed to contain the exact answer |
|
|
|
per element, how far a correct implementation's finite output can be from |
|
the lowest and highest finite output a correct implementation can produce |
|
where a correct implementation may output |
|
per element, whether a correct implementation can produce |
|
the normal answer: what an ordinary implementation that adds in index order computes, emulated exactly |
|
the operation's backward on the same inputs |
|
a result for one named output, such as attention's |
|
the same result in another layout |
|
the operation's required rounding steps |
|
the operation's name |
tolerance(), finite_range(), may_be(), and covers() take the same
options: compute, ulps, flush_to_zero, standard, and workers.
standard picks the orders of additions they allow for. By default they
cover normal accumulation, the order ordinary kernels add in: index
order, or SIMD lanes side by side, in the
compute format. With standard="any_order" they cover any order
of additions at all, as a parallel reduction or atomic adds on a GPU may use,
and the tolerance can be wider. A finite output is covered where it lies
within finite_range(), which lies within tolerance() of rounded and can
be closer on one side, or within finite_range(standard="any_order") when you
pass that option:
The reference, rounded, with the band of tolerance() around it and the
wider band of tolerance(standard="any_order").
Example: a test report#
When a check fails in a test suite, the report should say which operation
failed and what its reference guarantees. r.op names the operation and
r.guarantee says what rounded satisfies. Here a small helper reports on
two outputs for a bfloat16 linear layer, 128 tokens of hidden size 1024
through a 1024 by 1024 weight: PyTorch's, and that of a kernel that
truncates its float32 sums to bfloat16, a bug
Find a bug in a matmul backend
describes:
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 weight
x = torch.randn(128, 1024, generator=g).bfloat16()
w = (torch.randn(1024, 1024, generator=g) / 32).bfloat16()
# ExactRef's result for the layer's product
r = er.matmul(x, w.T)
def report(result, output):
"""One line for a test report: the operation, its guarantee, and the verdict."""
covered = result.covers(output).scalars()
failed = covered.count(False)
verdict = "covered"
if failed:
verdict = f"{100 * failed / len(covered):.0f}% of elements not covered"
print(f"{result.op} ({result.guarantee}): {verdict}")
# PyTorch's output
report(r, x @ w.T)
# The buggy kernel: float32 sums, truncated to bfloat16 by dropping their low 16 bits
sums = x.float() @ w.float().T
report(r, (sums.view(torch.int32) & -65536).view(torch.float32).bfloat16())
matmul (correctly_rounded): covered
matmul (correctly_rounded): 48% of elements not covered
As the next step's input#
To check a computation of several steps one step at a time, you can pass a
result in place of an array to any operation, backward, or
algorithm. The new
result's bounds then cover every value the earlier result allows. A result
with one output can be passed directly. For a result with named outputs,
such as a backward's gradients or var's variance and mean, pass
r[name]. Two
exceptions: the tensor-core algorithms take a float32 A or B only as an
array of TF32 values, and the held-scalar algorithms take no earlier result
of shape () as a scalar operand. Chains and any_of
describes how.
Full specification#
- class Result#
What an operation definition returns.
rounded: the exact answer rounded once to the output format.exact: the exact answer as certified enclosures (ExactArray).tolerance(): how far normal accumulation's finite output can be fromroundedon these inputs, a proven bound;tolerance(standard="any_order")covers every accumulation order that does not overflow.finite_range(),may_be()andcovers(): the lowest and highest finite output, the infinities and NaN an implementation may produce, and the judgment of an implementation's output.normal(): the output of normal accumulation in index order on these inputs, computed when asked for.
For one output these are the arrays themselves; several outputs, and a backward's gradients whatever their number, are named: attention's
outputandlogsumexp, and a backward'sgrad_plus its input's name, for exampleresult.rounded.grad_A.result[name]is a result holding just that output. A one-output result's output is named by its operation: matmul'sC, gemm'sD, multiply's and add'soutput, sum'ss, matrix_exp'sEand matrix_exp_frechet'sL, and the Fourier transforms'X(fft, rfft, ihfft, hfft) orx(ifft, irfft).guaranteestates whatroundedsatisfies, andboundarieslists the operation's required rounding boundaries.backward(grad)runs the operation's backward from the same inputs.A result with one unnamed output (a forward's; pass a backward's gradient as
result[name]) can be passed in place of an array to any operation, backward or algorithm, except as a tensor-core algorithm's float32AorB(its stored values need not be tf32 values) and as a held-scalar algorithm's scalar of shape () (the chainmultiply(s, 1, dtype=...)holds it), which raise ValueError. The implementation under test stored that output, so each stored value is one this result's bounds allow: within its tolerance ofrounded(part by part for complex values), or an infinity or NaN thatmay_be()allows. The later result'sroundedandexactare the exact answer onrounded, rounded once; its bounds cover every value these bounds allow, taken with the same arguments: an infinite radius leaves no bound in the outputs it reaches, and a stored infinity or NaN passes on as their flags (proofs/foundations.md, Results as inputs); itsnormal()works on thisnormal(); and an algorithm'srun()usesrounded.- guarantee#
What
roundedsatisfies:"correctly_rounded"for floating-point and complex outputs,"exact"for integer outputs.
- op#
The operation's name, such as
"matmul"or"matmul.backward".
- tolerance(compute: Format | str | None = None, *, ulps: int | Fraction | None = None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) Array | Outputs#
Worst-case
|implementation output - rounded|per element.The bound covers every implementation that loses precision only at the operation's required boundaries:
at most one rounding to
computeat each required rounding boundary,accumulation in
compute: withstandard="normal"(the default), normal accumulation, which adds in index order or in 2 or 4 SIMD-style lanes, rounds each product and then adds it, and starts a new partial sum where adding the next value would overflow; withstandard="any_order", any order (any summation tree, with or without fused multiply-add) that does not overflow,library functions within
ulpsunits in the last place ofcompute, for matrix functions a backward error measured inulps, and for Fourier transforms twiddle factors withinulpsunits ofcompute's unit roundoff (see each operation),the final rounding to the output format.
An output within the normal tolerance is no worse than normal accumulation can be. Beyond it but within the any-order tolerance, it is technically correct but worse than normal accumulation can be (for example from a poor accumulation order). Beyond the any-order tolerance, no implementation that rounds only there without overflowing could produce it. Matrix functions bound a backward error instead, and Fourier transforms their passes of butterflies, the same under
standard="normal"and"any_order".computedefaults to float32 for inputs narrower than float32 and to the input format otherwise; the Fourier transforms, whose inputs are promoted to the output format first, as PyTorch's are, apply that rule to the output format (a complex one's parts' format). Withflush_to_zero, the implementation flushes values to zero astorch.set_flush_denormal(True)does, wherever a value moves into a float format: an input below the smallest normal number of its own format or of the compute format may be read as zero, a result below the compute format's may be produced as zero, and so may an output below the output format's. A format with less precision than float32 counts as float32 here, since implementations hold its values in float32: under the default compute format a float16 value is not flushed, while undercompute="float16"one below float16's smallest normal number may be. An operand that is promoted to a wider format is read by its own format's number.The result is a float64 array rounded upward, counting only finite output values the output format can represent. For complex outputs it is complex128 with one bound per part: its real part bounds
|Re(output - rounded)|and its imaginary part|Im(output - rounded)|. A finite reference gets a finite tolerance wherever its finite outputs can be bounded;infmarks elements with no finite bound, andnanelements whose reference is not finite.finite_range()gives the lowest and highest finite output,may_be()the infinities and NaN an implementation may produce, andcovers()judges an implementation's output. Results are kept, so repeating a call with the same arguments returns at once.workersis the number of threads the bounds are computed on (default: the physical cores, as PyTorch picks its own); it changes only the time. Each operation's bound is proven inproofs/.
- finite_range(compute: Format | str | None = None, *, ulps: int | Fraction | None = None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) tuple[Array, Array] | Outputs#
The lowest and highest finite output of a correct implementation, per element, as
(low, high)arrays of the output's dtype; the arguments aretolerance()'s.They lie within
tolerance()ofrounded, and can be closer on one side. Where the reference is an infinity only because a finite exact value rounds past the largest finite value, they hold the finite outputs that can still occur. Where no finite output can occur, both are NaN, solow <= output <= highis false.
- may_be(kind: str, compute: Format | str | None = None, *, ulps: int | Fraction | None = None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) Array | Outputs#
Where a correct implementation may output
kind("+inf","-inf"or"nan"), as a bool array; for complex outputs it has a last axis of 2 (real part, imaginary part). The other arguments aretolerance()'s. A reference that is not finite counts, and a format without infinity gives NaN past its largest value only withoverflow="nan"or a directed rounding away from zero (else its largest value). It can be true where no correct implementation overflows (an overflow check uses the error bound), never false where one can.
- covers(output, compute: Format | str | None = None, *, ulps: int | Fraction | None = None, flush_to_zero: bool = False, standard: str = 'normal', workers: int | None = None) Array | Outputs#
Where a correct implementation can produce
output, as a bool array: a finite value withinfinite_range(), or an infinity or NaN thatmay_be()allows.outputis an implementation's output (anythingasarraytakes) with this result's dtype and shape; for complex outputs the array has a last axis of 2 (real part, imaginary part).assert result.covers(output).all()checks an implementation. The other arguments aretolerance()'s; the standard, the compute format and flushing describe the implementations judged correct. A result with named outputs takes{name: output}(a dict, orOutputssuch as an implementation's outputs read back) for any of them and returnsOutputsof those, asAttentionAlgorithm.coversdoes.
- normal(compute: Format | str | None = None, *, flush_to_zero: bool = False, workers: int | None = None) Array | Outputs#
The output of normal accumulation in index order on these inputs.
Each product is rounded to
computeand added in index order, each sum rounded tocompute(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 asroundedis.computeandflush_to_zeroare as intolerance(); each operation says what else its normal answer fixes. It is computed only when called, and kept.
- reshape(shape) Result#
This result's one unnamed output with its elements in row-major order in a new
shape.Moving elements rounds nothing:
rounded,exact,tolerance()andnormal()are this result's, moved the same way, so the view can be passed to a later operation in place of an array. A view has no backward of its own: callbackwardon this result, with the gradient reshaped back.
Outputs#
Backwards, attention, var, std, and batch_norm when it updates
running statistics return outputs held by name, even a backward with one
gradient, such as sum's. r.rounded
and the other per-element methods return them as an Outputs, and r[name]
is a result for one of them. Here the layer's gradients, read by name, check
the ones PyTorch's autograd computes:
- class Outputs#
Named outputs of one operation, as a read-only mapping:
outputs.grad_Aoroutputs["grad_A"], anddict(outputs),outputs.items()andlen(outputs). The names are attention'soutputandlogsumexp, and a backward'sgrad_plus its input's name, such asgrad_Aorgrad_query.
# The gradient of the layer's output, from the next layer
grad = torch.randn(128, 1024, generator=g).bfloat16()
# PyTorch's autograd, on copies that record gradients
x_, w_ = x.clone().requires_grad_(), w.clone().requires_grad_()
torch.nn.functional.linear(x_, w_).backward(grad)
# matmul's backward on the same inputs
gb = r.backward(grad)
# Listing gb.rounded gives the names; one output, read by attribute
print("outputs:", list(gb.rounded))
print("grad_A shape:", gb.rounded.grad_A.shape)
# gb[name] is a result for one output. grad_B is the gradient of w.T, so the
# gradient of w is its transpose.
autograd = {"grad_A": x_.grad, "grad_B": w_.grad.T}
for name, tensor in autograd.items():
print(f"{name} covered:", gb[name].covers(tensor).all())
outputs: ['grad_A', 'grad_B']
grad_A shape: (128, 1024)
grad_A covered: True
grad_B covered: True
Boundary#
r.boundaries maps each required rounding step's name to a Boundary.
These are the steps where the tolerance allows for a rounding. A kernel that
rounds anywhere else, for example one that keeps its partial sums in
bfloat16 where the step's sums are in float32, can fall outside the
tolerance:
- class Boundary#
One of an operation's rounding boundaries, where every correct implementation turns an exact intermediate value into a finite-precision number: its
kind("round", one rounding of a computed value;"accumulate", a sum of terms;"function", a library function's result within some ulps;"backward", a matrix function's backward error;"butterfly", a Fourier transform's butterfly outputs within a stated accuracy per radix), adescriptionof the value, and for an accumulation what itapplies_to:"sum"or"dot".
# The rounding steps the tolerance allows for, in the layer's product
for name, step in r.boundaries.items():
# Its kind, what it applies to ("dot" for products, "sum" for plain terms),
# and what it rounds
print(f"{name}: {step.kind}, applies to {step.applies_to}: {step.description}")
accumulate: accumulate, applies to dot: summation of the k products of one output element
matmul has one step: the sum of each element's products, in the compute format. Algorithms describe kernels that round in further places, such as a bfloat16 accumulator.