Rebase multi-API serving on latest main

Signed-off-by: Sy03 <1370724210@qq.com>
This commit is contained in:
Sy03 committed 2026-09-16 12:13:04 +08:00
1 parent 78934753ff
commit dc3c7dbe16
25 files changed
+1832 -202

No files matched your search

+17 -19
View File
@@ -76,11 +76,12 @@ from vllm_omni.engine.stage_client import StageClient
from vllm_omni.engine.stage_init_utils import build_stage0_input_processor
from vllm_omni.engine.stage_pool import StagePool
from vllm_omni.engine.stage_runtime import (
OmniClientConfig,
StageRuntimeInfo,
create_stage_runtime,
)
from vllm_omni.entrypoints.pd_utils import PDDisaggregationMixin
from vllm_omni.entrypoints.utils import parse_stage_overrides
from vllm_omni.entrypoints.utils import prepare_stage_config_inputs
from vllm_omni.inputs.data import OmniInteractionPrompt, OmniSamplingParams
from vllm_omni.metrics.prometheus import OmniRequestCounter
@@ -133,6 +134,7 @@ class AsyncOmniEngine:
_transfer_emitter: Any = None
_prom_metrics: Any = None
_enable_orch_monitor: bool = False
_client_config: OmniClientConfig | None = None
# Lazily created by get_output_blocking_async().
_output_drain_executor: concurrent.futures.ThreadPoolExecutor | None = None
@@ -147,6 +149,7 @@ class AsyncOmniEngine:
log_stats: bool = False,
tokenizer: str | None = None,
trust_remote_code: bool | None = None,
client_config: OmniClientConfig | None = None,
**kwargs: Any,
) -> None:
self.model = model
@@ -166,6 +169,7 @@ class AsyncOmniEngine:
# --log-stats CLI flag set by the user via OmniBase.
self._log_stats = log_stats
self._enable_orch_monitor = bool(kwargs.pop("enable_orch_monitor", False))
self._client_config = client_config
logger.info(f"[AsyncOmniEngine] Initializing with model {model}")
@@ -177,6 +181,8 @@ class AsyncOmniEngine:
_stage_id_kwarg = kwargs.get("stage_id")
if isinstance(_stage_id_kwarg, int) and not single_stage_mode:
single_stage_mode = True
if client_config is not None and int(client_config.get("client_count", 1)) > 1 and single_stage_mode:
raise ValueError("Multiple API servers cannot be combined with single-stage distributed mode")
self.single_stage_mode: bool = single_stage_mode
self._single_stage_id_filter: int | None = (
@@ -332,6 +338,7 @@ class AsyncOmniEngine:
omni_lb_policy=self._omni_lb_policy,
request_queue=self.request_queue,
log_stats=self._log_stats,
client_config=self._client_config,
)
self._runtime.initialize()
@@ -1021,24 +1028,15 @@ class AsyncOmniEngine:
) -> tuple[str, list[Any]]:
"""Resolve stage configs and inject defaults shared by orchestrator/headless."""
for legacy_arg in ("stage_configs_path", "stage_configs"):
if legacy_arg in kwargs:
raise ValueError(f"`{legacy_arg}` is no longer supported; use `deploy_config` instead.")
# log_stats is captured by __init__; its CLI-only negative alias must
# not cross into per-stage structured config ownership validation.
kwargs.pop("disable_log_stats", None)
deploy_config_path = kwargs.pop("deploy_config", None)
strategy_config_path = kwargs.pop("strategy_config", None)
# CLI callers arrive pre-parsed; offline Python callers may use the
# JSON-string form documented in recipes.
stage_overrides = parse_stage_overrides(kwargs.pop("stage_overrides", None))
# ``diffusion_streaming_output`` is the public AsyncOmni/serve kwarg;
# stage configs know the field as ``streaming_output``. Mirror only a
# truthy value so the CLI's False default does not override deploy YAML.
if kwargs.get("diffusion_streaming_output") and kwargs.get("streaming_output") is None:
kwargs["streaming_output"] = True
config_inputs = prepare_stage_config_inputs(
model,
kwargs,
trust_remote_code=trust_remote_code,
)
kwargs = config_inputs.kwargs
deploy_config_path = config_inputs.deploy_config_path
strategy_config_path = config_inputs.strategy_config_path
stage_overrides = config_inputs.stage_overrides
resolution = cast(
_ConfigResolutionResult,
+24 -7
View File
@@ -13,6 +13,7 @@ import threading
from collections.abc import Callable, Iterator
from dataclasses import dataclass, field
from multiprocessing import connection
from multiprocessing.process import BaseProcess
from types import SimpleNamespace
from typing import Any
@@ -1134,6 +1135,8 @@ def launch_stage_replica(
stage_visible_devices: str | None = None,
spawn_device_lock: threading.Lock | None = None,
omni_parallel_stage_init: bool = False,
num_api_servers: int = 1,
watched_frontend_processes: list[BaseProcess] | None = None,
) -> Iterator[StageReplicaResources]:
"""Launch a local LLM stage replica.
@@ -1144,6 +1147,8 @@ def launch_stage_replica(
keep the same returned resource bundle.
"""
if omni_master_server is not None:
if num_api_servers != 1:
raise ValueError("Multiple API servers are not supported with distributed stage launch")
with _launch_omni_core_engines(
vllm_config=vllm_config,
executor_class=executor_class,
@@ -1169,7 +1174,16 @@ def launch_stage_replica(
from vllm_omni.engine.stage_engine_core_proc_manager import StageEngineCoreProcManager
addresses = get_engine_zmq_addresses(vllm_config)
if num_api_servers > 1:
# Multi-API Omni is intentionally local-only. IPC paths avoid the
# bind-after-allocation race of tcp://host:0 and are stable for every
# stage, including stages that are not used by APIServerProcessManager.
addresses = EngineZmqAddresses(
inputs=[get_open_zmq_ipc_path() for _ in range(num_api_servers)],
outputs=[get_open_zmq_ipc_path() for _ in range(num_api_servers)],
)
else:
addresses = get_engine_zmq_addresses(vllm_config)
handshake_address = get_open_zmq_ipc_path()
engines_to_handshake = [CoreEngine(index=0, local=True)]
with scoped_spawn_device_env(stage_visible_devices, spawn_device_lock, stage_id=stage_id, replica_id=replica_id):
@@ -1193,18 +1207,21 @@ def launch_stage_replica(
manager=engine_manager,
addresses=addresses,
)
engine_launch = CoreEngineLaunch(
engine_manager=engine_manager,
coordinator=None,
addresses=addresses,
tensor_queue=None,
)
if watched_frontend_processes is not None:
engine_launch.watched_frontend_processes = watched_frontend_processes
wait_for_engine_startup(
handshake_socket,
engines_to_handshake,
vllm_config.parallel_config,
False, # coordinated_dp
vllm_config.cache_config,
CoreEngineLaunch(
engine_manager=engine_manager,
coordinator=None,
addresses=addresses,
tensor_queue=None,
),
engine_launch,
)
+10 -3
View File
@@ -1445,6 +1445,8 @@ def build_vllm_config(
stage_connector_spec: dict[str, Any] | None = None,
engine_args_dict: dict[str, Any] | None = None,
headless: bool = False,
api_process_count: int = 1,
api_process_rank: int = 0,
) -> tuple[Any, type]:
"""Build engine args, then create VllmConfig and executor_class.
@@ -1459,6 +1461,9 @@ def build_vllm_config(
)
filtered_engine_args_dict = filter_dataclass_kwargs(OmniEngineArgs, engine_args_dict)
if api_process_count != 1 or api_process_rank != 0:
filtered_engine_args_dict["_api_process_count"] = api_process_count
filtered_engine_args_dict["_api_process_rank"] = api_process_rank
# _to_dict serializes dataclass fields (e.g. StructuredOutputsConfig) into
# plain dicts. When OmniEngineArgs is instantiated with the dict, these
@@ -1715,6 +1720,7 @@ def acquire_device_locks(
stage_id: int,
engine_args_dict: dict[str, Any],
stage_init_timeout: int,
locked_devices: set[int] | None = None,
) -> list[int]:
"""Acquire exclusive file locks on devices needed by this stage.
@@ -1769,8 +1775,7 @@ def acquire_device_locks(
f"but only {len(physical_devices)} device(s) are available: {physical_devices}"
)
num_devices_to_lock = num_devices_per_stage
devices_to_lock = sorted(physical_devices[:num_devices_to_lock])
devices_to_lock = sorted(set(physical_devices[:num_devices_per_stage]) - (locked_devices or set()))
logger.debug(
"Parallel config: TP=%d, PP=%d, DP=%d, PCP=%d, SP=%d, CFG=%d; will lock %d devices: %s",
@@ -1780,7 +1785,7 @@ def acquire_device_locks(
prefill_context_parallel_size,
sequence_parallel_size,
cfg_parallel_size,
num_devices_to_lock,
len(devices_to_lock),
devices_to_lock,
)
@@ -1798,6 +1803,8 @@ def acquire_device_locks(
record_lock_holder_pid(lock_fd, lock_writable)
lock_acquired = True
lock_fds.append(lock_fd)
if locked_devices is not None:
locked_devices.add(device_id)
logger.debug("Acquired exclusive lock for device %s", device_id)
except BlockingIOError:
os.close(lock_fd)
+314 -115
View File
@@ -6,14 +6,15 @@
from __future__ import annotations
import concurrent.futures
import contextlib
import copy
import os
import threading
import time
from collections.abc import Callable, Iterator, Mapping, Sequence
from contextlib import ExitStack, contextmanager
from dataclasses import dataclass
from typing import Any, cast
from contextlib import AbstractContextManager, contextmanager
from dataclasses import dataclass, field
from multiprocessing.process import BaseProcess
from typing import Any, TypedDict, cast
import janus
from omegaconf import OmegaConf
@@ -92,6 +93,44 @@ class StageRemoteFactoryContext:
executor_class: type | None = None
class OmniClientConfig(TypedDict, total=False):
"""Per-frontend transport/configuration passed across process boundaries."""
client_count: int
client_index: int
stage_addresses: dict[int | str, dict[int | str, dict[str, Any]]]
input_address: str
output_address: str
stats_update_address: str
actual_address_pipe: Any
tensor_queue: Any
@dataclass
class StageEngineLaunch:
"""Engine resources handed to a local client or the serving parent.
Successful launch transfers resource ownership to the caller. Startup or
attachment failures are rolled back by ``launch_stage_engines``.
"""
client_configs: list[OmniClientConfig]
resources: list[StageReplicaResources]
watched_frontend_processes: list[BaseProcess] = field(default_factory=list)
def shutdown(self) -> None:
seen: set[int] = set()
for stage_resources in reversed(self.resources):
for resource in (stage_resources.manager, stage_resources.coordinator):
if resource is None or id(resource) in seen:
continue
seen.add(id(resource))
try:
resource.shutdown()
except Exception:
logger.warning("[StageEngineLaunch] resource shutdown failed", exc_info=True)
def _build_load_balancer_factory(policy: str) -> Callable[[], LoadBalancer]:
try:
normalized = LoadBalancingPolicy(policy)
@@ -123,13 +162,14 @@ class StageRuntime:
self,
stage_configs: list[Any],
model: str,
config_path: str,
config_path: str | None,
*,
stage_init_timeout: int,
async_chunk: bool,
tokenizer: str | None = None,
parallel_stage_init: bool = False,
log_stats: bool = False,
client_config: OmniClientConfig | None = None,
) -> None:
self._stage_configs = stage_configs
self._model = model
@@ -144,6 +184,14 @@ class StageRuntime:
self._parallel_stage_init = parallel_stage_init
self._log_stats = log_stats
self._num_stages = len(stage_configs)
self._client_count = int((client_config or {}).get("client_count", 1))
self._client_index = int((client_config or {}).get("client_index", 0))
if self._client_count < 1:
raise ValueError(f"client_count must be >= 1, got {self._client_count}")
if self._client_index != -1 and not 0 <= self._client_index < self._client_count:
raise ValueError(f"client_index must be in [0, {self._client_count}), got {self._client_index}")
self._external_stage_addresses = (client_config or {}).get("stage_addresses")
self._api_process_rank = self._client_index
# Populated by initialize()
self.stage_pools: list[StagePool] = []
@@ -262,6 +310,205 @@ class StageRuntime:
self._cleanup_after_initialize_failure()
raise exc
@contextmanager
def launch_stage_engines(
self,
num_api_servers: int = 1,
*,
stage_plans: Sequence[LogicalStageInitPlan] | None = None,
stage_init_timeout: int | None = None,
) -> Iterator[StageEngineLaunch]:
"""Launch EngineCore stages for local or subprocess client attachment.
The regular runtime supplies a replica plan from its device-group
scheduler; the serving parent resolves the whole pipeline here. Both
use the same device locks, spawn, readiness and rollback machinery.
One client completes readiness before attachment, preserving the
existing in-process frontend. Multiple clients attach in the caller's
``with`` body before readiness completes on context exit.
"""
if self._external_stage_addresses is not None:
raise ValueError("A runtime attached to external stage engines cannot launch engines")
if num_api_servers < 1:
raise ValueError(f"num_api_servers must be >= 1, got {num_api_servers}")
timeout = self._stage_init_timeout if stage_init_timeout is None else stage_init_timeout
resolve_plans = stage_plans is None
if stage_plans is None:
self._client_count = num_api_servers
self._api_process_rank = -1 if num_api_servers > 1 else self._client_index
self._init_visible_devices_baseline = os.environ.get(current_omni_platform.device_control_env_var)
stage_plans = self._prepare_stage_plans()
unsupported = [
plan.stage_id
for plan in stage_plans
if any(replica.metadata.stage_type == "diffusion" for replica in plan.replicas)
]
if unsupported:
raise ValueError(
"--api-server-count currently supports EngineCore stages only; "
f"diffusion stage(s) are not supported: {unsupported}"
)
if any(replica.launch_mode != "local" for plan in stage_plans for replica in plan.replicas):
raise ValueError("--api-server-count is not supported with remote or headless stages")
if num_api_servers > 1:
parallel_configs: list[Any] = []
for plan in stage_plans:
for replica in plan.replicas:
if replica.stage_vllm_config is None or replica.executor_class is None:
raise RuntimeError(f"LLM stage {plan.stage_id} is missing its engine configuration")
parallel_configs.append(replica.stage_vllm_config.parallel_config)
if any(getattr(parallel_config, "enable_fault_tolerance", False) for parallel_config in parallel_configs):
raise ValueError("--api-server-count > 1 cannot be combined with --enable-fault-tolerance")
if any(getattr(parallel_config, "enable_elastic_ep", False) for parallel_config in parallel_configs):
raise ValueError("--api-server-count > 1 cannot be combined with --enable-elastic-ep")
if any(
getattr(parallel_config, "data_parallel_size", 1) != 1 or getattr(parallel_config, "use_ray", False)
for parallel_config in parallel_configs
):
raise ValueError(
"--api-server-count > 1 currently supports one local process group per replica; "
"intra-replica data parallelism and Ray backends are not supported"
)
if resolve_plans and self._parallel_stage_init:
self._reject_unguardable_executors(stage_plans)
self._run_stage_admission(stage_plans)
client_configs: list[OmniClientConfig] = [
OmniClientConfig(
client_count=num_api_servers,
client_index=client_index,
stage_addresses={},
)
for client_index in range(num_api_servers)
]
entered_contexts: list[AbstractContextManager[StageReplicaResources]] = []
resources: list[StageReplicaResources] = []
watched_frontend_processes: list[BaseProcess] = []
# launch_stage_replica performs its readiness handshake in __exit__,
# after API workers are started, so initialization locks must remain
# held until all launch contexts have exited.
lock_fds: list[int] = []
locked_devices: set[int] = set()
launch: StageEngineLaunch | None = None
exited_contexts = 0
try:
for plan in stage_plans:
for replica in plan.replicas:
if replica.stage_vllm_config is None or replica.executor_class is None:
raise RuntimeError(f"LLM stage {plan.stage_id} is missing its engine configuration")
if replica.engine_args_dict is None:
raise RuntimeError(f"LLM stage {plan.stage_id} is missing engine args")
physical_devices = self._resolve_replica_physical_devices(
replica.metadata.stage_id,
replica.metadata.runtime_cfg,
)
if not self._parallel_stage_init:
with self._scoped_spawn_device_env(physical_devices):
lock_fds.extend(
acquire_device_locks(
replica.metadata.stage_id,
replica.engine_args_dict,
timeout,
locked_devices,
)
)
launch_context = launch_stage_replica(
vllm_config=replica.stage_vllm_config,
executor_class=replica.executor_class,
log_stats=self._log_stats,
stage_id=replica.metadata.stage_id,
replica_id=replica.replica_id,
stage_config=replica.stage_cfg,
omni_master_server=self._get_omni_master_server(),
omni_coordinator_address=self._get_coordinator_address(),
stage_visible_devices=physical_devices,
spawn_device_lock=self._spawn_device_lock,
omni_parallel_stage_init=self._parallel_stage_init,
num_api_servers=num_api_servers,
watched_frontend_processes=watched_frontend_processes if num_api_servers > 1 else None,
)
# Environment overlays are process-global. Serialize spawn;
# parallel initialization waits for READY outside this lock.
with self._replica_launch_lock:
with stage_runtime_env(replica.metadata.stage_id, replica.metadata.runtime_cfg):
stage_resources = launch_context.__enter__()
entered_contexts.append(launch_context)
if stage_resources is None:
raise RuntimeError(f"LLM stage {plan.stage_id} launcher returned no resources")
resources.append(stage_resources)
if num_api_servers == 1:
exited_contexts += 1
launch_context.__exit__(None, None, None)
addresses = stage_resources.addresses
# The generic resource bundle allows no addresses (e.g.
# diffusion), but EngineCore attachment requires them.
if addresses is None:
raise RuntimeError(f"LLM stage {plan.stage_id} launcher returned no addresses")
# Unlike the single-client handshake, only stage 0 is
# handed to APIServerProcessManager for address updates.
# Other stages must already expose connectable endpoints.
if num_api_servers > 1 and any(
address.startswith("tcp://") and address.rsplit(":", 1)[-1] == "0"
for address in (*addresses.inputs, *addresses.outputs)
):
raise RuntimeError(
f"Stage {plan.stage_id} returned deferred TCP addresses; "
"multi-API launch requires fixed ports or IPC addresses"
)
if len(addresses.inputs) != num_api_servers or len(addresses.outputs) != num_api_servers:
raise RuntimeError(
f"Stage {plan.stage_id} returned {len(addresses.inputs)} input and "
f"{len(addresses.outputs)} output addresses for {num_api_servers} API servers"
)
if num_api_servers == 1 and lock_fds:
release_device_locks(lock_fds)
lock_fds.clear()
locked_devices.clear()
for client_index, client_config in enumerate(client_configs):
stage_addresses = client_config["stage_addresses"]
replica_addresses = stage_addresses.setdefault(plan.stage_id, {})
replica_addresses[replica.replica_id] = {
"input_address": addresses.inputs[client_index],
"output_address": addresses.outputs[client_index],
}
if addresses.frontend_stats_publish_address is not None:
replica_addresses[replica.replica_id]["stats_update_address"] = (
addresses.frontend_stats_publish_address
)
launch = StageEngineLaunch(
client_configs=client_configs,
resources=resources,
watched_frontend_processes=watched_frontend_processes,
)
yield launch
while exited_contexts < len(entered_contexts):
entered_context = entered_contexts[exited_contexts]
exited_contexts += 1
entered_context.__exit__(None, None, None)
except BaseException as exc:
if launch is not None:
launch.shutdown()
else:
StageEngineLaunch(client_configs=client_configs, resources=resources).shutdown()
exc_info = (type(exc), exc, exc.__traceback__)
for pending_context in reversed(entered_contexts[exited_contexts:]):
with contextlib.suppress(BaseException):
pending_context.__exit__(*exc_info)
raise
finally:
if lock_fds:
release_device_locks(lock_fds)
def shutdown(self) -> None:
for pool in self.stage_pools:
for client in pool.clients:
@@ -398,6 +645,8 @@ class StageRuntime:
self._model,
stage_connector_spec=stage_connector_spec,
engine_args_dict=engine_args_dict,
api_process_count=self._client_count,
api_process_rank=self._api_process_rank,
)
for replica_id in range(num_replicas):
@@ -720,122 +969,70 @@ class StageRuntime:
stage_init_timeout: int,
) -> StagePoolClient:
"""Initialize one local LLM replica using vLLM's launch/attach pattern."""
resources: StageReplicaResources | None = None
stage_client = None
lock_fds: list[int] = []
try:
physical_devices = self._resolve_replica_physical_devices(
plan.metadata.stage_id,
plan.metadata.runtime_cfg,
)
if physical_devices:
logger.info(
"[stage_init] Stage-%s set runtime devices: %s",
plan.metadata.stage_id,
physical_devices,
)
vllm_config = plan.stage_vllm_config
executor_class = plan.executor_class
if vllm_config is None:
raise RuntimeError(f"LLM stage {plan.metadata.stage_id} is missing vllm_config")
if executor_class is None:
raise RuntimeError(f"LLM stage {plan.metadata.stage_id} is missing executor_class")
if plan.engine_args_dict is None:
raise RuntimeError(f"LLM stage {plan.metadata.stage_id} is missing engine args")
# G3 device locks: in the default (serial) path the parent holds a
# per-device LOCK_EX across the whole child init. When parallel stage
# init is enabled the engine-core child takes phased SH/EX locks
# itself (see stage_phase_lock), so the parent must NOT also hold the
# lock here — it would self-deadlock while waiting for the child's
# READY handshake.
if not self._parallel_stage_init:
g3_start = time.perf_counter()
with self._scoped_spawn_device_env(physical_devices):
lock_fds = acquire_device_locks(
plan.metadata.stage_id,
plan.engine_args_dict,
stage_init_timeout,
)
logger.debug(
"[stage_init] Stage-%s G3 device-lock acquire took %.3fs",
plan.metadata.stage_id,
time.perf_counter() - g3_start,
)
launch_cm = launch_stage_replica(
vllm_config=vllm_config,
executor_class=executor_class,
log_stats=self._log_stats,
stage_id=plan.metadata.stage_id,
replica_id=plan.replica_id,
stage_config=plan.stage_cfg,
omni_master_server=self._get_omni_master_server(),
omni_coordinator_address=self._get_coordinator_address(),
stage_visible_devices=physical_devices,
spawn_device_lock=self._spawn_device_lock,
omni_parallel_stage_init=self._parallel_stage_init,
)
# Only process spawning and the runtime.env overlay need the global
# launch lock. The launch context's exit waits for READY: holding the
# lock there serializes model loading and compilation even across
# different GPUs. Default initialization keeps its per-device EX
# locks until READY; parallel_stage_init uses child phase locks.
g2_start = time.perf_counter()
with ExitStack() as launch_stack:
with self._replica_launch_lock:
g2_locked = time.perf_counter()
with stage_runtime_env(plan.metadata.stage_id, plan.metadata.runtime_cfg):
resources = launch_stack.enter_context(launch_cm)
g2_spawned = time.perf_counter()
logger.debug(
"[stage_init] Stage-%s G2 launch-lock wait=%.3fs, spawn=%.3fs, READY=%.3fs",
plan.metadata.stage_id,
g2_locked - g2_start,
g2_spawned - g2_locked,
time.perf_counter() - g2_spawned,
external_addresses = self._get_external_client_addresses(
plan.metadata.stage_id,
plan.replica_id,
)
if external_addresses is not None:
if plan.stage_vllm_config is None or plan.executor_class is None:
raise RuntimeError(f"LLM stage {plan.metadata.stage_id} is missing its engine configuration")
return cast(
StagePoolClient,
StageEngineCoreClientBase.make_async_mp_client(
vllm_config=plan.stage_vllm_config,
executor_class=plan.executor_class,
log_stats=self._log_stats,
metadata=plan.metadata,
client_addresses=external_addresses,
client_count=self._client_count,
client_index=self._client_index,
),
)
logger.info("[StageRuntime] Stage %s engine startup completed", plan.metadata.stage_id)
if resources is None:
raise RuntimeError(f"LLM stage {plan.metadata.stage_id} launcher returned no resources")
if resources.addresses is None:
raise RuntimeError(f"LLM stage {plan.metadata.stage_id} launcher returned no addresses")
stage_client = StageEngineCoreClientBase.make_async_mp_client(
vllm_config=vllm_config,
executor_class=executor_class,
log_stats=self._log_stats,
metadata=plan.metadata,
client_addresses=self._client_addresses_from_zmq(resources.addresses),
engine_manager=resources.manager,
coordinator=resources.coordinator,
if plan.stage_vllm_config is None or plan.executor_class is None:
raise RuntimeError(f"LLM stage {plan.metadata.stage_id} is missing its engine configuration")
stage_plan = LogicalStageInitPlan(
stage_idx=plan.metadata.stage_id,
stage_id=plan.metadata.stage_id,
replicas=[plan],
)
with self.launch_stage_engines(
stage_plans=[stage_plan],
stage_init_timeout=stage_init_timeout,
) as launch:
resources = launch.resources[0]
return cast(
StagePoolClient,
StageEngineCoreClientBase.make_async_mp_client(
vllm_config=plan.stage_vllm_config,
executor_class=plan.executor_class,
log_stats=self._log_stats,
metadata=plan.metadata,
client_addresses=self._client_addresses_from_zmq(resources.addresses),
engine_manager=resources.manager,
coordinator=resources.coordinator,
),
)
logger.info("[StageRuntime] Stage %s initialized", plan.metadata.stage_id)
return cast(StagePoolClient, stage_client)
except Exception:
if stage_client is not None:
try:
stage_client.shutdown()
except Exception as cleanup_error:
logger.warning(
"[StageRuntime] Failed to cleanup stage %s after init failure: %s",
plan.metadata.stage_id,
cleanup_error,
)
else:
self._cleanup_launched_resources(
stage_id=plan.metadata.stage_id,
resources=resources,
)
raise
finally:
if lock_fds:
release_device_locks(lock_fds)
def _get_coordinator_address(self) -> str | None:
"""Return coordinator router address. Overridden by DistStageRuntime."""
return None
def _get_external_client_addresses(self, stage_id: int, replica_id: int) -> dict[str, Any] | None:
if self._external_stage_addresses is None:
return None
stage_addresses = self._external_stage_addresses.get(stage_id)
if stage_addresses is None:
stage_addresses = self._external_stage_addresses.get(str(stage_id))
if stage_addresses is None:
raise ValueError(f"Missing external addresses for stage {stage_id}")
replica_addresses = stage_addresses.get(replica_id)
if replica_addresses is None:
replica_addresses = stage_addresses.get(str(replica_id))
if replica_addresses is None:
raise ValueError(f"Missing external addresses for stage {stage_id} replica {replica_id}")
return dict(replica_addresses)
def _get_omni_master_server(self) -> OmniMasterServer | None:
"""Return the master server for local distributed launches, if any."""
return None
@@ -966,7 +1163,7 @@ class DistStageRuntime(StageRuntime):
self,
stage_configs: list[Any],
model: str,
config_path: str,
config_path: str | None,
*,
stage_init_timeout: int,
async_chunk: bool,
@@ -1303,7 +1500,7 @@ class DistStageRuntime(StageRuntime):
def create_stage_runtime(
stage_configs: list[Any],
model: str,
config_path: str,
config_path: str | None,
*,
single_stage_mode: bool,
stage_init_timeout: int,
@@ -1319,6 +1516,7 @@ def create_stage_runtime(
omni_lb_policy: str = "random",
request_queue: janus.Queue[EngineQueueMessage] | None = None,
log_stats: bool = False,
client_config: OmniClientConfig | None = None,
) -> StageRuntime:
"""Factory: select StageRuntime or DistStageRuntime."""
if single_stage_mode:
@@ -1350,4 +1548,5 @@ def create_stage_runtime(
tokenizer=tokenizer,
parallel_stage_init=parallel_stage_init,
log_stats=log_stats,
client_config=client_config,
)