Skip to content

vllm.model_executor.models.gemma4_mm

Gemma 4 multimodal model (image + audio + video support).

Adds vision tower, audio tower, and multimodal embedders on top of the text-only Gemma4ForCausalLM. The vision/audio encoders are loaded via AutoModel.from_config and run in eager mode while the language model uses the vLLM-optimized path.

Video support: Gemma4 does not have a native video tower. Videos are decomposed into timestamped image frames (up to 32 frames at 70 soft tokens each) and fed through the same vision tower as regular images. The processor inserts mm:ss timestamps between frames so the model can reason about temporal order.

Classes:

Gemma4AudioInputs

Bases: TensorSchema

Dimensions
  • bn: Batch size * number of audios
  • s: Sequence length (MEL spectrogram frames)
  • f: Number of features (MEL bins)
Source code in vllm/model_executor/models/gemma4_mm.py
class Gemma4AudioInputs(TensorSchema):
    """
    Dimensions:
        - bn: Batch size * number of audios
        - s: Sequence length (MEL spectrogram frames)
        - f: Number of features (MEL bins)
    """

    type: Literal["audio"] = "audio"
    input_features_padded: Annotated[
        torch.Tensor, TensorShape("bn", "s", "f", dynamic_dims={"s"})
    ]
    input_features_mask: Annotated[
        torch.Tensor, TensorShape("bn", "s", dynamic_dims={"s"})
    ]

Gemma4ForConditionalGeneration

Bases: Module, SupportsMultiModal, SupportsQuant, SupportsPP, SupportsLoRA, SupportsEagle3, SupportsEncoderCudaGraph

Methods:

  • get_mm_mapping

    Get the module prefix mapping for multimodal models.

Source code in vllm/model_executor/models/gemma4_mm.py
 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
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
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
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
@MULTIMODAL_REGISTRY.register_processor(
    Gemma4MultiModalProcessor,
    info=Gemma4ProcessingInfo,
    dummy_inputs=Gemma4DummyInputsBuilder,
)
class Gemma4ForConditionalGeneration(
    nn.Module,
    SupportsMultiModal,
    SupportsQuant,
    SupportsPP,
    SupportsLoRA,
    SupportsEagle3,
    SupportsEncoderCudaGraph,
):
    supports_encoder_cudagraph: ClassVar[Literal[True]] = True
    # Gemma4 clamps mm_prefix bidirectional ranges to the sliding window
    # in-kernel (HF's (causal OR blockwise) AND sliding_window). The model
    # runner reads this to keep image bidirectional ranges that exceed the
    # window instead of dropping them (which would make image attention
    # causal-only for images larger than the sliding window).
    mm_prefix_clamp_sliding_window: bool = True
    supports_tower_connector_lora = True

    packed_modules_mapping = {
        "qkv_proj": [
            "q_proj",
            "k_proj",
            "v_proj",
        ],
        "gate_up_proj": [
            "gate_proj",
            "up_proj",
        ],
    }

    # Maps checkpoint prefixes to vLLM module paths.
    hf_to_vllm_mapper = _GEMMA4_EXPERT_PARENT_MAPPER | WeightsMapper(
        orig_to_new_prefix={
            # vision tower
            "model.vision_tower": "vision_tower",
            "model.embed_vision": "embed_vision",
            # audio tower
            "model.audio_tower.": "audio_tower.",
            "model.embed_audio.": "embed_audio.",
            # backbone
            "model.language_model.": "language_model.model.",
            "lm_head.": "language_model.lm_head.",
            "model": "language_model.model",
        },
    )

    def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
        super().__init__()
        config = vllm_config.model_config.hf_config
        quant_config = vllm_config.quant_config
        multimodal_config = vllm_config.model_config.multimodal_config
        self.config = config
        self.quant_config = quant_config
        self.multimodal_config = multimodal_config
        self.model_dtype = vllm_config.model_config.dtype
        self.vllm_config = vllm_config
        lora_config = vllm_config.lora_config
        self._enable_mm_lora = bool(
            lora_config is not None and lora_config.enable_tower_connector_lora
        )

        # Only quantize towers when the quant method supports their
        # dimensions.  BNB/torchao handle arbitrary sizes; other methods
        # (Marlin, FP8, …) require dimensions divisible by 64, which
        # the vision tower (intermediate_size=4304) does not satisfy.
        # TODO(mgoin): remove this by fixing kernel padding.
        if quant_config and quant_config.get_name() in [
            "bitsandbytes",
            "torchao",
            "compressed-tensors",
        ]:
            tower_quant = quant_config
        else:
            vision_cfg = config.vision_config
            quantizable = (
                vision_cfg.hidden_size % 64 == 0
                and vision_cfg.intermediate_size % 64 == 0
            )
            tower_quant = quant_config if quantizable else None

        # ---- Vision tower (shared by image and video) ----
        with self._mark_tower_model(vllm_config, {"image", "video"}):
            self.vision_tower = AutoModel.from_config(config=config.vision_config)
            self.embed_vision = Gemma4MultimodalEmbedder(
                config.vision_config,
                config.text_config,
                quant_config=tower_quant,
                prefix=maybe_prefix(prefix, "embed_vision"),
            )
            recursive_replace_linear(
                self.vision_tower,
                tower_quant,
                prefix=maybe_prefix(prefix, "vision_tower"),
            )

        # ---- Audio tower (variants with audio_config) ----
        if config.audio_config is not None:
            with self._mark_tower_model(vllm_config, "audio"):
                self.audio_tower = AutoModel.from_config(config=config.audio_config)
                # AutoModel.from_config does NOT call post_init(),
                # which is needed to initialize buffers that are absent
                # from the checkpoint (e.g. inv_timescales for relative
                # position embeddings, softcap, gradient_clipping).
                self.audio_tower.post_init()
                self.embed_audio = Gemma4MultimodalEmbedder(
                    config.audio_config,
                    config.text_config,
                    quant_config=tower_quant,
                    prefix=maybe_prefix(prefix, "embed_audio"),
                )
                recursive_replace_linear(
                    self.audio_tower,
                    tower_quant,
                    prefix=maybe_prefix(prefix, "audio_tower"),
                )
        else:
            self.audio_tower = None
            self.embed_audio = None

        # ---- Language model (vLLM optimised) ----
        with self._mark_language_model(vllm_config):
            self.language_model: Gemma4ForCausalLM = init_vllm_registered_model(
                vllm_config=vllm_config,
                hf_config=config.text_config,
                prefix=maybe_prefix(prefix, "language_model"),
                architectures=["Gemma4ForCausalLM"],
            )

            # Pre-allocate PLE buffer for CUDA graph compatibility.
            # Some variants have hidden_size_per_layer_input=None (no PLE).
            ple_dim = config.text_config.hidden_size_per_layer_input
            if ple_dim is not None and ple_dim > 0:
                embed = self.language_model.model.embed_tokens
                self.per_layer_embeddings = torch.zeros(
                    vllm_config.scheduler_config.max_num_batched_tokens,
                    config.text_config.num_hidden_layers,
                    ple_dim,
                    device=next(embed.parameters()).device,
                    dtype=vllm_config.model_config.dtype,
                )
            else:
                self.per_layer_embeddings = None

        self.make_empty_intermediate_tensors = (
            self.language_model.make_empty_intermediate_tensors
        )

        # --- Precompute full-attention layer indices for bidi clearing ---
        self._full_attn_layer_idxs: frozenset[int] = frozenset()
        text_config = config.text_config
        if getattr(text_config, "use_bidirectional_attention", None) == "vision":
            layer_types = getattr(text_config, "layer_types", None)
            if layer_types:
                self._full_attn_layer_idxs = frozenset(
                    i for i, lt in enumerate(layer_types) if lt != "sliding_attention"
                )

        # --- MixtureOfExperts delegation to language_model ---
        self.moe_layers = self.language_model.moe_layers
        self.num_moe_layers = self.language_model.num_moe_layers
        self.num_logical_experts = self.language_model.num_logical_experts
        self.num_physical_experts = self.language_model.num_physical_experts
        self.num_local_physical_experts = self.language_model.num_local_physical_experts
        self.num_routed_experts = self.language_model.num_routed_experts
        self.num_expert_groups = self.language_model.num_expert_groups
        self.num_shared_experts = self.language_model.num_shared_experts
        self.num_redundant_experts = self.language_model.num_redundant_experts

        gen_cfg = vllm_config.model_config.try_get_generation_config()
        self._suppress_token_ids = gen_cfg.get("suppress_tokens") if gen_cfg else None

    # ------------------------------------------------------------------ #
    # Input parsing
    # ------------------------------------------------------------------ #

    def _parse_and_validate_image_input(
        self, **kwargs: object
    ) -> Gemma4ImageInputs | None:
        pixel_values = kwargs.pop("pixel_values", None)
        pixel_position_ids = kwargs.pop("pixel_position_ids", None)
        image_embeds = kwargs.pop("image_embeds", None)
        assert image_embeds is None, "Gemma4 does not support image_embeds."
        if pixel_values is None:
            return None
        return Gemma4ImagePixelInputs(
            pixel_values=pixel_values,
            pixel_position_ids=pixel_position_ids,
        )

    def _parse_and_validate_audio_input(
        self, **kwargs: object
    ) -> Gemma4AudioInputs | None:
        input_features_padded = kwargs.pop("input_features_padded", None)
        if input_features_padded is None:
            return None
        input_features_mask = kwargs.pop("input_features_mask", None)
        if input_features_mask is None:
            return None
        return Gemma4AudioInputs(
            input_features_padded=input_features_padded,
            input_features_mask=input_features_mask,
        )

    def _parse_and_validate_video_input(
        self, **kwargs: object
    ) -> dict[str, torch.Tensor] | None:
        pixel_values_videos = kwargs.pop("pixel_values_videos", None)
        pixel_position_ids_videos = kwargs.pop("pixel_position_ids_videos", None)
        video_frame_counts = kwargs.pop("video_frame_counts", None)
        if pixel_values_videos is None:
            return None
        return {
            "pixel_values_videos": pixel_values_videos,
            "pixel_position_ids_videos": pixel_position_ids_videos,
            "video_frame_counts": video_frame_counts,
        }

    def _parse_and_validate_multimodal_inputs(
        self, **kwargs: object
    ) -> dict[str, Gemma4ImageInputs | Gemma4AudioInputs | Gemma4VideoInputs | None]:
        mm_input_by_modality = {}
        for input_key in list(kwargs):
            if (
                input_key in ("pixel_values", "image_embeds")
                and "image" not in mm_input_by_modality
            ):
                mm_input_by_modality["image"] = self._parse_and_validate_image_input(
                    **kwargs
                )
            if (
                input_key == "pixel_values_videos"
                and "video" not in mm_input_by_modality
            ):
                mm_input_by_modality["video"] = self._parse_and_validate_video_input(
                    **kwargs
                )
            if (
                input_key == "input_features_padded"
                and "audio" not in mm_input_by_modality
            ):
                mm_input_by_modality["audio"] = self._parse_and_validate_audio_input(
                    **kwargs
                )
        return mm_input_by_modality

    @staticmethod
    def _encoder_chunk(
        patches_per_item: int,
        free_bytes: int,
        total_bytes: int,
        position_embedding_size: int,
    ) -> int:
        """Max chunk size whose F.one_hot transient fits in the budget.

        The dominant transient inside HF's ``Gemma4VisionPatchEmbedder.
        _position_embeddings`` is
        ``F.one_hot(clamped_positions, num_classes=position_embedding_size)``
        with shape ``(chunk, patches, 2, position_embedding_size)``,
        int64, plus its simultaneous cast to the position embedding
        table dtype. That, not the encoder residual stream, sets peak
        memory.
        """
        if patches_per_item <= 0:
            return 1
        # Half of currently-free, capped at 10% of total so we leave room
        # for the rest of profile_run / the subsequent encoder + pooler.
        budget = min(free_bytes // 2, total_bytes // 10)
        if budget <= 0:
            return 1
        # F.one_hot allocates (chunk, patches, 2, pos_emb_size) int64
        # (the inner 2 is the (x, y) coordinate axis, 8 is sizeof(int64)).
        # Outer 2x covers the int64 buffer and its concurrent bf16 cast
        # plus the matmul output that live alongside it at peak.
        cost = patches_per_item * 4 * position_embedding_size * 8
        return max(1, budget // cost) if cost > 0 else 1

    # ------------------------------------------------------------------ #
    # Image processing
    # ------------------------------------------------------------------ #

    def _process_image_input(
        self,
        image_input: Gemma4ImageInputs,
    ) -> list[torch.Tensor]:
        """Batch-encode images through the vision tower.

        Groups images by patch count (resolution bucket) so each
        encoder call processes a uniform-shape batch with no
        cross-resolution padding. With MM LoRA enabled, all images are
        padded into one batch so the encoder call matches the tower mapping.
        """
        pixel_values = image_input["pixel_values"]
        pixel_position_ids = image_input["pixel_position_ids"]

        vt = self.vision_tower
        vision_cfg = self.config.vision_config
        pooling_k2 = vision_cfg.pooling_kernel_size**2

        # Concurrent requests with different image resolutions may
        # arrive as a list of per-image tensors, while same-resolution
        # batches may arrive as a stacked tensor.
        buckets: dict[int, list[tuple[int, torch.Tensor, torch.Tensor]]] = {}
        total_images = (
            len(pixel_values)
            if isinstance(pixel_values, list)
            else pixel_values.shape[0]
        )
        pool_position_ids = pixel_position_ids

        if self._enable_mm_lora:
            max_soft_tokens = vision_cfg.default_output_length
            mm_processor_kwargs = getattr(
                getattr(self, "multimodal_config", None),
                "mm_processor_kwargs",
                None,
            )
            if isinstance(mm_processor_kwargs, Mapping):
                value, _ = _get_max_soft_tokens(mm_processor_kwargs)
                if isinstance(value, int) and value in _SUPPORTED_SOFT_TOKENS:
                    max_soft_tokens = value

            max_patches = max_soft_tokens * pooling_k2
            padded_position_ids: list[torch.Tensor] = []
            for idx in range(total_images):
                pv = pixel_values[idx]
                pp = pixel_position_ids[idx]
                num_patches = pv.shape[0]
                if num_patches > max_patches:
                    raise ValueError(
                        f"Image {idx} has {num_patches} patches, which exceeds "
                        f"the MM LoRA patch limit of {max_patches}."
                    )

                pad_len = max_patches - num_patches
                pv = torch.cat(
                    (pv, pv.new_zeros((pad_len, *pv.shape[1:]))),
                    dim=0,
                )
                pp = torch.cat(
                    (pp, pp.new_full((pad_len, *pp.shape[1:]), -1)),
                    dim=0,
                )
                buckets.setdefault(max_patches, []).append((idx, pv, pp))
                padded_position_ids.append(pp)
            pool_position_ids = padded_position_ids
        else:
            for idx in range(total_images):
                pv = pixel_values[idx]
                pp = pixel_position_ids[idx]
                buckets.setdefault(pv.shape[0], []).append((idx, pv, pp))

        # Encode each resolution bucket in memory-safe chunks. Re-read
        # free memory per bucket because the previous bucket's encoder
        # pass has already allocated activations we should account for.
        last_hidden_states_map: dict[int, torch.Tensor] = {}
        for patches, items in buckets.items():
            if self._enable_mm_lora:
                max_batch_size = len(items)
            else:
                free, total = torch.accelerator.get_memory_info()
                max_batch_size = min(
                    len(items),
                    self._encoder_chunk(
                        patches, free, total, vision_cfg.position_embedding_size
                    ),
                )

            for chunk_idx in range(0, len(items), max_batch_size):
                chunk_items = items[chunk_idx : chunk_idx + max_batch_size]

                pv_tensor = torch.cat(
                    [item[1].unsqueeze(0) for item in chunk_items], dim=0
                )
                pp_tensor = torch.cat(
                    [item[2].unsqueeze(0) for item in chunk_items], dim=0
                )
                pad_tensor = (pp_tensor == -1).all(dim=-1)

                inputs_embeds = vt.patch_embedder(
                    pv_tensor,
                    pp_tensor,
                    pad_tensor,
                ).to(self.model_dtype)
                # HuggingFace's mask builder probes `padding_mask.all()` to
                # decide whether the mask can be skipped, which syncs.
                with gpu_sync_allowed():
                    encoder_outputs = vt.encoder(
                        inputs_embeds=inputs_embeds,
                        attention_mask=~pad_tensor,
                        pixel_position_ids=pp_tensor,
                    )
                hidden_states = encoder_outputs.last_hidden_state

                for i, (orig_idx, _, _) in enumerate(chunk_items):
                    last_hidden_states_map[orig_idx] = hidden_states[i]

        # Pool per image to strip padding and reduce spatial resolution.
        all_valid_states: list[torch.Tensor] = [None] * total_images  # type: ignore[list-item]
        valid_lens = [0] * total_images

        for orig_idx in range(total_images):
            chunk_hidden = last_hidden_states_map[orig_idx]
            output_length = chunk_hidden.shape[0] // pooling_k2

            single_hidden = chunk_hidden.unsqueeze(0)
            single_pos_ids = pool_position_ids[orig_idx].unsqueeze(0)
            padding_positions = (single_pos_ids == -1).all(dim=-1)

            # The pooler goes through HuggingFace's mask builder, which probes
            # `padding_mask.all()`, and the mask indexing below needs the
            # selected count on the host.
            with gpu_sync_allowed():
                pooled_states, valid_mask = vt.pooler(
                    hidden_states=single_hidden,
                    pixel_position_ids=single_pos_ids,
                    padding_positions=padding_positions,
                    output_length=output_length,
                )
                valid_states = pooled_states[valid_mask]

            if getattr(vt.config, "standardize", False):
                valid_states = (valid_states - vt.std_bias) * vt.std_scale

            all_valid_states[orig_idx] = valid_states
            valid_lens[orig_idx] = valid_states.shape[0]

        # Project all images in a single batched call.
        flat_valid_states = torch.cat(all_valid_states, dim=0).to(self.model_dtype)
        flat_proj_embs = self.embed_vision(
            inputs_embeds=flat_valid_states.unsqueeze(0)
        ).squeeze(0)

        # Split back into per-image tensors (slicing returns views).
        per_image_embeddings: list[torch.Tensor] = []
        offset = 0
        for length in valid_lens:
            per_image_embeddings.append(flat_proj_embs[offset : offset + length])
            offset += length

        return per_image_embeddings

    # ------------------------------------------------------------------ #
    # Video processing (frames through vision tower)
    # ------------------------------------------------------------------ #

    def _process_video_input(
        self,
        video_input: dict[str, torch.Tensor],
    ) -> list[torch.Tensor]:
        """Batch-encode video frames through the vision tower.

        Gemma4 has no separate video tower; video frames are images at
        lower resolution (max_soft_tokens=70).  All frames across all
        videos in the batch are encoded together in chunks, then pooled
        and projected in a single batched call.

        Returns one concatenated embedding tensor per video (not per
        frame), matching the flat_from_sizes grouping that vLLM expects
        for embed_multimodal.
        """
        pixel_values = video_input["pixel_values_videos"]
        pixel_position_ids = video_input["pixel_position_ids_videos"]
        frame_counts = video_input["video_frame_counts"]

        vt = self.vision_tower
        vision_cfg = self.config.vision_config
        pooling_k2 = vision_cfg.pooling_kernel_size**2

        if isinstance(frame_counts, torch.Tensor):
            # Per-video frame counts drive the Python-level batching below.
            with gpu_sync_allowed():
                fc_list = frame_counts.tolist()
        else:
            fc_list = list(frame_counts)

        total_frames = pixel_values.shape[0]
        free, total = torch.accelerator.get_memory_info()
        max_batch_size = min(
            total_frames,
            self._encoder_chunk(
                pixel_values.shape[1],
                free,
                total,
                vision_cfg.position_embedding_size,
            ),
        )

        padding_positions = (pixel_position_ids == -1).all(dim=-1)

        # Encode frames in chunks bounded by _encoder_chunk.
        last_hidden_states_list: list[torch.Tensor] = []
        for i in range(0, total_frames, max_batch_size):
            pv_chunk = pixel_values[i : i + max_batch_size]
            pp_chunk = pixel_position_ids[i : i + max_batch_size]
            pad_chunk = padding_positions[i : i + max_batch_size]

            inputs_embeds = vt.patch_embedder(
                pv_chunk,
                pp_chunk,
                pad_chunk,
            ).to(self.model_dtype)
            # HuggingFace's mask builder probes `padding_mask.all()`.
            with gpu_sync_allowed():
                encoder_outputs = vt.encoder(
                    inputs_embeds=inputs_embeds,
                    attention_mask=~pad_chunk,
                    pixel_position_ids=pp_chunk,
                )
            last_hidden_states_list.append(encoder_outputs.last_hidden_state)

        last_hidden_states = torch.cat(last_hidden_states_list, dim=0)

        # Pool per frame to strip padding and reduce spatial resolution.
        output_length = pixel_values.shape[1] // pooling_k2
        all_frame_valid_states: list[torch.Tensor] = []
        frame_valid_lens: list[int] = []

        for i in range(total_frames):
            single_hidden = last_hidden_states[i].unsqueeze(0)
            single_pos_ids = pixel_position_ids[i].unsqueeze(0)
            single_pad_pos = padding_positions[i].unsqueeze(0)

            # As above, plus mask indexing that needs the count on the host.
            with gpu_sync_allowed():
                pooled_states, valid_mask = vt.pooler(
                    hidden_states=single_hidden,
                    pixel_position_ids=single_pos_ids,
                    padding_positions=single_pad_pos,
                    output_length=output_length,
                )
                valid_states = pooled_states[valid_mask]

            if getattr(vt.config, "standardize", False):
                valid_states = (valid_states - vt.std_bias) * vt.std_scale

            all_frame_valid_states.append(valid_states)
            frame_valid_lens.append(valid_states.shape[0])

        # Project all frames in a single batched call.
        flat_valid_states = torch.cat(all_frame_valid_states, dim=0).to(
            self.model_dtype
        )
        flat_proj_embs = self.embed_vision(
            inputs_embeds=flat_valid_states.unsqueeze(0)
        ).squeeze(0)

        # Regroup into per-video tensors (slicing returns views).
        per_video_embeddings: list[torch.Tensor] = []
        frame_idx = 0
        offset = 0
        for count in fc_list:
            video_tokens = sum(frame_valid_lens[frame_idx : frame_idx + count])
            per_video_embeddings.append(flat_proj_embs[offset : offset + video_tokens])
            offset += video_tokens
            frame_idx += count

        return per_video_embeddings

    # ------------------------------------------------------------------ #
    # Audio processing
    # ------------------------------------------------------------------ #

    def _process_audio_input(
        self,
        audio_input: Gemma4AudioInputs,
    ) -> list[torch.Tensor]:
        input_features, input_features_mask = batch_audio_features(
            audio_input["input_features_padded"],
            audio_input["input_features_mask"],
        )

        # Run audio tower — mask convention: True=valid, False=padding.
        audio_outputs = self.audio_tower(input_features, input_features_mask)
        if isinstance(audio_outputs, tuple):
            audio_encodings, audio_mask = audio_outputs
        else:
            audio_encodings = audio_outputs.last_hidden_state
            audio_mask = audio_outputs.attention_mask

        # Project into LM embedding space.
        audio_features = self.embed_audio(inputs_embeds=audio_encodings)

        # Strip padding per-batch element: only keep valid (non-padding)
        # tokens.
        # Boolean-mask indexing needs the selected count on the host.
        per_audio = []
        with gpu_sync_allowed():
            for enc, mask in zip(audio_features, audio_mask, strict=True):
                per_audio.append(enc[mask])  # [num_real, hidden_size]

        return per_audio

    # ------------------------------------------------------------------ #
    # MultiModalEmbeddings interface
    # ------------------------------------------------------------------ #

    def embed_multimodal(self, **kwargs: object) -> MultiModalEmbeddings:
        mm_input_by_modality = self._parse_and_validate_multimodal_inputs(**kwargs)
        multimodal_embeddings: list[torch.Tensor] = []

        for modality, multimodal_input in mm_input_by_modality.items():
            if multimodal_input is None:
                continue
            if modality == "image":
                multimodal_embeddings.extend(
                    self._process_image_input(multimodal_input)
                )
            elif modality == "video":
                multimodal_embeddings.extend(
                    self._process_video_input(multimodal_input)
                )
            elif modality == "audio":
                multimodal_embeddings.extend(
                    self._process_audio_input(multimodal_input)
                )

        return multimodal_embeddings

    # ------------------------------------------------------------------ #
    # EncoderCudaGraph protocol methods
    # ------------------------------------------------------------------ #

    def get_encoder_cudagraph_config(self) -> "EncoderCudaGraphConfig":
        from vllm.v1.worker.encoder_cudagraph_defs import EncoderCudaGraphConfig

        def pad_pixel_values(dst: torch.Tensor, src: torch.Tensor) -> None:
            dst.zero_()
            batch_size, num_patches = src.shape[0], src.shape[1]
            dst[:batch_size, :num_patches].copy_(src)

        def pad_pixel_position_ids(dst: torch.Tensor, src: torch.Tensor) -> None:
            dst.fill_(-1)
            batch_size, num_patches = src.shape[0], src.shape[1]
            dst[:batch_size, :num_patches].copy_(src)

        return EncoderCudaGraphConfig(
            modalities=["image", "video"],
            buffer_keys=[
                "pixel_values",
                "pixel_position_ids",
                "gather_indices",
            ],
            out_hidden_size=self.config.text_config.hidden_size,
            max_frames_per_video=_VIDEO_MAX_FRAMES,
            padding_logics={
                "pixel_values": pad_pixel_values,
                "pixel_position_ids": pad_pixel_position_ids,
            },
        )

    def get_encoder_cudagraph_budget_range(
        self,
        vllm_config: VllmConfig,
    ) -> tuple[int, int]:
        min_budget = _SUPPORTED_SOFT_TOKENS[0]
        max_budget = min(
            vllm_config.scheduler_config.max_num_batched_tokens,
            vllm_config.model_config.max_model_len,
        )
        return (min_budget, max_budget)

    def get_input_modality(self, mm_kwargs: dict[str, Any]) -> str:
        if "pixel_values" in mm_kwargs:
            return "image"
        elif "pixel_values_videos" in mm_kwargs:
            return "video"
        raise ValueError("Unsupported modality in mm_kwargs")

    def get_max_frames_per_video(self) -> int:
        return _VIDEO_MAX_FRAMES

    def get_encoder_cudagraph_item_specs(
        self,
        mm_kwargs: dict[str, Any],
    ) -> list["EncoderItemSpec"]:
        from vllm.v1.worker.encoder_cudagraph_defs import EncoderItemSpec

        vision_cfg = self.vision_tower.config
        pool_ratio = getattr(vision_cfg, "pooling_kernel_size", 2) ** 2

        modality = self.get_input_modality(mm_kwargs)
        if modality == "image":
            pixel_values = mm_kwargs["pixel_values"]
            if isinstance(pixel_values, list):
                return [
                    EncoderItemSpec(
                        input_size=pv.shape[0],
                        output_tokens=pv.shape[0] // pool_ratio,
                    )
                    for pv in pixel_values
                ]
            else:
                return [
                    EncoderItemSpec(
                        input_size=pixel_values.shape[1],
                        output_tokens=pixel_values.shape[1] // pool_ratio,
                    )
                    for _ in range(pixel_values.shape[0])
                ]
        elif modality == "video":
            pixel_values_videos = mm_kwargs["pixel_values_videos"]
            video_frame_counts = mm_kwargs["video_frame_counts"]
            fc_list = (
                video_frame_counts.tolist()
                if isinstance(video_frame_counts, torch.Tensor)
                else list(video_frame_counts)
            )
            np_patches = pixel_values_videos.shape[1]
            return [
                EncoderItemSpec(
                    input_size=fc * np_patches,
                    output_tokens=fc * (np_patches // pool_ratio),
                )
                for fc in fc_list
            ]
        raise ValueError(f"Unknown modality: {modality}")

    def select_encoder_cudagraph_items(
        self,
        mm_kwargs: dict[str, Any],
        indices: list[int],
    ) -> dict[str, Any]:
        modality = self.get_input_modality(mm_kwargs)
        if modality == "image":
            pixel_values = mm_kwargs["pixel_values"]
            pixel_position_ids = mm_kwargs["pixel_position_ids"]
            if len(indices) == 0:
                is_pv_list = isinstance(pixel_values, list)
                is_pp_list = isinstance(pixel_position_ids, list)
                return {
                    "pixel_values": ([] if is_pv_list else pixel_values[:0]),
                    "pixel_position_ids": (
                        [] if is_pp_list else pixel_position_ids[:0]
                    ),
                }
            if isinstance(pixel_values, list):
                return {
                    "pixel_values": [pixel_values[i] for i in indices],
                    "pixel_position_ids": [pixel_position_ids[i] for i in indices],
                }
            return {
                "pixel_values": pixel_values[indices],
                "pixel_position_ids": pixel_position_ids[indices],
            }
        elif modality == "video":
            pixel_values_videos = mm_kwargs["pixel_values_videos"]
            pixel_position_ids_videos = mm_kwargs["pixel_position_ids_videos"]
            video_frame_counts = mm_kwargs["video_frame_counts"]

            if len(indices) == 0:
                is_fc_tensor = isinstance(video_frame_counts, torch.Tensor)
                return {
                    "pixel_values_videos": pixel_values_videos[:0],
                    "pixel_position_ids_videos": pixel_position_ids_videos[:0],
                    "video_frame_counts": (
                        video_frame_counts[:0] if is_fc_tensor else []
                    ),
                }

            fc_list = (
                video_frame_counts.tolist()
                if isinstance(video_frame_counts, torch.Tensor)
                else list(video_frame_counts)
            )
            cum_frames = [0]
            for fc in fc_list:
                cum_frames.append(cum_frames[-1] + fc)

            selected_pv = torch.cat(
                [
                    pixel_values_videos[cum_frames[i] : cum_frames[i + 1]]
                    for i in indices
                ],
                dim=0,
            )
            selected_pp = torch.cat(
                [
                    pixel_position_ids_videos[cum_frames[i] : cum_frames[i + 1]]
                    for i in indices
                ],
                dim=0,
            )
            selected_fc = (
                video_frame_counts[indices]
                if isinstance(video_frame_counts, torch.Tensor)
                else [video_frame_counts[i] for i in indices]
            )
            return {
                "pixel_values_videos": selected_pv,
                "pixel_position_ids_videos": selected_pp,
                "video_frame_counts": selected_fc,
            }
        raise ValueError(f"Unknown modality: {modality}")

    def prepare_encoder_cudagraph_capture_inputs(
        self,
        token_budget: int = 256,
        max_batch_size: int = 4,
        max_frames_per_batch: int = 1,
        device: torch.device | str = "cpu",
        dtype: torch.dtype | None = None,
        path: str = "default",
        **kwargs: Any,
    ) -> "EncoderCudaGraphCaptureInputs":
        from vllm.v1.worker.encoder_cudagraph_defs import (
            EncoderCudaGraphCaptureInputs,
        )

        dtype = dtype or torch.float32

        max_size = max(max_batch_size, max_frames_per_batch)

        vision_cfg = self.vision_tower.config
        pool_ratio = getattr(vision_cfg, "pooling_kernel_size", 2) ** 2

        # Retrieve the model's actual configured maximum tokens:
        configured_max_tokens = getattr(
            self.config.vision_config,
            "num_soft_tokens",
            _SUPPORTED_SOFT_TOKENS[2],
        )
        # Dynamically compute the slot capacity per item bounded by both the
        # current graph budget and the user's maximum config:
        per_item_output = min(token_budget, configured_max_tokens)
        # Satisfy k^2 * per_item_output = per_item_patches
        per_item_patches = per_item_output * pool_ratio

        patch_size = self.vision_tower.config.patch_size
        num_channels = getattr(self.vision_tower.config, "num_channels", 3)
        patch_pixels = (patch_size**2) * num_channels

        dummy_pixel_values = torch.zeros(
            (max_size, per_item_patches, patch_pixels),
            device=device,
            dtype=dtype,
        )
        dummy_pixel_position_ids = torch.full(
            (max_size, per_item_patches, 2),
            -1,
            device=device,
            dtype=torch.long,
        )
        dummy_gather_indices = torch.zeros(
            (token_budget,),
            device=device,
            dtype=torch.long,
        )

        return EncoderCudaGraphCaptureInputs(
            values={
                "pixel_values": dummy_pixel_values,
                "pixel_position_ids": dummy_pixel_position_ids,
                "gather_indices": dummy_gather_indices,
            }
        )

    def prepare_encoder_cudagraph_replay_buffers(
        self,
        mm_kwargs: dict[str, Any],
        max_batch_size: int = 4,
        max_frames_per_batch: int = 1,
        path: str = "default",
        **kwargs: Any,
    ) -> "EncoderCudaGraphReplayBuffers":
        from vllm.v1.worker.encoder_cudagraph_defs import (
            EncoderCudaGraphReplayBuffers,
        )

        modality = self.get_input_modality(mm_kwargs)
        if modality == "image":
            pixel_values = mm_kwargs["pixel_values"]
            pixel_position_ids = mm_kwargs["pixel_position_ids"]
        elif modality == "video":
            pixel_values = mm_kwargs["pixel_values_videos"]
            pixel_position_ids = mm_kwargs["pixel_position_ids_videos"]
        else:
            raise ValueError(f"Unsupported modality: {modality}")

        if isinstance(pixel_values, list):
            max_patches = max(pv.shape[0] for pv in pixel_values)
            batch_size = len(pixel_values)
            pv_tensor = torch.zeros(
                (batch_size, max_patches, pixel_values[0].shape[1]),
                dtype=pixel_values[0].dtype,
                device=pixel_values[0].device,
            )
            pp_tensor = torch.full(
                (batch_size, max_patches, 2),
                -1,
                dtype=pixel_position_ids[0].dtype,
                device=pixel_position_ids[0].device,
            )
            for i, (pv, pp) in enumerate(zip(pixel_values, pixel_position_ids)):
                pv_tensor[i, : pv.shape[0]].copy_(pv)
                pp_tensor[i, : pp.shape[0]].copy_(pp)
            pixel_values = pv_tensor
            pixel_position_ids = pp_tensor

        item_specs = self.get_encoder_cudagraph_item_specs(mm_kwargs)
        per_item_out_tokens = [spec.output_tokens for spec in item_specs]
        total_tokens = sum(per_item_out_tokens)

        device = pixel_values.device
        vision_cfg = self.vision_tower.config
        pool_ratio = getattr(vision_cfg, "pooling_kernel_size", 2) ** 2
        per_item_output = pixel_values.shape[1] // pool_ratio

        # ONLY allocate an array of exact size `total_tokens`.
        # DO NOT pad it. The upstream Graph Manager handles the padding securely.
        gather_indices = torch.zeros((total_tokens,), dtype=torch.long, device=device)

        if modality == "image":
            dst_offset = 0
            for i, n_tok in enumerate(per_item_out_tokens):
                safe_n_tok = min(n_tok, per_item_output)
                src_start = i * per_item_output
                src_end = src_start + safe_n_tok
                gather_indices[dst_offset : dst_offset + safe_n_tok] = torch.arange(
                    src_start, src_end, dtype=torch.long, device=device
                )
                dst_offset += safe_n_tok
        elif modality == "video":
            video_frame_counts = mm_kwargs["video_frame_counts"]
            fc_list = (
                video_frame_counts.tolist()
                if isinstance(video_frame_counts, torch.Tensor)
                else list(video_frame_counts)
            )
            vision_cfg = self.vision_tower.config
            pool_ratio = getattr(vision_cfg, "pooling_kernel_size", 2) ** 2
            np_patches = pixel_values.shape[1]
            frame_output_tokens = np_patches // pool_ratio
            safe_frame_output_tokens = min(frame_output_tokens, per_item_output)

            dst_offset = 0
            frame_idx = 0
            for fc in fc_list:
                for f in range(fc):
                    src_start = (frame_idx + f) * per_item_output
                    src_end = src_start + safe_frame_output_tokens
                    gather_indices[
                        dst_offset : dst_offset + safe_frame_output_tokens
                    ] = torch.arange(
                        src_start, src_end, dtype=torch.long, device=device
                    )
                    dst_offset += safe_frame_output_tokens
                frame_idx += fc

        return EncoderCudaGraphReplayBuffers(
            values={
                "pixel_values": pixel_values,
                "pixel_position_ids": pixel_position_ids,
                "gather_indices": gather_indices,
            }
        )

    def encoder_cudagraph_forward(
        self,
        inputs: dict[str, torch.Tensor],
        path: str = "default",
        **kwargs: Any,
    ) -> torch.Tensor:
        pixel_values = inputs["pixel_values"]
        pixel_position_ids = inputs["pixel_position_ids"]
        gather_indices = inputs["gather_indices"]

        pad_tensor = (pixel_position_ids == -1).all(dim=-1)

        vt = self.vision_tower
        inputs_embeds = vt.patch_embedder(
            pixel_values,
            pixel_position_ids,
            pad_tensor,
        ).to(self.model_dtype)

        encoder_outputs = vt.encoder(
            inputs_embeds=inputs_embeds,
            attention_mask=~pad_tensor,
            pixel_position_ids=pixel_position_ids,
        )
        hidden_states = encoder_outputs.last_hidden_state

        pool_ratio = getattr(vt.config, "pooling_kernel_size", 2) ** 2
        per_item_output = pixel_values.shape[1] // pool_ratio

        pooled_states, _ = vt.pooler(
            hidden_states=hidden_states,
            pixel_position_ids=pixel_position_ids,
            padding_positions=pad_tensor,
            output_length=per_item_output,
        )

        if getattr(vt.config, "standardize", False):
            pooled_states = (pooled_states - vt.std_bias) * vt.std_scale

        flat_pooled = pooled_states.reshape(-1, pooled_states.shape[-1])
        gathered_states = flat_pooled[gather_indices]

        # Cast to the projection layer's dtype to resolve mixed-precision crash
        target_dtype = self.embed_vision.embedding_projection.weight.dtype
        gathered_states = gathered_states.to(target_dtype)

        flat_proj_embs = self.embed_vision(
            inputs_embeds=gathered_states.unsqueeze(0)
        ).squeeze(0)

        return flat_proj_embs

    def encoder_eager_forward(
        self,
        mm_kwargs: dict[str, Any],
        path: str = "default",
        **kwargs: Any,
    ) -> torch.Tensor:
        modality = self.get_input_modality(mm_kwargs)
        if modality == "image":
            image_input = self._parse_and_validate_image_input(**mm_kwargs)
            assert image_input is not None
            embeddings = self._process_image_input(image_input)
        elif modality == "video":
            video_input = self._parse_and_validate_video_input(**mm_kwargs)
            assert video_input is not None
            embeddings = self._process_video_input(video_input)
        else:
            raise ValueError(f"Unsupported modality: {modality}")

        return torch.cat(embeddings, dim=0)

    def embed_input_ids(
        self,
        input_ids: torch.Tensor,
        multimodal_embeddings: MultiModalEmbeddings | None = None,
        *,
        is_multimodal: torch.Tensor | None = None,
    ) -> torch.Tensor:
        # Cache per-layer embeddings (PLE) for the language model's
        # forward pass.  During profiling embed_input_ids is not called,
        # so the pre-allocated zeros are used instead.
        if self.per_layer_embeddings is not None:
            # Mask multimodal tokens (image/audio) to 0 for PLE
            # computation (using token_type_ids == 0 as text_mask).
            # Replicate this: map image token positions to token 0.
            if is_multimodal is not None:
                ple_input_ids = torch.where(
                    is_multimodal.to(input_ids.device, non_blocking=True),
                    torch.zeros_like(input_ids),
                    input_ids,
                )
            else:
                ple_input_ids = input_ids

            per_layer_inputs = self.language_model.model.get_per_layer_inputs(
                ple_input_ids
            )
            if per_layer_inputs is not None:
                per_layer_inputs = per_layer_inputs.reshape(
                    -1,
                    self.config.text_config.num_hidden_layers,
                    self.config.text_config.hidden_size_per_layer_input,
                )
                self.per_layer_embeddings[: per_layer_inputs.shape[0]].copy_(
                    per_layer_inputs
                )

        if multimodal_embeddings is None or is_multimodal is None:
            return super().embed_input_ids(input_ids)

        return super().embed_input_ids(
            input_ids,
            multimodal_embeddings=multimodal_embeddings,
            is_multimodal=is_multimodal,
        )

    # ------------------------------------------------------------------ #
    # Forward
    # ------------------------------------------------------------------ #

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

        # Select the pre-cached PLEs for this batch (None when PLE
        # is disabled for variants without PLE).
        per_layer_inputs = (
            self.per_layer_embeddings[: inputs_embeds.shape[0]]
            if self.per_layer_embeddings is not None and inputs_embeds is not None
            else None
        )

        # Gemma4 bidi: clear mm_prefix_range for full_attention layers.
        # Must run here (outside @support_torch_compile boundary) because
        # _run_decoder_layers is inside a compiled graph where Python
        # side effects are eliminated.
        self._clear_mm_prefix_for_full_attn_layers()

        hidden_states = self.language_model.model(
            input_ids,
            positions,
            per_layer_inputs=per_layer_inputs,
            intermediate_tensors=intermediate_tensors,
            inputs_embeds=inputs_embeds,
            **kwargs,
        )

        return hidden_states

    def compute_logits(
        self,
        hidden_states: torch.Tensor,
    ) -> torch.Tensor | None:
        logits = self.language_model.compute_logits(hidden_states)
        if logits is not None and self._suppress_token_ids:
            # Cache a per-device index tensor for the (static) suppressed-token
            # set and use `index_fill_`, so neither the Python-list indices nor
            # the scalar fill value take a host roundtrip per call.
            cache = getattr(self, "_suppress_token_ids_cache", None)
            if cache is None:
                cache = {}
                self._suppress_token_ids_cache = cache
            suppress_idx = cache.get(logits.device)
            if suppress_idx is None:
                suppress_idx = async_tensor_h2d(
                    self._suppress_token_ids, dtype=torch.long, device=logits.device
                )
                cache[logits.device] = suppress_idx
            logits.index_fill_(1, suppress_idx, -float("inf"))
        return logits

    # ------------------------------------------------------------------ #
    # Bidirectional attention helpers
    # ------------------------------------------------------------------ #

    def _clear_mm_prefix_for_full_attn_layers(self) -> None:
        """Clear mm_prefix_range for non-sliding layers.

        Gemma4 with use_bidirectional_attention='vision' applies
        bidirectional attention only to sliding_attention layers.
        Full attention layers use plain causal masking.

        Uses _full_attn_layer_idxs (precomputed in __init__) for O(1)
        lookup instead of per-call regex parsing.
        """
        if not self._full_attn_layer_idxs:
            return

        from vllm.forward_context import get_forward_context

        attn_metadata = get_forward_context().attn_metadata
        if attn_metadata is None:
            return

        def _process(metadata_dict: dict) -> None:
            for layer_name, metadata in metadata_dict.items():
                if ".layers." not in layer_name:
                    continue
                try:
                    layer_idx = int(layer_name.split(".layers.")[1].split(".")[0])
                except (ValueError, IndexError):
                    continue
                if layer_idx in self._full_attn_layer_idxs:
                    if hasattr(metadata, "mm_prefix_range"):
                        metadata.mm_prefix_range = None
                    if hasattr(metadata, "mm_prefix_range_tensor"):
                        metadata.mm_prefix_range_tensor = None
                    if hasattr(metadata, "mm_prefix_query_range_tensor"):
                        metadata.mm_prefix_query_range_tensor = None

        if isinstance(attn_metadata, list):
            for ub_metadata in attn_metadata:
                _process(ub_metadata)
        elif isinstance(attn_metadata, dict):
            _process(attn_metadata)

    # ------------------------------------------------------------------ #
    # Weight loading
    # ------------------------------------------------------------------ #

    def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
        # Some checkpoints have vestigial embed_vision.embedding and
        # embed_audio.embedding weights from the Gemma3n architecture
        # that are not used by Gemma4's MultimodalEmbedder (which only
        # has embedding_projection + embedding_post_projection_norm).
        ignore_prefixes = [
            "embed_vision.embedding.",
            "embed_audio.embedding.",
        ]
        # Models without audio tower should skip audio weights entirely.
        if self.audio_tower is None:
            ignore_prefixes.extend(
                [
                    "audio_tower.",
                    "embed_audio.",
                ]
            )
        loader = AutoWeightsLoader(
            self,
            ignore_unexpected_prefixes=ignore_prefixes,
        )
        return loader.load_weights(weights, mapper=self.hf_to_vllm_mapper)

    # ------------------------------------------------------------------ #
    # LoRA / multimodal mapping
    # ------------------------------------------------------------------ #

    def get_mm_mapping(self) -> MultiModelKeys:
        """Get the module prefix mapping for multimodal models."""
        connectors = ["embed_vision"]
        tower_models = ["vision_tower"]
        if self.audio_tower is not None:
            connectors.append("embed_audio")
            tower_models.append("audio_tower")

        return MultiModelKeys.from_string_field(
            language_model="language_model",
            connector=connectors,
            tower_model=tower_models,
        )

    def get_mm_lora_token_counts(
        self,
        *,
        modality: str,
        mm_kwargs: MultiModalKwargsItem | None,
        num_mm_embeds: int,
    ) -> tuple[int, int | None]:
        if modality in ("image", "video"):
            vision_config = self.config.vision_config
            pooling_k2 = vision_config.pooling_kernel_size**2

            if modality == "image":
                pixel_values_key = "pixel_values"
                max_soft_tokens = vision_config.default_output_length
                mm_processor_kwargs = getattr(
                    getattr(self, "multimodal_config", None),
                    "mm_processor_kwargs",
                    None,
                )
                if isinstance(mm_processor_kwargs, Mapping):
                    val, _ = _get_max_soft_tokens(mm_processor_kwargs)
                    if isinstance(val, int) and val in _SUPPORTED_SOFT_TOKENS:
                        max_soft_tokens = val
            else:
                pixel_values_key = "pixel_values_videos"
                max_soft_tokens = _VIDEO_MAX_SOFT_TOKENS

            tower_tokens = max_soft_tokens * pooling_k2 if modality == "image" else None
            connector_tokens = num_mm_embeds
            if tower_tokens is None and mm_kwargs is not None:
                field = mm_kwargs.get(pixel_values_key)
                if field is not None:
                    data = field.data
                    if isinstance(data, torch.Tensor) and data.ndim >= 2:
                        tower_tokens = int(math.prod(data.shape[:-1]))

            if tower_tokens is None:
                min_soft_tokens = min(_SUPPORTED_SOFT_TOKENS)
                tower_tokens = (
                    math.ceil(num_mm_embeds / min_soft_tokens)
                    * max_soft_tokens
                    * pooling_k2
                )

        if modality == "audio":
            tower_tokens = num_mm_embeds
            connector_tokens = num_mm_embeds

            if mm_kwargs is not None:
                field = mm_kwargs.get("input_features_padded")
                if field is not None:
                    data = field.data
                    if isinstance(data, torch.Tensor) and data.ndim >= 2:
                        batch_size = math.prod(data.shape[:-2])
                        audio_tokens = batch_size * math.ceil(data.shape[-2] / 4)
                        tower_tokens = audio_tokens
                        connector_tokens = audio_tokens

        return tower_tokens, connector_tokens

    @classmethod
    def get_placeholder_str(cls, modality: str, i: int) -> str | None:
        if modality == "image":
            return "<image_soft_token>"
        if modality == "audio":
            return "<audio_soft_token>"
        if modality == "video":
            return "<|video|>"
        raise ValueError(f"Unsupported modality: {modality}")

_clear_mm_prefix_for_full_attn_layers()

Clear mm_prefix_range for non-sliding layers.

Gemma4 with use_bidirectional_attention='vision' applies bidirectional attention only to sliding_attention layers. Full attention layers use plain causal masking.

Uses _full_attn_layer_idxs (precomputed in init) for O(1) lookup instead of per-call regex parsing.

Source code in vllm/model_executor/models/gemma4_mm.py
def _clear_mm_prefix_for_full_attn_layers(self) -> None:
    """Clear mm_prefix_range for non-sliding layers.

    Gemma4 with use_bidirectional_attention='vision' applies
    bidirectional attention only to sliding_attention layers.
    Full attention layers use plain causal masking.

    Uses _full_attn_layer_idxs (precomputed in __init__) for O(1)
    lookup instead of per-call regex parsing.
    """
    if not self._full_attn_layer_idxs:
        return

    from vllm.forward_context import get_forward_context

    attn_metadata = get_forward_context().attn_metadata
    if attn_metadata is None:
        return

    def _process(metadata_dict: dict) -> None:
        for layer_name, metadata in metadata_dict.items():
            if ".layers." not in layer_name:
                continue
            try:
                layer_idx = int(layer_name.split(".layers.")[1].split(".")[0])
            except (ValueError, IndexError):
                continue
            if layer_idx in self._full_attn_layer_idxs:
                if hasattr(metadata, "mm_prefix_range"):
                    metadata.mm_prefix_range = None
                if hasattr(metadata, "mm_prefix_range_tensor"):
                    metadata.mm_prefix_range_tensor = None
                if hasattr(metadata, "mm_prefix_query_range_tensor"):
                    metadata.mm_prefix_query_range_tensor = None

    if isinstance(attn_metadata, list):
        for ub_metadata in attn_metadata:
            _process(ub_metadata)
    elif isinstance(attn_metadata, dict):
        _process(attn_metadata)

_encoder_chunk(patches_per_item, free_bytes, total_bytes, position_embedding_size) staticmethod

Max chunk size whose F.one_hot transient fits in the budget.

The dominant transient inside HF's Gemma4VisionPatchEmbedder. _position_embeddings is F.one_hot(clamped_positions, num_classes=position_embedding_size) with shape (chunk, patches, 2, position_embedding_size), int64, plus its simultaneous cast to the position embedding table dtype. That, not the encoder residual stream, sets peak memory.

Source code in vllm/model_executor/models/gemma4_mm.py
@staticmethod
def _encoder_chunk(
    patches_per_item: int,
    free_bytes: int,
    total_bytes: int,
    position_embedding_size: int,
) -> int:
    """Max chunk size whose F.one_hot transient fits in the budget.

    The dominant transient inside HF's ``Gemma4VisionPatchEmbedder.
    _position_embeddings`` is
    ``F.one_hot(clamped_positions, num_classes=position_embedding_size)``
    with shape ``(chunk, patches, 2, position_embedding_size)``,
    int64, plus its simultaneous cast to the position embedding
    table dtype. That, not the encoder residual stream, sets peak
    memory.
    """
    if patches_per_item <= 0:
        return 1
    # Half of currently-free, capped at 10% of total so we leave room
    # for the rest of profile_run / the subsequent encoder + pooler.
    budget = min(free_bytes // 2, total_bytes // 10)
    if budget <= 0:
        return 1
    # F.one_hot allocates (chunk, patches, 2, pos_emb_size) int64
    # (the inner 2 is the (x, y) coordinate axis, 8 is sizeof(int64)).
    # Outer 2x covers the int64 buffer and its concurrent bf16 cast
    # plus the matmul output that live alongside it at peak.
    cost = patches_per_item * 4 * position_embedding_size * 8
    return max(1, budget // cost) if cost > 0 else 1

_process_image_input(image_input)

Batch-encode images through the vision tower.

Groups images by patch count (resolution bucket) so each encoder call processes a uniform-shape batch with no cross-resolution padding. With MM LoRA enabled, all images are padded into one batch so the encoder call matches the tower mapping.

Source code in vllm/model_executor/models/gemma4_mm.py
def _process_image_input(
    self,
    image_input: Gemma4ImageInputs,
) -> list[torch.Tensor]:
    """Batch-encode images through the vision tower.

    Groups images by patch count (resolution bucket) so each
    encoder call processes a uniform-shape batch with no
    cross-resolution padding. With MM LoRA enabled, all images are
    padded into one batch so the encoder call matches the tower mapping.
    """
    pixel_values = image_input["pixel_values"]
    pixel_position_ids = image_input["pixel_position_ids"]

    vt = self.vision_tower
    vision_cfg = self.config.vision_config
    pooling_k2 = vision_cfg.pooling_kernel_size**2

    # Concurrent requests with different image resolutions may
    # arrive as a list of per-image tensors, while same-resolution
    # batches may arrive as a stacked tensor.
    buckets: dict[int, list[tuple[int, torch.Tensor, torch.Tensor]]] = {}
    total_images = (
        len(pixel_values)
        if isinstance(pixel_values, list)
        else pixel_values.shape[0]
    )
    pool_position_ids = pixel_position_ids

    if self._enable_mm_lora:
        max_soft_tokens = vision_cfg.default_output_length
        mm_processor_kwargs = getattr(
            getattr(self, "multimodal_config", None),
            "mm_processor_kwargs",
            None,
        )
        if isinstance(mm_processor_kwargs, Mapping):
            value, _ = _get_max_soft_tokens(mm_processor_kwargs)
            if isinstance(value, int) and value in _SUPPORTED_SOFT_TOKENS:
                max_soft_tokens = value

        max_patches = max_soft_tokens * pooling_k2
        padded_position_ids: list[torch.Tensor] = []
        for idx in range(total_images):
            pv = pixel_values[idx]
            pp = pixel_position_ids[idx]
            num_patches = pv.shape[0]
            if num_patches > max_patches:
                raise ValueError(
                    f"Image {idx} has {num_patches} patches, which exceeds "
                    f"the MM LoRA patch limit of {max_patches}."
                )

            pad_len = max_patches - num_patches
            pv = torch.cat(
                (pv, pv.new_zeros((pad_len, *pv.shape[1:]))),
                dim=0,
            )
            pp = torch.cat(
                (pp, pp.new_full((pad_len, *pp.shape[1:]), -1)),
                dim=0,
            )
            buckets.setdefault(max_patches, []).append((idx, pv, pp))
            padded_position_ids.append(pp)
        pool_position_ids = padded_position_ids
    else:
        for idx in range(total_images):
            pv = pixel_values[idx]
            pp = pixel_position_ids[idx]
            buckets.setdefault(pv.shape[0], []).append((idx, pv, pp))

    # Encode each resolution bucket in memory-safe chunks. Re-read
    # free memory per bucket because the previous bucket's encoder
    # pass has already allocated activations we should account for.
    last_hidden_states_map: dict[int, torch.Tensor] = {}
    for patches, items in buckets.items():
        if self._enable_mm_lora:
            max_batch_size = len(items)
        else:
            free, total = torch.accelerator.get_memory_info()
            max_batch_size = min(
                len(items),
                self._encoder_chunk(
                    patches, free, total, vision_cfg.position_embedding_size
                ),
            )

        for chunk_idx in range(0, len(items), max_batch_size):
            chunk_items = items[chunk_idx : chunk_idx + max_batch_size]

            pv_tensor = torch.cat(
                [item[1].unsqueeze(0) for item in chunk_items], dim=0
            )
            pp_tensor = torch.cat(
                [item[2].unsqueeze(0) for item in chunk_items], dim=0
            )
            pad_tensor = (pp_tensor == -1).all(dim=-1)

            inputs_embeds = vt.patch_embedder(
                pv_tensor,
                pp_tensor,
                pad_tensor,
            ).to(self.model_dtype)
            # HuggingFace's mask builder probes `padding_mask.all()` to
            # decide whether the mask can be skipped, which syncs.
            with gpu_sync_allowed():
                encoder_outputs = vt.encoder(
                    inputs_embeds=inputs_embeds,
                    attention_mask=~pad_tensor,
                    pixel_position_ids=pp_tensor,
                )
            hidden_states = encoder_outputs.last_hidden_state

            for i, (orig_idx, _, _) in enumerate(chunk_items):
                last_hidden_states_map[orig_idx] = hidden_states[i]

    # Pool per image to strip padding and reduce spatial resolution.
    all_valid_states: list[torch.Tensor] = [None] * total_images  # type: ignore[list-item]
    valid_lens = [0] * total_images

    for orig_idx in range(total_images):
        chunk_hidden = last_hidden_states_map[orig_idx]
        output_length = chunk_hidden.shape[0] // pooling_k2

        single_hidden = chunk_hidden.unsqueeze(0)
        single_pos_ids = pool_position_ids[orig_idx].unsqueeze(0)
        padding_positions = (single_pos_ids == -1).all(dim=-1)

        # The pooler goes through HuggingFace's mask builder, which probes
        # `padding_mask.all()`, and the mask indexing below needs the
        # selected count on the host.
        with gpu_sync_allowed():
            pooled_states, valid_mask = vt.pooler(
                hidden_states=single_hidden,
                pixel_position_ids=single_pos_ids,
                padding_positions=padding_positions,
                output_length=output_length,
            )
            valid_states = pooled_states[valid_mask]

        if getattr(vt.config, "standardize", False):
            valid_states = (valid_states - vt.std_bias) * vt.std_scale

        all_valid_states[orig_idx] = valid_states
        valid_lens[orig_idx] = valid_states.shape[0]

    # Project all images in a single batched call.
    flat_valid_states = torch.cat(all_valid_states, dim=0).to(self.model_dtype)
    flat_proj_embs = self.embed_vision(
        inputs_embeds=flat_valid_states.unsqueeze(0)
    ).squeeze(0)

    # Split back into per-image tensors (slicing returns views).
    per_image_embeddings: list[torch.Tensor] = []
    offset = 0
    for length in valid_lens:
        per_image_embeddings.append(flat_proj_embs[offset : offset + length])
        offset += length

    return per_image_embeddings

_process_video_input(video_input)

Batch-encode video frames through the vision tower.

Gemma4 has no separate video tower; video frames are images at lower resolution (max_soft_tokens=70). All frames across all videos in the batch are encoded together in chunks, then pooled and projected in a single batched call.

Returns one concatenated embedding tensor per video (not per frame), matching the flat_from_sizes grouping that vLLM expects for embed_multimodal.

Source code in vllm/model_executor/models/gemma4_mm.py
def _process_video_input(
    self,
    video_input: dict[str, torch.Tensor],
) -> list[torch.Tensor]:
    """Batch-encode video frames through the vision tower.

    Gemma4 has no separate video tower; video frames are images at
    lower resolution (max_soft_tokens=70).  All frames across all
    videos in the batch are encoded together in chunks, then pooled
    and projected in a single batched call.

    Returns one concatenated embedding tensor per video (not per
    frame), matching the flat_from_sizes grouping that vLLM expects
    for embed_multimodal.
    """
    pixel_values = video_input["pixel_values_videos"]
    pixel_position_ids = video_input["pixel_position_ids_videos"]
    frame_counts = video_input["video_frame_counts"]

    vt = self.vision_tower
    vision_cfg = self.config.vision_config
    pooling_k2 = vision_cfg.pooling_kernel_size**2

    if isinstance(frame_counts, torch.Tensor):
        # Per-video frame counts drive the Python-level batching below.
        with gpu_sync_allowed():
            fc_list = frame_counts.tolist()
    else:
        fc_list = list(frame_counts)

    total_frames = pixel_values.shape[0]
    free, total = torch.accelerator.get_memory_info()
    max_batch_size = min(
        total_frames,
        self._encoder_chunk(
            pixel_values.shape[1],
            free,
            total,
            vision_cfg.position_embedding_size,
        ),
    )

    padding_positions = (pixel_position_ids == -1).all(dim=-1)

    # Encode frames in chunks bounded by _encoder_chunk.
    last_hidden_states_list: list[torch.Tensor] = []
    for i in range(0, total_frames, max_batch_size):
        pv_chunk = pixel_values[i : i + max_batch_size]
        pp_chunk = pixel_position_ids[i : i + max_batch_size]
        pad_chunk = padding_positions[i : i + max_batch_size]

        inputs_embeds = vt.patch_embedder(
            pv_chunk,
            pp_chunk,
            pad_chunk,
        ).to(self.model_dtype)
        # HuggingFace's mask builder probes `padding_mask.all()`.
        with gpu_sync_allowed():
            encoder_outputs = vt.encoder(
                inputs_embeds=inputs_embeds,
                attention_mask=~pad_chunk,
                pixel_position_ids=pp_chunk,
            )
        last_hidden_states_list.append(encoder_outputs.last_hidden_state)

    last_hidden_states = torch.cat(last_hidden_states_list, dim=0)

    # Pool per frame to strip padding and reduce spatial resolution.
    output_length = pixel_values.shape[1] // pooling_k2
    all_frame_valid_states: list[torch.Tensor] = []
    frame_valid_lens: list[int] = []

    for i in range(total_frames):
        single_hidden = last_hidden_states[i].unsqueeze(0)
        single_pos_ids = pixel_position_ids[i].unsqueeze(0)
        single_pad_pos = padding_positions[i].unsqueeze(0)

        # As above, plus mask indexing that needs the count on the host.
        with gpu_sync_allowed():
            pooled_states, valid_mask = vt.pooler(
                hidden_states=single_hidden,
                pixel_position_ids=single_pos_ids,
                padding_positions=single_pad_pos,
                output_length=output_length,
            )
            valid_states = pooled_states[valid_mask]

        if getattr(vt.config, "standardize", False):
            valid_states = (valid_states - vt.std_bias) * vt.std_scale

        all_frame_valid_states.append(valid_states)
        frame_valid_lens.append(valid_states.shape[0])

    # Project all frames in a single batched call.
    flat_valid_states = torch.cat(all_frame_valid_states, dim=0).to(
        self.model_dtype
    )
    flat_proj_embs = self.embed_vision(
        inputs_embeds=flat_valid_states.unsqueeze(0)
    ).squeeze(0)

    # Regroup into per-video tensors (slicing returns views).
    per_video_embeddings: list[torch.Tensor] = []
    frame_idx = 0
    offset = 0
    for count in fc_list:
        video_tokens = sum(frame_valid_lens[frame_idx : frame_idx + count])
        per_video_embeddings.append(flat_proj_embs[offset : offset + video_tokens])
        offset += video_tokens
        frame_idx += count

    return per_video_embeddings

get_mm_mapping()

Get the module prefix mapping for multimodal models.

Source code in vllm/model_executor/models/gemma4_mm.py
def get_mm_mapping(self) -> MultiModelKeys:
    """Get the module prefix mapping for multimodal models."""
    connectors = ["embed_vision"]
    tower_models = ["vision_tower"]
    if self.audio_tower is not None:
        connectors.append("embed_audio")
        tower_models.append("audio_tower")

    return MultiModelKeys.from_string_field(
        language_model="language_model",
        connector=connectors,
        tower_model=tower_models,
    )

Gemma4ImagePixelInputs

Bases: TensorSchema

Pre-patchified image inputs from the Gemma4 image processor.

Dimensions
  • bn: Batch size * number of images
  • np: Number of patches (max_patches = max_soft_tokens * pooling_kernel_size²)
  • pp: Patch pixels (patch_size² * 3)

The Gemma4 image processor outputs pixel_values as (batch, max_patches, patch_pixels) — already patchified with zero-padding for patches beyond the real image content. pixel_position_ids provides (x, y) coordinates per patch, with (-1, -1) for padding patches.

Source code in vllm/model_executor/models/gemma4_mm.py
class Gemma4ImagePixelInputs(TensorSchema):
    """
    Pre-patchified image inputs from the Gemma4 image processor.

    Dimensions:
        - bn: Batch size * number of images
        - np: Number of patches (max_patches = max_soft_tokens * pooling_kernel_size²)
        - pp: Patch pixels (patch_size² * 3)

    The Gemma4 image processor outputs pixel_values as
    (batch, max_patches, patch_pixels) — already patchified with
    zero-padding for patches beyond the real image content.
    pixel_position_ids provides (x, y) coordinates per patch,
    with (-1, -1) for padding patches.
    """

    type: Literal["pixel_values"] = "pixel_values"
    pixel_values: Annotated[
        torch.Tensor | list[torch.Tensor],
        TensorShape("bn", "np", "pp", dynamic_dims={"np"}),
    ]
    pixel_position_ids: Annotated[
        torch.Tensor | list[torch.Tensor],
        TensorShape("bn", "np", 2, dynamic_dims={"np"}),
    ]

Gemma4MultimodalEmbedder

Bases: Module

Projects vision/audio soft tokens into LM embedding space.

Architecture

inputs_embeds → embedding_projection → embedding_post_projection_norm

Unlike Gemma3n which has separate hard/soft embedding paths with per-path normalization and a learned embedding table, Gemma4 uses a simplified 2-layer design: a linear projection followed by RMSNorm (without learnable scale). The checkpoint confirms this — only embedding_projection.weight exists; there is no embedding table or pre-projection norm weights.

Methods:

  • forward

    Project soft tokens from a multimodal tower into LM space.

Source code in vllm/model_executor/models/gemma4_mm.py
class Gemma4MultimodalEmbedder(nn.Module):
    """Projects vision/audio soft tokens into LM embedding space.

    Architecture:
        inputs_embeds → embedding_projection → embedding_post_projection_norm

    Unlike Gemma3n which has separate hard/soft embedding paths with
    per-path normalization and a learned embedding table, Gemma4 uses a
    simplified 2-layer design: a linear projection followed by RMSNorm
    (without learnable scale).  The checkpoint confirms this — only
    ``embedding_projection.weight`` exists; there is no embedding table
    or pre-projection norm weights.
    """

    def __init__(
        self,
        multimodal_config: Gemma4VisionConfig | Gemma4AudioConfig,
        text_config: Gemma4TextConfig,
        *,
        quant_config: "QuantizationConfig | None" = None,
        prefix: str = "",
    ):
        super().__init__()

        self.eps = multimodal_config.rms_norm_eps
        self.text_hidden_size = text_config.hidden_size

        # Audio tower uses output_proj_dims (1536) rather than hidden_size
        # (1024); vision uses hidden_size (768) directly.
        embedding_dim = (
            getattr(multimodal_config, "output_proj_dims", None)
            or multimodal_config.hidden_size
        )

        self.embedding_pre_projection_norm = RMSNorm(
            embedding_dim,
            eps=self.eps,
            has_weight=False,
        )

        self.embedding_projection = ReplicatedLinear(
            embedding_dim,
            self.text_hidden_size,
            bias=False,
            quant_config=quant_config,
            prefix=maybe_prefix(prefix, "embedding_projection"),
        )

    def forward(self, inputs_embeds: torch.Tensor) -> torch.Tensor:
        """Project soft tokens from a multimodal tower into LM space."""
        embs_normed = self.embedding_pre_projection_norm(inputs_embeds)
        embs_proj, _ = self.embedding_projection(embs_normed)
        return embs_proj

forward(inputs_embeds)

Project soft tokens from a multimodal tower into LM space.

Source code in vllm/model_executor/models/gemma4_mm.py
def forward(self, inputs_embeds: torch.Tensor) -> torch.Tensor:
    """Project soft tokens from a multimodal tower into LM space."""
    embs_normed = self.embedding_pre_projection_norm(inputs_embeds)
    embs_proj, _ = self.embedding_projection(embs_normed)
    return embs_proj

Gemma4ProcessingInfo

Bases: BaseProcessingInfo

Methods:

Source code in vllm/model_executor/models/gemma4_mm.py
class Gemma4ProcessingInfo(BaseProcessingInfo):
    def get_hf_config(self):
        return self.ctx.get_hf_config(Gemma4Config)

    def get_default_tok_params(self):
        """Gemma4's chat template already embeds a literal ``<bos>`` token in
        the rendered text.  If ``add_special_tokens=True`` (the base-class
        default), the tokenizer prepends *another* BOS, producing a
        ``[2, 2, ...]`` double-BOS sequence that the model was not trained on.

        Setting ``add_special_tokens=False`` here prevents the duplicate and
        ensures both ``llm.generate()`` and the chat/completions API behave
        correctly for IT models. For PT models (without chat template), we
        keep the default (True) to ensure BOS is added for raw prompts.
        """
        tokenizer = self.ctx.get_tokenizer()
        has_chat_template = getattr(tokenizer, "chat_template", None) is not None

        params = super().get_default_tok_params()
        if has_chat_template:
            params = params.with_kwargs(add_special_tokens=False)
        return params

    def get_hf_processor(self, **kwargs: object) -> Gemma4Processor:
        return self.ctx.get_hf_processor(
            Gemma4Processor,
            **kwargs,
        )

    def validate_num_items(self, modality: str, num_items: int) -> None:
        if (
            modality == "audio"
            and num_items > 0
            and self.get_hf_config().audio_config is None
        ):
            model_config = self.ctx.model_config
            model = get_served_model_name(
                model_config.model, model_config.served_model_name
            )
            raise ValueError(
                f"Audio input was provided but the model "
                f"'{model}' does not have an audio tower. "
                f"Audio inference is only supported for Gemma4 "
                f"models that include an audio_config "
                f"(i.e., models that include an audio_config)."
            )
        super().validate_num_items(modality, num_items)

    def get_supported_mm_limits(self) -> Mapping[str, int | None]:
        limits: dict[str, int | None] = {"image": None}
        if self.get_hf_config().audio_config is not None:
            limits["audio"] = None
        limits["video"] = None
        return limits

    def get_mm_max_tokens_per_item(
        self, seq_len: int, mm_counts: Mapping[str, int]
    ) -> Mapping[str, int] | None:
        config = self.get_hf_config()
        # Upper bound: the pooler outputs max_soft_tokens slots per image.
        # After padding is stripped the actual count is ≤ this value, but
        # vLLM needs the max for memory planning.
        tokens_per_image = config.vision_config.default_output_length
        merged_kwargs = self.ctx.get_merged_mm_kwargs({})
        val, _ = _get_max_soft_tokens(merged_kwargs)
        if isinstance(val, int) and val in _SUPPORTED_SOFT_TOKENS:
            tokens_per_image = val
        tokens: dict[str, int] = {"image": tokens_per_image}
        if config.audio_config is not None:
            # Audio max tokens from the processor's audio_seq_length.
            processor = self.get_hf_processor()
            tokens["audio"] = processor.audio_seq_length
        # Video: each frame ≤ 70 soft tokens + boi + eoi + ~6 ts tokens.
        num_frames = _VIDEO_MAX_FRAMES
        mm_config = self.ctx.model_config.get_multimodal_config()
        video_opts = mm_config.limit_per_prompt.get("video")
        if (
            isinstance(video_opts, VideoDummyOptions)
            and video_opts.num_frames is not None
        ):
            num_frames = min(num_frames, video_opts.num_frames)
        tokens["video"] = num_frames * (_VIDEO_MAX_SOFT_TOKENS + 2 + 6)
        return tokens

    def get_data_parser(self) -> MultiModalDataParser:
        config = self.get_hf_config()
        kwargs: dict[str, Any] = {"video_needs_metadata": True}
        if getattr(config, "audio_config", None) is not None:
            processor = self.get_hf_processor()
            kwargs["target_sr"] = processor.feature_extractor.sampling_rate
        return MultiModalDataParser(**kwargs)

    def _compute_num_soft_tokens(
        self,
        image_width: int,
        image_height: int,
        max_soft_tokens: int | None = None,
    ) -> int:
        """Compute the number of soft tokens the vision tower produces
        for an image of the given dimensions, after padding is stripped.

        Args:
            max_soft_tokens: Override for the vision config's
                ``default_output_length``.  When *None*, the value from
                the model config is used.
        """
        vision_cfg = self.get_hf_config().vision_config
        patch_size = vision_cfg.patch_size
        pooling_kernel_size = vision_cfg.pooling_kernel_size

        if max_soft_tokens is None:
            max_soft_tokens = vision_cfg.default_output_length

        unit = patch_size * pooling_kernel_size
        max_patches = max_soft_tokens * pooling_kernel_size**2
        num_patches_orig = (image_height / patch_size) * (image_width / patch_size)
        scale = math.sqrt(max_patches / num_patches_orig)
        target_h = max(unit, int(math.floor(image_height * scale / unit)) * unit)
        target_w = max(unit, int(math.floor(image_width * scale / unit)) * unit)
        num_patches = (target_h // patch_size) * (target_w // patch_size)
        # Clamp to ``max_soft_tokens``: extreme aspect ratios (e.g. 3x900)
        # cause the floor() above to round one dim up to ``unit`` while the
        # other scales freely, which over-shoots ``max_patches``. The HF
        # Gemma 4 image processor caps its vision-tower output at
        # ``max_soft_tokens``, so without this clamp the prompt-side
        # placeholder count exceeds the encoder output and
        # ``_merge_multimodal_embeddings`` crashes.
        return min(num_patches // (pooling_kernel_size**2), max_soft_tokens)

    def get_image_repl(
        self,
        *,
        image_width: int,
        image_height: int,
        processor: Gemma4Processor | None,
        max_soft_tokens: int | None = None,
    ) -> PromptUpdateDetails[list[int]]:
        """Return the dynamic image token sequence for this image.

        Computes the exact number of soft tokens the vision tower will
        produce after stripping padding.

        Args:
            max_soft_tokens: Override for the default token budget.
                When *None*, falls back to the model config value.
        """
        if processor is None:
            processor = self.get_hf_processor()

        num_soft = self._compute_num_soft_tokens(
            image_width,
            image_height,
            max_soft_tokens=max_soft_tokens,
        )
        config = self.get_hf_config()
        token_ids = (
            [config.boi_token_id]
            + [processor.image_token_id] * num_soft
            + [config.eoi_token_id]
        )
        return PromptUpdateDetails.select_token_id(token_ids, processor.image_token_id)

    @staticmethod
    def _compute_audio_num_tokens(
        num_samples: int, sampling_rate: int, audio_seq_length: int
    ) -> int:
        """Replicate the audio encoder's sequence-length arithmetic.

        Mirrors: mel framing (_unfold in Gemma4AudioFeatureExtractor)
        followed by two Conv2d subsampling layers (kernel=3, stride=2,
        semicausal padding top=1, bottom=1), capped at audio_seq_length.
        """
        frame_length = int(round(sampling_rate * 20.0 / 1000.0))
        hop_length = int(round(sampling_rate * 10.0 / 1000.0))
        frame_size_for_unfold = frame_length + 1
        pad_left = frame_length // 2
        padded_samples = num_samples + pad_left
        num_mel_frames = (padded_samples - frame_size_for_unfold) // hop_length + 1
        if num_mel_frames <= 0:
            return 0
        t = num_mel_frames
        for _ in range(2):
            t = (t + 2 - 3) // 2 + 1
        return min(t, audio_seq_length)

    def get_audio_repl(
        self,
        *,
        audio_len: int,
        processor: Gemma4Processor | None,
    ) -> PromptUpdateDetails[list[int]]:
        """Return the dynamic audio token sequence for this audio.

        Computes the number of soft tokens from the audio waveform
        length by replicating the audio encoder's sequence-length
        arithmetic (mel framing + two Conv2d subsampling layers).
        """
        if processor is None:
            processor = self.get_hf_processor()

        sampling_rate = processor.feature_extractor.sampling_rate
        num_tokens = self._compute_audio_num_tokens(
            audio_len, sampling_rate, processor.audio_seq_length
        )
        config = self.get_hf_config()
        token_ids = (
            [config.boa_token_id]
            + [processor.audio_token_id] * num_tokens
            + [getattr(config, "eoa_token_id", config.eoa_token_index)]
        )
        return PromptUpdateDetails.select_token_id(token_ids, processor.audio_token_id)

    def get_video_repl(
        self,
        *,
        timestamps: list[float],
        num_soft_tokens_per_frame: list[int],
        processor: Gemma4Processor,
    ) -> PromptUpdateDetails[list[int]]:
        """Build the full token replacement for one video.

        Produces the same interleaved sequence as the HF Gemma4Processor:
            mm:ss <boi><|video|>*N<eoi> mm:ss <boi><|video|>*N<eoi> ...
        """
        tokenizer = self.ctx.get_tokenizer()
        config = self.get_hf_config()

        boi_token_id = config.boi_token_id
        eoi_token_id = config.eoi_token_id
        video_token_id = processor.video_token_id

        all_token_ids: list[int] = []
        for i, (ts, n_tokens) in enumerate(zip(timestamps, num_soft_tokens_per_frame)):
            # mm:ss timestamp — matches transformers: int-truncated,
            # zero-padded.
            minutes = int(ts // 60)
            seconds = int(ts % 60)
            ts_str = f"{minutes:02d}:{seconds:02d}"

            prefix = f" {ts_str} " if i > 0 else f"{ts_str} "
            ts_token_ids = tokenizer.encode(prefix, add_special_tokens=False)
            all_token_ids.extend(ts_token_ids)

            all_token_ids.append(boi_token_id)
            all_token_ids.extend([video_token_id] * n_tokens)
            all_token_ids.append(eoi_token_id)

        return PromptUpdateDetails.select_token_id(all_token_ids, video_token_id)

_compute_audio_num_tokens(num_samples, sampling_rate, audio_seq_length) staticmethod

Replicate the audio encoder's sequence-length arithmetic.

Mirrors: mel framing (_unfold in Gemma4AudioFeatureExtractor) followed by two Conv2d subsampling layers (kernel=3, stride=2, semicausal padding top=1, bottom=1), capped at audio_seq_length.

Source code in vllm/model_executor/models/gemma4_mm.py
@staticmethod
def _compute_audio_num_tokens(
    num_samples: int, sampling_rate: int, audio_seq_length: int
) -> int:
    """Replicate the audio encoder's sequence-length arithmetic.

    Mirrors: mel framing (_unfold in Gemma4AudioFeatureExtractor)
    followed by two Conv2d subsampling layers (kernel=3, stride=2,
    semicausal padding top=1, bottom=1), capped at audio_seq_length.
    """
    frame_length = int(round(sampling_rate * 20.0 / 1000.0))
    hop_length = int(round(sampling_rate * 10.0 / 1000.0))
    frame_size_for_unfold = frame_length + 1
    pad_left = frame_length // 2
    padded_samples = num_samples + pad_left
    num_mel_frames = (padded_samples - frame_size_for_unfold) // hop_length + 1
    if num_mel_frames <= 0:
        return 0
    t = num_mel_frames
    for _ in range(2):
        t = (t + 2 - 3) // 2 + 1
    return min(t, audio_seq_length)

_compute_num_soft_tokens(image_width, image_height, max_soft_tokens=None)

Compute the number of soft tokens the vision tower produces for an image of the given dimensions, after padding is stripped.

Parameters:

  • max_soft_tokens

    (int | None, default: None ) –

    Override for the vision config's default_output_length. When None, the value from the model config is used.

Source code in vllm/model_executor/models/gemma4_mm.py
def _compute_num_soft_tokens(
    self,
    image_width: int,
    image_height: int,
    max_soft_tokens: int | None = None,
) -> int:
    """Compute the number of soft tokens the vision tower produces
    for an image of the given dimensions, after padding is stripped.

    Args:
        max_soft_tokens: Override for the vision config's
            ``default_output_length``.  When *None*, the value from
            the model config is used.
    """
    vision_cfg = self.get_hf_config().vision_config
    patch_size = vision_cfg.patch_size
    pooling_kernel_size = vision_cfg.pooling_kernel_size

    if max_soft_tokens is None:
        max_soft_tokens = vision_cfg.default_output_length

    unit = patch_size * pooling_kernel_size
    max_patches = max_soft_tokens * pooling_kernel_size**2
    num_patches_orig = (image_height / patch_size) * (image_width / patch_size)
    scale = math.sqrt(max_patches / num_patches_orig)
    target_h = max(unit, int(math.floor(image_height * scale / unit)) * unit)
    target_w = max(unit, int(math.floor(image_width * scale / unit)) * unit)
    num_patches = (target_h // patch_size) * (target_w // patch_size)
    # Clamp to ``max_soft_tokens``: extreme aspect ratios (e.g. 3x900)
    # cause the floor() above to round one dim up to ``unit`` while the
    # other scales freely, which over-shoots ``max_patches``. The HF
    # Gemma 4 image processor caps its vision-tower output at
    # ``max_soft_tokens``, so without this clamp the prompt-side
    # placeholder count exceeds the encoder output and
    # ``_merge_multimodal_embeddings`` crashes.
    return min(num_patches // (pooling_kernel_size**2), max_soft_tokens)

get_audio_repl(*, audio_len, processor)

Return the dynamic audio token sequence for this audio.

Computes the number of soft tokens from the audio waveform length by replicating the audio encoder's sequence-length arithmetic (mel framing + two Conv2d subsampling layers).

Source code in vllm/model_executor/models/gemma4_mm.py
def get_audio_repl(
    self,
    *,
    audio_len: int,
    processor: Gemma4Processor | None,
) -> PromptUpdateDetails[list[int]]:
    """Return the dynamic audio token sequence for this audio.

    Computes the number of soft tokens from the audio waveform
    length by replicating the audio encoder's sequence-length
    arithmetic (mel framing + two Conv2d subsampling layers).
    """
    if processor is None:
        processor = self.get_hf_processor()

    sampling_rate = processor.feature_extractor.sampling_rate
    num_tokens = self._compute_audio_num_tokens(
        audio_len, sampling_rate, processor.audio_seq_length
    )
    config = self.get_hf_config()
    token_ids = (
        [config.boa_token_id]
        + [processor.audio_token_id] * num_tokens
        + [getattr(config, "eoa_token_id", config.eoa_token_index)]
    )
    return PromptUpdateDetails.select_token_id(token_ids, processor.audio_token_id)

get_default_tok_params()

Gemma4's chat template already embeds a literal <bos> token in the rendered text. If add_special_tokens=True (the base-class default), the tokenizer prepends another BOS, producing a [2, 2, ...] double-BOS sequence that the model was not trained on.

Setting add_special_tokens=False here prevents the duplicate and ensures both llm.generate() and the chat/completions API behave correctly for IT models. For PT models (without chat template), we keep the default (True) to ensure BOS is added for raw prompts.

Source code in vllm/model_executor/models/gemma4_mm.py
def get_default_tok_params(self):
    """Gemma4's chat template already embeds a literal ``<bos>`` token in
    the rendered text.  If ``add_special_tokens=True`` (the base-class
    default), the tokenizer prepends *another* BOS, producing a
    ``[2, 2, ...]`` double-BOS sequence that the model was not trained on.

    Setting ``add_special_tokens=False`` here prevents the duplicate and
    ensures both ``llm.generate()`` and the chat/completions API behave
    correctly for IT models. For PT models (without chat template), we
    keep the default (True) to ensure BOS is added for raw prompts.
    """
    tokenizer = self.ctx.get_tokenizer()
    has_chat_template = getattr(tokenizer, "chat_template", None) is not None

    params = super().get_default_tok_params()
    if has_chat_template:
        params = params.with_kwargs(add_special_tokens=False)
    return params

get_image_repl(*, image_width, image_height, processor, max_soft_tokens=None)

Return the dynamic image token sequence for this image.

Computes the exact number of soft tokens the vision tower will produce after stripping padding.

Parameters:

  • max_soft_tokens

    (int | None, default: None ) –

    Override for the default token budget. When None, falls back to the model config value.

Source code in vllm/model_executor/models/gemma4_mm.py
def get_image_repl(
    self,
    *,
    image_width: int,
    image_height: int,
    processor: Gemma4Processor | None,
    max_soft_tokens: int | None = None,
) -> PromptUpdateDetails[list[int]]:
    """Return the dynamic image token sequence for this image.

    Computes the exact number of soft tokens the vision tower will
    produce after stripping padding.

    Args:
        max_soft_tokens: Override for the default token budget.
            When *None*, falls back to the model config value.
    """
    if processor is None:
        processor = self.get_hf_processor()

    num_soft = self._compute_num_soft_tokens(
        image_width,
        image_height,
        max_soft_tokens=max_soft_tokens,
    )
    config = self.get_hf_config()
    token_ids = (
        [config.boi_token_id]
        + [processor.image_token_id] * num_soft
        + [config.eoi_token_id]
    )
    return PromptUpdateDetails.select_token_id(token_ids, processor.image_token_id)

get_video_repl(*, timestamps, num_soft_tokens_per_frame, processor)

Build the full token replacement for one video.

Produces the same interleaved sequence as the HF Gemma4Processor

mm:ss <|video|>N mm:ss <|video|>N ...

Source code in vllm/model_executor/models/gemma4_mm.py
def get_video_repl(
    self,
    *,
    timestamps: list[float],
    num_soft_tokens_per_frame: list[int],
    processor: Gemma4Processor,
) -> PromptUpdateDetails[list[int]]:
    """Build the full token replacement for one video.

    Produces the same interleaved sequence as the HF Gemma4Processor:
        mm:ss <boi><|video|>*N<eoi> mm:ss <boi><|video|>*N<eoi> ...
    """
    tokenizer = self.ctx.get_tokenizer()
    config = self.get_hf_config()

    boi_token_id = config.boi_token_id
    eoi_token_id = config.eoi_token_id
    video_token_id = processor.video_token_id

    all_token_ids: list[int] = []
    for i, (ts, n_tokens) in enumerate(zip(timestamps, num_soft_tokens_per_frame)):
        # mm:ss timestamp — matches transformers: int-truncated,
        # zero-padded.
        minutes = int(ts // 60)
        seconds = int(ts % 60)
        ts_str = f"{minutes:02d}:{seconds:02d}"

        prefix = f" {ts_str} " if i > 0 else f"{ts_str} "
        ts_token_ids = tokenizer.encode(prefix, add_special_tokens=False)
        all_token_ids.extend(ts_token_ids)

        all_token_ids.append(boi_token_id)
        all_token_ids.extend([video_token_id] * n_tokens)
        all_token_ids.append(eoi_token_id)

    return PromptUpdateDetails.select_token_id(all_token_ids, video_token_id)

Gemma4VideoInputs

Bases: TensorSchema

Video frame inputs — same tensor format as image inputs.

Gemma4 has no separate video tower; video frames are processed through the vision tower at lower resolution (max_soft_tokens=70).

Source code in vllm/model_executor/models/gemma4_mm.py
class Gemma4VideoInputs(TensorSchema):
    """Video frame inputs — same tensor format as image inputs.

    Gemma4 has no separate video tower; video frames are processed
    through the vision tower at lower resolution (max_soft_tokens=70).
    """

    type: Literal["pixel_values_videos"] = "pixel_values_videos"
    pixel_values_videos: Annotated[
        torch.Tensor,
        TensorShape("bn", "np", "pp"),
    ]
    pixel_position_ids_videos: Annotated[
        torch.Tensor,
        TensorShape("bn", "np", 2),
    ]

_get_max_soft_tokens(merged_kwargs)

Return configured image max_soft_tokens and whether it is top-level.

Source code in vllm/model_executor/models/gemma4_mm.py
def _get_max_soft_tokens(
    merged_kwargs: Mapping[str, object],
) -> tuple[object | None, bool]:
    """Return configured image max_soft_tokens and whether it is top-level."""
    val = merged_kwargs.get("max_soft_tokens")
    if val is not None:
        return val, True

    images_kwargs = merged_kwargs.get("images_kwargs")
    if isinstance(images_kwargs, Mapping):
        return images_kwargs.get("max_soft_tokens"), False

    return None, False