Skip to content

vllm.v1.attention.backends.flex_attention

Attention layer with FlexAttention.

Classes:

Functions:

BlockSparsityHint

Bases: NamedTuple

This prunes KV blocks from the BlockMask before the flex_attention kernel is invoked, so that blocks that are fully masked never get loaded. Use this with custom mask_mods that are sparse to avoid the kernel iterating over all KV blocks unnecessarily.

Attributes:

  • hint_fn (_block_sparsity_hint_signature) –

    (q_block_idx [num_tokens, 1], kv_block_idx [1, num_kv_blocks], block_size int) -> bool Tensor [num_tokens, num_kv_blocks]. Returns True for block pairs that may contain non-masked elements.

FlexAttentionBackend

Bases: AttentionBackend

Methods:

supports_attn_type(attn_type) classmethod

FlexAttention supports both decoder and encoder-only attention.

supports_mm_prefix() classmethod

FlexAttention supports full attention for image tokens.

FlexAttentionImpl

Bases: AttentionImpl

Methods:

  • forward –

    Forward pass with FLexAttention.

  • view_as_4d –

    View a 3d tensor as 4D.

forward(layer, query, key, value, kv_cache, attn_metadata, output, output_scale=None, output_block_scale=None)

Forward pass with FLexAttention.

Parameters:

  • layer

    (Module) –

    The attention layer, providing the q/k/v quantization scales.

  • query

    (Tensor) –

    shape = [num_tokens, num_heads, head_size]

  • key

    (Tensor) –

    shape = [num_tokens, num_kv_heads, head_size]

  • value

    (Tensor) –

    shape = [num_tokens, num_kv_heads, head_size]

  • kv_cache

    (Tensor) –

    shape = [num_blocks, num_kv_heads, block_size, 2 * head_size]

  • attn_metadata

    (FlexAttentionMetadata) –

    Metadata for attention.

  • output

    (Tensor) –

    Tensor that the attention result is written into.

  • output_scale

    (Tensor | None, default: None ) –

    Scale for fused output quantization; not supported by this backend.

  • output_block_scale

    (Tensor | None, default: None ) –

    Block scale for fused output quantization; not supported by this backend.

Returns:

  • Tensor –

    shape = [num_tokens, num_heads * head_size]

view_as_4d(tensor) staticmethod

View a 3d tensor as 4D.

FlexAttentionMetadata dataclass

Methods:

_build_block_mask_direct()

Direct block mask construction for paged KV cache attention.

This method constructs the block mask directly using BlockMask.from_kv_blocks which is much more efficient than the generic create_block_mask approach.

The direct path works as follows: 1. For each query token, fetch blocks from block_table using max_seq_len and exclude out of sliding window blocks if needed. (this fetches more blocks than needed for shorter sequences) 2. Group query tokens into chunks of q_block_size 3. For each group, deduplicate the blocks using unique_static_unsorted 4. Create BlockMask using the deduplicated block indices

Over-estimation occurs when a group of q_block_size tokens contains multiple sequence IDs (doc_ids). In this case, we fetch ALL blocks for each sequence represented in the group, even though individual query tokens may only need a subset of those blocks based on causal masking and their position.

_convert_physical_to_logical(request_lookup, q_idx, physical_kv_idx)

Convert physical indices to logical indices for both query and kv.

NB is_within_lower_bound: do sequences start on block_boundaries?

Returns:

get_bidirectional_mask_mod()

Creates the encoder mask_mod function for FlexAttention.

Since the encoder bidirectional attention doesn't run with KV cache, this function creates a mask based on the packed query sequences.

get_paged_mask_mod()

Creates the mask_mod function for FlexAttention.

This function creates the combined mask mod function that handles
  1. The paged attention block mapping
  2. The mapping from packed query sequences to logical query entries

It also by defaults adds the decoding offset to the query indices. With this info we create the "logical" indices that are passed to mask_mod functions. This allows mask mod functions to be agnostic to layout of the query and key/value tensors.

get_prefix_lm_mask_mod()

Creates the prefix LM mask_mod function for FlexAttention.

get_rswa_mask_mod()

Creates the Reference Sliding Window Attention (R-SWA) mask_mod.

R-SWA keeps the whole prefix (image + prompt tokens, i.e. logical index < prefix_len) globally visible while generated tokens additionally attend a fixed sliding window of recent tokens. This term is combined with the base causal mask via logical AND, so it only ever removes far-away generated tokens that fall outside the window and outside the prefix.

