Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions tests/v1/kv_offload/tiering/test_fs_tier.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,11 +104,15 @@ def lookup_and_wait(
tier.lookup(k, ctx)
tier.on_schedule_end()
deadline = time.monotonic() + timeout
latest: list[bool | None] = [None] * len(keys)
while time.monotonic() < deadline:
if not tier._lookup_manager._pending_results.empty():
latest = [tier.lookup(k, ctx) for k in keys]
tier.on_schedule_end() # attempt result drain
if all(v is not None for v in latest):
break
time.sleep(0.01)
return [tier.lookup(k, ctx) for k in keys]
assert all(v is not None for v in latest), "lookup results did not resolve in time"
return [bool(v) for v in latest]


def _page_aligned_zero_tensor(
Expand Down
195 changes: 112 additions & 83 deletions vllm/v1/kv_offload/tiering/async_lookup.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

Each secondary tier that wants non-blocking lookups composes its own
AsyncLookupManager instance internally. The manager maintains lookup
state and uses a background thread to execute batch_lookup() calls.
state while a concrete runtime strategy (thread/process) executes lookups.

Locking design
--------------
Expand All @@ -16,16 +16,16 @@
thread. lookup(), flush(), and cleanup() read and write them directly.

* _lookup_queue is written by the scheduler (flush → put_nowait, one item
per step) and read by the background thread (get). queue.Queue is
thread-safe.
per step) and read by the background worker (get). Queue primitives are
thread/process-safe.

* _pending_results is written by the background thread (put) and read by
* _pending_results is written by the background worker (put) and read by
the scheduler (get_nowait inside drain_results). queue.SimpleQueue is
thread-safe by design.
thread-safe by design and multiprocessing.Queue is process-safe.

lookup() accumulates new keys in _lookup_batch without touching the queue.
flush() is called once per step from the tier's on_schedule_end(), posting
the entire batch as a single queue item so the background thread sees one
the entire batch as a single queue item so the background worker sees one
batch per step.
drain_results() is called before any lookup() calls in the same step, so
lookup() is a pure OrderedDict operation.
Expand All @@ -34,8 +34,11 @@
import queue
import threading
from abc import ABC, abstractmethod
from collections.abc import Iterable
from collections.abc import Callable, Iterable
from dataclasses import dataclass, field
from typing import cast

from typing_extensions import override

from vllm.logger import init_logger
from vllm.v1.kv_offload.base import OffloadKey, ReqContext
Expand All @@ -49,17 +52,20 @@ class LookupState:
request_ids: set[str] = field(default_factory=set) # requests asking for the lookup


class AsyncLookupManager(ABC):
LookupBatch = list[tuple[OffloadKey, ReqContext]]
LookupResults = list[tuple[OffloadKey, bool]]


class BaseAsyncLookupManager(ABC):
"""
Per-tier async lookup manager for secondary tier existence checks.

Each secondary tier that wants non-blocking lookups composes its own
AsyncLookupManager instance internally. The manager maintains lookup
state (cache, queue) and uses a background thread to execute the actual
batch_lookup() calls.
state (cache, queue) and lets subclasses decide the worker runtime
strategy (thread vs process).

Subclasses implement only batch_lookup() — all queue management,
state tracking, and result delivery is provided by this base class.
Subclasses provide queue transport and worker lifecycle.

The owning tier delegates its lookup(), on_schedule_end(), and
on_request_finished() to this manager:
Expand All @@ -83,41 +89,8 @@ def __init__(
# Flushed as one queue item per step by flush().
self._lookup_batch: list[tuple[OffloadKey, ReqContext]] = []

# Scheduler → worker: one full step's batch per item.
# None is used as a shutdown sentinel.
self._lookup_queue: queue.SimpleQueue[
list[tuple[OffloadKey, ReqContext]] | None
] = queue.SimpleQueue()

# Worker → scheduler: completed result batches.
# Each item is a list of (key, found) pairs.
# SimpleQueue is explicitly thread-safe for one writer / one reader.
self._pending_results: queue.SimpleQueue[list[tuple[OffloadKey, bool]]] = (
queue.SimpleQueue()
)
self._need_to_drain: bool = False

self._thread = threading.Thread(
target=self._worker,
name=f"vllm_offloading_lookup_{tier_type}",
daemon=True,
)
self._thread.start()

@abstractmethod
def batch_lookup(
self, keys: list[OffloadKey], req_context: ReqContext
) -> Iterable[bool]:
"""
Check whether a batch of blocks exist in this tier.

Called from the worker thread — must be synchronous and must not
touch the primary tier or scheduler state.

Returns a list parallel to keys: True if present, False if not.
"""
...

# ------------------------------------------------------------------
# Scheduler-thread API
# ------------------------------------------------------------------
Expand Down Expand Up @@ -145,7 +118,7 @@ def lookup(self, key: OffloadKey, req_context: ReqContext) -> bool | None:
return state.result

def flush(self) -> None:
"""Post this step's accumulated keys to the worker thread.
"""Post this step's accumulated keys to the worker.

Called once per step from on_schedule_end() after all lookup() calls
are done. The worker receives the full batch and processes it during
Expand All @@ -154,7 +127,7 @@ def flush(self) -> None:
"""
self._need_to_drain = True
if self._lookup_batch:
self._lookup_queue.put(self._lookup_batch)
self.send_lookup_batch(self._lookup_batch)
self._lookup_batch = []

def drain_results(self) -> None:
Expand All @@ -163,9 +136,8 @@ def drain_results(self) -> None:
Called from lookup() before checking state.
"""
while True:
try:
batch = self._pending_results.get_nowait()
except queue.Empty:
batch = self.try_recv_result_batch()
if batch is None:
break
for key, result in batch:
state = self._lookup_state.get(key)
Expand All @@ -184,48 +156,105 @@ def cleanup(self, req_id: str) -> None:
if not state.request_ids:
del self._lookup_state[key]

@abstractmethod
def send_lookup_batch(self, batch: LookupBatch) -> None: ...

@abstractmethod
def try_recv_result_batch(self) -> LookupResults | None: ...

@abstractmethod
def shutdown(self) -> None:
"""Stop the background worker."""
...

@staticmethod
def execute_lookup_batch(
pending: LookupBatch,
tier_type: str,
batch_lookup: Callable[[list[OffloadKey], ReqContext], Iterable[bool]],
) -> LookupResults:
"""Resolve one queued lookup batch grouped by request id."""
batches: dict[str, tuple[ReqContext, list[OffloadKey]]] = {}
for key, req_context in pending:
req_id = req_context.req_id
if req_id not in batches:
batches[req_id] = (req_context, [])
batches[req_id][1].append(key)

if not batches:
return []

results: LookupResults = []
for req_context, keys in batches.values():
try:
hits = batch_lookup(keys, req_context)
except Exception as exc:
logger.warning(
"batch_lookup failed on tier %s for %d keys: %s",
tier_type,
len(keys),
exc,
)
hits = (False for _ in keys)

for key, hit in zip(keys, hits):
results.append((key, hit))

return results


class AsyncLookupManager(BaseAsyncLookupManager, ABC):
"""Thread-backed async lookup manager."""

def __init__(self, tier_type: str) -> None:
super().__init__(tier_type=tier_type)
# Scheduler → worker: one full step's batch per item.
# None is used as a shutdown sentinel.
self._lookup_queue: queue.SimpleQueue[LookupBatch | None] = queue.SimpleQueue()

# Worker → scheduler: completed result batches.
# SimpleQueue is explicitly thread-safe for one writer / one reader.
self._pending_results: queue.SimpleQueue[LookupResults] = queue.SimpleQueue()

self._thread = threading.Thread(
target=self._worker,
name=f"vllm_offloading_lookup_{tier_type}",
daemon=True,
)
self._thread.start()

@abstractmethod
def batch_lookup(
self, keys: list[OffloadKey], req_context: ReqContext
) -> Iterable[bool]:
"""Check whether a batch of blocks exist in this tier."""
...

@override
def shutdown(self) -> None:
"""Stop the worker thread."""
self._lookup_queue.put(None) # unblock _worker from _lookup_queue.get()
self._thread.join()

# ------------------------------------------------------------------
# Internal helpers
# ------------------------------------------------------------------
@override
def send_lookup_batch(self, batch: LookupBatch) -> None:
self._lookup_queue.put(batch)

@override
def try_recv_result_batch(self) -> LookupResults | None:
try:
return cast(LookupResults, self._pending_results.get_nowait())
except queue.Empty:
return None

def _worker(self) -> None:
while True:
pending = self._lookup_queue.get()
if pending is None:
break

# Group by req_id.
batches: dict[str, tuple[ReqContext, list[OffloadKey]]] = {}
for key, req_context in pending:
req_id = req_context.req_id
if req_id not in batches:
batches[req_id] = (req_context, [])
batches[req_id][1].append(key)

if not batches:
continue

results: list[tuple[OffloadKey, bool]] = []
for req_context, keys in batches.values():
try:
hits = self.batch_lookup(keys, req_context)
except Exception as exc:
logger.warning(
"batch_lookup failed on tier %s for %d keys: %s",
self._tier_type,
len(keys),
exc,
)
hits = (False for _ in keys)

for key, hit in zip(keys, hits):
results.append((key, hit))

# Post the entire batch as one item — no lock needed.
results = self.execute_lookup_batch(
pending,
self._tier_type,
self.batch_lookup,
)
if results:
self._pending_results.put(results)
Loading
Loading