vllm.multimodal.processing
¶
Modules:
-
context– -
dummy_inputs– -
inputs– -
processor– -
video_kwargs–Per-video kwargs declarations available without importing model classes.
Classes:
-
BaseDummyInputsBuilder–Abstract base class that constructs the dummy data to profile
-
BaseMultiModalProcessor–Abstract base class to process multi-modal inputs to be used in vLLM.
-
BaseProcessingInfo–Base class to provide the information necessary for data processing.
-
EncDecMultiModalProcessor– -
InputProcessingContext–Contains information about the model which may be used to
-
ProcessorInputs–Represents the keyword arguments to
-
PromptIndexTargets– -
PromptInsertion–Defines how to insert placeholder tokens into a prompt.
-
PromptReplacement–Defines how to replace portions of an input prompt with placeholder tokens.
-
PromptUpdate–Defines how to update a prompt with placeholder tokens.
-
PromptUpdateDetails–Details about the token sequence that is part of the update.
-
TimingContext–Helper class to record execution times during multi-modal processing.
Functions:
-
cached_encode–Encode text while caching repeated tokenizer calls.
BaseDummyInputsBuilder
¶
Abstract base class that constructs the dummy data to profile multi-modal models.
Methods:
-
get_dummy_mm_data–Build the multimodal input which, after processing, results in
-
get_dummy_text–Build the text input corresponding to
mm_counts.
get_dummy_mm_data(seq_len, mm_counts, mm_options)
abstractmethod
¶
Build the multimodal input which, after processing, results in the maximum possible number of placeholder tokens.
Parameters:
-
(seq_len¶int) –Sequence length
-
(mm_counts¶Mapping[str, int]) –Count of items per modality
-
(mm_options¶MultiModalDummyOptions) –Configurable options per modality (optional). If None, use model defaults for backward compatibility. If provided, models can use these to customize dummy data generation.
get_dummy_text(mm_counts)
abstractmethod
¶
Build the text input corresponding to mm_counts.
BaseMultiModalProcessor
¶
Abstract base class to process multi-modal inputs to be used in vLLM.
Not to be confused with transformers.ProcessorMixin.
Methods:
-
apply–Process multi-modal inputs to be used in vLLM.
-
build_mm_kwargs_from_processed_tensors–Build multimodal kwargs from this processor's batched output tensors.
-
get_dummy_inputs–Build the input which, after processing, results in
-
get_dummy_mm_inputs–Create dummy data for profiling the memory usage of a model.
Attributes:
-
per_video_kwargs(Mapping[str, VideoKwargScope]) –Fields whose list values are indexed by video position.
per_video_kwargs = {}
class-attribute
¶
Fields whose list values are indexed by video position.
_apply_hf_processor_main(mm_items, hf_kwargs)
¶
Apply the HF processor on the multi-modal data.
_apply_prompt_updates(token_ids, mm_prompt_updates)
¶
Apply multi-modal prompt updates to token IDs.
_apply_prompt_updates_via_text(token_ids, mm_prompt_updates, *, encode_segments_separately=False)
¶
Apply multi-modal prompt updates in text space, then encode the result.
A non-special-token target may be tokenized differently inside the prompt because the tokens may go across the boundaries of the target (e.g. when searching for "foo" in "food", if "food" itself makes up a token, then the token ID of "foo" will not appear at all). Since it is inefficient to search for all possible tokenizations of the target in the prompt, we instead perform text-based updates on the decoded token IDs, then encode them back.
_cached_apply_hf_processor(inputs, timing_ctx)
¶
Apply the HF processor on the full prompt text, caching the results and reusing cached results.
_call_hf_processor(hf_data, hf_kwargs)
¶
Call the HF processor on the normalized multi-modal inputs.
_finalize_hf_mm_data(hf_data, hf_kwargs, passthrough_data, processed_data=None)
¶
Merge passthrough fields and apply model-specific postprocessing.
_get_cache_missing_processor_kwargs(inputs, mm_is_cached)
¶
Select processor options for the items missing from the cache.
_get_hf_mm_inputs(mm_items, hf_kwargs)
¶
Extract the multi-modal data and corresponding keyword arguments for HF processing.
If the HF processor expects the multi-modal data under different keys than those provided by the multi-modal items, or requires additional keyword arguments, you should override this method.
_get_hf_mm_text(mm_counts)
¶
Get the text to pass to the HF processor alongside the multi-modal data.
By default, no text is passed. If the HF processor requires that
text and multi-modal items correspond to each other, you should
override this method to return dummy text generated by
DummyInputsBuilder.
_get_mm_fields_config(hf_inputs, hf_processor_mm_kwargs)
abstractmethod
¶
Given the HF-processed data, output the metadata of each field.
_get_mm_hashes(inputs)
¶
Get each item's processor and encoder cache identity.
_get_prompt_updates(mm_items, hf_processor_mm_kwargs, out_mm_kwargs)
abstractmethod
¶
Given the original multi-modal items for this modality and HF-processed data, output the updates to perform.
The information returned by this method is used to update token inputs which bypass the HF processor. It is also used to update the output of HF processor if the HF process does not apply prompt updates to text inputs.
Moreover, this information is critical to determine the token positions
in order to construct
PlaceholderRange
for each multi-modal item.
_iter_text_matches(update, prompt_text, tokenizer, *, start_idx=0)
¶
Yield each instance of update.target found in prompt_text.
_postprocess_hf_mm_data(mm_data, hf_processor_mm_kwargs, processed_data)
¶
Post-process the combined processor and passthrough data.
By default, the output is returned as-is. If you need to modify the output of the HF processor before it is converted into multi-modal keyword arguments, you should override this method.
_postprocess_prompt(prompt)
¶
Post-process the prompt token IDs before locating or applying multi-modal prompt updates.
By default, the prompt is returned as-is. If the HF processor (or chat template) applies additional transformations to the prompt that are not reflected in its multi-modal outputs, you should override this method to replicate them.
_recompute_cached_prompt_update(cached_update, new_item_idx)
¶
Override this if other attributes of ResolvedPromptUpdate
also need to be recomputed after retrieving from the cache.
_resolve_per_video_kwargs(kwargs)
¶
Resolve the model's processor kwargs before selecting video lists.
apply(inputs, timing_ctx)
¶
Process multi-modal inputs to be used in vLLM.
The main steps are:
- Perform MM-specific post-processing to the token inputs.
- Apply HF Processor on multi-modal data together with optional dummy text, outputting processed multi-modal data tensors.
- Find and update sequences in the token IDs with placeholder tokens. The number of placeholder tokens equals the feature size of the multi-modal data outputted by the multi-modal encoder.
- Extract information about the placeholder tokens from the processed token IDs.
build_mm_kwargs_from_processed_tensors(tensors)
¶
Build multimodal kwargs from this processor's batched output tensors.
Parameters:
Returns:
-
MultiModalKwargsItems–The items, with this model's field metadata restored.
Raises:
-
ValueError–If
tensorshas fields the model does not declare, only CPU-side metadata fields, or a flat field whose sizes don't cover its tensor exactly.
get_dummy_inputs(seq_len, mm_counts, mm_options)
¶
get_dummy_mm_inputs(mm_counts, *, cache=None, scheduler_config=None, seq_len=None)
¶
Create dummy data for profiling the memory usage of a model.
BaseProcessingInfo
¶
Base class to provide the information necessary for data processing.
Methods:
-
get_data_parser–Constructs a parser to preprocess multi-modal data items
-
get_default_tok_params–Construct the default parameters for tokenization.
-
get_hf_processor–Subclasses can override this method to handle
-
get_mm_max_tokens_per_item–Return the maximum number of tokens per item of for each modality.
-
get_supported_mm_limits–Return the maximum supported number of items for each modality.
-
get_supported_mm_processor_kwargs–Return supported kwarg names for each HF processor kwargs scope.
-
get_video_frame_limits–The
max_frames/min_framesof the HF video processor, which the -
parse_mm_data–Normalize
MultiModalDataDict -
validate_num_input_items–Validate a modality count with its input representation available.
-
validate_num_items–Raise
ValueErrorif the number of input items for the given modality
Attributes:
-
allow_missing_mm_embeddings(bool) –Whether pre-computed embedding tensors may be omitted.
-
allowed_mm_limits(Mapping[str, int]) –The maximum allowed number of items for each modality.
-
default_mm_limits(Mapping[str, int]) –Per-modality item caps applied when the operator sets no explicit count.
-
supported_mm_limits(Mapping[str, int | None]) –The maximum supported number of items for each modality.
-
supported_mm_processor_kwargs(dict[str, set[str]]) –Supported kwarg names for each HF processor kwargs scope.
allow_missing_mm_embeddings
property
¶
Whether pre-computed embedding tensors may be omitted.
allowed_mm_limits
cached
property
¶
The maximum allowed number of items for each modality.
default_mm_limits = {}
class-attribute
¶
Per-modality item caps applied when the operator sets no explicit count.
supported_mm_limits
cached
property
¶
The maximum supported number of items for each modality.
supported_mm_processor_kwargs
cached
property
¶
Supported kwarg names for each HF processor kwargs scope.
_get_expected_hidden_size()
¶
Get expected hidden size for embedding validation if mm_embeds are enabled.
This validates hidden dimensions to prevent a vulnerability where embeddings
with correct ndim but wrong shape could cause crashes at inference time.
_merge_and_resolve_mm_processor_kwargs(mm_kwargs)
¶
Merge configured and request mm_processor_kwargs.
Flat kwargs are routed into the HuggingFace processor kwarg scopes that support them after the configured/request merge. When a routed flat value conflicts with an existing scoped value, the scoped value takes precedence.
get_data_parser()
¶
Constructs a parser to preprocess multi-modal data items
before passing them to
_get_hf_mm_inputs.
You can support additional modalities by creating a subclass
of MultiModalDataParser
that has additional subparsers.
get_default_tok_params()
¶
Construct the default parameters for tokenization.
get_hf_processor(**kwargs)
¶
Subclasses can override this method to handle specific kwargs from model config or user inputs.
get_mm_max_tokens_per_item(seq_len, mm_counts)
¶
Return the maximum number of tokens per item of for each modality.
When None (the default) is returned, vLLM will generate dummy inputs
(images/videos) at maximum possible sizes and process them to determine
the maximum token count per modality.
This approach works but can be very slow for certain models (e.g., Qwen2.5-VL), leading to very long startup time. For better performance, each model can override this method to return pre-computed maximum token counts, avoiding the need for dummy input generation and processing.
Note
The maximum number of tokens per item of each modality returned from this function should respect the model's maximum sequence length and the maximum number of items of each modality allowed, and agree with dummy inputs (images/videos) at maximum possible sizes.
get_supported_mm_limits()
¶
Return the maximum supported number of items for each modality.
A value of None means unlimited number of items.
Omitting a modality from the returned dictionary means that it is not supported at all.
get_supported_mm_processor_kwargs()
¶
Return supported kwarg names for each HF processor kwargs scope.
get_video_frame_limits()
¶
The max_frames/min_frames of the HF video processor, which the
video loader samples to; empty for models without one.
parse_mm_data(mm_data, *, validate=True)
¶
Normalize MultiModalDataDict
to MultiModalDataItems
before passing them to
_get_hf_mm_inputs.
validate_num_input_items(modality, num_items, *, is_embedding)
¶
Validate a modality count with its input representation available.
validate_num_items(modality, num_items)
¶
Raise ValueError if the number of input items for the given modality
is invalid.
EncDecMultiModalProcessor
¶
Bases: BaseMultiModalProcessor[_I]
Methods:
-
apply–Process multi-modal inputs to be used in vLLM.
-
create_decoder_prompt–Create input prompt for the decoder.
-
create_encoder_prompt–Create input prompt for the encoder. HF processor will be applied on
-
should_skip_decoder_start_token–Whether to leave the decoder start token out of this decoder prompt.
Attributes:
-
skip_decoder_start_token(bool) –Set this if the decoder prompt always carries its complete prefix,
skip_decoder_start_token = False
class-attribute
instance-attribute
¶
Set this if the decoder prompt always carries its complete prefix, so the decoder start token must not be prepended to it.
apply(inputs, timing_ctx)
¶
Process multi-modal inputs to be used in vLLM. The main processing steps are modified to fit encoder-decoder model: 1. Create encoder prompt from input prompt text. 2. Apply the HF processor on encoder prompt. 3. Copy the input prompt text as decoder prompt inputs.
create_decoder_prompt(prompt, mm_items)
¶
Create input prompt for the decoder.
create_encoder_prompt(prompt, mm_items)
abstractmethod
¶
Create input prompt for the encoder. HF processor will be applied on this prompt during profiling and generation.
should_skip_decoder_start_token(decoder_prompt_token_ids)
¶
Whether to leave the decoder start token out of this decoder prompt.
Override this instead of setting skip_decoder_start_token if only
some decoder prompts carry their complete prefix.
InputProcessingContext
dataclass
¶
Contains information about the model which may be used to modify the inputs.
Methods:
-
call_hf_processor–Call
hf_processoron the promptdata -
get_hf_config–Get the HuggingFace configuration
-
get_hf_image_processor_config–Get the HuggingFace image processor configuration of the model.
-
get_hf_processor–Get the HuggingFace processor
-
get_hf_processor_kwargs–Resolve the kwargs the Hugging Face processor passes to a modality.
-
get_merged_mm_kwargs–Merge configured and request
mm_processor_kwargs. -
get_mm_config–Get the multimodal config of the model.
-
init_processor–Initialize a HuggingFace-like processor class, merging the
Attributes:
-
model_config(ModelConfig) –The configuration of the model.
-
tokenizer(TokenizerLike | None) –The tokenizer used to tokenize the inputs.
model_config
instance-attribute
¶
The configuration of the model.
tokenizer
instance-attribute
¶
The tokenizer used to tokenize the inputs.
call_hf_processor(hf_processor, data, kwargs={})
¶
Call hf_processor on the prompt data
(text, image, audio...) with configurable options kwargs.
get_hf_config(typ=None)
¶
Get the HuggingFace configuration
(transformers.PreTrainedConfig) of the model,
additionally checking its type.
Raises:
-
TypeError–If the configuration is not of the specified type.
get_hf_image_processor_config()
¶
Get the HuggingFace image processor configuration of the model.
get_hf_processor(typ=None, /, **kwargs)
¶
Get the HuggingFace processor
(transformers.ProcessorMixin) of the model,
additionally checking its type.
Raises:
-
TypeError–If the processor is not of the specified type.
get_hf_processor_kwargs(hf_processor, kwargs, *, scope)
¶
Resolve the kwargs the Hugging Face processor passes to a modality.
get_merged_mm_kwargs(kwargs, *, supported_mm_processor_kwargs=None)
¶
Merge configured and request mm_processor_kwargs.
When supported_mm_processor_kwargs is provided, flat keys are matched
against the keys supported by each HuggingFace processor kwarg scope.
Matching flat keys are routed to every scope that supports them and
removed from the shared flat namespace; keys not supported by any scope
remain flat.
Without supported_mm_processor_kwargs, flat keys already represented
in at least one existing mapping-valued scope are removed from the shared
flat namespace; all other flat keys are left unchanged because there is
no information to determine which scopes should receive them.
get_mm_config()
¶
Get the multimodal config of the model.
Raises:
-
RuntimeError–If the model is not a multimodal model.
init_processor(typ, /, **kwargs)
¶
Initialize a HuggingFace-like processor class, merging the keyword arguments with those in the model's configuration.
ProcessorInputs
dataclass
¶
Represents the keyword arguments to
vllm.multimodal.processing.BaseMultiModalProcessor.apply.
PromptIndexTargets
¶
Methods:
-
end–Resolves to the end of the prompt (after the last token).
-
prefix–Resolves to a location in the prompt after the given prefix.
-
start–Resolves to the start of the prompt (before the first token).
end()
staticmethod
¶
Resolves to the end of the prompt (after the last token).
This results in a match even if the prompt is empty.
prefix(seq)
staticmethod
¶
Resolves to a location in the prompt after the given prefix.
start()
staticmethod
¶
Resolves to the start of the prompt (before the first token).
This results in a match even if the prompt is empty.
PromptInsertion
dataclass
¶
Bases: PromptUpdate
Defines how to insert placeholder tokens into a prompt.
Example:
For each image, insert a number of <image> feature placeholders
equal to the feature size of the vision encoder after the <s> token:
PromptInsertion(
modality="image",
target=[bos_token_id],
insertion=[image_token_id] * image_feature_size,
)
Insert these tokens at the start of the prompt:
PromptInsertion(
modality="image",
target=PromptIndexTargets.start(),
insertion=[image_token_id] * image_feature_size,
)
Insert these tokens after a prefix Images::
PromptInsertion(
modality="image",
target=PromptIndexTargets.prefix(images_prefix_token_ids),
insertion=[image_token_id] * image_feature_size,
)
Insert these tokens at the end of the prompt:
PromptInsertion(
modality="image",
target=PromptIndexTargets.end(),
insertion=[image_token_id] * image_feature_size,
)
Attributes:
-
insertion(PromptUpdateContent) –Given the index of the processed item within
PromptReplacement
dataclass
¶
Bases: PromptUpdate
Defines how to replace portions of an input prompt with placeholder tokens.
Example:
For each image, replace one <image> input placeholder in the prompt
with a number of <image> feature placeholders
equal to the feature size of the vision encoder:
PromptReplacement(
modality="image",
target=[image_token_id],
replacement=[image_token_id] * image_feature_size,
)
As above, but further pad the feature placeholders with <image_bos>
and <image_eos>, which are not supposed to be passed to the vision
encoder:
PromptReplacement(
modality="image",
target=[image_token_id],
replacement=PromptUpdateDetails(
full=(
[image_bos_id] + [image_token_id] * image_feature_size + [image_eos_id]
),
is_embed=lambda full: torch.tensor(full) == image_token_id,
),
)
Attributes:
-
replacement(PromptUpdateContent) –Given the index of the processed item within
PromptUpdate
dataclass
¶
Bases: ABC
Defines how to update a prompt with placeholder tokens.
Note
The target and content are token sequences. When converting text
to token sequences, remember to encode it with
add_special_tokens=False to match how the prompt itself is
tokenized. Otherwise, the updated prompt may contain duplicated
special tokens or fail to match the target.
Methods:
-
resolve–Given the index of the processed item within
Attributes:
-
content(PromptUpdateContent) –The placeholder tokens that are part of the update.
-
modality(str) –The modality for which the update is made.
-
mode(UpdateMode) –Defines how to update the prompt.
-
target(PromptUpdateTarget) –The token sequence to update.
PromptUpdateDetails
dataclass
¶
Details about the token sequence that is part of the update.
Attributes:
full
instance-attribute
¶
The full content.
is_embed = None
class-attribute
instance-attribute
¶
Given full,
return a boolean mask of shape (len(full),) indicating which positions
of full to assign embeddings to.
None (default) means to assign embeddings to all positions of full.
The embeddings are obtained by calling
SupportsMultiModal.embed_multimodal.
TimingContext
dataclass
¶
Helper class to record execution times during multi-modal processing.
Methods:
-
record–Record the execution time for a processing stage.
Attributes:
-
enabled(bool) –If disabled,
TimingContext.recordbecomes a no-op. -
stage_secs(dict[str, float]) –The execution time (in seconds) for each processing stage.
enabled = True
class-attribute
instance-attribute
¶
If disabled, TimingContext.record becomes a no-op.
stage_secs = field(default_factory=dict)
class-attribute
instance-attribute
¶
The execution time (in seconds) for each processing stage.
record(stage)
¶
Record the execution time for a processing stage.
cached_encode(tokenizer, text, *, truncation=None, add_special_tokens=True)
cached
¶
Encode text while caching repeated tokenizer calls.