Backward#

Every operation except matrix_exp_frechet has a backward operation, so you can check gradients, such as the ones PyTorch's autograd computes, the same way you check forward outputs. Each gradient is the exact value rounded once, with a tolerance: how far from it a correct implementation's output can be. Where the forward has a normal answer, what an ordinary implementation that adds in index order computes, emulated exactly, the gradient has one too.

Calling a backward#

There are two ways. The standalone .backward takes the forward's inputs and the output gradient. A forward result's backward(grad) reuses its inputs. Here both are used on a bfloat16 linear layer, 128 tokens of hidden size 1024 through a 1024 by 1024 weight, with an upstream gradient from the next layer:

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 weight, and the gradient of its output
x = torch.randn(128, 1024, generator=g).bfloat16()
w = (torch.randn(1024, 1024, generator=g) / 32).bfloat16()
grad = torch.randn(128, 1024, generator=g).bfloat16()

# The standalone backward of x @ w.T: the forward's inputs, then the output gradient
gb = er.matmul.backward(x, w.T, grad)
# Each gradient, rounded once to bfloat16, named grad_ plus the input's name
# (matmul's inputs are A and B)
print("grad_A:", gb.rounded.grad_A.shape)
print("grad_B:", gb.rounded.grad_B.shape)

# The same grad_B from the forward result's backward, which reuses x and w.T
again = er.matmul(x, w.T).backward(grad)
print("same grad_B:", again.rounded.grad_B.identical(gb.rounded.grad_B))
Output
grad_A: (128, 1024)
grad_B: (1024, 1024)
same grad_B: True

The output gradient grad is required; it has no default of ones. Each gradient is named grad_ plus the input's name:

Backward

Gradients

er.matmul.backward(A, B, grad)

grad_A, grad_B

er.gemm.backward(A, B, C, grad, alpha=, beta=)

grad_A, grad_B, grad_C

er.add.backward(x, y, grad, alpha=)

grad_x, grad_y

er.subtract.backward(x, y, grad, alpha=)

grad_x, grad_y

er.multiply.backward(x, y, grad)

grad_x, grad_y

er.divide.backward(x, y, grad)

grad_x, grad_y

er.reciprocal.backward(x, grad)

grad_x

er.convert_float_format.backward(x, grad)

grad_x

er.sqrt.backward(z, grad)

grad_z

er.rsqrt.backward(x, grad)

grad_x

er.exp.backward(x, grad), and the same for expm1, log, log1p, tanh, and sigmoid

grad_x

er.sum.backward(x, grad, axis=, keepdims=)

grad_x

er.mean.backward(x, grad, axis=, keepdims=)

grad_x

er.cumulative_sum.backward(x, grad, axis)

grad_x

er.var.backward(x, grad, axis=, correction=, keepdims=), and the same for std

grad_x

er.scatter_add.backward(base, index, src, grad, axis=, alpha=)

grad_base, grad_src

er.softmax.backward(x, grad, axis=), and the same for log_softmax

grad_x

er.logsumexp.backward(x, grad, axis=, keepdims=)

grad_x

er.layer_norm.backward(x, grad, normalized_shape, weight, bias, eps)

grad_x, grad_weight, grad_bias

er.rms_norm.backward(x, grad, normalized_shape, weight, eps)

grad_x, grad_weight

er.batch_norm.backward(x, grad, running_mean, running_var, weight, bias, training, eps)

grad_x, grad_weight, grad_bias

er.convolution.backward(input, weight, bias, grad, ...)

grad_input, grad_weight, grad_bias

er.scaled_dot_product_attention.backward(query, key, value, grad, ...)

grad_query, grad_key, grad_value

er.matrix_exp.backward(A, grad)

grad_A

er.fft.fft.backward(x, grad, n=, axis=, norm=), and the same for ifft, rfft, irfft, hfft, and ihfft

grad_x; grad_X for ifft and irfft

matrix_exp_frechet has no backward. grad must have the forward output's shape. Where the forward has several outputs, grad is the gradient of the main one: var, std, or batch normalization's output. The normalizations take x and grad first, then the forward's other arguments. A scalar operand of add, subtract, multiply, or divide gets no gradient; the other operand's is still named, as rounded.grad_x or rounded.grad_y. A normalization's weight and bias get gradients only where they are given.

An input that the forward broadcast, such as a bias row added to every token, gets the sum of the gradients of all its copies:

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.

Checking against PyTorch's autograd#

Run PyTorch's backward, then compare each gradient with covers(), which says per element whether a correct implementation can produce that output. For the layer above:

Code
# Copies of x and w that record gradients for PyTorch's autograd
x_, w_ = x.clone().requires_grad_(), w.clone().requires_grad_()
# PyTorch's backward, which stores the gradients in x_.grad and w_.grad
torch.nn.functional.linear(x_, w_).backward(grad)

# gb["grad_A"] is a result holding just grad_A, so it has covers()
print("grad_A covered:", gb["grad_A"].covers(x_.grad).all())
# grad_B is the gradient of w.T: transposed, it is the gradient of w
print("grad_B covered:", gb["grad_B"].transpose(0, 1).covers(w_.grad).all())
Output
grad_A covered: True
grad_B covered: True

Attention takes one more step. On the CPU, PyTorch runs its flash kernel, which rounds in places the operation itself does not. It multiplies by a rounded reciprocal of the row sum. Its backward reuses the forward's output and logsumexp, and adds the gradients block by block. An attention algorithm, one specific way of computing attention with its own bounds, describes exactly that kernel. Here it checks causal attention with 4 heads, 1024 positions, and head dimension 64, long enough that the kernel's blocks split:

Code
# Query, key, and value of shape (batch, heads, positions, head dimension)
q, k, v = (torch.randn(1, 4, 1024, 64, generator=g) for _ in range(3))
# Copies that record gradients for PyTorch's autograd
q_, k_, v_ = (t.clone().requires_grad_() for t in (q, k, v))
# PyTorch's attention with a causal mask: no query attends to a later key
out = torch.nn.functional.scaled_dot_product_attention(q_, k_, v_, is_causal=True)
# A random output gradient, and PyTorch's backward from it
grad = torch.randn(1, 4, 1024, 64, generator=g)
out.backward(grad)

# PyTorch's CPU kernel: normalization by a rounded reciprocal, and gradients
# added in blocks of 256 queries and 512 keys, its sizes for 768 queries or more
cpu_kernel = er.nn.attention.AttentionAlgorithm(
    reciprocal=True, backward_blocks=(256, 512))
# ExactRef's forward, for its logsumexp, because PyTorch's function does not
# return its own
fwd = er.scaled_dot_product_attention(q, k, v, is_causal=True)
# The gradients PyTorch computed, by name
grads = {"grad_query": q_.grad, "grad_key": k_.grad, "grad_value": v_.grad}
# Judge them as the kernel's fused backward, given its stored output and the
# forward's logsumexp result
checked = cpu_kernel.backward_covers(
    grads, q, k, v, grad, out=out.detach(), logsumexp=fwd["logsumexp"], is_causal=True)
for name in grads:
    print(f"{name} covered:", checked[name].all())
Output
grad_query covered: True
grad_key covered: True
grad_value covered: True

These inputs are float32. For bfloat16 and float16 inputs, the kernel's forward uses an approximate exp. A check like this one, which passes ExactRef's own forward result as logsumexp, then needs ulps, the error in ulps that its bounds allow each exp and log, set to the kernel's exp_ulps value. Algorithms lists them.

What each backward computes#

  • matmul: grad_A = grad @ B^H and grad_B = A^H @ grad, where ^H is the conjugate transpose, as PyTorch uses for complex inputs. If broadcasting copied an operand in the forward, its gradient adds up the contributions of all the copies. ExactRef computes each gradient, copies included, as one matmul, so every element is rounded once, and its tolerance and normal answer are that matmul's. PyTorch does the same, except when both operands have batch dimensions that broadcast against each other. Then PyTorch rounds each batch's product before adding up the copies: an extra rounding the default tolerance does not allow for.

  • gemm: 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.

  • add: grad_x = grad and grad_y = conj(alpha) * grad, each summed over its operand's broadcast copies.

  • multiply: grad_x = grad * conj(y) and grad_y = grad * conj(x), each summed over its operand's broadcast copies. Where an operand is broadcast, PyTorch rounds each product before summing the copies, an extra rounding the default tolerance does not allow for.

  • subtract: grad_x = grad and grad_y = -conj(alpha) * grad, each summed over its operand's broadcast copies.

  • divide: grad_x = grad / conj(y) and grad_y = -grad * conj(x / y**2), each summed over its operand's broadcast copies. The tolerance bounds PyTorch's steps, grad / conj(y) and -grad * conj((x / y) / y).

  • reciprocal: grad_x = -grad / conj(x)**2. The tolerance bounds PyTorch's steps, -grad * conj(r * r) with r = 1 / x. In float16 and bfloat16 PyTorch rounds every step of divide's and reciprocal's gradients to the dtype: check them with compute= the dtype.

  • convert_float_format: grad_x is grad rounded once to x's format.

  • sqrt: grad_z = grad / (2 * conj(sqrt(z))). The tolerance bounds PyTorch's steps, grad / (2 * conj(result)).

  • rsqrt: grad_x = -grad / (2 * conj(x * sqrt(x))). The tolerance bounds PyTorch's steps, (-0.5 * grad) * conj(result**3).

  • exp and expm1: grad_x = grad * exp(x). The tolerance bounds PyTorch's steps on the forward's result, grad * result and grad * (result + 1).

  • log: grad_x = grad / x, with divide's tolerance; log1p: grad_x = grad / (1 + x), with PyTorch's steps, grad / (x + 1).

  • tanh: grad_x = grad * (1 - tanh(x)**2). The tolerance bounds PyTorch's steps, grad * (1 - result * result).

  • sigmoid: grad_x = grad * s * (1 - s), with s = sigmoid(x). The tolerance bounds PyTorch's steps, (grad * (1 - result)) * result.

  • The six functions above conjugate their factor for a complex input, as PyTorch does: grad * conj(exp(x)), for example. In float16 and bfloat16, check the gradients of expm1 and log1p, and float16 sigmoid's, with compute= the dtype. For a CUDA kernel, check all six that way.

  • sum: grad_x holds, at every element of x, the gradient of the output it was summed into.

  • mean: grad_x holds that gradient divided by the number of elements averaged. The tolerance bounds the one division.

  • cumulative_sum: grad_x at element i of each line is the sum of grad from i to the line's end: the running sum of grad taken from the far end of the axis, with a running sum's tolerance.

  • var: grad_x = 2 * grad * (x - mean) / (count - correction). The tolerance bounds PyTorch's steps, (2 / (count - correction)) * grad * (x - mean). In float16 and bfloat16 PyTorch rounds each step to the dtype: check with compute= the dtype.

  • std: grad_x = grad * (x - mean) / ((count - correction) * std), and 0 where the standard deviation is 0, as PyTorch sets it. The tolerance bounds PyTorch's steps, grad / (2 * result) and then var's. In float16 and bfloat16, check with compute= the dtype.

  • scatter_add: grad_base = grad, and grad_src is conj(alpha) * grad read at each source element's output position.

  • softmax: with P the softmax of a row, grad_x = P * (grad - sum(grad * P)). The tolerance bounds PyTorch's CPU steps on the forward's result, (grad - S) * result with S the row's sum of grad * result. CUDA's steps, grad * result - result * S, are softmax_algorithm(products=True) (softmax algorithms).

  • log_softmax: grad_x = grad - P * sum(grad). The tolerance bounds PyTorch's steps, grad - exp(result) * sum(grad).

  • logsumexp: grad_x = grad * softmax(x) over the reduced elements. The tolerance bounds PyTorch's steps, grad * exp(x - result). In float16 and bfloat16 PyTorch rounds each step to the dtype: check with compute= the dtype.

  • layer_norm, rms_norm, and batch_norm: each gradient is the exact value rounded once, and the tolerance bounds the steps of PyTorch's CPU backward kernel. In float16 and bfloat16, check layer_norm's gradients, and batch_norm's in training, with compute= the dtype. grad_bias is the sum of grad over the normalized slices, or over each channel for batch normalization. A slice, or a channel in training, with a value that is not finite gets NaN gradients. In evaluation batch_norm uses the running statistics instead, so such a value changes only the gradients it enters, and grad_x does not depend on x.

  • convolution: grad_input is grad spread back through the weights (the transposed contraction, or the plain one for a transposed convolution), grad_weight is each input window times grad, summed over the batch and the positions, and grad_bias is grad summed over the batch and the positions. Each element is one exact sum rounded once.

  • scaled_dot_product_attention: with P the attention weights, dP = grad V^T, D = sum P * dP per row, and dS = P * (dP - D), it returns grad_value = P^T grad, grad_query = scale * dS K, and grad_key = scale * dS^T Q. The tolerance and the special values follow autograd through PyTorch's math backend (SDPBackend.MATH). Dropout must be 0, and a float mask gets no gradient. A fused backward kernel rounds differently: its tolerance is AttentionAlgorithm.backward_tolerance.

  • matrix_exp: grad_A = matrix_exp_frechet(A^H, grad), which is what PyTorch computes.

  • The Fourier transforms: each gradient is the transform of grad with the exponent's sign flipped, scaled as the forward is. It follows PyTorch's convention, dL/dRe + i dL/dIm, and is its real part for a real input. For rfft and ihfft, grad is filled with zeros past the half spectrum first; for irfft and hfft, the entries the forward counted twice are doubled. Entries the forward trimmed get +0. There is no normal answer.

Three backwards can raise ReferenceUnavailableError instead of returning. In attention's, grad_key and grad_value, and grad_query when it adds up broadcast copies of a query row, add terms from rows with different softmax denominators. ExactRef can find these sums exactly only when every term is a rational number. Otherwise, a sum that lies exactly where the rounding switches from one output value to the next, or that is exactly zero because its terms cancel, raises. logsumexp's raises for a complex input where a part of the gradient is exactly zero because its terms cancel. matrix_exp's raises on the same kinds of input as matrix_exp itself. See Guarantees and limits.

Where to go next#