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:
-
check_enough_kv_cache_memory–Checks whether
available_memoryis enough for the KV cache to hold at -
create_kv_cache_group_specs–Create KVCacheGroupSpec object for each kv cache group layer.
-
eagle_proof_margin–Tokens an EAGLE group matches past a cache hit before dropping them.
-
estimate_max_model_len–Estimates the maximum model length that can fit in the available memory
-
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_kv_cache_config_from_groups–Generate the KV cache configuration from the KV cache groups and spec
-
get_kv_cache_configs–Generates the KV cache configurations for a model.
-
get_kv_cache_groups–Split the layers in the model into groups with the same KV cache spec.
-
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
-
get_uniform_page_size–Get the page size of the KV cache.
-
hash_block_tokens–Computes a hash value corresponding to the contents of a block and
-
is_kv_cache_spec_uniform–Whether all layers in the given KVCacheSpec have the same KV cache spec.
-
kv_cache_groups_tp_replicas–Consecutive TP ranks holding identical KV for every layer.
-
make_block_hash_with_group_id–Pack a
BlockHashand group id into aBlockHashWithGroupId. -
max_memory_usage_bytes–Get the maximum memory usage in bytes for the given KV cache specs.
-
may_override_num_blocks–Override the number of kv cache blocks if
num_gpu_blocks_overrideis set. -
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
-
unify_hybrid_kv_cache_specs–This function tries to convert the KV cache specs to one type if the model
-
unify_kv_cache_spec_page_size–Unify the page size of the given KVCacheSpec. If the page size of all layers
-
update_kv_cache_capacity–Store and log the resolved KV cache capacity.
-
validate_kv_cache_layout–Validate that the resolved layout can express this model's packing.
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
2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 | |
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
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 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 | |
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
_annotate_eagle_groups(vllm_config, kv_cache_spec, kv_cache_groups, use_trailing_layer_fallback=False)
¶
Flag the KV cache groups that hold drafter attention layers.
Two detection rules, in order of preference:
- Spec-driven.
non_causal_multi_token_decodeis declared on MLAAttentionSpec and set by drafter attention layers that run a non-causal multi-token decode (today only Kimi-K3 DSpark). It survives MLAAttentionSpec.merge, so it still identifies a group after per-group spec merging, wherever grouping happens to land. It is sufficient but not necessary: a drafter whose spec is indistinguishable from the target's cannot be found this way. - Positional fallback for MTP drafters (including DeepseekV4/V4.1 DSpark), whose
MTP block reuses the target's own decoder layer and so carries no spec
marker. Their draft attention layers always register after every
target layer, so flag whichever group holds the last registered layer.
This rule is only valid where the groups partition exactly the layers
of
kv_cache_spec, which is re-checked here before applying it. When a drafter's trailing caches span several groups, this rule flags only the group holding the very last layer and must be generalized. FIXME(yifan): avoid/generalize this hacky check.
Parameters:
-
(vllm_config¶VllmConfig) –Config supplying the speculative method, if any.
-
(kv_cache_spec¶dict[str, KVCacheSpec]) –The kv cache spec of each attention layer, in layer registration order. Only read by rule 2.
-
(kv_cache_groups¶list[KVCacheGroupSpec]) –Groups to annotate in place.
-
(use_trailing_layer_fallback¶bool, default:False) –Enable rule 2. Callers gate this on
_uses_trailing_mtp_layers.
Source code in vllm/v1/core/kv_cache_utils.py
_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.
Source code in vllm/v1/core/kv_cache_utils.py
_auto_fit_max_model_len(vllm_config, projected_groups_per_worker, available_memory)
¶
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:
-
(vllm_config¶VllmConfig) –The global VllmConfig (will be modified in-place)
-
(projected_groups_per_worker¶list[list[KVCacheGroupSpec]]) –KV cache groups projected to each worker.
-
(available_memory¶list[int]) –Memory available for KV cache in bytes for each worker.
Source code in vllm/v1/core/kv_cache_utils.py
2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 | |
_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.
Source code in vllm/v1/core/kv_cache_utils.py
_estimate_max_model_len_from_groups(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.
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
_get_kv_cache_bytes_per_block(kv_cache_groups)
¶
Return the largest cache group's bytes per block.
Source code in vllm/v1/core/kv_cache_utils.py
_get_kv_cache_groups_glm5_next(vllm_config, kv_cache_spec)
¶
Build GLM-5.3-Flash groups with Mamba/MLA and tail/indexer aliasing.
Source code in vllm/v1/core/kv_cache_utils.py
1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 | |
_get_kv_cache_groups_uniform_page_size(kv_cache_spec)
¶
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. It is already handled by
_get_kv_cache_config_uniform_type.
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:
-
(kv_cache_spec¶dict[str, KVCacheSpec]) –The KVCacheSpec of each attention layer in the model
Returns: The generated KVCacheGroupSpecs
Source code in vllm/v1/core/kv_cache_utils.py
1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 | |
_get_kv_cache_groups_uniform_spec(kv_cache_specs)
¶
Generates the KV cache configuration for a model with the same KV cache spec for all layers.
Parameters:
-
(kv_cache_specs¶dict[str, KVCacheSpec]) –The kv cache spec of each attention layer in the model
Returns:
-
list[KVCacheGroupSpec]–The generated KVCacheGroupSpecs
Source code in vllm/v1/core/kv_cache_utils.py
_get_kv_cache_groups_uniform_type(spec)
¶
Generates the KV cache configuration for a model with one type of KV cache but different hidden sizes. All layers are merged into one group.
Parameters:
-
(spec¶UniformTypeKVCacheSpecs) –The UniformTypeKVCacheSpecs of the model
Returns:
-
list[KVCacheGroupSpec]–The generated KVCacheGroupSpecs
Source code in vllm/v1/core/kv_cache_utils.py
_get_packed_kv_cache_groups(vllm_config, kv_cache_spec)
¶
Group mixed-page-size layers for contiguous block-outermost packing.
Greedily buckets layers into uniform-type specs. 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.
Source code in vllm/v1/core/kv_cache_utils.py
2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 | |
_glm5_next_tensor_layout(kv_cache_groups)
¶
Recognize the GLM-5.3-Flash grouping after optional PP projection.
Source code in vllm/v1/core/kv_cache_utils.py
1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 | |
_groups_partition_layers_exactly(kv_cache_spec, kv_cache_groups)
¶
Whether the groups cover every layer of kv_cache_spec exactly once.
The trailing-layer draft fallback is only meaningful when the last registered layer is guaranteed to appear in exactly one group.
Source code in vllm/v1/core/kv_cache_utils.py
_max_memory_usage_bytes_from_groups(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.
Source code in vllm/v1/core/kv_cache_utils.py
_pool_bytes_per_block(kv_cache_groups)
¶
Bytes consumed by one block in the worker's shared KV cache pool, mirroring
the divisor used by get_kv_cache_config_from_groups to convert
available_memory into num_blocks. Used to compute the effective KV cache
capacity once num_gpu_blocks_override is applied.
Source code in vllm/v1/core/kv_cache_utils.py
_pp_balanced_mamba_group_count(vllm_config, mamba_layer_names, mla_layer_names)
¶
Return a Mamba group count whose PP projections fit the MLA slots.
Source code in vllm/v1/core/kv_cache_utils.py
_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, adjusting UniformTypeKVCacheSpecs accordingly.
Parameters:
-
(global_kv_cache_groups¶list[KVCacheGroupSpec]) –The global KV cache groups for the whole model.
-
(worker_spec¶dict[str, KVCacheSpec]) –The KV cache spec of each layer on this worker.
Returns:
-
list[KVCacheGroupSpec]–The projected KV cache groups containing only this worker's layers.
Source code in vllm/v1/core/kv_cache_utils.py
_promote_local_kv_cache_specs(kv_cache_spec)
¶
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.
Source code in vllm/v1/core/kv_cache_utils.py
1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 | |
_try_get_full_allocation_fallback_groups(kv_cache_spec)
¶
Try a supported full-allocation fallback for local-attention layers.
Source code in vllm/v1/core/kv_cache_utils.py
_uses_trailing_mtp_layers(vllm_config)
¶
Whether the drafter's KV layers can be located positionally.
MTP drafters register their KV layers after the target layers, without a
distinguishing spec marker. DeepseekV4/V4.1 do this with dspark too.
The annotator separately checks that the groups partition the layers exactly.
Source code in vllm/v1/core/kv_cache_utils.py
_warn_if_unannotated_eagle_mamba(vllm_config, kv_cache_groups)
¶
Warn when no KV cache group could be identified as the draft model's.
Parameters:
-
(vllm_config¶VllmConfig) –Config supplying the speculative method, if any.
-
(kv_cache_groups¶list[KVCacheGroupSpec]) –Groups as they will be handed to consumers.
Source code in vllm/v1/core/kv_cache_utils.py
check_enough_kv_cache_memory(vllm_config, kv_cache_spec, available_memory)
¶
Checks whether available_memory is enough for the KV cache to hold at
least one request with the model's max_model_len.
Parameters:
-
(vllm_config¶VllmConfig) –The global VllmConfig
-
(kv_cache_spec¶dict[str, KVCacheSpec]) –The kv cache spec of each attention layer in the model
-
(available_memory¶int) –Memory available for KV cache in bytes.
Raises:
-
ValueError–If there is not enough memory available for the KV cache.
Source code in vllm/v1/core/kv_cache_utils.py
create_kv_cache_group_specs(kv_cache_spec, grouped_layer_names)
¶
Create KVCacheGroupSpec object for each kv cache group layer. The layers in the same group should share the same KVCacheSpec.
Parameters:
-
(kv_cache_spec¶dict[str, KVCacheSpec]) –A mapping from each layer name to its corresponding KVCacheSpec.
-
(grouped_layer_names¶list[list[str]]) –A list of kv cache groups, where each element is a list of layer names that belong to the same group and should share the same KVCacheSpec.
Returns:
-
list[KVCacheGroupSpec]–A list of KVCacheGroupSpec objects, one for each group.
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
estimate_max_model_len(vllm_config, kv_cache_spec, available_memory)
¶
Estimates the maximum model length that can fit in the available memory using binary search.
This function temporarily modifies max_model_len during estimation but restores the original value before returning, ensuring no side effects.
Parameters:
-
(vllm_config¶VllmConfig) –The global VllmConfig
-
(kv_cache_spec¶dict[str, KVCacheSpec]) –The kv cache spec of each attention layer in the model
-
(available_memory¶int) –Memory available for KV cache in bytes.
Returns:
-
int–The estimated maximum model length that can fit in the available memory.
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_kv_cache_config_from_groups(vllm_config, kv_cache_groups, available_memory)
¶
Generate the KV cache configuration from the KV cache groups and spec of each layer.
Parameters:
-
(vllm_config¶VllmConfig) –The global VllmConfig
-
(kv_cache_groups¶list[KVCacheGroupSpec]) –The KV cache groups
-
(available_memory¶int) –Memory available for KV cache in bytes
Returns: The generated KVCacheConfig
Source code in vllm/v1/core/kv_cache_utils.py
1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 | |
get_kv_cache_configs(vllm_config, kv_cache_specs, available_memory)
¶
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.
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
-
(kv_cache_specs¶list[dict[str, KVCacheSpec]]) –List of dict[layer_name, KVCacheSpec] for each worker.
-
(available_memory¶list[int]) –Memory available for KV cache in bytes for each worker.
Returns:
-
list[KVCacheConfig]–The generated KVCacheConfigs for each worker.
Source code in vllm/v1/core/kv_cache_utils.py
2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 | |
get_kv_cache_groups(vllm_config, kv_cache_spec)
¶
Split the layers in the model into groups with the same KV cache spec.
Parameters:
-
(vllm_config¶VllmConfig) –The global VllmConfig
-
(kv_cache_spec¶dict[str, KVCacheSpec]) –The kv cache spec of each attention layer in the model
Returns:
-
list[KVCacheGroupSpec]–The generated KVCacheGroups
Source code in vllm/v1/core/kv_cache_utils.py
2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 | |
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
get_uniform_page_size(kv_cache_specs)
¶
Get the page size of the KV cache.
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
is_kv_cache_spec_uniform(kv_cache_spec)
¶
Whether all layers in the given KVCacheSpec have the same KV cache spec. Note that we regard FullAttentionSpec with and without sliding window as the same type.
Parameters:
-
(kv_cache_spec¶dict[str, KVCacheSpec]) –The kv cache spec of each attention layer in the model
Returns:
-
bool–True if all layers have the same type, False otherwise.
Source code in vllm/v1/core/kv_cache_utils.py
kv_cache_groups_tp_replicas(groups, tp_size, dcp_size=1)
¶
Consecutive TP ranks holding identical KV for every layer.
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
max_memory_usage_bytes(vllm_config, kv_cache_specs)
¶
Get the maximum memory usage in bytes for the given KV cache specs.
Source code in vllm/v1/core/kv_cache_utils.py
may_override_num_blocks(vllm_config, num_blocks)
¶
Override the number of kv cache blocks if num_gpu_blocks_override is set.
The override is logged once, at the call site in get_kv_cache_configs.
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
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 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 | |
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
unify_hybrid_kv_cache_specs(kv_cache_spec)
¶
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 SlidingWindowSpec to FullAttentionSpec if both types are present.
Parameters:
-
(kv_cache_spec¶dict[str, KVCacheSpec]) –The kv cache spec of each attention layer in the model
Source code in vllm/v1/core/kv_cache_utils.py
unify_kv_cache_spec_page_size(kv_cache_spec)
¶
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:
-
(kv_cache_spec¶dict[str, KVCacheSpec]) –The KVCacheSpec of each attention layer in the model
Returns:
-
dict[str, KVCacheSpec]–The updated KVCacheSpec with the same page_size_bytes.
Source code in vllm/v1/core/kv_cache_utils.py
1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 | |
update_kv_cache_capacity(vllm_config, kv_cache_config)
¶
Store and log the resolved KV cache capacity.
Source code in vllm/v1/core/kv_cache_utils.py
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.