Repository navigation
[Metal] Keep SDPA VJP scores in float32 for half precision inputs - #4910
Merged
Merged
Conversation
The fused backward rebuilds P = exp(scale * S - lse) from the score tile S and the float32 lse of the forward. S was stored in the input dtype, so for bfloat16 the rounding of large scores went into the exponent, and for float16 S could overflow while the scaled scores still fit. Compute S with the float32 matmul on float32 copies of the Q and K tiles and keep it in float32. dS is written over dP instead of S. Fixes ml-explore#4904
zcbenz
force-pushed
the
sdpa-vjp-fp32-scores
branch
from
November 23, 2026 01:08
1c11749 to
e1ec592
Compare
zcbenz
force-pushed
the
sdpa-vjp-fp32-scores
branch
from
November 23, 2026 01:11
e1ec592 to
75f440e
Compare
zcbenz
approved these changes
Nov 23, 2026
Open
2 of 4 tasks
1 task
rcfa
pushed a commit
to cubiculum-ai/mlx
that referenced
this pull request
Nov 26, 2026
…-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)
This was referenced Nov 29, 2026
Lumonopolis
added a commit
to Lumonopolis/modellab
that referenced
this pull request
Nov 30, 2026
What: Preserve score reasons, omit unscored/excluded epochs, retain zeroed failed attempts, reject infinite scores and disable baselines for zeroed scores. Add real-log regression coverage and documentation. Update only MLX/MLX-Metal to 0.32.5, Inspect AI to 0.3.292 and OpenAI SDK to 3.59.0. Why: Canonical Inspect NaN scores poisoned report means. Released upstream fixes address Metal attention gradients, evaluation parsing/logging and credentials exposed by SDK exceptions without a trainer migration. Next: Run guarded real-model fit, memory and exact-resume checks before promotion/deployment. Use a quiet window and retain old environments for existing checkpoints that require exact continuation. Risk: MLX kernels can change results; GPU and remote-host behavior remain unverified. This is staged work only. CPU suite: 218 passed, 34 skipped; four staged report integrations passed; Python 3.11 report units passed. Independent review and rendered report checks passed. No live changes. Ref: docs/evaluation.md; ml-explore/mlx#4910; https://github.com/UKGovernmentBEIS/inspect_ai/releases/tag/0.3.292 Co-authored-by: Lumonopolis <Lumonopolis@users.noreply.github.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.
Fix half precision SDPA backward gradients at large scores
Problem
The fused Metal backward pass for
mx.fast.scaled_dot_product_attentionproduces incorrect gradients with bf16/fp16 inputs when attention scores become large, even though forward output remains correct.The issue comes from storing
S = Q @ K.Tin the input dtype before reconstructing attention probabilities withexp(scale * S - lse). Rounding errors in the scores are amplified by the exponential, and fp16 scores can overflow before scaling.Fix
compute the score matmul using float32 Q and K tiles and keep the resulting scores in float32. The remaining backward computations retain their existing precision.
The dS output reuses the dP buffer to avoid additional allocation.
Validation
The regression test covers bf16/fp16, causal and unmasked attention, GQA, irregular tile sizes, and all three gradients (dQ, dK, dV).
All 12 subtests fail on unmodified
main: bf16 gradient errors range from 668× to 80,818×, while fp16 produces inf/NaN. All of 12 pass with the fix.On the std=30 reproducer from #4904, the bf16 dV norm changes from
2.009e10to392.8, compared with392.4for the float32 reference.Float32 gradients remain bit-identical to
main.Performance
Benchmarked on an Apple M1 Pro (16 GB), running the same benchmark separately against unmodified
mainand this branch.Benchmark script: bench_vjp.py
Run command:
python bench_vjp.py --iters 15The ratios below are patched execution time divided by
main(higher than 1 means slower):Additional temporary memory applies only to bf16/fp16: approximately +74–84 MB at B=1 with 32 heads, and up to +192 MB at B=4 with 16 heads. Float32 memory usage is unchanged.
The change is Metal-only and does not modify CUDA. M5 hardware has not been tested.
Fixes #4904