[Bugfix] Eliminate frontend ZMQ port TOCTOU with inherited listeners (#54113)
Signed-off-by: Bugen Zhao <i@bugenzhao.com> Co-authored-by: OpenAI Codex <codex@openai.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
OpenAI Codex
Claude Opus 5.5
parent
fb2ac82458
commit
f226af0e11
@@ -328,19 +328,10 @@ def run_multi_api_server(args: argparse.Namespace):
|
||||
None
|
||||
)
|
||||
|
||||
from vllm.v1.engine.utils import get_engine_zmq_addresses
|
||||
from vllm.v1.engine.utils import bind_engine_zmq_listeners
|
||||
|
||||
# Defer port allocation to the child's bind() to avoid TOCTOU, except
|
||||
# for Rust front-end and Ray DP, which can't see the post-bind rebind
|
||||
# (CLI-arg subprocess / pickled-into-actor snapshot respectively) and
|
||||
# so pre-allocate driver-side -- reintroducing the original race only
|
||||
# there.
|
||||
is_ray_dp = parallel_config.data_parallel_backend == "ray"
|
||||
addresses = get_engine_zmq_addresses(
|
||||
vllm_config,
|
||||
num_api_servers,
|
||||
defer_api_server_ports=not (rust_frontend_path or is_ray_dp),
|
||||
)
|
||||
zmq_listeners = bind_engine_zmq_listeners(vllm_config, num_api_servers)
|
||||
addresses = zmq_listeners.addresses
|
||||
|
||||
with launch_core_engines(
|
||||
vllm_config, executor_class, log_stats, addresses
|
||||
@@ -365,8 +356,8 @@ def run_multi_api_server(args: argparse.Namespace):
|
||||
sock=sock,
|
||||
grpc_sock=grpc_sock,
|
||||
args=args,
|
||||
input_address=addresses.inputs[0],
|
||||
output_address=addresses.outputs[0],
|
||||
input_listener=zmq_listeners.inputs[0],
|
||||
output_listener=zmq_listeners.outputs[0],
|
||||
engine_start_index=expected_engine_start_index,
|
||||
engine_count=expected_engine_count,
|
||||
data_parallel_size=parallel_config.data_parallel_size,
|
||||
@@ -379,22 +370,12 @@ def run_multi_api_server(args: argparse.Namespace):
|
||||
sock=sock,
|
||||
args=args,
|
||||
num_servers=num_api_servers,
|
||||
input_addresses=addresses.inputs,
|
||||
output_addresses=addresses.outputs,
|
||||
input_listeners=zmq_listeners.inputs,
|
||||
output_listeners=zmq_listeners.outputs,
|
||||
stats_update_address=stats_update_address,
|
||||
tensor_queue=engine_launch.tensor_queue,
|
||||
)
|
||||
|
||||
if not is_ray_dp:
|
||||
# Forward each child's bound endpoints to the engine handshake
|
||||
# (runs on ``with`` exit). Skipped for Ray DP, where addresses
|
||||
# are pre-allocated above and Ray actors already hold them.
|
||||
actual_inputs, actual_outputs = (
|
||||
api_server_manager.gather_actual_addresses()
|
||||
)
|
||||
addresses.inputs = actual_inputs
|
||||
addresses.outputs = actual_outputs
|
||||
|
||||
# Set frontend processes to watch during engine startup.
|
||||
# If any of these processes exit before the engines are up, the engine startup
|
||||
# will be aborted with an error.
|
||||
|
||||
+92
-11
@@ -11,6 +11,7 @@ from collections.abc import (
|
||||
Iterator,
|
||||
Sequence,
|
||||
)
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
|
||||
@@ -25,6 +26,23 @@ from vllm.logger import init_logger
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
@dataclass
|
||||
class ZmqListener:
|
||||
"""A supervisor-bound listener that a ZMQ socket can adopt."""
|
||||
|
||||
address: str
|
||||
socket: socket.socket
|
||||
|
||||
def close(self) -> None:
|
||||
self.socket.close()
|
||||
|
||||
def cleanup(self) -> None:
|
||||
self.close()
|
||||
if self.address.startswith("ipc://"):
|
||||
with contextlib.suppress(FileNotFoundError):
|
||||
os.unlink(self.address.removeprefix("ipc://"))
|
||||
|
||||
|
||||
def close_sockets(sockets: Sequence[zmq.Socket | zmq.asyncio.Socket]):
|
||||
for sock in sockets:
|
||||
if sock is not None:
|
||||
@@ -307,6 +325,27 @@ def make_zmq_path(scheme: str, host: str, port: int | None = None) -> str:
|
||||
|
||||
|
||||
# Adapted from: https://github.com/sgl-project/sglang/blob/v0.4.1/python/sglang/srt/utils.py#L783 # noqa: E501
|
||||
# Apply the existing make_zmq_socket memory policy to every socket owner.
|
||||
_ZMQ_LARGE_BUFFER_SIZE = 512 * 1024**2
|
||||
_ZMQ_LARGE_BUFFER_MIN_TOTAL_MEMORY = 32 * 1024**3
|
||||
_ZMQ_LARGE_BUFFER_MIN_AVAILABLE_MEMORY = 16 * 1024**3
|
||||
|
||||
|
||||
def _get_zmq_socket_buffer_size() -> int:
|
||||
"""Choose the shared libzmq and inherited-listener buffer policy."""
|
||||
mem = psutil.virtual_memory()
|
||||
# For systems with substantial memory (>32GB total, >16GB available):
|
||||
# - Set a large 0.5GB buffer to improve throughput
|
||||
# For systems with less memory:
|
||||
# - Use system default (-1) to avoid excessive memory consumption
|
||||
if (
|
||||
mem.total > _ZMQ_LARGE_BUFFER_MIN_TOTAL_MEMORY
|
||||
and mem.available > _ZMQ_LARGE_BUFFER_MIN_AVAILABLE_MEMORY
|
||||
):
|
||||
return _ZMQ_LARGE_BUFFER_SIZE
|
||||
return -1
|
||||
|
||||
|
||||
def make_zmq_socket(
|
||||
ctx: zmq.asyncio.Context | zmq.Context, # type: ignore[name-defined]
|
||||
path: str,
|
||||
@@ -315,22 +354,19 @@ def make_zmq_socket(
|
||||
identity: bytes | None = None,
|
||||
linger: int | None = None,
|
||||
router_handover: bool = False,
|
||||
listener: socket.socket | None = None,
|
||||
) -> zmq.Socket | zmq.asyncio.Socket: # type: ignore[name-defined]
|
||||
"""Make a ZMQ socket with the proper bind/connect semantics."""
|
||||
mem = psutil.virtual_memory()
|
||||
socket = ctx.socket(socket_type)
|
||||
"""Make a ZMQ socket with the proper bind/connect semantics.
|
||||
|
||||
# Calculate buffer size based on system memory
|
||||
total_mem = mem.total / 1024**3
|
||||
available_mem = mem.available / 1024**3
|
||||
# For systems with substantial memory (>32GB total, >16GB available):
|
||||
# - Set a large 0.5GB buffer to improve throughput
|
||||
# For systems with less memory:
|
||||
# - Use system default (-1) to avoid excessive memory consumption
|
||||
buf_size = int(0.5 * 1024**3) if total_mem > 32 and available_mem > 16 else -1
|
||||
When supplied, ``listener`` is detached and its fd moves to libzmq.
|
||||
"""
|
||||
socket = ctx.socket(socket_type)
|
||||
buf_size = _get_zmq_socket_buffer_size()
|
||||
|
||||
if bind is None:
|
||||
bind = socket_type not in (zmq.PUSH, zmq.SUB, zmq.XSUB)
|
||||
if listener is not None and not bind:
|
||||
raise ValueError("An inherited ZMQ listener requires bind=True")
|
||||
|
||||
if socket_type in (zmq.PULL, zmq.DEALER, zmq.ROUTER):
|
||||
socket.setsockopt(zmq.RCVHWM, 0)
|
||||
@@ -353,6 +389,9 @@ def make_zmq_socket(
|
||||
if socket_type == zmq.XPUB:
|
||||
socket.setsockopt(zmq.XPUB_VERBOSE, True)
|
||||
|
||||
if listener is not None:
|
||||
socket.setsockopt(zmq.USE_FD, listener.detach())
|
||||
|
||||
# Determine if the path is a TCP socket with an IPv6 address.
|
||||
# Enable IPv6 on the zmq socket if so.
|
||||
scheme, host, _ = split_zmq_path(path)
|
||||
@@ -367,6 +406,48 @@ def make_zmq_socket(
|
||||
return socket
|
||||
|
||||
|
||||
def make_zmq_listener(path: str, socket_type: Any) -> ZmqListener:
|
||||
"""Bind and listen on a raw socket for later ZMQ adoption."""
|
||||
scheme, host, port = split_zmq_path(path)
|
||||
if scheme == "tcp":
|
||||
family = socket.AF_INET6 if is_valid_ipv6_address(host) else socket.AF_INET
|
||||
bind_address: str | tuple[str, int] = (host, int(port))
|
||||
elif scheme == "ipc":
|
||||
family = socket.AF_UNIX
|
||||
bind_address = path.removeprefix("ipc://")
|
||||
os.makedirs(os.path.dirname(bind_address), exist_ok=True)
|
||||
else:
|
||||
raise ValueError(f"Cannot inherit a {scheme} ZMQ listener")
|
||||
|
||||
listener = socket.socket(family, socket.SOCK_STREAM)
|
||||
bound = False
|
||||
try:
|
||||
buf_size = _get_zmq_socket_buffer_size()
|
||||
if buf_size >= 0:
|
||||
# Accepted stream sockets inherit these settings from the listener.
|
||||
# ZMQ_USE_FD adopts this pre-created socket, so the policy belongs
|
||||
# here as well as on the eventual libzmq socket.
|
||||
if socket_type in (zmq.PULL, zmq.DEALER, zmq.ROUTER):
|
||||
listener.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, buf_size)
|
||||
if socket_type in (zmq.PUSH, zmq.DEALER, zmq.ROUTER):
|
||||
listener.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, buf_size)
|
||||
|
||||
listener.bind(bind_address)
|
||||
bound = True
|
||||
listener.listen()
|
||||
if scheme == "tcp":
|
||||
path = get_tcp_uri(host, listener.getsockname()[1])
|
||||
return ZmqListener(address=path, socket=listener)
|
||||
except BaseException:
|
||||
listener.close()
|
||||
# A failed bind leaves any existing pathname owned by its listener.
|
||||
if scheme == "ipc" and bound:
|
||||
assert isinstance(bind_address, str)
|
||||
with contextlib.suppress(FileNotFoundError):
|
||||
os.unlink(bind_address)
|
||||
raise
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def zmq_socket_ctx(
|
||||
path: str,
|
||||
|
||||
@@ -11,7 +11,6 @@ from collections import Counter, defaultdict
|
||||
from collections.abc import Awaitable, Callable, Sequence
|
||||
from concurrent.futures import Future
|
||||
from dataclasses import dataclass
|
||||
from multiprocessing.connection import Connection
|
||||
from multiprocessing.queues import Queue
|
||||
from threading import Thread
|
||||
from typing import Any, TypeAlias, TypeVar
|
||||
@@ -56,7 +55,8 @@ from vllm.v1.engine.tensor_ipc import TensorIpcSender
|
||||
from vllm.v1.engine.utils import (
|
||||
CoreEngineActorManager,
|
||||
CoreEngineProcManager,
|
||||
get_engine_zmq_addresses,
|
||||
EngineZmqAddresses,
|
||||
get_engine_zmq_bind_addresses,
|
||||
launch_core_engines,
|
||||
)
|
||||
from vllm.v1.executor import Executor
|
||||
@@ -634,63 +634,50 @@ class MPClient(EngineCoreClient):
|
||||
self.stats_update_address = client_addresses.get("stats_update_address")
|
||||
# Tensor queues passed via client_addresses for multi-API-server case
|
||||
tensor_queue = client_addresses.get("tensor_queue")
|
||||
input_listener = client_addresses.get("input_listener")
|
||||
output_listener = client_addresses.get("output_listener")
|
||||
self.input_socket = self.resources.input_socket = make_zmq_socket(
|
||||
self.ctx,
|
||||
input_address,
|
||||
zmq.ROUTER,
|
||||
bind=True,
|
||||
router_handover=enable_input_socket_handover,
|
||||
listener=input_listener,
|
||||
)
|
||||
self.resources.output_socket = make_zmq_socket(
|
||||
self.ctx, output_address, zmq.PULL
|
||||
self.ctx,
|
||||
output_address,
|
||||
zmq.PULL,
|
||||
listener=output_listener,
|
||||
)
|
||||
|
||||
# Report bound endpoints back so the parent can forward
|
||||
# them to engines (mirrors the DPCoordinator pattern).
|
||||
actual_address_pipe: Connection | None = client_addresses.get(
|
||||
"actual_address_pipe"
|
||||
)
|
||||
if actual_address_pipe is not None:
|
||||
try:
|
||||
actual_input = self.input_socket.getsockopt(
|
||||
zmq.LAST_ENDPOINT
|
||||
).decode()
|
||||
actual_output = self.resources.output_socket.getsockopt(
|
||||
zmq.LAST_ENDPOINT
|
||||
).decode()
|
||||
actual_address_pipe.send(
|
||||
{
|
||||
"input_address": actual_input,
|
||||
"output_address": actual_output,
|
||||
}
|
||||
)
|
||||
finally:
|
||||
actual_address_pipe.close()
|
||||
# Engines are managed externally: this process does not fork
|
||||
# them, so there is no fork race; start the MM warmup now.
|
||||
self._start_mm_warmup()
|
||||
else:
|
||||
# Engines are managed by this client.
|
||||
addresses = get_engine_zmq_addresses(vllm_config)
|
||||
bind_addresses = get_engine_zmq_bind_addresses(vllm_config)
|
||||
self.input_socket = self.resources.input_socket = make_zmq_socket(
|
||||
self.ctx,
|
||||
addresses.inputs[0],
|
||||
bind_addresses.inputs[0],
|
||||
zmq.ROUTER,
|
||||
bind=True,
|
||||
router_handover=enable_input_socket_handover,
|
||||
)
|
||||
self.resources.output_socket = make_zmq_socket(
|
||||
self.ctx, addresses.outputs[0], zmq.PULL
|
||||
self.ctx, bind_addresses.outputs[0], zmq.PULL
|
||||
)
|
||||
|
||||
# Resolve ``tcp://host:0`` placeholders to bound endpoints
|
||||
# before engines DEALER-connect. No-op for IPC.
|
||||
addresses.inputs[0] = self.input_socket.getsockopt(
|
||||
zmq.LAST_ENDPOINT
|
||||
).decode()
|
||||
addresses.outputs[0] = self.resources.output_socket.getsockopt(
|
||||
zmq.LAST_ENDPOINT
|
||||
).decode()
|
||||
# EngineZmqAddresses contains only endpoints resolved by the
|
||||
# sockets that own the bind operation.
|
||||
addresses = EngineZmqAddresses(
|
||||
inputs=[self.input_socket.getsockopt(zmq.LAST_ENDPOINT).decode()],
|
||||
outputs=[
|
||||
self.resources.output_socket.getsockopt(
|
||||
zmq.LAST_ENDPOINT
|
||||
).decode()
|
||||
],
|
||||
)
|
||||
|
||||
with launch_core_engines(
|
||||
vllm_config, executor_class, log_stats, addresses
|
||||
|
||||
+67
-16
@@ -23,9 +23,10 @@ from vllm.platforms import current_platform
|
||||
from vllm.ray.ray_env import get_env_vars_to_copy
|
||||
from vllm.utils import numa_utils
|
||||
from vllm.utils.network_utils import (
|
||||
get_open_port,
|
||||
ZmqListener,
|
||||
get_open_zmq_ipc_path,
|
||||
get_tcp_uri,
|
||||
make_zmq_listener,
|
||||
zmq_socket_ctx,
|
||||
)
|
||||
from vllm.utils.system_utils import get_mp_context, set_env_var
|
||||
@@ -82,8 +83,18 @@ class CoreEngine:
|
||||
self.state = CoreEngineState.NEW
|
||||
|
||||
|
||||
@dataclass
|
||||
class EngineZmqBindAddresses:
|
||||
"""Frontend endpoints before their owning sockets bind."""
|
||||
|
||||
inputs: list[str]
|
||||
outputs: list[str]
|
||||
|
||||
|
||||
@dataclass
|
||||
class EngineZmqAddresses:
|
||||
"""Resolved frontend endpoints advertised to engine processes."""
|
||||
|
||||
# ZMQ input socket addresses for each front-end client (requests)
|
||||
inputs: list[str]
|
||||
# ZMQ output socket addresses for each front-end client (responses)
|
||||
@@ -98,6 +109,27 @@ class EngineZmqAddresses:
|
||||
frontend_stats_publish_address: str | None = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class EngineZmqListeners:
|
||||
inputs: list[ZmqListener]
|
||||
outputs: list[ZmqListener]
|
||||
|
||||
@property
|
||||
def addresses(self) -> EngineZmqAddresses:
|
||||
return EngineZmqAddresses(
|
||||
inputs=[listener.address for listener in self.inputs],
|
||||
outputs=[listener.address for listener in self.outputs],
|
||||
)
|
||||
|
||||
def cleanup(self) -> None:
|
||||
for listener in (*self.inputs, *self.outputs):
|
||||
listener.cleanup()
|
||||
|
||||
def __del__(self) -> None:
|
||||
with contextlib.suppress(Exception):
|
||||
self.cleanup()
|
||||
|
||||
|
||||
@dataclass
|
||||
class EngineHandshakeMetadata:
|
||||
"""Metadata sent to each engine process during startup handshake,
|
||||
@@ -1079,22 +1111,16 @@ class CoreEngineActorManager:
|
||||
ray.util.remove_placement_group(pg)
|
||||
|
||||
|
||||
def get_engine_zmq_addresses(
|
||||
def get_engine_zmq_bind_addresses(
|
||||
vllm_config: VllmConfig,
|
||||
num_api_servers: int = 1,
|
||||
*,
|
||||
defer_api_server_ports: bool = True,
|
||||
) -> EngineZmqAddresses:
|
||||
"""Allocate ZMQ addresses for engine-client communication.
|
||||
) -> EngineZmqBindAddresses:
|
||||
"""Create ZMQ endpoint templates for engine-client communication.
|
||||
|
||||
By default each TCP address is a ``tcp://host:0`` placeholder; the
|
||||
consumer (API-server child or single-process ``MPClient``) binds, then
|
||||
recovers the kernel-assigned port via ``getsockopt(zmq.LAST_ENDPOINT)``
|
||||
and writes it back into ``addresses`` before the engine handshake.
|
||||
|
||||
Set ``defer_api_server_ports=False`` only when the consumer cannot
|
||||
report a bound port back (e.g. the Rust front-end). IPC paths are
|
||||
unaffected."""
|
||||
Each TCP address is a ``tcp://host:0`` placeholder. A single-process
|
||||
``MPClient`` binds its own ZMQ sockets. Cross-process frontends use
|
||||
``bind_engine_zmq_listeners`` so the supervisor binds raw listeners before
|
||||
launching engines and transfers listener ownership to each frontend."""
|
||||
parallel_config = vllm_config.parallel_config
|
||||
local_engine_count = parallel_config.data_parallel_size_local
|
||||
local_start_index = parallel_config.data_parallel_rank_local
|
||||
@@ -1119,14 +1145,39 @@ def get_engine_zmq_addresses(
|
||||
def _addr() -> str:
|
||||
if client_local_only:
|
||||
return get_open_zmq_ipc_path()
|
||||
return get_tcp_uri(host, 0 if defer_api_server_ports else get_open_port())
|
||||
return get_tcp_uri(host, 0)
|
||||
|
||||
return EngineZmqAddresses(
|
||||
return EngineZmqBindAddresses(
|
||||
inputs=[_addr() for _ in range(num_api_servers)],
|
||||
outputs=[_addr() for _ in range(num_api_servers)],
|
||||
)
|
||||
|
||||
|
||||
def bind_engine_zmq_listeners(
|
||||
vllm_config: VllmConfig,
|
||||
num_api_servers: int = 1,
|
||||
) -> EngineZmqListeners:
|
||||
"""Bind frontend transport listeners before launching engines."""
|
||||
bind_addresses = get_engine_zmq_bind_addresses(
|
||||
vllm_config,
|
||||
num_api_servers,
|
||||
)
|
||||
inputs: list[ZmqListener] = []
|
||||
outputs: list[ZmqListener] = []
|
||||
try:
|
||||
inputs.extend(
|
||||
make_zmq_listener(address, zmq.ROUTER) for address in bind_addresses.inputs
|
||||
)
|
||||
outputs.extend(
|
||||
make_zmq_listener(address, zmq.PULL) for address in bind_addresses.outputs
|
||||
)
|
||||
return EngineZmqListeners(inputs=inputs, outputs=outputs)
|
||||
except BaseException:
|
||||
for listener in (*inputs, *outputs):
|
||||
listener.cleanup()
|
||||
raise
|
||||
|
||||
|
||||
FrontendProcess = BaseProcess | _SubprocessWrapper
|
||||
|
||||
|
||||
|
||||
+104
-129
@@ -29,7 +29,7 @@ from torch.autograd.profiler import record_function
|
||||
import vllm.envs as envs
|
||||
from vllm.logger import init_logger
|
||||
from vllm.usage.usage_lib import UsageContext, is_usage_stats_enabled, usage_message
|
||||
from vllm.utils.network_utils import get_open_zmq_ipc_path, get_tcp_uri
|
||||
from vllm.utils.network_utils import ZmqListener, get_open_zmq_ipc_path, get_tcp_uri
|
||||
from vllm.utils.system_utils import decorate_logs, kill_process_tree, set_process_title
|
||||
from vllm.utils.torch_utils import PIN_MEMORY
|
||||
from vllm.v1.core.sched.output import SchedulerOutput
|
||||
@@ -177,28 +177,22 @@ class APIServerProcessManager:
|
||||
sock: Any,
|
||||
args: argparse.Namespace,
|
||||
num_servers: int,
|
||||
input_addresses: list[str],
|
||||
output_addresses: list[str],
|
||||
input_listeners: list[ZmqListener],
|
||||
output_listeners: list[ZmqListener],
|
||||
target_server_fn: Callable | None = None,
|
||||
stats_update_address: str | None = None,
|
||||
tensor_queue: Queue | None = None,
|
||||
):
|
||||
"""Initialize and start API server worker processes.
|
||||
|
||||
``input_addresses``/``output_addresses`` may contain
|
||||
``tcp://host:0`` placeholders; each child must report the actual
|
||||
bound endpoint over its ``actual_address_pipe`` in ``client_config``
|
||||
and the parent collects them via
|
||||
:py:meth:`gather_actual_addresses`.
|
||||
|
||||
Args:
|
||||
target_server_fn: Override function to call for each API server process
|
||||
listen_address: Address to listen for client connections
|
||||
sock: Socket for client connections
|
||||
args: Command line arguments
|
||||
num_servers: Number of API server processes to start
|
||||
input_addresses: Input addresses for each API server
|
||||
output_addresses: Output addresses for each API server
|
||||
input_listeners: Input listeners for each API server
|
||||
output_listeners: Output listeners for each API server
|
||||
stats_update_address: Optional stats update address
|
||||
tensor_queue: Optional tensor IPC queue for sharing MM tensors
|
||||
|
||||
@@ -209,7 +203,6 @@ class APIServerProcessManager:
|
||||
|
||||
spawn_context = multiprocessing.get_context("spawn")
|
||||
self.processes: list[BaseProcess] = []
|
||||
self._address_pipes: list[connection.Connection] = []
|
||||
|
||||
admission_counters = None
|
||||
if num_servers > 1 and getattr(args, "max_num_queued_reqs", None) is not None:
|
||||
@@ -220,126 +213,65 @@ class APIServerProcessManager:
|
||||
SharedAdmissionStats.num_counters(num_servers),
|
||||
)
|
||||
|
||||
for i, in_addr, out_addr in zip(
|
||||
range(num_servers), input_addresses, output_addresses
|
||||
):
|
||||
client_config: dict[str, Any] = {
|
||||
"input_address": in_addr,
|
||||
"output_address": out_addr,
|
||||
"client_count": num_servers,
|
||||
"client_index": i,
|
||||
}
|
||||
if admission_counters is not None:
|
||||
client_config["mp_admission_counters"] = admission_counters
|
||||
if stats_update_address is not None:
|
||||
client_config["stats_update_address"] = stats_update_address
|
||||
if tensor_queue is not None:
|
||||
client_config["tensor_queue"] = tensor_queue
|
||||
|
||||
parent_recv, child_send = spawn_context.Pipe(duplex=False)
|
||||
self._address_pipes.append(parent_recv)
|
||||
client_config["actual_address_pipe"] = child_send
|
||||
|
||||
proc = spawn_context.Process(
|
||||
target=target_server_fn or run_api_server_worker_proc,
|
||||
name=f"ApiServer_{i}",
|
||||
args=(listen_address, sock, args, client_config),
|
||||
listeners = [*input_listeners, *output_listeners]
|
||||
self._listeners = listeners
|
||||
try:
|
||||
listener_pairs = zip(
|
||||
range(num_servers), input_listeners, output_listeners, strict=True
|
||||
)
|
||||
self.processes.append(proc)
|
||||
proc.start()
|
||||
for i, input_listener, output_listener in listener_pairs:
|
||||
client_config: dict[str, Any] = {
|
||||
"input_address": input_listener.address,
|
||||
"output_address": output_listener.address,
|
||||
"input_listener": input_listener.socket,
|
||||
"output_listener": output_listener.socket,
|
||||
"client_count": num_servers,
|
||||
"client_index": i,
|
||||
}
|
||||
if admission_counters is not None:
|
||||
client_config["mp_admission_counters"] = admission_counters
|
||||
if stats_update_address is not None:
|
||||
client_config["stats_update_address"] = stats_update_address
|
||||
if tensor_queue is not None:
|
||||
client_config["tensor_queue"] = tensor_queue
|
||||
|
||||
# Drop parent's write end so reader sees EOF on child death.
|
||||
child_send.close()
|
||||
proc = spawn_context.Process(
|
||||
target=target_server_fn or run_api_server_worker_proc,
|
||||
name=f"ApiServer_{i}",
|
||||
args=(listen_address, sock, args, client_config),
|
||||
)
|
||||
self.processes.append(proc)
|
||||
proc.start()
|
||||
input_listener.close()
|
||||
output_listener.close()
|
||||
except BaseException:
|
||||
_shutdown_processes_and_cleanup_listeners(self.processes, listeners)
|
||||
raise
|
||||
|
||||
logger.info("Started %d API server processes", len(self.processes))
|
||||
|
||||
# Shutdown only the API server processes on garbage collection
|
||||
# The extra processes are managed by their owners
|
||||
self._finalizer = weakref.finalize(self, shutdown, self.processes)
|
||||
|
||||
def gather_actual_addresses(
|
||||
self,
|
||||
timeout: float = envs.VLLM_ENGINE_READY_TIMEOUT_S,
|
||||
) -> tuple[list[str], list[str]]:
|
||||
"""Return (inputs, outputs) reported by each child, indexed by
|
||||
``client_index``. Raises ``RuntimeError`` on timeout or premature
|
||||
child exit."""
|
||||
n = len(self._address_pipes)
|
||||
inputs: list[str | None] = [None] * n
|
||||
outputs: list[str | None] = [None] * n
|
||||
pending: dict[connection.Connection, int] = {
|
||||
pipe: i for i, pipe in enumerate(self._address_pipes)
|
||||
}
|
||||
sentinel_to_idx: dict[Any, int] = {
|
||||
proc.sentinel: i for i, proc in enumerate(self.processes)
|
||||
}
|
||||
|
||||
deadline = time.monotonic() + timeout
|
||||
try:
|
||||
while pending:
|
||||
remaining = deadline - time.monotonic()
|
||||
if remaining <= 0:
|
||||
missing = [self.processes[i].name for i in pending.values()]
|
||||
raise RuntimeError(
|
||||
f"Timed out after {timeout:.1f}s waiting for "
|
||||
f"API server(s) to report bound ZMQ addresses: "
|
||||
f"{missing}"
|
||||
)
|
||||
waitables: list[Any] = list(pending.keys()) + list(
|
||||
sentinel_to_idx.keys()
|
||||
)
|
||||
ready = connection.wait(waitables, timeout=remaining)
|
||||
# Drain pipes before checking sentinels: a child that sent
|
||||
# its message and then exited can surface both events in
|
||||
# the same poll, and we must record the success first.
|
||||
for item in ready:
|
||||
if isinstance(item, connection.Connection) and item in pending:
|
||||
idx = pending.pop(item)
|
||||
try:
|
||||
msg: dict[str, str] = item.recv()
|
||||
except EOFError as e:
|
||||
raise RuntimeError(
|
||||
f"API server {self.processes[idx].name} "
|
||||
f"closed its address pipe without "
|
||||
f"reporting its bound ZMQ addresses"
|
||||
) from e
|
||||
inputs[idx] = msg["input_address"]
|
||||
outputs[idx] = msg["output_address"]
|
||||
item.close()
|
||||
for item in ready:
|
||||
if item in sentinel_to_idx:
|
||||
idx = sentinel_to_idx.pop(item)
|
||||
pipe = self._address_pipes[idx]
|
||||
if pipe in pending:
|
||||
proc = self.processes[idx]
|
||||
raise RuntimeError(
|
||||
f"API server process {proc.name} exited "
|
||||
f"(code={proc.exitcode}) before reporting "
|
||||
f"its bound ZMQ addresses"
|
||||
)
|
||||
finally:
|
||||
for pipe in pending:
|
||||
with contextlib.suppress(Exception):
|
||||
pipe.close()
|
||||
|
||||
return inputs, outputs # type: ignore[return-value]
|
||||
self._finalizer = weakref.finalize(
|
||||
self,
|
||||
_shutdown_processes_and_cleanup_listeners,
|
||||
self.processes,
|
||||
listeners,
|
||||
)
|
||||
|
||||
def shutdown(self, timeout: float | None = None) -> None:
|
||||
"""Shutdown API server processes with configurable timeout"""
|
||||
for pipe in self._address_pipes:
|
||||
with contextlib.suppress(Exception):
|
||||
pipe.close()
|
||||
self._address_pipes = []
|
||||
|
||||
if self._finalizer.detach() is not None:
|
||||
shutdown(self.processes, timeout=timeout)
|
||||
_shutdown_processes_and_cleanup_listeners(
|
||||
self.processes, self._listeners, timeout=timeout
|
||||
)
|
||||
|
||||
|
||||
class RustFrontendProcessManager:
|
||||
"""Manages a single Rust frontend subprocess.
|
||||
|
||||
Launches the Rust vllm-rs binary in 'frontend' mode, passing the
|
||||
listening socket fd and ZMQ transport addresses. Provides the same
|
||||
HTTP and ZMQ listener file descriptors. Provides the same
|
||||
interface as APIServerProcessManager for process monitoring.
|
||||
"""
|
||||
|
||||
@@ -348,8 +280,8 @@ class RustFrontendProcessManager:
|
||||
binary_path: str,
|
||||
sock: Any,
|
||||
args: argparse.Namespace,
|
||||
input_address: str,
|
||||
output_address: str,
|
||||
input_listener: ZmqListener,
|
||||
output_listener: ZmqListener,
|
||||
engine_start_index: int,
|
||||
engine_count: int,
|
||||
data_parallel_size: int,
|
||||
@@ -359,18 +291,22 @@ class RustFrontendProcessManager:
|
||||
import os
|
||||
import subprocess
|
||||
|
||||
fd = sock.fileno()
|
||||
os.set_inheritable(fd, True)
|
||||
listen_fd = sock.fileno()
|
||||
input_fd = input_listener.socket.fileno()
|
||||
output_fd = output_listener.socket.fileno()
|
||||
inherited_fds = [listen_fd, input_fd, output_fd]
|
||||
for fd in inherited_fds:
|
||||
os.set_inheritable(fd, True)
|
||||
|
||||
cmd = [
|
||||
binary_path,
|
||||
"frontend",
|
||||
"--listen-fd",
|
||||
str(fd),
|
||||
"--input-address",
|
||||
input_address,
|
||||
"--output-address",
|
||||
output_address,
|
||||
str(listen_fd),
|
||||
"--input-listener-fd",
|
||||
str(input_fd),
|
||||
"--output-listener-fd",
|
||||
str(output_fd),
|
||||
"--engine-start-index",
|
||||
str(engine_start_index),
|
||||
"--engine-count",
|
||||
@@ -378,12 +314,11 @@ class RustFrontendProcessManager:
|
||||
"--data-parallel-size",
|
||||
str(data_parallel_size),
|
||||
]
|
||||
pass_fds = [fd]
|
||||
if grpc_sock is not None:
|
||||
grpc_fd = grpc_sock.fileno()
|
||||
os.set_inheritable(grpc_fd, True)
|
||||
cmd.extend(["--grpc-listen-fd", str(grpc_fd)])
|
||||
pass_fds.append(grpc_fd)
|
||||
inherited_fds.append(grpc_fd)
|
||||
if stats_update_address is not None:
|
||||
cmd.extend(["--coordinator-address", stats_update_address])
|
||||
from vllm.entrypoints.serve.utils.api_utils import jsonify_non_default_args
|
||||
@@ -425,18 +360,34 @@ class RustFrontendProcessManager:
|
||||
|
||||
redacted_json = json.dumps(redact_sensitive_args(args_dict), sort_keys=True)
|
||||
logger.info("Launching Rust frontend: %s", " ".join(cmd[:-1] + [redacted_json]))
|
||||
self._proc = subprocess.Popen(cmd, pass_fds=pass_fds)
|
||||
self._listeners = [input_listener, output_listener]
|
||||
try:
|
||||
self._proc = subprocess.Popen(cmd, pass_fds=inherited_fds)
|
||||
except BaseException:
|
||||
for listener in self._listeners:
|
||||
listener.cleanup()
|
||||
raise
|
||||
else:
|
||||
input_listener.close()
|
||||
output_listener.close()
|
||||
|
||||
# Create a process wrapper with a sentinel fd for monitoring
|
||||
self.processes: list[_SubprocessWrapper] = [
|
||||
_SubprocessWrapper(self._proc, "RustFrontend")
|
||||
]
|
||||
|
||||
self._finalizer = weakref.finalize(self, _shutdown_subprocesses, self.processes)
|
||||
self._finalizer = weakref.finalize(
|
||||
self,
|
||||
_shutdown_subprocesses_and_cleanup_listeners,
|
||||
self.processes,
|
||||
self._listeners,
|
||||
)
|
||||
|
||||
def shutdown(self, timeout: float | None = None) -> None:
|
||||
if self._finalizer.detach() is not None:
|
||||
_shutdown_subprocesses(self.processes, timeout=timeout)
|
||||
_shutdown_subprocesses_and_cleanup_listeners(
|
||||
self.processes, self._listeners, timeout=timeout
|
||||
)
|
||||
|
||||
|
||||
class _SubprocessWrapper:
|
||||
@@ -533,6 +484,18 @@ def _shutdown_subprocesses(
|
||||
logger.debug_once("[shutdown] Subprocess manager: complete")
|
||||
|
||||
|
||||
def _shutdown_subprocesses_and_cleanup_listeners(
|
||||
procs: list[_SubprocessWrapper],
|
||||
listeners: list[ZmqListener],
|
||||
timeout: float | None = None,
|
||||
) -> None:
|
||||
try:
|
||||
_shutdown_subprocesses(procs, timeout=timeout)
|
||||
finally:
|
||||
for listener in listeners:
|
||||
listener.cleanup()
|
||||
|
||||
|
||||
def run_api_server_worker_proc(
|
||||
listen_address, sock, args, client_config=None, **uvicorn_kwargs
|
||||
) -> None:
|
||||
@@ -687,6 +650,18 @@ def shutdown(procs: list[BaseProcess], timeout: float | None = None) -> None:
|
||||
logger.debug_once("[shutdown] Process manager: complete")
|
||||
|
||||
|
||||
def _shutdown_processes_and_cleanup_listeners(
|
||||
procs: list[BaseProcess],
|
||||
listeners: list[ZmqListener],
|
||||
timeout: float | None = None,
|
||||
) -> None:
|
||||
try:
|
||||
shutdown(procs, timeout=timeout)
|
||||
finally:
|
||||
for listener in listeners:
|
||||
listener.cleanup()
|
||||
|
||||
|
||||
def copy_slice(
|
||||
from_tensor: torch.Tensor, to_tensor: torch.Tensor, length: int
|
||||
) -> torch.Tensor:
|
||||
|
||||
Reference in New Issue
Block a user