Dot-product arithmetic#

This page states what one step of the core routine rounds (the mac) and in what order the terms of a dot product are summed. It gives the equations the kernels follow and a run for each. The same arithmetic runs in every entry point of Quantized numerical kernels, and Calling the kernels lists the objects that specify it.

What is simulated#

For \(C = AB\) with \(A \in \mathbb{R}^{M \times K}\) and \(B \in \mathbb{R}^{K \times N}\), each output element is a dot product of length \(K\), computed as a running sum in the order \(k = 1, \dots, K\). Two arithmetics are implemented, named after the kernel’s own policies.

SplitMac. The product and the sum are rounded separately, to formats that may differ:

\[s_0 = 0, \qquad s_k = Q_{\text{acc}}\Big(s_{k-1} + Q_{\text{mul}}(a_{ik}\, b_{kj})\Big), \qquad c_{ij} = s_K .\]

With acc=None the sum is left unrounded and only the products are rounded: \(s_k = s_{k-1} + Q_{\text{mul}}(a_{ik} b_{kj})\).

FusedMac. Each step is one fused multiply-add, rounded once, as in a hardware FMA unit:

\[s_k = Q_{\text{fma}}\big(a_{ik}\, b_{kj} + s_{k-1}\big).\]

The product is exact inside the FMA; the carrier still rounds the FMA’s result once before the format does (What the carrier rounds, below). With fma=None nothing is rounded at all, and the dot product is a sequence of FMAs.

In both arithmetics the operands \(a_{ik}\) and \(b_{kj}\) are read as they are. Rounding them is a quantizer’s job, and the layers apply one before the GEMM (see Layers).

One rounding mode serves both roundings of a SplitMac. The mode is a compile-time parameter of the kernel, and rounding the product one way and the sum another would multiply the number of kernels. Saturation, subnormal handling and the number of stochastic bits are properties of each format and can differ between the two.

Everything the formats do not round is computed in the operands’ carrier: the product before its rounding, the sum before its rounding, and an unrounded accumulator. The carrier is binary32 for float32, float16 and bfloat16 operands, and binary64 for float64 ones (float64 and the carrier, below).

The following run reproduces a SplitMac dot product by hand, step by step, and gets the same bits.

docs/snippets/gemm_splitmac.py#
"""A SplitMac dot product, reproduced step by step in Python."""

import torch

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

torch.manual_seed(0)
K = 8
a = torch.randn(1, K)
b = torch.randn(K, 1)
fmt = BinaryK(8, 4)
q = Quant(fmt)  # round to Binary8p4

# The op: every product rounded to Binary8p4, and the running sum rounded to
# Binary8p4 after every addition. The *operands* are read as they are.
out = binaryK_matmul(a, b, mul_K=8, mul_P=4, acc_K=8, acc_P=4)

# The same thing by hand, in the same order.
s = torch.zeros(1)
for k in range(K):
    s = q(s + q(a[0, k] * b[k, 0]))

print(f"float32 torch.matmul : {(a @ b).item():.6f}")
print(f"binaryK_matmul       : {out.item():.6f}")
print(f"by hand              : {s.item():.6f}   equal: {torch.equal(out.flatten(), s)}")

# Leaving the accumulator unquantized (acc=None / accumulate_quant=False)
# keeps the running sum in float32; only the products are rounded.
out32 = binaryK_matmul(a, b, mul_K=8, mul_P=4, accumulate_quant=False)
s32 = torch.zeros(1)
for k in range(K):
    s32 = s32 + q(a[0, k] * b[k, 0])
same = torch.equal(out32.flatten(), s32)
print(f"\nBinary8p4 products, fp32 sum : {out32.item():.6f}   by hand equal: {same}")
output#
float32 torch.matmul : -0.526053
binaryK_matmul       : -0.562500
by hand              : -0.562500   equal: True

Binary8p4 products, fp32 sum : -0.554688   by hand equal: True

The next run does the same for FusedMac, using float64 to hold the exact product-and-add before the single rounding:

docs/snippets/gemm_fusedmac.py#
"""SplitMac vs FusedMac: two roundings per step, or one."""

import torch

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

torch.manual_seed(0)
K = 8
a = torch.randn(1, K)
b = torch.randn(K, 1)
binary8p4 = BinaryK(8, 4)
q = Quant(binary8p4)

split = qmatmul(a, b, SplitMac(binary8p4, binary8p4))  # round(round(a*b) + s), twice per step
fused = qmatmul(a, b, FusedMac(binary8p4))  # round(a*b + s), once per step

# FusedMac by hand: the product-and-add is exact (float64 holds it), then
# rounded once to Binary8p4.
s = torch.zeros(1, dtype=torch.float64)
for k in range(K):
    s = q((a[0, k].double() * b[k, 0].double() + s).float()).double()

print(f"float32 torch.matmul           : {(a @ b).item():.6f}")
print(f"SplitMac(Binary8p4, Binary8p4) : {split.item():.6f}")
same = torch.equal(fused.flatten(), s.float())
print(f"FusedMac(Binary8p4)            : {fused.item():.6f}   by hand equal: {same}")

# FusedMac(None) is the unrounded fused step: float32 FMAs, in order.
unrounded = qmatmul(a, b, FusedMac(None))
print(f"FusedMac(None)                 : {unrounded.item():.6f}")
output#
float32 torch.matmul           : -0.526053
SplitMac(Binary8p4, Binary8p4) : -0.562500
FusedMac(Binary8p4)            : -0.500000   by hand equal: True
FusedMac(None)                 : -0.526053

The accumulation format usually matters most. Over a long dot product the rounding errors of the partial sums build up, and a format with three mantissa bits cannot usefully hold a sum of thousands of terms:

docs/snippets/gemm_accumulation.py#
"""How the accumulation format decides the error of a long dot product."""

import warnings

import torch

from mptorch import BinaryK, FormatRangeWarning, RoundMode
from mptorch.quant import FusedMac, SplitMac, qmatmul

torch.manual_seed(0)
M, K, N = 64, 4096, 64
# Entries of size ~1/4, so the dot products (std ~4) stay inside Binary8p4's
# range of 224 and the question is precision rather than overflow.
a = torch.randn(M, K) / 4
b = torch.randn(K, N) / 4
exact = (a.double() @ b.double()).float()

