Skip to content

Integrate the upstream fused Metal SDPA backward with its follow-up fixes, and keep attention sinks off it - #61

Merged
jjang-ai merged 7 commits into
osaurus-ai:mainfrom
rcfa:apple/r3-metal-sdpa-vjp
Nov 28, 2026
Merged

jjang-ai merged 7 commits into
osaurus-ai:mainfrom
rcfa:apple/r3-metal-sdpa-vjp

Conversation

@rcfa

@rcfa rcfa commented Nov 26, 2026

Copy link
Copy Markdown

Branch apple/r3-metal-sdpa-vjp, 7 commits on origin/main 23f364e.

Bring in Apple's fused Metal backward for scaled_dot_product_attention (ml-explore/mlx PR 4563, first in v0.32.4)
and the round-3 commits that patch it or its routing: part of ml-explore#4929, ml-explore#4893, part of ml-explore#4927, and ml-explore#4910. The code of these
five is Apple's and its contributors': each commit is a git cherry-pick -x of the upstream commit, with the upstream
author kept and the (cherry picked from commit …) line recording provenance. The last two commits are ours: a test
and a fix for a regression that ml-explore#4563 brings to this fork (attention sinks under training, see below).

Why we push them: on origin/main, the Metal SDPA backward is throw "NYI" and training forces the unfused forward.
ml-explore#4910, ml-explore#4893 and parts of ml-explore#4927 and ml-explore#4929 change code that only exists after ml-explore#4563, so they come with it.

Behaviour change: since ml-explore#4563, training on Metal (under grad) runs the fused forward with a logsumexp and the fused
backward for float32, float16 and bfloat16, causal or no mask. vmlx-swift's LoRA and DoRA training changes path.
MLX_SDPA_VJP_FALLBACK=1 restores the unfused backward.

Included, in upstream order:

Upstream Commit Here What it fixes
ml-explore#4563 83b976e 8969d04 Metal had no fused SDPA backward: ScaledDotProductAttentionVJP::eval_gpu threw NYI, and training forced the unfused forward. Adds blocked backward kernels (dq, dk, dv; float32, float16, bfloat16; no array mask, no sinks), lets the full-attention forward write the logsumexp, and routes training on Metal to the fused forward and backward. Applies cleanly.
ml-explore#4929 777d741 fad73c4 Only the Metal SDPA VJP hunk here: with an empty q or k the fused backward now fills the gradients with zeros. The rest of ml-explore#4929 is in apple/r3-core.
ml-explore#4893 8e98fb8 4eecadd On NAX GPUs, causal or masked attention with head dim 256, float16 or bfloat16, 512 to 1023 query rows and B·H ≥ 8 took the unfused path; it now takes the fused kernel. Head dim 512 on NAX now also takes array masks. Routing on GPUs without NAX is unchanged.
ml-explore#4927 58d91ee f8ba5a3 Only the part without the window size here: the SDPA VJP threw for gradients of the mask or the sinks, and its fallback got the forward output and logsumexp as extra primals and returned all their gradients. Such gradients now go to Custom::vjp, and the fallback takes the primals only and returns the gradients of q, k and v. Adds test_sdpa_grad_sinks_and_nested, without windows.
ml-explore#4910 25f42f6 2b658bd The fused backward stored the scores S = Q·Kᵀ in the input's half precision, so large scores overflowed (float16) or lost precision when it rebuilt P = exp(scale·S − lse), and the gradients blew up. S, and for half-precision inputs the Q and K operands, are now float32. Adds a test.

Our commits

Commit What it does
8a335fe Test test_sdpa_grad_q_with_sinks: the gradient of q alone, with attention sinks and a causal mask, against a float32 reference on the CPU. The gradient of the sinks is not requested, so the fused backward is not bypassed.
99160df Fix: the fused Metal backward does not compute attention sinks; it throws "NYI: attention sinks". Since ml-explore#4563, training on Metal takes the fused forward with its logsumexp, so the gradient of q with sinks reached that throw; unfused training, as before ml-explore#4563, computed it. ScaledDotProductAttentionVJP::use_fallback now also takes has_sinks. On Metal, sinks choose the fallback: the forward then gives no logsumexp, and the vjp goes through Custom::vjp. CUDA's fused backward handles sinks, so CUDA ignores the argument. Apple's main routes the same way as ml-explore#4563.

