Skip to content

vllm.v1.worker.utils

Classes:

Functions:

AttentionGroup dataclass

Methods:

map_kv_cache_to_kernel_blocks(kv_cache)

Views a packed cache in manager blocks as kernel blocks.

map_kv_cache_to_manager_blocks(kv_cache, num_blocks)

Views a packed cache in kernel blocks as manager blocks.

EncoderTimingStats dataclass

Per-request timing statistics for encoder forward pass.

Attributes:

encoder_forward_secs = 0.0 class-attribute instance-attribute

Time spent in vision encoder forward pass (seconds).

num_encoder_calls = 0 class-attribute instance-attribute

Number of times encoder was called for this request.

KVBlockZeroer

Manages efficient zeroing of KV cache blocks via a Triton kernel.

Construct once after KV caches are allocated to precompute segment addresses, then call zero_block_ids each step to zero newly-allocated blocks.

Methods:

  • __init__ –

    Precompute the absolute-address table for the Triton zeroing kernel.

  • warmup –

    JIT-compile the zeroing kernel before the first real request.

  • zero_block_ids –

    Zero the KV cache memory for the given block IDs.

__init__(device, attn_groups_iter, kernel_block_sizes, static_forward_context, num_blocks, runner_only_attn_layers=None)

Precompute the absolute-address table for the Triton zeroing kernel.

Each entry is the absolute byte address of a segment start on the GPU, so segments in different CUDA allocations work correctly.

Per-layer views are standardized [B, H, N, C] with blocks at dim 0; dims physically outside B (separate head groups under LHBNC) each get their own segment. A segment's page spans everything inside its block, so under BHLNC it also covers the block's other layers -- safe, since block IDs are global pool indices and a newly allocated block owns its whole tile.

Block IDs from the scheduler reference logical blocks whose size may differ from the kernel block size (virtual block splitting). Each virtual block is represented as an independent segment so its physical block stride and zeroed page span remain independent.

Only AttentionSpec layers are processed; Mamba layers are skipped.

warmup(num_kv_blocks)

JIT-compile the zeroing kernel before the first real request.

zero_block_ids(block_ids)

Zero the KV cache memory for the given block IDs.

_block_copy_runs(blocks, block_ids)

Split copies between the [2, num_copies] source and destination block_ids of blocks into contiguous runs.

Returns:

  • ndarray –

    An int64 array of shape [3, num_runs] holding source addresses,

  • ndarray –

    destination addresses and sizes in bytes.

_block_size_is_supported(supported_sizes, block_size)

Check if the block size is supported by all backends.

An exact int declaration must match exactly; a MultipleOf declaration accepts any multiple of its base.

_zero_kv_blocks_kernel(seg_addrs_ptr, seg_block_strides_ptr, seg_page_sizes_ptr, block_ids_ptr, BLOCK_SIZE)

Zero KV cache blocks across all segments in a single launch.

Each segment is a contiguous region of one block's data. Layer-compact layouts have one segment per layer buffer; dimensions physically outside the block dim (separate head groups under LHBNC) and virtual block splits each get their own segment.

Segments may have different block strides and page sizes (e.g. packed KV views or models with multiple KV cache groups like MLA + DSA indexer). Each segment's block stride determines where a logical block begins, while its page size determines how many elements are cleared.

seg_addrs_ptr holds absolute byte addresses (int64) for each segment, allowing segments to live in different CUDA allocations.

Programs are mapped directly onto a 3-D grid as (block_index, seg_index, chunk_index).

add_kv_sharing_layers_to_kv_cache_groups(shared_kv_cache_layers, kv_cache_groups, runner_only_attn_layers=None)

Sets up KV cache sharing by reusing the allocated KV caches in kv_caches for layers that do not allocate its own KV cache, based on the mapping in shared_kv_cache_layers. Adds these layers to the corresponding KV cache group, which is needed to ensure that attention metadata is assigned later.

Parameters:

  • shared_kv_cache_layers

    (dict[str, str]) –

    Layer pairings for cross-layer KV sharing. If an Attention layer layer_name is in the keys of this dict, it means this layer will perform attention using the keys and values from the KV cache of shared_kv_cache_layers[layer_name].

  • kv_cache_groups

    (list[KVCacheGroup]) –

    The KV cache groups of the model.

  • runner_only_attn_layers

    (set[str] | None, default: None ) –

    Attention layers handled by the runner only, which are excluded from the KV cache groups.

allocate_kv_cache(kv_cache_config, device, layout, kernel_block_sizes=None, allocate=None)

Allocate the KV cache and view it as [B, H, N, C] per layer.

