[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
+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()