Skip to content

vllm.model_executor.layers.attention

Modules:

Classes:

Functions:

Attention

Bases: Module, AttentionLayerBase

Attention layer.

This class takes query, key, and value tensors as input. The input tensors can either contain prompt tokens or generation tokens. The class does the following:

  1. Store the input key and value tensors in the KV cache.
  2. Perform (multi-head/multi-query/grouped-query) attention.
  3. Return the output tensor.

Methods:

  • __init__ –

    The KV cache is stored inside this class and is accessed via

  • forward –

    The KV cache is stored inside this class and is accessed via

__init__(num_heads, head_size, scale, num_kv_heads=None, alibi_slopes=None, use_alibi_sqrt=None, cache_config=None, quant_config=None, logits_soft_cap=None, per_layer_sliding_window=None, prefix='', attn_type=AttentionType.DECODER, kv_sharing_target_layer_name=None, mm_prefix_clamp_sliding_window=False, attn_backend=None, head_size_v=None, query_pre_quantized=False, **extra_impl_args)

The KV cache is stored inside this class and is accessed via self.kv_cache.

forward(query, key, value, output_shape=None, output_dtype=None)

The KV cache is stored inside this class and is accessed via self.kv_cache.

Attention metadata (attn_metadata) is set using a context manager in the model runner's execute_model method. It is accessed via forward context using vllm.forward_context.get_forward_context().attn_metadata.

CrossAttention

Bases: Attention

Cross-attention for encoder-decoder models. Handles attention between decoder queries and encoder keys/values.

EncoderOnlyAttention

Bases: Attention

Encoder attention is a special case that doesn't need a KV Cache.

Methods:

  • __init__ –

    attn_backend replaces the selected backend (e.g. a model's own

__init__(num_heads, head_size, scale, cache_config=None, attn_type=None, attn_backend=None, **kwargs)

attn_backend replaces the selected backend (e.g. a model's own subclass); it is wrapped for non-causal metadata like the default. A given backend skips the backend selector and its validation, and overrides --attention-backend: checking that it supports the head size, dtype, KV cache dtype and platform is the caller's responsibility. A warning names the backend that is used. Its get_name() must be the name of a registered AttentionBackendEnum member.

Of the in-tree models, only the BERT classes (BertModel, BertPoolingModel and their layers) pass attn_backend through.

MLAAttention

Bases: Module, AttentionLayerBase

Multi-Head Latent Attention layer.

NOTE: Please read the comment at the top of the file before trying to understand this class

This class takes query, and compressed key/value tensors as input. The class does the following:

  1. Store the input key and value tensors in the KV cache.
  2. Perform (multi-head/multi-query/grouped-query) attention.
  3. Return the output tensor.

Methods:

  • prepare_mqa_query –

    Write the KV cache, then absorb, concat (and DCP-gather) the MQA

_apply_lora_projection(x, out, *, is_query)

Add kv_b_proj adapters to the absorbed, head-major MLA projection.

_forward_dcp_decode(q, kv_cache, attn_metadata, gathered_context)

The attention output of a DCP ShardQ step's leading decode tokens (head-sharded query) on the DCP path: query gather, the DCP-local partials, LSE combine.

_gather_pcp_cache_inputs(kv_c_normed, k_pe, slot_mapping)

Gather into fixed-size buffers padded with PAD_SLOT_ID, so the cache write stays in the piecewise graph while the gather, which depends on the step's decode/prefill split, runs eagerly.

_prepare_mqa_query(mqa_q, qrep_decode, fused_q_heads=None, gather_query=True)

Absorb the MQA query (and, with gather_query, DCP-gather it).

prepare_mqa_query(q, kv_c_normed, k_pe)

Write the KV cache, then absorb, concat (and DCP-gather) the MQA query of all tokens ahead of forward, so this can overlap independent work such as the indexer. forward given the result skips its KV-cache write and attends with the leading rows, as MQA tokens come first. Only the symmetric-memory gather is moved: an NCCL gather could race concurrent collectives on the same communicator.

MMEncoderAttention

Bases: CustomOp

Multi-headed attention without any cache, used for multimodal encoder.

Methods:

__init__(num_heads, head_size, scale=None, num_kv_heads=None, prefix='')

Args: num_heads: number of attention heads per partition. head_size: hidden_size per attention head. scale: scale factor. num_kv_heads: number of kv heads. prefix: This has no effect, it is only here to make it easier to swap between Attention and MultiHeadAttention

_forward_fa(query, key, value, cu_seqlens=None, max_seqlen=None)

Input shape: (batch_size x seq_len x hidden_size) or (batch_size x seq_len x num_heads x head_size)

_forward_sdpa(query, key, value, cu_seqlens=None)

Input shape: (batch_size x seq_len x hidden_size) or (batch_size x seq_len x num_heads x head_size)

_forward_triton(query, key, value, cu_seqlens=None, max_seqlen=None, sequence_lengths=None)

Input shape: (batch_size x seq_len x hidden_size) or (batch_size x seq_len x num_heads x head_size)

_init_fp8_state()

Initialize FP8 attention state from multimodal config.

No-op if FP8 is not requested. Raises ValueError if FP8 is requested but the platform does not support it.

_record_amax_and_update_scales(query, key, value)

Record Q/K/V amax into circular history and recompute scales.

All work stays on GPU with no device-to-host sync. The Python-side history position counter is mutated, so this method must NOT be called inside CUDA graph capture/replay. When CUDA graphs are used for the encoder, dynamic scaling should be disabled by providing a static scale file via --mm-encoder-fp8-scale-path.

process_weights_after_loading()

Populate FP8 scale buffers (always float32) after weights are loaded.

view_qkv_to_4d(query, key, value, bsz, q_len, kv_len)

Reshape query, key, value to 4D tensors: (batch_size, seq_len, num_heads, head_size)

PrefillPrefixLMAttention

Bases: Attention

Decoder attention that runs non-causally (Prefix LM).

This reuses the encoder-only backend wrapper, which forces causal=False on every metadata build (prefill and decode alike), while keeping attn_type=DECODER so a KV cache is still allocated.

Effect by phase: - Prefill: query tokens attend to each other bidirectionally -- this is where the Prefix LM (non-causal) behavior actually takes effect. - Single-token decode: causal=False is a no-op. The one new query attends to the whole (frozen) KV cache exactly as a causal decode would, and cached tokens cannot attend back to it, so the output is identical to a causal decoder.

RSWAAttention

Bases: Attention

Attention layer whose KV cache is managed by RSWAManager.

Drop-in replacement for the standard Attention layer when the model is configured with Reference Sliding Window Attention (R-SWA, rswa_window > 0). The actual masking logic lives in the attention backend (FlexAttention or FA4 mask_mod); this layer only overrides get_kv_cache_config so the KV cache manager instantiates RSWAManager (instead of FullAttentionManager) and can therefore evict "gap" blocks to keep per-request KV memory bounded at O(prefix + window).

StaticSinkAttention

Bases: Attention, CustomOp

Attention with static sink tokens.

is_deferred_attention_layer(layer)

Whether an attention-like layer requires deferred post-load processing.