Skip to content

vllm.v1.core.kv_cache_planning

KV cache planning: grouping, sizing, and memory-fit logic.

Classes:

Functions:

DefaultKVCacheConfigBuilder

Bases: KVCacheConfigBuilder

Default grouping and placement, backed by the module-level functions here.

Note

This class is part of the experimental KVCacheConfigBuilder interface and is subject to change.

Subclasses override only the hooks they need. The planning flow and its invariants (num_gpu_blocks_override, null-block reservation, auto-fit, admission checks, cross-rank convergence) stay in the Core-owned get_kv_cache_configs.

Methods:

get_kv_cache_config_from_groups(vllm_config, kv_cache_groups, num_blocks)

See KVCacheConfigBuilder.get_kv_cache_config_from_groups.

get_kv_cache_groups(vllm_config, layer_configs)

See KVCacheConfigBuilder.get_kv_cache_groups.

A model implementing SupportsKVCacheGrouping owns the grouping decision; otherwise the default grouping is used.

_approximate_gcd(values, *, lower_bound=None)

Pick a chunk size that minimizes total upward padding.

Each x is rounded up to a multiple of d:

x -> ceil(x / d) * d

Total padding is:

pad(d) = sum_i (ceil(x_i / d) * d - x_i)

We brute-force d in [lower_bound, max(values)] (fine for small lists / small maxima) and return the d with minimum padding. Ties prefer larger d.

_auto_fit_max_model_len(builder, vllm_config, projected_groups_per_worker, available_memory, after_warmup=False)

When max_model_len is set to -1, this function estimates the largest context length that can be supported with the available GPU memory. It uses binary search to find the maximum length that fits across all workers.

Parameters:

  • builder

    (KVCacheConfigBuilder) –

    The builder whose hooks drive block accounting.

  • vllm_config

    (VllmConfig) –

    The global VllmConfig (will be modified in-place)

  • projected_groups_per_worker

    (list[list[KVCacheGroup]]) –

    KV cache groups projected to each worker.

  • available_memory

    (list[int]) –

    Memory available for KV cache in bytes for each worker.

  • after_warmup

    (bool, default: False ) –

    Whether this re-fits a length fitted before CUDA graph capture and warmup to the memory measured after them.

_bucket_layers(layer_configs)

Greedily bucket layers that can share a block table, in layer order.

_check_exact_partition(groups, layer_configs)

Ensure the groups partition every input layer exactly once.

_ensure_min_page_size(groups, common_page, hidden_specs)

Scale up group block sizes so the common page is at least as large as the biggest hidden-state per-token cost.

This protects the hidden state extraction feature, where we store hidden states in the KV cache, and return them to clients using a custom hidden state connector.

Returns the (possibly scaled) groups and updated common page size.

_estimate_max_model_len_from_groups(builder, vllm_config, kv_cache_groups, available_memory)

Binary search for the maximum model length that fits in available memory. Returns 0 if even 1 token doesn't fit.

_get_kv_cache_bytes_per_block(kv_cache_groups, layout)

Return the largest cache group's bytes per block.

_get_kv_cache_groups_uniform_page_size(layer_configs)

Generates the KV cache groups for hybrid models with multiple attention types but still with a uniform page size (physical memory per block per layer) for all layers.

Detailed explanation about kv cache management of hybrid models: The layers in the models are repeated with some patterns, e.g., a model with 10 full attention layers and 20 sliding window attention layers can be regarded as repeating the pattern (1 * full, 2 * sw) 10 times. The KVCacheManager allocates different block tables for each of the 3 layers in the pattern, and repeats each of them 10 times to generate the block_table for the 30 layers in the model. Therefore, we can group the layers in the model into 3 kv_cache_groups, each of which contains 10 layers in the model. The KVCacheManager allocates the block_table for each group based on its kv_cache spec, and the model runner applies the block table to each layer in the group. For example: 1. A model only uses full attention. The pattern is (num_hidden_layers * full), so there is only one group and the block table is shared by all layers. 2. A model with 10 full attention layers and 20 sliding window attention layers. There are 3 layers in the pattern (1 * full, 2 * sw), so there are 3 kv_cache_groups, each of which represents 10 layers.

