diff --git a/mlx/fast.cpp b/mlx/fast.cpp index 3aa60286e4..d49b0a5518 100644 --- a/mlx/fast.cpp +++ b/mlx/fast.cpp @@ -843,6 +843,7 @@ array scaled_dot_product_attention( v = expand_dims(v, 2, s); } auto scores = matmul(q, swapaxes(k, -1, -2, s), s); + 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 +894,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 +915,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) { + // 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 auto start = Shape(scores.ndim(), 0); diff --git a/python/tests/test_fast_sdpa.py b/python/tests/test_fast_sdpa.py index 5229c8b301..a1e16ef0c0 100644 --- a/python/tests/test_fast_sdpa.py +++ b/python/tests/test_fast_sdpa.py @@ -775,6 +775,45 @@ 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 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 + # 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): + 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]: