Repository navigation
perf(gemma3n): remove per-forward GPU→CPU sync in sliding-mask offset - #53
Merged
Merged
Conversation
The sliding-window mask index computation in `Gemma3nDecoderLayer` called `cachePosition.max().item()` to derive the slice offset. `.item()` forces a GPU→CPU sync on every forward pass — one per layer per token during decode. Rewrite the offset entirely in MLXArray ops so the scalar stays on GPU: `max(0, cachePosition.max() - (effectiveSeqLen - 1))` as a 0-d int32 array that broadcasts into `maskIndexes = baseIndexes + offsetGPU`. Semantically identical; no sync point. Also adds `Gemma3nOffsetTests` pinning the CPU-reference vs GPU-formulation equivalence across 10 (pastSeenTokens, seqLen, slidingWindow) configurations including boundary cases at the window edge. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Five VLM prompt-prep paths computed image-token positions by pulling the full boolean mask off GPU with `.asArray(Bool.self)` then running a Swift `for … where` loop to build an `[Int]` / `[UInt32]` array. Each call was a GPU→CPU sync sized to the full mask plus a Swift-side linear scan. Switch to `argWhere(mask, count:)` (added in ekryski/mlx-swift#10). The count is already known at each callsite (`scaledImageFeatures.shape[0]`, `imageFeatures.dim(0)`, validated `nImageMaskElements`) so we just pass it through. One `.item()` for the count — or none, where the count was already computed for the size-mismatch guard — replaces the full-mask readback, and the index tensor stays on GPU all the way into the scatter. Files touched: - Gemma3.swift / `maskedScatter` - Gemma4.swift / `gemma4MaskedScatter` - LFM2VL.swift / `mergeInputIdsWithImageFeatures` - Qwen3VL.swift / `applyDeepstack` + `mergeInputIdsWithImageFeatures` - Qwen35.swift / `mergeInputIdsWithImageFeatures` Dead helpers removed: `Qwen3VL.maskIndices`, `Qwen3VL.nonZero`, `Qwen35.nonZero`. Not touched in this PR: - Pixtral / Mistral3 / FastVLM / QwenVL / Idefics3 / GlmOcr — these use the mask to build Swift `Int` slice boundaries for range-based embed splitting, not a direct scatter. Rewriting to stay on GPU requires restructuring the interleaving algorithm and is a separate refactor. - Qwen3VL / Qwen25VL cuSeqlens paths — Swift-side block-diagonal mask construction with integer ranges. - MediaProcessing Int64 conversions — one-shot at frame-timing setup. Tests: new `Tests/MLXLMTests/MaskedScatterTests.swift` pins the CPU-reference vs GPU-path identity across single-block, interleaved, zero-count, and size-mismatch cases (5 scenarios). Plus the existing `Gemma3nOffsetTests` from the earlier commit still passes (12 cases across 3 tests). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
|
Biggest contributor in the stack. M2 Pro 32GB testing shows no-quant decode went from 14.5 to 29.9 tok/s at 1K (+106%) and 16.5 to 23.2 at 16K (+41%). GPU→CPU sync removal is the likely driver. No regression on turbo4v2 path. |
4 tasks done
4 tasks done
ekryski
added a commit
that referenced
this pull request
May 5, 2026
…ward-port main fixes Reverses the Gemma4 VLM merge direction: restore alpha's pre-merge 1538-line implementation (with all its perf work intact) as the base, then forward-port the two small targeted fixes from main on top. Why: main's 1929-line VLM Gemma4 (which the merge initially adopted) was written independently from alpha's, with structurally different norm classes (`Gemma4RMSNormZeroShift` + `Gemma4RMSNormNoScale` vs alpha's fused-RMSNorm-RoPE path), no compiled QKV, and no GPU-resident masked-scatter. Taking main's text-decoder wholesale would have lost: - argWhere-based gemma4MaskedScatter (avoids `asArray(Bool.self)` full-mask CPU readback during VLM image-token splice — alpha's #53 perf optimization) - Compiled QKV for attention - Fused gate_up_proj + compile()-cached SharedMLP forward - FusedGateUpSwitchGLU MoE routing for 26B-A4B - Symbolic .slidingWindow SDPA mask routing Forward-ported from main on top of alpha's base: - #211 (system message + modality order): added `Gemma4MessageGenerator` struct (system messages stay text-only; user/assistant messages emit images first, then videos, then text — matching the Gemma 4 chat template). `Gemma4Processor.prepare` now uses it instead of `Qwen2VLMessageGenerator()`. - #202 (modern dim API): `flattenedSource.shape[0]` → `dim(0)` in `gemma4MaskedScatter`. Other #202 hunks (`maskArray.shape.last` cleanup, unused token-count diagnostics) didn't apply — alpha's attention-mask handling is structured differently and the processor never had those diagnostics. Verification: - `swift build` clean, `swift build --build-tests` clean. - `swift test --skip Benchmarks` passes 152 tests in 14 suites. - LLM-side Gemma 4 E2B smoke (3 KV modes × 4 contexts) coherent — exercises the same Gemma4TextConfiguration decode path. Note: full image-input smoke for the VLM path (loading via VLMModelFactory and running an image+prompt through Gemma4Processor) would benefit from a new `--method vision` mode in InferenceBenchmark that takes an image path. Scoped as a follow-up — see comment on the PR for the proposed shape. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Gemma3nDecoderLayer.callAsFunctioncomputed its sliding-window mask offset viacachePosition.max().item(), forcing a GPU→CPU sync on every forward pass (once per layer per token).max(0, cachePosition.max() - (effectiveSeqLen - 1))as a 0-d int32 MLXArray that broadcasts into the mask index vector.Scope
First of six PRs from the post-P0 performance plan. Scoped down from the original "GPU→CPU roundtrip cleanup" to the one load-bearing site — the per-forward LLM hot path. The VLM prompt-prep sites listed in the plan (~12 call sites across Qwen3VL, Qwen25VL, Gemma3/4 VLM, FastVLM, Pixtral, Mistral3, Idefics3, LFM2VL, QwenVL, GlmOcr, Qwen35 VLM) all depend on either (a) an
argWhereop not currently exposed in mlx-swift, or (b) algorithmic restructuring of Swift-side index/loop logic. Those are better as a follow-up PR afterargWherelands in mlx-swift.Test plan
Tests/MLXLMTests/Gemma3nOffsetTests.swift: 10 parameterized cases pinning CPU-reference vs GPU-formulation equivalence, plus boundary cases (zero-clamp, per-token advance past the window).KVCacheTestsandSpeculativeDecodingTestsboth pass locally (swift test -c release --skip-build).--ppl. User to run headline numbers vsalphabaseline.