Highlights

Contents

Part III
03

Attention Kernels at Inference Time

Prefill and decode expose different attention shapes. One efficient kernel is not best for every shape. Distinguish the API, its backend, and the tiling or parallelism that actually reduces work on the device.

YOU ARE HEREmessageschat templatetokenizertoken IDsconfig.jsonmodel.safetensorsint8 / int4 weightsOUR DECODER, REBUILT FROM THE CONFIGprefilldecodeattention kernelKV cacheparity checkvs referenceLM head → logitssamplingdetokenizereply textnext token

#Section 10Scaled Dot-Product Attention APIs

SDPA is PyTorch’s scaled_dot_product_attention interface for scaled, masked attention. A fused implementation combines operations to avoid intermediate transfers. The modern guide explains its arguments and mask conventions.

Three of those details matter more at inference than in training.

Causal mode. is_causal=True is right for prefill and wrong for single-token decode, because PyTorch aligns its causal mask to the top-left corner. Section 9 showed the failure. Decode with one query row needs no mask; several new rows against a longer cache need an explicit bottom-right-aligned mask.

Dropout behavior. SDPA applies dropout whenever dropout_p > 0. It does not look at model.eval(). Hugging Face’s Qwen3 code passes a dropout of 0.0 unless the module is training, and your own code must do the same, or inference becomes random in a way that greedy decoding cannot remove. Qwen3’s config sets attention_dropout to 0.0 anyway, but a ported model with a nonzero value will bite.

Padding in batched inference. When several prompts of different lengths are batched, the short ones are padded and the padding must be masked. That forces an explicit boolean mask, and an explicit mask rules out some kernels (Section 14).

Why framework kernels outperform manual attention: a hand-written version launches separate kernels for the matmul, the scale, the mask, the softmax and the second matmul, and writes the full score matrix to GPU memory between them. A fused kernel reads QQ, KK and VV once, keeps the scores in on-chip memory and writes only the output. The next section counts what that saves.

HAND-WRITTEN ATTENTION vs ONE FUSED KERNEL: TRIPS TO GPU MEMORYby hand: five kernelsQ Kᵀscalemasksoftmax× VHBM: a T × T score matrix written and read back four timesfused (SDPA / FlashAttention): one kernelQ Kᵀ → scale → mask → softmax → × V, scores stay on the chipread Q, K, Vwrite O
Figure 4.18Where the time goes in hand-written attention: each of five kernels writes its result to GPU memory and the next reads it back. A fused kernel keeps the scores on the chip and touches memory only for its inputs and output.

#Section 11The Memory Problem With Standard Attention

Materializing the attention matrix creates large intermediate tensors. Writing and rereading them in GPU HBM consumes bandwidth. A fused kernel can keep score tiles on-chip instead.

Prefill has a large pairwise score grid. Single-token decode has only a new query row, so its larger concern is reading the retained KV history.

#Section 12FlashAttention

FlashAttention uses tiling and on-chip SRAM to evaluate exact dense attention without retaining the full score grid. Its speed comes from reduced transfers, not fewer allowed comparisons. See the tile mechanism.

What changes at decode: Flash-Decoding

Prefill supplies many query blocks to parallelize. Single-token decode has fewer query blocks, so dividing work only by query and head can leave processors idle.

Flash-Decoding, published in October 2023 by Tri Dao, Daniel Haziza, Francisco Massa and Grigory Sizov, splits the other way. It cuts the cache into chunks along the sequence, lets different processors handle different chunks of the same head in parallel, and then merges the partial results with one small extra step. The merge uses exactly the rescaling rule of online softmax, so the result is still exact. The authors reported up to eight times faster generation for very long sequences. vLLM, SGLang and FlashInfer all use split-KV decoding of this kind.

ONE QUERY, A LONG CACHE: WHO DOES THE READING?FlashAttention at decodeqK,V 0K,V 1K,V 2K,V 3K,V 4K,V 5K,V 6K,V 7one processor walks all 8 blocks in turn; the rest of the GPU waitsFlash-Decodingqprocessor 1K,V 0K,V 1m, ℓ, oprocessor 2K,V 2K,V 3m, ℓ, oprocessor 3K,V 4K,V 5m, ℓ, oprocessor 4K,V 6K,V 7m, ℓ, omerge → exact osame answer, all at once
Figure 4.19Decode with one query. FlashAttention gives each head to one processor, which walks the whole cache alone; Flash-Decoding splits the cache into chunks processed in parallel, then merges the partial results.

#Section 13Online Softmax

Online softmax retains a running maximum and normalization sum across blocks. If a later block raises the maximum, rescale earlier totals before adding the new contribution. This preserves stable normalization without retaining every score.

Inference adds one use: combining partial attention blocks computed by different processors, as Flash-Decoding does. Each chunk returns three things: its maximum score mim_i, its sum of exponentials ℓi\ell_i (computed relative to mim_i), and its normalized output oio_i. The merged result is

m=max⁡(m1,m2),ai=ℓi emi−m,o=a1o1+a2o2a1+a2.m = \max(m_1, m_2), \qquad a_i = \ell_i\, e^{m_i - m}, \qquad o = \frac{a_1 o_1 + a_2 o_2}{a_1 + a_2}.

Read it as: bring both sums onto the same reference maximum, then average the two outputs weighted by how much probability mass each chunk holds.

With the numbers from Section 7

The figure merges independently processed chunks by converting their totals to one maximum reference. The resulting output matches the full computation up to rounding.

MERGING TWO PARTIAL SOFTMAX RESULTS, NUMBERS FROM SECTION 7chunk 1: positions 0, 1scores 1.4142, 0.7071values [1, 2], [3, 0]m1 = 1.4142 ℓ1 = 1.4931o1 = [1.6605, 1.3395]chunk 2: positions 2, 3scores 2.1213, 0.7071values [0, 4], [2, 2]m2 = 2.1213 ℓ2 = 1.2431o2 = [0.3911, 3.6089]m = 2.1213 a1 = 1.4931 · e−0.7071 = 0.7362 a2 = 1.2431o = (0.7362 o1 + 1.2431 o2) / 1.9793 = [0.8633, 2.7648]single pass over all four positions (Section 7): [0.8633, 2.7648]
Figure 4.20Two chunks of the cache processed separately, then merged with the online-softmax rule. The merged output equals the single-pass result of Section 7 to four decimals.

#Section 14SDPA vs FlashAttention

The two names are often used as if they were the same thing. They are not. SDPA as an interface is a function signature: give it QQ, KK, VV and a mask, get the attention output. FlashAttention as an implementation is one particular kernel that can compute it. SDPA has several kernels behind it and a dispatcher that picks one per call, which Chapter 2 drew in Section 24.

When SDPA can dispatch to FlashAttention depends on the inputs. The hardware and dtype requirements for PyTorch's flash backend are an NVIDIA GPU of the Ampere generation or newer, fp16 or bf16 tensors, and a head size it supports (up to 256). It also does not accept an arbitrary attn_mask; it handles causal masking through is_causal. When any condition fails, SDPA uses one of its fallback implementations: the memory-efficient kernel, which accepts masks and fp32, or the plain math kernel, which builds the full score matrix like the hand-written version.

At inference this has a practical consequence. Batched decode with padded prompts needs an explicit mask, which can silently move you from the flash kernel to a slower one. Running a model in fp32 for a parity test does the same. Neither is an error; both show up as a speed difference you did not expect. Serving engines avoid padding altogether by packing sequences of different lengths into one ragged batch and passing their lengths to kernels written for that.

#Section 15Attention Performance

Everything in this part comes down to one question per workload: does the GPU run out of arithmetic or out of memory bandwidth first? Five quantities decide it.

Sequence length grows attention's arithmetic quadratically in prefill and its cache reads linearly in decode. Batch size multiplies the arithmetic but, for the weights, not the bytes: one read of WQW_Q serves every sequence in the batch. Head dimension and number of heads set the size of each query and key: the arithmetic scales with H×dhH \times d_h, the cache with Hkv×dhH_{kv} \times d_h.

Prefill throughput

Prefill is compute-bound, so its throughput is the GPU's arithmetic rate divided by the operations per token. For Llama 3 8B with a 2,048-token prompt, that is at most about 63,600 prompt tokens per second on one H100, falling as prompts get longer because attention's share grows (Section 2). Batching several prompts together barely helps once a single prompt is long enough to fill the GPU.

Decode throughput

Decode batching shares weight reads, but every sequence still brings its own history.

Throughput eventually flattens as cache reads and memory capacity dominate. Increasing the batch can then worsen per-user latency without much total gain.

LLAMA 3 8B DECODE, ONE H100, CONTEXT 2,048: LOWER BOUND FROM DATASHEET PEAKSbatch sizetotal tokens/s050100150200250tokens/s per user02,5005,0007,50010,0001641282382192196,66110410,1064280 GB fullmore users: more total, slower each
Figure 4.21Decode throughput for Llama 3 8B on one H100 at a 2,048-token context. Total tokens per second (orange) rises and flattens as the batch grows; each user's tokens per second (slate) falls. Memory runs out at 238 sequences.

Memory versus compute bottlenecks

Batching does not share independent conversations' KV histories. Smaller representations, fewer KV heads, or shorter retained contexts target those reads directly.

BATCHED DECODE: WEIGHTS ARE SHARED, CACHES ARE NOTweights: read oncefor the whole batchuser 1own KV cacheuser 2own KV cacheuser 3own KV cacheuser 4own KV cacheone weight read serves every user; each cache is read for one user only
Figure 4.22Why batching helps the weights and not the cache. One read of each weight serves every user in the batch; every user's cache is read for that user alone.
Prefill Decode
Queries per sequence TT 1
Score shape (B,H,T,T)(B, H, T, T) (B,H,1,S)(B, H, 1, S)
Mask causal none (one row)
Bottleneck arithmetic memory bandwidth, then capacity
Kernel that wins FlashAttention split-KV (Flash-Decoding), paged
Helped by faster matmul, fewer FLOPs batching, GQA, quantization, smaller cache