Skip to content

vllm.multimodal.encoder_budget

Classes:

  • MultiModalBudget –

    Helper class to calculate budget information for multi-modal models.

Functions:

MultiModalBudget

Helper class to calculate budget information for multi-modal models.

Source code in vllm/multimodal/encoder_budget.py
class MultiModalBudget:
    """Helper class to calculate budget information for multi-modal models."""

    def __init__(
        self,
        vllm_config: VllmConfig,
        mm_registry: MultiModalRegistry,
        *,
        enable_cache: bool = True,
    ) -> None:
        super().__init__()

        self.model_config = model_config = vllm_config.model_config
        self.scheduler_config = scheduler_config = vllm_config.scheduler_config

        self.max_model_len = model_config.max_model_len
        self.max_num_reqs = scheduler_config.max_num_seqs

        with set_default_torch_num_threads():  # Avoid hang during startup
            cache = (
                processor_only_cache_from_config(vllm_config) if enable_cache else None
            )
            processor = mm_registry.create_processor(model_config)

            self.cache = cache
            self.processor = processor
            mm_config = model_config.get_multimodal_config()

            supported_mm_limits = processor.info.supported_mm_limits
            self.mm_limits = mm_limits = processor.info.allowed_mm_limits

            # Modalities that pass through the MM encoder tower
            tower_modalities = {
                modality
                for modality in supported_mm_limits
                if mm_limits.get(modality, 0) > 0
            }
            # Modalities that bypass the tower (pre-computed embeddings only)
            embed_only_modalities = {
                modality
                for modality in supported_mm_limits
                if mm_limits.get(modality, 0) == 0
                and mm_config is not None
                and mm_config.is_mm_embeds_enabled(modality)
            }

            active_modalities = tower_modalities | embed_only_modalities

            all_mm_max_toks_per_item = get_mm_max_toks_per_item(
                processor,
                cache=cache,
                mm_counts=dict.fromkeys(active_modalities, 1),
            )

        if embed_only_modalities:
            logger.info_once(
                "enable_mm_embeds is True; modalities handled as embedding-only: %s",
                tuple(embed_only_modalities),
            )

        # Some models (e.g., Qwen3Omni with use_audio_in_video=True) share
        # placeholders between modalities, so not all active modalities will
        # have their own entry in the returned dict. We filter to only include
        # modalities that have independent placeholder tokens.
        active_mm_max_toks_per_item = {
            modality: all_mm_max_toks_per_item[modality]
            for modality in active_modalities
            if modality in all_mm_max_toks_per_item
        }
        tower_mm_max_toks_per_item = {
            modality: active_mm_max_toks_per_item[modality]
            for modality in tower_modalities
            if modality in active_mm_max_toks_per_item
        }

        # Encoder budget is computed from all active modalities (including
        # embedding-only ones that need encoder cache space).
        encoder_compute_budget, encoder_cache_size = compute_mm_encoder_budget(
            scheduler_config,
            active_mm_max_toks_per_item,
        )

        self.encoder_compute_budget = encoder_compute_budget
        self.encoder_cache_size = encoder_cache_size

        mm_max_items_per_prompt = dict[str, int]()
        mm_max_items_per_batch = dict[str, int]()

        # Per-prompt/per-batch limits are only relevant for tower modalities
        # (embedding-only modalities don't go through the encoder tower).
        for modality, max_toks_per_item in tower_mm_max_toks_per_item.items():
            (
                mm_max_items_per_prompt[modality],
                mm_max_items_per_batch[modality],
            ) = self._get_max_items(modality, max_toks_per_item)

        self.mm_max_toks_per_item = tower_mm_max_toks_per_item
        self.mm_max_items_per_prompt: Mapping[str, int] = mm_max_items_per_prompt
        self.mm_max_items_per_batch: Mapping[str, int] = mm_max_items_per_batch

    def _get_max_items(
        self,
        modality: str,
        max_tokens_per_item: int,
    ) -> tuple[int, int]:
        if max_tokens_per_item == 0:
            return 0, 0

        # Check how many items of this modality can be supported by
        # the encoder budget.
        if (encoder_budget := self.get_encoder_budget()) == 0:
            return 0, 0

        max_encoder_items_per_batch = encoder_budget // max_tokens_per_item

        # Check how many items of this modality can be supported by
        # the decoder budget.
        mm_limit = self.mm_limits[modality]

        max_items_per_prompt = max(
            1,
            min(mm_limit, self.max_model_len // max_tokens_per_item),
        )

        scheduler_config = self.scheduler_config
        max_num_reqs = self.max_num_reqs

        if not scheduler_config.enable_chunked_prefill:
            max_num_reqs = min(
                max_num_reqs,
                scheduler_config.max_num_batched_tokens // max_tokens_per_item,
            )

        max_decoder_items_per_batch = max_num_reqs * max_items_per_prompt

        max_items_per_batch = max(
            1,
            min(max_encoder_items_per_batch, max_decoder_items_per_batch),
        )

        return max_items_per_prompt, max_items_per_batch

    def get_modality_with_max_tokens(self) -> str:
        mm_max_toks_per_item = self.mm_max_toks_per_item
        modality, _ = max(mm_max_toks_per_item.items(), key=lambda x: (x[1], x[0]))

        return modality

    def get_encoder_budget(self) -> int:
        return min(self.encoder_compute_budget, self.encoder_cache_size)

    def get_dummy_encoder_profile_inputs(
        self,
        modality: str | None = None,
        max_items_per_batch: int | None = None,
    ) -> list[tuple[str, MultiModalKwargsItem]]:
        if self.get_encoder_budget() <= 0 or not self.mm_max_toks_per_item:
            return []

        if modality is None:
            modality = self.get_modality_with_max_tokens()
        if max_items_per_batch is None:
            max_items_per_batch = self.mm_max_items_per_batch[modality]

        num_profile_items = max(self.mm_max_items_per_batch[modality], 1)
        # Don't use `max_items_per_batch` here to avoid redundant computation
        dummy_mm_inputs = self.processor.get_dummy_mm_inputs(
            mm_counts={modality: 1},
            cache=self.cache,
            seq_len=self.processor.info.get_dummy_seq_len(
                self.max_model_len, self.get_encoder_budget() // num_profile_items
            ),
        )
        dummy_mm_item = dummy_mm_inputs["mm_kwargs"][modality][0]

        # We use the cache so that the item is saved to the cache,
        # but not read from the cache
        assert dummy_mm_item is not None, "Item should not already be cached"

        return [(modality, dummy_mm_item)] * max_items_per_batch

    def get_dummy_encoder_profile_single_input(
        self,
        dummy_mm_inputs: list[tuple[str, MultiModalKwargsItem]],
    ) -> list[tuple[str, MultiModalKwargsItem]]:
        if not dummy_mm_inputs:
            return []

        modality, dummy_mm_item = dummy_mm_inputs[0]
        num_profile_items = max(self.mm_max_items_per_batch[modality], 1)
        encoder_budget = self.get_encoder_budget()
        info = self.processor.info
        seq_len = info.get_dummy_seq_len(self.max_model_len, encoder_budget)
        if num_profile_items == 1 or seq_len == info.get_dummy_seq_len(
            self.max_model_len, encoder_budget // num_profile_items
        ):
            return []

        single_item = self.processor.get_dummy_mm_inputs(
            mm_counts={modality: 1}, seq_len=seq_len
        )["mm_kwargs"][modality][0]
        assert single_item is not None
        shapes = [
            json_map_leaves(
                lambda value: getattr(value, "shape", value), item.get_data()
            )
            for item in (dummy_mm_item, single_item)
        ]
        if shapes[0] == shapes[1]:
            return []

        return [(modality, single_item)]

    def get_dummy_encoder_profile_modality_inputs(
        self,
        dummy_mm_inputs: list[tuple[str, MultiModalKwargsItem]],
    ) -> list[list[tuple[str, MultiModalKwargsItem]]]:
        if not dummy_mm_inputs:
            return []

        modalities = self.processor.info.get_extra_profiled_modalities(
            tuple(self.mm_max_toks_per_item)
        )
        profiles = []
        for modality in modalities:
            if (
                modality == dummy_mm_inputs[0][0]
                or self.mm_max_items_per_batch.get(modality, 0) <= 0
            ):
                continue
            split_inputs = self.get_dummy_encoder_profile_inputs(modality)
            profiles.append(split_inputs)
            if single_input := self.get_dummy_encoder_profile_single_input(
                split_inputs
            ):
                profiles.append(single_input)
        return profiles

    def reset_cache(self) -> None:
        if self.cache is not None:
            self.cache.clear_cache()

get_mm_max_toks_per_item(processor, mm_counts, cache)

Get the maximum number of tokens per data item from each modality based on underlying model configuration.

Source code in vllm/multimodal/encoder_budget.py
def get_mm_max_toks_per_item(
    processor: BaseMultiModalProcessor,
    mm_counts: Mapping[str, int],
    cache: BaseMultiModalProcessorCache | None,
) -> Mapping[str, int]:
    """Get the maximum number of tokens per data item from each modality based
    on underlying model configuration.
    """
    max_tokens_per_item = processor.info.get_mm_max_tokens_per_item(
        seq_len=processor.info.ctx.model_config.max_model_len,
        mm_counts=mm_counts,
    )
    if max_tokens_per_item is not None:
        return max_tokens_per_item

    mm_inputs = processor.get_dummy_mm_inputs(mm_counts, cache=cache)

    return {
        modality: sum(item.get_num_embeds() for item in placeholders)
        for modality, placeholders in mm_inputs["mm_placeholders"].items()
    }