Skip to content

vllm.model_executor.models.transformers.multimodal

Transformers modeling backend mixin for multi-modal models.

Classes:

MultiModalMixin

Bases: SupportsMultiModal, SupportsMRoPE, Base

Methods:

  • get_language_model –

    Transformers modeling backend multimodal classes do not contain a separate

  • get_mm_mapping –

    Get the module prefix in multimodal models

Source code in vllm/model_executor/models/transformers/multimodal.py
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
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
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
class MultiModalMixin(SupportsMultiModal, SupportsMRoPE, Base):
    def __init__(self, *, vllm_config: "VllmConfig", prefix: str = ""):
        # Skip SupportsMRoPE.__init__ and call the next class in MRO
        super(SupportsMRoPE, self).__init__(vllm_config=vllm_config, prefix=prefix)
        self._init_deepstack(vllm_config)
        self._init_per_layer_inputs(vllm_config)

    def _init_deepstack(self, vllm_config: "VllmConfig"):
        """DeepStack models add extra vision features to the image tokens after
        each of the first few decoder layers. Transformers selects those tokens with a
        boolean mask, which CUDA graphs can't capture, so we add the features from a
        fixed-address buffer instead."""
        vision_config = getattr(self.config, "vision_config", None)
        indexes = getattr(vision_config, "deepstack_visual_indexes", None) or []
        self.deepstack_num_levels = len(indexes)
        self.deepstack_num_tokens = 0
        self.register_buffer("deepstack_input_embeds", None, persistent=False)
        if not self.deepstack_num_levels:
            if "deepstack" in self.config.to_json_string():
                logger.warning_once(
                    "Only DeepStack configured by `vision_config."
                    "deepstack_visual_indexes` is supported, so this model's "
                    "DeepStack features will be ignored and outputs may be degraded."
                )
            return
        if (
            not self.pp_group.is_first_rank
            and self.start_layer < self.deepstack_num_levels
        ):
            raise ValueError(
                f"The first {self.deepstack_num_levels} decoder layers receive "
                "DeepStack features and must be on the first pipeline parallel rank."
            )
        if not self.pp_group.is_first_rank:
            return
        if (layers := self._decoder_layers) is None:
            raise ValueError(
                f"Could not identify the decoder layers of {type(self.model)} to add "
                "DeepStack features to."
            )
        max_tokens = vllm_config.scheduler_config.max_num_batched_tokens
        hidden_size = self.text_config.hidden_size
        buffer = torch.zeros(self.deepstack_num_levels, 1, max_tokens, hidden_size)
        # CUDA graphs replay their capture-time input addresses
        self.register_buffer("deepstack_input_embeds", buffer, persistent=False)

        def add_deepstack(level: int):
            def hook(module, args, output: torch.Tensor) -> torch.Tensor:
                return output + self.deepstack_input_embeds[level, :, : output.shape[1]]

            return hook

        # Ignore levels beyond the last decoder layer
        for level, layer in zip(range(self.deepstack_num_levels), layers):
            layer.register_forward_hook(add_deepstack(level))

    def _set_deepstack_input_embeds(
        self,
        multimodal_embeddings: MultiModalEmbeddings | None,
        is_multimodal: torch.Tensor | None,
    ) -> MultiModalEmbeddings | None:
        """Write the DeepStack features to their buffer, returning the embeddings
        without them."""
        # Cleared here rather than after `forward`, which full CUDA graphs skip
        if self.deepstack_num_tokens:
            self.deepstack_input_embeds[:, 0, : self.deepstack_num_tokens].zero_()
            self.deepstack_num_tokens = 0
        if multimodal_embeddings is None or len(multimodal_embeddings) == 0:
            return multimodal_embeddings
        multimodal_embeddings, deepstack_flat = self._split_deepstack_embeds(
            multimodal_embeddings
        )
        is_multimodal = _require_is_multimodal(is_multimodal)
        num_tokens = is_multimodal.numel()
        buffer = self.deepstack_input_embeds[:, 0, :num_tokens]
        # If is_multimodal is on CPU this avoids a D2H sync
        buffer[:, is_multimodal] = deepstack_flat.to(buffer.dtype)
        self.deepstack_num_tokens = num_tokens
        return multimodal_embeddings

    def _init_per_layer_inputs(self, vllm_config: "VllmConfig"):
        """Per-layer embedding models give each decoder layer an extra embedding of
        every token. Transformers looks them up from `input_ids`, which the model
        doesn't receive alongside `inputs_embeds`, so we look them up in
        `embed_input_ids` and pass them from a fixed-address buffer instead."""
        self.register_buffer("per_layer_inputs", None, persistent=False)
        decoder = self.model.get_decoder()
        # Some checkpoints of per-layer embedding architectures disable them
        size: int = getattr(decoder, "hidden_size_per_layer_input", 0)
        if not (size and hasattr(decoder, "get_per_layer_inputs")):
            return
        self.check_version("5.21.0", "per-layer embedding models")
        if self.pp_group.world_size > 1:
            raise ValueError(
                "Transformers modeling backend does not support pipeline "
                "parallelism for per-layer embedding models."
            )
        max_tokens = vllm_config.scheduler_config.max_num_batched_tokens
        num_layers = self.text_config.num_hidden_layers
        buffer = torch.zeros(1, max_tokens, num_layers, size)
        # CUDA graphs replay their capture-time input addresses
        self.register_buffer("per_layer_inputs", buffer, persistent=False)

        def add_per_layer_inputs(module, args, kwargs):
            if (inputs_embeds := kwargs.get("inputs_embeds")) is not None:
                num_tokens = inputs_embeds.shape[1]
                kwargs["per_layer_inputs"] = self.per_layer_inputs[:, :num_tokens]
            return args, kwargs

        self.model.register_forward_pre_hook(add_per_layer_inputs, with_kwargs=True)

    def _set_per_layer_inputs(
        self, input_ids: torch.Tensor, is_multimodal: torch.Tensor | None
    ):
        if is_multimodal is not None:
            is_multimodal = is_multimodal.to(input_ids.device, non_blocking=True)
            input_ids = input_ids.masked_fill(is_multimodal, 0)
        per_layer_inputs = self.model.get_decoder().get_per_layer_inputs(input_ids)
        self.per_layer_inputs[0, : len(input_ids)].copy_(per_layer_inputs)

    def _find_encoder_classes(
        self, model: "PreTrainedModel"
    ) -> dict[str, type["PreTrainedModel"]]:
        """Modalities whose encoder cannot be told apart from the model itself are
        omitted, as are those `get_encoder` rejects or has no encoder for."""
        encoder_classes: dict[str, type[PreTrainedModel]] = {}
        for modality in _MODALITY_TO_TOKEN_TYPE_ID:
            try:
                encoder = model.get_encoder(modality=modality)
            except (TypeError, ValueError):
                continue
            if encoder is not None and type(encoder) is not type(model):
                encoder_classes[modality] = type(encoder)
        return encoder_classes

    @contextmanager
    def _mark_model_components(self, vllm_config: "VllmConfig"):
        model_config = vllm_config.model_config
        encoder_classes = self._pre_trained_model_classes.encoders
        if not encoder_classes:
            logger.debug("No encoders identified, so no components will be marked")
            yield
            return

        if model_config.skip_tokenizer_init:
            # Determining the supported modalities needs the HF processor, which in
            # turn needs a tokenizer
            mm_config = model_config.get_multimodal_config()
            if mm_config.mm_encoder_only or any(
                mm_config.get_limit_per_prompt(modality) == 0
                for modality in encoder_classes
            ):
                logger.warning_once(
                    "Unable to determine the supported modalities without a "
                    "tokenizer, so no model components will be skipped."
                )
            yield
            return

        # Modalities we don't serve report a limit of 999, which would stop their
        # encoder ever being skipped
        supported_modalities = MULTIMODAL_REGISTRY.get_processing_info(
            model_config
        ).supported_mm_limits

        # One encoder often serves several modalities, and may only be skipped when
        # all of them are disabled, so mark it once for the whole set
        modalities_by_encoder = defaultdict(set)
        for modality, encoder_cls in encoder_classes.items():
            if modality in supported_modalities:
                modalities_by_encoder[encoder_cls].add(modality)

        with ExitStack() as stack:
            stack.enter_context(
                self._mark_language_model(
                    vllm_config, targets=self._pre_trained_model_classes.decoder
                )
            )
            for encoder_cls, modalities in modalities_by_encoder.items():
                # Built on meta, so `recursive_replace` offloads them when materialised
                tower = self._mark_tower_model(
                    vllm_config, modalities, targets=encoder_cls, auto_offload=False
                )
                stack.enter_context(tower)
            yield

    def _decorate_for_torch_compile(self):
        """Decorate the model's decoder and encoder classes to indicate to vLLM
        that they support torch compile if `can_enable_torch_compile` and
        `should_torch_compile_mm_encoder` are True respectively.
        """
        super()._decorate_for_torch_compile()
        # Decorate the encoder model classes to support torch compile if needed
        if self.compilation_config.compile_mm_encoder:
            encoder_classes = self._pre_trained_model_classes.encoders
            if not encoder_classes:
                raise ValueError(
                    "Unable to infer any encoder classes from the model. "
                    "You must either: update the model so that "
                    "https://huggingface.co/docs/transformers/en/main_classes/model#transformers.PreTrainedModel.get_encoder"
                    " can detect the encoders correctly, or remove "
                    "'compile_mm_encoder'."
                )
            logger.warning_once(
                "Multimodal encoder compilation with the Transformers modeling backend "
                "is an experimental feature. It relies on:\n"
                "- The encoder being torch compilable.\n"
                "- The encoder's non-tensor inputs being type hinted, because "
                "unannotated inputs are assumed to be tensors.\n"
                "- The 0-th dimension of all tensor inputs to the encoder being the "
                "dynamic dimension (e.g. sequence length, number of patches).\n"
                "Please report any issues you encounter to help us improve it."
            )
            # One encoder can serve several modalities, and must only be decorated once
            for encoder_cls in dict.fromkeys(encoder_classes.values()):
                self._decorate_cls_for_torch_compile(
                    cls=encoder_cls,
                    dynamic_arg_dims=infer_dynamic_arg_dims(encoder_cls),
                    enable_if=should_torch_compile_mm_encoder,
                    is_encoder=True,
                )

    def get_language_model(self) -> torch.nn.Module:
        """Transformers modeling backend multimodal classes do not contain a separate
        vLLM language model class. Therefore, in order to return a language model vLLM
        class, we use a wrapper to give `self` the same interface as a text model."""
        # Exclude self and object
        bases = self.__class__.mro()[1:-1]
        # Keep only classes defined in `vllm.model_executor.models.transformers`
        bases = [b for b in bases if ".transformers." in b.__module__]
        # Exclude MultiModalMixin itself
        bases = [b for b in bases if b is not MultiModalMixin]

        class LanguageModel(*bases):  # type: ignore[misc]
            # `reserve_aux_intermediate_tensor_slots` needs `config.hidden_size`
            supports_aux_hidden_states_over_pp = False

            def __init__(self, multimodal_model):
                # Don't call super().__init__() to avoid re-initialization
                self.__dict__.update(multimodal_model.__dict__)

            model = getattr_iter(self.model, ("language_model", "text_model"), None)

        return LanguageModel(self)

    def get_mm_mapping(self) -> MultiModelKeys:
        """Get the module prefix in multimodal models"""
        for name in ("language_model", "text_model"):
            if getattr(self.model, name, None) is not None:
                return MultiModelKeys.from_string_field(language_model=f"model.{name}")
        raise ValueError(
            "Could not locate the language model submodule for LoRA support"
        )

    def _split_embeddings(
        self, embeddings: torch.Tensor, split_sizes: list[int]
    ) -> list[torch.Tensor]:
        total_expected = sum(split_sizes)

        # Flatten to 2D: [total_tokens, hidden_dim]
        if embeddings.ndim > 2:
            embeddings = embeddings.reshape(-1, embeddings.shape[-1])

        total_tokens = embeddings.shape[0]
        if total_tokens == total_expected:
            # Direct match: split_sizes are actual token counts
            token_split_sizes = split_sizes
        elif total_expected > 0 and total_tokens % total_expected == 0:
            # Uniform expansion: each item expands to N tokens
            tokens_per_item = total_tokens // total_expected
            token_split_sizes = [s * tokens_per_item for s in split_sizes]
        elif total_expected > 0:
            # TODO: make this an error once we know profiling never relies on it
            if total_tokens == 0:
                raise ValueError(
                    "Encoder returned empty embeddings. "
                    f"Expected {total_expected} tokens from "
                    f"split_sizes={split_sizes}"
                )
            # Keep the counts out of the message: `warning_once` keys its cache on
            # the args, so varying them would log on every new pair
            logger.warning_once(
                "Encoder returned a different number of tokens than expected; "
                "padding or truncating to fit. The embeddings are not trustworthy "
                "outside of memory profiling."
            )
            logger.debug(
                "Encoder returned %s tokens but %s were expected",
                total_tokens,
                total_expected,
            )
            if total_tokens < total_expected:
                repeat_factor = (total_expected + total_tokens - 1) // total_tokens
                embeddings = embeddings.repeat(repeat_factor, 1)
            embeddings = embeddings[:total_expected]
            token_split_sizes = split_sizes
        else:
            return []

        return list(torch.split(embeddings, token_split_sizes, dim=0))

    def _process_audio_input(self, **kwargs) -> list[torch.Tensor] | None:
        input_features: torch.Tensor | None = kwargs.pop("input_features", None)
        if input_features is None:
            input_features = kwargs.pop("input_values", None)
        if input_features is None:
            return None

        num_audio_tokens = kwargs.pop("num_audio_tokens")
        kwargs.pop("token_type_ids", None)
        kwargs.pop("mm_token_type_ids", None)

        # Per-audio token counts are needed as Python ints to split.
        with gpu_sync_allowed():
            split_sizes = num_audio_tokens.flatten().tolist()
        if isinstance(input_features, torch.Tensor):
            # HuggingFace's `get_audio_features` implementations branch on
            # per-sample feature lengths internally.
            with gpu_sync_allowed():
                # Padded again as windows, unlike audios, are all the same length
                kwargs = {
                    key: pad_sequence(value, batch_first=True)
                    if isinstance(value, list)
                    else value
                    for key, value in kwargs.items()
                }
                audio_output = self.model.get_audio_features(
                    input_features, return_dict=True, **kwargs
                )
            return self._split_embeddings(audio_output.pooler_output, split_sizes)

        # Audios the processor left un-padded arrive as a list once their
        # lengths differ. Encode them one at a time so that none of them is
        # padded to match another.
        embeddings: list[torch.Tensor] = []
        for index, features in enumerate(input_features):
            audio_output = self.model.get_audio_features(
                features.unsqueeze(0),
                return_dict=True,
                **self._select_item_kwargs(kwargs, index, len(input_features)),
            )
            embeddings.extend(
                self._split_embeddings(audio_output.pooler_output, [split_sizes[index]])
            )
        return embeddings

    def _process_image_input(self, **kwargs) -> list[torch.Tensor] | None:
        pixel_values: torch.Tensor | None = kwargs.pop("pixel_values", None)
        image_embeds: torch.Tensor | None = kwargs.pop("image_embeds", None)
        # Model might use `image_patches` instead of `pixel_values`
        if pixel_values is None:
            pixel_values = kwargs.pop("image_patches", None)

        if image_embeds is not None:
            return [image_embeds]

        if pixel_values is None:
            return None

        return self._process_vision_input(
            "image", pixel_values, kwargs.pop("num_image_patches"), **kwargs
        )

    def _process_video_input(self, **kwargs) -> list[torch.Tensor] | None:
        pixel_values_videos: torch.Tensor | None = kwargs.pop(
            "pixel_values_videos", None
        )
        if pixel_values_videos is None:
            return None

        kwargs.pop("second_per_grid_ts", None)
        kwargs.pop("use_audio_in_video", None)
        return self._process_vision_input(
            "video", pixel_values_videos, kwargs.pop("num_video_patches"), **kwargs
        )

    def _process_vision_input(
        self,
        modality: str,
        pixel_values: torch.Tensor,
        num_patches: torch.Tensor,
        **kwargs,
    ) -> list[torch.Tensor]:
        split_sizes = num_patches.flatten().tolist()
        if isinstance(pixel_values, torch.Tensor):
            vision_embeddings = self._get_features(modality, pixel_values, **kwargs)
            if isinstance(vision_embeddings, torch.Tensor):
                return self._split_embeddings(vision_embeddings, split_sizes)
            if len(vision_embeddings) == len(split_sizes):
                return list(vision_embeddings)
            # Encoders which return one entry per batch row (Transformers >= 5.20.1)
            return self._split_embeddings(
                torch.cat(list(vision_embeddings)), split_sizes
            )

        # Items the processor left un-padded arrive as a list once their
        # shapes differ. Encode them one at a time so that none of them is
        # padded to match another.
        embeddings: list[torch.Tensor] = []
        for index, item in enumerate(pixel_values):
            features = self._get_features(
                modality,
                item.unsqueeze(0),
                **self._select_item_kwargs(kwargs, index, len(pixel_values)),
            )
            # Encoders which return one entry per item return a single entry
            if not isinstance(features, torch.Tensor):
                features = torch.cat(list(features))
            embeddings.extend(self._split_embeddings(features, [split_sizes[index]]))
        return embeddings

    def _select_item_kwargs(
        self, kwargs: dict[str, Any], index: int, num_items: int
    ) -> dict[str, Any]:
        """Narrow the entries of `kwargs` that hold one row per item down to the item
        at `index`. Length is all there is to match on, so an unrelated entry of the
        same length is narrowed too."""

        def select(value: torch.Tensor | list) -> torch.Tensor | list:
            if isinstance(value, torch.Tensor):
                return value[index : index + 1]
            # Ragged fields arrive as a list of per-item tensors
            item = value[index]
            return item.unsqueeze(0) if isinstance(item, torch.Tensor) else [item]

        return {
            key: select(value)
            if isinstance(value, (torch.Tensor, list)) and len(value) == num_items
            else value
            for key, value in kwargs.items()
        }

    def _get_features(self, modality: str, pixel_values: torch.Tensor, **kwargs) -> Any:
        # grid_thw fields are registered keep_on_cpu; restore the on-device
        # placement that HF get_*_features implementations expect.
        for key, value in kwargs.items():
            if isinstance(value, torch.Tensor) and value.is_cpu:
                kwargs[key] = async_tensor_h2d(value, pixel_values.device)

        # The underlying HuggingFace `get_*_features` implementations
        # contain model-internal syncs (e.g. Idefics3 filters all-zero
        # padding images via boolean-mask indexing, LlavaOnevision
        # branches on per-sample batch counts).
        with gpu_sync_allowed():
            get_modality_features = getattr(self.model, f"get_{modality}_features")
            features = get_modality_features(pixel_values, return_dict=True, **kwargs)
        embeddings = features.pooler_output
        if not self.deepstack_num_levels:
            return embeddings
        # Carried alongside the embeddings so the encoder cache keeps them together
        if not (deepstack := getattr(features, "deepstack_features", None)):
            logger.warning_once(
                "`get_%s_features` returned no `deepstack_features`, so DeepStack "
                "features will be ignored and outputs may be degraded.",
                modality,
            )
            return embeddings
        if isinstance(embeddings, torch.Tensor):
            return torch.cat([embeddings, *deepstack], dim=-1)
        return [torch.cat(item, dim=-1) for item in zip(embeddings, *deepstack)]

    def embed_multimodal(self, **kwargs) -> MultiModalEmbeddings:
        # Each helper detects its own inputs. We are called once per modality, so the
        # leftovers a helper forwards to the HF model can't belong to the other one.
        embeddings: list[torch.Tensor] = []
        for process_input in (
            self._process_audio_input,
            self._process_image_input,
            self._process_video_input,
        ):
            embeddings.extend(process_input(**kwargs) or [])
        return embeddings

    def _split_deepstack_embeds(
        self, multimodal_embeddings: MultiModalEmbeddings
    ) -> tuple[list[torch.Tensor], torch.Tensor]:
        """Split the DeepStack features off `multimodal_embeddings`."""
        hidden_size = self.text_config.hidden_size
        deepstack_size = hidden_size * self.deepstack_num_levels
        embeddings, deepstack = [], []
        for item in multimodal_embeddings:
            embeddings.append(item[..., :hidden_size])
            # Precomputed embeddings have no DeepStack features
            if item.shape[-1] == hidden_size:
                deepstack.append(item.new_zeros(*item.shape[:-1], deepstack_size))
            else:
                deepstack.append(item[..., hidden_size:])
        # [num_mm_tokens, levels * hidden] -> [levels, num_mm_tokens, hidden]
        deepstack_flat = torch.cat(deepstack).reshape(-1, deepstack_size)
        deepstack_flat = deepstack_flat.unflatten(-1, (-1, hidden_size)).transpose(0, 1)
        return embeddings, deepstack_flat

    def embed_input_ids(
        self,
        input_ids: torch.Tensor,
        multimodal_embeddings: MultiModalEmbeddings | None = None,
        *,
        is_multimodal: torch.Tensor | None = None,
    ) -> torch.Tensor:
        if self.per_layer_inputs is not None:
            self._set_per_layer_inputs(input_ids, is_multimodal)
        if self.deepstack_input_embeds is not None:
            multimodal_embeddings = self._set_deepstack_input_embeds(
                multimodal_embeddings, is_multimodal
            )
        return super().embed_input_ids(
            input_ids, multimodal_embeddings, is_multimodal=is_multimodal
        )

    def get_mrope_input_positions(
        self,
        input_tokens: list[int],
        mm_features: list[MultiModalFeatureSpec],
    ) -> tuple[torch.Tensor, int]:
        gathered = MultiModalFeatureSpec.gather_kwargs(
            mm_features,
            {
                "image_grid_thw",
                "video_grid_thw",
                "second_per_grid_ts",
                "audio_feature_lengths",
                "use_audio_in_video",
            },
        )

        def stack(name: str) -> torch.Tensor | None:
            values = gathered.get(name)
            return torch.stack(values) if values else None

        use_audio_in_video = any(gathered.get("use_audio_in_video", [])) or None

        # `get_rope_index` doesn't always accept arbitrary `kwargs`
        if not hasattr(self, "_get_rope_index_kwarg_names"):
            import inspect

            params = inspect.signature(self.model.get_rope_index).parameters
            self._get_rope_index_kwarg_names = (
                None
                if any(p.kind == inspect.Parameter.VAR_KEYWORD for p in params.values())
                else frozenset(params)
            )

        kwarg_names = self._get_rope_index_kwarg_names

        def accepts_kwarg(name: str) -> bool:
            return kwarg_names is None or name in kwarg_names

        if gathered.get("audio_feature_lengths") and not accepts_kwarg("audio_seqlens"):
            raise NotImplementedError(
                "Transformers modeling backend does not support audio inputs in "
                "M-RoPE models whose `get_rope_index` takes no `audio_seqlens`."
            )

        seconds_name = (
            "second_per_grid_ts"
            if accepts_kwarg("second_per_grid_ts")
            else "second_per_grids"
        )

        # Drop a grid the model can't accept only when there is nothing to pass.
        kwargs = {
            name: value
            for name, value in (
                ("image_grid_thw", stack("image_grid_thw")),
                ("video_grid_thw", stack("video_grid_thw")),
                (seconds_name, stack("second_per_grid_ts")),
                ("audio_seqlens", stack("audio_feature_lengths")),
                ("use_audio_in_video", use_audio_in_video),
            )
            if value is not None or accepts_kwarg(name)
        }
        if accepts_kwarg("attention_mask"):
            kwargs["attention_mask"] = torch.ones(1, len(input_tokens), dtype=torch.int)
        if accepts_kwarg("mm_token_type_ids"):
            mm_token_type_ids = torch.zeros(len(input_tokens), dtype=torch.int)
            for feature in mm_features:
                position = feature.mm_position
                offset, length = position.offset, position.length
                is_embed = position.is_embed
                if is_embed is None:
                    is_embed = slice(None)
                mm_token_type_id = _MODALITY_TO_TOKEN_TYPE_ID[feature.modality]
                mm_token_type_ids[offset : offset + length][is_embed] = mm_token_type_id
            kwargs["mm_token_type_ids"] = mm_token_type_ids.unsqueeze(0)

        mrope_positions, mrope_position_delta = self.model.get_rope_index(
            input_ids=token_ids_to_tensor(input_tokens).unsqueeze(0),
            **kwargs,
        )

        mrope_positions = mrope_positions[:, 0]
        mrope_position_delta = mrope_position_delta[0].item()

        return mrope_positions, mrope_position_delta

_decorate_for_torch_compile()

Decorate the model's decoder and encoder classes to indicate to vLLM that they support torch compile if can_enable_torch_compile and should_torch_compile_mm_encoder are True respectively.

Source code in vllm/model_executor/models/transformers/multimodal.py
def _decorate_for_torch_compile(self):
    """Decorate the model's decoder and encoder classes to indicate to vLLM
    that they support torch compile if `can_enable_torch_compile` and
    `should_torch_compile_mm_encoder` are True respectively.
    """
    super()._decorate_for_torch_compile()
    # Decorate the encoder model classes to support torch compile if needed
    if self.compilation_config.compile_mm_encoder:
        encoder_classes = self._pre_trained_model_classes.encoders
        if not encoder_classes:
            raise ValueError(
                "Unable to infer any encoder classes from the model. "
                "You must either: update the model so that "
                "https://huggingface.co/docs/transformers/en/main_classes/model#transformers.PreTrainedModel.get_encoder"
                " can detect the encoders correctly, or remove "
                "'compile_mm_encoder'."
            )
        logger.warning_once(
            "Multimodal encoder compilation with the Transformers modeling backend "
            "is an experimental feature. It relies on:\n"
            "- The encoder being torch compilable.\n"
            "- The encoder's non-tensor inputs being type hinted, because "
            "unannotated inputs are assumed to be tensors.\n"
            "- The 0-th dimension of all tensor inputs to the encoder being the "
            "dynamic dimension (e.g. sequence length, number of patches).\n"
            "Please report any issues you encounter to help us improve it."
        )
        # One encoder can serve several modalities, and must only be decorated once
        for encoder_cls in dict.fromkeys(encoder_classes.values()):
            self._decorate_cls_for_torch_compile(
                cls=encoder_cls,
                dynamic_arg_dims=infer_dynamic_arg_dims(encoder_cls),
                enable_if=should_torch_compile_mm_encoder,
                is_encoder=True,
            )

_find_encoder_classes(model)

Modalities whose encoder cannot be told apart from the model itself are omitted, as are those get_encoder rejects or has no encoder for.

Source code in vllm/model_executor/models/transformers/multimodal.py
def _find_encoder_classes(
    self, model: "PreTrainedModel"
) -> dict[str, type["PreTrainedModel"]]:
    """Modalities whose encoder cannot be told apart from the model itself are
    omitted, as are those `get_encoder` rejects or has no encoder for."""
    encoder_classes: dict[str, type[PreTrainedModel]] = {}
    for modality in _MODALITY_TO_TOKEN_TYPE_ID:
        try:
            encoder = model.get_encoder(modality=modality)
        except (TypeError, ValueError):
            continue
        if encoder is not None and type(encoder) is not type(model):
            encoder_classes[modality] = type(encoder)
    return encoder_classes

_init_deepstack(vllm_config)

DeepStack models add extra vision features to the image tokens after each of the first few decoder layers. Transformers selects those tokens with a boolean mask, which CUDA graphs can't capture, so we add the features from a fixed-address buffer instead.

Source code in vllm/model_executor/models/transformers/multimodal.py
def _init_deepstack(self, vllm_config: "VllmConfig"):
    """DeepStack models add extra vision features to the image tokens after
    each of the first few decoder layers. Transformers selects those tokens with a
    boolean mask, which CUDA graphs can't capture, so we add the features from a
    fixed-address buffer instead."""
    vision_config = getattr(self.config, "vision_config", None)
    indexes = getattr(vision_config, "deepstack_visual_indexes", None) or []
    self.deepstack_num_levels = len(indexes)
    self.deepstack_num_tokens = 0
    self.register_buffer("deepstack_input_embeds", None, persistent=False)
    if not self.deepstack_num_levels:
        if "deepstack" in self.config.to_json_string():
            logger.warning_once(
                "Only DeepStack configured by `vision_config."
                "deepstack_visual_indexes` is supported, so this model's "
                "DeepStack features will be ignored and outputs may be degraded."
            )
        return
    if (
        not self.pp_group.is_first_rank
        and self.start_layer < self.deepstack_num_levels
    ):
        raise ValueError(
            f"The first {self.deepstack_num_levels} decoder layers receive "
            "DeepStack features and must be on the first pipeline parallel rank."
        )
    if not self.pp_group.is_first_rank:
        return
    if (layers := self._decoder_layers) is None:
        raise ValueError(
            f"Could not identify the decoder layers of {type(self.model)} to add "
            "DeepStack features to."
        )
    max_tokens = vllm_config.scheduler_config.max_num_batched_tokens
    hidden_size = self.text_config.hidden_size
    buffer = torch.zeros(self.deepstack_num_levels, 1, max_tokens, hidden_size)
    # CUDA graphs replay their capture-time input addresses
    self.register_buffer("deepstack_input_embeds", buffer, persistent=False)

    def add_deepstack(level: int):
        def hook(module, args, output: torch.Tensor) -> torch.Tensor:
            return output + self.deepstack_input_embeds[level, :, : output.shape[1]]

        return hook

    # Ignore levels beyond the last decoder layer
    for level, layer in zip(range(self.deepstack_num_levels), layers):
        layer.register_forward_hook(add_deepstack(level))

_init_per_layer_inputs(vllm_config)

Per-layer embedding models give each decoder layer an extra embedding of every token. Transformers looks them up from input_ids, which the model doesn't receive alongside inputs_embeds, so we look them up in embed_input_ids and pass them from a fixed-address buffer instead.

Source code in vllm/model_executor/models/transformers/multimodal.py
def _init_per_layer_inputs(self, vllm_config: "VllmConfig"):
    """Per-layer embedding models give each decoder layer an extra embedding of
    every token. Transformers looks them up from `input_ids`, which the model
    doesn't receive alongside `inputs_embeds`, so we look them up in
    `embed_input_ids` and pass them from a fixed-address buffer instead."""
    self.register_buffer("per_layer_inputs", None, persistent=False)
    decoder = self.model.get_decoder()
    # Some checkpoints of per-layer embedding architectures disable them
    size: int = getattr(decoder, "hidden_size_per_layer_input", 0)
    if not (size and hasattr(decoder, "get_per_layer_inputs")):
        return
    self.check_version("5.21.0", "per-layer embedding models")
    if self.pp_group.world_size > 1:
        raise ValueError(
            "Transformers modeling backend does not support pipeline "
            "parallelism for per-layer embedding models."
        )
    max_tokens = vllm_config.scheduler_config.max_num_batched_tokens
    num_layers = self.text_config.num_hidden_layers
    buffer = torch.zeros(1, max_tokens, num_layers, size)
    # CUDA graphs replay their capture-time input addresses
    self.register_buffer("per_layer_inputs", buffer, persistent=False)

    def add_per_layer_inputs(module, args, kwargs):
        if (inputs_embeds := kwargs.get("inputs_embeds")) is not None:
            num_tokens = inputs_embeds.shape[1]
            kwargs["per_layer_inputs"] = self.per_layer_inputs[:, :num_tokens]
        return args, kwargs

    self.model.register_forward_pre_hook(add_per_layer_inputs, with_kwargs=True)

_select_item_kwargs(kwargs, index, num_items)

Narrow the entries of kwargs that hold one row per item down to the item at index. Length is all there is to match on, so an unrelated entry of the same length is narrowed too.

Source code in vllm/model_executor/models/transformers/multimodal.py
def _select_item_kwargs(
    self, kwargs: dict[str, Any], index: int, num_items: int
) -> dict[str, Any]:
    """Narrow the entries of `kwargs` that hold one row per item down to the item
    at `index`. Length is all there is to match on, so an unrelated entry of the
    same length is narrowed too."""

    def select(value: torch.Tensor | list) -> torch.Tensor | list:
        if isinstance(value, torch.Tensor):
            return value[index : index + 1]
        # Ragged fields arrive as a list of per-item tensors
        item = value[index]
        return item.unsqueeze(0) if isinstance(item, torch.Tensor) else [item]

    return {
        key: select(value)
        if isinstance(value, (torch.Tensor, list)) and len(value) == num_items
        else value
        for key, value in kwargs.items()
    }

_set_deepstack_input_embeds(multimodal_embeddings, is_multimodal)

Write the DeepStack features to their buffer, returning the embeddings without them.

Source code in vllm/model_executor/models/transformers/multimodal.py
def _set_deepstack_input_embeds(
    self,
    multimodal_embeddings: MultiModalEmbeddings | None,
    is_multimodal: torch.Tensor | None,
) -> MultiModalEmbeddings | None:
    """Write the DeepStack features to their buffer, returning the embeddings
    without them."""
    # Cleared here rather than after `forward`, which full CUDA graphs skip
    if self.deepstack_num_tokens:
        self.deepstack_input_embeds[:, 0, : self.deepstack_num_tokens].zero_()
        self.deepstack_num_tokens = 0
    if multimodal_embeddings is None or len(multimodal_embeddings) == 0:
        return multimodal_embeddings
    multimodal_embeddings, deepstack_flat = self._split_deepstack_embeds(
        multimodal_embeddings
    )
    is_multimodal = _require_is_multimodal(is_multimodal)
    num_tokens = is_multimodal.numel()
    buffer = self.deepstack_input_embeds[:, 0, :num_tokens]
    # If is_multimodal is on CPU this avoids a D2H sync
    buffer[:, is_multimodal] = deepstack_flat.to(buffer.dtype)
    self.deepstack_num_tokens = num_tokens
    return multimodal_embeddings

_split_deepstack_embeds(multimodal_embeddings)

Split the DeepStack features off multimodal_embeddings.

