/* Adapted from Apple MLX steel_attention_nax.h, copyright 2024–25 Apple Inc. MIT License Copyright © 2023 Apple Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using namespace mlx::steel; struct MaxOp { template METAL_FUNC static constexpr T apply(T x, T y) { return metal::max(x, y); } }; struct SumOp { template METAL_FUNC static constexpr T apply(T x, T y) { return x + y; } }; struct MulOp { template METAL_FUNC static constexpr T apply(T x, T y) { return x * y; } }; struct ExpSubOp { template METAL_FUNC static constexpr T apply(T x, T y) { return fast::exp2(x - y); } }; // Kernel body const int active_keys = range_end[0]; using T = bfloat; using AccumType = float; constexpr int BQ = 32, BK = 32, BD = 128, WM = 2, WN = 1; constexpr bool align_Q = false, align_K = KEY_ALIGNED; auto tid = threadgroup_position_in_grid; auto simd_group_id = simdgroup_index_in_threadgroup; // Keep the head and query-block offsets in 64-bit arithmetic on the M5 NAX path. auto Q = query + (ulong(tid.y) * 1600 + ulong(tid.x) * BQ) * BD; auto K = keys + ulong(tid.y) * CACHE_ROWS * BD; auto V = values + ulong(tid.y) * CACHE_ROWS * BD; auto O = result + (ulong(tid.y) * 1560 + ulong(tid.x) * BQ) * BD; const metal::uniform scale2 = make_uniform(0.08838834764831845f) * make_uniform(1.44269504089f); // Prepare MMA tiles constexpr short kU = 16; constexpr int kNWarps = WM * WN; static_assert( BQ >= (kNWarps * kU) && BQ % (kNWarps * kU) == 0, "Each simdgroup must host at least 1 simdgroup matrix along Q sequence."); // Q seq frags per warp constexpr int TQ = BQ / (kNWarps * kU); // HeadDim frags (all warps load the same frags) constexpr int TD = BD / kU; // KV seq frags per warp constexpr short TK = BK / kU; static_assert(TQ == 1, "Check TQ"); using otile_t = NAXTile; otile_t Otile; Otile.clear(); // Prepare mma tile offsets const short tm = kU * TQ * simd_group_id; Q += tm * BD; const short2 simd_coord = otile_t::NAXFrag_t::get_coord(); const short sn = simd_coord.x; // Init row reduction variables constexpr short kRowsPT = otile_t::kRowsPerThread; metal::vec max_score; metal::vec sum_score{0}; // Match the finite minimum used by the MLX kernel. STEEL_PRAGMA_UNROLL for (short i = 0; i < kRowsPT; ++i) { max_score[i] = (-FLT_MAX); } const int kb_lim = (active_keys + BK - 1) / BK; const bool is_last_q = int(tid.x) == 1560 / BQ; const short lim_rows_q = (1560 % BQ) - tm; const short lim_rows_k = (active_keys % BK); NAXTile cached_query[TD]; STEEL_PRAGMA_UNROLL for (short id = 0; id < TD; ++id) { const int Q_load_off = id * kU; if (!align_Q && is_last_q) { cached_query[id].load_rows(Q + Q_load_off, BD, lim_rows_q); } else { cached_query[id].load(Q + Q_load_off, BD); } } // Loop over KV seq length for (int kb = 0; kb < kb_lim; kb++) { const int is_last_k = kb == active_keys / BK; // Do S = Q @ K.T using stile_t = NAXTile; stile_t Stile; Stile.clear(); STEEL_PRAGMA_UNROLL for (short iq = 0; iq < TQ; iq++) { STEEL_PRAGMA_UNROLL for (short ik = 0; ik < TK; ik += 2) { #pragma clang loop unroll_count(8) for (short id = 0; id < TD; id++) { NAXTile Ktile; const int K_load_off = ik * kU * BD + id * kU; if (!align_K && is_last_k) { Ktile.load_rows(K + K_load_off, BD, lim_rows_k - ik * kU); } else { Ktile.load(K + K_load_off, BD); } stile_t::NAXFrag_t::mma( Stile.frag_at(iq, ik), Stile.frag_at(iq, ik + 1), cached_query[id].frag_at(0, 0), metal::false_type{}, Ktile.frag_at(0, 0), Ktile.frag_at(1, 0), metal::true_type{}); } } } // Scale S STEEL_PRAGMA_UNROLL for (short ii = 0; ii < stile_t::kElemsPerTile; ii++) { Stile.elems()[ii] *= float(scale2); } // Mask out length sequence if (!align_K && is_last_k) { constexpr auto neg_inf = (-FLT_MAX); STEEL_PRAGMA_UNROLL for (short iq = 0; iq < TQ; iq++) { STEEL_PRAGMA_UNROLL for (short ik = 0; ik < TK; ik++) { const short col_pos = ik * kU + sn; thread auto &fg = Stile.frag_at(iq, ik); STEEL_PRAGMA_UNROLL for (short ii = 0; ii < stile_t::kFragThrRows; ii++) { STEEL_PRAGMA_UNROLL for (short jj = 0; jj < stile_t::kFragThrCols; jj++) { const auto loc = ii * stile_t::kFragThrCols + jj; fg[loc] = ((col_pos + jj) < (active_keys % BK)) ? fg[loc] : neg_inf; } } } } } // Update the running softmax over KV tiles. metal::vec new_max; metal::vec factor; STEEL_PRAGMA_UNROLL for (short i = 0; i < kRowsPT; ++i) { new_max[i] = max_score[i]; } // Row max Stile.template row_reduce(new_max); // exp(Si - rowmax(Si)) Stile.template row_bin_op(new_max); // Factor exp(rowmax(Si) - rowmax(Si-1)) STEEL_PRAGMA_UNROLL for (short i = 0; i < kRowsPT; ++i) { factor[i] = fast::exp2(max_score[i] - new_max[i]); max_score[i] = new_max[i]; } // Row Sum STEEL_PRAGMA_UNROLL for (short i = 0; i < kRowsPT; ++i) { sum_score[i] = sum_score[i] * factor[i]; } Stile.template row_reduce(sum_score); // Update O Otile.template row_bin_op(factor); simdgroup_barrier(mem_flags::mem_none); // Do O = P @ V STEEL_PRAGMA_UNROLL for (short iq = 0; iq < TQ; iq++) { STEEL_PRAGMA_UNROLL for (short id = 0; id < TD; id += 2) { if constexpr (BD == 128) { if (id == 4) { threadgroup_barrier(mem_flags::mem_none); } } STEEL_PRAGMA_UNROLL for (short ik = 0; ik < TK; ik++) { NAXTile Vtile; const int V_load_off = ik * kU * BD + id * kU; if (!align_K && is_last_k) { Vtile.load_rows(V + V_load_off, BD, lim_rows_k - ik * kU); } else { Vtile.load(V + V_load_off, BD); } otile_t::NAXFrag_t::mma( Otile.frag_at(iq, id), Otile.frag_at(iq, id + 1), Stile.frag_at(iq, ik), metal::false_type{}, Vtile.frag_at(0, 0), Vtile.frag_at(0, 1), metal::false_type{}); } } } // Prepare for next iteration K += BK * BD; V += BK * BD; } // Normalize output threadgroup_barrier(mem_flags::mem_none); metal::vec rcp; STEEL_PRAGMA_UNROLL for (short i = 0; i < kRowsPT; ++i) { rcp[i] = 1.f / sum_score[i]; } Otile.template row_bin_op(rcp); // Store results O += tm * BD; if (!align_Q && is_last_q) { if (lim_rows_q <= 0) return; Otile.store_rows(O, BD, lim_rows_q); } else { Otile.store(O, BD); }