vllm.multimodal.processing.processor
¶
Classes:
-
BaseMultiModalProcessor–Abstract base class to process multi-modal inputs to be used in vLLM.
-
EncDecMultiModalProcessor– -
HFMultiModalInputs– -
PromptIndex–Resolves to an index in the prompt.
-
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.
-
ResolvedPromptUpdate–A
PromptUpdatewith its
Functions:
-
apply_token_matches–Apply the updates in
mm_prompt_updatestoprompt. -
cached_encode–Encode text while caching repeated tokenizer calls.
-
full_groupby_modality–Convenience function to apply
-
iter_token_matches–Yield each occurrence of
match_idsintoken_ids. -
replace_token_matches–Replace each occurrence of
match_idsintoken_ids
Attributes:
-
MultiModalIsCached–A collection of the
is_cachedflag for each item, with a similar structure as -
MultiModalPromptUpdates–A collection of prompt updates with a similar structure as
-
MultiModalPromptUpdatesApplyResult–For an item
MultiModalPromptUpdates[k][i], -
PromptUpdateContent(TypeAlias) –Given the index of the processed item within
-
PromptUpdateInfo(TypeAlias) –The token sequence that is part of the update.
-
PromptUpdateTarget(TypeAlias) –Given the index of the processed item within
-
UpdateTarget(TypeAlias) –The token sequence to update.
MultiModalIsCached = dict[str, list[bool]]
module-attribute
¶
A collection of the is_cached flag for each item, with a similar structure as
MultiModalKwargsItems.
MultiModalPromptUpdates = Mapping[str, Sequence[Sequence[ResolvedPromptUpdate]]]
module-attribute
¶
A collection of prompt updates with a similar structure as
MultiModalKwargsItems.
MultiModalPromptUpdatesApplyResult = Mapping[str, list[int | None]]
module-attribute
¶
For an item MultiModalPromptUpdates[k][i],
MultiModalPromptUpdatesApplyResult[k][i] represents the index of the
ResolvedPromptUpdate instance that has been applied, or None if none of the
ResolvedPromptUpdate instances have been applied.
PromptUpdateContent = Callable[[int], PromptUpdateInfo] | PromptUpdateInfo
module-attribute
¶
Given the index of the processed item within
modality,
output the corresponding token sequence.
For convenience, you can directly pass in the token sequence instead of a function if it does not depend on the input.
PromptUpdateInfo = list[int] | PromptUpdateDetails
module-attribute
¶
The token sequence that is part of the update.
If only part of the content corresponds to feature placeholders, you can
use PromptUpdateDetails to
specify which part.
PromptUpdateTarget = Callable[[int], UpdateTarget] | UpdateTarget
module-attribute
¶
Given the index of the processed item within
modality,
output the corresponding token sequence.
For convenience, you can directly pass in the token sequence instead of a function if it does not depend on the input.
UpdateTarget = list[int] | PromptIndex
module-attribute
¶
The token sequence to update.
_IterMatches = Callable[[ResolvedPromptUpdate, int], Generator[PromptTargetMatch, None, None]]
module-attribute
¶
Yields each match of an update's target, given the search start index.
_QueueMatch = tuple[_UpdateQueue, PromptTargetMatch, int]
module-attribute
¶
A queue together with its next match and selected alternative index.
_UpdateQueue = deque[tuple[int, Sequence[ResolvedPromptUpdate]]]
module-attribute
¶
Items with the same ordered match rules, stored as (priority, alternatives).
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.
_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.
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.
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.
HFMultiModalInputs
¶
Bases: NamedTuple
Attributes:
PromptIndex
dataclass
¶
Resolves to an index in the prompt.
Attributes:
-
get_text_match_index(_GetTextMatchIndex) –Resolves the index against a decoded text prompt.
get_text_match_index
instance-attribute
¶
Resolves the index against a decoded text prompt.
Used only by the private text-based fallback of
BaseMultiModalProcessor._apply_prompt_updates.
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.
ResolvedPromptUpdate
dataclass
¶
A PromptUpdate with its
lazy attributes resolved.
Methods:
-
iter_token_matches–Yield each instance of
self.targetfound inprompt.
Attributes:
-
content(PromptUpdateDetails) –The placeholder tokens that are part of the update.
-
item_idx(int) –The index within
modalityof the item this update pertains to. -
modality(str) –The modality for which the update is made.
-
mode(UpdateMode) –Defines how to update the prompt.
-
target(UpdateTarget) –The token sequence to update.
content = field(repr=False)
class-attribute
instance-attribute
¶
The placeholder tokens that are part of the update.
item_idx
instance-attribute
¶
The index within modality of the item this update pertains to.
modality
instance-attribute
¶
The modality for which the update is made.
mode
instance-attribute
¶
Defines how to update the prompt.
target
instance-attribute
¶
The token sequence to update.
iter_token_matches(prompt, *, start_idx=0)
¶
Yield each instance of self.target found in prompt.
_MatchedUpdate
¶
Bases: NamedTuple
A resolved update selected for a match in the original prompt.
Attributes:
-
match(PromptTargetMatch) –The target range in the original prompt.
-
priority(int) –The original item order used to preserve match tie-breaking.
-
update(ResolvedPromptUpdate) –The selected update for the multimodal item.
-
update_idx(int) –The selected update's index within the item's alternatives.
match
instance-attribute
¶
The target range in the original prompt.
priority
instance-attribute
¶
The original item order used to preserve match tie-breaking.
update
instance-attribute
¶
The selected update for the multimodal item.
update_idx
instance-attribute
¶
The selected update's index within the item's alternatives.
_compile_prompt_update_queues(mm_prompt_updates)
¶
Group items with identical match rules into ordered queues.
_find_queue_match(queue, iter_matches, *, start_idx, mode=None)
¶
Find the first matching alternative for the next queued item.
_iter_placeholders(prompt, mm_prompt_updates)
¶
Yield each set of placeholder tokens found in prompt.
Matches are exclusive even when multiple modalities share
the same placeholder tokens. In that case, the modality that
appears earlier in mm_prompt_updates takes priority.
Note that empty matches are ignored.
_next_priority(queue)
¶
Return the original priority of the next queued item.
_plan_prompt_updates(prompt, mm_prompt_updates)
¶
Plan non-overlapping prompt updates before rendering the output.
_plan_prompt_updates_with(mm_prompt_updates, iter_matches)
¶
Plan non-overlapping prompt updates before rendering the output.
_target_key(target)
¶
Return a hashable key that preserves target matching semantics.
apply_token_matches(prompt, mm_prompt_updates)
¶
Apply the updates in mm_prompt_updates to prompt.
Matches are exclusive even when multiple modalities share
the same placeholder tokens. In that case, the modality that
appears earlier in mm_prompt_updates takes priority.
cached_encode(tokenizer, text, *, truncation=None, add_special_tokens=True)
cached
¶
Encode text while caching repeated tokenizer calls.
full_groupby_modality(values)
¶
Convenience function to apply
full_groupby
based on modality.
iter_token_matches(token_ids, match_ids, *, start_idx=0)
¶
Yield each occurrence of match_ids in token_ids.
Note that empty matches are ignored.
replace_token_matches(token_ids, match_ids, new_ids)
¶
Replace each occurrence of match_ids in token_ids
with new_ids.
Note that empty matches are ignored.