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.
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 |
|---|---|---|---|---|---|
|
64 |
11 |
53 |
yes |
yes |
|
32 |
8 |
24 |
yes |
yes |
|
16 |
5 |
11 |
yes |
yes |
|
16 |
8 |
8 |
yes |
yes |
|
8 |
5 |
3 |
yes |
yes |
|
8 |
4 |
4 |
yes |
yes |
|
8 |
3 |
5 |
yes |
yes |
|
8 |
4 |
4 |
no |
yes |
|
8 |
5 |
3 |
no |
no |
|
8 |
4 |
4 |
no |
no |
|
8 |
4 |
4 |
no |
no |
Name |
Largest finite |
Smallest normal |
Smallest subnormal |
|---|---|---|---|
|
1.797693e+308 |
2.225074e-308 |
4.940656e-324 |
|
3.402823e+38 |
1.175494e-38 |
1.401298e-45 |
|
65504 |
6.103516e-05 |
5.960464e-08 |
|
3.389531e+38 |
1.175494e-38 |
9.18355e-41 |
|
57344 |
6.103516e-05 |
1.525879e-05 |
|
240 |
0.015625 |
0.001953125 |
|
15.5 |
0.25 |
0.015625 |
|
448 |
0.015625 |
0.001953125 |
|
57344 |
3.051758e-05 |
7.629395e-06 |
|
240 |
0.0078125 |
0.0009765625 |
|
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 |
|
|---|---|---|---|---|
|
two |
|
signed, 8 to 64 bits |
|
|
two |
|
unsigned, 8 to 64 bits |
|
|
two |
|
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:
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)))
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.
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 |
|
Past the largest value |
|---|---|---|
floating-point with infinity |
|
infinity, or the largest finite value when the rounding direction points toward zero |
floating-point without infinity |
|
the largest value; NaN when a directed rounding points away from zero |
floating-point without infinity |
|
NaN wherever IEEE 754 would give infinity |
any floating-point |
|
the largest finite value, also for infinities the format cannot hold |
integer |
|
wraps around, as PyTorch does |
integer |
|
raises |
integer |
|
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#
- 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") andcomponents(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.
specialselects 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 infloat8_e4m3fn)."fnuz": finite only, no negative zero; the negative-zero encoding is the only NaN (as infloat8_e4m3fnuz).
biasdefaults to2**(e-1) - 1, or2**(e-1)for"fnuz".nan_encodingsgives 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_encodingsgives (PyTorch's bfloat16 NaN is always0x7FC0; 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 ofitemsizebytes, 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
componentformat.
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 |
|---|---|
|
the Python scalar for an encoding: a float (exact for formats no wider than float64), an int, a bool, or a complex |
|
|
|
raises if a buffer of bytes holds an invalid encoding |
|
encodings per element: 1, or 2 for a complex format |
|
the exact value of an encoding as a pair |
|
the encoding of |
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.
# 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)
kernel's value: (-154, -10)
as a float: -0.150390625
expected bits: 0xbe1e
steps apart: 4