Repository navigation
Description
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. Noteeoa_token_idmay be absent and should fall back toeoa_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_typesdefaults 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:
- Patchify the (resized, normalized) image into non-overlapping
model_patch_size × model_patch_size × 3patches → flat vectors of lengthmodel_patch_size² · 3(e.g.48·48·3 = 6912), plus a 2-D(x, y)position per patch. Padding patches use position-1. patch_ln1(LayerNorm overpatch_dim) →patch_dense(Linearpatch_dim → mm_embed_dim) →patch_ln2(LayerNorm overmm_embed_dim).- Add learned 2-D positional embeddings:
pos_embeddingof shape(mm_posemb_size, 2, mm_embed_dim), indexed by the(x, y)ids (x uses slot 0, y uses slot 1);-1positions contribute zero. pos_norm(LayerNorm overmm_embed_dim) → per-patch features atoutput_proj_dims.- 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 onimage_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:
- 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.
- Assign each contiguous run of vision/video tokens a block id (increment at each block start); non-vision tokens get
-1. - 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 setsno_chunked_prefill = truefor 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*(androtary_emb.inv_freq) andlm_head.weight(output is tied toembed_tokens). - Strip a leading
model.prefix; remaplanguage_model.<x>→language_model.model.<x>unless it already starts withlanguage_model.model.. - MoE experts (fused):
…experts.gate_up_proj→ split into…experts.switch_glu.gate_proj.weightand…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.rsalready hasswitch_gluhandling — reuse it. - Drop
embed_audio*tensors whenaudio_configis absent. - Expected top-level prefixes:
language_model.model.layers.*,vision_embedder.*,embed_vision.*,embed_audio.*. - Honor per-tensor quantization overrides from the
quantizationmap (mixed 4/8-bit).
8. Processor (net-new front-end)
- Image: aspect-ratio-preserving resize to a multiple of
model_patch_sizebounded bynum_soft_tokens · pooling_kernel_size²patches, rescale, normalize, patchify intomodel_patch_size²·3vectors + 2-D positions, pad tonum_soft_tokens(pad positions =-1). - Audio: chunk waveform into
audio_samples_per_tokenframes + 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 undersrc/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, aGemma4UnifiedVLM-style variant) insrc/models/mod.rs(next toGemma4@207 /Gemma4VLM@209), including the display-name arms (@480,@486). - Add a
"gemma4_unified"match arm insrc/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 waygemma4_has_vision_weightsdoes. - Register the architecture in
src/model_metadata.rs(VLM + config-backed flags, mirroring Gemma4VLM). - Add
LoadedModel::Gemma4Unified(…)insrc/loaded_model.rs(@67/@70) and extend thedelegate_language_model!arms (@159–177). - Add
gemma4_unifiedconfig structs (top-level + text/vision/audio sub-configs). Reusesrc/models/gemma4.rs::TextConfig, adding theuse_bidirectional_attentionfield; parse sub-configs withsrc/loading/vlm.rshelpers (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_audiousing the existingGemma4MultimodalEmbedder. - Implement the waveform→frame audio feature extractor (§3).
Phase 3 — Attention masking
- Compute
mm_token_type_idsfrominput_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_prefillfor image/video prompts and ensure the scheduler does not split vision spans during prefill.
Phase 4 — Loader & multimodal merge
- Add
load_gemma4_unified(...)insrc/loading/vlm_gemma.rs, mirroringload_gemma4_vlm(config read → weight load+backing →sanitize(§7) → build text backbone viaGemma4Model::from_weights→ buildVisionEmbedder+embed_vision(+ optionalembed_audio) → assemble the model). - Dispatch the new
ModelTypein thesrc/loading/mod.rsVLM 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 runwith--image(and text-only), and throughmlxcel serve(/v1/chat/completionswith an image part). This is required for completion — not just standalone modules. - Add the architecture to the
mlxcel archcatalog (src/commands/models.rs) and todocs/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/
eoafallback),mm_token_type_idsderivation, the blockwise bidirectional overlay (image-only → bidirectional intra-block; image+audio → fully causal; decode → causal), andsanitizeweight remaps (prefix normalization + MoEswitch_glusplit). - Loader test:
mlx-community/gemma-4-12b-it-4bitloads, 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 0prompt 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-4bitloads as agemma4_unifiedmodel (not misrouted toGemma4VLM) and runs through bothmlxcel generate/runandmlxcel 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 archanddocs/supported-models.mdlist 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
feat: add Gemma 4 Unified (gemma4_unified) multimodal architecture (#153
feat: add Gemma 4 Unified (gemma4_unified) multimodal architecture (l…