Pidoku

Attention Backends

Module 18 Lesson 18.c 45 min Difficulty 4/5

Prerequisites 13.l, 12.l, 18.b


Before you start: words you need#

WordPlain meaning
Attention backendOne implementation of the attention operation in vLLM (FlashAttention, FlashInfer, Triton, …), plus the code that prepares its inputs.
KernelA function that runs on the GPU.
Compute capabilityNVIDIA’s number for a GPU generation: 8.x Ampere (A100), 9.0 Hopper (H100, H200), 10.x Blackwell data centre (B200, B300), 12.x Blackwell workstation and consumer (RTX PRO 6000, RTX 50).
Metadata builderPer-step code that turns vLLM’s generic index tensors into the exact inputs one kernel wants.
MLAMulti-head latent attention: stores one compressed vector per token instead of keys and values per head (12.g).
FA2 / FA3 / FA4FlashAttention versions 2, 3 and 4. FA3 targets Hopper, FA4 targets Blackwell (13.l).
trtllm-genNVIDIA’s TensorRT-LLM attention kernels for Blackwell, reached through the FlashInfer library.

1. What is it?#

Attention is the one operation in the model that must understand vLLM’s unusual memory layout: a flat batch of tokens from many requests (18.b), each request’s context scattered across blocks anywhere in a shared cache (12.l). Ordinary attention code cannot do that, so vLLM needs kernels that take a block table as an input.

It does not have one such kernel. It has a registry of attention backends, about forty-five in v0.32.0 (FlashAttention, FlashInfer, Triton, a family for latent attention, AMD and CPU backends, and more), and at startup it picks the best one that supports your GPU generation, your model’s attention variant and your cache data type. Which backend you got explains a good part of your performance, and it is one line in the startup log.

This lesson is about vLLM’s selection and plumbing. How FlashAttention itself works is 13.l. Facts checked on 12 November 2026 against vLLM v0.32.0.


2. Why does it exist?#

  • Hardware differs. The fastest kernel on a Hopper H100 (FA3) is not the fastest on a Blackwell B200 (FlashInfer’s trtllm-gen, or FA4), and neither runs on AMD.
  • Models differ. Grouped-query attention, latent attention, sliding windows, attention sinks, sparse attention, bidirectional attention for image tokens, and state-space layers all need different kernels.
  • Cache formats differ. BF16, FP8 and NVFP4 KV caches (13.h) are supported by different kernels.

No single kernel covers all combinations, so vLLM keeps an ordered list per platform and a validation check per backend.


3. Simple analogy#

A delivery company has vans, bikes and lorries. For each parcel the dispatcher goes down a list in order (fastest first) and takes the first vehicle that can carry it: the bike cannot take a fridge, the lorry cannot enter the old town. The parcel arrives either way; which vehicle took it decides how fast.


4. Tiny example: what each machine picks#

A Llama-style model (grouped-query attention, head size 128, BF16, BF16 KV cache):

H100   (compute capability 9.0)   FLASH_ATTN   -> FlashAttention 3
B200   (compute capability 10.0)  FLASHINFER   -> trtllm-gen kernels
RTX PRO 6000 (12.0)               FLASH_ATTN   -> FlashAttention 2
A100   (8.0)                      FLASH_ATTN   -> FlashAttention 2

Force FlashAttention on the B200 (--attention-backend FLASH_ATTN) and you get FA4 instead.


5. Technical explanation#

What paged attention requires of a kernel#

inputs    queries for the T tokens of this step            (flat, all requests)
          the new keys and values for those T tokens
          the whole KV cache tensor for this layer
          block_table[N, max_blocks]                        where each request's context lives
          slot_mapping[T]                                   where to store the new K and V
          query_start_loc[N+1], seq_lens[N]                 request boundaries

does      1. write the T new keys and values into the cache at slot_mapping
          2. for each request, attend from its queries over its first seq_len tokens,
             fetching them block by block through its row of block_table

The mathematics is unchanged; only the addressing differs. vLLM’s documentation still has a long page on the original 2023 hand-written CUDA kernel. It opens with a warning that it “no longer describes the code used in vLLM today.” Read it as history.

The registry#

AttentionBackendEnum in vllm/v1/attention/backends/registry.py lists the attention backends. The ones you are most likely to meet:

BackendWhat it isTypical use
FLASH_ATTNvLLM’s build of FlashAttention, accepting block tables. Version 2, 3 or 4 chosen per GPU.Default on Hopper, Ampere and Blackwell workstation GPUs
FLASHINFERThe FlashInfer library: its own kernels, plus TensorRT-LLM’s (XQA on Hopper decode, trtllm-gen on Blackwell)Default on Blackwell data-centre GPUs
TRITON_ATTNAn implementation in TritonFallback; the portable option
FLEX_ATTENTIONBuilt on PyTorch FlexAttentionUnusual attention masks; batch-invariant mode
TRITON_FLASH_ATTN, TRITON_FLASHINFERComposite backends: two kernels sharing one cacheModels whose image tokens need bidirectional attention (“MM prefix”)
FLASHINFER_MLA, CUTLASS_MLA, FLASH_ATTN_MLA, FLASHMLA, TRITON_MLA, TOKENSPEED_MLA, *_SPARSELatent-attention kernels, dense and sparseDeepSeek, Kimi and GLM-style models
TURBOQUANT, ULTRAQUANTBackends reading a compressed KV cacheLow-bit KV cache formats
B12XAn optional package for SM120/SM121Blackwell workstation GPUs
ROCM_ATTN, ROCM_AITER_FA, ROCM_AITER_UNIFIED_ATTN, …AMD implementationsAMD Instinct GPUs
CPU_ATTNA CPU implementationCPU-only installs
NO_ATTENTIONA stubModels with no KV cache

A second enum, MambaAttentionBackendEnum in the same file, lists the state-space and linear layers (MAMBA1, MAMBA2, SHORT_CONV, LINEAR, GDN_ATTN). They are not attention, but they keep per-request state in the same block-table plumbing, so the scheduler and KV cache manager treat them alike (17.i).

How one is chosen#

For each attention layer the platform produces an ordered list and the first backend whose validation passes wins. For ordinary attention on NVIDIA (_get_backend_priorities in vllm/platforms/cuda.py, v0.32.0):

Python
# SM100f defaults to FlashInfer for TRTLLM causal attention, but its non-causal
# cutlass path (used for dflash attention) is known to have problems.
# So prefer FlashAttention when non-causal on SM100f.
if device_capability.major == 10 and not use_non_causal:
    return [
        *([AttentionBackendEnum.TRITON_FLASHINFER] if use_mm_prefix else []),
        AttentionBackendEnum.FLASHINFER,
        AttentionBackendEnum.FLASH_ATTN,
        AttentionBackendEnum.TRITON_ATTN,
        AttentionBackendEnum.FLEX_ATTENTION,
        AttentionBackendEnum.TURBOQUANT,
    ]
else:
    return [
        *([AttentionBackendEnum.TRITON_FLASH_ATTN]
          if device_capability.major == 9 and use_mm_prefix else []),
        AttentionBackendEnum.FLASH_ATTN,
        AttentionBackendEnum.FLASHINFER,
        AttentionBackendEnum.TRITON_ATTN,
        AttentionBackendEnum.FLEX_ATTENTION,
        AttentionBackendEnum.TURBOQUANT,
    ]
GPU generationFirst choiceThen
Blackwell data centre (10.x), causal attentionFlashInferFlashAttention (FA4), Triton
Blackwell data centre, bidirectional (for example DFlash drafters)FlashAttentionFlashInfer, Triton
Hopper (9.0)FlashAttention (FA3)FlashInfer, Triton
Ampere, Ada, Blackwell workstation (12.x)FlashAttention (FA2)FlashInfer, Triton

The latent-attention list is longer and depends on head count and cache data type, with comments citing the benchmark issue behind each order. On Blackwell data-centre GPUs it starts FLASHINFER_MLA, TOKENSPEED_MLA, CUTLASS_MLA, FLASH_ATTN_MLA, FLASHMLA, TRITON_MLA.