To simplify the implementation, we make the following assumptions: 1. Physical memory per block: Must be the same across all KV cache groups. Breaking this assumption is non-trivial due to memory fragmentation concerns when allocating blocks of different sizes. 2. Tokens per block (block_size): Currently, we directly use CacheConfig.block_size for all layers. It can be extended to vary by KV cache group, but within each KV cache group, all layers must share the same block size. 3. Physical memory per token per layer: This property is decided by model config. Currently we only support models that have the same physical memory per token per layer for all layers. Can be relaxed with a simple extension, but still need to keep physical memory per block the same for all groups. 4. Number of layers per group: Currently assumed the same for all layers. Can be relaxed with a simple extension, but still need to keep physical memory per block the same for all groups. 5. Attention type within groups: All layers in a group must share the same attention type. One exception is that, when --disable-hybrid-kv-cache-manager is true, the single group for full attention layers may also include attention layers using sliding window or LLaMA 4 local attention. See unify_hybrid_kv_cache_specs for more details. 6. Support for multiple attention types: The design for most components is general to an arbitrary number of attention types. But find_longest_cache_hit only supports one attention type or two types of full-attention plus exactly one another type. The general implementation of this function is feasible but we don't know how to implement it cleanly yet.

As we assume tokens per block, physical memory per token per layer, and number of layers per group are the same now, we can ensure that physical memory per block is the same for all groups.

Parameters:

Returns: The generated KVCacheGroups

_get_layer_block_stride(spec)

A layer-outer block stride: the page padded to its alignment.

_get_packed_kv_cache_groups(vllm_config, layer_configs)

Group mixed-page-size layers for contiguous block-outermost packing.

Greedily buckets layers that can share a block table. Buckets with equal layer counts per page size are treated as a repeating layer pattern (one layer per page size) and split into groups covering the same number of pattern repeats (picked by _approximate_gcd to minimize padding), so all groups pack into the same per-block layout. Mamba buckets are additionally split to fit the block the attention buckets already need. Returns None when the layout is not block-outermost or all layers already share one page size.

_group_layers_by_spec(group)

The group's layers by spec, in the order its spec regions are placed.

Layers with the same spec are placed together, in order of first appearance. get_kv_cache_config_from_groups places the regions in this order, and _overlaid_layers_match checks the overlaid layers in it.

_max_memory_usage_bytes_from_groups(builder, vllm_config, kv_cache_groups)

Calculate maximum memory usage in bytes from KV cache groups.

This correctly accounts for padding in hybrid models. For example, if a model has 8 full attention layers and 9 sliding window layers, they will be padded to 9 full + 9 sliding window for uniform group sizes.

Each group independently claims blocks from the shared pool, so a request consumes the sum of the per-group block counts, i.e. bytes_per_block * total_blocks.

_more_kv_cache_memory_hint(vllm_config, after_warmup=False)

How the user can make room for the KV cache, for error messages. after_warmup: the KV cache was sized after CUDA graph capture and warmup.

_overlaid_layers_match(kv_cache_groups)

Whether the groups can overlay each other in a layer-compact layout.

In a layer-compact layout, each layer of a group gets a region of its own. The regions of every group start at byte 0 and follow one another. So the i-th layer of a group shares its region with the i-th layer of every other group. A block belongs to one group at a time, so this is safe if the layers that share a region have the same block stride.

For example, with block strides P and p:

[P, P, p, p] and [P, P]      match
[P, P, p, p] and [P, P, P]   do not match: the third region is p or P

_pool_bytes_per_block(vllm_config, kv_cache_groups)

Bytes consumed by one block in the worker's shared device KV cache pool.

_pool_bytes_per_block_from_builder(builder, vllm_config, kv_cache_groups)

Bytes consumed by one block in the worker's device KV cache pool.

Core places one block with the builder and reads the size of its single device backing. A placement with several device allocations declares the value through KVCacheConfigBuilder._get_pool_bytes_per_block. HiSparse keeps the pure computation, since probing its placement would check the host pool against max_model_len before auto-fit shortens it.

_project_kv_cache_groups_to_worker(global_kv_cache_groups, worker_spec)

Projects global KV cache groups onto a single worker's assigned layers.

In pipeline parallelism, each worker only owns a subset of layers. This function filters the global groups to include only layers present on the given worker.

Parameters:

Returns:

  • list[KVCacheGroup] –

    The projected KV cache groups containing only this worker's layers.

_promote_local_kv_cache_specs(layer_configs)

Use full-attention allocation for local-attention cache specs.

The returned specs affect KV cache management only. Attention modules keep their original sliding-window or chunked-local compute behavior.

Promoted layers also take the full-attention block size when there is exactly one, so they can share its block table, and their page padding is raised to cover the resized page (#48776).

_try_get_full_allocation_fallback_groups(layer_configs)

Try a supported full-allocation fallback for local-attention layers.

Full attention is never worse here: without a common page size, a separate sliding-window group still pays for every layer's page on each block ID, so freeing out-of-window blocks saves no memory.

can_share_block_table(layer_configs)

Whether the layers can form one KV cache group: one manager policy, block size and DCP sharding, with layouts the manager accepts side by side.

finalize_extensible_kv_cache(vllm_config, kv_cache_configs, scheduler_kv_cache_config, compilation_times)

Settle the KV cache size from the memory workers measured after warmup.

Every rank must agree on one block count, so the minimum becomes the scheduler's num_blocks; the caller commits it on the workers.

get_global_kv_cache_groups(vllm_config, layer_configs)

Group the layers of the whole model (all workers' specs merged).

get_kv_cache_config_from_groups(vllm_config, kv_cache_groups, num_blocks)

Materialize KV cache tensors for kv_cache_groups and exactly num_blocks blocks.

get_kv_cache_configs(vllm_config, layer_configs, available_memory, global_kv_cache_groups)

Generates the KV cache configurations for a model. Since we use a shared centralized controller for all workers, we need the kv_cache_config to be consistent across all workers to make sure the KV cache allocation can be applied to all workers. However, different workers may have different memory available, and different type of layers (when pipeline parallel is enabled). To handle the difference between workers, the current implementation is: 1. Merge the KV cache specs of all workers to get the KVCacheSpecs for the whole model. 2. Generate the KV cache groups based on the layer ratio of the whole model. This also handles spec unification for hybrid models. (Steps 1-2 are done by get_global_kv_cache_groups.) 3. Handle auto-fit max_model_len and memory checks using per-worker projected groups to account for PP sharding. 4. Generate the KV cache configs for each worker based on the KV cache grouping strategy. (This is reasonable because the layer ratio of different PP stages are similar.) 5. Change the num_blocks of each worker to the smallest among all workers and shrink tensor sizes proportionally to avoid allocating unused memory.

Parameters:

  • vllm_config

    (VllmConfig) –

    The global VllmConfig

  • layer_configs

    (list[dict[str, KVCacheLayerConfig]]) –

    List of dict[layer_name, KVCacheLayerConfig] for each worker.

  • available_memory

    (list[int]) –

    Memory available for KV cache in bytes for each worker.

  • global_kv_cache_groups

    (list[KVCacheGroup]) –

    From get_global_kv_cache_groups.

Returns:

get_kv_cache_groups(vllm_config, layer_configs)

Split the layers in the model into groups that share a block table.

Parameters:

Returns:

get_kv_cache_groups_from_builder(builder, vllm_config, layer_configs)

Group the layers with the builder and check the result.

Core checks every grouping, whether it comes from the default grouping, a model's SupportsKVCacheGrouping or a platform builder.

get_pipeline_stages(vllm_config, kv_cache_configs)

The KV cache of every pipeline stage, described by the first worker of each stage (workers are ordered by PP rank, then by PCP and TP rank).

kv_cache_groups_tp_replicas(groups, tp_size, dcp_size=1)

Consecutive TP ranks holding identical KV for every layer.

resolve_mamba_block_size(vllm_config, layer_configs)

Mamba block size for every worker's prefix-caching Mamba specs, or None if the workers already agree.

Each worker sizes its Mamba blocks from the attention layers it holds, which a pipeline stage may lack, but the scheduler aligns every Mamba group to one size. The result is the largest size that every attention block size of the model is a multiple of.

shrink_kv_cache_configs(vllm_config, kv_cache_configs, num_blocks)

Lower num_blocks of every config in place after measured sizing. The tensors' size follows (their strides and offsets keep describing the reservation). Raises if max_model_len no longer fits.

unify_hybrid_kv_cache_specs(layer_configs)

This function tries to convert the KV cache specs to one type if the model is a hybrid model with multiple type of KV cache. It will convert all local-attention layers to full attention if both types are present.

Parameters:

unify_kv_cache_spec_page_size(layer_configs)

Unify the page size of the given KVCacheSpec. If the page size of all layers are the same, return the original KVCacheSpec. If not same, unify the page size by increasing the block size of layers with smaller page size. Two cases cannot be unified by block size alone and pad their physical page to the maximum instead: Mamba layers, whose page size comes from state shapes and is independent of block size; and non-MLA attention layers whose page does not evenly divide the maximum (the padded page is read through a strided view). MLA is excluded because sparse MLA indexes the cache in whole token rows (see flat_kv_row_view), so its block stride can only be padded by its own row-aligned alignment, not to an arbitrary page size. Raise NotImplementedError if failed to unify the page size; get_kv_cache_groups catches it to try the full-allocation fallback (e.g. MLA next to an incompatible sliding-window draft).

Parameters:

Returns:

validate_kv_cache_layout(layout, kv_cache_groups)

Validate that the resolved layout can express this model's packing.

The layout was chosen once in the engine core from the backends' supported sets; a backend whose model packs pages side by side (e.g. the DeepSeek-V4 indexer) declares block-outermost layouts there, so an inexpressible layout reaching this point is an error.