vllm.v1.core.kv_cache_utils
¶
KV-Cache Utilities.
Classes:
-
BlockHashListWithBlockSize–Convert block-hash granularity from
hash_block_sizetotarget_block_size. -
FreeKVCacheBlockQueue–This class organizes a list of KVCacheBlock objects to a doubly linked
-
KVCacheBlock–KV-cache block metadata.
Functions:
-
eagle_proof_margin–Tokens an EAGLE group matches past a cache hit before dropping them.
-
generate_block_hash_extra_keys–Generate extra keys for the block hash. The extra keys can come from
-
generate_scheduler_kv_cache_config–Generate the KV cache configuration for the scheduler.
-
get_block_hash–Extract the
BlockHashfrom aBlockHashWithGroupId. -
get_group_id–Extract the group id from a
BlockHashWithGroupId. -
get_kv_cache_capacity–Get the group-aware KV cache token capacity and max concurrency.
-
get_max_concurrency_for_kv_cache_config–Get the maximum concurrency for the given KV cache configuration.
-
get_none_hash_seed–Return the seed NONE_HASH was derived from.
-
get_request_block_hasher–Returns a function which computes the list of un-computed block hashes
-
hash_block_tokens–Computes a hash value corresponding to the contents of a block and
-
make_block_hash_with_group_id–Pack a
BlockHashand group id into aBlockHashWithGroupId. -
partial_hash_hits_enabled–Whether aligned Mamba states support sub-block prefix-cache hits.
-
resolve_block_hashes–Resolve the block-hash view at
block_size. -
resolve_cache_hit_alignment_tokens–Token granularity at which prefix-cache hits land.
-
resolve_dcp_kv_block_size–Return the token span of a cache block under DCP.
-
resolve_dcp_kv_cache_spec–Return a KV cache spec with block sizes adjusted for DCP.
-
resolve_kv_cache_block_sizes–Resolve (scheduler_block_size, hash_block_size).
-
resolve_none_hash_seed–Resolve the seed to derive NONE_HASH from.
-
to_event_extra_keys–Convert block-hash extra keys to the untagged per-block list published
-
update_kv_cache_capacity–Store and log the resolved KV cache capacity.
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_hasheswere computed. -
(target_block_size¶int) –Desired block size; must be a multiple of
hash_block_size.
Source code in vllm/v1/core/kv_cache_utils.py
1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 | |
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:
-
(blocks¶list[KVCacheBlock]) –A list of KVCacheBlock objects.
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.
-
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.
Source code in vllm/v1/core/kv_cache_utils.py
224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 | |
append(block)
¶
Put a block back into the free list and increase num_free_blocks by 1.
Parameters:
-
(block¶KVCacheBlock) –The block to append.
Source code in vllm/v1/core/kv_cache_utils.py
append_n(blocks)
¶
Put a list of blocks back into the free list
Parameters:
-
(blocks¶list[KVCacheBlock]) –The blocks to append.
Source code in vllm/v1/core/kv_cache_utils.py
get_all_free_blocks()
¶
Get all free blocks in the free list. Mainly used for testing.
Returns:
-
list[KVCacheBlock]–A list of free blocks.
Source code in vllm/v1/core/kv_cache_utils.py
iter_blocks_after(cursor)
¶
Iterate free blocks in eviction order after the cursor.
Source code in vllm/v1/core/kv_cache_utils.py
popleft()
¶
Pop the first free block and reduce num_free_blocks by 1.
Returns:
-
KVCacheBlock–The first free block.
Source code in vllm/v1/core/kv_cache_utils.py
popleft_n(n)
¶
Pop the first n free blocks and reduce num_free_blocks by n.
Parameters:
Returns:
-
list[KVCacheBlock]–A list of n free blocks.
Source code in vllm/v1/core/kv_cache_utils.py
prepend_n(blocks)
¶
Put a list of blocks at the front of the free list.
Source code in vllm/v1/core/kv_cache_utils.py
remove(block)
¶
Remove a block in the free list and reduce num_free_blocks by 1.
Parameters:
-
(block¶KVCacheBlock) –The block to remove.
Source code in vllm/v1/core/kv_cache_utils.py
KVCacheBlock
dataclass
¶
KV-cache block metadata.
Methods:
-
reset_hash–Reset the block hash when the block is evicted.
Source code in vllm/v1/core/kv_cache_utils.py
_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:
Returns:
-
list[tuple[str, str, str]]–Return the LoRA name and path of the request if it is a LoRA request.
-
list[tuple[str, str, str]]–Return empty list otherwise.
Source code in vllm/v1/core/kv_cache_utils.py
_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:
Source code in vllm/v1/core/kv_cache_utils.py
_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:
-
list[tuple[str, bytes]]–Return a stable hash of the block prompt embeddings if prompt embeds
-
list[tuple[str, bytes]]–are present. Return empty list otherwise.
Source code in vllm/v1/core/kv_cache_utils.py
eagle_proof_margin(block_size, hash_block_size, fine_grained_lookup)
¶
Tokens an EAGLE group matches past a cache hit before dropping them.
Fine-grained lookups drop one hash unit; others drop one cache block.
Source code in vllm/v1/core/kv_cache_utils.py
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:
Source code in vllm/v1/core/kv_cache_utils.py
generate_scheduler_kv_cache_config(kv_cache_configs)
¶
Generate the KV cache configuration for the scheduler.
Source code in vllm/v1/core/kv_cache_utils.py
get_block_hash(key)
¶
get_group_id(key)
¶
get_kv_cache_capacity(vllm_config, kv_cache_config)
¶
Get the group-aware KV cache token capacity and max concurrency.
Source code in vllm/v1/core/kv_cache_utils.py
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 — cdiv(per-request bytes, page bytes) of the group's spec — and all device groups draw those block ids from one shared pool, so the per-request total is the sum over groups. The memory/page ratio is identical whether a group carries an aggregated UniformTypeKVCacheSpecs (worker config) or a representative per-layer spec (scheduler config), so both capacity call sites agree.
Host groups use a separate pool; the smaller concurrency limit applies.
Source code in vllm/v1/core/kv_cache_utils.py
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.
Source code in vllm/v1/core/kv_cache_utils.py
get_request_block_hasher(hash_block_size, caching_hash_fn)
¶
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).
Source code in vllm/v1/core/kv_cache_utils.py
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.
Source code in vllm/v1/core/kv_cache_utils.py
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.
Source code in vllm/v1/core/kv_cache_utils.py
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.
Source code in vllm/v1/core/kv_cache_utils.py
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.
Source code in vllm/v1/core/kv_cache_utils.py
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.
Source code in vllm/v1/core/kv_cache_utils.py
resolve_dcp_kv_block_size(spec, dcp_world_size)
¶
Return the token span of a cache block under DCP.
resolve_dcp_kv_cache_spec(spec, dcp_world_size)
¶
Return a KV cache spec with block sizes adjusted for DCP.
Source code in vllm/v1/core/kv_cache_utils.py
resolve_kv_cache_block_sizes(kv_cache_config, vllm_config)
¶
Resolve (scheduler_block_size, hash_block_size).
scheduler_block_sizeis the token-alignment invariant used by the scheduler (e.g. fornum_computed_tokensrounding). 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_sizeis the granularity at whichRequest.block_hashesis computed. Single group: equals scheduler block size, and any othercache_config.prefix_match_unitis rejected while block hashing is active. Multiple groups:cache_config.prefix_match_unitoverride if set, else the GCD of group block sizes; every group's block size must be divisible by it. Returns the scheduler block size (i.e. disables finer hashing) if block hashing is inactive or a mamba group is not using cache mode "align".
Source code in vllm/v1/core/kv_cache_utils.py
782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 | |
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.
Source code in vllm/v1/core/kv_cache_utils.py
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.
Source code in vllm/v1/core/kv_cache_utils.py
update_kv_cache_capacity(vllm_config, kv_cache_config)
¶
Store and log the resolved KV cache capacity.