vllm.v1.attention.backends.utils ¶
Classes:
-
PerLayerParameters–Currently, FlashInfer backend only support models in which all layers share
Functions:
-
compute_mm_prefix_range_tensor–Convert mm_prefix_range dict to padded tensor for Triton kernel.
-
fill_mm_prefix_query_ranges–Map each scheduled query token to the mm_prefix range containing it.
-
get_dcp_local_seq_lens–While using dcp, kv_cache size stored on each rank may be different,
-
get_flashinfer_layout_string–Return the layout name in FlashInfer's convention (NHD/HND).
-
get_num_attention_heads_from_layers–Per-TP-rank
num_headsshared by the named Attention layers. -
get_per_layer_parameters–Scan layers in
layer_namesand determine some hyperparameters -
get_supported_kv_cache_layouts–Layouts every one of the worker's backends supports, most preferred first.
-
infer_global_hyperparameters–Currently, FlashInfer backend other than trtllm-gen
-
log2_lse_to_ln–Convert a base-2 log-sum-exp tensor to natural-log units.
-
mamba_get_block_table_tensor–Get the block table tensor for mamba kernels from the input
-
record_kv_cache_layout–Adopt a layout resolved elsewhere (the engine core) in this process.
-
reorder_batch_to_split_decodes_and_prefills–Reorders the batch to split into prefill and decode requests; places all
-
reshape_attn_output_for_spec_decode–Reshapes the attention output tensor, so that
-
reshape_query_for_spec_decode–Reshapes the query tensor for the specified batch size, so that
-
resolve_kv_cache_layout–Resolve one KV cache layout for the whole model.
-
split_decodes_and_prefills–Assuming a reordered batch, finds the boundary between prefill and decode
-
split_decodes_prefills_and_extends–Assuming a reordered batch, finds the boundary between prefill and decode
-
split_prefill_chunks–Split the prefill requests into chunks such that the total sequence length
-
subclass_attention_metadata–Return a new subclass of
metadata_clswith additional fields
PerLayerParameters dataclass ¶
Currently, FlashInfer backend only support models in which all layers share the same values for the following hyperparameters. Should not be used for trtllm-gen backend since it supports different values for the following hyperparameters.
Source code in vllm/v1/attention/backends/utils.py
compute_mm_prefix_range_tensor(mm_prefix_range, num_seqs, device) ¶
Convert mm_prefix_range dict to padded tensor for Triton kernel.
Returns shape: (num_seqs, max_ranges, 2) with 0-padding for empty ranges. Empty ranges have start==end==0, which kernel skips via is_valid check.
Source code in vllm/v1/attention/backends/utils.py
fill_mm_prefix_query_ranges(out, mm_prefix_range, query_start_loc_cpu, seq_lens_cpu) ¶
Map each scheduled query token to the mm_prefix range containing it.
Writes into out, a caller-owned (max_num_batched_tokens, 2) int32 staging buffer, and returns the number of rows written (0 if no range covers any scheduled query token, in which case out is untouched and the caller should skip the mask_mod entirely). Row i holds the absolute [start, end] bounds of the bidirectional range that query token i belongs to, or (-1, -1) when it is outside every range.
mm_prefix ranges never overlap, so "query and key share a range" is equivalent to "the key lies inside the query's own range". The kernel therefore needs no key-side lookup, and this metadata is sized by scheduled query tokens rather than by context length -- bounded by max_num_batched_tokens instead of num_seqs * max_seq_len.
Ranges are absolute prompt positions and may extend past the tokens scheduled so far under chunked prefill; the portion outside the current chunk is simply not recorded. Degenerate ranges (start >= end) are skipped to match the Triton path's start < end validity check.
seq_lens_cpu only needs to be exact for prefill rows, since mm_prefix ranges cover prompt tokens: an over-estimate on a decode row shifts that row's query position further past every range, which still matches nothing.
Source code in vllm/v1/attention/backends/utils.py
get_dcp_local_seq_lens(seq_lens, dcp_size=1, dcp_rank=None, cp_kv_cache_interleave_size=1) ¶
While using dcp, kv_cache size stored on each rank may be different, use this function to calculate split decode seq_lens of each dcp rank. Only consider dcp now, we can extend the case of cp based on this.
Source code in vllm/v1/attention/backends/utils.py
get_flashinfer_layout_string(layout) ¶
Return the layout name in FlashInfer's convention (NHD/HND).
Source code in vllm/v1/attention/backends/utils.py
get_num_attention_heads_from_layers(vllm_config, layer_names) ¶
Per-TP-rank num_heads shared by the named Attention layers.
Use in metadata builders whose plan-time allocations depend on the head count: the model-wide get_num_attention_heads() is wrong for models with non-uniform per-layer head counts. All layers in one attention group must agree on num_heads; this is asserted. Returns None when no matching Attention layer is found.
Source code in vllm/v1/attention/backends/utils.py
get_per_layer_parameters(vllm_config, layer_names, cls_) ¶
Scan layers in layer_names and determine some hyperparameters to use during plan.
Source code in vllm/v1/attention/backends/utils.py
get_supported_kv_cache_layouts(backends) ¶
Layouts every one of the worker's backends supports, most preferred first.
Every backend declares the layouts its kernels support, most preferred first (supported_kv_cache_layouts), or None when any layout works; workers where nothing declares follow the default preference. Identical declarations keep their order; otherwise the layout the most backends put first wins, ties keeping the enum order. An empty intersection is a hard error.
Source code in vllm/v1/attention/backends/utils.py
infer_global_hyperparameters(per_layer_params) ¶
Currently, FlashInfer backend other than trtllm-gen only support models in which all layers share the same values for the following hyperparameters: - window_left - logits_soft_cap - sm_scale
So this function asserts that all layers share the same values for these hyperparameters and returns the global values.
Source code in vllm/v1/attention/backends/utils.py
log2_lse_to_ln(lse) ¶
mamba_get_block_table_tensor(block_table, seq_lens, kv_cache_spec, mamba_cache_mode) ¶
Get the block table tensor for mamba kernels from the input common_attn_metadata.block_table_tensor given different mamba cache modes.
-
"all": input (#requests, cdiv(max_model_len, block_size) + num_speculative_blocks); output (#requests, cdiv(max_model_len, block_size) + num_speculative_blocks).
-
"none": input (#requests, 1 + num_speculative_blocks); output (#requests, 1 + num_speculative_blocks).
-
"align": input (#requests, cdiv(max_model_len, block_size)); output (#requests, 1 + num_speculative_blocks), which are the last 1 + num_speculative_blocks of each request.
Source code in vllm/v1/attention/backends/utils.py
record_kv_cache_layout(cache_config, layout_name) ¶
Adopt a layout resolved elsewhere (the engine core) in this process.
Source code in vllm/v1/attention/backends/utils.py
reorder_batch_to_split_decodes_and_prefills(input_batch, scheduler_output, decode_threshold=1) ¶
Reorders the batch to split into prefill and decode requests; places all requests with <= decode_threshold tokens at the front of the batch.
The batch is reordered into 4 regions
decode: (num_scheduled <= threshold AND is not prefilling) short_extend: (num_scheduled <= threshold AND is chunked prefilling) long_extend: (num_scheduled > threshold AND is chunked prefilling) prefill: (num_computed == 0) # First chunks
Returns:
-
bool–True if the batch was modified, False otherwise.
Source code in vllm/v1/attention/backends/utils.py
862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 | |
reshape_attn_output_for_spec_decode(attn_output) ¶
Reshapes the attention output tensor, so that the batch_size and seq_len dimensions are combined.
Source code in vllm/v1/attention/backends/utils.py
reshape_query_for_spec_decode(query, batch_size) ¶
Reshapes the query tensor for the specified batch size, so that it has shape (batch_size, seq_len, num_heads, head_dim).
Source code in vllm/v1/attention/backends/utils.py
resolve_kv_cache_layout(vllm_config, supported_layouts, kv_cache_specs=None) ¶
Resolve one KV cache layout for the whole model.
Runs once in the engine core. Every worker reports the layouts its backends support, most preferred first (get_supported_kv_cache_layouts); all ranks run the same backends, so their lists must agree. Specs mixing HNC shapes narrow the candidates to block-compact layouts. An explicit VLLM_KV_CACHE_LAYOUT must be one of the candidates or resolution fails, with the legacy NHD/HND names as aliases for LBNHC/LBHNC; the connector's preference is used when compatible and dropped with a warning otherwise. A layout already present on cache_config wins outright, and the result is recorded there (see CacheConfig.kv_cache_layout); it reaches workers through the set_kv_cache_layout RPC and KVCacheConfig.kv_cache_layout.
Source code in vllm/v1/attention/backends/utils.py
split_decodes_and_prefills(common_attn_metadata, decode_threshold=1, require_uniform=False, treat_short_extends_as_decodes=True) ¶
Assuming a reordered batch, finds the boundary between prefill and decode requests.
The batch is expected to be ordered as
decode → short_extend → long_extend → prefill
Parameters:
-
(common_attn_metadata¶CommonAttentionMetadata) –CommonAttentionMetadata object containing the batch metadata.
-
(decode_threshold¶int, default:1) –The maximum query length to be considered a decode.
-
(require_uniform¶bool, default:False) –If True, requires that all decode requests have the same query length. When set, some queries may be considered prefills even if they are <= decode_threshold, in order to ensure uniformity.
-
(treat_short_extends_as_decodes¶bool, default:True) –If True (default), short extends (query_len <= threshold but still prefilling) are counted as decodes. If False, they are counted as prefills.
Returns:
-
num_decodes(int) –The number of decode requests.
-
num_prefills(int) –The number of prefill requests.
-
num_decode_tokens(int) –The number of tokens in the decode requests.
-
num_prefill_tokens(int) –The number of tokens in the prefill requests.
Source code in vllm/v1/attention/backends/utils.py
split_decodes_prefills_and_extends(common_attn_metadata, decode_threshold=1) ¶
Assuming a reordered batch, finds the boundary between prefill and decode requests.
Parameters:
-
(common_attn_metadata¶CommonAttentionMetadata) –CommonAttentionMetadata object containing the batch metadata.
-
(decode_threshold¶int, default:1) –The maximum query length to be considered a decode.
Returns:
-
num_decodes(int) –The number of decode requests.
-
num_extends(int) –The number of extend requests.
-
num_prefills(int) –The number of prefill requests.
-
num_decode_tokens(int) –The number of tokens in the decode requests.
-
num_extend_tokens(int) –The number of tokens in the extend requests.
-
num_prefill_tokens(int) –The number of tokens in the prefill requests.
Source code in vllm/v1/attention/backends/utils.py
split_prefill_chunks(seq_lens_cpu, workspace_size, request_offset=0) ¶
Split the prefill requests into chunks such that the total sequence length of each chunk is less than or equal to the workspace size.
Parameters:
-
(seq_lens_cpu¶Tensor) –The sequence lengths of the prefill requests on CPU.
-
(workspace_size¶int) –The maximum workspace size (in tokens) per chunk.
-
(request_offset¶int, default:0) –The offset to add to the request indices.
Returns: A list of tuples of (reqs_start, reqs_end) representing chunk boundaries.
Source code in vllm/v1/attention/backends/utils.py
subclass_attention_metadata(name_prefix, metadata_cls, fields) ¶
Return a new subclass of metadata_cls with additional fields