Data in and out#

Operations accept Python lists, NumPy arrays, and PyTorch tensors directly, so you rarely handle ExactRef's own arrays. This page is for when you need control over how data gets in and comes out: converting the way a kernel converts, reading an element's exact value or bits, or planting a special value in an input. ExactRef keeps data in its own arrays so that every value is exact and no input can change during a calculation.

Arrays#

An er.Array is one flat byte buffer plus a dtype, a shape, and a byte order. It is immutable. Every operation turns its inputs into arrays, and rounded, tolerance(), and the other parts of its result are arrays too.

Code
import torch
import exactref as er

# Seeded, so every run uses the same values
g = torch.Generator().manual_seed(67)
# A layer's activations: 128 tokens of hidden size 4096, in bfloat16
acts = torch.randn(128, 4096, generator=g).bfloat16()

# Imported exactly, in the tensor's own format
x = er.asarray(acts)
# Its repr names the dtype, the shape, and the byte order
print("array:", repr(x))

# The shape, the number of elements, the number of dimensions, and the bytes held
print("shape:", x.shape)
print("size:", x.size)
print("ndim:", x.ndim)
print("nbytes:", x.nbytes)
# The dtype is a format object; name is its name as a string
print("dtype:", x.dtype.name)
Output
array: Array(bfloat16, shape=(128, 4096), byteorder='little')
shape: (128, 4096)
size: 524288
ndim: 2
nbytes: 1048576
dtype: bfloat16

Importing with asarray#

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

  • Python values and nested lists or tuples. Without a dtype, bools become bool, ints int64, floats float64, and complex numbers complex128. A value that format cannot hold exactly raises. Fraction values, and ExactRef's exact values FloatValue and ComplexValue (described under Reading arrays below), 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, and NumPy, bfloat16 and float8 included. A PyTorch tensor's lazy conjugate and negative views are applied first, and a tensor that requires grad is detached. A GPU tensor must be copied to the CPU first.

  • An Array, returned as it is, or a MutableArray (an editable array, described under Building arrays below), as a frozen copy.

Data that carries its own format is imported exactly. Give a dtype to convert: each value is rounded once, with rounding (default: to nearest, ties to even) and overflow saying how. Converting a value that is not a whole number to an integer format needs an explicit rounding, as a quantization step chooses its own; without one it raises ValueError. A kernel that converts its float32 inputs to bfloat16 by truncating them is checked on inputs converted the same way, with rounding=er.Rounding.TOWARD_ZERO, as Get started shows on a layer's activations. On a single value:

Code
# 0.1 rounded to the nearest float32 value, the default
nearest = er.asarray([0.1], "float32")
print("nearest:", nearest.tolist())

# 0.1 rounded toward zero, to the float32 value just below it
toward_zero = er.asarray([0.1], "float32", rounding=er.Rounding.TOWARD_ZERO)
print("toward zero:", toward_zero.tolist())
Output
nearest: [0.10000000149011612]
toward zero: [0.09999999403953552]
to nearest, toward +inf toward zero, toward -inf 0.1 0.09999999403953552 0.10000000149011612 the two float32 values around 0.1

Each rounding mode picks one of the two float32 values around the exact 0.1.

The five roundings are er.Rounding.NEAREST_EVEN, NEAREST_AWAY, TOWARD_ZERO, TOWARD_POSITIVE, and TOWARD_NEGATIVE.

asarray converts your own data. To check a conversion another implementation made, such as a kernel's cast of float32 activations to bfloat16, use convert_float_format, an operation whose covers() judges the converted tensor.

Overflow#

Low-precision kernels convert their inputs and outputs, and the conversion decides what happens past a format's range. In a format with infinity, a value that rounds past the largest finite value becomes infinity, as IEEE 754 says, unless the rounding points toward zero. overflow="saturate" gives the largest finite value instead, as a kernel that clamps does:

