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
+59 -8
View File
@@ -4,6 +4,7 @@
import dataclasses
import importlib
import pickle
from abc import ABC, abstractmethod
from collections.abc import Callable, Sequence
from functools import partial
from inspect import isclass
@@ -53,6 +54,27 @@ MMF_CLASS_TO_FACTORY: dict[type[BaseMultiModalField], str] = {
bytestr: TypeAlias = bytes | bytearray | memoryview | zmq.Frame
class OOBTensorConsumer(ABC):
@abstractmethod
def __call__(self, tensor: torch.Tensor) -> dict | None:
"""
Called with tensors for the current message.
Returns None to reject the tensor (falls back to regular serialization),
otherwise a dict with arbitrary placeholder data to be included
in the serialized message.
"""
return None
@abstractmethod
def new_message(self) -> None:
"""Called at the start of each new encoded message."""
pass
# dtype, shape, metadata -> tensor
OOBTensorProvider = Callable[[str, tuple[int, ...], dict], torch.Tensor]
def _log_insecure_serialization_warning():
logger.warning_once(
"Allowing insecure serialization using pickle due to "
@@ -119,9 +141,16 @@ class MsgpackEncoder:
By default, arrays below 256B are serialized inline Larger will get sent
via dedicated messages. Note that this is a per-tensor limit.
When a ``oob_tensor_consumer`` is provided, tensors (CUDA and CPU) will be
offered to it for out-of-band handling.
"""
def __init__(self, size_threshold: int | None = None):
def __init__(
self,
size_threshold: int | None = None,
oob_tensor_consumer: OOBTensorConsumer | None = None,
):
if size_threshold is None:
size_threshold = envs.VLLM_MSGPACK_ZERO_COPY_THRESHOLD
self.encoder = msgpack.Encoder(enc_hook=self.enc_hook)
@@ -130,11 +159,14 @@ class MsgpackEncoder:
# pass custom data to the hook otherwise.
self.aux_buffers: list[bytestr] | None = None
self.size_threshold = size_threshold
self.oob_tensor_consumer = oob_tensor_consumer
if envs.VLLM_ALLOW_INSECURE_SERIALIZATION:
_log_insecure_serialization_warning()
def encode(self, obj: Any) -> Sequence[bytestr]:
try:
if self.oob_tensor_consumer is not None:
self.oob_tensor_consumer.new_message()
self.aux_buffers = bufs = [b""]
bufs[0] = self.encoder.encode(obj)
# This `bufs` list allows us to collect direct pointers to backing
@@ -147,6 +179,8 @@ class MsgpackEncoder:
def encode_into(self, obj: Any, buf: bytearray) -> Sequence[bytestr]:
try:
if self.oob_tensor_consumer is not None:
self.oob_tensor_consumer.new_message()
self.aux_buffers = [buf]
bufs = self.aux_buffers
self.encoder.encode_into(obj, buf)
@@ -222,17 +256,19 @@ class MsgpackEncoder:
def _encode_tensor(
self, obj: torch.Tensor
) -> tuple[str, tuple[int, ...], int | memoryview]:
assert self.aux_buffers is not None
) -> tuple[str, tuple[int, ...], int | dict | memoryview]:
oob_consumer = self.oob_tensor_consumer
# view the tensor as a contiguous 1D array of bytes
arr_data = tensor_data(obj)
if obj.nbytes < self.size_threshold:
if obj.nbytes < self.size_threshold and obj.is_cpu:
# Smaller tensors are encoded inline, just like ndarrays.
data = msgpack.Ext(CUSTOM_TYPE_RAW_VIEW, arr_data)
data = msgpack.Ext(CUSTOM_TYPE_RAW_VIEW, tensor_data(obj))
elif oob_consumer is not None and (data := oob_consumer(obj)) is not None:
assert isinstance(data, dict)
else:
# Otherwise encode index of backing buffer to avoid copy.
assert self.aux_buffers is not None
data = len(self.aux_buffers)
self.aux_buffers.append(arr_data)
self.aux_buffers.append(tensor_data(obj))
dtype = str(obj.dtype).removeprefix("torch.")
return dtype, obj.shape, data
@@ -279,9 +315,17 @@ class MsgpackDecoder:
Note that unlike vanilla `msgspec` Decoders, this interface is generally
not thread-safe when encoding tensors / numpy arrays.
``oob_tensor_provider`` must be used when an OOBTensorConsumer is used on the
encoder side.
"""
def __init__(self, t: Any | None = None, share_mem: bool = True):
def __init__(
self,
t: Any | None = None,
share_mem: bool = True,
oob_tensor_provider: OOBTensorProvider | None = None,
):
self.share_mem = share_mem
self.pin_tensors = is_pin_memory_available()
args = () if t is None else (t,)
@@ -289,6 +333,7 @@ class MsgpackDecoder:
*args, ext_hook=self.ext_hook, dec_hook=self.dec_hook
)
self.aux_buffers: Sequence[bytestr] = ()
self.oob_tensor_provider = oob_tensor_provider
if envs.VLLM_ALLOW_INSECURE_SERIALIZATION:
_log_insecure_serialization_warning()
@@ -353,6 +398,12 @@ class MsgpackDecoder:
def _decode_tensor(self, arr: Any) -> torch.Tensor:
dtype, shape, data = arr
if isinstance(data, dict):
assert self.oob_tensor_provider, (
"Received OOB tensor but tensor provider is not set"
)
return self.oob_tensor_provider(dtype, shape, data)
is_aux = isinstance(data, int)
buffer = self.aux_buffers[data] if is_aux else data
buffer = buffer if isinstance(buffer, memoryview) else memoryview(buffer)