Merge branch 'main' into patches

Signed-off-by: MOVZX <movzx@yahoo.com>
This commit is contained in:
2026-10-09 17:41:13 +00:00
1122 changed files with 60114 additions and 20956 deletions
+3 -6
View File
@@ -479,8 +479,8 @@ class BlockPool:
kv_cache_group_id: KV cache group that owns the partial entry.
block_size: Cache block size for the owning group. The partial
entry hash itself is always the prefix-chain hash at
``num_tokens``; ``block_size`` is used to assert that the
entry is partial within the owning cache block.
``num_tokens``; ``block_size`` must be a multiple of the hash
block size.
replace_existing_hashes: Whether the block contents were replaced
and all existing cache entries must be removed before the new
entry is registered.
@@ -494,9 +494,6 @@ class BlockPool:
return None
assert block_size % self.hash_block_size == 0
assert replace_existing_hashes or (
block_size > self.hash_block_size and num_tokens % block_size != 0
)
block_hash = self._get_partial_block_hash(request, num_tokens)
num_hash_blocks = num_tokens // self.hash_block_size
block_hash_with_group_id = make_block_hash_with_group_id(
@@ -829,7 +826,7 @@ class BlockPool:
def reset_prefix_cache(self) -> bool:
"""Reset prefix cache. This function may be used in RLHF
flows to invalid prefix caching after the weights are updated,
flows to invalidate prefix caching after the weights are updated,
or used for resetting prefix caching status for benchmarking.
Returns:
+53 -78
View File
@@ -4,13 +4,14 @@ from abc import ABC, abstractmethod
from collections.abc import Sequence
from typing import NamedTuple
from vllm.logger import init_logger
from vllm.utils.math_utils import cdiv, round_down
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 (
BlockHash,
KVCacheBlock,
eagle_proof_margin,
partial_hash_hits_enabled,
)
from vllm.v1.core.single_type_kv_cache_manager import (
CrossAttentionManager,
@@ -28,8 +29,6 @@ from vllm.v1.kv_cache_interface import (
)
from vllm.v1.request import Request
logger = init_logger(__name__)
def _validate_prefix_cache_retention_interval(
retention_interval: int | None,
@@ -341,6 +340,14 @@ class KVCacheCoordinator(ABC):
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:
"""Return the prefix eligible for hashing in this group."""
# Only cache tokens with finalized KV. The last num_reprefillable_tokens
# tokens can be re-prefilled during multi-module MTP.
return max(0, num_computed_tokens - self.num_reprefillable_tokens)
def cache_blocks(self, request: Request, num_computed_tokens: int) -> None:
"""Cache the blocks for the request.
@@ -352,17 +359,12 @@ class KVCacheCoordinator(ABC):
"""
boundaries = self.get_replay_boundaries(request)
for manager in self.single_type_managers:
for group_id, manager in enumerate(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(
0, num_computed_tokens - self.num_reprefillable_tokens
)
manager.cache_blocks(
request,
num_tokens_to_cache,
self.get_num_cacheable_tokens(num_computed_tokens, group_id),
retention_interval=self.retention_interval,
replay_boundaries=boundaries,
)
@@ -692,37 +694,15 @@ class HybridKVCacheCoordinator(KVCacheCoordinator):
# managers in every group. TP needs hashing finer than the Mamba block;
# DCP accepts equality because it scales the effective full-attention
# block instead.
has_partial_mamba_group = any(
isinstance(g.kv_cache_spec, MambaSpec)
and g.kv_cache_spec.mamba_cache_mode == "align"
and (
(dcp_world_size == 1 and g.kv_cache_spec.block_size > hash_block_size)
or (
dcp_world_size > 1 and g.kv_cache_spec.block_size >= hash_block_size
)
)
for g in kv_cache_config.kv_cache_groups
)
self.enable_partial_hash_hits = (
allow_partial_hash_hits and has_partial_mamba_group
allow_partial_hash_hits
and partial_hash_hits_enabled(
kv_cache_config.kv_cache_groups,
hash_block_size,
dcp_world_size,
[type(manager) for manager in self.single_type_managers],
)
)
if self.enable_partial_hash_hits:
unsupported_partial_hit_managers = {
type(manager).__name__
for manager, group in zip(
self.single_type_managers, kv_cache_config.kv_cache_groups
)
if group.kv_cache_spec.prefix_cacheable
and not manager.supports_fine_grained_hash_lookup
and manager.block_size != hash_block_size
}
if unsupported_partial_hit_managers:
self.enable_partial_hash_hits = False
logger.warning_once(
"Disabling fine-grained prefix-cache hits because these KV "
"cache managers require block-aligned lookups: %s.",
", ".join(sorted(unsupported_partial_hit_managers)),
)
cache_hit_alignment_tokens = self._cache_hit_alignment_tokens
for manager in self.single_type_managers:
manager.cache_hit_alignment_tokens = cache_hit_alignment_tokens
@@ -809,39 +789,22 @@ class HybridKVCacheCoordinator(KVCacheCoordinator):
return num_tokens
return round_down(num_tokens, self.scheduler_block_size)
def cache_blocks(self, request: Request, num_computed_tokens: int) -> None:
def get_num_cacheable_tokens(
self, num_computed_tokens: int, kv_cache_group_id: int
) -> int:
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.
if manager.use_eagle and cached_num_computed_tokens > 0:
# Only cache tokens with finalized KV. The last
# num_reprefillable_tokens tokens can be re-prefilled during
# multi-module MTP.
num_finalized_computed_tokens = max(
0, num_computed_tokens - self.num_reprefillable_tokens
)
cached_num_finalized_computed_tokens = self._align_cacheable(
num_finalized_computed_tokens
)
num_tokens_to_cache = min(
num_finalized_computed_tokens,
cached_num_finalized_computed_tokens + manager.block_size,
)
# The manager already knows the fine hit granularity
# (``scheduler_block_size``); retention is passed separately so it
# can keep both the coarse segment tails and the fine replay
# boundary (which needs the fine value).
manager.cache_blocks(
request,
num_tokens_to_cache,
retention_interval=self.retention_interval,
replay_boundaries=boundaries,
manager = self.single_type_managers[kv_cache_group_id]
# EAGLE matches one block past the aligned boundary, then drops it.
if manager.use_eagle and cached_num_computed_tokens > 0:
num_finalized_computed_tokens = max(
0, num_computed_tokens - self.num_reprefillable_tokens
)
return min(
num_finalized_computed_tokens,
self._align_cacheable(num_finalized_computed_tokens)
+ manager.block_size,
)
return cached_num_computed_tokens
def find_longest_cache_hit(
self,
@@ -913,15 +876,15 @@ class HybridKVCacheCoordinator(KVCacheCoordinator):
# mamba: its finder never drops (draft models have no mamba
# layers), so the hit would grow past the candidate.
if drop_eagle_block and not isinstance(spec, MambaSpec):
eagle_margin = (
self.hash_block_size
if self.enable_partial_hash_hits
and manager_cls.supports_fine_grained_hash_lookup
and group_block_size > self.hash_block_size
else group_block_size
eagle_margin = eagle_proof_margin(
group_block_size,
self.hash_block_size,
self.enable_partial_hash_hits
and manager_cls.supports_fine_grained_hash_lookup,
)
_max_length = min(
curr_hit_length + eagle_margin, max_cache_hit_length
curr_hit_length + eagle_margin,
len(block_hashes) * self.hash_block_size,
)
hit_blocks, _new_hit_length = manager_cls.find_longest_cache_hit(
block_hashes=block_hashes,
@@ -997,9 +960,21 @@ class HybridKVCacheCoordinator(KVCacheCoordinator):
for spec, group_ids, manager_cls, use_eagle in self.attention_groups:
manager = self.single_type_managers[group_ids[0]]
lookup_length = max_cache_hit_length
if use_eagle and not isinstance(spec, MambaSpec):
eagle_margin = eagle_proof_margin(
manager.block_size,
self.hash_block_size,
self.enable_partial_hash_hits
and manager_cls.supports_fine_grained_hash_lookup,
)
lookup_length = min(
max_cache_hit_length + eagle_margin,
len(block_hashes) * self.hash_block_size,
)
blocks, group_hit = manager_cls.find_longest_cache_hit(
block_hashes=block_hashes,
max_length=max_cache_hit_length,
max_length=lookup_length,
kv_cache_group_ids=group_ids,
block_pool=manager.block_pool,
kv_cache_spec=spec,
+125 -36
View File
@@ -53,6 +53,7 @@ from vllm.v1.utils import tensor_data
if TYPE_CHECKING:
from vllm.v1.core.block_pool import BlockPool
from vllm.v1.core.single_type_kv_cache_manager import SingleTypeKVCacheManager
# BlockHash represents the hash of a single KV-cache block used for
@@ -303,19 +304,17 @@ class FreeKVCacheBlockQueue:
The first free block.
"""
if (
self.fake_free_list_head.next_free_block is self.fake_free_list_tail
or self.fake_free_list_head.next_free_block is None
):
head = self.fake_free_list_head
first_block = head.next_free_block
if first_block is self.fake_free_list_tail or first_block is None:
assert self.num_free_blocks == 0, (
f"num_free_blocks ({self.num_free_blocks}) is out of sync "
"with the free list."
)
raise ValueError("No free blocks available")
first_block: KVCacheBlock = self.fake_free_list_head.next_free_block
if first_block.next_free_block is None:
next_block = first_block.next_free_block
if next_block is None:
# This should not happen if the block is from the free list.
# It indicates a bug in the caller's logic.
raise RuntimeError(
@@ -325,8 +324,8 @@ class FreeKVCacheBlockQueue:
# Connect fake_head and the next block of first_block (i.e. second block
# or fake tail).
self.fake_free_list_head.next_free_block = first_block.next_free_block
first_block.next_free_block.prev_free_block = self.fake_free_list_head
head.next_free_block = next_block
next_block.prev_free_block = head
# Remove the block from the linked list.
first_block.prev_free_block = first_block.next_free_block = None
@@ -350,6 +349,16 @@ class FreeKVCacheBlockQueue:
self.num_free_blocks -= n
curr_block = self.fake_free_list_head.next_free_block
if n == 1:
assert curr_block is not None
next_block = curr_block.next_free_block
curr_block.prev_free_block = None
curr_block.next_free_block = None
if next_block is not None:
self.fake_free_list_head.next_free_block = next_block
next_block.prev_free_block = self.fake_free_list_head
return [curr_block]
# Pop n blocks from the head of the list
ret = []
for _ in range(n):
@@ -375,15 +384,17 @@ class FreeKVCacheBlockQueue:
block: The block to remove.
"""
if block.prev_free_block is None or block.next_free_block is None:
prev_block = block.prev_free_block
next_block = block.next_free_block
if prev_block is None or next_block is None:
# This should not happen if the block is from the free list.
# It indicates a bug in the caller's logic.
raise RuntimeError(f"remove() called on an invalid block: {block}")
# Link the previous block to the next block.
block.prev_free_block.next_free_block = block.next_free_block
prev_block.next_free_block = next_block
# Link the next block to the previous block.
block.next_free_block.prev_free_block = block.prev_free_block
next_block.prev_free_block = prev_block
# Remove the block from the linked list.
block.prev_free_block = block.next_free_block = None
@@ -397,19 +408,19 @@ class FreeKVCacheBlockQueue:
block: The block to append.
"""
if self.fake_free_list_tail.prev_free_block is None:
tail = self.fake_free_list_tail
last_block = tail.prev_free_block
if last_block is None:
raise RuntimeError(
"prev_free_block of fake_free_list_tail should always exist"
)
last_block: KVCacheBlock = self.fake_free_list_tail.prev_free_block
# Connect the new block after the last block.
last_block.next_free_block = block
block.prev_free_block = last_block
# Connect the fake tail after the new block.
block.next_free_block = self.fake_free_list_tail
self.fake_free_list_tail.prev_free_block = block
block.next_free_block = tail
tail.prev_free_block = block
self.num_free_blocks += 1
@@ -441,10 +452,11 @@ class FreeKVCacheBlockQueue:
blocks: The blocks to append.
"""
if len(blocks) == 0:
if not blocks:
return
last_block = self.fake_free_list_tail.prev_free_block
tail = self.fake_free_list_tail
last_block = tail.prev_free_block
assert last_block is not None, (
"prev_free_block of fake_free_list_tail should always exist"
)
@@ -455,8 +467,8 @@ class FreeKVCacheBlockQueue:
last_block = block
# Connect the last block of <blocks> to the fake tail
last_block.next_free_block = self.fake_free_list_tail
self.fake_free_list_tail.prev_free_block = last_block
last_block.next_free_block = tail
tail.prev_free_block = last_block
self.num_free_blocks += len(blocks)
@@ -736,6 +748,60 @@ def resolve_dcp_kv_cache_spec(spec: KVCacheSpec, dcp_world_size: int) -> KVCache
return replace(spec, block_size=block_size)
def partial_hash_hits_enabled(
kv_cache_groups: Sequence[KVCacheGroupSpec],
hash_block_size: int,
dcp_world_size: int = 1,
manager_classes: Sequence[type["SingleTypeKVCacheManager"]] | None = None,
) -> bool:
"""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.
"""
if not any(
isinstance(spec, MambaSpec)
and spec.mamba_cache_mode == "align"
and (
(dcp_world_size == 1 and spec.block_size > hash_block_size)
or (dcp_world_size > 1 and spec.block_size >= hash_block_size)
)
for group in kv_cache_groups
for spec in iter_layer_specs(group.kv_cache_spec)
):
return False
if manager_classes is None:
return True
unsupported_managers = {
manager_cls.__name__
for group, manager_cls in zip(kv_cache_groups, manager_classes)
if group.kv_cache_spec.prefix_cacheable
and not manager_cls.supports_fine_grained_hash_lookup
and resolve_dcp_kv_block_size(group.kv_cache_spec, dcp_world_size)
!= hash_block_size
}
if unsupported_managers:
logger.warning_once(
"Disabling fine-grained prefix-cache hits because these KV "
"cache managers require block-aligned lookups: %s.",
", ".join(sorted(unsupported_managers)),
)
return False
return True
def eagle_proof_margin(
block_size: int, hash_block_size: int, fine_grained_lookup: bool
) -> int:
"""Tokens an EAGLE group matches past a cache hit before dropping them.
Fine-grained lookups drop one hash unit; others drop one cache block.
"""
if fine_grained_lookup and block_size > hash_block_size:
return hash_block_size
return block_size
def resolve_kv_cache_block_sizes(
kv_cache_config: KVCacheConfig,
vllm_config: VllmConfig,
@@ -764,8 +830,7 @@ def resolve_kv_cache_block_sizes(
if groups and not groups[0].kv_cache_spec.dcp_sharded:
dcp = 1
bs = cache_config.block_size * dcp
# The Mamba prefill checkpoint builder reads prefix_match_unit directly,
# so a value dropped here puts its checkpoints off the scheduler's grid.
# Reject a prefix_match_unit that would otherwise be silently ignored.
if (
cache_config.prefix_match_unit not in (None, bs)
and len(groups) == 1
@@ -786,8 +851,8 @@ def resolve_kv_cache_block_sizes(
]
scheduler_block_size = math.lcm(*group_block_sizes)
logger.info("kv cache group sizes %s", group_block_sizes)
logger.info("kv lcm block sizes %s", scheduler_block_size)
logger.info_once("kv cache group sizes %s", tuple(group_block_sizes))
logger.info_once("kv lcm block sizes %s", scheduler_block_size)
# Block hashes are only consumed by prefix caching and KV connectors
# (P/D, offloading); when neither is active, keep hash_block_size equal
@@ -828,18 +893,10 @@ def resolve_kv_cache_block_sizes(
and isinstance(spec.tokens_per_state, int)
and spec.tokens_per_state > 1
}
has_partial_mamba_group = any(
isinstance(spec, MambaSpec)
and spec.mamba_cache_mode == "align"
and (
(dcp == 1 and block_size > hash_block_size)
or (dcp > 1 and block_size >= hash_block_size)
)
for group, block_size in zip(groups, group_block_sizes)
for spec in iter_layer_specs(group.kv_cache_spec)
)
cache_hit_alignment = (
hash_block_size if has_partial_mamba_group else scheduler_block_size
hash_block_size
if partial_hash_hits_enabled(groups, hash_block_size, dcp)
else scheduler_block_size
)
if any(cache_hit_alignment % alignment for alignment in prefix_alignments):
raise ValueError(
@@ -850,6 +907,38 @@ def resolve_kv_cache_block_sizes(
return scheduler_block_size, hash_block_size
def resolve_cache_hit_alignment_tokens(
kv_cache_config: KVCacheConfig,
vllm_config: VllmConfig,
scheduler_block_size: int,
hash_block_size: int,
) -> int:
"""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``.
"""
groups = kv_cache_config.kv_cache_groups
if not vllm_config.cache_config.enable_prefix_caching or len(groups) <= 1:
return scheduler_block_size
manager_classes = []
for group in groups:
manager_cls = KVCacheSpecRegistry.get_manager_class(
group.kv_cache_spec, group.role
)
assert manager_cls is not None
manager_classes.append(manager_cls)
if partial_hash_hits_enabled(
groups,
hash_block_size,
vllm_config.parallel_config.decode_context_parallel_size,
manager_classes,
):
return hash_block_size
return scheduler_block_size
def get_request_block_hasher(
hash_block_size: int,
caching_hash_fn: Callable[[Any], bytes],
+1 -1
View File
@@ -26,7 +26,7 @@ class PauseState(enum.IntEnum):
- UNPAUSED: Normal operation
- PAUSE_NEW: No new requests are scheduled, requests already in
running state are scheduled.
running state or holding KV blocks are scheduled.
- PAUSE_ALL: No requests are scheduled
"""
+135 -67
View File
@@ -147,9 +147,15 @@ class Scheduler(SchedulerInterface):
self.kv_events_config is not None
and self.kv_events_config.enable_kv_cache_events
)
# Diffusion models may not sample any tokens for a denoising step.
# Pooling and diffusion models do not append a sampled token after
# prefill, so they should not reserve one context slot while scheduling.
self.num_sampled_tokens_per_step = (
1 if not vllm_config.model_config.is_diffusion else 0
0
if (
vllm_config.model_config.runner_type == "pooling"
or vllm_config.model_config.is_diffusion
)
else 1
)
# Create KVConnector for the Scheduler. Note that each Worker
@@ -284,10 +290,14 @@ class Scheduler(SchedulerInterface):
# DSV41 SWA bounded replay: groups that declare a replay window are rebuilt
# after a prefix hit by recomputing its trailing tokens. One window
# for all such groups, so the rewind matches every group's allocation.
replay_windows = {
group.kv_cache_spec.prefix_replay_tokens
for group in kv_cache_config.kv_cache_groups
self.prefix_replay_group_ids = tuple(
group_id
for group_id, group in enumerate(kv_cache_config.kv_cache_groups)
if group.kv_cache_spec.prefix_replay_tokens > 0
)
replay_windows = {
kv_cache_config.kv_cache_groups[group_id].kv_cache_spec.prefix_replay_tokens
for group_id in self.prefix_replay_group_ids
}
assert len(replay_windows) <= 1, (
f"Prefix replay windows should agree: {sorted(replay_windows)}"
@@ -371,9 +381,8 @@ class Scheduler(SchedulerInterface):
or group.kv_cache_spec.num_prefill_checkpoint_blocks > 0
for group in kv_cache_config.kv_cache_groups
)
# A finer prefix_match_unit is configured: a mamba partial tail entry
# can only be registered by a step ending exactly at the prompt's last
# hash boundary, so the split adds that stop.
# Fine-grained hits reuse the prompt's hash-aligned Mamba checkpoint.
# Split there only if the backend cannot save it within the final chunk.
self.mamba_partial_cache_hit = (
self.need_mamba_block_aligned_split
and self.hash_block_size < self.block_size
@@ -450,14 +459,19 @@ class Scheduler(SchedulerInterface):
# The last block-aligned position whose state can be cached. With
# Eagle, FullAttn prunes the last matching block, so back off one
# block to avoid a Mamba cache miss.
last_cache_position = request.num_tokens - request.num_tokens % block_size
if self.use_eagle_block_drop:
last_cache_position = max(last_cache_position - block_size, 0)
ckpt_block_size = (
self.hash_block_size if self.mamba_partial_cache_hit else self.block_size
)
last_cache_position = get_mamba_prefill_checkpoint_position(
request.num_tokens,
block_size,
self.use_eagle_block_drop,
)
end = start + num_new_tokens
checkpoint_position = get_mamba_prefill_checkpoint_position(
prefill_end,
self.hash_block_size,
ckpt_block_size,
drop_eagle_block=self.use_eagle_block_drop,
)
use_internal_checkpoint = (
@@ -490,18 +504,14 @@ class Scheduler(SchedulerInterface):
next_block_boundary = (start // block_size + 1) * block_size
tail_boundary = (
request.num_prompt_tokens // self.hash_block_size * self.hash_block_size
get_mamba_prefill_checkpoint_position(
request.num_prompt_tokens,
self.hash_block_size,
self.use_eagle_block_drop,
)
if self.mamba_partial_cache_hit and not use_internal_checkpoint
else 0
)
if tail_boundary and self.use_eagle_block_drop:
# Eagle matches one hash unit past the candidate and drops it, so
# nothing proves the prompt's own last hash boundary. Materialize
# the state one unit lower, where the hit can actually land. Keyed on
# the block-drop bit, not plain use_eagle: this shift exists only to
# compensate for the drop, and the Mamba manager's matching gate
# reads the same bit (the coordinator is handed use_eagle_block_drop).
tail_boundary = max(tail_boundary - self.hash_block_size, 0)
junction = request.shared_prefix_boundary
# Block-floored: a sub-block junction's state is not separately cacheable.
block_floored = start + (junction - start) // block_size * block_size
@@ -522,8 +532,7 @@ class Scheduler(SchedulerInterface):
else 0,
# Never run past the last cacheable block boundary mid-chunk.
last_cache_position,
# Fine-grained hits: the prompt's partial-tail entry can only be
# registered by a chunk ending exactly at its last hash boundary.
# Stop at the prompt checkpoint unless the backend saves it internally.
tail_boundary
if last_cache_position < tail_boundary < request.num_prompt_tokens
else 0,
@@ -709,6 +718,7 @@ class Scheduler(SchedulerInterface):
# Schedule encoder inputs.
encoder_inputs_to_schedule = None
external_load_encoder_input: list[int] = []
duplicate_encoder_inputs: list[int] = []
new_encoder_compute_budget = encoder_compute_budget
if request.has_encoder_inputs:
(
@@ -716,6 +726,7 @@ class Scheduler(SchedulerInterface):
num_new_tokens,
new_encoder_compute_budget,
external_load_encoder_input,
duplicate_encoder_inputs,
) = self._try_schedule_encoder_inputs(
request,
request.num_computed_tokens,
@@ -856,17 +867,13 @@ class Scheduler(SchedulerInterface):
# Encoder-related.
if encoder_inputs_to_schedule:
scheduled_encoder_inputs[request_id] = encoder_inputs_to_schedule
# Allocate the encoder cache.
for i in encoder_inputs_to_schedule:
self.encoder_cache_manager.allocate(request, i)
if self.ec_connector is not None:
self.ec_connector.update_state_after_alloc(request, i)
encoder_compute_budget = new_encoder_compute_budget
if external_load_encoder_input:
for i in external_load_encoder_input:
self.encoder_cache_manager.allocate(request, i)
if self.ec_connector is not None:
self.ec_connector.update_state_after_alloc(request, i)
if encoder_inputs_to_schedule or external_load_encoder_input:
self._allocate_encoder_inputs(
request,
(encoder_inputs_to_schedule or []) + external_load_encoder_input,
duplicate_encoder_inputs,
)
# Record the LoRAs in scheduled_running_reqs
scheduled_loras: set[int] = set()
@@ -879,7 +886,7 @@ class Scheduler(SchedulerInterface):
assert len(scheduled_loras) <= self.lora_config.max_loras
# Next, schedule the WAITING requests.
if not preempted_reqs and self._pause_state == PauseState.UNPAUSED:
if not preempted_reqs and self._pause_state != PauseState.PAUSED_ALL:
step_skipped_waiting: deque[Request] = deque()
step_skipped_kv_holding: deque[Request] = deque()
@@ -892,8 +899,11 @@ class Scheduler(SchedulerInterface):
step_skipped_waiting.appendleft(request_to_skip)
while token_budget > 0:
# Requests holding KV blocks are always drained first.
request_queue = self.kv_holding_waiting or self.waiting
# Requests holding KV blocks are always drained first, and are
# the only ones admitted under PAUSED_NEW (e.g. async KV loads).
request_queue = self.kv_holding_waiting
if not request_queue and self._pause_state == PauseState.UNPAUSED:
request_queue = self.waiting
if not request_queue or input_budget <= draft_slots:
break
# Paused streaming sessions (WAITING_FOR_STREAMING_REQ) are not
@@ -969,14 +979,17 @@ class Scheduler(SchedulerInterface):
skip_request(request_queue)
continue
if self.prefix_replay_tokens:
# SWA bounded replay recomputes the hit's last
if self.prefix_replay_tokens and not (
ext_tokens and self._load_restores_replay_window(request)
):
# DSV41 SWA bounded replay recomputes the hit's last
# window, from the block holding its first
# token; the sliding-window groups retire
# whole blocks below the window of the hit's
# next token. Hits end on a block boundary, or
# a hit ending one token short of one would
# retire the block the replay starts in.
# retire the block the replay starts in. A load
# that carries the window replays nothing.
ext_tokens -= ext_tokens % self.block_size
load_kv_async = load_kv_async and ext_tokens > 0
@@ -1022,9 +1035,17 @@ class Scheduler(SchedulerInterface):
num_new_local_computed_tokens + num_external_computed_tokens
)
assert num_computed_tokens <= request.num_tokens
if 0 < num_computed_tokens <= self.prefix_replay_tokens:
# SWA bounded replay: a hit no longer than the replayed
# window would be recomputed in full and save nothing.
# DSV41 SWA bounded replay: a KV load that carries the
# window is taken as is; any other hit no longer than the
# replayed window would be recomputed in full and save
# nothing.
window_loaded = bool(
num_external_computed_tokens
) and self._load_restores_replay_window(request)
if (
not window_loaded
and 0 < num_computed_tokens <= self.prefix_replay_tokens
):
new_computed_blocks = (
self.kv_cache_manager.empty_kv_cache_blocks
)
@@ -1065,6 +1086,7 @@ class Scheduler(SchedulerInterface):
encoder_inputs_to_schedule = None
external_load_encoder_input = []
duplicate_encoder_inputs = []
new_encoder_compute_budget = encoder_compute_budget
pad_spec_decode = False
@@ -1086,7 +1108,7 @@ class Scheduler(SchedulerInterface):
if did_prefix_cache_lookup:
# Fresh admission: local and/or sync external hit.
num_replay_tokens = self._mark_prefix_replay(
request, num_computed_tokens
request, num_computed_tokens, window_loaded
)
num_computed_tokens -= num_replay_tokens
# Number of tokens to be scheduled.
@@ -1166,6 +1188,7 @@ class Scheduler(SchedulerInterface):
num_new_tokens,
new_encoder_compute_budget,
external_load_encoder_input,
duplicate_encoder_inputs,
) = self._try_schedule_encoder_inputs(
request,
num_computed_tokens,
@@ -1261,10 +1284,20 @@ class Scheduler(SchedulerInterface):
self.connector_prefix_cache_stats is not None
and connector_prefix_cache_queries != 0
):
preempted = request.num_preemptions > 0
self.connector_prefix_cache_stats.record(
num_tokens=connector_prefix_cache_queries,
num_hits=connector_prefix_cache_hits,
preempted=request.num_preemptions > 0,
preempted=preempted,
# The connector knows the tier only after the load
# plan above exists.
hits_by_source=(
self.connector.get_external_cache_hit_sources(
request, connector_prefix_cache_hits
)
if connector_prefix_cache_hits and not preempted
else None
),
)
# Record at admission so unscheduled lookups are not counted.
@@ -1335,18 +1368,14 @@ class Scheduler(SchedulerInterface):
# Encoder-related.
if encoder_inputs_to_schedule:
scheduled_encoder_inputs[request_id] = encoder_inputs_to_schedule
# Allocate the encoder cache.
for i in encoder_inputs_to_schedule:
self.encoder_cache_manager.allocate(request, i)
if self.ec_connector is not None:
self.ec_connector.update_state_after_alloc(request, i)
encoder_compute_budget = new_encoder_compute_budget
# Allocate for external load encoder cache
if external_load_encoder_input:
for i in external_load_encoder_input:
self.encoder_cache_manager.allocate(request, i)
if self.ec_connector is not None:
self.ec_connector.update_state_after_alloc(request, i)
if encoder_inputs_to_schedule or external_load_encoder_input:
self._allocate_encoder_inputs(
request,
(encoder_inputs_to_schedule or [])
+ external_load_encoder_input,
duplicate_encoder_inputs,
)
# re-queue requests skipped in this pass ahead of older skipped items.
if step_skipped_kv_holding:
@@ -1632,6 +1661,7 @@ class Scheduler(SchedulerInterface):
session.num_prompt_tokens : num_computed_tokens
]
del session._all_token_ids[num_computed_tokens:]
del session.block_hashes[num_computed_tokens // self.hash_block_size :]
session._output_token_ids.clear()
assert session.prompt_token_ids is not None
# Extend prompt with kept output tokens.
@@ -1742,6 +1772,20 @@ class Scheduler(SchedulerInterface):
self.encoder_cache_mismatch_reqs.add(request.request_id)
return True
def _allocate_encoder_inputs(
self,
request: Request,
input_ids: list[int],
duplicate_input_ids: list[int],
) -> None:
for input_id in input_ids:
self.encoder_cache_manager.allocate(request, input_id)
if self.ec_connector is not None:
self.ec_connector.update_state_after_alloc(request, input_id)
for input_id in duplicate_input_ids:
self.encoder_cache_manager.check_and_update_cache(request, input_id)
def _try_schedule_encoder_inputs(
self,
request: Request,
@@ -1749,7 +1793,7 @@ class Scheduler(SchedulerInterface):
num_new_tokens: int,
encoder_compute_budget: int,
shift_computed_tokens: int = 0,
) -> tuple[list[int], int, int, list[int]]:
) -> tuple[list[int], int, int, list[int], list[int]]:
"""Determine which encoder inputs need to be scheduled in the current step,
and update `num_new_tokens` and encoder token budget accordingly.
@@ -1770,12 +1814,13 @@ class Scheduler(SchedulerInterface):
blocks and externally cached blocks (via KVConnector).
"""
if num_new_tokens == 0 or not request.has_encoder_inputs:
return [], num_new_tokens, encoder_compute_budget, []
return [], num_new_tokens, encoder_compute_budget, [], []
encoder_inputs_to_schedule: list[int] = []
mm_features = request.mm_features
assert mm_features is not None
assert len(mm_features) > 0
external_load_encoder_input = []
duplicate_encoder_inputs = []
# NOTE: since scheduler operates on the request level (possibly with
# multiple encoder inputs per request), we need to create temporary
@@ -1832,9 +1877,10 @@ class Scheduler(SchedulerInterface):
scheduled_num_encoder_embeds,
num_encoder_embeds,
):
return [], 0, encoder_compute_budget, []
return [], 0, encoder_compute_budget, [], []
# The same encoder input has already been scheduled in the
# current step.
duplicate_encoder_inputs.append(i)
continue
cached_num_encoder_embeds = (
@@ -1849,7 +1895,7 @@ class Scheduler(SchedulerInterface):
num_encoder_embeds,
)
):
return [], 0, encoder_compute_budget, []
return [], 0, encoder_compute_budget, [], []
if self.encoder_cache_manager.check_and_update_cache(request, i):
# The encoder input is already computed and cached from a
@@ -1925,6 +1971,7 @@ class Scheduler(SchedulerInterface):
num_new_tokens,
encoder_compute_budget,
external_load_encoder_input,
duplicate_encoder_inputs,
)
def _make_scheduled_encoder_input_stats(
@@ -2757,7 +2804,8 @@ class Scheduler(SchedulerInterface):
return 0
num_running, num_waiting = self.get_request_counts()
if self._pause_state == PauseState.PAUSED_NEW:
return num_running
# Requests holding KV blocks still drain; queued ones stay queued.
num_waiting = len(self.kv_holding_waiting)
num_waiting -= self.num_waiting_for_streaming_input
return num_waiting + num_running
@@ -3053,16 +3101,31 @@ class Scheduler(SchedulerInterface):
self._request_remaining_blocks(req) for req in self._inflight_prefills
)
def _mark_prefix_replay(self, request: Request, num_hit_tokens: int) -> int:
def _load_restores_replay_window(self, request: Request) -> bool:
"""Whether the KV connector's load for ``request`` restores every DSV41
SWA bounded-replay group, as a P/D transfer of the request's own blocks
does; a prefix-cache store holds no window."""
assert self.connector is not None
return bool(self.prefix_replay_group_ids) and set(
self.prefix_replay_group_ids
).issubset(self.connector.get_loaded_kv_cache_group_ids(request))
def _mark_prefix_replay(
self, request: Request, num_hit_tokens: int, window_loaded: bool
) -> int:
"""Record where a prefix hit's replay starts and return the number of
hit tokens to recompute; the caller rewinds the computed count by it.
The replayed tokens are the hit's last window (see
``Request.replay_start``): the worker rebuilds their sliding-window KV
and leaves their cached KV alone.
and leaves their cached KV alone. A hit whose KV load carries the
window replays nothing.
"""
if not self.prefix_replay_tokens:
return 0
if window_loaded:
request.replay_start = 0
return 0
num_replay_tokens = min(self.prefix_replay_tokens, num_hit_tokens)
request.replay_start = num_hit_tokens - num_replay_tokens
return num_replay_tokens
@@ -3076,7 +3139,8 @@ class Scheduler(SchedulerInterface):
"""
assert self.connector is not None
if request.request_id in self.failed_recving_kv_req_ids:
load_failed = request.request_id in self.failed_recving_kv_req_ids
if load_failed:
# Request had KV load failures; num_computed_tokens was already
# updated in _update_requests_with_invalid_blocks
if request.num_computed_tokens:
@@ -3102,11 +3166,15 @@ class Scheduler(SchedulerInterface):
# This will cache the blocks iff caching is enabled.
self.kv_cache_manager.cache_blocks(request, request.num_computed_tokens)
# SWA bounded replay recomputes the tail of the hit, which covers the
# last token; otherwise a full prompt hit re-computes that token so the
# next one can be sampled.
# DSV41 SWA bounded replay recomputes the tail of a hit loaded without
# its window, or of a failed load, which may have lost it; the replay
# covers the last token. Otherwise a full prompt hit re-computes that
# token so the next one can be sampled.
num_replay_tokens = self._mark_prefix_replay(
request, request.num_computed_tokens
request,
request.num_computed_tokens,
window_loaded=not load_failed
and self._load_restores_replay_window(request),
)
if num_replay_tokens > 0:
request.num_computed_tokens -= num_replay_tokens
+41 -31
View File
@@ -876,7 +876,14 @@ class FullAttentionManager(SingleTypeKVCacheManager):
block are intentionally skipped.
"""
hash_block_size = self.block_pool.hash_block_size
boundary_tokens = request.num_prompt_tokens // hash_block_size * hash_block_size
# A resend matches at most `prompt_len - 1` tokens, but EAGLE lookups
# read the whole prompt before dropping a hash unit.
token_limit = (
request.num_prompt_tokens
if self.use_eagle
else request.num_prompt_tokens - 1
)
boundary_tokens = token_limit // hash_block_size * hash_block_size
if boundary_tokens == 0 or boundary_tokens > num_tokens:
return
if boundary_tokens % self.block_size == 0:
@@ -1797,7 +1804,7 @@ class MambaManager(SingleTypeKVCacheManager):
# is kept, so `prefill_end` skips reserving blocks for the others.
checkpoint_position = get_mamba_prefill_checkpoint_position(
num_tokens,
self.block_pool.hash_block_size,
self.cache_hit_alignment_tokens,
self.drop_eagle_checkpoint_block,
)
if not self._needs_internal_checkpoint(
@@ -1821,7 +1828,7 @@ class MambaManager(SingleTypeKVCacheManager):
if num_new_blocks > 0:
blocks_allocated = request_id in self._allocated_block_reqs
physical_block_cap = 1 + int(has_partial_hit) + checkpoint_block
if not blocks_allocated or checkpoint_block:
if not blocks_allocated:
physical_block_cap += self.num_speculative_blocks
num_new_blocks = min(num_new_blocks, physical_block_cap)
@@ -1894,12 +1901,14 @@ class MambaManager(SingleTypeKVCacheManager):
[self._null_block for _ in range(prev_block_len, null_end)]
)
if blocks_allocated and not checkpoint_block:
# Relocate exclusively owned speculative scratch blocks.
if blocks_allocated:
# Relocate exclusively owned scratch blocks this step leaves
# behind. In a checkpoint step, one at the checkpoint index
# stays: the worker exports the checkpoint into that column.
for block_idx in range(
prev_block_len - self.num_speculative_blocks, prev_block_len
):
if block_idx < num_skipped_blocks:
if block_idx < num_skipped_blocks - checkpoint_block:
self._relocate_speculative_block(req_blocks, block_idx)
else:
break
@@ -1907,7 +1916,7 @@ class MambaManager(SingleTypeKVCacheManager):
if has_partial_hit:
num_new_blocks = max(num_new_blocks, 0) + 1
max_new_blocks = 1 + int(has_partial_hit) + checkpoint_block
if not blocks_allocated or checkpoint_block:
if not blocks_allocated:
max_new_blocks += self.num_speculative_blocks
assert num_new_blocks <= max_new_blocks
new_blocks = self.block_pool.get_new_blocks(num_new_blocks)
@@ -2080,20 +2089,29 @@ class MambaManager(SingleTypeKVCacheManager):
checkpoint_position
== get_mamba_prefill_checkpoint_position(
request.num_prompt_tokens,
hash_block_size,
self.cache_hit_alignment_tokens,
self.drop_eagle_checkpoint_block,
)
)
is_retained_checkpoint = False
if checkpoint_position % self.block_size == 0:
block_idx = checkpoint_position // self.block_size - 1
retained = self.reachable_block_mask(
block_idx,
block_idx + 1,
self.cache_hit_alignment_tokens,
self.kv_cache_spec,
self.drop_eagle_checkpoint_block,
retention_interval=retention_interval,
)
is_retained_checkpoint = retained is None or retained[0]
if (
retention_interval == 0
and num_tokens < request.num_prompt_tokens
and not is_prompt_checkpoint
not is_prompt_checkpoint
and not is_retained_checkpoint
and checkpoint_position != request.shared_prefix_boundary
):
# retention_interval == 0 keeps this transient checkpoint
# request-local. The slot may carry a hash from this step's
# full-block pass; that must go too, since the checkpoint
# state is about to overwrite the block.
# The transient state overwrites this slot, so neither it nor
# the full-block hash registered earlier this step is reusable.
self.block_pool._maybe_evict_cached_block(checkpoint_block)
return None
if checkpoint_block.block_hash_num_tokens == checkpoint_position:
@@ -2106,21 +2124,13 @@ class MambaManager(SingleTypeKVCacheManager):
block_size=self.block_size,
replace_existing_hashes=True,
)
if self.block_size == hash_block_size:
if num_tokens <= 0 or num_tokens % hash_block_size != 0:
return None
if num_tokens % self.block_size == 0:
return None
if num_tokens % hash_block_size != 0:
return None
latest_prompt_hash_boundary = (
request.num_prompt_tokens // hash_block_size
) * hash_block_size
if self.drop_eagle_checkpoint_block:
# Eagle groups match one hash unit past the candidate and drop it,
# so register the tail one unit lower.
latest_prompt_hash_boundary = max(
latest_prompt_hash_boundary - hash_block_size, 0
)
latest_prompt_hash_boundary = get_mamba_prefill_checkpoint_position(
request.num_prompt_tokens,
hash_block_size,
self.drop_eagle_checkpoint_block,
)
# The junction is the other position a sibling resumes at: where one was
# observed to stop, and where the scheduler already ends a chunk. Bounded
# to the prompt chunk being computed -- during decode the target is the
@@ -2133,7 +2143,7 @@ class MambaManager(SingleTypeKVCacheManager):
):
return None
block_idx = num_tokens // self.block_size
block_idx = cdiv(num_tokens, self.block_size) - 1
blocks = self.req_to_blocks[request.request_id]
if block_idx >= len(blocks):
return None
@@ -2148,7 +2158,7 @@ class MambaManager(SingleTypeKVCacheManager):
kv_cache_group_id=self.kv_cache_group_id,
block_size=self.block_size,
)
if partial_hash is not None:
if partial_hash is not None and num_tokens % self.block_size:
self._partial_hit_reqs[request.request_id] = (block_idx, source_block)
self.num_cached_block[request.request_id] = block_idx
# Producer of this partial tail: the boundary state currently lives