Skip to content

perf(gemma3n): remove per-forward GPU→CPU sync in sliding-mask offset - #53

Merged
ekryski merged 2 commits into
alphafrom
ek/gpu-cpu-roundtrip-cleanup
Apr 23, 2026
Merged

ekryski merged 2 commits into
alphafrom
ek/gpu-cpu-roundtrip-cleanup

Conversation

@ekryski

@ekryski ekryski commented Apr 17, 2026 •

Copy link
Copy Markdown
Owner

Summary

  • Gemma3nDecoderLayer.callAsFunction computed its sliding-window mask offset via cachePosition.max().item(), forcing a GPU→CPU sync on every forward pass (once per layer per token).
  • Rewrite keeps the offset arithmetic on GPU: max(0, cachePosition.max() - (effectiveSeqLen - 1)) as a 0-d int32 MLXArray that broadcasts into the mask index vector.
  • Semantically identical; no change to output values.
  • Requires feat(ops): add argWhere for GPU-side mask-index extraction mlx-swift#10

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 argWhere op not currently exposed in mlx-swift, or (b) algorithmic restructuring of Swift-side index/loop logic. Those are better as a follow-up PR after argWhere lands in mlx-swift.

Test plan

  • New 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).
  • Safety regression: KVCacheTests and SpeculativeDecodingTests both pass locally (swift test -c release --skip-build).
  • Benchmark: Gemma3n decode at 1024, 4096 ctx with --ppl. User to run headline numbers vs alpha baseline.

ekryski and others added 2 commits April 16, 2026 18:42
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>
@TheTom

TheTom commented Apr 18, 2026

Copy link
Copy Markdown

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.

@ekryski
ekryski merged commit 05178d3 into alpha Apr 23, 2026
@ekryski
ekryski deleted the ek/gpu-cpu-roundtrip-cleanup branch April 23, 2026 19:01
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>
@github-actions github-actions Bot added the performance Performance improvement (auto-applied from perf: prefix) label Nov 24, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

performance Performance improvement (auto-applied from perf: prefix)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants