[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:
@@ -103,5 +103,15 @@ class ECTransferConfig:
|
||||
def is_ec_consumer(self) -> bool:
|
||||
return self.ec_connector is not None and self.ec_role in get_args(ECConsumer)
|
||||
|
||||
@property
|
||||
def is_encode_only(self) -> bool:
|
||||
"""Whether this instance encodes but does not run the language model.
|
||||
|
||||
It allocates no KV cache either -- `GPUModelRunner.get_kv_cache_spec`
|
||||
returns {} for it -- so it is the one role that can spend accelerator
|
||||
time and memory on frontend work.
|
||||
"""
|
||||
return self.is_ec_producer and not self.is_ec_consumer
|
||||
|
||||
def get_from_extra_config(self, key, default) -> Any:
|
||||
return self.ec_connector_extra_config.get(key, default)
|
||||
|
||||
@@ -18,6 +18,7 @@ from vllm.config.multimodal import (
|
||||
MMCacheType,
|
||||
MMEncoderTPMode,
|
||||
MMHasherAlgorithm,
|
||||
MMProcessorDevice,
|
||||
MMTensorIPC,
|
||||
MultiModalConfig,
|
||||
)
|
||||
@@ -395,6 +396,7 @@ class ModelConfig:
|
||||
video_pruning_method: InitVar[str | None] = None
|
||||
mm_tensor_ipc: InitVar[MMTensorIPC] = None
|
||||
mm_ipc_gpu_memory_gb: InitVar[float | None] = None
|
||||
mm_processor_device: InitVar[MMProcessorDevice | None] = None
|
||||
|
||||
def compute_hash(self) -> str:
|
||||
"""
|
||||
@@ -525,6 +527,7 @@ class ModelConfig:
|
||||
video_pruning_method: str | None,
|
||||
mm_tensor_ipc: MMTensorIPC,
|
||||
mm_ipc_gpu_memory_gb: float | None,
|
||||
mm_processor_device: MMProcessorDevice | None,
|
||||
) -> None:
|
||||
# Keep set served_model_name before maybe_model_redirect(self.model)
|
||||
self.served_model_name = get_served_model_name(
|
||||
@@ -763,6 +766,10 @@ class ModelConfig:
|
||||
)
|
||||
mm_encoder_tp_mode = "weights"
|
||||
|
||||
mm_processor_kwargs = MultiModalConfig.fold_mm_processor_device(
|
||||
mm_processor_kwargs, mm_processor_device
|
||||
)
|
||||
|
||||
mm_config_kwargs = dict(
|
||||
language_model_only=language_model_only,
|
||||
limit_per_prompt=limit_mm_per_prompt,
|
||||
|
||||
@@ -5,14 +5,19 @@ from collections.abc import Mapping
|
||||
from pathlib import Path
|
||||
from typing import Any, Literal, TypeAlias, TypedDict, cast, final
|
||||
|
||||
import torch
|
||||
from pydantic import ConfigDict, Field, field_validator, model_validator
|
||||
from pydantic.dataclasses import dataclass
|
||||
|
||||
import vllm.envs as envs
|
||||
from vllm.config.ec_transfer import ECTransferConfig
|
||||
from vllm.config.utils import config, get_from_deprecated_env_if_set
|
||||
from vllm.logger import init_logger
|
||||
from vllm.utils.hashing import safe_hash
|
||||
from vllm.v1.attention.backends.registry import AttentionBackendEnum
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
@dataclass
|
||||
class BaseDummyOptions:
|
||||
@@ -64,6 +69,10 @@ MMCacheType = Literal["shm", "lru"]
|
||||
VideoPruningMethod = Literal["evs", "vidcom2"]
|
||||
MMTensorIPC = Literal["direct_rpc", "torch_shm"]
|
||||
MMHasherAlgorithm = Literal["blake3", "sha256", "sha512"]
|
||||
MMProcessorDevice: TypeAlias = str
|
||||
"""`"auto"`, `"cpu"`, or the platform's own accelerator name
|
||||
(`current_platform.device_type`, e.g. `"cuda"` on CUDA and ROCm,
|
||||
`"xpu"` on XPU). Validated against that set by the CLI."""
|
||||
|
||||
|
||||
def _get_mm_hasher_algorithm() -> MMHasherAlgorithm:
|
||||
@@ -222,6 +231,20 @@ class MultiModalConfig:
|
||||
- "direct_rpc": Use msgspec serialization via RPC
|
||||
- "torch_shm": Use torch.multiprocessing shared memory for zero-copy IPC
|
||||
Defaults to "direct_rpc". """
|
||||
mm_embeds_from_ec_connector: bool = False
|
||||
"""Whether a pre-computed-embedding input may omit the `*_embeds` tensor.
|
||||
|
||||
In an encode/prefill/decode (EPD) deployment the encoder instance publishes
|
||||
embeddings through the EC connector, so the request that reaches the
|
||||
prefill/decode instance only needs to carry the grid/size metadata that
|
||||
sizes the placeholder range — the embeddings themselves come from the
|
||||
connector, keyed by `mm_hash`.
|
||||
|
||||
Derived, not user-settable: `VllmConfig.__post_init__` sets this to True
|
||||
exactly on EC consumers. Everywhere else it stays False so that a request
|
||||
which forgets its embeddings still fails fast in the frontend, with a clear
|
||||
error, rather than deep inside the model."""
|
||||
|
||||
mm_ipc_gpu_memory_gb: float = Field(default=0, ge=0)
|
||||
"""Amount of GPU memory (in GiB) sequestered on the engine's device for
|
||||
GPU-side multimodal work in the API-server (frontend) process, such as
|
||||
@@ -319,6 +342,119 @@ class MultiModalConfig:
|
||||
)
|
||||
return self
|
||||
|
||||
@staticmethod
|
||||
def fold_mm_processor_device(
|
||||
mm_processor_kwargs: dict[str, Any] | None,
|
||||
mm_processor_device: MMProcessorDevice | None,
|
||||
) -> dict[str, Any] | None:
|
||||
"""Fold the `mm_processor_device` convenience flag into the kwargs.
|
||||
|
||||
The flag keeps no state of its own: `mm_processor_kwargs["device"]` is
|
||||
the only representation of where the processor runs, so an explicit
|
||||
`device` there always wins and `"auto"` stays unresolved for
|
||||
`VllmConfig`, which is where the EC role needed to resolve it lives.
|
||||
|
||||
Args:
|
||||
mm_processor_kwargs: The kwargs as given, or None.
|
||||
mm_processor_device: The flag's value, or None when unset.
|
||||
|
||||
Returns:
|
||||
The kwargs to build the config with, unchanged unless the flag adds
|
||||
a `device`.
|
||||
"""
|
||||
if mm_processor_device in (None, "auto"):
|
||||
return mm_processor_kwargs
|
||||
if (mm_processor_kwargs or {}).get("device") is not None:
|
||||
return mm_processor_kwargs
|
||||
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
# Any explicit value other than "cpu" means "the accelerator", so a
|
||||
# programmatically-set "cuda" still works on a platform whose device type
|
||||
# is named differently ("xpu"), and degrades to CPU where there is none.
|
||||
device = (
|
||||
"cpu"
|
||||
if mm_processor_device == "cpu"
|
||||
else (current_platform.device_type or "cpu")
|
||||
)
|
||||
return {**(mm_processor_kwargs or {}), "device": device}
|
||||
|
||||
def get_mm_processor_device_type(self) -> str | None:
|
||||
"""The torch device type `mm_processor_kwargs["device"]` names.
|
||||
|
||||
`mm_processor_kwargs` is untyped, so `device` may be any form torch
|
||||
accepts -- `"cuda"`, `"cuda:1"`, `torch.device(...)`, or a bare index.
|
||||
Normalising through torch rather than parsing the string keeps the
|
||||
non-string forms from slipping past a caller's comparison.
|
||||
|
||||
Returns:
|
||||
The device type, or None when no device is requested.
|
||||
|
||||
Raises:
|
||||
ValueError: If `device` is not something `torch.device` accepts.
|
||||
`validate_mm_processor_device` is what surfaces this during
|
||||
startup, so the value is only parsed once.
|
||||
"""
|
||||
device = (self.mm_processor_kwargs or {}).get("device")
|
||||
if device is None:
|
||||
return None
|
||||
try:
|
||||
return torch.device(device).type # type: ignore[arg-type]
|
||||
except (RuntimeError, TypeError, ValueError):
|
||||
raise ValueError(
|
||||
f'Invalid "device" in mm_processor_kwargs: {device!r}. Expected a '
|
||||
'torch device such as "cpu", "cuda" or "cuda:0".'
|
||||
) from None
|
||||
|
||||
def validate_mm_processor_device(self, ec_config: ECTransferConfig | None) -> None:
|
||||
"""Check `mm_processor_kwargs["device"]` for this deployment.
|
||||
|
||||
The only place the requested device is validated, so it runs even on a
|
||||
CPU-only platform: the value is parsed before any early return.
|
||||
|
||||
Args:
|
||||
ec_config: The deployment's EC config, or None when it is not an
|
||||
encode/prefill/decode deployment. Passed in because it is not
|
||||
reachable from here, and because a field assigned after
|
||||
construction would not re-trigger this config's validators.
|
||||
|
||||
Raises:
|
||||
ValueError: If the requested device is not a torch device, or if it
|
||||
is the accelerator on an instance that also runs the language
|
||||
model.
|
||||
"""
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
device_type = self.get_mm_processor_device_type()
|
||||
accelerator = current_platform.device_type
|
||||
if device_type is None or accelerator in ("", "cpu"):
|
||||
return
|
||||
if device_type != accelerator:
|
||||
return
|
||||
|
||||
if ec_config is None or not ec_config.is_encode_only:
|
||||
raise ValueError(
|
||||
f"Cannot run the multi-modal processor on {device_type!r}: this "
|
||||
"instance also runs the language model. The processor would "
|
||||
"share the device with the model's forward pass, so its "
|
||||
"transform kernels contend with that compute, and because it "
|
||||
"runs in the API-server process its allocations are outside the "
|
||||
"memory the engine profiled for its KV cache -- risking OOM or "
|
||||
"a silently shrunken cache.\n"
|
||||
"Accelerator preprocessing is only supported on an encode-only "
|
||||
"instance of an encode/prefill/decode deployment (an EC "
|
||||
"producer that is not also a consumer), which runs no forward "
|
||||
"pass and allocates no KV cache.\n"
|
||||
'Use --mm-processor-device=cpu, or drop "device" from '
|
||||
"--mm-processor-kwargs."
|
||||
)
|
||||
|
||||
logger.info_once(
|
||||
"Running the multi-modal processor on %s. Override with "
|
||||
"--mm-processor-device=cpu.",
|
||||
device_type,
|
||||
)
|
||||
|
||||
def compute_hash(self) -> str:
|
||||
"""
|
||||
WARNING: Whenever a new field is added to this config,
|
||||
|
||||
@@ -1509,6 +1509,10 @@ class VllmConfig:
|
||||
)
|
||||
current_platform.check_and_update_config(self)
|
||||
|
||||
self._resolve_mm_embeds_from_ec_connector()
|
||||
self._resolve_mm_processor_device()
|
||||
self._validate_mm_processor_device()
|
||||
|
||||
if self.use_v2_model_runner:
|
||||
self._validate_v2_model_runner()
|
||||
elif self.parallel_config.prefill_context_parallel_size > 1:
|
||||
@@ -2185,6 +2189,101 @@ class VllmConfig:
|
||||
f"kernel_config={self.kernel_config!r}"
|
||||
)
|
||||
|
||||
def _resolve_mm_embeds_from_ec_connector(self) -> None:
|
||||
"""Allow `*_embeds` to be omitted only where the connector supplies them.
|
||||
|
||||
That is exactly an EC consumer: the encoder instance publishes the
|
||||
embeddings through the EC connector, so the request only has to carry
|
||||
the grid metadata that sizes the placeholder range. On every other
|
||||
deployment a missing `*_embeds` is a client error and must keep failing
|
||||
fast in the frontend.
|
||||
"""
|
||||
model_config = self.model_config
|
||||
if model_config is None:
|
||||
return
|
||||
mm_config = model_config.multimodal_config
|
||||
if mm_config is None:
|
||||
return
|
||||
|
||||
ec_config = self.ec_transfer_config
|
||||
# Derived, so overwrite unconditionally rather than honouring a value
|
||||
# that was set by hand.
|
||||
mm_config.mm_embeds_from_ec_connector = (
|
||||
ec_config is not None and ec_config.is_ec_consumer
|
||||
)
|
||||
if mm_config.mm_embeds_from_ec_connector:
|
||||
logger.info_once(
|
||||
"EC consumer: pre-computed-embedding inputs may omit the "
|
||||
"embedding tensor; embeddings are loaded from the EC connector."
|
||||
)
|
||||
|
||||
def _resolve_mm_processor_device(self) -> None:
|
||||
"""Settle `--mm-processor-device=auto` now that the EC role is known.
|
||||
|
||||
"auto" means "the accelerator, but only where the processor has it to
|
||||
itself and its output can be handed over without a copy back to host":
|
||||
an encode-only instance whose tensor transport carries device tensors.
|
||||
Every other deployment keeps the processor on CPU.
|
||||
|
||||
An explicit device -- from `--mm-processor-device` or straight from
|
||||
`mm_processor_kwargs` -- is already folded in by `MultiModalConfig`, so
|
||||
it is left alone here and validated by `_validate_mm_processor_device`.
|
||||
"""
|
||||
model_config = self.model_config
|
||||
if model_config is None:
|
||||
return
|
||||
mm_config = model_config.multimodal_config
|
||||
if mm_config is None:
|
||||
return
|
||||
if mm_config.get_mm_processor_device_type() is not None:
|
||||
return
|
||||
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
device_type = current_platform.device_type
|
||||
if device_type in ("", "cpu"):
|
||||
return
|
||||
|
||||
ec_config = self.ec_transfer_config
|
||||
# An EC producer that is not also a consumer runs no forward pass and
|
||||
# allocates no KV cache, so frontend accelerator work has the device to
|
||||
# itself.
|
||||
if ec_config is None or not ec_config.is_encode_only:
|
||||
return
|
||||
|
||||
if mm_config.mm_tensor_ipc != "torch_shm":
|
||||
# Any other transport serializes host bytes, so the output would be
|
||||
# copied back, and that copy costs more than running the transform
|
||||
# on device saves.
|
||||
logger.info_once(
|
||||
"EPD encoder instance: keeping the multi-modal processor on CPU "
|
||||
"because mm_tensor_ipc=%s cannot carry device tensors. Add "
|
||||
"--mm-tensor-ipc=torch_shm to run it on the accelerator.",
|
||||
mm_config.mm_tensor_ipc,
|
||||
)
|
||||
return
|
||||
|
||||
mm_config.mm_processor_kwargs = {
|
||||
**(mm_config.mm_processor_kwargs or {}),
|
||||
"device": device_type,
|
||||
}
|
||||
logger.info_once(
|
||||
"EPD encoder instance: running the multi-modal processor on %s. "
|
||||
"Override with --mm-processor-device=cpu.",
|
||||
device_type,
|
||||
)
|
||||
|
||||
def _validate_mm_processor_device(self) -> None:
|
||||
"""Hand the EC config to `MultiModalConfig`, which owns the rule."""
|
||||
model_config = self.model_config
|
||||
if model_config is None:
|
||||
return
|
||||
mm_config = model_config.multimodal_config
|
||||
if mm_config is None:
|
||||
return
|
||||
|
||||
mm_config.validate_mm_processor_device(self.ec_transfer_config)
|
||||
|
||||
def _get_v2_model_runner_unsupported_features(self) -> list[str]:
|
||||
"""Collect features not yet supported by the V2 model runner."""
|
||||
unsupported: list[str] = []
|
||||
|
||||
Reference in New Issue
Block a user