Skip to content

vllm.v1.core.kv_cache_manager

Classes:

KVCacheBlocks dataclass

The allocation result of KVCacheManager, work as the interface between Scheduler and KVCacheManager, to hide KVCacheManager's internal data structure from the Scheduler.

Methods:

Attributes:

blocks instance-attribute

blocks[i][j] refers to the i-th kv_cache_group and the j-th block of tokens.We don't use block of tokens as the outer dimension because it assumes all kv_cache_groups have the same number of blocks, which is true for now but will be broken if we want to give different block_size to different kv_cache_groups in the future.

Each single type KVCacheBlocks could be represented as: - list[KVCacheBlock] for more than one KVCacheBlock - an empty tuple for requests without KVCacheBlock (a precomputed KVCacheBlocks is in KVCacheManager to avoid GC overhead)

__add__(other)

Adds two KVCacheBlocks instances.

get_block_ids(allow_none=False, *, group_ids=None)

get_block_ids(
    allow_none: Literal[False] = False,
    *,
    group_ids: Sequence[int] | None = None,
) -> tuple[list[int], ...]
get_block_ids(
    allow_none: Literal[True] = True,
    *,
    group_ids: Sequence[int] | None = None,
) -> tuple[list[int], ...] | None

Converts the KVCacheBlocks instance to block_ids.

Parameters:

  • allow_none

    (bool, default: False ) –

    Return None when every selected group is empty.

  • group_ids

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

    KV cache groups to include. Includes all groups by default.

Returns:

  • tuple[list[int], ...] | None –

    tuple[list[int], ...]: A tuple of lists where: - the outer tuple corresponds to KV cache groups - each inner list contains the block_ids of the blocks in that group

get_unhashed_block_ids()

Get block_ids of unhashed blocks from KVCacheBlocks instance.

get_unhashed_block_ids_all_groups()

Get block_ids of unhashed blocks from KVCacheBlocks instance.

new_empty()

Creates a new KVCacheBlocks instance with no blocks.

KVCacheManager

Methods:

Attributes:

usage property

Get the KV cache usage.

Returns:

  • float –

    The KV cache usage (between 0.0 and 1.0).

allocate_slots(request, num_new_tokens, num_new_computed_tokens=0, new_computed_blocks=None, num_lookahead_tokens=0, num_external_computed_tokens=0, delay_cache_blocks=False, num_encoder_tokens=0, full_sequence_must_fit=False, reserved_blocks=0, has_scheduled_reqs=True, skip_zeroing_group_ids=())

Add slots for a request with new tokens to append.

Parameters:

  • request

    (Request) –

    The request to allocate slots.

  • num_new_tokens

    (int) –

    The number of new tokens to be allocated and computed.

  • num_new_computed_tokens

    (int, default: 0 ) –

    The number of new computed tokens just hitting the prefix caching, excluding external tokens.

  • new_computed_blocks

    (KVCacheBlocks | None, default: None ) –

    The cached blocks for the above new computed tokens, grouped as a tuple by kv cache groups.

  • num_lookahead_tokens

    (int, default: 0 ) –

    The number of speculative tokens to allocate. This is used by spec decode proposers with kv-cache such as eagle.

  • num_external_computed_tokens

    (int, default: 0 ) –

    The number of tokens that their KV caches are not cached by vLLM but cached by the connector.

  • delay_cache_blocks

    (bool, default: False ) –

    Whether to skip caching the blocks. This is used by P/D when allocating blocks used in a KV transfer which will complete in a future step.

  • num_encoder_tokens

    (int, default: 0 ) –

    The number of encoder tokens to allocate for cross-attention in encoder-decoder models(e.g., Whisper). For decoder-only models, this should be 0.

  • full_sequence_must_fit

    (bool, default: False ) –

    Only allocate blocks if the KV cache has enough free blocks to hold the full sequence, accounting for prefix cache hits and sliding window. Used as an admission gate to prevent over-admitting requests when chunked prefill would otherwise only check the first chunk

  • reserved_blocks

    (int, default: 0 ) –

    Number of free blocks that must be left available for other in-flight sequences to complete. The actual allocation is only made if it fits within (free blocks - reserved_blocks). Used to gate async KV-connector loads so their initial allocation cannot consume blocks an already in-flight (prefilling) sequence is relying on.

  • has_scheduled_reqs

    (bool, default: True ) –

    Whether any requests are already scheduled to run this step, controls whether watermark is applied.

  • skip_zeroing_group_ids

    (tuple[int, ...], default: () ) –

    Groups whose external-token blocks will be written by an async load and must not be zeroed concurrently.

Blocks layout:

----------------------------------------------------------------------
| < comp > | < new_comp > | < ext_comp >  | < new >  | < lookahead > |
----------------------------------------------------------------------
                                          |   < to be computed >     |
----------------------------------------------------------------------
                          |            < to be allocated >           |
----------------------------------------------------------------------
                          | < to be cached (roughly, |
                          | details below)>          |
----------------------------------------------------------------------
| Prefix-cached tokens from either vLLM   |
| or connector. Can be safely removed if  |
| they are outside sliding window.        |
----------------------------------------------------------------------
|   < cached by vLLM >    | not cached by |
                          | vLLM, but     |
| ref_cnt  | ref_cnt not  | cached by     |
| increased| increased yet| connector     |
----------------------------------------------------------------------

Abbreviations:

comp      = request.num_computed_tokens
new_comp  = num_new_computed_tokens
          = len(new_computed_blocks) * block_size
ext_comp  = num_external_computed_tokens, cached by the connector
new       = num_new_tokens, including unverified draft tokens
lookahead = num_lookahead_tokens

NOTE: for new tokens which include both verified and unverified draft tokens, we only cache the verified tokens (by capping the number at request.num_tokens).

The allocation has three stages: - Free unnecessary blocks in comp and check if we have sufficient free blocks (return None if not). - Handle prefix tokens (comp + new_comp + ext_comp): - Free unnecessary blocks (e.g. outside sliding window) - Allocate new blocks for ext_comp tokens inside sliding window - Allocate new blocks for tokens to be computed (new + lookahead)

Returns:

cache_blocks(request, num_computed_tokens)

Cache the blocks for the request, if enabled.

Parameters:

  • request

    (Request) –

    The request to cache the blocks.

  • num_computed_tokens

    (int) –

    The number of computed tokens, including tokens that are already cached and tokens to be cached.

estimate_cached_tokens(request)

Estimate the number of tokens cached by the request.

evict_blocks(block_ids)

Evict blocks from the prefix cache by their block IDs.

Parameters:

  • block_ids

    (set[int]) –

    Set of block IDs to evict from cache.

extend_cached_prefix(request, num_tokens)

Extends num_tokens, a cached prefix length of the request, by the full-attention blocks cached after it (if any such groups).

finalize_partial_tail_offloads(request)

Consume safe producer partial tails when a request finishes.

A mamba align table block is a valid boundary source only if no later token was forwarded. The connector pins and queues the exact table block before request cleanup, then releases the pin when every worker reports the store job complete.

free(request)

Free the blocks allocated for the request. We free the blocks in reverse order so that the tail blocks are evicted first when caching is enabled.

Parameters:

  • request

    (Request) –

    The request to free the blocks.

get_block_ids(request_id)

Get the block ids of a request.

get_block_ids_for_computed_tokens(request_id, num_computed_tokens)

Get block ids covering the request's computed tokens.

get_blocks(request_id)

Get the blocks of a request.

get_computed_blocks(request, max_cache_hit_length=None)

Get the computed (cached) blocks for the request. Note that the computed blocks must be full.

Parameters:

  • request

    (Request) –

    The request to get the computed blocks.

  • max_cache_hit_length

    (int | None, default: None ) –

    Upper bound on the hit length. Defaults to request.get_max_cache_hit_length(); explicit bounds can only reduce the request's cache hit limit.

Returns:

  • tuple[KVCacheBlocks, int, int] –

    A tuple containing: - A list of blocks that are computed for the request. - The number of computed tokens. - shared_prefix_boundary: the block-aligned token position of a shared prefix that a sparse-retention group (Mamba / sliding window) has not cached yet (Marconi-style APC), or 0 if none. Pinned so sparse prefix-cache retention does not drop the junction and defeat cross-request reuse.

get_computed_blocks_for_connector(request, max_cache_hit_length=None)

Local prefix-cache lookup for a request scheduled with a KV connector.

Hybrid (Mamba + full-attention) models can have per-group prefix hits diverge under block pressure: the full-attention tail may be evicted while a deeper Mamba state survives, or vice versa. Report the full-attention hit as the local prefix - the connector transfers the remaining suffix and the Mamba state is transferred unconditionally by nixl's _apply_prefix_caching - and flag when that hit ran deeper than a lagging group. Such a hit only has a valid Mamba state at its boundary if the connector supplies it, so the caller must fall back to get_computed_blocks to reconcile when no external tokens are found.

Non-hybrid models and already-convergent hits use get_computed_blocks.

Returns:

  • KVCacheBlocks –

    The get_computed_blocks triple (blocks, number of local computed

  • int –

    tokens, shared-prefix boundary) plus hit_diverged.

get_num_cached_tokens(request)

How many of a request's tokens are already in the prefix cache.

Unlike get_computed_blocks, this only probes the cache: it takes no references, allocates no blocks and emits no events, so it is safe to call for a request that may not be scheduled.

Parameters:

  • request

    (Request) –

    The request to probe.

Returns:

  • int –

    The number of cached tokens, or 0 if lookup is disabled.

get_state_checkpoint_tokens(num_tokens)

Prompt position whose Mamba state a prefill of num_tokens tokens leaves prefix-cached (the boundary a later request can hit), or 0 if no group prefix-caches recurrent states at block boundaries. Accounts for the hash lookahead.

make_prefix_cache_stats()

Get (and reset) the prefix cache stats.

Returns:

  • PrefixCacheStats | None –

    The current prefix caching stats, or None if logging is disabled.

new_step_starts()

Notify the coordinator that a new step is starting.

pop_blocks_for_free(request)

Pop the request's bookkeeping and return its blocks without returning them to the block pool. The caller must eventually free them in reverse order (so that tail blocks are evicted first).

Parameters:

  • request

    (Request) –

    The request to pop the blocks for.

Returns:

prefix_cache_lookup_enabled(request)

Whether a local prefix cache lookup may be run for this request.

record_blocks_for_zeroing(request_id, start_token)

Re-record the request's blocks from start_token onwards for zeroing, e.g. blocks a failed async KV load left unwritten.

start_token must be block-aligned: zeroing a partially-valid block would wipe its valid prefix.

remove_skipped_blocks(request_id, processed_computed_tokens, num_prompt_tokens=None)

Remove the blocks that are no longer needed from blocks and replace the removed blocks with null_block.

Parameters:

  • request_id

    (str) –

    The request ID.

  • processed_computed_tokens

    (int) –

    Computed-token prefix length covering fully processed and committed tokens only (safe to free).

  • num_prompt_tokens

    (int | None, default: None ) –

    Optional prompt length for R-SWA gap eviction.

reset_prefix_cache()

Reset prefix cache. This function may be used in RLHF flows to invalidate prefix caching after the weights are updated, or used for resetting prefix caching status for benchmarking.

Returns:

  • bool ( bool ) –

    True if the prefix cache is successfully reset,

  • bool –

    False otherwise.

take_boundary_state_offloads()

Drain this step's boundary-state hand-offs for a KV connector.

Returns {request_id: [(group_id, block_id, boundary_tokens), ...]} for mamba boundary states: the request's committed boundary-state snapshots and, on a sub-block partial hit, the CoW copy of its last-prompt-boundary state. Only mamba groups contribute; empty otherwise. A connector reads the referenced blocks — never resolving them positionally — and offloads them so a later request can hit that prefix.

take_events()

Take the KV cache events from the block pool.

Returns:

take_kv_cache_block_copies()

Drain pending copies and return their retained endpoints.

take_new_block_ids()

Drain and return new attention block IDs for zeroing.

truncate_computed_blocks(blocks, num_computed_tokens)

Return a lookup-result view truncated at an aligned token endpoint.

An external hit can supply the final Mamba state even when the local Mamba group ends before this endpoint. Other groups must cover it. Pure slicing: refcounts are untouched and blocks is not mutated.