Skip to content

[Metal] Keep SDPA VJP scores in float32 for half precision inputs - #4910

Merged
zcbenz merged 2 commits into
ml-explore:mainfrom
arhaamatiq:sdpa-vjp-fp32-scores
Nov 23, 2026
Merged

zcbenz merged 2 commits into
ml-explore:mainfrom
arhaamatiq:sdpa-vjp-fp32-scores

Conversation

@arhaamatiq

Copy link
Copy Markdown
Contributor

Fix half precision SDPA backward gradients at large scores

Problem

The fused Metal backward pass for mx.fast.scaled_dot_product_attention produces 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.T in the input dtype before reconstructing attention probabilities with exp(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.009e10 to 392.8, compared with 392.4 for 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 main and this branch.

Benchmark script: bench_vjp.py

Run command: python bench_vjp.py --iters 15

The ratios below are patched execution time divided by main (higher than 1 means slower):

Dtype Median ratio Range / maximum
bf16 1.01× 0.94–1.04×
fp16 1.05× Max 1.08×
float32 0.99× Effectively unchanged

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

  • ☑️ I understand it is strictly prohibited to use AI to write PR description
  • AI usage disclosure: Claude Code was used to assist with code generation, regression tests, and benchmarking. I reviewed changes and verified reported results locally.

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
zcbenz force-pushed the sdpa-vjp-fp32-scores branch from 1c11749 to e1ec592 Compare November 23, 2026 01:08
@zcbenz
zcbenz force-pushed the sdpa-vjp-fp32-scores branch from e1ec592 to 75f440e Compare November 23, 2026 01:11
@zcbenz
zcbenz merged commit 25f42f6 into ml-explore:main Nov 23, 2026
24 checks passed
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)
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>
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.

[BUG] mx.fast.scaled_dot_product_attention: half-precision gradients are wrong at large attention scores since 0.32.4

2 participants