From 7964c8fd7f8128b69d08a57fefeb0add888fe989 Mon Sep 17 00:00:00 2001 From: Pierre Ablin Date: Sat, 21 Nov 2026 02:14:35 +0100 Subject: [PATCH 1/4] update bool masks --- mlx/fast.cpp | 16 ++++++++++------ python/tests/test_fast_sdpa.py | 24 ++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 6 deletions(-) diff --git a/mlx/fast.cpp b/mlx/fast.cpp index 5d44b09622..5760affa23 100644 --- a/mlx/fast.cpp +++ b/mlx/fast.cpp @@ -976,14 +976,18 @@ array scaled_dot_product_attention( force_fused, stream)) { if (has_bool_mask && !ScaledDotProductAttention::supports_bool_mask()) { - // Convert bool mask to additive mask. + // Convert bool mask to additive mask before the broadcast, so it is not + // copied for each head. The fused kernel needs a contiguous last axis. float inf = std::numeric_limits::infinity(); - array& mask = inputs[3]; - mask = where( - mask, - full_like(mask, 0, final_type, stream), - full_like(mask, -inf, final_type, stream), + auto shape = mask_arr->ndim() > 0 ? mask_arr->shape() : Shape{1}; + shape.back() = keys.shape(-2); + auto mask = where( + broadcast_to(*mask_arr, shape, stream), + array(0.0f, final_type), + array(-inf, final_type), stream); + mask = contiguous(mask, false, stream); + inputs[3] = broadcast_to(mask, inputs[3].shape(), stream); } Shape out_shape{q.shape(0), q.shape(1), q.shape(2), v.shape(-1)}; auto primitive = std::make_shared( diff --git a/python/tests/test_fast_sdpa.py b/python/tests/test_fast_sdpa.py index 98eb8c36b6..a767be3e15 100644 --- a/python/tests/test_fast_sdpa.py +++ b/python/tests/test_fast_sdpa.py @@ -1155,6 +1155,30 @@ def test_sdpa_broadcast_mask(self): out = mx.fast.scaled_dot_product_attention(q, k, v, scale=scale, mask=mask) self.assertTrue(mx.allclose(ref, out, atol=1e-4, rtol=1e-4)) + def test_sdpa_bool_mask_memory(self): + B, H, L, D = 1, 8, 1024, 64 + q, k, v = (mx.random.normal((B, H, L, D), mx.float16) for _ in range(3)) + bool_mask = make_causal_mask(L, L) + add_mask = mx.where(bool_mask, 0.0, -mx.inf).astype(mx.float16) + mx.eval(q, k, v, bool_mask, add_mask) + + def run(mask): + mx.synchronize() + mx.reset_peak_memory() + before = mx.get_active_memory() + out = mx.fast.scaled_dot_product_attention( + q, k, v, scale=D**-0.5, mask=mask + ) + mx.eval(out) + mx.synchronize() + return out, mx.get_peak_memory() - before + + out_add, mem_add = run(add_mask) + out_bool, mem_bool = run(bool_mask) + self.assertTrue(mx.allclose(out_bool, out_add, atol=1e-3, rtol=1e-3)) + # The bool mask can add one additive mask, not one for each head. + self.assertLess(mem_bool - mem_add, 2 * add_mask.nbytes) + def test_sdpa_noncontiguous_inputs(self): mask = mx.ones(shape=(4, 1, 7, 7), dtype=mx.bool_) mx.random.seed(0) From e491a330ff547d9e1c7808a516f06fbca3a8a069 Mon Sep 17 00:00:00 2001 From: Pierre Ablin Date: Sat, 21 Nov 2026 15:30:52 +0100 Subject: [PATCH 2/4] add test --- python/tests/test_fast_sdpa.py | 60 ++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) diff --git a/python/tests/test_fast_sdpa.py b/python/tests/test_fast_sdpa.py index a767be3e15..323d0dbd33 100644 --- a/python/tests/test_fast_sdpa.py +++ b/python/tests/test_fast_sdpa.py @@ -1,6 +1,7 @@ import math import os import unittest +from functools import partial from itertools import product import mlx.core as mx @@ -1179,6 +1180,65 @@ def run(mask): # The bool mask can add one additive mask, not one for each head. self.assertLess(mem_bool - mem_add, 2 * add_mask.nbytes) + def test_sdpa_bool_mask_layouts(self): + B, Hq, Hkv, qL, kL, D = 2, 8, 2, 128, 256, 64 + scale = D**-0.5 + mx.random.seed(0) + q = mx.random.normal((B, Hq, qL, D)) + k = mx.random.normal((B, Hkv, kL, D)) + v = mx.random.normal((B, Hkv, kL, D)) + cotan = mx.random.normal((B, Hq, qL, D)) + + # Each query keeps at least one key. + keys = (mx.random.uniform(shape=(B, 1, 1, kL)) < 0.8) | (mx.arange(kL) == 0) + wide = mx.random.uniform(shape=(qL, 2 * kL)) < 0.8 + wide = wide | mx.eye(qL, 2 * kL, dtype=mx.bool_) + tall = mx.random.uniform(shape=(kL, qL)) < 0.8 + tall = tall | mx.eye(kL, qL, dtype=mx.bool_) + mx.eval(keys, wide, tall) + masks = { + "scalar": mx.array(True), + "keys": keys, + "queries": mx.ones((B, 1, qL, 1), dtype=mx.bool_), + "sliced": wide[:, :kL], + "transposed": tall.T, + } + + def attention(q, k, v, mask, cotan, fused): + def f(q, k, v): + return mx.fast.scaled_dot_product_attention( + q, k, v, scale=scale, mask=mask, force_fused=fused + ) + + out, vjps = mx.vjp(f, [q, k, v], [cotan]) + return out + vjps + + def reference(q, k, v, mask, cotan): + def f(q, k, v): + return mlx_ref_attn(q, k, v, scale=scale, mask=mask) + + out, vjps = mx.vjp(f, [q, k, v], [cotan]) + return out + vjps + + for dtype in (mx.float16, mx.bfloat16): + inputs = [x.astype(dtype) for x in (q, k, v)] + ct = cotan.astype(dtype) + # Use the fused kernels when they take a mask with the gradients. + try: + attention(*inputs, keys, ct, True) + fused = True + except ValueError: + fused = False + eager = partial(attention, fused=fused) + compiled = mx.compile(eager) + tol = 4e-2 if dtype == mx.bfloat16 else 1e-2 + for name, mask in masks.items(): + expected = reference(q, k, v, mask, cotan) + for mode, fn in (("eager", eager), ("compiled", compiled)): + with self.subTest(dtype=dtype, mask=name, mode=mode): + for out, ref in zip(fn(*inputs, mask, ct), expected): + self.assertTrue(mx.allclose(out, ref, atol=tol, rtol=tol)) + def test_sdpa_noncontiguous_inputs(self): mask = mx.ones(shape=(4, 1, 7, 7), dtype=mx.bool_) mx.random.seed(0) From 4a2179940837db62296c3b9ac4c8842694c21e51 Mon Sep 17 00:00:00 2001 From: Pierre Ablin Date: Sat, 21 Nov 2026 16:26:46 +0100 Subject: [PATCH 3/4] better test --- python/tests/test_fast_sdpa.py | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/python/tests/test_fast_sdpa.py b/python/tests/test_fast_sdpa.py index 323d0dbd33..5f4e735d83 100644 --- a/python/tests/test_fast_sdpa.py +++ b/python/tests/test_fast_sdpa.py @@ -1220,17 +1220,18 @@ def f(q, k, v): out, vjps = mx.vjp(f, [q, k, v], [cotan]) return out + vjps + # cuDNN attention runs on CUDA GPUs from sm80 on. Require the fused + # kernels there, and use the default path elsewhere. + fused = ( + mx.default_device() == mx.gpu + and mx.cuda.is_available() + and mx.device_info(mx.gpu)["compute_capability_major"] >= 8 + ) + eager = partial(attention, fused=fused) + compiled = mx.compile(eager) for dtype in (mx.float16, mx.bfloat16): inputs = [x.astype(dtype) for x in (q, k, v)] ct = cotan.astype(dtype) - # Use the fused kernels when they take a mask with the gradients. - try: - attention(*inputs, keys, ct, True) - fused = True - except ValueError: - fused = False - eager = partial(attention, fused=fused) - compiled = mx.compile(eager) tol = 4e-2 if dtype == mx.bfloat16 else 1e-2 for name, mask in masks.items(): expected = reference(q, k, v, mask, cotan) From d253de48aa7ab0efe88bc61c32ae4181907a1672 Mon Sep 17 00:00:00 2001 From: Pierre Ablin Date: Mon, 23 Nov 2026 10:01:04 +0100 Subject: [PATCH 4/4] rm tests --- python/tests/test_fast_sdpa.py | 85 ---------------------------------- 1 file changed, 85 deletions(-) diff --git a/python/tests/test_fast_sdpa.py b/python/tests/test_fast_sdpa.py index 5f4e735d83..98eb8c36b6 100644 --- a/python/tests/test_fast_sdpa.py +++ b/python/tests/test_fast_sdpa.py @@ -1,7 +1,6 @@ import math import os import unittest -from functools import partial from itertools import product import mlx.core as mx @@ -1156,90 +1155,6 @@ def test_sdpa_broadcast_mask(self): out = mx.fast.scaled_dot_product_attention(q, k, v, scale=scale, mask=mask) self.assertTrue(mx.allclose(ref, out, atol=1e-4, rtol=1e-4)) - def test_sdpa_bool_mask_memory(self): - B, H, L, D = 1, 8, 1024, 64 - q, k, v = (mx.random.normal((B, H, L, D), mx.float16) for _ in range(3)) - bool_mask = make_causal_mask(L, L) - add_mask = mx.where(bool_mask, 0.0, -mx.inf).astype(mx.float16) - mx.eval(q, k, v, bool_mask, add_mask) - - def run(mask): - mx.synchronize() - mx.reset_peak_memory() - before = mx.get_active_memory() - out = mx.fast.scaled_dot_product_attention( - q, k, v, scale=D**-0.5, mask=mask - ) - mx.eval(out) - mx.synchronize() - return out, mx.get_peak_memory() - before - - out_add, mem_add = run(add_mask) - out_bool, mem_bool = run(bool_mask) - self.assertTrue(mx.allclose(out_bool, out_add, atol=1e-3, rtol=1e-3)) - # The bool mask can add one additive mask, not one for each head. - self.assertLess(mem_bool - mem_add, 2 * add_mask.nbytes) - - def test_sdpa_bool_mask_layouts(self): - B, Hq, Hkv, qL, kL, D = 2, 8, 2, 128, 256, 64 - scale = D**-0.5 - mx.random.seed(0) - q = mx.random.normal((B, Hq, qL, D)) - k = mx.random.normal((B, Hkv, kL, D)) - v = mx.random.normal((B, Hkv, kL, D)) - cotan = mx.random.normal((B, Hq, qL, D)) - - # Each query keeps at least one key. - keys = (mx.random.uniform(shape=(B, 1, 1, kL)) < 0.8) | (mx.arange(kL) == 0) - wide = mx.random.uniform(shape=(qL, 2 * kL)) < 0.8 - wide = wide | mx.eye(qL, 2 * kL, dtype=mx.bool_) - tall = mx.random.uniform(shape=(kL, qL)) < 0.8 - tall = tall | mx.eye(kL, qL, dtype=mx.bool_) - mx.eval(keys, wide, tall) - masks = { - "scalar": mx.array(True), - "keys": keys, - "queries": mx.ones((B, 1, qL, 1), dtype=mx.bool_), - "sliced": wide[:, :kL], - "transposed": tall.T, - } - - def attention(q, k, v, mask, cotan, fused): - def f(q, k, v): - return mx.fast.scaled_dot_product_attention( - q, k, v, scale=scale, mask=mask, force_fused=fused - ) - - out, vjps = mx.vjp(f, [q, k, v], [cotan]) - return out + vjps - - def reference(q, k, v, mask, cotan): - def f(q, k, v): - return mlx_ref_attn(q, k, v, scale=scale, mask=mask) - - out, vjps = mx.vjp(f, [q, k, v], [cotan]) - return out + vjps - - # cuDNN attention runs on CUDA GPUs from sm80 on. Require the fused - # kernels there, and use the default path elsewhere. - fused = ( - mx.default_device() == mx.gpu - and mx.cuda.is_available() - and mx.device_info(mx.gpu)["compute_capability_major"] >= 8 - ) - eager = partial(attention, fused=fused) - compiled = mx.compile(eager) - for dtype in (mx.float16, mx.bfloat16): - inputs = [x.astype(dtype) for x in (q, k, v)] - ct = cotan.astype(dtype) - tol = 4e-2 if dtype == mx.bfloat16 else 1e-2 - for name, mask in masks.items(): - expected = reference(q, k, v, mask, cotan) - for mode, fn in (("eager", eager), ("compiled", compiled)): - with self.subTest(dtype=dtype, mask=name, mode=mode): - for out, ref in zip(fn(*inputs, mask, ct), expected): - self.assertTrue(mx.allclose(out, ref, atol=tol, rtol=tol)) - def test_sdpa_noncontiguous_inputs(self): mask = mx.ones(shape=(4, 1, 7, 7), dtype=mx.bool_) mx.random.seed(0)