Skip to content

feat: add Gemma 4 Unified (gemma4_unified) multimodal architecture support #151

Closed

Description

@inureyes

Summary

Add runtime support for the Gemma 4 Unified architecture to the mlxcel loaders and inference path:

  • HF identity: model_type: "gemma4_unified", architectures: ["Gemma4UnifiedForConditionalGeneration"]
  • Sub-configs: text_config (gemma4_unified_text), vision_config (gemma4_unified_vision), audio_config (gemma4_unified_audio)

Gemma 4 Unified is a single text + vision + audio model. It differs structurally from the model already wired up under model_type: "gemma4" / ModelType::Gemma4VLM. The existing Gemma 4 VLM path uses a ViT vision tower plus a Conformer audio encoder. The Unified variant is encoder-free: images and audio are turned into soft tokens by lightweight patch / feature embedders and reasoned over entirely by the shared Gemma 4 language backbone, using blockwise bidirectional attention over image/video token spans during prefill.

Because the language backbone is the same Gemma 4 transformer we already run, most of this work is new front-end plumbing (config, registration, two small embedders, a processor, and one mask change) rather than a new decoder.

Reference model for development & testing

A complete checkpoint is already present in the local model store and should be used for structure verification and end-to-end testing:

mlx-community/gemma-4-12b-it-4bit

Top-level config highlights (read the real values from the checkpoint's config.json during implementation):

{
  "architectures": ["Gemma4UnifiedForConditionalGeneration"],
  "model_type": "gemma4_unified",
  "image_token_id": 258880,
  "audio_token_id": 258881,
  "boi_token_id":   255999,   // begin-of-image
  "eoi_token_id":   258882,   // end-of-image
  "boa_token_id":   256000,   // begin-of-audio
  "eoa_token_index":258883,   // end-of-audio
  "audio_config": { "model_type": "gemma4_unified_audio", "audio_embed_dim": 640,
                    "hidden_size": 640, "output_proj_dims": 640, "rms_norm_eps": 1e-6 },
  "quantization": { "group_size": 64, "bits": 4, "mode": "affine",
                    "language_model.model.layers.N.mlp.{gate,up,down}_proj": { "bits": 8 } /* mixed precision */ }
}

The checkpoint uses mixed-precision quantization (4-bit default, several MLP projections at 8-bit). Per-tensor quant overrides from the quantization map must be honored on load.


Architecture overview

1. Identity & config (gemma4_unified)

New config schema (defaults shown; the loader must read actual values from the checkpoint):

  • Top-level ModelConfig: model_type, vocab_size: 262144, token ids (image_token_id 258880, audio_token_id 258881, video_token_id 258884, boi 255999, eoi 258882, boa 256000, eoa 258883), vision_soft_tokens_per_image: 280, vision_soft_tokens_per_video_frame: 70, tie_word_embeddings: true. Note eoa_token_id may be absent and should fall back to eoa_token_index.
  • text_config (gemma4_unified_text): hidden_size 3840, num_hidden_layers 48, intermediate_size 15360, num_attention_heads 16, head_dim 256, global_head_dim 512, num_key_value_heads 8, num_global_key_value_heads 1, sliding_window 1024, sliding_window_pattern 6, attention_k_eq_v true, use_double_wide_mlp false, use_bidirectional_attention "vision" (new field), vocab_size 262144, vocab_size_per_layer_input 262144. RoPE: full_attention → {partial_rotary_factor 0.25, rope_theta 1e6, rope_type "proportional"}, sliding_attention → {rope_theta 1e4, rope_type "default"}. layer_types defaults to a repeated [sliding ×(pattern-1), full ×1] pattern.
  • vision_config (gemma4_unified_vision): patch_size 16, pooling_kernel_size 3, model_patch_size 48, mm_embed_dim 3840, mm_posemb_size 1120, num_soft_tokens 280, output_proj_dims 3840, rms_norm_eps 1e-6. (hidden_size == output_proj_dims.)
  • audio_config (gemma4_unified_audio): audio_samples_per_token 640, audio_embed_dim 640, hidden_size 640, output_proj_dims 640, rms_norm_eps 1e-6. No Conformer fields — this is not an encoder.

The text backbone config already has equivalents in src/models/gemma4.rs::TextConfig (num_kv_shared_layers, hidden_size_per_layer_input, attention_k_eq_v, use_double_wide_mlp, enable_moe_block, switch_glu MLP handling). The only net-new text-config field is use_bidirectional_attention.

2. Vision path — encoder-free patch embedder (net-new)

There is no ViT. src/vision/encoders/gemma4.rs::Gemma4VisionModel is not reused. The Unified vision module is a small patch projector:

  1. Patchify the (resized, normalized) image into non-overlapping model_patch_size × model_patch_size × 3 patches → flat vectors of length model_patch_size² · 3 (e.g. 48·48·3 = 6912), plus a 2-D (x, y) position per patch. Padding patches use position -1.
  2. patch_ln1 (LayerNorm over patch_dim) → patch_dense (Linear patch_dim → mm_embed_dim) → patch_ln2 (LayerNorm over mm_embed_dim).
  3. Add learned 2-D positional embeddings: pos_embedding of shape (mm_posemb_size, 2, mm_embed_dim), indexed by the (x, y) ids (x uses slot 0, y uses slot 1); -1 positions contribute zero.
  4. pos_norm (LayerNorm over mm_embed_dim) → per-patch features at output_proj_dims.
  5. Project to the text hidden size with the shared multimodal embedder (see below).

num_soft_tokens (280) patches per image become 280 soft tokens occupying image_token_id placeholder positions. Videos reuse the same path per frame (video_token_id, 70 soft tokens/frame).

3. Audio path — projection-only (net-new, lightweight)

There is no Conformer encoder (contrast with the existing src/audio Conformer used by gemma4). The waveform feature extractor simply chunks the raw waveform into audio_samples_per_token (640)-sample frames → (num_frames, 640) features + a validity mask. These are projected to the text hidden size by the shared multimodal embedder and scattered into audio_token_id placeholder positions.

4. Shared multimodal embedder (reuse)

Both vision and audio projections use the existing src/vision/gemma4_multimodal_embedder.rs::Gemma4MultimodalEmbedder shape (pre-projection RMSNorm + Linear from output_proj_dims → text hidden). Instantiate it twice: embed_vision (3840 → 3840) and embed_audio (640 → 3840). embed_audio must be omitted when audio_config is absent.

5. Multimodal merge & per-layer inputs (reuse)

  • Merge: scatter image/video/audio features into placeholder positions using the existing masked-scatter helper (src/vision/gemma4_multimodal_embedder.rs / src/vision/merge.rs), exactly as the current Gemma 4 VLM merge does — keyed on image_token_id, video_token_id, audio_token_id.
  • Per-layer inputs: Gemma 4 computes per-layer input embeddings from the text-only token ids. Multimodal placeholder positions must be zeroed before computing per-layer inputs. The text backbone already supports hidden_size_per_layer_input; just feed it text-masked ids.

6. Attention masking — the key new runtime behavior

This is the one decoder-side change. The Unified text model needs a multimodal token-type signal and a blockwise bidirectional overlay during image/video prefill.

mm_token_type_ids (per token, derived from input_ids):

value token kind derived from
0 text default
1 image input_ids == image_token_id
2 video input_ids == video_token_id
3 audio input_ids == audio_token_id

Mask rule (applied only when text_config.use_bidirectional_attention == "vision"):

  • Enable the bidirectional overlay only when: prefill (seq_len > 1) and at least one vision/video token is present and no audio token (type == 3) is present in the sequence. If any audio token is present, the whole prompt stays fully causal (this preserves audio-grounded image reasoning on the quantized Unified checkpoints).
  • When enabled, for each attention layer:
    1. Materialize the base mask as an array (full-attention → causal; sliding layers → causal and windowed) instead of the lazy "causal" form, so it can be modified.
    2. Assign each contiguous run of vision/video tokens a block id (increment at each block start); non-vision tokens get -1.
    3. Overlay: same_block[q, k] = (block[q] != -1) && (block[q] == block[k]); new_mask = base_mask OR same_block (broadcast across heads). Tokens inside the same image/video span attend to each other in both directions; everything else (text↔text, text↔vision, cross-block) stays causal/windowed.
  • Decode (seq_len == 1): unchanged causal/sliding behavior.

mlxcel already has bidirectional-mask building blocks to mirror: src/lib/mlxcel-core/src/drafter/masks.rs (bidirectional_full_mask, bidirectional_swa_mask) and the bidirectional handling in src/models/gemma3.rs. The new piece is the blockwise span overlay keyed on mm_token_type_ids in the Gemma 4 text mask construction.

⚠️ Prefill chunking interaction. With bidirectional vision enabled, an image/video prompt must be prefilled in a single chunk — chunked/paged prefill that splits a vision block would compute the block mask incorrectly. The model sets no_chunked_prefill = true for this case. Given the recent paged/chunked-prefill work in this runtime, the loader must mark these models so the scheduler prefills image/video prompts without splitting a vision span (text-only and audio prompts are unaffected and may use the normal path).

7. Weight mapping / sanitize

When mapping checkpoint tensors to module params:

  • Drop *rotary_emb* (and rotary_emb.inv_freq) and lm_head.weight (output is tied to embed_tokens).
  • Strip a leading model. prefix; remap language_model.<x> → language_model.model.<x> unless it already starts with language_model.model..
  • MoE experts (fused): …experts.gate_up_proj → split into …experts.switch_glu.gate_proj.weight and …experts.switch_glu.up_proj.weight (swap last two axes, split the doubled dim in half); …experts.down_proj → …experts.switch_glu.down_proj.weight. src/models/gemma4.rs already has switch_glu handling — reuse it.
  • Drop embed_audio* tensors when audio_config is absent.
  • Expected top-level prefixes: language_model.model.layers.*, vision_embedder.*, embed_vision.*, embed_audio.*.
  • Honor per-tensor quantization overrides from the quantization map (mixed 4/8-bit).

8. Processor (net-new front-end)

  • Image: aspect-ratio-preserving resize to a multiple of model_patch_size bounded by num_soft_tokens · pooling_kernel_size² patches, rescale, normalize, patchify into model_patch_size²·3 vectors + 2-D positions, pad to num_soft_tokens (pad positions = -1).
  • Audio: chunk waveform into audio_samples_per_token frames + mask (as in §3).
  • Chat template: render <boi> <image_soft_token>×N <eoi> and <boa> <audio_soft_token>×M <eoa> spans; emit the placeholder token ids that the merge step (§5) replaces. Reuse the Gemma 4 chat-template/prompt plumbing under src/vision/processors/gemma4.rs.

9. Speculative drafter (optional, can be deferred)

The checkpoint family ships an MTP assistant drafter (gemma4_unified_assistant-style). mlxcel already has Gemma 4 MTP target/drafter paths. Wiring a Unified drafter is out of scope for the core deliverable and may be tracked as a follow-up; the main goal is correct base generation.


Implementation plan (phased)

Phase 1 — Config & architecture registration

  • Add ModelType::Gemma4Unified (and, if needed, a Gemma4UnifiedVLM-style variant) in src/models/mod.rs (next to Gemma4 @207 / Gemma4VLM @209), including the display-name arms (@480, @486).
  • Add a "gemma4_unified" match arm in src/models/detection.rs::get_model_type (next to the "gemma4" | "gemma4_text" arm @111). Route to the unified loader; detect optional audio via weights/config the way gemma4_has_vision_weights does.
  • Register the architecture in src/model_metadata.rs (VLM + config-backed flags, mirroring Gemma4VLM).
  • Add LoadedModel::Gemma4Unified(…) in src/loaded_model.rs (@67/@70) and extend the delegate_language_model! arms (@159–177).
  • Add gemma4_unified config structs (top-level + text/vision/audio sub-configs). Reuse src/models/gemma4.rs::TextConfig, adding the use_bidirectional_attention field; parse sub-configs with src/loading/vlm.rs helpers (read_sanitized_vlm_config, parse_required_vlm_subconfig).

Phase 2 — Embedders

  • Implement the encoder-free VisionEmbedder (§2) as a new module (e.g. src/vision/encoders/gemma4_unified.rs).
  • Wire embed_vision / embed_audio using the existing Gemma4MultimodalEmbedder.
  • Implement the waveform→frame audio feature extractor (§3).

Phase 3 — Attention masking

  • Compute mm_token_type_ids from input_ids (§6).
  • Add the blockwise bidirectional overlay to the Gemma 4 text mask construction, gated on use_bidirectional_attention == "vision", prefill, vision-present, audio-absent.
  • Mark the model no_chunked_prefill for image/video prompts and ensure the scheduler does not split vision spans during prefill.

Phase 4 — Loader & multimodal merge

  • Add load_gemma4_unified(...) in src/loading/vlm_gemma.rs, mirroring load_gemma4_vlm (config read → weight load+backing → sanitize (§7) → build text backbone via Gemma4Model::from_weights → build VisionEmbedder + embed_vision (+ optional embed_audio) → assemble the model).
  • Dispatch the new ModelType in the src/loading/mod.rs VLM router (try_load_vlm_model_from_dir).
  • Reuse the masked-scatter merge and text-masked per-layer-input computation (§5).

Phase 5 — Processor

  • Implement the Unified image processor (patchify + 2-D positions + padding) and audio feature extractor in/near src/vision/processors/gemma4.rs.
  • Wire image/audio/video placeholder spans into the prompt path and confirm token ids match config.

Phase 6 — Integration, catalog & docs

  • Verify the model runs through the real CLI flow: mlxcel generate / mlxcel run with --image (and text-only), and through mlxcel serve (/v1/chat/completions with an image part). This is required for completion — not just standalone modules.
  • Add the architecture to the mlxcel arch catalog (src/commands/models.rs) and to docs/supported-models.md (it currently lists "Gemma 4 VL" @47).

Phase 7 — Speculative drafter (optional follow-up)

  • (Deferred) Wire a Gemma 4 Unified MTP assistant drafter.

Phase 8 — Tests & validation

  • Unit tests: config parsing (3 sub-configs + token-id/eoa fallback), mm_token_type_ids derivation, the blockwise bidirectional overlay (image-only → bidirectional intra-block; image+audio → fully causal; decode → causal), and sanitize weight remaps (prefix normalization + MoE switch_glu split).
  • Loader test: mlx-community/gemma-4-12b-it-4bit loads, reports both vision and audio embedders, and honors mixed-precision quant.
  • End-to-end on mlx-community/gemma-4-12b-it-4bit:
    • text-only generation is coherent;
    • image grounding is correct (a deterministic --temp 0 prompt over a known image describes the actual subject);
    • mixed image+audio prompt stays image-grounded;
    • server path returns a well-formed OpenAI-compatible response for an image request.

Acceptance criteria

  • mlx-community/gemma-4-12b-it-4bit loads as a gemma4_unified model (not misrouted to Gemma4VLM) and runs through both mlxcel generate/run and mlxcel serve.
  • Text-only, image, and image+audio prompts all produce correct, coherent output at --temp 0; image prompts are visually grounded.
  • The blockwise bidirectional mask is active for image/video-only prefill and disabled when audio tokens are present; decode is causal.
  • Weight load honors mixed-precision quantization and the documented prefix/MoE remaps.
  • mlxcel arch and docs/supported-models.md list Gemma 4 Unified.
  • New unit + loader + e2e tests pass; the feature is integrated into the real CLI/server flow (no orphaned modules).

Key mlxcel touchpoints

Area File Note
ModelType enum / display src/models/mod.rs add Gemma4Unified (@207/@209, @480/@486)
Type detection src/models/detection.rs add "gemma4_unified" arm (@111)
Metadata registry src/model_metadata.rs VLM + config-backed flags
LoadedModel + delegation src/loaded_model.rs add variant (@67/@70), macro arms (@159–177)
Text backbone (reuse) src/models/gemma4.rs TextConfig (+use_bidirectional_attention), Gemma4Model, switch_glu
Unified loader src/loading/vlm_gemma.rs new load_gemma4_unified, mirror load_gemma4_vlm
Config parse helpers src/loading/vlm.rs read_sanitized_vlm_config, parse_required_vlm_subconfig
VLM router src/loading/mod.rs try_load_vlm_model_from_dir dispatch
Vision embedder (new) src/vision/encoders/gemma4_unified.rs (new) encoder-free patch projector
Multimodal embedder (reuse) src/vision/gemma4_multimodal_embedder.rs embed_vision / embed_audio, masked scatter
Merge src/vision/merge.rs placeholder scatter
Processor src/vision/processors/gemma4.rs patchify + audio frames + chat template
Bidirectional mask refs src/lib/mlxcel-core/src/drafter/masks.rs, src/models/gemma3.rs patterns to mirror
Arch catalog / docs src/commands/models.rs, docs/supported-models.md list Gemma 4 Unified

Activity

  1. added
    type:enhancement
    area:models
    priority:high
    status:ready
    status:in-progress
    status:review
    status:done
    and removed
    status:ready
    status:in-progress
    status:review
    on Jun 4, 2026
  2. added a commit that references this issue on Jun 4, 2026
    d490679
  3. self-assigned this
    on Jun 4, 2026
  4. added this to the 0.1 milestone on Jun 5, 2026
  5. added a commit that references this issue on Oct 27, 2026
    9670ae4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

area:modelspriority:highstatus:donetype:enhancement

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions