Block matrix products#

A product of two tensors in block formats (Block formats) runs on the core routine of Quantized numerical kernels. Its tile load decodes each element from its code and its block’s scale. This page states what that product computes:

  • where it quantizes;

  • why its blocks must run along the dimension it sums over;

  • when it equals the dot product that OCP MX defines;

  • where a per-tensor scale enters the sum.

Calling the kernels has the functions that run it, and Layers the layer recipes built on it.

Quantization in the loop#

For \(C = AB\) with \(A \in \mathbb{R}^{M \times K}\) and \(B \in \mathbb{R}^{K \times N}\), a block product rounds in two places.

The operands, once per product. Each operand is block-quantized along \(K\), the dimension the product sums over. \(A\) is split into blocks of \(\beta\) consecutive \(k\) along each row, and \(B\) along each column. There is one scale per block, or per tile of \(\rho\) rows or columns for a 2D format. The kernel reads each element decoded:

\[\tilde a_{ik} = e^A_{ik}\, \sigma^A_{\lfloor i/\rho \rfloor,\, \lfloor k/\beta \rfloor}, \qquad \tilde b_{kj} = e^B_{kj}\, \sigma^B_{\lfloor j/\rho \rfloor,\, \lfloor k/\beta \rfloor},\]

This is an element value times its block’s scale, the value that block_unpack() returns, computed in the carrier: binary32, or binary64 when either operand was packed in binary64 or the call names carrier=torch.float64.

The sum, at every step. The loop is the core routine’s, with two specifics. There is no multiply format: the product is the carrier’s own, because the decoded element values are what a block-format unit multiplies. The sum is rounded to the accumulate format:

\[s_k = Q_{\text{acc}}\big(s_{k-1} + \operatorname{fl}(\tilde a_{ik}\, \tilde b_{kj})\big) \quad \text{(split)}, \qquad s_k = Q_{\text{acc}}\big(\tilde a_{ik}\, \tilde b_{kj} + s_{k-1}\big) \quad \text{(fused)},\]

Here \(\operatorname{fl}\) is a product in the carrier. \(Q_{\text{acc}}\) rounds to a BinaryK accumulate format in the call’s rounding mode; without an accumulate format it is the carrier’s own addition. Every accumulate algorithm of Dot-product arithmetic applies, and \(c_{ij} = s_K\).

Why the blocks run along K#

When \(\beta\) consecutive terms of the sum share both operands’ scales, the scales can be factored out of that part of the sum. Take the block \(\kappa\) of \(K\), the set of its \(\beta\) consecutive \(k\). Let \(\sigma^A_{i\kappa}\) and \(\sigma^B_{\kappa j}\) be the scales that row \(i\) of \(A\) and column \(j\) of \(B\) have over it. Then

\[\sum_{k \in \kappa} \tilde a_{ik}\, \tilde b_{kj} \;=\; \sigma^A_{i\kappa}\, \sigma^B_{\kappa j} \sum_{k \in \kappa} e^A_{ik}\, e^B_{kj} .\]

OCP MX v1.0 defines the dot product of two blocks this way, and a longer dot product as the sum of its blocks’ dot products. A block-format unit multiplies narrow elements and applies the scales once per block. This factorization requires the blocks to run along the summed dimension.

MPTorch’s decode is random access, so it could multiply operands blocked either way. But the products it simulates are the ones hardware computes. And a training step sums over a different dimension in each of its three products:

pass

product

sums over

packs

forward

\(x W^\top\)

input features

\(x\) along its features, \(W\) along its input features

input gradient

\(G W\)

output features

\(G\) along its features, \(W\) along its output features

weight gradient

\(G^\top x\)

the batch

\(G\) and \(x\) along the batch

Each tensor is therefore quantized twice, along two axes: the weight for the forward pass and the input gradient, the input for the forward pass and the weight gradient, and the output gradient for the two backward passes. With 1D blocks the two quantizations of a tensor differ, so the input gradient multiplies a weight that the forward pass never saw. A square tile holds the same elements whichever axis is packed, so one packing serves both passes (Block formats, “2D tiles”). Layers has the recipe.

Exact products, and OCP’s order of summation#

Under an E8M0 scale a decoded value is an element times a power of two, \(\tilde a = e \cdot 2^X\), and the element has at most 8 significant bits. A product of two decoded values is then a product of two significands of at most 16 bits, times a power of two. It is exact in binary32 as long as it stays in binary32’s normal range. In that range rounding also commutes with a power-of-two scale: \(Q(2^X y) = 2^X Q(y)\). Two things follow for the MX formats:

  • The split step rounds only the sum, because \(\operatorname{fl}(\tilde a \tilde b) = \tilde a \tilde b\). A fused step is the same step.

  • The block product is exactly OCP’s two-level dot product, provided its terms are summed in OCP’s order. That order is the BLOCK accumulate algorithm with block_size \(= \beta\) and no outer format: a block’s products are summed on their own and then added to the total,

    \[c_{ij} = \sum_\kappa \operatorname{fl}\Big( \sigma^A_{i\kappa} \sigma^B_{\kappa j} \, D_{ij\kappa} \Big), \qquad D_{ij\kappa} = \sum_{k \in \kappa} e^A_{ik}\, e^B_{kj} \ \text{(rounded as the accumulator rounds)},\]

    with the outer sum in binary32. OCP leaves the precision of a block’s internal sum to the implementation, and the accumulate format is where you choose it. The default, NAIVE, adds every product to one running total across the blocks. That is a different order and in general a different result.

