vllm.model_executor.models.interfaces
¶
Classes:
-
DiarizedTranscriptionSegment–A timestamped, speaker-attributed segment produced by an ASR model.
-
EagleModelMixin– -
HasInnerState–The interface required for all models that has inner state.
-
IsAttentionFree–The interface required for all models like Mamba that lack attention,
-
IsHybrid–The interface required for all models like Zamba2 that have both
-
LocalArgmaxMixin–Mixin for draft model heads in speculative decoding.
-
MixtureOfExperts–Check if the model is a mixture of experts (MoE) model.
-
SpeculativeDraftModel–The interface of a speculative decoding draft model which declares the
-
StreamingDiarizedTranscriptParser–Stateful parser for streamed
diarized_jsonoutput. -
StreamingTranscriptionPostProcessor–Stateful streaming post-processor for transcription deltas.
-
SupportsCrossEncoding–The interface required for all models that support cross encoding.
-
SupportsEagle–The interface required for models that support
-
SupportsEagle3–The interface required for models that support
-
SupportsEagleBase–Base interface for models that support EAGLE-based speculative decoding.
-
SupportsEncoderCudaGraph–Interface for models whose vision encoder supports CUDA graph
-
SupportsHCSP–Support sequence-parallel HC without changing MoE parallelism.
-
SupportsKVCacheGrouping–The interface required for models that own their KV cache grouping.
-
SupportsLateInteraction–The interface required for all models that support late interaction.
-
SupportsLoRA–The interface required for all models that support LoRA.
-
SupportsMRoPE–The interface required for all models that support M-RoPE.
-
SupportsMambaPrefixCaching–The interface for attention-free Mamba models that support prefix
-
SupportsMultiModal–The interface required for all multi-modal models.
-
SupportsMultiModalEmbeddings–The interface for models that can merge external multimodal embeddings.
-
SupportsMultiModalPruning–The interface required for models that support returning both input
-
SupportsPP–The interface required for all models that support pipeline parallel.
-
SupportsQuant–The interface required for all models that support quantization.
-
SupportsRealtime–The interface required for all models that support transcription.
-
SupportsReplaySSM–The interface for models whose recurrent layers support ReplaySSM
-
SupportsScoreTemplate–The interface required for all models that support score template.
-
SupportsTranscription–The interface required for all models that support transcription.
Functions:
-
get_eagle_decoder–The decoder of
modelthat takes the aux hidden states, if any. -
get_mixture_of_experts_model–Return the MixtureOfExperts contained within an arbitrary model.
-
supports_any_eagle–Check if model supports any EAGLE variant (1, 2, or 3).
Attributes:
-
MultiModalEmbeddings(TypeAlias) –The output embeddings must be one of the following formats:
MultiModalEmbeddings = list[Tensor] | Tensor | tuple[Tensor, ...]
module-attribute
¶
The output embeddings must be one of the following formats:
- A list or tuple of 2D tensors, where each tensor corresponds to each input multimodal data item (e.g, image).
- A single 3D tensor, with the batch dimension grouping the 2D tensors.
DiarizedTranscriptionSegment
dataclass
¶
A timestamped, speaker-attributed segment produced by an ASR model.
EagleModelMixin
¶
Methods:
-
aux_hidden_state_slot_keys–IntermediateTensorskeys of the aux hidden states this PP stage -
collect_remote_aux_hidden_states–Deprecated, kept for out-of-tree models: returns []. The model runner
aux_hidden_state_slot_keys()
¶
IntermediateTensors keys of the aux hidden states this PP stage
receives from earlier stages, and of those it takes and sends on (none
on the last stage).
The forward returns only the aux hidden states this stage takes; the runner adds the received ones once, on the last stage.
collect_remote_aux_hidden_states(intermediate_tensors)
¶
Deprecated, kept for out-of-tree models: returns []. The model runner now adds the earlier PP stages' aux hidden states on the last stage.
HasInnerState
¶
Bases: Protocol
The interface required for all models that has inner state.
Attributes:
-
has_inner_state(Literal[True]) –A flag that indicates this model has inner state.
has_inner_state = True
class-attribute
¶
A flag that indicates this model has inner state. Models that has inner state usually need access to the scheduler_config for max_num_seqs, etc. True for e.g. both Mamba2 and Zamba2.
IsAttentionFree
¶
Bases: Protocol
The interface required for all models like Mamba that lack attention, but do have state whose size is constant wrt the number of tokens.
Attributes:
-
is_attention_free(Literal[True]) –A flag that indicates this model has no attention.
is_attention_free = True
class-attribute
¶
A flag that indicates this model has no attention. Used for block manager and attention backend selection. True for Mamba2 but not Zamba2.
IsHybrid
¶
Bases: Protocol
The interface required for all models like Zamba2 that have both attention and mamba blocks, indicates that hf_config has 'layers_block_type'
Methods:
-
get_mamba_state_copy_func–Calculate copy-function callables for each Mamba state.
-
get_mamba_state_shape_from_config–Calculate shapes for Mamba's convolutional and state caches.
Attributes:
is_hybrid = True
class-attribute
¶
A flag that indicates this model has both mamba and attention blocks , also indicates that the model's hf_config has 'layers_block_type'
get_mamba_state_copy_func()
classmethod
¶
Calculate copy-function callables for each Mamba state.
Returns:
-
MambaStateCopyFunc–A tuple of MambaStateCopyFunc callables that correspond, in order,
-
...–to the Mamba states produced by the model. Each callable accepts
-
tuple[MambaStateCopyFunc, ...]–(state, block_ids, cur_block_idx, num_accepted_tokens) and returns
-
tuple[MambaStateCopyFunc, ...]–a MambaCopySpec describing the memory-copy parameters for prefix
-
tuple[MambaStateCopyFunc, ...]–caching.
get_mamba_state_shape_from_config(vllm_config)
classmethod
¶
Calculate shapes for Mamba's convolutional and state caches.
Parameters:
-
(vllm_config¶VllmConfig) –vLLM config
Returns:
-
MambaStateShapes–Shapes for each state cache used by the model.
LocalArgmaxMixin
¶
Mixin for draft model heads in speculative decoding.
Provides a D2T-aware get_top_tokens that preserves the
local-argmax communication reduction even when the draft vocabulary
is smaller than the target vocabulary.
When draft_id_to_target_id is present (shape (draft_vocab_size,),
containing per-token offset to target vocab id), the draft argmax index
k is mapped to the target vocab id via::
target_id = k + draft_id_to_target_id[k]
This is mathematically equivalent to computing the full-vocab scatter logits and taking the global argmax, but requires only O(batch * 2 * tp_size) communication instead of O(batch * vocab_size).
Requires the subclass to expose
self.logits_processor: LogitsProcessor
self.lm_head: ParallelLMHead
self.draft_id_to_target_id (optional): nn.Parameter
Methods:
-
get_top_tokens–Vocab-parallel argmax with optional D2T remapping.
get_top_tokens(hidden_states)
¶
Vocab-parallel argmax with optional D2T remapping.
MixtureOfExperts
¶
Bases: Protocol
Check if the model is a mixture of experts (MoE) model.
Methods:
-
set_eplb_state–Register the EPLB state in the MoE model.
Attributes:
-
expert_weights(MutableSequence[Sequence[Tensor]]) –Expert weights saved in this rank.
-
moe_layers(Sequence[MoERunner]) –List of MoE layers in this model.
-
num_expert_groups(int) –Number of expert groups in this model.
-
num_local_physical_experts(int) –Number of local physical experts in this model.
-
num_logical_experts(int) –Number of logical experts in this model.
-
num_moe_layers(int) –Number of MoE layers in this model.
-
num_physical_experts(int) –Number of physical experts in this model.
-
num_redundant_experts(int) –Number of redundant experts in this model.
-
num_routed_experts(int) –Number of routed experts in this model.
-
num_shared_experts(int) –Number of shared experts in this model.
expert_weights
instance-attribute
¶
Expert weights saved in this rank.
The first dimension is the layer, and the second dimension is different parameters in the layer, e.g. up/down projection weights.
moe_layers
instance-attribute
¶
List of MoE layers in this model.
num_expert_groups
instance-attribute
¶
Number of expert groups in this model.
num_local_physical_experts
instance-attribute
¶
Number of local physical experts in this model.
num_logical_experts
instance-attribute
¶
Number of logical experts in this model.
num_moe_layers
instance-attribute
¶
Number of MoE layers in this model.
num_physical_experts
instance-attribute
¶
Number of physical experts in this model.
num_redundant_experts
instance-attribute
¶
Number of redundant experts in this model.
num_routed_experts
instance-attribute
¶
Number of routed experts in this model.
num_shared_experts
instance-attribute
¶
Number of shared experts in this model.
set_eplb_state(expert_load_view, logical_to_physical_map, logical_replica_count)
¶
Register the EPLB state in the MoE model.
Since these are views of the actual EPLB state, any changes made by the EPLB algorithm are automatically reflected in the model's behavior without requiring additional method calls to set new states.
You should also collect model's expert_weights here instead of in
the weight loader, since after initial weight loading, further
processing like quantization may be applied to the weights.
Parameters:
SpeculativeDraftModel
¶
Bases: Protocol
The interface of a speculative decoding draft model which declares the speculator it's for. This is read through the model registry, so that it's available without importing the model.
Attributes:
-
speculator_config_class(type[SpeculatorConfig]) –The config class of the speculator that this is a draft model of.
speculator_config_class
class-attribute
¶
The config class of the speculator that this is a draft model of. Unless a speculative method is configured that the checkpoint can't override, a draft checkpoint with this model's architecture uses this speculator.
StreamingDiarizedTranscriptParser
¶
Stateful parser for streamed diarized_json output.
This default parses the output once generation has finished.
Methods:
-
process_delta–Yield the segments that this raw decoded delta completes.
process_delta(text_delta, finished)
¶
Yield the segments that this raw decoded delta completes.
Raises:
-
ValueError–If the output is not a valid diarized transcript.
StreamingTranscriptionPostProcessor
¶
Stateful streaming post-processor for transcription deltas.
SupportsCrossEncoding
¶
SupportsEagle
¶
Bases: SupportsEagleBase, Protocol
The interface required for models that support EAGLE-1 and EAGLE-2 speculative decoding.
Attributes:
-
supports_eagle(Literal[True]) –A flag that indicates this model supports EAGLE-1 and EAGLE-2
supports_eagle = True
class-attribute
¶
A flag that indicates this model supports EAGLE-1 and EAGLE-2 speculative decoding.
Note
There is no need to redefine this flag if this class is in the MRO of your model class.
SupportsEagle3
¶
Bases: SupportsEagleBase, Protocol
The interface required for models that support EAGLE-3 speculative decoding.
Methods:
-
get_eagle3_default_aux_hidden_state_layers–Get the default layer indices that should output auxiliary hidden states
-
set_aux_hidden_state_layers–Set which layers should output auxiliary hidden states for EAGLE-3.
Attributes:
-
supports_eagle3(Literal[True]) –A flag that indicates this model supports EAGLE-3
supports_eagle3 = True
class-attribute
¶
A flag that indicates this model supports EAGLE-3 speculative decoding.
Note
There is no need to redefine this flag if this class is in the MRO of your model class.
get_eagle3_default_aux_hidden_state_layers()
¶
Get the default layer indices that should output auxiliary hidden states for EAGLE-3 for this model. Models can override this method to provide different default layers based on their architecture, but it is encouraged to instead include the layer specification in the model's config if possible.
Returns:
SupportsEagleBase
¶
Bases: Protocol
Base interface for models that support EAGLE-based speculative decoding.
Attributes:
-
has_own_embed_tokens(bool) –A flag that indicates this model has trained its own input embeddings.
-
has_own_lm_head(bool) –A flag that indicates this model has trained its own lm_head.
SupportsEncoderCudaGraph
¶
Bases: Protocol
Interface for models whose vision encoder supports CUDA graph capture/replay.
Models implement these methods to provide the
EncoderCudaGraphManager with all model-specific logic
(input handling, metadata computation, forward pass) without the
manager needing to know model internals.
Methods:
-
encoder_cudagraph_forward–Run the encoder forward pass with precomputed buffers.
-
encoder_eager_forward–Run the encoder forward pass without precomputed buffers.
-
get_encoder_cudagraph_budget_range–Return (min_token_budget, max_token_budget) for auto-inference.
-
get_encoder_cudagraph_item_specs–Return specs describing each item in the batch.
-
get_input_modality–Return the modality of the inputs (default: image-only).
-
get_max_frames_per_video–Return model-specific max frames per video.
-
postprocess_encoder_output–Post-process encoder output, directly call scatter_output_slices by default.
-
prepare_encoder_cudagraph_capture_inputs–Create dummy inputs and buffers for CUDA graph capture.
-
prepare_encoder_cudagraph_replay_buffers–Compute buffer values from actual batch inputs for replay.
-
select_encoder_cudagraph_items–Select a subset of items and return mm_kwargs for the sub-batch.
encoder_cudagraph_forward(values, path='default')
¶
Run the encoder forward pass with precomputed buffers.
Used during both CUDA graph capture and replay.
encoder_eager_forward(mm_kwargs, path='default')
¶
Run the encoder forward pass without precomputed buffers.
Used as eager fallback when inputs exceed all budgets.
get_encoder_cudagraph_budget_range(vllm_config)
¶
Return (min_token_budget, max_token_budget) for auto-inference.
- min_token_budget: estimated smallest possible encoder input (e.g. 64 for a 224x224 image)
- max_token_budget: estimated largest budget worth capturing (e.g. max_num_batched_tokens)
Used when encoder_cudagraph_token_budgets and/or
encoder_cudagraph_max_vision_items_per_batch are not explicitly
specified by the user.
get_encoder_cudagraph_item_specs(mm_kwargs)
¶
Return specs describing each item in the batch.
Replaces the former separate methods for num_items, per_item_output_tokens, and per_item_input_sizes. The manager derives all three from this single return value.
get_input_modality(mm_kwargs)
¶
Return the modality of the inputs (default: image-only).
get_max_frames_per_video()
¶
Return model-specific max frames per video.
postprocess_encoder_output(outputs, indices, per_item_out_tokens, dest, clone=False, batch_mm_kwargs=None)
¶
Post-process encoder output, directly call scatter_output_slices by default.
By default, delegates directly to scatter_output_slices. Override this for models that require additional processing on the raw encoder output prior to scattering, e.g. Step3-VL, which merges features according to dynamic patch counts before scattering.
With clone=True, the tensors written to dest must not alias
outputs: they are graph output buffers, shared across the token
budgets of a path, that the next replay overwrites.
prepare_encoder_cudagraph_capture_inputs(token_budget, max_batch_size, max_frames_per_batch, device, dtype, path='default', axis_keys=None)
¶
Create dummy inputs and buffers for CUDA graph capture.
Parameters:
-
(token_budget¶int) –Token budget the capture is sized for.
-
(max_batch_size¶int) –Maximum number of items in a captured batch.
-
(max_frames_per_batch¶int) –Maximum number of frames in a captured batch.
-
(device¶device) –Device the dummy inputs and buffers are created on.
-
(dtype¶dtype) –Dtype of the dummy inputs and buffers.
-
(path¶str, default:'default') –Configured encoder path.
-
(axis_keys¶tuple[Hashable, ...] | None, default:None) –The resolved capture-axis keys (one per axis of
EncoderCudaGraphConfig.capture_axes) this capture is for. None or empty when no capture axes are configured; models without capture axes ignore it.
prepare_encoder_cudagraph_replay_buffers(mm_kwargs, max_batch_size, max_frames_per_batch, path='default')
¶
Compute buffer values from actual batch inputs for replay.
Must provide every capture buffer that smaller budgets share as a prefix view: other budgets' captures overwrite its capture-time contents, so the manager raises if replay omits it.
select_encoder_cudagraph_items(mm_kwargs, indices)
¶
Select a subset of items and return mm_kwargs for the sub-batch.
Called by the manager during greedy packing and DP sharding to extract inputs for a specific set of items (e.g. images at indices [0, 3, 5]). The implementation is model-specific because input formats differ:
- Qwen-family: slice concatenated pixel_values by cumulative patch offsets, subset grid_thw by indices.
- Batched models (CLIP): index pixel_values along dim 0.
Models that configure EncoderCudaGraphConfig.capture_axes must
additionally store the resolved per-axis keys (one key per axis, in
order) under ENCODER_CUDAGRAPH_AXIS_KEYS_KWARG in the returned
dict; the manager pops it before the kwargs are used elsewhere.
SupportsKVCacheGrouping
¶
Bases: Protocol
The interface required for models that own their KV cache grouping.
Note
Experimental. The classmethod contract may change as model-owned grouping stabilizes.
Implementing it lets a model replace the default KV cache grouping (which layers share a block table) while Core keeps owning placement, byte accounting, and admission.
Methods:
-
get_kv_cache_groups–Split the model's layers into logical KV cache groups.
get_kv_cache_groups(vllm_config, layer_configs)
classmethod
¶
Split the model's layers into logical KV cache groups.
SupportsLateInteraction
¶
Bases: Protocol
The interface required for all models that support late interaction.
Late interaction models (like ColBERT) encode queries and documents separately into per-token embeddings, then compute similarity via MaxSim (max over document tokens, sum over query tokens).
SupportsLoRA
¶
Bases: Protocol
The interface required for all models that support LoRA.
Attributes:
-
supports_lora(Literal[True]) –A flag that indicates this model supports LoRA.
supports_lora = True
class-attribute
¶
A flag that indicates this model supports LoRA.
Note
There is no need to redefine this flag if this class is in the MRO of your model class.
SupportsMRoPE
¶
Bases: Protocol
The interface required for all models that support M-RoPE.
Methods:
-
get_mrope_input_positions–Get M-RoPE input positions and delta value for this specific model.
Attributes:
-
supports_mrope(Literal[True]) –A flag that indicates this model supports M-RoPE.
supports_mrope = True
class-attribute
¶
A flag that indicates this model supports M-RoPE.
Note
There is no need to redefine this flag if this class is in the MRO of your model class.
get_mrope_input_positions(input_tokens, mm_features)
¶
Get M-RoPE input positions and delta value for this specific model.
This method should be implemented by each model that supports M-RoPE to provide model-specific logic for computing input positions.
Parameters:
-
(input_tokens¶list[int]) –List of input token IDs
-
(mm_features¶list[MultiModalFeatureSpec]) –Information about each multi-modal data item
Returns:
SupportsMambaPrefixCaching
¶
Bases: Protocol
The interface for attention-free Mamba models that support prefix
caching. Hybrid models get the same methods from IsHybrid.
Methods:
-
get_mamba_state_copy_func–Return copy functions for the model's Mamba states.
-
get_mamba_state_copy_funcs–Map legacy copy functions to each requested Mamba backend.
SupportsMultiModal
¶
Bases: SupportsMultiModalEmbeddings, Protocol
The interface required for all multi-modal models.
Methods:
-
configure_mm_token_handling–Check if any multimodal tokens are out of vocabulary. If so, we will
-
embed_input_ids–Apply token embeddings to
input_ids. -
embed_multimodal–Returns multimodal embeddings generated from multimodal kwargs
-
get_language_model–Returns the underlying language model used for text generation.
-
get_mm_lora_token_counts–Return
(tower_tokens, connector_tokens)for multimodal LoRA mappings. -
get_placeholder_str–Get the placeholder text for the
ithmodalityitem in the prompt.
Attributes:
-
requires_raw_input_tokens(bool) –A flag that indicates this model processes input id tokens
-
supports_encoder_tp_data(bool) –A flag that indicates whether this model supports
-
supports_mm_device_do_normalize(bool) –A flag that indicates whether this model supports
-
supports_multimodal(Literal[True]) –A flag that indicates this model supports multi-modal inputs.
-
supports_multimodal_raw_input_only(bool) –A flag that indicates this model supports multi-modal inputs and processes
-
supports_tower_connector_lora(bool) –A flag that indicates whether this model supports
_has_oov_mm_tokens = False
class-attribute
instance-attribute
¶
In general, this should be set at init time by invoking
configure_mm_token_handling models & passing all potentially
OOV multimodal tokens.
_language_model_names = ()
class-attribute
instance-attribute
¶
Set internally by _mark_language_model.
_processor_factory
class-attribute
¶
Set internally by MultiModalRegistry.register_processor.
_tower_model_names = ()
class-attribute
instance-attribute
¶
Set internally by _mark_tower_model.
requires_raw_input_tokens = False
class-attribute
¶
A flag that indicates this model processes input id tokens in their raw form and not input embeddings.
supports_encoder_tp_data = False
class-attribute
¶
A flag that indicates whether this model supports
multimodal_config.mm_encoder_tp_mode="data".
supports_mm_device_do_normalize = False
class-attribute
¶
A flag that indicates whether this model supports
multimodal_config.mm_device_do_normalize.
supports_multimodal = True
class-attribute
¶
A flag that indicates this model supports multi-modal inputs.
Note
There is no need to redefine this flag if this class is in the MRO of your model class.
supports_multimodal_raw_input_only = False
class-attribute
¶
A flag that indicates this model supports multi-modal inputs and processes them in their raw form and not embeddings.
supports_tower_connector_lora = False
class-attribute
¶
A flag that indicates whether this model supports
lora_config.enable_tower_connector_lora.
_mark_composite_model(vllm_config, *, language_targets, tower_targets)
¶
Composite wrapper over _mark_language_model and
_mark_tower_model by modality.
_mark_language_model(vllm_config, *, targets=None)
¶
Mark each child module that was assigned to this model during this context as a language model component.
Language model components are automatically skipped in --mm-encoder-only
mode.
If targets is set, instead include descendants that are an instance
of targets, even if they aren't direct children.
_mark_tower_model(vllm_config, modalities, *, targets=None, auto_offload=True)
¶
Mark each child module that was assigned to this model during this context as a tower model component.
Tower model components are automatically skipped when --limit-mm-per-prompt
is set to zero for all of their modalities, and on pipeline stages after the
first, since encoders run on the first stage only.
Parameters:
-
(vllm_config¶VllmConfig) –The vLLM config, used to read the per-modality limits.
-
(modalities¶set[str] | str) –The modalities the marked components encode.
-
(targets¶type[Module] | tuple[type[Module], ...] | None, default:None) –If set, mark descendants that are an instance of
targets, even if they aren't direct children. -
(auto_offload¶bool, default:True) –Route the marked components through the active offloader (when it supports tower offloading) on exit, since
make_layersonly ever sees the decoder layer stack. Set toFalseif the caller offloads them itself, e.g. once they are materialised.
configure_mm_token_handling(vocab_size, mm_token_ids)
¶
Check if any multimodal tokens are out of vocabulary. If so, we will explicitly mask all multimodal tokens out when computing text embeddings, since the multimodal embeddings will be scattered over the results.
embed_input_ids(input_ids, multimodal_embeddings=None, *, is_multimodal=None)
¶
Apply token embeddings to input_ids.
If multimodal_embeddings is passed, scatter them into
input_ids according to the mask is_multimodal.
NOTE: If this model has multimodal tokens that are of vocabulary (i.e., self._has_oov_mm_tokens=True), the input_ids will be copied and masked to 0 during the forward pass for the text embeddings.
embed_multimodal(**kwargs)
¶
Returns multimodal embeddings generated from multimodal kwargs to be merged with text embeddings.
Note
The returned multimodal embeddings must be in the same order as the appearances of their corresponding multimodal data item in the input prompt.
get_language_model()
¶
Returns the underlying language model used for text generation.
This is typically the torch.nn.Module instance responsible for
processing the merged multimodal embeddings and producing hidden states
Returns:
-
VllmModel–torch.nn.Module: The core language model component.
get_mm_lora_token_counts(*, modality, mm_kwargs, num_mm_embeds)
¶
Return (tower_tokens, connector_tokens) for multimodal LoRA mappings.
MM LoRA uses these counts to build adapter mappings for the tower and connector forwards. Models with multiple modalities can override this when each modality has different encoder padding or pooling behavior.
get_placeholder_str(modality, i)
classmethod
¶
Get the placeholder text for the ith modality item in the prompt.
SupportsMultiModalEmbeddings
¶
SupportsMultiModalPruning
¶
Bases: Protocol
The interface required for models that support returning both input embeddings and positions. Model may require custom positions for dynamic pruning of multimodal embeddings.
Methods:
-
recompute_mrope_positions–Update part of input mrope positions (starting with
Attributes:
-
supported_video_pruning_methods(tuple[VideoPruningMethod, ...]) –Video pruning methods (as reported by
supported_video_pruning_methods = ('evs',)
class-attribute
¶
Video pruning methods (as reported by
MultiModalConfig.get_video_pruning_spec) implemented by this model.
Models supporting methods beyond EVS should override this.
recompute_mrope_positions(input_ids, multimodal_embeddings, mrope_positions, num_computed_tokens)
¶
Update part of input mrope positions (starting with num_computed_tokens index). Original mrope_positions are computed for unpruned sequence and becomes incorrect once pruning occurs, so once we prune media tokens we should reflect this in the mrope_positions before we feed it to LLM.
Parameters:
-
(input_ids¶list[int] | Tensor) –(N,) All input tokens of the prompt containing entire sequence. Either a host-side list or an already device-resident tensor.
-
(multimodal_embeddings¶Sequence[Tensor]) –Sequence of multimodal embeddings that fits into the prefill chunk that is being processed.
-
(mrope_positions¶LongTensor) –Existing mrope positions (3, N) for entire sequence
-
(num_computed_tokens¶int) –A number of computed tokens so far.
Returns:
SupportsPP
¶
Bases: Protocol
The interface required for all models that support pipeline parallel.
Methods:
-
forward–Accept
IntermediateTensorswhen
Attributes:
-
make_empty_intermediate_tensors(_MakeEmptyIntermediateTensors) –Called when PP rank > 0 for profiling purposes.
-
supports_pp(Literal[True]) –A flag that indicates this model supports pipeline parallel.
make_empty_intermediate_tensors
instance-attribute
¶
Called when PP rank > 0 for profiling purposes.
supports_pp = True
class-attribute
¶
A flag that indicates this model supports pipeline parallel.
Note
There is no need to redefine this flag if this class is in the MRO of your model class.
forward(input_ids, positions, *, intermediate_tensors)
¶
Accept IntermediateTensors when
PP rank > 0.
Return IntermediateTensors only
for the last PP rank.
SupportsQuant
¶
SupportsRealtime
¶
Bases: Protocol
The interface required for all models that support transcription.
Attributes:
-
realtime_max_tokens(int) –Maximum tokens to generate per streaming audio segment.
realtime_max_tokens = 1
class-attribute
¶
Maximum tokens to generate per streaming audio segment. Override in subclasses based on the model's expected output length.
SupportsReplaySSM
¶
Bases: Protocol
The interface for models whose recurrent layers support ReplaySSM cached decode.
This is currently experimental.
SupportsScoreTemplate
¶
Bases: Protocol
The interface required for all models that support score template.
Methods:
-
get_score_template–Generate a full prompt by populating the score template with query and document content.
-
post_process_tokens–Perform architecture-specific manipulations on the input tokens.
Attributes:
-
supports_score_template(Literal[True]) –A flag that indicates this model supports score template.
supports_score_template = True
class-attribute
¶
A flag that indicates this model supports score template.
Note
There is no need to redefine this flag if this class is in the MRO of your model class.
get_score_template(query, document)
classmethod
¶
Generate a full prompt by populating the score template with query and document content.
post_process_tokens(prompt)
classmethod
¶
Perform architecture-specific manipulations on the input tokens.
SupportsTranscription
¶
Bases: Protocol
The interface required for all models that support transcription.
Methods:
-
get_generation_prompt–Get the prompt for the ASR model.
-
get_language_detection_prompt–Return a prompt that triggers language detection.
-
get_language_token_ids–Return token IDs that represent valid language tokens.
-
get_num_audio_tokens–Map from audio duration to number of audio tokens produced by the ASR
-
get_speech_to_text_config–Get the speech to text config for the ASR model.
-
get_streaming_diarized_parser_cls–Return a stateful parser class for streamed
diarized_jsonoutput. -
get_streaming_post_processor_cls–Return a stateful post-processor class for streaming output deltas.
-
parse_diarized_transcript–Parse the model-specific diarized transcript format.
-
parse_language_detection_output–Parse the detected language from model output token IDs.
-
post_process_output–Post-process the raw model output text.
-
validate_language–Ensure the language specified in the transcription request
Attributes:
-
no_space_languages(set[str]) –Languages that don't need a space between words.
-
supports_diarized_transcription(bool) –Enables the
diarized_jsonresponse format for the model. -
supports_explicit_language_detection(bool) –Transcription models that require an explicit language detection step
-
supports_segment_timestamp(bool) –Enables the segment timestamp option for supported models by setting this to
True. -
supports_transcription_only(bool) –Transcription models can opt out of text generation by setting this to
no_space_languages = {'ja', 'zh'}
class-attribute
¶
Languages that don't need a space between words. For example, Japanese (ja) and Chinese (zh) don't need a space between words.
supports_diarized_transcription = False
class-attribute
¶
Enables the diarized_json response format for the model.
supports_explicit_language_detection = False
class-attribute
¶
Transcription models that require an explicit language detection step
(e.g. Whisper needs a separate forward pass to predict the language
token) should set this to True and implement
get_language_detection_prompt and
parse_language_detection_output and
get_language_token_ids.
supports_segment_timestamp = False
class-attribute
¶
Enables the segment timestamp option for supported models by setting this to True.
supports_transcription_only = False
class-attribute
¶
Transcription models can opt out of text generation by setting this to
True.
get_generation_prompt(stt_params)
classmethod
¶
Get the prompt for the ASR model. The model has control over the construction, as long as it returns a valid PromptType.
get_language_detection_prompt(audio, stt_config)
classmethod
¶
Return a prompt that triggers language detection.
Only needs to be implemented when
supports_explicit_language_detection is True.
get_language_token_ids(tokenizer)
classmethod
¶
Return token IDs that represent valid language tokens.
Used to constrain language detection to only produce valid language tokens.
Only needs to be implemented when
supports_explicit_language_detection is True.
get_num_audio_tokens(audio_duration_s, stt_config, model_config)
classmethod
¶
Map from audio duration to number of audio tokens produced by the ASR model, without running a forward pass. This is used for estimating the amount of processing for this audio.
get_speech_to_text_config(model_config, task_type)
classmethod
¶
Get the speech to text config for the ASR model.
get_streaming_diarized_parser_cls()
classmethod
¶
Return a stateful parser class for streamed diarized_json output.
The default sends all segments once the output is complete. Models whose output marks where each segment ends can return a parser that sends each segment as soon as it is final.
get_streaming_post_processor_cls()
classmethod
¶
Return a stateful post-processor class for streaming output deltas.
Each instance receives the next decoded text delta and whether the request output is final. It returns the cleaned delta that should be sent to the client.
parse_diarized_transcript(text, model_config)
classmethod
¶
Parse the model-specific diarized transcript format.
Receives the raw decoded output of one audio chunk, without
post_process_output applied, and returns timestamps relative to that
chunk. Only models that set supports_diarized_transcription must
override this method.
parse_language_detection_output(token_ids, tokenizer)
classmethod
¶
Parse the detected language from model output token IDs.
Only needs to be implemented when
supports_explicit_language_detection is True.
post_process_output(text, model_config)
classmethod
¶
Post-process the raw model output text.
Some ASR models output structured formats (e.g., language tags, special tokens) that need to be stripped before returning to the user.
Parameters:
-
(text¶str) –Raw decoded text from the model.
-
(model_config¶ModelConfig) –The config of the model.
Returns:
-
str–Cleaned transcription text.
validate_language(language)
classmethod
¶
Ensure the language specified in the transcription request is a valid ISO 639-1 language code. If the request language is valid, but not natively supported by the model, trigger a warning (but not an exception).
_require_is_multimodal(is_multimodal)
¶
A helper function to be used in the context of vllm.model_executor.models.interfaces.SupportsMultiModal.embed_input_ids to provide a better error message.
get_eagle_decoder(model)
¶
The decoder of model that takes the aux hidden states, if any.
get_mixture_of_experts_model(model)
¶
Return the MixtureOfExperts contained within an arbitrary model.
- If the model itself is a MixtureOfExperts, return the model directly.
- If the model is a multi-modal model, and its
language_modelis a MixtureOfExperts, return thelanguage_model. - If neither, return None.
Parameters:
Returns:
-
MixtureOfExperts | None–The MixtureOfExperts instance contained within the model, or None.