[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:
co-authored by
Claude Fable 5
OpenAI Codex
Dao Le
parent
16d6c376bc
commit
6b110badbb
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user