Add tensor IPC transfer mechanism for multimodal data (#32104)

Signed-off-by: Brandon Pelfrey <bpelfrey@nvidia.com>
Signed-off-by: Brandon Pelfrey <brandonpelfrey@gmail.com>
Signed-off-by: Nick Hill <nickhill123@gmail.com>
Co-authored-by: Nick Hill <nickhill123@gmail.com>
This commit is contained in:
Brandon Pelfrey
2026-03-21 20:10:20 +00:00
committed by GitHub
co-authored by Nick Hill
parent 61e381dcf0
commit 80b70884eb
13 changed files with 1430 additions and 25 deletions
+17 -7
View File
@@ -13,6 +13,7 @@ from enum import IntEnum
from functools import partial
from inspect import isclass, signature
from logging import DEBUG
from multiprocessing.queues import Queue
from typing import Any, TypeVar, cast
import msgspec
@@ -59,6 +60,7 @@ from vllm.v1.engine import (
UtilityOutput,
UtilityResult,
)
from vllm.v1.engine.tensor_ipc import TensorIpcReceiver
from vllm.v1.engine.utils import (
EngineHandshakeMetadata,
EngineZmqAddresses,
@@ -788,6 +790,7 @@ class EngineCoreProc(EngineCore):
executor_class: type[Executor],
log_stats: bool,
client_handshake_address: str | None = None,
tensor_queue: Queue | None = None,
*,
engine_index: int = 0,
):
@@ -802,6 +805,12 @@ class EngineCoreProc(EngineCore):
self.engines_running = False
self.shutdown_state = EngineShutdownState.RUNNING
# Receiver for tensor IPC
self.tensor_ipc_receiver: TensorIpcReceiver | None = None
if tensor_queue is not None:
self.tensor_ipc_receiver = TensorIpcReceiver(tensor_queue)
logger.info("Using tensor IPC queue for multimodal tensor sharing")
with self._perform_handshakes(
handshake_address,
identity,
@@ -1340,9 +1349,11 @@ class EngineCoreProc(EngineCore):
):
"""Input socket IO thread."""
# Msgpack serialization decoding.
add_request_decoder = MsgpackDecoder(EngineCoreRequest)
generic_decoder = MsgpackDecoder()
# Msgpack serialization decoding with optional tensor IPC receiver.
add_request_decoder = MsgpackDecoder(
EngineCoreRequest, oob_tensor_provider=self.tensor_ipc_receiver
)
generic_decoder = MsgpackDecoder(oob_tensor_provider=self.tensor_ipc_receiver)
with ExitStack() as stack, zmq.Context() as ctx:
input_sockets = [
@@ -1418,10 +1429,7 @@ class EngineCoreProc(EngineCore):
self.input_queue.put_nowait((request_type, request))
def process_output_sockets(
self,
output_paths: list[str],
coord_output_path: str | None,
engine_index: int,
self, output_paths: list[str], coord_output_path: str | None, engine_index: int
):
"""Output socket IO thread."""
@@ -1580,6 +1588,7 @@ class DPEngineCoreProc(EngineCoreProc):
executor_class: type[Executor],
log_stats: bool,
client_handshake_address: str | None = None,
tensor_queue: Queue | None = None,
):
assert vllm_config.model_config.is_moe, (
"DPEngineCoreProc should only be used for MoE models"
@@ -1605,6 +1614,7 @@ class DPEngineCoreProc(EngineCoreProc):
log_stats,
client_handshake_address,
engine_index=dp_rank,
tensor_queue=tensor_queue,
)
def _init_data_parallel(self, vllm_config: VllmConfig):
+17 -4
View File
@@ -12,6 +12,7 @@ from collections import defaultdict, deque
from collections.abc import Awaitable, Callable, Sequence
from concurrent.futures import Future
from dataclasses import dataclass
from multiprocessing.queues import Queue
from threading import Thread
from typing import Any, TypeAlias, TypeVar
@@ -45,6 +46,7 @@ from vllm.v1.engine import (
from vllm.v1.engine.coordinator import DPCoordinator
from vllm.v1.engine.core import EngineCore, EngineCoreProc
from vllm.v1.engine.exceptions import EngineDeadError
from vllm.v1.engine.tensor_ipc import TensorIpcSender
from vllm.v1.engine.utils import (
CoreEngineActorManager,
CoreEngineProcManager,
@@ -477,9 +479,6 @@ class MPClient(EngineCoreClient):
client_addresses: dict[str, str] | None = None,
):
self.vllm_config = vllm_config
# Serialization setup.
self.encoder = MsgpackEncoder()
self.decoder = MsgpackDecoder(EngineCoreOutputs)
# ZMQ setup.
sync_ctx = zmq.Context(io_threads=2)
@@ -501,11 +500,14 @@ class MPClient(EngineCoreClient):
enable_input_socket_handover = parallel_config.enable_elastic_ep
self.stats_update_address: str | None = None
tensor_queue: Queue | None = None
if client_addresses:
# Engines are managed externally to this client.
input_address = client_addresses["input_address"]
output_address = client_addresses["output_address"]
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") # type: ignore[assignment]
self.input_socket = self.resources.input_socket = make_zmq_socket(
self.ctx,
input_address,
@@ -532,7 +534,7 @@ class MPClient(EngineCoreClient):
with launch_core_engines(
vllm_config, executor_class, log_stats, addresses
) as (engine_manager, coordinator, addresses):
) as (engine_manager, coordinator, addresses, tensor_queue):
self.resources.coordinator = coordinator
self.resources.engine_manager = engine_manager
@@ -542,6 +544,17 @@ class MPClient(EngineCoreClient):
coordinator.get_stats_publish_address()
)
# Serialization setup with tensor queues for multimodal tensor IPC.
tensor_ipc_sender: TensorIpcSender | None = None
model_config = getattr(vllm_config, "model_config", None)
if model_config is not None and model_config.multimodal_config is not None:
mm_tensor_ipc = model_config.multimodal_config.mm_tensor_ipc
if mm_tensor_ipc == "torch_shm" and tensor_queue is not None:
tensor_ipc_sender = TensorIpcSender(tensor_queue)
self.encoder = MsgpackEncoder(oob_tensor_consumer=tensor_ipc_sender)
self.decoder = MsgpackDecoder(EngineCoreOutputs)
dp_size = parallel_config.data_parallel_size
dp_rank = parallel_config.data_parallel_index
dp_local_size = parallel_config.data_parallel_size_local
+178
View File
@@ -0,0 +1,178 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Tensor IPC transport via torch.multiprocessing.Queue.
This module contains the queue-based transport logic for sharing tensors
between processes (e.g., API server -> engine core). The msgpack layer
emits/consumes lightweight :class:`TensorIpcData` values, while transport
state such as request association, handle generation, queue routing, buffering,
and cleanup lives here.
"""
import dataclasses
import uuid
from collections import defaultdict
from dataclasses import field
from multiprocessing.queues import Queue as MPQueue
from typing import Any
import torch
from vllm.logger import init_logger
from vllm.v1.serial_utils import OOBTensorConsumer
logger = init_logger(__name__)
TensorIpcQueue = MPQueue
@dataclasses.dataclass
class TensorIpcData:
"""
Data sent via torch.multiprocessing.Queue for zero-copy IPC.
Contains the tensor_id and the actual tensor. The tensor is
shared in memory (GPU or CPU) for efficient inter-process communication.
"""
sender_id: str
message_id: int
tensor_id: int
tensor: torch.Tensor
class TensorIpcSender(OOBTensorConsumer):
"""Send-side logic for tensor IPC via torch.multiprocessing.Queue.
Uses a single queue targeting rank 0 (the only rank that consumes
multimodal tensors during TP>1 / PP>1. Note: DP>1 not supported).
"""
def __init__(self, queue: TensorIpcQueue):
self.queue = queue
self._tensor_id_counter = 0
self._message_counter = 0
self._sender_id = uuid.uuid4().hex[:8]
def set_target_engine(self, target_engine: int) -> None:
if target_engine != 0:
raise IndexError(
"TensorIpcSender only supports a single queue; "
f"got target engine {target_engine}"
)
def new_message(self) -> None:
self._message_counter += 1
self._tensor_id_counter = 0
def __call__(self, tensor: torch.Tensor) -> dict[str, Any] | None:
"""Send tensor via queue, return its handle. Returns None if failed."""
try:
# Move tensor to shared memory for IPC
# This is required for proper inter-process communication
if not tensor.is_shared():
tensor = tensor.share_memory_()
metadata = {
"sender_id": self._sender_id,
"message_id": self._message_counter,
"tensor_id": self._tensor_id_counter,
}
self._tensor_id_counter += 1
ipc_data = TensorIpcData(**metadata, tensor=tensor) # type: ignore[arg-type]
# Use a timeout to avoid blocking indefinitely
self.queue.put(ipc_data, timeout=10.0)
logger.debug(
"Sent tensor %s for (shape=%s, device=%s) "
"via IPC queue (shared memory)",
metadata,
tensor.shape,
tensor.device,
)
return metadata
except Exception as e:
logger.warning(
"Failed to send tensor via IPC queue: %s. "
"Falling back to standard serialization.",
e,
)
return None
@dataclasses.dataclass
class _Sender:
current_message_id: int = -1
tensors: dict[int, dict[int, torch.Tensor]] = field(default_factory=dict)
class TensorIpcReceiver:
"""Receive-side logic for tensor IPC via torch.multiprocessing.Queue.
Wraps the queue receive logic previously embedded in MsgpackDecoder.
"""
def __init__(self, queue: TensorIpcQueue):
self.queue = queue
self._tensor_buffers = defaultdict[str, _Sender](_Sender)
def __call__(
self, dtype: str, shape: tuple[int, ...], meta: dict[str, Any]
) -> torch.Tensor:
"""Retrieve a tensor from torch.multiprocessing.Queue.
Uses a drain-and-buffer pattern: drains all available tensors from
the queue, buffering them, until the requested tensor is found.
Works for CUDA and CPU.
"""
# Create lookup key from handle
sender_id: str = meta["sender_id"]
message_id: int = meta["message_id"]
tensor_id: int = meta["tensor_id"]
# Drain all available tensors. We save them regardless if this is
# the one we're waiting for as they may arrive out of order from
# multiple producers.
while True:
sender = self._tensor_buffers.get(sender_id)
if sender is not None:
tensors = sender.tensors
tensor = tensors.get(message_id, {}).pop(tensor_id, None)
if tensor is not None:
if sender.current_message_id != message_id:
while tensors and (mid := next(iter(tensors))) < message_id:
if sender.tensors.pop(mid):
logger.warning(
"Discarding %d stale tensors from sender %s",
sender_id,
)
sender.current_message_id = message_id
logger.debug(
"Received tensor %s from sender %s for (shape=%s, device=%s) "
"via IPC queue (shared memory)",
(message_id, tensor_id),
sender_id,
tensor.shape,
tensor.device,
)
return tensor
ipc_data: TensorIpcData = self.queue.get(timeout=10.0)
# Store tensor
sender = self._tensor_buffers[ipc_data.sender_id]
if sender.current_message_id > ipc_data.message_id:
logger.warning(
"Ignoring stale tensor from sender %s", ipc_data.sender_id
)
continue
sender.tensors.setdefault(ipc_data.message_id, {})[ipc_data.tensor_id] = (
ipc_data.tensor
)
+15 -2
View File
@@ -10,6 +10,7 @@ from dataclasses import dataclass
from enum import Enum, auto
from multiprocessing import Process, connection
from multiprocessing.process import BaseProcess
from multiprocessing.queues import Queue
from typing import TYPE_CHECKING
from unittest.mock import patch
@@ -95,6 +96,7 @@ class CoreEngineProcManager:
executor_class: type[Executor],
log_stats: bool,
client_handshake_address: str | None = None,
tensor_queue: Queue | None = None,
):
context = get_mp_context()
common_kwargs = {
@@ -103,6 +105,7 @@ class CoreEngineProcManager:
"handshake_address": handshake_address,
"executor_class": executor_class,
"log_stats": log_stats,
"tensor_queue": tensor_queue,
}
if client_handshake_address:
@@ -864,6 +867,7 @@ def launch_core_engines(
CoreEngineProcManager | CoreEngineActorManager | None,
DPCoordinator | None,
EngineZmqAddresses,
Queue | None,
]
]:
"""Launch engine and DP coordinator processes as needed."""
@@ -878,6 +882,14 @@ def launch_core_engines(
offline_mode = local_start_index is not None
# Create a single tensor IPC queue for sharing multimodal tensors between
# API servers and engine core. Returns a single queue since we only support
# DP=1 for this data flow.
tensor_queue: Queue | None = None
multimodal_config = vllm_config.model_config.multimodal_config
if multimodal_config is not None and multimodal_config.mm_tensor_ipc == "torch_shm":
tensor_queue = get_mp_context().Queue()
# Run the DP Coordinator process with rank 0 when in online DP mode.
# The coordinator is needed for:
# 1. Internal/hybrid LB: collecting and publishing queue stats for load balancing
@@ -913,7 +925,7 @@ def launch_core_engines(
log_stats=log_stats,
)
yield engine_actor_manager, coordinator, addresses
yield engine_actor_manager, coordinator, addresses, tensor_queue
return
if offline_mode:
@@ -975,11 +987,12 @@ def launch_core_engines(
local_engine_count=local_engine_count,
start_index=dp_rank,
local_start_index=local_start_index or 0,
tensor_queue=tensor_queue,
)
else:
local_engine_manager = None
yield local_engine_manager, coordinator, addresses
yield local_engine_manager, coordinator, addresses, tensor_queue
# Now wait for engines to start.
wait_for_engine_startup(