Skip to content

feat: add Gemma 4 Unified (gemma4_unified) multimodal architecture - #153

Merged
inureyes merged 11 commits into
mainfrom
feature/issue-151-gemma4-unified
Jun 4, 2026
Merged

inureyes merged 11 commits into
mainfrom
feature/issue-151-gemma4-unified

Conversation

@inureyes

@inureyes inureyes commented Jun 4, 2026

Copy link
Copy Markdown
Member

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

  • New TextConfig.use_bidirectional_attention selector and overlay_block_bidirectional, which OR a same_block overlay 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 new bidirectional_block_ids argument on forward_with_speculative_sinks (existing callers pass None) plus Gemma4Model/Gemma4Wrapper unified-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²·3 vectors + 2-D positions, padded to num_soft_tokens with -1) and raw-waveform audio chunking (audio_samples_per_token frames + validity mask).
  • src/vision/gemma4_unified.rs + gemma4_unified_mask.rs: the Gemma4UnifiedModel (merge via the shared Gemma4MultimodalEmbedder for both embed_vision and embed_audio, text-masked per-layer inputs, blockwise overlay) and the pure mm_token_type_ids / vision block-id derivation.
  • src/vision/gemma4_unified_config.rs: the 3 sub-config schema with the eoa_token_index fallback.

Registration & loader:

  • ModelType::Gemma4Unified (detection by model_type, enum/display/catalog), LoadedModel::Gemma4Unified + delegate_language_model! arm, model_metadata VLM entry, VlmRuntimeRef::Gemma4Unified for image/audio prompt prep.
  • src/loading/vlm_gemma_unified.rs: load_gemma4_unified (weight load + sanitize prefix normalization, rotary/lm_head drop, audio drop, MoE switch_glu split; mixed-precision quant resolved by per-tensor shape inference), dispatched from the VLM router.
  • CLI (mlxcel generate --image/--audio) and server (/v1/chat/completions) image and image+audio paths wired; the mlxcel arch catalog and docs/supported-models.md list the architecture.

Deferred (follow-up)

  • Video input for gemma4_unified is gated behind an explicit video input is not yet supported for gemma4_unified error (not a silent stub); text / image / image+audio is the implemented path.
  • MTP speculative drafter (issue §9) is out of scope; the model falls into the existing non-MTP arms.
  • Real-model end-to-end verification on 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's config.json / model.safetensors.index.json.