Not included here: the window-size part of ml-explore#4927 (cuDNN window masks, window_size_ in the VJP primitive) needs
ml-explore/mlx PR 4734, which the fork holds back because it changes the C/Swift contract. The other round-3 commits
are in apple/r3-core, apple/r3-metal, apple/r3-cuda, apple/r3-python-docs-build, apple/r3-affine-qmv and
apple/fixes-2. Left out of the batch, by ml-explore/mlx PR number: 4903 (the same fix as the fork's #17, no test);
4887, 4883, 4801, 4781 and the NAX parts of the affine qmv_mma commits, 4734, 4647.

Conflict resolutions

Overlaps

None with the batch's other branches (merge-tree). ml-explore#4893 moved here from apple/r3-metal for that reason: Apple
applied it on top of ml-explore#4563.

Validation

Compared with main (23f364e), built and run the same way:

  • Linux arm64 (container vmlx-arm64, clang Release, Highway), C++ suite on the CPU.

  • macOS (M4 Max, Release, Metal on), C++ suite (tests/tests) on the CPU and on Metal.

  • Python (macOS, Python 3.14.5): test_fast_sdpa on the GPU with this branch; and the 16 test modules the batch
    touches, on the GPU and with DEVICE=cpu, on main and on the integration tree 63ac1f9df (origin/main with all
    batch branches merged; it has this branch up to 2b658bd, without our two commits).

  • Linux: 412 of 412 cases pass at the tip, as main.

  • macOS: 390 of 390 cases pass on the CPU and on Metal at the tip, as main.

  • Python, the sinks regression: at 8a335fe (the test, before the fix) test_sdpa_grad_q_with_sinks errors with
    NYI: attention sinks; main computes that gradient (unfused; relative error 6e-4). At the tip test_fast_sdpa
    gives 32 ok on the GPU (3 skip: CUDA, NAX, value dims).

  • Python, integration tree: no test that passes on main fails. GPU: main fails 3 tests, the integration tree 1
    (test_input_dilation_grad, as main). CPU: both fail the same 4 (GPU-only tests that do not skip on the CPU, one
    of them in test_fast_sdpa, and the Winograd budget). All new tests of the batch pass: 27 on the GPU, 85 on the CPU
    (the rest skip). main's CPU run stops at test_reduce: test_init_reduce_large_output (from ml-explore/mlx PR
    4437) crashes it with SIGSEGV, the overflow that this batch's fix/reduce-int64-loops fixes. So test_reduce,
    test_threads, test_vmap and test_zero_copy have no main CPU result; on the integration tree none of their
    tests fails on the CPU.

  • Not run: a GPU with NAX (Use fused SDPA for causal head_dim 256 with 512 to 1023 query rows ml-explore/mlx#4893's routing and head dim 512 with array masks); test_fast_sdpa with DEVICE=cpu at
    the tip; vmlx-swift training through the fused backward.

Validation of the batch in shared

This batch's PRs but the last (fix/float-floor-divide, which came out of this validation), merged together on
main 23f364e with the two overlap resolutions (apple/fixes-2 and apple/r3-core in
python/tests/test_quantized.py; apple/r3-core and apple/fixes-3 in mlx/allocator.h), are mlx 8de1a51; vmlx-swift 31458a0d3 builds on it (osaurus-ai/vmlx-swift main bbd237750 with our open vmlx-swift
patches). Built and run, compared with main:

  • macOS (M4 Max, Release, Metal on): C++ suite 410 of 410 on the CPU and on Metal. vmlx-swift builds for macOS 14.0;
    its suite (swift test --no-parallel, 1046 tests) fails no test that passes on its main.
  • Linux arm64 and amd64 (containers, clang Release, Highway): C++ suite 431 of 431 on both (main 412 of 412).
    vmlx-swift's Linux CI steps pass: VMLXLinuxTests 37 of 37, the CPU kernel tests 61 of 61 at both thread settings.
  • Linux, the CI-equivalent Python run (osaurus-ai's Linux job, built and run the same way: GCC, Debug, Highway,
    DEVICE=cpu, python/tests module by module, torch 2.15 for the CPU). arm64: main 881 pass, 92 skip, 2 fail;
    the batch 906 pass, 96 skip, 2 fail (tree c43a37eec, which differs from 8de1a51 only in a C++ test). amd64: main
    882 pass, 92 skip, 1 fail; the batch 906 pass, 96 skip, 1 fail, 1 error. No test that passes on main fails on the batch. The failures are
    main's own: test_compile_sigmoid_matches_eager (bfloat16: the compiled CPU sigmoid is less accurate than the
    eager Highway kernel) and, on arm64 only, bfloat16 test_torch_conv_2D, where torch 2.15's own aarch64 bfloat16
    conv2d is off by up to 8.8 against float64 (MLX is within 0.06). test_async_eval_error_in_synchronize failed once on amd64; it fails about 1 run in 5 there on main too: the error it expects from synchronize can come from async_eval (the same code is on ml-explore/mlx main).
  • Three tests of main fail at random, on every branch alike, because they draw unseeded inputs or race:
    test_double.TestDouble.test_unary_ops in about 8% of runs (float32 erf is accurate to 1.5e-7 absolute, which
    misses rtol 1e-5 near 0 against the fork's accurate float64 erf); test_ops.TestOps.test_divmod in about 1%
    (the float16 quotient is off by one when a / b rounds up to an integer, e.g. 73.625 / 1.248 = 58.99 gives 59;
    ml-explore/mlx main has the same code); and, on amd64, test_async_eval_error_in_synchronize (above). This batch's
    fix/float-floor-divide fixes the second; the first gets a PR of its own.
  • osaurus-ai/mlx's GitHub Actions have not run since 2026-10-08, so this PR shows no checks; the runs above follow
    its Linux and macOS jobs.
  • This branch alone, the same Linux Python run (arm64): 883 pass, 93 skip, 2 fail: test_compile_sigmoid_matches_eager, test_torch_conv_2D as on main.

🤖 Generated with Claude Code

tpegolotti and others added 7 commits November 24, 2026 10:43
osaurus-ai/mlx takes here only the hunk for the fused Metal SDPA backward, which ml-explore#4563 brings.
The rest of this commit is on apple/r3-core.
(cherry picked from commit 777d741)
…l-explore#4893)

Co-authored-by: Jeroen van Menen <235760+jvmenen@users.noreply.github.com>
Co-authored-by: Cheng <git@zcbenz.com>
(cherry picked from commit 8e98fb8)
osaurus-ai/mlx takes only the part of this commit that is independent of the window size: the
VJP fallback (gradients of the mask or the sinks, and the fallback's primals) and the gradient
test, without windows. The window size needs ml-explore#4734, which osaurus-ai/mlx does not take.

Ported: Apple's commit adds `|| other_grads` to an `if (outputs.size() != 2)` that came
upstream with ml-explore/mlx PR 4565, which the fork does not have. So this commit also adds
that check: without the logsumexp output, the VJP takes the fallback. The fused Metal backward
needs that output.

(cherry picked from commit 58d91ee)
…-explore#4910)

Co-authored-by: Cheng <git@zcbenz.com>
Ported: the test sets MLX_SDPA_VJP_FALLBACK, MLX_SDPA_VJP_BQ and
MLX_SDPA_VJP_BK with mock.patch.dict(os.environ) in place of
mx.config.scoped_update: the config module (ml-explore/mlx PR 4647) is
not in the fork, and env::get_var reads them at each call.
scaled_dot_product_attention.cpp also includes <algorithm>, which
Apple's file already does.

(cherry picked from commit 25f42f6)
The gradient of q alone, with sinks: the gradient of the sinks is not
requested, so the fused backward is not bypassed. On Metal, training now
takes the fused forward with logsumexp, and the fused backward throws
"NYI: attention sinks".
The fused Metal backward does not compute attention sinks: it throws
"NYI: attention sinks". Since ml-explore#4563, training on Metal takes the fused
forward with its logsumexp, so the gradient of q with sinks reached that
throw. Unfused training, as before ml-explore#4563, computed it.

ScaledDotProductAttentionVJP::use_fallback now also takes has_sinks. On
Metal, sinks choose the fallback: the forward then gives no logsumexp,
and the vjp goes through Custom::vjp. CUDA's fused backward handles
sinks, so CUDA ignores the argument.
@jjang-ai
jjang-ai merged commit f2596be into osaurus-ai:main Nov 28, 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.

7 participants