[Bugfix][Mooncake] Save exact Mamba boundary states (#51358)

Signed-off-by: Yifan Qiao <yifanqiao@inferact.ai>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Co-authored-by: OpenAI Codex <codex@openai.com>
Co-authored-by: Dao Le <daole@inferact.ai>
This commit is contained in:
Yifan Qiao
2026-08-29 02:40:53 +00:00
committed by GitHub
co-authored by Claude Fable 5 OpenAI Codex Dao Le
parent 16d6c376bc
commit 6b110badbb
20 changed files with 1493 additions and 272 deletions
@@ -87,6 +87,11 @@ class MooncakeStoreCoordinator:
for g in kv_cache_groups
), "scheduler_block_size must be a multiple of each group's block_size"
self.kv_cache_groups = kv_cache_groups
self.mamba_group_ids = {
group_id
for group_id, group in enumerate(kv_cache_groups)
if isinstance(_unwrap_spec(group.kv_cache_spec), MambaSpec)
}
self.hash_block_size = hash_block_size
self.lcm_block_size = scheduler_block_size
self.enable_partial_hash_hits = partial_hash_hits_enabled(
@@ -205,12 +210,23 @@ class MooncakeStoreCoordinator:
Reuses the engine's ``SingleTypeKVCacheManager.reachable_block_mask``
so the store retains exactly the blocks the local prefix cache would.
Mamba groups are always all-False: the normal save resolves blocks
positionally from the connector's append-only block-ID snapshot, but
an align-mode mamba block table is not append-only (interior state
blocks are nulled/freed, and speculative decoding relocates the spec
blocks in place), so a positional read may hit a null, freed, or live
speculative-state block and persist wrong bytes under a valid prefix
hash. Mamba state is persisted only through the connector-pinned exact
block hand-off path
(``SchedulerOutput.kv_connector_block_state.boundary_state_offloads``).
"""
return self._reachable_masks(
aligned_token_len,
start_token,
retention_interval=self.retention_interval,
num_prompt_tokens=num_prompt_tokens,
exclude_mamba=True,
)
def lookup_mask(
@@ -237,6 +253,7 @@ class MooncakeStoreCoordinator:
*,
retention_interval: int | None,
num_prompt_tokens: int | None,
exclude_mamba: bool = False,
) -> tuple[list[bool] | None, ...]:
mask_alignment = (
self.hash_block_size
@@ -252,6 +269,9 @@ class MooncakeStoreCoordinator:
spec = _unwrap_spec(g.kv_cache_spec)
end_chunk = aligned_token_len // spec.block_size
start_chunk = min(end_chunk, max(0, cdiv(start_token, spec.block_size)))
if exclude_mamba and isinstance(spec, MambaSpec):
masks.append([False] * (end_chunk - start_chunk))
continue
manager_cls = KVCacheSpecRegistry.get_manager_class(spec)
assert manager_cls is not None
use_eagle = g_idx in self.eagle_group_ids
@@ -406,11 +406,11 @@ class ReqMeta:
# serve that purpose: it is reused once a preempted request resumes, so it
# would release the wrong job's blocks.
store_job_id: int | None = None
# Core-provided per-mamba-group
# (group_id, cow_block_id, boundary_tokens) for this request's partial tail.
# Present only on the producer's CoW step; drives the connector's offload
# (the FA group's block is derived from block_ids and boundary_tokens).
partial_tail_offloads: list[tuple[int, int, int]] | None = None
# Core-provided (group_id, block_id, boundary_tokens) mamba "align"
# boundary states. A block-aligned entry is a committed boundary snapshot;
# a non-aligned entry is the sub-block CoW tail. The store-job reference
# keeps each exact block alive until every worker rank finishes the job.
boundary_state_offloads: list[tuple[int, int, int]] | None = None
@staticmethod
def from_request_tracker(
@@ -23,11 +23,12 @@ from vllm.distributed.kv_transfer.kv_connector.v1.mooncake.store.worker import (
LookupKeyClient,
)
from vllm.logger import init_logger
from vllm.v1.attention.backends.utils import NULL_BLOCK_ID
from vllm.v1.core.block_pool import BlockPool
from vllm.v1.core.kv_cache_manager import KVCacheBlocks
from vllm.v1.core.kv_cache_utils import resolve_kv_cache_block_sizes
from vllm.v1.core.sched.output import NewRequestData, SchedulerOutput
from vllm.v1.kv_cache_interface import KVCacheConfig
from vllm.v1.kv_cache_interface import KVCacheConfig, MambaSpec
from vllm.v1.outputs import KVConnectorOutput
from vllm.v1.request import Request
@@ -80,12 +81,15 @@ class MooncakeStoreScheduler:
self._hash_block_size,
vllm_config.parallel_config.decode_context_parallel_size,
)
# Per-request state
self.load_specs: dict[str, LoadSpec] = {} # to be loaded
self._request_trackers: dict[str, RequestTracker] = {} # scheduled new requests
self._unfinished_requests: dict[str, tuple[Request, tuple[list[int], ...]]] = {}
self._unfinished_request_ids: set[str] = set()
mamba_groups = {
group_id: group.kv_cache_spec
for group_id, group in enumerate(kv_cache_config.kv_cache_groups)
if isinstance(group.kv_cache_spec, MambaSpec)
}
assert all(
spec.mamba_cache_mode == "align" for spec in mamba_groups.values()
), "MooncakeStoreScheduler requires mamba_cache_mode='align'"
self._boundary_state_group_ids = frozenset(mamba_groups)
self._gpu_block_pool: BlockPool | None = None
self._num_workers = vllm_config.parallel_config.world_size
@@ -93,6 +97,12 @@ class MooncakeStoreScheduler:
# store_job_id -> (referenced block ids, ranks yet to report completion)
self._pinned_saves: dict[int, tuple[list[int], int]] = {}
# Per-request state
self.load_specs: dict[str, LoadSpec] = {} # to be loaded
self._request_trackers: dict[str, RequestTracker] = {} # scheduled new requests
self._unfinished_requests: dict[str, tuple[Request, tuple[list[int], ...]]] = {}
self._unfinished_request_ids: set[str] = set()
def bind_gpu_block_pool(self, gpu_block_pool: BlockPool) -> None:
self._gpu_block_pool = gpu_block_pool
@@ -381,47 +391,41 @@ class MooncakeStoreScheduler:
if req_meta is not None:
meta.add_request(req_meta)
# Flush partial-tail offloads in the step they arrive: the CoW copy is
# enqueued before the connector event records, so this step's event
# fences the cow block. Ride the request's save meta when present, else
# emit an offload-only ReqMeta (token_len_chunk=0 skips the normal
# save; can_save=True takes the normal enqueue path).
step_partial_tails = getattr(scheduler_output, "partial_tail_offloads", None)
if step_partial_tails and not is_consumer:
pending = dict(step_partial_tails)
for req_meta in meta.requests:
if req_meta.can_save:
groups = pending.pop(req_meta.req_id, None)
if groups:
req_meta.partial_tail_offloads = groups
tracker = self._request_trackers.get(req_meta.req_id)
if tracker is not None:
tracker.has_pending_offload = True
for req_id, groups in pending.items():
tracker = self._request_trackers.get(req_id)
req_tuple = self._unfinished_requests.get(req_id)
if tracker is None or req_tuple is None:
# Request finished/preempted within this step; its blocks
# are going away, so the offload is conservatively dropped.
logger.debug("Dropping partial-tail offload for request %s", req_id)
continue
assert len({boundary for _, _, boundary in groups}) == 1
tracker.has_pending_offload = True
meta.add_request(
ReqMeta(
req_id=req_id,
token_len_chunk=0,
block_ids=tracker.allocated_block_ids,
block_hashes=req_tuple[0].block_hashes,
can_save=True,
num_prompt_tokens=tracker.prefill_end_tokens,
partial_tail_offloads=groups,
)
)
block_state = getattr(scheduler_output, "kv_connector_block_state", None)
if (
block_state is not None
and block_state.boundary_state_offloads
and not is_consumer
):
self._handle_boundary_state_offloads(
block_state.boundary_state_offloads, meta
)
self._apply_current_save_block_ids(meta, scheduler_output)
self._reference_save_blocks(meta)
return meta
def _apply_current_save_block_ids(
self,
meta: MooncakeStoreConnectorMetadata,
scheduler_output: SchedulerOutput,
) -> None:
"""Replace append-only mirrors with the core's current block tables."""
save_metas = [req_meta for req_meta in meta.requests if req_meta.can_save]
if not save_metas:
return
block_state = scheduler_output.kv_connector_block_state
assert block_state is not None, (
"Current block tables are required for Mooncake store jobs"
)
for req_meta in save_metas:
block_ids = block_state.block_ids.get(req_meta.req_id)
assert block_ids is not None, (
f"Missing current block table for store request {req_meta.req_id}"
)
req_meta.block_ids = block_ids
def _reference_save_blocks(self, meta: MooncakeStoreConnectorMetadata) -> None:
"""Take a GPU block reference for every store job this step emits.
@@ -439,21 +443,86 @@ class MooncakeStoreScheduler:
req_meta.store_job_id = store_job_id = self._next_store_job_id
self._next_store_job_id += 1
block_ids: list[int] = []
if req_meta.partial_tail_offloads:
# A partial-tail CoW block is deliberately kept out of the
# request's block table, so it is absent from `block_ids` even
# though the worker DMAs out of it just as asynchronously.
# It leads the list, as in `pop_blocks_for_free`.
block_ids += [bid for _, bid, _ in req_meta.partial_tail_offloads]
if req_meta.boundary_state_offloads:
block_ids.extend(
block_id for _, block_id, _ in req_meta.boundary_state_offloads
)
assert NULL_BLOCK_ID not in block_ids, (
"A null block cannot back a boundary-state offload"
)
# Every allocated block is referenced, not just the ones covering
# this job's token range: a rank resumes from its own last
# successful offset, which lags the scheduler's whenever a save was
# skipped or failed, so it may read anywhere below the range.
block_ids += [bid for group in req_meta.block_ids for bid in group]
block_ids.extend(
block_id
for group_id, group in enumerate(req_meta.block_ids)
if group_id not in self._boundary_state_group_ids
for block_id in group
if block_id != NULL_BLOCK_ID
)
# An aligned boundary block may also be present in the request's
# block table. Take and release exactly one reference per block.
block_ids = list(dict.fromkeys(block_ids))
assert NULL_BLOCK_ID not in block_ids
if not block_ids:
continue
self._pinned_saves[store_job_id] = (block_ids, self._num_workers)
pool.touch([pool.blocks[bid] for bid in block_ids])
pool.touch([pool.blocks[block_id] for block_id in block_ids])
def _handle_boundary_state_offloads(
self,
offloads: dict[str, list[tuple[int, int, int]]],
meta: MooncakeStoreConnectorMetadata,
) -> None:
"""Attach exact boundary-state blocks to store jobs for this step.
Flushed in the step they arrive: the CoW copy is enqueued before the
connector event records, so this step's event fences the exact block.
Entries ride the request's save meta when present, else an
offload-only ReqMeta (``token_len_chunk=0`` skips the normal save,
``can_save=True`` takes the normal enqueue and store-job pinning path).
"""
save_metas = {m.req_id: m for m in meta.requests if m.can_save}
for req_id, entries in offloads.items():
tracker = self._request_trackers.get(req_id)
req_tuple = self._unfinished_requests.get(req_id)
if tracker is None or req_tuple is None:
# Request finished/preempted within this step; its blocks are
# going away, so the offload is conservatively dropped.
logger.debug("Dropping boundary-state offload for request %s", req_id)
continue
accepted: list[tuple[int, int, int]] = []
for group_id, block_id, boundary_tokens in entries:
# Every other group stops saving at the end of this prefill, so
# a mamba-only key past it can never complete a joint hybrid
# hit. `prefill_end_tokens` — not the original prompt length —
# is the boundary: a resumed request re-prefills and re-saves
# its previously generated tokens for every group.
if boundary_tokens > tracker.prefill_end_tokens:
continue
if block_id == NULL_BLOCK_ID:
continue
if group_id not in self._boundary_state_group_ids:
continue
accepted.append((group_id, block_id, boundary_tokens))
if not accepted:
continue
tracker.has_pending_offload = True
if (req_meta := save_metas.get(req_id)) is not None:
req_meta.boundary_state_offloads = accepted
continue
meta.add_request(
ReqMeta(
req_id=req_id,
token_len_chunk=0,
block_ids=tracker.allocated_block_ids,
block_hashes=req_tuple[0].block_hashes,
can_save=True,
num_prompt_tokens=tracker.prefill_end_tokens,
boundary_state_offloads=accepted,
)
)
def update_connector_output(self, connector_output: KVConnectorOutput) -> None:
"""Drop the block references of store jobs every rank has finished."""
@@ -648,48 +648,76 @@ class KVCacheStoreSendingThread(KVTransferThread):
self._skip_store_requests.clear()
return True
def _maybe_offload_partial_tail(self, req_meta: ReqMeta) -> bool:
"""Offload the request's sub-block partial tail (its last prompt hash
boundary) so a later request can hit the sub-block prefix.
def _boundary_snapshot_puts(
self, req_meta: ReqMeta, entries: list[tuple[int, int, int]]
) -> list[tuple[str, list[int], list[int], KeyMetadata]]:
"""Puts for committed mamba "align" boundary-state snapshots.
Covers every block from the normal save's lcm floor to the boundary:
the normal save floors to ``lcm_block_size``, so a smaller-block
group's full blocks in that gap are never persisted elsewhere, and
the consumer's lookup needs every group at every probed boundary.
Full blocks are keyed by their block-end hash, the partial boundary
block by the boundary sub-hash; the mamba "align" boundary block is
the core-provided CoW block. All keys are deduped against the store.
These are block-aligned boundaries, i.e. exactly what the normal save
would key — but ``store_mask`` masks mamba groups out of it entirely, so
this is their *only* writer. The exclusion is not an optimization: the
normal save resolves a chunk's address as
``req_meta.block_ids[g][start // block_size]``, and ``block_ids`` is the
connector's append-only mirror of the core's per-group table. An
align-mode table is mutated in place (a superseded state block is freed
and nulled; speculative blocks relocate), and the connector is never
told, so a stale mirror entry is indistinguishable from a live one — a
retry of a failed or pressure-skipped chunk would read a block that now
belongs to another request.
Returns:
True when no put is needed or every put succeeds, False otherwise.
Each entry's handed-off block *is* the boundary state and is pinned by
the core, so it is uploaded under its boundary-end hash key and never
resolved positionally.
"""
if not self.coord.enable_partial_hash_hits or not req_meta.block_hashes:
return True
partial_tail_offloads = req_meta.partial_tail_offloads
if not partial_tail_offloads:
return True
hash_block_size = self.coord.hash_block_size
boundaries = {boundary for _, _, boundary in partial_tail_offloads}
puts: list[tuple[str, list[int], list[int], KeyMetadata]] = []
for group_id, block_id, boundary in entries:
if boundary == 0 or block_id == NULL_BLOCK_ID:
continue
hash_idx = boundary // hash_block_size - 1
if hash_idx >= len(req_meta.block_hashes):
continue
db = self.token_databases[group_id]
# Distribute across ranks by the same rule as normal chunks.
put_step = self.group_put_steps[group_id]
put_step_rank = (self.tp_rank + group_id) % put_step
if (boundary // db.block_size - 1) % put_step != put_step_rank:
continue
addr, size = db.prepare_value_for_block(block_id)
puts.append(
(db.key_for(req_meta.block_hashes[hash_idx]), addr, size, db.metadata)
)
return puts
def _sub_block_tail_puts(
self, req_meta: ReqMeta, entries: list[tuple[int, int, int]]
) -> list[tuple[str, list[int], list[int], KeyMetadata]]:
"""Puts for the request's sub-block partial tail (its last prompt hash
boundary), so a later request can hit the sub-block prefix.
Covers every group's blocks from the normal save's lcm floor to the
boundary: the normal save floors to ``lcm_block_size``, so a
smaller-block group's full blocks in that gap are never persisted
elsewhere, and the consumer's lookup needs every group at every probed
boundary. Full blocks are keyed by their block-end hash and the partial
boundary block by the boundary sub-hash; a mamba "align" group
contributes only its boundary block, from the core-provided CoW block.
"""
boundaries = {boundary for _, _, boundary in entries}
if len(boundaries) != 1:
raise ValueError(
"Partial-tail offloads for one request must share a boundary"
"Sub-block partial-tail offloads for one request must share a boundary"
)
boundary = boundaries.pop()
if boundary == 0:
return True
if boundary // hash_block_size - 1 >= len(req_meta.block_hashes):
return True
mamba_offloads = {
group_id: block_id for group_id, block_id, _ in partial_tail_offloads
}
hash_block_size = self.coord.hash_block_size
if boundary == 0 or boundary // hash_block_size - 1 >= len(
req_meta.block_hashes
):
return []
keys: list[str] = []
addrs: list[list[int]] = []
sizes: list[list[int]] = []
group_ids: list[str] | None = (
[] if self.enable_group_semantics and self.supports_group_ids else None
)
mamba_offloads = {group_id: block_id for group_id, block_id, _ in entries}
saved = self._saved_offset.get(req_meta.req_id, 0)
puts: list[tuple[str, list[int], list[int], KeyMetadata]] = []
for g_idx, db in enumerate(self.token_databases):
group_blocks = req_meta.block_ids[g_idx]
# Distribute across ranks by the same rule as normal chunks.
@@ -705,16 +733,20 @@ class KVCacheStoreSendingThread(KVTransferThread):
continue
valid_end = min((block_idx + 1) * db.block_size, boundary)
key_hash = req_meta.block_hashes[valid_end // hash_block_size - 1]
if (
g_idx in mamba_offloads
and valid_end == boundary
and boundary % db.block_size != 0
):
block_id = mamba_offloads[g_idx]
else:
if block_idx >= len(group_blocks):
if g_idx in mamba_offloads:
if valid_end != boundary:
# Interior align-mode state positions are null or
# stale (the block table is not append-only) and never
# valid gap content; only the boundary block is
# persisted, from the core-provided hand-off.
continue
block_id = mamba_offloads[g_idx]
elif g_idx in self.coord.mamba_group_ids:
continue
elif block_idx < len(group_blocks):
block_id = group_blocks[block_idx]
else:
continue
if block_id == NULL_BLOCK_ID:
logger.debug(
"Skipping unavailable partial-tail source block "
@@ -725,20 +757,58 @@ class KVCacheStoreSendingThread(KVTransferThread):
)
continue
addr, size = db.prepare_value_for_block(block_id)
key = db.key_for(key_hash)
keys.append(key)
addrs.append(addr)
sizes.append(size)
if group_ids is not None:
group_ids.append(
_make_mooncake_group_id(
db.metadata,
key.rsplit("@", 1)[-1],
)
)
puts.append((db.key_for(key_hash), addr, size, db.metadata))
return puts
if not keys:
def _maybe_offload_boundary_states(self, req_meta: ReqMeta) -> bool:
"""Persist connector-pinned mamba "align" boundary states handed off
for this request, deduped against the store.
This is every mamba key the connector writes — ``store_mask`` excludes
mamba groups from the positional normal save, aligned boundaries
included (see :meth:`_boundary_snapshot_puts`).
The two entry kinds are keyed and sourced differently, so they are
prepared separately and put in one batch:
- block-aligned for its group: a committed boundary-state snapshot,
the handed-off block itself;
- not block-aligned: the sub-block CoW partial tail, which also has to
cover the other groups' blocks in the normal save's lcm gap.
Returns:
True when no put is needed or every put succeeds, False otherwise.
"""
offloads = req_meta.boundary_state_offloads
if not offloads or not req_meta.block_hashes:
return True
snapshots: list[tuple[int, int, int]] = []
sub_block: list[tuple[int, int, int]] = []
for group_id, block_id, boundary in offloads:
entry = (group_id, block_id, boundary)
if boundary % self.token_databases[group_id].block_size == 0:
snapshots.append(entry)
else:
sub_block.append(entry)
puts = self._boundary_snapshot_puts(req_meta, snapshots)
if sub_block and self.coord.enable_partial_hash_hits:
puts.extend(self._sub_block_tail_puts(req_meta, sub_block))
if not puts:
return True
keys = [key for key, _, _, _ in puts]
addrs = [addr for _, addr, _, _ in puts]
sizes = [size for _, _, size, _ in puts]
group_ids: list[str] | None = (
[
_make_mooncake_group_id(metadata, key.rsplit("@", 1)[-1])
for key, _, _, metadata in puts
]
if self.enable_group_semantics and self.supports_group_ids
else None
)
exists_start = time.perf_counter()
try:
exists = self.store.batch_is_exist(keys)
@@ -751,7 +821,7 @@ class KVCacheStoreSendingThread(KVTransferThread):
num_failed_keys=len(keys),
)
logger.error(
"Failed to check partial-tail keys for request %s: %s",
"Failed to check boundary-state keys for request %s: %s",
req_meta.req_id,
e,
)
@@ -787,7 +857,7 @@ class KVCacheStoreSendingThread(KVTransferThread):
num_failed_keys=len(keys),
)
logger.error(
"Failed to put partial-tail keys for request %s: %s",
"Failed to put boundary-state keys for request %s: %s",
req_meta.req_id,
e,
)
@@ -805,7 +875,8 @@ class KVCacheStoreSendingThread(KVTransferThread):
if failed:
failed_codes = {res[i] for i in failed}
logger.warning(
"Partial-tail put failed for request %s: %d/%d keys failed (codes=%s)",
"Boundary-state put failed for request %s: %d/%d keys failed "
"(codes=%s)",
req_meta.req_id,
len(failed),
len(keys),
@@ -818,7 +889,7 @@ class KVCacheStoreSendingThread(KVTransferThread):
if self._clear_store_pressure():
logger.info(
"Mooncake CPU/disk offloading pressure cleared after a "
"successful partial-tail batch"
"successful boundary-state batch"
)
return True
@@ -857,10 +928,10 @@ class KVCacheStoreSendingThread(KVTransferThread):
)
return
# Offload the sub-block partial tail (independent of the normal
# block-aligned save, which may be skipped this step).
if req_meta.partial_tail_offloads is not None and not (
self._maybe_offload_partial_tail(req_meta)
# Offload the handed-off mamba boundary states (independent of the
# normal positional save, which may be skipped this step).
if req_meta.boundary_state_offloads is not None and not (
self._maybe_offload_boundary_states(req_meta)
):
return
@@ -887,6 +958,7 @@ class KVCacheStoreSendingThread(KVTransferThread):
# Rotate the stride phase per group to balance load across ranks.
put_step = self.group_put_steps[g_idx]
put_step_rank = (self.tp_rank + g_idx) % put_step
group_blocks = block_ids_per_group[g_idx]
for start, end, block_hash in db.process_tokens(
token_len,
req_meta.block_hashes,
@@ -1130,6 +1130,9 @@ class OffloadingConnectorScheduler:
if bid != 0:
self._current_batch_allocated_block_ids.add(bid)
for copy in scheduler_output.kv_cache_block_copies or ():
self._current_batch_allocated_block_ids.add(copy.dst_block_id)
# Zero out stale block_ids in sliding window groups' pending-store
# positions. Only sliding window groups can have stale entries (blocks
# freed by remove_skipped_blocks then reallocated). Only positions in
@@ -1151,18 +1154,89 @@ class OffloadingConnectorScheduler:
):
group_state.block_ids[j] = 0
def _build_aligned_boundary_store_jobs(
self, handoffs: dict[str, list[tuple[int, int, int]]]
) -> dict[int, TransferJob]:
store_jobs: dict[int, TransferJob] = {}
num_groups = len(self.config.kv_group_configs)
for req_id, entries in handoffs.items():
req_status = self._req_status.get(req_id)
if req_status is None:
continue
req = req_status.req
max_boundary = self._calc_num_offloadable_tokens(req_status, req.num_tokens)
for group_idx, block_id, boundary in entries:
group_config = self.config.kv_group_configs[group_idx]
if (
block_id == 0
or boundary > max_boundary
or boundary % group_config.tokens_per_chunk != 0
):
continue
key = self._make_boundary_key(req, group_idx, boundary)
store_output = self.manager.prepare_store([key], req_status.req_context)
if store_output is None:
self._connector_stats.increase_counter(
_ConnectorMetricName.ALLOCATION_FAILURE
)
continue
if not store_output.keys_to_store:
continue
job_id = self._generate_job_id()
req_status.transfer_jobs.add(job_id)
self._block_id_to_pending_jobs.setdefault(block_id, set()).add(job_id)
self._jobs[job_id] = TransferJobStatus(
req_id=req_id,
pending_count=self.config.num_workers,
keys={key},
is_store=True,
fenced_block_ids=[block_id],
)
group_sizes = [0] * num_groups
group_sizes[group_idx] = 1
block_indices = [0] * num_groups
block_indices[group_idx] = boundary // group_config.tokens_per_block - 1
store_jobs[job_id] = TransferJob(
req_id=req_id,
src_spec=GPULoadStoreSpec(
[block_id],
group_sizes=group_sizes,
block_indices=block_indices,
),
dst_spec=store_output.store_spec,
)
self._events_tracker.record_store(
req,
group_config,
boundary // group_config.tokens_per_chunk - 1,
key,
)
return store_jobs
def _build_partial_tail_store_jobs(
self, scheduler_output: SchedulerOutput
) -> dict[int, TransferJob]:
handoffs = scheduler_output.partial_tail_offloads
if not self.config.supports_partial_tail or not handoffs:
block_state = scheduler_output.kv_connector_block_state
handoffs = block_state.boundary_state_offloads if block_state else None
if not handoffs:
return {}
store_jobs: dict[int, TransferJob] = {}
store_jobs = self._build_aligned_boundary_store_jobs(handoffs)
if not self.config.supports_partial_tail:
return store_jobs
for req_id, entries in handoffs.items():
entries = [
entry
for entry in entries
if entry[2] % self._partial_tail_block_size != 0
]
if not entries:
continue
req_status = self._req_status.get(req_id)
assert req_status is not None
assert entries
boundaries = {boundary for _, _, boundary in entries}
assert len(boundaries) == 1
boundary = boundaries.pop()
@@ -1282,6 +1356,9 @@ class OffloadingConnectorScheduler:
group_config, group_state, num_offloadable_tokens
)
if group_config.requires_cow_source:
continue
start_chunk_idx = group_state.next_stored_chunk_idx
if num_chunks <= start_chunk_idx:
continue
+4
View File
@@ -716,6 +716,10 @@ class BlockPool:
if self.metrics_collector:
self.metrics_collector.on_block_accessed(block)
def is_block_writable(self, block: KVCacheBlock) -> bool:
"""Return whether a block can be mutated by its sole owner."""
return not block.is_null and block.ref_cnt == 1 and block.block_hash is None
def free_blocks(self, ordered_blocks: Iterable[KVCacheBlock]) -> None:
"""Free a list of blocks. The blocks should be ordered by their
eviction priority, where the first block will be evicted first.
+12 -28
View File
@@ -189,10 +189,6 @@ class KVCacheManager:
tuple(() for _ in range(self.num_kv_cache_groups))
)
# Off-table cow blocks handed to a KV connector for partial-tail
# offload; pinned until the request's blocks are freed.
self._partial_tail_pins: dict[str, list[KVCacheBlock]] = {}
@property
def usage(self) -> float:
"""Get the KV cache usage.
@@ -575,9 +571,6 @@ class KVCacheManager:
Args:
request: The request to free the blocks.
"""
pins = self._partial_tail_pins.pop(request.request_id, None)
if pins:
self.block_pool.free_blocks(pins)
self.coordinator.free(request.request_id)
def remove_skipped_blocks(
@@ -610,14 +603,7 @@ class KVCacheManager:
Returns:
The request's blocks in allocation order.
"""
blocks = self.coordinator.pop_blocks_for_free(request.request_id)
# Pins ride the same (possibly deferred) free as the request blocks.
# Preemption may release a pin under a still-queued offload — the same
# exposure normal saves of table blocks already have.
pins = self._partial_tail_pins.pop(request.request_id, None)
if pins:
blocks = pins + blocks
return blocks
return self.coordinator.pop_blocks_for_free(request.request_id)
def evict_blocks(self, block_ids: set[int]) -> None:
"""evict blocks from the prefix cache by their block IDs.
@@ -854,18 +840,18 @@ class KVCacheManager:
retained_blocks = [block for pair in pending_copies for block in pair]
return copies, retained_blocks
def take_partial_tail_offloads(self) -> dict[str, list[tuple[int, int, int]]]:
"""Drain producer partial-tail offload hand-offs per request.
def take_boundary_state_offloads(
self,
) -> dict[str, list[tuple[int, int, int]]]:
"""Drain this step's boundary-state hand-offs for a KV connector.
Returns ``{request_id: [(group_id, block_id, boundary_tokens), ...]}``
for the durable boundary blocks of producers' last-prompt-boundary
partial tails. Only mamba "align" groups contribute; empty otherwise.
A KV connector reads the referenced blocks and offloads them so a later
request can hit the sub-block prefix.
Each handed-off block lives off the request block table, so it is
pinned here and unpinned when the request's blocks are freed — for a
producer with saved tokens, after the connector reports sends done.
for mamba "align" boundary states: the
request's committed boundary-state snapshots and, on a sub-block partial
hit, the CoW copy of its last-prompt-boundary state. Only mamba "align"
groups contribute; empty otherwise. A connector reads the referenced
blocks — never resolving them positionally — and offloads them so a
later request can hit that prefix.
"""
offloads: dict[str, list[tuple[int, int, int]]] = {}
for mgr in self.coordinator.single_type_managers:
@@ -874,9 +860,7 @@ class KVCacheManager:
group_id,
block,
boundary_tokens,
) in mgr.take_pending_partial_tail_offloads():
self.block_pool.touch((block,))
self._partial_tail_pins.setdefault(req_id, []).append(block)
) in mgr.take_pending_boundary_state_offloads():
offloads.setdefault(req_id, []).append(
(group_id, block.block_id, boundary_tokens)
)
+12 -5
View File
@@ -205,6 +205,16 @@ class ScheduledEncoderInputStats:
output_tokens: int = 0
@dataclass
class KVConnectorBlockState:
"""Scheduler-local block state offered to a producer-side KV connector."""
# Authoritative current block-table snapshots.
block_ids: dict[str, tuple[list[int], ...]]
# Exact Mamba "align" boundary-state hand-offs.
boundary_state_offloads: dict[str, list[tuple[int, int, int]]]
@dataclass
class SchedulerOutput:
# list of the requests that are scheduled for the first time.
@@ -278,11 +288,8 @@ class SchedulerOutput:
# CoW copies to apply after zeroing new blocks and before forward.
kv_cache_block_copies: list[KVCacheBlockCopy] | None = None
# Producer partial-tail offload hand-off for external KV connectors:
# {request_id: [(group_id, block_id, boundary_tokens), ...]} pointing at
# the durable boundary block of a producer's last-prompt-boundary partial
# tail (mamba "align" CoW target). None unless partial hash hits are active.
partial_tail_offloads: dict[str, list[tuple[int, int, int]]] | None = None
# Scheduler-local; always None by the time this reaches a worker.
kv_connector_block_state: KVConnectorBlockState | None = None
# Dynamic speculative decoding: optimal K chosen by scheduler.
# Number of spec tokens to schedule for the next step.
+31 -15
View File
@@ -42,6 +42,7 @@ from vllm.v1.core.sched.interface import PauseState, SchedulerInterface
from vllm.v1.core.sched.output import (
CachedRequestData,
GrammarOutput,
KVConnectorBlockState,
NewRequestData,
ScheduledEncoderInputStats,
SchedulerOutput,
@@ -1263,20 +1264,32 @@ class Scheduler(SchedulerInterface):
self.prev_step_scheduled_req_ids.clear()
self.prev_step_scheduled_req_ids.update(num_scheduled_tokens.keys())
# Producer partial-tail hand-off for external KV connectors. Drained
# before the CoW retentions are released below, so the pin lands while
# the cow block still holds a retention ref. Without a producer-side
# connector nothing consumes the hand-off, so skip the drain (and its
# pin); the manager drops stale entries when the request's blocks are
# popped for free.
pending_partial_tail_offloads = None
if (
self.connector is not None
and self.vllm_config.kv_transfer_config is not None
and self.vllm_config.kv_transfer_config.is_kv_producer
):
pending_partial_tail_offloads = (
self.kv_cache_manager.take_partial_tail_offloads() or None
# Mamba "align" boundary states must be handed off with exact block ids;
# they cannot be reconstructed from a connector's append-only block
# table. Drained every step so stale offers cannot accumulate.
boundary_state_offloads = self.kv_cache_manager.take_boundary_state_offloads()
kv_connector_block_state = None
if self.connector is not None:
snapshot_req_ids = {req.req_id for req in new_reqs_data}
snapshot_req_ids.update(
req_id
for req_id, block_ids in zip(
cached_reqs_data.req_ids,
cached_reqs_data.new_block_ids,
strict=True,
)
if block_ids
)
snapshot_req_ids.update(
req_id for req_id in boundary_state_offloads if req_id in self.requests
)
kv_connector_block_state = KVConnectorBlockState(
block_ids={
req_id: self.kv_cache_manager.get_block_ids(req_id)
for req_id in snapshot_req_ids
},
boundary_state_offloads=boundary_state_offloads,
)
kv_cache_block_copies, cow_retained_blocks = (
@@ -1325,7 +1338,7 @@ class Scheduler(SchedulerInterface):
new_block_ids_to_zero=self._get_new_block_ids_to_zero(),
has_sync_kv_loads=has_sync_kv_loads,
kv_cache_block_copies=pending_kv_cache_block_copies,
partial_tail_offloads=pending_partial_tail_offloads,
kv_connector_block_state=kv_connector_block_state,
num_spec_tokens_to_schedule=num_spec_tokens_to_schedule,
ec_manager_metadata=self.encoder_cache_manager.get_manager_metadata(),
)
@@ -1345,6 +1358,9 @@ class Scheduler(SchedulerInterface):
)
scheduler_output.ec_connector_metadata = ec_meta
# Connector-only block state must not be dispatched to workers.
scheduler_output.kv_connector_block_state = None
# Advance the fence only for non-empty steps (those that actually
# write KV and have their output processed later in update_from_output).
if self.defer_block_free and total_num_scheduled_tokens > 0:
+52 -26
View File
@@ -112,13 +112,14 @@ class SingleTypeKVCacheManager(ABC):
# managers (full attention, mamba "align"); harmlessly empty elsewhere.
self._partial_hit_reqs: dict[str, tuple[int, KVCacheBlock]] = {}
self._pending_cow_copies: list[tuple[KVCacheBlock, KVCacheBlock]] = []
# Partial-tail offload hand-off for external KV connectors: when a
# producer registers its last-prompt-boundary partial tail and the
# durable boundary block is not on the append-only request block table
# (mamba "align" CoW target), record the request, group, block, and
# exact token boundary so a connector can offload it under the right
# hash. Populated only by mamba "align".
self._pending_partial_tail_offloads: list[
# Boundary-state offload hand-off for external KV connectors. A mamba
# "align" block table is not append-only (interior states are
# nulled/freed and speculative blocks relocate in place), so a
# connector cannot resolve its state blocks positionally. Record
# (request, group, block, exact token boundary) for each committed
# boundary state so a connector can offload the right block under the
# right hash. Populated only by mamba "align".
self._pending_boundary_state_offloads: list[
tuple[str, int, KVCacheBlock, int]
] = []
@@ -385,19 +386,19 @@ class SingleTypeKVCacheManager(ABC):
self._pending_cow_copies = []
return pending_copies
def take_pending_partial_tail_offloads(
def take_pending_boundary_state_offloads(
self,
) -> list[tuple[str, int, KVCacheBlock, int]]:
"""Drain producer partial-tail hand-offs.
"""Drain producer boundary-state hand-offs.
Entries are ``(req_id, group_id, block, boundary_tokens)``.
Only mamba "align" populates this. The block lives off the request
block table, so the caller must pin it until the connector has read
it — nothing else keeps it alive once the CoW retention is released.
Only mamba "align" populates this. The blocks are not kept alive by
the request block table for the whole request, so a caller that reads
them asynchronously must pin them first.
"""
pending = self._pending_partial_tail_offloads
self._pending_partial_tail_offloads = []
pending = self._pending_boundary_state_offloads
self._pending_boundary_state_offloads = []
return pending
def _apply_cow(
@@ -1292,7 +1293,7 @@ class MambaManager(SingleTypeKVCacheManager):
# Requests that registered their own last-prompt-boundary partial
# tail (producers). On the next step's CoW the boundary state moves
# into a private cow_block; we record that block for connector
# offload (see _pending_partial_tail_offloads).
# offload (see _pending_boundary_state_offloads).
self._producer_partial_tail_reqs: dict[str, int] = {}
@classmethod
@@ -1625,13 +1626,12 @@ class MambaManager(SingleTypeKVCacheManager):
)
if blocks_allocated:
# reuse previous speculative blocks in this step
# Relocate exclusively owned speculative scratch blocks.
for block_idx in range(
prev_block_len - self.num_speculative_blocks, prev_block_len
):
if block_idx < num_skipped_blocks:
req_blocks.append(req_blocks[block_idx])
req_blocks[block_idx] = self._null_block
self._relocate_speculative_block(req_blocks, block_idx)
else:
break
num_new_blocks = num_required_blocks - len(req_blocks)
@@ -1664,7 +1664,7 @@ class MambaManager(SingleTypeKVCacheManager):
# This CoW preserved a producer's own boundary
# state in cow_block; hand it to the connector for
# partial-tail offload once the copy has run.
self._pending_partial_tail_offloads.append(
self._pending_boundary_state_offloads.append(
(
request_id,
self.kv_cache_group_id,
@@ -1685,17 +1685,31 @@ class MambaManager(SingleTypeKVCacheManager):
returned_blocks.extend(new_blocks)
return returned_blocks
def _relocate_speculative_block(
self, req_blocks: list[KVCacheBlock], block_idx: int
) -> None:
block = req_blocks[block_idx]
assert self.block_pool.is_block_writable(block), (
"Speculative Mamba blocks must be exclusively owned and unhashed "
"before relocation"
)
req_blocks.append(block)
req_blocks[block_idx] = self._null_block
def pop_blocks_for_free(self, request_id: str) -> list[KVCacheBlock]:
if self.mamba_cache_mode == "align":
self._allocated_block_reqs.discard(request_id)
self.last_state_block_idx.pop(request_id, None)
self._num_checkpoint_blocks.pop(request_id, None)
self._producer_partial_tail_reqs.pop(request_id, None)
# A hand-off whose request died in this same scheduling pass must
# not reach the connector: its unpin hook (free) has already run.
self._pending_partial_tail_offloads = [
# An offer is only guaranteed to hold committed bytes until the end
# of the pass that made it. This request's blocks are going back to
# the pool now, so drop its not-yet-offered hand-offs rather than
# let a connector claim a block another request may already have
# been handed.
self._pending_boundary_state_offloads = [
entry
for entry in self._pending_partial_tail_offloads
for entry in self._pending_boundary_state_offloads
if entry[0] != request_id
]
return super().pop_blocks_for_free(request_id)
@@ -1722,9 +1736,9 @@ class MambaManager(SingleTypeKVCacheManager):
if partial_hash is not None:
self.cached_blocks_this_step.add(partial_hash)
if num_cached_blocks_after > num_cached_blocks_before:
for block in self.req_to_blocks[request.request_id][
num_cached_blocks_before:num_cached_blocks_after
]:
blocks = self.req_to_blocks[request.request_id]
for idx in range(num_cached_blocks_before, num_cached_blocks_after):
block = blocks[idx]
# Skip null blocks (align-mode skipped states) and blocks that
# were not cached this step — with sparse retention
# (reachable_block_mask) the intermediate state snapshots carry
@@ -1732,6 +1746,18 @@ class MambaManager(SingleTypeKVCacheManager):
if block.is_null or block.block_hash is None:
continue
self.cached_blocks_this_step.add(block.block_hash)
if self.mamba_cache_mode == "align":
# Offer every retained boundary with its exact block.
# The connector filters against its save window, which may
# extend past the original prompt during resumed prefill.
self._pending_boundary_state_offloads.append(
(
request.request_id,
self.kv_cache_group_id,
block,
(idx + 1) * self.block_size,
)
)
def new_step_starts(self) -> None:
self.cached_blocks_this_step.clear()