Test plan

  • cargo check --lib --tests — clean
  • cargo clippy --lib --tests — no warnings on new code
  • cargo test --lib gemma4_unified — 21 passed (config parsing incl. eoa_token_index fallback + 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 (sanitize prefix normalization, rotary/lm_head drop, audio drop, MoE switch_glu split)

Closes #151

inureyes added 10 commits June 4, 2026 14:54
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.
@inureyes inureyes added status:review Under review type:enhancement New features, capabilities, or significant additions priority:high High priority area:models Model architectures, weights, loading, metadata labels Jun 4, 2026
@inureyes

inureyes commented Jun 4, 2026

Copy link
Copy Markdown
Member Author

Implementation Review Summary

Intent

Add the encoder-free gemma4_unified multimodal architecture (text + image + audio) reusing the existing Gemma 4 backbone, with a patch-projection vision embedder, waveform-chunk audio path, and blockwise bidirectional attention over image/video spans during prefill (closes #151).

Findings Addressed

None auto-fixed in this pass — see Remaining.

Remaining Items

  • Audio path materializes the trailing zero-padded frame as a real soft token (MEDIUM) — src/vision/processors/gemma4_unified.rs::process_audio counts the trailing partial frame via div_ceil, so num_frames includes one invalid frame. expand_gemma4_audio_tokens_for_server then emits that many audio_token_id placeholders and get_input_embeddings_with_audio projects/scatters all num_frames rows. The computed mask is explicitly discarded (let _ = audio_mask; in src/vision/gemma4_unified.rs), and the in-code comment ("invalid frames simply are not referenced because the placeholder count equals the valid frame count") is inaccurate — the placeholder count equals num_frames, not the valid-frame count. Net effect: one spurious zero-derived audio soft token per clip whose length isn't an exact multiple of audio_samples_per_token. Recommended fix: count only complete frames (drop the trailing partial) so num_frames, the placeholder count, and the projected feature count all reflect valid frames; or apply the validity mask in the scatter. The text/image path is unaffected.
  • Quantized-MoE expert split not handled (LOW) — sanitize_gemma4_unified_weights splits only unquantized experts.gate_up_proj (.weight); a quantized-MoE Gemma 4 Unified checkpoint's .scales/.biases would not be split. Dormant for the dense reference checkpoint; acknowledged in the PR body.

Verification

  • All stated requirements implemented (text/image/image+audio across CLI + server; video explicitly gated; MTP out of scope)
  • No placeholder/mock/TODO code in the live path
  • Integrated into project code flow (detection, ModelType enum/display/catalog, metadata, LoadedModel + delegate macro, VlmRuntimeRef, per-layer-input binding for all 3 sequence ops, VLM router, tensor-parallel fallback arch, CLI generate --image/--audio, server /v1/chat/completions image and image+audio)
  • Project conventions followed (module layout under 500-line cap, license headers, error handling, clippy clean)
  • Existing modules reused (shared Gemma 4 decoder, Gemma4MultimodalEmbedder, masked_scatter/merge_llava, per-layer-inputs state, switch_glu; no_chunked_prefill achieved via the existing vlm-embeddings chunked-prefill bypass rather than a new flag)
  • No unintended structural changes to the existing gemma4/Gemma4VLM paths (additive bidirectional_block_ids arg with None at existing callers)
  • Tests pass — cargo check --lib --tests clean; cargo clippy --lib --tests -- -D warnings clean; cargo test --lib gemma4_unified 21 passed; cargo test --lib gemma_unified 4 passed

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

inureyes commented Jun 4, 2026

Copy link
Copy Markdown
Member Author

PR Finalization Complete

Audio validity-mask fix (MEDIUM)

Took Option A: made all chunked audio frames valid soft tokens by emitting an all-true mask. The trailing partial frame was already zero-padded and included in num_frames; the mask was just internally inconsistent with the actual semantics (and was discarded anyway). No behavioral change to the emitted audio token count.

Files changed:

  • src/vision/processors/gemma4_unified.rs (process_audio): rewrote mask generation to vec![1i32; num_frames] (all valid); replaced the incorrect doc comment with the accurate invariant: placeholder count == mask length == projected-feature count == num_frames.
  • src/vision/gemma4_unified.rs: replaced the misleading scatter comment ("placeholder count equals the valid frame count") with an accurate explanation of why the mask is not consumed during embedding merge.
  • src/vision/processors/gemma4_unified_tests.rs: updated audio_chunks_into_frames_with_mask to assert!(mask1, ...) (trailing partial frame is valid), added the invariant explanation in the test comment.

Tests

All 25 narrow tests pass:

  • cargo test --lib gemma4_unified — 21 passed (config parsing incl. eoa_token_index fallback + mixed-precision quant; processor patchify/positions/padding + audio chunking; mm_token_type_ids/block-id derivation; blockwise bidirectional overlay)
  • cargo test --lib gemma_unified — 4 passed (sanitize prefix normalization, rotary/lm_head drop, audio drop, MoE switch_glu split)

Lint/Format

  • cargo check --lib --tests — clean
  • cargo clippy --lib --tests -- -D warnings — clean
  • cargo fmt — applied across all files touched by this PR

Docs

docs/supported-models.md already lists Gemma 4 Unified accurately (line 48-49). The Korean docs directory (docs/ko/) does not exist in the repository, so no translation update is needed.

Intentionally-scoped items (unchanged, documented in PR body)

  • Video input gated behind an explicit error — not filled in.
  • MTP speculative drafter — out of scope.
  • LOW: quantized-MoE switch_glu split handles only unquantized gate_up_proj.

All checks passing. Ready for merge.

@inureyes inureyes added status:done Completed and removed status:review Under review labels Jun 4, 2026
@inureyes
inureyes merged commit d490679 into main Jun 4, 2026
4 checks passed
@inureyes
inureyes deleted the feature/issue-151-gemma4-unified branch June 4, 2026 07:15
@inureyes inureyes added this to the 0.1 milestone Jun 21, 2026
@inureyes inureyes self-assigned this Aug 31, 2026
be-free-snowboy pushed a commit to freestylejs/snowbrain-mlxcel that referenced this pull request Oct 27, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:models Model architectures, weights, loading, metadata priority:high High priority status:done Completed type:enhancement New features, capabilities, or significant additions

Projects

None yet

Development

Successfully merging this pull request may close these issues.

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

1 participant