“Passes validation” is each backend’s validate_configuration(), built on checks such as supports_head_size, supports_dtype, supports_kv_cache_dtype, supports_block_size and supports_combination. A backend can decline for the head size, the model data type, the KV cache data type, the block size, sinks, sparsity, the attention type, or a missing optional package.

Which FlashAttention version#

Inside FLASH_ATTN, get_flash_attn_version (vllm/v1/attention/backends/fa_utils.py) picks:

GPUDefaultFalls back to FA2 when
Hopper (9.0)FA3ALiBi; some unsupported shapes may move up to FA4 instead
Blackwell data centre (10.x)FA4ALiBi, batch-invariant mode, head sizes FA4 cannot fit in tensor memory, or head size 256 with features its dedicated kernel lacks
Everything elseFA2—

Force one with --attention-config.flash_attn_version=2, 3 or 4. FlashAttention-4, released in March 2026 and presented at MLSys 2026, is written in CuTe-DSL for Blackwell and reaches about 1.6 PFLOP/s in BF16 on a B200 (13.l). On Blackwell, head size 256 runs on a dedicated FA4 kernel that needs a KV block size of 128; vLLM advertises that automatically unless you pin --block-size.

Forcing a choice#

Shell
vllm serve <model> --attention-backend FLASH_ATTN
# or, equivalently (the two are mutually exclusive)
vllm serve <model> --attention-config.backend FLASH_ATTN

If the forced backend cannot support the configuration, startup fails with the reason. Models whose layers fall into several KV-cache groups can override per group with --attention-config.backend_per_kind. Forcing is useful for bisecting a correctness or performance problem (“is it the kernel?”) and for working around a bug on new hardware.

What a backend must provide#

Each backend is a class implementing the interface in vllm/v1/attention/backend.py:

PiecePurpose
validate_configuration() and the supports_* checksSay whether this model, GPU and cache are supported
get_supported_kernel_block_sizes()Which KV block sizes the kernel accepts (for example “multiples of 16”)
customize_spec()Adjust the layer’s KV cache spec when the kernel wants KV packed its own way. The source calls it a temporary API; the plan is for backends to build the spec themselves.
get_builder_cls()The metadata builder: each step, convert the generic index tensors into what this kernel expects
get_impl_cls()The implementation: store new keys and values, compute attention
get_cudagraph_support()Which batch shapes can be recorded in a CUDA graph (below)

The metadata builder runs every step, per group of layers. For some backends it is cheap; for others it plans work in proportion to the batch. It is part of the per-step cost that async scheduling hides behind the GPU.


6. Under the hood#

Backends differ in what can be recorded#

CUDA graphs (18.d) record a fixed sequence of GPU work for replay. Whether attention can be recorded depends on whether its control flow depends on the batch’s contents. Each backend declares a level (AttentionCGSupport):

Python
class AttentionCGSupport(Enum):
    ALWAYS = 3
    """Cudagraph always supported; supports mixed-prefill-decode"""
    UNIFORM_BATCH = 2
    """Cudagraph supported for batches the only contain query lengths that are
    the same, this can be used for spec-decode
        i.e. "decodes" are 1 + num_speculative_tokens"""
    UNIFORM_SINGLE_TOKEN_DECODE = 1
    """Cudagraph supported for batches the only contain query_len==1 decodes"""
    NEVER = 0
    """NO cudagraph support"""

Examples from v0.32.0: TRITON_ATTN declares ALWAYS; FLASH_ATTN declares ALWAYS with FA3 and UNIFORM_BATCH otherwise; FlashInfer computes its level from the configuration and drops to UNIFORM_SINGLE_TOKEN_DECODE under decode context parallelism. A backend at ALWAYS lets the whole forward pass replay as one graph for any batch; a lower level allows that only for pure decode steps, and vLLM downgrades the configured CUDA graph mode to match.

Two kinds of work inside one attention call#

  • Prefill has long queries. Attention is a large matrix product, and FlashAttention’s tiling is what matters (13.l).
  • Decode has one query per request and thousands of context tokens. The cost is fetching keys and values from scattered blocks: memory bandwidth.

