diff --git a/metal/kernels/moe_mm.metal b/metal/kernels/moe_mm.metal index 9121c83f..0d689876 100644 --- a/metal/kernels/moe_mm.metal +++ b/metal/kernels/moe_mm.metal @@ -463,6 +463,88 @@ template <> struct W4 { // 32 a block: d, 16 bytes; low nibbles are } }; +// W8: the runs k .. k + 3 and k + 16 .. k + 19 of a row (k % 32 < 16): one 32-group, so the per-group fields (scale, +// sign word) are read once. The generic one is two W4. +template struct W8 { + static inline void run(device const uchar* row, int k, threadgroup const uint* tab, thread half4& a, thread half4& b) { + a = W4::run(row, k, tab); + b = W4::run(row, k + 16, tab); + } +}; +template <> struct W8 { + static inline void run(device const uchar* row, int k, threadgroup const uint* tab, thread half4& a, thread half4& b) { + device const uchar* bl = row + (k >> 8) * 98; + const int ib = (k & 255) >> 5, l = (k & 31) >> 3, hh = (k & 7) >> 2; + const uint aux = rd32(bl + 2 + 64 + 4 * ib); + threadgroup const uchar* ks = (threadgroup const uchar*)(tab + 256); + const float sc = rdh(bl) * (0.5f + float(aux >> 28)) * 0.5f; + const uint s0 = ks[(aux >> (7 * l)) & 127], s1 = ks[(aux >> (7 * (l + 2))) & 127]; + device const uchar* qs = bl + 2 + 8 * ib + hh; + a = w4_signed(tab[qs[2 * l]], hh ? s0 >> 4 : s0, sc); + b = w4_signed(tab[qs[2 * l + 4]], hh ? s1 >> 4 : s1, sc); + } +}; +template <> struct W8 { + static inline void run(device const uchar* row, int k, threadgroup const uint* tab, thread half4& a, thread half4& b) { + device const uchar* bl = row + (k >> 8) * 66; + const int ib = (k & 255) >> 5, l = (k & 31) >> 3, hh = (k & 7) >> 2; + const uint a0 = rd32(bl + 2 + 8 * ib), a1 = rd32(bl + 2 + 8 * ib + 4); + threadgroup const uchar* ks = (threadgroup const uchar*)(tab + 512); + const float sc = rdh(bl) * (0.5f + float(a1 >> 28)) * 0.25f; + const uint i0 = (a0 >> (8 * l)) & 255, i1 = (a0 >> (8 * (l + 2))) & 255; + const uint s0 = ks[(a1 >> (7 * l)) & 127], s1 = ks[(a1 >> (7 * (l + 2))) & 127]; + a = w4_signed(tab[2 * i0 + hh], hh ? s0 >> 4 : s0, sc); + b = w4_signed(tab[2 * i1 + hh], hh ? s1 >> 4 : s1, sc); + } +}; +template <> struct W8 { + static inline void run(device const uchar* row, int k, threadgroup const uint* tab, thread half4& a, thread half4& b) { + device const uchar* bl = row + (k >> 8) * 74; + const int ib = (k & 255) >> 5, l = (k & 31) >> 3, hh = (k & 7) >> 2; + device const ushort* q = (device const ushort*)(bl + 2) + 4 * ib; + const uint v0 = q[l], v1 = q[l + 2]; + threadgroup const uchar* ks = (threadgroup const uchar*)(tab + 1024); + const uint scb = bl[66 + ib]; + const float d = rdh(bl); + const float sc0 = d * (0.5f + float((scb >> (4 * (l >> 1))) & 15)) * 0.25f; + const float sc1 = d * (0.5f + float((scb >> (4 * ((l + 2) >> 1))) & 15)) * 0.25f; + const uint s0 = ks[v0 >> 9], s1 = ks[v1 >> 9]; + a = w4_signed(tab[2 * (v0 & 511) + hh], hh ? s0 >> 4 : s0, sc0); + b = w4_signed(tab[2 * (v1 & 511) + hh], hh ? s1 >> 4 : s1, sc1); + } +}; +template <> struct W8 { + static inline void run(device const uchar* row, int k, threadgroup const uint* tab, thread half4& a, thread half4& b) { + device const uchar* bl = row + (k >> 8) * 82; + const int ib = (k & 255) >> 5, l = (k & 31) >> 3, hh = (k & 7) >> 2; + const uint qh = bl[66 + ib], scb = bl[74 + ib]; + const float d = rdh(bl); + const uint i0 = uint(bl[2 + 4 * ib + l]) | ((qh << (8 - 2 * l)) & 0x300); + const uint i1 = uint(bl[2 + 4 * ib + l + 2]) | ((qh << (8 - 2 * (l + 2))) & 0x300); + const uint s0 = bl[2 + 32 + 4 * ib + l], s1 = bl[2 + 32 + 4 * ib + l + 2]; + const float sc0 = d * (0.5f + float((scb >> (4 * (l >> 1))) & 15)) * 0.25f; + const float sc1 = d * (0.5f + float((scb >> (4 * ((l + 2) >> 1))) & 15)) * 0.25f; + a = w4_signed(tab[2 * i0 + hh], hh ? s0 >> 4 : s0, sc0); + b = w4_signed(tab[2 * i1 + hh], hh ? s1 >> 4 : s1, sc1); + } +}; +template <> struct W8 { + static inline void run(device const uchar* row, int k, threadgroup const uint* tab, thread half4& a, thread half4& b) { + device const uchar* bl = row + (k >> 8) * 110; + const int ib = (k & 255) >> 5, l = (k & 31) >> 3, hh = (k & 7) >> 2; + const uint qh = bl[66 + ib], scb = bl[106 + (ib >> 1)]; + const float sc = rdh(bl) * float(1 + 2 * ((scb >> (4 * (ib & 1))) & 15)); + const int l1 = l + 2; + const uint i0 = hh ? (uint(bl[2 + 8 * ib + 2 * l + 1]) | ((qh << (7 - 2 * l)) & 256)) + : (uint(bl[2 + 8 * ib + 2 * l]) | ((qh << (8 - 2 * l)) & 256)); + const uint i1 = hh ? (uint(bl[2 + 8 * ib + 2 * l1 + 1]) | ((qh << (7 - 2 * l1)) & 256)) + : (uint(bl[2 + 8 * ib + 2 * l1]) | ((qh << (8 - 2 * l1)) & 256)); + const uint s0 = bl[74 + 4 * ib + l], s1 = bl[74 + 4 * ib + l1]; + a = w4_signed(tab[i0], hh ? s0 >> 4 : s0, sc); + b = w4_signed(tab[i1], hh ? s1 >> 4 : s1, sc); + } +}; + template kernel void mm_gu3(device const uchar* W [[buffer(0)]], device const half* XS [[buffer(1)]], device half* HS [[buffer(2)]], device const int2* tiles [[buffer(3)]], constant MmArgs& a [[buffer(4)]], @@ -487,13 +569,31 @@ kernel void mm_gu3(device const uchar* W [[buffer(0)]], device const half* XS [[ for (uint16_t i = 0; i < accg.get_capacity(); ++i) if (accg.is_valid_element(i)) { accg[i] = 0.0f; accu[i] = 0.0f; } for (int k0 = 0; k0 < int(a.n_embd); k0 += TK) { + const uint16_t cap = rg.get_capacity(), half_cap = cap / 2; #pragma clang loop unroll(full) - for (uint16_t i = 0; i < rg.get_capacity(); i += 4) { + for (uint16_t i = 0; i < half_cap; i += 4) { const auto ix = rg.get_multidimensional_index(i); + const auto iy = rg.get_multidimensional_index(i + half_cap); const int k = k0 + ix[0], n = ix[1]; - const half4 wg = W4::run(g0 + ulong(n) * a.gu_row, k, tab), wu = W4::run(u0 + ulong(n) * a.gu_row, k, tab); + device const uchar* rgw = g0 + ulong(n) * a.gu_row; + device const uchar* ruw = u0 + ulong(n) * a.gu_row; + half4 wg, wu, wg2, wu2; + if (TK == 32 && iy[0] == ix[0] + 16 && iy[1] == ix[1] && (ix[0] & 31) < 16) { + // the lane's two runs of this row sit in one 32-group (the layout: element i + cap / 2 is k + 16) + W8::run(rgw, k, tab, wg, wg2); + W8::run(ruw, k, tab, wu, wu2); + } else { + const int k2 = k0 + iy[0]; + device const uchar* rgw2 = g0 + ulong(iy[1]) * a.gu_row; + device const uchar* ruw2 = u0 + ulong(iy[1]) * a.gu_row; + wg = W4::run(rgw, k, tab); wu = W4::run(ruw, k, tab); + wg2 = W4::run(rgw2, k2, tab); wu2 = W4::run(ruw2, k2, tab); + } rg[i] = wg.x; rg[i + 1] = wg.y; rg[i + 2] = wg.z; rg[i + 3] = wg.w; ru[i] = wu.x; ru[i + 1] = wu.y; ru[i + 2] = wu.z; ru[i + 3] = wu.w; + const uint16_t j = i + half_cap; + rg[j] = wg2.x; rg[j + 1] = wg2.y; rg[j + 2] = wg2.z; rg[j + 3] = wg2.w; + ru[j] = wu2.x; ru[j + 1] = wu2.y; ru[j + 2] = wu2.z; ru[j + 3] = wu2.w; } tA = tX.template slice(k0, row0); op.run(tA, rg, accg); diff --git a/metal/kernels/qsa_prompt.metal b/metal/kernels/qsa_prompt.metal index 6696cde8..eef0c236 100644 --- a/metal/kernels/qsa_prompt.metal +++ b/metal/kernels/qsa_prompt.metal @@ -109,3 +109,174 @@ kernel void qsa_q_f16(device const float* q [[buffer(0)]], device half* qh [[buf uint gid [[thread_position_in_grid]]) { if (gid < n) qh[gid] = half(q[gid]); } + +// qsa_score as a GEMM (fp32 operands, so the selection sees qsa_score's values to fp32 rounding): S[(t, h)][b] = +// qidx[t][h] . pooled[b] for 16 tokens x IH heads (64 rows) by 64 blocks a threadgroup; the epilogue sums relu over +// the heads. The tail block n_bid (the `dead` key, + 1e9 when it has cells) and blocks past it are left to the +// scalar path: the tail is scored here by one simdgroup a token; blocks > n_bid are not written (qsa_topk reads +// b <= n_bid). grid (ceil(max blocks / 64), ceil(T / 16)), 128 threads. +kernel void qsa_score_mm(device const float* qidx [[buffer(0)]], device const float* pooled [[buffer(1)]], + device const float* dead [[buffer(2)]], device float* scores [[buffer(3)]], + constant QsaArgs& a [[buffer(4)]], + uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]], + ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) { + threadgroup float ot[64 * 64]; + const int b0 = int(tg.x) * 64, t0 = int(tg.y) * 16; + const uint nb_all = (a.pos0 + a.n_tok) / 4 + 1; // blocks any token of the chunk can score + tensor, tensor_inline> tQ((device float*)qidx, dextents(ID, int(a.n_tok) * IH)); + tensor, tensor_inline> tK((device float*)pooled, dextents(ID, int(nb_all))); + tensor, tensor_inline> tO(ot, dextents(64, 64)); + constexpr auto desc = matmul2d_descriptor(64, 64, dynamic_length_v, false, true, false); + matmul2d> op; + auto mA = tQ.slice(0, t0 * IH); + auto mB = tK.slice(0, b0); + op.run(mA, mB, tO); + threadgroup_barrier(mem_flags::mem_threadgroup); + const uint stride = a.max_cells / 4 + 2; + for (int idx = tid; idx < 16 * 64; idx += 128) { + const int tt = idx >> 6, j = idx & 63, t = t0 + tt, b = b0 + j; + if (t >= int(a.n_tok)) continue; + const uint n_kv = a.pos0 + uint(t) + 1, n_bid = n_kv >> 2; + if (uint(b) >= n_bid) continue; + float s = 0.0f; + for (int h = 0; h < IH; ++h) s += max(ot[(tt * IH + h) * 64 + j], 0.0f); + scores[uint(t) * stride + b] = s; + } + // the tail block of each token in this threadgroup's block range (the first column threadgroup does it) + if (tg.x == 0) + for (int tt = sg; tt < 16; tt += 4) { + const int t = t0 + tt; + if (t >= int(a.n_tok)) break; + const uint n_kv = a.pos0 + uint(t) + 1, n_bid = n_kv >> 2; + float k[4]; + for (int i = 0; i < 4; ++i) k[i] = dead[lane + 32 * i]; + float s = 0.0f; + for (int h = 0; h < IH; ++h) { + float d = 0.0f; + for (int i = 0; i < 4; ++i) d = fma(qidx[(t * IH + h) * ID + lane + 32 * i], k[i], d); + d = simd_sum(d); + s += max(d, 0.0f); + } + if ((n_kv & 3) != 0) s += 1e9f; + if (lane == 0) scores[uint(t) * stride + n_bid] = s; + } +} + +// qsa_flash: the whole attention of a (kv head g, token t) in one threadgroup (no split-K partials, no merge): the +// width selected cells in chunks of 64 with an online softmax; 4 simdgroups, simdgroup s owns dims 64 s .. 64 s + 63 +// (its slice of S's K sum and its 64 output dims). Out: xq = (acc / l) * sigmoid(gate) as fp16 (attn_output's GEMM +// operand). grid (QKV, n_tok), 128 threads. +kernel void qsa_flash(device const half* qh [[buffer(0)]], device const char* kq [[buffer(1)]], + device const char* vq [[buffer(2)]], device const half* ksc [[buffer(3)]], + device const half* vsc [[buffer(4)]], device const int* ids [[buffer(5)]], + device const float* qfull [[buffer(6)]], device half* xqh [[buffer(7)]], constant QsaArgs& a [[buffer(8)]], + uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]], + ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) { + constexpr int HPG = QH / QKV; + threadgroup float sp[4][16 * QCH]; + threadgroup half p[16 * QCH]; + threadgroup int cid[QCH]; + threadgroup float vs[QCH]; + threadgroup float fac[16], lsum[16], mrun[16]; + const int g = int(tg.x), t = int(tg.y); + const uint n_kv = a.pos0 + uint(t) + 1, width = min(n_kv, uint(QBUDGET)); + const int nch = int((width + QCH - 1) / QCH); + if (tid < 16) { mrun[tid] = -INFINITY; lsum[tid] = 0.0f; } + constexpr auto dS = matmul2d_descriptor(16, QCH, 32, false, true, false, matmul2d_descriptor::mode::multiply_accumulate); + constexpr auto dO = matmul2d_descriptor(16, 64, QCH, false, true, false, matmul2d_descriptor::mode::multiply_accumulate); + matmul2d opS; + matmul2d opO; + tensor, tensor_inline> tQ((device half*)qh + (uint(t) * QH + g * HPG) * QD, + dextents(QD, HPG)); + tensor, tensor_inline> tP(p, dextents(QCH, 16)); + auto rv = opO.template get_right_input_cooperative_tensor(); + auto acc = opO.template get_destination_cooperative_tensor<__tensor_ops_detail::__remove_addrspace_t, + __tensor_ops_detail::__remove_addrspace_t, float>(); + for (uint16_t i = 0; i < acc.get_capacity(); ++i) + if (acc.is_valid_element(i)) acc[i] = 0.0f; + const int d0 = sg * 64; + for (int ch = 0; ch < nch; ++ch) { + const int c0 = ch * QCH, nc = min(QCH, int(width) - c0); + threadgroup_barrier(mem_flags::mem_threadgroup); + if (tid < QCH) { + const int id = tid < nc ? ids[t * QBUDGET + c0 + tid] : -1; + cid[tid] = id; + vs[tid] = id >= 0 ? float(vsc[(uint(id) * QKV + g) * 4 + sg * 0]) : 0.0f; // (per-simdgroup scale below) + } + threadgroup_barrier(mem_flags::mem_threadgroup); + // S partial over this simdgroup's 64 dims + { + auto rk = opS.template get_right_input_cooperative_tensor(); + auto tA = tQ.template slice<32, 16>(d0, 0); + auto s = opS.template get_destination_cooperative_tensor<__tensor_ops_detail::__remove_addrspace_t, + __tensor_ops_detail::__remove_addrspace_t, float>(); + for (uint16_t i = 0; i < s.get_capacity(); ++i) + if (s.is_valid_element(i)) s[i] = 0.0f; + for (int k0 = d0; k0 < d0 + 64; k0 += 32) { +#pragma clang loop unroll(full) + for (uint16_t i = 0; i < rk.get_capacity(); i += 4) { + const auto ix = rk.get_multidimensional_index(i); + const int k = k0 + ix[0], c = ix[1], id = cid[c]; + half4 w = half4(0.0h); + if (id >= 0) { + const uint row = uint(id) * QKV + g; + const char4 q4 = *(device const char4*)(kq + row * QD + k); + w = half4(float4(q4) * float(ksc[row * 4 + (k >> 6)])); + } + rk[i] = w.x; rk[i + 1] = w.y; rk[i + 2] = w.z; rk[i + 3] = w.w; + } + tA = tQ.template slice<32, 16>(k0, 0); + opS.run(tA, rk, s); + } + tensor, tensor_inline> tS(sp[sg], dextents(QCH, 16)); + s.store(tS); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + // online softmax per head row: simdgroup 0, lane = row + if (sg == 0 && lane < 16) { + if (lane < HPG) { + float m = mrun[lane]; + for (int c = 0; c < nc; ++c) { + const int q = lane * QCH + c; + m = max(m, (((sp[0][q] + sp[1][q]) + (sp[2][q] + sp[3][q])) * 0.0625f)); + } + const float f = exp(mrun[lane] - m); + float l = lsum[lane] * f; + for (int c = 0; c < QCH; ++c) { + const int q = lane * QCH + c; + const float e = c < nc ? exp(((sp[0][q] + sp[1][q]) + (sp[2][q] + sp[3][q])) * 0.0625f - m) : 0.0f; + l += e; + p[q] = half(e); + } + mrun[lane] = m; + lsum[lane] = l; + fac[lane] = f; + } else { + for (int c = 0; c < QCH; ++c) p[lane * QCH + c] = half(0.0f); + fac[lane] = 0.0f; + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + // rescale this simdgroup's accumulator rows, then acc += P V over its 64 dims + for (uint16_t i = 0; i < acc.get_capacity(); ++i) + if (acc.is_valid_element(i)) acc[i] *= fac[acc.get_multidimensional_index(i)[1]]; +#pragma clang loop unroll(full) + for (uint16_t i = 0; i < rv.get_capacity(); ++i) { + const auto ix = rv.get_multidimensional_index(i); // (cell, dim) + const int c = ix[0], d = d0 + ix[1], id = cid[c]; + rv[i] = id >= 0 ? half(float(vq[(uint(id) * QKV + g) * QD + d]) * float(vsc[(uint(id) * QKV + g) * 4 + sg])) : half(0.0f); + } + opO.run(tP, rv, acc); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (uint16_t i = 0; i < acc.get_capacity(); ++i) + if (acc.is_valid_element(i)) { + const auto ix = acc.get_multidimensional_index(i); // (dim, row) + const int h = ix[1], d = d0 + ix[0]; + if (h < HPG) { + const int hh = g * HPG + h; + const float gate = qfull[(uint(t) * QH + hh) * 2 * QD + QD + d]; + xqh[(uint(t) * QH + hh) * QD + d] = half(acc[i] / lsum[h] * (1.0f / (1.0f + exp(-gate)))); + } + } +} diff --git a/metal/tests/prompt_chain.cpp b/metal/tests/prompt_chain.cpp index 9d0513b4..878c4f00 100644 --- a/metal/tests/prompt_chain.cpp +++ b/metal/tests/prompt_chain.cpp @@ -127,8 +127,7 @@ int main(int argc, char** argv) { // the expert GEMMs: "v2" (threadgroup-staged weights) or "v3:TM,TN,TK,SG" (register operands, TN rows a simdgroup) const char* gu_env = std::getenv("PC_GU"); const char* dn_env = std::getenv("PC_DN"); - // defaults (M5 Max, moe_mm_parity --v3 --bench): gate/up 16,32,32,4 for Q2_0 and 16,16,32,8 for the i-quants - // (both 5 threadgroups across n_ff), down 16,64,32,2 + // defaults (M5 Max, moe_mm_parity --v3 --bench): gate/up 16,32,32,4 (every format), down 16,64,32,2 const std::string gu_mode = gu_env ? gu_env : "v3:auto", dn_mode = dn_env ? dn_env : "v3:16,64,32,2"; auto v3_tile = [](const std::string& m, int* t) { std::sscanf(m.c_str() + 3, "%d,%d,%d,%d", &t[0], &t[1], &t[2], &t[3]); }; int gu3[4] = {16, 64, 16, 2}, dn3[4] = {16, 64, 16, 2}; @@ -136,7 +135,7 @@ int main(int argc, char** argv) { else if (gu_mode == "v3:auto") { gu3[0] = 16; gu3[1] = 32; gu3[2] = 32; gu3[3] = 4; } auto tl3 = [](const int* t) { return std::to_string(t[0]) + "_" + std::to_string(t[1]) + "_" + std::to_string(t[2]) + "_" + std::to_string(t[3]); }; auto gu3_for = [&](int type) -> std::string { - if (gu_mode == "v3:auto" && type != ref::Q2_0) return "16_16_32_8"; + (void)type; // one tile for every format since the paired-run decoders (W8) return tl3(gu3); }; if (dn_mode.rfind("v3:", 0) == 0) v3_tile(dn_mode, dn3); @@ -349,9 +348,14 @@ int main(int argc, char** argv) { mtl::Arg::B(pooled[qi]), mtl::Arg::V(a)}, 33, T, 256, "qsa prep"); if (pos0 + T > QB) { // some token's context is past the budget: select + if (qsa_mode == "mm") + D(P(lqsa, "qsa_score_mm"), {mtl::Arg::B(qidx), mtl::Arg::B(pooled[qi]), mtl::Arg::B(dead[qi]), + mtl::Arg::B(scores), mtl::Arg::V(a)}, + ((pos0 + T) / 4 + 1 + 63) / 64, (T + 15) / 16, 128, "qsa score"); + else D(P(lqsa, "qsa_score"), {mtl::Arg::B(qidx), mtl::Arg::B(pooled[qi]), mtl::Arg::B(dead[qi]), mtl::Arg::B(scores), mtl::Arg::V(a)}, - ((pos0 + T) / 4 + 1 + 7) / 8, T, 256, "qsa sel"); + ((pos0 + T) / 4 + 1 + 7) / 8, T, 256, "qsa score"); D(P(lqsa, "qsa_topk"), {mtl::Arg::B(scores), mtl::Arg::B(qids), mtl::Arg::V(a)}, T, 1, 1024, "qsa sel"); } else { // within the budget the selection is the identity: qsa_topk only writes 0..n_kv-1 @@ -414,7 +418,7 @@ int main(int argc, char** argv) { gu.p = gu_v3 ? P(lib, "mm_gu3_" + std::to_string(eg.type) + "_" + gu3_for(eg.type)) : P(lib, "mm_gu2_" + std::to_string(eg.type) + "_16_64_16_2", mtl::Constants().i(5, 0)); gu.args = {mtl::Arg::B(W), mtl::Arg::B(XS), mtl::Arg::B(HS), mtl::Arg::B(tiles), mtl::Arg::V(ma)}; - gu.tg[0] = gu_v3 ? (gu_mode == "v3:auto" && eg.type != ref::Q2_0 ? 256 : 32 * gu3[3]) : 64; + gu.tg[0] = gu_v3 ? 32 * gu3[3] : 64; gu.indirect = &meta; gu.ind_off = 2 * 4; push(gu, "experts gu"); @@ -495,6 +499,10 @@ int main(int argc, char** argv) { } if (breakdown) { // each class alone on the first chunk (pos0 0) and on a chunk at pos0 = PMAX - C (QSA past the budget) + if (PMAX > C) { // the classes of a chunk past the budget (score) too + run_chunk(std::max(0, PMAX - C), C, false); + all_cls.insert(cls.begin(), cls.end()); + } for (int p0 : {0, std::max(0, PMAX - C)}) { const std::string keep_only = only; std::map by; diff --git a/metal/tests/qsa_prompt_parity.cpp b/metal/tests/qsa_prompt_parity.cpp index 6a5dc4af..60486956 100644 --- a/metal/tests/qsa_prompt_parity.cpp +++ b/metal/tests/qsa_prompt_parity.cpp @@ -35,7 +35,8 @@ int main(int argc, char** argv) { for (size_t i = 0; i < (size_t)T * QH * QD; ++i) qcur.as()[i] = r.sym() * 3.0f; for (size_t i = 0; i < (size_t)T * QH * 2 * QD; ++i) qfull.as()[i] = r.sym(); mtl::Pipeline pa = cx.pipeline(lib, "qsa_attn"), pm = cx.pipeline(lib, "qsa_merge"), pmm = cx.pipeline(lib, "qsa_attn_mm"), - pq = cx.pipeline(lib, "qsa_q_f16"); + pq = cx.pipeline(lib, "qsa_q_f16"), pf = cx.pipeline(lib, "qsa_flash"); + mtl::Buffer xf = cx.alloc(2 * (size_t)T * QH * QD); int fails = 0; for (uint32_t pos0 : {0u, 30000u}) { // ids: within the budget the identity; past it 2051 distinct ascending cells < n_kv @@ -60,6 +61,8 @@ int main(int argc, char** argv) { D(pq, {mtl::Arg::B(qcur), mtl::Arg::B(qh), mtl::Arg::V(nq)}, (nq + 255) / 256, 1, 1, 256), D(pmm, {mtl::Arg::B(qh), mtl::Arg::B(kq), mtl::Arg::B(vq), mtl::Arg::B(ksc), mtl::Arg::B(vsc), mtl::Arg::B(ids), mtl::Arg::B(part), mtl::Arg::V(a)}, NCH, QKV, T, 32), D(pm, {mtl::Arg::B(part), mtl::Arg::B(qfull), mtl::Arg::B(xb), mtl::Arg::V(a)}, QH, T, 1, 256)}; + const mtl::Dispatch fl = D(pf, {mtl::Arg::B(qh), mtl::Arg::B(kq), mtl::Arg::B(vq), mtl::Arg::B(ksc), mtl::Arg::B(vsc), + mtl::Arg::B(ids), mtl::Arg::B(qfull), mtl::Arg::B(xf), mtl::Arg::V(a)}, QKV, T, 1, 128); if (bench) { auto timeit = [&](const std::vector& ds) { cx.warm(ds, 0.3); @@ -67,8 +70,8 @@ int main(int argc, char** argv) { for (int i = 0; i < 5; ++i) t.push_back(cx.run(ds)); return median(t); }; - std::printf("pos0 %5u, T %d: qsa_attn %.2f ms, qsa_attn_mm %.2f ms, merge %.2f ms\n", pos0, T, timeit({ref_ds[0]}) * 1e3, - timeit({mm_ds[1]}) * 1e3, timeit({ref_ds[1]}) * 1e3); + std::printf("pos0 %5u, T %d: qsa_attn %.2f ms, qsa_attn_mm %.2f ms, merge %.2f ms; qsa_flash (no merge) %.2f ms\n", pos0, + T, timeit({ref_ds[0]}) * 1e3, timeit({mm_ds[1]}) * 1e3, timeit({ref_ds[1]}) * 1e3, timeit({fl}) * 1e3); continue; } cx.run(ref_ds); @@ -83,6 +86,54 @@ int main(int argc, char** argv) { const bool ok = rel < 3e-3; fails += !ok; std::printf("pos0 %5u, T %d: qsa_attn_mm vs qsa_attn (after merge) rel L2 %.2e %s\n", pos0, T, rel, ok ? "PASS" : "FAIL"); + cx.run({fl}); + double sf = 0; + for (size_t i = 0; i < (size_t)T * QH * QD; ++i) { + const double e = ref::f16_to_f32(xf.as()[i]) - xa.as()[i]; + sf += e * e; + } + const double relf = std::sqrt(sf / sr); + const bool okf = relf < 3e-3; + fails += !okf; + std::printf("pos0 %5u, T %d: qsa_flash (fp16 out) vs qsa_attn + merge rel L2 %.2e %s\n", pos0, T, relf, okf ? "PASS" : "FAIL"); + } + // qsa_score_mm vs qsa_score at pos0 30000: the scores of every block <= n_bid + { + const uint32_t pos0 = 30000, MB = MAXC / 4 + 2, nb = (pos0 + T) / 4 + 1; + mtl::Buffer qidx = cx.alloc(4 * (size_t)T * 4 * 128), pooled = cx.alloc(4 * (size_t)MB * 128), dead = cx.alloc(4 * 128), + sa = cx.alloc(4 * (size_t)T * MB), sb = cx.alloc(4 * (size_t)T * MB); + for (size_t i = 0; i < (size_t)T * 4 * 128; ++i) qidx.as()[i] = r.sym(); + for (size_t i = 0; i < (size_t)MB * 128; ++i) pooled.as()[i] = r.sym(); + for (int i = 0; i < 128; ++i) dead.as()[i] = r.sym(); + QsaArgs a{pos0, 0, (uint32_t)MAXC, (uint32_t)T, 1e-6f}; + mtl::Pipeline ps = cx.pipeline(lib, "qsa_score"), psm = cx.pipeline(lib, "qsa_score_mm"); + mtl::Dispatch d1; d1.p = &ps; d1.args = {mtl::Arg::B(qidx), mtl::Arg::B(pooled), mtl::Arg::B(dead), mtl::Arg::B(sa), mtl::Arg::V(a)}; + d1.grid[0] = (nb + 7) / 8; d1.grid[1] = T; d1.tg[0] = 256; + mtl::Dispatch d2; d2.p = &psm; d2.args = {mtl::Arg::B(qidx), mtl::Arg::B(pooled), mtl::Arg::B(dead), mtl::Arg::B(sb), mtl::Arg::V(a)}; + d2.grid[0] = (nb + 63) / 64; d2.grid[1] = (T + 15) / 16; d2.tg[0] = 128; + if (bench) { + auto timeit = [&](const mtl::Dispatch& d) { + cx.warm({d}, 0.3); + std::vector t; + for (int i = 0; i < 5; ++i) t.push_back(cx.run({d})); + return median(t); + }; + std::printf("score pos0 %u, T %d: qsa_score %.2f ms, qsa_score_mm %.2f ms\n", pos0, T, timeit(d1) * 1e3, timeit(d2) * 1e3); + } else { + cx.run({d1}); + cx.run({d2}); + double worst = 0; + for (int t = 0; t < T; ++t) { + const uint32_t nbid = (pos0 + t + 1) / 4; + for (uint32_t b = 0; b <= nbid; ++b) { + const double x = sa.as()[(size_t)t * MB + b], y = sb.as()[(size_t)t * MB + b]; + worst = std::max(worst, std::fabs(x - y) / (std::fabs(x) + 1.0)); // scores are O(10) + } + } + const bool ok = worst < 1e-5; + fails += !ok; + std::printf("score pos0 %u, T %d: qsa_score_mm vs qsa_score worst rel %.2e %s\n", pos0, T, worst, ok ? "PASS" : "FAIL"); + } } if (!bench) std::printf("%s\n", fails ? "SOME FAILED" : "ALL PASS"); return fails ? 1 : 0;