Skip to content

vllm.v1.core.kv_cache_utils

KV-Cache Utilities.

Classes:

Functions:

BlockHashListWithBlockSize

Convert block-hash granularity from hash_block_size to target_block_size. Used when KV cache groups have different block sizes: hash_block_size is the size used to compute the original block_hashes; target_block_size is the group's actual block size.

Currently, only scaling up by an integer factor is supported (i.e., target_block_size is a multiple of hash_block_size). Conversion is performed lazily on access for efficiency. Each hash_block_size hash is already chained over its entire prefix, so the hash at the last hash_block_size boundary of a target_block_size block uniquely fingerprints that block's prefix; we use it directly.

Example (hash_block_size = 16, target_block_size = 32): the second 16-size hash already covers tokens 0-31, so it is the 32-size hash:

Block hashes with block_size 16: | Token Range | 0-15 | 16-31 | 32-47 | 48-63 | |-------------|------|-------|-------|-------| | Hash | A | B | C | D |

Block hashes with block_size 32: | Token Range | 0-31 | 32-63 | |-------------|------|-------| | Hash | B | D |

Parameters:

  • block_hashes

    (list[BlockHash]) –

    Block hashes to convert, computed at hash_block_size.

  • hash_block_size

    (int) –

    Block size at which block_hashes were computed.

  • target_block_size

    (int) –

    Desired block size; must be a multiple of hash_block_size.

FreeKVCacheBlockQueue

This class organizes a list of KVCacheBlock objects to a doubly linked list of free blocks. We implement this class instead of using Python builtin deque to support removing a block in the middle of the queue in O(1) time. To close the performance gap to the builtin deque which is implemented in C++, this class does not allocate any Python objects when manipulating the linked list. Instead, this class manipulates the prev_free_block and next_free_block attributes of the given blocks.

The queue is ordered by block ID in the beginning. When a block is allocated and then freed, it will be appended back with the eviction order: 1. The least recent used block is at the front (LRU). 2. If two blocks have the same last accessed time (allocated by the same sequence), the one with more hash tokens (the tail of a block chain) is at the front. Note that we maintain this order by reversing the block order when free blocks of a request. This operation is outside of this class.

Parameters:

Methods:

  • append –

    Put a block back into the free list and increase

  • append_n –

    Put a list of blocks back into the free list

  • get_all_free_blocks –

    Get all free blocks in the free list. Mainly used for testing.

  • insert_before_cached –

    Insert blocks right before the first appended block (or at the tail

  • iter_blocks_after –

    Iterate free blocks in eviction order after the cursor.

  • popleft –

    Pop the first free block and reduce num_free_blocks by 1.

  • popleft_n –

    Pop the first n free blocks and reduce num_free_blocks by n.

  • prepend_n –

    Put a list of blocks at the front of the free list.

  • remove –

    Remove a block in the free list and reduce num_free_blocks by 1.

append(block)

Put a block back into the free list and increase num_free_blocks by 1.

Parameters:

append_n(blocks)

Put a list of blocks back into the free list

Parameters:

get_all_free_blocks()

Get all free blocks in the free list. Mainly used for testing.

Returns:

insert_before_cached(blocks)

Insert blocks right before the first appended block (or at the tail if none exist), preserving FIFO order among inserted blocks.

iter_blocks_after(cursor)

Iterate free blocks in eviction order after the cursor.

popleft()

Pop the first free block and reduce num_free_blocks by 1.

Returns:

popleft_n(n)

Pop the first n free blocks and reduce num_free_blocks by n.

Parameters:

  • n

    (int) –

    The number of blocks to pop.

Returns:

prepend_n(blocks)

Put a list of blocks at the front of the free list.

remove(block)

Remove a block in the free list and reduce num_free_blocks by 1.

Parameters:

KVCacheBlock dataclass

KV-cache block metadata.

Methods:

  • reset_hash –

    Reset the block hash when the block is evicted.

reset_hash()

Reset the block hash when the block is evicted.

_gen_lora_extra_hash_keys(request)

Generate extra keys related to LoRA for block hash computation.

The adapter path is included so that re-pointing a LoRA name at a different adapter does not reuse KV computed with the previous one.

Parameters:

  • request

    (Request) –

    The request object.

Returns:

_gen_mm_extra_hash_keys(request, start_token_idx, end_token_idx, start_mm_idx)

Generate extra keys related to MultiModal request for block hash computation. For multi-modal inputs, the extra keys are ("mm", mm_hash, start_offset) tuples that indicate a mm input contained in the block and its starting offset in the block tokens.

Parameters:

  • request

    (Request) –

    The request object.

  • start_token_idx

    (int) –

    The start token index of the block.

  • end_token_idx

    (int) –

    The end token index of the block.

  • start_mm_idx

    (int) –

    The start multi-modal index of the block.

Returns:

  • tuple[list[Any], int] –

    A tuple of extra keys and the next multi-modal index.

_gen_prompt_embeds_extra_hash_keys(request, start_token_idx, end_token_idx)

Generate extra keys related to prompt embeds for block hash computation.

Parameters:

  • request

    (Request) –

    The request object.

  • start_token_idx

    (int) –

    The start token index of the block.

  • end_token_idx

    (int) –

    The end token index of the block.

Returns:

frontend_block_hashes(request, prefix_hash_config)

Return the frontend's prompt block hashes, unless their count doesn't match the prompt, in which case the engine hashes the prompt itself.

generate_block_hash_extra_keys(request, start_token_idx, end_token_idx, start_mm_idx)

Generate extra keys for the block hash. The extra keys can come from the multi-modal inputs, request specific metadata (e.g., LoRA names), and hashed data from prompt embeddings.

Parameters:

  • request

    (Request) –

    The request object.

  • start_token_idx

    (int) –

    The start token index of the block.

  • end_token_idx

    (int) –

    The end token index of the block.

  • start_mm_idx

    (int) –

    The start multi-modal index of the block.

Returns:

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

    A tuple of extra keys and the next multi-modal index.

generate_lookahead_block_hash_extra_keys(request, start_token_idx, end_token_idx, hash_end_token_idx, start_mm_idx)

Generate extra keys for the block and its lookahead tokens.

Rewind the MM index to retain inputs overlapping the next block.

generate_scheduler_kv_cache_config(kv_cache_configs)

Generate the KV cache configuration for the scheduler.

get_block_hash(key)

Extract the BlockHash from a BlockHashWithGroupId.

get_group_id(key)

Extract the group id from a BlockHashWithGroupId.

get_kv_cache_capacity(vllm_config, kv_cache_config)

Get the group-aware KV cache token capacity and max concurrency.

get_max_concurrency_for_kv_cache_config(vllm_config, kv_cache_config)

Get the maximum concurrency for the given KV cache configuration.

A request at max_model_len consumes whole blocks from each group's block table, and all device groups draw those block ids from one shared pool, so the per-request total is the sum over groups.

Host groups use a separate pool; the smaller concurrency limit applies.

get_none_hash_seed()

Return the seed NONE_HASH was derived from.

Components that must agree on NONE_HASH across processes (the P2P tier advertises this during its connect handshake) read the resolved seed here instead of re-deriving it, so they observe the random seed too. Falls back to the deterministic seed before init_none_hash has run.

get_request_block_hasher(hash_block_size, caching_hash_fn, num_hash_lookahead_tokens=0)

Returns a function which computes the list of un-computed block hashes of a request.

Hashes are computed at hash_block_size granularity and chained over the full prefix, so each hash uniquely fingerprints the prefix ending at its boundary. Coarser group block sizes and partial-cache boundaries reuse these hashes directly (see BlockHashListWithBlockSize).

With num_hash_lookahead_tokens (L) > 0, each hash also covers the L tokens after its block, which the drafter's KV at the block's last position depends on, so it is emitted only once those tokens exist. The block tokens stay the hashed tokens; the extra keys become (E, *tokens), where E covers the block and those tokens.

hash_block_tokens(hash_function, parent_block_hash, curr_block_token_ids, extra_keys=None)

Computes a hash value corresponding to the contents of a block and the contents of the preceding block(s). The hash value is used for prefix caching. We use LRU cache for this function to avoid recomputing hash values for the same block contents.

Parameters:

  • hash_function

    (Callable[[Any], bytes]) –

    The hash function used to compute block hash.

  • parent_block_hash

    (BlockHash | None) –

    The hash of the parent block. None if this is the first block.

  • curr_block_token_ids

    (Sequence[int]) –

    A list of token ids in the current block. The current block is assumed to be full.

  • extra_keys

    (tuple[Any, ...] | None, default: None ) –

    Extra keys for the block.

Returns:

  • BlockHash –

    The hash value of the block and the token ids in the block.

  • BlockHash –

    The entire tuple is used as the hash key of the block.

is_mamba_prefix_caching_group(group)

Whether group holds Mamba state with prefix caching enabled.

make_block_hash_with_group_id(block_hash, group_id)

Pack a BlockHash and group id into a BlockHashWithGroupId.

The group id is encoded using 4 bytes in big-endian order and appended to the block hash bytes. This representation avoids creating tuples while still allowing us to recover both components when needed.

null_head_len(blocks)

Number of leading null blocks, e.g. a sliding-window table's skipped prefix.

partial_hash_hits_enabled(kv_cache_groups, hash_block_size, dcp_world_size=1, manager_classes=None)

Whether aligned Mamba states support sub-block prefix-cache hits.

If manager_classes (one per group) is given, also require every other prefix-cacheable group to support fine-grained lookups.

resolve_block_hashes(block_hashes, hash_block_size, block_size, *, supports_fine_grained_hash_lookup=False, alignment_tokens=None)

Resolve the block-hash view at block_size.

When block_size equals hash_block_size, reuse the precomputed block hashes directly; otherwise view them at block_size granularity. Fine-grained lookup keeps the original hashes for partial cache hits.

resolve_cache_hit_alignment_tokens(kv_cache_config, vllm_config, scheduler_block_size, hash_block_size)

Token granularity at which prefix-cache hits land.

Mirrors the alignment the hybrid KV cache coordinator pushes to its managers: fine-grained hits land on hash_block_size, all others on scheduler_block_size.

resolve_dcp_kv_block_size(group, dcp_world_size)

Return the token span of a group's cache block under DCP.

resolve_kv_cache_block_sizes(kv_cache_config, vllm_config)

Resolve (scheduler_block_size, hash_block_size).

  • scheduler_block_size is the token-alignment invariant used by the scheduler (e.g. for num_computed_tokens rounding). Single group: cache_config.block_size * dcp. Multiple groups: LCM of every group's effective block size. Attention groups are scaled by DCP; Mamba groups keep their full per-rank state and are not scaled.
  • hash_block_size is the granularity at which Request.block_hashes is computed. Single group: equals scheduler block size, and any other cache_config.prefix_match_unit is rejected while block hashing is active. Multiple groups: cache_config.prefix_match_unit override if set, else the GCD of group block sizes; every group's block size must be divisible by it. An explicit override is also rejected if prefix-cache hits would fall back to scheduler_block_size instead of landing on it. Returns the scheduler block size (i.e. disables finer hashing) if block hashing is inactive, or prefix caching is off for a mamba group.

resolve_none_hash_seed(hash_fn)

Resolve the seed to derive NONE_HASH from.

PYTHONHASHSEED wins if set. Otherwise cryptographic algorithms get the fixed default (shareable across processes) and non-cryptographic ones get fresh random bytes, keeping the seed unpredictable where collision resistance depends on it.

to_event_extra_keys(extra_keys)

Convert block-hash extra keys to the untagged per-block list published in KV events.

External KV event consumers parse the pre-tagging shapes: bare LoRA names and cache salts, (mm_identifier, offset) pairs and bare prompt-embeds digests. Events keep that format until consumers handle the tagged keys.

Parameters:

  • extra_keys

    (Iterable[tuple[Any, ...] | None] | None) –

    One entry per block, each as returned by generate_block_hash_extra_keys, or None.

Returns:

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

    One untagged entry per block, or None if there are no entries.

trim_null_head(blocks)

blocks without its leading null blocks; blocks itself if none.

update_kv_cache_capacity(vllm_config, kv_cache_config)

Store and log the resolved KV cache capacity.