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.
#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 , and once, keeps the scores in on-chip memory and writes only the output. The next section counts what that saves.
#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.
#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 , its sum of exponentials (computed relative to ), and its normalized output . The merged result is
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.
#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 , , 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 serves every sequence in the batch. Head dimension and number of heads set the size of each query and key: the arithmetic scales with , the cache with .
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.
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.
| Prefill | Decode | |
|---|---|---|
| Queries per sequence | 1 | |
| Score shape | ||
| 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 |