binary8p4 = BinaryK(8, 4)
binary8p4_sr = BinaryK(8, 4, prng_bits=8)
binary8p3 = BinaryK(8, 3)
# 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)  # bfloat16's field widths: 8 exponent, 7 mantissa bits
# float32's own precision, over a narrower exponent range: no 8-exponent-bit
# binaryK fits inside binary32 at any bias, so this is as wide as it goes.
wide = BinaryK(31, 24)  # 7 exponent, 23 mantissa bits

configs = {
    "torch.matmul (float32)": None,
    "SplitMac(Binary8p4, acc=None)": SplitMac(binary8p4, None),
    "SplitMac(Binary8p4, 24-bit acc)": SplitMac(binary8p4, wide),
    "SplitMac(Binary8p4, Binary16p8)": SplitMac(binary8p4, binary16p8),
    "SplitMac(Binary8p4, Binary8p3)": SplitMac(binary8p4, binary8p3),
    "SplitMac(Binary8p4, Binary8p4)": SplitMac(binary8p4, binary8p4),
    "SplitMac(Binary8p4, Binary8p4), SR": SplitMac(
        binary8p4_sr, binary8p4_sr, rounding=RoundMode.SR
    ),
    "FusedMac(Binary8p4)": FusedMac(binary8p4),
    "FusedMac(Binary16p8)": FusedMac(binary16p8),
}
print(f"{'arithmetic':<36}{'rel. error':>12}{'max |err|':>12}")
for name, mac in configs.items():
    out = qmatmul(a, b, mac)
    err = out - exact
    print(f"{name:<36}{err.norm() / exact.norm():>12.2e}{err.abs().max():>12.2f}")
output#
arithmetic                            rel. error   max |err|
torch.matmul (float32)                  2.67e-07        0.00
SplitMac(Binary8p4, acc=None)           2.65e-02        0.39
SplitMac(Binary8p4, 24-bit acc)         2.65e-02        0.39
SplitMac(Binary8p4, Binary16p8)         7.64e-02        1.83
SplitMac(Binary8p4, Binary8p3)          8.28e-01       13.02
SplitMac(Binary8p4, Binary8p4)          6.56e-01       10.03
SplitMac(Binary8p4, Binary8p4), SR      1.12e+00       42.79
FusedMac(Binary8p4)                     6.38e-01        9.71
FusedMac(Binary16p8)                    7.04e-02        1.67

The table shows three things:

  • Rounding the products to Binary8p4 costs a relative error of a few percent whatever the accumulator, because each product carries the format’s \(2^{-4}\) relative error. A float32 accumulator (acc=None, or the same thing spelled as a 24-bit format) adds nothing to it.

  • A Binary16p8 accumulator, which has bfloat16’s eight bits of precision, is noticeably worse, and a Binary8p4 one is useless.

  • Stochastic rounding does not help here; it is worse than round-to-nearest. The terms have random signs, so there is no systematic bias to remove, only variance to add. Stochastic rounding helps when the increments are systematically below half a spacing. That is the accumulator case shown in Formats and rounding and the weight-update case in the Tutorial: training in 8-bit floating point.

The two formats of a SplitMac may come from different families: \(Q_{\text{mul}}\) a BinaryK and \(Q_{\text{acc}}\) a SuperFP, or the reverse. The equation is the one above, each rounding in its own format, and the result holds the accumulate format’s values. Such a mac holds one format per slot (the palette kernels are single-family), and its sum is always rounded (with acc=None the mac has one family again). Every algorithm of the next section applies, with an outer format of the accumulate’s family, in either carrier.

docs/snippets/gemm_cross_family.py#
"""A SplitMac whose products and sums are rounded in two format families."""

import torch

from mptorch import BinaryK, SuperFP
from mptorch.quant import Quant, SplitMac, binaryK_superfp_matmul, qmm

torch.manual_seed(0)
K = 8
a = torch.randn(1, K)
b = torch.randn(K, 1)
binary8p4 = BinaryK(8, 4)
# 12 bits: a 6-bit mantissa in the top 31 binades, from 2**-14 up, and 63
# powers of two below them, down to 2**-77.
superfp12 = SuperFP(6, 5, 31, 15)


def by_hand(q_mul, q_acc):
    s = torch.zeros(1)
    for k in range(K):
        s = q_acc(s + q_mul(a[0, k] * b[k, 0]))
    return s


# Binary8p4 products, each partial sum rounded to the SuperFP format.
mac = SplitMac(binary8p4, superfp12)
out = qmm(a, b, mac)
s = by_hand(Quant(binary8p4), Quant(superfp12))
flat = binaryK_superfp_matmul(
    a,
    b,
    mul_K=8,
    mul_P=4,
    acc_man_bits=6,
    acc_exp_bits=5,
    acc_normal_binades=31,
    acc_bias=15,
)
print(f"float32 torch.matmul           : {(a @ b).item():.6f}")
same = torch.equal(out.flatten(), s)
print(f"Binary8p4 products, SuperFP sum: {out.item():.6f}   by hand equal: {same}")
print(f"binaryK_superfp_matmul         : {flat.item():.6f}   equal: {torch.equal(flat, out)}")

# The reverse: SuperFP products summed in Binary16p11.
binary16p11 = BinaryK(16, 11)
rev = qmm(a, b, SplitMac(superfp12, binary16p11))
s = by_hand(Quant(superfp12), Quant(binary16p11))
same = torch.equal(rev.flatten(), s)
print(f"SuperFP products, Binary16p11  : {rev.item():.6f}   by hand equal: {same}")

# A palette in either slot has no cross-family operator to select.
try:
    SplitMac([binary8p4, BinaryK(8, 3)], superfp12)
except ValueError as e:
    print(f"\nValueError: {e}")
output#
float32 torch.matmul           : -0.526053
Binary8p4 products, SuperFP sum: -0.554688   by hand equal: True
binaryK_superfp_matmul         : -0.554688   equal: True
SuperFP products, Binary16p11  : -0.539062   by hand equal: True

ValueError: a SplitMac whose multiply and accumulate formats are of different families (BinaryK and SuperFP) takes one format per slot: the cross-family ops have no palette variant

