Skip to content

vllm.model_executor.models.paddleocr_vl

Classes:

Functions:

  • all_gather_interleave –

    All-gather the input tensor interleavely across model parallel group.

  • smart_resize –

    Rescales the image so that the following conditions are met:

PaddleOCRVLForConditionalGeneration

Bases: Module, SupportsMultiModal, SupportsMRoPE, SupportsEncoderCudaGraph

Methods:

  • encode_image –

    Encode the flat patches of all images in one vision tower call.

  • iter_mm_grid_thw –

    Iterate over multimodal features and yield grid information.

Source code in vllm/model_executor/models/paddleocr_vl.py
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
@MULTIMODAL_REGISTRY.register_processor(
    PaddleOCRVLMultiModalProcessor,
    info=PaddleOCRVLProcessingInfo,
    dummy_inputs=PaddleOCRVLDummyInputsBuilder,
)
class PaddleOCRVLForConditionalGeneration(
    nn.Module, SupportsMultiModal, SupportsMRoPE, SupportsEncoderCudaGraph
):
    hf_to_vllm_mapper = WeightsMapper(
        orig_to_new_prefix={
            "model.": "language_model.model.",
            "lm_head.": "language_model.lm_head.",
        }
    )

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

        raise ValueError("Only image modality is supported")

    def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
        super().__init__()
        config = vllm_config.model_config.hf_config
        if hasattr(config, "text_config"):
            text_config = config.text_config.to_dict()
            unsafe_keys = ["model_type", "architectures", "tie_word_embeddings"]
            for key in unsafe_keys:
                text_config.pop(key, None)
            config.update(text_config)

        quant_config = vllm_config.quant_config

        self.config = config

        with self._mark_tower_model(vllm_config, "image"):
            self.visual = SiglipVisionModel(
                config=config.vision_config,
                quant_config=quant_config,
                prefix=maybe_prefix(prefix, "visual"),
            )
            self.mlp_AR = Projector(config, config.vision_config)

        with self._mark_language_model(vllm_config):
            self.language_model = Ernie4_5ForCausalLM(
                vllm_config=vllm_config,
                prefix=maybe_prefix(prefix, "language_model"),
            )

            for layer in self.language_model.model.layers:
                if not isinstance(layer, PPMissingLayer):
                    layer.self_attn.rotary_emb.is_neox_style = True

        self.make_empty_intermediate_tensors = (
            self.language_model.make_empty_intermediate_tensors
        )

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

    def iter_mm_grid_thw(
        self, mm_features: list[MultiModalFeatureSpec]
    ) -> Iterator[tuple[int, int, int, int, float]]:
        """Iterate over multimodal features and yield grid information.

        Args:
            mm_features: List of multimodal feature specifications

        Yields:
            Tuple of (offset, grid_t, grid_h, grid_w, t_factor) for each frame/image

        """
        spatial_merge_size = self.config.vision_config.spatial_merge_size
        tokens_per_second = getattr(self.config.vision_config, "tokens_per_second", 1.0)
        for mm_feature in sorted(mm_features, key=lambda f: f.mm_position.offset):
            offset = mm_feature.mm_position.offset
            feature_data = mm_feature.data
            assert feature_data is not None
            if mm_feature.modality == "image":
                grid_data = feature_data["image_grid_thw"].data
                assert isinstance(grid_data, torch.Tensor)
                t, h, w = grid_data.tolist()
                assert t == 1, f"Image must have 1 frame, got {t}"
                yield offset, 1, h // spatial_merge_size, w // spatial_merge_size, 1.0
            elif mm_feature.modality == "video":
                grid_data = feature_data["video_grid_thw"].data
                assert isinstance(grid_data, torch.Tensor)
                t, h, w = grid_data.tolist()
                second_per_grid_ts = 1.0
                second_per_grid_item = feature_data.get("second_per_grid_ts")
                if second_per_grid_item is not None:
                    second_per_grid_data = second_per_grid_item.data
                    assert isinstance(second_per_grid_data, torch.Tensor)
                    second_per_grid_ts = second_per_grid_data.item()
                t_factor = second_per_grid_ts * tokens_per_second
                yield (
                    offset,
                    t,
                    h // spatial_merge_size,
                    w // spatial_merge_size,
                    t_factor,
                )
            else:
                raise ValueError(f"Unsupported modality: {mm_feature.modality}")

    def get_mrope_input_positions(
        self,
        input_tokens: list[int],
        mm_features: list[MultiModalFeatureSpec],
    ) -> tuple[torch.Tensor, int]:
        llm_pos_ids_list: list = []
        st = 0

        for (
            offset,
            llm_grid_t,
            llm_grid_h,
            llm_grid_w,
            t_factor,
        ) in self.iter_mm_grid_thw(mm_features):
            text_len = offset - st
            st_idx = llm_pos_ids_list[-1].max() + 1 if len(llm_pos_ids_list) > 0 else 0
            llm_pos_ids_list.append(
                np.broadcast_to(np.arange(text_len), (3, text_len)) + st_idx
            )

            grid_indices = np.indices((llm_grid_t, llm_grid_h, llm_grid_w))
            if t_factor != 1.0:
                grid_indices[0] = (grid_indices[0] * t_factor).astype(np.int64)

            llm_pos_ids_list.append(grid_indices.reshape(3, -1) + text_len + st_idx)
            st = offset + llm_grid_t * llm_grid_h * llm_grid_w

        if st < len(input_tokens):
            st_idx = llm_pos_ids_list[-1].max() + 1 if len(llm_pos_ids_list) > 0 else 0
            text_len = len(input_tokens) - st
            llm_pos_ids_list.append(
                np.broadcast_to(np.arange(text_len), (3, text_len)) + st_idx
            )

        llm_positions = np.concatenate(llm_pos_ids_list, axis=1).reshape(3, -1)
        mrope_position_delta = (llm_positions.max() + 1 - len(input_tokens)).item()

        return torch.from_numpy(llm_positions), mrope_position_delta

    def _parse_and_validate_image_input(
        self, **kwargs: object
    ) -> PaddleOCRImagePixelInputs | None:
        pixel_values = kwargs.pop("pixel_values", None)
        image_grid_thw = kwargs.pop("image_grid_thw", None)

        if pixel_values is None:
            return None

        return PaddleOCRImagePixelInputs(
            type="pixel_values",
            pixel_values=pixel_values,
            image_grid_thw=image_grid_thw,
        )

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

        return self.language_model(
            input_ids, positions, intermediate_tensors, inputs_embeds
        )

    def encode_image(
        self,
        pixel_values: torch.Tensor,
        image_grid_thw: list[tuple[int, int, int]],
    ) -> torch.Tensor:
        """Encode the flat patches of all images in one vision tower call."""
        pixel_values = pixel_values.type(self.visual.dtype)
        seq_lens = [math.prod(grid) for grid in image_grid_thw]

        # Built on the host; concat straight into a pinned buffer so the
        # H2D copy stays non-blocking.
        siglip_position_ids = torch.concat(
            [
                torch.arange(seq_len) % (h * w)
                for seq_len, (_, h, w) in zip(seq_lens, image_grid_thw)
            ],
            dim=0,
            out=torch.empty(sum(seq_lens), dtype=torch.int64, pin_memory=PIN_MEMORY),
        ).to(pixel_values.device, non_blocking=True)
        # One segment per image so that images never attend to each other.
        cu_seqlens = torch.from_numpy(np.cumsum([0, *seq_lens], dtype=np.int32))

        return self.visual(
            pixel_values=pixel_values,
            image_grid_thw=image_grid_thw,
            position_ids=siglip_position_ids,
            interpolate_pos_encoding=True,
            cu_seqlens=cu_seqlens,
        )

    def _process_image_input(
        self, image_input: PaddleOCRImagePixelInputs
    ) -> MultiModalEmbeddings:
        image_grid_thw = image_input.image_grid_thw
        grids = [tuple(grid) for grid in image_grid_thw.tolist()]
        vision_outputs = self.encode_image(image_input.pixel_values, grids).squeeze(0)
        vision_outputs = vision_outputs.split([math.prod(grid) for grid in grids])
        return self.mlp_AR(vision_outputs, image_grid_thw)

    def embed_multimodal(self, **kwargs) -> MultiModalEmbeddings:
        image_input = self._parse_and_validate_image_input(**kwargs)
        if image_input is None:
            return ()

        multimodal_embeddings: tuple[torch.Tensor, ...] = ()
        image_embeds = self._process_image_input(image_input)
        multimodal_embeddings += tuple(image_embeds)

        return multimodal_embeddings

    # -- SupportsEncoderCudaGraph protocol methods --
    #
    # The graph covers the vision tower and the projector. Per-image work
    # (position embedding interpolation, rotary, cu_seqlens and the 2x2 merge
    # order) is precomputed by `SiglipVisionModel.prepare_encoder_metadata`.

    def get_encoder_cudagraph_config(self) -> EncoderCudaGraphConfig:
        attn_backend = self.visual.vision_model.encoder.attn_backend
        # TORCH_SDPA calls `.tolist()` on the device cu_seqlens and FlashInfer
        # needs extra metadata, so neither can be captured.
        if attn_backend not in _MAX_SEQLEN_ATTN_BACKENDS:
            raise ValueError(
                "cudagraph_mm_encoder is not supported with the "
                f"{attn_backend.name} ViT attention backend for PaddleOCR-VL. "
                "Set --mm-encoder-attn-backend to one of "
                f"{sorted(b.name for b in _MAX_SEQLEN_ATTN_BACKENDS)} or "
                "disable cudagraph_mm_encoder."
            )

        return EncoderCudaGraphConfig(
            modalities=["image"],
            buffer_keys=[
                "pixel_values",
                "position_embeddings",
                "rotary_pos_emb",
                "cu_seqlens",
                "max_seqlen",
                "merge_index",
            ],
            out_hidden_size=self.config.hidden_size,
        )

    def get_encoder_cudagraph_budget_range(
        self,
        vllm_config: VllmConfig,
    ) -> tuple[int, int]:
        # 64 is a safe floor; smaller items still fit the smallest budget.
        min_budget = 64
        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]:
        m = self.config.vision_config.spatial_merge_size
        return [
            EncoderItemSpec(
                input_size=t * h * w,
                output_tokens=t * (h // m) * (w // m),
            )
            for t, h, w in mm_kwargs["image_grid_thw"].tolist()
        ]

    def select_encoder_cudagraph_items(
        self,
        mm_kwargs: dict[str, Any],
        indices: list[int],
    ) -> dict[str, Any]:
        grid_thw = mm_kwargs["image_grid_thw"]
        pixel_values = mm_kwargs["pixel_values"]

        if len(indices) == 0:
            return {"pixel_values": pixel_values[:0], "image_grid_thw": grid_thw[:0]}

        # Cumulative patch offsets for slicing the concatenated pixel_values.
        cum_patches = np.cumsum([0, *grid_thw.prod(-1).tolist()])
        selected_pv = torch.cat(
            [pixel_values[cum_patches[i] : cum_patches[i + 1]] for i in indices]
        )
        return {"pixel_values": selected_pv, "image_grid_thw": grid_thw[indices]}

    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,
    ) -> EncoderCudaGraphCaptureInputs:
        vision_config = self.config.vision_config
        m = vision_config.spatial_merge_size
        # Ceil so the buffer fits the worst case of one item using the full
        # budget. Image grid (T=1) with h=m, so each item yields
        # per_mm_item_output merged tokens.
        per_mm_item_output = (token_budget + max_batch_size - 1) // max_batch_size
        grid_config = [[1, m, per_mm_item_output * m] for _ in range(max_batch_size)]

        dummy_pixel_values = torch.randn(
            sum(t * h * w for t, h, w in grid_config),
            vision_config.num_channels,
            vision_config.patch_size,
            vision_config.patch_size,
            device=device,
            dtype=dtype,
        )

        # max_seqlen is baked at capture: worst case is one item consuming the
        # full budget - seq_len = token_budget * spatial_merge_size**2.
        metadata = self.visual.prepare_encoder_metadata(
            grid_config,
            max_batch_size=max_batch_size,
            max_seqlen_override=token_budget * (m**2),
            device=device,
        )
        values = metadata | {"pixel_values": dummy_pixel_values}
        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",
    ) -> EncoderCudaGraphReplayBuffers:
        metadata = self.visual.prepare_encoder_metadata(
            mm_kwargs["image_grid_thw"].tolist(), max_batch_size=max_batch_size
        )
        values = metadata | {"pixel_values": mm_kwargs["pixel_values"]}
        return EncoderCudaGraphReplayBuffers(values=values)

    def encoder_cudagraph_forward(
        self,
        values: dict[str, torch.Tensor],
        path: str = "default",
    ) -> torch.Tensor:
        vision_outputs = self.visual(values["pixel_values"], encoder_metadata=values)
        return self.mlp_AR.forward_packed(vision_outputs, values["merge_index"])

    def encoder_eager_forward(
        self,
        mm_kwargs: dict[str, Any],
        path: str = "default",
    ) -> torch.Tensor:
        image_input = self._parse_and_validate_image_input(**mm_kwargs)
        assert image_input is not None
        return torch.cat(self._process_image_input(image_input))

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

encode_image(pixel_values, image_grid_thw)

Encode the flat patches of all images in one vision tower call.

Source code in vllm/model_executor/models/paddleocr_vl.py
def encode_image(
    self,
    pixel_values: torch.Tensor,
    image_grid_thw: list[tuple[int, int, int]],
) -> torch.Tensor:
    """Encode the flat patches of all images in one vision tower call."""
    pixel_values = pixel_values.type(self.visual.dtype)
    seq_lens = [math.prod(grid) for grid in image_grid_thw]

    # Built on the host; concat straight into a pinned buffer so the
    # H2D copy stays non-blocking.
    siglip_position_ids = torch.concat(
        [
            torch.arange(seq_len) % (h * w)
            for seq_len, (_, h, w) in zip(seq_lens, image_grid_thw)
        ],
        dim=0,
        out=torch.empty(sum(seq_lens), dtype=torch.int64, pin_memory=PIN_MEMORY),
    ).to(pixel_values.device, non_blocking=True)
    # One segment per image so that images never attend to each other.
    cu_seqlens = torch.from_numpy(np.cumsum([0, *seq_lens], dtype=np.int32))

    return self.visual(
        pixel_values=pixel_values,
        image_grid_thw=image_grid_thw,
        position_ids=siglip_position_ids,
        interpolate_pos_encoding=True,
        cu_seqlens=cu_seqlens,
    )

iter_mm_grid_thw(mm_features)

Iterate over multimodal features and yield grid information.

Parameters:

Yields:

  • tuple[int, int, int, int, float] –

    Tuple of (offset, grid_t, grid_h, grid_w, t_factor) for each frame/image

Source code in vllm/model_executor/models/paddleocr_vl.py
def iter_mm_grid_thw(
    self, mm_features: list[MultiModalFeatureSpec]
) -> Iterator[tuple[int, int, int, int, float]]:
    """Iterate over multimodal features and yield grid information.

    Args:
        mm_features: List of multimodal feature specifications

    Yields:
        Tuple of (offset, grid_t, grid_h, grid_w, t_factor) for each frame/image

    """
    spatial_merge_size = self.config.vision_config.spatial_merge_size
    tokens_per_second = getattr(self.config.vision_config, "tokens_per_second", 1.0)
    for mm_feature in sorted(mm_features, key=lambda f: f.mm_position.offset):
        offset = mm_feature.mm_position.offset
        feature_data = mm_feature.data
        assert feature_data is not None
        if mm_feature.modality == "image":
            grid_data = feature_data["image_grid_thw"].data
            assert isinstance(grid_data, torch.Tensor)
            t, h, w = grid_data.tolist()
            assert t == 1, f"Image must have 1 frame, got {t}"
            yield offset, 1, h // spatial_merge_size, w // spatial_merge_size, 1.0
        elif mm_feature.modality == "video":
            grid_data = feature_data["video_grid_thw"].data
            assert isinstance(grid_data, torch.Tensor)
            t, h, w = grid_data.tolist()
            second_per_grid_ts = 1.0
            second_per_grid_item = feature_data.get("second_per_grid_ts")
            if second_per_grid_item is not None:
                second_per_grid_data = second_per_grid_item.data
                assert isinstance(second_per_grid_data, torch.Tensor)
                second_per_grid_ts = second_per_grid_data.item()
            t_factor = second_per_grid_ts * tokens_per_second
            yield (
                offset,
                t,
                h // spatial_merge_size,
                w // spatial_merge_size,
                t_factor,
            )
        else:
            raise ValueError(f"Unsupported modality: {mm_feature.modality}")

Projector

Bases: Module

Methods:

  • forward_packed –

    Project packed images using a precomputed 2x2 merge gather order.

Source code in vllm/model_executor/models/paddleocr_vl.py
class Projector(nn.Module):
    def __init__(
        self,
        text_config: PreTrainedConfig,
        vision_config: PreTrainedConfig,
        prefix: str = "",
    ):
        super().__init__()
        self.text_config = text_config
        self.vision_config = vision_config
        self.merge_kernel_size = (2, 2)

        self.hidden_size = (
            self.vision_config.hidden_size
            * self.merge_kernel_size[0]
            * self.merge_kernel_size[1]
        )

        self.pre_norm = torch.nn.LayerNorm(self.vision_config.hidden_size, eps=1e-05)
        self.linear_1 = nn.Linear(self.hidden_size, self.hidden_size, bias=True)
        self.act = GELUActivation()
        self.linear_2 = nn.Linear(
            self.hidden_size, self.text_config.hidden_size, bias=True
        )

    def forward(
        self,
        image_features: torch.Tensor,
        image_grid_thw: torch.Tensor,
    ) -> torch.Tensor:
        m1, m2 = self.merge_kernel_size
        if isinstance(image_features, (list, tuple)):
            # Norm and MLP are per-token, so run them once over all images;
            # only the 2x2 merge depends on each image's grid.
            sizes = [image_feature.shape[0] for image_feature in image_features]
            normed_features = self.pre_norm(torch.cat(image_features)).split(sizes)
            merged_features = [
                rearrange(
                    image_feature,
                    "(t h p1 w p2) d -> (t h w) (p1 p2 d)",
                    t=t,
                    h=h // m1,
                    p1=m1,
                    w=w // m2,
                    p2=m2,
                )
                for image_feature, (t, h, w) in zip(normed_features, image_grid_thw)
            ]
            hidden_states = self.linear_1(torch.cat(merged_features))
            hidden_states = self.act(hidden_states)
            hidden_states = self.linear_2(hidden_states)

            return hidden_states.split([f.shape[0] for f in merged_features])

        dims = image_features.shape[:-1]
        dim = image_features.shape[-1]
        image_features = image_features.view(np.prod(dims), dim)
        hidden_states = self.pre_norm(image_features).view(-1, self.hidden_size)
        hidden_states = self.linear_1(hidden_states)
        hidden_states = self.act(hidden_states)
        hidden_states = self.linear_2(hidden_states)

        return hidden_states.view(*dims, -1)

    def forward_packed(
        self,
        image_features: torch.Tensor,
        merge_index: torch.Tensor,
    ) -> torch.Tensor:
        """Project packed images using a precomputed 2x2 merge gather order."""
        x = image_features.reshape(-1, image_features.shape[-1])
        x = self.pre_norm(x)
        x = x[merge_index].reshape(-1, self.hidden_size)
        x = self.linear_1(x)
        x = self.act(x)
        return self.linear_2(x)

forward_packed(image_features, merge_index)

Project packed images using a precomputed 2x2 merge gather order.

Source code in vllm/model_executor/models/paddleocr_vl.py
def forward_packed(
    self,
    image_features: torch.Tensor,
    merge_index: torch.Tensor,
) -> torch.Tensor:
    """Project packed images using a precomputed 2x2 merge gather order."""
    x = image_features.reshape(-1, image_features.shape[-1])
    x = self.pre_norm(x)
    x = x[merge_index].reshape(-1, self.hidden_size)
    x = self.linear_1(x)
    x = self.act(x)
    return self.linear_2(x)

SiglipAttention

Bases: Module

SigLIP vision attention adapted from Qwen2.5-VisionAttention.

Source code in vllm/model_executor/models/paddleocr_vl.py
class SiglipAttention(nn.Module):
    """SigLIP vision attention adapted from Qwen2.5-VisionAttention."""

    def __init__(
        self,
        *,
        embed_dim: int,
        num_heads: int,
        projection_size: int,
        quant_config: QuantizationConfig | None = None,
        prefix: str = "",
    ) -> None:
        super().__init__()

        self.tp_size = parallel_state.get_tensor_model_parallel_world_size()
        self.tp_rank = parallel_state.get_tensor_model_parallel_rank()
        self.hidden_size_per_attention_head = dist_utils.divide(
            projection_size, num_heads
        )
        self.num_attention_heads_per_partition = dist_utils.divide(
            num_heads, self.tp_size
        )

        self.qkv_proj = QKVParallelLinear(
            hidden_size=embed_dim,
            head_size=self.hidden_size_per_attention_head,
            total_num_heads=num_heads,
            total_num_kv_heads=num_heads,
            bias=True,
            quant_config=quant_config,
            prefix=f"{prefix}.qkv_proj",
        )
        self.out_proj = RowParallelLinear(
            input_size=projection_size,
            output_size=embed_dim,
            quant_config=quant_config,
            prefix=f"{prefix}.out_proj",
        )
        self.attn = MMEncoderAttention(
            num_heads=self.num_attention_heads_per_partition,
            head_size=self.hidden_size_per_attention_head,
            scale=self.hidden_size_per_attention_head**-0.5,
            prefix=f"{prefix}.attn",
        )
        self.apply_rotary_emb = ApplyRotaryEmb(
            enforce_enable=True,
            enable_fp32_compute=True,
        )

    def split_qkv(self, qkv: torch.Tensor) -> tuple[torch.Tensor, ...]:
        seq_len, bs, _ = qkv.shape
        if self.tp_size > 1:
            qkv = all_gather_interleave(qkv, self.qkv_proj.hidden_size, self.tp_size)

        q, k, v = qkv.chunk(3, dim=2)

        if self.tp_size > 1:
            splitter = partial(
                dist_utils.split_tensor_along_last_dim, num_partitions=self.tp_size
            )
            q = splitter(q)[self.tp_rank]
            k = splitter(k)[self.tp_rank]
            v = splitter(v)[self.tp_rank]

        new_shape = (
            seq_len,
            bs,
            self.num_attention_heads_per_partition,
            self.hidden_size_per_attention_head,
        )
        q, k, v = (x.view(*new_shape) for x in (q, k, v))
        return q, k, v

    def forward(
        self,
        hidden_states: torch.Tensor,
        *,
        cu_seqlens: torch.Tensor,
        rotary_pos_emb: torch.Tensor | None,
        max_seqlen: torch.Tensor | None,
    ) -> torch.Tensor:
        batch_size, _, _ = hidden_states.shape

        x = rearrange(hidden_states, "b s d -> s b d")
        x, _ = self.qkv_proj(x)
        q, k, v = self.split_qkv(x)
        q, k, v = (rearrange(t, "s b h d -> b s h d") for t in (q, k, v))

        if rotary_pos_emb is not None:
            qk_concat = torch.cat([q, k], dim=0)
            qk_rotated = self.apply_rotary_emb(
                qk_concat,
                rotary_pos_emb.cos(),
                rotary_pos_emb.sin(),
            )
            q, k = torch.chunk(qk_rotated, 2, dim=0)

        context_layer = self.attn(
            query=q,
            key=k,
            value=v,
            cu_seqlens=cu_seqlens,
            max_seqlen=max_seqlen,
        )
        context_layer = rearrange(context_layer, "b s h d -> b s (h d)")

        output, _ = self.out_proj(context_layer)
        return output

SiglipEncoder

Bases: Module

Methods:

  • rot_pos_emb –

    Gather the 2D rotary embedding of every patch.

Source code in vllm/model_executor/models/paddleocr_vl.py
class SiglipEncoder(nn.Module):
    def __init__(
        self,
        config: PreTrainedConfig,
        quant_config: QuantizationConfig | None = None,
        prefix: str = "",
    ):
        super().__init__()
        self.config = config
        embed_dim = config.hidden_size
        num_heads = config.num_attention_heads
        head_dim = embed_dim // num_heads

        self.attn_backend = get_vit_attn_backend(
            head_size=head_dim,
            dtype=torch.get_default_dtype(),
        )

        self.layers = nn.ModuleList(
            [
                SiglipEncoderLayer(
                    config,
                    quant_config=quant_config,
                    prefix=f"{prefix}.layers.{layer_idx}",
                )
                for layer_idx in range(config.num_hidden_layers)
            ]
        )
        self.rotary_pos_emb = SigLIPRotaryEmbedding(head_dim // 2)

    @staticmethod
    def flatten_list(image_grid_thw):
        tmp_image_grid_thw = list()
        for image_grid in image_grid_thw:
            if isinstance(image_grid, list):
                tmp_image_grid_thw.extend(image_grid)
            else:
                tmp_image_grid_thw.append(image_grid)
        return tmp_image_grid_thw

    def rot_pos_emb(
        self,
        image_grid_thw: Sequence[tuple[int, int, int]],
        device: torch.device,
        height_position_ids: torch.Tensor | None = None,
        width_position_ids: torch.Tensor | None = None,
    ) -> torch.Tensor:
        """Gather the 2D rotary embedding of every patch."""
        if width_position_ids is None or height_position_ids is None:
            split_hids = list()
            split_wids = list()
            for t, h, w in image_grid_thw:
                image_pids = torch.arange(t * h * w, device=device) % (h * w)
                split_hids.append(image_pids // w)
                split_wids.append(image_pids % w)
            width_position_ids = torch.concat(split_wids, dim=0)
            height_position_ids = torch.concat(split_hids, dim=0)

        pids = torch.stack(
            [height_position_ids, width_position_ids],
            dim=-1,
        )
        # The ids are built from the grids above, so `h`/`w` bound them
        # and the table size is known on the host.
        max_grid_size = max(max(h, w) for _, h, w in image_grid_thw)
        rope_emb_max_grid = self.rotary_pos_emb(max_grid_size)
        return rope_emb_max_grid[pids].flatten(1)

    def compute_max_seqlen(self, cu_seqlens: torch.Tensor) -> torch.Tensor | None:
        if self.attn_backend not in _MAX_SEQLEN_ATTN_BACKENDS:
            return None
        return (cu_seqlens[1:] - cu_seqlens[:-1]).max()

    def forward(
        self,
        inputs_embeds,
        cu_seqlens: torch.Tensor | None = None,
        image_grid_thw: list[tuple[int, int, int] | list[tuple[int, int, int]]]
        | None = None,
        height_position_ids: torch.Tensor | None = None,
        width_position_ids: torch.Tensor | None = None,
        rotary_pos_emb: torch.Tensor | None = None,
        max_seqlen: torch.Tensor | None = None,
    ) -> torch.Tensor:
        device = inputs_embeds.device

        if cu_seqlens is None:
            raise ValueError("cu_seqlens cannot be None for SiglipEncoder.")

        # The encoder CUDA graph passes precomputed rotary and attention
        # metadata, so only the eager path derives them here.
        if rotary_pos_emb is None:
            rotary_pos_emb = self.rot_pos_emb(
                self.flatten_list(image_grid_thw),
                device,
                height_position_ids,
                width_position_ids,
            )
            if not isinstance(cu_seqlens, torch.Tensor):
                cu_seqlens = torch.tensor(cu_seqlens, dtype=torch.int32)

            # Computed before the H2D copy: the attention wrappers call
            # `.item()` on it, which would sync on every layer for a device
            # tensor.
            max_seqlen = self.compute_max_seqlen(cu_seqlens)

        if cu_seqlens.is_cpu:
            cu_seqlens = async_tensor_h2d(cu_seqlens, dtype=torch.int32, device=device)
        else:
            cu_seqlens = cu_seqlens.to(device=device, non_blocking=True)

        hidden_states = inputs_embeds
        for encoder_layer in self.layers:
            hidden_states = encoder_layer(
                hidden_states,
                cu_seqlens=cu_seqlens,
                rotary_pos_emb=rotary_pos_emb,
                max_seqlen=max_seqlen,
            )
        return hidden_states

rot_pos_emb(image_grid_thw, device, height_position_ids=None, width_position_ids=None)

Gather the 2D rotary embedding of every patch.

Source code in vllm/model_executor/models/paddleocr_vl.py
def rot_pos_emb(
    self,
    image_grid_thw: Sequence[tuple[int, int, int]],
    device: torch.device,
    height_position_ids: torch.Tensor | None = None,
    width_position_ids: torch.Tensor | None = None,
) -> torch.Tensor:
    """Gather the 2D rotary embedding of every patch."""
    if width_position_ids is None or height_position_ids is None:
        split_hids = list()
        split_wids = list()
        for t, h, w in image_grid_thw:
            image_pids = torch.arange(t * h * w, device=device) % (h * w)
            split_hids.append(image_pids // w)
            split_wids.append(image_pids % w)
        width_position_ids = torch.concat(split_wids, dim=0)
        height_position_ids = torch.concat(split_hids, dim=0)

    pids = torch.stack(
        [height_position_ids, width_position_ids],
        dim=-1,
    )
    # The ids are built from the grids above, so `h`/`w` bound them
    # and the table size is known on the host.
    max_grid_size = max(max(h, w) for _, h, w in image_grid_thw)
    rope_emb_max_grid = self.rotary_pos_emb(max_grid_size)
    return rope_emb_max_grid[pids].flatten(1)

SiglipVisionEmbeddings

Bases: Module

Methods:

Source code in vllm/model_executor/models/paddleocr_vl.py
class SiglipVisionEmbeddings(nn.Module):
    def __init__(self, config: PreTrainedConfig):
        super().__init__()
        self.config = config
        self.embed_dim = config.hidden_size
        self.image_size = config.image_size
        self.patch_size = config.patch_size

        self.patch_embedding = Conv2dLayer(
            in_channels=config.num_channels,
            out_channels=self.embed_dim,
            kernel_size=self.patch_size,
            stride=self.patch_size,
            padding="valid",
        )

        self.num_patches = (self.image_size // self.patch_size) ** 2
        self.num_positions = self.num_patches
        self.cache_position_embedding: dict[tuple[int, int], torch.Tensor] = {}
        self.cache_position_count: dict[tuple[int, int], int] = {}
        self.position_embedding = nn.Embedding(self.num_positions, self.embed_dim)

        self.register_buffer(
            "position_ids",
            torch.arange(self.num_positions).expand((1, -1)),
            persistent=False,
        )

    def interpolate_pos_encoding(
        self,
        embeddings: torch.Tensor,
        height: int,
        width: int,
        is_after_patchify: bool = False,
    ) -> torch.Tensor:
        num_positions = self.position_embedding.weight.shape[0]

        patch_pos_embed = self.position_embedding.weight.unsqueeze(0)

        dim = embeddings.shape[-1]

        if is_after_patchify:
            new_height = height
            new_width = width
        else:
            new_height = height // self.patch_size
            new_width = width // self.patch_size

        sqrt_num_positions = torch_int(num_positions**0.5)
        patch_pos_embed = patch_pos_embed.reshape(
            1, sqrt_num_positions, sqrt_num_positions, dim
        )
        patch_pos_embed = patch_pos_embed.permute(0, 3, 1, 2)

        patch_pos_embed = nn.functional.interpolate(
            patch_pos_embed,
            size=(new_height, new_width),
            mode="bilinear",
            align_corners=False,
        )

        patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)
        return patch_pos_embed

    def get_position_embeddings(
        self, image_grid_thw: Sequence[tuple[int, int, int]]
    ) -> torch.Tensor:
        """Interpolate the position embedding to each image grid and concat."""
        weight = self.position_embedding.weight
        return torch.concat(
            [
                self.interpolate_pos_encoding(weight, h, w, True)
                .squeeze(0)
                .repeat(t, 1)
                for t, h, w in image_grid_thw
            ],
            dim=0,
        )

    def forward(
        self,
        pixel_values: torch.FloatTensor,
        position_ids: torch.Tensor | None = None,
        image_grid_thw: Sequence[tuple[int, int, int]] | None = None,
        interpolate_pos_encoding=False,
        position_embeddings: torch.Tensor | None = None,
    ) -> torch.Tensor:
        if pixel_values.dim() == 4:
            pixel_values = pixel_values.unsqueeze(0)
        if pixel_values.dim() == 5:
            # The encoder CUDA graph passes precomputed position embeddings.
            if position_embeddings is None:
                if position_ids is None:
                    raise ValueError(
                        "position_ids cannot be None when pixel_values.dim() is 5."
                    )
                assert image_grid_thw is not None
                position_embeddings = self.get_position_embeddings(image_grid_thw)
            target_dtype = self.patch_embedding.weight.dtype
            pixel_values = rearrange(pixel_values, "b l c h w -> (b l) c h w")
            patch_embeds = self.patch_embedding(pixel_values.to(dtype=target_dtype))
            embeddings = patch_embeds.flatten(-2).squeeze(-1)
            embeddings = embeddings + position_embeddings
            return embeddings.unsqueeze(0)
        else:
            raise ValueError(
                "Unsupported pixel_values dimension:"
                f" {pixel_values.dim()}. Expected 4 or 5."
            )

get_position_embeddings(image_grid_thw)

Interpolate the position embedding to each image grid and concat.

Source code in vllm/model_executor/models/paddleocr_vl.py
def get_position_embeddings(
    self, image_grid_thw: Sequence[tuple[int, int, int]]
) -> torch.Tensor:
    """Interpolate the position embedding to each image grid and concat."""
    weight = self.position_embedding.weight
    return torch.concat(
        [
            self.interpolate_pos_encoding(weight, h, w, True)
            .squeeze(0)
            .repeat(t, 1)
            for t, h, w in image_grid_thw
        ],
        dim=0,
    )

SiglipVisionModel

Bases: Module

Methods:

Source code in vllm/model_executor/models/paddleocr_vl.py
class SiglipVisionModel(nn.Module):
    hf_to_vllm_mapper = WeightsMapper(
        orig_to_new_stacked={
            ".q_proj": (".qkv_proj", "q"),
            ".k_proj": (".qkv_proj", "k"),
            ".v_proj": (".qkv_proj", "v"),
        },
        # The SigLIP attention pooling head and packing pos embedding are
        # present in the checkpoint but absent from this vision tower.
        orig_to_new_substr={
            "head.attention": None,
            "head.layernorm": None,
            "head.mlp": None,
            "head.probe": None,
            "packing_position_embedding": None,
        },
    )

    def __init__(
        self,
        config,
        quant_config: QuantizationConfig | None = None,
        prefix: str = "",
    ):
        super().__init__()

        self.vision_model = SiglipVisionTransformer(
            config,
            quant_config=quant_config,
            prefix=maybe_prefix(prefix, "vision_model"),
        )
        self.quant_config = quant_config

    @property
    def dtype(self) -> torch.dtype:
        return self.vision_model.embeddings.patch_embedding.weight.dtype

    @property
    def device(self) -> torch.device:
        return self.vision_model.embeddings.patch_embedding.weight.device

    def get_input_embeddings(self) -> nn.Module:
        return self.vision_model.embeddings.patch_embedding

    def prepare_encoder_metadata(
        self,
        grid_thw: Sequence[Sequence[int]],
        *,
        max_batch_size: int | None = None,
        max_seqlen_override: int | None = None,
        device: torch.device | None = None,
    ) -> dict[str, torch.Tensor | None]:
        """Compute the encoder CUDA graph metadata outside the graph.

        Args:
            grid_thw: The `[t, h, w]` patch grid of each image.
            max_batch_size: If set, pad `cu_seqlens` with empty sequences to
                `max_batch_size + 1` entries for a fixed buffer shape.
            max_seqlen_override: If set, use this value for `max_seqlen`. It is
                baked in at capture time, so it must cover any replay.
            device: Device for the returned tensors. Defaults to `self.device`.

        Returns:
            Dict with `position_embeddings`, `rotary_pos_emb`, `cu_seqlens`,
            `max_seqlen` (on CPU, or None for non-varlen backends) and
            `merge_index`.

        """
        if device is None:
            device = self.device
        embeddings = self.vision_model.embeddings
        encoder = self.vision_model.encoder
        merge_size = self.vision_model.config.spatial_merge_size
        grids = [(t, h, w) for t, h, w in grid_thw]

        seq_lens = [math.prod(grid) for grid in grids]
        if max_batch_size is not None:
            seq_lens += [0] * (max_batch_size - len(seq_lens))
        cu_seqlens = torch.from_numpy(np.cumsum([0, *seq_lens], dtype=np.int32))

        if max_seqlen_override is not None:
            max_seqlen = torch.tensor(max_seqlen_override, dtype=torch.int32)
        else:
            max_seqlen = encoder.compute_max_seqlen(cu_seqlens)

        merge_index = build_image_merge_gather_idx(grids, (merge_size, merge_size))
        return {
            "position_embeddings": embeddings.get_position_embeddings(grids),
            "rotary_pos_emb": encoder.rot_pos_emb(grids, device),
            "cu_seqlens": async_tensor_h2d(cu_seqlens, device=device),
            "max_seqlen": max_seqlen,
            "merge_index": async_tensor_h2d(merge_index, device=device),
        }

    def forward(
        self,
        pixel_values,
        interpolate_pos_encoding: bool = False,
        position_ids: torch.Tensor | None = None,
        image_grid_thw: Sequence[tuple[int, int, int]] | None = None,
        cu_seqlens: torch.Tensor | None = None,
        encoder_metadata: Mapping[str, torch.Tensor | None] | None = None,
    ) -> BaseModelOutputWithPooling:
        return self.vision_model(
            pixel_values=pixel_values,
            interpolate_pos_encoding=interpolate_pos_encoding,
            position_ids=position_ids,
            image_grid_thw=image_grid_thw,
            cu_seqlens=cu_seqlens,
            encoder_metadata=encoder_metadata,
        )

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

prepare_encoder_metadata(grid_thw, *, max_batch_size=None, max_seqlen_override=None, device=None)

Compute the encoder CUDA graph metadata outside the graph.

Parameters:

  • grid_thw

    (Sequence[Sequence[int]]) –

    The [t, h, w] patch grid of each image.

  • max_batch_size

    (int | None, default: None ) –

    If set, pad cu_seqlens with empty sequences to max_batch_size + 1 entries for a fixed buffer shape.

  • max_seqlen_override

    (int | None, default: None ) –

    If set, use this value for max_seqlen. It is baked in at capture time, so it must cover any replay.

  • device

    (device | None, default: None ) –

    Device for the returned tensors. Defaults to self.device.

Returns:

  • dict[str, Tensor | None] –

    Dict with position_embeddings, rotary_pos_emb, cu_seqlens,

  • dict[str, Tensor | None] –

    max_seqlen (on CPU, or None for non-varlen backends) and

  • dict[str, Tensor | None] –

    merge_index.

Source code in vllm/model_executor/models/paddleocr_vl.py
def prepare_encoder_metadata(
    self,
    grid_thw: Sequence[Sequence[int]],
    *,
    max_batch_size: int | None = None,
    max_seqlen_override: int | None = None,
    device: torch.device | None = None,
) -> dict[str, torch.Tensor | None]:
    """Compute the encoder CUDA graph metadata outside the graph.

    Args:
        grid_thw: The `[t, h, w]` patch grid of each image.
        max_batch_size: If set, pad `cu_seqlens` with empty sequences to
            `max_batch_size + 1` entries for a fixed buffer shape.
        max_seqlen_override: If set, use this value for `max_seqlen`. It is
            baked in at capture time, so it must cover any replay.
        device: Device for the returned tensors. Defaults to `self.device`.

    Returns:
        Dict with `position_embeddings`, `rotary_pos_emb`, `cu_seqlens`,
        `max_seqlen` (on CPU, or None for non-varlen backends) and
        `merge_index`.

    """
    if device is None:
        device = self.device
    embeddings = self.vision_model.embeddings
    encoder = self.vision_model.encoder
    merge_size = self.vision_model.config.spatial_merge_size
    grids = [(t, h, w) for t, h, w in grid_thw]

    seq_lens = [math.prod(grid) for grid in grids]
    if max_batch_size is not None:
        seq_lens += [0] * (max_batch_size - len(seq_lens))
    cu_seqlens = torch.from_numpy(np.cumsum([0, *seq_lens], dtype=np.int32))

    if max_seqlen_override is not None:
        max_seqlen = torch.tensor(max_seqlen_override, dtype=torch.int32)
    else:
        max_seqlen = encoder.compute_max_seqlen(cu_seqlens)

    merge_index = build_image_merge_gather_idx(grids, (merge_size, merge_size))
    return {
        "position_embeddings": embeddings.get_position_embeddings(grids),
        "rotary_pos_emb": encoder.rot_pos_emb(grids, device),
        "cu_seqlens": async_tensor_h2d(cu_seqlens, device=device),
        "max_seqlen": max_seqlen,
        "merge_index": async_tensor_h2d(merge_index, device=device),
    }

all_gather_interleave(local_tensor, hidden_size, tp_size)

All-gather the input tensor interleavely across model parallel group.

Source code in vllm/model_executor/models/paddleocr_vl.py
def all_gather_interleave(local_tensor: torch.Tensor, hidden_size: int, tp_size: int):
    """All-gather the input tensor interleavely across model parallel group."""
    import torch.distributed as dist

    gathered_tensors = [torch.zeros_like(local_tensor) for _ in range(tp_size)]
    dist.all_gather(
        gathered_tensors, local_tensor, group=parallel_state.get_tp_group().device_group
    )

    gathered_tensors_split = [
        torch.split(tensor, hidden_size // tp_size, -1) for tensor in gathered_tensors
    ]
    ordered_tensors = [
        tensor for pair in zip(*gathered_tensors_split) for tensor in pair
    ]
    result_tensor = torch.cat(ordered_tensors, dim=-1)
    return result_tensor

smart_resize(height, width, factor=28, min_pixels=28 * 28 * 130, max_pixels=28 * 28 * 1280)

Rescales the image so that the following conditions are met:

  1. Both dimensions (height and width) are divisible by 'factor'.

  2. The total number of pixels is within the range ['min_pixels', 'max_pixels'].

  3. The aspect ratio of the image is maintained as closely as possible.

Source code in vllm/model_executor/models/paddleocr_vl.py
def smart_resize(
    height: int,
    width: int,
    factor: int = 28,
    min_pixels: int = 28 * 28 * 130,
    max_pixels: int = 28 * 28 * 1280,
):
    """Rescales the image so that the following conditions are met:

    1. Both dimensions (height and width) are divisible by 'factor'.

    2. The total number of pixels is within the range ['min_pixels', 'max_pixels'].

    3. The aspect ratio of the image is maintained as closely as possible.

    """
    if height < factor:
        width = round((width * factor) / height)
        height = factor

    if width < factor:
        height = round((height * factor) / width)
        width = factor

    if max(height, width) / min(height, width) > 200:
        raise ValueError(
            f"absolute aspect ratio must be smaller than 200, "
            f"got {max(height, width) / min(height, width)}"
        )
    h_bar = round(height / factor) * factor
    w_bar = round(width / factor) * factor
    if h_bar * w_bar > max_pixels:
        beta = math.sqrt((height * width) / max_pixels)
        h_bar = math.floor(height / beta / factor) * factor
        w_bar = math.floor(width / beta / factor) * factor
    elif h_bar * w_bar < min_pixels:
        beta = math.sqrt(min_pixels / (height * width))
        h_bar = math.ceil(height * beta / factor) * factor
        w_bar = math.ceil(width * beta / factor) * factor
    return h_bar, w_bar