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

r.rounded

the exact answer, rounded once to the output format

r.exact

enclosures guaranteed to contain the exact answer

r.guarantee

"correctly_rounded", or "exact" for integer outputs

r.tolerance()

per element, how far a correct implementation's finite output can be from rounded

r.finite_range()

the lowest and highest finite output a correct implementation can produce

r.may_be(kind)

where a correct implementation may output "+inf", "-inf", or "nan"

r.covers(output)

per element, whether a correct implementation can produce output

r.normal()

the normal answer: what an ordinary implementation that adds in index order computes, emulated exactly

r.backward(grad)

the operation's backward on the same inputs

r[name]

a result for one named output, such as attention's logsumexp or a backward's grad_A

r.reshape(shape), r.transpose(i, j)

the same result in another layout

r.boundaries

the operation's required rounding steps

r.op

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:

rounded tolerance() any order any order

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:

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 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())
Output
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 from rounded on these inputs, a proven bound; tolerance(standard="any_order") covers every accumulation order that does not overflow.

  • finite_range(), may_be() and covers(): 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 output and logsumexp, and a backward's grad_ plus its input's name, for example result.rounded.grad_A. result[name] is a result holding just that output. A one-output result's output is named by its operation: matmul's C, gemm's D, multiply's and add's output, sum's s, matrix_exp's E and matrix_exp_frechet's L, and the Fourier transforms' X (fft, rfft, ihfft, hfft) or x (ifft, irfft). guarantee states what rounded satisfies, and boundaries lists 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 float32 A or B (its stored values need not be tf32 values) and as a held-scalar algorithm's scalar of shape () (the chain multiply(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 of rounded (part by part for complex values), or an infinity or NaN that may_be() allows. The later result's rounded and exact are the exact answer on rounded, 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); its normal() works on this normal(); and an algorithm's run() uses rounded.

guarantee#

What rounded satisfies: "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 compute at each required rounding boundary,

  • accumulation in compute: with standard="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; with standard="any_order", any order (any summation tree, with or without fused multiply-add) that does not overflow,

  • library functions within ulps units in the last place of compute, for matrix functions a backward error measured in ulps, and for Fourier transforms twiddle factors within ulps units of compute'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".

compute defaults 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). With flush_to_zero, the implementation flushes values to zero as torch.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 under compute="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; inf marks elements with no finite bound, and nan elements whose reference is not finite. finite_range() gives the lowest and highest finite output, may_be() the infinities and NaN an implementation may produce, and covers() judges an implementation's output. Results are kept, so repeating a call with the same arguments returns at once. workers is 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 in proofs/.

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 are tolerance()'s.

They lie within tolerance() of rounded, 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, so low <= output <= high is 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 are tolerance()'s. A reference that is not finite counts, and a format without infinity gives NaN past its largest value only with overflow="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 within finite_range(), or an infinity or NaN that may_be() allows.

output is an implementation's output (anything asarray takes) 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 are tolerance()'s; the standard, the compute format and flushing describe the implementations judged correct. A result with named outputs takes {name: output} (a dict, or Outputs such as an implementation's outputs read back) for any of them and returns Outputs of those, as AttentionAlgorithm.covers does.

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 compute and added in index order, each sum rounded to compute (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. compute and flush_to_zero are as in tolerance(); 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() and normal() 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: call backward on this result, with the gradient reshaped back.

transpose(i: int, j: int) -> Result#

This result's one unnamed output with dimensions i and j swapped, as reshape describes for views; a 0-d result's transpose is the result itself, its backward included, as PyTorch transposes a 0-d tensor's dimension 0 with itself.

backward(grad, **options) -> Result#

The operation's backward for these inputs and the output gradient grad.

The same as calling the operation's standalone .backward with this result's inputs; options are its keyword options (such as dtype and rounding), with the same defaults.

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_A or outputs["grad_A"], and dict(outputs), outputs.items() and len(outputs). The names are attention's output and logsumexp, and a backward's grad_ plus its input's name, such as grad_A or grad_query.

Code
# 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())
Output
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), a description of the value, and for an accumulation what it applies_to: "sum" or "dot".

Code
# 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}")
Output
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.