The run below checks both points on MXFP8 operands whose magnitudes change along \(K\), by rebuilding OCP’s sum from the codes. It then illustrates the next section.

Tensor scales: in the loop or after it#

A cast scale (NVFP4’s E4M3, or a superfp) comes with a float32 scale per tensor, \(S_t\). The block product can apply it in one of two places.

In the loop (the default). The decode includes it. A block’s scale is the scale format’s value times the tensor scale, \(\sigma^A = \operatorname{fl}(s^A S^A_t)\) for \(A\) and likewise for \(B\), so

\[\tilde a_{ik} = \operatorname{fl}\big(e^A_{ik} \cdot \operatorname{fl}(s^A S^A_t)\big),\]

which is a value of up to 24 significant bits. The decode and every product can round, and the accumulator sees the operands’ own magnitudes.

After it, with tensor_scale_epilogue=True, as NVIDIA’s NVFP4 GEMMs do. The loop runs on the elements times their block scales alone, and the result is multiplied once by the product of the two tensor scales:

\[c_{ij} = \operatorname{fl}\big(\alpha\, s_K\big), \qquad \alpha = \operatorname{fl}\big(S^A_t S^B_t\big), \qquad s_k = Q_{\text{acc}}\big(s_{k-1} + \operatorname{fl}(e^A s^A \, e^B s^B)\big).\]

Here \(s_k\) is the running sum, and \(s^A\) and \(s^B\) are the scale formats’ values for the two elements’ blocks. With E2M1 elements and E4M3 scales, an element times its block’s scale, \(e^A s^A\), has at most six significant bits, and a product of two at most twelve. The loop therefore rounds only the sum.

In exact arithmetic the two options give the same product. They also give the same bits when the tensor scales are powers of two and the sum is in binary32: every value then differs by a power of two, which commutes with each rounding in binary32’s normal range. Otherwise they differ in three ways:

  • Accuracy. With a binary32 sum the epilogue rounds less. In the run it is two to three times closer to the exact product.

  • Range. In the epilogue the accumulator sums values that the tensor scales have not yet shrunk. Under NVFP4’s default \(S_t = \max|x| / (6 \cdot 448)\), a tensor’s largest element decodes to \(6 \cdot 448 = 2688\) whatever the tensor’s own magnitude, and a product of two such elements to about \(7 \cdot 10^6\). A narrow accumulate format can therefore overflow where the in-loop product does not, as the run’s last lines show. NVIDIA’s GEMMs accumulate in FP32.

  • The result’s values. The epilogue’s result is \(\alpha s_K\) rounded to binary32. It is not a value of the accumulate format.

An E8M0 format has no tensor scale, and the option changes nothing there.

docs/snippets/kernels_block.py#
"""The block GEMM's arithmetic: exact products, OCP's two-level sum, and where
NVFP4's tensor scales are applied."""

import torch

from mptorch import MXFP8_E4M3, NVFP4, AccumulateAlgorithm, BinaryK
from mptorch.quant import BlockPacked, block_matmul, block_pack

torch.manual_seed(0)
M, K, N = 16, 256, 12
a = torch.randn(M, K) * torch.logspace(-3, 3, K)  # magnitudes that change along K
b = torch.randn(K, N)

# 1. Under an E8M0 scale a decoded MX value is an element (four significant
#    bits for E4M3) times a power of two, so a product of two is exact.
pa, pb = block_pack(a, MXFP8_E4M3), block_pack(b, MXFP8_E4M3, 0)
A, B = pa.unpack(), pb.unpack()
exact = A.double()[:, :, None] * B.double()[None, :, :]
print(
    "MXFP8 products exact in binary32:",
    torch.equal((A[:, :, None] * B[None, :, :]).double(), exact),
)


# 2. OCP MX defines the dot product of two blocks as 2^(X_A + X_B) times the
#    sum of the element products, and a longer one as the sum of those. Rebuilt
#    from the codes, with binary32 sums: the elements decoded under a scale of
#    1 (E8M0 code 127), each block's sum scaled, the scaled sums added.
def elements(p):
    ones = torch.full_like(p.scales, 127)
    return BlockPacked(p.data, ones, p.fmt, p.shape, p.axis, 1.0, p.dtype).unpack()


