Skip to content

Commit b5cd8b7

Browse files
roberteg16claude
andcommitted
[Model] Gemma 4: native packed vision tower on MMEncoderAttention
Replace the transformers vision tower (padded images, SDPA with a mask) with a native one built from vLLM layers that packs all images or video frames of a batch into one sequence: cu_seqlens instead of padding, MMEncoderAttention (any --mm-encoder-attn-backend), the axial 2D RoPE from get_rope applied with ApplyRotaryEmb, and moonvit's packed patch merger for pooling. Parameter names match transformers, so checkpoints load without a mapper. Encoder CUDA graphs move to token budgets (as in Qwen3-VL): eager, capture and replay share prepare_encoder_metadata and the tower forward. Sequence slots and max_seqlen are sized from what a budget can hold and the configured max_soft_tokens; other items are marked eager_only. With TORCH_SDPA, capture falls back to eager (needs the encoder CUDA graph eager fallback for packed TORCH_SDPA). DiffusionGemma and EmbeddingGemma2 reuse the same tower; Gemma 4 Unified moves the (now host-side) positions to the device and opts out of encoder graphs. Co-Authored-By: Claude <noreply@anthropic.com> Signed-off-by: Robert Esclapez Garcia <robert.garcia@amd.com>
1 parent cc7248c commit b5cd8b7

9 files changed

Lines changed: 841 additions & 810 deletions

File tree

‎tests/models/multimodal/pooling/test_embedding_gemma2.py‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -254,7 +254,8 @@ def test_encoder_contract():
254254
"_process_video_input",
255255
"_process_audio_input",
256256
"embed_multimodal",
257-
"_encoder_chunk",
257+
"_pack_vision",
258+
"_embed_vision",
258259
]
259260

260261
for name in borrowed_methods:
@@ -308,7 +309,8 @@ def test_instance_attribute_access(vllm_runner):
308309
"_process_video_input",
309310
"_process_audio_input",
310311
"embed_multimodal",
311-
"_encoder_chunk",
312+
"_pack_vision",
313+
"_embed_vision",
312314
]
313315
attrs_accessed = set()
314316
for name in borrowed_methods:

‎tests/models/multimodal/processing/test_gemma4.py‎

Lines changed: 78 additions & 103 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
33

44
from collections.abc import Mapping
5+
from functools import partial
56
from types import SimpleNamespace
67

78
import numpy as np
@@ -15,12 +16,12 @@
1516
Gemma4ForConditionalGeneration,
1617
Gemma4ImagePixelInputs,
1718
)
19+
from vllm.model_executor.models.gemma4_vision import Gemma4VisionModel
1820
from vllm.model_executor.models.interfaces import supports_multimodal
1921
from vllm.multimodal import MULTIMODAL_REGISTRY
2022
from vllm.multimodal.cache import MultiModalProcessorOnlyCache
2123
from vllm.multimodal.inputs import MultiModalFieldConfig
22-
from vllm.utils.mem_constants import GiB_bytes
23-
from vllm.v1.worker.encoder_cudagraph_defs import ENCODER_CUDAGRAPH_AXIS_KEYS_KWARG
24+
from vllm.v1.attention.backends.registry import AttentionBackendEnum
2425

2526
from ....conftest import ImageTestAssets
2627
from ...utils import build_model_context
@@ -339,124 +340,98 @@ def test_limit_mm_per_prompt(
339340
)
340341

341342

342-
# Regression guard for PR #43169 follow-up: the batched Gemma4 vision encoder
343-
# admitted ``chunk ~= 53`` on a 22 GiB L4 with a 26B AWQ model loaded,
344-
# allocating 2.43 GiB int64 inside
345-
# ``F.one_hot(num_classes=position_embedding_size)`` and OOMing because only
346-
# 2.41 GiB was actually free. The fix sizes ``chunk`` from currently-free GPU
347-
# memory and counts the ``F.one_hot`` transient as the dominant cost.
348-
349-
_encoder_chunk = Gemma4ForConditionalGeneration._encoder_chunk
350-
351-
# Gemma4 vision config default (HF: configuration_gemma4.py).
352-
_POSITION_EMBEDDING_SIZE = 10240
353-
# Video frame: max_soft_tokens=70, pooling_kernel_size=2 -> 70 * 4 patches.
354-
_VIDEO_PATCHES_PER_FRAME = 280
355-
356-
357-
def test_encoder_chunk_tight_budget_fits_in_free():
358-
free = 3 * GiB_bytes # L4 22 GiB after 26B AWQ load.
359-
total = 22 * GiB_bytes
360-
chunk = _encoder_chunk(
361-
_VIDEO_PATCHES_PER_FRAME, free, total, _POSITION_EMBEDDING_SIZE
343+
def _gemma4_for_encoder_cudagraph(
344+
attn_backend: AttentionBackendEnum = AttentionBackendEnum.TRITON_ATTN,
345+
) -> Gemma4ForConditionalGeneration:
346+
model = object.__new__(Gemma4ForConditionalGeneration)
347+
vision_config = SimpleNamespace(
348+
patch_size=16,
349+
pooling_kernel_size=3,
350+
default_output_length=280,
351+
position_embedding_size=10240,
362352
)
363-
one_hot_bytes = chunk * _VIDEO_PATCHES_PER_FRAME * 2 * _POSITION_EMBEDDING_SIZE * 8
364-
assert one_hot_bytes <= free // 2
365-
366-
367-
def test_encoder_chunk_roomy_gpu_keeps_batching():
368-
chunk = _encoder_chunk(
369-
_VIDEO_PATCHES_PER_FRAME,
370-
60 * GiB_bytes,
371-
80 * GiB_bytes,
372-
_POSITION_EMBEDDING_SIZE,
353+
vision_tower = SimpleNamespace(
354+
config=vision_config,
355+
attn_backend=attn_backend,
356+
qkv_stride=64,
357+
device=torch.device("cpu"),
373358
)
374-
assert chunk > 8
375-
376-
377-
def test_encoder_chunk_zero_patches_is_safe():
378-
assert (
379-
_encoder_chunk(0, 60 * GiB_bytes, 80 * GiB_bytes, _POSITION_EMBEDDING_SIZE) == 1
380-
)
381-
382-
383-
def test_encoder_chunk_zero_position_embedding_size_is_safe():
384-
# Degenerate config: must not raise ZeroDivisionError.
385-
assert (
386-
_encoder_chunk(_VIDEO_PATCHES_PER_FRAME, 60 * GiB_bytes, 80 * GiB_bytes, 0) == 1
359+
vision_tower.prepare_encoder_metadata = partial(
360+
Gemma4VisionModel.prepare_encoder_metadata, vision_tower
387361
)
388-
389-
390-
def test_encoder_chunk_no_free_memory_falls_back_to_one():
391-
assert (
392-
_encoder_chunk(
393-
_VIDEO_PATCHES_PER_FRAME, 0, 22 * GiB_bytes, _POSITION_EMBEDDING_SIZE
394-
)
395-
== 1
362+
model.vision_tower = vision_tower
363+
model.config = SimpleNamespace(
364+
vision_config=vision_config, text_config=SimpleNamespace(hidden_size=8)
396365
)
366+
return model
397367

398368

399-
def _gemma4_for_encoder_cudagraph() -> Gemma4ForConditionalGeneration:
400-
model = object.__new__(Gemma4ForConditionalGeneration)
401-
vision_config = SimpleNamespace(
402-
patch_size=16, pooling_kernel_size=3, default_output_length=280
403-
)
404-
model.vision_tower = SimpleNamespace(config=vision_config)
405-
model.config = SimpleNamespace(vision_config=vision_config)
406-
return model
369+
def _padded_image(
370+
columns: int, rows: int, max_patches: int = 2520
371+
) -> tuple[torch.Tensor, torch.Tensor]:
372+
"""Patches laid out like the processor's: row-major, padded at the end."""
373+
grid = torch.meshgrid(torch.arange(columns), torch.arange(rows), indexing="xy")
374+
positions = torch.full((max_patches, 2), -1, dtype=torch.long)
375+
positions[: columns * rows] = torch.stack(grid, -1).reshape(-1, 2)
376+
return torch.zeros(max_patches, 768), positions
407377

408378

409-
@pytest.mark.parametrize(
410-
("token_budget", "row_tokens"), [(4096, 70), (4096, 280), (70, 280)]
411-
)
412-
def test_encoder_cudagraph_capture_rows_fit_token_budget(
413-
token_budget: int, row_tokens: int
414-
):
415-
# Regression for #61045: rows were max_frames_per_batch (58 * 32) at
416-
# 280 tokens each, so the 4096-token buffer alone was 6.69 GiB.
379+
@pytest.mark.parametrize("token_budget", [70, 4480])
380+
def test_encoder_cudagraph_capture_buffers_fit_token_budget(token_budget: int):
381+
# Regression for #61045: buffers sized by max_frames_per_batch rows
382+
# instead of the token budget took 6.69 GiB at a 4096-token budget.
417383
model = _gemma4_for_encoder_cudagraph()
418-
inputs = model.prepare_encoder_cudagraph_capture_inputs(
384+
values = model.prepare_encoder_cudagraph_capture_inputs(
419385
token_budget=token_budget,
420-
max_batch_size=58,
421-
max_frames_per_batch=58 * 32,
422-
device="meta",
386+
max_batch_size=1,
387+
max_frames_per_batch=32,
388+
device=torch.device("cpu"),
423389
dtype=torch.bfloat16,
424-
axis_keys=(row_tokens,),
425-
)
390+
).values
426391

427-
num_rows, row_patches, _ = inputs.values["pixel_values"].shape
428-
assert row_patches == row_tokens * 9
429-
assert num_rows == max(1, token_budget // row_tokens)
392+
assert values["pixel_values"].shape == (token_budget * 9, 768)
393+
assert values["pixel_position_ids"].shape == (token_budget * 9, 2)
394+
assert values["pool_gather_idx"].shape == (token_budget * 9,)
395+
# A slot per image or frame that fits, each of at least 35 tokens: the
396+
# manager does not bound frames, e.g. a 64-frame video in 4480 tokens.
397+
assert values["cu_seqlens"].shape == (max(1, token_budget // 35) + 1,)
398+
# The largest image of the configured max_soft_tokens (280).
399+
assert values["max_seqlen"].item() == min(token_budget, 280) * 9
430400

431401

432-
def test_encoder_cudagraph_mixed_width_images_pack_by_padded_width():
402+
def test_encoder_cudagraph_replay_packs_images_without_padding():
433403
model = _gemma4_for_encoder_cudagraph()
404+
images = [
405+
_padded_image(9, 6),
406+
_padded_image(60, 42),
407+
_padded_image(3, 3),
408+
_padded_image(90, 42, max_patches=3780),
409+
]
434410
mm_kwargs = {
435-
"pixel_values": [torch.zeros(2520, 768), torch.zeros(630, 768)],
436-
"pixel_position_ids": [
437-
torch.zeros(2520, 2, dtype=torch.long),
438-
torch.zeros(630, 2, dtype=torch.long),
439-
],
411+
"pixel_values": [pixel_values for pixel_values, _ in images],
412+
"pixel_position_ids": [positions for _, positions in images],
440413
}
441414

442415
specs = model.get_encoder_cudagraph_item_specs(mm_kwargs)
443-
assert [spec.output_tokens for spec in specs] == [280, 70]
444-
assert [spec.get_path_output_tokens("default") for spec in specs] == [280, 280]
445-
446-
selected = model.select_encoder_cudagraph_items(mm_kwargs, [1])
447-
assert selected[ENCODER_CUDAGRAPH_AXIS_KEYS_KWARG] == (70,)
448-
selected = model.select_encoder_cudagraph_items(mm_kwargs, [0, 1])
449-
assert selected[ENCODER_CUDAGRAPH_AXIS_KEYS_KWARG] == (280,)
450-
451-
452-
@pytest.mark.parametrize(
453-
"mm_processor_kwargs",
454-
[{"max_soft_tokens": 560}, {"images_kwargs": {"max_soft_tokens": 560}}],
455-
)
456-
def test_encoder_cudagraph_config_respects_max_soft_tokens(mm_processor_kwargs):
416+
assert [spec.output_tokens for spec in specs] == [6, 280, 1, 420]
417+
# Below the 35 tokens the graphs' sequence slots assume, or above their
418+
# max_seqlen (configured 280 tokens): eager.
419+
assert [spec.eager_only for spec in specs] == [True, False, True, True]
420+
421+
selected = model.select_encoder_cudagraph_items(mm_kwargs, [0, 2])
422+
values = model.prepare_encoder_cudagraph_replay_buffers(
423+
selected, max_batch_size=4, max_frames_per_batch=4
424+
).values
425+
assert values["pixel_values"].shape == (54 + 9, 768)
426+
assert values["cu_seqlens"].tolist() == [0, 54, 63]
427+
# Each 3x3 block of the 9x6 image, then the 3x3 image.
428+
assert values["pool_gather_idx"][:9].tolist() == [0, 1, 2, 9, 10, 11, 18, 19, 20]
429+
assert values["pool_gather_idx"][9:18].tolist() == [3, 4, 5, 12, 13, 14, 21, 22, 23]
430+
assert values["pool_gather_idx"][54:].tolist() == list(range(54, 63))
431+
432+
433+
def test_encoder_metadata_rejects_grids_not_divisible_by_pooling():
457434
model = _gemma4_for_encoder_cudagraph()
458-
model.config.text_config = SimpleNamespace(hidden_size=8)
459-
model.multimodal_config = SimpleNamespace(mm_processor_kwargs=mm_processor_kwargs)
460-
461-
config = model.get_encoder_cudagraph_config()
462-
assert config.capture_axes == ((70, 140, 280, 560),)
435+
_, positions = _padded_image(4, 3)
436+
with pytest.raises(ValueError, match="multiples of 3"):
437+
model.vision_tower.prepare_encoder_metadata([positions[:12].numpy()])

‎tests/models/multimodal/processing/test_gemma4_unified.py‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
33

44
from collections.abc import Mapping
5+
from types import SimpleNamespace
56

67
import pytest
78
import torch
@@ -500,3 +501,10 @@ def test_cuda_execution_with_gpu_sync_allowed():
500501
assert len(out) == 2
501502
assert out[0].device.type == "cuda"
502503
assert out[0].dtype == torch.bfloat16
504+
505+
506+
def test_encoder_cudagraph_config_has_no_modalities():
507+
"""No vision tower to capture: the embedder runs eager."""
508+
model = object.__new__(Gemma4UnifiedForConditionalGeneration)
509+
model.config = SimpleNamespace(text_config=SimpleNamespace(hidden_size=8))
510+
assert model.get_encoder_cudagraph_config().modalities == []
Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
# SPDX-License-Identifier: Apache-2.0
2+
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3+
"""The packed Gemma 4 vision tower against transformers' padded one."""
4+
5+
from unittest.mock import patch
6+
7+
import pytest
8+
import torch
9+
from transformers import AutoModel
10+
from transformers.models.gemma4 import Gemma4VisionConfig
11+
12+
from vllm.model_executor.layers.attention import mm_encoder_attention
13+
from vllm.model_executor.models import gemma4_vision
14+
from vllm.model_executor.models.gemma4_vision import Gemma4VisionModel
15+
from vllm.platforms import current_platform
16+
from vllm.v1.attention.backends.registry import AttentionBackendEnum
17+
18+
# fp32 for a tight comparison: backends that support it.
19+
BACKENDS = [AttentionBackendEnum.TORCH_SDPA, AttentionBackendEnum.TRITON_ATTN]
20+
21+
# (columns, rows) of patches; both multiples of the pooling kernel. Equal
22+
# grids, adjacent or not, share one SDPA call.
23+
GRIDS = [(9, 6), (9, 6), (3, 3), (12, 9), (9, 6), (6, 15)]
24+
MAX_PATCHES = 15 * 12
25+
26+
27+
def _config(use_clipped_linears: bool) -> Gemma4VisionConfig:
28+
return Gemma4VisionConfig(
29+
hidden_size=64,
30+
intermediate_size=128,
31+
num_hidden_layers=2,
32+
num_attention_heads=4,
33+
num_key_value_heads=4,
34+
head_dim=16,
35+
position_embedding_size=32,
36+
use_clipped_linears=use_clipped_linears,
37+
standardize=True,
38+
)
39+
40+
41+
def _hf_tower(config: Gemma4VisionConfig) -> torch.nn.Module:
42+
config._attn_implementation = "sdpa"
43+
tower = AutoModel.from_config(config).eval()
44+
with torch.no_grad():
45+
for name, tensor in tower.state_dict().items():
46+
if name.endswith(("input_min", "output_min")):
47+
tensor.fill_(-2.0)
48+
elif name.endswith(("input_max", "output_max")):
49+
tensor.fill_(2.0)
50+
elif (
51+
name.endswith("std_scale")
52+
or name.endswith("norm.weight")
53+
or "layernorm" in name
54+
):
55+
tensor.uniform_(0.5, 1.5)
56+
else:
57+
tensor.normal_(std=0.1)
58+
return tower
59+
60+
61+
def _image(columns: int, rows: int) -> tuple[torch.Tensor, torch.Tensor]:
62+
"""Patches laid out like the processor's: row-major, padded at the end."""
63+
grid = torch.meshgrid(torch.arange(columns), torch.arange(rows), indexing="xy")
64+
positions = torch.full((MAX_PATCHES, 2), -1, dtype=torch.long)
65+
positions[: columns * rows] = torch.stack(grid, -1).reshape(-1, 2)
66+
pixel_values = torch.zeros(MAX_PATCHES, 3 * 16 * 16)
67+
pixel_values[: columns * rows] = torch.rand(columns * rows, 3 * 16 * 16)
68+
return pixel_values, positions
69+
70+
71+
@pytest.mark.skipif(not current_platform.is_cuda_alike(), reason="needs a GPU")
72+
@pytest.mark.parametrize("backend", BACKENDS)
73+
@pytest.mark.parametrize("use_clipped_linears", [False, True])
74+
@torch.inference_mode()
75+
def test_packed_tower_matches_transformers(
76+
default_vllm_config, dist_init, backend, use_clipped_linears
77+
):
78+
torch.manual_seed(0)
79+
config = _config(use_clipped_linears)
80+
hf_tower = _hf_tower(config).cuda()
81+
images = [_image(*grid) for grid in GRIDS]
82+
expected = [
83+
hf_tower(pv[None].cuda(), pos[None].cuda()).last_hidden_state
84+
for pv, pos in images
85+
]
86+
87+
with (
88+
patch.object(gemma4_vision, "get_vit_attn_backend", lambda **_: backend),
89+
patch.object(mm_encoder_attention, "get_vit_attn_backend", lambda **_: backend),
90+
torch.device("cuda"),
91+
):
92+
tower = Gemma4VisionModel(config)
93+
tower.load_state_dict(hf_tower.state_dict())
94+
95+
num_patches = [columns * rows for columns, rows in GRIDS]
96+
metadata = tower.prepare_encoder_metadata(
97+
[pos[:n].numpy() for (_, pos), n in zip(images, num_patches)]
98+
)
99+
pixel_values = torch.cat([pv[:n] for (pv, _), n in zip(images, num_patches)])
100+
actual = tower(pixel_values.cuda(), metadata).split([n // 9 for n in num_patches])
101+
102+
for got, want in zip(actual, expected):
103+
torch.testing.assert_close(got, want, rtol=1e-3, atol=1e-3)

0 commit comments

Comments
 (0)