Repository navigation
Description
Problem
Gemma 4 prefill still builds the full [1, L, 262144] logits tensor, plus a final_logit_softcapping copy, and then keeps a single row. This happens in most real runs:
Gemma4Wrapper::forward_last_logits(src/models/gemma4.rs) takes the full-logits path for prompts of up to 4096 tokens (FULL_LOGITS_MAX_PREFILL, added in fix: gemma-4 long-prompt prefill OOMs on CUDA because attention materializes O(heads*L^2) scores instead of using flash SDPA #672) so that short-context greedy output stays byte-identical to the batched head kernel. The hidden state is sliced first only for prompts longer than 4096 tokens.Gemma4Wrapperdoes not overrideforward_last_logits_with_sequence_idorforward_last_logits_with_embeddings_and_sequence_id, so server prefill falls back to the trait default (full logits) at every length.- The published Gemma 4 checkpoints (for example mlx-community
gemma-4-e4b-it-4bitandgemma-4-12b-it-4bit) ship vision/audio weights and load asGemma4VLModel(src/vision/gemma4_vl.rs) orGemma4UnifiedModel(src/vision/gemma4_unified.rs). Neither wrapper forwards the threeforward_last_logits*entry points, so these checkpoints do not get even the fix: gemma-4 long-prompt prefill OOMs on CUDA because attention materializes O(heads*L^2) scores instead of using flash SDPA #672 long-prompt saving.
Why the 4096 gate can go
#1955, #1969 and #1971 moved 11 other families to single-row head projection at every length, and greedy output stayed byte-identical. mlx-lm also computes the last prompt token as a one-token step. Gemma 3 4B, which has the same 262k vocabulary, gained +19.2% on pp512 prefill.
Plan
Remove the gate. Override all three entry points on Gemma4Wrapper, handling sequence state and per-layer inputs exactly as the existing forward paths do. Forward the three entry points from Gemma4VLModel and Gemma4UnifiedModel, covering the embeddings path with per-layer inputs and the unified bidirectional vision block ids.
Acceptance Criteria
- On the text wrapper and both VLM wrappers, all three entry points slice the hidden state before the LM head at every prompt length.
- A unit test checks that each entry point matches the sliced full forward at the last position and at an interior position, and fails when the slice is shifted by one row.
- Greedy output on Gemma 4 E4B and 12B matches main for a short prompt, a 512-token prompt, and an image prompt.
- pp512 and pp2048 prefill are measured against main using the
bench_decode.sharguments, and the results are recorded indocs/benchmark_results/. - The change is wired into the real CLI and server prefill paths.
Activity
perf(gemma4): project only the sampled row at prefill on every path (l…