[Core] Move pause and resume functions into engine (#34125)

Signed-off-by: ahao-anyscale <ahao@anyscale.com>
Signed-off-by: Aaron Hao <ahao@anyscale.com>
Signed-off-by: hao-aaron <ahao@anyscale.com>
Signed-off-by: Nick Hill <nickhill123@gmail.com>
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
Co-authored-by: Nick Hill <nickhill123@gmail.com>
This commit is contained in:
Aaron Hao
2026-02-13 00:15:10 -08:00
committed by GitHub
co-authored by gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com> Nick Hill
parent 47e9b63e1a
commit dddbff4624
9 changed files with 621 additions and 136 deletions
+6 -49
View File
@@ -172,9 +172,6 @@ class AsyncLLM(EngineClient):
)
self.logger_manager.log_engine_initialized()
# Pause / resume state for async RL workflows.
self._pause_cond = asyncio.Condition()
self._paused = False
self._client_count = client_count
self.output_handler: asyncio.Task | None = None
@@ -387,10 +384,6 @@ class AsyncLLM(EngineClient):
# to handle startup failure gracefully in the OpenAI server.
self._run_output_handler()
# Respect pause state before accepting new requests.
async with self._pause_cond:
await self._pause_cond.wait_for(lambda: not self._paused)
# Create a new output collector for the request.
queue = RequestOutputCollector(params.output_kind, request.request_id)
@@ -741,7 +734,9 @@ class AsyncLLM(EngineClient):
"""
Pause generation to allow model weight updates.
New generation/encoding requests are blocked until resume.
All mode handling (abort / wait / keep) and cache clearing is done
in the engine. New generation/encoding requests will not be scheduled
until resume is called.
Args:
mode: How to handle in-flight requests:
@@ -751,11 +746,8 @@ class AsyncLLM(EngineClient):
- ``"keep"``: Freeze requests in queue; they resume on
:meth:`resume_generation`.
wait_for_inflight_requests: DEPRECATED: use mode argument.
Whether to wait for in-flight requests to complete before pausing.
clear_cache: Whether to clear KV cache and prefix cache after
draining. Set to ``False`` to preserve cache for faster resume.
Default is ``True`` (clear caches).
"""
if wait_for_inflight_requests:
warnings.warn(
@@ -766,50 +758,15 @@ class AsyncLLM(EngineClient):
stacklevel=2,
)
mode = "wait"
if mode == "keep":
# Freeze requests in the scheduler - they will resume on
# resume_generation().
await self.engine_core.pause_scheduler_async()
else:
if self._client_count > 1:
raise NotImplementedError(
"pause_generation is not supported with --api-server-count > 1"
" when mode is not 'keep'"
)
async with self._pause_cond:
if not self._paused:
self._paused = True
if mode == "abort":
request_ids = list(self.output_processor.request_states.keys())
if request_ids:
await self.abort(request_ids, internal=True)
elif mode == "wait":
if self.output_processor.has_unfinished_requests():
await self.output_processor.wait_for_requests_to_drain()
else:
raise ValueError(f"Invalid mode: {mode}")
# Clear cache
if clear_cache:
await self.reset_prefix_cache(reset_running_requests=True)
await self.reset_mm_cache()
await self.reset_encoder_cache()
await self.engine_core.pause_scheduler_async(mode=mode, clear_cache=clear_cache)
async def resume_generation(self) -> None:
"""Resume generation after :meth:`pause_generation`."""
async with self._pause_cond:
await self.engine_core.resume_scheduler_async()
self._paused = False
self._pause_cond.notify_all() # Wake up all waiting requests
await self.engine_core.resume_scheduler_async()
async def is_paused(self) -> bool:
"""Return whether the engine is currently paused."""
async with self._pause_cond:
return self._paused
return await self.engine_core.is_scheduler_paused_async()
async def encode(
self,
+125 -50
View File
@@ -5,7 +5,7 @@ import queue
import signal
import threading
import time
from collections import deque
from collections import defaultdict, deque
from collections.abc import Callable, Generator
from concurrent.futures import Future
from contextlib import ExitStack, contextmanager
@@ -40,7 +40,7 @@ from vllm.v1.core.kv_cache_utils import (
get_request_block_hasher,
init_none_hash,
)
from vllm.v1.core.sched.interface import SchedulerInterface
from vllm.v1.core.sched.interface import PauseState, SchedulerInterface
from vllm.v1.core.sched.output import SchedulerOutput
from vllm.v1.engine import (
EngineCoreOutput,
@@ -48,6 +48,7 @@ from vllm.v1.engine import (
EngineCoreRequest,
EngineCoreRequestType,
FinishReason,
PauseMode,
ReconfigureDistributedRequest,
ReconfigureRankType,
UtilityOutput,
@@ -210,8 +211,7 @@ class EngineCore:
self.aborts_queue = queue.Queue[list[str]]()
# Pause state for "keep" mode - freezes requests in queue.
self._scheduler_paused = False
self.per_step_hooks: set[Callable] = set()
# Mark the startup heap as static so that it's ignored by GC.
# Reduces pause times of oldest generation collections.
@@ -326,20 +326,6 @@ class EngineCore:
# (i.e. client-aborted vs stop criteria met).
self.scheduler.finish_requests(request_ids, RequestStatus.FINISHED_ABORTED)
def pause_scheduler(self) -> None:
"""Pause the scheduler, keeping requests frozen in queue.
Requests are kept frozen in queue and can be resumed later.
"""
self._scheduler_paused = True
def resume_scheduler(self) -> None:
"""Resume the scheduler after a pause.
Resumes processing of frozen requests in the queue.
"""
self._scheduler_paused = False
@contextmanager
def log_error_detail(self, scheduler_output: SchedulerOutput):
"""Execute the model and log detailed info on failure."""
@@ -393,10 +379,6 @@ class EngineCore:
was executed.
"""
# If paused, don't schedule any work.
if self._scheduler_paused:
return {}, False
# Check for any requests remaining in the scheduler - unfinished,
# or finished and not yet removed from the batch.
if not self.scheduler.has_requests():
@@ -447,9 +429,6 @@ class EngineCore:
batch in the job queue is finished.
3. Update the scheduler from the output.
"""
# If paused, don't schedule any work.
if self._scheduler_paused:
return {}, False
batch_queue = self.batch_queue
assert batch_queue is not None
@@ -613,6 +592,20 @@ class EngineCore:
# Reset the GPU model runner's encoder cache (physical storage)
self.model_executor.reset_encoder_cache()
def pause_scheduler(
self, mode: PauseMode = "abort", clear_cache: bool = True
) -> Future[Any] | None:
"""Pause scheduling. No-op in base EngineCore; overridden in EngineCoreProc."""
return None
def resume_scheduler(self) -> None:
"""Resume scheduling. No-op in base EngineCore; overridden in EngineCoreProc."""
def is_scheduler_paused(self) -> bool:
"""Return whether the scheduler is in any pause state. False in base EngineCore
and overridden in EngineCoreProc."""
return False
def sleep(self, level: int = 1):
"""Put the engine to sleep at the specified level.
@@ -650,7 +643,7 @@ class EngineCore:
def is_sleeping(self) -> bool:
"""Check if engine is sleeping at any level."""
return self._scheduler_paused or self.model_executor.is_sleeping
return self.is_scheduler_paused() or self.model_executor.is_sleeping
def execute_dummy_batch(self):
self.model_executor.execute_dummy_batch()
@@ -1053,13 +1046,9 @@ class EngineCoreProc(EngineCore):
# 1) Poll the input queue until there is work to do.
self._process_input_queue()
# 2) Step the engine core and return the outputs.
# Skip if scheduling is paused (level 0 sleep)
if not self._scheduler_paused:
self._process_engine_step()
else:
# When scheduling is paused, still need to check for wake up
# by processing any utility requests that might resume scheduling
pass
self._process_engine_step()
# 3) Run any per-step hooks.
self._process_per_step_hooks()
def _process_input_queue(self):
"""Exits when an engine step needs to be performed."""
@@ -1067,9 +1056,9 @@ class EngineCoreProc(EngineCore):
waited = False
while (
not self.engines_running
and (not self.scheduler.has_requests() or self._scheduler_paused)
and not self.scheduler.has_requests()
and not self.batch_queue
and not self._scheduler_paused
and not self.per_step_hooks
):
if self.input_queue.empty():
# Drain aborts queue; all aborts are also processed via input_queue.
@@ -1109,6 +1098,13 @@ class EngineCoreProc(EngineCore):
return model_executed
def _process_per_step_hooks(self) -> None:
if self.per_step_hooks:
for hook in list(self.per_step_hooks):
finished = hook(self)
if finished:
self.per_step_hooks.discard(hook)
def _handle_client_request(
self, request_type: EngineCoreRequestType, request: Any
) -> None:
@@ -1122,18 +1118,14 @@ class EngineCoreProc(EngineCore):
elif request_type == EngineCoreRequestType.UTILITY:
client_idx, call_id, method_name, args = request
output = UtilityOutput(call_id)
try:
method = getattr(self, method_name)
result = method(*self._convert_msgspec_args(method, args))
output.result = UtilityResult(result)
except BaseException as e:
logger.exception("Invocation of %s method failed", method_name)
output.failure_message = (
f"Call to {method_name} method failed: {str(e)}"
)
self.output_queue.put_nowait(
(client_idx, EngineCoreOutputs(utility_output=output))
# Lazily look-up utility method so that failure will be handled/returned.
get_result = lambda: (method := getattr(self, method_name)) and method(
*self._convert_msgspec_args(method, args)
)
enqueue_output = lambda out: self.output_queue.put_nowait(
(client_idx, EngineCoreOutputs(utility_output=out))
)
self._invoke_utility_method(method_name, get_result, output, enqueue_output)
elif request_type == EngineCoreRequestType.EXECUTOR_FAILED:
raise RuntimeError("Executor failed.")
else:
@@ -1141,6 +1133,25 @@ class EngineCoreProc(EngineCore):
"Unrecognized input request type encountered: %s", request_type
)
@staticmethod
def _invoke_utility_method(
name: str, get_result: Callable, output: UtilityOutput, enqueue_output: Callable
):
try:
result = get_result()
if isinstance(result, Future):
# Defer utility output handling until future completion.
callback = lambda future: EngineCoreProc._invoke_utility_method(
name, future.result, output, enqueue_output
)
result.add_done_callback(callback)
return
output.result = UtilityResult(result)
except Exception as e:
logger.exception("Invocation of %s method failed", name)
output.failure_message = f"Call to {name} method failed: {str(e)}"
enqueue_output(output)
@staticmethod
def _convert_msgspec_args(method, args):
"""If a provided arg type doesn't match corresponding target method
@@ -1347,6 +1358,74 @@ class EngineCoreProc(EngineCore):
)
)
def pause_scheduler(
self, mode: PauseMode = "abort", clear_cache: bool = True
) -> Future | None:
"""Pause generation; behavior depends on mode.
All pause states queue new adds. PAUSE_ABORT and PAUSE_KEEP skip step();
PAUSE_WAIT allows step() so in-flight requests can drain.
- ``abort``: Set PAUSE_ABORT, abort all requests, wait for abort
outputs to be sent (when running with output_queue), clear caches,
then complete the returned Future.
- ``wait``: Set PAUSE_WAIT (queue adds, keep stepping); when drained,
set PAUSE_KEEP, clear caches, complete the returned Future.
- ``keep``: Set PAUSE_KEEP; return a Future that completes when the
output queue is empty.
"""
if mode not in ("keep", "abort", "wait"):
raise ValueError(f"Invalid pause mode: {mode}")
future: Future[Any] = Future()
def wait_until_idle(engine: "EngineCoreProc") -> bool:
scheduler = engine.scheduler
out_queue = engine.output_queue
if scheduler.has_requests() or engine.batch_queue or not out_queue.empty():
return False
if clear_cache:
engine.reset_prefix_cache(reset_running_requests=True)
engine.reset_mm_cache()
engine.reset_encoder_cache()
future.set_result(None)
return True
if mode == "abort":
aborted_reqs = self.scheduler.finish_requests(
None, RequestStatus.FINISHED_ABORTED
)
self._send_abort_outputs(aborted_reqs)
pause_state = PauseState.PAUSED_ALL if mode == "keep" else PauseState.PAUSED_NEW
self.scheduler.set_pause_state(pause_state)
if not wait_until_idle(self):
self.per_step_hooks.add(wait_until_idle)
return future
return None
def _send_abort_outputs(self, aborted_reqs: list[tuple[str, int]]) -> None:
if aborted_reqs:
# Map client_index to list of request_ids that belong to that client.
by_client = defaultdict[int, set[str]](set)
for req_id, client_index in aborted_reqs:
by_client[client_index].add(req_id)
for client_index, req_ids in by_client.items():
outputs = [
EngineCoreOutput(req_id, [], finish_reason=FinishReason.ABORT)
for req_id in req_ids
]
eco = EngineCoreOutputs(finished_requests=req_ids, outputs=outputs)
self.output_queue.put_nowait((client_index, eco))
def resume_scheduler(self) -> None:
"""Resume the scheduler and flush any requests queued while paused."""
self.scheduler.set_pause_state(PauseState.UNPAUSED)
def is_scheduler_paused(self) -> bool:
"""Return whether the scheduler is in any pause state."""
return self.scheduler.pause_state != PauseState.UNPAUSED
class DPEngineCoreProc(EngineCoreProc):
"""ZMQ-wrapper for running EngineCore in background process
@@ -1450,10 +1529,6 @@ class DPEngineCoreProc(EngineCoreProc):
# 1) Poll the input queue until there is work to do.
self._process_input_queue()
# Skip processing if scheduling is paused (level 0 sleep)
if self._scheduler_paused:
continue
# 2) Step the engine core.
executed = self._process_engine_step()
self._maybe_publish_request_counts()
+8 -18
View File
@@ -36,6 +36,7 @@ from vllm.v1.engine import (
EngineCoreOutputs,
EngineCoreRequest,
EngineCoreRequestType,
PauseMode,
ReconfigureDistributedRequest,
ReconfigureRankType,
UtilityOutput,
@@ -979,16 +980,17 @@ class AsyncMPClient(MPClient):
if request_ids and not self.resources.engine_dead:
await self._send_input(EngineCoreRequestType.ABORT, request_ids)
async def pause_scheduler_async(self) -> None:
"""Pause the scheduler, keeping requests frozen in queue.
Blocks until the EngineCore acknowledges the pause.
"""
await self.call_utility_async("pause_scheduler")
async def pause_scheduler_async(
self, mode: PauseMode = "abort", clear_cache: bool = True
) -> None:
await self.call_utility_async("pause_scheduler", mode, clear_cache)
async def resume_scheduler_async(self) -> None:
"""Resume the scheduler after a pause."""
await self.call_utility_async("resume_scheduler")
async def is_scheduler_paused_async(self) -> bool:
return await self.call_utility_async("is_scheduler_paused")
async def profile_async(
self, is_start: bool = True, profile_prefix: str | None = None
) -> None:
@@ -1203,18 +1205,6 @@ class DPAsyncMPClient(AsyncMPClient):
def get_core_engine_for_request(self, request: EngineCoreRequest):
return self.core_engine
async def pause_scheduler_async(self) -> None:
"""Pause the scheduler, keeping requests frozen in queue."""
raise NotImplementedError(
"pause_scheduler_async is not yet supported for data parallel"
)
async def resume_scheduler_async(self) -> None:
"""Resume the scheduler after a pause."""
raise NotImplementedError(
"resume_scheduler_async is not yet supported for data parallel"
)
class DPLBAsyncMPClient(DPAsyncMPClient):
"""Asyncio-compatible client for multi-proc, multi-engine (data parallel)