Merge remote-tracking branch 'upstream/main' into patches

Signed-off-by: MOVZX <movzx@yahoo.com>
This commit is contained in:
2026-10-03 21:59:03 +07:00
1012 changed files with 61873 additions and 14499 deletions
+3 -2
View File
@@ -25,6 +25,7 @@ from vllm.v1.core.kv_cache_utils import (
make_block_hash_with_group_id,
maybe_convert_block_hash,
resolve_block_hashes,
to_event_extra_keys,
)
from vllm.v1.request import Request
@@ -367,7 +368,7 @@ class BlockPool:
lora_id=request.lora_request.adapter_id if request.lora_request else None,
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,
extra_keys=to_event_extra_keys(extra_keys_list),
group_idx=kv_cache_group_id,
session_id=request.session_id,
)
@@ -557,7 +558,7 @@ class BlockPool:
lora_name=request.lora_request.name
if request.lora_request
else None,
extra_keys=[extra_keys],
extra_keys=to_event_extra_keys([extra_keys]),
group_idx=kv_cache_group_id,
session_id=request.session_id,
)
+9
View File
@@ -174,6 +174,7 @@ class KVCacheCoordinator(ABC):
num_local_computed_tokens: int,
num_tokens_main_model: int,
apply_admission_cap: bool = False,
prefill_end: int = 0,
) -> int:
"""Get the number of device blocks needed to be allocated for the request.
@@ -195,12 +196,19 @@ class KVCacheCoordinator(ABC):
per-request admission cap (SWA / chunked-local). Set only by
the full-sequence admission gate; per-step allocation must
leave it False so the predictor matches `allocate_new_blocks`.
prefill_end: The token index the request's prefill ends at, the
same value the scheduler splits chunks against. Under sparse
retention Mamba reserves a prefill checkpoint only on the chunk
reaching it; under dense retention every chunk publishes a
state, so it is ignored (0).
Returns:
The number of blocks to allocate.
"""
num_blocks_to_allocate = 0
if self.retention_interval != 0:
prefill_end = 0
for i, manager in enumerate(self.single_type_managers):
if isinstance(manager, CrossAttentionManager):
# For cross-attention, we issue a single static allocation
@@ -223,6 +231,7 @@ class KVCacheCoordinator(ABC):
num_local_computed_tokens,
num_tokens_main_model,
apply_admission_cap=apply_admission_cap,
prefill_end=prefill_end,
)
return num_blocks_to_allocate
+6
View File
@@ -512,6 +512,10 @@ class KVCacheManager:
):
watermark_blocks = self.watermark_blocks
# Matches the scheduler's own prefill boundary: `num_tokens - 1`
# extends it to resumed requests replaying their output tokens.
prefill_end = max(request.num_prompt_tokens, request.num_tokens - 1)
if full_sequence_must_fit:
# First check and fail if the full request sequence won't fit.
full_num_tokens = min(request.num_tokens, self.max_model_len)
@@ -525,6 +529,7 @@ class KVCacheManager:
num_local_computed_tokens=num_local_computed_tokens,
num_tokens_main_model=full_num_tokens,
apply_admission_cap=True,
prefill_end=prefill_end,
)
required_blocks = num_blocks_to_allocate + watermark_blocks
if required_blocks > self.block_pool.get_num_free_blocks():
@@ -559,6 +564,7 @@ class KVCacheManager:
+ num_external_computed_tokens,
num_local_computed_tokens=num_local_computed_tokens,
num_tokens_main_model=num_tokens_main_model,
prefill_end=prefill_end,
)
# Keep `reserved_blocks` free for other in-flight sequences, and an
+102 -25
View File
@@ -9,7 +9,7 @@ import os
from collections import defaultdict
from collections.abc import Callable, Iterable, Iterator, Sequence
from dataclasses import dataclass, field, replace
from functools import partial
from functools import partial, reduce
from typing import TYPE_CHECKING, Any, NamedTuple, NewType, TypeAlias, cast, overload
from vllm import envs
@@ -21,7 +21,6 @@ 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,
@@ -502,8 +501,8 @@ def _gen_mm_extra_hash_keys(
) -> tuple[list[Any], int]:
"""Generate extra keys related to MultiModal request for block hash
computation. For multi-modal inputs, the extra keys are
(mm_hash, start_offset) that indicate a mm input contained in the
block and its starting offset in the block tokens.
("mm", mm_hash, start_offset) tuples that indicate a mm input contained
in the block and its starting offset in the block tokens.
Args:
request: The request object.
@@ -549,7 +548,7 @@ def _gen_mm_extra_hash_keys(
# relative to the start of the block so prefix-cache keys stay
# distinct when the same MM item appears at different positions
# within otherwise-identical placeholder blocks.
extra_keys.append((mm_feature.identifier, offset - start_token_idx))
extra_keys.append(("mm", mm_feature.identifier, offset - start_token_idx))
if end_token_idx >= offset + length:
# If this block contains the end of the current mm input,
@@ -565,25 +564,29 @@ def _gen_mm_extra_hash_keys(
return extra_keys, curr_mm_idx
def _gen_lora_extra_hash_keys(request: Request) -> list[str]:
def _gen_lora_extra_hash_keys(request: Request) -> list[tuple[str, str, str]]:
"""Generate extra keys related to LoRA for block hash computation.
The adapter path is included so that re-pointing a LoRA name at a different
adapter does not reuse KV computed with the previous one.
Args:
request: The request object.
Returns:
Return LoRA name of the request if it is a LoRA request. Return empty
list otherwise.
Return the LoRA name and path of the request if it is a LoRA request.
Return empty list otherwise.
"""
if not request.lora_request:
lora_request = request.lora_request
if not lora_request:
return []
return [request.lora_request.lora_name]
return [("lora", lora_request.lora_name, lora_request.lora_path)]
def _gen_prompt_embeds_extra_hash_keys(
request: Request, start_token_idx: int, end_token_idx: int
) -> list[bytes]:
) -> list[tuple[str, bytes]]:
"""Generate extra keys related to prompt embeds for block hash computation.
Args:
@@ -605,7 +608,7 @@ def _gen_prompt_embeds_extra_hash_keys(
# Hash prompt embeds once per block and cache on request
embeds_hash = hashlib.sha256(tensor_data(block_prompt_embeds)).digest()
request._prompt_embeds_per_block_hashes[block_range] = embeds_hash
return [embeds_hash]
return [("prompt_embeds", embeds_hash)]
def generate_block_hash_extra_keys(
@@ -629,9 +632,11 @@ def generate_block_hash_extra_keys(
mm_extra_keys, new_start_mm_idx = _gen_mm_extra_hash_keys(
request, start_token_idx, end_token_idx, start_mm_idx
)
lora_extra_keys: list[str] = _gen_lora_extra_hash_keys(request)
cache_salt_keys: list[str] = (
[request.cache_salt] if (start_token_idx == 0 and request.cache_salt) else []
lora_extra_keys = _gen_lora_extra_hash_keys(request)
cache_salt_keys: list[tuple[str, str]] = (
[("cache_salt", request.cache_salt)]
if (start_token_idx == 0 and request.cache_salt)
else []
)
prompt_embeds_keys = _gen_prompt_embeds_extra_hash_keys(
request, start_token_idx, end_token_idx
@@ -647,6 +652,35 @@ def generate_block_hash_extra_keys(
return tuple(extra_keys), new_start_mm_idx
def to_event_extra_keys(
extra_keys: Iterable[tuple[Any, ...] | None] | None,
) -> list[tuple[Any, ...] | None] | None:
"""Convert block-hash extra keys to the untagged per-block list published
in KV events.
External KV event consumers parse the pre-tagging shapes: bare LoRA names
and cache salts, ``(mm_identifier, offset)`` pairs and bare prompt-embeds
digests. Events keep that format until consumers handle the tagged keys.
Args:
extra_keys: One entry per block, each as returned by
`generate_block_hash_extra_keys`, or None.
Returns:
One untagged entry per block, or None if there are no entries.
"""
if not extra_keys:
return None
event_keys = [
None
if keys is None
else tuple(key[1:] if key[0] == "mm" else key[1] for key in keys)
for keys in extra_keys
]
return event_keys or None
def hash_block_tokens(
hash_function: Callable[[Any], bytes],
parent_block_hash: BlockHash | None,
@@ -714,7 +748,9 @@ def resolve_kv_cache_block_sizes(
group's effective block size. Attention groups are scaled by DCP;
Mamba groups keep their full per-rank state and are not scaled.
- ``hash_block_size`` is the granularity at which ``Request.block_hashes``
is computed. Single group: equals scheduler block size. Multiple groups:
is computed. Single group: equals scheduler block size, and any other
``cache_config.prefix_match_unit`` is rejected while block hashing is
active. Multiple groups:
``cache_config.prefix_match_unit`` override if set, else the GCD of
group block sizes; every group's block size must be divisible by it.
Returns the scheduler block size (i.e. disables finer hashing) if block
@@ -728,6 +764,21 @@ 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.
if (
cache_config.prefix_match_unit not in (None, bs)
and len(groups) == 1
and (
cache_config.enable_prefix_caching
or vllm_config.kv_transfer_config is not None
)
):
raise ValueError(
f"Invalid prefix_match_unit={cache_config.prefix_match_unit}; "
"with a single KV cache group, prefix-cache hits land on the "
f"block size ({bs}). Unset it or set it to {bs}."
)
return bs, bs
group_block_sizes = [
@@ -1103,7 +1154,9 @@ def _pool_bytes_per_block(kv_cache_groups: list[KVCacheGroupSpec]) -> int:
`available_memory` into `num_blocks`. Used to compute the effective KV cache
capacity once `num_gpu_blocks_override` is applied.
"""
return _get_kv_cache_bytes_per_block(kv_cache_groups)
return _get_kv_cache_bytes_per_block(
[group for group in kv_cache_groups if not group.host_resident]
)
def get_uniform_page_size(kv_cache_specs: Iterable[KVCacheSpec]) -> int:
@@ -2361,6 +2414,26 @@ def get_kv_cache_groups(
return groups
def _layer_tp_replicas(spec: KVCacheSpec, tp_size: int, dcp_size: int) -> int:
if not isinstance(spec, AttentionSpec) or spec.max_tp_shards is None:
return 1
if spec.dcp_sharded and dcp_size > 1:
return 1
return max(1, tp_size // spec.max_tp_shards)
def kv_cache_groups_tp_replicas(
groups: list[KVCacheGroupSpec], tp_size: int, dcp_size: int = 1
) -> int:
"""Consecutive TP ranks holding identical KV for every layer."""
specs = [spec for g in groups for spec in iter_layer_specs(g.kv_cache_spec)]
if not specs:
return 1
return reduce(
math.gcd, (_layer_tp_replicas(s, tp_size, dcp_size) for s in specs), tp_size
)
def generate_scheduler_kv_cache_config(
kv_cache_configs: list[KVCacheConfig],
) -> KVCacheConfig:
@@ -2428,12 +2501,10 @@ def _max_memory_usage_bytes_from_groups(
Each group independently claims blocks from the shared pool, so a request consumes
the sum of the per-group block counts, i.e. ``bytes_per_block * total_blocks``.
"""
kv_cache_groups = [group for group in kv_cache_groups if not group.host_resident]
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,
@@ -2491,12 +2562,11 @@ def _estimate_max_model_len_from_groups(
vllm_config.model_config.max_model_len = model_len
if hisparse_enabled:
try:
config = get_kv_cache_config_from_groups(
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
@@ -2606,6 +2676,9 @@ def _project_kv_cache_groups_to_worker(
worker_layer_names = [
layer_name for layer_name in group.layer_names if layer_name in worker_spec
]
if len(worker_layer_names) == len(group.layer_names):
projected_groups.append(group)
continue
group_spec = group.kv_cache_spec
if worker_layer_names and isinstance(group_spec, UniformTypeKVCacheSpecs):
group_spec = UniformTypeKVCacheSpecs(
@@ -2721,9 +2794,6 @@ 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.
@@ -2775,6 +2845,13 @@ def get_kv_cache_configs(
vllm_config, groups, min_num_blocks * _pool_bytes_per_block(groups)
)
for kv_cache_config in kv_cache_configs:
kv_cache_config.kv_tp_replicas = kv_cache_groups_tp_replicas(
kv_cache_config.kv_cache_groups,
vllm_config.parallel_config.tensor_parallel_size,
vllm_config.parallel_config.decode_context_parallel_size,
)
return kv_cache_configs
+19 -8
View File
@@ -1,15 +1,11 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Async scheduling for diffusion requests.
These rules live here so Scheduler.schedule() and AsyncScheduler stay
unchanged. VllmConfig selects this class for a diffusion model under async
scheduling. A sync scheduler creates no output placeholders, which both rules
read.
"""
"""Canvas-width handling and async read deferral for diffusion requests."""
from vllm.v1.core.sched.async_scheduler import AsyncScheduler
from vllm.v1.core.sched.output import SchedulerOutput
from vllm.v1.core.sched.scheduler import Scheduler
from vllm.v1.outputs import DraftTokenIds
from vllm.v1.request import Request
@@ -38,7 +34,22 @@ def _read_in_flight(request: Request, width: int) -> bool:
return request.num_output_placeholders >= steps * width
class DiffusionAsyncScheduler(AsyncScheduler):
class DiffusionScheduler(Scheduler):
def update_draft_token_ids(self, draft_token_ids: DraftTokenIds) -> None:
for i, (req_id, token_ids) in enumerate(
zip(draft_token_ids.req_ids, draft_token_ids.draft_token_ids)
):
request = self.requests.get(req_id)
if request is None:
continue
width = diffusion_canvas_width(request, self.num_spec_tokens)
# Remove padded positions before the base scheduler validates grammar.
if len(token_ids) > width:
draft_token_ids.draft_token_ids[i] = token_ids[:width]
super().update_draft_token_ids(draft_token_ids)
class DiffusionAsyncScheduler(DiffusionScheduler, AsyncScheduler):
def schedule(self, throttle_prefills: bool = False) -> SchedulerOutput:
for request in self.running:
width = diffusion_canvas_width(request, self.num_spec_tokens)
+5
View File
@@ -335,3 +335,8 @@ class GrammarOutput:
structured_output_request_ids: list[str]
# Bitmask ordered as structured_output_request_ids.
grammar_bitmask: "npt.NDArray[np.int32]"
# Per request, ordered as structured_output_request_ids: how many leading
# drafts the bitmask constrained. `grammar_bitmask` fills every row after
# the first -1 placeholder with the all-permissive `_full_mask`, so drafts
# from this index on must not be accepted. None invalidates every draft.
num_acceptable_drafts: list[int] | None = None
+45 -11
View File
@@ -62,6 +62,10 @@ from vllm.v1.kv_cache_interface import (
)
from vllm.v1.metrics.perf import ModelMetrics, PerfStats
from vllm.v1.metrics.stats import (
KV_FETCH_COMPLETED_WAITING,
KV_FETCH_IN_PROGRESS,
KV_FETCH_STAGES,
KV_FETCH_WAITING_TO_START,
PrefixCacheStats,
RequestSpecDecodeMetrics,
SchedulerStats,
@@ -71,6 +75,7 @@ from vllm.v1.request import Request, RequestStatus, StreamingUpdate
from vllm.v1.spec_decode.dynamic.utils import build_dynamic_sd_schedule_lookup
from vllm.v1.spec_decode.metrics import SpecDecodingStats
from vllm.v1.structured_output import StructuredOutputManager
from vllm.v1.structured_output.utils import strip_speculative_padding
from vllm.v1.utils import record_function_or_nullcontext
logger = init_logger(__name__)
@@ -411,6 +416,13 @@ class Scheduler(SchedulerInterface):
# async KV loads). Their remaining-block reservation gates async loads.
self._inflight_prefills: set[Request] = set()
# Requests with an async KV load, by stage (KV_FETCH_STAGES).
# None when not tracked (stats disabled or no KV connector).
self._kv_fetch_stages: dict[Request, str] | None = (
{} if self.log_stats and self.connector is not None else None
)
self._kv_fetch_counts: dict[str, int] = dict.fromkeys(KV_FETCH_STAGES, 0)
def _mamba_block_aligned_split(
self,
request: Request,
@@ -1038,6 +1050,9 @@ class Scheduler(SchedulerInterface):
num_local_cached_tokens=num_new_local_computed_tokens,
num_external_cached_tokens=num_external_computed_tokens,
)
self._set_kv_fetch_stage(
request, KV_FETCH_WAITING_TO_START if load_kv_async else None
)
else:
# KVTransfer: WAITING reqs have num_computed_tokens > 0
# after async KV recvs are completed. A streaming-input
@@ -1115,6 +1130,7 @@ class Scheduler(SchedulerInterface):
if (
not self.scheduler_config.enable_chunked_prefill
and num_new_tokens > request_token_budget
and not self.is_mm_encoder_only
):
# If chunked_prefill is disabled,
# we can stop the scheduling here.
@@ -1274,6 +1290,7 @@ class Scheduler(SchedulerInterface):
# only the successfully loaded tokens.
request.num_computed_tokens = num_computed_tokens
self._inflight_prefills.add(request)
self._set_kv_fetch_stage(request, KV_FETCH_IN_PROGRESS)
if self.needs_kv_cache_zeroing:
# Skip zeroing of the blocks the async load will
# overwrite; the zeroing could race the write.
@@ -1314,6 +1331,7 @@ class Scheduler(SchedulerInterface):
input_budget -= num_new_tokens + draft_slots
request.status = RequestStatus.RUNNING
request.num_computed_tokens = num_computed_tokens
self._set_kv_fetch_stage(request, None)
if pad_spec_decode:
assert num_new_tokens == 1 + self.num_spec_tokens
scheduled_spec_decode_tokens[request_id] = [
@@ -1962,7 +1980,14 @@ class Scheduler(SchedulerInterface):
structured_output_request_ids,
scheduler_output.scheduled_spec_decode_tokens,
)
return GrammarOutput(structured_output_request_ids, bitmask)
spec_tokens = scheduler_output.scheduled_spec_decode_tokens
num_acceptable_drafts = [
len(strip_speculative_padding(spec_tokens.get(req_id, [])))
for req_id in structured_output_request_ids
]
return GrammarOutput(
structured_output_request_ids, bitmask, num_acceptable_drafts
)
def update_from_output(
self,
@@ -2579,6 +2604,11 @@ class Scheduler(SchedulerInterface):
)
if self.connector is not None:
self.connector.on_new_request(request)
kv_transfer_params = request.kv_transfer_params
if kv_transfer_params and kv_transfer_params.get("do_remote_prefill"):
# Count P/D requests on arrival: connector matching is
# skipped while all run slots are taken.
self._set_kv_fetch_stage(request, KV_FETCH_WAITING_TO_START)
if self.log_stats:
request.record_event(EngineCoreEventType.QUEUED)
@@ -2655,6 +2685,7 @@ class Scheduler(SchedulerInterface):
if self.aux_output_connector is not None:
self.aux_output_connector.request_finished(request)
self._inflight_prefills.discard(request)
self._set_kv_fetch_stage(request, None)
connector_delay_free_blocks, kv_xfer_params = self._connector_finished(request)
# EC Connector: mirror the KV hook. The contract requires firing
@@ -2781,16 +2812,6 @@ class Scheduler(SchedulerInterface):
Otherwise, this method will only reset the KV prefix cache when there
is no running requests taking KV cache.
"""
if reset_running_requests and self.aux_output_connector is not None:
if self._pause_state != PauseState.PAUSED_ALL:
raise RuntimeError(
"AuxOutput Connector only supports resetting running requests "
"after pause(mode='keep')."
)
if any(request.num_in_flight_tokens for request in self.requests.values()):
raise RuntimeError(
"AuxOutput Connector cannot reset while model output is in flight."
)
if reset_running_requests:
# For logging.
timestamp = time.monotonic()
@@ -2890,6 +2911,7 @@ class Scheduler(SchedulerInterface):
num_running_reqs=num_running,
num_waiting_reqs=num_waiting - num_deferred,
num_skipped_waiting_reqs=num_deferred,
num_kv_fetch_reqs_by_stage=self._kv_fetch_counts.copy(),
kv_cache_usage=self.kv_cache_manager.usage,
prefix_cache_stats=prefix_cache_stats,
connector_prefix_cache_stats=connector_prefix_cache_stats,
@@ -3012,6 +3034,7 @@ class Scheduler(SchedulerInterface):
num_local_computed_tokens=request.num_computed_tokens,
num_tokens_main_model=full_num_tokens,
apply_admission_cap=True,
prefill_end=max(request.num_prompt_tokens, request.num_tokens - 1),
)
return num_blocks + self._spec_decode_step_blocks()
@@ -3028,6 +3051,16 @@ class Scheduler(SchedulerInterface):
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
if kv_fetch_stages is not None:
prev_stage = kv_fetch_stages.pop(request, None)
if prev_stage is not None:
self._kv_fetch_counts[prev_stage] -= 1
if stage is not None:
kv_fetch_stages[request] = stage
self._kv_fetch_counts[stage] += 1
def _inflight_prefill_reserved_blocks(self) -> int:
"""Num blocks in-flight prefills still need to finish (their reservation)."""
return sum(
@@ -3148,6 +3181,7 @@ class Scheduler(SchedulerInterface):
req = self.requests[req_id]
if req.status == RequestStatus.WAITING_FOR_REMOTE_KVS:
self.finished_recving_kv_req_ids.add(req_id)
self._set_kv_fetch_stage(req, KV_FETCH_COMPLETED_WAITING)
else:
assert RequestStatus.is_finished(req.status)
self._free_blocks(self.requests[req_id])
+54 -63
View File
@@ -112,7 +112,7 @@ class SingleTypeKVCacheManager(ABC):
self.kv_cache_spec = kv_cache_spec
self.block_pool = block_pool
self.enable_caching = enable_caching
self._max_admission_blocks_per_request = max_admission_blocks_per_request
self.max_admission_blocks_per_request = max_admission_blocks_per_request
# Record newly allocated block ids only when worker-side zeroing will
# consume them and this manager holds a spec type that gets zeroed.
self._record_new_block_ids = (
@@ -184,6 +184,7 @@ class SingleTypeKVCacheManager(ABC):
num_local_computed_tokens: int,
num_tokens_main_model: int,
apply_admission_cap: bool = False,
prefill_end: int = 0,
) -> int:
"""Get the number of blocks needed to be allocated for the request.
@@ -201,15 +202,19 @@ class SingleTypeKVCacheManager(ABC):
model in spec decode). w/o spec decode, it is num_tokens;
with spec decode, it is num_tokens - num_lookahead_tokens.
apply_admission_cap: If True, clamp by `num_required_blocks` by
`_max_admission_blocks_per_request`for recycling-aware specs
`max_admission_blocks_per_request`for recycling-aware specs
(SWA, chunked-local).
prefill_end: The token index the request's prefill ends at, the
same value the scheduler splits chunks against. Mamba reserves
a prefill checkpoint only on the chunk reaching it; 0 (dense
retention) reserves one on every chunk.
Returns:
The number of blocks to allocate.
"""
num_required_blocks = cdiv(num_tokens, self.block_size)
if apply_admission_cap and self._max_admission_blocks_per_request is not None:
if apply_admission_cap and self.max_admission_blocks_per_request is not None:
# Recycling-aware specs (SWA, chunked-local) cap the per-request
# reservation here so admission matches the startup pool sizer
# (`SlidingWindowSpec.max_admission_blocks_per_request` / its
@@ -220,7 +225,7 @@ class SingleTypeKVCacheManager(ABC):
# Drift between the two would re-introduce the deadlock from
# issue #39734 or, worse, mid-prefill OOM.
num_required_blocks = min(
num_required_blocks, self._max_admission_blocks_per_request
num_required_blocks, self.max_admission_blocks_per_request
)
num_req_blocks = len(self.req_to_blocks.get(request_id, ()))
@@ -1215,6 +1220,7 @@ class CircularBufferManager(FullAttentionManager):
num_local_computed_tokens: int,
num_tokens_main_model: int,
apply_admission_cap: bool = False,
prefill_end: int = 0,
) -> int:
return 0 if self.req_to_blocks.get(request_id) else 1
@@ -1687,12 +1693,14 @@ class MambaManager(SingleTypeKVCacheManager):
query_start: int,
query_end: int,
checkpoint_position: int,
prefill_end: int,
) -> bool:
assert isinstance(self.kv_cache_spec, MambaSpec)
checkpoint_idx = cdiv(query_end, self.block_size) - 2
blocks = self.req_to_blocks[request_id]
return (
self.has_prefill_checkpoint_blocks
and query_end >= prefill_end
and is_mamba_prefill_checkpoint_valid(
query_start=query_start,
query_end=query_end,
@@ -1721,6 +1729,7 @@ class MambaManager(SingleTypeKVCacheManager):
num_local_computed_tokens: int,
num_tokens_main_model: int,
apply_admission_cap: bool = False,
prefill_end: int = 0,
) -> int:
assert isinstance(self.kv_cache_spec, MambaSpec)
if (
@@ -1747,6 +1756,7 @@ class MambaManager(SingleTypeKVCacheManager):
num_local_computed_tokens,
num_tokens_main_model,
apply_admission_cap=apply_admission_cap,
prefill_end=prefill_end,
)
else:
# We don't allocate blocks for lookahead tokens in align mode, because if
@@ -1774,6 +1784,11 @@ class MambaManager(SingleTypeKVCacheManager):
)
if has_partial_hit:
num_new_blocks = max(num_new_blocks, 0) + 1
# Keyed on the chunk end like the worker's
# `compute_mamba_prefill_checkpoints`, which writes the state there.
# The helper returns a boundary strictly below its input, so every
# chunk has one; under sparse retention only the prefill-end chunk's
# 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,
@@ -1784,6 +1799,7 @@ class MambaManager(SingleTypeKVCacheManager):
total_computed_tokens,
num_tokens,
checkpoint_position,
prefill_end,
):
checkpoint_position = 0
checkpoint_block = int(checkpoint_position > 0)
@@ -2051,9 +2067,21 @@ class MambaManager(SingleTypeKVCacheManager):
blocks = self.req_to_blocks[request.request_id]
assert 0 <= checkpoint_idx < len(blocks)
checkpoint_block = blocks[checkpoint_idx]
# The prompt's final chunk caches only up to its last full block,
# so ``num_tokens < num_prompt_tokens`` holds there too; its
# checkpoint is the prompt's reusable boundary, not a transient one.
is_prompt_checkpoint = (
checkpoint_position
== get_mamba_prefill_checkpoint_position(
request.num_prompt_tokens,
hash_block_size,
self.drop_eagle_checkpoint_block,
)
)
if (
retention_interval == 0
and num_tokens < request.num_prompt_tokens
and not is_prompt_checkpoint
and checkpoint_position != request.shared_prefix_boundary
):
# retention_interval == 0 keeps this transient checkpoint
@@ -2220,8 +2248,8 @@ class SinkFullAttentionManager(FullAttentionManager):
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.
Every page gets a host block: allocation fails when the host pool cannot
back it, so each GPU-resident page can be written back and later reclaimed.
"""
coordinator: "HiSparseCoordinator | None" = None
@@ -2244,7 +2272,7 @@ 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=device_pool.metrics_collector,
metrics_collector=None,
medium=MEDIUM_CPU,
event_owner=device_pool,
)
@@ -2269,45 +2297,23 @@ class HiSparseSourceManager(FullAttentionManager):
num_local_computed_tokens: int,
num_tokens_main_model: int,
apply_admission_cap: bool = False,
prefill_end: int = 0,
) -> 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(
required = super().get_num_blocks_to_allocate(
request_id,
fit_blocks * self.block_size,
min(num_tokens_main_model, fit_blocks * self.block_size),
num_tokens,
new_computed_blocks,
total_computed_tokens,
num_local_computed_tokens,
num_tokens_main_model,
)
req_blocks.extend([self._null_block] * (num_required - len(req_blocks)))
return new_blocks
# Host blocks come from a private pool, so they never count against
# the GPU pool. Use the same admission sentinel as Mamba instead.
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_external_computed_blocks(
self,
@@ -2369,12 +2375,6 @@ class _HiSparseAuxiliaryManager(SingleTypeKVCacheManager):
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,
@@ -2427,6 +2427,7 @@ class HiSparseHotManager(_HiSparseAuxiliaryManager):
num_local_computed_tokens: int,
num_tokens_main_model: int,
apply_admission_cap: bool = False,
prefill_end: int = 0,
) -> int:
assert not new_computed_blocks
# A hot region is needed to read host-backed history: an external
@@ -2490,6 +2491,8 @@ class HiSparseHotManager(_HiSparseAuxiliaryManager):
class HiSparseResidentManager(_HiSparseAuxiliaryManager):
"""Track GPU-resident pages for otherwise host-backed KV."""
max_admission_blocks_per_request: int
def get_num_blocks_to_allocate(
self,
request_id: str,
@@ -2499,6 +2502,7 @@ class HiSparseResidentManager(_HiSparseAuxiliaryManager):
num_local_computed_tokens: int,
num_tokens_main_model: int,
apply_admission_cap: bool = False,
prefill_end: int = 0,
) -> int:
del num_tokens_main_model
assert not new_computed_blocks
@@ -2515,8 +2519,7 @@ class HiSparseResidentManager(_HiSparseAuxiliaryManager):
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)
required = min(required, self.max_admission_blocks_per_request)
return max(required - max(existing, host_pages), 0)
def allocate_external_computed_blocks(
@@ -2551,18 +2554,6 @@ class HiSparseResidentManager(_HiSparseAuxiliaryManager):
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]: