Repository navigation
feat: add Gemma 4 Unified (gemma4_unified) multimodal architecture - #153
Conversation
Extend the shared Gemma 4 text backbone with the runtime hook the new gemma4_unified architecture needs: a TextConfig.use_bidirectional_attention selector and a blockwise bidirectional attention overlay applied to both the full-attention and sliding-window base masks during prefill. overlay_block_bidirectional builds same_block[q,k] = (block[q] >= 0) && (block[q] == block[k]) from a per-position vision block-id vector and sets the additive mask to 0 wherever a query and key share a non-negative image/video span id, leaving text and cross-block pairs causal/windowed. The overlay is threaded through a new bidirectional_block_ids argument on Gemma4TextModel::forward_with_speculative_sinks and surfaced via new Gemma4Model/Gemma4Wrapper unified-forward helpers; existing callers pass None so fully-causal behaviour is unchanged.
Add the Gemma 4 Unified multimodal architecture: an encoder-free patch-projection vision embedder, a raw-waveform audio feature path, the shared multimodal projector reused for both modalities, config schema (3 sub-configs + eoa_token_index fallback), and the blockwise-bidirectional prefill forward. Registration: new ModelType::Gemma4Unified (detection by model_type, enum/display/catalog), LoadedModel::Gemma4Unified + delegate_language_model! arm, model_metadata VLM entry, loader load_gemma4_unified (sanitize prefix-normalization + MoE switch_glu split + mixed-precision quant via shape inference) dispatched from the VLM router, VlmRuntimeRef::Gemma4Unified for image/audio prompt preparation, and the server audio path.
Add focused unit tests for the Gemma 4 Unified additions: config parsing (3 sub-configs, eoa_token_index fallback, mixed-precision quant inheritance, optional audio, vision defaults), the encoder-free image processor (patch dim, 2-D positions, padding, soft-token budget) and waveform audio chunking + validity mask, mm_token_type_ids / vision_block_ids derivation (image-only bidirectional intra-block, image+audio fully causal, decode causal), the additive blockwise bidirectional mask overlay, and the sanitize weight remaps (prefix normalization, rotary/lm_head drop, audio drop, MoE switch_glu split).
The area-preserving resize upscales small images to the soft-token budget (matching the existing Gemma 4 processor), so the patch-grid assertions now use image sizes and budgets that land on a deterministic grid without distortion.
Wire the Gemma 4 Unified image+audio path into the CLI generate flow (compute_gemma4_unified_multimodal_embeddings), gate video input behind an explicit not-yet-supported error in the server, add the architecture to docs/supported-models.md, and let the mlxcel arch catalog pick it up via the new ModelType display metadata.
Slice each image's projected features to its real (non-padding) patch count so the row count aligns exactly with the image placeholder tokens the processor emitted, keeping merge_llava's cumulative-index scatter correct when a small image produces fewer real patches than the padded soft-token budget.
Cast the incoming f32 patch matrix to the embedder's native weight dtype (bf16/f16) so the learned 2-D positional-embedding add does not mix f32 patch features with the bf16 pos_embedding table.
Extract the pure token-type/block-id derivation into src/vision/gemma4_unified_mask.rs and the unified loader+sanitize into src/loading/vlm_gemma_unified.rs (with their own test files), keeping gemma4_unified.rs and vlm_gemma.rs under the project's 500-line limit.
Implementation Review SummaryIntent
Findings AddressedNone auto-fixed in this pass — see Remaining. Remaining Items
Verification
Note: this review session had read-only tooling, so the MEDIUM/LOW items above are reported rather than auto-fixed. |
… are valid soft tokens The `process_audio` function was marking trailing partial frames as invalid (`mask == false`) while the embedding merge path discarded the mask entirely, with a comment claiming "placeholder count equals the valid frame count" — which was inaccurate because `num_frames` always includes the zero-padded tail. The correct invariant: every chunked frame (including the zero-padded trailing partial) is a real audio soft token. The checkpoint is built expecting exactly `num_frames = ceil(samples / audio_samples_per_token)` soft tokens, so the placeholder count, the mask length, and the projected-feature count all equal `num_frames`. Adopted Option A: mark all frames valid and update comments; the emitted audio token count is unchanged. Changes: - `src/vision/processors/gemma4_unified.rs`: rewrite `process_audio` to emit all-true mask; update doc comment to state the accurate invariant. - `src/vision/gemma4_unified.rs`: replace misleading scatter comment with accurate description of why the mask is not consumed during embedding merge. - `src/vision/processors/gemma4_unified_tests.rs`: update `audio_chunks_into_frames_with_mask` to assert both frames valid; add explanatory comment. - `cargo fmt` reformatting across several files touched by the PR.
PR Finalization CompleteAudio validity-mask fix (MEDIUM)Took Option A: made all chunked audio frames valid soft tokens by emitting an all- Files changed:
TestsAll 25 narrow tests pass:
Lint/Format
Docs
Intentionally-scoped items (unchanged, documented in PR body)
All checks passing. Ready for merge. |
Summary
Add the Gemma 4 Unified (
gemma4_unified) multimodal architecture: a single text + image + audio model that reuses the existing Gemma 4 text backbone but is encoder-free — images become soft tokens via a lightweight patch-projection embedder and audio via raw-waveform chunking, with blockwise bidirectional attention over image/video token spans during prefill. Because the language backbone is the same Gemma 4 transformer mlxcel already runs, this is mostly new front-end plumbing plus one decoder-side mask change.What changed
Text backbone (reused,
src/models/gemma4.rs):TextConfig.use_bidirectional_attentionselector andoverlay_block_bidirectional, which OR asame_blockoverlay onto both the full-attention and sliding-window base masks so each contiguous image/video span attends bidirectionally within itself while text and cross-block pairs stay causal/windowed. Threaded through a newbidirectional_block_idsargument onforward_with_speculative_sinks(existing callers passNone) plusGemma4Model/Gemma4Wrapperunified-forward helpers.New front-end:
src/vision/encoders/gemma4_unified.rs: encoder-free patch projector (patch_ln1→patch_dense→patch_ln2→ learned 2-D positional embedding →pos_norm).src/vision/processors/gemma4_unified.rs: image patchify (model_patch_size²·3vectors + 2-D positions, padded tonum_soft_tokenswith-1) and raw-waveform audio chunking (audio_samples_per_tokenframes + validity mask).src/vision/gemma4_unified.rs+gemma4_unified_mask.rs: theGemma4UnifiedModel(merge via the sharedGemma4MultimodalEmbedderfor bothembed_visionandembed_audio, text-masked per-layer inputs, blockwise overlay) and the puremm_token_type_ids/ vision block-id derivation.src/vision/gemma4_unified_config.rs: the 3 sub-config schema with theeoa_token_indexfallback.Registration & loader:
ModelType::Gemma4Unified(detection bymodel_type, enum/display/catalog),LoadedModel::Gemma4Unified+delegate_language_model!arm,model_metadataVLM entry,VlmRuntimeRef::Gemma4Unifiedfor image/audio prompt prep.src/loading/vlm_gemma_unified.rs:load_gemma4_unified(weight load +sanitizeprefix normalization, rotary/lm_headdrop, audio drop, MoEswitch_glusplit; mixed-precision quant resolved by per-tensor shape inference), dispatched from the VLM router.mlxcel generate --image/--audio) and server (/v1/chat/completions) image and image+audio paths wired; themlxcel archcatalog anddocs/supported-models.mdlist the architecture.Deferred (follow-up)
gemma4_unifiedis gated behind an explicitvideo input is not yet supported for gemma4_unifiederror (not a silent stub); text / image / image+audio is the implemented path.mlx-community/gemma-4-12b-it-4bit(load + temp-0 image grounding + server response) is left to the orchestrator; structure was verified against the checkpoint'sconfig.json/model.safetensors.index.json.Test plan
cargo check --lib --tests— cleancargo clippy --lib --tests— no warnings on new codecargo test --lib gemma4_unified— 21 passed (config parsing incl.eoa_token_indexfallback + mixed-precision quant, processor patchify/positions/padding + audio chunking,mm_token_type_ids/ vision block-id derivation, additive blockwise bidirectional overlay)cargo test --lib gemma_unified— 4 passed (sanitizeprefix normalization, rotary/lm_headdrop, audio drop, MoEswitch_glusplit)Closes #151