matmul#

Matrix multiplication combines two matrices into a third: each element of A @ B is the dot product of a row of A with a column of B, a sum of products. It is the core operation of linear algebra and of neural networks, where linear layers and attention are built on it. Each output element is a long sum, so how far a float result lands from the exact one depends on how many terms there are, how large they are, and the order an implementation adds them in.

In ExactRef, er.matmul(A, B), also er.linalg.products.matmul, is the matrix product, with NumPy's batching and 1-D promotion, as in torch.matmul. Its result holds the reference, the exact product rounded once to the output format, and bounds on the outputs a correct implementation can produce. Both operands must have the same dtype, and the output can be any format of the same kind. To check another implementation's output against it, use covers(), as in Checking PyTorch below. An operand can also be an earlier result, to check a chain of steps: the bounds then cover every value that result allows, since the implementation may have stored any of them.

Arguments#

Argument

Meaning

Default

A, B

the operands: arrays, tensors, or earlier results with the same dtype, matrices or batches of them; a 1-D operand is promoted as in NumPy

required

dtype

the output format, of the same kind as the inputs

the input format

rounding

the rounding mode of the reference and of a correct implementation's final rounding into the output format

er.Rounding.NEAREST_EVEN

overflow

what a result past the output format's range becomes: "ieee", "saturate", or "nan" for floats; "wrap", "error", or "saturate" for integers

each format's own rule; integers wrap

workers

the number of threads the call computes on; no result depends on it

the performance cores on Apple Silicon, else the physical cores, as PyTorch picks

Examples#

The product of a linear layer: 128 tokens of hidden size 4096 through the key projection of a model with 8 key heads of 128, such as Llama 3 8B, in bfloat16:

Code
import torch
import exactref as er

# Seeded, so every run uses the same values
g = torch.Generator().manual_seed(67)
# The layer's input, and its weight scaled as in a trained model
x = torch.randn(128, 4096, generator=g).bfloat16()
w = (torch.randn(1024, 4096, generator=g) / 64).bfloat16()

# ExactRef's result for the product x @ w.T
r = er.matmul(x, w.T)
print("shape:", r.rounded.shape)
# Row 0's first three elements: exact sums of 4096 products, rounded once
print("rounded:", r.rounded.tolist()[0][:3])
# How far a correct implementation's output can be from each of them
print("tolerance:", r.tolerance().tolist()[0][:3])
Output
shape: (128, 1024)
rounded: [0.4140625, 2.515625, -0.8046875]
tolerance: [0.0, 0.0, 0.0]

Each element is the exact sum of 4096 products, rounded once to bfloat16. The tolerance allows for one rounding at each step where every correct implementation has to round, a boundary: here each partial sum of the products, then the final rounding to bfloat16. By default it covers normal accumulation, the order ordinary kernels add in: index order, or a few SIMD lanes side by side. For bfloat16 inputs the tolerance assumes the additions happen in float32, the compute format, much finer than the output, so for these three elements, as for most others, every correct implementation lands on rounded. An element whose exact value lies close to a point where the rounding switches from one bfloat16 value to the next has a tolerance of one step instead, because the order of additions can move it across that point.

Shapes#

A batch of sequences goes through the same weight, and a decoding step multiplies one token's vector by it. Batch dimensions broadcast, and a 1-D operand is promoted to a matrix and the added dimension removed afterwards, as in NumPy and PyTorch:

Code
# A batch of 2 sequences of 128 tokens, through the same weight
xb = torch.randn(2, 128, 4096, generator=g).bfloat16()
print("batch:", er.matmul(xb, w.T).rounded.shape)

# One token's vector, as in a decoding step: a 1-D left operand acts as a row
token = torch.randn(4096, generator=g).bfloat16()
print("token @ w.T:", er.matmul(token, w.T).rounded.shape)
# A 1-D right operand acts as a column
print("w @ token:", er.matmul(w, token).rounded.shape)
Output
batch: (2, 128, 1024)
token @ w.T: (1024,)
w @ token: (1024,)

Output format and rounding#

Many kernels read bfloat16 but write float32: they add the products in float32 and skip the final rounding to bfloat16. dtype rounds the exact product once to the format they write:

Code
# The kernel: bfloat16 values, multiplied and added in float32, float32 output
out32 = x.float() @ w.float().T

# The exact product of the bfloat16 inputs, rounded once to float32
wide = er.matmul(x, w.T, dtype="float32")
print("dtype:", wide.rounded.dtype.name)
print("covered:", wide.covers(out32).all())
Output
dtype: float32
covered: True

