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)

Gemma4ForConditionalGeneration

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

Methods:

  • get_mm_mapping –

    Get the module prefix mapping for multimodal models.

_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.

_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.

_process_image_input_local(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.

_process_video_input_local(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.

get_mm_mapping()

Get the module prefix mapping for multimodal 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.

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.

forward(inputs_embeds)

Project soft tokens from a multimodal tower into LM space.

Gemma4ProcessingInfo

Bases: BaseProcessingInfo

Methods:

_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.

_compute_num_soft_tokens(image_width, image_height, max_soft_tokens=None, do_resize=True, *, is_video_frame=False)

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

Parameters:

  • image_width

    (int) –

    Width of the image in pixels.

  • image_height

    (int) –

    Height of the image in pixels.

  • 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.

  • do_resize

    (bool, default: True ) –

    Whether the image processor resizes the image.

  • is_video_frame

    (bool, default: False ) –

    Whether to describe the budget as fixed per frame.

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).

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.

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

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:

  • image_width

    (int) –

    Width of the image in pixels.

  • image_height

    (int) –

    Height of the image in pixels.

  • processor

    (Gemma4Processor | None) –

    The Gemma4 processor, when already constructed.

  • max_soft_tokens

    (int | None, default: None ) –

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

  • do_resize

    (bool, default: True ) –

    Whether the image processor resizes the image.

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 ...

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).

_get_max_soft_tokens(merged_kwargs)

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