Source code in vllm/model_executor/models/transformers/multimodal.py
def _split_deepstack_embeds(
    self, multimodal_embeddings: MultiModalEmbeddings
) -> tuple[list[torch.Tensor], torch.Tensor]:
    """Split the DeepStack features off `multimodal_embeddings`."""
    hidden_size = self.text_config.hidden_size
    deepstack_size = hidden_size * self.deepstack_num_levels
    embeddings, deepstack = [], []
    for item in multimodal_embeddings:
        embeddings.append(item[..., :hidden_size])
        # Precomputed embeddings have no DeepStack features
        if item.shape[-1] == hidden_size:
            deepstack.append(item.new_zeros(*item.shape[:-1], deepstack_size))
        else:
            deepstack.append(item[..., hidden_size:])
    # [num_mm_tokens, levels * hidden] -> [levels, num_mm_tokens, hidden]
    deepstack_flat = torch.cat(deepstack).reshape(-1, deepstack_size)
    deepstack_flat = deepstack_flat.unflatten(-1, (-1, hidden_size)).transpose(0, 1)
    return embeddings, deepstack_flat

get_language_model()

Transformers modeling backend multimodal classes do not contain a separate vLLM language model class. Therefore, in order to return a language model vLLM class, we use a wrapper to give self the same interface as a text model.

Source code in vllm/model_executor/models/transformers/multimodal.py
def get_language_model(self) -> torch.nn.Module:
    """Transformers modeling backend multimodal classes do not contain a separate
    vLLM language model class. Therefore, in order to return a language model vLLM
    class, we use a wrapper to give `self` the same interface as a text model."""
    # Exclude self and object
    bases = self.__class__.mro()[1:-1]
    # Keep only classes defined in `vllm.model_executor.models.transformers`
    bases = [b for b in bases if ".transformers." in b.__module__]
    # Exclude MultiModalMixin itself
    bases = [b for b in bases if b is not MultiModalMixin]

    class LanguageModel(*bases):  # type: ignore[misc]
        # `reserve_aux_intermediate_tensor_slots` needs `config.hidden_size`
        supports_aux_hidden_states_over_pp = False

        def __init__(self, multimodal_model):
            # Don't call super().__init__() to avoid re-initialization
            self.__dict__.update(multimodal_model.__dict__)

        model = getattr_iter(self.model, ("language_model", "text_model"), None)

    return LanguageModel(self)

get_mm_mapping()

Get the module prefix in multimodal models

Source code in vllm/model_executor/models/transformers/multimodal.py
def get_mm_mapping(self) -> MultiModelKeys:
    """Get the module prefix in multimodal models"""
    for name in ("language_model", "text_model"):
        if getattr(self.model, name, None) is not None:
            return MultiModelKeys.from_string_field(language_model=f"model.{name}")
    raise ValueError(
        "Could not locate the language model submodule for LoRA support"
    )

MultiModalProcessingInfo

Bases: BaseProcessingInfo

Methods:

Source code in vllm/model_executor/models/transformers/multimodal.py
class MultiModalProcessingInfo(BaseProcessingInfo):
    def _get_audio_processor(self) -> Any:
        # TODO: drop feature_extractor branch once huggingface/transformers#44394 lands.
        return getattr_iter(
            self.get_hf_processor(), ("audio_processor", "feature_extractor")
        )

    @cached_property
    def _is_audio_model(self) -> bool:
        return self._get_audio_processor() is not None

    @cached_property
    def _is_image_model(self) -> bool:
        return hasattr(self.get_hf_processor(), "image_processor")

    @cached_property
    def _is_video_model(self) -> bool:
        if not hasattr(self.get_hf_processor(), "video_processor"):
            return False
        try:
            Base.check_version("5.18.0", "video inputs")
        except ImportError as e:
            logger.info_once("%s, so video inputs are disabled.", e)
            return False
        num_frames = self._get_min_video_frames()
        side = _MIN_DUMMY_SIDE
        # TODO: Drop the except branch once every video processor can count, see
        # https://github.com/huggingface/transformers/issues/43329
        try:
            mm_tokens = self._get_num_mm_tokens(video_sizes=([num_frames, side, side],))
        except AttributeError:
            logger.info_once(
                "%s cannot count video tokens yet, so the Transformers modeling "
                "backend serves this model without video inputs. Please report "
                "this to transformers so it can be fixed.",
                type(self.get_hf_processor()).__name__,
            )
            return False
        return mm_tokens["num_video_tokens"] is not None

    @cached_property
    def _video_needs_metadata(self) -> bool:
        video_processor = getattr(self.get_hf_processor(), "video_processor", None)
        return getattr(video_processor, "do_sample_frames", False)

    def _get_min_video_frames(self) -> int:
        video_processor = self.get_hf_processor().video_processor
        # A processor without `temporal_patch_size` groups no frames, so one is enough
        return getattr(video_processor, "temporal_patch_size", 1)

    def _get_supported_modalities(self) -> list[str]:
        modalities = []
        if self._is_audio_model:
            modalities.append("audio")
        if self._is_image_model:
            modalities.append("image")
        if self._is_video_model:
            modalities.append("video")
        if not modalities:
            raise ValueError(
                f"{type(self.get_hf_processor()).__name__} exposes no image, video "
                "or audio processor, so the Transformers modeling backend cannot "
                "serve this model as multi-modal."
            )
        return modalities

    @cached_property
    def _fuses_audio_into_video(self) -> bool:
        return bool(get_load_audio_from_video(self.ctx.get_merged_mm_kwargs({})))

    def _get_placeholder_ids(self, modality: str) -> list[int]:
        token = getattr(self.get_hf_processor(), f"{modality}_token")
        if isinstance(token, str):
            tokenizer = self.get_tokenizer()
            return cached_encode(tokenizer, token, add_special_tokens=False)
        if isinstance(token, int):
            return [token]
        return list(token)

    def _get_placeholder_id(self, modality: str) -> int | None:
        """The placeholder token id, if the placeholder is a single token."""
        ids = self._get_placeholder_ids(modality)
        return ids[0] if len(ids) == 1 else None

    def _get_audio_sampling_rate(self) -> float:
        sub = self._get_audio_processor()
        if sub is not None and hasattr(sub, "sampling_rate"):
            return sub.sampling_rate
        return 16000.0

    def get_data_parser(self) -> MultiModalDataParser:
        target_sr = self._get_audio_sampling_rate() if self._is_audio_model else None
        return MultiModalDataParser(
            target_sr=target_sr,
            video_needs_metadata=self._video_needs_metadata,
            expected_hidden_size=self._get_expected_hidden_size(),
            allow_missing_mm_embeddings=self.allow_missing_mm_embeddings,
        )

    def get_supported_mm_limits(self):
        return dict.fromkeys(self._get_supported_modalities())

    def get_mm_max_tokens_per_item(self, seq_len, mm_counts):
        modalities = self._get_supported_modalities()
        max_tokens = {}
        if "audio" in modalities:
            max_tokens["audio"] = self.get_max_audio_tokens(seq_len)
        if "image" in modalities:
            max_tokens["image"] = self.get_max_image_tokens()
        if "video" in modalities:
            max_tokens["video"] = self.get_max_video_tokens(seq_len, mm_counts)
        return max_tokens

    def _get_max_audio_length(self) -> int | None:
        """Samples the audio processor truncates audios to, or None if it doesn't."""
        sub = self._get_audio_processor()
        # TODO: read only `truncation`/`max_length` once
        # huggingface/transformers#44394 lands.
        if hasattr(sub, "truncation"):
            return sub.max_length if sub.truncation else None
        max_length = getattr_iter(sub, ("n_samples", "nb_max_samples"))
        return max_length if max_length and self._is_audio_capped else None

    @cached_property
    def _is_audio_capped(self) -> bool:
        """Whether long audios stop adding tokens, as `n_samples` can be a window
        that the processor splits them into (e.g. MOSS-Transcribe-Diarize)."""
        num_samples = int(1800 * self._get_audio_sampling_rate())
        tokens = self._count_audio_tokens(num_samples)
        return tokens == self._count_audio_tokens(2 * num_samples)

    @cached_property
    def _audio_samples_per_token(self) -> float:
        """Samples behind each audio token, measured on a 60 s audio."""
        num_samples = int(60 * self._get_audio_sampling_rate())
        return num_samples / self._count_audio_tokens(num_samples)

    def _count_audio_tokens(self, num_samples: int) -> int:
        processor = self.get_hf_processor()
        outputs = self.ctx.call_hf_processor(
            processor,
            dict(
                text=getattr(processor, "audio_token", ""),
                audio=[np.zeros(num_samples, dtype=np.float32)],
                return_text_replacement_offsets=True,
            ),
            {},
        )
        replacement = outputs["text_replacement_offsets"][0][0]["replacement"]
        tokenizer = self.get_tokenizer()
        seq = cached_encode(tokenizer, replacement, add_special_tokens=False)
        return len(seq)

    @cached_property
    def _has_transcription_request(self) -> bool:
        return hasattr(self.get_hf_processor(), "apply_transcription_request")

    @cached_property
    def _is_long_form_audio_model(self) -> bool:
        """Whether a whole recording goes through in a single pass."""
        return self._has_transcription_request and not self._get_max_audio_length()

    def _get_max_long_form_audio_length(self, seq_len: int) -> int:
        """Samples of the longest audio that fits in `seq_len`, set with
        `--limit-mm-per-prompt`, or the longest the API decodes."""
        limits = [int(seq_len * self._audio_samples_per_token)]
        options = self.ctx.get_mm_config().limit_per_prompt.get("audio")
        if length := getattr(options, "length", None):
            return min(length, *limits)
        # 0 disables a limit
        if max_duration_s := envs.VLLM_MAX_AUDIO_DECODE_DURATION_S:
            limits.append(int(max_duration_s * self._get_audio_sampling_rate()))
        if max_bytes := envs.VLLM_MAX_AUDIO_DECODE_BYTES:
            limits.append(max_bytes // np.dtype(np.float32).itemsize)
        return min(limits)

    def get_max_audio_tokens(self, seq_len: int) -> int:
        # Measured, as config limits can be per encoder window (e.g. Qwen3-ASR)
        if self._has_transcription_request:
            if not (length := self._get_max_audio_length()):
                length = self._get_max_long_form_audio_length(seq_len)
            return math.ceil(length / self._audio_samples_per_token)
        config = self.get_hf_config()
        audio_config_names = ("audio_config", "encoder_config")
        names = ("max_source_positions", "max_position_embeddings", "max_pos_emb")
        audio_config = getattr_iter(config, audio_config_names, default=config)
        val = getattr_iter(audio_config, names)
        if val is None:
            val = getattr(self.get_hf_processor(), "audio_seq_length", None)
        if val is not None:
            return int(val)
        raise ValueError(
            f"Unable to get max input length from {type(audio_config).__name__}. "
            f"The following attribute names were checked: {names}, and "
            "`audio_seq_length` on the processor."
        )

    def _get_num_mm_tokens(self, **sizes: Sequence[Sequence[int]]) -> Any:
        processor = self.get_hf_processor()
        multimodal_config = self.ctx.model_config.get_multimodal_config()
        mm_processor_kwargs = multimodal_config.mm_processor_kwargs or {}
        return processor._get_num_multimodal_tokens(**sizes, **mm_processor_kwargs)

    def get_max_image_tokens(self) -> int:
        size = self.get_image_size_with_most_features()
        return self._get_num_image_tokens(size)

    def get_max_video_tokens(self, seq_len: int, mm_counts: Mapping[str, int]) -> int:
        num_frames = self.get_num_frames_with_most_features(
            seq_len, mm_counts.get("video", 0)
        )
        return self._get_max_video_tokens_for_frames(num_frames)

    def _get_max_video_tokens_for_frames(self, num_frames: int) -> int:
        size = self.get_video_size_with_most_features(num_frames)
        return self._get_num_video_tokens(num_frames, size)

    def _get_num_image_tokens(self, size: ImageSize) -> int:
        mm_tokens = self._get_num_mm_tokens(image_sizes=([size.height, size.width],))
        return mm_tokens["num_image_tokens"][0]

    def _get_num_video_tokens(self, num_frames: int, size: ImageSize) -> int:
        video_sizes = ([num_frames, size.height, size.width],)
        mm_tokens = self._get_num_mm_tokens(video_sizes=video_sizes)
        return mm_tokens["num_video_tokens"][0]

    def _get_size_candidates(
        self, sub_processor: Any, divisors: tuple[int, ...]
    ) -> list[ImageSize]:
        """Candidate sizes read off a sub-processor's `size`.

        The keys are one of `VALID_SIZE_DICT_KEYS`, so the bound is either exact
        or an area budget, which `divisors` splits over its items. `shortest_edge`
        bounds only the small side, so it yields no candidate.

        `longest_edge` is read as the area budget Qwen and GLM use it for. A
        processor using it as an edge length (SmolVLM) yields a tiny candidate,
        which is only chosen if it ties on tokens, so it is still correct.
        """
        size = getattr(sub_processor, "size", None) or {}
        height = size.get("height", size.get("max_height"))
        width = size.get("width", size.get("max_width"))
        if height and width:
            return [ImageSize(width=width, height=height)]
        if max_pixels := size.get("max_pixels", size.get("longest_edge")):
            sides = {math.isqrt(max_pixels // divisor) for divisor in divisors}
            return [
                ImageSize(width=side, height=side) for side in sorted(sides) if side
            ]
        return []

    def _get_size_with_most_tokens(
        self, candidates: list[ImageSize], count: Callable[[ImageSize], int]
    ) -> ImageSize:
        """Smallest size found that yields the most tokens.

        `size` bounds the resized output, not the token count, so the candidates
        are compared by token count against an arbitrary large fallback, which
        tiling processors need. The fallback goes last so a candidate wins a tie.
        Resize rounding can give a large input fewer tokens (Qwen2.5-VL), so the
        candidates matter for the count, not only for memory.

        The winner is then halved while the count holds, so processors with no
        usable bound aren't profiled on huge dummy inputs.
        """
        sizes = [*candidates, ImageSize(width=_MAX_DUMMY_SIDE, height=_MAX_DUMMY_SIDE)]
        num_tokens = [count(size) for size in sizes]
        most_tokens = max(num_tokens)
        size = sizes[num_tokens.index(most_tokens)]

        while min(size.width, size.height) // 2 >= _MIN_DUMMY_SIDE:
            smaller = ImageSize(width=size.width // 2, height=size.height // 2)
            if count(smaller) < most_tokens:
                break
            size = smaller
        return size

    def get_image_size_with_most_features(self) -> ImageSize:
        return self._get_size_with_most_tokens(
            self._get_size_candidates(self.get_hf_processor().image_processor, (1,)),
            self._get_num_image_tokens,
        )

    def get_video_size_with_most_features(self, num_frames: int) -> ImageSize:
        """Per-frame size that yields the most video tokens.

        The video processor's `size` budget may cover one frame, every frame or
        every temporal patch, so all three splits are tried.
        """
        video_processor = self.get_hf_processor().video_processor
        grid_t = max(num_frames // self._get_min_video_frames(), 1)
        return self._get_size_with_most_tokens(
            self._get_size_candidates(video_processor, (num_frames, grid_t, 1)),
            lambda size: self._get_num_video_tokens(num_frames, size),
        )

    def get_num_frames_with_most_features(self, seq_len: int, num_videos: int) -> int:
        num_videos = max(num_videos, 1)
        step = self._get_min_video_frames()
        num_frames = step
        while (
            num_frames + step <= _MAX_FRAMES_PER_VIDEO
            and self._get_max_video_tokens_for_frames(num_frames + step) * num_videos
            <= seq_len
        ):
            num_frames += step
        return num_frames

_audio_samples_per_token cached property

Samples behind each audio token, measured on a 60 s audio.

_is_audio_capped cached property

Whether long audios stop adding tokens, as n_samples can be a window that the processor splits them into (e.g. MOSS-Transcribe-Diarize).

_is_long_form_audio_model cached property

Whether a whole recording goes through in a single pass.

_get_max_audio_length()

Samples the audio processor truncates audios to, or None if it doesn't.

Source code in vllm/model_executor/models/transformers/multimodal.py
def _get_max_audio_length(self) -> int | None:
    """Samples the audio processor truncates audios to, or None if it doesn't."""
    sub = self._get_audio_processor()
    # TODO: read only `truncation`/`max_length` once
    # huggingface/transformers#44394 lands.
    if hasattr(sub, "truncation"):
        return sub.max_length if sub.truncation else None
    max_length = getattr_iter(sub, ("n_samples", "nb_max_samples"))
    return max_length if max_length and self._is_audio_capped else None

_get_max_long_form_audio_length(seq_len)

Samples of the longest audio that fits in seq_len, set with --limit-mm-per-prompt, or the longest the API decodes.

Source code in vllm/model_executor/models/transformers/multimodal.py
def _get_max_long_form_audio_length(self, seq_len: int) -> int:
    """Samples of the longest audio that fits in `seq_len`, set with
    `--limit-mm-per-prompt`, or the longest the API decodes."""
    limits = [int(seq_len * self._audio_samples_per_token)]
    options = self.ctx.get_mm_config().limit_per_prompt.get("audio")
    if length := getattr(options, "length", None):
        return min(length, *limits)
    # 0 disables a limit
    if max_duration_s := envs.VLLM_MAX_AUDIO_DECODE_DURATION_S:
        limits.append(int(max_duration_s * self._get_audio_sampling_rate()))
    if max_bytes := envs.VLLM_MAX_AUDIO_DECODE_BYTES:
        limits.append(max_bytes // np.dtype(np.float32).itemsize)
    return min(limits)

_get_placeholder_id(modality)

The placeholder token id, if the placeholder is a single token.

Source code in vllm/model_executor/models/transformers/multimodal.py
def _get_placeholder_id(self, modality: str) -> int | None:
    """The placeholder token id, if the placeholder is a single token."""
    ids = self._get_placeholder_ids(modality)
    return ids[0] if len(ids) == 1 else None

_get_size_candidates(sub_processor, divisors)

Candidate sizes read off a sub-processor's size.

The keys are one of VALID_SIZE_DICT_KEYS, so the bound is either exact or an area budget, which divisors splits over its items. shortest_edge bounds only the small side, so it yields no candidate.

longest_edge is read as the area budget Qwen and GLM use it for. A processor using it as an edge length (SmolVLM) yields a tiny candidate, which is only chosen if it ties on tokens, so it is still correct.

Source code in vllm/model_executor/models/transformers/multimodal.py
def _get_size_candidates(
    self, sub_processor: Any, divisors: tuple[int, ...]
) -> list[ImageSize]:
    """Candidate sizes read off a sub-processor's `size`.

    The keys are one of `VALID_SIZE_DICT_KEYS`, so the bound is either exact
    or an area budget, which `divisors` splits over its items. `shortest_edge`
    bounds only the small side, so it yields no candidate.

    `longest_edge` is read as the area budget Qwen and GLM use it for. A
    processor using it as an edge length (SmolVLM) yields a tiny candidate,
    which is only chosen if it ties on tokens, so it is still correct.
    """
    size = getattr(sub_processor, "size", None) or {}
    height = size.get("height", size.get("max_height"))
    width = size.get("width", size.get("max_width"))
    if height and width:
        return [ImageSize(width=width, height=height)]
    if max_pixels := size.get("max_pixels", size.get("longest_edge")):
        sides = {math.isqrt(max_pixels // divisor) for divisor in divisors}
        return [
            ImageSize(width=side, height=side) for side in sorted(sides) if side
        ]
    return []

_get_size_with_most_tokens(candidates, count)

Smallest size found that yields the most tokens.

size bounds the resized output, not the token count, so the candidates are compared by token count against an arbitrary large fallback, which tiling processors need. The fallback goes last so a candidate wins a tie. Resize rounding can give a large input fewer tokens (Qwen2.5-VL), so the candidates matter for the count, not only for memory.

The winner is then halved while the count holds, so processors with no usable bound aren't profiled on huge dummy inputs.

Source code in vllm/model_executor/models/transformers/multimodal.py
def _get_size_with_most_tokens(
    self, candidates: list[ImageSize], count: Callable[[ImageSize], int]
) -> ImageSize:
    """Smallest size found that yields the most tokens.

    `size` bounds the resized output, not the token count, so the candidates
    are compared by token count against an arbitrary large fallback, which
    tiling processors need. The fallback goes last so a candidate wins a tie.
    Resize rounding can give a large input fewer tokens (Qwen2.5-VL), so the
    candidates matter for the count, not only for memory.

    The winner is then halved while the count holds, so processors with no
    usable bound aren't profiled on huge dummy inputs.
    """
    sizes = [*candidates, ImageSize(width=_MAX_DUMMY_SIDE, height=_MAX_DUMMY_SIDE)]
    num_tokens = [count(size) for size in sizes]
    most_tokens = max(num_tokens)
    size = sizes[num_tokens.index(most_tokens)]

    while min(size.width, size.height) // 2 >= _MIN_DUMMY_SIDE:
        smaller = ImageSize(width=size.width // 2, height=size.height // 2)
        if count(smaller) < most_tokens:
            break
        size = smaller
    return size

get_video_size_with_most_features(num_frames)

Per-frame size that yields the most video tokens.

The video processor's size budget may cover one frame, every frame or every temporal patch, so all three splits are tried.

Source code in vllm/model_executor/models/transformers/multimodal.py
def get_video_size_with_most_features(self, num_frames: int) -> ImageSize:
    """Per-frame size that yields the most video tokens.

    The video processor's `size` budget may cover one frame, every frame or
    every temporal patch, so all three splits are tried.
    """
    video_processor = self.get_hf_processor().video_processor
    grid_t = max(num_frames // self._get_min_video_frames(), 1)
    return self._get_size_with_most_tokens(
        self._get_size_candidates(video_processor, (num_frames, grid_t, 1)),
        lambda size: self._get_num_video_tokens(num_frames, size),
    )

MultiModalProcessor

Bases: BaseMultiModalProcessor[MultiModalProcessingInfo]

Locates placeholders from the text_replacement_offsets the HF processor reports, expressing each one as a PromptUpdate.

Stating the expansion as an update is what lets it be rebuilt from an unexpanded prompt, so this processor takes the base class's processing path and with it the multi-modal processor cache.

Source code in vllm/model_executor/models/transformers/multimodal.py
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
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
class MultiModalProcessor(BaseMultiModalProcessor[MultiModalProcessingInfo]):
    """Locates placeholders from the `text_replacement_offsets` the HF processor
    reports, expressing each one as a `PromptUpdate`.

    Stating the expansion as an update is what lets it be rebuilt from an
    unexpanded prompt, so this processor takes the base class's processing path
    and with it the multi-modal processor cache.
    """

    def _get_hf_mm_inputs(
        self,
        mm_items: MultiModalDataItems,
        hf_kwargs: Mapping[str, object],
    ) -> HFMultiModalInputs:
        """Pass the video metadata along to the HF processor."""
        hf_inputs = super()._get_hf_mm_inputs(mm_items, hf_kwargs)
        hf_data = hf_inputs.hf_data

        if "videos" not in hf_data or not self.info._video_needs_metadata:
            return hf_inputs

        videos = hf_data["videos"]
        assert isinstance(videos, Sequence)
        videos, metadata = zip(*videos)
        hf_data["videos"] = list(videos)
        hf_data["video_metadata"] = [
            {k: v for k, v in item.items() if k != "do_sample_frames"}
            for item in metadata
        ]
        do_sample_frames = {item.get("do_sample_frames", False) for item in metadata}
        if len(do_sample_frames) > 1:
            raise ValueError(
                "The videos in a request must agree on `do_sample_frames`, "
                "since the HF processor takes one value for all of them."
            )

        return hf_inputs._replace(
            hf_kwargs={
                "do_sample_frames": do_sample_frames.pop(),
                **hf_inputs.hf_kwargs,
            }
        )

    def _get_modality_field_names(self, modality: str) -> set[str]:
        """Names of the fields the sub-processor for `modality` produces."""
        # TODO: use else branch only once huggingface/transformers#44394 lands.
        if modality == "audio":
            sub_processor = self.info._get_audio_processor()
        else:
            processor = self.info.get_hf_processor()
            sub_processor = getattr(processor, f"{modality}_processor", None)

        # Pre-computed embeddings bypass the sub-processor entirely
        names = {f"{modality}_embeds"}
        for name in getattr(sub_processor, "model_input_names", None) or ():
            # Companion masks are emitted but not always declared
            names.update((name, f"{name}_mask"))
            if name == "input_features":
                names.add("feature_attention_mask")
        return names

    def _partition_keys_by_modality(
        self,
        keys: list[str],
        modalities: list[str],
    ) -> dict[str, list[str]]:
        """Attribute each HF processor output key to the modality that produced it."""
        if len(modalities) == 1:
            return {modalities[0]: keys}

        claimed = {m: self._get_modality_field_names(m) for m in modalities}

        owned: dict[str, list[str]] = {modality: [] for modality in modalities}
        unclaimed = []
        for key in keys:
            for modality in modalities:
                if key in claimed[modality]:
                    owned[modality].append(key)
                    break
            else:
                unclaimed.append(key)

        if unclaimed:
            logger.warning_once(
                "Unable to attribute %s to any of the modalities %s, so they "
                "will not be passed to the model. Add them to the relevant "
                "sub-processor's `model_input_names` to fix this.",
                tuple(unclaimed),
                tuple(modalities),
            )

        return owned

    def _get_slice_dim(self, data: Any, total_rows: int) -> int:
        """Which dimension of a field holds the rows belonging to each item.

        Some processors (e.g., Idefics3) return image fields with a leading batch
        dimension, putting the rows one dimension further in.
        """
        if not isinstance(data, torch.Tensor) or data.ndim < 2:
            return 0
        if data.shape[0] != total_rows and data.shape[1] == total_rows:
            return 1
        return 0

    def _get_mm_fields_config(
        self,
        hf_inputs: "BatchFeature",
        hf_processor_mm_kwargs: Mapping[str, object],
    ) -> Mapping[str, MultiModalFieldConfig]:
        # HF Processors always return a mask but vLLM doesn't need it
        hf_inputs.pop("attention_mask", None)
        num_audio_windows = hf_inputs.pop("num_audio_windows", None)

        # Absent if the modality had no items
        sizes = {
            modality: hf_inputs.get(key)
            for modality, key in _MODALITY_SIZE_KEYS.items()
        }
        modalities = [m for m, size in sizes.items() if size is not None]

        # Keys we wrote ourselves, rather than ones a sub-processor produced
        own_keys = {*_MODALITY_SIZE_KEYS.values(), "num_video_tokens"} | {
            f"{modality}_replacement_{suffix}"
            for modality in modalities
            for suffix in ("ids", "sizes")
        }
        # Registered by name below, so no sub-processor has to claim them
        own_keys |= {
            "image_grid_thw",
            "video_grid_thw",
            "second_per_grid_ts",
            "audio_feature_lengths",
            "use_audio_in_video",
        }
        keys = [key for key in hf_inputs if key not in own_keys]
        owned = self._partition_keys_by_modality(keys, modalities)

        mm_fields = {
            key: self._get_field_config(modality, key, hf_inputs, sizes[modality])
            for modality in modalities
            for key in owned[modality]
        }

        if num_audio_windows is not None:
            for key in owned["audio"]:
                if len(hf_inputs[key]) == num_audio_windows.sum():
                    mm_fields[key] = MultiModalFieldConfig.flat_from_sizes(
                        "audio", num_audio_windows
                    )

        for modality in modalities:
            # One row per item, and only ever read on the CPU
            mm_fields[_MODALITY_SIZE_KEYS[modality]] = MultiModalFieldConfig.batched(
                modality, keep_on_cpu=True
            )
            replacement_sizes = hf_inputs.get(f"{modality}_replacement_sizes")
            if replacement_sizes is not None:
                mm_fields[f"{modality}_replacement_ids"] = (
                    MultiModalFieldConfig.flat_from_sizes(
                        modality, replacement_sizes, keep_on_cpu=True
                    )
                )

        if "audio" in modalities:
            mm_fields["audio_feature_lengths"] = MultiModalFieldConfig.batched(
                "audio", keep_on_cpu=True
            )
        if "image" in modalities:
            # Always one row per item, whatever they describe
            mm_fields["image_grid_thw"] = MultiModalFieldConfig.batched(
                "image", keep_on_cpu=True
            )
        if "video" in modalities:
            mm_fields["video_grid_thw"] = MultiModalFieldConfig.batched(
                "video", keep_on_cpu=True
            )
            mm_fields["use_audio_in_video"] = MultiModalFieldConfig.shared(
                "video", len(sizes["video"]), keep_on_cpu=True
            )
            mm_fields["second_per_grid_ts"] = MultiModalFieldConfig.batched(
                "video", keep_on_cpu=True
            )

        return mm_fields

    def _get_field_config(
        self,
        modality: str,
        key: str,
        hf_inputs: "BatchFeature",
        sizes: torch.Tensor,
    ) -> MultiModalFieldConfig:
        data = hf_inputs[key]
        # Un-padded fields are already one entry per item, so index rather than slice
        if modality == "audio" or isinstance(data, list):
            # Only read to drop padding, which would sync if this was on the GPU
            keep_on_cpu = key == "padding_mask"
            return MultiModalFieldConfig.batched(modality, keep_on_cpu=keep_on_cpu)

        total = int(sizes.sum())
        dim = self._get_slice_dim(data, total)
        if modality != "video":
            return MultiModalFieldConfig.flat_from_sizes(modality, sizes, dim=dim)

        rows = data.shape[dim]
        if rows == len(sizes):
            return MultiModalFieldConfig.batched("video")
        if rows == total:
            return MultiModalFieldConfig.flat_from_sizes("video", sizes, dim=dim)
        num_frames = hf_inputs.get("num_frames_per_video")
        if num_frames is not None and rows == int(num_frames.sum()):
            return MultiModalFieldConfig.flat_from_sizes("video", num_frames, dim=dim)
        # VideoLLaMA3's compression mask has one row per token the processor counts
        num_video_tokens = hf_inputs["num_video_tokens"]
        if rows == int(num_video_tokens.sum()):
            return MultiModalFieldConfig.flat_from_sizes(
                "video", num_video_tokens, dim=dim
            )
        # NOTE: Any other layout would need a per-model guess, which we'd like to avoid
        raise ValueError(
            f"{type(self.info.get_hf_processor()).__name__} returned {rows} row(s) of "
            f"`{key}` for {len(sizes)} video(s) with {total} patch(es), so the rows "
            "cannot be attributed to a video."
        )

    def _get_hf_mm_text(self, mm_counts: Mapping[str, int]) -> str:
        if self.info._fuses_audio_into_video and mm_counts.get("video"):
            mm_counts = {**mm_counts, "audio": 0}
        return self.dummy_inputs.get_dummy_text(mm_counts)

    def _unpad_audios(
        self,
        hf_inputs: "BatchFeature",
        mm_data: Mapping[str, object],
        mm_kwargs: Mapping[str, object],
    ) -> None:
        """Replace the audio fields with each audio processed on its own.

        Processors pad every audio up to the longest in the call, which would leave
        an item's data dependent on what it was processed with. Unlike images,
        nothing in the output states how long each one really is, and processors
        pad a lone audio too, so the only way to know what an audio produces by
        itself is to process it by itself.
        """
        audios = mm_data.get("audio")
        if not isinstance(audios, Iterable) or not audios:
            return
        audios = list(audios)
        tensors = {
            key: value
            for key in self._get_modality_field_names("audio")
            if isinstance(value := hf_inputs.get(key), torch.Tensor)
        }
        # Processors can split long audios into windows, with a row for each one
        is_windowed = any(len(value) != len(audios) for value in tensors.values())
        if len({len(audio) for audio in audios}) == 1 and not is_windowed:
            return

        alone = [
            self.info.ctx.call_hf_processor(
                self.info.get_hf_processor(**mm_kwargs),
                dict(
                    text=self.dummy_inputs.get_dummy_text({"audio": 1}), audio=[audio]
                ),
                mm_kwargs,
            )
            for audio in audios
        ]

        for key, value in tensors.items():
            if len(value) == len(audios):
                hf_inputs[key] = [output[key][0] for output in alone]
            else:
                windows = [len(output[key]) for output in alone]
                hf_inputs["num_audio_windows"] = torch.tensor(windows)

    def _unpad_images(self, hf_inputs: "BatchFeature") -> None:
        """Trim each image back to its own size when the processor padded them all
        to the largest in the batch.

        An image's data has to depend on nothing but that image, or the multi-modal
        processor cache would store it under that image's hash and later reuse it
        beside a different neighbour. Padding is re-applied when the encoder runs.
        """
        pixel_values = hf_inputs.get("pixel_values")
        image_sizes = hf_inputs.get("image_sizes")
        if not isinstance(pixel_values, torch.Tensor):
            return
        if not isinstance(image_sizes, torch.Tensor):
            return
        if pixel_values.ndim != 4 or len(pixel_values) != len(image_sizes):
            return

        # The sizes describe the trailing dimensions only if the largest of them is
        # what the batch was padded up to. Otherwise they mean something else, as
        # in llava-onevision, where they are the sizes before any processing.
        maxima = image_sizes.max(dim=0).values
        if maxima.tolist() != list(pixel_values.shape[-2:]):
            return

        hf_inputs["pixel_values"] = [
            image[..., :height, :width]
            for image, (height, width) in zip(pixel_values, image_sizes.tolist())
        ]

    def _get_prompt_updates(
        self,
        mm_items: MultiModalDataItems,
        hf_processor_mm_kwargs: Mapping[str, object],
        out_mm_kwargs: MultiModalKwargsItems,
    ) -> Sequence[PromptUpdate]:
        """Replace each modality's placeholder token with the token ids that item's
        replacement text encodes to, marking which of them hold embeddings."""
        updates = []
        for modality, items in out_mm_kwargs.items():
            target = self.info._get_placeholder_ids(modality)
            placeholder_id = self.info._get_placeholder_id(modality)
            # Popped so they are neither cached nor sent to the model; the updates
            # they produce are cached alongside the item instead
            replacements = []
            for item in items:
                ids = item.pop(f"{modality}_replacement_ids").data
                assert isinstance(ids, torch.Tensor)
                replacements.append(
                    PromptUpdateDetails.select_token_id(
                        ids.tolist(), _get_embed_token_id(ids, placeholder_id)
                    )
                )
            updates.append(
                PromptReplacement(
                    modality=modality,
                    target=target,
                    replacement=replacements.__getitem__,
                )
            )
        return updates

    def _derive_audio_from_video_placeholders(
        self,
        placeholders: Mapping[str, list[PlaceholderFeaturesInfo]],
    ) -> Mapping[str, list[PlaceholderFeaturesInfo]]:
        """The placeholders for audios folded into videos, which share their span."""
        audio_token_id = self.info._get_placeholder_id("audio")
        audio_placeholders = []
        for item_idx, video in enumerate(placeholders["video"]):
            audio_placeholders.append(
                PlaceholderFeaturesInfo(
                    modality="audio",
                    item_idx=item_idx,
                    start_idx=video.start_idx,
                    tokens=video.tokens,
                    is_embed=torch.tensor(video.tokens).eq(audio_token_id),
                )
            )
        return {**placeholders, "audio": audio_placeholders}

    def _cached_apply_hf_processor(
        self,
        inputs: ProcessorInputs,
        timing_ctx: TimingContext,
    ) -> MultiModalProcessingResult:
        if self.info._fuses_audio_into_video:
            # load_audio_from_video can't make use of a cache yet
            return self._apply_hf_processor(inputs, timing_ctx)
        return super()._cached_apply_hf_processor(inputs, timing_ctx)

    def _maybe_apply_prompt_updates(
        self,
        mm_items: MultiModalDataItems,
        mm_res: MultiModalProcessingResult,
    ) -> tuple[list[int], Mapping[str, list[PlaceholderFeaturesInfo]]]:
        mm_item_counts = mm_items.get_all_counts()
        if not self.info._fuses_audio_into_video or not mm_item_counts.get("video"):
            return super()._maybe_apply_prompt_updates(mm_items, mm_res)

        self._validate_mm_kwargs(mm_res.kwargs, mm_item_counts)
        self._validate_mm_updates(mm_res.prompt_updates, mm_item_counts)

        # Filter out audio updates, they are embedded in video
        updates = {k: v for k, v in mm_res.prompt_updates.items() if k != "audio"}
        prompt_ids, placeholders = self._apply_prompt_updates(
            mm_res.prompt_ids, updates
        )
        placeholders = self._derive_audio_from_video_placeholders(placeholders)
        self._validate_mm_placeholders(placeholders, mm_item_counts)
        return prompt_ids, placeholders

    def _get_num_image_patches(
        self,
        hf_inputs: "BatchFeature",
        mm_data: Mapping[str, object],
        num_images: int,
    ) -> torch.Tensor:
        """How many rows of the image fields belong to each image.

        Taken from whichever per-image count the processor reports,
        and checked against the data it has to slice.
        """
        if (grid := hf_inputs.get("image_grid_thw")) is not None:
            num_patches = grid.prod(-1)
        elif (counts := self._get_num_patches_per_image(mm_data)) is not None:
            num_patches = torch.tensor(counts)
        else:
            num_patches = torch.ones(num_images, dtype=torch.long)

        image_data = hf_inputs.get("pixel_values", hf_inputs.get("image_patches"))
        if isinstance(image_data, torch.Tensor):
            total = int(num_patches.sum())
            rows = image_data.shape[self._get_slice_dim(image_data, total)]
            if rows != total:
                raise ValueError(
                    f"{type(self.info.get_hf_processor()).__name__} returned "
                    f"{rows} row(s) of image data for {num_images} image(s), which "
                    f"cannot be split into the {num_patches.tolist()} row(s) per "
                    "image derived from its outputs, so the rows cannot be "
                    "attributed to an image. Gemma3 does this when "
                    "`do_pan_and_scan` crops an image."
                )
        return num_patches

    def _get_num_patches_per_image(
        self, mm_data: Mapping[str, object]
    ) -> list[int] | None:
        """Ask the HF processor how many rows of image data each image produces."""
        images = mm_data.get("images")
        if not isinstance(images, Iterable) or not images:
            return None
        try:
            sizes = [(image.height, image.width) for image in images]
            mm_tokens = self.info.get_hf_processor()._get_num_multimodal_tokens(
                image_sizes=sizes, **self.info.ctx.get_merged_mm_kwargs({})
            )
            return list(mm_tokens["num_image_patches"])
        except (AttributeError, KeyError, TypeError):
            return None

    def _apply_hf_processor_main(
        self,
        mm_items: MultiModalDataItems,
        hf_kwargs: Mapping[str, object],
    ) -> "BatchFeature":
        hf_data, hf_kwargs, passthrough_data = self._get_hf_mm_inputs(
            mm_items, hf_kwargs
        )

        if not hf_data:
            return self._finalize_hf_mm_data(hf_data, hf_kwargs, passthrough_data)

        prompt_text = hf_data.pop("text")
        assert isinstance(prompt_text, str)

        fuses_audio_into_video = self.info._fuses_audio_into_video
        override = get_load_audio_from_video(hf_kwargs)
        if override is not None and override != fuses_audio_into_video:
            raise ValueError(
                "load_audio_from_video is a server-level setting and cannot be "
                "overridden per request; pass it in --mm-processor-kwargs instead."
            )
        item_counts = mm_items.get_all_counts()
        num_audios = item_counts.get("audio", 0)
        num_videos = item_counts.get("video", 0)
        load_audio_from_video = fuses_audio_into_video and num_videos > 0
        if load_audio_from_video and num_audios != num_videos:
            raise ValueError(
                f"load_audio_from_video requires equal number of audio and video "
                f"items, got {num_audios=}, {num_videos=}"
            )

        # Only the main call may fuse, not those processing each audio alone
        unfused_kwargs = hf_kwargs
        if fuses_audio_into_video:
            unfused_kwargs = {
                **hf_kwargs,
                "load_audio_from_video": False,
                "use_audio_in_video": False,
            }
        call_kwargs = unfused_kwargs
        if load_audio_from_video:
            call_kwargs = {
                **unfused_kwargs,
                "load_audio_from_video": True,
                "audio_from_video_indices": list(range(num_videos)),
            }

        # Ask for the replacement each placeholder expands to, and record it as
        # per-item fields: its token ids, and the tokens or patches behind them
        if has_mm_data := any(hf_data.values()):
            hf_data = {**hf_data, "return_text_replacement_offsets": True}

        try:
            hf_inputs = self.info.ctx.call_hf_processor(
                self.info.get_hf_processor(**unfused_kwargs),
                dict(text=prompt_text, **hf_data),
                call_kwargs,
            )
        except ValueError:
            if any(hf_data.values()):
                raise
            # Some processors reject a prompt holding placeholders with
            # no data to go with them, so tokenize it without them
            tokenizer = self.info.get_tokenizer()
            hf_inputs = transformers.BatchFeature(
                dict(input_ids=[tokenizer.encode(prompt_text)]), tensor_type="pt"
            )

        self._unpad_images(hf_inputs)
        self._unpad_audios(hf_inputs, hf_data, unfused_kwargs)

        feature_attention_mask = hf_inputs.get("feature_attention_mask")
        # Qwen-Omni's `get_rope_index` takes these lengths as `audio_seqlens`
        if feature_attention_mask is not None:
            lengths = [mask.sum(-1) for mask in feature_attention_mask]
            hf_inputs["audio_feature_lengths"] = torch.stack(lengths)

        # Qwen-Omni's alias for Qwen2.5-VL's `second_per_grid_ts`
        if "video_second_per_grid" in hf_inputs:
            hf_inputs["second_per_grid_ts"] = hf_inputs.pop("video_second_per_grid")

        if load_audio_from_video:
            hf_inputs["use_audio_in_video"] = torch.tensor(True)

        # Drop the inputs the model would reject
        hf_inputs.pop("mm_token_type_ids", None)
        hf_inputs.pop("token_type_ids", None)

        offsets = hf_inputs.pop("text_replacement_offsets", None)
        # Some processors return an empty batch as a tensor rather than a list
        if offsets is None or len(offsets) == 0 or len(offsets[0]) == 0:
            if has_mm_data:
                raise ValueError(
                    f"{type(self.info.get_hf_processor()).__name__} returned no "
                    "text replacement offsets, so the Transformers modeling backend "
                    "cannot locate the placeholder of each item. Its `__call__` has "
                    "to reach `ProcessorMixin.get_text_with_replacements` with one "
                    "replacement per item, which usually means implementing "
                    "`replace_<modality>_token`. Please report this to transformers "
                    "so it can be fixed."
                )
            hf_inputs.pop("input_ids", None)
            return self._finalize_hf_mm_data(
                hf_data, hf_kwargs, passthrough_data, hf_inputs
            )

        tokenizer = self.info.get_tokenizer()
        replacements = defaultdict[str, list[list[int]]](list)
        for entry in offsets[0]:
            replacements[entry["type"]].append(
                cached_encode(tokenizer, entry["replacement"], add_special_tokens=False)
            )

        if load_audio_from_video:
            audio_token_id = self.info._get_placeholder_id("audio")
            replacements["audio"] = [
                seq for seq in replacements["video"] if audio_token_id in seq
            ]

        for modality, seqs in replacements.items():
            hf_inputs[f"{modality}_replacement_ids"] = torch.tensor(
                [token_id for seq in seqs for token_id in seq]
            )
            hf_inputs[f"{modality}_replacement_sizes"] = torch.tensor(
                [len(seq) for seq in seqs]
            )
            if modality == "image":
                hf_inputs["num_image_patches"] = self._get_num_image_patches(
                    hf_inputs, hf_data, len(seqs)
                )
            elif modality == "audio":
                hf_inputs["num_audio_tokens"] = _count_embed_tokens(
                    seqs, self.info._get_placeholder_id("audio")
                )
            elif modality == "video":
                grid = hf_inputs.get("video_grid_thw")
                hf_inputs["num_video_patches"] = (
                    grid.prod(-1)
                    if grid is not None
                    else torch.ones(len(seqs), dtype=torch.long)
                )
                hf_inputs["num_video_tokens"] = _count_embed_tokens(
                    seqs, self.info._get_placeholder_id("video")
                )

        hf_inputs.pop("input_ids")

        return self._finalize_hf_mm_data(
            hf_data, hf_kwargs, passthrough_data, hf_inputs
        )

_derive_audio_from_video_placeholders(placeholders)

The placeholders for audios folded into videos, which share their span.

Source code in vllm/model_executor/models/transformers/multimodal.py
def _derive_audio_from_video_placeholders(
    self,
    placeholders: Mapping[str, list[PlaceholderFeaturesInfo]],
) -> Mapping[str, list[PlaceholderFeaturesInfo]]:
    """The placeholders for audios folded into videos, which share their span."""
    audio_token_id = self.info._get_placeholder_id("audio")
    audio_placeholders = []
    for item_idx, video in enumerate(placeholders["video"]):
        audio_placeholders.append(
            PlaceholderFeaturesInfo(
                modality="audio",
                item_idx=item_idx,
                start_idx=video.start_idx,
                tokens=video.tokens,
                is_embed=torch.tensor(video.tokens).eq(audio_token_id),
            )
        )
    return {**placeholders, "audio": audio_placeholders}

_get_hf_mm_inputs(mm_items, hf_kwargs)

Pass the video metadata along to the HF processor.

Source code in vllm/model_executor/models/transformers/multimodal.py
def _get_hf_mm_inputs(
    self,
    mm_items: MultiModalDataItems,
    hf_kwargs: Mapping[str, object],
) -> HFMultiModalInputs:
    """Pass the video metadata along to the HF processor."""
    hf_inputs = super()._get_hf_mm_inputs(mm_items, hf_kwargs)
    hf_data = hf_inputs.hf_data

    if "videos" not in hf_data or not self.info._video_needs_metadata:
        return hf_inputs

    videos = hf_data["videos"]
    assert isinstance(videos, Sequence)
    videos, metadata = zip(*videos)
    hf_data["videos"] = list(videos)
    hf_data["video_metadata"] = [
        {k: v for k, v in item.items() if k != "do_sample_frames"}
        for item in metadata
    ]
    do_sample_frames = {item.get("do_sample_frames", False) for item in metadata}
    if len(do_sample_frames) > 1:
        raise ValueError(
            "The videos in a request must agree on `do_sample_frames`, "
            "since the HF processor takes one value for all of them."
        )

    return hf_inputs._replace(
        hf_kwargs={
            "do_sample_frames": do_sample_frames.pop(),
            **hf_inputs.hf_kwargs,
        }
    )

_get_modality_field_names(modality)

Names of the fields the sub-processor for modality produces.

Source code in vllm/model_executor/models/transformers/multimodal.py
def _get_modality_field_names(self, modality: str) -> set[str]:
    """Names of the fields the sub-processor for `modality` produces."""
    # TODO: use else branch only once huggingface/transformers#44394 lands.
    if modality == "audio":
        sub_processor = self.info._get_audio_processor()
    else:
        processor = self.info.get_hf_processor()
        sub_processor = getattr(processor, f"{modality}_processor", None)

    # Pre-computed embeddings bypass the sub-processor entirely
    names = {f"{modality}_embeds"}
    for name in getattr(sub_processor, "model_input_names", None) or ():
        # Companion masks are emitted but not always declared
        names.update((name, f"{name}_mask"))
        if name == "input_features":
            names.add("feature_attention_mask")
    return names

_get_num_image_patches(hf_inputs, mm_data, num_images)

How many rows of the image fields belong to each image.

Taken from whichever per-image count the processor reports, and checked against the data it has to slice.

Source code in vllm/model_executor/models/transformers/multimodal.py
def _get_num_image_patches(
    self,
    hf_inputs: "BatchFeature",
    mm_data: Mapping[str, object],
    num_images: int,
) -> torch.Tensor:
    """How many rows of the image fields belong to each image.

    Taken from whichever per-image count the processor reports,
    and checked against the data it has to slice.
    """
    if (grid := hf_inputs.get("image_grid_thw")) is not None:
        num_patches = grid.prod(-1)
    elif (counts := self._get_num_patches_per_image(mm_data)) is not None:
        num_patches = torch.tensor(counts)
    else:
        num_patches = torch.ones(num_images, dtype=torch.long)

    image_data = hf_inputs.get("pixel_values", hf_inputs.get("image_patches"))
    if isinstance(image_data, torch.Tensor):
        total = int(num_patches.sum())
        rows = image_data.shape[self._get_slice_dim(image_data, total)]
        if rows != total:
            raise ValueError(
                f"{type(self.info.get_hf_processor()).__name__} returned "
                f"{rows} row(s) of image data for {num_images} image(s), which "
                f"cannot be split into the {num_patches.tolist()} row(s) per "
                "image derived from its outputs, so the rows cannot be "
                "attributed to an image. Gemma3 does this when "
                "`do_pan_and_scan` crops an image."
            )
    return num_patches

_get_num_patches_per_image(mm_data)

Ask the HF processor how many rows of image data each image produces.

Source code in vllm/model_executor/models/transformers/multimodal.py
def _get_num_patches_per_image(
    self, mm_data: Mapping[str, object]
) -> list[int] | None:
    """Ask the HF processor how many rows of image data each image produces."""
    images = mm_data.get("images")
    if not isinstance(images, Iterable) or not images:
        return None
    try:
        sizes = [(image.height, image.width) for image in images]
        mm_tokens = self.info.get_hf_processor()._get_num_multimodal_tokens(
            image_sizes=sizes, **self.info.ctx.get_merged_mm_kwargs({})
        )
        return list(mm_tokens["num_image_patches"])
    except (AttributeError, KeyError, TypeError):
        return None

_get_prompt_updates(mm_items, hf_processor_mm_kwargs, out_mm_kwargs)

Replace each modality's placeholder token with the token ids that item's replacement text encodes to, marking which of them hold embeddings.

Source code in vllm/model_executor/models/transformers/multimodal.py
def _get_prompt_updates(
    self,
    mm_items: MultiModalDataItems,
    hf_processor_mm_kwargs: Mapping[str, object],
    out_mm_kwargs: MultiModalKwargsItems,
) -> Sequence[PromptUpdate]:
    """Replace each modality's placeholder token with the token ids that item's
    replacement text encodes to, marking which of them hold embeddings."""
    updates = []
    for modality, items in out_mm_kwargs.items():
        target = self.info._get_placeholder_ids(modality)
        placeholder_id = self.info._get_placeholder_id(modality)
        # Popped so they are neither cached nor sent to the model; the updates
        # they produce are cached alongside the item instead
        replacements = []
        for item in items:
            ids = item.pop(f"{modality}_replacement_ids").data
            assert isinstance(ids, torch.Tensor)
            replacements.append(
                PromptUpdateDetails.select_token_id(
                    ids.tolist(), _get_embed_token_id(ids, placeholder_id)
                )
            )
        updates.append(
            PromptReplacement(
                modality=modality,
                target=target,
                replacement=replacements.__getitem__,
            )
        )
    return updates

_get_slice_dim(data, total_rows)

Which dimension of a field holds the rows belonging to each item.

Some processors (e.g., Idefics3) return image fields with a leading batch dimension, putting the rows one dimension further in.

Source code in vllm/model_executor/models/transformers/multimodal.py
def _get_slice_dim(self, data: Any, total_rows: int) -> int:
    """Which dimension of a field holds the rows belonging to each item.

    Some processors (e.g., Idefics3) return image fields with a leading batch
    dimension, putting the rows one dimension further in.
    """
    if not isinstance(data, torch.Tensor) or data.ndim < 2:
        return 0
    if data.shape[0] != total_rows and data.shape[1] == total_rows:
        return 1
    return 0

_partition_keys_by_modality(keys, modalities)

Attribute each HF processor output key to the modality that produced it.

Source code in vllm/model_executor/models/transformers/multimodal.py
def _partition_keys_by_modality(
    self,
    keys: list[str],
    modalities: list[str],
) -> dict[str, list[str]]:
    """Attribute each HF processor output key to the modality that produced it."""
    if len(modalities) == 1:
        return {modalities[0]: keys}

    claimed = {m: self._get_modality_field_names(m) for m in modalities}

    owned: dict[str, list[str]] = {modality: [] for modality in modalities}
    unclaimed = []
    for key in keys:
        for modality in modalities:
            if key in claimed[modality]:
                owned[modality].append(key)
                break
        else:
            unclaimed.append(key)

    if unclaimed:
        logger.warning_once(
            "Unable to attribute %s to any of the modalities %s, so they "
            "will not be passed to the model. Add them to the relevant "
            "sub-processor's `model_input_names` to fix this.",
            tuple(unclaimed),
            tuple(modalities),
        )

    return owned

_unpad_audios(hf_inputs, mm_data, mm_kwargs)

Replace the audio fields with each audio processed on its own.

Processors pad every audio up to the longest in the call, which would leave an item's data dependent on what it was processed with. Unlike images, nothing in the output states how long each one really is, and processors pad a lone audio too, so the only way to know what an audio produces by itself is to process it by itself.

Source code in vllm/model_executor/models/transformers/multimodal.py
def _unpad_audios(
    self,
    hf_inputs: "BatchFeature",
    mm_data: Mapping[str, object],
    mm_kwargs: Mapping[str, object],
) -> None:
    """Replace the audio fields with each audio processed on its own.

    Processors pad every audio up to the longest in the call, which would leave
    an item's data dependent on what it was processed with. Unlike images,
    nothing in the output states how long each one really is, and processors
    pad a lone audio too, so the only way to know what an audio produces by
    itself is to process it by itself.
    """
    audios = mm_data.get("audio")
    if not isinstance(audios, Iterable) or not audios:
        return
    audios = list(audios)
    tensors = {
        key: value
        for key in self._get_modality_field_names("audio")
        if isinstance(value := hf_inputs.get(key), torch.Tensor)
    }
    # Processors can split long audios into windows, with a row for each one
    is_windowed = any(len(value) != len(audios) for value in tensors.values())
    if len({len(audio) for audio in audios}) == 1 and not is_windowed:
        return

    alone = [
        self.info.ctx.call_hf_processor(
            self.info.get_hf_processor(**mm_kwargs),
            dict(
                text=self.dummy_inputs.get_dummy_text({"audio": 1}), audio=[audio]
            ),
            mm_kwargs,
        )
        for audio in audios
    ]

    for key, value in tensors.items():
        if len(value) == len(audios):
            hf_inputs[key] = [output[key][0] for output in alone]
        else:
            windows = [len(output[key]) for output in alone]
            hf_inputs["num_audio_windows"] = torch.tensor(windows)

_unpad_images(hf_inputs)

Trim each image back to its own size when the processor padded them all to the largest in the batch.

An image's data has to depend on nothing but that image, or the multi-modal processor cache would store it under that image's hash and later reuse it beside a different neighbour. Padding is re-applied when the encoder runs.

Source code in vllm/model_executor/models/transformers/multimodal.py
def _unpad_images(self, hf_inputs: "BatchFeature") -> None:
    """Trim each image back to its own size when the processor padded them all
    to the largest in the batch.

    An image's data has to depend on nothing but that image, or the multi-modal
    processor cache would store it under that image's hash and later reuse it
    beside a different neighbour. Padding is re-applied when the encoder runs.
    """
    pixel_values = hf_inputs.get("pixel_values")
    image_sizes = hf_inputs.get("image_sizes")
    if not isinstance(pixel_values, torch.Tensor):
        return
    if not isinstance(image_sizes, torch.Tensor):
        return
    if pixel_values.ndim != 4 or len(pixel_values) != len(image_sizes):
        return

    # The sizes describe the trailing dimensions only if the largest of them is
    # what the batch was padded up to. Otherwise they mean something else, as
    # in llava-onevision, where they are the sizes before any processing.
    maxima = image_sizes.max(dim=0).values
    if maxima.tolist() != list(pixel_values.shape[-2:]):
        return

    hf_inputs["pixel_values"] = [
        image[..., :height, :width]
        for image, (height, width) in zip(pixel_values, image_sizes.tolist())
    ]

_count_embed_tokens(seqs, placeholder_id=None)

Number of embedding tokens in each item's replacement.

Source code in vllm/model_executor/models/transformers/multimodal.py
def _count_embed_tokens(
    seqs: list[list[int]], placeholder_id: int | None = None
) -> torch.Tensor:
    """Number of embedding tokens in each item's replacement."""
    counts = []
    for seq in seqs:
        ids = torch.tensor(seq)
        counts.append(int(ids.eq(_get_embed_token_id(ids, placeholder_id)).sum()))
    return torch.tensor(counts)

_get_embed_token_id(replacement_ids, placeholder_id=None)

The token an expansion repeats is the one holding the embeddings.

Source code in vllm/model_executor/models/transformers/multimodal.py
def _get_embed_token_id(
    replacement_ids: torch.Tensor, placeholder_id: int | None = None
) -> int:
    """The token an expansion repeats is the one holding the embeddings."""
    if placeholder_id is not None and (replacement_ids == placeholder_id).sum() > 1:
        return placeholder_id
    return int(replacement_ids.mode().values)