rounding rounds the reference another way, such as toward zero. Find a bug in a matmul backend uses it to show that a kernel truncates its output.

Integer inputs#

An int8 quantized layer multiplies int8 activations by int8 weights and adds the products in int32. Integer products are exact, so the result's guarantee, what rounded satisfies, is "exact" and the tolerance 0: a correct kernel returns rounded itself.

Code
# The layer's activations and weights, quantized to int8
xq = torch.randint(-128, 128, (128, 4096), generator=g, dtype=torch.int8)
wq = torch.randint(-128, 128, (1024, 4096), generator=g, dtype=torch.int8)

# The exact product, with its sums kept in int32
q = er.matmul(xq, wq.T, dtype="int32")
print("guarantee:", q.guarantee)
print("largest tolerance:", max(q.tolerance().scalars()))
# PyTorch's int32 product, compared bit for bit
print("identical:", q.rounded.identical(er.asarray(xq.int() @ wq.int().T)))
Output
guarantee: exact
largest tolerance: 0.0
identical: True

Where a sum is stored in a narrow integer format, overflow decides the answer: PyTorch's int8 product wraps around past 127, while a kernel that clamps its int8 output saturates. They wrap by default, as in PyTorch, and overflow chooses another rule:

Code
# An int8 row and column whose exact product, 100 + 100 = 200, is past 127
a = er.asarray([[100, 100]], "int8")
b = er.asarray([[1], [1]], "int8")

# By default 200 wraps around to 200 - 256
print("wrap:", er.matmul(a, b).rounded.tolist())
# overflow="saturate" clamps to the int8 range instead
print("saturate:", er.matmul(a, b, overflow="saturate").rounded.tolist())

# overflow="error" raises instead
try:
    er.matmul(a, b, overflow="error")
except OverflowError as error:
    print(f"{type(error).__name__}: {error}")
Output
wrap: [[-56]]
saturate: [[127]]
OverflowError: output element (0, 0) is 200, outside the int8 range [-128, 127]

Complex inputs#

A discrete Fourier transform is a complex matrix product. Here it transforms 64 signals of 256 samples in complex64:

Code
import math

# The 256-point transform as a matrix: entry (j, n) is exp(-2 pi i j n / 256)
n = torch.arange(256)
angles = -2 * math.pi * (n[:, None] * n[None, :] % 256) / 256
dft = torch.polar(torch.ones(256, 256), angles).to(torch.complex64)
# 64 signals, one per column
signals = torch.randn(256, 64, generator=g, dtype=torch.complex64)

# ExactRef's result for the transform of every signal
spectra = er.matmul(dft, signals)
# Could a correct implementation produce PyTorch's output?
print("covered:", spectra.covers(dft @ signals).all())
# One bound per part, held as a complex number
print("tolerance dtype:", spectra.tolerance().dtype.name)
Output
covered: True
tolerance dtype: complex128

The real part of each tolerance bounds the error of the real part, and the imaginary part that of the imaginary part.

Special values#

A kernel that skips work on zeros, such as one that skips the all-zero tiles of a sparse weight, loses the NaN that inf * 0 gives. Infinities and NaN follow IEEE rules on the exact sum, so the reference keeps it. In a complex result, the real and imaginary parts are each a sum of real products, and each part follows the rules on its own products:

Code
inf = float("inf")
# A row that holds an infinity, and a column whose matching entry is 0
row = er.asarray([[inf, 1.0]], "float32")
col = er.asarray([[0.0], [1.0]], "float32")

# inf * 0 is NaN, so the exact sum is NaN
s = er.matmul(row, col)
print("rounded:", s.rounded.tolist())
# A kernel that skips the zero product returns 1.0, which no correct one does
print("1.0 covered:", s.covers(er.asarray([[1.0]], "float32")).all())

# The 1x1 complex matrix [inf + 0j] times [2 + 0j]: the imaginary part is
# inf * 0 + 0 * 2, and inf * 0 is NaN
c = er.asarray([[complex(inf)]], "complex64")
print("complex:", er.matmul(c, er.asarray([[2 + 0j]], "complex64")).rounded.tolist())
Output
rounded: [[nan]]
1.0 covered: False
complex: [[(inf+nanj)]]

Checking PyTorch#

To check an implementation, pass its output to covers(). Here it checks PyTorch's product for the layer from the first example, in bfloat16 and in float32:

Code
# Could a correct implementation produce PyTorch's bfloat16 output? covers()
# answers per element, and all() asks whether every element is covered.
print("bfloat16 covered:", r.covers(x @ w.T).all())

