SDPA: One Call, Several Kernels
An attention API can select different implementations. Correct output does not prove the fastest backend ran. Follow dispatch, masks, shapes, and evaluation dropout through PyTorch’s interface.
#Section 22Six Lines Become One
Chapter 1’s hand-written attention:
s = q @ k.transpose(-2, -1) # scores (B, H, T, T)
s = s / math.sqrt(q.size(-1)) # scale
s = s.masked_fill(mask, float('-inf')) # causal mask
w = s.softmax(dim=-1) # weights (B, H, T, T)
w = F.dropout(w, p, training) # optional dropout
o = w @ v # output (B, H, T, d)Every line is correct, and every line hands a full tensor to the next one through the GPU's main memory. SDPA, torch.nn.functional.scaled_dot_product_attention, added in PyTorch 2.0 in 2023, replaces all six with one call that computes the same mathematical result:
o = F.scaled_dot_product_attention(q, k, v, is_causal=True,
dropout_p=p if self.training else 0.0)The difference is what happens inside. A kernel is a program that runs on the GPU. The hand-written version launches several kernels, each reading its input from main memory and writing its output back. SDPA can instead run one fused kernel that does all six steps in a single pass, keeping intermediate results in the GPU's small, fast on-chip memory. Part VI shows why that matters so much. For now: same answer, often several times faster, and far less memory.
#Section 23The Arguments
Each argument maps onto something from Chapter 1.
query, key and value are the three tensors, with the heads before the tokens: shape for the query, where is the number of query positions and the head size, and for keys and values, where is the number of key positions. In training . During generation with a cache, is 1 and is the cache length.
attn_mask is an optional mask, either boolean or numeric. dropout_p is the probability of randomly dropping attention weights; it applies whenever it is non-zero, so you must pass 0 at evaluation yourself. is_causal applies the causal triangle for you. scale defaults to , as in Chapter 1's Part VII. enable_gqa, added in PyTorch 2.5, lets keys and values have fewer heads than queries and shares them across groups without copying (Part IV).
#Section 24Which Kernel Runs
SDPA is a dispatcher. Each time you call it, it checks your inputs and picks one of several implementations, called backends. On an NVIDIA GPU the main ones are FlashAttention (Part VI), the fastest but the pickiest; memory-efficient attention, based on Meta's xFormers work, which handles more cases and still never stores the full grid; a cuDNN backend on recent hardware; and the math backend, which is simply the six hand-written lines in C++, the fallback that handles everything.
The checks are, roughly: is the data type 16-bit (fp16 or bf16)? Is there no custom mask tensor? Is the head size within the supported range? Is the GPU recent enough? Pass all of them and you get FlashAttention. Fail the data type check, for example by running in 32-bit, and Flash is skipped immediately; you usually get the memory-efficient kernel instead. Pass an arbitrary attn_mask tensor and Flash is skipped too. If nothing else applies, the math kernel runs.
A fallback can be correct but materialize the full score grid, greatly increasing long-context memory. Inspect the selected backend before attributing fused-kernel performance to the API call.
#Section 25Masks: Where the Bugs Live
Boolean masks: True means attend
SDPA accepts a boolean mask in which True means "this query may attend to this key" and False means "hide it". That is the opposite of masked_fill in Chapter 1's code, where True marked the cells to fill with minus infinity, and the opposite of several other libraries. Take three real tokens followed by two padding tokens. The correct mask has True in the first three columns and False in the last two. Invert it by accident and real tokens can see only the padding and not each other. Nothing crashes; the model quietly reads garbage.
A numeric mask is the other option: a float tensor that is added to the scores, with 0 where attention is allowed and where it is not, exactly as in Chapter 1's Section 45. Numeric masks are unambiguous, which is one reason some codebases prefer them.
is_causal when L ≠ S
When the number of queries equals the number of keys, is_causal=True gives the usual triangle and all is well. But during generation with a KV cache, there is 1 new query and keys. Where should the triangle sit?
PyTorch's is_causal=True aligns the triangle with the top-left corner: query 0 may see key 0, query 1 may see keys 0 and 1, and so on. With one query and six keys, the single new query lands in row 0 and may see only key 0. That is wrong: the newest token is the last position and should see all six. What decode needs is the triangle aligned to the bottom-right corner, where the last query sees every key.
Two fixes cover these cases. For a single new token, pass is_causal=False: the newest token may see everything before it, so no mask is needed. For several new tokens at once, such as speculative decoding or chunked prefill, use PyTorch's torch.nn.attention.bias.causal_lower_right(L, S) helper, which builds the bottom-right-aligned mask in a form the fast kernels still accept.
#Section 26Shapes and Control
Getting into (B, H, T, d) and back
SDPA wants the heads before the tokens. After the projection, a Finch-24 query comes out as . view(B, T, 8, 64) splits it into heads, giving . transpose(1, 2) swaps heads and tokens, giving , the order SDPA wants. After SDPA, transpose back to and reshape to to glue the heads together for the output projection.
One subtle detail. After a transpose, the tensor's numbers are no longer laid out in memory in the order its shape suggests, and view refuses to reshape such a tensor (or, in older code with .contiguous() forgotten, people work around it wrongly). Use .reshape, which copies when it must, or call .contiguous() before .view. Getting the order of these steps wrong is the reshape bug of Chapter 1, Section 52: right shapes, scrambled heads.
Forcing and checking a backend
Sometimes you want to be certain you are getting a fused kernel rather than quietly falling back. PyTorch provides a context manager for that:
from torch.nn.attention import sdpa_kernel, SDPBackend
with sdpa_kernel(SDPBackend.FLASH_ATTENTION): # allow only Flash
o = F.scaled_dot_product_attention(q, k, v, is_causal=True)If the inputs are not supported by FlashAttention, this raises an error instead of silently slowing down. It is a good check to run once when setting up a model; in production you usually let the dispatcher choose.
Sharp edges of SDPA
attn_mask and is_causal together. Passing both is an error in PyTorch, and ambiguous anyway. Fold the causal pattern into your mask, or use only is_causal.
dropout_p at evaluation. SDPA does not know whether the model is training. A fixed dropout_p drops weights during evaluation too. Pass dropout_p=self.p if self.training else 0.0.
Rows with nothing to see. If a mask hides every key from some query, softmax divides zero by zero and returns NaN, as in Chapter 1, Section 42. Make sure every query can attend to at least one key.
The default scale. The default is . Models that use a different scale, or none, must pass scale explicitly; otherwise results are subtly wrong.
Grouped heads on older PyTorch. Before version 2.5 there is no enable_gqa; keys and values must be expanded to the query head count first, using the expand-reshape helper of Part IV.