[EPD] Remove duplicate image preprocessing in EPD and enable preprocess on GPU (#50390)

Signed-off-by: Tianyu Guo <guoty@inferact.ai>
This commit is contained in:
Tianyu Guo
2026-08-05 15:59:54 -07:00
committed by GitHub
parent 38ebd97bca
commit b30291cf0c
22 changed files with 904 additions and 45 deletions
+13 -1
View File
@@ -23,7 +23,7 @@ from typing_extensions import TypeVar
from vllm.utils.collection_utils import is_list_of
from vllm.utils.import_utils import LazyLoader
from vllm.utils.jsontree import json_map_leaves
from vllm.utils.jsontree import json_iter_leaves, json_map_leaves
from .media import MediaWithBytes
@@ -286,6 +286,13 @@ def nested_tensors_equal(
return a == b
def _nested_tensors_are_cpu(tensors: NestedTensors) -> bool:
"""Whether every tensor in `tensors` lives in host memory."""
return not any(
isinstance(x, torch.Tensor) and not x.is_cpu for x in json_iter_leaves(tensors)
)
def _nested_tensors_h2d(
tensors: NestedTensors,
device: torch.types.Device,
@@ -478,6 +485,11 @@ class BaseMultiModalField(ABC):
pin_memory = False
batch = [elem.data for elem in elems]
if pin_memory and not _nested_tensors_are_cpu(batch):
# Data already sits on an accelerator (e.g. a device-side HF
# processor handed it over by IPC). Pinning is a host-memory
# concept, and `pin_memory()` rejects device tensors outright.
pin_memory = False
out = self._reduce_data(batch, pin_memory=pin_memory)
return _nested_tensors_h2d(out, device=device)
+89 -6
View File
@@ -40,8 +40,18 @@ from .media import MediaWithBytes
_T = TypeVar("_T")
_I = TypeVar("_I")
EmbeddingFieldRole: TypeAlias = Literal["values", "metadata"]
"""What a field of a pre-computed-embedding input carries.
`"values"` is the embedding tensor itself; `"metadata"` is a key that sizes the
prompt's placeholder range. The distinction is what lets one declaration serve
both an ordinary request (everything present) and an EC consumer (embeddings
arrive through the connector, metadata still in the request).
"""
if TYPE_CHECKING:
import PIL.Image as PILImage
else:
PILImage = LazyLoader("PILImage", globals(), "PIL.Image")
@@ -250,34 +260,62 @@ class DictEmbeddingItems(
self,
data: Mapping[str, torch.Tensor],
modality: str,
required_fields: set[str],
required_fields: Set[str],
fields_factory: Callable[
[Mapping[str, torch.Tensor]],
Mapping[str, MultiModalFieldConfig],
],
optional_fields: Set[str] = frozenset(),
) -> None:
"""
Args:
data: The dictionary of tensors for this modality.
modality: The modality these items belong to.
required_fields: Fields `data` must contain.
fields_factory: Builds the field config from the data.
optional_fields: Fields `data` may omit. Which fields these are is
the caller's decision -- see
`MultiModalDataParser.embedding_field_sets`, where a deployment
that receives embeddings through an EC connector makes the
embeddings optional. They still need a field config, since they
are used whenever they *are* supplied.
"""
from transformers.feature_extraction_utils import BatchFeature
super().__init__(data, modality)
missing_required_data_keys = required_fields - data.keys()
# Nothing required would leave nothing to size the placeholder range
# from, so the item would parse into zero entries and silently produce a
# wrong prompt instead of failing here.
if not required_fields:
raise ValueError(
f"Cannot parse {modality!r} embeddings: every declared field is "
f"optional ({sorted(optional_fields)}), so nothing is left to "
"size the placeholder range."
)
declared_fields = set(required_fields) | set(optional_fields)
missing_required_data_keys = set(required_fields) - data.keys()
if missing_required_data_keys:
data_keys = set(data.keys())
msg = (
f"The data should contain the fields: {required_fields}, "
f"The data should contain the fields: {set(required_fields)}, "
f"but only found the following keys: {data_keys}"
)
raise ValueError(msg)
fields_config = fields_factory(data)
missing_required_fields = required_fields - fields_config.keys()
# Check every declared field, not just the required ones: an optional
# field still needs a config for when it is supplied.
missing_required_fields = declared_fields - fields_config.keys()
if missing_required_fields:
fields = set(fields_config.keys())
msg = f"{required_fields=} should be a subset of {fields=}"
msg = f"{declared_fields=} should be a subset of {fields=}"
raise ValueError(msg)
self.fields_config = fields_config
self.required_fields = required_fields
self.required_fields = set(required_fields)
self._kwargs = MultiModalKwargsItems.from_hf_inputs(
BatchFeature(dict(data)),
@@ -516,8 +554,50 @@ class MultiModalDataParser:
embedding inputs. If provided, validates that user-supplied
embeddings have the correct hidden size to prevent crashes
during model inference.
embeds_from_ec_connector (bool): Whether pre-computed embeddings may be
absent from the request because an encode/prefill/decode encoder
instance publishes them through an EC connector instead. Derived by
`BaseProcessingInfo.embeds_from_ec_connector`.
"""
embedding_fields: Mapping[str, Mapping[str, EmbeddingFieldRole]] = {}
"""Per-modality field roles for pre-computed-embedding inputs.
Declared here rather than inside `_parse_*_data` so an EC producer can read
it too: on a producer the request carries real media, so the branch that
builds `DictEmbeddingItems` never runs, yet the producer still has to know
which processed keys to publish. One declaration, both sides, no drift.
A modality absent from this mapping can only be sent whole in the request.
"""
@classmethod
def placeholder_metadata_fields(cls, modality: str) -> set[str]:
"""The keys that size `modality`'s placeholder range.
What an EC producer publishes alongside the embedding, and what a
consumer keeps requiring once the embedding itself is gone.
"""
return {
field
for field, role in cls.embedding_fields.get(modality, {}).items()
if role == "metadata"
}
def embedding_field_sets(self, modality: str) -> tuple[set[str], set[str]]:
"""`modality`'s (required, optional) fields for this deployment.
Resolves the static roles in `embedding_fields` against where the
embeddings actually come from: on an EC consumer they arrive through the
connector, so the request may omit them; anywhere else a request that
claims to carry pre-computed embeddings has to actually carry them.
"""
metadata = self.placeholder_metadata_fields(modality)
values = set(self.embedding_fields.get(modality, {})) - metadata
if self.embeds_from_ec_connector:
return metadata, values
return metadata | values, set()
def __init__(
self,
*,
@@ -526,9 +606,12 @@ class MultiModalDataParser:
audio_resample_method: Literal["pyav", "scipy", "soxr"] = "pyav",
video_needs_metadata: bool = False,
expected_hidden_size: int | None = None,
embeds_from_ec_connector: bool = False,
) -> None:
super().__init__()
self.embeds_from_ec_connector = embeds_from_ec_connector
self.audio_resampler = AudioResampler(
target_sr=target_sr,
method=audio_resample_method,
+35 -8
View File
@@ -1,7 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import time
from abc import abstractmethod
from collections.abc import Callable, Mapping
from contextlib import contextmanager
from dataclasses import dataclass, field
@@ -227,13 +226,30 @@ class InputProcessingContext:
self,
output: JSONTree,
) -> JSONTree:
def _postprocess_one(x: object):
if isinstance(x, torch.Tensor): # noqa: SIM102
# This mimics the behavior of transformers.BatchFeature
if x.is_floating_point():
x = x.to(dtype=self.model_config.dtype)
# "torch_shm" puts tensors on a torch.multiprocessing queue, which
# shares device tensors by CUDA IPC handle, so a device-side processor
# can hand `pixel_values` straight to the worker. Every other transport
# serializes host bytes, so the result has to be copied back first.
keep_on_device = (
self.model_config.get_multimodal_config().mm_tensor_ipc == "torch_shm"
)
return x
def _postprocess_one(x: object):
if not isinstance(x, torch.Tensor):
return x
# Bind to a Tensor-typed local: reassigning the `object`-typed
# parameter would discard the isinstance narrowing.
tensor = x
# This mimics the behavior of transformers.BatchFeature
if tensor.is_floating_point():
tensor = tensor.to(dtype=self.model_config.dtype)
if not tensor.is_cpu and not keep_on_device:
tensor = tensor.cpu()
return tensor
return json_map_leaves(_postprocess_one, output)
@@ -350,6 +366,17 @@ class BaseProcessingInfo:
return None
@property
def embeds_from_ec_connector(self) -> bool:
"""Whether pre-computed embeddings may arrive outside the request.
True only on an EC consumer, where an encode/prefill/decode encoder
instance publishes them through the connector instead, so the request
carries only the metadata that sizes the placeholder range.
"""
mm_config = self.ctx.model_config.multimodal_config
return mm_config is not None and mm_config.mm_embeds_from_ec_connector
def get_data_parser(self) -> MultiModalDataParser:
"""
Constructs a parser to preprocess multi-modal data items
@@ -362,6 +389,7 @@ class BaseProcessingInfo:
"""
return MultiModalDataParser(
expected_hidden_size=self._get_expected_hidden_size(),
embeds_from_ec_connector=self.embeds_from_ec_connector,
)
@cached_property
@@ -372,7 +400,6 @@ class BaseProcessingInfo:
def skip_prompt_length_check(self) -> bool:
return False
@abstractmethod
def get_supported_mm_limits(self) -> Mapping[str, int | None]:
"""
Return the maximum supported number of items for each modality.