[AuxOutput] Add block-keyed storage for routed-expert outputs (#45635)
Signed-off-by: aoshen02 <aoshen@inferact.ai> Signed-off-by: Nick Hill <nickhill123@gmail.com> Co-authored-by: aoshen02 <aoshen@inferact.ai> Co-authored-by: OpenAI Codex <codex@openai.com> Co-authored-by: Roger Wang <hey@rogerw.io> Co-authored-by: Nick Hill <nickhill123@gmail.com> Co-authored-by: Codex <noreply@openai.com>
This commit is contained in:
co-authored by
aoshen02
OpenAI Codex
Roger Wang
Nick Hill
Codex
parent
0aee727ff6
commit
0b7f11a1ee
@@ -0,0 +1,2 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
@@ -0,0 +1,157 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Scheduler-side control plane for execution auxiliary outputs."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Iterator, Sequence
|
||||
from dataclasses import dataclass
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import numpy as np
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.v1.core.sched.output import SchedulerOutput
|
||||
from vllm.v1.request import Request
|
||||
|
||||
|
||||
@dataclass
|
||||
class PackedBlockHashes:
|
||||
"""Contiguous, self-contained block hashes for scheduler-worker IPC."""
|
||||
|
||||
data: bytes
|
||||
item_size: int
|
||||
|
||||
def __iter__(self) -> Iterator[bytes]:
|
||||
for start in range(0, len(self.data), self.item_size):
|
||||
yield self.data[start : start + self.item_size]
|
||||
|
||||
|
||||
@dataclass
|
||||
class AuxOutputConnectorMetadata:
|
||||
generation: int
|
||||
requests: dict[str, int]
|
||||
block_hashes: dict[str, PackedBlockHashes]
|
||||
finished_requests: tuple[str, ...]
|
||||
|
||||
|
||||
@dataclass
|
||||
class AuxRequestOutput:
|
||||
token_start: int
|
||||
rows: np.ndarray
|
||||
|
||||
|
||||
class AuxOutputSchedulerConnector:
|
||||
"""Build worker metadata without owning auxiliary output payloads or stores."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
# Number of hashes already sent to the worker for each active request.
|
||||
self._sent_hash_counts: dict[str, int] = {}
|
||||
# Terminal events are delivered with the next connector metadata.
|
||||
self._finished_requests: dict[str, PackedBlockHashes | None] = {}
|
||||
self._generation = 0
|
||||
|
||||
def build_connector_meta(
|
||||
self,
|
||||
scheduler_output: SchedulerOutput,
|
||||
requests: dict[str, Request],
|
||||
) -> AuxOutputConnectorMetadata:
|
||||
"""Build one step's incremental worker metadata."""
|
||||
scheduled_requests: dict[str, int] = {}
|
||||
block_hashes_by_request: dict[str, PackedBlockHashes] = {}
|
||||
for request_id in scheduler_output.num_scheduled_tokens:
|
||||
num_sent = self._sent_hash_counts.setdefault(request_id, 0)
|
||||
request = requests[request_id]
|
||||
packed = self._pack_new_hashes(request.block_hashes, num_sent)
|
||||
if packed is not None:
|
||||
block_hashes_by_request[request_id] = packed
|
||||
self._sent_hash_counts[request_id] = len(request.block_hashes)
|
||||
assert request.sampling_params is not None
|
||||
scheduled_requests[request_id] = max(
|
||||
request.sampling_params.routed_experts_prompt_start,
|
||||
0 if request.num_output_tokens == 0 else request.num_tokens - 1,
|
||||
)
|
||||
# A settled token can complete a hash block after the next async schedule
|
||||
# was built. Send a hash-only update if the request was not rescheduled.
|
||||
if len(self._sent_hash_counts) != len(scheduled_requests):
|
||||
for request_id, num_sent in self._sent_hash_counts.items():
|
||||
if request_id in scheduled_requests:
|
||||
continue
|
||||
request = requests[request_id]
|
||||
packed = self._pack_new_hashes(request.block_hashes, num_sent)
|
||||
if packed is None:
|
||||
continue
|
||||
block_hashes_by_request[request_id] = packed
|
||||
self._sent_hash_counts[request_id] = len(request.block_hashes)
|
||||
# Sending transfers ownership of these one-shot events.
|
||||
finished_requests = tuple(self._finished_requests)
|
||||
block_hashes_by_request.update(
|
||||
(request_id, block_hashes)
|
||||
for request_id, block_hashes in self._finished_requests.items()
|
||||
if block_hashes is not None
|
||||
)
|
||||
self._finished_requests = {}
|
||||
return AuxOutputConnectorMetadata(
|
||||
self._generation,
|
||||
scheduled_requests,
|
||||
block_hashes_by_request,
|
||||
finished_requests,
|
||||
)
|
||||
|
||||
def take_output(
|
||||
self,
|
||||
request: Request,
|
||||
output: dict[str, AuxRequestOutput] | None,
|
||||
) -> np.ndarray | None:
|
||||
"""Return the accepted R3 rows for one scheduled request."""
|
||||
request_id = request.request_id
|
||||
assert output is not None and request_id in output, (
|
||||
f"auxiliary output worker output is missing {request_id}"
|
||||
)
|
||||
request_output = output[request_id]
|
||||
token_end = request.num_tokens - 1
|
||||
local_end = token_end - request_output.token_start
|
||||
if local_end < 0:
|
||||
assert not request.is_finished(), (
|
||||
"finished auxiliary output output has no accepted token range: "
|
||||
f"request={request_id}, token_end={token_end}, "
|
||||
f"output_start={request_output.token_start}, "
|
||||
"output_end="
|
||||
f"{request_output.token_start + len(request_output.rows)}"
|
||||
)
|
||||
return None
|
||||
assert local_end <= len(request_output.rows), (
|
||||
"auxiliary output worker output has an invalid token range: "
|
||||
f"request={request_id}, token_end={token_end}, "
|
||||
f"output_start={request_output.token_start}, "
|
||||
f"output_end={request_output.token_start + len(request_output.rows)}"
|
||||
)
|
||||
return request_output.rows[:local_end]
|
||||
|
||||
def request_finished(self, request: Request) -> None:
|
||||
"""Queue a request's terminal event and final block hashes."""
|
||||
request_id = request.request_id
|
||||
num_sent = self._sent_hash_counts.pop(request_id, None)
|
||||
if num_sent is None:
|
||||
return
|
||||
# The next metadata delivers this terminal event to the worker.
|
||||
self._finished_requests[request_id] = self._pack_new_hashes(
|
||||
request.block_hashes, num_sent
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _pack_new_hashes(
|
||||
block_hashes: Sequence[bytes], num_sent: int
|
||||
) -> PackedBlockHashes | None:
|
||||
assert num_sent <= len(block_hashes), "KV block-hash history shrank"
|
||||
new_hashes = block_hashes[num_sent:]
|
||||
if not new_hashes:
|
||||
return None
|
||||
return PackedBlockHashes(b"".join(new_hashes), len(new_hashes[0]))
|
||||
|
||||
def reset(self) -> None:
|
||||
"""Start a new auxiliary output namespace after a prefix-cache reset."""
|
||||
# The worker drops temporary state on generation changes; resend hashes.
|
||||
self._sent_hash_counts.clear()
|
||||
self._finished_requests.clear()
|
||||
self._generation += 1
|
||||
@@ -0,0 +1,219 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Routed-experts auxiliary output keys, publication, and materialization."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Hashable, Iterable, Sequence
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
import numpy as np
|
||||
|
||||
from vllm.distributed.aux_output_connector.store import (
|
||||
BackgroundBlockObjectStore,
|
||||
BlockObject,
|
||||
BlockObjectStore,
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class _RequestTail:
|
||||
slot: int
|
||||
block_start: int
|
||||
length: int = 0
|
||||
|
||||
|
||||
class RoutedExpertsBuffer:
|
||||
"""Own incomplete and unkeyed full routed-experts blocks."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
dtype: np.dtype[Any],
|
||||
shape_per_token: tuple[int, ...],
|
||||
block_size: int,
|
||||
max_num_seqs: int,
|
||||
max_num_batched_tokens: int,
|
||||
max_concurrent_batches: int,
|
||||
) -> None:
|
||||
self.dtype = dtype
|
||||
self.shape_per_token = shape_per_token
|
||||
self.block_size = block_size
|
||||
max_step_blocks = (
|
||||
max_num_batched_tokens + block_size - 1
|
||||
) // block_size + max_num_seqs
|
||||
# In-flight full blocks plus one incomplete tail per active request.
|
||||
max_blocks = max_concurrent_batches * max_step_blocks + max_num_seqs
|
||||
self._rows: np.ndarray = np.empty(
|
||||
(max_blocks, block_size, *shape_per_token), dtype=dtype
|
||||
)
|
||||
self._free_slots = list(range(len(self._rows) - 1, -1, -1))
|
||||
self._owned_slots: dict[int, int] = {}
|
||||
self._requests: dict[Hashable, _RequestTail] = {}
|
||||
|
||||
def _tail(self, request_id: Hashable, block_start: int) -> _RequestTail:
|
||||
tail = self._requests.get(request_id)
|
||||
if tail is not None:
|
||||
assert tail.block_start == block_start, (
|
||||
"auxiliary output capture skipped an incomplete block: "
|
||||
f"request={request_id}, expected={tail.block_start}, "
|
||||
f"actual={block_start}"
|
||||
)
|
||||
return tail
|
||||
assert self._free_slots, "auxiliary output block pool is exhausted"
|
||||
tail = _RequestTail(self._free_slots.pop(), block_start)
|
||||
self._requests[request_id] = tail
|
||||
return tail
|
||||
|
||||
def capture(
|
||||
self, request_id: Hashable, token_start: int, rows: np.ndarray
|
||||
) -> list[tuple[int, np.ndarray]]:
|
||||
"""Stage rows and return completed blocks without retaining them."""
|
||||
rows = np.asarray(rows)
|
||||
assert rows.shape[1:] == self.shape_per_token and rows.dtype == self.dtype, (
|
||||
"routed-experts capture profile changed"
|
||||
)
|
||||
if token_start < 0:
|
||||
raise ValueError("auxiliary output token start must be non-negative")
|
||||
|
||||
completed: list[tuple[int, np.ndarray]] = []
|
||||
offset = 0
|
||||
while offset < len(rows):
|
||||
position = token_start + offset
|
||||
block_start = position // self.block_size * self.block_size
|
||||
local_start = position - block_start
|
||||
|
||||
# Full aligned input blocks do not need tail staging.
|
||||
if (
|
||||
request_id not in self._requests
|
||||
and local_start == 0
|
||||
and len(rows) - offset >= self.block_size
|
||||
):
|
||||
completed.append((block_start, rows[offset : offset + self.block_size]))
|
||||
offset += self.block_size
|
||||
continue
|
||||
|
||||
tail = self._tail(request_id, block_start)
|
||||
assert local_start == tail.length, (
|
||||
"auxiliary output capture is not contiguous: "
|
||||
f"request={request_id}, expected={block_start + tail.length}, "
|
||||
f"actual={position}"
|
||||
)
|
||||
count = min(self.block_size - local_start, len(rows) - offset)
|
||||
if count == 1:
|
||||
self._rows[tail.slot, local_start] = rows[offset]
|
||||
else:
|
||||
self._rows[tail.slot, local_start : local_start + count] = rows[
|
||||
offset : offset + count
|
||||
]
|
||||
tail.length += count
|
||||
offset += count
|
||||
if tail.length == self.block_size:
|
||||
block = self._rows[tail.slot]
|
||||
del self._requests[request_id]
|
||||
self._owned_slots[id(block)] = tail.slot
|
||||
completed.append((block_start, block))
|
||||
|
||||
return completed
|
||||
|
||||
def read(
|
||||
self, request_id: Hashable, token_start: int, token_end: int
|
||||
) -> np.ndarray:
|
||||
tail = self._requests.get(request_id)
|
||||
assert tail is not None, (
|
||||
f"auxiliary output buffer is missing request {request_id}"
|
||||
)
|
||||
local_start = token_start - tail.block_start
|
||||
local_end = token_end - tail.block_start
|
||||
assert 0 <= local_start < local_end <= tail.length, (
|
||||
"auxiliary output range is unavailable: "
|
||||
f"request={request_id}, range=[{token_start}, {token_end}), "
|
||||
f"available=[{tail.block_start}, {tail.block_start + tail.length})"
|
||||
)
|
||||
return self._rows[tail.slot, local_start:local_end].copy()
|
||||
|
||||
def retain_block(self, rows: np.ndarray) -> np.ndarray:
|
||||
"""Retain one unkeyed block after the current capture call."""
|
||||
if id(rows) in self._owned_slots:
|
||||
return rows
|
||||
assert self._free_slots, "auxiliary output block pool is exhausted"
|
||||
slot = self._free_slots.pop()
|
||||
retained = self._rows[slot]
|
||||
retained[...] = rows
|
||||
self._owned_slots[id(retained)] = slot
|
||||
return retained
|
||||
|
||||
def release_block(self, rows: np.ndarray) -> None:
|
||||
slot = self._owned_slots.pop(id(rows), None)
|
||||
if slot is not None:
|
||||
self._free_slots.append(slot)
|
||||
|
||||
def discard(self, request_id: Hashable) -> None:
|
||||
tail = self._requests.pop(request_id, None)
|
||||
if tail is not None:
|
||||
self._free_slots.append(tail.slot)
|
||||
|
||||
def reset(self) -> None:
|
||||
self._requests.clear()
|
||||
self._owned_slots.clear()
|
||||
self._free_slots[:] = range(len(self._rows) - 1, -1, -1)
|
||||
|
||||
|
||||
def routed_experts_keys(
|
||||
block_hashes: Iterable[bytes], aux_output_namespace: str
|
||||
) -> list[str]:
|
||||
prefix = f"vllm-artifact/{aux_output_namespace}/"
|
||||
return [prefix + block_hash.hex() for block_hash in block_hashes]
|
||||
|
||||
|
||||
def materialize_routed_experts(
|
||||
store: BackgroundBlockObjectStore | BlockObjectStore,
|
||||
aux_output_keys: list[str],
|
||||
*,
|
||||
shape_per_token: tuple[int, ...],
|
||||
dtype: np.dtype[Any],
|
||||
) -> np.ndarray:
|
||||
if not aux_output_keys:
|
||||
raise ValueError("routed-experts auxiliary output key list must not be empty")
|
||||
payload = store.get_concatenated(aux_output_keys)
|
||||
return np.frombuffer(payload, dtype=dtype).reshape((-1, *shape_per_token))
|
||||
|
||||
|
||||
def publish_routed_experts(
|
||||
store: BackgroundBlockObjectStore | BlockObjectStore,
|
||||
*,
|
||||
batches: Sequence[tuple[Sequence[str], list[tuple[int, np.ndarray]]]],
|
||||
block_size: int,
|
||||
retain_keys: Sequence[str] = (),
|
||||
release_keys: Sequence[str] = (),
|
||||
) -> None:
|
||||
"""Publish immutable full R3 blocks."""
|
||||
objects = []
|
||||
for aux_output_keys, blocks in batches:
|
||||
for block_start, array in blocks:
|
||||
if block_start < 0 or block_start % block_size:
|
||||
raise ValueError(
|
||||
"auxiliary output block start is not hash-block aligned"
|
||||
)
|
||||
block_index = block_start // block_size
|
||||
if block_index >= len(aux_output_keys):
|
||||
raise ValueError(
|
||||
"auxiliary output block has no corresponding key: "
|
||||
f"start={block_start}, index={block_index}, "
|
||||
f"keys={len(aux_output_keys)}, block_size={block_size}"
|
||||
)
|
||||
if len(array) != block_size:
|
||||
raise ValueError(
|
||||
"auxiliary output block length does not match hash block size"
|
||||
)
|
||||
objects.append(
|
||||
BlockObject(
|
||||
key=aux_output_keys[block_index],
|
||||
payload=array.tobytes(order="C"),
|
||||
)
|
||||
)
|
||||
store.put(
|
||||
objects,
|
||||
retain_keys=retain_keys,
|
||||
release_keys=release_keys,
|
||||
)
|
||||
@@ -0,0 +1,234 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""In-process auxiliary-output storage."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import mmap
|
||||
import queue
|
||||
import threading
|
||||
from collections import OrderedDict
|
||||
from collections.abc import Iterable
|
||||
from dataclasses import dataclass
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class BlockObject:
|
||||
"""One immutable auxiliary output object."""
|
||||
|
||||
key: str
|
||||
payload: bytes
|
||||
|
||||
|
||||
class BlockObjectStoreError(RuntimeError):
|
||||
"""AuxOutput storage or retrieval failed."""
|
||||
|
||||
|
||||
class BackgroundBlockObjectStore:
|
||||
"""Serialize store mutations on a background thread."""
|
||||
|
||||
def __init__(self, store: BlockObjectStore, *, max_pending_batches: int) -> None:
|
||||
self._store = store
|
||||
self._queue: queue.Queue[
|
||||
tuple[list[BlockObject], tuple[str, ...], tuple[str, ...]] | None
|
||||
] = queue.Queue(maxsize=max_pending_batches)
|
||||
self._error: BaseException | None = None
|
||||
self._closed = False
|
||||
self._thread = threading.Thread(
|
||||
target=self._run,
|
||||
daemon=True,
|
||||
name="vllm-aux-output-writer",
|
||||
)
|
||||
self._thread.start()
|
||||
|
||||
def _run(self) -> None:
|
||||
while True:
|
||||
update = self._queue.get()
|
||||
try:
|
||||
if update is None:
|
||||
return
|
||||
if self._error is None:
|
||||
objects, retain_keys, release_keys = update
|
||||
self._store.put(
|
||||
objects,
|
||||
retain_keys=retain_keys,
|
||||
release_keys=release_keys,
|
||||
)
|
||||
except BaseException as error:
|
||||
self._error = error
|
||||
finally:
|
||||
self._queue.task_done()
|
||||
|
||||
def _raise_if_failed(self) -> None:
|
||||
if self._error is not None:
|
||||
raise BlockObjectStoreError(
|
||||
"auxiliary output publication failed"
|
||||
) from self._error
|
||||
|
||||
def put(
|
||||
self,
|
||||
objects: list[BlockObject],
|
||||
*,
|
||||
retain_keys: Iterable[str] = (),
|
||||
release_keys: Iterable[str] = (),
|
||||
) -> None:
|
||||
retains = tuple(retain_keys)
|
||||
releases = tuple(release_keys)
|
||||
if not objects and not retains and not releases:
|
||||
return
|
||||
if self._closed:
|
||||
raise RuntimeError("auxiliary output store is closed")
|
||||
self._queue.put((objects, retains, releases))
|
||||
self._raise_if_failed()
|
||||
|
||||
def get_concatenated(self, keys: list[str]) -> bytes:
|
||||
self._queue.join()
|
||||
self._raise_if_failed()
|
||||
return self._store.get_concatenated(keys)
|
||||
|
||||
def close(self) -> None:
|
||||
if self._closed:
|
||||
return
|
||||
self._closed = True
|
||||
self._queue.join()
|
||||
self._queue.put(None)
|
||||
self._thread.join()
|
||||
self._store.close()
|
||||
self._raise_if_failed()
|
||||
|
||||
|
||||
class BlockObjectStore:
|
||||
"""Single-owner bounded store that fails closed after an eviction."""
|
||||
|
||||
_UNALLOCATED_SLOT = -1
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
max_bytes: int,
|
||||
object_nbytes: int,
|
||||
) -> None:
|
||||
if object_nbytes <= 0:
|
||||
raise ValueError("auxiliary output object size must be positive")
|
||||
if max_bytes < object_nbytes:
|
||||
raise ValueError("auxiliary output store must fit at least one object")
|
||||
self.object_nbytes = object_nbytes
|
||||
self.num_slots = max_bytes // object_nbytes
|
||||
self._lru: OrderedDict[str, int] = OrderedDict()
|
||||
self._references: dict[str, int] = {}
|
||||
self._free_slots: list[int] = []
|
||||
self._next_slot = 0
|
||||
self._arena: mmap.mmap | None = mmap.mmap(
|
||||
-1, self.num_slots * self.object_nbytes
|
||||
)
|
||||
|
||||
def _evict_to_fit(self, protected: set[str]) -> None:
|
||||
excess = len(self._lru) - self.num_slots
|
||||
if excess <= 0:
|
||||
return
|
||||
victims = []
|
||||
for key in self._lru:
|
||||
if key not in self._references and key not in protected:
|
||||
victims.append(key)
|
||||
if len(victims) == excess:
|
||||
break
|
||||
if len(victims) != excess:
|
||||
raise BlockObjectStoreError(
|
||||
"auxiliary output store cannot retain the requested batch: "
|
||||
f"limit={self.num_slots} objects"
|
||||
)
|
||||
for victim in victims:
|
||||
slot = self._lru.pop(victim)
|
||||
if slot != self._UNALLOCATED_SLOT:
|
||||
self._free_slots.append(slot)
|
||||
|
||||
def _allocate_slot(self) -> int:
|
||||
if self._free_slots:
|
||||
return self._free_slots.pop()
|
||||
slot = self._next_slot
|
||||
self._next_slot += 1
|
||||
return slot
|
||||
|
||||
def put(
|
||||
self,
|
||||
objects: list[BlockObject],
|
||||
*,
|
||||
retain_keys: Iterable[str] = (),
|
||||
release_keys: Iterable[str] = (),
|
||||
) -> None:
|
||||
arena = self._arena
|
||||
if arena is None:
|
||||
raise RuntimeError("auxiliary output store is closed")
|
||||
unique = {obj.key: obj for obj in objects}
|
||||
self._retain(retain_keys)
|
||||
terminal_order = self._release(release_keys)
|
||||
for key in unique:
|
||||
self._lru.setdefault(key, self._UNALLOCATED_SLOT)
|
||||
self._lru.move_to_end(key)
|
||||
for key in terminal_order:
|
||||
if key in self._lru:
|
||||
self._lru.move_to_end(key)
|
||||
try:
|
||||
self._evict_to_fit(set(unique) - set(terminal_order))
|
||||
except BlockObjectStoreError:
|
||||
for key in unique:
|
||||
if self._lru.get(key) == self._UNALLOCATED_SLOT:
|
||||
del self._lru[key]
|
||||
raise
|
||||
for object_id, obj in unique.items():
|
||||
slot = self._lru.get(object_id)
|
||||
if slot is None:
|
||||
continue
|
||||
if slot != self._UNALLOCATED_SLOT:
|
||||
continue
|
||||
slot = self._allocate_slot()
|
||||
offset = slot * self.object_nbytes
|
||||
arena[offset : offset + self.object_nbytes] = obj.payload
|
||||
self._lru[object_id] = slot
|
||||
|
||||
def _retain(self, keys: Iterable[str]) -> None:
|
||||
for key in keys:
|
||||
references = self._references.get(key, 0)
|
||||
self._references[key] = references + 1
|
||||
|
||||
def _release(self, keys: Iterable[str]) -> list[str]:
|
||||
terminal_order = []
|
||||
for key in keys:
|
||||
references = self._references[key] - 1
|
||||
if references:
|
||||
self._references[key] = references
|
||||
continue
|
||||
del self._references[key]
|
||||
terminal_order.append(key)
|
||||
return terminal_order
|
||||
|
||||
def get_concatenated(self, keys: list[str]) -> bytes:
|
||||
arena_obj = self._arena
|
||||
if arena_obj is None:
|
||||
raise RuntimeError("auxiliary output store is closed")
|
||||
try:
|
||||
entries = [self._lru[key] for key in keys]
|
||||
except KeyError as error:
|
||||
raise BlockObjectStoreError(
|
||||
"auxiliary output object does not exist; the object may have been "
|
||||
f"evicted (used={len(self._lru)}, "
|
||||
f"limit={self.num_slots} objects). Increase "
|
||||
"aux_output_config.max_bytes when a KV cache hit requires it."
|
||||
) from error
|
||||
arena = memoryview(arena_obj)
|
||||
try:
|
||||
payload = b"".join(
|
||||
arena[slot * self.object_nbytes : (slot + 1) * self.object_nbytes]
|
||||
for slot in entries
|
||||
)
|
||||
finally:
|
||||
arena.release()
|
||||
for key in keys:
|
||||
self._lru.move_to_end(key)
|
||||
return payload
|
||||
|
||||
def close(self) -> None:
|
||||
arena = self._arena
|
||||
if arena is not None:
|
||||
self._arena = None
|
||||
arena.close()
|
||||
@@ -0,0 +1,412 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Worker-side auxiliary-output data plane."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Iterable, Sequence
|
||||
from dataclasses import dataclass, field
|
||||
from threading import Lock
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.distributed.aux_output_connector.connector import (
|
||||
AuxOutputConnectorMetadata,
|
||||
AuxRequestOutput,
|
||||
)
|
||||
from vllm.distributed.aux_output_connector.routed_experts import (
|
||||
RoutedExpertsBuffer,
|
||||
materialize_routed_experts,
|
||||
publish_routed_experts,
|
||||
routed_experts_keys,
|
||||
)
|
||||
from vllm.distributed.aux_output_connector.store import (
|
||||
BackgroundBlockObjectStore,
|
||||
BlockObjectStore,
|
||||
)
|
||||
from vllm.distributed.parallel_state import get_tp_group
|
||||
from vllm.model_executor.layers.fused_moe.routed_experts_capturer import (
|
||||
RoutedExpertsCapturer,
|
||||
bind_routed_experts_capturer,
|
||||
)
|
||||
from vllm.v1.core.kv_cache_utils import resolve_kv_cache_block_sizes
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.v1.kv_cache_interface import KVCacheConfig
|
||||
from vllm.v1.worker.gpu.input_batch import InputBatch
|
||||
|
||||
|
||||
@dataclass
|
||||
class _WorkerRequestState:
|
||||
aux_output_keys: list[str] = field(default_factory=list)
|
||||
pending_blocks: list[tuple[int, np.ndarray]] = field(default_factory=list)
|
||||
capture_cursor: int | None = None
|
||||
scheduled_cursor: int = 0
|
||||
emit_cursor: int = 0
|
||||
pending_outputs: int = 0
|
||||
# Terminal event received; teardown waits for in-flight step outputs.
|
||||
finished: bool = False
|
||||
|
||||
|
||||
@dataclass
|
||||
class PendingAuxOutput:
|
||||
"""Own one step's R3 snapshot until its asynchronous copy is consumed."""
|
||||
|
||||
connector: AuxOutputWorkerConnector
|
||||
request_ids: list[str]
|
||||
token_starts: np.ndarray
|
||||
query_start_loc: np.ndarray
|
||||
# GPU snapshot taken on the main stream.
|
||||
routed_experts_gpu: torch.Tensor
|
||||
# Filled by enqueue_cpu_copy on the output copy stream.
|
||||
routed_experts: np.ndarray | None = None
|
||||
num_sampled: np.ndarray | None = None
|
||||
num_rejected: np.ndarray | None = None
|
||||
|
||||
def enqueue_cpu_copy(
|
||||
self, num_sampled: np.ndarray, num_rejected: np.ndarray
|
||||
) -> None:
|
||||
"""Enqueue asynchronous D2H copies; call on the output copy stream."""
|
||||
self.num_sampled = num_sampled
|
||||
self.num_rejected = num_rejected
|
||||
self.routed_experts = self.routed_experts_gpu.to(
|
||||
"cpu", non_blocking=True
|
||||
).numpy()
|
||||
|
||||
def process_output(self) -> dict[str, AuxRequestOutput]:
|
||||
return self.connector.process_output(self)
|
||||
|
||||
|
||||
class AuxOutputWorkerConnector:
|
||||
"""Own capture, request tails, and backend resources on the output worker."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
vllm_config: VllmConfig,
|
||||
model: torch.nn.Module,
|
||||
kv_cache_config: KVCacheConfig,
|
||||
) -> None:
|
||||
max_num_batched_tokens = vllm_config.scheduler_config.max_num_batched_tokens
|
||||
capturer = RoutedExpertsCapturer(
|
||||
max_num_batched_tokens=max_num_batched_tokens, vllm_config=vllm_config
|
||||
)
|
||||
bind_routed_experts_capturer(model, capturer)
|
||||
self._capturer = capturer
|
||||
self._store: BackgroundBlockObjectStore | None = None
|
||||
self._buffer: RoutedExpertsBuffer | None = None
|
||||
self._requests: dict[str, _WorkerRequestState] = {}
|
||||
self._generation = 0
|
||||
self._step_metadata: AuxOutputConnectorMetadata | None = None
|
||||
# Steps whose asynchronous copy has not been consumed yet. The engine
|
||||
# consumes step outputs in order, so at most max_concurrent_batches
|
||||
# are outstanding; guarded by _lock against the output thread.
|
||||
self._pending_outputs: list[PendingAuxOutput] = []
|
||||
self._lock = Lock()
|
||||
self._max_concurrent_batches = vllm_config.max_concurrent_batches
|
||||
# Every TP rank participates in capture collectives, but only the
|
||||
# executor output rank owns the auxiliary output data plane.
|
||||
if not get_tp_group().is_first_rank:
|
||||
return
|
||||
|
||||
shape_per_token = self._capturer.shape_per_token
|
||||
dtype: np.dtype[Any] = np.dtype(self._capturer.output_dtype_name)
|
||||
scheduler_block_size, hash_block_size = resolve_kv_cache_block_sizes(
|
||||
kv_cache_config, vllm_config
|
||||
)
|
||||
hashes_per_kv_block = scheduler_block_size // hash_block_size
|
||||
block_nbytes = hash_block_size * int(np.prod(shape_per_token)) * dtype.itemsize
|
||||
max_bytes = vllm_config.aux_output_config.max_bytes
|
||||
if max_bytes is None:
|
||||
max_bytes = kv_cache_config.num_blocks * hashes_per_kv_block * block_nbytes
|
||||
self._store = BackgroundBlockObjectStore(
|
||||
BlockObjectStore(max_bytes=max_bytes, object_nbytes=block_nbytes),
|
||||
max_pending_batches=2 * vllm_config.scheduler_config.max_num_seqs,
|
||||
)
|
||||
self._buffer = RoutedExpertsBuffer(
|
||||
dtype,
|
||||
shape_per_token,
|
||||
hash_block_size,
|
||||
vllm_config.scheduler_config.max_num_seqs,
|
||||
max_num_batched_tokens,
|
||||
vllm_config.max_concurrent_batches,
|
||||
)
|
||||
|
||||
def prepare_output(self, input_batch: InputBatch) -> PendingAuxOutput | None:
|
||||
"""Snapshot one step's R3 tensor for asynchronous CPU transfer."""
|
||||
if self._buffer is None or self._step_metadata is None:
|
||||
return None
|
||||
|
||||
request_ids = list(input_batch.req_ids)
|
||||
query_start_loc = input_batch.query_start_loc_np[: len(request_ids) + 1]
|
||||
num_rows = int(query_start_loc[-1])
|
||||
pending_output = PendingAuxOutput(
|
||||
connector=self,
|
||||
request_ids=request_ids,
|
||||
token_starts=input_batch.num_computed_tokens_np,
|
||||
query_start_loc=query_start_loc,
|
||||
routed_experts_gpu=self._capturer.snapshot_routing_data(num_rows),
|
||||
)
|
||||
with self._lock:
|
||||
assert len(self._pending_outputs) < self._max_concurrent_batches, (
|
||||
"auxiliary output step outputs are not consumed in order"
|
||||
)
|
||||
self._pending_outputs.append(pending_output)
|
||||
for request_id in pending_output.request_ids:
|
||||
self._requests[request_id].pending_outputs += 1
|
||||
return pending_output
|
||||
|
||||
def process_output(self, pending: PendingAuxOutput) -> dict[str, AuxRequestOutput]:
|
||||
"""Commit one consumed R3 snapshot and build request outputs.
|
||||
|
||||
Request teardown deferred by begin_step is completed here once no
|
||||
in-flight step covers the request.
|
||||
"""
|
||||
with self._lock:
|
||||
teardown = []
|
||||
release_keys: list[str] = []
|
||||
try:
|
||||
outputs = self._commit_output(pending)
|
||||
finally:
|
||||
self._pending_outputs.remove(pending)
|
||||
for request_id in pending.request_ids:
|
||||
state = self._requests[request_id]
|
||||
state.pending_outputs -= 1
|
||||
if state.pending_outputs == 0 and state.finished:
|
||||
teardown.append(request_id)
|
||||
release_keys.extend(reversed(state.aux_output_keys))
|
||||
if teardown:
|
||||
self._publish_blocks([], release_keys=release_keys)
|
||||
self._teardown(teardown)
|
||||
return outputs
|
||||
|
||||
def _commit_output(self, pending: PendingAuxOutput) -> dict[str, AuxRequestOutput]:
|
||||
buffer = self._buffer
|
||||
store = self._store
|
||||
assert buffer is not None and store is not None
|
||||
block_size = buffer.block_size
|
||||
|
||||
routed_experts = pending.routed_experts
|
||||
num_sampled = pending.num_sampled
|
||||
num_rejected = pending.num_rejected
|
||||
assert (
|
||||
routed_experts is not None
|
||||
and num_sampled is not None
|
||||
and num_rejected is not None
|
||||
), "auxiliary output CPU copy was not enqueued"
|
||||
|
||||
# Publish the whole batch before materializing any consumer output.
|
||||
materialize_outputs: list[tuple[str, int, int]] = []
|
||||
block_batches = []
|
||||
outputs: dict[str, AuxRequestOutput] = {}
|
||||
|
||||
# Use the ModelRunner's actual batch boundaries rather than rebuilding them.
|
||||
for request_id, token_start, start, end, sampled, rejected in zip(
|
||||
pending.request_ids,
|
||||
pending.token_starts,
|
||||
pending.query_start_loc[:-1],
|
||||
pending.query_start_loc[1:],
|
||||
num_sampled,
|
||||
num_rejected,
|
||||
strict=True,
|
||||
):
|
||||
request_num_tokens = end - start
|
||||
assert request_num_tokens > 0, (
|
||||
"auxiliary output request token count must be positive"
|
||||
)
|
||||
state = self._requests[request_id]
|
||||
|
||||
# Capture precedes speculative acceptance, so discard the rejected
|
||||
# suffix. Batch boundaries still span the full executed range.
|
||||
rejected = int(rejected)
|
||||
assert 0 <= rejected <= request_num_tokens, (
|
||||
"auxiliary output rejected-token count is invalid"
|
||||
)
|
||||
rows = routed_experts[start : end - rejected]
|
||||
|
||||
capture_start = token_start
|
||||
capture_cursor = state.capture_cursor
|
||||
if capture_cursor is None:
|
||||
capture_cursor = capture_start
|
||||
|
||||
assert capture_start >= capture_cursor, (
|
||||
"auxiliary output capture moved backwards"
|
||||
)
|
||||
if capture_start > capture_cursor:
|
||||
# Reattach after an optimistically scheduled suffix was rejected.
|
||||
assert capture_cursor < state.scheduled_cursor, (
|
||||
"auxiliary output capture has an unbacked token gap"
|
||||
)
|
||||
capture_start = capture_cursor
|
||||
|
||||
emit_start = state.emit_cursor
|
||||
# Complete blocks without keys remain pending until a hash update.
|
||||
completed = buffer.capture(request_id, capture_start, rows)
|
||||
token_end = capture_start + len(rows)
|
||||
state.capture_cursor = token_end
|
||||
state.scheduled_cursor = token_start + request_num_tokens
|
||||
block_batches.append((state, completed))
|
||||
|
||||
if sampled > 0 and emit_start <= token_end:
|
||||
if emit_start >= capture_start:
|
||||
outputs[request_id] = AuxRequestOutput(
|
||||
emit_start, rows[emit_start - capture_start :]
|
||||
)
|
||||
state.emit_cursor = token_end
|
||||
else:
|
||||
materialize_outputs.append((request_id, emit_start, token_end))
|
||||
|
||||
# A consumer may reuse a block produced earlier in the same batch.
|
||||
self._publish_blocks(block_batches)
|
||||
|
||||
for request_id, emit_start, token_end in materialize_outputs:
|
||||
state = self._requests[request_id]
|
||||
stored_end = (
|
||||
min(token_end // block_size, len(state.aux_output_keys)) * block_size
|
||||
)
|
||||
if emit_start < stored_end:
|
||||
first_block = emit_start // block_size
|
||||
stored = materialize_routed_experts(
|
||||
store,
|
||||
state.aux_output_keys[first_block : stored_end // block_size],
|
||||
shape_per_token=buffer.shape_per_token,
|
||||
dtype=buffer.dtype,
|
||||
)
|
||||
local_start = emit_start % block_size
|
||||
rows = stored[local_start : local_start + stored_end - emit_start]
|
||||
if stored_end < token_end:
|
||||
rows = np.concatenate(
|
||||
(rows, buffer.read(request_id, stored_end, token_end))
|
||||
)
|
||||
else:
|
||||
rows = buffer.read(request_id, emit_start, token_end)
|
||||
outputs[request_id] = AuxRequestOutput(emit_start, rows)
|
||||
state.emit_cursor = token_end
|
||||
return outputs
|
||||
|
||||
def _publish_blocks(
|
||||
self,
|
||||
batches: list[tuple[_WorkerRequestState, list[tuple[int, np.ndarray]]]],
|
||||
retain_keys: Sequence[str] = (),
|
||||
release_keys: Sequence[str] = (),
|
||||
) -> None:
|
||||
store = self._store
|
||||
buffer = self._buffer
|
||||
assert store is not None and buffer is not None
|
||||
ready_batches = []
|
||||
for state, completed in batches:
|
||||
blocks = state.pending_blocks + completed
|
||||
keyed_end = len(state.aux_output_keys) * buffer.block_size
|
||||
ready = [(start, rows) for start, rows in blocks if start < keyed_end]
|
||||
state.pending_blocks = [
|
||||
(start, buffer.retain_block(rows))
|
||||
for start, rows in blocks
|
||||
if start >= keyed_end
|
||||
]
|
||||
if ready:
|
||||
ready_batches.append((state.aux_output_keys, ready))
|
||||
if ready_batches or retain_keys or release_keys:
|
||||
publish_routed_experts(
|
||||
store,
|
||||
batches=ready_batches,
|
||||
block_size=buffer.block_size,
|
||||
retain_keys=retain_keys,
|
||||
release_keys=release_keys,
|
||||
)
|
||||
for _, blocks in ready_batches:
|
||||
for _, rows in blocks:
|
||||
buffer.release_block(rows)
|
||||
|
||||
def _teardown(self, request_ids: Iterable[str]) -> None:
|
||||
"""Drop finished requests' temporary state after publishing key releases."""
|
||||
buffer = self._buffer
|
||||
assert buffer is not None
|
||||
for request_id in request_ids:
|
||||
state = self._requests.pop(request_id)
|
||||
for _, rows in state.pending_blocks:
|
||||
buffer.release_block(rows)
|
||||
buffer.discard(request_id)
|
||||
|
||||
def begin_step(self, metadata: AuxOutputConnectorMetadata | None) -> None:
|
||||
"""Apply one scheduler step's request and block-hash updates.
|
||||
|
||||
While an unconsumed step covers a finished request, its teardown is
|
||||
deferred to that step's process_output.
|
||||
"""
|
||||
self._step_metadata = metadata
|
||||
if self._buffer is None or metadata is None:
|
||||
return
|
||||
assert not metadata.requests.keys() & metadata.finished_requests, (
|
||||
"auxiliary output request cannot run and finish in one step"
|
||||
)
|
||||
assert metadata.generation >= self._generation, (
|
||||
"auxiliary output metadata generation moved backwards"
|
||||
)
|
||||
with self._lock:
|
||||
release_keys: list[str] = []
|
||||
if metadata.generation > self._generation:
|
||||
# A generation change follows a prefix-cache reset, which the
|
||||
# scheduler only performs once all model output is consumed.
|
||||
assert not self._pending_outputs, (
|
||||
"auxiliary output generation changed with output in flight"
|
||||
)
|
||||
release_keys.extend(
|
||||
key
|
||||
for state in self._requests.values()
|
||||
for key in reversed(state.aux_output_keys)
|
||||
)
|
||||
self._buffer.reset()
|
||||
self._requests.clear()
|
||||
self._generation = metadata.generation
|
||||
for request_id, emit_start in metadata.requests.items():
|
||||
state = self._requests.setdefault(
|
||||
request_id, _WorkerRequestState(emit_cursor=emit_start)
|
||||
)
|
||||
if state.pending_outputs == 0:
|
||||
# In-flight steps leave the worker cursor behind the
|
||||
# scheduler's optimistic view; only check settled requests.
|
||||
assert emit_start <= state.emit_cursor, (
|
||||
"auxiliary output Scheduler emit cursor moved ahead"
|
||||
)
|
||||
block_batches: list[
|
||||
tuple[_WorkerRequestState, list[tuple[int, np.ndarray]]]
|
||||
] = []
|
||||
retained_keys: list[str] = []
|
||||
for request_id, block_hashes in metadata.block_hashes.items():
|
||||
state = self._requests[request_id]
|
||||
keys = routed_experts_keys(block_hashes, str(self._generation))
|
||||
state.aux_output_keys.extend(keys)
|
||||
retained_keys.extend(keys)
|
||||
block_batches.append((state, []))
|
||||
finished_now: list[str] = []
|
||||
for request_id in metadata.finished_requests:
|
||||
state = self._requests[request_id]
|
||||
state.finished = True
|
||||
if state.pending_outputs:
|
||||
continue
|
||||
finished_now.append(request_id)
|
||||
release_keys.extend(reversed(state.aux_output_keys))
|
||||
self._publish_blocks(block_batches, retained_keys, release_keys)
|
||||
self._teardown(finished_now)
|
||||
|
||||
def close(self) -> None:
|
||||
with self._lock:
|
||||
self._pending_outputs.clear()
|
||||
if self._store is not None:
|
||||
try:
|
||||
self._store.close()
|
||||
finally:
|
||||
self._store = None
|
||||
|
||||
|
||||
def get_aux_output_connector(
|
||||
model: torch.nn.Module, vllm_config: VllmConfig, kv_cache_config: KVCacheConfig
|
||||
) -> AuxOutputWorkerConnector:
|
||||
return AuxOutputWorkerConnector(
|
||||
model=model,
|
||||
kv_cache_config=kv_cache_config,
|
||||
vllm_config=vllm_config,
|
||||
)
|
||||
Reference in New Issue
Block a user