diff --git a/fork.yaml b/fork.yaml index 8adb49b1be..05188e6a6d 100644 --- a/fork.yaml +++ b/fork.yaml @@ -148,6 +148,40 @@ def: - "tests/qmv_batch_invariant_tests.cpp" - "tests/CMakeLists.txt" - ".github/workflows/fork-tests.yml" + - title: "Prefill-row invariance scope (opt-in, per thread)" + description: | + A thread-local scope, `ThreadPrefillRows` in C++ and + `mlx_metal_set_thread_prefill_rows` in C, that names a number of reference rows. + `quantized_matmul` and `fast::scaled_dot_product_attention` read it when the op is + built and keep it in the primitive (`prefill_rows()`), so the route follows the + thread that built the graph, not the one that evaluates it; `is_equivalent` compares + it, autograd keeps it, and the compile cache keeps traces from inside and outside a + scope apart. In a scope a transposed, non-batched quantized product of two or more + rows takes `qmm_splitk` with the K split that the reference rows would get, and skips + the NAX split-K route, which chooses its split from the row count; head-dim 256 causal + or masked attention takes the fused NAX kernel from 16 queries instead of 1024. Each + row of a prompt chunk then has the same bits whatever the chunk's length, the + batch-invariant kernel idea of Thinking Machines (2025) applied to prompt chunks. Ops + built outside a scope, and with 0 rows, take the routes they took before; one-row + products keep `qmv`, and attention of 8 or fewer queries keeps the vector kernels. + `state()` is unchanged, so an exported graph imports with 0. `tests/prefill_rows_tests.cpp` + checks that ops built outside a scope keep their bits, that each short product in a + scope matches the same rows of a 4096-row product, that compiled functions trace again + in a scope, and the head-dim 256 attention route. + globs: + - "mlx/utils.h" + - "mlx/utils.cpp" + - "mlx/backend/common/command_buffer_limits.h" + - "mlx/primitives.h" + - "mlx/primitives.cpp" + - "mlx/ops.cpp" + - "mlx/fast_primitives.h" + - "mlx/fast.cpp" + - "mlx/compile.cpp" + - "mlx/backend/metal/quantized.cpp" + - "mlx/backend/metal/scaled_dot_product_attention.cpp" + - "tests/prefill_rows_tests.cpp" + - "tests/CMakeLists.txt" - title: "GPT-OSS MXFP4 decode: masked-tail gathered qmv" description: | GPT-OSS 20B gathered MXFP4 decode has K=2880, which misses the fast vector kernel's diff --git a/mlx/backend/common/command_buffer_limits.h b/mlx/backend/common/command_buffer_limits.h index e5ca795989..93939d0c23 100644 --- a/mlx/backend/common/command_buffer_limits.h +++ b/mlx/backend/common/command_buffer_limits.h @@ -33,6 +33,20 @@ MLX_API void mlx_metal_set_thread_command_buffer_limits( /// 32 x 32 whatever the tile. MLX_API void mlx_metal_set_thread_qmm_steel_tile(int tile, int* previous_tile); +/// Reference row count for the quantized matmuls and attention ops that the +/// calling thread builds from now on; 0 ends the scope. Stores the thread's +/// previous value in `previous_rows` when it is not null. An op keeps the +/// value of the thread that builds it, whichever thread evaluates it. On the +/// GPU, a quantized `x @ w.T` of two or more rows built with `rows` > 0 splits +/// K as a product of `rows` rows would (and skips the NAX split-K kernel), so +/// a row's bits do not depend on how many rows share the call. Head-dim 256 +/// causal or masked attention takes the fused NAX kernel from 16 queries +/// instead of 1024. Ops built with 0 are unchanged. +MLX_API void mlx_metal_set_thread_prefill_rows(int rows, int* previous_rows); + +/// The calling thread's prefill reference rows (0 outside a scope). +MLX_API int mlx_metal_thread_prefill_rows(void); + #ifdef __cplusplus } #endif diff --git a/mlx/backend/metal/quantized.cpp b/mlx/backend/metal/quantized.cpp index 0d5e6c8220..00de26164a 100644 --- a/mlx/backend/metal/quantized.cpp +++ b/mlx/backend/metal/quantized.cpp @@ -1541,18 +1541,23 @@ void qmm_splitk( int K, metal::Device& d, const Stream& s, - const std::string& mode) { - // The split-K NAX route. - if (use_qmm_nax_splitk(x, biases, mode, M, N, K, group_size)) { + const std::string& mode, + int ref_rows = 0) { + // The split-K NAX route. A product with reference rows (a prefill-row + // scope) skips it, because that route chooses its K split from M. + if (ref_rows == 0 && + use_qmm_nax_splitk(x, biases, mode, M, N, K, group_size)) { return qmm_splitk_nax( x, w, scales, biases, out, group_size, bits, M, N, K, d, s, mode); } - // Choose split_k to target ~512 threadgroups + // Choose split_k to target ~512 threadgroups, counted for `ref_rows` rows + // when they are given so that the split does not depend on M. int bm = 32, bn = 32; int n_tiles = (N + bn - 1) / bn; int m_tiles = (M + bm - 1) / bm; - int current_tgs = n_tiles * m_tiles; + int split_m_tiles = ref_rows > 0 ? (ref_rows + bm - 1) / bm : m_tiles; + int current_tgs = n_tiles * split_m_tiles; int split_k = std::max(1, 512 / current_tgs); // Each K partition must be a whole number of BK-wide (32) K-tiles as well as @@ -2510,6 +2515,28 @@ void QuantizedMatmul::eval_gpu(const std::vector& inputs, array& out) { // to the limit - 1. bool vector_rows = env::qmv_batch_invariant() && M < vector_limit; + // A product built in a prefill-row scope (`thread_prefill_rows`) takes the + // split-K route with the K split of `prefill_rows_` rows from two rows on. + // Then each row has the same bits whatever the row count of the call. + if (prefill_rows_ > 0 && transpose_ && non_batched && M >= 2) { + qmm_splitk( + x, + w, + scales, + biases, + out, + group_size_, + bits_, + M, + N, + K, + d, + s, + mode, + prefill_rows_); + return; + } + // For few rows use qmv_mma when N/K is large enough. if (!vector_rows && transpose_ && non_batched && (M >= 6) && (M <= 16) && use_qmv_mma(x, w, scales, mode_, M, N, K, d)) { diff --git a/mlx/backend/metal/scaled_dot_product_attention.cpp b/mlx/backend/metal/scaled_dot_product_attention.cpp index 86b5b6df67..bc0b9a27a6 100644 --- a/mlx/backend/metal/scaled_dot_product_attention.cpp +++ b/mlx/backend/metal/scaled_dot_product_attention.cpp @@ -1446,10 +1446,12 @@ bool ScaledDotProductAttention::use_fallback( } // Use headdim-split kernel when NAX is enabled and there are enough query - // blocks to fill the machine. + // blocks to fill the machine. Inside a prefill-row scope it starts from 16 + // queries, so a prompt chunk takes one kernel whatever its length. + const int d256_nax_min_queries = thread_prefill_rows() > 0 ? 16 : 1024; if (metal::is_nax_available() && (env::enable_tf32() || q.dtype() != float32) && - query_sequence_length >= 1024 && query_head_dim == 256 && + query_sequence_length >= d256_nax_min_queries && query_head_dim == 256 && (do_causal || has_arr_mask)) { return false; } diff --git a/mlx/compile.cpp b/mlx/compile.cpp index fbb04aa6ed..6cfa2050a3 100644 --- a/mlx/compile.cpp +++ b/mlx/compile.cpp @@ -323,10 +323,12 @@ std::uintptr_t get_function_address(const std::function& fun) { class CompileCache { public: struct CacheEntry { - CacheEntry(std::optional stream, bool shapeless) - : stream(stream), shapeless(shapeless) {} + CacheEntry(std::optional stream, bool shapeless, int prefill_rows) + : stream(stream), shapeless(shapeless), prefill_rows(prefill_rows) {} std::optional stream; bool shapeless; + // The traced ops keep the prefill rows of the thread that traced them. + int prefill_rows; std::vector inputs; std::vector outputs; std::vector tape; @@ -395,8 +397,10 @@ class CompileCache { }; // Loop over entries and check: // - Default stream and device match the entry's default stream + // - The thread's prefill rows match the entry's // - Inputs match i.e. shapes and types must be equal. auto stream = peek_default_stream(default_device()); + int prefill_rows = thread_prefill_rows(); for (CacheEntry& entry : entries) { // Check that the default stream and device match if (entry.stream != stream) { @@ -405,6 +409,9 @@ class CompileCache { if (entry.shapeless != shapeless) { continue; } + if (entry.prefill_rows != prefill_rows) { + continue; + } // Check the inputs match and return if so if (has_same_shape_and_dtype(inputs, entry.inputs) && @@ -413,7 +420,7 @@ class CompileCache { } } // Otherwise append a new cache entry - entries.push_back(CacheEntry{stream, shapeless}); + entries.push_back(CacheEntry{stream, shapeless, prefill_rows}); return {entries.back(), std::move(entries_ptr)}; } diff --git a/mlx/fast.cpp b/mlx/fast.cpp index 2afb834166..d78b032f95 100644 --- a/mlx/fast.cpp +++ b/mlx/fast.cpp @@ -7,6 +7,7 @@ #include "mlx/ops.h" #include "mlx/transforms.h" #include "mlx/transforms_impl.h" +#include "mlx/utils.h" namespace mlx::core::fast { @@ -957,7 +958,8 @@ array scaled_dot_product_attention( do_causal, has_sinks, output_logsumexp, - force_fused); + force_fused, + thread_prefill_rows()); if (output_logsumexp) { return array::make_arrays( {std::move(out_shape), Shape{q.shape(0), q.shape(1), q.shape(2), 1}}, @@ -1027,7 +1029,8 @@ bool ScaledDotProductAttention::is_equivalent(const Primitive& other) const { return scale_ == a_other.scale_ && do_causal_ == a_other.do_causal_ && has_sinks_ == a_other.has_sinks_ && output_logsumexp_ == a_other.output_logsumexp_ && - force_fused_ == a_other.force_fused_; + force_fused_ == a_other.force_fused_ && + prefill_rows_ == a_other.prefill_rows_; } bool ScaledDotProductAttentionVJP::is_equivalent(const Primitive& other) const { diff --git a/mlx/fast_primitives.h b/mlx/fast_primitives.h index 6d5effd791..db44530a33 100644 --- a/mlx/fast_primitives.h +++ b/mlx/fast_primitives.h @@ -276,13 +276,15 @@ class ScaledDotProductAttention : public Custom { bool do_causal, bool has_sinks, bool output_logsumexp, - bool force_fused) + bool force_fused, + int prefill_rows = 0) : Custom(stream, std::move(fallback)), scale_(scale), do_causal_(do_causal), has_sinks_(has_sinks), output_logsumexp_(output_logsumexp), - force_fused_(force_fused) {} + force_fused_(force_fused), + prefill_rows_(prefill_rows) {} static bool use_fallback( const array& q, @@ -325,6 +327,11 @@ class ScaledDotProductAttention : public Custom { output_logsumexp_, force_fused_); } + // The building thread's prefill reference rows (`thread_prefill_rows`). + // Not part of `state()`: an exported graph imports with 0. + int prefill_rows() const { + return prefill_rows_; + } private: float scale_; @@ -332,6 +339,7 @@ class ScaledDotProductAttention : public Custom { bool has_sinks_; bool output_logsumexp_; bool force_fused_; + int prefill_rows_; }; class ScaledDotProductAttentionVJP : public Custom { diff --git a/mlx/ops.cpp b/mlx/ops.cpp index bb7053d0e0..e904873360 100644 --- a/mlx/ops.cpp +++ b/mlx/ops.cpp @@ -4988,7 +4988,12 @@ array quantized_matmul( std::move(out_shape), dtype, std::make_shared( - to_stream(s), group_size, bits, qmode, transpose), + to_stream(s), + group_size, + bits, + qmode, + transpose, + thread_prefill_rows()), std::move(inputs)); } diff --git a/mlx/primitives.cpp b/mlx/primitives.cpp index b6f603dd7a..773856216b 100644 --- a/mlx/primitives.cpp +++ b/mlx/primitives.cpp @@ -3622,6 +3622,7 @@ std::vector QuantizedMatmul::vjp( for (auto arg : argnums) { // gradient wrt to x if (arg == 0) { + ThreadPrefillRows scope(prefill_rows_); vjps.push_back(quantized_matmul( cotangents[0], primals[1], @@ -3686,6 +3687,7 @@ std::vector QuantizedMatmul::jvp( throw std::runtime_error( "[QuantizedMatmul::jvp] No JVP wrt the quantized matrix yet."); } + ThreadPrefillRows scope(prefill_rows_); return {quantized_matmul( tangents[0], primals[1], @@ -3702,7 +3704,8 @@ std::vector QuantizedMatmul::jvp( bool QuantizedMatmul::is_equivalent(const Primitive& other) const { const QuantizedMatmul& qm_other = static_cast(other); return group_size_ == qm_other.group_size_ && bits_ == qm_other.bits_ && - mode_ == qm_other.mode_ && transpose_ == qm_other.transpose_; + mode_ == qm_other.mode_ && transpose_ == qm_other.transpose_ && + prefill_rows_ == qm_other.prefill_rows_; } std::vector QuantizedMatmul::output_shapes( diff --git a/mlx/primitives.h b/mlx/primitives.h index 68995b7503..b7078ef23d 100644 --- a/mlx/primitives.h +++ b/mlx/primitives.h @@ -1642,12 +1642,14 @@ class QuantizedMatmul : public UnaryPrimitive { int group_size, int bits, QuantizationMode mode, - bool transpose) + bool transpose, + int prefill_rows = 0) : UnaryPrimitive(stream), group_size_(group_size), bits_(bits), mode_(mode), - transpose_(transpose) {} + transpose_(transpose), + prefill_rows_(prefill_rows) {} void eval_cpu(const std::vector& inputs, array& out) override; void eval_gpu(const std::vector& inputs, array& out) override; @@ -1660,12 +1662,18 @@ class QuantizedMatmul : public UnaryPrimitive { auto state() const { return std::make_tuple(group_size_, bits_, mode_, transpose_); } + // The building thread's prefill reference rows (`thread_prefill_rows`). + // Not part of `state()`: an exported graph imports with 0. + int prefill_rows() const { + return prefill_rows_; + } private: int group_size_; int bits_; QuantizationMode mode_; bool transpose_; + int prefill_rows_; }; class QQMatmul : public UnaryPrimitive { diff --git a/mlx/utils.cpp b/mlx/utils.cpp index 07130fa690..c8cfdd18ee 100644 --- a/mlx/utils.cpp +++ b/mlx/utils.cpp @@ -1,5 +1,6 @@ // Copyright © 2023 Apple Inc. +#include #include #include #include @@ -7,6 +8,7 @@ #include #include +#include "mlx/backend/common/command_buffer_limits.h" #include "mlx/dtype_utils.h" #include "mlx/types/limits.h" #include "mlx/utils.h" @@ -289,6 +291,20 @@ std::ostream& operator<<(std::ostream& os, array a) { return os; } +namespace { +thread_local int thread_prefill_rows_ = 0; +} // namespace + +int thread_prefill_rows() { + return thread_prefill_rows_; +} + +int set_thread_prefill_rows(int rows) { + int previous = thread_prefill_rows_; + thread_prefill_rows_ = std::max(0, rows); + return previous; +} + namespace env { int get_var(const char* name, int default_value) { @@ -356,3 +372,18 @@ iinfo::iinfo(Dtype dtype) : dtype(dtype) { } } // namespace mlx::core + +#if defined(__APPLE__) +extern "C" void mlx_metal_set_thread_prefill_rows( + int rows, + int* previous_rows) { + int previous = mlx::core::set_thread_prefill_rows(rows); + if (previous_rows != nullptr) { + *previous_rows = previous; + } +} + +extern "C" int mlx_metal_thread_prefill_rows(void) { + return mlx::core::thread_prefill_rows(); +} +#endif diff --git a/mlx/utils.h b/mlx/utils.h index f47f276431..458adae0dc 100644 --- a/mlx/utils.h +++ b/mlx/utils.h @@ -180,6 +180,29 @@ inline int next_power_of_2(int n) { return pow(2, std::ceil(std::log2(n))); } +// The calling thread's prefill reference rows: 0 outside a prefill-row scope. +// A quantized matmul or an attention op keeps the value of the thread that +// builds it (see `mlx_metal_set_thread_prefill_rows`). +MLX_API int thread_prefill_rows(); + +// Sets the calling thread's prefill reference rows (negative values are 0) +// and returns the previous value. +MLX_API int set_thread_prefill_rows(int rows); + +// Sets the calling thread's prefill reference rows for the life of the object. +struct ThreadPrefillRows { + explicit ThreadPrefillRows(int rows) + : previous_(set_thread_prefill_rows(rows)) {} + ~ThreadPrefillRows() { + set_thread_prefill_rows(previous_); + } + ThreadPrefillRows(const ThreadPrefillRows&) = delete; + ThreadPrefillRows& operator=(const ThreadPrefillRows&) = delete; + + private: + int previous_; +}; + namespace env { int get_var(const char* name, int default_value); diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index abb29b114d..e2bfcd2c46 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -27,6 +27,7 @@ if(MLX_BUILD_METAL) endforeach() list(APPEND GPU_TEST_SOURCES residency_tests.cpp gptoss_mxfp4_tests.cpp quantized_tile_tests.cpp qmv_batch_invariant_tests.cpp) + list(APPEND GPU_TEST_SOURCES prefill_rows_tests.cpp) # MLX reads MLX_QMV_BATCH_INVARIANT once in each process, so this entry runs # the case again in a new process with the switch on. The tests entries run it # with the switch off. The entry fails also if no test case has this name. diff --git a/tests/prefill_rows_tests.cpp b/tests/prefill_rows_tests.cpp new file mode 100644 index 0000000000..7d9578cee4 --- /dev/null +++ b/tests/prefill_rows_tests.cpp @@ -0,0 +1,255 @@ +// Copyright © 2026 Eigen Labs. +#include +#include + +#include "doctest/doctest.h" +#include "mlx/backend/common/command_buffer_limits.h" +#include "mlx/backend/metal/device.h" +#include "mlx/fast.h" +#include "mlx/mlx.h" +#include "mlx/primitives.h" + +using namespace mlx::core; + +namespace { + +constexpr int reference_rows = 4096; + +// The calling thread's prefill reference rows for the scope. +struct ScopedPrefillRows { + int previous = 0; + explicit ScopedPrefillRows(int rows) { + mlx_metal_set_thread_prefill_rows(rows, &previous); + } + ~ScopedPrefillRows() { + mlx_metal_set_thread_prefill_rows(previous, nullptr); + } +}; + +// True when a and b have the same shape and the same bytes. +bool same_bits(const array& a, const array& b) { + if (a.shape() != b.shape() || a.dtype() != b.dtype()) { + return false; + } + auto bits = a.itemsize() == 2 ? uint16 : uint32; + return array_equal(view(a, bits, Device::cpu), view(b, bits, Device::cpu)) + .item(); +} + +array rows_of(const array& a, int start, int stop) { + return contiguous( + slice(a, {start, 0}, {stop, a.shape(1)}, Device::gpu), + false, + Device::gpu); +} + +struct Product { + array x; + std::vector q; + + // 4-bit affine weights in groups of 64, as the Qwen 3.5 checkpoints use. + Product(int M, int N, int K, Dtype dtype) + : x(astype( + random::normal({M, K}, float32, 0.0f, 1.0f, random::key(K + N)), + dtype, + Device::gpu)), + q(quantize( + astype( + random::normal( + {N, K}, + float32, + 0.0f, + 1.0f / std::sqrt(float(K)), + random::key(3 * K + N)), + dtype, + Device::gpu), + 64, + 4, + "affine", + std::nullopt, + Device::gpu)) {} + + array operator()(const array& rows) const { + return quantized_matmul( + rows, q[0], q[1], q[2], true, 64, 4, "affine", Device::gpu); + } +}; + +} // namespace + +TEST_CASE("prefill rows scope changes only the ops built inside it") { + CHECK_EQ(mlx_metal_thread_prefill_rows(), 0); + Product product(256, 1024, 4096, bfloat16); + + // Evaluation detaches an array's primitive, so keep the primitives of the + // arrays whose routes are compared. + auto before = product(product.x); + auto before_p = before.primitive_ptr(); + eval(before); + + array inside_built(0.0f); + array inside_evaluated(0.0f); + std::shared_ptr inside_p; + { + ScopedPrefillRows scope(reference_rows); + CHECK_EQ(mlx_metal_thread_prefill_rows(), reference_rows); + inside_built = product(product.x); + inside_p = inside_built.primitive_ptr(); + inside_evaluated = product(product.x); + eval(inside_evaluated); + } + CHECK_EQ(mlx_metal_thread_prefill_rows(), 0); + + // Built outside a scope, evaluated inside one. + auto outside_built = product(product.x); + { + ScopedPrefillRows scope(reference_rows); + eval(outside_built); + } + auto after = product(product.x); + auto after_p = after.primitive_ptr(); + eval(after); + // Built inside the scope, evaluated after it ended. + eval(inside_built); + + CHECK_EQ(static_cast(*before_p).prefill_rows(), 0); + CHECK_EQ( + static_cast(*inside_p).prefill_rows(), reference_rows); + CHECK(before_p->is_equivalent(*after_p)); + CHECK_FALSE(before_p->is_equivalent(*inside_p)); + + // Ops built outside the scope have the bits of ops that never saw one, + // whatever the thread's scope when they are evaluated. + CHECK(same_bits(after, before)); + CHECK(same_bits(outside_built, before)); + // An op built in the scope keeps its route after the scope ends. + CHECK(same_bits(inside_built, inside_evaluated)); +} + +TEST_CASE("short products in the prefill rows scope match the reference rows") { + // The rows of a product built in the scope have the bits of the same rows + // in a product of `reference_rows` rows, at every row count from 2. The + // shapes are the Qwen 3.5 9B projections whose split-K choice depends on + // the row count outside the scope (the K/V projections, N = 1024). + struct Shape { + int N; + int K; + }; + for (auto [N, K] : + {Shape{1024, 4096}, Shape{4096, 12288}, Shape{12288, 4096}}) { + for (auto dtype : {bfloat16, float16}) { + CAPTURE(N); + CAPTURE(K); + CAPTURE(dtype); + Product product(reference_rows, N, K, dtype); + ScopedPrefillRows scope(reference_rows); + auto reference = product(product.x); + eval(reference); + int outside_differs = 0; + for (int M : {2, 3, 7, 16, 31, 33, 64, 65, 100, 128, + 129, 200, 256, 257, 384, 511, 512, 1000, 1024, 2048}) { + CAPTURE(M); + auto rows = rows_of(product.x, 0, M); + auto inside = product(rows); + eval(inside); + CHECK(same_bits(inside, rows_of(reference, 0, M))); + { + ScopedPrefillRows none(0); + auto outside = product(rows); + eval(outside); + outside_differs += !same_bits(outside, rows_of(reference, 0, M)); + } + } + // How many row counts take another route without the scope on this + // GPU; informational, it depends on the device. + MESSAGE( + "row counts with other bits outside the scope: ", outside_differs); + } + } +} + +TEST_CASE("compiled functions trace again inside the prefill rows scope") { + Product product(256, 1024, 4096, bfloat16); + auto compiled = compile([](const std::vector& inputs) { + return std::vector{quantized_matmul( + inputs[0], + inputs[1], + inputs[2], + inputs[3], + true, + 64, + 4, + "affine", + Device::gpu)}; + }); + std::vector inputs{ + product.x, product.q[0], product.q[1], product.q[2]}; + + auto outside = compiled(inputs)[0]; + eval(outside); + array inside(0.0f); + array inside_direct(0.0f); + { + ScopedPrefillRows scope(reference_rows); + inside = compiled(inputs)[0]; + inside_direct = product(product.x); + eval(inside, inside_direct); + } + auto outside_again = compiled(inputs)[0]; + auto outside_direct = product(product.x); + eval(outside_again, outside_direct); + + CHECK(same_bits(inside, inside_direct)); + CHECK(same_bits(outside, outside_direct)); + CHECK(same_bits(outside_again, outside_direct)); +} + +TEST_CASE("head-dim 256 attention in the prefill rows scope") { + // Qwen 3.5 9B full attention: 16 query heads, 4 key/value heads, head dim + // 256. The last 128 queries of a causal 2048-query call, attended alone + // over the same keys, as a prompt chunk that starts at 1920. + constexpr int L = 2048, tail = 128, H = 16, Hkv = 4, D = 256; + auto normal = [](Shape shape, int seed) { + return astype( + random::normal(shape, float32, 0.0f, 1.0f, random::key(seed)), + bfloat16, + Device::gpu); + }; + auto q = normal({1, H, L, D}, 1); + auto k = normal({1, Hkv, L, D}, 2); + auto v = normal({1, Hkv, L, D}, 3); + auto q_tail = slice(q, {0, 0, L - tail, 0}, {1, H, L, D}, Device::gpu); + float scale = 1.0f / std::sqrt(float(D)); + auto attend = [&](const array& queries) { + return fast::scaled_dot_product_attention( + queries, + k, + v, + scale, + "causal", + std::nullopt, + std::nullopt, + false, + Device::gpu); + }; + + auto outside = attend(q_tail); + array inside(0.0f); + array full(0.0f); + { + ScopedPrefillRows scope(reference_rows); + inside = attend(q_tail); + full = attend(q); + } + eval(outside, inside, full); + if (metal::is_nax_available()) { + // Both calls take the fused NAX kernel in the scope, so the chunk's + // queries have the bits of the same queries in the longer call. + auto full_tail = + slice(full, {0, 0, L - tail, 0}, {1, H, L, D}, Device::gpu); + CHECK(same_bits(inside, full_tail)); + } else { + // Without neural accelerators the scope does not change attention. + CHECK(same_bits(inside, outside)); + } +}