gemm#

GEMM, short for general matrix multiply, is the classic BLAS routine that multiplies two matrices and adds the result to a third: D = beta * C + alpha * (A @ B), where alpha and beta are scalars. It is the computation behind a linear layer with a bias, and PyTorch exposes it as addmm, with addmv, addr, and baddbmm for a vector, an outer product, and batches. The scaling and the extra addition give an implementation more choices than a plain product: it may apply alpha to an operand, to each product, or to the sum, and add beta * C first or last.

In ExactRef, er.gemm(A, B, C, *, alpha=1, beta=1), also er.linalg.products.gemm, computes beta * C + alpha * (A @ B) exactly and rounds once, with matmul's batching and 1-D promotion, and with C broadcast to the output's shape. The output can be any format of the inputs' kind. To check another implementation's output against it, use covers(), as in Checking PyTorch below. The tolerance, per element how far a correct implementation's output can be from that once-rounded answer (the reference), allows for the choices an implementation makes along the way:

exact in ExactRef's reference A @ B k products * alpha taken exactly + beta * C C broadcast round once what the tolerance lets an implementation do at each step round or fuse each product, add them up apply it to an operand, product, or (partial) sum round it, and add it at any point to the output format

One output element of gemm. The reference computes the first three steps exactly and rounds once. The tolerance allows for an implementation that rounds at each step, in the ways listed under it.

Arguments#

Argument

Meaning

Default

A, B

the matrices to multiply, with matmul's batching and 1-D promotion

required

C

the matrix added, broadcast to the output's shape

required

alpha

the factor on A @ B, taken exactly; must be finite

1

beta

the factor on C, taken exactly; must be finite

1

reduce_batch

also sum over the output's batch dimensions, so each element is one sum over all batches

False

dtype

the output format, of the same kind as the inputs

the operands' promoted 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

With flush_to_zero=True, an operand promoted to a wider format is read by its own format: its values below that format's smallest normal number, or float32's for a narrower format, may be zeros (flushing).

Examples#

A linear layer with a bias, as torch.nn.Linear runs it: addmm(b, x, w.T). Here 128 tokens of hidden size 4096 go through a weight of 1024 outputs, 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 and bias scaled as in a trained model
x = torch.randn(128, 4096, generator=g).bfloat16()
w = (torch.randn(1024, 4096, generator=g) / 64).bfloat16()
b = (torch.randn(1024, generator=g) / 64).bfloat16()

# ExactRef's result for x @ w.T + b; the bias row is broadcast to every token
r = er.gemm(x, w.T, b)
print("shape:", r.rounded.shape)
# Row 0's first three elements: exact values, rounded once to bfloat16
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.423828125, 2.484375, -0.796875]
tolerance: [0.0, 0.0, 0.0]

Each element is beta * C + alpha * (A @ B) computed exactly, then rounded once. alpha and beta are taken exactly as given, and must be finite. By default the tolerance covers normal accumulation, the order ordinary kernels add in: index order, or a few SIMD lanes side by side. Before the final rounding, it assumes each step rounds in the compute format, the format an implementation adds in along the way: float32 by default for inputs narrower than float32, such as these, and the input format otherwise.

addmv and addr#

addmv multiplies a matrix by a vector, as a decoding step does for one token, and addr adds an outer product, as a rank-1 update of a weight does. addmv is gemm with a 1-D operand, and addr is gemm with its two vectors reshaped into a column and a row:

Code
# One token's vector through the layer, plus the bias: the addmv shape
token = torch.randn(4096, generator=g).bfloat16()
print("addmv:", er.gemm(w, token, b).rounded.shape)

# A rank-1 update of the weight, w + 0.5 * u v^T: the addr shape, with u as
# a column and v as a row
u = er.asarray(torch.randn(1024, generator=g).bfloat16()).reshape((1024, 1))
v = er.asarray(torch.randn(4096, generator=g).bfloat16()).reshape((1, 4096))
print("addr:", er.gemm(u, v, w, alpha=0.5).rounded.shape)
Output
addmv: (1024,)
addr: (1024, 4096)

beta = 0 and alpha = 0#

BLAS callers pass beta = 0 to write into a buffer they have not initialized, such as one from torch.empty. Whatever the buffer holds must not reach the output. With beta = 0, C is not read, and with alpha = 0, neither A nor B is, as in PyTorch and BLAS:

