Arrays and values#
Operations accept Python lists, NumPy arrays, and PyTorch tensors directly, so you rarely build ExactRef arrays by hand. This page is the reference for when you do: importing data, reading exact values or raw bits, and editing values.
ExactRef stores data as raw bits with a format, so every value it reads or returns is exact: bfloat16 and float8 values keep their encodings, and -0, infinities, and NaN keep their identity. Its arrays are immutable, so an input cannot change during a calculation.
ExactRef holds data in Array (immutable) and MutableArray (editable): one
flat byte buffer plus a dtype, a shape, and a byte order. asarray imports
data into them. A FloatValue or ComplexValue is the exact value of one
element. Data in and out walks through them with
examples.
A bfloat16 array of shape (2, 3): six elements of 2 bytes each, stored row by row in one buffer of 12 bytes. Element (1, 2) holds 1.5, whose encoding 0x3FC0 is stored low byte first.
At a glance#
To |
Use |
|---|---|
import data |
|
round float32 data to TF32 |
|
read values |
|
read exact values |
|
read raw bits |
|
read the layout |
|
change the layout |
|
build an array |
|
edit values |
|
test a bool array |
|
compare bit for bit |
|
asarray#
- asarray(obj, dtype: Format | str | None = None, *, rounding: Rounding | None = None, overflow: str | None = None) Array#
Import data as an immutable
Array.Accepted sources:
Array(returned as is) andMutableArray(frozen copy).Python scalars and nested lists or tuples. Without
dtype, bools becomebool, intsint64, floatsfloat64and complex numberscomplex128; a value the inferred format cannot hold exactly raises.Fraction,FloatValueandComplexValueneed an explicitdtype.Objects with the buffer protocol whose element format is known: NumPy arrays,
array.array,memoryview, andbytes(asuint8).CPU tensors with
__dlpack__(PyTorch, JAX, NumPy), including bfloat16 and float8. A PyTorch tensor's lazy conjugate and negative views are applied first, and one that requires grad is detached.
Data that carries its own format is imported exactly. When
dtypenames a different format, values are converted withroundingandoverflow. Following PyTorch, converting array data to an integer dtype wraps on overflow by default (liketensor.to), while Python values that do not fit raise (liketorch.tensor); other defaults are each format's own: in a format without infinity, a value past the largest rounds within the format's values (FloatFormat.encode). Converting toboolreads every nonzero value, NaN included, as True, as PyTorch does. Converting a float that is not a whole number to an integer dtype needsrounding(ValueError without it). To reinterpret raw bytes instead, useArray(dtype, shape, buffer).
round_to_tf32#
- round_to_tf32(x, rounding: Rounding, *, overflow: str = 'ieee') Array#
Round float32 data to TF32 values, as NVIDIA's tensor cores read float32 inputs.
xis float32 data in any formasarrayaccepts; Python values become float64 there, so pass them aser.round_to_tf32(er.asarray(values, "float32"), rounding). The result is a float32Arraywhose every value is a TF32 value: 11 significant bits in float32's exponent range, with subnormals on the grid of 2**-136 (NVIDIA leaves the handling of subnormal inputs in its mma instructions unspecified). NaN stays NaN, and infinities and signed zeros stay.roundingis required, since kernels differ: PTX'scvt.rna.tf32.f32rounds to nearest with ties away from zero (NEAREST_AWAY),cvt.rnandcvt.rz(sm_90 and later) round to nearest even and toward zero, andwgmmatruncates the low 13 bits of float32 inputs (TOWARD_ZERO). Past the largest TF32 value, (2 - 2**-10) * 2**127,overflowapplies as for a format: "ieee" gives infinity where the rounding is to nearest or outward and the largest value otherwise, "saturate" always gives the largest value (as PTX's.satfinite), and "nan" acts as "ieee", since TF32 has infinities.
Check low-precision kernels says which
rounding matches which kernel.
Array#
- class Array(dtype: Format | str, shape, buffer, *, byteorder: str = 'little')#
An immutable array, suitable as a reference input.
Its storage is a
bytesobject that no caller can modify, so values cannot change during a calculation.- dtype#
The element format, a
Format.
- shape#
The shape, a tuple of ints.
- ndim#
The number of dimensions.
- nbytes#
The size of the buffer in bytes.
- byteorder#
"little"or"big".
- property buffer: bytes#
The underlying bytes, for bulk routines.
- mutable_copy() MutableArray#
Return a mutable array with independent storage.
- all() bool#
Whether every element is true: nonzero, as in PyTorch (NaN is true, a zero of either sign false). True for an empty array.
- any() bool#
Whether some element is true (nonzero, as
allreads it). False for an empty array.
- byte_offset(index=()) int#
Return the byte at which element
indexstarts.
- encoding(index=()) int | tuple[int, int]#
Return the raw encoding of one element: an unsigned int, or a pair for complex.
- encodings() list[int] | list[tuple[int, int]]#
Return every raw encoding in row-major order.
- classmethod from_encodings(dtype: Format | str, shape, encodings, *, byteorder: str = 'little') _A#
Build an array from raw encodings in row-major order.
- classmethod from_values(dtype: Format | str, shape, values, *, byteorder: str = 'little', **options) _A#
Build an array by encoding values in row-major order.
options(such asrounding) are passed todtype.encode.
- identical(other: _ArrayBase) bool#
Whether
otherhas the same dtype, shape and encodings (byte order ignored).
- scalar(index=()) float | complex | int | bool#
Return one element as an ordinary Python
float,complex,intorbool.
- scalars() list[float | complex | int | bool]#
Return every element as a Python scalar in row-major order.
- property size: int#
The number of elements.
- tolist() list | float | complex | int | bool#
Return the elements as nested lists of Python scalars (a bare scalar for shape
()).
- value(index=()) FloatValue | ComplexValue | int | bool#
Return the exact value of one element (a
FloatValue,ComplexValue,intorbool).
- values() list[FloatValue | ComplexValue | int | bool]#
Return every exact value in row-major order.
MutableArray#
- class MutableArray(dtype: Format | str, shape, buffer, *, byteorder: str = 'little')#
An array whose elements can be set, for data being built or edited.
Writes go through the codec (
set_value) or checked bulk methods. Callfreeze()to obtain an immutableArray.- property buffer: memoryview#
A read-only view of the current bytes, for bulk routines.
- set_encoding(index, bits) None#
Store a raw encoding (an int, or a pair for complex) at one element.
- set_value(index, value, **options) None#
Encode a value and store it at one element.
options(such asrounding) are passed todtype.encode.
- set_encodings(encodings) None#
Replace every element with raw encodings in row-major order.
- set_values(values, **options) None#
Replace every element by encoding values in row-major order.
- set_bytes(data) None#
Replace the whole buffer with bytes of exactly the same length.
- copy() MutableArray#
Return a mutable array with independent storage.
MutableArray also has every reading method of Array.
FloatValue#
A FloatValue is the exact value of one floating-point element, which
a.value(index) returns. An operation's result r holds the reference
r.rounded, the exact answer rounded once to the output format, and its
tolerance, per element how far a correct implementation's output can be from
the reference. r.covers(output) says per element whether a correct
implementation can produce output. When a kernel's output fails that check,
the values of a failing element and of the reference give its exact error.
Here the kernel
under test has the classic accumulator bug: it keeps its running sum in
bfloat16. It is written in PyTorch so the example runs anywhere, and it
computes one token of hidden size 4096 through a 4096 by 1024 weight:
import torch
import exactref as er
# Seeded, so every run uses the same values
g = torch.Generator().manual_seed(67)
# One token's activations and the layer's weight, in bfloat16
x = torch.randn(1, 4096, generator=g).bfloat16()
w = (torch.randn(4096, 1024, generator=g) / 64).bfloat16()
# The kernel: each product rounded to bfloat16, then added to a bfloat16 running sum
out = x[:, :1] * w[:1]
for k in range(1, 4096):
out = out + x[:, k:k + 1] * w[k:k + 1]
# The reference, and the kernel's output as an ExactRef array
r = er.matmul(x, w)
kernel = er.asarray(out)
# How many elements no correct implementation could produce
covered = r.covers(kernel)
print("outside the tolerance:", covered.scalars().count(False), "of", covered.size)
# Each element's error, kernel minus reference, as an exact fraction
errors = [got.to_fraction() - ref.to_fraction() for got, ref in zip(kernel.values(), r.rounded.values())]
# The element with the largest error
column = max(range(len(errors)), key=lambda i: abs(errors[i]))
print("element:", (0, column))
# Its two exact values, and the error between them
print("kernel:", repr(kernel.value((0, column))))
print("reference:", repr(r.rounded.value((0, column))))
print("error:", errors[column])
outside the tolerance: 996 of 1024
element: (0, 141)
kernel: FloatValue(kind='finite', negative=False, significand=171, exponent=-8)
reference: FloatValue(kind='finite', negative=False, significand=17, exponent=-4)
error: -101/256
Each FloatValue reads as (-1)**negative * significand * 2**exponent: the
kernel stored 171/256, where the reference is 17/16: the running sum in
bfloat16 lost 101/256, about 0.39, at this element, where bfloat16 values are
1/128 apart.
- class FloatValue(kind: str, negative: bool, significand: int = 0, exponent: int = 0)#
The exact value of one binary floating-point encoding.
A finite value equals
(-1)**negative * significand * 2**exponent. The pair is normalized (significandis odd, or zero withexponent == 0), so equal values have equal fields. UnlikeFraction, aFloatValuekeeps signed zeros, infinities and NaN.Equality is structural, not IEEE comparison: a NaN equals another NaN of the same sign, and
-0differs from+0. NaN payloads are not represented; read raw encodings when a payload must be preserved.- classmethod from_float(x: float) FloatValue#
Return the exact value of a Python float, including its sign: its bytes decoded as float64, with no float arithmetic, so a thread that flushes subnormals to zero gets the value it passed.
- to_fraction() Fraction#
Return the exact rational value. The sign of zero is not preserved.
ComplexValue#
A ComplexValue is the exact value of one complex element: a FloatValue
for each part. Here PyTorch computes a complex64 product, as a filter bank
does: 128 signals of 1024 samples times a 1024 by 128 complex matrix. The
check reads one element part by part:
# The signals and the matrix, in complex64
s = torch.randn(128, 1024, dtype=torch.complex64, generator=g)
h = torch.randn(1024, 128, dtype=torch.complex64, generator=g) / 32
# PyTorch's product, and ExactRef's reference for it
out = s @ h
r = er.matmul(s, h)
# Element (0, 0) of the reference and of PyTorch's output, each a ComplexValue
ref, got = r.rounded.value((0, 0)), er.asarray(out).value((0, 0))
# The reference's two parts, as Python floats
print("reference:", float(ref.real.to_fraction()), float(ref.imag.to_fraction()))
# The tolerance of a complex element has one bound per part
bound = r.tolerance().value((0, 0))
# Each part's exact error, against that part's bound
real_error = got.real.to_fraction() - ref.real.to_fraction()
imag_error = got.imag.to_fraction() - ref.imag.to_fraction()
print("real part within its bound:", abs(real_error) <= bound.real.to_fraction())
print("imaginary part within its bound:", abs(imag_error) <= bound.imag.to_fraction())
reference: -0.18821458518505096 0.28254491090774536
real part within its bound: True
imaginary part within its bound: True
r.covers(out) checks every element at once, against r.finite_range(),
which lies within the tolerance.
- class ComplexValue(real: FloatValue, imag: FloatValue)#
The exact value of one complex encoding: a pair of
FloatValueparts.- classmethod from_complex(z: complex) ComplexValue#
Return the exact value of a Python complex, including signed zeros.