# The same layer in float32
x32, w32 = x.float(), w.float()
print("float32 covered:", er.matmul(x32, w32.T).covers(x32 @ w32.T).all())
Output
bfloat16 covered: True
float32 covered: True

Backward#

er.matmul.backward(A, B, grad), or er.matmul(A, B).backward(grad), returns grad_A = grad @ B^H and grad_B = A^H @ grad, each one matmul rounded once. They are named outputs of one result, and gb["grad_A"] reads one as a result of its own. Here they check the gradients PyTorch's autograd computes for a bfloat16 layer of hidden size 1024, given the gradient of its output from the next layer:

Code
# The layer's input and weight, and the gradient of its output
h = torch.randn(128, 1024, generator=g).bfloat16()
wh = (torch.randn(1024, 1024, generator=g) / 32).bfloat16()
grad = torch.randn(128, 1024, generator=g).bfloat16()

# PyTorch's autograd for h @ wh.T, on copies that record gradients
h_, wh_ = h.clone().requires_grad_(), wh.clone().requires_grad_()
(h_ @ wh_.T).backward(grad)

# ExactRef's gradients, held by name
gb = er.matmul.backward(h, wh.T, grad)
print("outputs:", list(gb.rounded))
# grad_A is the gradient of h
print("grad_A covered:", gb["grad_A"].covers(h_.grad).all())
# grad_B is the gradient of wh.T: transposed, it is the gradient of wh
print("grad_B covered:", gb["grad_B"].transpose(0, 1).covers(wh_.grad).all())
Output
outputs: ['grad_A', 'grad_B']
grad_A covered: True
grad_B covered: True

Backward explains the gradients and their names.

Full specification#

er.matmul#

matmul(A, B, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, workers: int | None = None) -> Result#

Matrix product with NumPy batching and 1-D promotion.

Each output element is the exact sum of exact products, rounded once to dtype (default: the input dtype); exact holds the exact sums. A and B must share a dtype, as in torch.matmul, and dtype must be of their kind; convert one with asarray(x, d) first.

tolerance() budgets the required boundary, accumulation in the compute format, then the rounding to dtype. By default it covers normal accumulation: in index order or in 2 or 4 SIMD-style lanes, each product rounded and then added, starting a new partial sum where adding the next value would overflow (fused multiply-adds are covered too). standard="any_order" covers every order (any tree of additions, with or without fused multiply-add or rounding each product first) that does not overflow. ulps changes nothing here (matmul calls no library function), but must be at least 1/2, as everywhere. normal() is the output of normal accumulation in index order; for complex inputs each part is the sum of its 2k real products, taken in index order.

Non-finite inputs follow IEEE rules applied to the exact sum: NaN if any product is NaN (including inf * 0) or infinities of both signs occur, otherwise the infinity. An exact zero sum is +0, or -0 when rounding toward -inf; an empty sum (k = 0) is +0. Integer results wrap on overflow unless overflow says otherwise. For complex inputs each part follows these rules on its own real terms (a_re b_re and -a_im b_im for the real part, a_re b_im and a_im b_re for the imaginary part): (inf + 0j) @ (2 + 0j) is inf + nanj, as in PyTorch's batched product.

A and B may also be earlier results, as Result describes.

er.matmul.backward#

backward(A, B, grad, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, workers: int | None = None) -> Result#

Gradients of matmul(A, B) for the output gradient grad.

grad_A = grad @ B^H and grad_B = A^H @ grad (^H: conjugate transpose, as PyTorch uses for complex inputs), each summed over the batch copies that broadcasting made of its operand, with that operand's shape. Each gradient is one matmul: the broadcast copies are folded into its contraction, so every element is one exact sum rounded once, and exact, tolerance() and normal() are that matmul's. PyTorch folds the same way except when both operands keep batch dimensions that broadcast against each other; then it rounds each batch's product to the dtype before summing the copies. That extra rounding is the chain sum(matmul(A^H, grad), axes, keepdims=True) for grad_B (and sum(matmul(grad, B^H), axes, keepdims=True) for grad_A), axes the batch dimensions along which the operand was broadcast and A^H formed exactly by the caller; its tolerance bounds PyTorch's gradient. grad must have the output's shape and the inputs' dtype. A, B and grad may also be earlier results.

See also#

  • Algorithms: matmul's accumulation orders, with their own run() and bounds, and matmul_mma for tensor cores.

  • PyTorch equivalents: mm, bmm, mv, dot, and the roundings PyTorch adds.

  • The proof.