Repository navigation
feat(ops): add argWhere for GPU-side mask-index extraction - #10
Merged
Merged
Conversation
NumPy / PyTorch have a native `argwhere` / `nonzero` that returns a variable-size tensor. MLX does not support variable-size outputs from a single graph op, so we expose the operation with a `count: Int` parameter supplied by the caller (typically known from a prior validation step, e.g. comparing a visual-token count against a feature-token count). Implementation is a pure composition of existing ops and stays on GPU: positions = arange(n); masked = where(mask, positions, n); sorted; slice 0..<count. Unlike `mask.asArray(Bool.self).enumerated` patterns, no per-element CPU readback — the whole mask can stay in GPU memory. Tests cover: - all-true and all-false edge cases (including count=0 zero-output fast path) - mixed true/false ordering - randomized equivalence vs a CPU-loop reference - nonzero numeric input (coerced to bool, matching NumPy semantics) - use as a scatter index into another MLXArray Motivating use case: mlx-swift-lm VLM prompt-prep paths currently force a per-prompt GPU→CPU sync via `.asArray(Bool.self)` to locate image-token positions. With `argWhere`, those callers can stay on GPU and use the returned index tensor directly for scatter/gather. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
ekryski
added a commit
to ekryski/mlx-swift-lm
that referenced
this pull request
Apr 17, 2026
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>
|
Tested on M2 Pro 32GB with the full perf stack merged into alpha. No regression observed. argWhere compiles and runs without issues on Apple GPU Family 8. |
Merged
3 tasks done
ekryski
added a commit
to ekryski/mlx-swift-lm
that referenced
this pull request
Apr 23, 2026
…#53) * perf(gemma3n): remove per-forward GPU→CPU sync in sliding-mask offset 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> * perf(vlm): replace .asArray(Bool)+Swift-loop mask indexing with argWhere 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> --------- 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
argWhere(_ mask: MLXArray, count: Int)op inMLX.Ops.arange → where → sort → slice. Stays on GPU.mask.asArray(Bool.self).enumerated()loops to build scatter indices.Why
count: Intinstead of variable-size outputMLX graph ops require shape-known outputs. NumPy
np.nonzeroand PyTorchtorch.nonzeroboth handle this with dynamic-shape tensors that MLX doesn't support. Callers typically already know the count from input validation (e.g., `nImageTokens == nImageFeatures`), so accepting it as a parameter is natural.Test plan