Skip to content

fix(vision): use the transformers mask for Gemma 3 image prefill - #2773

Merged
inureyes merged 5 commits into
mainfrom
fix/issue-2760-gemma3-image-mask
Oct 30, 2026
Merged

inureyes merged 5 commits into
mainfrom
fix/issue-2760-gemma3-image-mask

Conversation

@inureyes

@inureyes inureyes commented Oct 30, 2026 •

Copy link
Copy Markdown
Member

Summary

Behavior change: Gemma 3 image outputs change. Gemma 3 image prefill now uses the transformers mask (causal plus bidirectional attention inside each image block on global layers, the same intersected with the sliding window on sliding layers) instead of a fully bidirectional mask on every layer. PaliGemma keeps its prefix-LM mask and its output is byte-identical.

  • vision::merge: prepare_inputs_for_multimodal takes an explicit MultimodalMask (Gemma3ImageBlocks or PrefixLm) and builds the mask through the public multimodal_attention_mask; image blocks are maximal runs of image_token_id, numbered per batch row, <start_of_image>/<end_of_image> stay text.
  • MergeStrategy::PaliGemma is new and load_paligemma_vlm uses it; load_gemma3_vlm (Gemma 3, not Gemma3n) keeps MergeStrategy::Gemma3.
  • gemma3.rs external-mask branch: global layers take the mask as is, sliding layers take mask AND (q - k < window), built once per forward and only when the key axis exceeds the window.
  • Trace reference arm (scripts/mlx_vlm_image_logit_trace.py) passes the same Gemma 3 mask. mlx-vlm applies one passed mask to every layer, so the script refuses a sequence longer than the sliding window; the traced sequence is 335 tokens against a 1024-token window, so the band is a no-op there.

Other Gemma 3 forwards: every Gemma3Wrapper entry that carries an external mask (forward_with_embeddings, forward_with_embeddings_and_sequence_id, forward_last_logits_with_embeddings_and_sequence_id) funnels into hidden_with_caches_and_embeddings, so the one branch covers them. The non-decode forward_batched_with_ids path calls forward_with_sequence_id, which takes no mask (unchanged, and no VLM caller reaches it with one). Gemma3StageModel::execute_hidden and Gemma3Backbone::forward_embeds take no external mask (they build text masks only), so no VLM mask reaches them.

Out of scope, unchanged: the OpenXLA Gemma 3 path (src/lib/mlxcel-xla/src/prepared_gemma3.rs, GEMMA3_VLM_MASK_MODE) still mirrors the old bidirectional mask on every layer and needs a follow-up issue. PaliGemma's reference-arm mask and Gemma3n are untouched.

Evidence

Failing first, with the fix logic reverted on this branch: 6 of the new tests failed (the four Gemma 3 mask tests, the sliding-band test, and the tiny model, row 0 logit 0: external mask 0.5711894, text prefill 0.6478121). With only the gemma3.rs layer split reverted, the tiny model alone failed at the first row past the window: row 4 logit 0: external mask 0.76741546, text prefill 0.72449356.

Trace pair (gemma-3-4b-it-4bit, test_image_shapes.png, --mlxcel-prompt, float32 CPU reference, decided gap 2):

