Skip to content

vllm.multimodal.inputs

Classes:

Functions:

Attributes:

AudioItem = Union[HfAudioItem, tuple[np.ndarray, float], 'torch.Tensor'] module-attribute

Represents a single audio item, which can be passed to a HuggingFace AudioProcessor.

Alternatively, a tuple (audio, sampling_rate), where the sampling rate is different from that expected by the model; these are resampled to the model's sampling rate before being processed by HF.

Alternatively, a 3-D tensor or batch of 2-D tensors, which are treated as audio embeddings; these are directly passed to the model without HF processing.

BatchedTensorInputs = dict[str, NestedTensors] module-attribute

A dictionary containing nested tensors which have been batched via MultiModalKwargsItems.get_data.

HfAudioItem = Union[list[float], np.ndarray, 'torch.Tensor'] module-attribute

Represents a single audio item, which can be passed to a HuggingFace AudioProcessor.

HfImageItem = Union['Image', np.ndarray, 'torch.Tensor'] module-attribute

A transformers.image_utils.ImageInput representing a single image item, which can be passed to a HuggingFace ImageProcessor.

HfVideoItem = Union[list['Image'], np.ndarray, 'torch.Tensor', list[np.ndarray], list['torch.Tensor']] module-attribute

A transformers.image_utils.VideoInput representing a single video item, which can be passed to a HuggingFace VideoProcessor.

ImageItem = Union[HfImageItem, 'torch.Tensor', MediaWithBytes[HfImageItem]] module-attribute

A transformers.image_utils.ImageInput representing a single image item, which can be passed to a HuggingFace ImageProcessor.

Alternatively, a 3-D tensor or batch of 2-D tensors, which are treated as image embeddings; these are directly passed to the model without HF processing.

NestedTensors = Union[list['NestedTensors'], list['torch.Tensor'], 'torch.Tensor', tuple['torch.Tensor', ...]] module-attribute

Uses a list instead of a tensor if the dimensions of each element do not match.

VideoItem = Union[HfVideoItem, 'torch.Tensor', tuple[HfVideoItem, dict[str, Any]], MediaWithBytes[tuple[HfVideoItem, dict[str, Any]]]] module-attribute

A transformers.video_utils.VideoInput representing a single video item. This can be passed to a HuggingFace VideoProcessor with transformers.video_utils.VideoMetadata.

Alternatively, a 3-D tensor or batch of 2-D tensors, which are treated as video embeddings; these are directly passed to the model without HF processing.

VisionChunk = VisionChunkImage | VisionChunkVideo module-attribute

A vision chunk is either an image or a video chunk.

BaseMultiModalField dataclass

Bases: ABC

Defines how to interpret tensor data belonging to a keyword argument for MultiModalKwargsItems, and vice versa.

Methods:

Attributes:

  • keep_on_cpu (bool) –

    If True, then this field is excluded from being moved to the accelerator when

keep_on_cpu = False class-attribute instance-attribute

If True, then this field is excluded from being moved to the accelerator when group_and_batch_mm_items is called to batch the data.

build_elems(modality, key, data) abstractmethod

Construct MultiModalFieldElem instances to represent the provided data.

This is the inverse of reduce_data.

reduce_data(elems, *, device=None, pin_memory=False)

Merge the data from multiple instances of MultiModalFieldElem.

This is the inverse of build_elems.

MultiModalBatchedField dataclass

MultiModalFeatureSpec dataclass

Represents a single multimodal input with its processed data and metadata.

Used to track multimodal data through processing and caching. A request containing multiple multimodal items will have one MultiModalFeatureSpec per item.

Attributes:

  • data (MultiModalKwargsItem | None) –

    Represents multimodal data for this feature.

  • identifier (str) –

    The hash for caching encoder outputs (with LoRA prefix if applicable).

  • is_metadata_only (bool) –

    Whether data only supplies the layout, not inputs for the encoder.

  • mm_hash (str | None) –

    The hash for caching processor outputs (without LoRA prefix).

  • mm_position (PlaceholderRange) –

    The location of the modality tokens corresponding to this item

  • modality (str) –

    The input modality, e.g., "image", "audio", "video".

  • skip_mm_cache (bool) –

    If true, skip the multimodal processor cache for this item/feature so

data instance-attribute

Represents multimodal data for this feature.

Can be None if the item is cached, to skip IPC between API server and engine core processes.

identifier instance-attribute

The hash for caching encoder outputs (with LoRA prefix if applicable).

is_metadata_only = False class-attribute instance-attribute

Whether data only supplies the layout, not inputs for the encoder.

mm_hash = None class-attribute instance-attribute

The hash for caching processor outputs (without LoRA prefix).

mm_position instance-attribute

The location of the modality tokens corresponding to this item in the prompt, e.g., PlaceholderRange(offset=2, length=336).

modality instance-attribute

The input modality, e.g., "image", "audio", "video".

skip_mm_cache = False class-attribute instance-attribute

If true, skip the multimodal processor cache for this item/feature so pre-rendered or unrecorded features do not insert into or evict entries from the receiver cache.

MultiModalFieldConfig dataclass

Methods:

  • batched –

    Defines a field where an element in the batch is obtained by

  • flat –

    Defines a field where an element in the batch is obtained by

  • flat_from_sizes –

    Defines a field where an element in the batch is obtained by

  • shared –

    Defines a field where an element in the batch is obtained by

batched(modality, *, keep_on_cpu=False) staticmethod

Defines a field where an element in the batch is obtained by indexing into the first dimension of the underlying data.

Parameters:

  • modality

    (str) –

    The modality of the multi-modal item that uses this keyword argument.

  • keep_on_cpu

    (bool, default: False ) –

    Whether to keep this field on the CPU for the model inputs.

Example:

Input:
    Data: [[AAAA]
        [BBBB]
        [CCCC]]

Output:
    Element 1: [AAAA]
    Element 2: [BBBB]
    Element 3: [CCCC]

flat(modality, slices, dim=0, *, keep_on_cpu=False) staticmethod

Defines a field where an element in the batch is obtained by slicing along the first dimension of the underlying data.

Parameters:

  • modality

    (str) –

    The modality of the multi-modal item that uses this keyword argument.

  • slices

    (Sequence[slice] | Sequence[Sequence[slice]]) –

    For each multi-modal item, a slice (dim=0) or a tuple of slices (dim>0) that is used to extract the data corresponding to it.

  • dim

    (int, default: 0 ) –

    The dimension to extract data, default to 0.

  • keep_on_cpu

    (bool, default: False ) –

    Whether to keep this field on the CPU for the model inputs.

Example:

Given:
    slices: [slice(0, 3), slice(3, 7), slice(7, 9)]

Input:
    Data: [AAABBBBCC]

Output:
    Element 1: [AAA]
    Element 2: [BBBB]
    Element 3: [CC]

Given:
    slices: [
        (slice(None), slice(0, 3)),
        (slice(None), slice(3, 7)),
        (slice(None), slice(7, 9))]
    dim: 1

Input:
    Data: [[A],[A],[A],[B],[B],[B],[B],[C],[C]]

Output:
    Element 1: [[A],[A],[A]]
    Element 2: [[B],[B],[B],[B]]
    Element 3: [[C],[C]]

flat_from_sizes(modality, size_per_item, dim=0, *, keep_on_cpu=False) staticmethod

Defines a field where an element in the batch is obtained by slicing along the first dimension of the underlying data.

Parameters:

  • modality

    (str) –

    The modality of the multi-modal item that uses this keyword argument.

  • size_per_item

    (Tensor) –

    For each multi-modal item, the size of the slice that is used to extract the data corresponding to it.

  • dim

    (int, default: 0 ) –

    The dimension to slice, default to 0.

  • keep_on_cpu

    (bool, default: False ) –

    Whether to keep this field on the CPU for the model inputs.

Example:

Given:
    size_per_item: [3, 4, 2]

Input:
    Data: [AAABBBBCC]

Output:
    Element 1: [AAA]
    Element 2: [BBBB]
    Element 3: [CC]

Given:
    size_per_item: [3, 4, 2]
    dim: 1

Input:
    Data: [[A],[A],[A],[B],[B],[B],[B],[C],[C]]

Output:
    Element 1: [[A],[A],[A]]
    Element 2: [[B],[B],[B],[B]]
    Element 3: [[C],[C]]
Info

MultiModalFieldConfig.flat

shared(modality, batch_size, *, keep_on_cpu=False) staticmethod

Defines a field where an element in the batch is obtained by taking the entirety of the underlying data.

This means that the data is the same for each element in the batch.

Parameters:

  • modality

    (str) –

    The modality of the multi-modal item that uses this keyword argument.

  • batch_size

    (int) –

    The number of multi-modal items which share this data.

  • keep_on_cpu

    (bool, default: False ) –

    Whether to keep this field on the CPU for the model inputs.

Example:

Given:
    batch_size: 4

Input:
    Data: [XYZ]

Output:
    Element 1: [XYZ]
    Element 2: [XYZ]
    Element 3: [XYZ]
    Element 4: [XYZ]

MultiModalFieldElem dataclass

Represents a processed keyword argument to pass to a model for a MultiModalKwargsItem.

Attributes:

data instance-attribute

The tensor data of this field in MultiModalKwargsItem, i.e. the value of the keyword argument to be passed to the model.

It may be set to None if it is determined that the item is cached in EngineCore.

field instance-attribute

Defines how to combine the tensor data of this field with others in order to batch multi-modal items together for model inference.

skip_mm_cache = False class-attribute instance-attribute

If True, this field carries its full tensor data for inference but must not be inserted into, or update, the receiver-side multimodal LRU cache.

The combination of data and this flag encodes three states:

  • data is a full tensor, skip_mm_cache=False: a normal item that participates in both the sender and receiver LRU (insertion and update).
  • data=None, skip_mm_cache=False: the sender has already cached this item; the receiver resolves the data by hash from its cache.
  • data is a full tensor, skip_mm_cache=True: an item rebuilt from the render endpoint's features. It bypassed the sender cache, so it must bypass the receiver cache as well; inserting it would evict P1 entries that the sender still believes are cached, causing a later MultiModalCacheMissError.

MultiModalKwargsItem

Bases: UserDict[str, MultiModalFieldElem]

A dictionary of processed keyword arguments to pass to the model, corresponding to a single item in MultiModalDataItems.

Methods:

  • dummy –

    Convenience class for testing.

dummy(nbytes=1) staticmethod

Convenience class for testing.

MultiModalKwargsItems

Bases: UserDict[str, Sequence[_I]]

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:

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 for each keyword argument.

Methods:

  • get_data –

    Construct a dictionary of keyword arguments to pass to the model.

get_data(*, device=None, pin_memory=False)

Construct a dictionary of keyword arguments to pass to the model.

MultiModalSharedField dataclass

PlaceholderRange dataclass

Placeholder location information for multi-modal data.

Example: Prompt: AAAA BBBB What is in these images?

Images A and B will have:

A: PlaceholderRange(offset=0, length=4)
B: PlaceholderRange(offset=5, length=4)

Methods:

Attributes:

  • is_embed (Tensor | None) –

    A boolean mask of shape (length,) indicating which positions

  • length (int) –

    The length of the placeholder.

  • offset (int) –

    The start index of the placeholder in the prompt.

is_embed = None class-attribute instance-attribute

A boolean mask of shape (length,) indicating which positions between offset and offset + length to assign embeddings to.

length instance-attribute

The length of the placeholder.

offset instance-attribute

The start index of the placeholder in the prompt.

extract_embeds_range()

Extract the start and end indices of the embedded region in prompt.

For example, given PlaceholderRange(offset=2, length=5) and is_embed = [False, True, False, True, True], the output is [(1 + offset, 1 + offset), (3 + offset, 4 + offset)].

Returns:

  • list[tuple[int, int]] –

    A tuple (start, end) representing the start and end

  • list[tuple[int, int]] –

    indices (inclusive) of the embedded region.

  • list[tuple[int, int]] –

    Returns full placeholder range if is_embed is None.

get_embeds_indices_in_range(start_idx, end_idx)

Returns the starting and ending indices of the embeddings of encoder outputs in the range of [start_idx, end_idx) in the placeholders.

For example, given: PlaceholderRange(offset=2, length=5, is_embed=[False, True, False, True, True])

If start_idx=3 and end_idx=5, the output is (1, 3) because we want to get the second and the third embeddings from the encoder output.

VisionChunkImage

Bases: TypedDict

Represents an image wrapped as a vision chunk.

VisionChunkVideo

Bases: TypedDict

Represents a video chunk with metadata.

_is_dense(t)

Whether t's elements fill a contiguous storage range, possibly permuted (e.g. a transposed matrix). Such layouts can be copied with pitched cudaMemcpy2D/3DAsync directly from pinned memory, whereas gapped layouts (e.g. strided slices) stage through a pageable temp.

_nested_tensors_are_cpu(tensors)

Whether every tensor in tensors lives in host memory.

batched_tensors_equal(a, b)

Equality check between BatchedTensorInputs objects.

nested_tensors_equal(a, b, check_dtype=True)

Equality check between NestedTensors objects.

If check_dtype is True, the tensors must have the same dtype.