Many backends run different code for the two and split a mixed batch internally. That is why the runner may reorder the batch so decodes come first (reorder_batch_threshold on the metadata builder): the backend can then treat the front and back as two uniform groups.

Cascade attention is gone#

Earlier releases could use cascade attention when every running request shared a long prefix: compute the shared part once, then the per-request parts. It applied only when all requests shared the prefix and it did not work with full CUDA graphs. vLLM v0.32.0 removed it. Shared prefixes now save work through the prefix cache (17.f), not a special kernel.

Latent attention is a different cache, not just a different kernel#

MLA stores one compressed vector per token. Its backends differ in two ways beyond the kernel: the cache page is much smaller, which changes the sizing arithmetic (17.h), and prefill and decode use different formulations of the same mathematics (prefill has its own backend choice, --attention-config.mla_prefill_backend). Some of these models default to an FP8 cache; in v0.32.0, GLM-5.x on SM100 uses FP8 KV with --kv-cache-dtype auto. See 12.g for the technique.

Paged attention gives the same answer#

Attention through a block table gives exactly the same answer as attention over a contiguous array. This is the whole correctness argument for paging the cache.

Go
package main

import (
	"fmt"
	"math"
)

const (
	blockSize = 4
	dim       = 3 // size of one key or value vector
	numBlocks = 8
)

type vec [dim]float64

func dot(a, b vec) float64 {
	s := 0.0
	for i := range a {
		s += a[i] * b[i]
	}
	return s
}

// attend computes softmax(q.K) . V over the keys and values it is given.
func attend(q vec, keys, values []vec) vec {
	scores := make([]float64, len(keys))
	maxScore := math.Inf(-1)
	for i, k := range keys {
		scores[i] = dot(q, k) / math.Sqrt(dim)
		maxScore = math.Max(maxScore, scores[i])
	}
	sum := 0.0
	for i := range scores {
		scores[i] = math.Exp(scores[i] - maxScore)
		sum += scores[i]
	}
	var out vec
	for i, v := range values {
		for d := range out {
			out[d] += scores[i] / sum * v[d]
		}
	}
	return out
}

// pagedAttend never sees a contiguous sequence. It walks the block table.
func pagedAttend(q vec, keyCache, valueCache []vec, blockTable []int, seqLen int) vec {
	keys := make([]vec, 0, seqLen)
	values := make([]vec, 0, seqLen)
	for pos := 0; pos < seqLen; pos++ {
		slot := blockTable[pos/blockSize]*blockSize + pos%blockSize
		keys = append(keys, keyCache[slot])
		values = append(values, valueCache[slot])
	}
	return attend(q, keys, values)
}

func main() {
	const seqLen = 10
	// A sequence's keys and values, as an ordinary contiguous array.
	keys := make([]vec, seqLen)
	values := make([]vec, seqLen)
	for i := range keys {
		for d := 0; d < dim; d++ {
			keys[i][d] = math.Sin(float64(i*3 + d))
			values[i][d] = math.Cos(float64(i*5 + d*2))
		}
	}
	q := vec{0.3, -1.1, 0.7}

	// The same data stored the vLLM way: one big cache, the sequence's three
	// blocks scattered through it in no particular order.
	keyCache := make([]vec, numBlocks*blockSize)
	valueCache := make([]vec, numBlocks*blockSize)
	blockTable := []int{6, 1, 4}
	for pos := 0; pos < seqLen; pos++ {
		slot := blockTable[pos/blockSize]*blockSize + pos%blockSize // slot_mapping
		keyCache[slot] = keys[pos]
		valueCache[slot] = values[pos]
	}

	a := attend(q, keys, values)
	b := pagedAttend(q, keyCache, valueCache, blockTable, seqLen)

	fmt.Printf("contiguous attention: [% .6f % .6f % .6f]\n", a[0], a[1], a[2])
	fmt.Printf("paged attention:      [% .6f % .6f % .6f]\n", b[0], b[1], b[2])
	fmt.Println("identical:", a == b)
	fmt.Printf("\nblock table %v: positions 0-3 are in slots %d-%d, 4-7 in %d-%d, 8-9 in %d-%d\n",
		blockTable, 6*blockSize, 6*blockSize+3, 1*blockSize, 1*blockSize+3, 4*blockSize, 4*blockSize+1)
	fmt.Printf("%d of %d slots hold this sequence; the rest belong to other requests or are free\n",
		seqLen, numBlocks*blockSize)
}

Output:

contiguous attention: [-0.007549  0.003507  0.004630]
paged attention:      [-0.007549  0.003507  0.004630]
identical: true

block table [6 1 4]: positions 0-3 are in slots 24-27, 4-7 in 4-7, 8-9 in 16-17
10 of 32 slots hold this sequence; the rest belong to other requests or are free

pagedAttend copies the keys into a temporary list and calls the ordinary function. A real kernel does not copy: it reads each block in place. The extra indirection, one table lookup per block, is the whole runtime cost of paging, and at 16 tokens per block it is small next to the arithmetic.


7. Performance implications#

  • The backend sets both attention speed and graph coverage. A fast kernel that only supports single-token decode graphs can lose to a slightly slower one that supports ALWAYS, on workloads with many mixed steps.
  • Decode attention is bandwidth-bound. Its cost grows with context length times batch size. An FP8 or NVFP4 KV cache halves or quarters the bytes read, if the backend supports it (13.h).
  • Blackwell defaults to FlashInfer because NVIDIA’s trtllm-gen decode kernels lead there; FA4 is the strongest choice for prefill-heavy or bidirectional work. Measure both on your traffic.
  • Metadata building is per step CPU work. Backends that plan heavily per batch cost more at small batch sizes, where the GPU step is short.

8. Production implications#

  • Log the backend. The startup log names the backend per layer group. Record it with your benchmark results; an upgrade that silently changes the default can move latency.
  • Pin when you need stability. Defaults change between releases. If a benchmark or a correctness test depends on one kernel, set --attention-backend explicitly.
  • New hardware, new defaults. Workstation Blackwell (SM120) gets FA2 by default in v0.32.0, not FA4; the optional b12x backend targets it.
  • Check the feature table. The documentation’s backend table is generated from each backend’s validation code, so it is the most reliable answer to “does X support an FP8 cache with sinks at head size 256?”

9. Common mistakes#

  1. Assuming FlashAttention is always used. On B200 and B300 the default is FlashInfer.
  2. Assuming FLASH_ATTN means one kernel. It means FA2, FA3 or FA4 depending on the GPU and the model.
  3. Forcing a backend in production after a one-off debug. It disables future improvements to the default choice.
  4. Pinning --block-size to a value the preferred kernel does not support, which quietly moves you to a slower backend (or fails if the backend was forced).
  5. Expecting cascade attention to speed up shared system prompts. It was removed in v0.32.0; use prefix caching.

10. Hands-on exercise#

  1. In the program, change the block table to [0, 1, 2], which makes the layout contiguous. Confirm the result is unchanged. Then try another order.
  2. Start a server with VLLM_LOGGING_LEVEL=DEBUG and find the lines where backends are considered. Which were skipped, and why?
  3. On one GPU, force FLASH_ATTN, FLASHINFER and TRITON_ATTN in turn on the same model and measure decode throughput at 32 concurrent requests with vllm bench serve.
  4. On a Blackwell data-centre GPU, compare --attention-config.flash_attn_version=4 and 2 under FLASH_ATTN for an 8,000-token prompt. Report time to first token.

11. Interview questions#

  1. What two extra inputs distinguish a paged attention kernel from a standard one, and what is each used for?
  2. On an H100, which backend and FlashAttention version are used for a Llama-style model? On a B200?
  3. Why does the attention backend affect whether a whole forward pass can be replayed as a CUDA graph?
  4. Why does vLLM prefer FlashAttention over FlashInfer on Blackwell when attention is bidirectional?
  5. Why are Mamba layers listed alongside attention backends?

12. Further reading#

Checked on 12 November 2026.

↑↓ navigate↵ openesc close

100% drag to pan · scroll or pinch to zoom · double-click to zoom in