Repository navigation
Integrate the upstream fused Metal SDPA backward with its follow-up fixes, and keep attention sinks off it - #61
Merged
Conversation
(cherry picked from commit 83b976e)
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.
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.
Branch
apple/r3-metal-sdpa-vjp, 7 commits onorigin/main23f364e.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 -xof the upstream commit, with the upstreamauthor kept and the
(cherry picked from commit …)line recording provenance. The last two commits are ours: a testand 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 isthrow "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 fusedbackward for float32, float16 and bfloat16, causal or no mask. vmlx-swift's LoRA and DoRA training changes path.
MLX_SDPA_VJP_FALLBACK=1restores the unfused backward.Included, in upstream order:
ScaledDotProductAttentionVJP::eval_gputhrew 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.apple/r3-core.Custom::vjp, and the fallback takes the primals only and returns the gradients of q, k and v. Addstest_sdpa_grad_sinks_and_nested, without windows.Our commits
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.ScaledDotProductAttentionVJP::use_fallbacknow also takeshas_sinks. On Metal, sinks choose the fallback: the forward then gives no logsumexp, and the vjp goes throughCustom::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) needsml-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-qmvandapple/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
ScaledDotProductAttentionVJP::eval_gpuhunk, for the backward that Adding VJP for the scaled dot product attention. ml-explore/mlx#4563 brings (noted in thecommit message).
mlx/backend/metal/scaled_dot_product_attention.cpp: the added and removed lines equal Apple's. Theconflict was context: the fork keeps its
elsebranch for 8 or fewer query rows (qhd == vhd && qhd == 192) and doesnot take Apple's newer split-attention block there.
mlx/fast.cpp: only the VJP hunk, withoutwindow_size_(theother_gradsfallback,inputs.end() - 3,the first 3 vjps returned).
python/tests/test_fast_sdpa.py: onlytest_sdpa_grad_sinks_and_nested, without thewindow cases. The CUDA SDPA and
fast_primitives.hhunks are not taken. Noted in the commit message.python/tests/test_fast_sdpa.py: the test setsMLX_SDPA_VJP_FALLBACK,MLX_SDPA_VJP_BQandMLX_SDPA_VJP_BKwithmock.patch.dict(os.environ)in place ofmx.config.scoped_update(the config module,ml-explore/mlx PR 4647, is not in the fork);
env::get_varreads them at each eval.mlx/fast.cpp: Apple's commit adds|| other_gradsto an existingif (outputs.size() != 2), which cameupstream with ml-explore/mlx PR 4565 (the gated-delta VJP, not in the fork). The port adds the whole
if (outputs.size() != 2 || other_grads): without the logsumexp output, the VJP takes the fallback. The fix forattention sinks below depends on it.
mlx/backend/metal/scaled_dot_product_attention.cpp: the port also adds#include <algorithm>(forstd::min), which Apple's file already has.Overlaps
None with the batch's other branches (merge-tree). ml-explore#4893 moved here from
apple/r3-metalfor that reason: Appleapplied 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_sdpaon the GPU with this branch; and the 16 test modules the batchtouches, on the GPU and with
DEVICE=cpu, onmainand on the integration tree 63ac1f9df (origin/mainwith allbatch 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_sinkserrors withNYI: attention sinks;maincomputes that gradient (unfused; relative error 6e-4). At the tiptest_fast_sdpagives 32 ok on the GPU (3 skip: CUDA, NAX, value dims).
Python, integration tree: no test that passes on
mainfails. GPU:mainfails 3 tests, the integration tree 1(
test_input_dilation_grad, asmain). CPU: both fail the same 4 (GPU-only tests that do not skip on the CPU, oneof 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 attest_reduce:test_init_reduce_large_output(from ml-explore/mlx PR4437) crashes it with SIGSEGV, the overflow that this batch's
fix/reduce-int64-loopsfixes. Sotest_reduce,test_threads,test_vmapandtest_zero_copyhave nomainCPU result; on the integration tree none of theirtests 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_sdpawithDEVICE=cpuatthe tip; vmlx-swift training through the fused backward.
Validation of the batch in
sharedThis batch's PRs but the last (
fix/float-floor-divide, which came out of this validation), merged together onmain23f364e with the two overlap resolutions (apple/fixes-2andapple/r3-coreinpython/tests/test_quantized.py;apple/r3-coreandapple/fixes-3inmlx/allocator.h), are mlx 8de1a51; vmlx-swift 31458a0d3 builds on it (osaurus-ai/vmlx-swiftmainbbd237750 with our open vmlx-swiftpatches). Built and run, compared with
main:its suite (
swift test --no-parallel, 1046 tests) fails no test that passes on itsmain.main412 of 412).vmlx-swift's Linux CI steps pass:
VMLXLinuxTests37 of 37, the CPU kernel tests 61 of 61 at both thread settings.DEVICE=cpu,python/testsmodule by module, torch 2.15 for the CPU). arm64:main881 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:
main882 pass, 92 skip, 1 fail; the batch 906 pass, 96 skip, 1 fail, 1 error. No test that passes on
mainfails on the batch. The failures aremain's own:test_compile_sigmoid_matches_eager(bfloat16: the compiled CPU sigmoid is less accurate than theeager Highway kernel) and, on arm64 only, bfloat16
test_torch_conv_2D, where torch 2.15's own aarch64 bfloat16conv2d is off by up to 8.8 against float64 (MLX is within 0.06).
test_async_eval_error_in_synchronizefailed once on amd64; it fails about 1 run in 5 there onmaintoo: the error it expects fromsynchronizecan come fromasync_eval(the same code is on ml-explore/mlx main).mainfail at random, on every branch alike, because they draw unseeded inputs or race:test_double.TestDouble.test_unary_opsin about 8% of runs (float32erfis accurate to 1.5e-7 absolute, whichmisses
rtol1e-5 near 0 against the fork's accurate float64erf);test_ops.TestOps.test_divmodin about 1%(the float16 quotient is off by one when
a / brounds 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'sfix/float-floor-dividefixes the second; the first gets a PR of its own.its Linux and macOS jobs.
test_compile_sigmoid_matches_eager,test_torch_conv_2Das onmain.🤖 Generated with Claude Code