Highlights

Contents

Part V
05

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.

YOU ARE HEREMODERN DECODER BLOCKATTENTION HALFRMSNormq, k, v projRoPE (q, k)GQA: 8 q, 2 kvSDPAFlash kernelo proj+MLP HALFRMSNormgate, up projSiLU(g) ⊙ udown proj+residual stream: x + Attn(Norm(x)), then h + MLP(Norm(h))what changed since GPT-2: positions, norm, MLP, K/V sharing, the attention kernel, and no biases

#Section 22Six Lines Become One

Chapter 1’s hand-written attention:

python
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 (B,H,T,T)(B, H, T, T) 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:

python
o = F.scaled_dot_product_attention(q, k, v, is_causal=True,
                                   dropout_p=p if self.training else 0.0)
SIX HAND-WRITTEN LINES (CHAPTER 1) BECOME ONE FUSED CALLs = q @ k.transpose(-2, -1)s = s / math.sqrt(q.size(-1))s = s.masked_fill(mask, -inf)w = s.softmax(dim=-1)w = dropout(w, p)o = w @ vwrites the T × T grid s and w to memoryo = F.scaled_dot_product_attention( q, k, v, is_causal=True, dropout_p=p if training else 0.0)same answer; can run as one kernelthat never stores the grid
Figure 2.33Six hand-written lines and the single call that replaces them. The answer is the same; the difference is that the call can run as one fused kernel that never writes the score grid to memory.

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 (B,H,L,E)(B, H, L, E) for the query, where LL is the number of query positions and EE the head size, and (B,Hkv,S,E)(B, H_{kv}, S, E) for keys and values, where SS is the number of key positions. In training L=S=TL = S = T. During generation with a cache, LL is 1 and SS 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 1/E1/\sqrt{E}, 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).

THE ARGUMENTS OF scaled_dot_product_attentionquery(B, H, L, E) L = query lengthkey, value(B, H_kv, S, E) S = key lengthattn_maskbool (True = may attend) or float added to scoresdropout_pprobability of dropping a weight; 0 at evalis_causalapply a causal triangle (top-left aligned)scaledefaults to 1 / √Eenable_gqaaccept H_kv < H and share heads (PyTorch 2.5+)returns(B, H, L, E)
Figure 2.34The arguments of scaled_dot_product_attention. Each corresponds to one piece of the hand-written version; is_causal is highlighted because its alignment rule causes the most bugs.

#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.

HOW SDPA PICKS A KERNEL (SIMPLIFIED, CUDA GPU)fp16 or bf16?no custom mask tensor?head size supported?FlashAttentionmemory-efficientmath (fallback)yesyesyesno (fp32)no (mask)nothing else appliesfp32 skips Flashimmediately
Figure 2.35A simplified view of the dispatch decision. 16-bit inputs with no custom mask and a supported head size get FlashAttention; fp32 or an explicit mask tensor drop to the memory-efficient kernel; anything else falls back to math.

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.

MEMORY FOR ONE LAYER’S ATTENTION WEIGHTS: MATH KERNEL VERSUS A FUSED KERNEL (8 HEADS, bf16)T = 1,02416 MiBT = 4,096256 MiBT = 16,3844.0 GiBT = 65,53664.0 GiBred: full T × T weights (math). orange: on-chip tiles only, a fixed few hundred KiB (fused)
Figure 2.36Memory for one layer's attention weights. The math kernel stores the full T × T grid and grows as a square; fused kernels hold only small tiles.

#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.

BOOLEAN MASKS IN SDPA: True MEANS “MAY ATTEND” (3 REAL TOKENS + 2 PADDING)correct: pad columns FalseTTTFFTTTFFTTTFFTTTFFTTTFFinverted: real tokens see only paddingFFFTTFFFTTFFFTTFFFTTFFFTTBoth are valid boolean masks. The inverted one runs without error and reads garbage.
Figure 2.37Boolean masks in SDPA. True means may attend. The inverted mask is just as valid a tensor, so it runs without error while every real token attends only to padding.

A numeric mask is the other option: a float tensor that is added to the scores, with 0 where attention is allowed and −∞-\infty 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 SS 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.

is_causal WITH 1 QUERY AND 6 KEYS (DECODE): WHERE DOES THE TRIANGLE SIT?square 6 × 6: finetop-left (is_causal=True): wrongbottom-right: correctnew token sees only key 0new token sees all 6 keysfix for decode: is_causal=False with one new query,or torch.nn.attention.bias.causal_lower_right(L, S)
Figure 2.38Causal alignment when queries are fewer than keys. Top-left alignment, which is what is_causal=True does, lets the single decode query see only the first key; bottom-right alignment lets it see them all.

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 (B,T,512)(B, T, 512). view(B, T, 8, 64) splits it into heads, giving (B,T,8,64)(B, T, 8, 64). transpose(1, 2) swaps heads and tokens, giving (B,8,T,64)(B, 8, T, 64), the order SDPA wants. After SDPA, transpose back to (B,T,8,64)(B, T, 8, 64) and reshape to (B,T,512)(B, T, 512) to glue the heads together for the output projection.

GETTING INTO (B, H, T, d) AND BACK (FINCH-24 QUERIES)q_proj(x)(B, T, 512).view(B, T, 8, 64)(B, T, 8, 64).transpose(1, 2)(B, 8, T, 64)SDPA(B, 8, T, 64).transpose(1, 2)(B, T, 8, 64).reshape(B, T, 512)(B, T, 512)reshape after transpose needs contiguous memory: use .reshape, not .view
Figure 2.39The shape round trip around SDPA. Split into heads, move heads before tokens, run attention, move them back, and merge.

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:

python
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.

SDPA DROPOUT: EVALUATION NEEDS AN EXPLICIT ZEROdropout_p = 0.5one possible dropout draw0.00.40.00.8dropout_p = 0.0evaluation weights retained0.10.20.30.4model.eval() does not change the argument you passed
Figure 2.40Illustrative attention weights are 0.1, 0.2, 0.3 and 0.4. One possible dropout draw at p = 0.5 drops the first and third and scales survivors by 1 / (1 − p), giving 0, 0.4, 0 and 0.8. Dropout does not renormalize the row. Passing dropout_p = 0.0 retains every weight during evaluation.

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 1/E1/\sqrt{E}. 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.