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.

Array(bfloat16, shape=(2, 3), byteorder='little') 1.0 -2.0 0.5 3.0 -0.0 1.5 dtype: bfloat16, 2 bytes each shape: (2, 3), stored row by row byteorder: little, low byte first buffer: 12 bytes 80 3F 00 C0 00 3F 40 40 00 80 C0 3F (0, 0) (0, 1) (0, 2) (1, 0) (1, 1) (1, 2) element (1, 2): 1.5, encoding 0x3FC0, stored as C0 3F

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

er.asarray(obj, dtype=None, *, rounding=None, overflow=None)

round float32 data to TF32

er.round_to_tf32(x, rounding, *, overflow="ieee")

read values

a.tolist(), a.scalars(), a.scalar(index)

read exact values

a.value(index), a.values()

read raw bits

a.encoding(index), a.encodings(), a.buffer

read the layout

a.dtype, a.shape, a.size, a.ndim, a.nbytes, a.byteorder

change the layout

a.reshape(shape)

build an array

er.Array.zeros(dtype, shape), er.Array.from_values(dtype, shape, values), er.Array.from_encodings(dtype, shape, encodings)

edit values

a.mutable_copy(), then m.set_value(index, value) and m.freeze()

test a bool array

a.all(), a.any()

compare bit for bit

a.identical(b)

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) and MutableArray (frozen copy).

  • Python scalars and nested lists or tuples. Without dtype, bools become bool, ints int64, floats float64 and complex numbers complex128; a value the inferred format cannot hold exactly raises. Fraction, FloatValue and ComplexValue need an explicit dtype.

  • Objects with the buffer protocol whose element format is known: NumPy arrays, array.array, memoryview, and bytes (as uint8).

  • 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 dtype names a different format, values are converted with rounding and overflow. Following PyTorch, converting array data to an integer dtype wraps on overflow by default (like tensor.to), while Python values that do not fit raise (like torch.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 to bool reads every nonzero value, NaN included, as True, as PyTorch does. Converting a float that is not a whole number to an integer dtype needs rounding (ValueError without it). To reinterpret raw bytes instead, use Array(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.

x is float32 data in any form asarray accepts; Python values become float64 there, so pass them as er.round_to_tf32(er.asarray(values, "float32"), rounding). The result is a float32 Array whose 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.

rounding is required, since kernels differ: PTX's cvt.rna.tf32.f32 rounds to nearest with ties away from zero (NEAREST_AWAY), cvt.rn and cvt.rz (sm_90 and later) round to nearest even and toward zero, and wgmma truncates the low 13 bits of float32 inputs (TOWARD_ZERO). Past the largest TF32 value, (2 - 2**-10) * 2**127, overflow applies 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 bytes object 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.

reshape(shape) -> Array#

Return an array with the same storage and element count but a new shape.

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 all reads it). False for an empty array.

byte_offset(index=()) -> int#

Return the byte at which element index starts.

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 as rounding) are passed to dtype.encode.

identical(other: _ArrayBase) -> bool#

Whether other has the same dtype, shape and encodings (byte order ignored).

scalar(index=()) -> float | complex | int | bool#

Return one element as an ordinary Python float, complex, int or bool.

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, int or bool).

values() -> list[FloatValue | ComplexValue | int | bool]#

Return every exact value in row-major order.

classmethod zeros(dtype: Format | str, shape, *, byteorder: str = 'little') -> _A#

Return an array whose every byte is zero (+0, 0 or False).

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. Call freeze() to obtain an immutable Array.

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 as rounding) are passed to dtype.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.

freeze() -> Array#

Return an immutable copy. This array remains usable.

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:

Code
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])
Output
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 (significand is odd, or zero with exponent == 0), so equal values have equal fields. Unlike Fraction, a FloatValue keeps signed zeros, infinities and NaN.

Equality is structural, not IEEE comparison: a NaN equals another NaN of the same sign, and -0 differs 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:

Code
# 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())
Output
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 FloatValue parts.

classmethod from_complex(z: complex) -> ComplexValue#

Return the exact value of a Python complex, including signed zeros.