Skip to content

feat(ops): add argWhere for GPU-side mask-index extraction - #10

Merged
ekryski merged 1 commit into
alphafrom
ek/add-argwhere-op
Apr 23, 2026
Merged

ekryski merged 1 commit into
alphafrom
ek/add-argwhere-op

Conversation

@ekryski

@ekryski ekryski commented Apr 17, 2026 •

Copy link
Copy Markdown
Owner

Summary

  • New argWhere(_ mask: MLXArray, count: Int) op in MLX.Ops.
  • Pure-composition implementation: arange → where → sort → slice. Stays on GPU.
  • Unblocks mlx-swift-lm VLM prompt-prep paths that currently force GPU→CPU syncs via mask.asArray(Bool.self).enumerated() loops to build scatter indices.

Why count: Int instead of variable-size output

MLX graph ops require shape-known outputs. NumPy np.nonzero and PyTorch torch.nonzero both 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

  • All-true, all-false (count=0 fast path), mixed ordering cases
  • Randomized equivalence vs CPU-loop reference
  • Numeric (non-bool) input coercion
  • Use as scatter index into another MLXArray
  • CI runs: tests compile; local CLI run blocked by a known metallib-loading issue in the test bundle (affects any mlx-swift test suite, pre-existing). The tests run correctly when the metallib is present (via Xcode or mlx-swift-lm's harness).

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>
@TheTom

TheTom commented Apr 18, 2026

Copy link
Copy Markdown

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.

@ekryski
ekryski merged commit 14e4980 into alpha Apr 23, 2026
@ekryski
ekryski deleted the ek/add-argwhere-op branch April 23, 2026 18:54
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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants