vllm.v1.core.kv_cache_manager
¶
Classes:
-
KVCacheBlocks–The allocation result of KVCacheManager, work as the interface between
-
KVCacheManager–
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:
-
__add__–Adds two KVCacheBlocks instances.
-
get_block_ids–Converts the KVCacheBlocks instance to block_ids.
-
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.
Attributes:
-
blocks(tuple[Sequence[KVCacheBlock], ...]) –blocks[i][j]refers to the i-th kv_cache_group
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_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:
-
allocate_slots–Add slots for a request with new tokens to append.
-
cache_blocks–Cache the blocks for the request, if enabled.
-
estimate_cached_tokens–Estimate the number of tokens cached by the request.
-
evict_blocks–Evict blocks from the prefix cache by their block IDs.
-
extend_cached_prefix–Extends
num_tokens, a cached prefix length of the request, by the -
finalize_partial_tail_offloads–Consume safe producer partial tails when a request finishes.
-
free–Free the blocks allocated for the request.
-
get_block_ids–Get the block ids of a request.
-
get_block_ids_for_computed_tokens–Get block ids covering the request's computed tokens.
-
get_blocks–Get the blocks of a request.
-
get_computed_blocks–Get the computed (cached) blocks for the request.
-
get_computed_blocks_for_connector–Local prefix-cache lookup for a request scheduled with a KV connector.
-
get_num_cached_tokens–How many of a request's tokens are already in the prefix cache.
-
get_state_checkpoint_tokens–Prompt position whose Mamba state a prefill of
num_tokens -
make_prefix_cache_stats–Get (and reset) the prefix cache stats.
-
new_step_starts–Notify the coordinator that a new step is starting.
-
pop_blocks_for_free–Pop the request's bookkeeping and return its blocks without
-
prefix_cache_lookup_enabled–Whether a local prefix cache lookup may be run for this request.
-
record_blocks_for_zeroing–Re-record the request's blocks from start_token onwards for
-
remove_skipped_blocks–Remove the blocks that are no longer needed from
blocksand replace -
reset_prefix_cache–Reset prefix cache. This function may be used in RLHF
-
take_boundary_state_offloads–Drain this step's boundary-state hand-offs for a KV connector.
-
take_events–Take the KV cache events from the block pool.
-
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–Return a lookup-result view truncated at an aligned token endpoint.
Attributes:
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:
-
KVCacheBlocks | None–A list of new allocated blocks.
cache_blocks(request, num_computed_tokens)
¶
estimate_cached_tokens(request)
¶
Estimate the number of tokens cached by the request.
evict_blocks(block_ids)
¶
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)
¶
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_blockstriple (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:
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:
Returns:
-
list[KVCacheBlock]–The request's blocks in allocation order.
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:
reset_prefix_cache()
¶
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:
-
list[KVCacheEvent]–A list of KV cache events.
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.