Skip to content

[Model] Gemma 4: native packed vision tower on MMEncoderAttention - #1415

Draft
roberteg16 wants to merge 5 commits into
rogarcia.upstream-main-b2094acfrom
rogarcia.gemma4-native-vision
Draft

roberteg16 wants to merge 5 commits into
rogarcia.upstream-main-b2094acfrom
rogarcia.gemma4-native-vision

Conversation

@roberteg16

@roberteg16 roberteg16 commented Oct 29, 2026 •

Copy link
Copy Markdown

Overview

Gemma 4's vision tower becomes a native vLLM tower that packs images and video frames with cu_seqlens instead of padding them, so it runs on any --mm-encoder-attn-backend (vllm-project#43178, review of vllm-project#43440).

Not a duplicate: vllm-project#60577 keeps SDPA with a mask and is superseded; vllm-project#60478 patches the transformers tower this PR removes. Tower LoRA (vllm-project#42662), the data-parallel encoder (vllm-project#60314) and on-device input normalization (vllm-project#65577) keep working on the new tower.

Claims

  • Native tower from vLLM layers (MMEncoderAttention, get_rope + ApplyRotaryEmb, moonvit's packed merger); same checkpoints, no mapper. Reused by DiffusionGemma and EmbeddingGemma2.
  • MMStar unchanged (within ~2 points, in both directions); TTFT up to 7% lower with the default backend and 6-17% lower with TRITON_ATTN, which picks up gfx1151's encoder attention work ([ROCm][Perf] Encoder prefill attention on gfx1151: split-D head dims, alignment hint, launch config vllm-project/vllm#56450).
  • Encoder CUDA graphs follow token budgets like Qwen3-VL.
  • Packed TORCH_SDPA under cudagraph_mm_encoder now fails at startup with a clear error (it used to fail with a device-copy error during capture).

Validation

gfx1151, PR on 1b2505c vs that commit ("main"), torch 2.14 (ROCm nightly 10.3.0a20261106); unit tests, test_common and LoRA re-run after rebasing on b2094ac.

Model MMStar: same answer as main MMStar main / PR TTFT main / PR, SDPA (ms) TTFT main / PR, TRITON_ATTN (ms)
gemma-4-E2B-it 287 / 300 39.0 / 36.7 % 151.1 / 150.2 150.7 / 137.1
gemma-4-E4B-it 291 / 300 55.7 / 54.7 % 203.9 / 199.5 201.1 / 187.7
gemma-4-26B-A4B-it AWQ 284 / 300 59.3 / 59.0 % 502.4 / 469.2 510.5 / 423.2
gemma-4-31B-it AWQ 298 / 300 63.0 / 63.3 % 1189.9 / 1160.7 1188.2 / 1115.2

MMStar: first 300 questions, greedy, 64 tokens. TTFT: one 336x336 image per request, median of 15, stdev ≤ 13.4 ms (1024x800 gives the same gains). Scripts below.

pytest tests/models/multimodal/processing/test_gemma4.py \
  tests/models/multimodal/processing/test_gemma4_unified.py \
  tests/models/multimodal/test_gemma4_vision.py \
  tests/models/multimodal/pooling/test_embedding_gemma2.py \
  tests/kernels/attention/test_mha_attn.py \
  tests/v1/cudagraph/test_encoder_cudagraph.py          # 184 passed (*)
pytest tests/models/multimodal/generation/test_common.py -k gemma4   # 2 passed
pytest tests/lora/test_gemma4_tp.py::test_gemma4_lora                # passed
pytest tests/models/multimodal/generation/test_vit_cudagraph.py \
  -k "gemma4 or qwen2_5_vl or qwen3_vl"   # 6 passed with TRITON_ATTN (**)

(*) test_mha_attn_platform[hip] deselected: needs flash_attn, fails the same on main.
(**) gfx1151 defaults to TORCH_SDPA, which now stops with the new error; on main Qwen2.5-VL fails there with "Cannot copy between CPU and CUDA tensors during CUDA graph capture".

Also checked: encoder graph replay matches eager (images, videos, oversized items); VLLM_GPU_SYNC_CHECK=error passes; 31B AWQ with max_model_len=8192 keeps main's KV cache (7904 vs 7902 blocks); --dtype float16 on 26B AWQ works.
On H100, hnt2601 (vllm-project#65591) ran 31B BF16 with FLASH_ATTN, FLASHINFER and TRITON_ATTN, eager and with encoder graphs, matching main within bf16 noise, and DP (mm_encoder_tp_mode="data", TP=2) matching "weights". Online FP8 (vllm-project#64168) cannot run on gfx1151 (no kernel); test_patch_embedder_keeps_model_dtype_with_fp8_input_proj checks that pixels reach an FP8-stored input_proj in the model dtype, and fails with the pre-vllm-project#64168 cast.

MMStar and TTFT scripts
# mmstar.py MODEL OUT.json: first 300 MMStar questions, greedy, 64 tokens.
# Needs mmstar.parquet from https://huggingface.co/datasets/Lin-Chen/MMStar
import io, json, os, re, sys
os.environ["VLLM_ENABLE_V1_MULTIPROCESSING"] = "0"
import pyarrow.parquet as pq
from PIL import Image
from vllm import LLM, SamplingParams

def letter(text):
    text = text.strip()
    m = (re.match(r"\(?([A-D])(?:$|[\s.:)])", text)
         or re.search(r"(?:answer|option)(?: is)?[:\s*]*\(?([A-D])\b", text, re.I)
         or re.search(r"\*\*\(?([A-D])[:.)*]", text))
    return m.group(1) if m else None

model, out = sys.argv[1:3]
rows = pq.read_table("mmstar.parquet").to_pylist()[:300]
llm = LLM(model=model, max_model_len=4096, max_num_seqs=8,
          limit_mm_per_prompt={"image": 1}, gpu_memory_utilization=0.85, seed=0)
msgs = [[{"role": "user", "content": [
    {"type": "image_pil", "image_pil": Image.open(io.BytesIO(r["image"])).convert("RGB")},
    {"type": "text", "text": r["question"] + "\nAnswer with the option's letter."}]}]
    for r in rows]
outs = llm.chat(msgs, SamplingParams(temperature=0, max_tokens=64),
                chat_template_kwargs={"enable_thinking": False})
answers = [letter(o.outputs[0].text) for o in outs]
print("accuracy", sum(a == r["answer"] for a, r in zip(answers, rows)) / len(rows))
json.dump(answers, open(out, "w"))  # compare two runs answer by answer
# ttft.py MODEL [BACKEND]: one-image requests, max_tokens=1, new image each time.
import base64, io, os, statistics, sys, time
os.environ["VLLM_ENABLE_V1_MULTIPROCESSING"] = "0"
import numpy as np
from PIL import Image
from vllm import LLM, SamplingParams

kw = dict(model=sys.argv[1], max_model_len=4096, max_num_seqs=1,
          limit_mm_per_prompt={"image": 1, "video": 0},
          gpu_memory_utilization=0.85, seed=0)
if len(sys.argv) > 2:
    kw["mm_encoder_attn_backend"] = sys.argv[2]
llm = LLM(**kw)
rng = np.random.default_rng(0)
for w, h in [(336, 336), (1024, 800)]:
    times = []
    for i in range(3 + 15):
        buf = io.BytesIO()
        Image.fromarray(rng.integers(0, 255, (h, w, 3), dtype=np.uint8)).save(buf, "PNG")
        url = "data:image/png;base64," + base64.b64encode(buf.getvalue()).decode()
        msg = [{"role": "user", "content": [
            {"type": "image_url", "image_url": {"url": url}},
            {"type": "text", "text": "Describe the image."}]}]
        t0 = time.perf_counter()
        llm.chat(msg, SamplingParams(temperature=0, max_tokens=1), use_tqdm=False)
        if i >= 3:
            times.append((time.perf_counter() - t0) * 1e3)
    print(f"{w}x{h}: median {statistics.median(times):.1f} ms, "
          f"stdev {statistics.pstdev(times):.1f} ms")

Details

Four commits:

  1. [NFC] Move the cu_seqlens graph-buffer padding shared by Qwen2.5-VL and Qwen3-VL to MMEncoderAttention.cu_seqlens_buffer_padding(backend).
  2. Encoder CUDA graphs (+18 lines): EncoderItemSpec.eager_only and the clear TORCH_SDPA error.
  3. Gemma 4: new gemma4_vision.py (440 lines) while gemma4_mm.py drops 689. Removes the resolution buckets, _encoder_chunk, the tower LoRA padding and the row-width graph axis. Raw uint8 pixels are normalized on the device in _embed_vision, shared by eager and graph replay; the DP dispatch wraps the packed _process_*_input_local. Graphs size their sequence slots (budget // 35) and max_seqlen (configured max_soft_tokens) to what they can hold; larger items run eager.
  4. Gemma 4 (hnt2601): cap each eager tower call at 4 x 1120 soft tokens, so the memory profile does not grow with the batch (on H100, 31B with max_model_len=8192 failed to start without it). Tower LoRA keeps one call.

Trade-offs:

  • Behavior change: Gemma 4 with TORCH_SDPA (RDNA default) and cudagraph_mm_encoder (off by default) now needs another backend, e.g. TRITON_ATTN; documented in docs/design/cuda_graphs_multimodal.md.
  • Same as the old tower: replicated linears (DP mode splits items across ranks), and separate q/k/v and gate/up projections, because each clipped linear has its own bounds.
  • Numerics: GELUTanh is used directly because get_act_fn swaps in exact GELU on ROCm. vLLM's RMSNorm rounds differently from transformers', which MMStar covers.
  • FlashInfer: a new separate_qkv flag on maybe_recompute_cu_seqlens; GQA is rejected.

AI assistance (Claude Code) was used; the submitter reviewed every line and ran the tests above.

🤖 Generated with Claude Code


Pull Request Checklist
  • I used vLLM's /pr-checklist skill. (Mandatory for agents, optional for humans).

  • AI assistance was used during the creation of this PR.

  • Design Fit: Minimizes impact on core components, reuses existing functionality, and justifies added complexity.

  • Testing and Validation: Validates the change and ensures any added tests are meaningful and reliable, with CI coverage or documented CI resource constraints and validation performed outside CI.

  • Code Quality and Style: Keeps code and comments clear and concise, and updates relevant documentation and examples.

  • Pull Request Contents: Includes a brief summary and relevant links, supports claims with evidence, explains root causes and implementation trade-offs, and follows the contributing guide.

@roberteg16
roberteg16 force-pushed the rogarcia.gemma4-native-vision branch 7 times, most recently from d94b1ad to b5cd8b7 Compare October 30, 2026 09:08
@roberteg16
roberteg16 changed the base branch from rogarcia.upstream-main-3c39dda to rogarcia.mm-encoder-graph-infra October 30, 2026 09:29
@roberteg16
roberteg16 force-pushed the rogarcia.gemma4-native-vision branch from b5cd8b7 to 33db17f Compare October 30, 2026 11:37
@roberteg16
roberteg16 force-pushed the rogarcia.mm-encoder-graph-infra branch 2 times, most recently from 3296c7e to 84ee5f6 Compare November 1, 2026 10:02
@roberteg16
roberteg16 force-pushed the rogarcia.gemma4-native-vision branch from 33db17f to b37ab27 Compare November 1, 2026 10:02
@roberteg16
roberteg16 force-pushed the rogarcia.mm-encoder-graph-infra branch from 84ee5f6 to 291a2fd Compare November 1, 2026 10:02
@roberteg16
roberteg16 force-pushed the rogarcia.gemma4-native-vision branch from b37ab27 to 768f58c Compare November 1, 2026 10:02
@roberteg16
roberteg16 force-pushed the rogarcia.mm-encoder-graph-infra branch from 291a2fd to 4e21958 Compare November 2, 2026 12:58
@roberteg16
roberteg16 force-pushed the rogarcia.gemma4-native-vision branch 2 times, most recently from 0f1b4e7 to 69150d7 Compare November 2, 2026 16:57
@roberteg16
roberteg16 changed the base branch from rogarcia.mm-encoder-graph-infra to rogarcia.upstream-main-3c39dda November 2, 2026 16:57
@roberteg16
roberteg16 force-pushed the rogarcia.gemma4-native-vision branch from 69150d7 to 7f3503e Compare November 3, 2026 17:07
@roberteg16
roberteg16 changed the base branch from rogarcia.upstream-main-3c39dda to rogarcia.upstream-main-c1d8fad November 3, 2026 17:08
@roberteg16
roberteg16 force-pushed the rogarcia.gemma4-native-vision branch from 7f3503e to a65ccd1 Compare November 3, 2026 21:51
@roberteg16
roberteg16 changed the base branch from rogarcia.upstream-main-c1d8fad to rogarcia.upstream-main-81a2879 November 3, 2026 21:51
@roberteg16
roberteg16 force-pushed the rogarcia.gemma4-native-vision branch from a65ccd1 to 5e8b91d Compare November 6, 2026 13:46
@roberteg16
roberteg16 changed the base branch from rogarcia.upstream-main-81a2879 to rogarcia.upstream-main-1b2505c November 6, 2026 13:46
roberteg16 and others added 4 commits November 6, 2026 06:01
…oderAttention

The CUDA graph padding for cu_seqlens that Qwen2.5-VL and Qwen3-VL share
(cumulative, or FlashInfer's two-section layout) depends on the layout
maybe_recompute_cu_seqlens produces, so it moves from qwen2_5_vl.py next to
it as MMEncoderAttention.cu_seqlens_buffer_padding(backend), and models no
longer branch on the attention backend to pick it. No functional change.

Co-Authored-By: Claude <noreply@anthropic.com>
Signed-off-by: Robert Esclapez Garcia <robert.garcia@amd.com>
- EncoderItemSpec.eager_only lets a model send items its captured graphs
  cannot hold (e.g. longer than the captured max_seqlen) to the eager
  path; the manager packs the other items as before.
- TORCH_SDPA splits packed sequences (cu_seqlens) on the host, which
  cannot run under CUDA graph capture: Qwen2.5-VL or Qwen3-VL with
  TORCH_SDPA (the default ViT backend on RDNA without the flash-attn
  Triton backend) and cudagraph_mm_encoder failed at startup with a
  device-copy error. The wrapper now raises an error that names the
  backend and the way out.

Co-Authored-By: Claude <noreply@anthropic.com>
Signed-off-by: Robert Esclapez Garcia <robert.garcia@amd.com>
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.
TORCH_SDPA cannot capture packed images, so cudagraph_mm_encoder with it
now stops at startup with an error naming another backend.

With mm_device_do_normalize, pixels reach the tower as raw uint8 and are
normalized per channel in _embed_vision, shared by the eager and CUDA
graph paths; the CUDA graph buffers keep uint8. The data-parallel encoder
dispatch wraps the packed _process_{image,video}_input_local.

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: Hoang Nguyen Tien <hoang.nguyentien.2601@gmail.com>
Co-Authored-By: Claude <noreply@anthropic.com>
Signed-off-by: Robert Esclapez Garcia <robert.garcia@amd.com>
Signed-off-by: Hoang Nguyen Tien <hoang.nguyentien.2601@gmail.com>
Packing every image or frame of an encoder batch into one tower call raised
the encoder's peak activations: on gemma-4-31B-it (H100, max_model_len 8192,
gpu_memory_utilization 0.9) the profile run's peak activation memory grew
from 2.92 GiB to 3.96 GiB and the KV cache shrank 11.7%. Eager calls now pack
at most 4 x 1120 soft tokens. With tower LoRA the batch stays one call, since
the adapter mapping covers the whole encoder batch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Hoang Nguyen Tien <hoang.nguyentien.2601@gmail.com>
@roberteg16
roberteg16 force-pushed the rogarcia.gemma4-native-vision branch from 5e8b91d to 3bb1277 Compare November 6, 2026 14:15
@roberteg16
roberteg16 changed the base branch from rogarcia.upstream-main-1b2505c to rogarcia.upstream-main-b2094ac November 6, 2026 14:16
Restore the empty-input guards the local image and video paths had: with
no images, or a video with no frames, _encode_vision returns no soft
tokens instead of packing an empty batch, which failed in
np.concatenate. The data-parallel paths already skipped empty inputs; the
local ones are also reached directly from DiffusionGemma and
EmbeddingGemma2.

Co-Authored-By: Claude <noreply@anthropic.com>
Signed-off-by: Robert Esclapez Garcia <robert.garcia@amd.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants