Skip to content

vllm.model_executor.models.minicpmv

Inference-only MiniCPM-V model compatible with HuggingFace weights.

Classes:

MiniCPMV

Bases: MiniCPMVBaseModel, SupportsMultiModal, SupportsLoRA

Different versions of MiniCPMV use different visual encoders and LLMs, which is not conducive to the current integration logic of LoRA and bitsandbytes in vLLM. Therefore, it is necessary to separate them.

Source code in vllm/model_executor/models/minicpmv.py
@MULTIMODAL_REGISTRY.register_processor(
    MiniCPMVMultiModalProcessor,
    info=MiniCPMVProcessingInfo,
    dummy_inputs=MiniCPMVDummyInputsBuilder,
)
class MiniCPMV(MiniCPMVBaseModel, SupportsMultiModal, SupportsLoRA):
    """
    Different versions of MiniCPMV use different visual encoders and LLMs,
    which is not conducive to the current integration logic of LoRA and
    bitsandbytes in vLLM. Therefore, it is necessary to separate them.
    """

    def __new__(cls, *, vllm_config: VllmConfig, prefix: str = ""):
        config = vllm_config.model_config.hf_config
        version_values: tuple[int, ...]
        if not hasattr(config, "version"):
            if config.hidden_size == 2304 and config.query_num == 64:
                version_values = (2, 0)
            else:
                version_values = (2, 5)
        else:
            version_values = tuple(int(x) for x in str(config.version).split("."))
        # Dispatch class based on version
        if len(version_values) == 2:
            version_key = (version_values[0], version_values[1])
            instance_cls = _SUPPORT_VERSION.get(version_key)
        else:
            instance_cls = None
        if instance_cls is None:
            supported_versions = ", ".join(
                [f"{v[0]}.{v[1]}" for v in sorted(_SUPPORT_VERSION.keys())]
            )
            raise ValueError(
                f"Currently, MiniCPMV only supports versions "
                f"{supported_versions}. Got version: {version_values}"
            )

        # quant_config references base class members,
        # so update values before init is called
        cls.packed_modules_mapping.update(instance_cls.packed_modules_mapping)
        cls.embedding_modules.update(instance_cls.embedding_modules)
        return instance_cls(vllm_config=vllm_config, prefix=prefix)

MiniCPMVBaseModel

Bases: Module, SupportsMultiModal, SupportsPP

The abstract class of MiniCPMV can only be inherited, but cannot be instantiated.

Methods:

Source code in vllm/model_executor/models/minicpmv.py
class MiniCPMVBaseModel(nn.Module, SupportsMultiModal, SupportsPP):
    """
    The abstract class of MiniCPMV can only be inherited, but cannot be
    instantiated.
    """

    supports_encoder_tp_data = True

    @classmethod
    def get_placeholder_str(cls, modality: str, i: int) -> str | None:
        if modality.startswith("image"):
            return "(<image>./</image>)"
        if modality.startswith("video"):
            return "(<video>./</video>)"

        raise ValueError("Only image or video modality is supported")

    def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
        config = vllm_config.model_config.hf_config
        multimodal_config = vllm_config.model_config.multimodal_config
        assert multimodal_config is not None
        quant_config = vllm_config.quant_config
        self.use_data_parallel = multimodal_config.mm_encoder_tp_mode == "data"
        super().__init__()
        # All MiniCPM-V models disable `tie_word_embeddings` but
        # `PretrainedConfig.tie_word_embeddings` defaults to True; we cannot
        # check `tie_word_embeddings` until vLLM integrate MiniCPM-V model
        # and config class
        self.config = config
        self.multimodal_config = multimodal_config
        self.vllm_config = vllm_config

        self.version = get_version_by_config(self.config)

        with self._mark_language_model(vllm_config):
            self.llm = self.init_llm(
                vllm_config=vllm_config, prefix=maybe_prefix(prefix, "llm")
            )

        with self._mark_tower_model(vllm_config, {"image", "video"}):
            self.vpm = self.init_vision_module(
                config, quant_config, prefix=maybe_prefix(prefix, "vpm")
            )
            self.vision_dim = (
                self.vpm.embed_dim
                if self.version == (2, 0)
                else self.vpm.embeddings.embed_dim
            )
            self.embed_dim = self.config.hidden_size

            self.resampler = self.init_resampler(
                self.embed_dim,
                self.vision_dim,
                quant_config=quant_config,
                prefix=maybe_prefix(prefix, "resampler"),
            )
            self._resampler_moved = False

        self.make_empty_intermediate_tensors = self.llm.make_empty_intermediate_tensors

    def _ensure_resampler_device(self) -> None:
        if self._resampler_moved:
            return
        # Only move device, DO NOT touch dtype (fp8 quant needs its own dtype)
        self.resampler.to(current_platform.device_type)
        self._resampler_moved = True

    def _parse_and_validate_vision_input(
        self,
        modality: str,
        **kwargs: object,
    ) -> MiniCPMVImageInputs | None:
        pixel_values = kwargs.pop("pixel_values", None)
        image_embeds = kwargs.pop("image_embeds", None)

        if pixel_values is None and image_embeds is None:
            return None

        if image_embeds is not None:
            return MiniCPMVImageEmbeddingInputs(
                type="image_embeds",
                image_embeds=image_embeds,
            )

        assert is_list_of(pixel_values, list, check="all")
        pixel_values_list: list[list[torch.Tensor]] = []
        for pixel_value in pixel_values:
            assert is_list_of(pixel_value, torch.Tensor, check="all")
            pixel_values_list.append(pixel_value)
        tgt_sizes = kwargs.pop("tgt_sizes")

        num_slices_flat = torch.tensor([len(ps) for ps in pixel_values_list])
        pixel_values_flat = flatten_2d_lists(pixel_values_list)
        tgt_sizes_flat = flatten_bn(tgt_sizes, concat=True)

        return MiniCPMVImagePixelInputs(
            type="pixel_values",
            pixel_values=pixel_values_flat,
            tgt_sizes=tgt_sizes_flat,
            num_slices=num_slices_flat,
        )

    def _parse_and_validate_multimodal_inputs(
        self, **kwargs: object
    ) -> MiniCPMVMultiModalInputs:
        kwargs.pop("modality", None)
        modalities: MiniCPMVMultiModalInputs = {}

        # Preserve the order of modalities if there are multiple of them
        # from the order of kwargs.
        for input_key in kwargs:
            if (
                input_key in ("pixel_values", "image_embeds")
                and "images" not in modalities
            ):
                modalities["images"] = self._parse_and_validate_vision_input(
                    "images", **kwargs
                )
            if (
                input_key in ("video_pixel_values", "video_embeds")
                and "videos" not in modalities
            ):
                modalities["videos"] = self._parse_and_validate_vision_input(
                    "videos", **_image_kwargs_from_video(kwargs)
                )

        return modalities

    def _process_vision_input(
        self,
        image_input: MiniCPMVImageInputs,
    ) -> torch.Tensor | list[torch.Tensor] | tuple[torch.Tensor, ...]:
        if image_input["type"] == "image_embeds":
            return image_input["image_embeds"]

        assert isinstance(image_input, MiniCPMVImagePixelInputs)
        image_features_flat = self.get_vision_hidden_states(image_input)

        num_slices = image_input["num_slices"]
        return [e.flatten(0, 1) for e in image_features_flat.split(num_slices.tolist())]

    def _process_multimodal_inputs(self, modalities: MiniCPMVMultiModalInputs):
        # The result multimodal_embeddings is tuple of tensors, with each
        # tensor corresponding to a multimodal data item (image or video).
        multimodal_embeddings: tuple[torch.Tensor, ...] = ()

        # NOTE: It is important to iterate over the keys in this dictionary
        # to preserve the order of the modalities.
        for modality in modalities:
            if modality == "images":
                image_input = modalities["images"]
                assert image_input is not None
                image_embeddings = self._process_vision_input(image_input)
                multimodal_embeddings += tuple(image_embeddings)
            if modality == "videos":
                video_input = modalities["videos"]
                assert video_input is not None
                video_embeddings = self._process_vision_input(video_input)
                multimodal_embeddings += tuple(video_embeddings)

        return multimodal_embeddings

    def embed_multimodal(self, **kwargs: object) -> MultiModalEmbeddings:
        modalities = self._parse_and_validate_multimodal_inputs(**kwargs)
        if not modalities:
            return []

        return self._process_multimodal_inputs(modalities)

    def forward(
        self,
        input_ids: torch.Tensor | None,
        positions: torch.Tensor,
        intermediate_tensors: IntermediateTensors | None = None,
        inputs_embeds: torch.Tensor | None = None,
        **kwargs: Any,
    ) -> torch.Tensor:
        if intermediate_tensors is not None:
            inputs_embeds = None

        hidden_states = self.llm.model(
            input_ids=input_ids,
            positions=positions,
            intermediate_tensors=intermediate_tensors,
            inputs_embeds=inputs_embeds,
        )
        return hidden_states

    def compute_logits(
        self,
        hidden_states: torch.Tensor,
    ) -> torch.Tensor | None:
        return self.llm.compute_logits(hidden_states)

    def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
        loader = AutoWeightsLoader(self)
        loaded = loader.load_weights(weights)
        self._ensure_resampler_device()
        return loaded

    def get_mm_mapping(self) -> MultiModelKeys:
        """
        Get the module prefix in multimodal models
        """
        return MultiModelKeys.from_string_field(
            language_model="llm", connector="resampler", tower_model="vpm"
        )

    def init_llm(
        self,
        vllm_config: VllmConfig,
        prefix: str = "",
    ) -> nn.Module:
        raise NotImplementedError

    def init_vision_module(
        self,
        config: PretrainedConfig,
        quant_config: QuantizationConfig | None,
        prefix: str = "",
    ) -> nn.Module:
        raise NotImplementedError

    def init_resampler(
        self,
        embed_dim: int,
        vision_dim: int,
        quant_config: QuantizationConfig | None = None,
        prefix: str = "",
    ) -> nn.Module:
        raise NotImplementedError

    def get_vision_hidden_states(self, data: MiniCPMVImagePixelInputs) -> torch.Tensor:
        raise NotImplementedError

get_mm_mapping()

Get the module prefix in multimodal models

Source code in vllm/model_executor/models/minicpmv.py
def get_mm_mapping(self) -> MultiModelKeys:
    """
    Get the module prefix in multimodal models
    """
    return MultiModelKeys.from_string_field(
        language_model="llm", connector="resampler", tower_model="vpm"
    )

MiniCPMVImageEmbeddingInputs

Bases: TensorSchema

Dimensions
  • bn: Batch size * number of images
  • ns: Number of slices
  • hs: Hidden size (must match language model backbone)
Source code in vllm/model_executor/models/minicpmv.py
class MiniCPMVImageEmbeddingInputs(TensorSchema):
    """
    Dimensions:
        - bn: Batch size * number of images
        - ns: Number of slices
        - hs: Hidden size (must match language model backbone)
    """

    type: Literal["image_embeds"]
    image_embeds: Annotated[
        torch.Tensor | list[torch.Tensor],
        TensorShape("bn", "ns", "hs", dynamic_dims={"ns"}),
    ]

MiniCPMVImagePixelInputs

Bases: TensorSchema

Dimensions
  • bns: Batch size * number of images * number of slices
  • bn: Batch size * number of images
  • c: Number of channels
  • h: Height
  • w: Width
Source code in vllm/model_executor/models/minicpmv.py
class MiniCPMVImagePixelInputs(TensorSchema):
    """
    Dimensions:
        - bns: Batch size * number of images * number of slices
        - bn: Batch size * number of images
        - c: Number of channels
        - h: Height
        - w: Width
    """

    type: Literal["pixel_values"] = "pixel_values"

    # Note that the patch size may vary, so we pass it as a list instead of a
    # batched tensor.
    pixel_values: Annotated[
        list[torch.Tensor],
        TensorShape("bns", "c", "h", "w", dynamic_dims={"h", "w"}),
    ]
    tgt_sizes: Annotated[
        torch.Tensor,
        TensorShape("bns", 2),  # This should be in `(height, width)` format.
    ]
    num_slices: Annotated[
        torch.Tensor,
        TensorShape("bn"),
    ]

MiniCPMVMultiModalProcessor

Bases: BaseMultiModalProcessor[_I]

Source code in vllm/model_executor/models/minicpmv.py
class MiniCPMVMultiModalProcessor(BaseMultiModalProcessor[_I]):
    def get_image_prompt_texts(self, image_size: ImageSize, image_idx: int = 0) -> str:
        return self.info.get_slice_image_placeholder(
            image_size,
            image_idx=image_idx,
        )

    def get_video_prompt_texts(self, image_size: ImageSize, num_frames: int) -> str:
        return (
            self.info.get_slice_image_placeholder(
                image_size=image_size,
                image_idx=0,
                max_slice_nums=self.info.get_video_max_slice_num(),
                use_image_id=False,
            )
            * num_frames
        )

    def process_images(
        self,
        mm_data: Mapping[str, object],
        mm_kwargs: Mapping[str, object],
    ) -> Mapping[str, NestedTensors]:
        if (images := mm_data.get("images")) is None:
            return {}

        mm_items = self.info.parse_mm_data({"image": images}, validate=False)
        parsed_images = mm_items.get_items(
            "image", (MiniCPMVImageEmbeddingItems, ImageProcessorItems)
        )

        if isinstance(parsed_images, MiniCPMVImageEmbeddingItems):
            image_inputs = {}
        else:
            image_inputs = self._call_hf_processor_on_prompts(
                prompts=[self.info.image_pattern] * len(parsed_images),
                mm_data={"images": [[image] for image in parsed_images]},
                mm_kwargs=mm_kwargs,
                out_keys={"pixel_values", "image_sizes", "tgt_sizes"},
            )

        return image_inputs

    def process_videos(
        self,
        mm_data: Mapping[str, object],
        mm_kwargs: Mapping[str, object],
    ) -> Mapping[str, NestedTensors]:
        if (videos := mm_data.get("videos")) is None:
            return {}

        mm_items = self.info.parse_mm_data({"video": videos}, validate=False)
        parsed_videos = mm_items.get_items(
            "video", (MiniCPMVVideoEmbeddingItems, VideoProcessorItems)
        )

        if isinstance(parsed_videos, MiniCPMVVideoEmbeddingItems):
            video_inputs = {}
        else:
            video_inputs = self._call_hf_processor_on_prompts(
                prompts=[
                    self.info.image_pattern * len(video) for video in parsed_videos
                ],
                mm_data={"images": list(parsed_videos)},
                mm_kwargs={
                    **mm_kwargs,
                    "max_slice_nums": self.info.get_video_max_slice_num(),
                },
                out_keys={"pixel_values", "image_sizes", "tgt_sizes"},
            )

        video_inputs = {f"video_{k}": v for k, v in video_inputs.items()}

        return video_inputs

    def process_mm_inputs(
        self,
        mm_data: Mapping[str, object],
        mm_kwargs: Mapping[str, object],
    ) -> Mapping[str, NestedTensors]:
        return {
            **self.process_images(mm_data, mm_kwargs),
            **self.process_videos(mm_data, mm_kwargs),
        }

    def _apply_prompt_updates(
        self,
        token_ids: list[int],
        mm_prompt_updates: MultiModalPromptUpdates,
    ) -> tuple[list[int], Mapping[str, list[PlaceholderFeaturesInfo]]]:
        """Apply multi-modal prompt updates to token IDs."""
        new_token_ids, match_result = self._apply_token_matches(
            token_ids,
            mm_prompt_updates,
        )

        # If the target does not consist of special tokens, it may be
        # tokenized differently inside the prompt, so fall back to
        # performing the updates on the decoded text, then encoding the
        # result back. The segments are encoded separately to avoid BPE
        # merges across segment boundaries.
        if not all(
            all(update_idx is not None for update_idx in update_idxs)
            for update_idxs in match_result.values()
        ):
            new_token_ids, match_result = self._apply_prompt_updates_via_text(
                token_ids,
                mm_prompt_updates,
                encode_segments_separately=True,
            )

        matched_updates = defaultdict[str, list[Sequence[ResolvedPromptUpdate]]](list)
        for modality, update_idxs in match_result.items():
            for item_idx, update_idx in enumerate(update_idxs):
                assert update_idx is not None, (
                    "Failed to apply prompt replacement for "
                    f"mm_items[{modality!r}][{item_idx}]"
                )

                matched_updates[modality].append(
                    [mm_prompt_updates[modality][item_idx][update_idx]]
                )

        placeholders = self._find_mm_placeholders(
            new_token_ids,
            dict(matched_updates),
        )

        return new_token_ids, placeholders

    def _call_hf_processor_on_prompts(
        self,
        prompts: list[str],
        mm_data: Mapping[str, Sequence[object]],
        mm_kwargs: Mapping[str, object],
        *,
        out_keys: set[str],
    ) -> dict[str, NestedTensors]:
        # This processor supports zipping prompt and mm_data together
        if self.info.get_model_version() in {(2, 6), (4, 0), (4, 5), (4, 6)}:
            inputs = self.info.ctx.call_hf_processor(
                self.info.get_hf_processor(**mm_kwargs),
                dict(text=prompts, **mm_data),
                mm_kwargs,
            )
        else:
            inputs = defaultdict[str, list[torch.Tensor]](list)

            for i, prompt in enumerate(prompts):
                inputs_one = self.info.ctx.call_hf_processor(
                    self.info.get_hf_processor(**mm_kwargs),
                    dict(text=prompt, **{k: v[i] for k, v in mm_data.items()}),
                    mm_kwargs,
                )

                for k, v in inputs_one.items():
                    assert len(v) == 1, (k, len(v))
                    inputs[k].append(v[0])

        return {k: inputs[k] for k in out_keys}

    def _apply_hf_processor_main(
        self,
        mm_items: MultiModalDataItems,
        hf_processor_mm_kwargs: Mapping[str, object],
    ) -> BatchFeature:
        valid_mm_items = mm_items.select(
            {k for k, c in mm_items.get_all_counts().items() if c > 0}
        )
        mm_data, passthrough_data = self._get_hf_mm_data(valid_mm_items)

        prompt_text = self.dummy_inputs.get_dummy_text(mm_items.get_all_counts())

        tokenizer = self.info.get_tokenizer()

        input_ids = torch.tensor([tokenizer.encode(prompt_text)])
        mm_inputs = self.process_mm_inputs(mm_data, hf_processor_mm_kwargs)

        processed_data = BatchFeature(
            {
                "input_ids": input_ids,
                **mm_inputs,
            }
        )
        processed_data.update(passthrough_data)
        return processed_data

    def _get_prompt_updates(
        self,
        mm_items: MultiModalDataItems,
        hf_processor_mm_kwargs: Mapping[str, object],
        out_mm_kwargs: MultiModalKwargsItems,
    ) -> Sequence[PromptUpdate]:
        placeholders = [
            ("image", self.info.image_pattern),
            ("video", self.info.video_pattern),
        ]

        # hard code for inconsistency of encode-decode image_pattern
        additional_placeholders = []
        tokenizer = self.info.get_tokenizer()
        for modality, pattern in placeholders:
            sub_pattern = tokenizer.decode(
                cached_encode(tokenizer, pattern, add_special_tokens=False)
            )
            if sub_pattern != pattern:
                additional_placeholders.append((modality, sub_pattern))
        placeholders += additional_placeholders

        vocab = tokenizer.get_vocab()
        unk_token_ids = [vocab["<unk>"]]

        def get_image_replacement(item_idx: int):
            images = mm_items.get_items(
                "image", (MiniCPMVImageEmbeddingItems, ImageProcessorItems)
            )
            assert isinstance(
                images, (MiniCPMVImageEmbeddingItems, ImageProcessorItems)
            )

            image_size = images.get_image_size(item_idx)

            return PromptUpdateDetails.select_token_ids(
                cached_encode(
                    tokenizer,
                    self.get_image_prompt_texts(image_size, item_idx),
                    add_special_tokens=False,
                ),
                unk_token_ids,
            )

        def get_video_replacement(item_idx: int):
            videos = mm_items.get_items(
                "video", (MiniCPMVVideoEmbeddingItems, VideoProcessorItems)
            )
            assert isinstance(
                videos, (MiniCPMVVideoEmbeddingItems, VideoProcessorItems)
            )

            frame_size = videos.get_frame_size(item_idx)
            num_frames = videos.get_num_frames(item_idx)

            return PromptUpdateDetails.select_token_ids(
                cached_encode(
                    tokenizer,
                    self.get_video_prompt_texts(frame_size, num_frames),
                    add_special_tokens=False,
                ),
                unk_token_ids,
            )

        get_replacement = {
            "image": get_image_replacement,
            "video": get_video_replacement,
        }

        return [
            PromptReplacement(
                modality=modality,
                target=cached_encode(tokenizer, pattern, add_special_tokens=False),
                replacement=get_replacement[modality],
            )
            for modality, pattern in placeholders
        ]

    def _recompute_cached_prompt_update(
        self,
        cached_update: ResolvedPromptUpdate,
        new_item_idx: int,
    ) -> ResolvedPromptUpdate:
        new_update = super()._recompute_cached_prompt_update(
            cached_update,
            new_item_idx,
        )

        if cached_update.modality == "image":
            tokenizer = self.info.get_tokenizer()
            image_processor = self.info.get_image_processor()
            version = self.info.get_model_version()

            text = tokenizer.decode(cached_update.content.full)
            prev_item_idx = cached_update.item_idx

            if version == (2, 0) or version == (2, 5):
                im_start = image_processor.im_start_token
                im_end = image_processor.im_end_token
            elif hasattr(image_processor, "im_id_start"):
                im_start = image_processor.im_id_start
                im_end = image_processor.im_id_end
            else:
                # transformers v5.7+ keeps im_id tokens on the tokenizer.
                im_start = getattr(tokenizer, "image_id_start_token", "<image_id>")
                im_end = getattr(tokenizer, "image_id_end_token", "</image_id>")

            embed_text = getattr(tokenizer, "image_token", "<unk>")
            new_update = new_update.with_content(
                PromptUpdateDetails.select_token_ids(
                    cached_encode(
                        tokenizer,
                        text.replace(
                            f"{im_start}{prev_item_idx}{im_end}",
                            f"{im_start}{new_item_idx}{im_end}",
                            1,
                        ),
                        add_special_tokens=False,
                    ),
                    cached_encode(tokenizer, embed_text, add_special_tokens=False),
                )
            )

        return new_update

    def _get_mm_fields_config(
        self,
        hf_inputs: BatchFeature,
        hf_processor_mm_kwargs: Mapping[str, object],
    ) -> Mapping[str, MultiModalFieldConfig]:
        return _minicpmv_field_config(hf_inputs)

_apply_prompt_updates(token_ids, mm_prompt_updates)

Apply multi-modal prompt updates to token IDs.

Source code in vllm/model_executor/models/minicpmv.py
def _apply_prompt_updates(
    self,
    token_ids: list[int],
    mm_prompt_updates: MultiModalPromptUpdates,
) -> tuple[list[int], Mapping[str, list[PlaceholderFeaturesInfo]]]:
    """Apply multi-modal prompt updates to token IDs."""
    new_token_ids, match_result = self._apply_token_matches(
        token_ids,
        mm_prompt_updates,
    )

    # If the target does not consist of special tokens, it may be
    # tokenized differently inside the prompt, so fall back to
    # performing the updates on the decoded text, then encoding the
    # result back. The segments are encoded separately to avoid BPE
    # merges across segment boundaries.
    if not all(
        all(update_idx is not None for update_idx in update_idxs)
        for update_idxs in match_result.values()
    ):
        new_token_ids, match_result = self._apply_prompt_updates_via_text(
            token_ids,
            mm_prompt_updates,
            encode_segments_separately=True,
        )

    matched_updates = defaultdict[str, list[Sequence[ResolvedPromptUpdate]]](list)
    for modality, update_idxs in match_result.items():
        for item_idx, update_idx in enumerate(update_idxs):
            assert update_idx is not None, (
                "Failed to apply prompt replacement for "
                f"mm_items[{modality!r}][{item_idx}]"
            )

            matched_updates[modality].append(
                [mm_prompt_updates[modality][item_idx][update_idx]]
            )

    placeholders = self._find_mm_placeholders(
        new_token_ids,
        dict(matched_updates),
    )

    return new_token_ids, placeholders

Resampler4_5

Bases: Resampler2_5

Methods:

