Check gradients and custom backward kernels#
The problem#
You wrote a custom torch.autograd.Function with its own backward, or a
fused backward kernel, and need to know its gradients are right.
torch.autograd.gradcheck compares with finite differences, which needs
float64 and is approximate. Comparing with PyTorch's own autograd in float32
or bfloat16 runs into the same rounding questions as the forward.
Why the usual approach falls short#
Finite differences check the formula, not the rounding of a float32 or bfloat16 gradient kernel. Autograd's gradient is one correct answer among many, and a hand-picked tolerance around it fails or passes for the wrong reasons, just as in the forward.
The solution#
Every operation but matrix_exp_frechet also has a backward, such as
er.matmul.backward. Like the forward, it gives each gradient as the exact
value rounded once, with a tolerance: per element, how far a correct
implementation's gradient can be from that value. Check every gradient your function returns with covers(),
which says per element whether a correct implementation can produce it.
Here the function is a fused linear layer with a bias, x @ weight.T + bias
in one call, with a hand-written backward. It runs in bfloat16 on a layer of
width 1024, for 128 tokens. Its ExactRef counterpart is er.gemm, PyTorch's
addmm, whose backward gives the gradients of its three inputs, A, B, and
C, as named outputs: grad_ plus the input's name, read as
grads["grad_A"] and so on:
import torch
import exactref as er
# Seeded, so every run uses the same values
g = torch.Generator().manual_seed(67)
class LinearBias(torch.autograd.Function):
"""x @ weight.T + bias in one call, with its own backward."""
@staticmethod
def forward(ctx, x, weight, bias):
# Keep the inputs the backward needs
ctx.save_for_backward(x, weight)
# bias + x @ weight.T as one fused call
return torch.addmm(bias, x, weight.T)
@staticmethod
def backward(ctx, grad):
x, weight = ctx.saved_tensors
# The gradients of x, weight, and bias, from the output's gradient grad
return grad @ weight, grad.T @ x, grad.sum(0)
# The layer's input, weight, bias, and the gradient of its output, in bfloat16
x = torch.randn(128, 1024, generator=g).bfloat16()
weight = (torch.randn(1024, 1024, generator=g) / 32).bfloat16()
bias = (torch.randn(1024, generator=g) / 32).bfloat16()
grad = (torch.randn(128, 1024, generator=g) / 32).bfloat16()
# Copies that track gradients; x, weight, and bias themselves stay as they are
x_, weight_, bias_ = (t.clone().requires_grad_() for t in (x, weight, bias))
# Run the function and its backward, which fills x_.grad, weight_.grad, and bias_.grad
LinearBias.apply(x_, weight_, bias_).backward(grad)
# ExactRef's gradients of gemm(A, B, C) = C + A @ B, with A = x, B = weight.T,
# and C = bias, for the same output gradient
grads = er.gemm.backward(x, weight.T, bias, grad)
# Check each gradient. grad_B is the gradient of weight.T, so it is compared
# with the transpose of weight's gradient.
print("grad x covered:", grads["grad_A"].covers(x_.grad).all())
print("grad weight covered:", grads["grad_B"].covers(weight_.grad.T).all())
print("grad bias covered:", grads["grad_C"].covers(bias_.grad).all())
grad x covered: True
grad weight covered: True
grad bias covered: True
The bias was added to every token's row, so its gradient adds the output gradient's rows together. ExactRef gives that sum as the exact value rounded once, like every other gradient:
The bias gradient adds the output gradient over the tokens: one sum per feature, rounded once.
A backward that adds those rows up in a bfloat16 running sum, one token at a time, loses accuracy at every addition. The check catches it, on the gradient where the bug is:
class BuggyBias(LinearBias):
"""LinearBias with a buggy backward."""
@staticmethod
def backward(ctx, grad):
x, weight = ctx.saved_tensors
# The bug: the bias gradient kept in bfloat16 while the rows are added
grad_bias = torch.zeros(grad.shape[1], dtype=grad.dtype)
for row in grad:
grad_bias = grad_bias + row
return grad @ weight, grad.T @ x, grad_bias
# Fresh copies, and the buggy backward
x_, weight_, bias_ = (t.clone().requires_grad_() for t in (x, weight, bias))
BuggyBias.apply(x_, weight_, bias_).backward(grad)
# The same ExactRef gradients judge the new ones
print("grad x covered:", grads["grad_A"].covers(x_.grad).all())
print("grad weight covered:", grads["grad_B"].covers(weight_.grad.T).all())
print("grad bias covered:", grads["grad_C"].covers(bias_.grad).all())
grad x covered: True
grad weight covered: True
grad bias covered: False
Attention's backward works the same way, with the gradients grad_query,
grad_key, and grad_value. A fused attention backward kernel rounds in
places attention itself does not; check it with the backward_covers() of the
matching attention algorithm,
which models those extra roundings, as
Check fused attention kernels shows.