[Feat] Phase 1 foundation types for multimodal output decoupling (#1816)
Signed-off-by: Megha Agarwal <agarwalmegha1308@gmail.com> Signed-off-by: Megha Agarwal <agarwalmegha@microsoft.com> Co-authored-by: Zhou Taichang <tzhouam@connect.ust.hk>
This commit is contained in:
1 parent
77d773ad47
commit
9eeac248f2
4 files changed
+346
No files matched your search
@@ -7,6 +7,7 @@ from vllm.engine.arg_utils import EngineArgs
|
||||
from vllm.logger import init_logger
|
||||
|
||||
from vllm_omni.config import OmniModelConfig
|
||||
from vllm_omni.engine.output_modality import OutputModality
|
||||
from vllm_omni.plugins import load_omni_general_plugins
|
||||
|
||||
logger = init_logger(__name__)
|
||||
@@ -143,3 +144,8 @@ class OmniEngineArgs(EngineArgs):
|
||||
task_type=self.task_type,
|
||||
)
|
||||
return omni_config
|
||||
|
||||
@property
|
||||
def output_modality(self) -> OutputModality:
|
||||
"""Parse engine_output_type into a type-safe OutputModality flag."""
|
||||
return OutputModality.from_string(self.engine_output_type)
|
||||
@@ -0,0 +1,90 @@
|
||||
"""Multimodal output data structures for vLLM-Omni.
|
||||
|
||||
This module defines structured types for multimodal outputs.
|
||||
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any
|
||||
|
||||
import torch
|
||||
from vllm.outputs import CompletionOutput
|
||||
|
||||
|
||||
@dataclass
|
||||
class MultimodalPayload:
|
||||
"""Structured multimodal output payload.
|
||||
|
||||
Attributes:
|
||||
tensors: Dictionary mapping modality/key names to their tensors.
|
||||
metadata: Optional dictionary for non-tensor metadata
|
||||
(e.g., sample rate for audio, image dimensions).
|
||||
"""
|
||||
|
||||
tensors: dict[str, torch.Tensor] = field(default_factory=dict)
|
||||
metadata: dict[str, Any] = field(default_factory=dict)
|
||||
|
||||
@property
|
||||
def primary_tensor(self) -> torch.Tensor | None:
|
||||
"""Return the first tensor in the payload, or None if empty."""
|
||||
if self.tensors:
|
||||
return next(iter(self.tensors.values()))
|
||||
return None
|
||||
|
||||
@property
|
||||
def is_empty(self) -> bool:
|
||||
"""Return True if the payload has no tensors."""
|
||||
return len(self.tensors) == 0
|
||||
|
||||
def get(self, key: str) -> torch.Tensor | None:
|
||||
"""Get a tensor by key, returning None if not found."""
|
||||
return self.tensors.get(key)
|
||||
|
||||
def __contains__(self, key: str) -> bool:
|
||||
return key in self.tensors
|
||||
|
||||
def __len__(self) -> int:
|
||||
return len(self.tensors)
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, data: dict[str, Any] | None) -> MultimodalPayload | None:
|
||||
"""Create a MultimodalPayload from a raw dictionary.
|
||||
|
||||
Separates torch.Tensor values into tensors and everything
|
||||
else into metadata.
|
||||
"""
|
||||
if not data:
|
||||
return None
|
||||
tensors: dict[str, torch.Tensor] = {}
|
||||
metadata: dict[str, Any] = {}
|
||||
for k, v in data.items():
|
||||
if isinstance(v, torch.Tensor):
|
||||
tensors[k] = v
|
||||
else:
|
||||
metadata[k] = v
|
||||
if not tensors and not metadata:
|
||||
return None
|
||||
return cls(tensors=tensors, metadata=metadata)
|
||||
|
||||
|
||||
@dataclass
|
||||
class MultimodalCompletionOutput(CompletionOutput):
|
||||
"""CompletionOutput with multimodal support.
|
||||
|
||||
Inherits all CompletionOutput fields and adds multimodal_output.
|
||||
As a CompletionOutput subclass, compatible with all existing vLLM consumers.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
multimodal_output: MultimodalPayload | None = None,
|
||||
**kwargs: Any,
|
||||
):
|
||||
super().__init__(**kwargs)
|
||||
self.multimodal_output = multimodal_output
|
||||
|
||||
def __repr__(self) -> str:
|
||||
base = super().__repr__()
|
||||
return f"{base[:-1]}, multimodal_output={self.multimodal_output!r})"
|
||||
@@ -0,0 +1,97 @@
|
||||
"""Output modality types for vLLM-Omni.
|
||||
|
||||
This module defines the OutputModality enum and TensorAccumulationStrategy
|
||||
for type-safe multimodal output routing and tensor merging.
|
||||
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from enum import Enum, Flag, auto
|
||||
|
||||
_MODALITY_ALIASES: dict[str, str] = {
|
||||
"speech": "audio",
|
||||
"images": "image",
|
||||
"latents": "latent",
|
||||
"wav": "audio",
|
||||
"waveform": "audio",
|
||||
"pixel_values": "image",
|
||||
"pixels": "image",
|
||||
}
|
||||
|
||||
|
||||
class OutputModality(Flag):
|
||||
"""Bit-flag enum for output modalities.
|
||||
|
||||
Compose freely with ``|`` — no need to enumerate every combination.
|
||||
|
||||
Single: ``OutputModality.TEXT``, ``OutputModality.IMAGE``, ...
|
||||
Compound: ``OutputModality.TEXT | OutputModality.IMAGE`` (text+image)
|
||||
|
||||
Note: POOLING is intentionally excluded. Pooling/embedding is vLLM's
|
||||
native path (pooling_output → PoolingRequestOutput), handled entirely
|
||||
by the base OutputProcessor. vLLM-Omni's layer does not participate.
|
||||
"""
|
||||
|
||||
TEXT = auto()
|
||||
IMAGE = auto()
|
||||
AUDIO = auto()
|
||||
LATENT = auto()
|
||||
|
||||
@classmethod
|
||||
def from_string(cls, s: str | None) -> OutputModality:
|
||||
"""Parse a free-text modality string into an OutputModality flag.
|
||||
|
||||
Handles common aliases and compound strings separated by + or ,.
|
||||
|
||||
Examples::
|
||||
|
||||
OutputModality.from_string("text+image")
|
||||
# → OutputModality.TEXT | OutputModality.IMAGE
|
||||
"""
|
||||
if not s or not s.strip():
|
||||
return cls.TEXT
|
||||
|
||||
parts = [p.strip().lower() for p in re.split(r"[+,]", s.strip())]
|
||||
result = cls(0)
|
||||
for p in parts:
|
||||
p = _MODALITY_ALIASES.get(p, p)
|
||||
try:
|
||||
result |= cls[p.upper()]
|
||||
except KeyError:
|
||||
raise ValueError(f"Unknown modality: {p!r}. Supported: {[m.name.lower() for m in cls]}")
|
||||
return result
|
||||
|
||||
@property
|
||||
def has_text(self) -> bool:
|
||||
return OutputModality.TEXT in self
|
||||
|
||||
@property
|
||||
def has_multimodal(self) -> bool:
|
||||
return bool(self & ~OutputModality.TEXT)
|
||||
|
||||
|
||||
class TensorAccumulationStrategy(Enum):
|
||||
"""Strategy for merging incremental multimodal tensors."""
|
||||
|
||||
CONCAT_DIM0 = "concat_dim0"
|
||||
"""Concatenate along dimension 0. Used for image/latent tensors."""
|
||||
|
||||
CONCAT_LAST = "concat_last"
|
||||
"""Concatenate along the last dimension. Used for audio waveforms."""
|
||||
|
||||
APPEND_LIST = "append_list"
|
||||
"""Append to a list (no tensor concatenation)."""
|
||||
|
||||
REPLACE = "replace"
|
||||
"""Replace previous tensor entirely with the latest one."""
|
||||
|
||||
|
||||
def get_accumulation_strategy(modality: OutputModality) -> TensorAccumulationStrategy:
|
||||
"""Determine tensor merge strategy from the multimodal flags."""
|
||||
if OutputModality.AUDIO in modality:
|
||||
return TensorAccumulationStrategy.CONCAT_LAST
|
||||
if OutputModality.IMAGE in modality or OutputModality.LATENT in modality:
|
||||
return TensorAccumulationStrategy.CONCAT_DIM0
|
||||
return TensorAccumulationStrategy.CONCAT_DIM0 # default
|
||||
Reference in new issue
Block a user