What the carrier rounds#

The equations above name the formats’ roundings. Each step also has one they do not name: the carrier computes the product, the sum and the FMA to its own precision first, 24 bits in binary32 and 53 in binary64, rounding to nearest, and the format’s cast then rounds that. Usually the second rounding absorbs the first. It does not when the exact value lies within the carrier’s last place of a format value: the carrier rounds it onto that value, and a directed mode then keeps it instead of going to the neighbour it should have gone to. 1 + 2^-30 rounded up to eight bits is 1 + 2^-7, but its binary32 sum is exactly 1, which every mode keeps. binary64 holds that gap, but not 2^-61:

docs/snippets/gemm_carrier_rounding.py#
"""What the carrier rounds: the nearest carrier step and the odd one."""

import torch

from mptorch import BinaryK, RoundMode
from mptorch.quant import SplitMac, qmm

# Eight bits of precision (the neighbours of 1 are 1 - 2^-8 and 1 + 2^-7), and
# a range that holds the products 2^-30 and 2^-61 exactly.
binary15p8 = BinaryK(15, 8)


def witness(sign: int, gap: int, dtype: torch.dtype):
    """Two products, 1 and sign * 2^-gap, each a Binary15p8 value: only the
    sum, 1 + sign * 2^-gap, is inexact."""
    h = gap // 2
    a = torch.tensor([[1.0, sign * 2.0**-h]], dtype=dtype)
    b = torch.tensor([[1.0], [2.0 ** -(gap - h)]], dtype=dtype)
    return a, b


def run(a, b, mode, carrier_rounding=RoundMode.RNE):
    mac = SplitMac(binary15p8, binary15p8, rounding=mode, carrier_rounding=carrier_rounding)
    return qmm(a, b, mac).item()


# (mode, the sign of the gap, the correct rounding of the exact sum)
cases = [
    (RoundMode.RNE, +1, 1.0),
    (RoundMode.RU, +1, 1 + 2**-7),
    (RoundMode.RD, -1, 1 - 2**-8),
    (RoundMode.RO, +1, 1 + 2**-7),
]
print(f"{'exact':10} {'mode':4} {'correct':>9} | {'carrier':8} {'nearest':>9} {'odd':>9}")
for mode, sign, correct in cases:
    for gap, dtype in ((30, torch.float32), (30, torch.float64), (61, torch.float64)):
        a, b = witness(sign, gap, dtype)
        carrier = "binary32" if dtype is torch.float32 else "binary64"
        nearest, odd = run(a, b, mode), run(a, b, mode, RoundMode.RO)
        exact = f"1 {'+' if sign > 0 else '-'} 2^-{gap}"
        print(f"{exact:10} {mode.name:4} {correct:9.7f} | {carrier:8} {nearest:9.7f} {odd:9.7f}")

# The guarantee needs a format narrower than the carrier: under RNE at most
# 22 bits of precision in binary32. A wider format raises, per call.
a, b = witness(+1, 30, torch.float32)
try:
    qmm(a, b, SplitMac(BinaryK(30, 23), carrier_rounding=RoundMode.RO))
except ValueError as e:
    print(f"\nValueError: {e}")
output#
exact      mode   correct | carrier    nearest       odd
1 + 2^-30  RNE  1.0000000 | binary32 1.0000000 1.0000000
1 + 2^-30  RNE  1.0000000 | binary64 1.0000000 1.0000000
1 + 2^-61  RNE  1.0000000 | binary64 1.0000000 1.0000000
1 + 2^-30  RU   1.0078125 | binary32 1.0000000 1.0078125
1 + 2^-30  RU   1.0078125 | binary64 1.0078125 1.0078125
1 + 2^-61  RU   1.0078125 | binary64 1.0000000 1.0078125
1 - 2^-30  RD   0.9960938 | binary32 1.0000000 0.9960938
1 - 2^-30  RD   0.9960938 | binary64 0.9960938 0.9960938
1 - 2^-61  RD   0.9960938 | binary64 1.0000000 0.9960938
1 + 2^-30  RO   1.0078125 | binary32 1.0000000 1.0078125
1 + 2^-30  RO   1.0078125 | binary64 1.0078125 1.0078125
1 + 2^-61  RO   1.0078125 | binary64 1.0000000 1.0078125

ValueError: carrier_rounding=RoundMode.RO: the multiply format's P is 23, and a binary32 step rounded to odd is rounded exactly under RoundMode.RNE only for P <= 22; binary64 holds it: pass carrier=torch.float64

On random data the effect follows the formats’ precision. dev/benchmarks/timing/carrier_double_rounding.py rates counts the outputs on which the binary32 and binary64 carriers disagree, at M = N = 256 over N(0, 1) operands quantized to the format. At K = 256 FP8 formats disagree on at most 0.04% of outputs, and formats of up to eleven bits of precision on at most 0.06% (split) and 0.5% (fused), under the directed modes. The widest disagree most: Binary16p12 fused on 1.4%, Binary24p16 on 4.6% split and 22% fused. A fused product of two P-bit operands has 2P bits before the add, more than binary32 keeps.

Rounding the carrier step to odd. carrier_rounding=RoundMode.RO on a SplitMac or FusedMac (and on the flat functions and the *_gemm_formats layer factories) rounds the carrier’s product, sum and FMA to odd instead. This is round toward zero onto the carrier’s grid with the last bit set whenever the result is inexact. An odd result stays strictly between the two carrier values next to the exact one, so every format whose rounding boundaries are all even carrier values rounds it exactly as it would the exact value (Boldo and Melquiond, “When double rounding is odd”). In terms of the format’s precision P:

the format’s rounding

binary32 (p = 24)

binary64 (p = 53)

RNE, RNA

P <= 22

P <= 51

RU, RD, RZ,

P <= 23

P <= 52

RO

SR

P + prng_bits <= 23

P + prng_bits <= 52

The midpoints that RNE and RNA round at take the extra bit. The bound holds below the carrier’s normal range and for saturating formats, but not for SR below the format’s smallest value, whose arms compute in the carrier before they draw. A call whose format is outside the bound raises. In binary32 the error names carrier=torch.float64 where binary64 holds the format.

Two results change beyond the corrected neighbours:

  • A finite exact sum larger than the carrier’s largest value reaches the cast as that value instead of as infinity, so SAT_PROPAGATE saturates it, as P3109 says a finite value should.

  • With acc=None only the product is rounded to odd: no format rounds the sum after it, so it stays the carrier’s nearest add.

The odd step is implemented for the NAIVE single-format GEMMs of one family, split and fused, on CPU and CUDA tensors in both carriers. The custom_matmul_*_odd ops are separate, so the default ones are what they were. KAHAN, BLOCK and TREE rely on error-free transforms rounded to nearest, and refuse it. So do palettes, the cross-family macs, the convolutions (conv_formats()) and an Apple GPU. On the CPU it assumes the default floating-point environment; a flush-to-zero mode (torch.set_flush_denormal(True)) breaks it in subnormal ranges, as it does the carrier arithmetic everywhere else.

It costs time, mostly on the CPU (carrier_double_rounding.py bench, measured on a Ryzen 9 7940HS and an RTX 4060 laptop GPU):

time against the nearest step

fused

split

CUDA, binary32

1.06-1.16x

1.05-1.16x

CUDA, binary64 (GeForce)

1.2x (SR) - 2.1x (RU)

1.2x (SR) - 1.5x

CPU, binary32

1.4-2.4x

1.6-2.1x

CPU, binary64

1.5-2.6x

1.1-1.7x

On a GPU, binary32 rounds to odd with two FMAs in the hardware’s directed modes and a select. The binary64 kernels of a consumer GPU are limited by its FP64 rate, which the second FMA and the directed modes’ own FP64 compares share. The CPU has no directed rounding to call, so each step is a sequence of error-free transforms on the sum’s dependency chain: a binary64 sum and an exact correction in binary32, and in binary64 an exact product split, two sums and a fix of the last bit.

Summing differently: KAHAN, BLOCK and TREE#

A narrow accumulator does badly in the table above because of the order of the sum as much as its width. There is one running sum, rounded \(K\) times, each time against a total that has grown far larger than the term being added. accumulate_algorithm changes the order and keeps the formats.

Take one output element and drop its indices \(i, j\), so that its terms are \(a_k b_k\) for \(k = 1, \dots, K\). Let \(p_k = Q_{\text{mul}}(a_k b_k)\) be the rounded product, \(s\) the running sum, \(Q_{\text{acc}}\) the accumulate rounding and \(Q_{\text{out}}\) a third rounding, the mac’s outer format. Each is the identity when its format is None. The algorithms are:

NAIVE

\(s \leftarrow Q_{\text{acc}}(s + p_k)\), the recurrence above.

KAHAN

Kahan’s compensated sum. The compensation \(c\) is held in the accumulate format, like the sum: \(y = Q_{\text{acc}}(p_k - c)\), \(t = Q_{\text{acc}}(s + y)\), \(c \leftarrow Q_{\text{acc}}(Q_{\text{acc}}(t - s) - y)\), \(s \leftarrow t\). This is four accumulate roundings per step, where NAIVE has one.

BLOCK

Two levels. The NAIVE recurrence runs on a block’s sum. After every block_size products, and after the last one, the block is added to a total \(T\), \(T \leftarrow Q_{\text{out}}(T + s)\), and restarted from zero. A block’s sum stays small, so a narrow acc loses little in it. outer (wider, or None for the carrier) is rounded once per block instead of once per product. block_size divides 16 or is a multiple of it.

TREE

The products of a block of block_size \(= 2^L\) (up to 256, 16 by default) are summed pairwise: \(Q_{\text{acc}}(Q_{\text{acc}}(p_1 + p_2) + Q_{\text{acc}}(p_3 + p_4))\) and so on up. Every addition is then of two terms of similar size. The block’s root is added to the total as in BLOCK. This is for SplitMac only: a fused multiply-add has no product term to pair.

In KAHAN and BLOCK, a fused mac’s step, \(Q_{\text{fma}}(s + a_k b_k)\), replaces the split one. A last partial block is added like a whole one, and nothing is padded. The CPU and CUDA kernels return the same bits in every deterministic mode. The result holds the values of the last rounding applied, which is outer’s when there is one. AccumulateAlgorithm states each algorithm step by step, including the draws of RoundMode.SR.

docs/snippets/gemm_kahan_block_tree.py#
"""KAHAN, BLOCK and TREE on the operands of gemm_accumulation.py."""

import warnings

import torch

from mptorch import AccumulateAlgorithm, BinaryK, FormatRangeWarning
from mptorch.quant import FusedMac, SplitMac, qmatmul

NAIVE, KAHAN, BLOCK, TREE = AccumulateAlgorithm

torch.manual_seed(0)
M, K, N = 64, 4096, 64
a = torch.randn(M, K) / 4
b = torch.randn(K, N) / 4
# The reference is computed in float64, on the CPU.
exact = a.double() @ b.double()

warnings.simplefilter("ignore", FormatRangeWarning)
binary8p4 = BinaryK(8, 4)
binary16p8 = BinaryK(16, 8)  # bfloat16's field widths: 8 exponent, 7 mantissa bits


def report(title, configs):
    print(f"{title:<42}{'rel. error':>12}{'max |err|':>12}")
    for name, mac in configs.items():
        err = qmatmul(a, b, mac).double() - exact
        print(f"  {name:<40}{err.norm() / exact.norm():>12.2e}{err.abs().max():>12.2e}")
    print()


# Nothing rounded but float32 itself: what each summation order is worth.
report(
    "float32 products and sums",
    {
        "NAIVE": FusedMac(None),
        "KAHAN": FusedMac(None, accumulate_algorithm=KAHAN),
        "BLOCK, 64 per block": FusedMac(None, accumulate_algorithm=BLOCK, block_size=64),
    },
)

# Binary8p4 products into a Binary16p8 accumulator, which NAIVE loses bits in at
# every one of the 4096 steps.
report(
    "Binary8p4 products, Binary16p8 sums",
    {
        "NAIVE": SplitMac(binary8p4, binary16p8),
        "KAHAN": SplitMac(binary8p4, binary16p8, accumulate_algorithm=KAHAN),
        "BLOCK, 16 per block": SplitMac(
            binary8p4, binary16p8, accumulate_algorithm=BLOCK, block_size=16
        ),
        "BLOCK, 64 per block": SplitMac(
            binary8p4, binary16p8, accumulate_algorithm=BLOCK, block_size=64
        ),
        "BLOCK, 64 per block, outer=Binary16p8": SplitMac(
            binary8p4, binary16p8, accumulate_algorithm=BLOCK, block_size=64, outer=binary16p8
        ),
        "TREE, 16 per block": SplitMac(binary8p4, binary16p8, accumulate_algorithm=TREE),
        "TREE, 256 per block": SplitMac(
            binary8p4, binary16p8, accumulate_algorithm=TREE, block_size=256
        ),
        "TREE, 256 per block, outer=Binary16p8": SplitMac(
            binary8p4, binary16p8, accumulate_algorithm=TREE, block_size=256, outer=binary16p8
        ),
        "the products' own error (acc=None)": SplitMac(binary8p4, None),
    },
)

# The same with an accumulator as narrow as the products.
report(
    "Binary8p4 products, Binary8p4 sums",
    {
        "NAIVE": SplitMac(binary8p4, binary8p4),
        "KAHAN": SplitMac(binary8p4, binary8p4, accumulate_algorithm=KAHAN),
        "BLOCK, 4 per block": SplitMac(
            binary8p4, binary8p4, accumulate_algorithm=BLOCK, block_size=4
        ),
        "BLOCK, 4 per block, outer=Binary16p8": SplitMac(
            binary8p4, binary8p4, accumulate_algorithm=BLOCK, block_size=4, outer=binary16p8
        ),
        "TREE, 4 per block": SplitMac(
            binary8p4, binary8p4, accumulate_algorithm=TREE, block_size=4
        ),
        "TREE, 4 per block, outer=Binary16p8": SplitMac(
            binary8p4, binary8p4, accumulate_algorithm=TREE, block_size=4, outer=binary16p8
        ),
    },
)

# The second table in binary64 (carrier=torch.float64 on these float32 operands):
# each product is exact there, so the multiply format rounds it once, not twice.
wide = torch.float64
report(
    "binary64: Binary8p4 products, Binary16p8 sums",
    {
        "NAIVE": SplitMac(binary8p4, binary16p8, carrier=wide),
        "KAHAN": SplitMac(binary8p4, binary16p8, accumulate_algorithm=KAHAN, carrier=wide),
        "TREE, 256 per block": SplitMac(
            binary8p4, binary16p8, accumulate_algorithm=TREE, block_size=256, carrier=wide
        ),
        "the products' own error (acc=None)": SplitMac(binary8p4, None, carrier=wide),
    },
)
output#
float32 products and sums                   rel. error   max |err|
  NAIVE                                       1.13e-06    3.99e-05
  KAHAN                                       3.64e-08    6.72e-07
  BLOCK, 64 per block                         2.05e-07    3.67e-06

Binary8p4 products, Binary16p8 sums         rel. error   max |err|
  NAIVE                                       7.64e-02    1.83e+00
  KAHAN                                       2.66e-02    3.77e-01
  BLOCK, 16 per block                         2.67e-02    3.89e-01
  BLOCK, 64 per block                         2.79e-02    4.02e-01
  BLOCK, 64 per block, outer=Binary16p8       2.97e-02    4.11e-01
  TREE, 16 per block                          2.66e-02    3.86e-01
  TREE, 256 per block                         2.68e-02    3.81e-01
  TREE, 256 per block, outer=Binary16p8       2.72e-02    3.77e-01
  the products' own error (acc=None)          2.65e-02    3.93e-01

Binary8p4 products, Binary8p4 sums          rel. error   max |err|
  NAIVE                                       6.56e-01    1.00e+01
  KAHAN                                       5.66e-02    9.91e-01
  BLOCK, 4 per block                          4.94e-02    7.34e-01
  BLOCK, 4 per block, outer=Binary16p8        6.23e-02    1.40e+00
  TREE, 4 per block                           4.83e-02    7.53e-01
  TREE, 4 per block, outer=Binary16p8         6.05e-02    1.19e+00

binary64: Binary8p4 products, Binary16p8 sums  rel. error   max |err|
  NAIVE                                       7.64e-02    1.83e+00
  KAHAN                                       2.66e-02    3.77e-01
  TREE, 256 per block                         2.68e-02    3.81e-01
  the products' own error (acc=None)          2.65e-02    3.93e-01

In float32 the three behave as in any numerical library: KAHAN recovers about a digit and a half over a 4096-term sum, and blocking about half of that. The other two tables show them with formats:

  • Second table. An accumulator with eight bits of precision costs NAIVE three times the error that the Binary8p4 products already carry. Every other row is back at the products’ own error, which no summation can improve on.

  • Third table. This is the narrowest case, sums in Binary8p4 itself. NAIVE is useless, and the other three are within a factor of two of the products’ error. An outer format narrower than the carrier costs a little, as expected: it is one more rounding, and in exchange the total is a value of a format you chose.

  • Fourth table. The second, in binary64 (carrier=torch.float64). A product of two float32 operands is exact there, so the multiply format rounds it once instead of twice. The errors are the second table’s to three digits: the formats round every intermediate far more than binary32 does.

The price is kernel time, in proportion to the roundings per step. On an RTX 4060 laptop GPU a 10243 split-mac GEMM takes 1.2 times NAIVE’s time under BLOCK, 1.3 under TREE and 2.2 under KAHAN (BinaryK(8, 4) products into BinaryK(16, 11) sums under RNE, September 2026). The three are implemented for the single-format ops, on the CPU, CUDA and Apple GPUs, in both carriers (next section) where the device has float64. A palette raises.

float64 and the carrier#

A float64 GEMM is computed in binary64 from end to end: every product, every sum and every rounding. So is a float32, float16 or bfloat16 GEMM that names carrier=torch.float64. This is a different arithmetic from the binary32 one, not the same one widened, in three ways:

  • Products of narrow operands are rounded once. In binary32 a product is rounded to 24 bits before the multiply format rounds it again. In binary64 the product of two operands of at most 26 significant bits is exact, and only the format rounds it. Two float32 values qualify, as do two values a quantizer has rounded. A binary64 GEMM can therefore round differently even when every operand is a float32 value, as the run’s first lines show. It agrees with the binary32 GEMM exactly when every product and sum is exact in both. Operands already rounded to a narrow format usually give that (the FP8 recipe in Layers agrees to the bit).

  • Wider formats. Each call holds the formats to its carrier’s bounds (Formats and rounding). Formats beyond binary32, such as a 30-bit multiply format into a 40-bit accumulator, are refused on float32 operands and computed exactly on float64 ones.

  • Wider random draws. Under SR each rounding draws two words of its element’s stream, and P - 1 + prng_bits may reach 52.

carrier=torch.float64 on a SplitMac / FusedMac, or on the flat function, computes narrower operands the binary64 way. Both operands are widened, the binary64 kernel runs, and the result is narrowed back to their dtype with one rounding. This is bit for bit the float64 call on the widened operands, random draws included, then stored.

The stored result is held to what that dtype can store (Formats and rounding). A float32 result is held to 24 bits of precision in its accumulate or fused format. For float32 operands, binary64 therefore improves everything before the last rounding: an unquantized sum no longer loses a bit per step, and the multiply format can be wider than the result. The run measures this.

The carrier is never narrower than the operands. carrier=torch.float32 on float64 operands raises, and a float32 and a float64 operand cannot be mixed in one call under either carrier.

Every accumulate algorithm runs in binary64 as NAIVE does, and so do the cross-family macs and the convolutions (Convolutions). A KAHAN compensation in binary64 carries the bits a binary64 sum drops.

docs/snippets/gemm_float64.py#
"""binary64 GEMMs: every product, sum and rounding in binary64, on any operands."""

import torch

from mptorch import AccumulateAlgorithm, BinaryK, SuperFP
from mptorch.quant import FusedMac, SplitMac, binaryK_matmul, qmatmul

F32, F64 = torch.float32, torch.float64
torch.manual_seed(0)

# The product is rounded once. (1 + 2**-13)**2 = 1 + 2**-12 + 2**-26 is just
# above the tie between 1 and 1 + 2**-11 on a 12-bit grid. binary32 rounds the
# product to 24 bits before the format sees it -- onto the tie itself, which
# round-to-nearest-even then sends to 1 -- and binary64 keeps it whole, for
# float64 operands and for float32 ones that name it.
p12 = SplitMac(BinaryK(16, 12), BinaryK(16, 12))
p12_64 = SplitMac(BinaryK(16, 12), BinaryK(16, 12), carrier=F64)
one = torch.full((1, 1), 1 + 2**-13)
print("float32 operands                ", qmatmul(one, one, p12).item())
print("float64 operands                ", qmatmul(one.double(), one.double(), p12).item())
out = qmatmul(one, one, p12_64)
print("float32, carrier=torch.float64  ", out.item(), out.dtype)

# Formats only binary64 carries, against float64's own product.
a = torch.randn(64, 256, dtype=F64)
b = torch.randn(256, 32, dtype=F64)


def error(out: torch.Tensor, exact: torch.Tensor) -> str:
    return f"{(torch.linalg.norm(out.double() - exact) / torch.linalg.norm(exact)).item():.1e}"


wide = SplitMac(BinaryK(40, 30), BinaryK(48, 40))
p24 = BinaryK(31, 24)
kahan = AccumulateAlgorithm.KAHAN
macs = [
    ("SplitMac(P=30, P=40)", wide),
    ("  KAHAN", SplitMac(BinaryK(40, 30), BinaryK(48, 40), accumulate_algorithm=kahan)),
    ("FusedMac(P=40)", FusedMac(BinaryK(48, 40))),
    ("SplitMac(P=24, P=24)", SplitMac(p24, p24)),
    ("SplitMac(superfp, P=40)", SplitMac(SuperFP(8, 6, 62, 31), BinaryK(48, 40))),
    ("SplitMac(P=4, P=4)", SplitMac(BinaryK(8, 4), BinaryK(8, 4))),
]
print("\nrelative error against a @ b, float64 operands")
for name, mac in macs:
    print(f"  {name:<24}{error(qmatmul(a, b, mac), a @ b)}")

# Float32 operands, against the exact product of their values, in each carrier.
# A result stored in float32 holds at most 24 bits, so what binary64 buys is
# everything before the last rounding: sums that do not lose a bit per step, and
# a multiply format wider than the result.
a32, b32 = a.float(), b.float()
exact32 = a32.double() @ b32.double()
macs32 = [
    ("SplitMac(P=24, None)", lambda c: SplitMac(p24, None, carrier=c)),
    ("FusedMac(None)", lambda c: FusedMac(None, carrier=c)),
    ("SplitMac(P=30, P=24)", lambda c: SplitMac(BinaryK(40, 30), p24, carrier=c)),
    ("SplitMac(P=4, P=4)", lambda c: SplitMac(BinaryK(8, 4), BinaryK(8, 4), carrier=c)),
]
print(f"\nfloat32 operands            {'binary32':<10}carrier=torch.float64")
for name, build in macs32:
    row = []
    for carrier in (None, F64):
        try:
            row.append(error(qmatmul(a32, b32, build(carrier)), exact32))
        except ValueError:
            row.append("raises")
    print(f"  {name:<26}{row[0]:<10}{row[1]}")

# The wide formats are refused where binary32 does the arithmetic, and where a
# float32 result would have to store them.
try:
    qmatmul(a32, b32, wide)
except ValueError as e:
    print("\nfloat32 operands:", str(e).split(": ")[0])
try:
    qmatmul(a32, b32, SplitMac(BinaryK(40, 30), BinaryK(48, 40), carrier=F64))
except ValueError as e:
    print("float32, carrier=torch.float64:", str(e).split(": ")[0])

# carrier=torch.float64 is the float64 call on the widened operands, narrowed,
# and so is the flat function's keyword; the result keeps the operands' dtype.
# (Binary8p4's values are float16's too, so `.to` narrows them exactly.)
binary8p4_64 = SplitMac(BinaryK(8, 4), BinaryK(8, 4), carrier=F64)
print()
for dtype in (F32, torch.float16):
    ad, bd = a.to(dtype), b.to(dtype)
    got = qmatmul(ad, bd, binary8p4_64)
    same = torch.equal(got, qmatmul(ad.double(), bd.double(), binary8p4_64).to(dtype))
    print(f"{str(dtype):<13} carrier=torch.float64 == the float64 call, narrowed: {same}")
