From 6cdd2a2548f184dcdc1561807b508adff1e73ac4 Mon Sep 17 00:00:00 2001 From: Gajesh Naik <26431906+Gajesh2007@users.noreply.github.com> Date: Sun, 6 Sep 2026 14:28:56 -0700 Subject: [PATCH] Keep vector SDPA partial accumulation in FP32 --- .../scaled_dot_product_attention.metal | 6 +-- mlx/backend/metal/kernels/sdpa_vector.h | 12 ++--- .../metal/scaled_dot_product_attention.cpp | 7 +-- python/tests/test_fast_sdpa.py | 47 +++++++++++++++++++ 4 files changed, 60 insertions(+), 12 deletions(-) diff --git a/mlx/backend/metal/kernels/scaled_dot_product_attention.metal b/mlx/backend/metal/kernels/scaled_dot_product_attention.metal index 187e6fffca..cfe5aec6c3 100644 --- a/mlx/backend/metal/kernels/scaled_dot_product_attention.metal +++ b/mlx/backend/metal/kernels/scaled_dot_product_attention.metal @@ -9,7 +9,7 @@ using namespace metal; // SDPA vector instantiations #define instantiate_sdpa_vector_aggregation(type, value_dim) \ instantiate_kernel( \ - "sdpa_vector_2pass_2_" #type "_" #value_dim, \ + "sdpa_vector_2pass_fp32partials_2_" #type "_" #value_dim, \ sdpa_vector_2pass_2, \ type, \ value_dim) @@ -22,7 +22,7 @@ using namespace metal; qk_dim, \ value_dim) \ instantiate_kernel( \ - "sdpa_vector_2pass_1_" #type "_" #qk_dim "_" #value_dim, \ + "sdpa_vector_2pass_fp32partials_1_" #type "_" #qk_dim "_" #value_dim, \ sdpa_vector_2pass_1, \ type, \ qk_dim, \ @@ -30,7 +30,7 @@ using namespace metal; #define instantiate_sdpa_vector_gqa(type, qk_dim, value_dim, hpt) \ instantiate_kernel( \ - "sdpa_vector_2pass_1_gqa_" #type "_" #qk_dim "_" #value_dim, \ + "sdpa_vector_2pass_fp32partials_1_gqa_" #type "_" #qk_dim "_" #value_dim, \ sdpa_vector_2pass_1_gqa, \ type, \ qk_dim, \ diff --git a/mlx/backend/metal/kernels/sdpa_vector.h b/mlx/backend/metal/kernels/sdpa_vector.h index 3f40dbd7c0..3631e49daa 100644 --- a/mlx/backend/metal/kernels/sdpa_vector.h +++ b/mlx/backend/metal/kernels/sdpa_vector.h @@ -181,7 +181,7 @@ template const device T* queries [[buffer(0)]], const device T* keys [[buffer(1)]], const device T* values [[buffer(2)]], - device T* out [[buffer(3)]], + device float* out [[buffer(3)]], device float* sums [[buffer(4)]], device float* maxs [[buffer(5)]], const constant int& N [[buffer(7)]], @@ -313,7 +313,7 @@ template } for (int i = 0; i < v_per_thread; i++) { - out[i] = static_cast(o[i]); + out[i] = o[i]; } } @@ -327,7 +327,7 @@ template const device T* queries [[buffer(0)]], const device T* keys [[buffer(1)]], const device T* values [[buffer(2)]], - device T* out [[buffer(3)]], + device float* out [[buffer(3)]], device float* sums [[buffer(4)]], device float* maxs [[buffer(5)]], const constant int& N [[buffer(7)]], @@ -449,10 +449,10 @@ template } const int o_offset = base_head + g; - device T* op = + device float* op = out + o_offset * blocks * V + block_idx * V + simd_lid * v_per_thread; for (int i = 0; i < v_per_thread; i++) { - op[i] = static_cast(acc[i]); + op[i] = acc[i]; } if (simd_lid == 0) { sums[o_offset * blocks + block_idx] = denom; @@ -462,7 +462,7 @@ template template [[kernel]] void sdpa_vector_2pass_2( - const device T* partials [[buffer(0)]], + const device float* partials [[buffer(0)]], const device float* sums [[buffer(1)]], const device float* maxs [[buffer(2)]], device T* out [[buffer(3)]], diff --git a/mlx/backend/metal/scaled_dot_product_attention.cpp b/mlx/backend/metal/scaled_dot_product_attention.cpp index 981d2b1817..c2ee37f29e 100644 --- a/mlx/backend/metal/scaled_dot_product_attention.cpp +++ b/mlx/backend/metal/scaled_dot_product_attention.cpp @@ -465,7 +465,7 @@ void sdpa_vector_2pass( // Set the kernel name std::string kname; kname.reserve(64); - kname += "sdpa_vector_2pass_1"; + kname += "sdpa_vector_2pass_fp32partials_1"; if (!mask && !sinks && q.shape(2) == 1 && q.shape(1) == 8 * k.shape(1) && q.shape(-1) == v.shape(-1) && (q.shape(-1) == 64 || q.shape(-1) == 128) && k.shape(2) >= 8192) { @@ -535,7 +535,8 @@ void sdpa_vector_2pass( intermediate_shape.end(), out.shape().begin(), out.shape().end() - 1); intermediate_shape.push_back(blocks); intermediate_shape.push_back(out.shape().back()); - array intermediate(intermediate_shape, q.dtype(), nullptr, {}); + // Keep unnormalized partials in float until the final reduction. + array intermediate(intermediate_shape, float32, nullptr, {}); intermediate_shape.pop_back(); array sums(intermediate_shape, float32, nullptr, {}); array maxs(std::move(intermediate_shape), float32, nullptr, {}); @@ -607,7 +608,7 @@ void sdpa_vector_2pass( // Final pass kname.clear(); - kname = "sdpa_vector_2pass_2_"; + kname = "sdpa_vector_2pass_fp32partials_2_"; kname += get_type_string(q.dtype()); kname += "_"; kname += std::to_string(v.shape(-1)); diff --git a/python/tests/test_fast_sdpa.py b/python/tests/test_fast_sdpa.py index b11ce884e5..539cd838f4 100644 --- a/python/tests/test_fast_sdpa.py +++ b/python/tests/test_fast_sdpa.py @@ -2,6 +2,7 @@ import os import unittest from itertools import product +from unittest.mock import patch import mlx.core as mx import mlx_tests @@ -356,6 +357,52 @@ def test_sdpa_vector_gqa_long(self): out = mx.fast.scaled_dot_product_attention(q, k, v, scale=scale) self.assertTrue(mx.allclose(ref, out, atol=1e-4, rtol=1e-4)) + @unittest.skipIf(not mx.is_available(mx.gpu), "GPU kernel path only") + def test_sdpa_two_pass_partial_cancellation(self): + # Uniform attention has the exact output 1 / L. Casting an + # unnormalized block sum to the input dtype loses the residual 1. + L = 8192 + for dtype, D, blocks, masked in product( + (mx.bfloat16, mx.float16, mx.float32), + (64, 128, 256), + (32, 128), + (False, True), + ): + with self.subTest(dtype=dtype, D=D, blocks=blocks, masked=masked): + amplitude = 2048 if dtype == mx.float16 else 256 + values = np.zeros((1, 1, L, D), dtype=np.float32) + values[:, :, 0, :] = amplitude + # D64/D128 without a mask uses contiguous GQA chunks. + gqa = D in (64, 128) and not masked + values[:, :, 1 if gqa else blocks, :] = 1 + values[:, :, L - 1 if gqa else 1, :] = -amplitude + q = mx.zeros((1, 8, 1, D), dtype=dtype) + k = mx.zeros((1, 1, L, D), dtype=dtype) + v = mx.array(values, dtype=dtype) + mask = mx.ones((L,), dtype=mx.bool_) if masked else None + with patch.dict(os.environ, MLX_SDPA_BLOCKS=str(blocks)): + out = mx.fast.scaled_dot_product_attention( + q, k, v, scale=1, mask=mask + ) + mx.eval(out) + self.assertEqual(out.dtype, dtype) + self.assertTrue(mx.array_equal(out, mx.full(out.shape, 1 / L, dtype))) + + @unittest.skipIf(not mx.is_available(mx.gpu), "GPU kernel path only") + def test_sdpa_two_pass_partial_overflow(self): + # The final mean is representable in FP16, but its partial sums are not. + L = 8192 + for D, blocks in product((64, 128, 256), (32, 128)): + with self.subTest(D=D, blocks=blocks): + q = mx.zeros((1, 8, 1, D), dtype=mx.float16) + k = mx.zeros((1, 1, L, D), dtype=mx.float16) + v = mx.full((1, 1, L, D), 32768, dtype=mx.float16) + with patch.dict(os.environ, MLX_SDPA_BLOCKS=str(blocks)): + out = mx.fast.scaled_dot_product_attention(q, k, v, scale=1) + mx.eval(out) + self.assertTrue(mx.all(mx.isfinite(out))) + self.assertTrue(mx.array_equal(out, mx.full(out.shape, 32768, mx.float16))) + def test_sdpa_fully_masked(self): Lkv = 8 mask = mx.array(False)