[Bugfix][KV Connector] Populate SimpleCPUOffload BlockStored metadata (#54325)

This commit is contained in:
mevince
2026-09-03 15:58:07 +00:00
committed by GitHub
parent e55b93f296
commit 4ae6228284
4 changed files with 1132 additions and 28 deletions
@@ -111,6 +111,10 @@ class SimpleCPUOffloadConnector(KVConnectorBase_V1, SupportsHMA):
raise ValueError(
'kv_offload_backend="disk" requires disk_path to be set.'
)
if disk_capacity_bytes <= 0:
raise ValueError(
'kv_offload_backend="disk" requires disk_capacity_bytes > 0.'
)
else:
ignored = [k for k in _DISK_ONLY_KEYS if k in extra_config]
if ignored:
+246 -28
View File
@@ -8,7 +8,13 @@ from dataclasses import dataclass, field, replace
from typing import TYPE_CHECKING, Any
from vllm.config import VllmConfig
from vllm.distributed.kv_events import KVCacheEvent
from vllm.distributed.kv_events import (
MEDIUM_CPU,
MEDIUM_STORAGE,
BlockRemoved,
BlockStored,
KVCacheEvent,
)
from vllm.distributed.kv_transfer.kv_connector.utils import yield_req_data
from vllm.logger import init_logger
from vllm.utils.math_utils import cdiv
@@ -17,11 +23,23 @@ from vllm.v1.core.kv_cache_coordinator import (
KVCacheCoordinator,
get_kv_cache_coordinator,
)
from vllm.v1.core.kv_cache_utils import (
BlockHashWithGroupId,
ExternalBlockHash,
generate_block_hash_extra_keys,
get_block_hash,
get_group_id,
make_block_hash_with_group_id,
maybe_convert_block_hash,
resolve_block_hashes,
)
from vllm.v1.core.sched.output import SchedulerOutput
from vllm.v1.kv_cache_interface import (
FullAttentionSpec,
MambaSpec,
SlidingWindowSpec,
get_kv_cache_spec_kind,
get_kv_cache_spec_sliding_window,
)
from vllm.v1.outputs import KVConnectorOutput
from vllm.v1.simple_kv_offload.metadata import (
@@ -38,10 +56,27 @@ if TYPE_CHECKING:
logger = init_logger(__name__)
@dataclass
class BlockStoreMeta:
"""Per-block metadata snapshot for BlockStored event emission.
Captured at store-prep time (when the Request is available) and carried
through TransferMeta to async completion, where the Request is gone.
"""
token_ids: list[int]
parent_block_hash: ExternalBlockHash | None
lora_id: int | None
lora_name: str | None
extra_keys: tuple[Any, ...] | None
block_size: int | None = None
@dataclass
class TransferMeta:
gpu_block_ids: list[int]
cpu_block_ids: list[int]
block_meta: list[dict[BlockHashWithGroupId, BlockStoreMeta]] | None = None
@dataclass
@@ -98,6 +133,7 @@ class SimpleCPUOffloadScheduler:
kv_cache_config, offload_capacity
)
self.num_cpu_blocks = self.cpu_kv_cache_config.num_blocks
self.kv_event_medium = MEDIUM_STORAGE if disk_capacity_bytes > 0 else MEDIUM_CPU
# Find the full attention kv group for prefix cache matching.
self.fa_gidx = -1
for g_idx, g in enumerate(self.cpu_kv_cache_config.kv_cache_groups):
@@ -414,17 +450,22 @@ class SimpleCPUOffloadScheduler:
) -> SimpleCPUOffloadMetadata:
# --- Stores ---
store_event = -1
store_gpu, store_cpu, store_req_ids = self.prepare_store_specs(scheduler_output)
store_gpu, store_cpu, store_req_ids, store_meta = self.prepare_store_specs(
scheduler_output
)
for transfer in self._pending_finished_stores:
store_gpu.extend(transfer.gpu_block_ids)
store_cpu.extend(transfer.cpu_block_ids)
if store_meta is not None:
assert transfer.block_meta is not None
store_meta.extend(transfer.block_meta)
self._pending_finished_stores.clear()
if store_gpu:
store_event = self._store_event_counter
self._store_event_counter += 1
self._store_event_to_blocks[store_event] = TransferMeta(
store_gpu, store_cpu
store_gpu, store_cpu, store_meta
)
if store_req_ids: # For eager mode only, track req->blocks mapping
self._store_event_to_reqs[store_event] = store_req_ids
@@ -469,7 +510,12 @@ class SimpleCPUOffloadScheduler:
def prepare_store_specs(
self, scheduler_output: SchedulerOutput
) -> tuple[list[int], list[int], list[str]]:
) -> tuple[
list[int],
list[int],
list[str],
list[dict[BlockHashWithGroupId, BlockStoreMeta]] | None,
]:
"""Prepare store specs for the store event."""
if self._lazy_mode:
return self._prepare_lazy_store_specs()
@@ -478,7 +524,12 @@ class SimpleCPUOffloadScheduler:
def _prepare_lazy_store_specs(
self,
) -> tuple[list[int], list[int], list[str]]:
) -> tuple[
list[int],
list[int],
list[str],
list[dict[BlockHashWithGroupId, BlockStoreMeta]] | None,
]:
"""Single-pass cursor walk: offload cached GPU blocks near eviction.
Walks the GPU free queue from the cursor, counting blocks that are
@@ -487,7 +538,7 @@ class SimpleCPUOffloadScheduler:
"""
gpu_pool = self._gpu_block_pool
if gpu_pool is None or self._target_free <= 0:
return [], [], []
return [], [], [], None
free_queue = gpu_pool.free_block_queue
cpu_pool = self.cpu_block_pool
@@ -525,11 +576,16 @@ class SimpleCPUOffloadScheduler:
else:
cpu_ids = []
return gpu_ids, cpu_ids, []
return gpu_ids, cpu_ids, [], None
def _prepare_eager_store_specs(
self, scheduler_output: SchedulerOutput
) -> tuple[list[int], list[int], list[str]]:
) -> tuple[
list[int],
list[int],
list[str],
list[dict[BlockHashWithGroupId, BlockStoreMeta]] | None,
]:
"""Identify newly computed blocks to offload from scheduler requests.
Only considers blocks whose KV data has been **confirmed computed** by
@@ -537,19 +593,22 @@ class SimpleCPUOffloadScheduler:
the finish-time flush if the request completes first.
Returns:
(gpu_block_ids, cpu_block_ids, req_ids) for the store event.
(gpu_block_ids, cpu_block_ids, req_ids, block_meta) for the store
event. ``block_meta`` is None when kv cache events are disabled.
"""
merged_gpu_block_ids: list[int] = []
merged_cpu_block_ids: list[int] = []
req_ids: list[str] = []
merged_block_meta: list[dict[BlockHashWithGroupId, BlockStoreMeta]] | None = (
[] if self.enable_kv_cache_events else None
)
gpu_block_pool = self._gpu_block_pool
if gpu_block_pool is None:
return [], [], []
return [], [], [], merged_block_meta
cpu_block_pool = self.cpu_block_pool
kv_cache_groups = self.cpu_kv_cache_config.kv_cache_groups
num_groups = len(kv_cache_groups)
num_groups = len(self.cpu_kv_cache_config.kv_cache_groups)
# Dedup against blocks already scheduled.
in_flight = self._in_flight_store_gpu_blocks
@@ -558,13 +617,13 @@ class SimpleCPUOffloadScheduler:
if state is None or state.finished:
continue
# Accumulate new block IDs.
if preempted:
state.block_ids = tuple([] for _ in range(num_groups))
state.num_stored_blocks = [0] * num_groups
if new_block_id_groups:
for g in range(min(num_groups, len(new_block_id_groups))):
if new_block_id_groups[g] is not None:
# Accumulate new block IDs.
state.block_ids[g].extend(new_block_id_groups[g])
num_new_tokens = scheduler_output.num_scheduled_tokens.get(req_id, 0)
@@ -575,8 +634,8 @@ class SimpleCPUOffloadScheduler:
if not block_ids_by_group:
continue
gpu_block_ids, advanced_per_group = self._select_eager_blocks_to_store(
state, block_ids_by_group
gpu_block_ids, advanced_per_group, block_meta = (
self._select_eager_blocks_to_store(state, block_ids_by_group)
)
# --- Phase 2: Batch allocate CPU blocks ---
@@ -592,6 +651,9 @@ class SimpleCPUOffloadScheduler:
merged_gpu_block_ids.extend(gpu_block_ids)
merged_cpu_block_ids.extend(cpu_block_ids)
in_flight.update(gpu_block_ids)
if merged_block_meta is not None:
assert block_meta is not None
merged_block_meta.extend(block_meta)
# Touch GPU blocks to prevent freeing during async copy
gpu_block_pool.touch(
@@ -609,20 +671,26 @@ class SimpleCPUOffloadScheduler:
for g in range(num_groups):
state.num_stored_blocks[g] += advanced_per_group[g]
return merged_gpu_block_ids, merged_cpu_block_ids, req_ids
return merged_gpu_block_ids, merged_cpu_block_ids, req_ids, merged_block_meta
def _select_eager_blocks_to_store(
self,
state: StoreRequestState,
block_ids_by_group: tuple[list[int], ...],
) -> tuple[list[int], list[int]]:
"""Return confirmed, uncached eager blocks and per-group cursor advances."""
) -> tuple[
list[int],
list[int],
list[dict[BlockHashWithGroupId, BlockStoreMeta]] | None,
]:
"""Return confirmed eager blocks, cursor advances, and event metadata."""
assert self._gpu_block_pool is not None
gpu_block_ids: list[int] = []
advanced_per_group = [0] * len(self.cpu_kv_cache_config.kv_cache_groups)
confirmed_tokens = (
state.request.num_computed_tokens - state.request.num_output_placeholders
block_meta: list[dict[BlockHashWithGroupId, BlockStoreMeta]] | None = (
[] if self.enable_kv_cache_events else None
)
request = state.request
confirmed_tokens = request.num_computed_tokens - request.num_output_placeholders
aligned_tokens = confirmed_tokens // self.block_size * self.block_size
num_free = self.cpu_block_pool.get_num_free_blocks()
@@ -637,7 +705,17 @@ class SimpleCPUOffloadScheduler:
* self.cp_world_size
)
ready = min(len(group_gpu_ids), aligned_tokens // group_size)
for gpu_block_id in group_gpu_ids[state.num_stored_blocks[g] : ready]:
resolved_hashes = (
resolve_block_hashes(
request.block_hashes, self.hash_block_size, group_size
)
if block_meta is not None
else None
)
curr_mm_idx = 0
secondary_mm_idx = 0
start = state.num_stored_blocks[g]
for i, gpu_block_id in enumerate(group_gpu_ids[start:ready], start=start):
gpu_block = self._gpu_block_pool.blocks[gpu_block_id]
if gpu_block.is_null or gpu_block.block_hash is None:
advanced_per_group[g] += 1
@@ -655,8 +733,65 @@ class SimpleCPUOffloadScheduler:
break
gpu_block_ids.append(gpu_block_id)
advanced_per_group[g] += 1
if block_meta is not None:
token_start = i * group_size
token_end = token_start + group_size
assert resolved_hashes is not None
parent_hash = (
None
if i == 0
else maybe_convert_block_hash(resolved_hashes[i - 1])
)
lora_req = request.lora_request
extra_keys, curr_mm_idx = generate_block_hash_extra_keys(
request, token_start, token_end, curr_mm_idx
)
meta_by_hash = {
gpu_block.block_hash: BlockStoreMeta(
token_ids=list(
request.all_token_ids[token_start:token_end]
),
parent_block_hash=parent_hash,
lora_id=lora_req.adapter_id if lora_req else None,
lora_name=lora_req.name if lora_req else None,
extra_keys=extra_keys,
)
}
first_hash_idx = token_start // self.hash_block_size
last_hash_idx = token_end // self.hash_block_size
for hash_idx in range(first_hash_idx, last_hash_idx):
block_hash = make_block_hash_with_group_id(
request.block_hashes[hash_idx], g
)
if block_hash == gpu_block.block_hash:
continue
hash_start = hash_idx * self.hash_block_size
hash_end = hash_start + self.hash_block_size
secondary_extra_keys, secondary_mm_idx = (
generate_block_hash_extra_keys(
request,
hash_start,
hash_end,
secondary_mm_idx,
)
)
meta_by_hash[block_hash] = BlockStoreMeta(
token_ids=list(request.all_token_ids[hash_start:hash_end]),
parent_block_hash=(
None
if hash_idx == 0
else maybe_convert_block_hash(
request.block_hashes[hash_idx - 1]
)
),
lora_id=lora_req.adapter_id if lora_req else None,
lora_name=lora_req.name if lora_req else None,
extra_keys=secondary_extra_keys,
block_size=self.hash_block_size,
)
block_meta.append(meta_by_hash)
return gpu_block_ids, advanced_per_group
return gpu_block_ids, advanced_per_group, block_meta
def update_connector_output(self, connector_output: KVConnectorOutput) -> None:
"""Handle async transfer completions from worker.
@@ -695,7 +830,11 @@ class SimpleCPUOffloadScheduler:
if not self._lazy_mode:
self._in_flight_store_gpu_blocks.difference_update(transfer.gpu_block_ids)
self._process_store_completion(transfer.gpu_block_ids, transfer.cpu_block_ids)
self._process_store_completion(
transfer.gpu_block_ids,
transfer.cpu_block_ids,
transfer.block_meta,
)
logger.debug(
"Store event %d completed: cached %d blocks to CPU",
event_idx,
@@ -713,15 +852,19 @@ class SimpleCPUOffloadScheduler:
self._cleanup_store_request(req_id)
def _process_store_completion(
self, gpu_block_ids: list[int], cpu_block_ids: list[int]
self,
gpu_block_ids: list[int],
cpu_block_ids: list[int],
block_meta: list[dict[BlockHashWithGroupId, BlockStoreMeta]] | None = None,
) -> None:
"""Register copied blocks in the CPU prefix cache and release refs."""
assert len(cpu_block_ids) == len(gpu_block_ids)
assert block_meta is None or len(block_meta) == len(gpu_block_ids)
cpu_blocks = [self.cpu_block_pool.blocks[bid] for bid in cpu_block_ids]
assert self._gpu_block_pool is not None
for gpu_block_id, cpu_block in zip(gpu_block_ids, cpu_blocks):
for i, (gpu_block_id, cpu_block) in enumerate(zip(gpu_block_ids, cpu_blocks)):
gpu_block = self._gpu_block_pool.blocks[gpu_block_id]
primary_hash = gpu_block.block_hash
assert primary_hash is not None
@@ -737,6 +880,76 @@ class SimpleCPUOffloadScheduler:
self.cpu_block_pool._insert_block_hash(
block_hash, cpu_block, num_tokens=None
)
if self.enable_kv_cache_events:
meta_by_hash = block_meta[i] if block_meta is not None else {}
primary_group_idx = get_group_id(primary_hash)
primary_spec = self.cpu_kv_cache_config.kv_cache_groups[
primary_group_idx
].kv_cache_spec
primary_block_size = primary_spec.block_size * (
self.cp_world_size if not isinstance(primary_spec, MambaSpec) else 1
)
events_to_emit: list[
tuple[BlockHashWithGroupId, BlockStoreMeta | None, int]
] = [
(
primary_hash,
meta_by_hash.get(primary_hash),
primary_block_size,
)
]
for secondary_hash in secondary_hashes:
secondary_meta = meta_by_hash.get(secondary_hash)
events_to_emit.append(
(
secondary_hash,
secondary_meta,
secondary_meta.block_size
if secondary_meta is not None
and secondary_meta.block_size is not None
else 0,
)
)
for block_hash, meta, event_block_size in events_to_emit:
group_idx = get_group_id(block_hash)
spec = self.cpu_kv_cache_config.kv_cache_groups[
group_idx
].kv_cache_spec
if meta is not None and len(meta.token_ids) != event_block_size:
# token_ids were sliced with a different g_block_size
# (e.g. Mamba+DCP where capture uses spec.block_size *
# cp_world_size but the event emits spec.block_size * 1).
# Emit empty metadata until #49962 fixes the sizing.
token_ids = []
parent_block_hash = None
extra_keys = None
else:
token_ids = meta.token_ids if meta else []
parent_block_hash = meta.parent_block_hash if meta else None
extra_keys = meta.extra_keys if meta else None
self.cpu_block_pool.kv_event_queue.append(
BlockStored(
block_hashes=[
maybe_convert_block_hash(get_block_hash(block_hash))
],
parent_block_hash=parent_block_hash,
token_ids=token_ids,
block_size=event_block_size,
lora_id=meta.lora_id if meta else None,
medium=self.kv_event_medium,
lora_name=meta.lora_name if meta else None,
extra_keys=(
[extra_keys] if extra_keys is not None else None
),
group_idx=group_idx,
kv_cache_spec_kind=get_kv_cache_spec_kind(spec).value,
kv_cache_spec_sliding_window=(
get_kv_cache_spec_sliding_window(spec)
),
locality="LOCAL",
)
)
# Free CPU and GPU blocks' ref counts to turn them into prefix cache
self.cpu_block_pool.free_blocks(cpu_blocks)
@@ -811,12 +1024,12 @@ class SimpleCPUOffloadScheduler:
gpu_pool = self._gpu_block_pool
if state is None or gpu_pool is None:
return
gpu_ids, _ = self._select_eager_blocks_to_store(state, block_ids)
gpu_ids, _, block_meta = self._select_eager_blocks_to_store(state, block_ids)
if not gpu_ids:
return
cpu_blocks = self.cpu_block_pool.get_new_blocks(len(gpu_ids))
self._pending_finished_stores.append(
TransferMeta(gpu_ids, [b.block_id for b in cpu_blocks])
TransferMeta(gpu_ids, [b.block_id for b in cpu_blocks], block_meta)
)
self._in_flight_store_gpu_blocks.update(gpu_ids)
gpu_pool.touch([gpu_pool.blocks[bid] for bid in gpu_ids])
@@ -882,7 +1095,12 @@ class SimpleCPUOffloadScheduler:
state.store_events.clear()
def take_events(self) -> Iterable[KVCacheEvent]:
return self.cpu_block_pool.take_events()
events = self.cpu_block_pool.take_events()
for event in events:
if isinstance(event, BlockRemoved):
event.medium = self.kv_event_medium
event.locality = "LOCAL"
return events
def reset(self) -> bool:
"""Abandon pending transfers and reset the CPU cache when safe.