[3/N] HiSparse: host-resident sparse-MLA decode hot-buffering (#53781)

Signed-off-by: Matthew Bonanni <mbonanni@redhat.com>
Signed-off-by: Lucas Wilkinson <lwilkins@redhat.com>
Signed-off-by: Lucas Wilkinson <lwilkinson@neuralmagic.com>
Signed-off-by: Matthew Bonanni <matthew@neuralmagic.com>
Signed-off-by: Nicolò Lucchesi <nicolo.lucchesi@mistral.ai>
Co-authored-by: OpenAI Codex <codex@openai.com>
Co-authored-by: Lucas Wilkinson <lwilkins@redhat.com>
Co-authored-by: Lucas Wilkinson <lwilkinson@neuralmagic.com>
Co-authored-by: Nicolò Lucchesi <nicolo.lucchesi@mistral.ai>
Co-authored-by: OpenAI Codex <noreply@openai.com>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Co-authored-by: Lucas Wilkinson <LucasWilkinson@users.noreply.github.com>
This commit is contained in:
Matthew Bonanni
2026-09-12 00:36:47 -04:00
committed by GitHub
co-authored by OpenAI Codex Lucas Wilkinson Lucas Wilkinson Nicolò Lucchesi OpenAI Codex Claude Opus 5 Lucas Wilkinson
parent 120ec4ebd2
commit d43bb2f37f
124 changed files with 14262 additions and 906 deletions
+51 -5
View File
@@ -1,6 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from collections.abc import Iterable, Sequence
from collections.abc import Callable, Iterable, Sequence
from typing import Any
from vllm.distributed.kv_events import (
@@ -157,6 +157,7 @@ class BlockPool:
actual block size can be a multiple of hash_block_size.
enable_kv_cache_events: Whether to enable kv cache events.
metrics_collector: Optional metrics collector for tracking block residency.
medium: Storage medium reported in KV cache events.
"""
def __init__(
@@ -166,14 +167,16 @@ class BlockPool:
hash_block_size: int,
enable_kv_cache_events: bool = False,
metrics_collector: KVCacheMetricsCollector | None = None,
medium: str = MEDIUM_GPU,
):
assert isinstance(num_gpu_blocks, int) and num_gpu_blocks > 0
self.num_gpu_blocks = num_gpu_blocks
self.medium = medium
self.enable_caching = enable_caching
self.hash_block_size = hash_block_size
# All kv-cache blocks.
self.blocks: list[KVCacheBlock] = [
KVCacheBlock(idx) for idx in range(num_gpu_blocks)
KVCacheBlock(idx, pool=self) for idx in range(num_gpu_blocks)
]
# Free block queue that constructs and manipulates a doubly linked
# list of free blocks (including eviction candidates when caching is
@@ -194,6 +197,9 @@ class BlockPool:
self.kv_event_queue: list[KVCacheEvent] = []
self.metrics_collector = metrics_collector
# Callbacks for blocks released with ``unpin_blocks`` whose contents
# are still being read until the pool reuses them.
self._reuse_watchers: dict[int, Callable[[KVCacheBlock], None]] = {}
def get_cached_block(
self, block_hash: BlockHash, kv_cache_group_ids: list[int]
@@ -364,7 +370,7 @@ class BlockPool:
token_ids=request.all_token_ids[start_token_idx:end_token_idx],
block_size=block_size,
lora_id=request.lora_request.adapter_id if request.lora_request else None,
medium=MEDIUM_GPU,
medium=self.medium,
lora_name=request.lora_request.name if request.lora_request else None,
extra_keys=extra_keys_list if extra_keys_list else None,
group_idx=kv_cache_group_id,
@@ -543,7 +549,7 @@ class BlockPool:
lora_id=request.lora_request.adapter_id
if request.lora_request
else None,
medium=MEDIUM_GPU,
medium=self.medium,
lora_name=request.lora_request.name
if request.lora_request
else None,
@@ -610,7 +616,7 @@ class BlockPool:
self.kv_event_queue.append(
BlockRemoved(
block_hashes=[maybe_convert_block_hash(get_block_hash(block_hash))],
medium=MEDIUM_GPU,
medium=self.medium,
group_idx=get_group_id(block_hash),
)
)
@@ -671,6 +677,9 @@ class BlockPool:
ret: list[KVCacheBlock] = self.free_block_queue.popleft_n(num_blocks)
if self._reuse_watchers:
self._notify_reuse(ret)
# In order to only iterate the list once, we duplicated code a bit
if self.enable_caching:
for block in ret:
@@ -687,6 +696,33 @@ class BlockPool:
self.metrics_collector.on_block_allocated(block)
return ret
def _notify_reuse(self, blocks: Iterable[KVCacheBlock]) -> None:
for block in blocks:
watcher = self._reuse_watchers.pop(block.block_id, None)
if watcher is not None:
watcher(block)
def unpin_blocks(
self,
blocks: Iterable[KVCacheBlock],
on_reuse: Callable[[KVCacheBlock], None],
) -> None:
"""Release references to blocks that stay readable until reused.
The blocks become last-resort eviction candidates regardless of prefix
caching: they join the tail of the free queue and count as free.
``on_reuse`` fires when ``get_new_blocks`` hands a block out (or the
cache is reset), so the caller can stop reading it.
"""
released: list[KVCacheBlock] = []
for block in blocks:
assert block.ref_cnt > 0 and not block.is_null
block.ref_cnt -= 1
self._reuse_watchers[block.block_id] = on_reuse
if block.ref_cnt == 0:
released.append(block)
self.free_block_queue.append_n(released)
def _maybe_evict_cached_block(self, block: KVCacheBlock) -> bool:
"""
If a block is cached in `cached_block_hash_to_block`, we reset its hash
@@ -742,7 +778,11 @@ class BlockPool:
# Identify blocks with hash (LRU cache) and without it (never match APC)
blocks_to_evict_last = []
blocks_to_evict_first = []
other_pools: dict[BlockPool, list[KVCacheBlock]] = {}
for block in ordered_blocks:
if block.pool is not None and block.pool is not self:
other_pools.setdefault(block.pool, []).append(block)
continue
block.ref_cnt -= 1
if block.ref_cnt == 0 and not block.is_null:
if block.block_hash is None or not self.enable_caching:
@@ -756,6 +796,8 @@ class BlockPool:
self.free_block_queue.prepend_n(blocks_to_evict_first)
# Blocks to reuse last are appended to the end of the free queue.
self.free_block_queue.append_n(blocks_to_evict_last)
for pool, blocks in other_pools.items():
pool.free_blocks(blocks)
def evict_blocks(self, block_ids: set[int]) -> None:
"""evict blocks from the prefix cache by their block IDs.
@@ -797,6 +839,10 @@ class BlockPool:
# Remove all hashes so that no new blocks will hit.
self.cached_block_hash_to_block = BlockHashToBlockMap()
self.cached_block_hashes_by_block.clear()
if self._reuse_watchers:
self._notify_reuse(
[self.blocks[block_id] for block_id in list(self._reuse_watchers)]
)
# Remove all hashes from all blocks.
for block in self.blocks:
+39 -8
View File
@@ -139,6 +139,7 @@ class KVCacheCoordinator(ABC):
max_in_flight_tokens=max_in_flight_tokens,
max_model_len=max_model_len,
block_pool=self.block_pool,
role=kv_cache_group.role,
enable_caching=enable_caching,
kv_cache_group_id=i,
dcp_world_size=dcp_world_size_for_kv_cache_spec(
@@ -179,7 +180,7 @@ class KVCacheCoordinator(ABC):
apply_admission_cap: bool = False,
) -> int:
"""
Get the number of blocks needed to be allocated for the request.
Get the number of device blocks needed to be allocated for the request.
Args:
request_id: The request ID.
@@ -343,6 +344,8 @@ class KVCacheCoordinator(ABC):
"""
boundaries = self.get_replay_boundaries(request)
for manager in self.single_type_managers:
if not manager.enable_caching:
continue
# Only cache tokens with finalized KV. The last num_reprefillable_tokens
# tokens can be re-prefilled during multi-module MTP.
num_tokens_to_cache = max(
@@ -355,6 +358,27 @@ class KVCacheCoordinator(ABC):
replay_boundaries=boundaries,
)
def emit_cached_block_events(
self, request: Request, computed_blocks: tuple[list[KVCacheBlock], ...]
) -> None:
for group_idx, group_blocks in enumerate(computed_blocks):
if group_blocks:
manager = self.single_type_managers[group_idx]
group = self.kv_cache_config.kv_cache_groups[group_idx]
manager.block_pool.emit_cached_block_events(
request,
len(group_blocks),
group.kv_cache_spec.block_size,
group_idx,
)
def reset_prefix_cache(self) -> bool:
"""Reset each manager's pool once."""
pools = dict.fromkeys(
manager.block_pool for manager in self.single_type_managers
)
return all([pool.reset_prefix_cache() for pool in pools])
def free(self, request_id: str) -> None:
"""
Free the blocks for the request.
@@ -728,10 +752,12 @@ class HybridKVCacheCoordinator(KVCacheCoordinator):
# Try to find an existing group with the same spec
for idx, group in enumerate(self.attention_groups):
if group.spec == spec:
assert manager_cls is group.manager_cls, (
"Expected same manager class for identical KV cache specs."
)
if (
group.spec == spec
and group.manager_cls is manager_cls
and self.single_type_managers[group.group_ids[0]].block_pool
is self.single_type_managers[i].block_pool
):
group.group_ids.append(i)
if use_eagle and not group.use_eagle:
self.attention_groups[idx] = group._replace(use_eagle=True)
@@ -782,6 +808,8 @@ class HybridKVCacheCoordinator(KVCacheCoordinator):
cached_num_computed_tokens = self._align_cacheable(num_computed_tokens)
boundaries = self.get_replay_boundaries(request)
for manager in self.single_type_managers:
if not manager.enable_caching:
continue
num_tokens_to_cache = cached_num_computed_tokens
# EAGLE groups match one block past each aligned boundary and drop
# it, so make that lookahead block eligible to be cached.
@@ -895,7 +923,7 @@ class HybridKVCacheCoordinator(KVCacheCoordinator):
block_hashes=block_hashes,
max_length=_max_length,
kv_cache_group_ids=group_ids,
block_pool=self.block_pool,
block_pool=self.single_type_managers[first_group_id].block_pool,
kv_cache_spec=spec,
drop_eagle_block=drop_eagle_block,
alignment_tokens=self._cache_hit_alignment_tokens,
@@ -929,7 +957,10 @@ class HybridKVCacheCoordinator(KVCacheCoordinator):
for group in self.attention_groups:
if not isinstance(group.spec, FullAttentionSpec):
continue
group_block_size = self.single_type_managers[group.group_ids[0]].block_size
manager = self.single_type_managers[group.group_ids[0]]
if manager.retains_longer_hit:
continue
group_block_size = manager.block_size
num_blocks = cdiv(hit_length, group_block_size)
for group_id in group.group_ids:
if (blks := hit_blocks_by_group[group_id]) is not None:
@@ -966,7 +997,7 @@ class HybridKVCacheCoordinator(KVCacheCoordinator):
block_hashes=block_hashes,
max_length=max_cache_hit_length,
kv_cache_group_ids=group_ids,
block_pool=self.block_pool,
block_pool=manager.block_pool,
kv_cache_spec=spec,
drop_eagle_block=use_eagle,
alignment_tokens=self._cache_hit_alignment_tokens,
+20 -13
View File
@@ -183,6 +183,11 @@ class KVCacheManager:
manager.fine_grained_prefix_cache = True
self.num_kv_cache_groups = len(kv_cache_config.kv_cache_groups)
self.block_pool = self.coordinator.block_pool
self.retained_hit_group_ids = tuple(
manager.kv_cache_group_id
for manager in self.coordinator.single_type_managers
if manager.retains_longer_hit
)
self.kv_cache_config = kv_cache_config
# Watermark: minimum number of KV cache blocks to keep free when
@@ -287,17 +292,7 @@ class KVCacheManager:
and self.enable_kv_cache_events
and getattr(request, "kv_cache_report_mode", "incremental") == "full"
):
for group_idx, group_blocks in enumerate(computed_blocks):
num_blocks = len(group_blocks)
if num_blocks > 0:
group = self.kv_cache_config.kv_cache_groups[group_idx]
block_size = group.kv_cache_spec.block_size
self.block_pool.emit_cached_block_events(
request,
num_blocks,
block_size,
group_idx,
)
self.coordinator.emit_cached_block_events(request, computed_blocks)
# The junction to pin is where the lagging sparse-retention group stops
# (``num_new_computed_tokens``) plus the uncached shared prefix -- i.e.
@@ -463,6 +458,16 @@ class KVCacheManager:
if new_computed_blocks is not None:
new_computed_block_list = new_computed_blocks.blocks
if self.retained_hit_group_ids:
# Only retain the prefix covered by the local and external hits.
reused = num_new_computed_tokens + num_external_computed_tokens
groups = list(new_computed_block_list)
for group_id in self.retained_hit_group_ids:
manager = self.coordinator.single_type_managers[group_id]
groups[group_id] = groups[group_id][
: cdiv(reused, manager.block_size)
]
new_computed_block_list = tuple(groups)
else:
new_computed_block_list = self.empty_kv_cache_blocks.blocks
@@ -564,7 +569,7 @@ class KVCacheManager:
# P/D: delay caching blocks if we have to recv from
# remote. Update state for locally cached blocks.
if not self.enable_caching or delay_cache_blocks:
if delay_cache_blocks:
return self.create_kv_cache_blocks(new_blocks)
# NOTE(woosuk): We want to commit (cache) up to num_local_computed_tokens
@@ -639,7 +644,7 @@ class KVCacheManager:
bool: True if the prefix cache is successfully reset,
False otherwise.
"""
if not self.block_pool.reset_prefix_cache():
if not self.coordinator.reset_prefix_cache():
return False
if self.log_stats:
assert self.prefix_cache_stats is not None
@@ -741,6 +746,8 @@ class KVCacheManager:
self.kv_cache_config.kv_cache_groups,
self.get_blocks(request.request_id).blocks,
):
if not group.kv_cache_spec.prefix_cacheable:
continue
if isinstance(
group.kv_cache_spec,
(CrossAttentionSpec, EncoderOnlyAttentionSpec),
+74 -10
View File
@@ -8,23 +8,30 @@ import math
import os
from collections import defaultdict
from collections.abc import Callable, Iterable, Iterator, Sequence
from dataclasses import dataclass, replace
from dataclasses import dataclass, field, replace
from functools import partial
from typing import Any, NamedTuple, NewType, TypeAlias, cast, overload
from typing import TYPE_CHECKING, Any, NamedTuple, NewType, TypeAlias, cast, overload
from vllm import envs
from vllm.config import VllmConfig
from vllm.logger import init_logger
from vllm.utils.hashing import xxhash, xxhash_cbor
from vllm.utils.math_utils import cdiv
from vllm.utils.math_utils import cdiv, round_up
from vllm.utils.mem_utils import format_gib
from vllm.utils.torch_utils import get_dtype_size
from vllm.v1.hisparse.layout import (
get_hisparse_gpu_memory_usage,
get_hisparse_host_pool_bytes,
get_hisparse_kv_cache_config,
get_hisparse_kv_cache_groups,
)
from vllm.v1.kv_cache_interface import (
AttentionSpec,
ChunkedLocalAttentionSpec,
CircularBufferSpec,
FullAttentionSpec,
HiddenStateCacheSpec,
HiSparseHotSpec,
KpoolTailSpec,
KVCacheConfig,
KVCacheGroupSpec,
@@ -44,6 +51,10 @@ from vllm.v1.kv_cache_spec_registry import KVCacheSpecRegistry
from vllm.v1.request import Request
from vllm.v1.utils import tensor_data
if TYPE_CHECKING:
from vllm.v1.core.block_pool import BlockPool
# BlockHash represents the hash of a single KV-cache block used for
# prefix caching. Treating it as a distinct type from `bytes` helps
# catch accidental misuse when passing around raw byte strings.
@@ -169,6 +180,10 @@ class KVCacheBlock:
block_id: int
# Reference count.
ref_cnt: int = 0
# Deferred frees may contain blocks from multiple pools.
pool: "BlockPool | None" = field(
default=None, repr=False, compare=False, kw_only=True
)
# The hash key (block hash + group id) of the block, only available
# when the block is full and cached.
_block_hash: BlockHashWithGroupId | None = None
@@ -1057,21 +1072,32 @@ def get_max_concurrency_for_kv_cache_config(
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
groups draw those block ids from one shared pool, so the per-request
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.
"""
num_blocks_per_request = sum(
cdiv(
num_blocks_per_request = 0
host_blocks_per_request = 0
for group in kv_cache_config.kv_cache_groups:
required = cdiv(
group.kv_cache_spec.max_memory_usage_bytes(vllm_config),
group.kv_cache_spec.page_size_bytes,
)
for group in kv_cache_config.kv_cache_groups
)
max_concurrency = kv_cache_config.num_blocks / num_blocks_per_request
return max_concurrency
if group.host_resident:
host_blocks_per_request += required
else:
num_blocks_per_request += required
limits = [kv_cache_config.num_blocks / num_blocks_per_request]
if host_blocks_per_request:
assert kv_cache_config.hisparse_host_num_blocks is not None
limits.append(
kv_cache_config.hisparse_host_num_blocks / host_blocks_per_request
)
return min(limits)
def may_override_num_blocks(vllm_config: VllmConfig, num_blocks: int) -> int:
@@ -1575,6 +1601,13 @@ def _get_kv_cache_bytes_per_block(
for group in kv_cache_groups
)
assert bytes_per_block > 0
hot_page_sizes = [
group.kv_cache_spec.page_size_bytes
for group in kv_cache_groups
if isinstance(group.kv_cache_spec, HiSparseHotSpec)
]
if hot_page_sizes:
bytes_per_block = round_up(bytes_per_block, math.lcm(*hot_page_sizes))
return bytes_per_block
@@ -1640,6 +1673,12 @@ def get_kv_cache_config_from_groups(
),
)
if vllm_config.attention_config.hisparse_config is not None:
host_budget = get_hisparse_host_pool_bytes(vllm_config)
return get_hisparse_kv_cache_config(
vllm_config, kv_cache_groups, available_memory, host_budget
)
if (glm5_layout := _glm5_next_tensor_layout(kv_cache_groups)) is not None:
(
attn_group,
@@ -2210,6 +2249,9 @@ def get_kv_cache_groups(
# attention free models.
return []
if hisparse_groups := get_hisparse_kv_cache_groups(vllm_config, kv_cache_spec):
return hisparse_groups
if is_kv_cache_spec_uniform(kv_cache_spec):
# KV cache of all layers are the same, which is true for
# most models. Allocate the same amount of memory for
@@ -2287,6 +2329,10 @@ def generate_scheduler_kv_cache_config(
assert all(
[cfg.num_blocks == kv_cache_configs[0].num_blocks for cfg in kv_cache_configs]
)
assert all(
cfg.hisparse_host_num_blocks == kv_cache_configs[0].hisparse_host_num_blocks
for cfg in kv_cache_configs
)
# All workers have the same kv_cache_config except layer names, so use
# an arbitrary one to initialize the scheduler.
cfg = copy.deepcopy(kv_cache_configs[0])
@@ -2347,6 +2393,9 @@ def _max_memory_usage_bytes_from_groups(
if not kv_cache_groups:
return 0
if vllm_config.attention_config.hisparse_config is not None:
return get_hisparse_gpu_memory_usage(vllm_config, kv_cache_groups)
if (glm5_layout := _glm5_next_tensor_layout(kv_cache_groups)) is not None:
(
attn_group,
@@ -2396,9 +2445,21 @@ def _estimate_max_model_len_from_groups(
Returns 0 if even 1 token doesn't fit.
"""
original_max = vllm_config.model_config.max_model_len
hisparse_enabled = (
vllm_config.attention_config.hisparse_config is not None
and bool(kv_cache_groups)
)
def fits(model_len: int) -> bool:
vllm_config.model_config.max_model_len = model_len
if hisparse_enabled:
try:
config = get_kv_cache_config_from_groups(
vllm_config, kv_cache_groups, available_memory
)
except ValueError:
return False
return get_max_concurrency_for_kv_cache_config(vllm_config, config) >= 1
return (
_max_memory_usage_bytes_from_groups(vllm_config, kv_cache_groups)
<= available_memory
@@ -2629,6 +2690,9 @@ def get_kv_cache_configs(
adjusted_memory.append(override * bytes_per_block)
available_memory = adjusted_memory
if vllm_config.attention_config.hisparse_config is not None:
available_memory = [min(available_memory)] * len(available_memory)
# Reserve the null block BlockPool permanently holds back, so auto-fit and
# the capacity check both plan against usable blocks. Allocation below
# still uses the full memory.
+3
View File
@@ -294,6 +294,9 @@ class SchedulerOutput:
# CoW copies to apply after zeroing new blocks and before forward.
kv_cache_block_copies: list[KVCacheBlockCopy] | None = None
# Complete block-table rows that replace incrementally appended block IDs.
block_table_updates: dict[str, tuple[list[int], ...]] | None = None
# Scheduler-local; always None by the time this reaches a worker.
kv_connector_block_state: KVConnectorBlockState | None = None
+33 -7
View File
@@ -316,10 +316,9 @@ class Scheduler(SchedulerInterface):
self.cache_config.enable_mamba_fine_grained_prefix_cache
),
)
# Bind GPU block pool to the KV connector. This must happen after
# kv_cache_manager is constructed so block_pool is available.
# Bind after construction so connectors can access the cache manager.
if self.connector is not None:
self.connector.bind_gpu_block_pool(self.kv_cache_manager.block_pool)
self.connector.bind_kv_cache_manager(self.kv_cache_manager)
self.use_pp = self.parallel_config.pipeline_parallel_size > 1
self.use_v2_model_runner = vllm_config.use_v2_model_runner
@@ -738,6 +737,12 @@ class Scheduler(SchedulerInterface):
# The request can be scheduled.
break
if (
self.connector is not None
and self.connector.has_pending_block_frees()
):
break
# The request cannot be scheduled.
# Preempt the lowest-priority request.
if self.policy == SchedulingPolicy.PRIORITY:
@@ -1895,14 +1900,20 @@ class Scheduler(SchedulerInterface):
outputs: dict[int, list[EngineCoreOutput]] = defaultdict(list)
spec_decoding_stats: SpecDecodingStats | None = None
failed_kv_load_req_ids = None
failed_kv_load_req_ids: set[str] = set()
if kv_connector_output and kv_connector_output.failed_recving:
failed_kv_load_req_ids.update(
self._handle_failed_recving(kv_connector_output.failed_recving)
)
if kv_connector_output and kv_connector_output.invalid_block_ids:
# These blocks contain externally computed tokens that failed to
# load. Identify affected requests and adjust their computed token
# count to trigger recomputation of the invalid blocks.
failed_kv_load_req_ids = self._handle_invalid_blocks(
kv_connector_output.invalid_block_ids,
num_scheduled_tokens,
failed_kv_load_req_ids.update(
self._handle_invalid_blocks(
kv_connector_output.invalid_block_ids,
num_scheduled_tokens,
)
)
# Persist per-step routed experts into the scheduler-side slot
@@ -3135,6 +3146,21 @@ class Scheduler(SchedulerInterface):
return affected_req_ids, total_affected_tokens, blocks_to_evict
def _handle_failed_recving(self, failed_req_ids: set[str]) -> set[str]:
"""Fail closed for layouts whose block IDs are not globally unique."""
affected_req_ids: set[str] = set()
for req_id in failed_req_ids:
request = self.requests.get(req_id)
if (
request is not None
and request.status == RequestStatus.WAITING_FOR_REMOTE_KVS
):
affected_req_ids.add(req_id)
if self.recompute_kv_load_failures:
request.num_computed_tokens = 0
self.failed_recving_kv_req_ids.add(req_id)
return set() if self.recompute_kv_load_failures else affected_req_ids
def _handle_invalid_blocks(
self, invalid_block_ids: set[int], num_scheduled_tokens: dict[str, int]
) -> set[str]:
+405 -3
View File
@@ -4,8 +4,9 @@ import itertools
from abc import ABC, abstractmethod
from collections import defaultdict
from collections.abc import Sequence
from typing import ClassVar
from typing import TYPE_CHECKING, ClassVar
from vllm.distributed.kv_events import MEDIUM_CPU
from vllm.logger import init_logger
from vllm.utils.math_utils import cdiv
from vllm.v1.core.block_pool import BlockPool
@@ -16,6 +17,7 @@ from vllm.v1.core.kv_cache_utils import (
KVCacheBlock,
resolve_block_hashes,
)
from vllm.v1.hisparse.block_pool import SharedEventQueueBlockPool
from vllm.v1.kv_cache_interface import (
AttentionSpec,
ChunkedLocalAttentionSpec,
@@ -23,7 +25,10 @@ from vllm.v1.kv_cache_interface import (
CrossAttentionSpec,
FullAttentionSpec,
HiddenStateCacheSpec,
HiSparseHotSpec,
HiSparseResidentSpec,
KpoolTailSpec,
KVCacheGroupRole,
KVCacheSpec,
MambaSpec,
MLAAttentionSpec,
@@ -37,6 +42,9 @@ from vllm.v1.kv_cache_interface import (
from vllm.v1.kv_cache_spec_registry import KVCacheSpecRegistry
from vllm.v1.request import Request
if TYPE_CHECKING:
from vllm.v1.hisparse.coordinator import HiSparseCoordinator
logger = init_logger(__name__)
@@ -48,6 +56,9 @@ class SingleTypeKVCacheManager(ABC):
supports_fine_grained_hash_lookup: ClassVar[bool] = False
# Keep this group's longer prefix until external cache lookup completes.
retains_longer_hit: bool = False
@property
def has_positionally_stable_blocks(self) -> bool:
"""Whether positional offload scans can follow this block table.
@@ -2191,10 +2202,388 @@ class SinkFullAttentionManager(FullAttentionManager):
assert sink_len is not None and sink_len > 0 and sink_len % self.block_size == 0
class HiSparseSourceManager(FullAttentionManager):
"""Host-tier manager with a private pool; publishes hashes once durable.
Host capacity is best effort: a page that cannot get a host block keeps a
null host entry, so its GPU copy is never written back and stays pinned.
"""
coordinator: "HiSparseCoordinator | None" = None
# The host tier keeps prefixes the device groups have already lost.
retains_longer_hit = True
@property
def records_new_block_ids(self) -> bool:
return False
def take_new_block_ids(self) -> list[int]:
self.new_block_ids = []
return []
def bind_host_pool(self, num_blocks: int) -> None:
"""Replace the device pool this group was built with by a host one."""
device_pool = self.block_pool
self.block_pool = SharedEventQueueBlockPool(
num_gpu_blocks=num_blocks,
enable_caching=self.enable_caching and self.kv_cache_spec.prefix_cacheable,
hash_block_size=device_pool.hash_block_size,
enable_kv_cache_events=device_pool.enable_kv_cache_events,
metrics_collector=device_pool.metrics_collector,
medium=MEDIUM_CPU,
event_owner=device_pool,
)
self._null_block = self.block_pool.null_block
def take_pending_cow_copies(self) -> list[tuple[KVCacheBlock, KVCacheBlock]]:
"""Host copies never reach the worker's generic block-copy path."""
return []
def take_host_cow_copies(self) -> list[tuple[KVCacheBlock, KVCacheBlock]]:
"""Drain host copies for the coordinator to hand to the connector."""
copies = self._pending_cow_copies
self._pending_cow_copies = []
return copies
def get_num_blocks_to_allocate(
self,
request_id: str,
num_tokens: int,
new_computed_blocks: Sequence[KVCacheBlock],
total_computed_tokens: int,
num_local_computed_tokens: int,
num_tokens_main_model: int,
apply_admission_cap: bool = False,
) -> int:
if (
total_computed_tokens > num_local_computed_tokens
or self._has_partial_local_hit(
new_computed_blocks, num_local_computed_tokens
)
):
# External loads need real destinations; future GPU-computed pages
# remain best effort. Use the same admission sentinel as Mamba.
required = super().get_num_blocks_to_allocate(
request_id,
total_computed_tokens,
new_computed_blocks,
total_computed_tokens,
num_local_computed_tokens,
total_computed_tokens,
)
if required > self.block_pool.get_num_free_blocks():
assert self.coordinator is not None
assert self.coordinator.gpu_pool is not None
return self.coordinator.gpu_pool.num_gpu_blocks + 1
return 0
def allocate_new_blocks(
self, request_id: str, num_tokens: int, num_tokens_main_model: int
) -> list[KVCacheBlock]:
req_blocks = self.req_to_blocks[request_id]
num_required = cdiv(num_tokens, self.block_size)
num_free = self.block_pool.get_num_free_blocks()
if request_id in self._partial_hit_reqs:
num_free -= 1
fit_blocks = min(num_required, len(req_blocks) + max(0, num_free))
new_blocks = super().allocate_new_blocks(
request_id,
fit_blocks * self.block_size,
min(num_tokens_main_model, fit_blocks * self.block_size),
)
req_blocks.extend([self._null_block] * (num_required - len(req_blocks)))
return new_blocks
def allocate_external_computed_blocks(
self,
request_id: str,
num_local_computed_tokens: int,
num_external_computed_tokens: int,
) -> None:
if num_external_computed_tokens <= 0:
return
# The connector writes these pages; only a successful receive makes
# them readable, not advancing the request's computed-token count.
assert self.coordinator is not None
self.coordinator.record_pending_host_import(
request_id, num_local_computed_tokens + num_external_computed_tokens
)
super().allocate_external_computed_blocks(
request_id, num_local_computed_tokens, num_external_computed_tokens
)
def cache_blocks(
self,
request: Request,
num_tokens: int,
retention_interval: int | None = None,
*,
replay_boundaries: Sequence[int],
) -> None:
assert self.coordinator is not None
self.coordinator.publish_when_ready(
request,
num_tokens,
retention_interval,
replay_boundaries=replay_boundaries,
)
def publish_blocks(
self,
request: Request,
num_tokens: int,
retention_interval: int | None = None,
*,
replay_boundaries: Sequence[int],
) -> None:
super().cache_blocks(
request,
num_tokens,
retention_interval=retention_interval,
replay_boundaries=replay_boundaries,
)
def pop_blocks_for_free(self, request_id: str) -> list[KVCacheBlock]:
assert self.coordinator is not None
self.coordinator.free(request_id)
return super().pop_blocks_for_free(request_id)
class _HiSparseAuxiliaryManager(SingleTypeKVCacheManager):
"""Base for ephemeral groups whose host source owns prefix caching."""
coordinator: "HiSparseCoordinator | None" = None
def __init__(self, kv_cache_spec: KVCacheSpec, **kwargs) -> None:
# Never prefix-cached, but the per-step ``cache_blocks`` hook is where
# residency work runs, so stay opted in regardless of prefix caching.
kwargs["enable_caching"] = True
super().__init__(kv_cache_spec, **kwargs)
def cache_blocks(
self,
request: Request,
num_tokens: int,
retention_interval: int | None = None,
*,
replay_boundaries: Sequence[int],
) -> None:
return None
def get_num_common_prefix_blocks(self, running_request_id: str) -> int:
return 0
@classmethod
def find_longest_cache_hit(
cls,
block_hashes: BlockHashList,
max_length: int,
kv_cache_group_ids: list[int],
block_pool: BlockPool,
kv_cache_spec: KVCacheSpec,
drop_eagle_block: bool,
alignment_tokens: int,
dcp_world_size: int = 1,
pcp_world_size: int = 1,
) -> tuple[tuple[list[KVCacheBlock], ...], int]:
return tuple([] for _ in kv_cache_group_ids), 0
class HiSparseHotManager(_HiSparseAuxiliaryManager):
"""Allocate a hot region only after a request acquires CPU-only history."""
def __init__(self, kv_cache_spec: HiSparseHotSpec, **kwargs) -> None:
super().__init__(kv_cache_spec, **kwargs)
self.blocks_per_request = kv_cache_spec.blocks_per_request
self.hot_required: set[str] = set()
def require_hot(self, request_id: str) -> None:
self.hot_required.add(request_id)
def has_hot(self, request_id: str) -> bool:
return len(self.req_to_blocks.get(request_id, ())) == self.blocks_per_request
def get_num_blocks_to_allocate(
self,
request_id: str,
num_tokens: int,
new_computed_blocks: Sequence[KVCacheBlock],
total_computed_tokens: int,
num_local_computed_tokens: int,
num_tokens_main_model: int,
apply_admission_cap: bool = False,
) -> int:
assert not new_computed_blocks
# A hot region is needed to read host-backed history: an external
# import, a new request resuming a host prefix, or one already asked
# to transition. Running requests keep their earlier answer.
host_import = total_computed_tokens > num_local_computed_tokens
resumes_host_prefix = (
num_local_computed_tokens > 0 and request_id not in self.num_cached_block
)
if host_import or resumes_host_prefix or request_id in self.hot_required:
return self.get_num_required_blocks(request_id)
return 0
def get_num_required_blocks(self, request_id: str) -> int:
return max(
self.blocks_per_request - len(self.req_to_blocks.get(request_id, ())),
0,
)
def add_local_computed_blocks(
self,
request_id: str,
new_computed_blocks: Sequence[KVCacheBlock],
num_local_computed_tokens: int,
num_external_computed_tokens: int,
) -> None:
assert not new_computed_blocks
self.num_cached_block[request_id] = 0
assert self.coordinator is not None
if num_local_computed_tokens > 0 or not self.coordinator.resident_managers:
self.require_hot(request_id)
def allocate_external_computed_blocks(
self,
request_id: str,
num_local_computed_tokens: int,
num_external_computed_tokens: int,
) -> None:
self.require_hot(request_id)
def allocate_new_blocks(
self, request_id: str, num_tokens: int, num_tokens_main_model: int
) -> list[KVCacheBlock]:
# Cold admissions can bypass add_local_computed_blocks.
self.num_cached_block[request_id] = 0
if request_id not in self.hot_required:
return []
req_blocks = self.req_to_blocks[request_id]
num_new_blocks = self.blocks_per_request - len(req_blocks)
if num_new_blocks <= 0:
return []
new_blocks = self.block_pool.get_new_blocks(num_new_blocks)
req_blocks.extend(new_blocks)
return new_blocks
def pop_blocks_for_free(self, request_id: str) -> list[KVCacheBlock]:
self.hot_required.discard(request_id)
return super().pop_blocks_for_free(request_id)
class HiSparseResidentManager(_HiSparseAuxiliaryManager):
"""Track GPU-resident pages for otherwise host-backed KV."""
def get_num_blocks_to_allocate(
self,
request_id: str,
num_tokens: int,
new_computed_blocks: Sequence[KVCacheBlock],
total_computed_tokens: int,
num_local_computed_tokens: int,
num_tokens_main_model: int,
apply_admission_cap: bool = False,
) -> int:
del num_tokens_main_model
assert not new_computed_blocks
if total_computed_tokens > num_local_computed_tokens:
if total_computed_tokens % self.block_size != 0:
raise ValueError(
"A host-only HiSparse import must end on a cache-block boundary."
)
imported_pages = total_computed_tokens // self.block_size
return max(cdiv(num_tokens, self.block_size) - imported_pages, 0)
existing = len(self.req_to_blocks.get(request_id, ()))
host_pages = cdiv(num_local_computed_tokens, self.block_size)
required = cdiv(num_tokens, self.block_size)
if apply_admission_cap:
assert self._max_admission_blocks_per_request is not None
required = min(required, self._max_admission_blocks_per_request)
return max(required - max(existing, host_pages), 0)
def allocate_external_computed_blocks(
self,
request_id: str,
num_local_computed_tokens: int,
num_external_computed_tokens: int,
) -> None:
"""Represent imported host history with null resident pages."""
assert num_external_computed_tokens > 0
num_tokens = num_local_computed_tokens + num_external_computed_tokens
blocks = self.req_to_blocks[request_id]
tail_page = cdiv(num_tokens, self.block_size) - 1
if len(blocks) <= tail_page:
blocks.extend([self._null_block] * (tail_page + 1 - len(blocks)))
def add_local_computed_blocks(
self,
request_id: str,
new_computed_blocks: Sequence[KVCacheBlock],
num_local_computed_tokens: int,
num_external_computed_tokens: int,
) -> None:
assert not new_computed_blocks
req_blocks = self.req_to_blocks[request_id]
assert not req_blocks
num_host_pages = cdiv(num_local_computed_tokens, self.block_size)
req_blocks.extend([self._null_block] * num_host_pages)
self.num_cached_block[request_id] = 0
assert self.coordinator is not None
self.coordinator.commit_computed_blocks(request_id, num_host_pages)
def cache_blocks(
self,
request: Request,
num_tokens: int,
retention_interval: int | None = None,
*,
replay_boundaries: Sequence[int],
) -> None:
assert self.coordinator is not None
self.coordinator.plan_prefix_materialization(request.request_id, num_tokens)
self.coordinator.update_residency(request.request_id)
def allocate_new_blocks(
self, request_id: str, num_tokens: int, num_tokens_main_model: int
) -> list[KVCacheBlock]:
del num_tokens_main_model
req_blocks = self.req_to_blocks[request_id]
num_new_blocks = cdiv(num_tokens, self.block_size) - len(req_blocks)
if num_new_blocks <= 0:
return []
new_blocks = self.block_pool.get_new_blocks(num_new_blocks)
req_blocks.extend(new_blocks)
return new_blocks
def pop_blocks_for_free(self, request_id: str) -> list[KVCacheBlock]:
assert self.coordinator is not None
self.coordinator.free(request_id)
return super().pop_blocks_for_free(request_id)
def adopt_resident_page(
self, request_id: str, block_idx: int, block: KVCacheBlock
) -> bool:
"""Point a null prefix page at a pinned GPU copy of its contents."""
blocks = self.req_to_blocks.get(request_id)
if blocks is None or block_idx >= len(blocks) or not blocks[block_idx].is_null:
return False
blocks[block_idx] = block
return True
def get_resident_page(self, request_id: str, block_idx: int) -> KVCacheBlock | None:
blocks = self.req_to_blocks.get(request_id)
if blocks is None or block_idx >= len(blocks):
return None
block = blocks[block_idx]
return None if block.is_null else block
def get_manager_for_kv_cache_spec(
kv_cache_spec: KVCacheSpec,
max_in_flight_tokens: int,
max_model_len: int,
role: str | None = None,
**kwargs,
) -> SingleTypeKVCacheManager:
"""
@@ -2212,7 +2601,7 @@ def get_manager_for_kv_cache_spec(
Returns:
An instance of the appropriate SingleTypeKVCacheManager subclass
"""
manager_class = KVCacheSpecRegistry.get_manager_class(kv_cache_spec)
manager_class = KVCacheSpecRegistry.get_manager_class(kv_cache_spec, role)
assert manager_class is not None, (
f"No manager registered for KVCacheSpec {type(kv_cache_spec)}"
)
@@ -2224,7 +2613,7 @@ def get_manager_for_kv_cache_spec(
# FullAttentionSpec sizing without a separate admission cap.
if isinstance(
kv_cache_spec,
(SlidingWindowSpec, ChunkedLocalAttentionSpec),
(SlidingWindowSpec, ChunkedLocalAttentionSpec, HiSparseResidentSpec),
):
kwargs["max_admission_blocks_per_request"] = (
kv_cache_spec.max_admission_blocks_per_request(
@@ -2238,11 +2627,24 @@ def get_manager_for_kv_cache_spec(
def register_all_kvcache_specs(vllm_config):
"""Built-in spec registration"""
KVCacheSpecRegistry.register_role_manager(
KVCacheGroupRole.HISPARSE_SOURCE, HiSparseSourceManager
)
KVCacheSpecRegistry.register(
FullAttentionSpec,
FullAttentionManager,
uniform_type_base_spec=FullAttentionSpec,
)
KVCacheSpecRegistry.register(
HiSparseHotSpec,
HiSparseHotManager,
uniform_type_base_spec=HiSparseHotSpec,
)
KVCacheSpecRegistry.register(
HiSparseResidentSpec,
HiSparseResidentManager,
uniform_type_base_spec=HiSparseResidentSpec,
)
KVCacheSpecRegistry.register(
SlidingWindowSpec,