[Multimodal] Simplify MM input definitions (#33331)
Signed-off-by: DarkLight1337 <tlleungac@connect.ust.hk>
This commit is contained in:
+65
-72
@@ -23,7 +23,7 @@ import numpy as np
|
||||
from PIL.Image import Image
|
||||
from typing_extensions import NotRequired, TypeVar
|
||||
|
||||
from vllm.utils.collection_utils import full_groupby, is_list_of
|
||||
from vllm.utils.collection_utils import is_list_of
|
||||
from vllm.utils.import_utils import LazyLoader
|
||||
from vllm.utils.jsontree import json_map_leaves
|
||||
|
||||
@@ -336,25 +336,33 @@ class MultiModalFeatureSpec:
|
||||
"""
|
||||
Represents a single multimodal input with its processed data and metadata.
|
||||
|
||||
Used by the V1 engine to track multimodal data through processing and
|
||||
caching. A request containing multiple multimodal items will have one
|
||||
MultiModalFeatureSpec per item.
|
||||
Used to track multimodal data through processing and caching.
|
||||
A request containing multiple multimodal items will have one
|
||||
`MultiModalFeatureSpec` per item.
|
||||
"""
|
||||
|
||||
data: Optional["MultiModalKwargsItem"]
|
||||
"""Multimodal data for this feature"""
|
||||
"""
|
||||
Represents multimodal data for this feature.
|
||||
|
||||
Can be `None` if the item is cached, to skip IPC between API server
|
||||
and engine core processes.
|
||||
"""
|
||||
|
||||
modality: str
|
||||
"""Based on the input, e.g., "image", "audio", "video"."""
|
||||
"""The input modality, e.g., `"image"`, `"audio"`, `"video"`."""
|
||||
|
||||
identifier: str
|
||||
"""mm_hash or uuid for caching encoder outputs."""
|
||||
"""The hash for caching encoder outputs (with LoRA prefix if applicable)."""
|
||||
|
||||
mm_position: PlaceholderRange
|
||||
"""e.g., PlaceholderRange(offset=2, length=336)"""
|
||||
"""
|
||||
The location of the `modality` tokens corresponding to this item
|
||||
in the prompt, e.g., `PlaceholderRange(offset=2, length=336)`.
|
||||
"""
|
||||
|
||||
mm_hash: str | None = None
|
||||
"""Base mm_hash for processor cache (without LoRA prefix)."""
|
||||
"""The hash for caching processor outputs (without LoRA prefix)."""
|
||||
|
||||
@staticmethod
|
||||
def gather_kwargs(features: list["MultiModalFeatureSpec"], keys: set[str]):
|
||||
@@ -373,23 +381,10 @@ class MultiModalFeatureSpec:
|
||||
@dataclass
|
||||
class MultiModalFieldElem:
|
||||
"""
|
||||
Represents a keyword argument inside a
|
||||
Represents a processed keyword argument to pass to a model for a
|
||||
[`MultiModalKwargsItem`][vllm.multimodal.inputs.MultiModalKwargsItem].
|
||||
"""
|
||||
|
||||
modality: str
|
||||
"""
|
||||
The modality of the corresponding multi-modal item.
|
||||
Each multi-modal item can consist of multiple keyword arguments.
|
||||
"""
|
||||
|
||||
key: str
|
||||
"""
|
||||
The key of this field in
|
||||
[`MultiModalKwargsItem`][vllm.multimodal.inputs.MultiModalKwargsItem],
|
||||
i.e. the name of the keyword argument to be passed to the model.
|
||||
"""
|
||||
|
||||
data: NestedTensors
|
||||
"""
|
||||
The tensor data of this field in
|
||||
@@ -417,11 +412,7 @@ class MultiModalFieldElem:
|
||||
else:
|
||||
data_equal = nested_tensors_equal(self.data, other.data)
|
||||
|
||||
return (
|
||||
(self.modality, self.key) == (other.modality, other.key)
|
||||
and data_equal
|
||||
and type(self.field) is type(other.field)
|
||||
) # noqa: E721
|
||||
return data_equal and type(self.field) is type(other.field) # noqa: E721
|
||||
|
||||
|
||||
@dataclass(frozen=True, kw_only=True)
|
||||
@@ -438,13 +429,8 @@ class BaseMultiModalField(ABC):
|
||||
when `MultiModalKwargsItems.get_data()` is called to batch the data.
|
||||
"""
|
||||
|
||||
def _field_factory(self, *, modality: str, key: str):
|
||||
f = partial(
|
||||
MultiModalFieldElem,
|
||||
modality=modality,
|
||||
key=key,
|
||||
field=self,
|
||||
)
|
||||
def _field_factory(self):
|
||||
f = partial(MultiModalFieldElem, field=self)
|
||||
|
||||
# Allow passing data as positional argument
|
||||
def factory(data: NestedTensors) -> MultiModalFieldElem:
|
||||
@@ -519,7 +505,7 @@ class MultiModalBatchedField(BaseMultiModalField):
|
||||
key: str,
|
||||
data: NestedTensors,
|
||||
) -> Sequence[MultiModalFieldElem]:
|
||||
field_factory = self._field_factory(modality=modality, key=key)
|
||||
field_factory = self._field_factory()
|
||||
return [field_factory(item) for item in data]
|
||||
|
||||
def _reduce_data(
|
||||
@@ -565,7 +551,7 @@ class MultiModalFlatField(BaseMultiModalField):
|
||||
key: str,
|
||||
data: NestedTensors,
|
||||
) -> Sequence[MultiModalFieldElem]:
|
||||
field_factory = self._field_factory(modality=modality, key=key)
|
||||
field_factory = self._field_factory()
|
||||
if not is_list_of(self.slices, slice, check="all"):
|
||||
assert isinstance(data, torch.Tensor), (
|
||||
"torch.Tensor is required for multiple slices"
|
||||
@@ -664,7 +650,7 @@ class MultiModalSharedField(BaseMultiModalField):
|
||||
key: str,
|
||||
data: NestedTensors,
|
||||
) -> Sequence[MultiModalFieldElem]:
|
||||
field_factory = self._field_factory(modality=modality, key=key)
|
||||
field_factory = self._field_factory()
|
||||
return [field_factory(data)] * self.batch_size
|
||||
|
||||
def _reduce_data(
|
||||
@@ -899,37 +885,19 @@ class MultiModalFieldConfig:
|
||||
|
||||
class MultiModalKwargsItem(UserDict[str, MultiModalFieldElem]):
|
||||
"""
|
||||
A collection of
|
||||
[`MultiModalFieldElem`][vllm.multimodal.inputs.MultiModalFieldElem]
|
||||
corresponding to a data item in
|
||||
A dictionary of processed keyword arguments to pass to the model,
|
||||
corresponding to a single item in
|
||||
[`MultiModalDataItems`][vllm.multimodal.parse.MultiModalDataItems].
|
||||
"""
|
||||
|
||||
@staticmethod
|
||||
def dummy(modality: str, nbytes: int = 1):
|
||||
def dummy(nbytes: int = 1):
|
||||
"""Convenience class for testing."""
|
||||
mm_elem = MultiModalFieldElem(
|
||||
modality=modality,
|
||||
key="dummy",
|
||||
data=torch.empty(nbytes, dtype=torch.uint8),
|
||||
field=MultiModalSharedField(batch_size=1),
|
||||
)
|
||||
return MultiModalKwargsItem.from_elems([mm_elem])
|
||||
|
||||
@staticmethod
|
||||
def from_elems(elems: Sequence[MultiModalFieldElem]):
|
||||
return MultiModalKwargsItem({elem.key: elem for elem in elems})
|
||||
|
||||
def __init__(self, data: Mapping[str, MultiModalFieldElem] = {}) -> None:
|
||||
super().__init__(data)
|
||||
|
||||
modalities = {elem.modality for elem in self.values()}
|
||||
assert len(modalities) == 1, f"Found different modalities={modalities}"
|
||||
self._modality = next(iter(modalities))
|
||||
|
||||
@property
|
||||
def modality(self) -> str:
|
||||
return self._modality
|
||||
return MultiModalKwargsItem({"dummy": mm_elem})
|
||||
|
||||
def get_data(self) -> dict[str, NestedTensors]:
|
||||
return {key: elem.data for key, elem in self.items()}
|
||||
@@ -945,9 +913,38 @@ _I = TypeVar(
|
||||
|
||||
class MultiModalKwargsItems(UserDict[str, Sequence[_I]]):
|
||||
"""
|
||||
A dictionary of
|
||||
[`MultiModalKwargsItem`][vllm.multimodal.inputs.MultiModalKwargsItem]s
|
||||
by modality.
|
||||
A dictionary of processed multi-modal inputs by modality.
|
||||
|
||||
For example, given a processor that processes
|
||||
images into `pixel_values` and `image_grid_thw`,
|
||||
and audios into `input_audio_features`,
|
||||
a prompt with 2 images and 1 audio will be processed
|
||||
into a `MultiModalKwargsItems` with the following structure:
|
||||
|
||||
```python
|
||||
MultiModalKwargsItems(
|
||||
{
|
||||
"image": [
|
||||
# For the first image
|
||||
MultiModalKwargsItem({"pixel_values": ..., "image_grid_thw": ...}),
|
||||
# For the second imgae
|
||||
MultiModalKwargsItem({"pixel_values": ..., "image_grid_thw": ...}),
|
||||
],
|
||||
"audio": [
|
||||
# For the first audio
|
||||
MultiModalKwargsItem({"input_audio_features": ...}),
|
||||
],
|
||||
}
|
||||
)
|
||||
```
|
||||
|
||||
Unlike HF processing which returns all items
|
||||
in a single dictionary with batched keyword arguments,
|
||||
we split up the items because some of them may already be cached.
|
||||
Also, items from multiple requests may be batched together to improve throughput,
|
||||
using the logic defined by the
|
||||
[`BaseMultiModalField`][vllm.multimodal.inputs.BaseMultiModalField]
|
||||
for each keyword argument.
|
||||
"""
|
||||
|
||||
@staticmethod
|
||||
@@ -967,7 +964,7 @@ class MultiModalKwargsItems(UserDict[str, Sequence[_I]]):
|
||||
elems_by_key[key] = elems
|
||||
keys_by_modality[config.modality].add(key)
|
||||
|
||||
items = list[MultiModalKwargsItem]()
|
||||
items_by_modality = dict[str, list[MultiModalKwargsItem]]()
|
||||
for modality, keys in keys_by_modality.items():
|
||||
elems_in_modality = {k: elems_by_key[k] for k in keys}
|
||||
batch_sizes = {k: len(v) for k, v in elems_in_modality.items()}
|
||||
@@ -979,15 +976,11 @@ class MultiModalKwargsItems(UserDict[str, Sequence[_I]]):
|
||||
)
|
||||
|
||||
batch_size = next(iter(batch_sizes.values()))
|
||||
for item_idx in range(batch_size):
|
||||
elems = [v[item_idx] for v in elems_in_modality.values()]
|
||||
items.append(MultiModalKwargsItem.from_elems(elems))
|
||||
items_by_modality[modality] = [
|
||||
MultiModalKwargsItem({k: v[i] for k, v in elems_in_modality.items()})
|
||||
for i in range(batch_size)
|
||||
]
|
||||
|
||||
return MultiModalKwargsItems.from_seq(items)
|
||||
|
||||
@staticmethod
|
||||
def from_seq(items: Sequence[MultiModalKwargsItem]):
|
||||
items_by_modality = full_groupby(items, key=lambda x: x.modality)
|
||||
return MultiModalKwargsItems(items_by_modality)
|
||||
|
||||
def __getitem__(self, modality: str) -> Sequence[_I]:
|
||||
|
||||
Reference in New Issue
Block a user