Every KVCacheTensor places its layers in the same backing allocation: layer l of block b starts at offset + l * layer_stride + b * block_stride. Cache groups overlay each other, so tensors may address the same bytes.

allocate replaces the default zeroed backing allocation: it takes the size in bytes and returns a one-byte-per-element tensor.

bind_kv_cache(kv_caches, forward_context, runner_kv_caches, num_attn_module=1, layer_kv_caches=None)

Bind the allocated KV cache to both ModelRunner and forward context so that the KV cache can be used in the forward pass.

This function

1) Fills the ModelRunner's kv cache list (runner_kv_caches) with kv_caches. 2) Associates each attention layer in the forward_context with its corresponding KV cache in kv_caches.

Parameters:

  • kv_caches

    (dict[str, Tensor]) –

    The allocated kv_caches with layer names as keys.

  • num_attn_module

    (int, default: 1 ) –

    Number of attention modules per layer entry.

  • forward_context

    (dict[str, Attention]) –

    The global forward context containing all Attention layers with layer names as keys.

  • runner_kv_caches

    (list[Tensor]) –

    The kv_cache declared by ModelRunner.

  • layer_kv_caches

    (dict[str, Tensor] | None, default: None ) –

    The views to bind to layers when they differ from kv_caches (e.g. kernel-block views). The runner keeps kv_caches, which are addressed by scheduler block IDs.

bind_kv_cache_to_layers(kv_caches, forward_context)

Bind layer cache views.

clear_layer_kv_caches(layers)

Detach the KV/state cache tensors installed by bind_kv_cache().

The model object can outlive the runner (e.g. LLMEngine's finalizer keeps it reachable until engine deletion), so dropping the runner's references alone does not release the KV cache memory on teardown paths.

customize_attention_spec(backend, spec, layer_name)

The backend's spec. Blocks larger than every kernel block size a backend takes are split into kernel blocks, which packed blocks must keep whole.

customize_layer_config(backend, layer_config, layer_name)

Apply customize_attention_spec to an attention layer's spec.

get_uniform_decode_token_count(num_reqs, num_tokens, max_query_len, decode_graph_eligible)

Per-request token count of a uniform decode batch, or None.

groups_with_metadata_builders(groups)

The groups that build attention metadata: groups made only of init_attn_backend's no_attn_metadata_layer_names have no builders.

is_uniform_query_len(num_reqs, num_tokens, max_query_len)

Whether every request in the batch has the same query length.

Shape test only; use get_uniform_decode_token_count to classify a scheduled batch, since a prompt chunk can have a decode batch's shape.

layer_kernel_block_size(group_id, kernel_block_sizes)

Kernel block size to view the group's pages with, if it differs.

layer_spec_for_tensor(kv_cache_config, tensor)

Cache group index and per-layer spec of the layers tensor places.

map_kv_caches_to_kernel_blocks(kv_caches, attn_groups)

The views to bind to layers. The manager views in kv_caches stay for KV connectors.

prepare_kernel_block_sizes(kv_cache_config, attn_groups)

Generate kernel_block_sizes that matches each block_size.

For attention backends that support virtual block splitting, use the supported block sizes from the backend. For other backends (like Mamba), use the same block size (no splitting).

Parameters:

Returns:

  • list[int] –

    List of kernel block sizes for each cache group.

request_memory(init_snapshot, cache_config, external_weight_memory=0)

Calculate the amount of memory required by vLLM, then validate that the current amount of free memory is sufficient for that.

reserve_encoder_cache_residency(encoder_outputs, dummy_outputs, encoder_cache_size)

Reserve the encoder cache's resident footprint during profiling, in bytes.

The dummy run only materialises one compute batch, so a cache larger than the compute budget would be under-reserved and the surplus handed to the KV cache.

sanity_check_mm_encoder_outputs(mm_embeddings, expected_num_items)

Perform sanity checks for the result of vllm.model_executor.models.SupportsMultiModal.embed_multimodal.

select_common_block_size(kv_manager_block_size, backends, kv_cache_specs=None, layer_names=None)

Select a block size that is supported by all backends and is a factor of kv_manager_block_size.

If kv_manager_block_size is supported by all backends, return it directly. Otherwise, return the max supported size.

Parameters:

  • kv_manager_block_size

    (int) –

    Block size of KV cache.

  • backends

    (list[type[AttentionBackend]]) –

    List of attention backend classes.

  • kv_cache_specs

    (Sequence[KVCacheSpec | None] | None, default: None ) –

    Per-backend cache specs for spec-specific constraints.

  • layer_names

    (Sequence[list[str]] | None, default: None ) –

    Per-backend layer names for layer-specific constraints.

Returns:

  • int –

    The selected block size.

Raises: