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:
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))
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 |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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:
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:
# 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())
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:
# 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())
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^Handgrad_B = A^H @ grad, where^His 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, andgrad_C = conj(beta) grad, each summed over its operand's broadcast copies and rounded once.add:
grad_x = gradandgrad_y = conj(alpha) * grad, each summed over its operand's broadcast copies.multiply:
grad_x = grad * conj(y)andgrad_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 = gradandgrad_y = -conj(alpha) * grad, each summed over its operand's broadcast copies.divide:
grad_x = grad / conj(y)andgrad_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)withr = 1 / x. In float16 and bfloat16 PyTorch rounds every step ofdivide's andreciprocal's gradients to the dtype: check them withcompute=the dtype.convert_float_format:
grad_xisgradrounded once tox'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 * resultandgrad * (result + 1).log:
grad_x = grad / x, withdivide'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), withs = 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 ofexpm1andlog1p, and float16sigmoid's, withcompute=the dtype. For a CUDA kernel, check all six that way.sum:
grad_xholds, at every element ofx, the gradient of the output it was summed into.mean:
grad_xholds that gradient divided by the number of elements averaged. The tolerance bounds the one division.cumulative_sum:
grad_xat elementiof each line is the sum ofgradfromito the line's end: the running sum ofgradtaken 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 withcompute=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 thenvar's. In float16 and bfloat16, check withcompute=the dtype.scatter_add:
grad_base = grad, andgrad_srcisconj(alpha) * gradread at each source element's output position.softmax: with
Pthe 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) * resultwithSthe row's sum ofgrad * result. CUDA's steps,grad * result - result * S, aresoftmax_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 withcompute=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, andbatch_norm's in training, withcompute=the dtype.grad_biasis the sum ofgradover 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 evaluationbatch_normuses the running statistics instead, so such a value changes only the gradients it enters, andgrad_xdoes not depend onx.convolution:
grad_inputisgradspread back through the weights (the transposed contraction, or the plain one for a transposed convolution),grad_weightis each input window timesgrad, summed over the batch and the positions, andgrad_biasisgradsummed over the batch and the positions. Each element is one exact sum rounded once.scaled_dot_product_attention: with
Pthe attention weights,dP = grad V^T,D = sum P * dPper row, anddS = P * (dP - D), it returnsgrad_value = P^T grad,grad_query = scale * dS K, andgrad_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 isAttentionAlgorithm.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
gradwith 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. Forrfftandihfft,gradis filled with zeros past the half spectrum first; forirfftandhfft, 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#
Check gradients and custom backward kernels: a custom
autograd.Functionor a fused backward.Algorithms: fused attention backward kernels.
Chains and any_of: gradients passed on to a later step.