vllm.v1.attention.backend
¶
Classes:
-
AttentionBackend–Abstract class for attention backends.
-
AttentionCGSupport–Constants for the cudagraph support of the attention backend
-
AttentionImpl–Standard attention implementation with forward method.
-
AttentionImplBase–Base class for attention implementations.
-
AttentionMetadataBuilder– -
AttentionType–Attention type.
-
CommonAttentionMetadata–Per-batch attention metadata, shared across layers and backends.
-
MLAAttentionImpl–MLA attention implementation with forward_mqa and forward_mha methods.
Functions:
-
max_decode_query_len–Widest request a spec-as-decode builder treats as a decode.
-
subclass_attention_backend–Return a new subclass where
get_builder_clsreturnsbuilder_cls.
AttentionBackend
¶
Bases: ABC
Abstract class for attention backends.
Methods:
-
customize_spec–Adjust the layer's KV cache spec for this backend's kernels. Used when the
-
get_supported_kernel_block_sizes_for_layers–Kernel block sizes for the named layers. Override when the sizes depend
-
supported_kv_cache_layouts–Layouts this backend's kernels can consume, most preferred first, or
-
supports_attn_type–Check if backend supports a given attention type.
-
supports_device_cpu_query_lens_mismatch–Whether this backend can run a batch whose device query_start_loc disagrees
-
supports_head_size_v–Whether the backend can serve a V head size that differs from K's.
-
supports_non_causal–Check if backend supports non-causal (bidirectional) attention
customize_spec(spec)
classmethod
¶
Adjust the layer's KV cache spec for this backend's kernels. Used when the kernels want KV packed in a specific way.
NOTE: temporary compatibility API. Today the Attention layer builds the spec from the model config and the backend only gets to adjust it post-hoc; the end state is for the backend to build and return the spec directly, at which point this hook goes away.
(see: https://github.com/vllm-project/vllm/issues/42449)
get_supported_kernel_block_sizes_for_layers(kv_cache_spec, layer_names)
classmethod
¶
Kernel block sizes for the named layers. Override when the sizes depend on layer geometry that the cache spec does not hold, such as query heads.
supported_kv_cache_layouts()
classmethod
¶
Layouts this backend's kernels can consume, most preferred first, or None when the kernels consume any layout and express no preference.
supports_attn_type(attn_type)
classmethod
¶
Check if backend supports a given attention type.
By default, only supports decoder attention. Backends should override this to support other attention types.
supports_device_cpu_query_lens_mismatch()
classmethod
¶
Whether this backend can run a batch whose device query_start_loc disagrees with the CPU one; backends that plan off the CPU query lengths must opt out.
Currently only verification requests are affected: adaptive verification trims their drafts on device. On the CPU the draft budget is evenly distributed across requests, so the total draft budget, the decode/prefill split point and the CPU prefill query lengths all stay correct.
SSM backends opt out: their recurrent-state planning is built from the CPU per-request boundaries, which the trimmed batch no longer matches.
supports_head_size_v(head_size, head_size_v)
classmethod
¶
Whether the backend can serve a V head size that differs from K's.
supports_non_causal()
classmethod
¶
Check if backend supports non-causal (bidirectional) attention for decoder models.
Unlike ENCODER_ONLY attention type which implies a different execution model, this refers to non-causal attention within the standard paged-KV-cache decoder path.
AttentionCGSupport
¶
Bases: Enum
Constants for the cudagraph support of the attention backend
Attributes:
-
ALWAYS–Cudagraph always supported; supports mixed-prefill-decode
-
NEVER–NO cudagraph support
-
UNIFORM_BATCH–Cudagraph supported for batches the only contain query lengths that are
-
UNIFORM_SINGLE_TOKEN_DECODE–Cudagraph supported for batches the only contain query_len==1 decodes
ALWAYS = 3
class-attribute
instance-attribute
¶
Cudagraph always supported; supports mixed-prefill-decode
NEVER = 0
class-attribute
instance-attribute
¶
NO cudagraph support
UNIFORM_BATCH = 2
class-attribute
instance-attribute
¶
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
class-attribute
instance-attribute
¶
Cudagraph supported for batches the only contain query_len==1 decodes
AttentionImpl
¶
Bases: AttentionImplBase[T], Generic[T]
Standard attention implementation with forward method.
Methods:
-
do_qk_norm_mrope_kvcache_update–Apply QK-norm and MRoPE, then write K/V to the cache.
-
do_qk_norm_rope_kvcache_update–If
fused_qk_norm_rope_kvcache_supportedreturns True, this method -
do_rope_and_kv_cache_update–If
fused_rope_kvcache_supportedreturns True, this method will be called -
fused_output_quant_supported–Does this attention implementation support fused output quantization.
-
fused_qk_norm_mrope_kvcache_supported–Whether this implementation supports fused QKNorm+MRoPE+KVCache.
-
fused_qk_norm_rope_kvcache_supported–Does this attention implementation support fused QKNorm+RoPE+KVCache fusion.
-
fused_rope_kvcache_supported–Does this attention implementation support RoPE+KVCache fusion.
-
set_interleaved_v_cache–Opt this implementation into the interleaved V-cache layout for all of
Attributes:
-
kv_quant_mode(KVQuantMode) –Return the KV cache quantization mode for this layer.
kv_quant_mode
property
¶
Return the KV cache quantization mode for this layer.
do_qk_norm_mrope_kvcache_update(layer, qkv, q_out, positions, q_weight, k_weight, rms_norm_eps, cos_sin_cache, is_neox, mrope_section, is_interleaved, rotary_dim, kv_cache, layer_slot_mapping)
¶
Apply QK-norm and MRoPE, then write K/V to the cache.
do_qk_norm_rope_kvcache_update(layer, qkv, q_out, k_out, positions, q_weight, k_weight, rms_norm_eps, cos_sin_cache, is_neox, kv_cache, layer_slot_mapping, q_out_fp8=None, q_scale=None)
¶
If fused_qk_norm_rope_kvcache_supported returns True, this method
will be called by the fused custom op. Applies QK-norm + RoPE and
writes K/V to the KV cache. Results are written to the pre-allocated
q_out and k_out tensors, and to q_out_fp8 (Q statically quantized by
q_scale) when set; V is split from QKV at the graph level.
do_rope_and_kv_cache_update(layer, query, key, value, positions, cos_sin_cache, is_neox, kv_cache, layer_slot_mapping, query_out=None, key_out=None)
¶
If fused_rope_kvcache_supported returns True, this method will be called
by torch.ops.vllm.fused_rope_and_unified_kv_cache_update
to perform the RoPE and KV cache update. The rotated q/k go to
query_out/key_out when given, else RoPE is applied in place. Overrides
without these arguments still work: the caller passes them copies.
fused_output_quant_supported(quant_key)
¶
Does this attention implementation support fused output quantization. This is used by the AttnFusionPass to only fuse output quantization onto implementations that support it.
Parameters:
Returns:
-
bool–is fusion supported for this type of quantization
fused_qk_norm_mrope_kvcache_supported()
¶
Whether this implementation supports fused QKNorm+MRoPE+KVCache.
fused_qk_norm_rope_kvcache_supported()
¶
Does this attention implementation support fused QKNorm+RoPE+KVCache fusion. This is used by the QkNormRopeKvCachePattern to only fuse the QKNorm ops with the RoPE ops and the KV cache update for implementations that support it.
fused_rope_kvcache_supported()
¶
Does this attention implementation support RoPE+KVCache fusion. This is used by the RopeKVCacheFusionPass to only fuse the RoPE ops with the KV cache update for implementations that support it.
set_interleaved_v_cache()
¶
Opt this implementation into the interleaved V-cache layout for all of its cache writers and readers. QkNormRopeKvCacheFusionPass calls this for every eligible layer when it is constructed, i.e. before any KV cache is written, so fused and unfused paths stay consistent whether or not the pattern matches. Default is a no-op; backends whose kernels read an interleaved V-cache under this fusion (e.g. ROCM_ATTN) override.
AttentionImplBase
¶
Base class for attention implementations.
Contains common attributes and initialization logic shared by both standard AttentionImpl and MLAAttentionImpl. Does not define a forward method - subclasses define their own forward interfaces.
Methods:
-
prepare_for_batch–Prepare implementation-specific state for the current batch.
prepare_for_batch(attn_metadata)
¶
Prepare implementation-specific state for the current batch.
AttentionMetadataBuilder
¶
Methods:
-
build–Central method that builds attention metadata.
-
build_for_cudagraph_capture–Build attention metadata for CUDA graph capture. Uses build by default.
-
get_cudagraph_support–Get the cudagraph support level of this builder class.
-
get_varlen_cudagraph_max_query_len–Get the largest per-request query length L of the variable-length
-
update_block_table–Update the block table for the attention metadata.
-
update_draft_decode_metadata–Update draft decode metadata in place.
build(common_prefix_len, common_attn_metadata, fast_build=False)
abstractmethod
¶
Central method that builds attention metadata. Some builders (MLA) require reorder_batch to be called prior to build.
Parameters:
-
(common_prefix_len¶int) –Deprecated and always 0. Kept for compatibility with out-of-tree builders.
-
(common_attn_metadata¶CommonAttentionMetadata) –The common attention metadata.
-
(fast_build¶bool, default:False) –The meta-data will prioritize speed of building over then speed at execution. Can be used for spec-decode where the result of a build call may only be used for few layers/iters.
build_for_cudagraph_capture(common_attn_metadata)
¶
Build attention metadata for CUDA graph capture. Uses build by default. Subclasses that override this method should call self.build or super().build_for_cudagraph_capture.
get_cudagraph_support(vllm_config, kv_cache_spec)
classmethod
¶
Get the cudagraph support level of this builder class.
get_varlen_cudagraph_max_query_len(vllm_config, kv_cache_spec)
classmethod
¶
Get the largest per-request query length L of the variable-length decode batches a FULL cudagraph of this builder class can replay.
The graph must replay any decode batch in which every real request has between 1 and L query tokens and every padding request has 0. Lengths come from the device query_start_loc; host metadata carries only the token count and an upper bound on the per-request length. Batches with a prefill never replay these graphs. Whether host metadata may understate device query lengths at all is a separate backend question; see supports_device_cpu_query_lens_mismatch().
Returns:
update_block_table(metadata, blk_table, slot_mapping)
¶
Update the block table for the attention metadata. Faster when theres multiple kv-cache groups that create virtually the same metadata but just with different block tables.
Only needs to be implemented if supports_update_block_table is True.
update_draft_decode_metadata(metadata)
¶
Update draft decode metadata in place.
Speculators can record this call inside their draft decode CUDA graphs,
so it runs once at capture and never again in Python. Implementations
must emit only capture-safe operations and write results into persistent
tensors that metadata already references.
AttentionType
¶
Bases: StrEnum
Attention type.
Use string to be compatible with torch.compile.
Attributes:
-
DECODER–Decoder attention between previous layer Q/K/V.
-
ENCODER–Encoder attention between previous layer Q/K/V for encoder-decoder.
-
ENCODER_DECODER–Attention between dec. Q and enc. K/V for encoder-decoder.
-
ENCODER_ONLY–Encoder attention between previous layer Q/K/V.
DECODER = 'decoder'
class-attribute
instance-attribute
¶
Decoder attention between previous layer Q/K/V.
ENCODER = 'encoder'
class-attribute
instance-attribute
¶
Encoder attention between previous layer Q/K/V for encoder-decoder.
ENCODER_DECODER = 'encoder_decoder'
class-attribute
instance-attribute
¶
Attention between dec. Q and enc. K/V for encoder-decoder.
ENCODER_ONLY = 'encoder_only'
class-attribute
instance-attribute
¶
Encoder attention between previous layer Q/K/V.
CommonAttentionMetadata
dataclass
¶
Per-batch attention metadata, shared across layers and backends. AttentionMetadataBuilder instances use it to construct per-layer metadata.
For many of the tensors we keep both GPU and CPU versions.
Methods:
-
compute_num_computed_tokens–Compute num_computed_tokens on device (seq_lens - query_lens).
-
token_to_req_indices–Build or reuse the per-token request index mapping.
Attributes:
-
dcp_local_seq_lens(Tensor | None) –Sequence lengths of the local rank in decode context parallelism world
-
dcp_local_seq_lens_cpu_upper_bound(Tensor | None) –(batch_size,) CPU upper bound on dcp_local_seq_lens. Under PCP+DCP it
-
is_prefilling(Tensor | None) –(batch_size,) bool tensor: True if request is still in prefill phase
-
max_query_len(int) –Longest query in batch
-
max_seq_len(int) –Longest context length (may be an upper bound)
-
mm_req_doc_ranges(dict[int, list[tuple[int, int]]] | None) –PrefixLM bidirectional ranges for multimodal tokens. Maps
-
num_actual_tokens(int) –Total number of tokens in batch
-
num_reqs(int) –Number of requests
-
positions(Tensor | None) –(num_actual_tokens,) token positions. Optional; set when the caller
-
query_start_loc_cpu(Tensor) –(batch_size + 1,), the start location of each request in query Tensor
-
req_idx(ndarray | None) –(batch_size,) index of each row's request in the runner's request
-
rswa_prefix_lens(Tensor | None) –(batch_size,) per-request prefix length (prompt/image token count) for
-
seq_lens(Tensor) –(batch_size,), the number of computed tokens for each request
-
seq_lens_cpu_upper_bound(Tensor | None) –(batch_size,) CPU upper bound on seq_lens. Precise for prefill rows
dcp_local_seq_lens = None
class-attribute
instance-attribute
¶
Sequence lengths of the local rank in decode context parallelism world
dcp_local_seq_lens_cpu_upper_bound = None
class-attribute
instance-attribute
¶
(batch_size,) CPU upper bound on dcp_local_seq_lens. Under PCP+DCP it holds, on every row, the largest shard any DCP rank has of the row's whole request, identical on every PCP rank, so the sparse backends pad their KV gather to it.
is_prefilling = None
class-attribute
instance-attribute
¶
(batch_size,) bool tensor: True if request is still in prefill phase (num_computed_tokens < num_prompt_tokens). Used by some backends to distinguish actual decodes from short extends.
max_query_len
instance-attribute
¶
Longest query in batch
max_seq_len
instance-attribute
¶
Longest context length (may be an upper bound)
mm_req_doc_ranges = None
class-attribute
instance-attribute
¶
PrefixLM bidirectional ranges for multimodal tokens. Maps request index to list of (start, end) token position ranges where bidirectional attention should apply. None for text-only batches or non-PrefixLM models. A request's ranges must not overlap.
num_actual_tokens
instance-attribute
¶
Total number of tokens in batch
num_reqs
instance-attribute
¶
Number of requests
positions = None
class-attribute
instance-attribute
¶
(num_actual_tokens,) token positions. Optional; set when the caller has positions available so that builders can pre-compute position-dependent sparse metadata for DeepSeek V4 C128A layers.
query_start_loc_cpu
instance-attribute
¶
(batch_size + 1,), the start location of each request in query Tensor
req_idx = None
class-attribute
instance-attribute
¶
(batch_size,) index of each row's request in the runner's request table. Rows of one request are adjacent, so equal neighbours are PCP chunks sharing one KV context.
rswa_prefix_lens = None
class-attribute
instance-attribute
¶
(batch_size,) per-request prefix length (prompt/image token count) for
Reference Sliding Window Attention (R-SWA). Tokens with logical index below
this stay globally visible; later (generated) tokens additionally see a
fixed sliding window. None disables R-SWA. The attention backend copies this
into its own persistent buffer and reads rswa_window from model config.
seq_lens
instance-attribute
¶
(batch_size,), the number of computed tokens for each request
seq_lens_cpu_upper_bound = None
class-attribute
instance-attribute
¶
(batch_size,) CPU upper bound on seq_lens. Precise for prefill rows and for all rows outside async spec decode; optimistic for async-spec decode rows (assumes every draft was accepted). Not safe for kernels that need exact per-row context lengths on decode rows.
compute_num_computed_tokens()
¶
Compute num_computed_tokens on device (seq_lens - query_lens).
token_to_req_indices(buffer)
¶
Build or reuse the per-token request index mapping.
MLAAttentionImpl
¶
Bases: AttentionImplBase[T], Generic[T]
MLA attention implementation with forward_mqa and forward_mha methods.
Methods:
-
decode_query_padded_num_heads–Head count forward_mqa pads this step's query to by repeating each
-
forward_mha–MHA-style prefill forward pass.
-
forward_mqa–MQA-style decode forward pass.
-
fused_output_quant_supported–Does this attention implementation support fused output quantization.
-
reserve_workspace–Called in the memory profiling run to claim persistent workspace
decode_query_padded_num_heads(attn_metadata)
¶
Head count forward_mqa pads this step's query to by repeating each head, so the caller may hand it the padded query directly; None when forward_mqa needs the unpadded query.
forward_mha(q, kv_c_normed, k_pe, kv_c_and_k_pe_cache, attn_metadata, k_scale, output, output_scale=None)
¶
MHA-style prefill forward pass.
forward_mqa(q, kv_c_and_k_pe_cache, attn_metadata, layer)
abstractmethod
¶
MQA-style decode forward pass.
fused_output_quant_supported(quant_key)
¶
Does this attention implementation support fused output quantization. Since MLA quantization is done manually in forward_impl (common code), all MLA backends support it by default.
reserve_workspace()
¶
Called in the memory profiling run to claim persistent workspace that is otherwise reserved after profiling.
max_decode_query_len(vllm_config)
¶
Widest request a spec-as-decode builder treats as a decode.
This is the widest per-request query any forward pass builds: a verification request (1 + num_speculative_tokens) plus the drafter's extra slots, e.g. the standalone draft model's correction token. The reorder threshold and the code that mirrors the builders' decode/prefill split all read this, so they cannot drift apart.
subclass_attention_backend(name_prefix, attention_backend_cls, builder_cls)
¶
Return a new subclass where get_builder_cls returns builder_cls.