From 96f45853a94b0826d72612ad931f662b3b184033 Mon Sep 17 00:00:00 2001 From: Ankit Gala <204639277+ankitgala007@users.noreply.github.com> Date: Fri, 27 Nov 2026 01:48:38 -0800 Subject: [PATCH 1/2] Zero attention weights of fully masked rows in the SDPA fallback A boolean mask that leaves a query row with no visible key filled every score with finfo.min, so the softmax was uniform and the fallback returned mean(V), while the fused kernels return 0 and the VJP disagreed with both. Zero the weights of such rows after the softmax so the output and its gradient are zero on every path. --- mlx/fast.cpp | 11 +++++++++++ python/tests/test_fast_sdpa.py | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+) diff --git a/mlx/fast.cpp b/mlx/fast.cpp index 3aa60286e4..076f129fa3 100644 --- a/mlx/fast.cpp +++ b/mlx/fast.cpp @@ -843,6 +843,10 @@ array scaled_dot_product_attention( v = expand_dims(v, 2, s); } auto scores = matmul(q, swapaxes(k, -1, -2, s), s); + // Rows where a boolean mask leaves no key visible. Their weights are + // zeroed after the softmax so the output and its gradient are zero, as + // in the fused kernels, instead of a uniform average over the keys. + std::optional has_visible_key; if (has_arr_mask || do_causal || window_size > 0) { // Mask must be broadcast-compatible with [B, n_q_heads, L_q, L_kv] auto make_or_fetch_mask = [&]() { @@ -893,6 +897,9 @@ array scaled_dot_product_attention( } } if (mask.dtype() == bool_) { + if (!has_sinks) { + has_visible_key = any(mask, -1, true, s); + } scores = where( mask, scores, array(finfo(scores.dtype()).min, scores.dtype()), s); } else { @@ -911,6 +918,10 @@ array scaled_dot_product_attention( scores = concatenate({broadcast_to(sinks, bsx_shape, s), scores}, -1, s); } scores = softmax(scores, std::vector{-1}, true, s); + if (has_visible_key) { + scores = + where(*has_visible_key, scores, array(0, scores.dtype()), s); + } if (has_sinks) { // Slice off scores auto start = Shape(scores.ndim(), 0); diff --git a/python/tests/test_fast_sdpa.py b/python/tests/test_fast_sdpa.py index 5229c8b301..dded2f6cfb 100644 --- a/python/tests/test_fast_sdpa.py +++ b/python/tests/test_fast_sdpa.py @@ -775,6 +775,39 @@ def test_sdpa_fully_masked(self): out = mx.fast.scaled_dot_product_attention(q, k, v, mask=mask, scale=1) self.assertFalse(mx.any(mx.isnan(out))) + def test_sdpa_fully_masked_row(self): + # A query row with no visible key gives zero output and zero gradient + # on every path, and the other rows are unaffected. + mx.random.seed(0) + L = 4 + mask = mx.ones((1, 1, L, L), dtype=mx.bool_) + mask[..., 1, :] = False + for D in [32, 64, 80, 128]: + q = mx.random.normal(shape=(1, 2, L, D)) + k = mx.random.normal(shape=(1, 2, L, D)) + v = mx.random.normal(shape=(1, 2, L, D)) + scale = 1.0 / D**0.5 + + out = mx.fast.scaled_dot_product_attention( + q, k, v, scale=scale, mask=mask + ) + ref = mlx_primitives_sdpa(q, k, v, scale=scale, mask=None) + self.assertTrue(mx.array_equal(out[..., 1, :], mx.zeros_like(out[..., 1, :]))) + for i in (0, 2, 3): + self.assertTrue( + mx.allclose(out[..., i, :], ref[..., i, :], atol=1e-4, rtol=1e-4) + ) + + def loss(q, k, v): + return mx.fast.scaled_dot_product_attention( + q, k, v, scale=scale, mask=mask + )[..., 1, :].sum() + + dq, dk, dv = mx.grad(loss, argnums=(0, 1, 2))(q, k, v) + for g in (dq, dk, dv): + self.assertFalse(mx.any(mx.isnan(g))) + self.assertEqual(mx.abs(g).max().item(), 0.0) + def test_sdpa_inf_score(self): Lkv = 8 for D in [4, 128]: From f8eca067a0d69921dcefa6b64d0bb6c74c06b319 Mon Sep 17 00:00:00 2001 From: Cheng Date: Sat, 28 Nov 2026 09:03:14 +0900 Subject: [PATCH 2/2] nit --- mlx/fast.cpp | 7 ++--- python/tests/test_fast_sdpa.py | 48 +++++++++++++++++++--------------- 2 files changed, 29 insertions(+), 26 deletions(-) diff --git a/mlx/fast.cpp b/mlx/fast.cpp index 076f129fa3..d49b0a5518 100644 --- a/mlx/fast.cpp +++ b/mlx/fast.cpp @@ -843,9 +843,6 @@ array scaled_dot_product_attention( v = expand_dims(v, 2, s); } auto scores = matmul(q, swapaxes(k, -1, -2, s), s); - // Rows where a boolean mask leaves no key visible. Their weights are - // zeroed after the softmax so the output and its gradient are zero, as - // in the fused kernels, instead of a uniform average over the keys. std::optional has_visible_key; if (has_arr_mask || do_causal || window_size > 0) { // Mask must be broadcast-compatible with [B, n_q_heads, L_q, L_kv] @@ -919,8 +916,8 @@ array scaled_dot_product_attention( } scores = softmax(scores, std::vector{-1}, true, s); if (has_visible_key) { - scores = - where(*has_visible_key, scores, array(0, scores.dtype()), s); + // Make sure scores are zero when all keys are masked out. + scores = where(*has_visible_key, scores, array(0, scores.dtype()), s); } if (has_sinks) { // Slice off scores diff --git a/python/tests/test_fast_sdpa.py b/python/tests/test_fast_sdpa.py index dded2f6cfb..a1e16ef0c0 100644 --- a/python/tests/test_fast_sdpa.py +++ b/python/tests/test_fast_sdpa.py @@ -777,36 +777,42 @@ def test_sdpa_fully_masked(self): def test_sdpa_fully_masked_row(self): # A query row with no visible key gives zero output and zero gradient - # on every path, and the other rows are unaffected. + # on fused and unfused paths, and the other rows are unaffected. mx.random.seed(0) L = 4 mask = mx.ones((1, 1, L, L), dtype=mx.bool_) mask[..., 1, :] = False - for D in [32, 64, 80, 128]: - q = mx.random.normal(shape=(1, 2, L, D)) - k = mx.random.normal(shape=(1, 2, L, D)) - v = mx.random.normal(shape=(1, 2, L, D)) - scale = 1.0 / D**0.5 + # D=4 uses the unfused fallback; D=64 supports the fused kernel. + for D, fused in ((4, False), (64, True)): + with self.subTest(fused=fused): + q = mx.random.normal(shape=(1, 2, L, D)) + k = mx.random.normal(shape=(1, 2, L, D)) + v = mx.random.normal(shape=(1, 2, L, D)) + scale = 1.0 / D**0.5 - out = mx.fast.scaled_dot_product_attention( - q, k, v, scale=scale, mask=mask - ) - ref = mlx_primitives_sdpa(q, k, v, scale=scale, mask=None) - self.assertTrue(mx.array_equal(out[..., 1, :], mx.zeros_like(out[..., 1, :]))) - for i in (0, 2, 3): + out = mx.fast.scaled_dot_product_attention( + q, k, v, scale=scale, mask=mask + ) + ref = mlx_primitives_sdpa(q, k, v, scale=scale, mask=None) self.assertTrue( - mx.allclose(out[..., i, :], ref[..., i, :], atol=1e-4, rtol=1e-4) + mx.array_equal(out[..., 1, :], mx.zeros_like(out[..., 1, :])) ) + for i in (0, 2, 3): + self.assertTrue( + mx.allclose( + out[..., i, :], ref[..., i, :], atol=1e-4, rtol=1e-4 + ) + ) - def loss(q, k, v): - return mx.fast.scaled_dot_product_attention( - q, k, v, scale=scale, mask=mask - )[..., 1, :].sum() + def loss(q, k, v): + return mx.fast.scaled_dot_product_attention( + q, k, v, scale=scale, mask=mask + )[..., 1, :].sum() - dq, dk, dv = mx.grad(loss, argnums=(0, 1, 2))(q, k, v) - for g in (dq, dk, dv): - self.assertFalse(mx.any(mx.isnan(g))) - self.assertEqual(mx.abs(g).max().item(), 0.0) + dq, dk, dv = mx.grad(loss, argnums=(0, 1, 2))(q, k, v) + for g in (dq, dk, dv): + self.assertFalse(mx.any(mx.isnan(g))) + self.assertEqual(mx.abs(g).max().item(), 0.0) def test_sdpa_inf_score(self): Lkv = 8