Formats and rounding#

This page presents the fundamentals that the rest of the documentation relies on:

  • what a number format is;

  • which formats MPTorch implements: scalar formats, and block formats that share a scale among their elements;

  • what each rounding mode does;

  • which arithmetic the simulation rounds in;

  • the equations the kernels follow.

Every example on this page comes from a run.

The simulation model#

MPTorch never computes in a narrow format. Every operation (a product, an addition, an activation) is carried out in an IEEE binary float, the carrier. Its result is then rounded to the target format \(F\) with a rounding mode \(\circ\):

\[\tilde{x} = Q_{F,\circ}(x).\]

For an elementwise step, such as rounding a weight tensor, that is all there is, and it is what the quantizers do (see Quantizers). A reduction such as a dot product has intermediate results, and each of them can be rounded. Which intermediates are rounded, and to which format, is the arithmetic that the kernels simulate (see Quantized numerical kernels). For one output element of a matrix product, this can look like:

\[c_{ij} = \sum_{k} a_{ik}\, b_{kj} \quad\longrightarrow\quad s_{k} = Q_{\text{acc}}\big(s_{k-1} + Q_{\text{mul}}(a_{ik} b_{kj})\big).\]

The carrier (see Carriers) has far more precision and range than the simulated format. Computing in it and rounding once therefore usually gives the correctly rounded result of the simulated operation, the number a machine working natively in \(F\) would produce. This holds for every format the carrier can hold.

BinaryK: the IEEE P3109 formats#

BinaryK is the family of binary floating-point formats defined by IEEE P3109, the upcoming Standard for Arithmetic Formats for Machine Learning (Fitzgibbon, Wintersteiger and Sarnoff give an overview of the draft). P3109 parameterizes a format by four things: its bitwidth \(K\), its precision \(P\), its signedness, and its domain, which says whether it has infinities. A format is named after them. Binary8p4se is the 8-bit signed (s) format with 4 bits of precision in the extended (e) domain, and Binary8p4sf is its finite-domain (f) twin.

The bits are laid out as in an IEEE 754 binary float. A value has a sign \(s\), a biased exponent \(e\) of \(E\) bits and a stored mantissa \(m\) of \(P-1\) bits. The \(P\)-th bit of precision is the implicit leading one. Its value is

\[x = (-1)^s \cdot \Big(1 + \frac{m}{2^{P-1}}\Big) \cdot 2^{\,e - \text{bias}} \qquad (1 \le e \le 2^E - 1)\]

for normal numbers, and

\[x = (-1)^s \cdot \frac{m}{2^{P-1}} \cdot 2^{\,1 - \text{bias}} \qquad (e = 0)\]

for subnormal numbers, which fill the gap between zero and the smallest normal with the same absolute spacing. You give the total width \(K\) and the precision \(P\). The exponent width follows: \(E = K - P\) for a signed format, and \(E = K - P + 1\) for an unsigned one, which has no sign bit. is_signed is P3109’s signedness, and the domain is set together with the saturation mode (below).

A few consequences are worth keeping in mind:

  • Within one binade \([2^q, 2^{q+1})\) there are \(2^{P-1}\) representable values, spaced \(2^{q-P+1}\) apart. This spacing is the unit in the last place (ulp). The relative spacing is therefore between \(2^{-P}\) and \(2^{1-P}\): neighbouring values are about 6-12 % apart with \(P = 4\) (E4M3’s precision) and 12-25 % apart with \(P = 3\) (E5M2’s). Rounding to nearest moves a value by at most half of that.

  • The largest finite value depends on the domain. In P3109’s extended domain (the default) the last code of the top binade is \(\infty\), and the largest finite value is \((2 - 2^{2-P}) \cdot 2^{\,2^E - 1 - \text{bias}}\). In the finite domain that code is a number, and the largest finite value is \((2 - 2^{1-P}) \cdot 2^{\,2^E - 1 - \text{bias}}\). Both hold for a signed format with \(P \ge 3\). Subnormals, saturation and sign says how to choose the domain, and Relation to IEEE P3109 gives the rules for the other formats.

  • The smallest normal is \(2^{1 - \text{bias}}\) and the smallest subnormal \(2^{1 - \text{bias} - (P-1)}\).

  • bias defaults to P3109’s, the middle of the exponent range: \(2^{E-1}\), which is \(2^{K-P-1}\) for a signed format and \(2^{K-P}\) for an unsigned one. Either way 1.0 is encoded at the middle code point. For the same exponent width, IEEE 754’s bias is \(2^{E-1} - 1\), one less. P3109 fixes the bias rather than the largest exponent, so that adding or removing the infinities moves no finite value. Pass bias= explicitly for a format outside P3109, such as the nearest spellings of the OCP 8-bit formats.

  • A BinaryK format uses every exponent code for finite values, where IEEE 754 reserves the top one for infinities and NaNs. Take a BinaryK format with the IEEE bias and the same exponent and mantissa widths as an IEEE 754 format (float16, float32). It agrees with that format on every value up to its largest finite one, and then continues for one more binade. So no BinaryK format is float16, bfloat16 or float32 (see The IEEE 754 dtypes are not P3109 formats). The OCP formats compare the same way, and the tutorial checks it exhaustively (see Tutorial: training in 8-bit floating point): E5M2 is laid out the IEEE way, so its BinaryK spelling also goes a binade past it, while E4M3 spends its top exponent field on numbers and is matched on every finite value.

Some formats of interest can be approximately represented in terms of BinaryK:

format

spelling

E

P-1

bias

Binary8p4se

BinaryK(8, 4)

4

3

8

Binary8p4sf

BinaryK(8, 4, saturation=SAT_FINITE)

4

3

8

Binary8p3se

BinaryK(8, 3)

5

2

16

Binary6p3se

BinaryK(6, 3)

3

2

4

E4M3’s layout (OCP, NVIDIA)

BinaryK(8, 4, bias=7)

4

3

7

E5M2’s layout (OCP, NVIDIA)

BinaryK(8, 3, bias=15)

5

2

15

float16’s layout

BinaryK(16, 11, bias=15)

5

10

15

bfloat16’s layout

BinaryK(16, 8, bias=127)

8

7

127

float32’s layout

BinaryK(32, 24, bias=127)

8

23

127

The last five rows have each format’s field widths and bias, but none of them is the format it is laid out as: whatever its bias, a BinaryK spends its codes the way P3109 does.

  • The E4M3 row comes closest. It has exactly E4M3’s finite values and differs in the special ones, and so in what an overflow returns.

  • The other four have more values than their namesakes, one binade past them.

The IEEE 754 dtypes are not P3109 formats says how far each row is from the format it is named after. The two 8-bit rows can be imported as mptorch.E4M3 and mptorch.E5M2. The MX block presets build on them with OCP’s largest values and NaN codes (see Block formats).

The following run constructs P3109’s two signed 8-bit formats with 4 and 3 bits of precision, derives their ranges from the formulas above, and checks them against the quantizer in both domains. Each boundary value is a fixed point of the rounding in the domain that has it. For example, \(10^{30}\) overflows to \(\infty\) in the extended domain and to the largest finite value in the finite one.

docs/snippets/formats_binaryK.py#
"""BinaryK: IEEE P3109's K-bit floating-point formats with P bits of precision."""

import torch

from mptorch import BinaryK, SaturationMode
from mptorch.quant import Quant

torch.manual_seed(0)

binary8p4 = BinaryK(8, 4)  # P3109 Binary8p4se: 1 sign, 4 exponent, 3 stored mantissa bits
binary8p3 = BinaryK(8, 3)  # P3109 Binary8p3se: 1 sign, 5 exponent, 2 stored mantissa bits


def describe(f: BinaryK) -> None:
    exp_bits = f.K - f.P if f.is_signed else f.K - f.P + 1
    top_binade = 2.0 ** (2**exp_bits - 1 - f.bias)
    max_extended = (2 - 2 ** (2 - f.P)) * top_binade  # the last code is infinity
    max_finite = (2 - 2 ** (1 - f.P)) * top_binade  # the last code is a number
    min_normal = 2.0 ** (1 - f.bias)
    min_subnormal = 2.0 ** (1 - f.bias - f.man_bits)
    print(f"{f}")
    print(f"  exponent bits {exp_bits}, mantissa bits {f.man_bits}, bias {f.bias}")
    print(f"  largest finite  {max_extended:g} (extended domain), {max_finite:g} (finite domain)")
    print(f"  smallest normal {min_normal:g}")
    print(f"  smallest subnormal {min_subnormal:g}")
    # The quantizer agrees with the formulas: each value is a fixed point in the
    # domain that has it, and 1e30 overflows -- to infinity in the extended
    # domain, to the largest finite value in the finite one.
    probe = torch.tensor([max_extended, max_finite, min_normal, min_subnormal, 1e30])
    for sat in (SaturationMode.SAT_NONE, SaturationMode.SAT_FINITE):
        q = Quant(BinaryK(f.K, f.P, bias=f.bias, saturation=sat))
        print(f"  {sat.name:<11}{q(probe).tolist()}")


describe(binary8p4)
describe(binary8p3)

# Between two consecutive powers of two the representable values are evenly
# spaced: 2**man_bits of them per binade. Here is the binade [1, 2) of Binary8p4.
x = torch.arange(1.0, 2.0, 1 / 16)
print("\ninput           ", [f"{v:.4f}" for v in x.tolist()])
print("Binary8p4 (RNE) ", [f"{v:.4f}" for v in Quant(binary8p4)(x).tolist()])
output#
BinaryK(K=8, P=4, bias=8, is_signed=True, prng_bits=0, saturation=<SaturationMode.SAT_NONE: 2>, domain=<Domain.EXTENDED: 0>, subnormals=<SubnormalsMode.SUBNORMALS: 0>)
  exponent bits 4, mantissa bits 3, bias 8
  largest finite  224 (extended domain), 240 (finite domain)
  smallest normal 0.0078125
  smallest subnormal 0.000976562
  SAT_NONE   [224.0, inf, 0.0078125, 0.0009765625, inf]
  SAT_FINITE [224.0, 240.0, 0.0078125, 0.0009765625, 240.0]
BinaryK(K=8, P=3, bias=16, is_signed=True, prng_bits=0, saturation=<SaturationMode.SAT_NONE: 2>, domain=<Domain.EXTENDED: 0>, subnormals=<SubnormalsMode.SUBNORMALS: 0>)
  exponent bits 5, mantissa bits 2, bias 16
  largest finite  49152 (extended domain), 57344 (finite domain)
  smallest normal 3.05176e-05
  smallest subnormal 7.62939e-06
  SAT_NONE   [49152.0, inf, 3.0517578125e-05, 7.62939453125e-06, inf]
  SAT_FINITE [49152.0, 57344.0, 3.0517578125e-05, 7.62939453125e-06, 57344.0]

input            ['1.0000', '1.0625', '1.1250', '1.1875', '1.2500', '1.3125', '1.3750', '1.4375', '1.5000', '1.5625', '1.6250', '1.6875', '1.7500', '1.8125', '1.8750', '1.9375']
Binary8p4 (RNE)  ['1.0000', '1.0000', '1.1250', '1.2500', '1.2500', '1.2500', '1.3750', '1.5000', '1.5000', '1.5000', '1.6250', '1.7500', '1.7500', '1.7500', '1.8750', '2.0000']

The last two lines show the grid. In \([1, 2)\) Binary8p4 has the eight values \(1, 1.125, \dots, 1.875\), and each input lands on the nearest one. Ties go to the even mantissa (\(1.0625 \to 1.0\), \(1.1875 \to 1.25\), \(1.9375 \to 2.0\)).

The IEEE 754 dtypes are not P3109 formats#

float16, bfloat16 and float32 are not exactly representable as P3109 formats in either domain, nor as BinaryK formats with any other bias. The two standards spend the code points of the same layout differently:

  • IEEE 754 reserves the whole top exponent field (\(2^{P-1}\) codes of each sign) for \(\pm\infty\) and the NaNs. It gives zero two encodings, \(+0.0\) and \(-0.0\).

  • P3109 spends one code of each sign on \(\pm\infty\), and only in the extended domain. Every other code of the top field is a finite value. A signed format has a single, unsigned zero, and the encoding IEEE 754 would read as \(-0.0\) is its one NaN.

  • P3109’s default bias, \(2^{E-1}\), is one more than IEEE 754’s for the same exponent width (\(2^{E-1}-1\)).

A bias can therefore line up at most one end of the range with that of the closest IEEE 754 dtype, and the special values never match. For float16, for instance:

format

largest finite value

smallest positive value

against float16’s finite values

float16

65504

\(2^{-24}\)

BinaryK(16, 11, bias=15)

130944

\(2^{-24}\)

all of them, and 1023 more in \([2^{16}, 130944]\)

Binary16p11se, BinaryK(16, 11)

65472

\(2^{-25}\)

all but 65504, whose code is \(+\infty\), and 1024 more below \(2^{-14}\)

Binary16p11sf

65504

\(2^{-25}\)

all of them, and 1024 more below \(2^{-14}\); no \(\pm\infty\)

None of the three has float16’s \(-0.0\) or its 2046 NaN codes; each has one zero and one NaN. bfloat16 and float32 differ from their spellings in the same way:

  • With the IEEE 754 bias, the BinaryK format reaches a binade past the dtype (about \(6.8 \cdot 10^{38}\) against \(3.4 \cdot 10^{38}\)), with \(2^{P-1} - 1\) extra values: 127 for bfloat16 and \(2^{23} - 1\) for float32.

  • With P3109’s bias, Binary16p8 and Binary32p24 lose the dtype’s largest value to \(+\infty\) in the extended domain and match it in the finite one. They add \(2^{P-1}\) values below the dtype’s smallest normal, down to \(2^{-134}\) and \(2^{-150}\).

The two OCP 8-bit formats relate to their BinaryK rows differently.

E5M2 reserves its top exponent field as IEEE 754 does. So BinaryK(8, 3, bias=15) relates to it as BinaryK(16, 11, bias=15) relates to float16 above: it has every finite value of E5M2 and one binade more. E5M2’s largest finite value is \(57344\). The BinaryK format adds \(65536\), \(81920\) and \(98304\) of each sign. Under SAT_FINITE it also adds \(114688\), the code that is \(\pm\infty\) in the extended domain.

E4M3 spends its top exponent field on finite values, as P3109 does. So BinaryK(8, 4, bias=7) has exactly E4M3’s finite values, up to \(448\). Only the special codes differ: the BinaryK format has \(\pm\infty\) where E4M3 has its two NaNs, and its one NaN where E4M3 has \(-0\). The difference shows in what an overflow returns. E4M3 has no infinity, and PyTorch’s conversion to torch.float8_e4m3fn saturates at \(\pm 448\). BinaryK(8, 4, bias=7) returns:

  • \(\pm\infty\) under SAT_NONE, the default.

  • \(\pm 448\) for a finite input under SAT_PROPAGATE, which leaves an infinite input infinite.

  • \(\pm 448\) for every input under SAT_FINITE_EXTENDED, infinite ones included. This is PyTorch’s result for every float32 input, except that a zero is always \(+0\).

  • \(\pm 480\) under SAT_FINITE. Its finite domain turns the infinity’s code into a number, which E4M3 does not have.

In MPTorch these differences show up in two places:

  • Quantizing to one of the dtype-layout rows is not the dtype’s own conversion. A value between the dtype’s largest finite value and the row’s stays finite, where the dtype would store \(\pm\infty\). And \(-0.0\) comes back as \(+0.0\).

  • The range checks flag these formats:

    • BinaryK(16, 8, bias=127) and BinaryK(32, 24, bias=127) reach \(2^{128}\). On a float32 tensor they warn that they outrun binary32.

    • Binary16p8 and Binary32p24 warn about their bottom there (see What the carrier can hold). A float64 tensor holds all four.

    • BinaryK(16, 11, bias=15), as the format of a GEMM’s result over float16 operands, warns that it reaches past float16 (see What a narrower tensor can store).

Subnormals, saturation and sign#

Two enums decide what happens at the ends of the range. Both are properties of the format, so two formats in one computation can differ in them.

SubnormalsMode decides the bottom of the range:

SUBNORMALS

Gradual underflow, as in IEEE 754 and in P3109, whose formats all have subnormals once \(P > 1\). The exponent code 0 encodes the subnormal numbers, down to \(2^{1-\text{bias}-(P-1)}\).

NORMALS

No subnormals, which takes the format outside P3109. The exponent code 0 encodes only the zero, and the smallest value is the smallest normal, \(2^{1-\text{bias}}\).

EXTENDED_NORMALS

No subnormals either, and also outside P3109. The exponent code 0 encodes one more binade of normal numbers, above \(2^{-\text{bias}}\), with the full mantissa. Its first code is still the zero, so the smallest value is one step above the power of two, \((1 + 2^{1-P})\, 2^{-\text{bias}}\).

Below its smallest value every mode rounds the same way: to zero or to that value, as the rounding mode decides (Relation to IEEE P3109 gives the rule). A value is flushed to zero only if the rounding mode says so. Under round-to-nearest, that is when it is nearer to zero than to the smallest value.

SaturationMode and Domain decide the top. P3109 chooses two things here, separately:

  • the domain: whether the format spends its top code of each sign on \(\pm\infty\) (extended) or on a number (finite);

  • the saturation mode: what an operation does with a result beyond the largest finite value.

The finite domain admits only SatFinite, which leaves four valid pairs. Each pair is one member of SaturationMode:

SAT_FINITE

P3109’s SatFinite, in the finite domain. Everything is clamped to the largest finite value, which here includes the top mantissa code. This applies to a finite input that overflows and to an infinite input, so the output never contains an infinity. NaN inputs pass through unchanged.

SAT_FINITE_EXTENDED

P3109’s SatFinite, in the extended domain. The format keeps its infinity codes, so its largest finite value is the same as under SAT_PROPAGATE and SAT_NONE. Everything is clamped to it, infinite inputs included, as under SAT_FINITE.

SAT_PROPAGATE

P3109’s SatPropagate, in the extended domain. A finite input that overflows is clamped to the largest finite value, which excludes the top mantissa code. This includes an input that rounds onto that code, like 480 in the run below. An infinite input stays infinite.

SAT_NONE

P3109’s SatNone, in the extended domain, and the default. An input that rounds past the largest finite value becomes \(\pm\infty\). P3109 rounds before it saturates, so this happens under every rounding mode, including those for which IEEE 754 stops at the largest finite value, such as rounding toward zero (the run’s SAT_NONE, RZ line).

A BinaryK or SuperFP can also name the pair as P3109 does, with domain= next to saturation=. BinaryK(8, 4, saturation=SAT_FINITE, domain=Domain.EXTENDED) is stored as saturation=SAT_FINITE_EXTENDED, and the two spellings make equal formats. If domain is left out, it follows from the mode: finite for SAT_FINITE and extended otherwise. domain=Domain.FINITE with any other mode raises. The flat functions of the schema tier take no format object, so they name the pair with the SaturationMode member alone.

docs/snippets/formats_modes.py#
"""What happens at the two ends of the range: subnormals and saturation."""

import torch

from mptorch import BinaryK, Domain, RoundMode, SaturationMode, SubnormalsMode
from mptorch.quant import Quant

torch.set_printoptions(precision=6, sci_mode=False)

# Small values, in E4M3's layout (bias 7): the smallest normal is 2**-6. Under
# EXTENDED_NORMALS the binade below it holds normals as well, but its
# mantissa-zero code is still the zero -- so 2**-7 is not one of them, and
# that binade starts at 1.125 * 2**-7.
small = torch.tensor([2.0**-5, 2.0**-6, 2.0**-7, 2.0**-8, 2.0**-9, 2.0**-10])
print("input               ", small.tolist())
for mode in SubnormalsMode:
    q = Quant(BinaryK(8, 4, bias=7, subnormals=mode))
    print(f"{mode.name:<20}", q(small).tolist())

# Large values, same layout: the top code, 480, is a number in the finite
# domain (SAT_FINITE) and infinity in the extended one (the other three),
# whose largest finite value is 448.
large = torch.tensor([448.0, 480.0, 500.0, 1e6, float("inf"), -float("inf"), float("nan")])
print("\ninput               ", large.tolist())
for mode in SaturationMode:
    q = Quant(BinaryK(8, 4, bias=7, saturation=mode))
    print(f"{mode.name:<20}", q(large).tolist())

# As in P3109, rounding comes before saturation, so SAT_NONE overflows to infinity
# even when rounding toward zero, where IEEE 754 would stop at 448.
q = Quant(BinaryK(8, 4, bias=7), RoundMode.RZ)
print(f"{'SAT_NONE, RZ':<20}", q(large).tolist())

# P3109's own spelling of the pair: SatFinite in the extended domain is
# SAT_FINITE_EXTENDED, and the two spellings make the same format.
f = BinaryK(8, 4, bias=7, saturation=SaturationMode.SAT_FINITE, domain=Domain.EXTENDED)
print(
    f"\n{f.saturation.name}, {f.domain.name}:",
    f == BinaryK(8, 4, bias=7, saturation=SaturationMode.SAT_FINITE_EXTENDED),
)

# An unsigned format has no sign bit, so negative inputs collapse to zero and
# the freed bit goes to the exponent (bias 16 instead of 8).
u = BinaryK(8, 4, is_signed=False)
print(f"\n{u}")
print("unsigned            ", Quant(u)(torch.tensor([-3.0, -0.001, 0.0, 3.0, 3000.0])).tolist())
output#
input                [0.03125, 0.015625, 0.0078125, 0.00390625, 0.001953125, 0.0009765625]
SUBNORMALS           [0.03125, 0.015625, 0.0078125, 0.00390625, 0.001953125, 0.0]
NORMALS              [0.03125, 0.015625, 0.0, 0.0, 0.0, 0.0]
EXTENDED_NORMALS     [0.03125, 0.015625, 0.0087890625, 0.0, 0.0, 0.0]

input                [448.0, 480.0, 500.0, 1000000.0, inf, -inf, nan]
SAT_FINITE           [448.0, 480.0, 480.0, 480.0, 480.0, -480.0, nan]
SAT_PROPAGATE        [448.0, 448.0, 448.0, 448.0, inf, -inf, nan]
SAT_NONE             [448.0, inf, inf, inf, inf, -inf, nan]
SAT_FINITE_EXTENDED  [448.0, 448.0, 448.0, 448.0, 448.0, -448.0, nan]
SAT_NONE, RZ         [448.0, inf, inf, inf, inf, -inf, nan]

SAT_FINITE_EXTENDED, EXTENDED: True

BinaryK(K=8, P=4, bias=16, is_signed=False, prng_bits=0, saturation=<SaturationMode.SAT_NONE: 2>, domain=<Domain.EXTENDED: 0>, subnormals=<SubnormalsMode.SUBNORMALS: 0>)
unsigned             [0.0, 0.0, 0.0, 3.0, 3072.0]

An unsigned format (is_signed=False) has no sign bit. Negative inputs become zero, and the freed bit goes to the exponent field. The run’s last line uses the unsigned BinaryK(8, 4), P3109’s Binary8p4ue. Compared with the signed Binary8p4se:

  • It has five exponent bits and the default bias \(2^{K-P} = 16\), where the signed format has four and \(2^{K-P-1} = 8\). Its normal exponents therefore run from \(-15\) to \(15\) instead of \(-7\) to \(7\).

  • Its largest finite value is \(1.625 \cdot 2^{15} = 53248\), against \(1.75 \cdot 2^{7} = 224\). The unsigned top binade ends in two reserved codes, \(+\infty\) and NaN, and the signed one in one.

The extra bit buys range, not precision. Both formats have \(P = 4\), so around \(3000\) the unsigned format’s values are 256 apart, and the run’s input \(3000\) comes back as \(3072\), the nearest of them.

Relation to IEEE P3109#

The sections above introduced P3109 one notion at a time: how it names a format after its parameters, its default bias, its two domains and its three saturation modes. This section puts them side by side and says in what sense a BinaryK is a P3109 format. It covers, in order:

  • which MPTorch argument stands for which notion of the standard.

  • the rule for the largest finite value, which the earlier sections stated only for a signed format with \(P \ge 3\).

  • how the correspondence is tested.

  • the two ways in which MPTorch departs from the standard.

Every parameter of a P3109 format, and each of its saturation and rounding modes, has a counterpart among the arguments of BinaryK and MPTorch’s enums. A BinaryK(K, P) left at its defaults is therefore the P3109 format with that bitwidth and precision, signed and in the extended domain, for every width the standard admits. The rounding modes are introduced further down (see Rounding modes); their rows are listed here so that the whole correspondence is in one table.

P3109

MPTorch

bitwidth \(K\), precision \(P\), signedness

BinaryK(K, P, is_signed=...)

extended / finite domain

domain=Domain.EXTENDED / Domain.FINITE

exponent bias \(2^{K-P-1}\), unsigned \(2^{K-P}\)

the default bias

SatNone, SatPropagate, SatFinite

saturation=SAT_NONE, SAT_PROPAGATE, SAT_FINITE

extended domain with SatFinite (one SaturationMode member, for the flat functions)

SAT_FINITE_EXTENDED

NearestTiesToEven, NearestTiesToAway

RNE, RNA

TowardPositive, TowardNegative, TowardZero

RU, RD, RZ

ToOdd

RO

StochasticA, StochasticB, StochasticC with \(N\) random bits

SR (SR_A), SR_B, SR_C with prng_bits=N

The top of the range is counted in P3109’s code points. The top binade has \(2^{P-1}\) codes:

  • In the extended domain, the last one is \(+\infty\).

  • An unsigned format spends its last one on NaN and, in the extended domain, the one below that on \(+\infty\).

The largest finite value is the highest code left: \(224\) for Binary8p4se, \(240\) for Binary8p4sf and \(53248\) for Binary8p4ue. With \(P \le 2\) the reserved codes can outnumber the top binade’s, which moves the largest finite value a binade or two lower. A finite result above it saturates in every rounding mode.

dev/benchmarks/formats/binaryK_values.py prints the whole code-point table of a format: every value, one per line, infinities and NaN included. With --verify it quantizes each value and checks that the kernel returns it unchanged. dev/benchmarks/formats/superfp_values.py does the same for SuperFP.

Two test files compare the formats to the standard:

  • tests/test_binaryk_quantize.py checks the six deterministic modes against gfloat, a reference implementation of P3109, below the top of the range.

  • tests/test_binaryk_p3109.py checks the top itself, against a transcription of the paper’s definitions: every precision of the 3- to 8-bit formats, signed and unsigned, in all three saturation modes. gfloat is not used there because it overflows the IEEE 754 way under directed rounding.

MPTorch departs from the standard in two ways.

By extension. Three options describe formats that P3109 does not define: a bias other than the default, the NORMALS and EXTENDED_NORMALS subnormal modes, and the widths the standard excludes (it requires \(K \ge 3\), and \(P < K\) for a signed format). These options are what make E4M3’s finite values reachable, as well as the nearest representations of E5M2 and the IEEE 754 dtypes (see The IEEE 754 dtypes are not P3109 formats).

The two extra subnormal modes change only the bottom of the range. Both concern the \(2^{P-1}\) codes of each sign whose exponent field is zero. SUBNORMALS spends these on the zero and the \(2^{P-1} - 1\) subnormals. The other two modes use them differently:

  • NORMALS leaves all of them unused except the zero, so the smallest positive value is the smallest normal, \(2^{1-\text{bias}}\).

  • EXTENDED_NORMALS spends them on one more binade of normals, \([2^{-\text{bias}}, 2^{1-\text{bias}})\), directly below the smallest normal. The mantissa-zero code of that binade does not encode \(2^{-\text{bias}}\). It remains the zero (and, with the sign bit set, the NaN), as in every other BinaryK format. The binade therefore holds \(2^{P-1} - 1\) values. The smallest is one step above the power of two at its foot, \((1 + 2^{1-P})\, 2^{-\text{bias}}\). With \(P = 1\) the binade holds no values.

Let \(x_{\min}\) be the smallest positive value of the format: \(2^{1-\text{bias}-(P-1)}\) under SUBNORMALS, and the two values in the list above under the other modes. Below \(x_{\min}\) all three modes round the same way. An input \(x\) with \(0 < |x| < x_{\min}\) has two candidates for its magnitude, zero and \(x_{\min}\), and the rounding mode picks between them (see Rounding modes):

  • RNE and RNA take the nearer one. On a tie, \(|x| = x_{\min} / 2\), RNE takes the zero and RNA takes \(x_{\min}\).

  • RU, RD and RZ take the candidate in their own direction.

  • RO takes \(x_{\min}\), the nonzero candidate.

  • SR takes \(x_{\min}\) with probability \(|x| / x_{\min}\), and the zero otherwise.

By simulating values rather than code points. A result is a value of the carrier, not an encoding, so P3109’s single NaN is whichever NaN came in. P3109’s single zero is unsigned, and here MPTorch does follow the standard: every zero the kernels return is \(+0.0\), whether it came from \(-0.0\) or from a negative value that rounded to zero. The same holds for SuperFP.

SuperFP: precision at the top, range below#

SuperFP is the second format family the kernels implement. It has the same three fields as a binary float (man_bits, exp_bits, bias), but only the top normal_binades binades carry a mantissa. The codes of the remaining \(2^{\mathrm{exp\_bits}} - \mathrm{normal\_binades}\) binades, \(2^{\mathrm{man\_bits}}\) codes each, are reinterpreted. The first is the zero. The others are further powers of two below the normal region, one per code: numbers with an implicit mantissa of exactly 1. With \(e_{\max} = 2^{\mathrm{exp\_bits}} - 1 - \text{bias}\), the three regions are

\[\begin{split}\begin{aligned} \text{normal:} &\quad [2^{\,e_{\max} - b + 1},\; 2^{\,e_{\max}+1}), && \text{full mantissa} \\ \text{supernormal:} &\quad [2^{\,e_{\max} - b + 2 - n},\; 2^{\,e_{\max} - b + 1}), && \text{powers of two only} \\ \text{underflow:} &\quad \text{below that}, && \text{flushed to zero} \end{aligned}\end{split}\]

where \(b = \mathrm{normal\_binades}\) and \(n = (2^{\mathrm{exp\_bits}} - b)\, 2^{\mathrm{man\_bits}}\) is the number of reinterpreted codes, of which \(n - 1\) are supernormals. There are no subnormals. The bias has no default: it is part of the format’s design and must be given. In the supernormal region, rounding acts on the exponent: to nearest, \(3 = 2^{1.58}\) becomes \(4\).

docs/snippets/formats_superfp.py#
"""SuperFP: precision at the top of the range, dynamic range below it."""

import torch

from mptorch import SuperFP
from mptorch.quant import Quant

# 3 mantissa bits, 4 exponent bits, bias 7 -- the same widths as E4M3 -- but
# only the top 2 binades keep their mantissa. The codes that would have
# encoded the other 14 binades' mantissas become 14 * 2**3 = 112 further
# powers of two below them.
f = SuperFP(man_bits=3, exp_bits=4, normal_binades=2, bias=7)
q = Quant(f)

max_exp = 2**f.exp_bits - 1 - f.bias  # 8: the top binade is [2**8, 2**9)
normal_lo = max_exp - f.normal_binades + 1  # 7
super_lo = normal_lo - (2**f.exp_bits - f.normal_binades) * 2**f.man_bits + 1  # -104
print(f"{f}")
lo, hi = 2.0**normal_lo, 2.0 ** (max_exp + 1)
print(f"  normal region      [2^{normal_lo}, 2^{max_exp + 1})  = [{lo:g}, {hi:g})")
print(f"  supernormal region [2^{super_lo}, 2^{normal_lo})  = powers of two only")
print(f"  below 2^{super_lo - 1} = {2.0 ** (super_lo - 1):g}: flushed to zero")

# In the normal region the mantissa is kept ...
x = torch.tensor([128.0, 144.0, 160.0, 176.0, 300.0, 448.0, 511.0])
print("\nnormal region     ", x.tolist())
print("quantized         ", q(x).tolist())
# ... below it only the power of two survives (3 is rounded to 4: round to
# nearest is taken on the exponent, and 3 = 2**1.58 is nearer to 2**2) ...
x = torch.tensor([1.0, 1.5, 3.0, 100.0, 2.0**-20, 3.0 * 2**-50])
print("\nsupernormal region", x.tolist())
print("quantized         ", q(x).tolist())
# ... and far below, the flush to zero.
x = torch.tensor([2.0**-104, 2.0**-105, 2.0**-106])
print("\nunderflow         ", x.tolist())
print("quantized         ", q(x).tolist())
output#
SuperFP(man_bits=3, exp_bits=4, normal_binades=2, bias=7, is_signed=True, prng_bits=0, saturation=<SaturationMode.SAT_NONE: 2>, domain=<Domain.EXTENDED: 0>)
  normal region      [2^7, 2^9)  = [128, 512)
  supernormal region [2^-104, 2^7)  = powers of two only
  below 2^-105 = 2.46519e-32: flushed to zero

normal region      [128.0, 144.0, 160.0, 176.0, 300.0, 448.0, 511.0]
quantized          [128.0, 144.0, 160.0, 176.0, 288.0, 448.0, inf]

supernormal region [1.0, 1.5, 3.0, 100.0, 9.5367431640625e-07, 2.6645352591003757e-15]
quantized          [1.0, 1.0, 4.0, 128.0, 9.5367431640625e-07, 3.552713678800501e-15]

underflow          [4.930380657631324e-32, 2.465190328815662e-32, 1.232595164407831e-32]
quantized          [4.930380657631324e-32, 0.0, 0.0]

With the same 8 bits as E4M3, this format reaches down to \(2^{-104}\) instead of \(2^{-9}\). The price is that it keeps its mantissa only in the two top binades. It suits quantities whose scale matters more than their digits.

FixedPoint: one step across the range#

FixedPoint is a fixed-point format, defined as in Gupta et al., Deep Learning with Limited Numerical Precision. A word of wl bits holds an integer \(k\), and its value is \(k \cdot 2^{-\text{fl}}\). Every value is a multiple of the same step, \(2^{-\text{fl}}\), so the grid is as fine at the top of the range as near zero, and there is no exponent field. With \(n\) magnitude bits (wl - 1 in a signed format, wl in an unsigned one), the range is

\[\begin{split}\begin{aligned} \text{two's complement (the default):} &\quad [-2^{\,n-\text{fl}},\; 2^{\,n-\text{fl}} - 2^{-\text{fl}}] \\ \text{symmetric:} &\quad [-(2^{\,n-\text{fl}} - 2^{-\text{fl}}),\; 2^{\,n-\text{fl}} - 2^{-\text{fl}}] \\ \text{unsigned:} &\quad [0,\; 2^{\,n-\text{fl}} - 2^{-\text{fl}}] \end{aligned}\end{split}\]

fl can be any integer: negative for a step larger than 1, or larger than wl for a format that holds only fractions.

  • Every rounding mode applies (Rounding modes). Under RNE a tie goes to the even integer code.

  • Below the step, the two candidates are zero and the step itself, as for a BinaryK format below its smallest subnormal.

  • A result past either end saturates to that end, and so does an infinity: the word has no code for one, so the format has no saturation mode.

  • A NaN passes through, a negative input to an unsigned format becomes zero, and the one zero is \(+0.0\), as for BinaryK.

  • Under SR the random bits are added directly below the step, so the probability is exactly the one Stochastic rounding states, at every prng_bits: none gives RZ.

  • The magnitude bits must fit the carrier’s precision, and with prng_bits they share it: at most 24 bits in all in binary32 and 53 in binary64 (Carriers).

  • There is no fixed-point arithmetic inside a SplitMac or a FusedMac yet, and they refuse a FixedPoint, as a Palette does. As the element of a block format, though, it is multiplied by the block GEMM (Block floating point).

docs/snippets/formats_fixedpoint.py#
"""FixedPoint: the multiples of one step that a word of bits holds."""

import torch

from mptorch import FixedPoint, RoundMode
from mptorch.quant import Quant

# 8 bits, 4 of them fractional: every value is a multiple of 1/16. Signed
# formats are two's complement by default, so the bottom is one step further
# from zero than the top.
f = FixedPoint(8, 4)
print(f)
print(f"  step {f.step}, range [{f.min_value}, {f.max_value}]")
sym = FixedPoint(8, 4, symmetric=True)
uns = FixedPoint(8, 4, is_signed=False)
print(f"  symmetric: [{sym.min_value}, {sym.max_value}]")
print(f"  unsigned:  [{uns.min_value}, {uns.max_value}]")

q = Quant(f)
# Inside the range: the nearest multiple of 1/16. Under RNE a tie goes to the
# even integer code: 0.09375 is 1.5 steps and becomes 2 steps.
x = torch.tensor([1.1, 3.3, 0.09375, -0.40625])
print("\ninside the range ", x.tolist())
print("quantized        ", q(x).tolist())
# Below the step: zero or the step. Half a step is the tie, and zero is the
# even code. A negative value that rounds to zero gives +0.0.
x = torch.tensor([0.03, 0.04, -0.03])
print("\nbelow the step   ", x.tolist())
print("quantized        ", q(x).tolist())
# Past the ends, infinities included: saturated, since there is no code for an
# infinity. A NaN passes through.
x = torch.tensor([9.0, -9.0, float("inf"), float("-inf"), float("nan")])
print("\npast the ends    ", x.tolist())
print("quantized        ", q(x).tolist())

# Every rounding mode applies.
x = torch.tensor([1.1, -1.1])
print("\nrounding modes of", x.tolist())
for mode in (RoundMode.RNE, RoundMode.RU, RoundMode.RD, RoundMode.RZ, RoundMode.RO):
    print(f"  {mode.name:<3}", Quant(f, mode)(x).tolist())

# An unsigned format rounds a negative input to zero, and fl may be negative:
# FixedPoint(8, -2) has a step of 4.
print("\nunsigned          ", Quant(uns)(torch.tensor([-1.0, 2.5])).tolist())
coarse = FixedPoint(8, -2)
print(f"{coarse}: step {coarse.step}, range [{coarse.min_value}, {coarse.max_value}]")
print("  10.0 and 1000.0 ->", Quant(coarse)(torch.tensor([10.0, 1000.0])).tolist())
output#
FixedPoint(wl=8, fl=4, is_signed=True, symmetric=False, prng_bits=0)
  step 0.0625, range [-8.0, 7.9375]
  symmetric: [-7.9375, 7.9375]
  unsigned:  [0.0, 15.9375]

inside the range  [1.100000023841858, 3.299999952316284, 0.09375, -0.40625]
quantized         [1.125, 3.3125, 0.125, -0.375]

below the step    [0.029999999329447746, 0.03999999910593033, -0.029999999329447746]
quantized         [0.0, 0.0625, 0.0]

past the ends     [9.0, -9.0, inf, -inf, nan]
quantized         [7.9375, -8.0, 7.9375, -8.0, nan]

rounding modes of [1.100000023841858, -1.100000023841858]
  RNE [1.125, -1.125]
  RU  [1.125, -1.0625]
  RD  [1.0625, -1.125]
  RZ  [1.0625, -1.0625]
  RO  [1.0625, -1.0625]

unsigned           [0.0, 2.5]
FixedPoint(wl=8, fl=-2, is_signed=True, symmetric=False, prng_bits=0): step 4.0, range [-512.0, 508.0]
  10.0 and 1000.0 -> [8.0, 508.0]

The carrier bounds a fixed-point format the way it bounds a float format (What the carrier can hold), with one difference: the format saturates onto its ends, so an end the carrier cannot hold raises rather than warns. In binary32 (binary64):

  • at most 24 (53) magnitude bits, and as many in all with prng_bits;

  • both ends inside the carrier’s range. In two’s complement the end farther out is the bottom, \(-2^{\,n-\text{fl}}\), so \(n - \text{fl} \le 127\) (1023); a symmetric or unsigned format may reach one binade higher, \(n - 1 - \text{fl} \le 127\) (1023);

  • a largest value at or above the carrier’s smallest normal, \(2^{-126}\) (\(2^{-1022}\)), or nothing but zero is returned;

  • a step of at least \(2^{-125}\) (\(2^{-1021}\)), the floor of BinaryK’s subnormals, which a fixed-point grid is placed on the same way. A finer step warns: values near zero may round incorrectly.

A float16 or bfloat16 result is rounded once more when it is stored, and held to the rule for an elementwise result (What a narrower tensor can store): the inputs are already the dtype’s values, so only an end of the range can miss its grid. An end past the dtype’s largest value warns, as does a largest value that is not one of the dtype’s (a saturated result is then rounded again), and a largest value below the dtype’s smallest raises. There is no fixed-point matrix product, so there is no rule for one.

A FixedPoint can also be the element of a block format, which gives block floating point (Block floating point).

Block formats#

BinaryK and SuperFP give every element an exponent of its own. A block format shares one scale among a block of consecutive elements and stores the elements as narrow codes, so a 4-bit element can carry values over the whole range of a float32 tensor, one block at a time. The OCP Microscaling (MX) formats and NVIDIA’s NVFP4 are block formats, and they are what the newest accelerators multiply natively. The MX formats are defined by the OCP Microscaling Formats (MX) Specification (version 1.0, September 2023) and evaluated by Rouhani et al.; NVFP4 is described in Pretraining Large Language Models with NVFP4 (Section 2 and Appendix B).

A BlockFormat is defined by an element format, a scale format and a block size. The element is a BinaryK, a SuperFP or a FixedPoint, and the scale a BinaryK or a SuperFP (see SuperFP elements and scales and Block floating point, below). A tensor is split into blocks of block_size consecutive elements along one axis, its packed axis, and each block stores one scale code beside its element codes. Element \(i\) of block \(\kappa\) stands for the value

\[x_i \;\approx\; e_i\, \sigma_\kappa ,\]

its element value \(e_i\) times its block’s scale \(\sigma_\kappa\).

As an example, in the MX formats the scale format is E8M0, an unsigned exponent with no mantissa: code \(c\) is the power of two \(2^{c - 127}\), and code 255 is NaN. Writing \(X_\kappa\) for the block’s exponent,

\[\sigma_\kappa = 2^{X_\kappa}, \qquad -127 \le X_\kappa \le 127 ,\]

so the block scale alone places a block anywhere in float32’s range, and the format needs nothing else.

Tensor scales#

A scale format with a mantissa – NVFP4’s E4M3, or a SuperFP – follows a block’s largest magnitude more closely than a power of two can, but over a much shorter range: E4M3’s positive values run from \(2^{-9}\) to \(448\). By itself it could represent only a block whose largest magnitude is between \(2^{-9}\) and \(448\) times the element format’s largest value. Such a format can therefore use a second scale, one float32 number \(S_t\) for the whole tensor. This tensor scale can usually bring back the tensor into the scale format’s range, with the block scale differentiating the blocks:

\[\sigma_\kappa = s_\kappa\, S_t ,\]

where \(s_\kappa\) is the value of the block’s scale code and the product is computed in float32. \(S_t\) is one number for the whole tensor, kept beside the codes (the tensor_scale of a BlockPacked), so it adds nothing to the bytes per element. How a block is quantized gives its default value.

MPTorch currently pairs the tensor scale to the kind of block scale being used; it is not an option of its own. A BlockFormat therefore can be in one of three states:

  • Block scale only: a power-of-two scale, as in the MX presets. Such a format has no tensor scale, and passing tensor_scale= to it raises.

  • Block scale and tensor scale: any scale with a mantissa, as in NVFP4. A static tensor_scale=1.0 leaves the block scale alone, which is block scaling with a mantissa scale.

  • No scale: scale=None stores the element codes as they are.

A tensor scale without block scales is not available.

The presets#

MPTorch includes as presets five of the six concrete formats of OCP MX v1.0, and NVIDIA’s NVFP4, and bfp() builds block floating point (Block floating point):

preset

element

block scale

tensor scale

block

largest element

bytes/element

MXFP8_E4M3

E4M3

E8M0

none

32

448

1.031

MXFP8_E5M2

E5M2

E8M0

none

32

57344

1.031

MXFP6_E2M3

E2M3

E8M0

none

32

7.5

0.781

MXFP6_E3M2

E3M2

E8M0

none

32

28

0.781

MXFP4_E2M1

E2M1

E8M0

none

32

6

0.531

NVFP4

E2M1

E4M3

float32

16

6

0.562

bfp(8)

FixedPoint(8, 6)

E8M0

none

16

1.984375

1.062

bfp(8, 32)

FixedPoint(8, 6)

E8M0

none

32

1.984375

1.031

“Largest element” is the format’s elem_max, the largest element value \(e_i\). The largest value a block can stand for is elem_max times its largest scale. OCP’s sixth format, MXINT8, has 8-bit two’s complement integer elements. bfp(8, 32) is its shape with sign-magnitude elements, which hold every MXINT8 value but one, \(-2\), so there is no MXINT8 preset. The element formats use OCP’s biases (IEEE 754’s), one below P3109’s default, so the presets spell them out (E4M3 = BinaryK(8, 4, bias=7)). Relation to IEEE P3109 explains how BinaryK relates to the standard.

How a block is quantized#

A block format stores each element \(x_i\) of a block as an element value \(e_i\), next to one scale \(s\) for the whole block, so that

\[x_i \approx e_i\, s .\]

Quantizing a block means choosing both. The scale \(s\) has to be a value of the scale format, and each \(e_i\) a value of the element format. Once the scale is fixed the elements follow: \(e_i\) is \(x_i / s\) rounded to the element format, and the block then stands for the decoded values \(\hat{x}_i = e_i\, s\). The main question is which scale to take, and the answer depends on the format. A tensor is quantized one block at a time.

The scale a block asks for#

One scale serves the whole block, so it can put at least one element exactly where we want it, and the natural choice is the largest. Let \(a = \max_i |x_i|\) be the block’s largest magnitude (NaNs aside) and elem_max the element format’s largest value: 6 for E2M1, whose magnitudes are 0, 0.5, 1, 1.5, 2, 3, 4 and 6, and 448 for E4M3. An element above elem_max cannot be stored, so the codes are used best when the block’s largest element sits exactly at the top, \(a = \mathrm{elem\_max} \cdot s\). That gives the scale

\[r = \frac{a}{\mathrm{elem\_max}} .\]

But \(r\) is rarely a value of the scale format. Let \(\lfloor r \rfloor\) and \(\lceil r \rceil\) be the scale format’s values nearest to \(r\) from below and from above; for E8M0 these are the two powers of two around \(r\). They are the two most common candidates, and each has a cost:

  • \(s = \lfloor r \rfloor\) is too small. The block’s largest element lands at \(a / \lfloor r \rfloor = \mathrm{elem\_max} \cdot r / \lfloor r \rfloor\), above elem_max. No code holds such a value, so it is clipped to elem_max (it saturates), in every rounding mode, and decodes as

    \[\hat{a} \;=\; \mathrm{elem\_max} \cdot \lfloor r \rfloor \;=\; a \cdot \frac{\lfloor r \rfloor}{r} \;<\; a .\]

    The block’s largest value comes back too small by the factor \(\lfloor r \rfloor / r\).

  • \(s = \lceil r \rceil\) is too large. The block’s largest element lands at \(\mathrm{elem\_max} \cdot r / \lceil r \rceil\), below elem_max, so every element is in range. But two neighbouring decoded values are one element step \(\delta\) times the scale apart, and that distance is now

    \[\delta \cdot \lceil r \rceil \;>\; \delta \cdot r .\]

    The block’s grid is coarser than necessary by the factor \(\lceil r \rceil / r\). Every element is rounded more coarsely, and small values reach zero sooner: rounded to nearest, an element becomes zero once its magnitude is below half the element format’s smallest value times the scale, \(0.25\, \lceil r \rceil\) for E2M1.

The run at the end of this section shows both choices on one MXFP4 block whose largest magnitude is 3.8. It asks for \(r = 3.8 / 6 \approx 0.63\), so \(\lfloor r \rfloor = 1/2\) and \(\lceil r \rceil = 1\):

  • Under the scale 1/2, 3.8 is 7.6 in the element’s units. It is clipped to 6 and decodes as \(6 \cdot 1/2 = 3.0\), which is 21% low: \(\lfloor r \rfloor / r = 0.5 / 0.63 = 0.79\).

  • Under the scale 1, it is 3.8, rounds to 4 and decodes as 4.0, which is 5% high. But the grid is twice as coarse: the block’s 0.3 decodes as 0.5 instead of 0.25, and anything below 0.25 would decode as zero.

The four rules: one dividing line each#

A block gets one scale, chosen once from the block’s own values and stored with it. A rule makes this choice: given a block, it returns the lower candidate or the upper one. Blocks hold different values, so the same rule gives some blocks of a tensor the lower candidate and others the upper one.

BlockFormat(..., scale_rounding=) names the rule, a member of ScaleRounding. Four of the rules choose between the two candidates and are described here; the other three also consider a third scale option (see Four Over Six, below).

A rule’s answer depends on where the scale the block asks for, \(r\), lies between the block’s two candidates:

\[\rho = \frac{r}{\lfloor r \rfloor} .\]

Under the lower candidate the block’s largest element lands at \(\mathrm{elem\_max} \cdot \rho\), so \(\rho\) also measures how much that candidate clips:

  • \(\rho = 1\): the lower candidate is the scale the block asks for, and nothing is clipped.

  • A larger \(\rho\): the lower candidate clips more, and the case for the upper one is stronger. Between two powers of two, \(\rho\) is below 2.

Each of the four rules has a dividing line \(\theta\), and gives a block

  • the lower candidate, \(\lfloor r \rfloor\), if the block’s \(\rho\) is below the line: there is little to clip, so the block keeps the finer grid;

  • the upper candidate, \(\lceil r \rceil\), if the block’s \(\rho\) is above the line: too much would be clipped, so the block takes the coarser grid instead.

The rules differ only in where they put the line. The table below has four MXFP4 blocks (E2M1 elements, power-of-two scale) with different largest magnitudes. Each asks for a scale between 1/2 and 1, its two candidates, and the last four columns give the scale each rule chooses:

largest magnitude \(a\)

\(r = a / 6\)

\(\rho\)

lands at, under 1/2

UP

SELECTIVE

OCP

NEAREST

3.1

0.52

1.03

6.2

1

1/2

1/2

1/2

3.6

0.60

1.20

7.2

1

1

1/2

1/2

4.2

0.70

1.40

8.4

1

1

1

1/2

5.0

0.83

1.67

10.0

1

1

1

1

A row is one block under the four rules. A column is one rule, whose answer changes once, where \(\rho\) passes its line: UP’s line is below all four blocks, SELECTIVE’s is between the first and the second, OCP’s between the second and the third, and NEAREST’s between the third and the fourth.

The next table gives each rule’s line, lowest first. Its last three columns are for E2M1 under a power-of-two scale, where the rules differ most, and \(T\) is explained under SELECTIVE below.

rule

gives the upper candidate when

dividing line \(\theta\)

largest element lands in

which then

UP

\(r\) is not itself a scale value

1

\((3, 6]\)

is never clipped

SELECTIVE

NEAREST does, or the lower candidate would put the largest element above \(T\)

7/6

\((3.5, 7]\)

moves no further than rounding moves it

OCP

the lower candidate would put the largest element past the element format’s top binade

4/3

\([4, 8)\)

is clipped above 7, up to 25% low

NEAREST

\(r\) is nearer to the upper candidate

3/2

\([4.5, 9]\)

is clipped above 7, up to 33% low

A rule with a low line gives most blocks the upper candidate: it clips little, and many blocks get the coarser grid. A rule with a high line does the reverse. The earlier example block (largest magnitude 3.8) has \(\rho = 0.63 / 0.5 = 1.27\), above the lines of UP and SELECTIVE and below those of OCP and NEAREST. The first two give it the scale 1 and the other two the scale 1/2, as the run shows.

OCP

This rule never computes \(r\). It rounds \(a\) and elem_max each down to a power of two, and divides:

\[s = 2^{\lfloor \log_2 a \rfloor - e_{\max}}, \qquad e_{\max} = \lfloor \log_2(\mathrm{elem\_max}) \rfloor .\]

This is the conversion that the OCP Microscaling Formats (MX) Specification gives (version 1.0, Section 6.3). It needs only the exponent of \(a\), and no division. The result is still one of the two candidates: the power of two that puts the block’s largest element in the element format’s top binade, \([2^{e_{\max}}, 2^{e_{\max}+1})\). For E2M1 that binade is \([4, 8)\), but E2M1 stops at 6. The rule therefore takes \(\lfloor r \rfloor\) whenever the largest element then stays below 8, and that element is clipped if it is above 6, by up to a quarter of its value. In general the dividing line is \(2^{e_{\max}+1} / \mathrm{elem\_max}\): 4/3 for E2M1 and 8/7 for E4M3. The rule exists for a power-of-two scale only.

NEAREST

Take the candidate nearer to \(r\), ties to even. This is NVFP4’s rule: Pretraining Large Language Models with NVFP4 (Appendix B.2) rounds each block’s scale to E4M3 this way. How much it clips depends on how far apart the two candidates are. In E4M3’s normal range they differ by at most a factor of 1.125, so the scale is at most a factor of 1.0625 below \(r\). The largest element then lands between 5.65 and 6.375, and E2M1 takes it to 6 either way. Two powers of two differ by a factor of 2: the dividing line is at 3/2, and the largest element is clipped by up to a third.

UP

Always take \(\lceil r \rceil\). No element ever passes elem_max. This is the rule that NVIDIA’s Recipes for Pre-training LLMs with MXFP8 (Section 3.3, Algorithm 1) uses for E8M0. Its authors describe the specification’s rule as rounding the scale down. They report training issues under it, which they hypothesize come from the clipped values, and none once the scale is rounded up. The price is the other cost, for every block: from a power of two, a grid up to twice as coarse as the block needs. The NVFP4 paper (Appendix B.4) counts this for a 4-bit element: in the worst case no element of the block reaches the values 4 and 6, and the block uses 2.58 of E2M1’s 3.58 binades. UP pays this even when the block’s largest element would have landed between 6 and 7 under \(\lfloor r \rfloor\), and so rounded to 6 without being clipped.

SELECTIVE

Take what NEAREST takes, except for blocks that the lower candidate would really clip; those get the upper one. Clipping does not always lose something. If E2M1’s values went on past 6, the next one would be 8. An element that lands between 6 and 7 would then still round to 6, so clipping it to 6 is no worse than rounding it. An element above 7 would round to 8, which does not exist, and clipping it to 6 moves it further than any rounding would.

The rule therefore uses a threshold \(T\): elem_max plus half the element format’s step above it (7 for E2M1). If the block’s largest element lands at or below \(T\) under NEAREST’s choice, the rule keeps that choice. Otherwise it takes \(\lceil r \rceil\). From a power of two its dividing line is \(T / \mathrm{elem\_max}\), which is 7/6 for E2M1. In the run, the block with 3.8 lands on 7.6 under the scale 1/2 and gets the scale 1, while the block with 3.3 lands on 6.6 and keeps the scale 1/2. This rule comes from no specification; it is MPTorch’s combination of the two before it.

Every rule’s result is kept within the scale format’s codes, and a block of zeros takes the smallest scale (code 0 for E8M0).

A rule need not stay between the two candidates. The three Four Over Six rules below may take a scale about 1.5 times \(r\).

By default scale_rounding is the rule of the scale format’s own specification: OCP for a power of two and NEAREST for a BinaryK with a mantissa. A SuperFP scale defaults to SELECTIVE, because its values below its normal binades are powers of two, where rounding to nearest clips the most (see SuperFP elements and scales). The format’s scale_rule is the rule in effect, and formats compare by it.

Scales with a mantissa, and the tensor scale#

A scale format with a mantissa (NVFP4’s E4M3, or a SuperFP) comes with a tensor scale \(S_t\) (see Tensor scales). An element is then stored as \(x_i \approx e_i\, s\, S_t\), and the scale the block asks for is measured relative to \(S_t\):

\[r = \frac{a}{\mathrm{elem\_max} \cdot S_t} .\]

The rules above choose between its two neighbours in the scale format, \(\lfloor r \rfloor\) and \(\lceil r \rceil\), as before. The chosen \(s\) stays inside the scale format: at most its largest value (448 for E4M3) and at least its smallest positive one. The block’s scale is the float32 product \(s \cdot S_t\).

By default \(S_t\) is computed from the tensor \(x\) itself:

\[S_t = \frac{\max|x|}{\mathrm{elem\_max} \cdot \mathrm{scale\_max}} ,\]

where scale_max is the scale format’s largest value, so \(S_t = \max|x| / (6 \cdot 448)\) for NVFP4. The block that holds the tensor’s largest magnitude then asks for exactly scale_max. It takes the largest scale and every other block a smaller one, so the scale format’s whole range lies below the tensor’s largest block. This is the NVFP4 paper’s choice (Appendix B.1 writes its reciprocal, the “global encode scale” \(6 \cdot 448 / \max|x|\)). Passing tensor_scale= gives a fixed value instead.

That range is finite. A block gets a scale of its own only while the scale it asks for is at least the scale format’s smallest positive value, \(s_{\min}\):

\[r \ge s_{\min} \quad\Longleftrightarrow\quad a \;\ge\; \mathrm{elem\_max} \cdot s_{\min} \cdot S_t \;=\; \max|x| \cdot \frac{s_{\min}}{\mathrm{scale\_max}} ,\]

where the last step uses the default \(S_t\). For E4M3, \(s_{\min} = 2^{-9}\) and scale_max is 448, so a block’s largest magnitude may be up to \(448 \cdot 2^{9} \approx 2.3 \cdot 10^{5}\) times smaller than the tensor’s. A block smaller than that still takes \(s_{\min}\). Its largest element then lands at \(\mathrm{elem\_max} \cdot r / s_{\min}\), below elem_max, and its elements are rounded coarsely or to zero.

With a mantissa the choice of rule matters less than with a power of two, because the two candidates are close together. In E4M3’s normal range, when NEAREST takes \(\lfloor r \rfloor\) it is at most a factor of 1.0625 below \(r\). E2M1’s top step (4 to 6) absorbs that, so SELECTIVE leaves NVFP4’s scales alone there. An element format with a finer top step (E2M3, E4M3) is clipped by that factor, and SELECTIVE gives those blocks \(\lceil r \rceil\) instead.

Four Over Six#

The rules so far all aim the block’s largest element at elem_max and choose the scale from the block’s largest magnitude alone. Four Over Six (Cook et al.) questions that aim. E2M1’s largest values are 3, 4 and 6. In a block whose largest element sits on 6, nothing between 67% and 100% of that element can be represented, and an element near 5 is off by a sixth of the block’s largest value after rounding. The paper finds that these near-maximal elements account for most of NVFP4’s quantization error (its Section 2.2). If the block’s largest element sits on 4 instead, the block gives up the value 6 but gains 3 at 75% of its largest value, and its other values are spaced more evenly.

A block therefore has a third candidate scale, and the rule chooses per block between two of the three:

  • the scale NEAREST takes, the candidate nearer to \(r\), under which the block’s largest element lands on elem_max (6 for E2M1);

  • the scale nearest to \(1.5\, r\), under which it lands on 4. In general the factor is elem_max over the largest power of two not above it, so 1.875 for E2M3 (7.5 and 4).

The rule quantizes the block under both scales in the call’s rounding mode, decodes both results, and measures each one’s error against the block’s original values. Let \(\hat{x}^{(6)}_i\) and \(\hat{x}^{(4)}_i\) be the decoded values under the first and the second scale, and \(E^{(6)}\), \(E^{(4)}\) their errors. The block takes the second scale if

\[E^{(4)} < E^{(6)} ,\]

and keeps the first otherwise, including on a tie. There are three rules, one per error measure, and the paper reports which worked best where:

FOUR_OVER_SIX_MSE

The sum of squared errors, \(E^{(k)} = \sum_i \big(\hat{x}^{(k)}_i - x_i\big)^2\). Best in most of the paper’s post-training quantization experiments (its Section 3.1).

FOUR_OVER_SIX_MAE

The sum of absolute errors, \(E^{(k)} = \sum_i \big|\hat{x}^{(k)}_i - x_i\big|\). Better than MSE in its pre-training experiments (its Appendix A.1).

FOUR_OVER_SIX_ABS_MAX

The largest absolute error of the block, \(E^{(k)} = \max_i \big|\hat{x}^{(k)}_i - x_i\big|\).

In the paper’s example (its Table 2, and the run below), the block \([10, 20, 30, 40]\) has the scale 6.5 under NEAREST and decodes as \([9.75, 19.5, 26, 39]\). Its second candidate is the scale 10, under which it is exact, so every measure takes it.

Four things are specific to these rules:

  • The scale format needs a mantissa. E4M3 can hold two scales a factor of 1.5 apart and E8M0 cannot, so a Four Over Six rule on a power-of-two scale raises. The paper has the same limit: the method does not apply to MXFP4 (its Section 5.2).

  • The default tensor scale changes. It gives the tensor’s largest block the scale 256 instead of 448, so that this block also has a second candidate: 256 is the largest scale whose multiple by 1.5 is still an E4M3 value (384). This follows the paper’s Appendix A.2. The format’s top_scale is that scale.

  • Errors are counted in fixed point. In the sums above, each \(|\hat{x}^{(k)}_i - x_i|\) is first truncated to a multiple of \(2^{\lfloor \log_2 a \rfloor - 22}\), at most a four millionth of the block’s largest magnitude, and the measure is added up in integers. A block’s error is then exact. The CPU and a GPU add the elements up in different orders, and with exact errors they always choose the same scale; with a sum of floats they could differ at a near tie.

  • Stochastic rounding uses one draw per element. Under SR both candidates round an element with the same random draw, the one the element is stored with. The choice is made on the rounded values, as in the paper. The paper notes that this favours the smaller error and so reintroduces a bias (its Appendix A.3).

The rule rounds every element a second time in each block whose two scales differ. On a CPU, block_quantize takes about 2.2 times as long as under NEAREST. For pre-training the paper recommends the rule for activations only (its Appendix A.4).

With 2D tiles (below) the block is the whole tile. The tile has one pair of candidate scales, from its largest magnitude; the error is taken over all of its elements; and it makes one choice. The paper’s reference implementation does the same for 16 x 16 tiles (its block_scale_2d). Since the errors are integers, the choice does not depend on the order in which they are added up, and a square tile makes the same choice whichever axis the tensor is packed along.

Rounding the elements#

Each element is divided by its block’s scale. The division is exact for a power of two and is done in float32 for a scale with a mantissa. The quotient is rounded by the element format’s cast (a BinaryK’s or a SuperFP’s) in the call’s rounding mode, under SaturationMode.SAT_FINITE, and then clamped to elem_max. With \(Q\) for that cast and \(\sigma\) for the block’s scale (\(s\), or \(s\, S_t\) for a scale with a mantissa):

\[e_i = \operatorname{sign}(x_i) \cdot \min\!\big( |Q(x_i / \sigma)|,\ \mathrm{elem\_max} \big) .\]

Every value above elem_max lands on it, in every rounding mode. The rounding mode applies to the elements only; the rule for the scale never depends on it.

The clamp is where OCP’s element formats differ from P3109’s. As a P3109 format, E4M3 has the largest finite value 480, but OCP spends that code on NaN. MXFP8_E4M3 therefore has elem_max=448.0 and nan_code=0x7F.

Decoding, and the special values#

Decoding an element is one float32 product, its value times its block’s scale:

\[\hat{x}_i = e_i\, \sigma, \qquad \sigma = s \ \text{ for a power-of-two scale}, \quad \sigma = s\, S_t \ \text{ for a scale with a mantissa},\]

where \(s\, S_t\) is itself a float32 product, computed once per block. The product \(e_i\, \sigma\) is exact for every OCP format. Two rules hold for every block format:

  • Non-finite values. An infinity saturates to elem_max. With an E8M0 scale its block takes the largest scale, \(2^{127}\). Since \(448 \cdot 2^{127}\) is past binary32, the element decodes to an infinity again. A NaN takes the element’s NaN code when the format has one (E4M3, E5M2). Otherwise the block’s scale becomes the scale’s NaN and the whole block decodes to NaN; for a 2D tile (below) that is up to 16,384 elements. With neither a NaN code nor a scale, a NaN becomes elem_max and is lost. The OCP specification leaves the conversion of a NaN to the implementation for the formats without a NaN code (Sections 5.3.2 and 5.3.3); these are MPTorch’s choices.

  • One zero. An element code with only its sign bit set is OCP’s \(-0\). MPTorch never writes it and reads it as \(+0\), so no block op returns -0.0, like every other cast in the library.

Quantizing twice#

Quantizing an already quantized tensor does not always return it unchanged, because the second pass chooses its scales from the rounded values:

  • With a power-of-two scale, OCP, UP and SELECTIVE change nothing the second time.

  • NEAREST with a power-of-two scale can move values. If the largest element was rounded down, the block now asks for a smaller scale, which can round to the next power of two down. Under that scale the element saturates.

  • UP with a mantissa scale can also move values, and so can any rule with a mantissa scale when the element format is finer than E2M1.

  • A Four Over Six rule changes nothing the second time on NVFP4. A block comes back with its largest element on the value its scale was chosen for, and under that scale it has no error at all.

The run#

The first four lines of the output show the example block above (largest magnitude 3.8, \(\rho = 1.27\)) and a second block whose largest magnitude is 3.3, so \(\rho = 1.1\). That is below every rule’s dividing line except UP’s. Under the scale 1/2 its largest element is 6.6, which rounds to 6 without being clipped, so only UP gives this block the scale 1. The table after them is the mean relative error of a block under each rule, over Gaussian blocks of every magnitude.

The last part is Four Over Six on NVFP4. It shows the paper’s block under NEAREST and under FOUR_OVER_SIX_MSE. Then, over Gaussian blocks, it shows how often each measure takes the second scale and the mean relative error that leaves, next to NEAREST’s. The same table follows for 16 x 16 tiles of Gaussian values. A tile of 256 such values has most of them far below its largest, where the first scale’s grid is the finer one, so the MSE and MAE measures rarely take the second scale there; the last column says that a tile’s choice is the same along either axis.

docs/snippets/block_scale_rounding.py#
"""How a block's scale is chosen: the ScaleRounding rules."""

import dataclasses

import torch

from mptorch import E2M1, MXFP4_E2M1, MXFP6_E2M3, NVFP4, BlockFormat, ScaleRounding, SuperFP
from mptorch.quant import block_pack, block_quantize, block_unpack

# The four rules that take one of the two scales around the one a block asks for.
R = ScaleRounding
BRACKET = (R.OCP, R.NEAREST, R.UP, R.SELECTIVE)

# Two MXFP4 blocks. The first one's largest magnitude, 3.8, is 7.6 at the
# scale 1/2, past E2M1's 6; the second one's, 3.3, is 6.6 there, which rounds
# to 6 anyway.
x = torch.zeros(2, 32)
x[0, :3] = torch.tensor([3.8, -1.3, 0.3])
x[1, :3] = torch.tensor([3.3, -1.3, 0.3])
for rule in BRACKET:
    fmt = dataclasses.replace(MXFP4_E2M1, scale_rounding=rule)
    scales = (2.0 ** (block_pack(x, fmt).scales[:, 0].double() - 127)).tolist()
    q = block_quantize(x, fmt)[:, :3].tolist()
    print(f"{rule.name:<9}  scales {scales}  blocks {q[0]}  {q[1]}")

# Each scale's default rule, and what the four cost over many blocks: the mean
# relative error of a block, over Gaussian blocks of every magnitude.
sfp = BlockFormat(E2M1, SuperFP(3, 4, 2, 7), 32)
print("\ndefaults:", MXFP4_E2M1.scale_rule.name, NVFP4.scale_rule.name, sfp.scale_rule.name)
torch.manual_seed(0)
x = torch.randn(20000, 32) * torch.exp2(torch.rand(20000, 1) * 30 - 15)
print(f"\n{'':<22}" + "".join(f"{r.name:>11}" for r in BRACKET))
for name, base in (
    ("MXFP4_E2M1", MXFP4_E2M1),
    ("MXFP6_E2M3", MXFP6_E2M3),
    ("E2M1, SuperFP scale", sfp),
):
    row = []
    for rule in BRACKET:
        if rule is ScaleRounding.OCP and base.has_tensor_scale:
            row.append(f"{'-':>11}")  # OCP is a power-of-two scale's rule
            continue
        q = block_quantize(x, dataclasses.replace(base, scale_rounding=rule))
        err = ((q - x).norm(dim=1) / x.norm(dim=1)).mean().item()
        row.append(f"{err:>11.4f}")
    print(f"{name:<22}" + "".join(row))

# Four Over Six, on NVFP4: a block may instead take the scale 1.5 times larger,
# under which its largest element lands on 4 and not on 6, if that gives it
# the smaller error. The block of the paper's Table 2, under each choice.
x = torch.zeros(1, 16)
x[0, :4] = torch.tensor([10.0, 20.0, 30.0, 40.0])
print()
for rule in (R.NEAREST, R.FOUR_OVER_SIX_MSE):
    p = block_pack(x, dataclasses.replace(NVFP4, scale_rounding=rule), tensor_scale=1.0)
    scale = p.scales.view(torch.float8_e4m3fn).float().item()
    print(f"{rule.name:<18} scale {scale:<5} block {block_unpack(p)[0, :4].tolist()}")

# Over many blocks: how often each measure takes the second scale, and the
# mean relative error of a block.
torch.manual_seed(0)
x = torch.randn(20000, 16) * torch.exp2(torch.rand(20000, 1) * 8 - 4)
nearest = block_pack(x, NVFP4)
print(f"\n{'NVFP4':<22}{'takes 4':>9}{'error':>9}")
for rule in (R.NEAREST, R.FOUR_OVER_SIX_MSE, R.FOUR_OVER_SIX_MAE, R.FOUR_OVER_SIX_ABS_MAX):
    fmt = dataclasses.replace(NVFP4, scale_rounding=rule)
    p = block_pack(x, fmt, tensor_scale=nearest.tensor_scale)
    took = (p.scales != nearest.scales).float().mean().item()
    err = ((block_unpack(p) - x).norm(dim=1) / x.norm(dim=1)).mean().item()
    print(f"{rule.name:<22}{took:>9.1%}{err:>9.4f}")
print("default tensor scale: NVFP4's block of the largest value takes the scale", end=" ")
print(NVFP4.top_scale, "and Four Over Six's", fmt.top_scale)

# On 2D tiles the block is the tile: one choice, from all 256 of its elements.
# A square tile makes it the same way whichever axis the matrix is packed along.
torch.manual_seed(0)
w = torch.randn(20, 20, 16, 16) * torch.exp2(torch.rand(20, 20, 1, 1) * 8 - 4)
w = w.permute(0, 2, 1, 3).reshape(320, 320)
tiled = dataclasses.replace(NVFP4, block_rows=16)
nearest = block_pack(w, tiled)
print(f"\n{'NVFP4, 16 x 16 tiles':<22}{'takes 4':>9}{'error':>9}   same along both axes")
for rule in (R.NEAREST, R.FOUR_OVER_SIX_MSE, R.FOUR_OVER_SIX_MAE, R.FOUR_OVER_SIX_ABS_MAX):
    fmt = dataclasses.replace(tiled, scale_rounding=rule)
    ts = nearest.tensor_scale
    p = block_pack(w, fmt, tensor_scale=ts)
    took = (p.scales != nearest.scales).float().mean().item()
    diff = (block_unpack(p) - w).reshape(20, 16, 20, 16).permute(0, 2, 1, 3).reshape(400, 256)
    ref = w.reshape(20, 16, 20, 16).permute(0, 2, 1, 3).reshape(400, 256)
    err = (diff.norm(dim=1) / ref.norm(dim=1)).mean().item()
    same = torch.equal(
        block_quantize(w, fmt, 0, tensor_scale=ts), block_quantize(w, fmt, 1, tensor_scale=ts)
    )
    print(f"{rule.name:<22}{took:>9.1%}{err:>9.4f}   {same}")
output#
OCP        scales [0.5, 0.5]  blocks [3.0, -1.5, 0.25]  [3.0, -1.5, 0.25]
NEAREST    scales [0.5, 0.5]  blocks [3.0, -1.5, 0.25]  [3.0, -1.5, 0.25]
UP         scales [1.0, 1.0]  blocks [4.0, -1.5, 0.5]  [3.0, -1.5, 0.5]
SELECTIVE  scales [1.0, 0.5]  blocks [4.0, -1.5, 0.5]  [3.0, -1.5, 0.25]

defaults: OCP NEAREST SELECTIVE

                              OCP    NEAREST         UP  SELECTIVE
MXFP4_E2M1                 0.1142     0.1255     0.1158     0.1113
MXFP6_E2M3                 0.0280     0.0651     0.0280     0.0278
E2M1, SuperFP scale             -     0.1246     0.1152     0.1107

NEAREST            scale 6.5   block [9.75, 19.5, 26.0, 39.0]
FOUR_OVER_SIX_MSE  scale 10.0  block [10.0, 20.0, 30.0, 40.0]

NVFP4                   takes 4    error
NEAREST                    0.0%   0.0937
FOUR_OVER_SIX_MSE         45.4%   0.0862
FOUR_OVER_SIX_MAE         33.8%   0.0873
FOUR_OVER_SIX_ABS_MAX     60.1%   0.0884
default tensor scale: NVFP4's block of the largest value takes the scale 448.0 and Four Over Six's 256.0

NVFP4, 16 x 16 tiles    takes 4    error   same along both axes
NEAREST                    0.0%   0.1117   True
FOUR_OVER_SIX_MSE          3.2%   0.1116   True
FOUR_OVER_SIX_MAE          0.0%   0.1117   True
FOUR_OVER_SIX_ABS_MAX     85.0%   0.1236   True

SuperFP elements and scales#

A SuperFP element or scale spends the codes that a binaryK spends on subnormals, and more, on powers of two below its normal binades: the supernormals.

  • As a block element, it trades the uniform steps near the top of a block for reach at the bottom. Small elements of a block with a wide spread survive where E2M1 flushes them to zero.

  • As a scale, it reaches far below E4M3’s \(2^{-9}\) in the same byte.

Its codes follow the format’s own layout: zero, then the supernormals from code 1, then the normal binades as in a binaryK. It rounds by the superfp casts, so a tie between two supernormals goes to the power of two with an even exponent, as in superfp_quantize(). A superfp scale is cast like E4M3 and multiplied by a tensor scale, and its all-ones code is NaN. Its default rule is ScaleRounding.SELECTIVE, because below its normal binades a superfp scale holds only powers of two, and rounding such a scale to nearest can clip a block’s largest element by up to a third. The paragraph after the run gives the details.

docs/snippets/block_superfp.py#
"""Block formats over SuperFP: supernormal elements, and a superfp scale."""

import torch

from mptorch import E2M1, E8M0, MXFP4_E2M1, NVFP4, BlockFormat, SuperFP
from mptorch.quant import BlockPacked, block_quantize, block_unpack

# A 4-bit superfp element: one normal binade (4, 6) and, below it, the powers
# of two down to 1/8. Codes 0..7 decode to its whole value set:
sfp4 = BlockFormat(SuperFP(1, 2, 1, 1), E8M0, 32)
codes = torch.tensor([[0x10, 0x32, 0x54, 0x76] * 4], dtype=torch.uint8)
one = BlockPacked(
    codes, torch.tensor([[127]], dtype=torch.uint8), sfp4, (1, 32), 1, 1.0, torch.float32
)
print("SuperFP(1, 2, 1, 1):", block_unpack(one)[0, :8].tolist())
print("E2M1:               ", [0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0])

# The same budget of bits spent differently: E2M1 has uniform steps near the
# top of a block, superfp has range at the bottom. On a block with a wide
# spread of magnitudes, superfp keeps the small ones:
torch.manual_seed(0)
x = torch.randn(256, 32) * torch.logspace(-3, 0, 32)
for name, fmt in (("MXFP4_E2M1", MXFP4_E2M1), ("SuperFP(1, 2, 1, 1)", sfp4)):
    q = block_quantize(x, fmt)
    zeros = (q == 0).float().mean().item()
    err = ((q - x).norm() / x.norm()).item()
    print(f"{name:20s} relative error {err:.3f}, flushed to zero {zeros:.0%}")

# A superfp scale: cast to nearest even like E4M3, times a tensor scale, but
# reaching down to 2^-104 in one byte where E4M3 stops at 2^-9. A block of
# values around 2^-66 keeps them; under NVFP4's E4M3 scale it flushes to zero.
sfp_scaled = BlockFormat(E2M1, SuperFP(3, 4, 2, 7), 16)
tiny = torch.tensor([[1.0, 3.0, -2.0, 6.0] * 4]) * 2.0**-66
for name, fmt in (("E4M3 scale (NVFP4)", NVFP4), ("SuperFP(3, 4, 2, 7) scale", sfp_scaled)):
    q = block_quantize(tiny, fmt, tensor_scale=1.0)
    print(f"{name:26s} decoded / 2^-66: {(q / 2.0**-66)[0, :4].tolist()}")
output#
SuperFP(1, 2, 1, 1): [0.0, 0.125, 0.25, 0.5, 1.0, 2.0, 4.0, 6.0]
E2M1:                [0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0]
MXFP4_E2M1           relative error 0.137, flushed to zero 64%
SuperFP(1, 2, 1, 1)  relative error 0.156, flushed to zero 44%
E4M3 scale (NVFP4)         decoded / 2^-66: [0.0, 0.0, 0.0, 0.0]
SuperFP(3, 4, 2, 7) scale  decoded / 2^-66: [1.0, 3.0, -2.0, 6.0]

Rounding a scale to nearest costs more here. Below its normal binades a superfp scale holds only powers of two, so the nearest scale can be a factor of 1.5 below \(a / \mathrm{elem\_max}\). Take a block whose ratio is 0.35:

  • Under NEAREST it gets the scale 0.25. Its largest element is 8.4 in E2M1’s units, saturates to 6, and decodes 29% low (33% at worst).

  • Under SELECTIVE it gets 0.5, because 8.4 is past 7, and the element decodes 5% low.

E4M3’s subnormals, below \(2^{-6}\), behave the same way, and NVFP4’s tensor scale keeps blocks away from them. The block GEMM decodes superfp operands like any others, so their element codes are at most 8 bits there too (see Block matrix products).

Block floating point#

A FixedPoint element gives block floating point: integer elements that share an exponent. bfp() builds the usual shape, FixedPoint(bits, bits - 2, symmetric=True) elements with an E8M0 scale. An element has a sign and bits - 1 magnitude bits, one step of \(2^{-(\text{bits} - 2)}\) from zero to its largest value, \(2 - 2^{-(\text{bits} - 2)}\). So emax is 0, and OCP’s rule gives a block the scale \(2^{\lfloor \log_2 a \rfloor}\) for its largest magnitude \(a\).

  • Signed and symmetric only. A block code is sign-magnitude. It has no code for a two’s complement format’s bottom, \(-2^{\,n-\text{fl}}\), and an unsigned element would lose its top code. Both raise. Any other fl gives the same block values and only moves emax, and any scale works, a cast one such as E4M3 included.

  • One grid. The kernels decode and round the element as the binaryK layout its integer code is: one exponent bit, \(n - 1\) mantissa bits and bias \(2 - n + \text{fl}\), whose exponent field 0 holds the codes below \(2^{n-1}\) and field 1 the rest, one step apart. No kernel has a fixed-point arm. A quantized block is therefore fixedpoint_quantize() of each element over the block’s scale, times that scale, in every deterministic mode, as the run shows.

  • Stochastic rounding goes through binaryK’s cast on that layout. It is exact on the upper half of the element’s range (field 1, rounded on the word). On the lower half (field 0, binaryK’s SUBNORMALS arm) it adds a power of two in the carrier first, so a probability can be one step of \(2^{-N}\) off just under a level (Stochastic rounding). fixedpoint_quantize() itself is exact.

  • The block GEMM takes element codes of up to 8 bits, so bfp(2) to bfp(8), paired with any block format. bfp(9) to bfp(16) pack, unpack and quantize only.

  • The carrier holds the element to the fixed-point rule (FixedPoint: one step across the range), its stochastic-rounding bits included.

docs/snippets/block_bfp.py#
"""Block floating point: fixed-point elements sharing a power-of-two scale."""

import torch

from mptorch import MXFP8_E4M3, BlockFormat, FixedPoint, RoundMode, bfp
from mptorch.quant import block_matmul, block_pack, block_quantize, fixedpoint_quantize

torch.manual_seed(0)
torch.set_printoptions(precision=6)

f = bfp(8)  # FixedPoint(8, 6, symmetric=True) elements, an E8M0 scale, blocks of 16
print("element:", f.elem)
print(f"elem_max {f.elem_max}, emax {f.emax}, {f.bytes_per_block} bytes of codes a block")

# A block is the elementwise fixed-point cast of each element over the
# block's scale, 2**floor(log2(amax)), times that scale.
x = torch.randn(1, 16) * 3
scale = torch.exp2(torch.floor(torch.log2(x.abs().max())))
print("\nscale           ", scale.item())
print("block_quantize  ", block_quantize(x, f)[0, :4])
print("fixedpoint * s  ", (fixedpoint_quantize(x / scale, 8, 6, symmetric=True) * scale)[0, :4])
print(
    "equal in every deterministic mode:",
    all(
        torch.equal(
            block_quantize(x, f, rounding=m),
            fixedpoint_quantize(x / scale, 8, 6, symmetric=True, rounding_mode=m) * scale,
        )
        for m in RoundMode
        if not m.is_stochastic
    ),
)

# The codes are sign-magnitude integers: 1.5 is 96 (= 1.5 * 2**6), -0.5 is
# 0x80 | 32. OCP's MXINT8 is two's complement, with one more code, -2.
v = torch.tensor([[1.5, -0.5, 1.0, 0.25] + [0.0] * 28])
print("\nbfp(8, 32) codes", block_pack(v, bfp(8, 32)).data[0, :4].tolist())

# Any signed, symmetric FixedPoint element works, under any scale; a two's
# complement or unsigned one has no sign-magnitude code for all its values.
e4m3 = BlockFormat(FixedPoint(8, 6, symmetric=True), MXFP8_E4M3.elem, 16)
print("\nan E4M3 scale:  ", e4m3.scale_rule.name, "rounding")
try:
    BlockFormat(FixedPoint(8, 6), f.scale, 16)
except ValueError as e:
    print("two's complement:", str(e).split(": ")[0])

# The block GEMM multiplies codes of up to 8 bits, so bfp(2) to bfp(8), in any
# pairing; wider ones pack, unpack and quantize only.
a, b = torch.randn(4, 64), torch.randn(64, 3)
pa, pb = block_pack(a, bfp(8, 32), axis=-1), block_pack(b, MXFP8_E4M3, axis=-2)
print("\nbfp8 x MXFP8:\n", block_matmul(pa, pb))
print("their decoded product, in float64:\n", (pa.unpack().double() @ pb.unpack().double()).float())
output#
element: FixedPoint(wl=8, fl=6, is_signed=True, symmetric=True, prng_bits=0)
elem_max 1.984375, emax 0, 16 bytes of codes a block

scale            4.0
block_quantize   tensor([-3.375000, -3.437500, -0.750000, -1.312500])
fixedpoint * s   tensor([-3.375000, -3.437500, -0.750000, -1.312500])
equal in every deterministic mode: True

bfp(8, 32) codes [96, 160, 64, 16]

an E4M3 scale:   NEAREST rounding
two's complement: a FixedPoint block element must be signed and symmetric, got FixedPoint(wl=8, fl=6, is_signed=True, symmetric=False, prng_bits=0)

bfp8 x MXFP8:
 tensor([[ -5.216736,   4.229614,  -7.110840],
        [ -4.395020,   6.504761,  -1.796387],
        [  0.992920, -13.446533,   0.986694],
        [  8.714096,  10.942261,   1.706543]])
their decoded product, in float64:
 tensor([[ -5.216736,   4.229614,  -7.110840],
        [ -4.395020,   6.504761,  -1.796387],
        [  0.992920, -13.446533,   0.986694],
        [  8.714096,  10.942261,   1.706543]])

2D tiles#

With block_rows > 1 a scale is shared by a tile of block_rows rows of block_size elements. The rows run along the axis before the packed one, never across a batch dimension. A tile changes only where the scale comes from: the codes and their layout are the 1D format’s, and scales has one row per tile. Two examples:

  • dataclasses.replace(NVFP4, block_rows=16) is NVFP4 with 16 x 16 tiles, the weight format of NVIDIA’s NVFP4 pretraining recipe (which scales activations and gradients 1 x 16).

  • 128 x 128 tiles are DeepSeek-V3’s weight blocking, here with an E8M0 scale (a scale is one byte).

A square tile covers the same elements whichever of a matrix’s two axes is packed, so it quantizes the matrix to the same values either way, in every deterministic rounding mode and under every scale rule, the Four Over Six rules included. One packed weight can therefore serve both a layer’s forward pass and its input gradient, which reads the weight transposed. A 1D block runs along one axis only and quantizes the two orientations differently. A matrix product needs its operands blocked along the dimension it sums over, because only then can each block’s scales be factored out of that block’s part of the sum, which is how block-format hardware computes it (see Block matrix products, “Why the blocks run along K”).

docs/snippets/block_tiles.py#
"""2D tiles: one scale per block_rows x block_size tile, and why a square one
quantizes a matrix the same along either axis."""

import dataclasses

import torch

from mptorch import NVFP4
from mptorch.quant import block_pack, block_quantize

torch.manual_seed(0)
w = torch.randn(64, 96)

w16 = dataclasses.replace(NVFP4, block_rows=16)  # NVFP4 with 16 x 16 weight tiles
p = block_pack(w, w16)
print("scales", tuple(p.scales.shape), " bytes/elem", round(p.nbytes / w.numel(), 3))

# Packed along either axis, a square tile covers the same 16 x 16 elements
# and takes the same scale, so the values agree; a 1D block does not.
print(
    "16 x 16 tiles, axis 0 == axis 1:",
    torch.equal(block_quantize(w, w16, 0), block_quantize(w, w16, 1)),
)
print(
    "1 x 16 blocks, axis 0 == axis 1:",
    torch.equal(block_quantize(w, NVFP4, 0), block_quantize(w, NVFP4, 1)),
)

# The transpose is free: .mT relabels the same codes
print("mT shares the codes:", p.mT.data.data_ptr() == p.data.data_ptr(), p.mT.shape, p.mT.axis)
output#
scales (4, 6)  bytes/elem 0.504
16 x 16 tiles, axis 0 == axis 1: True
1 x 16 blocks, axis 0 == axis 1: False
mT shares the codes: True (96, 64) 0

Using block formats#

Two other pages cover how block formats are used:

  • Quantizers, in its section “Block quantization and packed storage”, shows the functions that round a tensor to a block format, and how its element and scale codes are packed into bytes.

  • Block matrix products shows how two block-format tensors are multiplied, including where the product applies their tensor scales.

Rounding modes#

Every quantizer and every GEMM takes a RoundMode. Let \(\lfloor x \rfloor_F\) and \(\lceil x \rceil_F\) be the nearest representable values below and above \(x\). Then \(\lfloor x \rfloor_F \le x \le \lceil x \rceil_F\), with equality when \(x\) is representable. The modes are:

mode

name

\(Q(x)\)

RNE

round to nearest, ties to even

the nearer of the two; on a tie, the one with even mantissa

RNA

round to nearest, ties away

the nearer of the two; on a tie, the larger in magnitude

RU

round up (toward \(+\infty\))

\(\lceil x \rceil_F\)

RD

round down (toward \(-\infty\))

\(\lfloor x \rfloor_F\)

RZ

round toward zero (truncate)

\(\lfloor x \rfloor_F\) if \(x > 0\), \(\lceil x \rceil_F\) if \(x < 0\)

RO

round to odd

\(x\) if representable; else the neighbour with odd mantissa

SR

stochastic rounding (StochasticA)

\(\lceil x \rceil_F\) with probability \(\Pr(\text{up})\), else \(\lfloor x \rfloor_F\)

SR_B

stochastic rounding (StochasticB)

the same, with the probability read another way (below)

SR_C

stochastic rounding (StochasticC)

the same, with the probability read a third way (below)

RNE is the default of IEEE arithmetic and is unbiased on average. RZ is what cheap hardware does, and it is biased toward zero. RO is not a mode to compute in. Its use is in two-step rounding: rounding to odd at an intermediate width and then to nearest at the final one avoids the double rounding error that two nearest roundings can make. The GEMMs use it that way: carrier_rounding=RoundMode.RO rounds each mac step to odd in the carrier so that the format’s cast rounds the exact value (Dot-product arithmetic, “What the carrier rounds”).

docs/snippets/rounding_modes.py#
"""The seven rounding modes on the same inputs (Binary8p4: 3 mantissa bits)."""

import torch

from mptorch import BinaryK, RoundMode
from mptorch.quant import Quant

torch.manual_seed(0)
f = BinaryK(8, 4)

# In [1, 2) the representable values are 1, 1.125, 1.25, ... (spacing 1/8),
# so 1.0625 and 1.1875 are exact ties and 1.1 / 1.3 are not.
x = torch.tensor([1.0625, 1.1875, 1.1, 1.3, -1.0625, -1.1, 2.71828, -2.71828])
print(f"{'input':<6}", [f"{v:8.4f}" for v in x.tolist()])
for mode in RoundMode:
    y = Quant(f, mode)(x)
    print(f"{mode.name:<6}", [f"{v:8.4f}" for v in y.tolist()])

# The stochastic modes draw their random bits from the *format's* prng_bits.
# The format above has prng_bits=0, so they are deterministic there: SR is
# truncation (the RZ row), SR_B rounds to nearest with ties away (the RNA row)
# and SR_C to nearest with ties toward zero. Give the format some random bits
# and the same input rounds differently per draw.
f_sr = BinaryK(8, 4, prng_bits=8)
for draw in range(3):
    y = Quant(f_sr, RoundMode.SR)(x)
    print(f"SR #{draw} ", [f"{v:8.4f}" for v in y.tolist()])
output#
input  ['  1.0625', '  1.1875', '  1.1000', '  1.3000', ' -1.0625', ' -1.1000', '  2.7183', ' -2.7183']
RNE    ['  1.0000', '  1.2500', '  1.1250', '  1.2500', ' -1.0000', ' -1.1250', '  2.7500', ' -2.7500']
RNA    ['  1.1250', '  1.2500', '  1.1250', '  1.2500', ' -1.1250', ' -1.1250', '  2.7500', ' -2.7500']
RU     ['  1.1250', '  1.2500', '  1.1250', '  1.3750', ' -1.0000', ' -1.0000', '  2.7500', ' -2.5000']
RD     ['  1.0000', '  1.1250', '  1.0000', '  1.2500', ' -1.1250', ' -1.1250', '  2.5000', ' -2.7500']
RZ     ['  1.0000', '  1.1250', '  1.0000', '  1.2500', ' -1.0000', ' -1.0000', '  2.5000', ' -2.5000']
RO     ['  1.1250', '  1.1250', '  1.1250', '  1.3750', ' -1.1250', ' -1.1250', '  2.7500', ' -2.7500']
SR     ['  1.0000', '  1.1250', '  1.0000', '  1.2500', ' -1.0000', ' -1.0000', '  2.5000', ' -2.5000']
SR_B   ['  1.1250', '  1.2500', '  1.1250', '  1.2500', ' -1.1250', ' -1.1250', '  2.7500', ' -2.7500']
SR_C   ['  1.0000', '  1.1250', '  1.1250', '  1.2500', ' -1.0000', ' -1.1250', '  2.7500', ' -2.7500']
SR #0  ['  1.1250', '  1.2500', '  1.1250', '  1.2500', ' -1.0000', ' -1.1250', '  2.7500', ' -2.7500']
SR #1  ['  1.1250', '  1.1250', '  1.1250', '  1.2500', ' -1.1250', ' -1.1250', '  2.7500', ' -2.7500']
SR #2  ['  1.1250', '  1.1250', '  1.1250', '  1.3750', ' -1.1250', ' -1.0000', '  2.7500', ' -2.7500']

Stochastic rounding#

Under SR the rounding direction is random, with a probability that depends on where \(x\) sits between its two neighbours. Let \(f = (x - \lfloor x \rfloor_F) / (\lceil x \rceil_F - \lfloor x \rfloor_F) \in [0, 1)\) be that fraction. The ideal rule is \(\Pr(\text{up}) = f\), which makes the rounding unbiased: \(\mathbb{E}[Q(x)] = x\).

P3109 defines three stochastic modes, which read \(N\) random bits (prng_bits) three ways. Let \(\eta\) be the fraction of \(|x|\) between its two neighbours (\(\eta = f\) when \(x > 0\)), \(R\) a uniform integer in \([0, 2^N)\) and \(X = \eta 2^N\). The magnitude rounds away from zero when:

mode

P3109

rounds away iff

\(\Pr(\text{away})\)

SR (SR_A)

StochasticA

\(\lfloor X \rfloor + R \ge 2^N\)

\(\lfloor X \rfloor / 2^N\)

SR_B

StochasticB

\(\lfloor 2X \rfloor + 2R + 1 \ge 2^{N+1}\)

\(\lfloor X + 1/2 \rfloor / 2^N\)

SR_C

StochasticC

\(\mathrm{RNITE}(X) + R \ge 2^N\)

\(\mathrm{RNITE}(X) / 2^N\)

RNITE rounds to the nearest integer, ties to even. Each mode quantizes the ideal probability \(\eta\) to steps of \(2^{-N}\). StochasticA truncates it, which biases a value toward zero by less than one step. StochasticB and C round it to nearest, so they are off by at most half a step either way; they differ only at an exact half. All three tend to \(\eta\) as \(N\) grows.

prng_bits is set on the format (BinaryK(8, 4, prng_bits=8)) and is ignored by the deterministic modes. Three consequences of the definitions:

  • With prng_bits=0 nothing is random. SR is RZ, SR_B is RNA, and SR_C rounds to nearest with ties toward zero. The SR row above comes from a format with no random bits and is identical to the RZ row.

  • The format’s mantissa plus its random bits must fit in the carrier’s mantissa: 23 bits in binary32, 52 in binary64. Each call checks this. A FixedPoint format’s magnitude bits plus its random bits must fit the carrier’s precision, 24 bits or 53. At that bound the carrier holds no bit below the random ones, and SR_B and SR_C are SR.

  • The definition holds in every region of every format, with the region’s own two neighbours:

    • a BinaryK’s normal binades and its subnormals;

    • the floor of NORMALS and EXTENDED_NORMALS, between zero and the smallest value;

    • a SuperFP’s supernormal binades, and the region below its smallest value;

    • FixedPoint everywhere.

    The casts compute it on the input’s word with integers, so nothing is rounded in the carrier first, and the random bits are the same \(N\) bits everywhere.

  • One exception, in formats that already warn that the carrier cannot place their bottom. In a SuperFP whose smallest value is itself a carrier subnormal, and in a P = 1 format whose floor is \(2^{-126}\) (\(2^{-1022}\)) and whose random bits fill the carrier’s mantissa, the floor’s draw step can be finer than the carrier’s subnormal spacing. A carrier subnormal below the floor then always rounds up to it, where the definition would round up with probability \(|x| / x_{\min}\). Inputs at or above the floor are unaffected. Computing the exact probability there cost the CUDA stochastic GEMMs 6–8% for every format, so the casts do not.

A float64 operand is rounded in binary64, and its bits are drawn there too, two random words per draw.

The random streams are seeded from PyTorch’s default generator, so torch.manual_seed makes a stochastic run reproducible. In a GEMM each output element has its own stream, keyed on its position, so the result does not depend on how the work is split across threads.

docs/snippets/rounding_stochastic.py#
"""Stochastic rounding: unbiased in expectation, and why that matters."""

import warnings

import torch

from mptorch import BinaryK, FormatRangeWarning, RoundMode
from mptorch.quant import Quant

torch.manual_seed(0)

# 1. The probability of rounding up follows the residual. 0.3 sits between
#    the Binary8p4 neighbours 0.28125 and 0.3125, 60% of the way up. Each of
#    P3109's three stochastic modes reads prng_bits random bits its own way.
x = torch.full((1_000_000,), 0.3)
lo, hi = 0.28125, 0.3125
modes = (RoundMode.SR, RoundMode.SR_B, RoundMode.SR_C)
print("P(round up) over 1e6 draws")
print("prng_bits" + "".join(f"{m.name:>9}" for m in modes))
for prng_bits in (1, 2, 3, 4, 8, 16):
    row = f"{prng_bits:>9}"
    for mode in modes:
        q = Quant(BinaryK(8, 4, prng_bits=prng_bits), mode)(x)
        row += f"{(q == hi).float().mean().item():>9.4f}"
    print(row)
print(f"{'exact':>9}" + f"{(0.3 - lo) / (hi - lo):>9.4f}" * 3)

# 2. Accumulating small increments. In Binary16p8 (bfloat16's field widths: 8
#    exponent, 7 mantissa bits) the spacing just above 1 is 2**-7 = 0.0078, so adding
#    0.001 to 1.0 and rounding to nearest gives back 1.0 -- forever. Rounding
#    stochastically moves up with probability 0.001 / 0.0078 each step.
# An 8-exponent-bit binaryK reaches below 2**-126, where the casts cannot tell
# one input from another, so a float32 call with one warns (concepts, "What
# the carrier can hold"). Nothing here goes anywhere near that small.
warnings.simplefilter("ignore", FormatRangeWarning)

binary16p8 = BinaryK(16, 8)
n_steps, batch = 2000, 1000
for mode, bits in ((RoundMode.RNE, 0), (RoundMode.SR, 8)):
    q = Quant(BinaryK(16, 8, prng_bits=bits), mode)
    acc = torch.ones(batch)  # 1000 independent accumulators
    for _ in range(n_steps):
        acc = q(acc + 0.001)
    print(f"\n1.0 + 0.001 * {n_steps} = {1 + 0.001 * n_steps:.3f}")
    print(
        f"  {mode.name}: mean over {batch} accumulators = {acc.mean().item():.4f}"
        f"  (min {acc.min().item():.4f}, max {acc.max().item():.4f})"
    )
output#
P(round up) over 1e6 draws
prng_bits       SR     SR_B     SR_C
        1   0.4996   0.5013   0.5013
        2   0.4997   0.5000   0.4997
        3   0.5002   0.6251   0.6250
        4   0.5627   0.6257   0.6253
        8   0.5978   0.6020   0.6014
       16   0.5997   0.5996   0.5995
    exact   0.6000   0.6000   0.6000

1.0 + 0.001 * 2000 = 3.000
  RNE: mean over 1000 accumulators = 1.0000  (min 1.0000, max 1.0000)

1.0 + 0.001 * 2000 = 3.000
  SR: mean over 1000 accumulators = 2.9531  (min 2.5000, max 3.4375)

The output has two parts. The table shows each mode’s probability converging to the exact fraction, 0.6, as the number of random bits grows. With one or two bits all three round up half the time. From three bits on, StochasticB and C round the fraction to the nearest step and StochasticA truncates it, which is the bias the table above describes.

The lines after the table show why the extra variance can be worth it. They add \(0.001\) to \(1.0\) two thousand times in Binary16p8, which has bfloat16’s field widths, in 1000 independent accumulators. The exact sum is 3. An accumulator whose increments are smaller than half its spacing never moves under round-to-nearest, so the RNE accumulators all stay at \(1.0\). Stochastic rounding advances the sum by the right amount on average: the SR accumulators have a mean of 2.95, and range from 2.5 to 3.44. A small weight update applied to a large weight is the same situation (see Tutorial: training in 8-bit floating point for an example).

Carriers#

Every operation is computed in a carrier, an IEEE binary float with far more precision and range than the format it simulates. There are two carriers, binary32 and binary64, and by default a tensor’s dtype picks one:

  • A float32, float16 or bfloat16 tensor is computed in binary32. A float16 or bfloat16 result is then stored back in its own dtype, which is a second rounding (see What a narrower tensor can store).

  • A float64 tensor is computed in binary64 throughout. An elementwise quantizer rounds each value once, directly. A matrix product computes every partial product and every running sum in binary64 before rounding it.

Moving a model to float64 therefore does more than widen its storage:

  • Formats that binary32 cannot hold become simulable: up to 53 bits of precision, ten exponent bits, values down to \(2^{-1021}\).

  • A value that binary32 cannot hold is rounded on its own bits, not on the nearest float32.

The two carriers agree wherever both hold every intermediate exactly. Rounding a float64 tensor of float32 values to a format binary32 holds gives exactly the float32 answer. So does a matrix product whose every product and sum is exact in binary32, which is usual once a quantizer has rounded its operands to a narrow format.

Every function and object that computes takes a carrier keyword to override the default. Its value is the torch.dtype whose arithmetic the carrier uses: torch.float64 for binary64, torch.float32 for binary32, and None (the default) for the tensor’s own.

carrier=torch.float64 gives a float32, float16 or bfloat16 tensor binary64’s arithmetic. Its operands are widened to float64, computed and rounded in binary64, and the result is narrowed back to the tensor’s dtype with a single rounding. This is bit for bit the float64 call on the widened tensor, then stored. The result keeps the tensor’s dtype either way.

A carrier is never narrower than its tensor, so carrier=torch.float32 on a float64 tensor raises: narrowing the operands would round every input once before the format does.

The keyword is taken by the quantizers (binaryK_quantize(), superfp_quantize(), Quant), the matrix products (SplitMac, FusedMac and the flat *_matmul functions) and the layer factories (binaryK_gemm_formats() and its siblings).

carrier

binary32

binary64

carrier=

torch.float32

torch.float64

tensors computed in it by default

float32, float16, bfloat16

float64

tensors that can name it

float32, float16, bfloat16

every floating dtype

precision, \(P\) (man_bits + 1)

\(\le 24\)

\(\le 53\)

stochastic bits, man_bits + prng_bits

\(\le 23\)

\(\le 52\)

random words per stochastic rounding

1

2

largest finite value

\(< 2^{128}\)

\(< 2^{1024}\)

finest step

\(2^{-149}\)

\(2^{-1074}\)

smallest value, SUBNORMALS or SuperFP

\(\ge 2^{-125}\)

\(\ge 2^{-1021}\)

smallest value, the other two modes (*)

\(\ge 2^{-126}\)

\(\ge 2^{-1022}\)

exponent bits, at P3109’s bias

\(\le 7\)

\(\le 10\)

matrix products on a consumer GPU

fastest

about 3x slower

(*) NORMALS and EXTENDED_NORMALS. The bound is one binade higher (\(2^{-125}\) and \(2^{-1021}\)) at \(P = 1\), and for EXTENDED_NORMALS at the carrier’s full precision, \(P = 24\) and \(P = 53\).

The last row is a cost worth knowing. On a GPU, binary64 arithmetic is several times slower than binary32, so a float64 model’s matrix products are too (on the CPU the two are within a few percent). A narrower tensor that names binary64 pays that cost, plus a float64 copy of each operand and a narrowed copy of the result. In the other direction the choice is one of dtype, not of carrier: a float64 model that needs only formats binary32 can carry gets binary32’s speed by being a float32 model.

The rest of this section derives the table’s bounds and says what happens to a format that exceeds them.

What the carrier can hold#

The carrier has “far more” precision and range than every format in this guide, but not than every possible format. The carrier sets a bound on the format’s parameters. A format outside that bound is quantized partially: the result is still a tensor of plausible numbers, but some of the format’s values never appear in it. There are three limits, stated here in the format’s own terms, with binary64’s in parentheses:

  • Precision. \(P \le 24\) (53) for BinaryK, man_bits <= 23 (52) for SuperFP, and at most 24 (53) magnitude bits for FixedPoint. These are the carrier’s significand bits; it cannot hold a finer grid.

  • The top. The largest finite value must be at most the carrier’s. That is \(\text{bias} \ge 2^E - 128\) (\(2^E - 1024\)), where \(E\) is the exponent width (exp_bits for a SuperFP). Above that the cast saturates at the carrier’s largest value on the format’s grid, and the codes above it are unreachable. A FixedPoint format’s ends are its saturation points, so both must be carrier values (FixedPoint: one step across the range).

  • The bottom. A subnormal carrier value has exponent field 0 whatever its magnitude. Any part of a cast that reads that field therefore cannot tell values apart below the carrier’s smallest normal, \(2^{-126}\) (\(2^{-1022}\)). The limit depends on which parts of the cast read it:

    • BinaryK’s subnormals and SuperFP’s supernormals are placed on their grid using that field. Their smallest value must be at least \(2^{-125}\) (\(2^{-1021}\)), one binade above the carrier’s smallest normal. That is \(\text{bias} + P \le 127\) (1023) for BinaryK, and \(e_{\max} - b + 2 - n \ge -125\) (\(-1021\)) for SuperFP (using the notations from SuperFP: precision at the top, range below).

    • The two non-P3109 subnormal modes, NORMALS and EXTENDED_NORMALS, find their bottom by comparing the input’s magnitude with the format’s smallest value \(x_{\min}\), which reads no field. They are exact as long as \(x_{\min}\) is at least the carrier’s smallest normal. Below that, \(x_{\min}\) is not a normal carrier value and nothing is flushed to zero at all.

    • In two cases \(x_{\min}\) must be one binade higher, at least \(2^{-125}\) (\(2^{-1021}\)). Under rounding to nearest, the comparison also needs the midpoint \(x_{\min} / 2\) between zero and \(x_{\min}\), and in these two cases the carrier cannot place it:

      • At \(P = 1\). The format has one value per binade, and the rounding before the comparison works on the exponent field. With \(x_{\min} = 2^{-126}\), the midpoint \(2^{-127}\) (\(2^{-1023}\)) is a carrier subnormal, in the exponent field that all subnormals share. The rounding reads it as a tie between two binades and returns \(x_{\min}\), where round-to-nearest-even should return zero.

      • An EXTENDED_NORMALS format at the carrier’s full precision, \(P = 24\) (53). With its lowest binade starting at \(2^{-126}\), its smallest value is \(x_{\min} = 2^{-126}\,(1 + 2^{-23})\). The midpoint, \(2^{-127}\,(1 + 2^{-23})\), needs a step of \(2^{-150}\) (\(2^{-1075}\)), which is finer than the carrier’s finest step, \(2^{-149}\) (\(2^{-1074}\)). The carrier holds \(2^{-127}\) in its place. An input of exactly \(2^{-127}\) is below the true midpoint and should round to zero, but it now looks like a tie, and round-to-nearest-away returns \(x_{\min}\).

The last two limits together mean that a simulated format may span at most 253 binades (2045). So seven exponent bits is the most either family can carry in binary32, and ten in binary64. At P3109’s default bias that is \(K - P \le 7\) (10) for a signed BinaryK and \(K - P \le 6\) (9) for an unsigned one.

The 8-bit and 6-bit formats of this guide are well inside binary32’s bounds. A format with eight exponent bits is not, whatever its bias:

  • Binary16p8 and Binary32p24 reach below binary32’s floor. The kernel pages use Binary16p8 as an accumulator and silence the warning described below.

  • The bfloat16 and float32 layouts also reach past its top.

binary64 holds all four.

The carrier depends on the tensor, not on the format, so the limits are checked on every call, against the carrier that the call rounds in. The quantizers of Quantizers, the kernels of Quantized numerical kernels and the layers built on them all do this. When a BinaryK or SuperFP is built, it checks only what neither carrier can do. The plain-integer wrappers never see a format object, and check the same thing when they resolve their format. There is one rule for both, so binaryK_matmul(a, b, mul_K=16, mul_P=8) reports what qmatmul(a, b, BinaryK(16, 8)) reports.

There are two severities. What separates them is whether the format still works, not which limit it misses:

  • A format whose range exceeds the carrier’s warns with FormatRangeWarning, naming the line that made the call. This covers a format that reaches above the carrier’s largest finite value, is spaced finer than its smallest subnormal (\(2^{-149}\), \(2^{-1074}\)), or has a smallest value below the floor given in the list above. Such a format quantizes correctly over the part the carrier holds, and some of its values are never returned. A wide BinaryK used as a precision-only target is this case, so the warning can be silenced with warnings.simplefilter() when that is intended.

  • A format that cannot function raises ValueError. This covers more precision than the carrier’s, stochastic-rounding bits with no significand left to draw from, an exponent field wider than the kernels shift by, a SuperFP whose normal_binades leaves no supernormal codes, a FixedPoint end past the carrier’s largest value, and a format whose largest finite value is below the carrier’s normals, where every nonzero result overflows.

The run below shows both carriers on the same inputs and formats:

  • a float64 value rounded once in binary64, and the nearest float32 value rounded in binary32 and, with carrier=torch.float64, in binary64;

  • four formats, each checked against each carrier when a tensor meets it;

  • a 30-bit format computed exactly on a float64 tensor;

  • a product of float32 operands whose rounding only binary64 gets right.

docs/snippets/formats_carriers.py#
"""Carriers: the float arithmetic a tensor is rounded in, and what each can hold."""

import math
import warnings

import torch

from mptorch import BinaryK, FormatRangeWarning
from mptorch.quant import Quant, SplitMac, qmatmul

F32, F64 = torch.float32, torch.float64

# The carrier is the tensor's unless a call names one: binary64 for float64,
# binary32 for the rest. 1.0625 is the tie between 1.0 and 1.125 on Binary8p4's
# grid, and 1.1875 the tie between 1.125 and 1.25; 2**-30 either side of them is
# a bit float32 does not have, so the float32 value *is* the tie, and
# round-to-nearest-even takes over -- in either carrier, since binary64 cannot
# give a float32 tensor back bits it never had.
x = torch.tensor([1.0625 + 2**-30, 1.1875 - 2**-30], dtype=F64)
binary8p4 = BinaryK(8, 4)
print("input                              ", x.tolist())
print("float64, rounded in binary64       ", Quant(binary8p4)(x).tolist())
print("float32, rounded in binary32       ", Quant(binary8p4)(x.float()).tolist())
print("float32, carrier=torch.float64     ", Quant(binary8p4, carrier=F64)(x.float()).tolist())

# What each carrier makes of a format is checked when a tensor meets it, not
# when the format is built: here by a float32 tensor in each carrier, and a
# float64 one.
formats = [
    BinaryK(8, 4),  # Binary8p4: well inside both
    BinaryK(16, 8),  # smallest value 2**-134, below binary32's floor
    BinaryK(40, 30),  # 30 bits of precision, ten exponent bits
    BinaryK(64, 53),  # eleven exponent bits: past binary64 at the bottom too
]
calls = {
    "float32": lambda fmt: Quant(fmt)(torch.ones(4)),
    "float32, carrier=torch.float64": lambda fmt: Quant(fmt, carrier=F64)(torch.ones(4)),
    "float64": lambda fmt: Quant(fmt)(torch.ones(4, dtype=F64)),
}
print()
for fmt in formats:
    print(f"BinaryK({fmt.K}, {fmt.P})")
    for name, call in calls.items():
        with warnings.catch_warnings(record=True) as caught:
            warnings.simplefilter("always", FormatRangeWarning)
            try:
                call(fmt)
                verdict = f"warns ({caught[0].message}" if caught else "ok"
            except ValueError as e:
                verdict = f"raises ({e}"
        print(f"  {name}: {verdict.split(': ')[0] + (')' if verdict != 'ok' else '')}")

# Only what no carrier can do raises when the format is built.
try:
    BinaryK(64, 54)
except ValueError as e:
    print("\nBinaryK(64, 54):", str(e).split(": ")[0])

# A format float32 cannot carry, exactly, on a float64 tensor: pi to 30 bits
# of precision is pi rounded to the nearest multiple of 2**-28.
pi = torch.tensor([math.pi], dtype=F64)
got = Quant(BinaryK(40, 30))(pi).item()
want = round(math.pi * 2**28) / 2**28
print(
    f"\npi in BinaryK(40, 30): {got!r}, round(pi * 2**28) / 2**28: {want!r}, equal: {got == want}"
)

# Where the carrier does move a float32 result: a product. (1 + 2**-13)**2 is
# 1 + 2**-12 + 2**-26, a hair above the tie between 1 and 1 + 2**-11 on a
# 12-bit grid. binary32 rounds the product to 24 bits first, onto the tie, and
# RNE takes it down; binary64 holds the hair and rounds up. The result is a
# float32 tensor either way.
one = torch.full((1, 1), 1 + 2**-13)
p12 = BinaryK(16, 12)
print()
for carrier in (None, F64):
    out = qmatmul(one, one, SplitMac(p12, p12, carrier=carrier))
    print(f"(1 + 2**-13)**2 in P=12, carrier={carrier}: {out.item()!r} ({out.dtype})")

# A carrier is never narrower than the tensor: rounding a float64 one in
# binary32 would round every input once before the format does.
try:
    Quant(binary8p4, carrier=F32)(x)
except ValueError as e:
    print("\ncarrier=torch.float32 on float64:", str(e).split(";")[0])
output#
input                               [1.0625000009313226, 1.1874999990686774]
float64, rounded in binary64        [1.125, 1.125]
float32, rounded in binary32        [1.0, 1.25]
float32, carrier=torch.float64      [1.0, 1.25]

BinaryK(8, 4)
  float32: ok
  float32, carrier=torch.float64: ok
  float64: ok
BinaryK(16, 8)
  float32: warns (BinaryK(K=16, P=8, bias=128)'s smallest value is 2^-134, below 2^-125)
  float32, carrier=torch.float64: ok
  float64: ok
BinaryK(40, 30)
  float32: raises (BinaryK(K=40, P=30, bias=512) asks for 30 bits of precision, and it is rounded in binary32, which has 24)
  float32, carrier=torch.float64: ok
  float64: ok
BinaryK(64, 53)
  float32: raises (BinaryK(K=64, P=53, bias=1024) asks for 53 bits of precision, and it is rounded in binary32, which has 24)
  float32, carrier=torch.float64: warns (BinaryK(K=64, P=53, bias=1024) spaces its values 2^-1075 apart at the bottom, below binary64's 2^-1074)
  float64: warns (BinaryK(K=64, P=53, bias=1024) spaces its values 2^-1075 apart at the bottom, below binary64's 2^-1074)

BinaryK(64, 54): BinaryK(K=64, P=54, bias=512) asks for 54 bits of precision, and it is rounded in binary64, which has 53

pi in BinaryK(40, 30): 3.1415926553308964, round(pi * 2**28) / 2**28: 3.1415926553308964, equal: True

(1 + 2**-13)**2 in P=12, carrier=None: 1.0 (torch.float32)
(1 + 2**-13)**2 in P=12, carrier=torch.float64: 1.00048828125 (torch.float32)

carrier=torch.float32 on float64: carrier=torch.float32 is narrower than float64 operands, whose inputs it would round once before the format does

A carrier=torch.float64 call is held to binary64’s bounds even on a float32 tensor, because binary64 is what rounds it. Its result is also held to what the tensor’s dtype can store, which the next section describes.

dev/benchmarks/formats/format_limits.py reports all of this for a given format, in binary32 or with --carrier binary64. With --audit it checks the kernels against the format’s value set. Its sweep --audit walks every bound in the table above across its edge; each was measured where this section puts it.

What a narrower tensor can store#

A float16 or bfloat16 tensor is rounded in binary32, its default carrier, and the result is converted back when it is stored. The same happens to a float32 tensor under carrier=torch.float64, whose result is rounded in binary64. That conversion is a second rounding, onto the dtype’s grid, and MPTorch rounds it correctly to nearest.

For a float64 result stored as float16 or bfloat16, MPTorch rounds once, directly from float64 onto the dtype’s grid. It does not use PyTorch’s .to(), which converts float64 to bfloat16, and on most platforms to float16, in two steps: first to float32, then to the dtype. Two roundings can give a different result from one. Take the float64 value \(1 + 2^{-8} + 2^{-30}\). It lies just above the midpoint of the bfloat16 values \(1\) and \(1 + 2^{-7}\), so it should become \(1 + 2^{-7}\). PyTorch’s first step rounds it to \(1 + 2^{-8}\), which is exactly the midpoint, and its second step then rounds that tie to \(1\).

A format whose results are not all values of the dtype is quantized partially, as in the previous section, with one difference: a result above the dtype’s largest finite value is stored as \(\pm\infty\) whatever the format’s saturation mode. A SAT_FINITE format overflows too.

The dtype depends on the tensor, not on the format, so this is checked on every call. The check is made against the format whose values the result holds, and the rule depends on what the call rounded.

A GEMM’s result is the output of its last rounding: the accumulate format of a SplitMac, or the fused format of a FusedMac. That rounding is applied to products and sums that can land anywhere, so every value of the format can occur as a result, and all of them must be values of the dtype. For a BinaryK:

bound

float16

bfloat16

float32 (under binary64)

severity

precision

\(P \le 11\)

\(P \le 8\)

\(P \le 24\)

raises

top

largest value below \(2^{16}\)

float32’s

largest value below \(2^{128}\)

warns

finest step

\(\text{bias} + P \le 26\) (EXTENDED_NORMALS: \(\le 25\))

float32’s

\(\text{bias} + P \le 151\) (EXTENDED_NORMALS: \(\le 150\))

warns

A SuperFP is held to the same three bounds, in its own parameters. The rule does not depend on the carrier that rounded the result.

  • In binary32, only the precision bound is new for bfloat16. Its range is float32’s to within its precision, so a format that passes the float32 checks with at most eight bits of precision is inside it at both ends.

  • In binary64, the carrier accepts ranges that no narrower dtype holds, so every row of the table can apply.

A SplitMac’s multiply format is never stored, because its products are intermediates in the carrier. A step left unrounded stores no format’s values at all.

An elementwise quantizer’s result is the format’s rounding of a value that is already a value of the dtype. Wherever the format is at least as fine as the dtype, the result is the input itself. So neither high precision nor a fine bottom causes a problem; only the edges of the format’s range can land off the dtype’s grid. Each of these cases warns:

  • The format reaches past the dtype’s largest finite value, and that value is not on the format’s grid. An input near it then rounds up, out of the dtype’s range.

  • The format’s largest finite value is inside the dtype’s range but is not a value of the dtype, and the format saturates onto it.

  • An EXTENDED_NORMALS format’s hole, \(2^{-\text{bias}}\), is a value of the dtype, but the first value above it, where such an input rounds, is not.

Either kind of call raises for a format whose largest finite value is below the dtype’s smallest. Such a tensor could store nothing of the format but zero.

A block format’s decoded values are an element value times its block’s scale, computed in the carrier: binary64 for a float64 tensor or carrier=torch.float64, binary32 otherwise.

  • A BlockFormat’s element and cast scale must be formats the carrier holds entirely, and a power-of-two scale’s codes must lie in its range (\(2^{\pm 127}\) in binary32, \(2^{\pm 1023}\) in binary64). Building the format checks binary64’s bounds. A call that rounds in binary32 checks binary32’s, so an element with nine or ten exponent bits is a format of float64 tensors.

  • A packed tensor remembers the carrier it was packed in, and unpacking or multiplying it runs in that carrier or a wider one.

A result narrower than its carrier (float16 or bfloat16, and float32 too in binary64) rounds the decoded values a second time wherever the dtype does not hold them, and FormatRangeWarning reports it. That is always the case for a format with a tensor scale (NVFP4), whose decoded values are products in the carrier. For an E8M0 format it happens only when its largest element value has more significant bits than the dtype.

x = torch.ones(4, 4, dtype=torch.float16)
binaryK_quantize(x, 8, 4)                # fine
binaryK_quantize(x, 8, 3, bias=15)       # FormatRangeWarning: rounds up past 65504
binaryK_quantize(x, 16, 12, bias=8)      # fine: float16's values come back as they are
binaryK_matmul_fma(x, x, fma_K=16, fma_P=12, fma_bias=8)  # ValueError: 12 bits
qmatmul(x, x, SplitMac(BinaryK(8, 4), BinaryK(16, 11)))    # FormatRangeWarning: 2**-25

Both rules were measured against the kernels, not only derived. format_limits.py --dtype float16 --audit runs a format through a fused GEMM over operands of the dtype, and through the quantizer over every value of the dtype. sweep --dtype float16 --audit walks each boundary above. With --carrier binary64 both also go through the widened operands and the narrowed result.

On an Apple GPU#

On macOS every op also runs on "mps" tensors, as Metal kernels compiled from the same casts, GEMM policies, accumulate algorithms, convolution gathers and block-format decode that the CPU runs. MPS has no float64, so the carrier there is always binary32. float32, float16 and bfloat16 tensors compute exactly as on the CPU. carrier=torch.float64 and a float64 result are refused, because the device cannot hold a float64 tensor.

The results are the CPU’s, bit for bit, stochastic rounding included. An MPS call draws its one seed from the CPU generator, as a CPU call does, and gives every element the same random word. torch.manual_seed therefore reproduces a run across the two devices, not only on one. (CUDA draws from its own generator.)

The GPU’s float unit differs from the CPU’s in two ways. Both affect what a GEMM computes between its roundings, not the roundings themselves:

  • Subnormals. Apple GPUs flush binary32 subnormals to zero, in operands and results, in every mode Metal offers. The casts round on the word and are not affected. But a product, a running sum or a fused multiply-add whose exact value is below \(2^{-126}\) in magnitude becomes zero before the format sees it. The effect depends on the rounding mode:

    • Under RZ the CPU returns zero too.

    • Under RNE and RNA it does as well, for every format whose smallest value is at least \(2^{-125}\).

    • Under RU, RD, RO and SR the CPU can round such a value to the format’s smallest value where the GPU gives zero.

    • A sum left unrounded (accumulate_quant=False) can hold a subnormal on the CPU that the GPU drops.

    The same holds for the compensation of KAHAN, the block sums of BLOCK and TREE, and the products and sums of a block product. The quantizers are not affected, and neither are the block formats’ packing and decoding. They round every input exactly, subnormal ones included, in every mode. A decoded block value can itself be a subnormal (an E8M0 scale reaches \(2^{-127}\)), and it is the CPU’s, in a float32 and in a bfloat16 result.

  • NaN payloads. A NaN that reaches a product or a sum comes out of the GPU’s float unit as its canonical NaN, where the CPU keeps the operand’s payload. The casts pass a NaN through unchanged on every device, so a quantizer’s NaNs keep their payload.

The first call with a given format compiles its kernel, which takes from about 20 ms to a few hundred. Later calls with the same format, rounding mode and dtype reuse it. A convolution’s geometry and a block tensor’s shape are not part of the compiled kernel, so a new layer shape does not compile anything new.

Where rounding is applied#

A quantizer rounds a tensor, and a kernel rounds inside a reduction. The two compose, and MPTorch keeps them separate on purpose: