Skip to content

Expose batch-invariant Metal inference - #452

Closed
aleroot wants to merge 2 commits into
ml-explore:mainfrom
aleroot:fix/speculative-shape-invariance
Closed

aleroot wants to merge 2 commits into
ml-explore:mainfrom
aleroot:fix/speculative-shape-invariance

Conversation

@aleroot

@aleroot aleroot commented Aug 16, 2026

Copy link
Copy Markdown
Contributor

Proposed changes

Related issue: ml-explore/mlx-swift-lm#542

Problem

Autoregressive decoding evaluates one token at a time, while speculative decoding verifies a short block of tokens in one target-model call. These different shapes can select different Metal matmul and attention kernels with different floating-point reduction orders.

Although mathematically equivalent, the resulting BF16 values may differ slightly. Over many transformer layers and decoding rounds, these differences can eventually change a close argmax, causing temperature-zero speculative decoding to diverge from ordinary autoregressive decoding.

The underlying numerical fix belongs in MLX. Swift applications also need a supported way to enable and configure that behavior without relying exclusively on process environment variables.

Changes

This PR:

  • Updates the pinned MLX dependency with batch-invariant Metal matmul and SDPA execution.
  • Updates mlx-c with the corresponding setter and getter.
  • Exposes the setting through MLX-Swift:
GPU.batchInvariantLimit = 4
  • Adds exact BF16 tests comparing:
    • Short-block matmul against single-row matmul.
    • Multi-query causal SDPA against the equivalent single-query SDPA.
  • Documents that the setting is process-wide, defaults to zero, and can reduce performance when enabled.

For MTP speculative decoding, the limit should cover blockSize. For conventional speculative decoding, it should cover the complete verification width, normally numDraftTokens + 1.

Dependencies

The MLX and mlx-c dependency changes must land first. After they are merged, this PR’s submodule pointers should be updated to the final upstream commit SHAs if either dependency is squash-merged.

Checklist

Put an x in the boxes that apply.

@davidkoski

Copy link
Copy Markdown
Member

If we use #450 as the PR to pick up new mlx/mlx-c, this will likely sit on top of that. That requires that mlx-c expose the correct API

@aleroot

aleroot commented Aug 25, 2026

Copy link
Copy Markdown
Contributor Author

Looks like MLX team does not want to support anything like this. They closed the PR downstream, no sense to keep this open.

@aleroot aleroot closed this Aug 25, 2026
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