Formats and rounding#

A format is a way of storing numbers in a fixed number of bits. Formats come in four kinds: floating point, complex, integer, and bool. A floating-point format splits its bits between an exponent, which sets the range, and a significand, which sets the precision: bfloat16 has float32's range with far less precision, and the float8 formats trade both for size. Integer formats store whole numbers in a fixed range. Rounding modes say which nearby value an exact result becomes, and overflow modes what happens past the largest value.

Every dtype argument takes a format or its name. er.FORMATS maps names to format objects, and each format is also available by name, such as er.bfloat16; bool is er.bool_, because bool is Python's own name. An unknown name raises UnsupportedFormatError.

Floating-point formats#

A floating-point format stores a sign bit, then the exponent, then the fraction: the significand without its leading bit.

sign exponent fraction float32 8 23 32 bits TF32 8 10 zero in float32 bfloat16 8 7 16 bits float16 5 10 16 bits float8_e5m2 5 2 8 bits float8_e4m3fn 4 3 8 bits

The formats ML kernels use most, sign bit first. bfloat16 and TF32 keep float32's 8 exponent bits, so they keep its range; float16 and the float8 formats have fewer, so a smaller range. TF32 values are float32 values whose low 13 bits are zero, which er.round_to_tf32 makes. The other float8 formats have the layout their names give: e3m4 has 3 exponent bits and 4 fraction bits.

Name

Bits

Exponent bits

Precision (bits)

Infinity

-0

float64

64

11

53

yes

yes

float32

32

8

24

yes

yes

float16

16

5

11

yes

yes

bfloat16

16

8

8

yes

yes

float8_e5m2

8

5

3

yes

yes

float8_e4m3

8

4

4

yes

yes

float8_e3m4

8

3

5

yes

yes

float8_e4m3fn

8

4

4

no

yes

float8_e5m2fnuz

8

5

3

no

no

float8_e4m3fnuz

8

4

4

no

no

float8_e4m3b11fnuz

8

4

4

no

no

Name

Largest finite

Smallest normal

Smallest subnormal

float64

1.797693e+308

2.225074e-308

4.940656e-324

float32

3.402823e+38

1.175494e-38

1.401298e-45

float16

65504

6.103516e-05

5.960464e-08

bfloat16

3.389531e+38

1.175494e-38

9.18355e-41

float8_e5m2

57344

6.103516e-05

1.525879e-05

float8_e4m3

240

0.015625

0.001953125

float8_e3m4

15.5

0.25

0.015625

float8_e4m3fn

448

0.015625

0.001953125

float8_e5m2fnuz

57344

3.051758e-05

7.629395e-06

float8_e4m3fnuz

240

0.0078125

0.0009765625

float8_e4m3b11fnuz

30

0.0009765625

0.0001220703

The ranges are rounded to 7 significant digits.

Every floating-point format has NaN. Precision counts the implicit leading bit. The fn formats have no infinity, and the fnuz formats have no infinity and no negative zero.

Complex, integer, and bool formats#

Name

Parts

Name

Range

complex32

two float16

int8, int16, int32, int64

signed, 8 to 64 bits

complex64

two float32

uint8, uint16, uint32, uint64

unsigned, 8 to 64 bits

complex128

two float64

bool

False, True

Checking a quantized kernel needs its integer format's range. An int8 quantization step divides activations by a scale, rounds them to whole numbers, and clamps them to int8's range. Its check converts the same way:

Code
import torch
import exactref as er

# int8's range
print("int8 range:", er.int8.min_value, "to", er.int8.max_value)

# Activations already divided by the quantization scale, two of them past int8's range
scaled = torch.tensor([3.7, -150.2, 127.5, 126.5])
# The kernel: round to nearest (ties to even), then clamp
kernel = torch.clamp(torch.round(scaled), -128, 127).to(torch.int8)

# The same conversion in ExactRef: a value that is not whole needs a rounding,
# and overflow="saturate" clamps
q = er.asarray(scaled, "int8", rounding=er.Rounding.NEAREST_EVEN, overflow="saturate")
print("quantized:", q.tolist())
print("matches the kernel:", q.identical(er.asarray(kernel)))
Output
int8 range: -128 to 127
quantized: [4, -128, 127, 126]
matches the kernel: True

127.5 is a tie, so it rounds to the even 128, which clamps to 127.

Rounding#

class Rounding(*values)#

IEEE 754 rounding-direction attributes.

NEAREST_EVEN = 'nearest_even'#
NEAREST_AWAY = 'nearest_away'#
TOWARD_ZERO = 'toward_zero'#
TOWARD_POSITIVE = 'toward_positive'#
TOWARD_NEGATIVE = 'toward_negative'#
property is_nearest: bool#

Whether this mode rounds to nearest (ties to even or away).

NEAREST_EVEN (the default, except that round_to_tf32 and conversions to an integer format have none) rounds to nearest with ties to even, NEAREST_AWAY to nearest with ties away from zero, and the other three in their direction.

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.

Overflow#

overflow says what happens to a value past the format's range:

Format

overflow

Past the largest value

floating-point with infinity

"ieee" (default)

infinity, or the largest finite value when the rounding direction points toward zero

floating-point without infinity

"ieee" (default)

the largest value; NaN when a directed rounding points away from zero

floating-point without infinity

"nan"

NaN wherever IEEE 754 would give infinity

any floating-point

"saturate"

the largest finite value, also for infinities the format cannot hold

integer

"wrap" (default)

wraps around, as PyTorch does

integer

"error"

raises OverflowError

integer

"saturate"

clamps to the format's range

In a format with infinity, "nan" gives the same results as "ieee". Integer results of operations, and conversions of array data, wrap by default, as in PyTorch; converting Python values that do not fit raises.

Looking formats up#

get_format(dtype: Format | str) -> Format#

Return a format instance, looking up names in FORMATS.

exactref.FORMATS#

A dict from each format's name to its format object.

Format classes#

class Format#

How one element's encoding maps to a value.

Subclasses provide name, itemsize (bytes per element), kind ("float", "int", "bool" or "complex") and components (encodings per element: 1, or 2 for complex).

class FloatFormat(name: str, exponent_bits: int, mantissa_bits: int, special: str = 'ieee', bias: int | None = None, nan_encodings: tuple[int, int] | None = None)#

A signed binary floating-point format.

special selects how non-finite values are encoded:

  • "ieee": an all-ones exponent encodes infinity (zero mantissa) or NaN.

  • "fn": finite only; all-ones exponent and mantissa encode NaN (as in float8_e4m3fn).

  • "fnuz": finite only, no negative zero; the negative-zero encoding is the only NaN (as in float8_e4m3fnuz).

bias defaults to 2**(e-1) - 1, or 2**(e-1) for "fnuz". nan_encodings gives the encodings of positive and negative NaN when they differ from the quiet NaN with the value's sign. Elements take a whole number of bytes, at most 8.

property precision: int#

Significand bits, including the implicit leading bit.

property emin: int#

Exponent of the smallest normal value (2**emin).

property emax: int#

Exponent of the largest finite binade (2**emax <= max_finite).

decode(bits: int) -> FloatValue#

Return the exact value of an encoding.

encode(value: FloatValue | Fraction | int | float, *, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str = 'ieee') -> int#

Round a value to this format and return its encoding.

overflow="ieee" (the default) follows IEEE 754 in a format with infinity: a result rounding past the largest finite value becomes infinity, or the largest finite value when the rounding direction points toward zero. A format without infinity has no value past its largest, so the result rounds within the values it has: the largest finite value, or NaN when a directed rounding points away from zero, where the format has no value. In a format without infinity, overflow="nan" instead gives NaN wherever IEEE 754 would give infinity (to nearest too), as kernels that keep the IEEE rule in such a format do; in a format with infinity it changes nothing. overflow="saturate" replaces every infinity this format cannot hold, or that overflow would produce, with the largest finite value. An infinite value gives NaN in a format without infinity, except with "saturate".

NaN encodes as this format's canonical NaN: the quiet NaN with the value's sign, or the encoding nan_encodings gives (PyTorch's bfloat16 NaN is always 0x7FC0; its float8_e5m2 NaN has every mantissa bit set).

class IntFormat(name: str, itemsize: int, signed: bool)#

A two's-complement (signed) or unsigned integer format of itemsize bytes, 1 to 8.

class BoolFormat(name: str = 'bool', itemsize: int = 1)#

One byte holding 0 (False) or 1 (True). Other byte values are invalid.

class ComplexFormat(name: str, component: FloatFormat)#

A complex format: real then imaginary part, each in component format.

Helper methods#

Format objects also have helper methods that ExactRef uses internally. You can use them, but their names and signatures are not guaranteed to stay the same between releases.

Helper

What it does

fmt.to_scalar(bits)

the Python scalar for an encoding: a float (exact for formats no wider than float64), an int, a bool, or a complex

fmt.check_encoding(bits)

bits as an int (a pair of ints for a complex format), or raises if it is not a valid encoding

fmt.check_buffer(data)

raises if a buffer of bytes holds an invalid encoding

fmt.components

encodings per element: 1, or 2 for a complex format

fmt.scaled_value(bits) (float formats)

the exact value of an encoding as a pair (m, e), meaning m * 2**e, or None when it is not finite

fmt.encode_scaled(m, e, rounding=..., overflow="ieee") (float formats)

the encoding of m * 2**e, rounded as encode rounds it

The two scaled helpers matter when reading a failing element's bits from a kernel's bfloat16 output buffer: one turns the bits into an exact value, the other turns the exact answer into the bits a correct kernel stores.

Code
# A failing element's bits, read from a kernel's bfloat16 output buffer
bits = 0xBE1A
# Its exact value as a pair (m, e), meaning m * 2**e
print("kernel's value:", er.bfloat16.scaled_value(bits))
# The same value as a Python float
print("as a float:", er.bfloat16.to_scalar(bits))

# The element's exact answer, -2523 * 2**-14, rounded to bfloat16 as a correct kernel stores it
expected = er.bfloat16.encode_scaled(-2523, -14)
print("expected bits:", hex(expected))
# Both values are negative, so their encodings count the bfloat16 steps between them
print("steps apart:", expected - bits)
Output
kernel's value: (-154, -10)
as a float: -0.150390625
expected bits: 0xbe1e
steps apart: 4