flat = binaryK_matmul(a32, b32, mul_K=8, mul_P=4, carrier=F64)
agrees = torch.equal(flat, qmatmul(a32, b32, binary8p4_64))
print("binaryK_matmul(..., carrier=torch.float64) agrees:", agrees)

# A carrier is never narrower than the operands.
try:
    qmatmul(a, b, SplitMac(BinaryK(8, 4), BinaryK(8, 4), carrier=F32))
except ValueError as e:
    print("\ncarrier=torch.float32 on float64:", str(e).split(";")[0])
output#
float32 operands                 1.0
float64 operands                 1.00048828125
float32, carrier=torch.float64   1.00048828125 torch.float32

relative error against a @ b, float64 operands
  SplitMac(P=30, P=40)    3.9e-10
    KAHAN                 3.9e-10
  FusedMac(P=40)          4.4e-12
  SplitMac(P=24, P=24)    2.9e-07
  SplitMac(superfp, P=40) 8.1e-04
  SplitMac(P=4, P=4)      2.6e-01

float32 operands            binary32  carrier=torch.float64
  SplitMac(P=24, None)      3.0e-07   3.7e-08
  FusedMac(None)            2.9e-07   2.6e-08
  SplitMac(P=30, P=24)      raises    2.9e-07
  SplitMac(P=4, P=4)        2.6e-01   2.6e-01

float32 operands: 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: BinaryK(K=48, P=40, bias=128) has 40 bits of precision, and a float32 result holds 24

torch.float32 carrier=torch.float64 == the float64 call, narrowed: True
torch.float16 carrier=torch.float64 == the float64 call, narrowed: True
binaryK_matmul(..., carrier=torch.float64) agrees: True

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

In the float64 table, KAHAN adds nothing to a 40-bit accumulator, which already keeps what the 30-bit products carry, and a cross-family mac (a superfp multiply into a 40-bit binaryK sum) runs in binary64 like the single-family ones.

The float32 table shows the other side of the choice. Where the formats round every intermediate the carrier would (24 bits, or Binary8p4’s four on either side), the two carriers are within one rounding of each other or equal to the bit. Beyond what the formats keep, the carrier adds little. On a GPU it also costs time (see Calling the kernels, “Performance notes”), in addition to the float64 copies of the operands and the result.

Palettes: a format per output element#

A Palette in any format slot selects the spatially-varying kernel. Each output element’s dot product runs in the palette entry that an integer map, prec_idx, assigns to it. The map can have:

  • the output’s shape [M, N];

  • shape [M, 1], for one format per row;

  • shape [1, N], for one format per column.

It can also have a leading batch dimension, of the batch size or of size 1 to share the map. Its values must lie in [0, len(palette)). A palette’s entries must agree on everything except their widths (sign, stochastic bits, saturation and subnormal policy), because the kernel tabulates only the widths.

docs/snippets/gemm_palette.py#
"""Palette: a different format per output element, selected by prec_idx."""

import warnings

import torch

from mptorch import BinaryK, FormatRangeWarning
from mptorch.quant import Palette, QMatmul, SplitMac, matmul_formats, qmatmul

torch.manual_seed(0)
M, K, N = 6, 32, 4
a = torch.randn(M, K)
b = torch.randn(K, N)

# An 8-exponent-bit binaryK reaches below 2**-126, where binary32's 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)

binary8p4, binary8p3, binary16p8 = BinaryK(8, 4), BinaryK(8, 3), BinaryK(16, 8)
palette = Palette([binary8p4, binary8p3, binary16p8])
mac = SplitMac(palette, palette)  # entry i: multiply and accumulate in format i

# One map entry per output row: rows 0-1 in Binary8p4, 2-3 in Binary8p3, 4-5 in
# Binary16p8.
prec_idx = torch.tensor([[0], [0], [1], [1], [2], [2]])
out = qmatmul(a, b, mac, prec_idx=prec_idx)

# Each row equals the same row computed with that single format.
for fmt, rows in ((binary8p4, [0, 1]), (binary8p3, [2, 3]), (binary16p8, [4, 5])):
    single = qmatmul(a, b, SplitMac(fmt, fmt))
    print(
        f"rows {rows} == {fmt.K}/{fmt.P} single-format rows:", torch.equal(out[rows], single[rows])
    )

# A map can also be per column ([1, N]) or dense ([M, N]).
per_col = torch.tensor([[0, 1, 2, 0]])
dense = torch.randint(0, 3, (M, N))
print("per-column map:", tuple(qmatmul(a, b, mac, prec_idx=per_col).shape))
print("dense map:     ", tuple(qmatmul(a, b, mac, prec_idx=dense).shape))

# A palette that also has to differentiate needs one map per pass, because
# the three passes have three output shapes: [M, N], [M, K] and [K, N].
formats = matmul_formats(
    mac,
    prec_idx=prec_idx,  # forward, [M, N]-shaped (or [M, 1] / [1, N])
    agrad_prec_idx=torch.zeros(M, 1, dtype=torch.long),  # grad of a: [M, K]
    bgrad_prec_idx=torch.full((1, N), 2),  # grad of b: [K, N]
)
layer = QMatmul(formats)
a.requires_grad_(True)
layer(a, b).sum().backward()
print("grad through a palette:", tuple(a.grad.shape))

# Forgetting one is an error naming the argument, not a silent fallback.
try:
    qmatmul(a, b, mac, prec_idx=prec_idx).sum().backward()
except ValueError as e:
    print("ValueError:", e)