Source code in vllm/model_executor/models/minicpmv.py
class Resampler4_5(Resampler2_5):
    def __init__(
        self,
        num_queries: int,
        embed_dim: int,
        num_heads: int,
        kv_dim: int | None = None,
        norm_layer: Callable[[int], nn.LayerNorm] = DEFAULT_LN,
        max_size: tuple[int, int] = (70, 70),
        max_temporal_size: int = 36000,
        quant_config: QuantizationConfig | None = None,
        prefix: str = "",
    ) -> None:
        super().__init__(
            num_queries,
            embed_dim,
            num_heads,
            kv_dim,
            norm_layer,
            max_size,
            quant_config=quant_config,
            prefix=prefix,
        )

        trunc_normal_(self.query, std=0.02)
        self.max_temporal_size = max_temporal_size
        self._set_temporal_pos_cache(self.max_temporal_size)
        self.apply(self._init_weights)

    def get_1d_sincos_pos_embed_from_temporal_size(
        self, embed_dim: int, pos: np.ndarray
    ):
        """
        embed_dim: output dimension for each position
        pos: a list of positions to be encoded: size (M,)
        out: (M, D)
        """
        assert embed_dim % 2 == 0
        omega = np.arange(embed_dim // 2, dtype=np.float32)
        omega /= embed_dim / 2.0
        omega = 1.0 / 10000**omega  # (D/2,)

        pos = pos.reshape(-1)  # (M,)
        out = np.einsum("m,d->md", pos, omega)  # (M, D/2), outer product

        emb_sin = np.sin(out)  # (M, D/2)
        emb_cos = np.cos(out)  # (M, D/2)

        emb = np.concatenate([emb_sin, emb_cos], axis=1)  # (M, D)
        return emb

    def _set_temporal_pos_cache(
        self, max_temporal_size: int, device: torch.types.Device = "cpu"
    ) -> None:
        temporal_size = np.arange(max_temporal_size, dtype=np.float32)
        pos_embed = (
            torch.from_numpy(
                self.get_1d_sincos_pos_embed_from_temporal_size(
                    self.embed_dim, temporal_size
                )
            )
            .float()
            .to(device)
        )
        self.register_buffer("temporal_pos_embed", pos_embed, persistent=False)

    def _adjust_temporal_pos_cache(
        self, max_temporal_size: int, device: torch.types.Device = "cpu"
    ):
        if max_temporal_size > self.max_temporal_size:
            self.max_temporal_size = max_temporal_size
            self._set_temporal_pos_cache(self.max_temporal_size, device)

    def _init_weights(self, m: nn.Linear | nn.LayerNorm):
        if isinstance(m, nn.Linear):
            trunc_normal_(m.weight, std=0.02)
            if isinstance(m, nn.Linear) and m.bias is not None:
                nn.init.constant_(m.bias, 0)
        elif isinstance(m, nn.LayerNorm):
            nn.init.constant_(m.bias, 0)
            nn.init.constant_(m.weight, 1.0)

    def forward(
        self,
        x: torch.Tensor,
        tgt_sizes: torch.Tensor,
        # temporal_ids for high refresh rate videos
        temporal_ids=None,
    ) -> torch.Tensor:
        assert x.shape[0] == tgt_sizes.shape[0]
        bs = x.shape[0]

        device = x.device
        dtype = x.dtype

        patch_len = tgt_sizes[:, 0] * tgt_sizes[:, 1]

        self._adjust_pos_cache(tgt_sizes, device=device)

        temporal_pos_emb = False
        temporal_ids_flatten = None
        if temporal_ids is not None:
            # example: [[-1], [-1], [2, 6, 9]]
            temporal_ids_flatten = list(chain.from_iterable(temporal_ids))
            max_temporal_size = max(temporal_ids_flatten, default=0)
            if max_temporal_size > -1:
                temporal_pos_emb = True
            if max_temporal_size > self.max_temporal_size:
                self._adjust_temporal_pos_cache(max_temporal_size, device)

        max_patch_len = patch_len.max().item()
        assert isinstance(max_patch_len, int)

        key_padding_mask = torch.zeros(
            (bs, max_patch_len), dtype=torch.bool, device=device
        )

        x, _ = self.kv_proj(x)  # B * L * D
        x = self.ln_kv(x).permute(1, 0, 2)  # L * B * D
        q = self.ln_q(self.query)  # Q * D

        pos_embed_2d = []
        pos_embed_temporal = []
        for i in range(bs):
            tgt_h, tgt_w = tgt_sizes[i]
            if temporal_pos_emb:
                assert temporal_ids_flatten is not None
                if temporal_ids_flatten[i] == -1:
                    pos_embed_temporal.append(
                        torch.zeros(self.embed_dim, dtype=dtype, device=device)
                    )
                else:
                    pos_embed_temporal.append(
                        self.temporal_pos_embed[temporal_ids_flatten[i]].to(dtype)
                    )  # D

            pos_embed_2d.append(
                self.pos_embed[:tgt_h, :tgt_w, :]
                .reshape((tgt_h * tgt_w, -1))
                .to(device=device, dtype=dtype)
            )  # patches * D
            key_padding_mask[i, patch_len[i] :] = True

        pos_embed_2d = torch.nn.utils.rnn.pad_sequence(
            pos_embed_2d, batch_first=True, padding_value=0.0
        ).permute(1, 0, 2)  # BLD => L * B * D

        k = x + pos_embed_2d
        v = x
        if pos_embed_temporal:
            k += torch.stack(pos_embed_temporal, dim=0)
            bs = len(temporal_ids)
            merge_k = []
            merge_v = []
            merge_key_padding_mask = []

            start = 0
            for tp in temporal_ids:
                end = start + len(tp)
                # L * (end-start) * D -> (end-start) * L * D
                # -> 1 * L*(end-start) * D
                merge_k.append(
                    k[:, start:end, :].permute(1, 0, 2).reshape(-1, self.embed_dim)
                )
                merge_v.append(
                    v[:, start:end, :].permute(1, 0, 2).reshape(-1, self.embed_dim)
                )
                merge_key_padding_mask.append(
                    key_padding_mask[start:end, :].reshape(-1, 1)
                )

                start = end

            k = torch.nn.utils.rnn.pad_sequence(
                merge_k, batch_first=True, padding_value=0.0
            ).permute(1, 0, 2)  # L*(end-start)
            v = torch.nn.utils.rnn.pad_sequence(
                merge_v, batch_first=True, padding_value=0.0
            ).permute(1, 0, 2)  # L*(end-start)
            key_padding_mask = torch.nn.utils.rnn.pad_sequence(
                merge_key_padding_mask, batch_first=True, padding_value=True
            ).squeeze(-1)

        out = self.attn(
            self._repeat(q, bs),  # Q * B * D
            k,  # L * B * D +  L * B * D
            v,
            key_padding_mask=key_padding_mask,
        )[0]
        #  out: Q * B * D
        x = out.permute(1, 0, 2)  # B * Q * D

        x = self.ln_post(x)
        x = x @ self.proj
        return x

get_1d_sincos_pos_embed_from_temporal_size(embed_dim, pos)

embed_dim: output dimension for each position pos: a list of positions to be encoded: size (M,) out: (M, D)

Source code in vllm/model_executor/models/minicpmv.py
def get_1d_sincos_pos_embed_from_temporal_size(
    self, embed_dim: int, pos: np.ndarray
):
    """
    embed_dim: output dimension for each position
    pos: a list of positions to be encoded: size (M,)
    out: (M, D)
    """
    assert embed_dim % 2 == 0
    omega = np.arange(embed_dim // 2, dtype=np.float32)
    omega /= embed_dim / 2.0
    omega = 1.0 / 10000**omega  # (D/2,)

    pos = pos.reshape(-1)  # (M,)
    out = np.einsum("m,d->md", pos, omega)  # (M, D/2), outer product

    emb_sin = np.sin(out)  # (M, D/2)
    emb_cos = np.cos(out)  # (M, D/2)

    emb = np.concatenate([emb_sin, emb_cos], axis=1)  # (M, D)
    return emb

_MiniCPMVEncoderCudaGraphMixin

Bases: MiniCPMVBaseModel, SupportsEncoderCudaGraph

SupportsEncoderCudaGraph for MiniCPM-V Idefics2 + resampler (not 2.0).

Methods:

Source code in vllm/model_executor/models/minicpmv.py
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
class _MiniCPMVEncoderCudaGraphMixin(MiniCPMVBaseModel, SupportsEncoderCudaGraph):
    """SupportsEncoderCudaGraph for MiniCPM-V Idefics2 + resampler (not 2.0)."""

    supports_encoder_cudagraph: ClassVar[Literal[True]] = True

    def _mcpmv_slice_pixel_size(self) -> tuple[int, int]:
        image_size = int(self.vpm.embeddings.image_size)
        return image_size, image_size

    def _mcpmv_patch_grid_pixel_hw(
        self, patch_grid_key: tuple[int, int]
    ) -> tuple[int, int]:
        patch_size = int(self.vpm.embeddings.patch_size)
        th, tw = patch_grid_key
        return th * patch_size, tw * patch_size

    def _mcpmv_patch_grid_num_patches(self, patch_grid_key: tuple[int, int]) -> int:
        th, tw = patch_grid_key
        return th * tw

    def _mcpmv_patch_grid_keys(self) -> tuple[tuple[int, int], ...]:
        """Ordered patch-grid keys ``(nb_h, nb_w)`` for the capture axis."""
        max_side = int(self.vpm.embeddings.image_size) // int(
            self.vpm.embeddings.patch_size
        )
        keys: list[tuple[int, int]] = []
        seen: set[tuple[int, int]] = set()
        for th, tw in _MINICPMV_BASE_PATCH_BUCKETS:
            if th <= max_side and tw <= max_side:
                keys.append((th, tw))
                seen.add((th, tw))
        full = (max_side, max_side)
        if full not in seen:
            keys.append(full)
        return tuple(keys)

    def _mcpmv_resolve_patch_grid(
        self,
        tgt_sizes: torch.Tensor,
        slice_counts: list[int],
        indices: list[int],
    ) -> tuple[int, int]:
        """Smallest patch-grid key covering all selected items."""
        keys = self._mcpmv_patch_grid_keys()
        if not indices:
            return keys[0]
        tgt_groups = torch.split(tgt_sizes, slice_counts)
        selected = torch.cat([tgt_groups[i] for i in indices], dim=0)
        need_h = int(selected[:, 0].max().item())
        need_w = int(selected[:, 1].max().item())
        for th, tw in keys:
            if th >= need_h and tw >= need_w:
                return (th, tw)
        return keys[-1]

    def _mcpmv_max_slices_cap(
        self,
        token_budget: int,
        max_batch_size: int,
        max_frames_per_batch: int,
    ) -> int:
        max_slice_num = int(getattr(self.config, "max_slice_num", 9))
        query_num = max(1, int(self.config.query_num))
        max_slices_by_token_budget = max(1, token_budget // query_num)
        max_slices_by_content = max_batch_size * (max_slice_num + 1)
        if self.version in {(2, 6), (4, 0)} and max_frames_per_batch > 0:
            max_slices_by_content = max(
                max_slices_by_content,
                max_frames_per_batch * (max_slice_num + 1),
            )
        return max(1, min(max_slices_by_token_budget, max_slices_by_content))

    def get_encoder_cudagraph_config(self) -> EncoderCudaGraphConfig:
        buffer_keys = [
            _MINICPMV_CUDAGRAPH_BUF_KEY_PIXEL,
            _MINICPMV_CUDAGRAPH_BUF_KEY_TGT_SIZES,
            _MINICPMV_CUDAGRAPH_BUF_KEY_PATCH_MASK,
        ]
        # Video is only supported from 2.6 onward.
        modalities = ["image"]
        if self.version in {(2, 6), (4, 0)}:
            modalities.append("video")

        max_frames = self.get_max_frames_per_video() if "video" in modalities else 1

        return EncoderCudaGraphConfig(
            modalities=modalities,
            buffer_keys=buffer_keys,
            out_hidden_size=int(self.embed_dim),
            max_frames_per_video=max_frames,
            capture_axes=(self._mcpmv_patch_grid_keys(),),
        )

    def get_input_modality(self, mm_kwargs: dict[str, Any]) -> str:
        if "video_pixel_values" in mm_kwargs:
            return "video"
        return "image"

    def get_max_frames_per_video(self) -> int:
        info = MULTIMODAL_REGISTRY.get_processing_info(self.vllm_config.model_config)
        assert isinstance(info, MiniCPMVProcessingInfo)
        return int(
            info.get_num_frames_with_most_features(
                seq_len=self.vllm_config.model_config.max_model_len,
                mm_counts={
                    "video": self.multimodal_config.get_limit_per_prompt("video")
                },
            )
        )

    def get_encoder_cudagraph_budget_range(
        self, vllm_config: VllmConfig
    ) -> tuple[int, int]:
        # Each slice produces exactly query_num resampler output tokens.
        # A thumbnail-only image has 1 slice, so query_num is the smallest
        # possible encoder output and the natural minimum budget.
        min_budget = int(self.config.query_num)
        max_budget = min(
            vllm_config.scheduler_config.max_num_batched_tokens,
            vllm_config.model_config.max_model_len,
        )
        return (min_budget, max_budget)

    def get_encoder_cudagraph_item_specs(
        self, mm_kwargs: dict[str, Any]
    ) -> list[EncoderItemSpec]:
        video = self.get_input_modality(mm_kwargs) == "video"
        pixel_values_key = "video_pixel_values" if video else "pixel_values"
        pixel_values: list[list[torch.Tensor]] = mm_kwargs[pixel_values_key]
        slice_counts = [len(img) for img in pixel_values]
        tgt_sizes = _mcpmv_tgt_sizes_tensor(mm_kwargs, video=video)
        tgt_sizes = _mcpmv_normalize_tgt_sizes(tgt_sizes, slice_counts)
        patch_sums = tgt_sizes.prod(-1)
        input_sizes = [
            int(group.sum().item()) for group in torch.split(patch_sums, slice_counts)
        ]
        query_num = int(self.config.query_num)
        return [
            EncoderItemSpec(
                input_size=input_sizes[i],
                output_tokens=slice_counts[i] * query_num,
            )
            for i in range(len(pixel_values))
        ]

    def select_encoder_cudagraph_items(
        self,
        mm_kwargs: dict[str, Any],
        indices: list[int],
    ) -> dict[str, Any]:
        subset, patch_grid = self._mcpmv_select_items(mm_kwargs, indices)
        subset[ENCODER_CUDAGRAPH_AXIS_KEYS_KWARG] = (patch_grid,)
        return subset

    def _mcpmv_select_items(
        self, mm_kwargs: dict[str, Any], indices: list[int]
    ) -> tuple[dict[str, Any], tuple[int, int]]:
        """Slice mm_kwargs for `indices`; also returns the patch-grid key."""
        video = self.get_input_modality(mm_kwargs) == "video"
        pixel_values_key = "video_pixel_values" if video else "pixel_values"
        tgt_key = "video_tgt_sizes" if video else "tgt_sizes"
        flat_key = (
            _MINICPMV_CUDAGRAPH_FLAT_KEY_VIDEO
            if video
            else _MINICPMV_CUDAGRAPH_FLAT_KEY_IMAGE
        )
        device = next(self.vpm.parameters()).device
        pixel_values: list[list[torch.Tensor]] = mm_kwargs[pixel_values_key]
        tgt_sizes = _mcpmv_tgt_sizes_tensor(mm_kwargs, video=video)

        subset = {
            k: v
            for k, v in mm_kwargs.items()
            if k not in _ENCODER_CUDAGRAPH_MM_KWARGS_SKIP_KEYS
        }

        if not indices:
            pixel_h, pixel_w = self._mcpmv_slice_pixel_size()
            vpm_dtype = next(self.vpm.parameters()).dtype
            subset.update(
                {
                    pixel_values_key: [],
                    tgt_key: torch.zeros((0, 2), dtype=torch.long, device=device),
                    flat_key: torch.zeros(
                        (0, 3 * pixel_h * pixel_w), device=device, dtype=vpm_dtype
                    ),
                }
            )
            return subset, self._mcpmv_patch_grid_keys()[0]

        slice_counts = [len(item_slices) for item_slices in pixel_values]
        tgt_sizes = _mcpmv_normalize_tgt_sizes(tgt_sizes, slice_counts)
        tgt_groups = torch.split(tgt_sizes, slice_counts)

        patch_grid = self._mcpmv_resolve_patch_grid(tgt_sizes, slice_counts, indices)
        pixel_h, pixel_w = self._mcpmv_patch_grid_pixel_hw(patch_grid)

        selected_pixel_values = [pixel_values[i] for i in indices]
        selected_tgt_sizes_list = [tgt_groups[i] for i in indices]
        selected_tgt_sizes = torch.cat(selected_tgt_sizes_list, dim=0)

        selected_slices = flatten_2d_lists(selected_pixel_values)
        packed_flat_pixels = _mcpmv_pack_flat_pixels(
            selected_slices,
            pixel_height=pixel_h,
            pixel_width=pixel_w,
            max_num_slices=len(selected_slices),
            device=selected_slices[0].device,
            dtype=selected_slices[0].dtype,
            patch_size=int(self.vpm.embeddings.patch_size),
            tgt_sizes=selected_tgt_sizes,
        )

        subset.update(
            {
                pixel_values_key: selected_pixel_values,
                tgt_key: selected_tgt_sizes_list,
                flat_key: packed_flat_pixels,
                _MINICPMV_CUDAGRAPH_PATCH_GRID_KEY: patch_grid,
            }
        )
        return subset, patch_grid

    def prepare_encoder_cudagraph_capture_inputs(
        self,
        token_budget: int,
        max_batch_size: int,
        max_frames_per_batch: int,
        device: torch.device,
        dtype: torch.dtype,
        path: str = "default",
        axis_keys: tuple[Hashable, ...] | None = None,
    ):
        patch_grid = (
            cast("tuple[int, int]", axis_keys[0])
            if axis_keys
            # Without capture-axis context, use the largest (full-resolution)
            # patch grid.
            else self._mcpmv_patch_grid_keys()[-1]
        )
        return self._mcpmv_capture_inputs(
            token_budget,
            max_batch_size,
            max_frames_per_batch,
            device,
            dtype,
            patch_grid=patch_grid,
        )

    def _mcpmv_capture_inputs(
        self,
        token_budget: int,
        max_batch_size: int,
        max_frames_per_batch: int,
        device: torch.device,
        dtype: torch.dtype,
        patch_grid: tuple[int, int],
    ):
        th, tw = patch_grid
        pixel_h, pixel_w = self._mcpmv_patch_grid_pixel_hw(patch_grid)
        max_patches = self._mcpmv_patch_grid_num_patches(patch_grid)
        max_num_slices = self._mcpmv_max_slices_cap(
            token_budget,
            max_batch_size,
            max_frames_per_batch,
        )
        pixel_buffer = torch.zeros(
            (max_num_slices, 3, pixel_h, pixel_w), device=device, dtype=dtype
        )
        dummy_tgt_sizes = torch.zeros(
            (max_num_slices, 2), dtype=torch.long, device=device
        )
        dummy_tgt_sizes[:, 0] = th
        dummy_tgt_sizes[:, 1] = tw
        dummy_patch_mask = torch.ones(
            (max_num_slices, max_patches), dtype=torch.bool, device=device
        )
        values: dict[str, torch.Tensor] = {
            _MINICPMV_CUDAGRAPH_BUF_KEY_PIXEL: pixel_buffer,
            _MINICPMV_CUDAGRAPH_BUF_KEY_TGT_SIZES: dummy_tgt_sizes,
            _MINICPMV_CUDAGRAPH_BUF_KEY_PATCH_MASK: dummy_patch_mask,
        }
        return EncoderCudaGraphCaptureInputs(values=values)

    def prepare_encoder_cudagraph_replay_buffers(
        self,
        mm_kwargs: dict[str, Any],
        max_batch_size: int,
        max_frames_per_batch: int,
        path: str = "default",
    ):
        _ = max_batch_size
        _ = max_frames_per_batch
        video = self.get_input_modality(mm_kwargs) == "video"
        flat_key = (
            _MINICPMV_CUDAGRAPH_FLAT_KEY_VIDEO
            if video
            else _MINICPMV_CUDAGRAPH_FLAT_KEY_IMAGE
        )
        flat_pixels = mm_kwargs[flat_key]  # (num_actual_slices, 3*pixel_h*pixel_w)
        patch_grid = mm_kwargs[_MINICPMV_CUDAGRAPH_PATCH_GRID_KEY]
        pixel_h, pixel_w = self._mcpmv_patch_grid_pixel_hw(patch_grid)
        max_patches = self._mcpmv_patch_grid_num_patches(patch_grid)
        pixel_buffer = flat_pixels.reshape(-1, 3, pixel_h, pixel_w)

        device = next(self.vpm.parameters()).device
        tgt_sizes_raw = _mcpmv_tgt_sizes_tensor(mm_kwargs, video=video)
        if isinstance(tgt_sizes_raw, list):
            tgt_sizes_raw = torch.cat(tgt_sizes_raw, dim=0)
        # tgt_sizes arrives from CPU-side mm_kwargs; use a pinned async copy
        # to stay clean under VLLM_GPU_SYNC_CHECK.
        tgt_sizes = async_tensor_h2d(tgt_sizes_raw, device, dtype=torch.long)

        patches_per_slice = tgt_sizes.prod(-1).clamp(max=max_patches)
        col_idx = torch.arange(max_patches, device=device)
        patch_attention_mask = col_idx.unsqueeze(0) < patches_per_slice.unsqueeze(1)

        values: dict[str, torch.Tensor] = {
            _MINICPMV_CUDAGRAPH_BUF_KEY_PIXEL: pixel_buffer,
            _MINICPMV_CUDAGRAPH_BUF_KEY_TGT_SIZES: tgt_sizes,
            _MINICPMV_CUDAGRAPH_BUF_KEY_PATCH_MASK: patch_attention_mask,
        }
        return EncoderCudaGraphReplayBuffers(values=values)

    def encoder_cudagraph_forward(
        self,
        values: dict[str, torch.Tensor],
        path: str = "default",
    ) -> torch.Tensor:
        all_pixel_values = values[_MINICPMV_CUDAGRAPH_BUF_KEY_PIXEL]
        tgt_sizes = values[_MINICPMV_CUDAGRAPH_BUF_KEY_TGT_SIZES]
        patch_mask = values[_MINICPMV_CUDAGRAPH_BUF_KEY_PATCH_MASK]
        patch_attention_mask = patch_mask.unsqueeze(1)

        max_num_slices = all_pixel_values.shape[0]
        # v2.5 infers patch layout from the attention mask; pass tgt_sizes=None.
        vpm_tgt_sizes = None if self.version == (2, 5) else tgt_sizes
        vision_embedding = self.vpm(
            all_pixel_values,
            patch_attention_mask=patch_attention_mask,
            tgt_sizes=vpm_tgt_sizes,
        )

        resampler_out = self.resampler(vision_embedding, tgt_sizes)

        query_num = int(self.config.query_num)
        return resampler_out.reshape(max_num_slices * query_num, int(self.embed_dim))

    def encoder_eager_forward(
        self,
        mm_kwargs: dict[str, Any],
        path: str = "default",
    ) -> torch.Tensor:
        """Eager encoder path; returns ``(total_tokens, embed_dim)`` like
        ``encoder_cudagraph_forward``.
        """
        mm_kwargs_no_flat = {
            k: v
            for k, v in mm_kwargs.items()
            if k not in _ENCODER_CUDAGRAPH_MM_KWARGS_SKIP_KEYS
        }
        modalities = self._parse_and_validate_multimodal_inputs(**mm_kwargs_no_flat)
        segments: list[torch.Tensor] = []
        embed_dim = self.embed_dim
        for modality in modalities:
            if modality == "images":
                image_input = modalities["images"]
                assert isinstance(image_input, MiniCPMVImagePixelInputs)
                image_embeddings = self.get_vision_hidden_states(image_input)
                segments.append(image_embeddings.reshape(-1, embed_dim))
            elif modality == "videos":
                video_input = modalities["videos"]
                assert isinstance(video_input, MiniCPMVImagePixelInputs)
                video_embeddings = self.get_vision_hidden_states(video_input)
                segments.append(video_embeddings.reshape(-1, embed_dim))
        if not segments:
            raise RuntimeError(
                "MiniCPM-V encoder cudagraph eager path expects pixel_values "
                "or video_pixel_values"
            )
        return torch.cat(segments, dim=0)

_mcpmv_patch_grid_keys()

Ordered patch-grid keys (nb_h, nb_w) for the capture axis.

Source code in vllm/model_executor/models/minicpmv.py
def _mcpmv_patch_grid_keys(self) -> tuple[tuple[int, int], ...]:
    """Ordered patch-grid keys ``(nb_h, nb_w)`` for the capture axis."""
    max_side = int(self.vpm.embeddings.image_size) // int(
        self.vpm.embeddings.patch_size
    )
    keys: list[tuple[int, int]] = []
    seen: set[tuple[int, int]] = set()
    for th, tw in _MINICPMV_BASE_PATCH_BUCKETS:
        if th <= max_side and tw <= max_side:
            keys.append((th, tw))
            seen.add((th, tw))
    full = (max_side, max_side)
    if full not in seen:
        keys.append(full)
    return tuple(keys)

_mcpmv_resolve_patch_grid(tgt_sizes, slice_counts, indices)

Smallest patch-grid key covering all selected items.

Source code in vllm/model_executor/models/minicpmv.py
def _mcpmv_resolve_patch_grid(
    self,
    tgt_sizes: torch.Tensor,
    slice_counts: list[int],
    indices: list[int],
) -> tuple[int, int]:
    """Smallest patch-grid key covering all selected items."""
    keys = self._mcpmv_patch_grid_keys()
    if not indices:
        return keys[0]
    tgt_groups = torch.split(tgt_sizes, slice_counts)
    selected = torch.cat([tgt_groups[i] for i in indices], dim=0)
    need_h = int(selected[:, 0].max().item())
    need_w = int(selected[:, 1].max().item())
    for th, tw in keys:
        if th >= need_h and tw >= need_w:
            return (th, tw)
    return keys[-1]

_mcpmv_select_items(mm_kwargs, indices)

Slice mm_kwargs for indices; also returns the patch-grid key.

Source code in vllm/model_executor/models/minicpmv.py
def _mcpmv_select_items(
    self, mm_kwargs: dict[str, Any], indices: list[int]
) -> tuple[dict[str, Any], tuple[int, int]]:
    """Slice mm_kwargs for `indices`; also returns the patch-grid key."""
    video = self.get_input_modality(mm_kwargs) == "video"
    pixel_values_key = "video_pixel_values" if video else "pixel_values"
    tgt_key = "video_tgt_sizes" if video else "tgt_sizes"
    flat_key = (
        _MINICPMV_CUDAGRAPH_FLAT_KEY_VIDEO
        if video
        else _MINICPMV_CUDAGRAPH_FLAT_KEY_IMAGE
    )
    device = next(self.vpm.parameters()).device
    pixel_values: list[list[torch.Tensor]] = mm_kwargs[pixel_values_key]
    tgt_sizes = _mcpmv_tgt_sizes_tensor(mm_kwargs, video=video)

    subset = {
        k: v
        for k, v in mm_kwargs.items()
        if k not in _ENCODER_CUDAGRAPH_MM_KWARGS_SKIP_KEYS
    }

    if not indices:
        pixel_h, pixel_w = self._mcpmv_slice_pixel_size()
        vpm_dtype = next(self.vpm.parameters()).dtype
        subset.update(
            {
                pixel_values_key: [],
                tgt_key: torch.zeros((0, 2), dtype=torch.long, device=device),
                flat_key: torch.zeros(
                    (0, 3 * pixel_h * pixel_w), device=device, dtype=vpm_dtype
                ),
            }
        )
        return subset, self._mcpmv_patch_grid_keys()[0]

    slice_counts = [len(item_slices) for item_slices in pixel_values]
    tgt_sizes = _mcpmv_normalize_tgt_sizes(tgt_sizes, slice_counts)
    tgt_groups = torch.split(tgt_sizes, slice_counts)

    patch_grid = self._mcpmv_resolve_patch_grid(tgt_sizes, slice_counts, indices)
    pixel_h, pixel_w = self._mcpmv_patch_grid_pixel_hw(patch_grid)

    selected_pixel_values = [pixel_values[i] for i in indices]
    selected_tgt_sizes_list = [tgt_groups[i] for i in indices]
    selected_tgt_sizes = torch.cat(selected_tgt_sizes_list, dim=0)

    selected_slices = flatten_2d_lists(selected_pixel_values)
    packed_flat_pixels = _mcpmv_pack_flat_pixels(
        selected_slices,
        pixel_height=pixel_h,
        pixel_width=pixel_w,
        max_num_slices=len(selected_slices),
        device=selected_slices[0].device,
        dtype=selected_slices[0].dtype,
        patch_size=int(self.vpm.embeddings.patch_size),
        tgt_sizes=selected_tgt_sizes,
    )

    subset.update(
        {
            pixel_values_key: selected_pixel_values,
            tgt_key: selected_tgt_sizes_list,
            flat_key: packed_flat_pixels,
            _MINICPMV_CUDAGRAPH_PATCH_GRID_KEY: patch_grid,
        }
    )
    return subset, patch_grid

encoder_eager_forward(mm_kwargs, path='default')

Eager encoder path; returns (total_tokens, embed_dim) like encoder_cudagraph_forward.

Source code in vllm/model_executor/models/minicpmv.py
def encoder_eager_forward(
    self,
    mm_kwargs: dict[str, Any],
    path: str = "default",
) -> torch.Tensor:
    """Eager encoder path; returns ``(total_tokens, embed_dim)`` like
    ``encoder_cudagraph_forward``.
    """
    mm_kwargs_no_flat = {
        k: v
        for k, v in mm_kwargs.items()
        if k not in _ENCODER_CUDAGRAPH_MM_KWARGS_SKIP_KEYS
    }
    modalities = self._parse_and_validate_multimodal_inputs(**mm_kwargs_no_flat)
    segments: list[torch.Tensor] = []
    embed_dim = self.embed_dim
    for modality in modalities:
        if modality == "images":
            image_input = modalities["images"]
            assert isinstance(image_input, MiniCPMVImagePixelInputs)
            image_embeddings = self.get_vision_hidden_states(image_input)
            segments.append(image_embeddings.reshape(-1, embed_dim))
        elif modality == "videos":
            video_input = modalities["videos"]
            assert isinstance(video_input, MiniCPMVImagePixelInputs)
            video_embeddings = self.get_vision_hidden_states(video_input)
            segments.append(video_embeddings.reshape(-1, embed_dim))
    if not segments:
        raise RuntimeError(
            "MiniCPM-V encoder cudagraph eager path expects pixel_values "
            "or video_pixel_values"
        )
    return torch.cat(segments, dim=0)

_mcpmv_normalize_tgt_sizes(tgt_sizes, slice_counts)

Normalize tgt_sizes to shape (total_slices, 2).

Source code in vllm/model_executor/models/minicpmv.py
def _mcpmv_normalize_tgt_sizes(
    tgt_sizes: torch.Tensor | list[torch.Tensor],
    slice_counts: list[int],
) -> torch.Tensor:
    """Normalize tgt_sizes to shape ``(total_slices, 2)``."""

    if isinstance(tgt_sizes, list):
        if not tgt_sizes:
            tgt_sizes = torch.zeros((0, 2), dtype=torch.long)
        else:
            tgt_sizes = torch.cat(tgt_sizes, dim=0)

    total_slices = sum(slice_counts)
    if tgt_sizes.dim() == 2 and tgt_sizes.shape[0] == total_slices:
        return tgt_sizes
    if tgt_sizes.dim() == 3:
        return torch.cat(
            [tgt_sizes[i, : slice_counts[i], :] for i in range(len(slice_counts))],
            dim=0,
        )
    return torch.repeat_interleave(
        tgt_sizes,
        torch.tensor(slice_counts, device=tgt_sizes.device),
        dim=0,
    )

_mcpmv_pack_flat_pixels(slices, *, pixel_height, pixel_width, max_num_slices, device, dtype, patch_size, tgt_sizes)

Pack slice tensors into a fixed (max_num_slices, 3*H*W) buffer.

Source code in vllm/model_executor/models/minicpmv.py
def _mcpmv_pack_flat_pixels(
    slices: list[torch.Tensor],
    *,
    pixel_height: int,
    pixel_width: int,
    max_num_slices: int,
    device: torch.device,
    dtype: torch.dtype,
    patch_size: int,
    tgt_sizes: torch.Tensor,
) -> torch.Tensor:
    """Pack slice tensors into a fixed ``(max_num_slices, 3*H*W)`` buffer."""
    import torch.nn.functional as F

    flat_dim = 3 * pixel_height * pixel_width
    grid_h = pixel_height // patch_size
    grid_w = pixel_width // patch_size
    max_grid_patches = grid_h * grid_w

    packed = torch.zeros((max_num_slices, flat_dim), device=device, dtype=dtype)
    n = min(len(slices), max_num_slices)
    tgt_list = tgt_sizes.tolist()
    for i, slc in enumerate(slices[:n]):
        slc = slc.to(dtype=dtype, device=device)
        C, h, w = slc.shape
        if h == patch_size:
            nb_h, nb_w = int(tgt_list[i][0]), int(tgt_list[i][1])
            num_patches = nb_h * nb_w

            patches = (
                slc.view(C, patch_size, nb_h, nb_w, patch_size)
                .permute(0, 2, 3, 1, 4)
                .reshape(C, num_patches, patch_size, patch_size)
            )

            col = patches.permute(0, 2, 3, 1).reshape(
                1, C * patch_size * patch_size, num_patches
            )
            col_padded = col.new_zeros(1, C * patch_size * patch_size, max_grid_patches)
            col_padded[..., :num_patches] = col

            folded = F.fold(
                col_padded,
                output_size=(pixel_height, pixel_width),
                kernel_size=patch_size,
                stride=patch_size,
            )
            packed[i] = folded.reshape(-1)
        else:
            packed[i].view(3, pixel_height, pixel_width)[:, :h, :w] = slc
    return packed