Code
# A buffer can hold anything, NaN included: this one holds only NaN
buffer = torch.full((128, 1024), float("nan")).bfloat16()

# With beta=0 the result is the product alone, and no NaN reaches it
r0 = er.gemm(x, w.T, buffer, beta=0)
print("same as matmul:", r0.rounded.identical(er.matmul(x, w.T).rounded))
Output
same as matmul: True

Summing over batches: reduce_batch#

The weight gradient of a linear layer adds up the contributions of every token in every sequence of the batch. reduce_batch=True adds the output's batch dimensions into the sum, so each element is one exact sum over all batches, rounded once. With gradient accumulation over micro-batches, the gradient stored so far is C:

Code
# A layer of hidden size 1024, in float32
ws = torch.randn(1024, 1024, generator=g) / 32
ws_ = ws.clone().requires_grad_()
# Two micro-batches, each of 4 sequences of 128 tokens, with their output gradients
inputs = [torch.randn(4, 128, 1024, generator=g) for _ in range(2)]
grads = [torch.randn(4, 128, 1024, generator=g) for _ in range(2)]

# PyTorch's autograd for the first micro-batch; its gradient is stored in ws_.grad
torch.nn.functional.linear(inputs[0], ws_).backward(grads[0])
stored = ws_.grad.clone()
# The second micro-batch, which autograd adds to the stored gradient
torch.nn.functional.linear(inputs[1], ws_).backward(grads[1])

# grad^T @ input for each of the 4 sequences, summed over them, plus the stored
# gradient: 512 products and one more term per element, rounded once
total = er.gemm(grads[1].transpose(1, 2), inputs[1], stored, reduce_batch=True)
print("shape:", total.rounded.shape)
print("covered:", total.covers(ws_.grad).all())
Output
shape: (1024, 1024)
covered: True

PyTorch's addbmm rounds after each batch instead. To check it, call gemm once per batch and pass each call's result as the next call's C, as PyTorch equivalents shows. In such a chain, each call's bounds cover every value the earlier result allows, since the kernel may have stored any of them.

The normal answer#

normal() returns what an ordinary implementation computes. It adds the products in index order, then rounds alpha * sum and beta * C separately (beta * C needs no rounding when beta is 1, -1, i, or -i) and rounds their sum, with every step in the compute format. This is the order of a plain loop, and of Netlib's reference BLAS when A is transposed, so a plain loop kernel should match it bit for bit. Here such a kernel computes one head's attention scores the way BLOOM does, with baddbmm: the scale 1/sqrt(64) as alpha and the ALiBi position bias as C:

Code
def loop_kernel(A, B, C, alpha, beta):
    """A plain float32 GEMM: products added in index order, then the scaling."""
    acc = torch.zeros(A.shape[0], B.shape[1])
    for i in range(A.shape[1]):
        # Add the products of column i of A and row i of B, rounding each step
        acc = acc + A[:, i:i + 1] * B[i:i + 1, :]
    return alpha * acc + beta * C


# Queries and keys of one head: 512 positions with head dimension 64
q1 = torch.randn(512, 64, generator=g)
k1 = torch.randn(512, 64, generator=g)
# The ALiBi bias for a head with slope 0.5: half of each key's position
bias = 0.5 * torch.arange(512.0)

# The kernel's scores, and ExactRef's normal answer for the same gemm
scores = loop_kernel(q1, k1.T, bias, 0.125, 1.0)
normal = er.gemm(q1, k1.T, bias, alpha=0.125).normal()
print("identical:", normal.identical(er.asarray(scores)))
Output
identical: True

Checking PyTorch#

To check an implementation, pass its output to covers(). Here it checks PyTorch's linear 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(torch.nn.functional.linear(x, w, b)).all())

# The same layer in float32
x32, w32, b32 = x.float(), w.float(), b.float()
out32 = torch.nn.functional.linear(x32, w32, b32)
print("float32 covered:", er.gemm(x32, w32.T, b32).covers(out32).all())
Output
bfloat16 covered: True
float32 covered: True

Backward#

er.gemm.backward(A, B, C, grad, alpha=, beta=) returns grad_A = conj(alpha) grad @ B^H, grad_B = conj(alpha) A^H @ grad, and grad_C = conj(beta) grad, each summed over its operand's broadcast copies and rounded once. They are named outputs of one result, and gb["grad_C"] reads one as a result of its own. A bias is broadcast to every token, so its gradient adds up the output gradient over the tokens:

grad: one row per token token 1 token 2 token 3 add the rows round once grad_b the forward added b to every token's row, so its gradient sums over them

The bias gradient adds the output gradient over the tokens, as one sum rounded once.

Here the gradients check PyTorch's autograd for a bfloat16 linear layer with a bias, on 128 tokens of hidden size 1024:

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

# PyTorch's autograd, on copies that record gradients
hs_, wh_, bh_ = (t.clone().requires_grad_() for t in (hs, wh, bh))
torch.nn.functional.linear(hs_, wh_, bh_).backward(grad)

# ExactRef's gradients, held by name
gb = er.gemm.backward(hs, wh.T, bh, grad)
print("outputs:", list(gb.rounded))
# grad_C sums the output gradient over the 128 tokens: one sum per element
print("grad_C covered:", gb["grad_C"].covers(bh_.grad).all())
print("grad_A covered:", gb["grad_A"].covers(hs_.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_C']
grad_C covered: True
grad_A covered: True
grad_B covered: True

Full specification#

er.gemm#

gemm(A, B, C, *, alpha=1, beta=1, reduce_batch: bool = False, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, workers: int | None = None) -> Result#

D = beta C + alpha (A @ B), with matmul's batching and 1-D promotion and C broadcast to the output's shape (PyTorch's addmm, addmv, addr, baddbmm).

Each output element is the exact value rounded once to dtype (default: the operands' promoted format, as add promotes); dtype must be of the inputs' kind; convert across kinds with asarray(x, d) first. alpha and beta are taken exactly as given and must be finite (ValueError otherwise). With beta = 0 C is not read, and with alpha = 0 neither A nor B is, as in PyTorch and BLAS. With reduce_batch=True the output's batch dimensions are summed into the contraction, so each element is one exact sum over all batches (addbmm's exact form; PyTorch's addbmm rounds after each batch, which is a loop of gemm calls on earlier results). addr(C, v, w) is gemm with v as a column (m, 1) and w as a row (1, n).

tolerance() budgets the products rounded or fused in the compute format, alpha applied once on every product's way (to an operand, a product, a partial sum or the whole sum), beta C rounded once (not at all with beta 1 or -1, or i or -i, a wider C of shape () taken by value included, where the compute format holds the other operands' format) and added at any point (first, as PyTorch's CPU kernels do, or last), the additions in normal accumulation, and the final rounding; standard="any_order" allows any order of additions. With an alpha whose imaginary part is nonzero the normal tolerance is the any-order one. normal() adds the products in index order, then computes fl(fl(alpha * sum) + fl(beta * C)) in the compute format (the order of a plain loop, and of Netlib's reference BLAS when A is transposed; beta * C exact with beta 1, -1, i or -i). Integer results wrap on overflow unless overflow says otherwise. A non-finite input follows IEEE rules on the exact expression; for complex values in each part separately, as PyTorch's batched products do, with alpha and beta taken as exact coefficients: a zero part of a nonzero alpha or beta adds no term. A, B and C may also be earlier results.

er.gemm.backward#

backward(A, B, C, grad, *, alpha=1, beta=1, reduce_batch: bool = False, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, workers: int | None = None) -> Result#

Gradients of gemm(A, B, C, alpha=alpha, beta=beta) for the output gradient grad.

grad_A = conj(alpha) grad @ B^H, grad_B = conj(alpha) A^H @ grad and grad_C = conj(beta) grad, each summed over the copies that broadcasting (and reduce_batch) made of its operand, in that operand's shape and dtype. grad_A and grad_B are gemm calls with beta = 0 on matmul's backward operands, so each element is one exact value rounded once; PyTorch's product followed by its scaling is covered. grad_C is one product per element, as add's gradients: its default compute format is grad's, and it takes their zero signs, including where a complex beta other than 1 differs from PyTorch. grad must have the output's shape. A, B, C and grad may also be earlier results.

See also#

  • PyTorch equivalents: addmm, addmv, addr, baddbmm, and addbmm, with the roundings PyTorch adds.

  • Chains and any_of: for an implementation that scales an operand first, such as alpha * A, and stores the scaled values before the product.

  • Algorithms: gemm_mma, for gemm on tensor cores.

  • The proof.