get_sliding_window_mask_mod()

Creates the sliding window mask_mod function for FlexAttention.

Note that the sliding window mask here is bidirectional, we need to mask it with the bidirectional/causal mask for encoder/decoder.

get_transformed_score_mod()

Creates the transformed score_mod function for FlexAttention.

This function wraps the user's score_mod to handle physical-to-logical index conversion, similar to how get_mask_mod works for mask functions.

FlexAttentionMetadataBuilder

Bases: AttentionMetadataBuilder[FlexAttentionMetadata]

_make_metadata(**kwargs)

Create the metadata build returns and builds the block mask of. A subclass may return its own subclass, e.g. with another get_mask_mod and extra fields filled from this builder.

physical_to_logical_mapping(block_table, seq_lens, block_size, total_blocks)

Creates an inverse mapping from physical block locations to logical indices.

The original block_table maps from logical blocks to physical locations:

Logical to Physical (Original block_table): ┌───────────────────────────────────────────┐ │ Request 0: │ │ │ │ Logical Blocks: 0 1 2 3 4 5 6 7 │ │ │ │ │ │ │ │ │ │ │ │ v v v v v v v v │ │ Physical Blocks: 3 5 1 7 4 2 0 6 │ └───────────────────────────────────────────┘

This function creates the inverse mapping:

Physical to Logical (Inverse mapping): ┌───────────────────────────────────────────┐ │ Request 0: │ │ │ │ Physical Blocks: 0 1 2 3 4 5 6 7 │ │ │ │ │ │ │ │ │ │ │ │ v v v v v v v v │ │ Logical Blocks: 6 2 5 0 4 1 7 3 │ └───────────────────────────────────────────┘

If multiple logical blocks map to the same physical block, this function returns the latest (maximum) logical block index.

If a physical block is not mapped to by any logical block, its value in the result will be -1.

IMPORTANT: Garbage Value Protection ──────────────────────────────────── The block_table tensor may contain garbage values in unused positions (beyond the actual sequence length). For example, if a sequence only needs 3 blocks but the table has space for 8:

block_table[0] = [10, 25, 7, 999, 1234, 888, ...]
                            ^^^^^^^^^^^^^^^^^^^^
                            garbage values

These garbage values can cause issues because: 1. They may map to valid physical blocks by coincidence 2. The scatter_ operation will assign them logical indices 3. Later attention computations may incorrectly access these blocks

To prevent this, we use seq_lens and block_size to mask out unused entries, ensuring only valid block references are processed.

IMPORTANT: Reused physical blocks (sliding-window / hybrid attention) ──────────────────────────────────────────────────────────────────── For some attention types, physical cache blocks can be reused over time. This can cause the same physical block id to appear multiple times in a row of block_table at different logical block indices. In that case, only the latest logical block index corresponds to the current contents of that physical block. Therefore, the inverse mapping must pick the maximum logical block index for each physical block id.

Parameters:

  • block_table

    (Tensor) –

    Tensor of shape [max_reqs, max_num_blocks] mapping logical blocks to physical locations. May contain garbage values in unused positions.

  • seq_lens

    (Tensor) –

    Tensor of sequence lengths for each request. Used to determine how many blocks are actually needed per sequence.

  • block_size

    (int) –

    Size of each block in tokens. Used with seq_lens to compute the number of valid blocks per sequence.

  • total_blocks

    (int) –

    Total number of physical blocks available

Returns:

  • Tensor –

    A tensor of shape [max_reqs, total_blocks] where each entry

  • Tensor –

    physical_to_logical[req_id, physical_block] contains the logical

  • Tensor –

    block index for that physical block, or -1 if unused.

unique_static_unsorted(x, *, M, dim=-1, ignored_val=0, pad_val=-1)

  • Keeps the first occurrence of each non-zero value while preserving order, then left-packs those uniques and fills the rest with pad_val.
  • Returns (packed, keep_mask) with the same shape as x.
  • Requires that all values be in the range [0, M]
  • Skips ignored_val

Works on CPU or GPU, no Python loops, O(B·N) time / O(B·M) memory.

Example: x =[3, 1, 0, 1, 2], M=3, ignored_val=0 => [3, 1, 2, -1, -1]