scaled_dot_product_attention#
Scaled dot-product attention is the core of transformer models. Each query
vector scores every key vector with a dot product, scaled by 1/sqrt(E) for
vectors of length E. A softmax turns each query's scores into weights:
exponentials normalized to sum to 1. The output for the query is the
weighted average of the value vectors. A mask can hide keys, such as future
positions in a language model. Implementations differ a lot: PyTorch's math
path computes the weights as a full matrix, while fused kernels such as
FlashAttention process the keys in blocks with a running softmax and round
in extra places.
In ExactRef, er.scaled_dot_product_attention(query, key, value, ...), also
er.nn.attention.scaled_dot_product_attention, computes
softmax(Q K^T * scale + mask) V over the key axis, with the arguments,
shapes, and special values of
torch.nn.functional.scaled_dot_product_attention. It takes real
floating-point inputs, and the output can be any format of that
kind. To check another implementation's output against
it, use covers(), or, for a kernel that rounds in further places, an
attention algorithm (a named way of computing attention, with its own
bounds), as in Checking PyTorch below. Any input,
the mask included, can also be an earlier result, to check a chain
of steps: the bounds then cover every value that result allows, since the
implementation may have stored any of them.
The result holds the reference, the exact answer rounded once. Its
tolerance, per element how far a correct implementation's output can be from
the reference, allows for one rounding at each step of the computation
below: the steps where every correct implementation has to round
(boundaries), which r.boundaries lists. The weights
stay unnormalized until the last step, as in fused kernels:
Attention for one query, as the tolerance models it: the weighted sum of the values is divided by the row sum at the end. Kernels that round in further places need an attention algorithm.
Arguments#
Argument |
Meaning |
Default |
|---|---|---|
|
real arrays of shapes |
required |
|
a bool mask (True keeps a key) or a float mask added to the scaled scores (-inf removes a key) |
|
|
must be 0: dropout is random and has no reference |
|
|
keep key |
|
|
the factor on the scores; must be finite |
|
|
allow fewer key and value heads than query heads |
|
|
the output format, of the same kind as the inputs |
the input format |
|
the rounding mode of the reference and of a correct implementation's final rounding into the output format |
|
|
what a result past the output format's range becomes: |
each format's own rule |
|
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 |
Examples#
One attention layer of a language model: causal self-attention with 8 heads,
1024 positions, and head dimension 64, in bfloat16. Attention has two
named outputs, output and
logsumexp: rounded and tolerance() hold each by name, and a["output"]
is a result for that output alone:
import torch
import exactref as er
# Seeded, so every run uses the same values
g = torch.Generator().manual_seed(67)
# Query, key, and value of shape (batch, heads, positions, head dimension)
q, k, v = (torch.randn(1, 8, 1024, 64, generator=g).bfloat16() for _ in range(3))
# ExactRef's result for causal attention on them
a = er.scaled_dot_product_attention(q, k, v, is_causal=True)
# a.rounded holds both outputs, by name
print("outputs:", list(a.rounded))
print("output:", a.rounded.output.shape, a.rounded.output.dtype.name)
print("logsumexp:", a.rounded.logsumexp.shape, a.rounded.logsumexp.dtype.name)
outputs: ['output', 'logsumexp']
output: (1, 8, 1024, 64) bfloat16
logsumexp: (1, 8, 1024) float32
output is the attention output, each element the exact value rounded once.
logsumexp is each query's log(sum(exp(logits))), which fused kernels
keep for their backward pass. It is in the compute format of the
output, float32 for formats narrower than float32, as fused kernels return
it.
Masks, causality, and scale#
A bool mask keeps a key where it is True, and a float mask is added to the
scaled scores, so -inf removes a key. is_causal=True keeps key j for
query i only when j <= i, and scale defaults to 1/sqrt(E), as in
PyTorch. In a batch of sequences of different lengths, the shorter ones are
padded to one length, and a mask removes the padded keys. Here a sequence of
300 tokens is padded to the batch's 512 positions. Its padding mask and the
causal mask combine, and the padded sequence gets the same reference as the
sequence on its own:
# A shorter name for the operation
sdpa = er.scaled_dot_product_attention
# A sequence of 300 tokens, padded to 512 positions
qp, kp, vp = (torch.randn(1, 8, 512, 64, generator=g).bfloat16() for _ in range(3))
# True for the keys of real tokens, and True for key j <= query i
real = torch.arange(512) < 300
causal = torch.ones(512, 512, dtype=torch.bool).tril()
# Both masks at once: (512, 512), broadcast over the batch and the heads
padded = sdpa(qp, kp, vp, attn_mask=real & causal)
# The sequence alone: its 300 tokens, with is_causal
alone = sdpa(qp[:, :, :300], kp[:, :, :300], vp[:, :, :300], is_causal=True)
# The padded sequence's first 300 queries, head by head, against the sequence alone
rows = [head[:300] for head in padded.rounded.output.tolist()[0]]
print("same reference:", rows == alone.rounded.output.tolist()[0])
same reference: True
A masked key gets weight exactly 0, so padding changes nothing.
Grouped-query attention#
With enable_gqa, several query heads share each key and value head, as in
grouped-query attention: the query's head axis (the third from the end) is a
multiple of the key's and value's. Here 32 query heads share 8 key and value
heads, as in Llama 3 8B, with head dimension 128:
# 32 query heads, and 8 key and value heads, for 512 positions
gq = torch.randn(1, 32, 512, 128, generator=g).bfloat16()
gk, gv = (torch.randn(1, 8, 512, 128, generator=g).bfloat16() for _ in range(2))
grouped = sdpa(gq, gk, gv, is_causal=True, enable_gqa=True)
print("output:", grouped.rounded.output.shape)
# Query heads 0 to 3 use key head 0, heads 4 to 7 key head 1, and so on
gk4, gv4 = gk.repeat_interleave(4, dim=1), gv.repeat_interleave(4, dim=1)
repeated = sdpa(gq, gk4, gv4, is_causal=True)
print("same as repeated heads:", grouped.rounded.output.identical(repeated.rounded.output))
output: (1, 32, 512, 128)
same as repeated heads: True
Tolerance options#
The tolerance allows the implementation's exp and log to be off by up to
ulps units in the last place each. The default, 1, accepts either float
next to the exact value. A kernel with a less accurate exp needs a larger
value: CUDA's is within 2. Here is the largest tolerance for one float32 head
of 512 positions:
# One head of the first example, its first 512 positions, in float32
h32 = sdpa(*(t[:, :1, :512].float() for t in (q, k, v)), is_causal=True)
# The largest tolerance over the output's elements, with the default ulps
print("default:", max(h32.tolerance().output.scalars()))
# The same when exp and log may each be off by up to 8 ulps
print("ulps=8:", max(h32.tolerance(ulps=8).output.scalars()))
default: 2.765655517578125e-05
ulps=8: 3.5881996154785156e-05
Special values and dropout#
A NaN that an earlier layer produced for one token reaches attention in that
token's query, key, and value. A NaN in a query makes only that query's row
NaN. A NaN in a key or a value reaches only the rows that keep that key. A
masked key takes no part in a row's reference, whatever its score or value,
so the rows whose mask hides it keep a finite reference. A kernel that still
computes a masked key's terms, as PyTorch's math path does, gets NaN there
(the mask's -inf plus a NaN score is NaN, and a weight of 0 times a NaN value
is NaN), so may_be("nan") allows NaN in those rows. A kernel that skips
masked keys, as PyTorch's CPU flash kernel does, keeps them finite. Both are
covered.
from torch.nn.attention import SDPBackend, sdpa_kernel
# The first example's head 0, its first 512 positions, in float32, and a NaN
# at token 100
q0, k0, v0 = (t[:, :1, :512].float() for t in (q, k, v))
q_nan, k_nan = q0.clone(), k0.clone()
q_nan[0, 0, 100, 0] = k_nan[0, 0, 100, 0] = float("nan")
def nan_rows(result):
"""How many queries' output rows hold a NaN in the reference."""
return sum(any(x != x for x in row) for row in result.rounded.output.tolist()[0][0])
# Only query 100's row
print("NaN in a query:", nan_rows(sdpa(q_nan, k0, v0, is_causal=True)))
# The 412 rows that keep key 100, from row 100 on; rows 0 to 99 mask it
r_key = sdpa(q0, k_nan, v0, is_causal=True)
print("NaN in a key:", nan_rows(r_key))
# PyTorch's math path computes the masked terms, and its flash kernel skips them
for backend in (SDPBackend.MATH, SDPBackend.FLASH_ATTENTION):
with sdpa_kernel(backend):
out = torch.nn.functional.scaled_dot_product_attention(q0, k_nan, v0, is_causal=True)
print(f"{backend.name} covered:", r_key["output"].covers(out).all())
NaN in a query: 1
NaN in a key: 412
MATH covered: True
FLASH_ATTENTION covered: True
In rows 0 to 99, may_be("nan") is True, so the math path's NaN there is
covered, and so is the flash kernel's finite output.
A row with no kept key gets weight 0 on every key: its output is 0 and its
logsumexp -inf, as
Reading complicated tolerances
shows. Dropout is random and has no reference, so any dropout_p other than
0 raises ValueError.
Checking PyTorch#
PyTorch's CPU kernel does not compute attention the way the tolerance of
er.scaled_dot_product_attention itself assumes. That tolerance assumes one
softmax over all keys and a division by the row sum. The CPU kernel runs its
softmax over blocks of 512 keys and multiplies by a rounded reciprocal of the
row sum instead. For bfloat16 and float16 inputs it also rounds the weights
and uses an approximate exp. So this check describes the kernel with a
matching attention algorithm,
whose covers() takes the outputs by name. With 1024 keys, the kernel's
blocks split:
# PyTorch's CPU kernel for bfloat16; exp_ulps=8192 covers its fast exp on every machine
cpu_bf16 = er.nn.attention.AttentionAlgorithm(
online_softmax=True, block_size=512, reciprocal=True, weights="bfloat16", exp_ulps=8192)
# PyTorch's output for the first example
out = torch.nn.functional.scaled_dot_product_attention(q, k, v, is_causal=True)
# The same kernel through its operator, which also returns logsumexp
out_op, lse = torch.ops.aten._scaled_dot_product_flash_attention_for_cpu(
q, k, v, is_causal=True)[:2]
print("same output:", torch.equal(out, out_op))
# Could that kernel produce both of PyTorch's outputs?
checked = cpu_bf16.covers({"output": out, "logsumexp": lse}, q, k, v, is_causal=True)
print("output covered:", checked.output.all())
print("logsumexp covered:", checked.logsumexp.all())
# Four of the heads in float32, where the kernel neither rounds the weights nor
# uses the approximate exp
cpu_f32 = er.nn.attention.AttentionAlgorithm(
online_softmax=True, block_size=512, reciprocal=True)
q32, k32, v32 = (t[:, :4].float() for t in (q, k, v))
out32 = torch.nn.functional.scaled_dot_product_attention(q32, k32, v32, is_causal=True)
checked32 = cpu_f32.covers({"output": out32}, q32, k32, v32, is_causal=True)
print("float32 covered:", checked32.output.all())
same output: True
output covered: True
logsumexp covered: True
float32 covered: True
Other fused kernels round in further places, such as FlashAttention's bfloat16 weights, and attention algorithms describes them.
Padding masks#
Padding masks, such as the ones Hugging Face Transformers builds, hide a key
by adding the format's lowest finite value instead of -inf. When every key of
a query is padded, no key is removed: each score gets the same huge value
added. In exact arithmetic that shift cancels in the softmax, so the exact
output still weights the values by the scores. An implementation, though,
rounds each score plus its mask value once (the step r.boundaries lists as
logits). With the lowest finite value as the mask, that rounding erases the
score, so all the weights come out equal. The tolerance stays finite and
covers that output:
# The lowest finite float32 value
low = torch.finfo(torch.float32).min
# Two queries, two keys, and two values, each of length 1
query = torch.tensor([[[1.0], [0.5]]])
key = torch.tensor([[[1.0], [-1.0]]])
value = torch.tensor([[[1.0], [2.0]]])
# Query 0: every key padded. Query 1: key 1 padded.
mask = torch.tensor([[[low, low], [0.0, low]]])
# PyTorch's attention with this padding mask, one output per query
out = torch.nn.functional.scaled_dot_product_attention(
query, key, value, attn_mask=mask)
print("PyTorch:", out.flatten().tolist())
# ExactRef's reference for the same output
p = sdpa(query, key, value, attn_mask=mask)["output"]
print("rounded:", p.rounded.reshape((2,)).tolist())
print("tolerance:", p.tolerance().reshape((2,)).tolist())
# Could a correct implementation produce PyTorch's output?
print("covered:", p.covers(out).all())
PyTorch: [1.5, 1.0]
rounded: [1.119202971458435, 1.0]
tolerance: [0.38079774379730225, 9.5367431640625e-07]
covered: True
The tolerance is wide because it is measured from rounded, the exact answer
rounded once (1.119), and correct implementations land far from it here.
finite_range(), the lowest and highest finite output a correct
implementation can produce, shows where they land, around 1.5, the average
of the values with equal weights:
# The lowest and highest finite output of a correct implementation, per element
lo, hi = p.finite_range()
# Element 0 is query 0's output, whose keys are all padded
print("low:", lo.scalars()[0])
print("high:", hi.scalars()[0])
low: 1.4999992847442627
high: 1.5000007152557373
Backward#
er.scaled_dot_product_attention.backward(query, key, value, grad, ...) takes
the forward's arguments with grad after value, and returns grad_query,
grad_key, and grad_value, each rounded once. Its tolerance follows the
steps of autograd through PyTorch's math backend, but not all of that
backend's roundings: the backend scales the query and key by the square root
of the scale first, and on the CPU its softmax multiplies by a rounded
reciprocal of the row sum. Here it checks a training step's gradients for
causal attention with 2 heads, 512 positions, and head dimension 64, in
float32:
from torch.nn.attention import SDPBackend, sdpa_kernel
# Query, key, value, and the gradient of the output from the next layer
tq, tk, tv, grad = (torch.randn(1, 2, 512, 64, generator=g) for _ in range(4))
# PyTorch's math backend and its autograd, on copies that record gradients
tq_, tk_, tv_ = (t.clone().requires_grad_() for t in (tq, tk, tv))
with sdpa_kernel(SDPBackend.MATH):
out = torch.nn.functional.scaled_dot_product_attention(tq_, tk_, tv_, is_causal=True)
out.backward(grad)
# ExactRef's gradients, held by name, against autograd's
gb = sdpa.backward(tq, tk, tv, grad, is_causal=True)
autograd = {"grad_query": tq_.grad, "grad_key": tk_.grad, "grad_value": tv_.grad}
for name, tensor in autograd.items():
print(f"{name} covered:", gb[name].covers(tensor).all())
grad_query covered: True
grad_key covered: True
grad_value covered: True
Masked keys take no part in the backward either: their weights are exactly
0, so the gradients are those of the kept keys alone. Where a kernel that
computes masked keys' terms anyway can get a non-finite intermediate, as in
the forward, may_be("nan") allows the NaN it reaches in the gradients.
PyTorch's default CPU kernel rounds differently in its backward: it reuses the forward's output and logsumexp and adds the gradients block by block. Backward checks it with an attention algorithm.
Full specification#
er.scaled_dot_product_attention#
- scaled_dot_product_attention(query, key, value, attn_mask=None, dropout_p: float = 0.0, is_causal: bool = False, scale=None, enable_gqa: bool = False, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, workers: int | None = None) Result#
softmax(Q K^T * scale + mask) Vover the key axis.Shapes follow
torch.nn.functional.scaled_dot_product_attention: query(..., L, E), key(..., S, E), value(..., S, Ev); withenable_gqathe head axis (-3) of query is a multiple of key/value's. A bool mask keeps keys where True; a float mask is added to the scaled scores (-inf removes a key).is_causalkeeps key j for query i whenj <= i.scaledefaults to1/sqrt(E); a given one must be finite. With E = 0 the scores are empty sums and stay 0, as in PyTorch, so the logits are the mask alone.Every output is the exact value correctly rounded to
dtype, which must be floating point, as the inputs are. A masked key (False in a bool mask, -inf in a float mask, or above the diagonal withis_causal) takes no part, whatever its score or value. At the other keys non-finite values propagate through the formula as IEEE arithmetic does on exact values, as in PyTorch's math path: a logit of +inf or NaN makes the row NaN, a -inf logit removes its key (which then takes no part either), and a row with no finite logit has every output 0. A non-finite value at a kept key gives its column that infinity (NaN for both signs or NaN). An implementation that computes the terms of the keys a row does not keep meets NaN where one of their factors is not finite (0 times a non-finite value, or a masked key's NaN or overflowing score before its -inf bias), and so does a kept key whose computed weight may be exactly 0 (an exp that underflows, or a logit that may round to -inf) times a non-finite value; the tolerance's flags allow that NaN there (may_be("nan")). An exact zero is +0, or -0 when rounding toward -inf. Dropout is random and has no reference, sodropout_pmust be 0.The second output,
logsumexp(shape(..., Hq, L), as the fused kernels return it), islog(sum_j exp(l_j))over each row's kept keys, correctly rounded to the compute format ofdtype(float32 for formats narrower than float32, elsedtypeitself). It follows IEEE arithmetic on the exact values at the keys the row does not mask: NaN if a logit is NaN, +inf if one is +inf, and -inf, log(0), for a row with no kept key.tolerance()budgets the required boundaries: the score and value accumulations, the scale factor, one rounding of each logit, the shift by the row maximum,expwithinulps(default 1), the row sum, the final division, and the rounding todtype; forlogsumexp,logof the row sum withinulpsand one rounding of the row maximum plus that logarithm. The three sums (scores, row sum, value sums) are normal accumulations by default (index order or 2 or 4 SIMD-style lanes, asmatmuldescribes);standard="any_order"covers any order.normal()is the whole model with normal accumulation in index order and the scale,expandlogcorrectly rounded. Other roundings are not budgeted: a separate mask rounding, materialized probabilities, casting the weights to the input dtype before the value product (FlashAttention does this for bf16 and fp16), online-softmax rescaling, or a reciprocal of the row sum; named algorithms (AttentionAlgorithm) budget all of these, materialized probabilities (P normalized and rounded before the product with V, as PyTorch's math path does) withprobabilities. Pre-scaling Q and K changes the inputs: a consumer that wants it passes the pre-scaled values withscale=1. An implementation that adds such roundings can exceed the tolerance.Every input, the mask included, may also be an earlier result, as
Resultdescribes.
er.scaled_dot_product_attention.backward#
- backward(query, key, value, grad, attn_mask=None, dropout_p: float = 0.0, is_causal: bool = False, scale=None, enable_gqa: bool = False, *, dtype: Format | str | None = None, rounding: Rounding = Rounding.NEAREST_EVEN, overflow: str | None = None, workers: int | None = None) Result#
Gradients of
scaled_dot_product_attentionfor the output gradientgrad.The arguments are the forward's, with
gradaftervalue;gradhas the output's shape and the inputs' dtype. Returnsgrad_query,grad_keyandgrad_valuewith the inputs' shapes: withPthe attention weights,dP = grad V^T,D_i = sum_j P_ij dP_ijanddS = P * (dP - D),grad_value = P^T grad, grad_query = scale * dS K, grad_key = scale * dS^T Q,
each summed over the copies that broadcasting or
enable_gqamade of its input. Every output is the exact value correctly rounded todtype, which must be floating point, as the inputs are.A key a row does not keep (masked, or removed by a -inf logit, as in the forward) takes no part in that row's terms, whatever its
dP, score or value. Over the kept keys non-finite values propagate as IEEE arithmetic does on exact values through these formulas, as in PyTorch's math path: an infinite or NaNdPmakesDand the row'sdSnon-finite, and a NaN row of the forward makes every gradient it touches through its other keys NaN. A row with no kept key contributes 0. An implementation that computes the terms of the keys a row does not keep (P = 0there) meets NaN where one of their factors is not finite ordP - Doverflows, and so does a kept key whose computedPmay be exactly 0 times a non-finite output gradient; the tolerance's flags allow that NaN there. An exact zero is +0, or -0 when rounding toward -inf; an empty sum is +0. Dropout must be 0, and a float mask gets no gradient.Exactness:
grad_queryof a row is decided exactly (a Lindemann-Weierstrass test), unless heavily masked keys' effects cancel as the limitations describe.grad_key,grad_value, andgrad_querysummed over broadcast copies of a query row, are found exact when every term is rational. Otherwise, and in those cancelling cases, refinement stops at a precision cap and raisesReferenceUnavailableErrorrather than return an uncertain value (the accepted cases where an exact result can reach the cap).tolerance()budgets the required boundaries of the gradient computation: the forward's scores, scale factor, logits, shift,expwithinulps(default 1) and row sum, then the probabilitiesP(one rounding each), the accumulations ofdP,D,grad_value,dS KanddS^T Q, the rounding ofdP - D, ofdSand of the scale product, and the rounding todtype. The accumulations are normal accumulations by default (index order or 2 or 4 SIMD-style lanes, asmatmuldescribes);standard="any_order"covers any order.normal()is that program with normal accumulation in index order and the scale andexpcorrectly rounded. Not budgeted: computingPwith a reciprocal of the row sum, rounding to the input dtype in between, or computingDfrom the forward output; named algorithms (AttentionAlgorithm) budget these. Pre-scaling Q and K (PyTorch's math path scales each by the square root of the scale) changes the inputs: a consumer that wants it passes the pre-scaled values withscale=1. PyTorch's math path multiplies the gradients of the pre-scaled Q and K by the square root of the scale at the end; with pre-scaled inputs andscale=1, the reference is the gradient before that rounded product. Every input andgradmay also be an earlier result, asResultdescribes.
See also#
Algorithms: fused kernels, including the methods of PyTorch's CPU and CUDA kernels.
PyTorch equivalents: windows, ALiBi, variable-length layouts, and pre-scaled inputs.
The proofs: forward, backward, and algorithms.