eA, eB = elements(pa), elements(pb)
xA = torch.exp2(pa.scales.float() - 127)  # [M, K / 32]
xB = torch.exp2(pb.scales.float() - 127).T  # b is packed along K: [K / 32, N]
total = torch.zeros(M, N)
for blk in range(K // 32):
    s = torch.zeros(M, N)
    for k in range(32 * blk, 32 * blk + 32):
        s = s + eA[:, k, None] * eB[None, k, :]
    total = total + xA[:, blk, None] * xB[None, blk, :] * s
two_level = block_matmul(pa, pb, accumulate_algorithm=AccumulateAlgorithm.BLOCK, block_size=32)
naive = block_matmul(pa, pb)
print("BLOCK with block_size=32 == OCP's two-level sum:", torch.equal(two_level, total))
print(f"NAIVE, one running sum, differs in {int((naive != total).sum())} of {M * N} elements")

# 3. NVFP4's scale is an E4M3 value times a float32 tensor scale. By default a
#    decoded element carries both, e * (s * S_t), so the decode and the
#    product can round; tensor_scale_epilogue=True leaves S_t out of the loop
#    and multiplies the result by S_tA * S_tB once, as NVIDIA's GEMMs do.
qa, qb = block_pack(a, NVFP4), block_pack(b, NVFP4, 0)


def unit(p):  # the elements times their block scales, tensor scale 1
    return BlockPacked(p.data, p.scales, p.fmt, p.shape, p.axis, 1.0, p.dtype)


want = (unit(qa).unpack().double() * qa.tensor_scale) @ (
    unit(qb).unpack().double() * qb.tensor_scale
)  # the product of the operands' exact values
for name, epilogue in (("in the loop", False), ("as an epilogue", True)):
    y = block_matmul(qa, qb, tensor_scale_epilogue=epilogue)
    err = ((y.double() - want).norm() / want.norm()).item()
    print(f"NVFP4, tensor scales {name:<15} relative error {err:.1e}")

# Power-of-two tensor scales commute with every rounding: the two are equal.
ra = block_pack(a, NVFP4, tensor_scale=2.0**-8)
rb = block_pack(b, NVFP4, 0, tensor_scale=2.0**-9)
same = torch.equal(block_matmul(ra, rb), block_matmul(ra, rb, tensor_scale_epilogue=True))
print("power-of-two tensor scales, loop == epilogue:", same)

# Out of the loop, the accumulator sees the products before the tensor scales
# shrink them, so a narrow one needs their range.
acc = BinaryK(16, 11)
for name, epilogue in (("in the loop", False), ("as an epilogue", True)):
    y = block_matmul(qa, qb, acc=acc, tensor_scale_epilogue=epilogue)
    print(f"16-bit accumulator, tensor scales {name:<15} finite: {bool(y.isfinite().all())}")
output#
MXFP8 products exact in binary32: True
BLOCK with block_size=32 == OCP's two-level sum: True
NAIVE, one running sum, differs in 48 of 192 elements
NVFP4, tensor scales in the loop     relative error 1.0e-07
NVFP4, tensor scales as an epilogue  relative error 4.3e-08
power-of-two tensor scales, loop == epilogue: True
16-bit accumulator, tensor scales in the loop     finite: True
16-bit accumulator, tensor scales as an epilogue  finite: False

How the kernel decodes#

When it starts, each thread block fills two tables per operand from the operand’s format: the values of its 256 element codes and of its 256 scale codes. The scale table has the tensor scale folded in, unless that scale is applied after the loop. A tile load is then two table reads, one product in the carrier, and a test that keeps a zero unsigned.

Because of the tables, the block product takes element codes of at most 8 bits. That covers every OCP and NVFP4 format, every superfp element up to a byte, and block floating point from bfp(2) to bfp(8), whose integer codes the tables decode as the binaryK layout they are (Formats and rounding, “Block floating point”). The elementwise block operations take up to 16 bits. An arithmetic decode compiled in for wider codes took the kernels from 30-38 registers to 48-80, so it was left out.

An operand packed along its other dimension is read transposed, which costs one select in the load. Under stochastic rounding each output element draws as in every product of the routine.

The decode costs little compared with the arithmetic. At \(1024^3\) on an RTX 4060 laptop GPU, the block product was compared with the flat product on the decoded float32 operands (dev/benchmarks/timing/benchmark_block.py):

  • with a fused mac under round-to-nearest, the cheapest arithmetic and so the one where the decode shows most, it takes 1.15 to 1.18 times as long;

  • with a fused mac under stochastic rounding, 1.05 to 1.08 times;

  • with a split mac, less than half as long, because the flat product also rounds every product to a multiply format and the block product does not.

The kernels compute in binary32 or binary64 on the CPU and CUDA, and return a float32 or a float64 result accordingly. An Apple GPU has no float64, so it computes in binary32 only.