mlxcel build reference mask top-1 decided perplexity mlxcel vs reference
main causal (old) 20 / 64 5 / 43 4.8500 vs 5.1620 (old reference TSV from the #2750 run; same prompt ids and targets)
main transformers 18 / 64 7 / 48 4.8500 vs 6.0156
fixed transformers 4 / 64 0 / 48 6.2651 vs 6.0156

The 4 remaining top-1 differences sit where the reference gap is under 1 logit, all at rank 2.

Cost: when an image prompt is longer than the sliding window (1024 on the 4B checkpoint), the sliding layers get a second [B,1,S,S] f32 mask, built once per forward. Prompts at or under the window allocate nothing extra.

PaliGemma (paligemma2-3b-6bit): trace TSV byte-identical before and after (cmp), greedy mlxcel generate --image text identical.

GB10 smoke on Gemma 3, CLI and mlxcel-server (127.0.0.1, one image chat request) give the same coherent answer: "three geometric shapes arranged vertically ... Top: A square, colored red. Middle: A circle, colored blue. Bottom: A triangle, colored green." Before the fix the CLI said "a white square-like shape-dividing it into four equal parts".

Test plan

  • cargo test --profile test-fast --features cuda -p mlxcel --lib vision::merge -- --test-threads=1 (9 passed)
  • cargo test ... --lib models::gemma3 -- --test-threads=1 (49 passed, 11 ignored, rerun on the final head)
  • cargo test ... --lib multimodal:: -- --test-threads=1 (318 passed); vision:: and loading::vlm filters also pass
  • cargo fmt --all -- --check, cargo clippy --profile test-fast --features cuda -p mlxcel --lib --tests -- -D warnings
  • Trace pair, PaliGemma before/after, CLI and server smoke above, under gpu-lock

Closes #2760

Gemma 3 image prefill ran with a fully bidirectional mask over the whole prompt, and the same mask reached every layer, so text tokens attended to later prompt tokens and sliding-window layers attended past their window. transformers builds `causal OR same_image_block` for the full-attention layers and `sliding_window AND (causal OR same_image_block)` for the sliding layers; PaliGemma is a prefix LM and keeps the bidirectional prompt mask.

- vision::merge: `prepare_inputs_for_multimodal` takes an explicit `MultimodalMask`. `Gemma3ImageBlocks` is causal plus bidirectional attention inside each maximal run of image tokens (block ids per batch row from a cumulative sum of run starts); `PrefixLm` is the previous mask, unchanged.
- vision: new `MergeStrategy::PaliGemma` selects the prefix-LM mask; `load_paligemma_vlm` uses it, Gemma 3 keeps `MergeStrategy::Gemma3`. The strategy doc comments now name their real users.
- models::gemma3: in the external-mask branch, global layers take the VLM mask as is and sliding layers take it intersected with the `q - k < window` band, built once per forward and only when the key axis is wider than the window.
- scripts/mlx_vlm_image_logit_trace.py: the Gemma 3 reference arm passes the same mask instead of running causally; it refuses a sequence longer than the sliding window, since mlx-vlm applies one passed mask to every layer.

New tests pin the 13-token mask matrix, the no-image, padding and batch cases, the sliding-band intersection, and a tiny Gemma 3 whose external-mask logits must match the text prefill past a 4-token window; they fail against the previous mask and layer handling.

Refs #2760
…rs mask

The Gemma 3 parity row and its follow-up now name the cause of the remaining 5 / 43 decided disagreement (the prefill mask on both arms) and record the trace pair with the transformers mask in both arms: 4 / 64 top-1 and 0 / 48 decided positions, perplexity 6.2651 vs 6.0156, against 18 / 64 and 7 / 48 for the build before the fix.

Refs #2760
@inureyes inureyes added status:review Under review type:bug Bug fixes, error corrections, or issue resolutions priority:medium Medium priority area:models Model architectures, weights, loading, metadata modeltype:vlm Vision-language model labels Oct 30, 2026
@inureyes

Copy link
Copy Markdown
Member Author

Implementation Review Summary

Intent

Gemma 3 image prefill uses the transformers mask (causal plus bidirectional image blocks, banded on sliding layers), PaliGemma keeps its prefix-LM mask, and the trace reference arm uses the same Gemma 3 mask.

No CRITICAL, HIGH or MEDIUM findings, so nothing was changed on the branch.

Checked against transformers 5.22 (get_block_sequence_ids_for_mask, create_masks_for_vision_model, blockwise_overlay, sliding_window_overlay, padding_mask_function): I reimplemented those semantics independently in numpy, and they reproduce every expected matrix in the new tests exactly (13x13 full and sliding, right and left padding, the two-row batch). The layer split uses the same i % pattern == pattern - 1 global rule as the text path and make_caches, the band (q - k < window) matches sliding_window_overlay, and the text-only path is unchanged. Only load_gemma3_vlm hands Gemma3Wrapper an external mask, and every masked entry reaches hidden_with_caches_and_embeddings. The OpenXLA path builds its own prepared prefill and is untouched. The reference script used for the trace matches the committed one, and the docs numbers match the logs (18/64, 7/48, 4.8500 vs 6.0156 before; 4/64, 0/48, 6.2651 vs 6.0156 after). PaliGemma trace TSVs are byte-identical, and the greedy text is identical.

Remaining Items

  • PR body says the non-decode forward_batched_with_ids path carries the mask into hidden_with_caches_and_embeddings; it calls forward_with_sequence_id, which drops the mask (pre-existing, no VLM caller reaches it with a mask) (LOW)
  • multimodal_attention_mask doc says it is used by prepare_inputs_for_multimodal, which calls the private helper; the public function is only used by tests (LOW)
  • The "main vs causal (old)" row (20/64, 5/43) is carried over from fix(vision): align InternVL, MiniCPM-V 4.6 and Gemma 3 image prompts #2750, since this run's old-reference rerun timed out; it is still valid because the main build's perplexity (4.8500) and the old script are unchanged, but the PR could say so (LOW)
  • VisionModule maps the strategy to the mask with a nested if inside a combined match arm; two arms would read more plainly (LOW)

Verification

  • All stated requirements implemented
  • No placeholder/mock code remaining
  • Integrated into project code flow
  • Project conventions followed
  • Existing modules reused where applicable
  • No unintended structural changes
  • Tests pass: vision::merge 9, models::gemma3 49, multimodal:: 318 (CUDA, --test-threads=1, under gpu-lock); fmt and clippy -D warnings clean

@inureyes

Copy link
Copy Markdown
Member Author

Security and performance review

No CRITICAL, HIGH, or MEDIUM findings; nothing was changed. Reviewed at 4215da1.

LOW (not fixed)

  • Memory, src/models/gemma3.rs external_mask_with_window_band: for image prompts longer than the sliding window (1024 on the 4B checkpoint) the sliding layers now hold a second [B,1,S,S] f32 mask next to the external one, so persistent mask memory goes from 4·S² to 8·S² bytes, plus a transient [S,S] int32 difference and bool band while it is built. Main already allocated O(S²) here, the extra mask is built once per forward (not per layer), and it stays well under the per-layer [B,H,S,S] score buffer of masked SDPA, so the peak rises only modestly. Prompts at or under the window allocate nothing extra.
  • Panic paths: i % self.sliding_window_pattern divides by zero on a config with pattern 0, but main's text prefill path and make_caches_with_modes already do the same arithmetic on every request, and the value comes from the local checkpoint config, not the request. sliding_window as i32 has the same pre-existing wrap. Neither is new exposure.

Checked, no issue

  • Block ids and band are per row; S > window, batch > 1, and S == 1 behave correctly. The band always keeps the diagonal, so no new fully masked row. Server prefill is batch 1 with an all-ones padding mask.
  • Image tokens typed as text: the per-family image-token cardinality checks reject a mismatched count before the merge; a run only gains bidirectional attention within itself.
  • Hot path: no host syncs (array_shape and array_dtype read metadata), the new ops are O(S) for block ids and one O(S²) band per forward. Decode never takes the external mask, and the masked SDPA kernel is the one main already used.
  • scripts/mlx_vlm_image_logit_trace.py: no shell or eval; it refuses a sequence longer than the window instead of silently dropping the band.

Verification: vision::merge 9 passed, models::gemma3 49 passed (11 ignored), clippy -D warnings and cargo fmt --check clean.

prepare_inputs_for_multimodal now calls multimodal_attention_mask instead of the private helper directly, so the public builder's "Used by" doc is accurate and the mask is built in a single place. The mask is unchanged: it only recomputes the image-token comparison from the input ids.

VisionModule::prepare_inputs splits the combined Gemma3 | PaliGemma arm into two plain arms, each naming its MultimodalMask kind, instead of a nested if.

Validation: cargo fmt --check and clippy (test-fast, cuda, lib and tests, -D warnings) are clean. vision::merge 9/9 and every models::gemma3 submodule pass under gpu-lock. A single combined models::gemma3 run aborts on the known CUDA graph-capture flake in an unrelated test, so the submodules were run separately.

Refs #2760
@inureyes inureyes added status:done Completed and removed status:review Under review labels Oct 30, 2026
Bilingual (English and Korean) report on the Gemma 3 image prefill mask fix: the causal plus image-block mask in vision::merge, the sliding-window band applied in the Gemma 3 model, the PaliGemma prefix-LM strategy split, the trace reference arm change, the trace results, and the residuals (OpenXLA path, band unverified on a real checkpoint past the window).

Refs #2760
@inureyes
inureyes marked this pull request as ready for review October 30, 2026 21:16
@inureyes
inureyes merged commit 52e5fd5 into main Oct 30, 2026
21 checks passed
@inureyes
inureyes deleted the fix/issue-2760-gemma3-image-mask branch October 30, 2026 21:17
@inureyes inureyes added this to the 0.8 milestone Nov 30, 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 modeltype:vlm Vision-language model priority:medium Medium priority status:done Completed type:bug Bug fixes, error corrections, or issue resolutions

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(vision): Use the transformers mask for Gemma 3 image prefill

1 participant