ExactArray and Enclosure#
A result's rounded, the exact answer rounded once to the output format, is
the best the output format can hold, but it is not the exact value. When you
need the exact value itself, for example to grade an implementation that is
more precise than the output format or to measure an error exactly, use
r.exact. For each element it holds an enclosure: an interval
guaranteed to contain the exact value, given as a midpoint and a radius.
Example#
A careful kernel may take float32 inputs but add in float64. Graded against
rounded, it would look up to half a float32 unit in the last place
(ulp) wrong, because rounded itself is that far from the exact
value. Graded against r.exact, its real error shows. Here the kernel is a
decoding step's product, one token's 4096 activations through 256 outputs:
import math
from fractions import Fraction
import torch
import exactref as er
# Seeded, so every run uses the same values
g = torch.Generator().manual_seed(67)
# One token's float32 activations, and a weight with 256 outputs
x = torch.randn(4096, generator=g)
w = torch.randn(4096, 256, generator=g) / 64
# ExactRef's result: 256 exact dot products
r = er.matmul(x, w)
# The kernel: each dot product added in float64, as Python floats
xs = x.tolist()
outputs = []
for column in w.T.tolist():
total = 0.0
for a, b in zip(xs, column):
total += a * b
outputs.append(total)
def error_in_ulps(output, exact):
"""How far output is from the exact value, in float32 ulps at that value."""
# frexp writes the value as m * 2**exponent, with 0.5 <= m < 1; float32
# keeps 24 significant bits, so one ulp there is 2**(exponent - 24)
exponent = math.frexp(float(exact))[1]
# Fraction(output) is the output's exact value, so nothing rounds here
return float(abs(Fraction(output) - exact) / Fraction(2) ** (exponent - 24))
# Every element's enclosure; a radius of 0 means the midpoint is exact
enclosures = r.exact.values()
print("every radius 0:", all(e.radius == 0 for e in enclosures))
exact = [e.midpoint.to_fraction() for e in enclosures]
# The largest error of the float64 kernel, and of rounded itself
kernel = max(error_in_ulps(o, e) for o, e in zip(outputs, exact))
best = max(error_in_ulps(o, e) for o, e in zip(r.rounded.scalars(), exact))
print(f"float64 kernel: {kernel:.2g} ulps")
print(f"rounded: {best:.2g} ulps")
every radius 0: True
float64 kernel: 3.5e-06 ulps
rounded: 0.5 ulps
The float64 kernel is more than 100,000 times closer to the exact value than a float32 output can be.
What an ExactArray holds#
r.exact is an ExactArray. For each element it holds an
enclosure of the exact answer: a midpoint and a radius, with the
exact value guaranteed to lie within the radius of the midpoint. A complex
element has a pair, one per part. The midpoint has a 128-bit significand.
The radius is at most one unit in the midpoint's last place, or 0 when the
midpoint is the exact value. The array stores enclosures packed, not as one
Python object each.
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.
One exception: when the operation could not tell an element's exact value apart from zero, though it still knows how that value rounds, the midpoint is 0 and the exact value lies within the radius of 0.
Stored magnitudes lie between 2**-(2**20) and 2**(2**20). A value beyond
that range is stored as an infinity (too big) or a zero (too small), with its
sign and with out_of_range set. That is still enough to round it correctly
to every supported format.
Reading complicated tolerances measures one error this way, and Compare the accuracy of two implementations compares two implementations by their exact errors.
Full specification#
- class ExactArray#
Certified exact values of one output: per element a midpoint and a radius, the true value within the radius of the midpoint, packed so that no Python object exists per element until one is read.
- value(index=()) Enclosure | tuple[Enclosure, Enclosure]#
The enclosure of one element; a
(real, imaginary)pair for complex outputs.
- values() list[Enclosure | tuple[Enclosure, Enclosure]]#
Every element's enclosure in row-major order.
- reshape(shape) ExactArray#
The same elements in row-major order with a new shape of the same size.
- take(positions: Sequence[int], shape) ExactArray#
The elements at row-major
positions, as an array ofshape; a negative position counts from the end, as intorch.take.
- paired(shape) ExactArray#
A real array's entries read in pairs (real part, imaginary part) as a complex array of
shape.
- class Enclosure(midpoint: FloatValue, radius: Fraction, out_of_range: bool = False)#
A certified value: the true value lies in
[midpoint - radius, midpoint + radius].radiusis 0 whenmidpointis the exact value, NaN or infinite. Without_of_range, the true value is finite and nonzero withmidpoint's sign, and its magnitude is at least2**LIMIT(midpointinfinite) or below2**-LIMIT(midpointzero).