From bec61330b8da1fbb15e654eb0d968cdd446e96cf Mon Sep 17 00:00:00 2001 From: shoudi zheng <434782114@qq.com> Date: Sat, 5 Dec 2026 15:39:53 +0800 Subject: [PATCH] [Engine] qwen4/metal: rewrite q4_qsa_attend_batch with simdgroup_matrix (10x faster 4K prefill QSA) --- engine/metal/poly_tests/qwen4_parity.cpp | 217 +++++++++++++++ engine/metal/src/poly/qwen4.cpp | 9 +- engine/metal/src/poly/qwen4.metal | 338 +++++++++++++++++++++++ 3 files changed, 561 insertions(+), 3 deletions(-) diff --git a/engine/metal/poly_tests/qwen4_parity.cpp b/engine/metal/poly_tests/qwen4_parity.cpp index bc9532a429..069cdf246a 100644 --- a/engine/metal/poly_tests/qwen4_parity.cpp +++ b/engine/metal/poly_tests/qwen4_parity.cpp @@ -7,6 +7,7 @@ #include "ggml.h" #include +#include #include #include #include @@ -529,6 +530,222 @@ int test_qsa(g::Stream s) { bad += compare(dout.read(ref.size()), ref, lbl, 1e-4f); } } + + // 4) q4_qsa_attend batch MMA parity matrix (rows=1,64,512; G=4,8; dim=256; n_ids=0,17,64,512,2048; ring=0 & >0; Q8_0 & FP16) + timing + { + struct BatchCase { + const char* name; + int rows; + int G; + int n_kv; + int dim; + int n_cache; + int sel_cap; + int n_ids; // fixed n_ids, or -1 for mixed {0, 17, 64, 512} + int ring; // 0 or > 0 + bool strided; // test non-default Q8 row stride + bool bench; // run timing microbenchmark + }; + const BatchCase cases[] = { + {"r1_G8_n0", 1, 8, 2, 256, 128, 64, 0, 0, false, false}, + {"r1_G4_n17", 1, 4, 2, 256, 128, 64, 17, 0, false, false}, + {"r1_G8_n64", 1, 8, 2, 256, 128, 64, 64, 0, false, false}, + {"r64_G4_n512_rng", 64, 4, 2, 256, 257, 512, -1, 257, false, false}, + {"r64_G8_n2048", 64, 8, 2, 256, 2200, 2048, 2048, 0, false, false}, + {"r512_G8_n2048", 512, 8, 2, 256, 2200, 2048, 2048, 0, false, true}, + {"r20_G8_d128_fb", 20, 8, 2, 128, 160, 128, 80, 0, false, false}, + {"r20_G8_strided", 20, 8, 2, 256, 160, 128, 97, 0, true, false}, + }; + for (const auto& tc : cases) { + for (int use_q8 : {0, 1}) { + if (tc.strided && !use_q8) continue; + const int rows = tc.rows; + const int n_kv = tc.n_kv; + const int n_head = tc.G * n_kv; + const int dim = tc.dim; + const int n_cache = tc.n_cache; + const int sel_cap = tc.sel_cap; + const float scale = 1.0f / std::sqrt(float(dim)); + + auto q = values(size_t(rows) * n_head * dim, 0.4f); + auto kf = values(size_t(n_cache) * n_kv * dim, 0.5f); + auto vf = values(size_t(n_cache) * n_kv * dim, 0.5f); + + std::vector h_ids(size_t(rows) * sel_cap, 0), h_cnt(rows, 0); + const int mix_counts[4] = {0, 17, 64, 512}; + for (int r = 0; r < rows; ++r) { + const int cnt = (tc.n_ids >= 0) ? tc.n_ids : mix_counts[r & 3]; + h_cnt[r] = cnt; + for (int j = 0; j < cnt; ++j) { + // When ring > 0, emit un-wrapped logical indices > ring to exercise modulo wrap + const int raw = (tc.ring > 0) ? (j * 7 + r * 13 + tc.ring) : ((j * 7 + r * 5) % n_cache); + h_ids[size_t(r) * sel_cap + j] = raw; + } + } + + Buffer dq(q), dids(size_t(rows) * sel_cap * 4), dcnt(size_t(rows) * 4); + Buffer dout(size_t(rows) * n_head * dim * 4); + dids.put(h_ids.data(), h_ids.size() * 4); + dcnt.put(h_cnt.data(), h_cnt.size() * 4); + // Poison output buffer to prove n_ids == 0 explicitly zeroes out + ck(g::memset_async(dout.ptr, 0x3f, size_t(rows) * n_head * dim * 4, s)); + + const size_t kv_cols = size_t(n_kv) * dim; + const size_t k_rs = tc.strided ? (kv_cols + 64) : kv_cols; + const size_t v_rs = tc.strided ? (kv_cols + 96) : kv_cols; + + Buffer dk16(use_q8 ? 4 : size_t(n_cache) * kv_cols * 2); + Buffer dv16(use_q8 ? 4 : size_t(n_cache) * kv_cols * 2); + Buffer dkc(use_q8 ? size_t(n_cache) * k_rs : 4); + Buffer dks(use_q8 ? size_t(n_cache) * (k_rs / 32) * 2 : 4); + Buffer dvc(use_q8 ? size_t(n_cache) * v_rs : 4); + Buffer dvs(use_q8 ? size_t(n_cache) * (v_rs / 32) * 2 : 4); + + if (use_q8) { + if (tc.strided) { + Buffer dkf(kf), dvf(vf); + Buffer tkc(size_t(n_cache) * kv_cols), tks(size_t(n_cache) * (kv_cols / 32) * 2); + Buffer tvc(size_t(n_cache) * kv_cols), tvs(size_t(n_cache) * (kv_cols / 32) * 2); + p::store_q8(dkf.as(), tkc.as(), tks.as(), int(kv_cols), 0, n_cache, s); + p::store_q8(dvf.as(), tvc.as(), tvs.as(), int(kv_cols), 0, n_cache, s); + ck(g::stream_synchronize(s)); + auto hkc = tkc.read(size_t(n_cache) * kv_cols); + auto hks = tks.read(size_t(n_cache) * (kv_cols / 32)); + auto hvc = tvc.read(size_t(n_cache) * kv_cols); + auto hvs = tvs.read(size_t(n_cache) * (kv_cols / 32)); + std::vector pkc(size_t(n_cache) * k_rs, 0), pvc(size_t(n_cache) * v_rs, 0); + std::vector pks(size_t(n_cache) * (k_rs / 32), 0), pvs(size_t(n_cache) * (v_rs / 32), 0); + for (int r = 0; r < n_cache; ++r) { + std::memcpy(pkc.data() + size_t(r) * k_rs, hkc.data() + size_t(r) * kv_cols, kv_cols); + std::memcpy(pks.data() + size_t(r) * (k_rs / 32), hks.data() + size_t(r) * (kv_cols / 32), (kv_cols / 32) * 2); + std::memcpy(pvc.data() + size_t(r) * v_rs, hvc.data() + size_t(r) * kv_cols, kv_cols); + std::memcpy(pvs.data() + size_t(r) * (v_rs / 32), hvs.data() + size_t(r) * (kv_cols / 32), (kv_cols / 32) * 2); + } + dkc.put(pkc.data(), pkc.size()); + dks.put(pks.data(), pks.size() * 2); + dvc.put(pvc.data(), pvc.size()); + dvs.put(pvs.data(), pvs.size() * 2); + } else { + Buffer dkf(kf), dvf(vf); + p::store_q8(dkf.as(), dkc.as(), dks.as(), int(kv_cols), 0, n_cache, s); + p::store_q8(dvf.as(), dvc.as(), dvs.as(), int(kv_cols), 0, n_cache, s); + } + } else { + Buffer dkf(kf), dvf(vf); + p::store_f16(dkf.as(), dk16.as(), int(kv_cols), 0, n_cache, s); + p::store_f16(dvf.as(), dv16.as(), int(kv_cols), 0, n_cache, s); + } + + p::Kvq8 kq = use_q8 ? p::Kvq8{dkc.as(), dks.as(), tc.strided ? k_rs : 0} : p::Kvq8{}; + p::Kvq8 vq = use_q8 ? p::Kvq8{dvc.as(), dvs.as(), tc.strided ? v_rs : 0} : p::Kvq8{}; + + // Pass part_buf = nullptr so even rows == 1 routes through the batch kernel. + p::q4_qsa_attend(dq.as(), use_q8 ? nullptr : dk16.as(), use_q8 ? nullptr : dv16.as(), + kq, vq, dids.as(), sel_cap, dcnt.as(), dout.as(), + nullptr, 0, dim, n_head, n_kv, rows, scale, tc.ring, s); + ck(g::stream_synchronize(s)); + + // Reconstruct exact dequantized K/V on CPU + std::vector kd(size_t(n_cache) * kv_cols), vd(size_t(n_cache) * kv_cols); + if (use_q8) { + auto kc = dkc.read(size_t(n_cache) * k_rs); + auto ks = dks.read(size_t(n_cache) * (k_rs / 32)); + auto vc = dvc.read(size_t(n_cache) * v_rs); + auto vs = dvs.read(size_t(n_cache) * (v_rs / 32)); + for (int r = 0; r < n_cache; ++r) { + for (size_t c = 0; c < kv_cols; ++c) { + kd[size_t(r) * kv_cols + c] = float(kc[size_t(r) * k_rs + c]) * ggml_fp16_to_fp32(ks[size_t(r) * (k_rs / 32) + c / 32]); + vd[size_t(r) * kv_cols + c] = float(vc[size_t(r) * v_rs + c]) * ggml_fp16_to_fp32(vs[size_t(r) * (v_rs / 32) + c / 32]); + } + } + } else { + auto k16 = dk16.read(size_t(n_cache) * kv_cols); + auto v16 = dv16.read(size_t(n_cache) * kv_cols); + for (size_t i = 0; i < kd.size(); ++i) { + kd[i] = ggml_fp16_to_fp32(k16[i]); + vd[i] = ggml_fp16_to_fp32(v16[i]); + } + } + + // Sample rows for large n_ids cases to keep CPU reference fast while covering boundaries + std::vector check_rows; + if (rows <= 64 && sel_cap <= 512) { + check_rows.resize(rows); + std::iota(check_rows.begin(), check_rows.end(), 0); + } else { + for (int r : {0, 1, 7, 17, 31, 63, 128, 255, 384, rows - 1}) { + if (r >= 0 && r < rows && (check_rows.empty() || check_rows.back() != r)) + check_rows.push_back(r); + } + } + + auto got_all = dout.read(size_t(rows) * n_head * dim); + std::vector got_sub(check_rows.size() * n_head * dim, 0.0f); + std::vector ref_sub(check_rows.size() * n_head * dim, 0.0f); + for (size_t ri = 0; ri < check_rows.size(); ++ri) { + const int r = check_rows[ri]; + std::memcpy(got_sub.data() + ri * n_head * dim, + got_all.data() + size_t(r) * n_head * dim, + size_t(n_head) * dim * 4); + const int cnt = h_cnt[r]; + if (cnt <= 0) continue; + std::vector sc(cnt); + for (int h = 0; h < n_head; ++h) { + const int kvh = h / tc.G; + double mx = -1e300; + for (int j = 0; j < cnt; ++j) { + int cell = h_ids[size_t(r) * sel_cap + j]; + if (tc.ring > 0) cell %= tc.ring; + double dot = 0.0; + for (int d = 0; d < dim; ++d) + dot += double(q[(size_t(r) * n_head + h) * dim + d]) * + double(kd[(size_t(cell) * n_kv + kvh) * dim + d]); + sc[j] = dot * scale; + if (sc[j] > mx) mx = sc[j]; + } + double sum = 0.0; + for (int j = 0; j < cnt; ++j) { sc[j] = std::exp(sc[j] - mx); sum += sc[j]; } + for (int d = 0; d < dim; ++d) { + double acc = 0.0; + for (int j = 0; j < cnt; ++j) { + int cell = h_ids[size_t(r) * sel_cap + j]; + if (tc.ring > 0) cell %= tc.ring; + acc += sc[j] * double(vd[(size_t(cell) * n_kv + kvh) * dim + d]); + } + ref_sub[(ri * n_head + h) * dim + d] = float(acc / sum); + } + } + } + + char lbl[96]; + std::snprintf(lbl, sizeof(lbl), "q4_qsa_attend_batch %s %s", use_q8 ? "q8" : "f16", tc.name); + const float tol = (dim == 256 && tc.G <= 8) ? 2e-4f : 1e-4f; + bad += compare(got_sub, ref_sub, lbl, tol); + + if (tc.bench) { + const int warmup = 3, iters = 10; + for (int it = 0; it < warmup; ++it) { + p::q4_qsa_attend(dq.as(), use_q8 ? nullptr : dk16.as(), use_q8 ? nullptr : dv16.as(), + kq, vq, dids.as(), sel_cap, dcnt.as(), dout.as(), + nullptr, 0, dim, n_head, n_kv, rows, scale, tc.ring, s); + } + ck(g::stream_synchronize(s)); + const auto t0 = std::chrono::steady_clock::now(); + for (int it = 0; it < iters; ++it) { + p::q4_qsa_attend(dq.as(), use_q8 ? nullptr : dk16.as(), use_q8 ? nullptr : dv16.as(), + kq, vq, dids.as(), sel_cap, dcnt.as(), dout.as(), + nullptr, 0, dim, n_head, n_kv, rows, scale, tc.ring, s); + } + ck(g::stream_synchronize(s)); + const auto t1 = std::chrono::steady_clock::now(); + const double ms = std::chrono::duration(t1 - t0).count() / iters; + const double flops = 4.0 * double(rows) * double(n_head) * double(tc.n_ids) * double(dim); + const double tflops = (flops / (ms * 1e-3)) / 1e12; + std::printf(" bench %s: %.3f ms/call (%.2f TFLOP/s)\n", lbl, ms, tflops); + } + } + } + } return bad; } diff --git a/engine/metal/src/poly/qwen4.cpp b/engine/metal/src/poly/qwen4.cpp index 6b040de0f2..d68445161e 100644 --- a/engine/metal/src/poly/qwen4.cpp +++ b/engine/metal/src/poly/qwen4.cpp @@ -487,9 +487,12 @@ void q4_qsa_attend(const float* q, const uint16_t* keys, const uint16_t* vals, K gpu::metal::Access::R, gpu::metal::Access::R, gpu::metal::Access::W }; const size_t s[10] = {q_b, 0ULL, 0ULL, 0ULL, 0ULL, 0ULL, 0ULL, ids_b, cnt_b, q_b}; - const char* kbatch = is_q8 ? (G <= 8 ? "q4_qsa_attend_batch_q8_8" : "q4_qsa_attend_batch_q8_16") - : (G <= 8 ? "q4_qsa_attend_batch_f16_8" : "q4_qsa_attend_batch_f16_16"); - run(kbatch, a, stream, {uint32_t(n_kv), uint32_t(rows), 1}, 256, {a.p, 10, true, nullptr, m, s}); + const bool use_mma = (dim == 256 && G <= 8 && gpu::metal::optimize()); + const char* kbatch = use_mma + ? (is_q8 ? "q4_qsa_attend_batch_mma_q8_8" : "q4_qsa_attend_batch_mma_f16_8") + : (is_q8 ? (G <= 8 ? "q4_qsa_attend_batch_q8_8" : "q4_qsa_attend_batch_q8_16") + : (G <= 8 ? "q4_qsa_attend_batch_f16_8" : "q4_qsa_attend_batch_f16_16")); + run(kbatch, a, stream, {uint32_t(n_kv), uint32_t(rows), 1}, use_mma ? 128 : 256, {a.p, 10, true, nullptr, m, s}); } } diff --git a/engine/metal/src/poly/qwen4.metal b/engine/metal/src/poly/qwen4.metal index f907a5a9a8..7f5bd314ae 100644 --- a/engine/metal/src/poly/qwen4.metal +++ b/engine/metal/src/poly/qwen4.metal @@ -969,6 +969,344 @@ template [[host_name("q4_qsa_attend_batch_f16_16")]] kernel decltype(q4_qsa_atte template [[host_name("q4_qsa_attend_batch_q8_8")]] kernel decltype(q4_qsa_attend_batch_kernel) q4_qsa_attend_batch_kernel; template [[host_name("q4_qsa_attend_batch_q8_16")]] kernel decltype(q4_qsa_attend_batch_kernel) q4_qsa_attend_batch_kernel; +struct Row256Q8 { + uint2 raw; + half sc; +}; + +inline Row256Q8 prefetch_row256_q8(device const char* q8_codes, + device const half* q8_scales, + ulong cs, ulong ss, + int cell, int kvh, uint lane) { + if (cell < 0) return {uint2(0u), half(0.0h)}; + const ulong row = ulong(cell); + const ulong col_off = ulong(kvh * 256) + ulong(lane * 8u); + return { + *reinterpret_cast(q8_codes + row * cs + col_off), + q8_scales[row * ss + ulong(kvh * 8) + ulong(lane >> 2u)] + }; +} + +inline uint4 prefetch_row256_f16(device const half* f16_ptr, + ulong f16_rs, + int cell, int kvh, uint lane) { + if (cell < 0) return uint4(0u); + const ulong col_off = ulong(kvh * 256) + ulong(lane * 8u); + return *reinterpret_cast(f16_ptr + ulong(cell) * f16_rs + col_off); +} + +inline void store_row256_q8(Row256Q8 b, threadgroup half* dst_row, uint lane) { + *reinterpret_cast(dst_row + lane * 8u) = half4(as_type(b.raw.x)) * b.sc; + *reinterpret_cast(dst_row + lane * 8u + 4u) = half4(as_type(b.raw.y)) * b.sc; +} + +inline void store_row256_f16(uint4 raw, threadgroup half* dst_row, uint lane) { + *reinterpret_cast(dst_row + lane * 8u) = raw; +} + +// High-throughput simdgroup_matrix batch QSA attention for dim == 256, G <= 8. +// 128 threads = 4 warps; grid = (n_kv, rows, 1). +// Loads full 256-dim K/V rows coalesced across all 32 lanes (256 B Q8 / 512 B FP16 per row, +// zero scatter, zero divergence) into a shared 16-row tile skv[16][264], software-pipelining +// the next 16 rows' device loads in registers while 16 back-to-back 8x8x8 MMAs execute on +// the current tile (2x2 key/dim split for Q*K^T, 64 dims/warp for P*V). +// Total TG memory = 16,224 B (<= 16 KB -> 2 concurrent TGs/core, padded strides avoid bank conflicts). +template +kernel void q4_qsa_attend_batch_mma_kernel(constant Q4Args& a [[buffer(0)]], + uint2 group [[threadgroup_position_in_grid]], + uint tid [[thread_index_in_threadgroup]]) { + constexpr int kQStride = 264; // 256 + 8 half -> 4 banks mod 32 + constexpr int kKvStride = 264; // 256 + 8 half -> 4 banks mod 32 (16-byte aligned rows) + constexpr int kPfStride = 64; // 64 float + constexpr int kPhStride = 72; // 64 + 8 half -> 4 banks mod 32 + + threadgroup half sq_h[8][kQStride]; // 4,224 B + threadgroup uint4 skv_raw[(16 * kKvStride) / 8]; // 8,448 B -> skv[16][264] + o_tmp + threadgroup float sp_f[8][kPfStride]; // 2,048 B + threadgroup uint4 sp_h_raw[(8 * kPhStride) / 8]; // 1,152 B -> sp_h[8][72] + sp_tmp[2][64] + threadgroup int scell[kQsaChunk]; // 256 B + threadgroup float s_m[8]; // 32 B + threadgroup float s_l[8]; // 32 B + threadgroup float s_alpha[8]; // 32 B + + threadgroup half* skv = reinterpret_cast(skv_raw); + threadgroup half* sp_h = reinterpret_cast(sp_h_raw); + threadgroup float* sp_tmp = reinterpret_cast(sp_h_raw); + + const int sel_cap = a.n[0]; + const int n_head = a.n[3]; + const int n_kv = a.n[4]; + const int ring = a.n[5]; + const float scale = a.f[0]; + + const int kvh = int(group.x); + const int qi = int(group.y); + const int G = n_head / n_kv; + const uint lane = tid & 31u; + const uint warp = tid >> 5u; + + device const int* sel_ids = static_cast(a.p[7]); + device const int* sel_count = static_cast(a.p[8]); + device float* out = static_cast(a.p[9]); + const int n_ids = sel_count[qi]; + + device float* o_base = out + (ulong(qi) * ulong(n_head) + ulong(kvh * G)) * 256ul; + if (n_ids <= 0) { + for (int h = 0; h < G; ++h) { + o_base[ulong(h) * 256ul + ulong(tid)] = 0.0f; + o_base[ulong(h) * 256ul + ulong(tid) + 128ul] = 0.0f; + } + return; + } + + device const float* q_base = static_cast(a.p[0]) + + (ulong(qi) * ulong(n_head) + ulong(kvh * G)) * 256ul; + for (int h = 0; h < 8; ++h) { + if (h < G) { + sq_h[h][tid] = half(q_base[ulong(h) * 256ul + ulong(tid)]); + sq_h[h][tid + 128u] = half(q_base[ulong(h) * 256ul + ulong(tid) + 128ul]); + } else { + sq_h[h][tid] = half(0.0h); + sq_h[h][tid + 128u] = half(0.0h); + } + } + if (tid < 8u) { + s_m[tid] = -FLT_MAX; + s_l[tid] = 0.0f; + s_alpha[tid] = 0.0f; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + + device const half* k_f16 = static_cast(a.p[1]); + device const half* v_f16 = static_cast(a.p[2]); + device const char* k_codes = static_cast(a.p[3]); + device const half* k_scales = static_cast(a.p[4]); + device const char* v_codes = static_cast(a.p[5]); + device const half* v_scales = static_cast(a.p[6]); + const ulong k_cs = a.kv_rs; + const ulong k_ss = k_cs >> 5; + const ulong v_cs = a.v_rs; + const ulong v_ss = v_cs >> 5; + const ulong kv_f16_rs = ulong(n_kv) * 256ul; + + // Warp-private 528-float slice inside skv (2,112 B): holds all 8 O_acc tiles (512 floats) at once. + threadgroup float* o_tmp = reinterpret_cast(skv + warp * 4u * uint(kKvStride)); + const uint kh = warp >> 1u; + const uint dh = warp & 1u; + + simdgroup_float8x8 O_acc[8]; +#pragma clang loop unroll(full) + for (int j = 0; j < 8; ++j) { + O_acc[j] = make_filled_simdgroup_matrix(0.0f); + } + + for (int c0 = 0; c0 < n_ids; c0 += kQsaChunk) { + const int n_here = min(kQsaChunk, n_ids - c0); + if (int(tid) < kQsaChunk) { + int cell = (int(tid) < n_here) ? sel_ids[ulong(qi) * ulong(sel_cap) + ulong(c0 + int(tid))] : -1; + if (cell >= 0 && ring > 0) cell %= ring; + scell[tid] = cell; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + + // Phase 1: Q (8x256) * K_chunk^T (256x64) -> sp_f (8x64), software-pipelined 16 K rows/step. + { + Row256Q8 kq_buf[4]; + uint4 kf_buf[4]; +#pragma clang loop unroll(full) + for (uint r = 0u; r < 4u; ++r) { + const int cell = scell[warp * 4u + r]; + if (IS_Q8) kq_buf[r] = prefetch_row256_q8(k_codes, k_scales, k_cs, k_ss, cell, kvh, lane); + else kf_buf[r] = prefetch_row256_f16(k_f16, kv_f16_rs, cell, kvh, lane); + } + + for (int c_tile = 0; c_tile < n_here; c_tile += 16) { +#pragma clang loop unroll(full) + for (uint r = 0u; r < 4u; ++r) { + threadgroup half* dst = skv + (warp * 4u + r) * uint(kKvStride); + if (IS_Q8) store_row256_q8(kq_buf[r], dst, lane); + else store_row256_f16(kf_buf[r], dst, lane); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + + if (c_tile + 16 < n_here) { +#pragma clang loop unroll(full) + for (uint r = 0u; r < 4u; ++r) { + const int cell = scell[uint(c_tile + 16) + warp * 4u + r]; + if (IS_Q8) kq_buf[r] = prefetch_row256_q8(k_codes, k_scales, k_cs, k_ss, cell, kvh, lane); + else kf_buf[r] = prefetch_row256_f16(k_f16, kv_f16_rs, cell, kvh, lane); + } + } + + if (c_tile + int(kh) * 8 < n_here) { + simdgroup_float8x8 S_acc = make_filled_simdgroup_matrix(0.0f); + const int d_base = int(dh) * 128; + threadgroup half* sk_half = skv + kh * 8u * uint(kKvStride) + d_base; +#pragma clang loop unroll(full) + for (int d = 0; d < 128; d += 8) { + simdgroup_half8x8 mq, mk; + simdgroup_load(mq, &sq_h[0][d_base + d], kQStride, ulong2(0, 0), false); + simdgroup_load(mk, sk_half + d, kKvStride, ulong2(0, 0), true); + simdgroup_multiply_accumulate(S_acc, mq, mk, S_acc); + } + if (dh == 0u) { + simdgroup_store(S_acc, &sp_f[0][c_tile + int(kh) * 8], kPfStride, ulong2(0, 0), false); + } else { + simdgroup_store(S_acc, sp_tmp + kh * 64u, 8, ulong2(0, 0), false); + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + + const uint mh = tid >> 4u; + const uint mc = tid & 15u; + if (c_tile + int(mc) < n_here) { + sp_f[mh][c_tile + int(mc)] += sp_tmp[(mc >> 3u) * 64u + mh * 8u + (mc & 7u)]; + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + } + + // Phase 2: FP32 online softmax. Each of 4 warps handles 2 query heads. + for (int hh = 0; hh < 2; ++hh) { + const int h = int(warp) + hh * 4; + if (h < G) { + const float s0 = (int(lane) < n_here) ? (sp_f[h][lane] * scale) : -FLT_MAX; + const float s1 = (int(lane) + 32 < n_here) ? (sp_f[h][lane + 32u] * scale) : -FLT_MAX; + const float m_chunk = simd_max(max(s0, s1)); + const float m_old = s_m[h]; + const float m_new = max(m_old, m_chunk); + const float alpha = (m_old > -FLT_MAX * 0.5f) ? exp(m_old - m_new) : 0.0f; + const float w0 = (int(lane) < n_here) ? exp(s0 - m_new) : 0.0f; + const float w1 = (int(lane) + 32 < n_here) ? exp(s1 - m_new) : 0.0f; + const float l_chunk = simd_sum(w0 + w1); + sp_h[h * kPhStride + int(lane)] = half(w0); + sp_h[h * kPhStride + int(lane) + 32] = half(w1); + if (lane == 0u) { + s_alpha[h] = alpha; + s_m[h] = m_new; + s_l[h] = fma(s_l[h], alpha, l_chunk); + } + } else { + sp_h[h * kPhStride + int(lane)] = half(0.0h); + sp_h[h * kPhStride + int(lane) + 32] = half(0.0h); + if (lane == 0u) s_alpha[h] = 0.0f; + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + + // Phase 3: P (8x64) * V_chunk (64x256) -> O_acc[0..7] (8x64 per warp). + if (c0 > 0) { + bool need_rescale = false; + for (int h = 0; h < G; ++h) { + if (s_alpha[h] != 1.0f) need_rescale = true; + } + if (need_rescale) { + const uint r0 = lane >> 3u; + const uint r1 = (lane + 32u) >> 3u; + const float a0 = s_alpha[r0]; + const float a1 = s_alpha[r1]; +#pragma clang loop unroll(full) + for (int j = 0; j < 8; ++j) { + simdgroup_store(O_acc[j], o_tmp + uint(j) * 64u, 8, ulong2(0, 0), false); + } + simdgroup_barrier(mem_flags::mem_threadgroup); +#pragma clang loop unroll(full) + for (uint j = 0u; j < 8u; ++j) { + o_tmp[j * 64u + lane] *= a0; + o_tmp[j * 64u + lane + 32u] *= a1; + } + simdgroup_barrier(mem_flags::mem_threadgroup); +#pragma clang loop unroll(full) + for (int j = 0; j < 8; ++j) { + simdgroup_load(O_acc[j], o_tmp + uint(j) * 64u, 8, ulong2(0, 0), false); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + } + } + + // Software-pipelined 16 full V rows/step overlapping device prefetch with 16 back-to-back MMAs. + { + Row256Q8 vq_buf[4]; + uint4 vf_buf[4]; +#pragma clang loop unroll(full) + for (uint r = 0u; r < 4u; ++r) { + const int cell = scell[warp * 4u + r]; + if (IS_Q8) vq_buf[r] = prefetch_row256_q8(v_codes, v_scales, v_cs, v_ss, cell, kvh, lane); + else vf_buf[r] = prefetch_row256_f16(v_f16, kv_f16_rs, cell, kvh, lane); + } + + const uint d_warp = warp * 64u; + for (int k0 = 0; k0 < n_here; k0 += 16) { +#pragma clang loop unroll(full) + for (uint r = 0u; r < 4u; ++r) { + threadgroup half* dst = skv + (warp * 4u + r) * uint(kKvStride); + if (IS_Q8) store_row256_q8(vq_buf[r], dst, lane); + else store_row256_f16(vf_buf[r], dst, lane); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + + if (k0 + 16 < n_here) { +#pragma clang loop unroll(full) + for (uint r = 0u; r < 4u; ++r) { + const int cell = scell[uint(k0 + 16) + warp * 4u + r]; + if (IS_Q8) vq_buf[r] = prefetch_row256_q8(v_codes, v_scales, v_cs, v_ss, cell, kvh, lane); + else vf_buf[r] = prefetch_row256_f16(v_f16, kv_f16_rs, cell, kvh, lane); + } + } + + simdgroup_half8x8 mp0; + simdgroup_load(mp0, sp_h + k0, kPhStride, ulong2(0, 0), false); +#pragma clang loop unroll(full) + for (int j = 0; j < 8; ++j) { + simdgroup_half8x8 mv; + simdgroup_load(mv, skv + d_warp + uint(j) * 8u, kKvStride, ulong2(0, 0), false); + simdgroup_multiply_accumulate(O_acc[j], mp0, mv, O_acc[j]); + } + if (k0 + 8 < n_here) { + simdgroup_half8x8 mp1; + simdgroup_load(mp1, sp_h + k0 + 8, kPhStride, ulong2(0, 0), false); + threadgroup half* sv1 = skv + 8u * uint(kKvStride) + d_warp; +#pragma clang loop unroll(full) + for (int j = 0; j < 8; ++j) { + simdgroup_half8x8 mv; + simdgroup_load(mv, sv1 + uint(j) * 8u, kKvStride, ulong2(0, 0), false); + simdgroup_multiply_accumulate(O_acc[j], mp1, mv, O_acc[j]); + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + } + } + } + + // Phase 4: Final output normalization O_acc[0..7] / s_l -> out (all 8 tiles at once). + const uint r0 = lane >> 3u; + const uint c0_l = lane & 7u; + const uint r1 = (lane + 32u) >> 3u; + const float inv_l0 = (int(r0) < G && s_l[r0] > 0.0f) ? (1.0f / s_l[r0]) : 0.0f; + const float inv_l1 = (int(r1) < G && s_l[r1] > 0.0f) ? (1.0f / s_l[r1]) : 0.0f; +#pragma clang loop unroll(full) + for (int j = 0; j < 8; ++j) { + simdgroup_store(O_acc[j], o_tmp + uint(j) * 64u, 8, ulong2(0, 0), false); + } + simdgroup_barrier(mem_flags::mem_threadgroup); + const uint d_base = warp * 64u + c0_l; + if (int(r0) < G) { +#pragma clang loop unroll(full) + for (uint j = 0u; j < 8u; ++j) { + o_base[ulong(r0) * 256ul + ulong(d_base + j * 8u)] = o_tmp[j * 64u + lane] * inv_l0; + } + } + if (int(r1) < G) { +#pragma clang loop unroll(full) + for (uint j = 0u; j < 8u; ++j) { + o_base[ulong(r1) * 256ul + ulong(d_base + j * 8u)] = o_tmp[j * 64u + lane + 32u] * inv_l1; + } + } +} + +template [[host_name("q4_qsa_attend_batch_mma_f16_8")]] kernel decltype(q4_qsa_attend_batch_mma_kernel) q4_qsa_attend_batch_mma_kernel; +template [[host_name("q4_qsa_attend_batch_mma_q8_8")]] kernel decltype(q4_qsa_attend_batch_mma_kernel) q4_qsa_attend_batch_mma_kernel; + // ---- 4. MTP (blk.40) Input Fusion & 2D Split ---- kernel void q4_mtp_eh_concat_kernel(constant Q4Args& a [[buffer(0)]],