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.
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.
# 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)
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.
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.
# 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()))
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:
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))
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 |
|---|---|---|
|
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 |
|
how far each library function, such as |
each operation's own, below |
|
the implementation flushes values below a format's smallest normal number to zero, as |
|
|
|
|
|
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 |
# 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])
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 |
|---|---|
|
1: either float next to the exact value |
|
1.0001: also the float one full step from an exact value that lies just beside a float |
|
1/2: the square root correctly rounded |
|
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"), andr.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.outputmust 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.
# Row 0's first three elements, as a loop that adds in index order returns them
print("normal:", r.normal().tolist()[0][:3])
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, whosenormal()raisesNotImplementedError;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 nonormal().
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
outputandlogsumexp;varreturnsvarandmean, andstdreturnsstdandmean;batch_normin training, given running statistics, returnsoutput,running_mean, andrunning_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 asgrad_Afor matmul'sA.
r[name] is a result for just that output, which is what covers() and
later operations need:
# 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)
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:
# 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)
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:
# 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)
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.