output#
rows [0, 1] == 8/4 single-format rows: True
rows [2, 3] == 8/3 single-format rows: True
rows [4, 5] == 16/8 single-format rows: True
per-column map: (6, 4)
dense map:      (6, 4)
grad through a palette: (6, 32)
ValueError: this format is a palette, so its gradient of a needs its own prec_idx map (shaped like that pass's output): pass agrad_prec_idx= to matmul_formats

A format for every element#

A dense [M, N] map is the general case. Every output element’s dot product runs in the palette entry named by its own map entry, independently of its row, its column and its neighbours. How the map is chosen is up to the caller: a sensitivity analysis, a hardware assignment, a search.

The run below builds one per element. For each of the 20 elements of a product it takes the narrowest of eight BinaryK formats, from 3 to 24 bits of precision, whose result stays within 0.1% of the exact dot product there. It then runs the whole product as a single palette GEMM and checks every element against the single-format GEMM in that element’s format. They are equal to the bit, because an element’s dot product reads only its own row and column of the operands and its own palette entry.

The same map picks a pair when the multiply and the accumulate palettes differ. Entry i of a SplitMac palette pairs mul[i] with acc[i], so one element can multiply in 4 bits into a 24-bit sum while its neighbour does the opposite. A FusedMac takes a palette the same way. A batched product takes a [B, M, N] map, with a format per element of every sample. The fields a palette shares (sign, stochastic bits, saturation and subnormals) are shared by every element; a palette whose entries disagree on one is refused, with an error naming the entry.

docs/snippets/gemm_palette_elements.py#
"""A format for every output element: a dense prec_idx map over an eight-format palette."""

import torch

from mptorch import BinaryK, RoundMode, SubnormalsMode
from mptorch.quant import FusedMac, Palette, SplitMac, qmatmul

torch.manual_seed(0)
M, K, N = 4, 64, 5
a = torch.randn(M, K)
b = torch.randn(K, N)
exact = a @ b

# Eight BinaryK formats, from 3 to 24 bits of precision -- a palette holds at
# most eight, and its entries may differ in anything but the fields the
# kernel shares across the palette (sign, stochastic bits, saturation and
# subnormals).
formats = [
    BinaryK(8, 3),
    BinaryK(8, 4),
    BinaryK(10, 6),
    BinaryK(12, 8),
    BinaryK(16, 11),
    BinaryK(20, 15),
    BinaryK(24, 19),
    BinaryK(31, 24),
]
palette = Palette(formats)

# Choose each output element's format on its own: the narrowest whose
# single-format GEMM is within 0.1% of the exact dot product there, or the
# widest where none is. Any rule works -- a map is just an integer per element.
tol = 1e-3
errors = torch.stack([(qmatmul(a, b, SplitMac(f, f)) - exact).abs() / exact.abs() for f in formats])
fits = errors <= tol
prec_idx = torch.where(fits.any(0), fits.int().argmax(0), len(formats) - 1).to(torch.int32)
print("P of the format each output element runs in:")
print(torch.tensor([[formats[i].P for i in row] for row in prec_idx.tolist()]))

# One GEMM, every element in its own format.
out = qmatmul(a, b, SplitMac(palette, palette), prec_idx=prec_idx)
rel = (out - exact).abs() / exact.abs()
print(f"\nworst relative error {rel.max().item():.2e} (target {tol:.0e})")

# ... and each element is exactly what a single-format GEMM in its format gives.
same = torch.zeros(M, N, dtype=torch.bool)
for i, f in enumerate(formats):
    here = prec_idx == i
    same[here] = qmatmul(a, b, SplitMac(f, f))[here] == out[here]
print(f"all {M * N} elements equal their own format's GEMM: {bool(same.all())}")

# The multiply and the accumulate of each element can differ too: palette entry
# i pairs multiply format i with accumulate format i, so a map entry picks a
# pair -- here a 4-bit multiply into a 24-bit sum, or the other way round.
mul = Palette([BinaryK(8, 4), BinaryK(31, 24)])
acc = Palette([BinaryK(31, 24), BinaryK(8, 4)])
pairs = torch.tensor([[0, 1, 0, 1, 0], [1, 0, 1, 0, 1], [0, 0, 1, 1, 0], [1, 1, 0, 0, 1]])
split = qmatmul(a, b, SplitMac(mul, acc), prec_idx=pairs)
ok = all(
    torch.equal(split[pairs == i], qmatmul(a, b, SplitMac(mul[i], acc[i]))[pairs == i])
    for i in range(2)
)
print(f"\nper-element (multiply, accumulate) pairs match their own GEMM: {ok}")

# A fused step takes a palette the same way, and so do the shared fields: here
# every entry rounds stochastically with 8 random bits and no subnormals.
fused_formats = [
    BinaryK(8, 4, prng_bits=8, subnormals=SubnormalsMode.NORMALS),
    BinaryK(16, 11, prng_bits=8, subnormals=SubnormalsMode.NORMALS),
]
fused = qmatmul(a, b, FusedMac(fused_formats, rounding=RoundMode.SR), prec_idx=pairs)
print("stochastic fused palette:", tuple(fused.shape))

# A batched product takes one map per batch element, [B, M, N], so every
# element of every sample can run in its own format.
ab, bb = torch.randn(3, M, K), torch.randn(3, K, N)
per_sample = torch.randint(0, len(formats), (3, M, N))
batched = qmatmul(ab, bb, SplitMac(palette, palette), prec_idx=per_sample)
first = qmatmul(ab[0], bb[0], SplitMac(palette, palette), prec_idx=per_sample[0])
print("batched map, sample 0 equals its own call:", torch.equal(batched[0], first))

# The fields a palette shares must agree, and it says which entry does not.
try:
    Palette([BinaryK(8, 4), BinaryK(16, 11, subnormals=SubnormalsMode.NORMALS)])
except ValueError as e:
    print("\nValueError:", e)
output#
P of the format each output element runs in:
tensor([[11, 11, 15, 11, 11],
        [15, 15, 15, 15, 15],
        [ 8, 15, 11, 15, 11],
        [15,  8, 15,  6,  8]])

worst relative error 7.62e-04 (target 1e-03)
all 20 elements equal their own format's GEMM: True

per-element (multiply, accumulate) pairs match their own GEMM: True
stochastic fused palette: (4, 5)
batched map, sample 0 equals its own call: True

ValueError: a Palette shares subnormals across its entries (the kernel tabulates only the format widths): entry 1 has subnormals=<SubnormalsMode.NORMALS: 1>, entry 0 has <SubnormalsMode.SUBNORMALS: 0>