Check fused attention kernels#
The problem#
You are checking a FlashAttention-style kernel. It processes the keys in
blocks with a running softmax, rounds the weights to bfloat16 before the
product with V, and maybe uses exp2 or a reciprocal of the row sum. Its
output differs from PyTorch's math path by more than a float32 tolerance, and
you cannot tell whether the difference is the kernel's method or a bug.
Why the usual approach falls short#
Each of those methods adds a rounding that attention itself,
softmax(Q @ K.T * scale) @ V, does not have. The operation's own tolerance,
how far a correct implementation's output can be from the exact answer
rounded once, rejects a correct kernel. A tolerance loosened until the kernel passes
accepts real bugs. What you need is the bound for exactly the methods your
kernel uses.
The solution#
Describe the kernel's methods with an AttentionAlgorithm, an
algorithm: ExactRef's model of
one specific way of computing attention, with its own bounds. Then check the
kernel's outputs against it.
Here a FlashAttention kernel is emulated in PyTorch, for causal attention in
bfloat16 with 8 heads, 1024 positions, and head dimension 64. It walks over
the keys in blocks of 128. For each query it keeps a running maximum score, a
running sum of weights, and a running weighted sum of value rows. Each block's
weights are exp(score - running maximum), not yet divided by their sum, and
are rounded to bfloat16 for the product with V. When the maximum grows, the
earlier sums are rescaled to it. The division by the row sum comes once, at
the end:
Online softmax: each block of keys updates the running maximum m, the running sum l, and the weighted sum of value rows, after rescaling the earlier sums to the new maximum. Only the end divides by l.
import math
import torch
import exactref as er
# Seeded, so every run uses the same values
g = torch.Generator().manual_seed(67)
def flash_attention(q, k, v, block=128):
"""Causal attention as FlashAttention computes it. Returns the output and logsumexp."""
# The kernel computes in float32 on its bfloat16 inputs
q, k, v = q.float(), k.float(), v.float()
# Attention's default scale, 1/sqrt(head dimension)
scale = 1 / math.sqrt(q.shape[-1])
# Each query's position, as a column, to mask the keys after it
query_positions = torch.arange(q.shape[-2])[:, None]
# Per query: the running maximum score, the running sum of weights, and the
# running weighted sum of value rows
running_max = torch.full(q.shape[:-1] + (1,), float("-inf"))
row_sum = torch.zeros(q.shape[:-1] + (1,))
acc = torch.zeros(q.shape)
for start in range(0, k.shape[-2], block):
# Scaled scores of every query against this block's keys
scores = (q @ k[..., start:start + block, :].transpose(-2, -1)) * scale
# Keys after the query get -inf, so their weight is 0
later = torch.arange(start, start + block) > query_positions
scores = scores.masked_fill(later, float("-inf"))
# The maximum score so far, this block included
new_max = torch.maximum(running_max, scores.amax(-1, keepdim=True))
# This block's weights, relative to the new maximum and not yet normalized
weights = torch.exp(scores - new_max)
# The factor that moves the earlier sums to the new maximum
rescale = torch.exp(running_max - new_max)
# Rescale the earlier sums, then add this block's
row_sum = row_sum * rescale + weights.sum(-1, keepdim=True)
# The same for the value rows, with the weights rounded to bfloat16
acc = acc * rescale + weights.bfloat16().float() @ v[..., start:start + block, :]
running_max = new_max
# Divide by the row sum once, and store the output in bfloat16
out = (acc / row_sum).bfloat16()
# logsumexp, the log of the row's sum of exp(score), stays in float32
lse = (running_max + torch.log(row_sum)).squeeze(-1)
return out, lse
# Queries, keys, and values in bfloat16: (batch, heads, positions, head dimension)
q, k, v = (torch.randn(1, 8, 1024, 64, generator=g).bfloat16() for _ in range(3))
# Run the kernel
out, lse = flash_attention(q, k, v)
ExactRef names attention's two outputs output and logsumexp, and a result
gives one as r["output"]. covers() says, per element, whether a correct
implementation can produce an output. The bounds of plain
er.scaled_dot_product_attention reject the output, because they do not allow
for the bfloat16 weights. An AttentionAlgorithm that describes the kernel's
methods accepts both of the kernel's outputs, out and lse:
# Plain attention's reference and bounds for the same inputs, with none of the
# kernel's methods
plain = er.scaled_dot_product_attention(q, k, v, is_causal=True)
print("plain attention covers output:", plain["output"].covers(out).all())
# The kernel's methods: a running softmax over blocks of 128 keys, and bfloat16 weights
flash = er.nn.attention.AttentionAlgorithm(online_softmax=True, block_size=128, weights="bfloat16")
# Check both outputs; covers() takes them by name and returns one bool array per name
checked = flash.covers({"output": out, "logsumexp": lse}, q, k, v, is_causal=True)
print("algorithm covers output:", checked.output.all())
print("algorithm covers logsumexp:", checked.logsumexp.all())
plain attention covers output: False
algorithm covers output: True
algorithm covers logsumexp: True
Leaving out a method the kernel uses fails it, so the check also confirms which methods the kernel really has:
# The same methods without the bfloat16 weights
no_bf16 = er.nn.attention.AttentionAlgorithm(online_softmax=True, block_size=128)
# Check the output alone
print("output covered:", no_bf16.covers({"output": out}, q, k, v, is_causal=True).output.all())
output covered: False
The same check works on a real kernel. Here it is PyTorch's FlashAttention-2 backend on NVIDIA's DGX Spark (GB10), with the methods that Algorithms lists for it:
from torch.nn.attention import SDPBackend, sdpa_kernel
# PyTorch's FlashAttention-2 backend on the GPU, on the same inputs
with sdpa_kernel(SDPBackend.FLASH_ATTENTION):
out = torch.nn.functional.scaled_dot_product_attention(
q.cuda(), k.cuda(), v.cuda(), is_causal=True).cpu()
# FlashAttention-2's methods: blocks of 128 keys, exp2 and a fast exp and log,
# a reciprocal of the row sum, bfloat16 weights, and products on tensor cores
fa2 = er.nn.attention.AttentionAlgorithm(
online_softmax=True, block_size=128, exp2=True, reciprocal=True, exp_ulps=3,
fast_log=True, weights="bfloat16", mma=er.MMAStep(16, 25, -133, 64))
# CUDA's documented error of FlashAttention-2's fast log needs ulps=4
print("covered:", fa2.covers({"output": out}, q, k, v, is_causal=True, ulps=4).output.all())
The backward#
To check a fused backward kernel that takes the forward's out and
logsumexp as inputs, call
flash.backward_covers(gradients, q, k, v, grad, is_causal=True, out=out, logsumexp=lse),
with the kernel's gradients in gradients by name: grad_query, grad_key,
and grad_value. Without out and logsumexp, backward_covers() checks a
backward that recomputes the softmax itself. Some kernels, such as PyTorch's
CPU flash kernel, add the gradients block by block into gradients stored in
the output format. Describe that with the backward_blocks argument of
AttentionAlgorithm.