Quantized numerical kernels#
A quantizer rounds the operands of a computation. A matrix product has another place where rounding can happen: inside, at every step of every dot product. Consider a tensor core that takes 8-bit inputs and keeps a 32-bit running sum, an accumulator that keeps only 14 bits, and a fused multiply-add that rounds once per step. These are different arithmetics, and they give different results on the same operands. MPTorch’s kernels simulate them.
Every such computation runs on one routine: a batched matrix product in which every dot product is computed in the arithmetic you choose. This holds for a matrix product, the three products of a linear layer, the three passes of a convolution, and a product of two tensors in a block format. This page describes that routine. The pages under it cover each part and each operation:
Dot-product arithmetic: what a step of a dot product rounds, and in what order the terms are summed;
Block matrix products: products of block-format tensors, and where their scales enter the sum;
Convolutions: a convolution and its two gradients as matrix products whose matrices are never built;
Calling the kernels: the functions, objects and modules that run them.
Matrix multiplication as the core routine#
The routine computes
and each element \(c_{\beta i j}\) of the result is one dot product of length \(K\), computed as a running sum in a fixed order:
Only four things vary.
How the operands are read. The kernel reaches \(A\) and \(B\) only through its tile loads:
A dense operand is read through its strides. A transposed operand is then just a flag, and a broadcast one a stride of zero.
A convolution’s operands are gathered from the convolution’s own tensors, with zeros for the padding (Convolutions).
A block-format operand is decoded from its codes and scales (Block matrix products).
Whatever the load, it gives the step the value an explicit matrix would hold at that position.
What a step rounds. A mac specifies it. A SplitMac rounds the
product to one format and the sum to another. A FusedMac rounds one fused
multiply-add once. Anything the formats leave unrounded is computed in the
operands’ carrier, binary32 or binary64 (Formats and rounding, “Carriers”).
In what order the terms are summed. The choices are one running sum
(NAIVE), Kahan’s compensated sum, and two-level sums over blocks or
pairwise trees (Dot-product arithmetic). A rounded sum depends on its order, so
the order is part of the definition, and it is the same on every device.
What each output element has of its own. A palette gives each element its own format through an index map (Dot-product arithmetic). Under stochastic rounding each element draws from its own random stream, keyed on its index \((\beta, i, j)\) into the result, from one seed per call. A result therefore does not depend on how the work is tiled or threaded, or on the device. The CPU and CUDA kernels return the same bits in every deterministic mode. An Apple GPU returns the CPU’s bits, stochastic rounding included, except for what the GPU’s own float unit does between the roundings (On an Apple GPU).
For each step of its K-loop the kernel stages a \(16 \times 16\) tile of each operand (in shared or threadgroup memory on a GPU, per task on the CPU) and runs the step over the tile. The operations below differ only in their tile loads. That is how one routine serves them all without slowing any of them: each is bit for bit the routine applied to the explicit matrices it describes. Each entry point runs the following:
entry point |
matrix products per call |
operands |
|---|---|---|
|
\(AB\) forward; \(G B^\top\) and \(A^\top G\) backward |
dense; a transpose is a flag, and \([\dots, M, K] \times [K, N]\) is one product |
|
\(x W^\top\) forward; \(G W\) (input gradient) and \(G^\top x\) (weight gradient) |
dense |
|
the forward and the weight gradient, one each; the input gradient, one per residue class of the stride |
gathered from the input, the weight and the gradient |
|
as the rows above, each operand packed along the dimension its product sums over |
decoded from codes and scales |
The run below checks this with one mac and four entry points, each against the routine on explicit matrices:
a batched product, slice by slice;
a linear layer’s three products;
a convolution, against the product of its unfolded input;
a block product, against the product of its decoded operands.
"""One routine behind every entry point: a batched matmul, a layer's three
passes, a convolution and a block product, each equal to the GEMM of one mac
over explicit matrices."""
import warnings
import torch
import torch.nn.functional as F
from mptorch import MXFP8_E4M3, BinaryK, FormatRangeWarning
from mptorch.quant import (
QConv2d,
QLinear,
SplitMac,
binaryK_gemm_formats,
block_matmul,
block_pack,
conv_formats,
qmatmul,
)
torch.manual_seed(0)
mac = SplitMac(BinaryK(8, 4), BinaryK(12, 7)) # Binary8p4 products, a 12-bit running sum
def gemm(a, b):
"""The core routine on two explicit matrices."""
return qmatmul(a, b, mac)
# A batched product with a broadcast operand: one launch, each slice the 2D GEMM.
a, b = torch.randn(3, 5, 64), torch.randn(64, 7)
y = qmatmul(a, b, mac)
print("batched matmul, slice by slice:", all(torch.equal(y[i], gemm(a[i], b)) for i in range(3)))
# A linear layer: three GEMMs, x W^T forward, G W and G^T x backward.
lin = QLinear(64, 16, bias=False, formats=binaryK_gemm_formats(8, 4, acc_K=12, acc_P=7))
x = torch.randn(10, 64, requires_grad=True)
out = lin(x)
g = torch.randn_like(out)
out.backward(g)
W = lin.weight.detach()
print(
"linear layer, forward and both gradients:",
torch.equal(out.detach(), gemm(x.detach(), W.T)),
torch.equal(x.grad, gemm(g, W)),
torch.equal(lin.weight.grad, gemm(g.T, x.detach())),
)
# A convolution: the GEMM of the flattened weight and the unfolded input,
# though the kernel never builds the unfolded input.
conv = QConv2d(3, 8, 3, stride=2, padding=1, bias=False, formats=conv_formats(mac))
img = torch.randn(2, 3, 12, 12)
cols = F.unfold(img, 3, padding=1, stride=2) # [2, 27, 36]
want = gemm(conv.weight.detach().reshape(8, -1), cols).reshape(2, 8, 6, 6)
print("convolution forward:", torch.equal(conv(img).detach(), want))
# A block product: the GEMM of the decoded operands, with the multiply in
# binary32 (the float32 layout as a format; it warns that its top, 2^128, is
# past binary32's own).
pa, pb = block_pack(torch.randn(6, 64), MXFP8_E4M3), block_pack(b, MXFP8_E4M3, 0)
with warnings.catch_warnings():
warnings.simplefilter("ignore", FormatRangeWarning)
decoded = qmatmul(pa.unpack(), pb.unpack(), SplitMac(BinaryK(32, 24, bias=127), BinaryK(12, 7)))
print("block product:", torch.equal(block_matmul(pa, pb, acc=BinaryK(12, 7)), decoded))
batched matmul, slice by slice: True
linear layer, forward and both gradients: True True True
convolution forward: True
block product: True