Code
# 1e6 is past float16's largest finite value, so it becomes infinity
print("default:", er.asarray([1e6], "float16").tolist())
# Clamped to the largest finite float16 value
print("saturate:", er.asarray([1e6], "float16", overflow="saturate").tolist())
Output
default: [inf]
saturate: [65504.0]

Formats without infinity (float8_e4m3fn and the fnuz formats) round within the values they have: to the largest value, or to NaN when a directed rounding points away from zero. An FP8 matmul casts its inputs to one of these formats first, so its check needs the same cast. overflow="nan" gives NaN wherever IEEE 754 would give infinity, as some kernels do in these formats:

Code
# float8_e4m3fn has no infinity: rounding to nearest gives its largest value
print("default:", er.asarray([1000.0], "float8_e4m3fn").tolist())
# NaN where IEEE 754 would give infinity
print("nan:", er.asarray([1000.0], "float8_e4m3fn", overflow="nan").tolist())
Output
default: [448.0]
nan: [nan]

Integers follow PyTorch: converting array data wraps on overflow by default, like tensor.to, and Python values that do not fit raise, like torch.tensor. overflow="saturate" clamps, as an int8 quantization step does, and overflow="error" raises.

Code
import numpy as np

# An int16 NumPy array holding 300, past int8's largest value, 127
data = np.array([300], dtype=np.int16)
# Array data wraps around modulo 256: 300 - 256 = 44
print("wrap:", er.asarray(data, "int8").tolist())
# Clamped to int8's largest value
print("saturate:", er.asarray(data, "int8", overflow="saturate").tolist())

# A Python int that does not fit raises
try:
    er.asarray([300], "int8")
except OverflowError as error:
    print(f"{type(error).__name__}: {error}")
Output
wrap: [44]
saturate: [127]
OverflowError: 300 is outside the int8 range [-128, 127]

Converting to bool reads every nonzero value, NaN included, as True, as PyTorch does when a float mask becomes a bool mask:

Code
# Zero becomes False; NaN and 2.0 become True
print("bool:", er.asarray([0.0, float("nan"), 2.0], "bool").tolist())
Output
bool: [False, True, True]

Rounding to TF32#

er.round_to_tf32(x, rounding, *, overflow="ieee") rounds float32 data to TF32 values, as GPU tensor cores in TF32 mode do, and returns float32 values. Python values go in through er.asarray(values, "float32") first. Check low-precision kernels shows which rounding matches which kernel.

Reading arrays#

When a check fails, you read the elements behind it. Here is the reference for a bfloat16 layer, x times a 1024 by 4096 weight: r.rounded, the exact product rounded once to bfloat16.

Code
# The layer's weight, scaled as in a trained model
w = (torch.randn(1024, 4096, generator=g) / 64).bfloat16()
r = er.matmul(x, w.T)

# One element, at row 5, column 7, as a Python float
print("scalar:", r.rounded.scalar((5, 7)))
# Nested lists of Python values: row 5's first four elements
print("row 5:", r.rounded.tolist()[5][:4])
# The same elements in a new shape: 8 heads of 128 columns per token
print("reshaped:", r.rounded.reshape((128, 8, 128)).shape)
Output
scalar: 1.3203125
row 5: [1.1171875, 1.484375, 0.04541015625, 1.4609375]
reshaped: (128, 8, 128)

scalars() gives every element in one flat list, row by row.

A Python float keeps every finite value, the sign of zero, and infinities, but not which NaN encoding an element holds. To see an element's exact value or its bits, read the value or the encoding. To compare it with the exact product, read r.exact:

Code
# Element (5, 7)'s exact value, as a FloatValue: significand * 2**exponent
v = r.rounded.value((5, 7))
print("value:", repr(v))
# The same value as a Fraction
print("fraction:", v.to_fraction())
# Its raw bits as an unsigned int
print("encoding:", hex(r.rounded.encoding((5, 7))))

# r.exact holds an interval guaranteed to contain each exact value, a midpoint
# and a radius; here the radius is 0, so the midpoint is the exact product
exact = r.exact.value((5, 7)).midpoint.to_fraction()
# How far the reference is from the exact product: the error of rounding once
print("rounding error:", v.to_fraction() - exact)
Output
value: FloatValue(kind='finite', negative=False, significand=169, exponent=-7)
fraction: 169/128
encoding: 0x3fa9
rounding error: 217694639/137438953472

encodings() gives every element's raw bits and values() every element's exact value, row-major. A FloatValue is the exact value of one encoding: (-1)**negative * significand * 2**exponent when finite, with signed zeros, infinities, and NaN kept. to_fraction() gives it as a Fraction. A complex element's value is a ComplexValue, a pair of FloatValue parts.

A kernel outside PyTorch may hand back raw bits. er.Array.from_encodings reads them, here a bfloat16 buffer holding the values a check has to tell apart:

Code
# Raw bfloat16 bits: +0, -0, +inf, a NaN, and 1.0
out = er.Array.from_encodings("bfloat16", (5,), [0x0000, 0x8000, 0x7F80, 0x7FC0, 0x3F80])
print("values:", out.tolist())
# -0.0 keeps its sign in its exact value
print("-0.0:", repr(out.value((1,))))
Output
values: [0.0, -0.0, inf, nan, 1.0]
-0.0: FloatValue(kind='finite', negative=True, significand=0, exponent=0)

Bool arrays, such as the ones covers() returns (per element, whether a correct implementation can produce the output), have all() and any(). As in PyTorch, only an array of one element has a truth value, so write assert r.covers(out).all(): if r.covers(out): raises a ValueError. a.identical(b) is True when two arrays have the same dtype, shape, and encodings, whatever their byte order.

Building arrays#

er.Array.zeros(dtype, shape), er.Array.from_values(dtype, shape, values), and er.Array.from_encodings(dtype, shape, encodings) build an array directly. To edit one, take a MutableArray and freeze it when done. To test how a kernel handles a NaN in its input, plant one and see which outputs it may reach:

Code
# A mutable copy of the activations, with a NaN planted at token 3
m = x.mutable_copy()
m.set_value((3, 100), float("nan"))
# freeze() returns an immutable copy
planted = m.freeze()

# Per output element, whether a correct implementation may make it NaN
nan = er.matmul(planted, w.T).may_be("nan")
# The rows of the layer's output where any element may be NaN
print("rows that may be NaN:", [i for i, row in enumerate(nan.tolist()) if any(row)])
Output
rows that may be NaN: [3]

set_value rounds the value to the array's format (it takes rounding and overflow), and set_encoding stores raw bits. set_values, set_encodings, and set_bytes replace everything at once. To reinterpret raw bytes as an array, use er.Array(dtype, shape, buffer).

Formats#

er.FORMATS maps each format's name to its format object, and er.get_format(name) looks one up:

Code
import textwrap

# Every format name, sorted and wrapped at 72 characters
print("formats:")
print(textwrap.fill(" ".join(sorted(er.FORMATS)), 72))

# The bfloat16 format object
f = er.get_format("bfloat16")
# Significand bits, counting the leading bit that is not stored
print("precision:", f.precision)
# The smallest normal value is 2**emin
print("emin:", f.emin)
# The largest finite value lies between 2**emax and 2**(emax + 1)
print("emax:", f.emax)
Output
formats:
bfloat16 bool complex128 complex32 complex64 float16 float32 float64
float8_e3m4 float8_e4m3 float8_e4m3b11fnuz float8_e4m3fn float8_e4m3fnuz
float8_e5m2 float8_e5m2fnuz int16 int32 int64 int8 uint16 uint32 uint64
uint8
precision: 8
emin: -126
emax: 127

Formats are also available by name, such as er.bfloat16, er.float8_e4m3fn, and er.bool_ (bool is Python's own name), and every dtype argument takes either a format or its name. Formats and rounding lists each format's range and special values.