vllm.v1.core.kv_cache_utils
KV-Cache Utilities.
BlockHash ¶
Bases: NamedTuple
Hash value of a block (int), the token IDs in the block, and extra keys. We keep a tuple of token IDs and extra keys to reduce the likelihood of hash collisions when the hash value is the same. By using SHA256 however, hash collisions are practically impossible.
Source code in vllm/v1/core/kv_cache_utils.py
BlockHashWithGroupId ¶
Bases: NamedTuple
Source code in vllm/v1/core/kv_cache_utils.py
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:
Name | Type | Description | Default |
---|---|---|---|
blocks | list[KVCacheBlock] | A list of KVCacheBlock objects. | required |
Source code in vllm/v1/core/kv_cache_utils.py
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 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 |
|
__init__ ¶
__init__(blocks: list[KVCacheBlock]) -> None
Source code in vllm/v1/core/kv_cache_utils.py
append ¶
append(block: KVCacheBlock) -> None
Put a block back into the free list and increase num_free_blocks by 1.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
block | KVCacheBlock | The block to append. | required |
Source code in vllm/v1/core/kv_cache_utils.py
append_n ¶
append_n(blocks: list[KVCacheBlock]) -> None
Put a list of blocks back into the free list
Parameters:
Name | Type | Description | Default |
---|---|---|---|
blocks | list[KVCacheBlock] | The blocks to append. | required |
Source code in vllm/v1/core/kv_cache_utils.py
get_all_free_blocks ¶
get_all_free_blocks() -> list[KVCacheBlock]
Get all free blocks in the free list. Mainly used for testing.
Returns:
Type | Description |
---|---|
list[KVCacheBlock] | A list of free blocks. |
Source code in vllm/v1/core/kv_cache_utils.py
popleft ¶
popleft() -> KVCacheBlock
Pop the first free block and reduce num_free_blocks by 1.
Returns:
Type | Description |
---|---|
KVCacheBlock | The first free block. |
Source code in vllm/v1/core/kv_cache_utils.py
popleft_n ¶
popleft_n(n: int) -> list[KVCacheBlock]
Pop the first n free blocks and reduce num_free_blocks by n.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
n | int | The number of blocks to pop. | required |
Returns:
Type | Description |
---|---|
list[KVCacheBlock] | A list of n free blocks. |
Source code in vllm/v1/core/kv_cache_utils.py
remove ¶
remove(block: KVCacheBlock) -> None
Remove a block in the free list and reduce num_free_blocks by 1.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
block | KVCacheBlock | The block to remove. | required |
Source code in vllm/v1/core/kv_cache_utils.py
KVCacheBlock dataclass
¶
KV-cache block metadata.
Source code in vllm/v1/core/kv_cache_utils.py
__init__ ¶
__init__(
block_id: int,
ref_cnt: int = 0,
_block_hash: Optional[BlockHashWithGroupId] = None,
prev_free_block: Optional[KVCacheBlock] = None,
next_free_block: Optional[KVCacheBlock] = None,
is_null: bool = False,
) -> None
__repr__ ¶
__repr__() -> str
Source code in vllm/v1/core/kv_cache_utils.py
PrefixCachingMetrics ¶
Metrics for prefix caching with a hit rate of the max recent N requests.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
max_recent_requests | int | The number of the max recent requests to aggregate. Defaults to 1000. | 1000 |
Source code in vllm/v1/core/kv_cache_utils.py
__init__ ¶
__init__(max_recent_requests: int = 1000)
Source code in vllm/v1/core/kv_cache_utils.py
observe ¶
observe(stats: PrefixCacheStats)
Observe the prefix caching for a set of requests.
This function is called with information gathered when new requests are being scheduled and are looking for computed blocks.
When there are more than interval
requests, the oldest set of requests are removed from the metrics.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
stats | PrefixCacheStats | The prefix cache stats. | required |
Source code in vllm/v1/core/kv_cache_utils.py
_gen_lora_extra_hash_keys ¶
Generate extra keys related to LoRA for block hash computation.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request | Request | The request object. | required |
Returns:
Type | Description |
---|---|
list[int] | Return LoRA id of the request if it is a LoRA request. Return empty |
list[int] | list otherwise. |
Source code in vllm/v1/core/kv_cache_utils.py
_gen_mm_extra_hash_keys ¶
_gen_mm_extra_hash_keys(
request: Request,
start_token_idx: int,
end_token_idx: int,
start_mm_idx: int,
) -> tuple[list[Any], int]
Generate extra keys related to MultiModal request for block hash computation. For multi-modal inputs, the extra keys are (mm_hash, start_offset) that indicate a mm input contained in the block and its starting offset in the block tokens.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request | Request | The request object. | required |
start_token_idx | int | The start token index of the block. | required |
end_token_idx | int | The end token index of the block. | required |
start_mm_idx | int | The start multi-modal index of the block. | required |
Returns:
Type | Description |
---|---|
tuple[list[Any], int] | A tuple of extra keys and the next multi-modal index. |
Source code in vllm/v1/core/kv_cache_utils.py
_get_kv_cache_config_attention_free ¶
_get_kv_cache_config_attention_free() -> KVCacheConfig
_get_kv_cache_config_uniform_page_size ¶
_get_kv_cache_config_uniform_page_size(
vllm_config: VllmConfig,
kv_cache_spec: dict[str, KVCacheSpec],
available_memory: int,
) -> KVCacheConfig
Generates the KV cache configuration 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:
Name | Type | Description | Default |
---|---|---|---|
vllm_config | VllmConfig | The global VllmConfig | required |
kv_cache_spec | dict[str, KVCacheSpec] | The KVCacheSpec of each attention layer in the model | required |
available_memory | int | Memory available for KV cache in bytes. | required |
Returns: The generated KVCacheConfig
Source code in vllm/v1/core/kv_cache_utils.py
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 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 |
|
_get_kv_cache_config_uniform_type ¶
_get_kv_cache_config_uniform_type(
vllm_config: VllmConfig,
kv_cache_spec: dict[str, KVCacheSpec],
available_memory: int,
) -> KVCacheConfig
Generates the KV cache configuration for a model with one type of KV cache. Divide the available memory equally among all layers.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
vllm_config | VllmConfig | The global VllmConfig | required |
kv_cache_spec | dict[str, KVCacheSpec] | The kv cache spec of each attention layer in the model | required |
available_memory | int | Memory available for KV cache in bytes. | required |
Returns:
Type | Description |
---|---|
KVCacheConfig | The generated KVCacheConfig |
Source code in vllm/v1/core/kv_cache_utils.py
check_enough_kv_cache_memory ¶
check_enough_kv_cache_memory(
vllm_config: VllmConfig,
kv_cache_spec: dict[str, KVCacheSpec],
available_memory: int,
)
Checks whether available_memory
is enough for the KV cache to hold at least one request with the model's max_model_len.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
vllm_config | VllmConfig | The global VllmConfig | required |
kv_cache_spec | dict[str, KVCacheSpec] | The kv cache spec of each attention layer in the model | required |
available_memory | int | Memory available for KV cache in bytes. | required |
Raises:
Type | Description |
---|---|
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 ¶
create_kv_cache_group_specs(
kv_cache_spec: dict[str, KVCacheSpec],
grouped_layer_names: list[list[str]],
) -> list[KVCacheGroupSpec]
Create KVCacheGroupSpec object for each kv cache group layer. The layers in the same group should share the same KVCacheSpec.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
kv_cache_spec | dict[str, KVCacheSpec] | A mapping from each layer name to its corresponding KVCacheSpec. | required |
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. | required |
Returns: A list of KVCacheGroupSpec objects, one for each group.
Source code in vllm/v1/core/kv_cache_utils.py
estimate_max_model_len ¶
estimate_max_model_len(
vllm_config: VllmConfig,
kv_cache_spec: dict[str, KVCacheSpec],
available_memory: int,
) -> int
Estimates the maximum model length that can fit in the available memory using binary search.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
vllm_config | VllmConfig | The global VllmConfig | required |
kv_cache_spec | dict[str, KVCacheSpec] | The kv cache spec of each attention layer in the model | required |
available_memory | int | Memory available for KV cache in bytes. | required |
Returns:
Type | Description |
---|---|
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 ¶
generate_block_hash_extra_keys(
request: Request,
start_token_idx: int,
end_token_idx: int,
start_mm_idx: int,
) -> tuple[Optional[tuple[Any, ...]], int]
Generate extra keys for the block hash. The extra keys can come from the multi-modal inputs and request specific metadata (e.g., LoRA ID).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request | Request | The request object. | required |
start_token_idx | int | The start token index of the block. | required |
end_token_idx | int | The end token index of the block. | required |
start_mm_idx | int | The start multi-modal index of the block. | required |
Returns:
Type | Description |
---|---|
tuple[Optional[tuple[Any, ...]], int] | A tuple of extra keys and the next multi-modal index. |
Source code in vllm/v1/core/kv_cache_utils.py
get_kv_cache_config ¶
get_kv_cache_config(
vllm_config: VllmConfig,
kv_cache_spec: dict[str, KVCacheSpec],
available_memory: int,
) -> KVCacheConfig
Generates the KV cache configuration for a model.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
vllm_config | VllmConfig | The global VllmConfig | required |
kv_cache_spec | dict[str, KVCacheSpec] | The kv cache spec of each attention layer in the model | required |
available_memory | int | Memory available for KV cache in bytes. | required |
Returns:
Type | Description |
---|---|
KVCacheConfig | The generated KVCacheConfigs |
Source code in vllm/v1/core/kv_cache_utils.py
get_max_concurrency_for_kv_cache_config ¶
get_max_concurrency_for_kv_cache_config(
vllm_config: VllmConfig, kv_cache_config: KVCacheConfig
) -> float
Get the maximum concurrency for the given KV cache configuration.
Source code in vllm/v1/core/kv_cache_utils.py
get_num_blocks ¶
get_num_blocks(
vllm_config: VllmConfig,
num_layers: int,
available_memory: int,
page_size: int,
) -> int
Get the number of kv cache blocks.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
vllm_config | VllmConfig | The global VllmConfig | required |
num_layers | int | The number of layers | required |
available_memory | int | Memory available for KV cache in bytes. | required |
page_size | int | The page size of the KV cache. | required |
Source code in vllm/v1/core/kv_cache_utils.py
get_request_block_hasher ¶
get_request_block_hasher(
block_size: int, caching_hash_fn: Callable[[Any], int]
) -> Callable[[Request], list[BlockHash]]
Returns a function which computes the list of un-computed block hashes of a request.
Each request holds a list of its block hashes (request.block_hashes). When a request is created, it calls the below function to compute the hashes of all full blocks of the request's initial tokens. The hashes are then stored in request.block_hashes. Later, whenever new tokens are appended to the request, it calls the below function again to compute any new full blocks of tokens. The returned new hashes are appended to request.block_hashes.
Source code in vllm/v1/core/kv_cache_utils.py
get_uniform_page_size ¶
get_uniform_page_size(
kv_cache_spec: dict[str, KVCacheSpec],
) -> int
Get the page size of the KV cache.
Source code in vllm/v1/core/kv_cache_utils.py
hash_block_tokens ¶
hash_block_tokens(
hash_function: Callable,
parent_block_hash: Optional[int],
curr_block_token_ids: Sequence[int],
extra_keys: Optional[tuple[Any, ...]] = None,
) -> BlockHash
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:
Name | Type | Description | Default |
---|---|---|---|
parent_block_hash | Optional[int] | The hash of the parent block. None if this is the first block. | required |
curr_block_token_ids | Sequence[int] | A list of token ids in the current block. The current block is assumed to be full. | required |
extra_keys | Optional[tuple[Any, ...]] | Extra keys for the block. | None |
Returns:
Type | Description |
---|---|
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
init_none_hash ¶
init_none_hash(hash_fn: Callable)
Source code in vllm/v1/core/kv_cache_utils.py
is_kv_cache_page_size_uniform ¶
is_kv_cache_page_size_uniform(
kv_cache_spec: dict[str, KVCacheSpec],
) -> bool
Whether all layers in the given KVCacheSpec have the same page size. Args: kv_cache_spec: The KVCacheSpec of each attention layer in the model
Returns:
Type | Description |
---|---|
bool | True if all layers have the same page size, False otherwise. |
Source code in vllm/v1/core/kv_cache_utils.py
is_kv_cache_type_attention_free ¶
is_kv_cache_type_attention_free(
kv_cache_spec: dict[str, KVCacheSpec],
) -> bool
is_kv_cache_type_uniform ¶
is_kv_cache_type_uniform(
kv_cache_spec: dict[str, KVCacheSpec],
) -> bool
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:
Name | Type | Description | Default |
---|---|---|---|
kv_cache_spec | dict[str, KVCacheSpec] | The kv cache spec of each attention layer in the model | required |
Returns:
Type | Description |
---|---|
bool | True if all layers have the same type, False otherwise. |
Source code in vllm/v1/core/kv_cache_utils.py
max_memory_usage_bytes ¶
max_memory_usage_bytes(
vllm_config: VllmConfig,
kv_cache_specs: Iterable[KVCacheSpec],
) -> int
Get the maximum memory usage in bytes for the given KV cache specs.
Source code in vllm/v1/core/kv_cache_utils.py
need_extra_keys ¶
Check whether the blocks allocated to this request need extra hash keys.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request | Request | The request. | required |
Returns:
Name | Type | Description |
---|---|---|
bool | bool | Whether blocks allocated to this request need extra hash keys. |
Source code in vllm/v1/core/kv_cache_utils.py
unify_hybrid_kv_cache_specs ¶
unify_hybrid_kv_cache_specs(
kv_cache_spec: dict[str, KVCacheSpec],
)
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:
Name | Type | Description | Default |
---|---|---|---|
kv_cache_spec | dict[str, KVCacheSpec] | The kv cache spec of each attention layer in the model | required |
Source code in vllm/v1/core/kv_cache_utils.py
unify_kv_cache_configs ¶
unify_kv_cache_configs(
kv_cache_configs: list[KVCacheConfig],
)
Make the KV cache configurations for each worker consistent, so that all workers can be controlled by the same KVCacheManager. This function verifies that the layer group of each worker are the same, and changes the num_blocks of each worker to the smallest among all workers.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
kv_cache_configs | list[KVCacheConfig] | The KV cache configurations for each worker. Will be in-place modified to make them consistent. | required |