Merge branch 'main' into patches
Signed-off-by: MOVZX <movzx@yahoo.com>
This commit is contained in:
@@ -62,6 +62,30 @@ def _validate_prefix_cache_retention_interval(
|
||||
)
|
||||
|
||||
|
||||
def replay_boundaries(
|
||||
num_prompt_tokens: int, scheduler_block_size: int, use_eagle: bool
|
||||
) -> tuple[int, ...]:
|
||||
"""Positions a later request replaying a prompt can resume at.
|
||||
|
||||
A hit is the shortest across all groups, so every group retains state
|
||||
at each position; EAGLE groups also keep the block above, which they
|
||||
match and drop back from (see ``reachable_block_mask``).
|
||||
|
||||
Two positions are reachable: a resend of the identical prompt is capped
|
||||
at ``num_tokens - 1`` (its last token is recomputed for logits), a
|
||||
longer sibling matches the final aligned block. They differ only on a
|
||||
block-aligned prompt, where retaining just the higher one collapses the
|
||||
resend's hit to 0. The alignment is the scheduler block size, not the
|
||||
finer hash granularity, which would over-estimate the reach.
|
||||
"""
|
||||
if not use_eagle:
|
||||
return (num_prompt_tokens - 1,)
|
||||
block = scheduler_block_size
|
||||
resend = (num_prompt_tokens - 1) // block * block
|
||||
extension = num_prompt_tokens // block * block
|
||||
return tuple(sorted({max(resend - block, 0), max(extension - block, 0)}))
|
||||
|
||||
|
||||
class KVCacheCoordinator(ABC):
|
||||
"""Coordinate the KV cache of different KV cache groups."""
|
||||
|
||||
@@ -319,27 +343,6 @@ class KVCacheCoordinator(ABC):
|
||||
for manager in self.single_type_managers
|
||||
)
|
||||
|
||||
def get_replay_boundaries(self, request: Request) -> tuple[int, ...]:
|
||||
"""Positions a later request replaying this prompt can resume at.
|
||||
|
||||
A hit is the shortest across all groups, so every group retains state
|
||||
at each position; EAGLE groups also keep the block above, which they
|
||||
match and drop back from (see ``reachable_block_mask``).
|
||||
|
||||
Two positions are reachable: a resend of the identical prompt is capped
|
||||
at ``num_tokens - 1`` (its last token is recomputed for logits), a
|
||||
longer sibling matches the final aligned block. They differ only on a
|
||||
block-aligned prompt, where retaining just the higher one collapses the
|
||||
resend's hit to 0. The alignment is the scheduler block size, not the
|
||||
finer hash granularity, which would over-estimate the reach.
|
||||
"""
|
||||
if not self.eagle_group_ids:
|
||||
return (request.num_prompt_tokens - 1,)
|
||||
block = self.scheduler_block_size
|
||||
resend = (request.num_prompt_tokens - 1) // block * block
|
||||
extension = request.num_prompt_tokens // block * block
|
||||
return tuple(sorted({max(resend - block, 0), max(extension - block, 0)}))
|
||||
|
||||
def get_num_cacheable_tokens(
|
||||
self, num_computed_tokens: int, kv_cache_group_id: int
|
||||
) -> int:
|
||||
@@ -358,7 +361,11 @@ class KVCacheCoordinator(ABC):
|
||||
(including tokens that are already cached).
|
||||
|
||||
"""
|
||||
boundaries = self.get_replay_boundaries(request)
|
||||
boundaries = replay_boundaries(
|
||||
request.num_prompt_tokens,
|
||||
self.scheduler_block_size,
|
||||
use_eagle=bool(self.eagle_group_ids),
|
||||
)
|
||||
for group_id, manager in enumerate(self.single_type_managers):
|
||||
if not manager.enable_caching:
|
||||
continue
|
||||
@@ -419,23 +426,6 @@ class KVCacheCoordinator(ABC):
|
||||
blocks.extend(manager.pop_blocks_for_free(request_id))
|
||||
return blocks
|
||||
|
||||
def get_num_common_prefix_blocks(self, running_request_id: str) -> list[int]:
|
||||
"""Get the number of common prefix blocks for all requests with allocated
|
||||
KV cache for each kv cache group.
|
||||
|
||||
Args:
|
||||
running_request_id: The request ID of any running request, used to
|
||||
identify the common prefix blocks.
|
||||
|
||||
Returns:
|
||||
list[int]: The number of common prefix blocks for each kv cache group.
|
||||
|
||||
"""
|
||||
return [
|
||||
manager.get_num_common_prefix_blocks(running_request_id)
|
||||
for manager in self.single_type_managers
|
||||
]
|
||||
|
||||
def remove_skipped_blocks(
|
||||
self,
|
||||
request_id: str,
|
||||
@@ -520,9 +510,6 @@ class KVCacheCoordinatorNoPrefixCache(KVCacheCoordinator):
|
||||
)
|
||||
self.num_single_type_manager = len(self.single_type_managers)
|
||||
|
||||
def get_num_common_prefix_blocks(self, running_request_id: str) -> list[int]:
|
||||
return [0] * self.num_single_type_manager
|
||||
|
||||
def find_longest_cache_hit(
|
||||
self,
|
||||
block_hashes: list[BlockHash],
|
||||
@@ -661,8 +648,8 @@ class HybridKVCacheCoordinator(KVCacheCoordinator):
|
||||
self.hash_block_size = hash_block_size
|
||||
self.dcp_world_size = dcp_world_size
|
||||
# Only groups that participate in prefix caching must satisfy the
|
||||
# divisibility constraint; groups that opt out (e.g. GLM-5.3-Flash kpool
|
||||
# tail, block_size=kpool) are scratch buffers and excluded.
|
||||
# divisibility constraint; groups that opt out (e.g. circular buffers
|
||||
# such as the GLM-5.3-Flash indexer tail) are scratch and excluded.
|
||||
cacheable_block_sizes = [
|
||||
manager.block_size
|
||||
for manager, group in zip(
|
||||
@@ -724,8 +711,8 @@ class HybridKVCacheCoordinator(KVCacheCoordinator):
|
||||
"""
|
||||
self.attention_groups: list[SpecGroup] = []
|
||||
for i, g in enumerate(self.kv_cache_config.kv_cache_groups):
|
||||
# Skip groups that opt out of prefix caching (e.g. GLM-5.3-Flash
|
||||
# kpool tail): their blocks are per-request scratch, never
|
||||
# Skip groups that opt out of prefix caching (e.g. circular
|
||||
# buffers): their blocks are per-request scratch, never
|
||||
# shareable, so they must not participate in hit lookup (their
|
||||
# manager-level hooks already no-op). Their slot in the per-group
|
||||
# hit tuple stays empty.
|
||||
|
||||
@@ -689,39 +689,9 @@ class KVCacheManager:
|
||||
return True
|
||||
|
||||
def get_num_common_prefix_blocks(self, running_request_id: str) -> list[int]:
|
||||
"""Calculate the number of common prefix blocks for each kv cache group.
|
||||
|
||||
The function selects a running request and iterates through its blocks.
|
||||
A block is considered a common prefix block if ALL requests with
|
||||
allocated KV cache share it (i.e., ref_cnt equals the number of entries
|
||||
in req_to_blocks).
|
||||
|
||||
NOTE(woosuk): The number of requests with allocated KV cache is **greater
|
||||
than or equal to** the number of requests scheduled in the current step.
|
||||
This is because having allocated KV cache only indicates that:
|
||||
1. The request has not yet finished, and
|
||||
2. The request holds its blocks unfreed.
|
||||
|
||||
While all scheduled requests must have allocated KV cache, the inverse
|
||||
is not necessarily true. There may be requests with allocated KV cache
|
||||
that are not scheduled in the current step.
|
||||
|
||||
This can result in an edge case where the number of common prefix blocks
|
||||
is 0, even though all scheduled requests share a common prefix. This
|
||||
occurs because there may be unscheduled requests that do not share the
|
||||
common prefix. Currently, this case cannot be easily detected, so the
|
||||
function returns 0 in such cases.
|
||||
|
||||
Args:
|
||||
running_request_id: The request ID of any running request, used to
|
||||
identify the common prefix blocks.
|
||||
|
||||
Returns:
|
||||
list[int]: The number of common prefix blocks for each kv cache
|
||||
group.
|
||||
|
||||
"""
|
||||
return self.coordinator.get_num_common_prefix_blocks(running_request_id)
|
||||
"""Deprecated: cascade attention has been removed. Always returns 0
|
||||
for each KV cache group. Kept for out-of-tree schedulers."""
|
||||
return [0] * self.num_kv_cache_groups
|
||||
|
||||
def take_events(self) -> list[KVCacheEvent]:
|
||||
"""Take the KV cache events from the block pool.
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
+11
-1881
File diff suppressed because it is too large
Load Diff
@@ -2,7 +2,7 @@
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass
|
||||
from dataclasses import dataclass, field
|
||||
from functools import cached_property
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
@@ -253,9 +253,6 @@ class SchedulerOutput:
|
||||
# E.g., if a request has [0, 1], it could mean the vision encoder needs
|
||||
# to process that the request's 0-th and 1-th images in the current step.
|
||||
scheduled_encoder_inputs: dict[str, list[int]]
|
||||
# Number of common prefix blocks for all requests in each KV cache group.
|
||||
# This can be used for cascade attention.
|
||||
num_common_prefix_blocks: list[int]
|
||||
|
||||
# Request IDs that are finished in between the previous and the current
|
||||
# steps. This is used to notify the workers about the finished requests
|
||||
@@ -304,9 +301,6 @@ 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
|
||||
|
||||
@@ -314,6 +308,10 @@ class SchedulerOutput:
|
||||
# Number of spec tokens to schedule for the next step.
|
||||
num_spec_tokens_to_schedule: int = 0
|
||||
|
||||
# Deprecated: cascade attention has been removed, so this is always empty.
|
||||
# Kept for out-of-tree schedulers and workers.
|
||||
num_common_prefix_blocks: list[int] = field(default_factory=list)
|
||||
|
||||
@classmethod
|
||||
def make_empty(cls) -> "SchedulerOutput":
|
||||
return cls(
|
||||
@@ -323,7 +321,6 @@ class SchedulerOutput:
|
||||
total_num_scheduled_tokens=0,
|
||||
scheduled_spec_decode_tokens={},
|
||||
scheduled_encoder_inputs={},
|
||||
num_common_prefix_blocks=[],
|
||||
finished_req_ids=set(),
|
||||
free_encoder_mm_hashes=[],
|
||||
)
|
||||
|
||||
@@ -344,6 +344,17 @@ class Scheduler(SchedulerInterface):
|
||||
self.cache_config.enable_mamba_shared_prefix_checkpoint
|
||||
),
|
||||
)
|
||||
# Mamba managers already account for their speculative state blocks.
|
||||
num_spec_decode_tokens = (
|
||||
1 + self.num_spec_tokens + self.num_lookahead_tokens
|
||||
if self.num_spec_tokens
|
||||
else 0
|
||||
)
|
||||
self._spec_decode_step_blocks = sum(
|
||||
cdiv(num_spec_decode_tokens, manager.block_size)
|
||||
for manager in self.kv_cache_manager.coordinator.single_type_managers
|
||||
if not isinstance(manager.kv_cache_spec, MambaSpec)
|
||||
)
|
||||
# Bind after construction so connectors can access the cache manager.
|
||||
if self.connector is not None:
|
||||
self.connector.bind_kv_cache_manager(self.kv_cache_manager)
|
||||
@@ -1236,7 +1247,7 @@ class Scheduler(SchedulerInterface):
|
||||
# predictable preemptions.
|
||||
reserved_blocks = (
|
||||
self._inflight_prefill_reserved_blocks()
|
||||
+ self._spec_decode_step_blocks()
|
||||
+ self._spec_decode_step_blocks
|
||||
)
|
||||
|
||||
# Replayed tokens are already counted in the adopted hit; a
|
||||
@@ -1403,16 +1414,6 @@ class Scheduler(SchedulerInterface):
|
||||
scheduled_running_reqs
|
||||
) <= len(self.running)
|
||||
|
||||
# Get the longest common prefix among all requests in the running queue.
|
||||
# This can be potentially used for cascade attention.
|
||||
num_common_prefix_blocks = [0] * len(self.kv_cache_config.kv_cache_groups)
|
||||
with record_function_or_nullcontext("schedule: get_num_common_prefix_blocks"):
|
||||
if self.running:
|
||||
any_request_id = self.running[0].request_id
|
||||
num_common_prefix_blocks = (
|
||||
self.kv_cache_manager.get_num_common_prefix_blocks(any_request_id)
|
||||
)
|
||||
|
||||
# Construct the scheduler output.
|
||||
if self.use_v2_model_runner:
|
||||
scheduled_new_reqs.extend(scheduled_resumed_reqs)
|
||||
@@ -1505,7 +1506,6 @@ class Scheduler(SchedulerInterface):
|
||||
scheduled_spec_decode_tokens=scheduled_spec_decode_tokens,
|
||||
scheduled_encoder_inputs=scheduled_encoder_inputs,
|
||||
scheduled_encoder_input_stats=scheduled_encoder_input_stats,
|
||||
num_common_prefix_blocks=num_common_prefix_blocks,
|
||||
preempted_req_ids=self.reset_preempted_req_ids,
|
||||
# finished_req_ids is an existing state in the scheduler,
|
||||
# instead of being newly scheduled in this step.
|
||||
@@ -1863,6 +1863,26 @@ class Scheduler(SchedulerInterface):
|
||||
# already calculated encoder inputs and can skip here.
|
||||
continue
|
||||
|
||||
# If no encoder input chunking is allowed, we do not want to
|
||||
# partially schedule a multimodal item. If the scheduled range would
|
||||
# only cover part of the mm input, roll back to before the mm item.
|
||||
if (
|
||||
self.scheduler_config.disable_chunked_mm_input
|
||||
and not self.is_encoder_decoder
|
||||
# `<=`, not `<`: a chunk that starts exactly at the item still
|
||||
# splits it when it cannot cover the whole item.
|
||||
and num_computed_tokens <= start_pos
|
||||
and (num_computed_tokens + num_new_tokens)
|
||||
< (start_pos + num_encoder_tokens)
|
||||
):
|
||||
# Account for EAGLE shift when rolling back to avoid
|
||||
# encoder cache miss. This ensures the scheduled range
|
||||
# stops before start_pos even with the shift.
|
||||
num_new_tokens = max(
|
||||
0, start_pos - (num_computed_tokens + shift_computed_tokens)
|
||||
)
|
||||
break
|
||||
|
||||
if not self.is_encoder_decoder:
|
||||
# We are not using the encoder cache for encoder-decoder models,
|
||||
# yet.
|
||||
@@ -1902,22 +1922,6 @@ class Scheduler(SchedulerInterface):
|
||||
# previous step.
|
||||
continue
|
||||
|
||||
# If no encoder input chunking is allowed, we do not want to
|
||||
# partially schedule a multimodal item. If the scheduled range would
|
||||
# only cover part of the mm input, roll back to before the mm item.
|
||||
if (
|
||||
self.scheduler_config.disable_chunked_mm_input
|
||||
and num_computed_tokens < start_pos
|
||||
and (num_computed_tokens + num_new_tokens)
|
||||
< (start_pos + num_encoder_tokens)
|
||||
):
|
||||
# Account for EAGLE shift when rolling back to avoid
|
||||
# encoder cache miss. This ensures the scheduled range
|
||||
# stops before start_pos even with the shift.
|
||||
num_new_tokens = max(
|
||||
0, start_pos - (num_computed_tokens + shift_computed_tokens)
|
||||
)
|
||||
break
|
||||
if not self.encoder_cache_manager.can_allocate(
|
||||
request, i, encoder_compute_budget, num_embeds_to_schedule
|
||||
):
|
||||
@@ -3059,9 +3063,12 @@ class Scheduler(SchedulerInterface):
|
||||
def _request_remaining_blocks(self, request: Request) -> int:
|
||||
"""Blocks `request` still needs to hold its full sequence and be promoted."""
|
||||
full_num_tokens = min(request.num_tokens, self.max_model_len)
|
||||
num_blocks = self.kv_cache_manager.coordinator.get_num_blocks_to_allocate(
|
||||
num_tokens = full_num_tokens
|
||||
if self.num_spec_tokens:
|
||||
num_tokens += 1 + self.num_spec_tokens + self.num_lookahead_tokens
|
||||
return self.kv_cache_manager.coordinator.get_num_blocks_to_allocate(
|
||||
request_id=request.request_id,
|
||||
num_tokens=full_num_tokens,
|
||||
num_tokens=num_tokens,
|
||||
new_computed_blocks=self.kv_cache_manager.empty_kv_cache_blocks.blocks,
|
||||
num_encoder_tokens=0,
|
||||
total_computed_tokens=request.num_computed_tokens,
|
||||
@@ -3070,20 +3077,6 @@ class Scheduler(SchedulerInterface):
|
||||
apply_admission_cap=True,
|
||||
prefill_end=max(request.num_prompt_tokens, request.num_tokens - 1),
|
||||
)
|
||||
return num_blocks + self._spec_decode_step_blocks()
|
||||
|
||||
def _spec_decode_step_blocks(self) -> int:
|
||||
"""Number of blocks for the extra KV slots a spec decode step needs.
|
||||
|
||||
When using async kv load, scheduler must reserve enough blocks for
|
||||
full sequence + the spec decode step, otherwise request cannot be
|
||||
able to run after the async_load if we are out of kv blocks.
|
||||
"""
|
||||
if not self.num_spec_tokens:
|
||||
return 0
|
||||
return cdiv(
|
||||
1 + self.num_spec_tokens + self.num_lookahead_tokens, self.block_size
|
||||
)
|
||||
|
||||
def _set_kv_fetch_stage(self, request: Request, stage: str | None) -> None:
|
||||
kv_fetch_stages = self._kv_fetch_stages
|
||||
|
||||
@@ -7,9 +7,9 @@ from collections.abc import Sequence
|
||||
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
|
||||
from vllm.v1.core.kv_cache_metrics import KVCacheMetricsCollector
|
||||
from vllm.v1.core.kv_cache_utils import (
|
||||
BlockHashList,
|
||||
BlockHashListWithBlockSize,
|
||||
@@ -27,7 +27,6 @@ from vllm.v1.kv_cache_interface import (
|
||||
HiddenStateCacheSpec,
|
||||
HiSparseHotSpec,
|
||||
HiSparseResidentSpec,
|
||||
KpoolTailSpec,
|
||||
KVCacheGroupRole,
|
||||
KVCacheSpec,
|
||||
MambaSpec,
|
||||
@@ -45,8 +44,6 @@ from vllm.v1.request import Request
|
||||
if TYPE_CHECKING:
|
||||
from vllm.v1.hisparse.coordinator import HiSparseCoordinator
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
class SingleTypeKVCacheManager(ABC):
|
||||
"""An abstract base class for a manager that handle the kv cache management
|
||||
@@ -495,7 +492,7 @@ class SingleTypeKVCacheManager(ABC):
|
||||
boundary; a positive multiple of ``scheduler_block_size`` keeps
|
||||
a tail once per that-sized segment. Only SWA acts on it.
|
||||
replay_boundaries: Positions a later request replaying this prompt
|
||||
can resume at, from ``get_replay_boundaries``.
|
||||
can resume at, from ``replay_boundaries``.
|
||||
|
||||
"""
|
||||
if not self.kv_cache_spec.prefix_cacheable:
|
||||
@@ -508,7 +505,7 @@ class SingleTypeKVCacheManager(ABC):
|
||||
|
||||
# Token boundaries whose reachable tail must be retained under sparse
|
||||
# retention: every position a replaying sibling can resume at (see
|
||||
# ``get_replay_boundaries``) and any detected shared-prefix junction.
|
||||
# ``replay_boundaries``) and any detected shared-prefix junction.
|
||||
reachable_boundaries = [*replay_boundaries]
|
||||
if request.shared_prefix_boundary:
|
||||
reachable_boundaries.append(request.shared_prefix_boundary)
|
||||
@@ -591,21 +588,6 @@ class SingleTypeKVCacheManager(ABC):
|
||||
# Free blocks in reverse order so that the tail blocks are freed first.
|
||||
self.block_pool.free_blocks(reversed(self.pop_blocks_for_free(request_id)))
|
||||
|
||||
@abstractmethod
|
||||
def get_num_common_prefix_blocks(self, running_request_id: str) -> int:
|
||||
"""Get the number of common prefix blocks for all requests with allocated
|
||||
KV cache.
|
||||
|
||||
Args:
|
||||
running_request_id: The request ID.
|
||||
|
||||
Returns:
|
||||
The number of common prefix blocks for all requests with allocated
|
||||
KV cache.
|
||||
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
@classmethod
|
||||
@abstractmethod
|
||||
def find_longest_cache_hit(
|
||||
@@ -901,16 +883,6 @@ class FullAttentionManager(SingleTypeKVCacheManager):
|
||||
block_size=self.block_size,
|
||||
)
|
||||
|
||||
def get_num_common_prefix_blocks(self, running_request_id: str) -> int:
|
||||
blocks = self.req_to_blocks[running_request_id]
|
||||
num_common_blocks = 0
|
||||
for block in blocks:
|
||||
if block.ref_cnt == len(self.req_to_blocks):
|
||||
num_common_blocks += 1
|
||||
else:
|
||||
break
|
||||
return num_common_blocks
|
||||
|
||||
|
||||
class RSWAManager(FullAttentionManager):
|
||||
"""KV cache manager for Reference Sliding Window Attention (R-SWA).
|
||||
@@ -1197,14 +1169,6 @@ class SlidingWindowManager(SingleTypeKVCacheManager):
|
||||
num_computed_tokens - self.sliding_window + 1 - self.extra_retained_tokens,
|
||||
)
|
||||
|
||||
def get_num_common_prefix_blocks(self, running_request_id: str) -> int:
|
||||
"""NOTE(Chen): The prefix blocks are null blocks for sliding window layers.
|
||||
So it's not correct to count ref_cnt like FullAttentionManager. Return
|
||||
0 here for correctness. Need to support cascade attention + sliding
|
||||
window in the future.
|
||||
"""
|
||||
return 0
|
||||
|
||||
|
||||
class CircularBufferManager(FullAttentionManager):
|
||||
"""Claims the ring's single block per request; prefix caching disabled."""
|
||||
@@ -1292,17 +1256,10 @@ class CircularBufferManager(FullAttentionManager):
|
||||
) -> None:
|
||||
return
|
||||
|
||||
def get_num_common_prefix_blocks(self, running_request_id: str) -> int:
|
||||
return 0
|
||||
|
||||
def get_num_skipped_tokens(self, num_computed_tokens: int) -> int:
|
||||
return 0
|
||||
|
||||
|
||||
class KpoolTailManager(CircularBufferManager):
|
||||
"""One-block circular scratch manager for ``KpoolTailSpec``."""
|
||||
|
||||
|
||||
class ChunkedLocalAttentionManager(SingleTypeKVCacheManager):
|
||||
def __init__(self, kv_cache_spec: ChunkedLocalAttentionSpec, **kwargs) -> None:
|
||||
super().__init__(kv_cache_spec, **kwargs)
|
||||
@@ -1454,10 +1411,6 @@ class ChunkedLocalAttentionManager(SingleTypeKVCacheManager):
|
||||
) * self.attention_chunk_size
|
||||
return num_skipped_tokens
|
||||
|
||||
def get_num_common_prefix_blocks(self, running_request_id: str) -> int:
|
||||
"""Cascade attention is not supported by chunked local attention."""
|
||||
return 0
|
||||
|
||||
|
||||
class MambaManager(SingleTypeKVCacheManager):
|
||||
supports_fine_grained_hash_lookup: ClassVar[bool] = True
|
||||
@@ -1473,6 +1426,9 @@ class MambaManager(SingleTypeKVCacheManager):
|
||||
) -> None:
|
||||
super().__init__(kv_cache_spec, block_pool, **kwargs)
|
||||
self.mamba_cache_mode = kv_cache_spec.mamba_cache_mode
|
||||
assert self.mamba_cache_mode == "align" or not self.enable_caching, (
|
||||
"Mamba prefix caching requires mamba_cache_mode='align'"
|
||||
)
|
||||
self.num_speculative_blocks: int = kv_cache_spec.num_speculative_blocks
|
||||
self.has_prefill_checkpoint_blocks = (
|
||||
self.mamba_cache_mode == "align"
|
||||
@@ -1696,10 +1652,6 @@ class MambaManager(SingleTypeKVCacheManager):
|
||||
self.block_pool.free_blocks([blocks[last_state_block_idx]])
|
||||
blocks[last_state_block_idx] = self._null_block
|
||||
|
||||
def get_num_common_prefix_blocks(self, running_request_id: str) -> int:
|
||||
"""Cascade attention is not supported by mamba"""
|
||||
return 0
|
||||
|
||||
def _needs_internal_checkpoint(
|
||||
self,
|
||||
request_id: str,
|
||||
@@ -2208,11 +2160,6 @@ class CrossAttentionManager(SingleTypeKVCacheManager):
|
||||
# requests, so this method is not relevant.
|
||||
raise ValueError("Should not be called as prefix caching is disabled.")
|
||||
|
||||
def get_num_common_prefix_blocks(self, running_request_id: str) -> int:
|
||||
# Cross-attention blocks contain request-specific encoder states
|
||||
# and are not shared between different requests
|
||||
return 0
|
||||
|
||||
@classmethod
|
||||
def find_longest_cache_hit(
|
||||
cls,
|
||||
@@ -2289,7 +2236,11 @@ class HiSparseSourceManager(FullAttentionManager):
|
||||
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=None,
|
||||
metrics_collector=(
|
||||
KVCacheMetricsCollector(device_pool.metrics_collector.sample_rate)
|
||||
if device_pool.metrics_collector is not None
|
||||
else None
|
||||
),
|
||||
medium=MEDIUM_CPU,
|
||||
event_owner=device_pool,
|
||||
)
|
||||
@@ -2406,9 +2357,6 @@ class _HiSparseAuxiliaryManager(SingleTypeKVCacheManager):
|
||||
) -> None:
|
||||
return None
|
||||
|
||||
def get_num_common_prefix_blocks(self, running_request_id: str) -> int:
|
||||
return 0
|
||||
|
||||
@classmethod
|
||||
def find_longest_cache_hit(
|
||||
cls,
|
||||
@@ -2515,6 +2463,10 @@ class HiSparseResidentManager(_HiSparseAuxiliaryManager):
|
||||
|
||||
max_admission_blocks_per_request: int
|
||||
|
||||
def __init__(self, kv_cache_spec: HiSparseResidentSpec, **kwargs) -> None:
|
||||
super().__init__(kv_cache_spec, **kwargs)
|
||||
self.residency_changes: dict[str, dict[int, KVCacheBlock]] = {}
|
||||
|
||||
def get_num_blocks_to_allocate(
|
||||
self,
|
||||
request_id: str,
|
||||
@@ -2558,7 +2510,7 @@ class HiSparseResidentManager(_HiSparseAuxiliaryManager):
|
||||
tail_page = (num_tokens - 1) // self.block_size
|
||||
if len(blocks) <= tail_page:
|
||||
blocks.extend([self._null_block] * (tail_page + 1 - len(blocks)))
|
||||
if blocks[tail_page].is_null:
|
||||
if self.get_resident_page(request_id, tail_page) is None:
|
||||
blocks[tail_page] = self.block_pool.get_new_blocks(1)[0]
|
||||
|
||||
def add_local_computed_blocks(
|
||||
@@ -2592,25 +2544,55 @@ class HiSparseResidentManager(_HiSparseAuxiliaryManager):
|
||||
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)
|
||||
blocks = self.get_residency_row(request_id)
|
||||
self.residency_changes.pop(request_id, None)
|
||||
super().pop_blocks_for_free(request_id)
|
||||
return blocks
|
||||
|
||||
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:
|
||||
if blocks is None or block_idx >= len(blocks):
|
||||
return False
|
||||
blocks[block_idx] = block
|
||||
if self.get_resident_page(request_id, block_idx) is not None:
|
||||
return False
|
||||
self.residency_changes.setdefault(request_id, {})[block_idx] = block
|
||||
return True
|
||||
|
||||
def drop_resident_page(
|
||||
self, request_id: str, block_idx: int
|
||||
) -> KVCacheBlock | None:
|
||||
"""Stop reading a page from the GPU; return the block it was read from."""
|
||||
block = self.get_resident_page(request_id, block_idx)
|
||||
if block is not None:
|
||||
changes = self.residency_changes.setdefault(request_id, {})
|
||||
changes[block_idx] = self._null_block
|
||||
return block
|
||||
|
||||
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]
|
||||
changes = self.residency_changes.get(request_id)
|
||||
if changes:
|
||||
block = changes.get(block_idx, block)
|
||||
return None if block.is_null else block
|
||||
|
||||
def get_residency_row(self, request_id: str, start: int = 0) -> list[KVCacheBlock]:
|
||||
"""The request's row from ``start`` with residency changes applied. Unlike
|
||||
``get_resident_page``, host-only pages stay as the null block."""
|
||||
blocks = self.req_to_blocks.get(request_id, [])[start:]
|
||||
changes = self.residency_changes.get(request_id)
|
||||
if not changes:
|
||||
return blocks
|
||||
return [
|
||||
changes.get(block_idx, block)
|
||||
for block_idx, block in enumerate(blocks, start)
|
||||
]
|
||||
|
||||
|
||||
def get_manager_for_kv_cache_spec(
|
||||
kv_cache_spec: KVCacheSpec,
|
||||
@@ -2696,11 +2678,6 @@ def register_all_kvcache_specs(vllm_config):
|
||||
SlidingWindowManager,
|
||||
uniform_type_base_spec=SlidingWindowMLASpec,
|
||||
)
|
||||
KVCacheSpecRegistry.register(
|
||||
KpoolTailSpec,
|
||||
KpoolTailManager,
|
||||
uniform_type_base_spec=KpoolTailSpec,
|
||||
)
|
||||
|
||||
KVCacheSpecRegistry.register(
|
||||
MambaSpec, MambaManager, uniform_type_base_spec=MambaSpec
|
||||
|
||||
Reference in New Issue
Block a user