diff --git a/engine/include/strata/kernels/native_mmvq.hpp b/engine/include/strata/kernels/native_mmvq.hpp index 526eab495..6d53733e3 100644 --- a/engine/include/strata/kernels/native_mmvq.hpp +++ b/engine/include/strata/kernels/native_mmvq.hpp @@ -196,6 +196,23 @@ struct MmvqIds { bool native_mmvq_ids_supported(int ggml_type); void native_mmvq_ids_group(const int32_t* ids, int count, void* group_buf, void* stream); bool native_mmvq_ids(int ggml_type, const MmvqIds& ids, int count, int n_in, int n_out, void* stream); +#if defined(STRATA_GPU_METAL) +struct MmvqIdsGuSwiglu { + const void* const* table; + const int32_t* ids; + std::size_t gate_offset; + std::size_t up_offset; + const void* x; + std::size_t x_stride; + int x_every; + void* q8_out; + void* group_buf = nullptr; ///< optional kMmvqIdsGroupBytes scratch for GPU expert dedup (count <= 64) + bool group_ready = false; ///< true if native_mmvq_ids_group() already filled group_buf for this ids array +}; +bool native_mmvq_ids_gu_swiglu_q8_supported(int ggml_type); +bool native_mmvq_ids_gu_swiglu_q8(int ggml_type, const MmvqIdsGuSwiglu& ids, int count, int n_in, int n_ff, + void* stream); +#endif // Storage/dispatch helpers take stable GGML type IDs, avoiding a ggml runtime // dependency in the engine: Q4_0=2, Q5_0=6, Q8_0=8, Q2_K=10, Q3_K=11, Q4_K=12, Q5_K=13, diff --git a/engine/metal/poly_tests/quantized_parity.cpp b/engine/metal/poly_tests/quantized_parity.cpp index b516adf32..6db753264 100644 --- a/engine/metal/poly_tests/quantized_parity.cpp +++ b/engine/metal/poly_tests/quantized_parity.cpp @@ -447,6 +447,119 @@ int main(){ } } } + // Fused routed-expert gate_up + SwiGLU + Q8_1 (poly_mul_*_k1_gu_swiglu_q8 & _k1g_gu_swiglu_q8) + // across Q4_K, IQ2_XS, IQ3_XXS, IQ2_S, NVFP4, including ungrouped, grouped (group size > 8), and id == -1 zeroing. + { + g::metal::set_optimize(true); + const int fni = 512, fnf = 256, n_exp = 6, fcount = 32; + auto fwf = values(size_t(n_exp) * (2 * fnf) * fni, 0.5f); + auto fx = values(size_t(fcount) * fni, 0.7f); + std::vector fimp(fni, 1.f); + Buffer dfx(fx), fqx(k::native_q8_1_bytes(fni, fcount)); + k::native_quantize_q8_1(dfx.as(), fqx.ptr, fni, fcount, stream); + ck(g::stream_synchronize(stream)); + + // Expert 0 appears 9 times (> 8 chunk!), expert 2 appears 3 times, expert 4 appears 1 time, and -1 appears 3 times! + std::vector fids = { + 0, -1, 0, 2, 0, 3, 0, 5, + 0, 2, 0, 1, 0, 4, 0, 5, + 0, 3, 2, -1, 3, 5, 1, 3, + 5, 1, 3, 5, 1, -1, 5, 1, + }; + // Non-negative copy for unfused reference (we zero -1 rows in reference explicitly) + std::vector fids_ref = fids; + for (int32_t& id : fids_ref) if (id < 0) id = 0; + + Buffer dfids(fcount * 4), dfids_ref(fcount * 4), dfgrp(k::kMmvqIdsGroupBytes); + dfids.put(fids.data(), fcount * 4); + dfids_ref.put(fids_ref.data(), fcount * 4); + k::native_mmvq_ids_group(dfids.as(), fcount, dfgrp.ptr, stream); + + const size_t q8_out_bytes = k::native_q8_1_bytes(fnf, fcount); + const size_t q8_row_bytes = k::native_q8_1_bytes(fnf, 1); + + auto cmp_q8_with_skip = [&](const Buffer& got_b, const Buffer& ref_b, const char* lbl) { + auto gv = got_b.read(q8_out_bytes); + auto rv = ref_b.read(q8_out_bytes); + int mism = 0; + const size_t nblk_row = size_t(fnf / 32); + for (int r = 0; r < fcount; ++r) { + const size_t base = size_t(r) * q8_row_bytes; + if (fids[r] < 0) { + for (size_t i = 0; i < q8_row_bytes; ++i) + if (gv[base + i] != 0) ++mism; + } else { + for (size_t b = 0; b < nblk_row; ++b) { + const uint8_t* gb = gv.data() + base + b * 36; + const uint8_t* rb = rv.data() + base + b * 36; + _Float16 gd, gs, rd, rs; + std::memcpy(&gd, gb, 2); std::memcpy(&gs, gb + 2, 2); + std::memcpy(&rd, rb, 2); std::memcpy(&rs, rb + 2, 2); + if (std::abs(float(gd) - float(rd)) > 1e-4f + 2e-3f * std::abs(float(rd))) ++mism; + if (std::abs(float(gs) - float(rs)) > 1e-3f + 2e-3f * std::abs(float(rs))) ++mism; + for (int j = 0; j < 32; ++j) { + const float vg = float(gd) * float(int8_t(gb[4 + j])); + const float vr = float(rd) * float(int8_t(rb[4 + j])); + if (std::abs(vg - vr) > std::max(2e-3f, 2.0f * std::abs(float(rd)))) ++mism; + } + } + } + } + std::printf("%s: %d mismatches across %zu bytes\n", lbl, mism, q8_out_bytes); + return mism; + }; + + for (int ftype : {12, 17, 18, 22, 40}) { + auto ft = ggml_type(ftype); + ggml_quantize_init(ft); + const size_t gu_half_bytes = k::native_mmvq_weight_bytes(ftype, fni, fnf); + const size_t exp_bytes = 2 * gu_half_bytes; + std::vector fpacked(exp_bytes * n_exp); + ggml_quantize_chunk(ft, fwf.data(), fpacked.data(), 0, n_exp * (2 * fnf), fni, fimp.data()); + Buffer dfw(fpacked.size()); + dfw.put(fpacked.data(), fpacked.size()); + std::vector ftab(n_exp); + for (int e = 0; e < n_exp; ++e) ftab[e] = static_cast(dfw.ptr) + size_t(e) * exp_bytes; + Buffer dftab(n_exp * sizeof(void*)); + dftab.put(ftab.data(), n_exp * sizeof(void*)); + + Buffer fg_ref(size_t(fcount) * 2 * fnf * 4), fq_ref(q8_out_bytes), fq_ung(q8_out_bytes), fq_grp(q8_out_bytes); + for (int every : {1, 8}) { + // Unfused reference: native_mmvq_ids + swiglu_rows_quantize_q8_1 + k::MmvqIds ref_ids{dftab.as(), dfids_ref.as(), 0, fqx.ptr, + k::native_q8_1_bytes(fni), every, fg_ref.as(), size_t(2 * fnf)}; + k::native_mmvq_ids(ftype, ref_ids, fcount, fni, 2 * fnf, stream); + p::swiglu_rows_quantize_q8_1(fg_ref.as(), fq_ref.ptr, fnf, fcount, stream); + + // Pre-fill outputs with non-zero sentinel to verify id == -1 actually writes zeros! + ck(g::memset_async(fq_ung.ptr, 0x5A, q8_out_bytes, stream)); + ck(g::memset_async(fq_grp.ptr, 0x5A, q8_out_bytes, stream)); + + k::MmvqIdsGuSwiglu gu_ung{dftab.as(), dfids.as(), 0, gu_half_bytes, + fqx.ptr, k::native_q8_1_bytes(fni), every, fq_ung.ptr}; + k::MmvqIdsGuSwiglu gu_grp = gu_ung; + gu_grp.q8_out = fq_grp.ptr; + gu_grp.group_buf = dfgrp.ptr; + gu_grp.group_ready = true; + + const bool ok_u = k::native_mmvq_ids_gu_swiglu_q8(ftype, gu_ung, fcount, fni, fnf, stream); + const bool ok_g = k::native_mmvq_ids_gu_swiglu_q8(ftype, gu_grp, fcount, fni, fnf, stream); + ck(g::stream_synchronize(stream)); + if (!ok_u || !ok_g) { + std::printf("FAIL: native_mmvq_ids_gu_swiglu_q8 returned false for %s every=%d\n", + ggml_type_name(ft), every); + ++bad; + continue; + } + char flbl[128]; + std::snprintf(flbl, sizeof(flbl), "gu_swiglu_q8 ungrouped %s every=%d", ggml_type_name(ft), every); + bad += cmp_q8_with_skip(fq_ung, fq_ref, flbl); + std::snprintf(flbl, sizeof(flbl), "gu_swiglu_q8 grouped %s every=%d", ggml_type_name(ft), every); + bad += cmp_q8_with_skip(fq_grp, fq_ref, flbl); + } + } + } + p::metal_detail::allow_mm_rows(true); ck(g::stream_synchronize(stream));ck(g::stream_destroy(stream));ggml_quantize_free();return bad?1:0; } diff --git a/engine/metal/poly_tests/qwen4_parity.cpp b/engine/metal/poly_tests/qwen4_parity.cpp index 069cdf246..cbaaa042d 100644 --- a/engine/metal/poly_tests/qwen4_parity.cpp +++ b/engine/metal/poly_tests/qwen4_parity.cpp @@ -1,6 +1,7 @@ // metal/poly_tests/qwen4_parity.cpp - CPU reference parity tests for all Metal Qwen4 kernels + gdn_step_sigmoid. #include "test_utils.hpp" #include "qwen4_kernels.hpp" +#include "strata/gpu/metal.hpp" #include "strata/kernels/native_mmvq.hpp" #include "strata/poly/kernels.hpp" @@ -12,6 +13,7 @@ #include #include #include +#include #include #include @@ -48,57 +50,93 @@ int test_gr(g::Stream s) { auto wn = values(hc * n_embd, 0.2f); for (auto& v : wn) v += 1.0f; - // 1) q4_gr_norm_quant - { - Buffer dr(r), dwn(wn), dxn(r.size() * 4); - const size_t qb = k::native_q8_1_bytes(n_embd, rows * hc); - Buffer dxq(qb), dxq_ref(qb); - p::q4_gr_norm_quant(dr.as(), dwn.as(), dxn.as(), dxq.ptr, n_embd, hc, rows, eps, s); - k::native_quantize_q8_1(dxn.as(), dxq_ref.ptr, n_embd * hc, rows, s); - ck(g::stream_synchronize(s)); + // 1) q4_gr_norm_quant & 2) q4_gr_write + q4_gr_write_norm_quant + // Test WRITE_PREV=0/1, QUANT=0/1, scalar fallback (n_embd=66), cached vec4 (256, 2048), uncached vec4 (4608). + for (int ne : {66, 256, 2048, 4608}) { + const int rcnt = (ne >= 2048) ? 2 : rows; + auto rv = values(size_t(rcnt) * hc * ne, 0.9f); + auto bov = values(size_t(rcnt) * ne, 0.5f); + auto injv = values(size_t(rcnt) * hc, 0.7f); + auto wnv = values(size_t(hc) * ne, 0.2f); + for (auto& v : wnv) v += 1.0f; + const bool can_q = (ne % 32) == 0; + const size_t qb = can_q ? k::native_q8_1_bytes(ne, rcnt * hc) : 0; - std::vector ref_xn(r.size()); - for (int t = 0; t < rows; ++t) { - for (int c = 0; c < hc; ++c) { - double ss = 0; - const size_t off = size_t(t * hc + c) * n_embd; - for (int i = 0; i < n_embd; ++i) ss += double(r[off + i]) * r[off + i]; - const float inv = 1.0f / std::sqrt(float(ss / n_embd) + eps); - for (int i = 0; i < n_embd; ++i) ref_xn[off + i] = r[off + i] * inv * wn[size_t(c) * n_embd + i]; + // WRITE_PREV = 0, QUANT = 0 and (when ne%32==0) QUANT = 1 + { + Buffer dr(rv), dwn(wnv), dxn0(rv.size() * 4), dxn1(rv.size() * 4); + Buffer dxq(std::max(qb, 64)), dxq_ref(std::max(qb, 64)); + p::q4_gr_norm_quant(dr.as(), dwn.as(), dxn0.as(), nullptr, ne, hc, rcnt, eps, s); + if (can_q) { + p::q4_gr_norm_quant(dr.as(), dwn.as(), dxn1.as(), dxq.ptr, ne, hc, rcnt, eps, s); + k::native_quantize_q8_1(dxn1.as(), dxq_ref.ptr, ne * hc, rcnt, s); + } + ck(g::stream_synchronize(s)); + + std::vector ref_xn(rv.size()); + for (int t = 0; t < rcnt; ++t) { + for (int c = 0; c < hc; ++c) { + double ss = 0; + const size_t off = size_t(t * hc + c) * ne; + for (int i = 0; i < ne; ++i) ss += double(rv[off + i]) * rv[off + i]; + const float inv = 1.0f / std::sqrt(float(ss / ne) + eps); + for (int i = 0; i < ne; ++i) ref_xn[off + i] = rv[off + i] * inv * wnv[size_t(c) * ne + i]; + } + } + char lbl[96]; + std::snprintf(lbl, sizeof(lbl), "q4_gr_norm_0_0 ne=%d xn", ne); + bad += compare(dxn0.read(ref_xn.size()), ref_xn, lbl); + if (can_q) { + std::snprintf(lbl, sizeof(lbl), "q4_gr_norm_0_1 ne=%d xn", ne); + bad += compare(dxn1.read(ref_xn.size()), ref_xn, lbl); + std::snprintf(lbl, sizeof(lbl), "q4_gr_norm_0_1 ne=%d xq", ne); + bad += compare_q8_bytes(dxq, dxq_ref, qb, lbl); } } - bad += compare(dxn.read(ref_xn.size()), ref_xn, "q4_gr_norm_quant xn"); - bad += compare_q8_bytes(dxq, dxq_ref, qb, "q4_gr_norm_quant xq"); - } - // 2) q4_gr_write + q4_gr_write_norm_quant - { - Buffer dr1(r), dr2(r), dbo(bo), dinj(inj), dwn(wn), dxn(r.size() * 4); - const size_t qb = k::native_q8_1_bytes(n_embd, rows * hc); - Buffer dxq(qb), dxq_ref(qb); - p::q4_gr_write(dr1.as(), dbo.as(), dinj.as(), n_embd, hc, rows, s); - p::q4_gr_write_norm_quant(dr2.as(), dbo.as(), dinj.as(), dwn.as(), dxn.as(), dxq.ptr, n_embd, hc, rows, eps, s); - k::native_quantize_q8_1(dxn.as(), dxq_ref.ptr, n_embd * hc, rows, s); - ck(g::stream_synchronize(s)); + // WRITE_PREV = 1, QUANT = 0 and (when ne%32==0) QUANT = 1 + { + Buffer dr1(rv), dr2(rv), dr3(rv), dbo(bov), dinj(injv), dwn(wnv); + Buffer dxn0(rv.size() * 4), dxn1(rv.size() * 4); + Buffer dxq(std::max(qb, 64)), dxq_ref(std::max(qb, 64)); + p::q4_gr_write(dr1.as(), dbo.as(), dinj.as(), ne, hc, rcnt, s); + p::q4_gr_write_norm_quant(dr2.as(), dbo.as(), dinj.as(), dwn.as(), dxn0.as(), nullptr, ne, hc, rcnt, eps, s); + if (can_q) { + p::q4_gr_write_norm_quant(dr3.as(), dbo.as(), dinj.as(), dwn.as(), dxn1.as(), dxq.ptr, ne, hc, rcnt, eps, s); + k::native_quantize_q8_1(dxn1.as(), dxq_ref.ptr, ne * hc, rcnt, s); + } + ck(g::stream_synchronize(s)); - std::vector ref_r = r, ref_xn(r.size()); - for (int t = 0; t < rows; ++t) { - for (int c = 0; c < hc; ++c) { - const float gw = 2.0f * sig(inj[t * hc + c] / float(hc)); - const size_t off = size_t(t * hc + c) * n_embd; - double ss = 0; - for (int i = 0; i < n_embd; ++i) { - ref_r[off + i] += bo[size_t(t) * n_embd + i] * gw; - ss += double(ref_r[off + i]) * ref_r[off + i]; + std::vector ref_r = rv, ref_xn(rv.size()); + for (int t = 0; t < rcnt; ++t) { + for (int c = 0; c < hc; ++c) { + const float gw = 2.0f * sig(injv[t * hc + c] / float(hc)); + const size_t off = size_t(t * hc + c) * ne; + double ss = 0; + for (int i = 0; i < ne; ++i) { + ref_r[off + i] += bov[size_t(t) * ne + i] * gw; + ss += double(ref_r[off + i]) * ref_r[off + i]; + } + const float inv = 1.0f / std::sqrt(float(ss / ne) + eps); + for (int i = 0; i < ne; ++i) ref_xn[off + i] = ref_r[off + i] * inv * wnv[size_t(c) * ne + i]; } - const float inv = 1.0f / std::sqrt(float(ss / n_embd) + eps); - for (int i = 0; i < n_embd; ++i) ref_xn[off + i] = ref_r[off + i] * inv * wn[size_t(c) * n_embd + i]; + } + char lbl[96]; + std::snprintf(lbl, sizeof(lbl), "q4_gr_write ne=%d r", ne); + bad += compare(dr1.read(ref_r.size()), ref_r, lbl); + std::snprintf(lbl, sizeof(lbl), "q4_gr_norm_1_0 ne=%d r", ne); + bad += compare(dr2.read(ref_r.size()), ref_r, lbl); + std::snprintf(lbl, sizeof(lbl), "q4_gr_norm_1_0 ne=%d xn", ne); + bad += compare(dxn0.read(ref_xn.size()), ref_xn, lbl); + if (can_q) { + std::snprintf(lbl, sizeof(lbl), "q4_gr_norm_1_1 ne=%d r", ne); + bad += compare(dr3.read(ref_r.size()), ref_r, lbl); + std::snprintf(lbl, sizeof(lbl), "q4_gr_norm_1_1 ne=%d xn", ne); + bad += compare(dxn1.read(ref_xn.size()), ref_xn, lbl); + std::snprintf(lbl, sizeof(lbl), "q4_gr_norm_1_1 ne=%d xq", ne); + bad += compare_q8_bytes(dxq, dxq_ref, qb, lbl); } } - bad += compare(dr1.read(ref_r.size()), ref_r, "q4_gr_write r"); - bad += compare(dr2.read(ref_r.size()), ref_r, "q4_gr_write_norm_quant r"); - bad += compare(dxn.read(ref_xn.size()), ref_xn, "q4_gr_write_norm_quant xn"); - bad += compare_q8_bytes(dxq, dxq_ref, qb, "q4_gr_write_norm_quant xq"); } // 3) q4_gr_split_silu_quant + q4_gr_silu_quant @@ -138,28 +176,80 @@ int test_gr(g::Stream s) { bad += compare_q8_bytes(dq2, dq2_ref, qb, "q4_gr_silu_quant xq"); } - // 4) q4_gr_gate_mean_quant (hc=4 and hc=3) + // 4) q4_gr_gate_mean_quant (hc=4 and hc=3; rows=1, 4, 64; n_embd=256, 2048; quant=true/false + scalar fallback) for (int hcv : {4, 3}) { - auto xn = values(rows * hcv * n_embd, 0.8f); - auto gate = values(rows * hcv * n_embd, 1.2f); - const size_t qb = k::native_q8_1_bytes(n_embd, rows); - Buffer dxn(xn), dgate(gate), dmix(rows * n_embd * 4), dq(qb), dq_ref(qb); - p::q4_gr_gate_mean_quant(dxn.as(), dgate.as(), dmix.as(), dq.ptr, n_embd, hcv, rows, s); - k::native_quantize_q8_1(dmix.as(), dq_ref.ptr, n_embd, rows, s); + for (int rcnt : {1, 4, 64}) { + const int ne = (rcnt == 64 && hcv == 4) ? 2048 : n_embd; + auto xn = values(size_t(rcnt) * hcv * ne, 0.8f); + auto gate = values(size_t(rcnt) * hcv * ne, 1.2f); + const size_t qb = k::native_q8_1_bytes(ne, rcnt); + Buffer dxn(xn), dgate(gate), dmix(size_t(rcnt) * ne * 4), dmix_noq(size_t(rcnt) * ne * 4); + Buffer dq(qb), dq_ref(qb); + p::q4_gr_gate_mean_quant(dxn.as(), dgate.as(), dmix.as(), dq.ptr, ne, hcv, rcnt, s); + p::q4_gr_gate_mean_quant(dxn.as(), dgate.as(), dmix_noq.as(), nullptr, ne, hcv, rcnt, s); + k::native_quantize_q8_1(dmix.as(), dq_ref.ptr, ne, rcnt, s); + ck(g::stream_synchronize(s)); + std::vector ref_mix(size_t(rcnt) * ne, 0.0f); + for (int t = 0; t < rcnt; ++t) { + for (int d = 0; d < ne; ++d) { + float acc = 0; + for (int c = 0; c < hcv; ++c) { + const size_t idx = (size_t(t) * hcv + c) * ne + d; + acc += xn[idx] * sig(gate[idx]); + } + ref_mix[size_t(t) * ne + d] = acc / float(hcv); + } + } + char lbl[96]; + std::snprintf(lbl, sizeof(lbl), "q4_gr_gate_mean hc=%d r=%d ne=%d", hcv, rcnt, ne); + bad += compare(dmix.read(ref_mix.size()), ref_mix, lbl); + std::snprintf(lbl, sizeof(lbl), "q4_gr_gate_mean noq hc=%d r=%d ne=%d", hcv, rcnt, ne); + bad += compare(dmix_noq.read(ref_mix.size()), ref_mix, lbl); + std::snprintf(lbl, sizeof(lbl), "q4_gr_gate_mean xq hc=%d r=%d ne=%d", hcv, rcnt, ne); + bad += compare_q8_bytes(dq, dq_ref, qb, lbl); + } + } + // Non-multiple-of-4 scalar fallback for q4_gr_gate_mean_quant (quant=false) + { + const int ne = 66, hcv = 4, rcnt = 4; + auto xn = values(size_t(rcnt) * hcv * ne, 0.8f); + auto gate = values(size_t(rcnt) * hcv * ne, 1.2f); + Buffer dxn(xn), dgate(gate), dmix(size_t(rcnt) * ne * 4); + p::q4_gr_gate_mean_quant(dxn.as(), dgate.as(), dmix.as(), nullptr, ne, hcv, rcnt, s); ck(g::stream_synchronize(s)); - std::vector ref_mix(rows * n_embd, 0.0f); - for (int t = 0; t < rows; ++t) { - for (int d = 0; d < n_embd; ++d) { + std::vector ref_mix(size_t(rcnt) * ne, 0.0f); + for (int t = 0; t < rcnt; ++t) { + for (int d = 0; d < ne; ++d) { float acc = 0; for (int c = 0; c < hcv; ++c) { - const size_t idx = (size_t(t) * hcv + c) * n_embd + d; + const size_t idx = (size_t(t) * hcv + c) * ne + d; acc += xn[idx] * sig(gate[idx]); } - ref_mix[size_t(t) * n_embd + d] = acc / float(hcv); + ref_mix[size_t(t) * ne + d] = acc / float(hcv); } } - bad += compare(dmix.read(ref_mix.size()), ref_mix, hcv == 4 ? "q4_gr_gate_mean hc=4" : "q4_gr_gate_mean hc=3"); - bad += compare_q8_bytes(dq, dq_ref, qb, hcv == 4 ? "q4_gr_gate_mean xq hc=4" : "q4_gr_gate_mean xq hc=3"); + bad += compare(dmix.read(ref_mix.size()), ref_mix, "q4_gr_gate_mean scalar fallback ne=66"); + } + // Prefill microbenchmark for vectorized q4_gr_gate_mean_quant (512 x 2048 x hc=4 + Q8_1) + { + const int ne = 2048, hcv = 4, rcnt = 512; + auto xn = values(size_t(rcnt) * hcv * ne, 0.8f); + auto gate = values(size_t(rcnt) * hcv * ne, 1.2f); + const size_t qb = k::native_q8_1_bytes(ne, rcnt); + Buffer dxn(xn), dgate(gate), dmix(size_t(rcnt) * ne * 4), dq(qb); + for (int it = 0; it < 3; ++it) + p::q4_gr_gate_mean_quant(dxn.as(), dgate.as(), dmix.as(), dq.ptr, ne, hcv, rcnt, s); + ck(g::stream_synchronize(s)); + const int iters = 20; + const auto t0 = std::chrono::steady_clock::now(); + for (int it = 0; it < iters; ++it) + p::q4_gr_gate_mean_quant(dxn.as(), dgate.as(), dmix.as(), dq.ptr, ne, hcv, rcnt, 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 bytes = double(size_t(rcnt) * (2 * hcv + 1) * ne * 4 + qb); + std::printf(" bench q4_gr_gate_mean_vec4 r=512 ne=2048 hc=4 q8: %.3f ms/call (%.1f GB/s)\n", + ms, bytes / (ms * 1e6)); } // 5) q4_shexp_gate_mul (rows=1, 4, 8) @@ -182,7 +272,7 @@ int test_gr(g::Stream s) { bad += compare(dfo.read(ref.size()), ref, lbl, 1e-5f); } - // 6) q4_gr_up_gate_mean_quant (Q6_K, Q8_0, Q4_K; rows=1, 4, 8; quant=true/false) + // 6) q4_gr_up_gate_mean_quant (Q6_K, Q8_0, Q4_K; rows=1, 2, 4, 8; FP32 lo & Q8_1 lo; out_xq=non-null & null) for (int wt : {int(GGML_TYPE_Q6_K), int(GGML_TYPE_Q8_0), int(GGML_TYPE_Q4_K)}) { const auto gt = ggml_type(wt); ggml_quantize_init(gt); @@ -192,34 +282,71 @@ int test_gr(g::Stream s) { const size_t wb = k::native_mmvq_weight_bytes(wt, lr, hcv * ne); std::vector packed(wb); ggml_quantize_chunk(gt, wf.data(), packed.data(), 0, hcv * ne, lr, imp.data()); + std::vector dwf(wf.size()); + ggml_get_type_traits(gt)->to_float(packed.data(), dwf.data(), dwf.size()); Buffer dw(wb); dw.put(packed.data(), wb); - for (int rcnt : {1, 4, 8}) { + for (int rcnt : {1, 2, 4, 8}) { auto lo = values(rcnt * lr, 0.8f); auto xn = values(rcnt * hcv * ne, 0.7f); const size_t lo_qb = k::native_q8_1_bytes(lr, rcnt); const size_t out_qb = k::native_q8_1_bytes(ne, rcnt); Buffer dlo(lo), dloq(lo_qb), dxn(xn); Buffer dgate(rcnt * hcv * ne * 4), dout_ref(rcnt * ne * 4), dq_ref(out_qb); - Buffer dout_got(rcnt * ne * 4), dq_got(out_qb); + Buffer dout_q8(rcnt * ne * 4), dout_q8_noq(rcnt * ne * 4), dq_q8(out_qb); + Buffer dout_f32(rcnt * ne * 4), dout_f32_noq(rcnt * ne * 4), dq_f32(out_qb), dq_f32_ref(out_qb); + // Legacy Q8_1 lo path vs unfused native_mmvq + q4_gr_gate_mean_quant k::native_quantize_q8_1(dlo.as(), dloq.ptr, lr, rcnt, s); k::native_mmvq(wt, dw.ptr, dloq.ptr, dgate.as(), lr, hcv * ne, rcnt, s); p::q4_gr_gate_mean_quant(dxn.as(), dgate.as(), dout_ref.as(), dq_ref.ptr, ne, hcv, rcnt, s); - const bool ok = p::q4_gr_up_gate_mean_quant(dw.ptr, wt, dloq.ptr, dxn.as(), dout_got.as(), dq_got.ptr, - ne, hcv, lr, rcnt, s); + const bool ok_q8_1 = p::q4_gr_up_gate_mean_quant(dw.ptr, wt, dloq.ptr, dxn.as(), dout_q8.as(), dq_q8.ptr, + ne, hcv, lr, rcnt, s); + const bool ok_q8_0 = p::q4_gr_up_gate_mean_quant(dw.ptr, wt, dloq.ptr, dxn.as(), dout_q8_noq.as(), nullptr, + ne, hcv, lr, rcnt, s); + + // Direct FP32 lo path (lo_xq = nullptr) vs exact CPU dequantized-weight reference + const bool ok_f32_1 = p::q4_gr_up_gate_mean_quant(wt, dw.ptr, nullptr, dlo.as(), dxn.as(), + dout_f32.as(), dq_f32.ptr, nullptr, ne, hcv, lr, rcnt, s); + const bool ok_f32_0 = p::q4_gr_up_gate_mean_quant(wt, dw.ptr, nullptr, dlo.as(), dxn.as(), + dout_f32_noq.as(), nullptr, nullptr, ne, hcv, lr, rcnt, s); + k::native_quantize_q8_1(dout_f32.as(), dq_f32_ref.ptr, ne, rcnt, s); ck(g::stream_synchronize(s)); - if (!ok) { + if (!ok_q8_1 || !ok_q8_0 || !ok_f32_1 || !ok_f32_0) { std::printf("q4_gr_up_gate_mean_quant returned false for type=%s rows=%d\n", ggml_type_name(gt), rcnt); ++bad; continue; } - char lbl[96]; - std::snprintf(lbl, sizeof(lbl), "q4_gr_up_gate_mean %s r=%d out", ggml_type_name(gt), rcnt); - bad += compare(dout_got.read(rcnt * ne), dout_ref.read(rcnt * ne), lbl, 1e-4f); - std::snprintf(lbl, sizeof(lbl), "q4_gr_up_gate_mean %s r=%d xq", ggml_type_name(gt), rcnt); - bad += compare_q8_bytes(dq_got, dq_ref, out_qb, lbl); + + std::vector ref_f32(size_t(rcnt) * ne, 0.0f); + for (int t = 0; t < rcnt; ++t) { + for (int d = 0; d < ne; ++d) { + float acc = 0.0f; + for (int c = 0; c < hcv; ++c) { + const size_t wrow = size_t(c) * ne + d; + double dot = 0.0; + for (int k0 = 0; k0 < lr; ++k0) + dot += double(dwf[wrow * lr + k0]) * double(lo[size_t(t) * lr + k0]); + acc += xn[(size_t(t) * hcv + c) * ne + d] * sig(float(dot)); + } + ref_f32[size_t(t) * ne + d] = acc * 0.25f; + } + } + + char lbl[128]; + std::snprintf(lbl, sizeof(lbl), "q4_gr_up q8_lo %s r=%d q=1 out", ggml_type_name(gt), rcnt); + bad += compare(dout_q8.read(rcnt * ne), dout_ref.read(rcnt * ne), lbl, 1e-4f); + std::snprintf(lbl, sizeof(lbl), "q4_gr_up q8_lo %s r=%d q=0 out", ggml_type_name(gt), rcnt); + bad += compare(dout_q8_noq.read(rcnt * ne), dout_ref.read(rcnt * ne), lbl, 1e-4f); + std::snprintf(lbl, sizeof(lbl), "q4_gr_up q8_lo %s r=%d xq", ggml_type_name(gt), rcnt); + bad += compare_q8_bytes(dq_q8, dq_ref, out_qb, lbl); + std::snprintf(lbl, sizeof(lbl), "q4_gr_up f32_lo %s r=%d q=1 out", ggml_type_name(gt), rcnt); + bad += compare(dout_f32.read(rcnt * ne), ref_f32, lbl, 1e-4f); + std::snprintf(lbl, sizeof(lbl), "q4_gr_up f32_lo %s r=%d q=0 out", ggml_type_name(gt), rcnt); + bad += compare(dout_f32_noq.read(rcnt * ne), ref_f32, lbl, 1e-4f); + std::snprintf(lbl, sizeof(lbl), "q4_gr_up f32_lo %s r=%d xq", ggml_type_name(gt), rcnt); + bad += compare_q8_bytes(dq_f32, dq_f32_ref, out_qb, lbl); } } @@ -235,9 +362,578 @@ int test_gr(g::Stream s) { ck(g::stream_synchronize(s)); bad += compare_q8_bytes(dq_got, dq_ref, qb, "swiglu_rows_quantize_q8_1"); } + + // 8) q4_gr_down_silu_quant (Q8_0, Q4_K, Q6_K; has_inject=true/false; rows=1,2,4,8; quant=true/false) + { + Buffer dcnt(16 * sizeof(uint32_t)); + ck(g::memset_async(dcnt.ptr, 0, 16 * sizeof(uint32_t), s)); + for (int wt : {int(GGML_TYPE_Q8_0), int(GGML_TYPE_Q4_K), int(GGML_TYPE_Q6_K)}) { + const auto gt = ggml_type(wt); + ggml_quantize_init(gt); + const int hc_dim = 1024, lr = 128, hcv = 4; + std::vector imp(hc_dim, 1.0f); + for (bool has_inj : {true, false}) { + const int n_out = has_inj ? (lr + hcv) : lr; + auto wf = values(n_out * hc_dim, 0.5f); + const size_t wb = k::native_mmvq_weight_bytes(wt, hc_dim, n_out); + std::vector packed(wb); + ggml_quantize_chunk(gt, wf.data(), packed.data(), 0, n_out, hc_dim, imp.data()); + std::vector dwf(wf.size()); + ggml_get_type_traits(gt)->to_float(packed.data(), dwf.data(), dwf.size()); + Buffer dw(wb); + dw.put(packed.data(), wb); + + for (int rcnt : {1, 2, 4, 8}) { + auto xn = values(rcnt * hc_dim, 0.6f); + const size_t xn_qb = k::native_q8_1_bytes(hc_dim, rcnt); + const size_t lo_qb = k::native_q8_1_bytes(lr, rcnt); + Buffer dxn(xn), dxnq(xn_qb); + k::native_quantize_q8_1(dxn.as(), dxnq.ptr, hc_dim, rcnt, s); + ck(g::stream_synchronize(s)); + + // Reconstruct exact dequantized Q8_1 input for CPU reference + auto xqb = dxnq.read(xn_qb); + std::vector xq_f(xn.size()); + for (size_t i = 0; i < xn.size(); ++i) { + uint16_t dh; + std::memcpy(&dh, xqb.data() + (i / 32) * 36, 2); + xq_f[i] = ggml_fp16_to_fp32(dh) * float(reinterpret_cast(xqb.data())[(i / 32) * 36 + 4 + (i % 32)]); + } + std::vector ref_lo(rcnt * lr), ref_inj(rcnt * hcv, 0.0f); + for (int t = 0; t < rcnt; ++t) { + for (int o = 0; o < n_out; ++o) { + double acc = 0.0; + for (int i = 0; i < hc_dim; ++i) + acc += double(dwf[size_t(o) * hc_dim + i]) * double(xq_f[size_t(t) * hc_dim + i]); + if (o < lr) { + const float v = float(acc) / float(hcv); + ref_lo[size_t(t) * lr + o] = v * sig(v); + } else { + ref_inj[size_t(t) * hcv + (o - lr)] = float(acc); + } + } + } + + // Verify aliasing guard returns false, and null q8_cnt succeeds on Metal (fence-free follow-up quant). + if (has_inj && rcnt == 1) { + Buffer dlo_tmp(rcnt * lr * 4), dinj_tmp(rcnt * hcv * 4), dq_tmp(lo_qb); + if (p::q4_gr_down_silu_quant(wt, dw.ptr, dxnq.ptr, nullptr, dlo_tmp.as(), dxnq.ptr, + dinj_tmp.as(), dcnt.as(), hc_dim, lr, hcv, true, 1, s)) { + std::printf("FAIL: q4_gr_down_silu_quant allowed lo_xq == xn_xq\n"); + ++bad; + } + if (!p::q4_gr_down_silu_quant(wt, dw.ptr, dxnq.ptr, nullptr, dlo_tmp.as(), dq_tmp.ptr, + dinj_tmp.as(), nullptr, hc_dim, lr, hcv, true, 1, s)) { + std::printf("FAIL: q4_gr_down_silu_quant rejected null q8_cnt on fence-free Metal path\n"); + ++bad; + } + } + + for (bool do_q : {true, false}) { + Buffer dlo_got(rcnt * lr * 4), dinj_got(rcnt * hcv * 4), dq_got(lo_qb), dq_ref(lo_qb); + ck(g::memset_async(dinj_got.ptr, 0, rcnt * hcv * 4, s)); + const bool ok = p::q4_gr_down_silu_quant( + wt, dw.ptr, dxnq.ptr, nullptr, dlo_got.as(), do_q ? dq_got.ptr : nullptr, + has_inj ? dinj_got.as() : nullptr, do_q ? dcnt.as() : nullptr, + hc_dim, lr, hcv, has_inj, rcnt, s); + if (do_q) k::native_quantize_q8_1(dlo_got.as(), dq_ref.ptr, lr, rcnt, s); + ck(g::stream_synchronize(s)); + if (!ok) { + std::printf("FAIL: q4_gr_down_silu_quant returned false (type=%s inj=%d r=%d q=%d)\n", + ggml_type_name(gt), int(has_inj), rcnt, int(do_q)); + ++bad; + continue; + } + char lbl[128]; + std::snprintf(lbl, sizeof(lbl), "q4_gr_down %s inj=%d r=%d q=%d lo", + ggml_type_name(gt), int(has_inj), rcnt, int(do_q)); + bad += compare(dlo_got.read(ref_lo.size()), ref_lo, lbl, 1e-3f); + if (has_inj) { + std::snprintf(lbl, sizeof(lbl), "q4_gr_down %s inj=1 r=%d q=%d inj", + ggml_type_name(gt), rcnt, int(do_q)); + bad += compare(dinj_got.read(ref_inj.size()), ref_inj, lbl, 1e-3f); + } + if (do_q) { + std::snprintf(lbl, sizeof(lbl), "q4_gr_down %s inj=%d r=%d xq", + ggml_type_name(gt), int(has_inj), rcnt); + bad += compare_q8_bytes(dq_got, dq_ref, lo_qb, lbl); + } + } + } + } + } + + // 8b) 50-iteration back-to-back wait-free coherence & self-reset stress test (260 TGs, alternating inputs) + const int s_hc_dim = 2048, s_lr = 256, s_hc = 4, s_nout = s_lr + s_hc, s_iters = 50; + std::vector s_imp(s_hc_dim, 1.0f); + for (int wt : {int(GGML_TYPE_Q8_0), int(GGML_TYPE_Q4_K), int(GGML_TYPE_Q6_K)}) { + const auto gt = ggml_type(wt); + ggml_quantize_init(gt); + auto wf = values(s_nout * s_hc_dim, 0.5f); + const size_t wb = k::native_mmvq_weight_bytes(wt, s_hc_dim, s_nout); + std::vector packed(wb); + ggml_quantize_chunk(gt, wf.data(), packed.data(), 0, s_nout, s_hc_dim, s_imp.data()); + Buffer dw(wb); + dw.put(packed.data(), wb); + + for (int rcnt : {1, 4, 8}) { + auto xn_a = values(rcnt * s_hc_dim, 0.6f); + auto xn_b = values(rcnt * s_hc_dim, 0.9f); + for (size_t i = 0; i < xn_b.size(); ++i) xn_b[i] = -xn_b[i] * 0.7f + 0.15f; + const size_t xn_qb = k::native_q8_1_bytes(s_hc_dim, rcnt); + const size_t lo_qb = k::native_q8_1_bytes(s_lr, rcnt); + Buffer dxna(xn_a), dxnb(xn_b), dxnqa(xn_qb), dxnqb(xn_qb); + k::native_quantize_q8_1(dxna.as(), dxnqa.ptr, s_hc_dim, rcnt, s); + k::native_quantize_q8_1(dxnb.as(), dxnqb.ptr, s_hc_dim, rcnt, s); + + // Compute exact reference Q8_1 for input A and input B via unfused native_mmvq + q4_gr_split_silu_quant + Buffer dli_a(rcnt * s_nout * 4), dli_b(rcnt * s_nout * 4); + Buffer dlo_ra(rcnt * s_lr * 4), dlo_rb(rcnt * s_lr * 4); + Buffer dinj_ra(rcnt * s_hc * 4), dinj_rb(rcnt * s_hc * 4); + Buffer dq_ra(lo_qb), dq_rb(lo_qb); + k::native_mmvq(wt, dw.ptr, dxnqa.ptr, dli_a.as(), s_hc_dim, s_nout, rcnt, s); + p::q4_gr_split_silu_quant(dli_a.as(), dlo_ra.as(), dq_ra.ptr, dinj_ra.as(), s_lr, s_hc, rcnt, s); + k::native_mmvq(wt, dw.ptr, dxnqb.ptr, dli_b.as(), s_hc_dim, s_nout, rcnt, s); + p::q4_gr_split_silu_quant(dli_b.as(), dlo_rb.as(), dq_rb.ptr, dinj_rb.as(), s_lr, s_hc, rcnt, s); + + // Launch 50 back-to-back fused dispatches with NO sync and NO counter re-zeroing in between! + Buffer dlo_work(rcnt * s_lr * 4), dinj_work(rcnt * s_hc * 4); + Buffer dq_all(size_t(s_iters) * lo_qb); + ck(g::memset_async(dq_all.ptr, 0x5A, size_t(s_iters) * lo_qb, s)); + for (int it = 0; it < s_iters; ++it) { + const void* xq_in = (it & 1) ? dxnqb.ptr : dxnqa.ptr; + uint8_t* dst_q = static_cast(dq_all.ptr) + size_t(it) * lo_qb; + const bool ok = p::q4_gr_down_silu_quant( + wt, dw.ptr, xq_in, nullptr, dlo_work.as(), dst_q, dinj_work.as(), + dcnt.as(), s_hc_dim, s_lr, s_hc, true, rcnt, s); + if (!ok) ++bad; + } + ck(g::stream_synchronize(s)); + + auto got_all = dq_all.read(size_t(s_iters) * lo_qb); + auto ref_a = dq_ra.read(lo_qb); + auto ref_b = dq_rb.read(lo_qb); + int stress_bad = 0; + const size_t nblk = lo_qb / 36; + for (int it = 0; it < s_iters; ++it) { + const uint8_t* gp = got_all.data() + size_t(it) * lo_qb; + const uint8_t* rp = (it & 1) ? ref_b.data() : ref_a.data(); + for (size_t b = 0; b < nblk; ++b) { + uint16_t gd_h, gs_h, rd_h, rs_h; + std::memcpy(&gd_h, gp + b * 36, 2); std::memcpy(&gs_h, gp + b * 36 + 2, 2); + std::memcpy(&rd_h, rp + b * 36, 2); std::memcpy(&rs_h, rp + b * 36 + 2, 2); + const float gd = ggml_fp16_to_fp32(gd_h), gs = ggml_fp16_to_fp32(gs_h); + const float rd = ggml_fp16_to_fp32(rd_h), rs = ggml_fp16_to_fp32(rs_h); + if (std::abs(gd - rd) > 1e-4f + 2e-3f * std::abs(rd)) ++stress_bad; + if (std::abs(gs - rs) > 1e-3f + 2e-3f * std::abs(rs)) ++stress_bad; + for (int j = 0; j < 32; ++j) { + if (std::abs(int(int8_t(gp[b * 36 + 4 + j])) - int(int8_t(rp[b * 36 + 4 + j]))) > 1) + ++stress_bad; + } + } + } + auto cnt_vals = dcnt.read(16); + for (uint32_t v : cnt_vals) if (v != 0u) ++stress_bad; + std::printf("q4_gr_down stress 50x %s r=%d: %d mismatches\n", ggml_type_name(gt), rcnt, stress_bad); + bad += stress_bad; + } + } + + // 8c) Odd n_out tail test (hc=3, has_inject=true -> n_out=131) to exercise NR=2 odd tail + { + const int o_hc_dim = 512, o_lr = 128, o_hc = 3, o_nout = o_lr + o_hc, o_rows = 2; + std::vector o_imp(o_hc_dim, 1.0f); + for (int wt : {int(GGML_TYPE_Q8_0), int(GGML_TYPE_Q4_K), int(GGML_TYPE_Q6_K)}) { + const auto gt = ggml_type(wt); + ggml_quantize_init(gt); + auto wf = values(o_nout * o_hc_dim, 0.5f); + const size_t wb = k::native_mmvq_weight_bytes(wt, o_hc_dim, o_nout); + std::vector packed(wb); + ggml_quantize_chunk(gt, wf.data(), packed.data(), 0, o_nout, o_hc_dim, o_imp.data()); + Buffer dw(wb); + dw.put(packed.data(), wb); + auto xn = values(o_rows * o_hc_dim, 0.6f); + const size_t xn_qb = k::native_q8_1_bytes(o_hc_dim, o_rows); + Buffer dxn(xn), dxnq(xn_qb), dli(o_rows * o_nout * 4); + Buffer dlo_r(o_rows * o_lr * 4), dinj_r(o_rows * o_hc * 4); + Buffer dlo_g(o_rows * o_lr * 4), dinj_g(o_rows * o_hc * 4); + k::native_quantize_q8_1(dxn.as(), dxnq.ptr, o_hc_dim, o_rows, s); + k::native_mmvq(wt, dw.ptr, dxnq.ptr, dli.as(), o_hc_dim, o_nout, o_rows, s); + p::q4_gr_split_silu_quant(dli.as(), dlo_r.as(), nullptr, dinj_r.as(), o_lr, o_hc, o_rows, s); + const bool ok = p::q4_gr_down_silu_quant(wt, dw.ptr, dxnq.ptr, nullptr, dlo_g.as(), nullptr, + dinj_g.as(), nullptr, o_hc_dim, o_lr, o_hc, true, o_rows, s); + ck(g::stream_synchronize(s)); + if (!ok) { ++bad; continue; } + char lbl[96]; + std::snprintf(lbl, sizeof(lbl), "q4_gr_down odd_nout %s lo", ggml_type_name(gt)); + bad += compare(dlo_g.read(o_rows * o_lr), dlo_r.read(o_rows * o_lr), lbl, 1e-4f); + std::snprintf(lbl, sizeof(lbl), "q4_gr_down odd_nout %s inj", ggml_type_name(gt)); + bad += compare(dinj_g.read(o_rows * o_hc), dinj_r.read(o_rows * o_hc), lbl, 1e-4f); + } + } + + // 8d) Metal Graph / ICB capture + replay parity for full 3-stage GR pipeline (norm -> down -> up), + // testing BOTH direct FP32-lo path (lo_xq=null) and legacy Q8_1-lo follow-up path (lo_xq!=null). + { + const int g_ne = 512, g_hc = 4, g_hcdim = g_ne * g_hc, g_lr = 256, g_nout = g_lr + g_hc; + struct PairCase { int down_wt; int up_wt; bool use_f32_lo; bool out_q; }; + const PairCase pairs[] = { + {int(GGML_TYPE_Q8_0), int(GGML_TYPE_Q6_K), true, true}, + {int(GGML_TYPE_Q4_K), int(GGML_TYPE_Q4_K), true, true}, + {int(GGML_TYPE_Q6_K), int(GGML_TYPE_Q8_0), true, false}, + {int(GGML_TYPE_Q8_0), int(GGML_TYPE_Q6_K), false, true}, + {int(GGML_TYPE_Q4_K), int(GGML_TYPE_Q4_K), false, false}, + }; + for (const auto& pc : pairs) { + const auto gd = ggml_type(pc.down_wt), gu = ggml_type(pc.up_wt); + ggml_quantize_init(gd); + ggml_quantize_init(gu); + std::vector imp_d(g_hcdim, 1.0f), imp_u(g_lr, 1.0f); + auto wdf = values(size_t(g_nout) * g_hcdim, 0.4f); + auto wuf = values(size_t(g_hcdim) * g_lr, 0.5f); + const size_t wdb = k::native_mmvq_weight_bytes(pc.down_wt, g_hcdim, g_nout); + const size_t wub = k::native_mmvq_weight_bytes(pc.up_wt, g_lr, g_hcdim); + std::vector pkd(wdb), pku(wub); + ggml_quantize_chunk(gd, wdf.data(), pkd.data(), 0, g_nout, g_hcdim, imp_d.data()); + ggml_quantize_chunk(gu, wuf.data(), pku.data(), 0, g_hcdim, g_lr, imp_u.data()); + Buffer dwd(wdb), dwu(wub); + dwd.put(pkd.data(), wdb); + dwu.put(pku.data(), wub); + + auto wn_g = values(g_hcdim, 0.2f); + for (auto& v : wn_g) v += 1.0f; + Buffer dwn(wn_g); + + for (int rcnt : {1, 2, 4, 8}) { + auto rv = values(size_t(rcnt) * g_hcdim, 0.7f); + auto bov = values(size_t(rcnt) * g_ne, 0.4f); + auto pinj = values(size_t(rcnt) * g_hc, 0.5f); + const size_t xn_qb = k::native_q8_1_bytes(g_hcdim, rcnt); + const size_t lo_qb = k::native_q8_1_bytes(g_lr, rcnt); + const size_t out_qb = k::native_q8_1_bytes(g_ne, rcnt); + + Buffer dr_dir(rv), dr_grp(rv), dbo(bov), dpinj(pinj); + Buffer dxn_dir(size_t(rcnt) * g_hcdim * 4), dxn_grp(size_t(rcnt) * g_hcdim * 4); + Buffer dxnq_dir(xn_qb), dxnq_grp(xn_qb); + Buffer dlo_dir(size_t(rcnt) * g_lr * 4), dlo_grp(size_t(rcnt) * g_lr * 4); + Buffer dloq_dir(lo_qb), dloq_grp(lo_qb); + Buffer dinj_dir(size_t(rcnt) * g_hc * 4), dinj_grp(size_t(rcnt) * g_hc * 4); + Buffer dout_dir(size_t(rcnt) * g_ne * 4), dout_grp(size_t(rcnt) * g_ne * 4); + Buffer doutq_dir(out_qb), doutq_grp(out_qb); + + auto run_chain = [&](Buffer& dr, Buffer& dxn, Buffer& dxnq, Buffer& dlo, Buffer& dloq, + Buffer& dinj, Buffer& dout, Buffer& doutq) { + p::q4_gr_write_norm_quant(dr.as(), dbo.as(), dpinj.as(), dwn.as(), dxn.as(), dxnq.ptr, + g_ne, g_hc, rcnt, 1e-6f, s); + const bool ok1 = p::q4_gr_down_silu_quant( + pc.down_wt, dwd.ptr, dxnq.ptr, nullptr, dlo.as(), + pc.use_f32_lo ? nullptr : dloq.ptr, dinj.as(), nullptr, + g_hcdim, g_lr, g_hc, true, rcnt, s); + const bool ok2 = pc.use_f32_lo + ? p::q4_gr_up_gate_mean_quant(pc.up_wt, dwu.ptr, nullptr, dlo.as(), dxn.as(), + dout.as(), pc.out_q ? doutq.ptr : nullptr, nullptr, + g_ne, g_hc, g_lr, rcnt, s) + : p::q4_gr_up_gate_mean_quant(dwu.ptr, pc.up_wt, dloq.ptr, dxn.as(), + dout.as(), pc.out_q ? doutq.ptr : nullptr, + g_ne, g_hc, g_lr, rcnt, s); + if (!ok1 || !ok2) ++bad; + }; + + // Direct stream execution + run_chain(dr_dir, dxn_dir, dxnq_dir, dlo_dir, dloq_dir, dinj_dir, dout_dir, doutq_dir); + ck(g::stream_synchronize(s)); + + // Captured Metal Graph / ICB replay (verify repeatability & hazard barriers) + g::Graph gr = nullptr; + g::GraphExec gx = nullptr; + ck(g::begin_capture(s)); + run_chain(dr_grp, dxn_grp, dxnq_grp, dlo_grp, dloq_grp, dinj_grp, dout_grp, doutq_grp); + ck(g::end_capture(s, &gr)); + ck(g::graph_instantiate(&gx, gr)); + ck(g::graph_launch(gx, s)); + ck(g::stream_synchronize(s)); + ck(g::graph_exec_destroy(gx)); + ck(g::graph_destroy(gr)); + + char lbl[128]; + std::snprintf(lbl, sizeof(lbl), "q4_gr graph %s+%s f32lo=%d oq=%d r=%d out", + ggml_type_name(gd), ggml_type_name(gu), int(pc.use_f32_lo), int(pc.out_q), rcnt); + bad += compare(dout_grp.read(size_t(rcnt) * g_ne), dout_dir.read(size_t(rcnt) * g_ne), lbl, 0.0f); + std::snprintf(lbl, sizeof(lbl), "q4_gr graph %s+%s f32lo=%d oq=%d r=%d inj", + ggml_type_name(gd), ggml_type_name(gu), int(pc.use_f32_lo), int(pc.out_q), rcnt); + bad += compare(dinj_grp.read(size_t(rcnt) * g_hc), dinj_dir.read(size_t(rcnt) * g_hc), lbl, 0.0f); + if (pc.out_q) { + auto gv = doutq_grp.read(out_qb); + auto dv = doutq_dir.read(out_qb); + if (std::memcmp(gv.data(), dv.data(), out_qb) != 0) { + std::printf("FAIL: %s xq byte mismatch vs direct\n", lbl); + ++bad; + } + } + } + } + } + } + + // 9) q4_mul_sigmoid_q8_1 (rows = 1, 4, 8) against exact CPU reference and unfused mul_sigmoid + native_quantize_q8_1 + for (int rcnt : {1, 4, 8}) { + const int head_dim = 256, n_head = 16; + const int d_inner = n_head * head_dim; + auto att = values(rcnt * d_inner, 0.8f); + auto qg = values(rcnt * 2 * d_inner, 1.4f); + const size_t qb = k::native_q8_1_bytes(d_inner, rcnt); + Buffer datt_f(att), datt_u(att), dqg(qg), dq_fus(qb), dq_unf(qb), dq_cpu(qb); + + p::q4_mul_sigmoid_q8_1(datt_f.as(), dqg.as(), dq_fus.ptr, head_dim, n_head, rcnt, s); + p::mul_sigmoid(datt_u.as(), dqg.as() + head_dim, head_dim, rcnt * n_head, 2 * head_dim, false, s); + k::native_quantize_q8_1(datt_u.as(), dq_unf.ptr, d_inner, rcnt, s); + + std::vector ref_y(rcnt * d_inner); + for (int t = 0; t < rcnt; ++t) { + for (int h = 0; h < n_head; ++h) { + for (int d = 0; d < head_dim; ++d) { + const size_t ai = (size_t(t) * n_head + h) * head_dim + d; + const size_t gi = (size_t(t) * n_head + h) * (2 * head_dim) + head_dim + d; + ref_y[ai] = att[ai] * sig(qg[gi]); + } + } + } + Buffer dref_y(ref_y); + k::native_quantize_q8_1(dref_y.as(), dq_cpu.ptr, d_inner, rcnt, s); + ck(g::stream_synchronize(s)); + + char lbl[96]; + std::snprintf(lbl, sizeof(lbl), "q4_mul_sigmoid_q8_1 r=%d vs unfused", rcnt); + bad += compare_q8_bytes(dq_fus, dq_unf, qb, lbl); + // Also verify against CPU FP32 reference (dequantized Q8_1 values + block scales/sums) + auto gv = dq_fus.read(qb); + auto cv = dq_cpu.read(qb); + int cpu_bad = 0; + const size_t nblk = qb / 36; + for (size_t b = 0; b < nblk; ++b) { + uint16_t gd_h, gs_h, cd_h, cs_h; + std::memcpy(&gd_h, gv.data() + b * 36, 2); + std::memcpy(&gs_h, gv.data() + b * 36 + 2, 2); + std::memcpy(&cd_h, cv.data() + b * 36, 2); + std::memcpy(&cs_h, cv.data() + b * 36 + 2, 2); + const float gd = ggml_fp16_to_fp32(gd_h), gs = ggml_fp16_to_fp32(gs_h); + const float cd = ggml_fp16_to_fp32(cd_h), cs = ggml_fp16_to_fp32(cs_h); + if (std::abs(gd - cd) > 1e-4f + 2e-3f * std::abs(cd)) ++cpu_bad; + if (std::abs(gs - cs) > 1e-3f + 2e-3f * std::abs(cs)) ++cpu_bad; + for (int j = 0; j < 32; ++j) { + if (std::abs(int(int8_t(gv[b * 36 + 4 + j])) - int(int8_t(cv[b * 36 + 4 + j]))) > 1) ++cpu_bad; + } + } + std::printf("q4_mul_sigmoid_q8_1 r=%d vs cpu: %d mismatches across %zu blocks\n", rcnt, cpu_bad, nblk); + bad += cpu_bad; + } return bad; } +void bench_gr_decode(g::Stream s) { + const int ne = 2048, hc = 4, hc_dim = ne * hc, lr = 256, n_out = lr + hc; + const int n_calls = 80; // exact Qwen4 calls/token (40 layers x 2 sub-layers) + const int rounds = 5; + const int reps_per_round = 16; // >= 25 ms/round so M4 GPU stays at peak clock + + auto bench_graph = [&](const char* label, double bytes_per_call, auto&& emit_one) { + // Warmup once outside capture so pipeline is compiled + emit_one(0); + ck(g::stream_synchronize(s)); + + g::Graph gr = nullptr; + g::GraphExec gx = nullptr; + ck(g::begin_capture(s)); + for (int i = 0; i < n_calls; ++i) emit_one(i); + ck(g::end_capture(s, &gr)); + ck(g::graph_instantiate(&gx, gr)); + + // Warmup graph + ck(g::graph_launch(gx, s)); + ck(g::stream_synchronize(s)); + + double best_us = 1e30; + for (int rd = 0; rd < rounds; ++rd) { + const auto t0 = std::chrono::steady_clock::now(); + for (int r = 0; r < reps_per_round; ++r) ck(g::graph_launch(gx, s)); + ck(g::stream_synchronize(s)); + const auto t1 = std::chrono::steady_clock::now(); + const double us_per_call = + std::chrono::duration(t1 - t0).count() / double(reps_per_round * n_calls); + best_us = std::min(best_us, us_per_call); + } + ck(g::graph_exec_destroy(gx)); + ck(g::graph_destroy(gr)); + const double ms_per_tok = (best_us * double(n_calls)) / 1000.0; + const double gbps = bytes_per_call / (best_us * 1e3); + std::printf(" bench %-40s: %6.2f us/call | %5.2f ms/80 | %6.2f GB/s\n", + label, best_us, ms_per_tok, gbps); + }; + + // 1) q4_gr_norm_quant (WRITE_PREV=0) & q4_gr_write_norm_quant (WRITE_PREV=1), QUANT=1 + for (int rcnt : {1, 2}) { + const int w_copies = 80; // 80 * 32 KiB = 2.56 MiB (exact 40-layer x 2 footprint) + auto r = values(size_t(rcnt) * hc_dim, 0.8f); + auto bo = values(size_t(rcnt) * ne, 0.5f); + auto inj = values(size_t(rcnt) * hc, 0.4f); + auto wn1 = values(size_t(hc_dim), 0.2f); + for (auto& v : wn1) v += 1.0f; + Buffer dr(r), dbo(bo), dinj(inj), dxn(size_t(rcnt) * hc_dim * 4); + const size_t xq_b = k::native_q8_1_bytes(ne, rcnt * hc); + Buffer dxq(xq_b); + Buffer dwn(size_t(w_copies) * hc_dim * 4); + for (int c = 0; c < w_copies; ++c) + ck(g::memcpy_sync(static_cast(dwn.ptr) + size_t(c) * hc_dim * 4, + wn1.data(), size_t(hc_dim) * 4, g::kHostToDevice)); + char lbl[96]; + const double bytes0 = double(2ULL * size_t(rcnt) * hc_dim * 4 + size_t(hc_dim) * 4 + xq_b); + std::snprintf(lbl, sizeof(lbl), "q4_gr_norm_0_1 r=%d", rcnt); + bench_graph(lbl, bytes0, [&](int i) { + const float* wnp = dwn.as() + size_t(i % w_copies) * hc_dim; + p::q4_gr_norm_quant(dr.as(), wnp, dxn.as(), dxq.ptr, ne, hc, rcnt, 1e-6f, s); + }); + const double bytes1 = double(3ULL * size_t(rcnt) * hc_dim * 4 + size_t(rcnt) * ne * 4 + size_t(hc_dim) * 4 + xq_b); + std::snprintf(lbl, sizeof(lbl), "q4_gr_norm_1_1 r=%d", rcnt); + bench_graph(lbl, bytes1, [&](int i) { + const float* wnp = dwn.as() + size_t(i % w_copies) * hc_dim; + p::q4_gr_write_norm_quant(dr.as(), dbo.as(), dinj.as(), wnp, dxn.as(), dxq.ptr, ne, hc, rcnt, 1e-6f, s); + }); + } + + // 2) q4_gr_down_silu_quant (Q8_0, Q6_K, Q4_K; rows=1, 2; with and without lo_xq) + for (int wt : {int(GGML_TYPE_Q8_0), int(GGML_TYPE_Q6_K), int(GGML_TYPE_Q4_K)}) { + const auto gt = ggml_type(wt); + ggml_quantize_init(gt); + const size_t wb = k::native_mmvq_weight_bytes(wt, hc_dim, n_out); + const int copies = std::max(1, int((15ULL << 20) / wb)); // ~15 MiB total (< 20 MiB VRAM, busts 8 MiB SLC) + auto wf = values(size_t(n_out) * hc_dim, 0.5f); + std::vector imp(hc_dim, 1.0f); + std::vector packed(wb); + ggml_quantize_chunk(gt, wf.data(), packed.data(), 0, n_out, hc_dim, imp.data()); + Buffer dw(wb * size_t(copies)); + for (int c = 0; c < copies; ++c) + ck(g::memcpy_sync(static_cast(dw.ptr) + size_t(c) * wb, packed.data(), wb, g::kHostToDevice)); + Buffer dcnt(16 * sizeof(uint32_t)); + ck(g::memset_async(dcnt.ptr, 0, 16 * sizeof(uint32_t), s)); + + for (int rcnt : {1, 2}) { + auto xn = values(size_t(rcnt) * hc_dim, 0.6f); + const size_t xn_qb = k::native_q8_1_bytes(hc_dim, rcnt); + const size_t lo_qb = k::native_q8_1_bytes(lr, rcnt); + Buffer dxn(xn), dxnq(xn_qb), dlo(size_t(rcnt) * lr * 4), dinj(size_t(rcnt) * hc * 4), dloq(lo_qb); + k::native_quantize_q8_1(dxn.as(), dxnq.ptr, hc_dim, rcnt, s); + ck(g::stream_synchronize(s)); + + for (bool do_q : {false, true}) { + char lbl[96]; + std::snprintf(lbl, sizeof(lbl), "q4_gr_down %s r=%d q=%d", ggml_type_name(gt), rcnt, int(do_q)); + const double bytes = double(wb + xn_qb + size_t(rcnt) * (lr + hc) * 4 + (do_q ? lo_qb : 0)); + bench_graph(lbl, bytes, [&](int i) { + const void* wp = static_cast(dw.ptr) + size_t(i % copies) * wb; + p::q4_gr_down_silu_quant(wt, wp, dxnq.ptr, nullptr, dlo.as(), + do_q ? dloq.ptr : nullptr, dinj.as(), + do_q ? dcnt.as() : nullptr, + hc_dim, lr, hc, true, rcnt, s); + }); + } + } + } + + // 3) q4_gr_up_gate_mean_quant (Q6_K, Q4_K, Q8_0; rows=1, 2; QUANT=1) + for (int wt : {int(GGML_TYPE_Q6_K), int(GGML_TYPE_Q4_K), int(GGML_TYPE_Q8_0)}) { + const auto gt = ggml_type(wt); + ggml_quantize_init(gt); + const size_t wb = k::native_mmvq_weight_bytes(wt, lr, hc_dim); + const int copies = std::max(1, int((15ULL << 20) / wb)); // ~15 MiB total (< 20 MiB VRAM) + auto wf = values(size_t(hc_dim) * lr, 0.6f); + std::vector imp(lr, 1.0f); + std::vector packed(wb); + ggml_quantize_chunk(gt, wf.data(), packed.data(), 0, hc_dim, lr, imp.data()); + Buffer dw(wb * size_t(copies)); + for (int c = 0; c < copies; ++c) + ck(g::memcpy_sync(static_cast(dw.ptr) + size_t(c) * wb, packed.data(), wb, g::kHostToDevice)); + + for (int rcnt : {1, 2}) { + auto lo = values(size_t(rcnt) * lr, 0.8f); + auto xn = values(size_t(rcnt) * hc_dim, 0.7f); + const size_t lo_qb = k::native_q8_1_bytes(lr, rcnt); + const size_t out_qb = k::native_q8_1_bytes(ne, rcnt); + Buffer dlo(lo), dloq(lo_qb), dxn(xn), dout(size_t(rcnt) * ne * 4), doutq(out_qb); + k::native_quantize_q8_1(dlo.as(), dloq.ptr, lr, rcnt, s); + ck(g::stream_synchronize(s)); + + char lbl[96]; + std::snprintf(lbl, sizeof(lbl), "q4_gr_up %s r=%d f32_lo", ggml_type_name(gt), rcnt); + const double bytes_f32 = double(wb + size_t(rcnt) * lr * 4 + size_t(rcnt) * (hc_dim + ne) * 4 + out_qb); + bench_graph(lbl, bytes_f32, [&](int i) { + const void* wp = static_cast(dw.ptr) + size_t(i % copies) * wb; + p::q4_gr_up_gate_mean_quant(wt, wp, nullptr, dlo.as(), dxn.as(), dout.as(), doutq.ptr, nullptr, + ne, hc, lr, rcnt, s); + }); + std::snprintf(lbl, sizeof(lbl), "q4_gr_up %s r=%d q8_lo", ggml_type_name(gt), rcnt); + const double bytes = double(wb + lo_qb + size_t(rcnt) * (hc_dim + ne) * 4 + out_qb); + bench_graph(lbl, bytes, [&](int i) { + const void* wp = static_cast(dw.ptr) + size_t(i % copies) * wb; + p::q4_gr_up_gate_mean_quant(wp, wt, dloq.ptr, dxn.as(), dout.as(), doutq.ptr, + ne, hc, lr, rcnt, s); + }); + } + } + + // 4) Full 3-stage Qwen4 GR chain (write_norm -> down Q8_0 f32-lo -> up Q6_K f32-lo), 80 calls/tok (< 18 MiB VRAM) + { + const int wt_d = int(GGML_TYPE_Q8_0), wt_u = int(GGML_TYPE_Q6_K); + ggml_quantize_init(ggml_type(wt_d)); + ggml_quantize_init(ggml_type(wt_u)); + const size_t wdb = k::native_mmvq_weight_bytes(wt_d, hc_dim, n_out); + const size_t wub = k::native_mmvq_weight_bytes(wt_u, lr, hc_dim); + const int copies = 4; // 4 * (2.16 + 1.64) = 15.2 MiB (< 20 MiB VRAM, busts 8 MiB SLC) + auto wdf = values(size_t(n_out) * hc_dim, 0.4f); + auto wuf = values(size_t(hc_dim) * lr, 0.5f); + std::vector imp_d(hc_dim, 1.0f), imp_u(lr, 1.0f); + std::vector pkd(wdb), pku(wub); + ggml_quantize_chunk(ggml_type(wt_d), wdf.data(), pkd.data(), 0, n_out, hc_dim, imp_d.data()); + ggml_quantize_chunk(ggml_type(wt_u), wuf.data(), pku.data(), 0, hc_dim, lr, imp_u.data()); + Buffer dwd(wdb * copies), dwu(wub * copies); + for (int c = 0; c < copies; ++c) { + ck(g::memcpy_sync(static_cast(dwd.ptr) + size_t(c) * wdb, pkd.data(), wdb, g::kHostToDevice)); + ck(g::memcpy_sync(static_cast(dwu.ptr) + size_t(c) * wub, pku.data(), wub, g::kHostToDevice)); + } + auto wn1 = values(hc_dim, 0.2f); + for (auto& v : wn1) v += 1.0f; + Buffer dwn(size_t(copies) * hc_dim * 4); + for (int c = 0; c < copies; ++c) + ck(g::memcpy_sync(static_cast(dwn.ptr) + size_t(c) * hc_dim * 4, + wn1.data(), size_t(hc_dim) * 4, g::kHostToDevice)); + + for (int rcnt : {1, 2}) { + auto r = values(size_t(rcnt) * hc_dim, 0.7f); + auto bo = values(size_t(rcnt) * ne, 0.5f); + auto pinj = values(size_t(rcnt) * hc, 0.4f); + const size_t xn_qb = k::native_q8_1_bytes(hc_dim, rcnt); + const size_t out_qb = k::native_q8_1_bytes(ne, rcnt); + Buffer dr(r), dbo(bo), dpinj(pinj), dxn(size_t(rcnt) * hc_dim * 4), dxnq(xn_qb); + Buffer dlo(size_t(rcnt) * lr * 4), dinj(size_t(rcnt) * hc * 4); + Buffer dout(size_t(rcnt) * ne * 4), doutq(out_qb); + char lbl[96]; + std::snprintf(lbl, sizeof(lbl), "q4_gr FULL chain Q8+Q6 r=%d", rcnt); + const double bytes = double(wdb + wub + size_t(hc_dim) * 4 + + size_t(rcnt) * (4 * hc_dim + 2 * ne + lr + hc) * 4 + xn_qb + out_qb); + bench_graph(lbl, bytes, [&](int i) { + const int idx = i % copies; + const float* wnp = dwn.as() + size_t(idx) * hc_dim; + const void* wdp = static_cast(dwd.ptr) + size_t(idx) * wdb; + const void* wup = static_cast(dwu.ptr) + size_t(idx) * wub; + p::q4_gr_write_norm_quant(dr.as(), dbo.as(), dpinj.as(), wnp, dxn.as(), dxnq.ptr, ne, hc, rcnt, 1e-6f, s); + p::q4_gr_down_silu_quant(wt_d, wdp, dxnq.ptr, nullptr, dlo.as(), nullptr, dinj.as(), nullptr, + hc_dim, lr, hc, true, rcnt, s); + p::q4_gr_up_gate_mean_quant(wt_u, wup, nullptr, dlo.as(), dxn.as(), dout.as(), doutq.ptr, nullptr, + ne, hc, lr, rcnt, s); + }); + } + } +} + int test_ple(g::Stream s) { int bad = 0; const int n_embd = 128, hc = 4, channels = n_embd * hc, conv_k = 4, dil = 3, hlen = (conv_k - 1) * dil; @@ -437,6 +1133,187 @@ int test_qsa(g::Stream s) { bad += topk_bad; } + // 2b) q4_qsa_score_batch_mma vs CPU reference across n={1,4,17,64}, max_blocks={16,100,1027}, pos={0,512,4096} + // + NaN-poisoned future pool slots, non-packed score_stride, top-K match, scalar fallback, and timing bench + { + const bool prev_opt = g::metal::optimize(); + struct ScoreCase { + const char* name; + int rows; + int max_blocks; + int score_stride; + int64_t pos; + int idx_heads; + int idx_block; + }; + const ScoreCase cases[] = { + {"r1_b16_p0", 1, 16, 16, 0, 4, 4}, + {"r4_b16_p0", 4, 16, 16, 0, 4, 4}, + {"r4_b16_p0_zero", 4, 16, 16, 0, 4, 8}, // nv_max == 0: full-tile causal early-out + {"r4_b100_p512", 4, 100, 113, 512, 4, 4}, // strided score buffer + {"r17_b16_p0", 17, 16, 16, 0, 4, 4}, + {"r17_b100_p512", 17, 100, 100, 512, 4, 4}, + {"r17_b1027_p4k", 17, 1027, 1040, 4096, 4, 4}, + {"r64_b100_p0", 64, 100, 100, 0, 4, 4}, // partial causal triangle inside 64x100 + {"r64_b1027_p512",64, 1027, 1027, 512, 4, 4}, + {"r64_b1027_p4k", 64, 1027, 1027, 4096, 4, 4}, + {"r17_b100_h1", 17, 100, 100, 512, 1, 4}, + {"r17_b100_h8", 17, 100, 100, 512, 8, 4}, + }; + for (bool opt_mode : {true, false}) { + g::metal::set_optimize(opt_mode); + for (const auto& tc : cases) { + auto iq = values(size_t(tc.rows) * tc.idx_heads * idx_dim, 0.5f); + auto pool = values(size_t(tc.max_blocks) * idx_dim, 0.5f); + // Poison future causal blocks (b >= nv_max) with NaN to ensure MMA never reads/leaks them + const int64_t nv_max_all = (tc.pos + tc.rows) / tc.idx_block; + for (int b = int(std::max(0, nv_max_all)); b < tc.max_blocks; ++b) { + for (int d = 0; d < idx_dim; ++d) + pool[size_t(b) * idx_dim + d] = std::numeric_limits::quiet_NaN(); + } + + Buffer diq(iq), dpool(pool), dscore(size_t(tc.rows) * tc.score_stride * 4); + // Poison score buffer with +1234.0f to verify every valid (t, b) is written and padding is untouched + std::vector init_sc(size_t(tc.rows) * tc.score_stride, 1234.0f); + dscore.put(init_sc.data(), init_sc.size() * 4); + + p::q4_qsa_score(diq.as(), dpool.as(), dscore.as(), tc.score_stride, tc.max_blocks, + tc.idx_heads, idx_dim, tc.idx_block, tc.pos, tc.rows, s, nullptr); + ck(g::stream_synchronize(s)); + auto got = dscore.read(size_t(tc.rows) * tc.score_stride); + + int case_bad = 0; + float max_abs_err = 0.0f; + const float tol = opt_mode ? 2e-2f : 1e-4f; + const float inv_sqrt_d = 1.0f / std::sqrt(float(idx_dim)); + + for (int t = 0; t < tc.rows; ++t) { + const int64_t nv = (tc.pos + t + 1) / tc.idx_block; + for (int b = 0; b < tc.max_blocks; ++b) { + const float gv = got[size_t(t) * tc.score_stride + b]; + if (int64_t(b) >= nv) { + if (!(std::isinf(gv) && gv < 0.0f)) ++case_bad; + } else { + double tot = 0.0; + for (int h = 0; h < tc.idx_heads; ++h) { + double dot = 0.0; + for (int d = 0; d < idx_dim; ++d) + dot += double(iq[(size_t(t) * tc.idx_heads + h) * idx_dim + d]) * + double(pool[size_t(b) * idx_dim + d]); + if (dot > 0.0) tot += dot; + } + const float ref = float(tot) * inv_sqrt_d; + const float err = std::abs(gv - ref); + max_abs_err = std::max(max_abs_err, err); + if (!std::isfinite(gv) || err > tol) ++case_bad; + } + } + // Verify stride padding columns [max_blocks .. score_stride) were not overwritten + for (int b = tc.max_blocks; b < tc.score_stride; ++b) { + if (got[size_t(t) * tc.score_stride + b] != 1234.0f) ++case_bad; + } + } + std::printf("q4_qsa_score_%s %s: %d mismatches, max_abs_err=%g\n", + opt_mode ? "mma" : "scalar", tc.name, case_bad, max_abs_err); + bad += case_bad; + } + } + + // Top-K exact index match test (distinct score gaps > 0.25 so FP16 MMA selects exact same top-K blocks as CPU) + { + g::metal::set_optimize(true); + const int rows = 32, max_blocks = 256, top_blocks = 64, sel_cap = top_blocks * idx_block + idx_block - 1; + const int64_t pos = max_blocks * idx_block - rows; // (pos + rows) / idx_block == max_blocks (causal boundary!) + std::vector iq(size_t(rows) * idx_heads * idx_dim, 0.0f); + std::vector pool(size_t(max_blocks) * idx_dim, 0.0f); + for (int t = 0; t < rows; ++t) { + for (int h = 0; h < idx_heads; ++h) { + iq[(size_t(t) * idx_heads + h) * idx_dim + (t % 32)] = 1.0f; + iq[(size_t(t) * idx_heads + h) * idx_dim + 64] = 1.0f; + } + } + for (int b = 0; b < max_blocks; ++b) { + // Distinct well-separated rank per block modulated by permutation + const int rank = (b * 73 + 19) % max_blocks; + pool[size_t(b) * idx_dim + 64] = float(rank) * 0.5f; + pool[size_t(b) * idx_dim + (b % 32)] = 0.05f * float(b & 7); + } + Buffer diq(iq), dpool(pool), dscore(size_t(rows) * max_blocks * 4); + Buffer dsel(size_t(rows) * sel_cap * 4), dcnt(size_t(rows) * 4); + p::q4_qsa_score(diq.as(), dpool.as(), dscore.as(), max_blocks, max_blocks, + idx_heads, idx_dim, idx_block, pos, rows, s, nullptr); + p::q4_qsa_topk(dscore.as(), max_blocks, dsel.as(), sel_cap, dcnt.as(), + top_blocks, idx_block, pos, rows, s, nullptr); + ck(g::stream_synchronize(s)); + auto got_ids = dsel.read(size_t(rows) * sel_cap); + auto got_cnt = dcnt.read(rows); + + int topk_mma_bad = 0; + const float inv_sqrt_d = 1.0f / std::sqrt(float(idx_dim)); + for (int t = 0; t < rows; ++t) { + const int n_kv = int(pos + t + 1); + const int nv = n_kv / idx_block; + const int n_tail = n_kv - nv * idx_block; + std::vector ref_s(nv, 0.0f); + for (int b = 0; b < nv; ++b) { + double tot = 0.0; + for (int h = 0; h < idx_heads; ++h) { + double dot = 0.0; + for (int d = 0; d < idx_dim; ++d) + dot += double(iq[(size_t(t) * idx_heads + h) * idx_dim + d]) * + double(pool[size_t(b) * idx_dim + d]); + if (dot > 0.0) tot += dot; + } + ref_s[b] = float(tot) * inv_sqrt_d; + } + std::vector idx(nv); + std::iota(idx.begin(), idx.end(), 0); + std::stable_sort(idx.begin(), idx.end(), [&](int a, int b) { return ref_s[a] > ref_s[b]; }); + idx.resize(top_blocks); + std::sort(idx.begin(), idx.end()); + if (got_cnt[t] != top_blocks * idx_block + n_tail) ++topk_mma_bad; + for (int k0 = 0; k0 < top_blocks; ++k0) { + for (int c = 0; c < idx_block; ++c) { + if (got_ids[size_t(t) * sel_cap + k0 * idx_block + c] != idx[k0] * idx_block + c) ++topk_mma_bad; + } + } + for (int c = 0; c < n_tail; ++c) { + if (got_ids[size_t(t) * sel_cap + top_blocks * idx_block + c] != nv * idx_block + c) ++topk_mma_bad; + } + } + std::printf("q4_qsa_score_batch_mma top-K exact match: %d mismatches\n", topk_mma_bad); + bad += topk_mma_bad; + } + + // Microbenchmark: 4K prefill tile (rows=512, max_blocks=1024, pos=3584, idx_heads=4, idx_dim=128) + { + const int rows = 512, max_blocks = 1024; + const int64_t pos = 3584; + auto iq = values(size_t(rows) * idx_heads * idx_dim, 0.5f); + auto pool = values(size_t(max_blocks) * idx_dim, 0.5f); + Buffer diq(iq), dpool(pool), dscore(size_t(rows) * max_blocks * 4); + for (bool opt_mode : {false, true}) { + g::metal::set_optimize(opt_mode); + for (int it = 0; it < 3; ++it) + p::q4_qsa_score(diq.as(), dpool.as(), dscore.as(), max_blocks, max_blocks, + idx_heads, idx_dim, idx_block, pos, rows, s, nullptr); + ck(g::stream_synchronize(s)); + const int iters = 10; + const auto t0 = std::chrono::steady_clock::now(); + for (int it = 0; it < iters; ++it) + p::q4_qsa_score(diq.as(), dpool.as(), dscore.as(), max_blocks, max_blocks, + idx_heads, idx_dim, idx_block, pos, rows, s, nullptr); + 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 = 2.0 * double(rows) * double(max_blocks) * double(idx_heads) * double(idx_dim); + std::printf(" bench q4_qsa_score %s r=512 b=1024: %.3f ms/call (%.3f TFLOP/s)\n", + opt_mode ? "mma " : "scalar", ms, (flops / (ms * 1e-3)) / 1e12); + } + } + g::metal::set_optimize(prev_opt); + } + // 3) q4_qsa_attend (FP16 & Q8_0, split-K & batch) for (int use_q8 : {0, 1}) { for (int rows : {2, 20}) { @@ -783,20 +1660,58 @@ int test_mtp_split_and_gdn(g::Stream s) { bad += compare(dout.read(ref.size()), ref, "q4_mtp_eh_concat"); } - // 2) q4_split_2d + // 2) q4_split_2d (scalar non-multiple-of-4 fallback + vec4 bit-exact parity + prefill microbench) { - const int na = 97, nb = 61, rows = 5; - auto in = values(rows * (na + nb), 1.0f); - Buffer din(in), da(rows * na * 4), db(rows * nb * 4); - p::q4_split_2d(din.as(), da.as(), db.as(), na, nb, rows, s); - ck(g::stream_synchronize(s)); - std::vector ra(rows * na), rb(rows * nb); - for (int r = 0; r < rows; ++r) { - for (int c = 0; c < na; ++c) ra[r * na + c] = in[r * (na + nb) + c]; - for (int c = 0; c < nb; ++c) rb[r * nb + c] = in[r * (na + nb) + na + c]; + struct SplitCase { + const char* name; + int na; + int nb; + int rows; + }; + const SplitCase cases[] = { + {"scalar_97_61_r5", 97, 61, 5}, + {"scalar_128_61_r7", 128, 61, 7}, + {"scalar_61_128_r7", 61, 128, 7}, + {"vec4_32_32_r1", 32, 32, 1}, + {"vec4_2048_2048_r4", 2048, 2048, 4}, + {"vec4_8192_4096_r17", 8192, 4096, 17}, + {"vec4_2048_2048_r1024",2048, 2048, 1024}, + }; + for (const auto& tc : cases) { + const size_t width = size_t(tc.na) + size_t(tc.nb); + auto in = values(size_t(tc.rows) * width, 1.0f); + Buffer din(in), da(size_t(tc.rows) * tc.na * 4), db(size_t(tc.rows) * tc.nb * 4); + p::q4_split_2d(din.as(), da.as(), db.as(), tc.na, tc.nb, tc.rows, s); + ck(g::stream_synchronize(s)); + auto ga = da.read(size_t(tc.rows) * tc.na); + auto gb = db.read(size_t(tc.rows) * tc.nb); + std::vector ra(size_t(tc.rows) * tc.na), rb(size_t(tc.rows) * tc.nb); + for (int r = 0; r < tc.rows; ++r) { + std::memcpy(ra.data() + size_t(r) * tc.na, in.data() + size_t(r) * width, size_t(tc.na) * 4); + std::memcpy(rb.data() + size_t(r) * tc.nb, in.data() + size_t(r) * width + tc.na, size_t(tc.nb) * 4); + } + const int eq_a = (std::memcmp(ga.data(), ra.data(), ra.size() * 4) == 0) ? 0 : 1; + const int eq_b = (std::memcmp(gb.data(), rb.data(), rb.size() * 4) == 0) ? 0 : 1; + std::printf("q4_split_2d %s: bit-exact A=%s B=%s\n", tc.name, eq_a ? "FAIL" : "OK", eq_b ? "FAIL" : "OK"); + bad += eq_a + eq_b; + } + // Microbenchmark: 512 x (8192 + 4096) GDN qkv_gate split + { + const int na = 8192, nb = 4096, rows = 512; + auto in = values(size_t(rows) * (na + nb), 1.0f); + Buffer din(in), da(size_t(rows) * na * 4), db(size_t(rows) * nb * 4); + for (int it = 0; it < 3; ++it) p::q4_split_2d(din.as(), da.as(), db.as(), na, nb, rows, s); + ck(g::stream_synchronize(s)); + const int iters = 20; + const auto t0 = std::chrono::steady_clock::now(); + for (int it = 0; it < iters; ++it) p::q4_split_2d(din.as(), da.as(), db.as(), na, nb, rows, 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 bytes = 2.0 * 4.0 * double(rows) * double(na + nb); + std::printf(" bench q4_split_2d_vec4 r=512 na=8192 nb=4096: %.3f ms/call (%.1f GB/s)\n", + ms, bytes / (ms * 1e6)); } - bad += compare(da.read(ra.size()), ra, "q4_split_2d A"); - bad += compare(db.read(rb.size()), rb, "q4_split_2d B"); } // 3) gdn_step_sigmoid (rows=5 and rows=40) + q4_gdn_decode_fused parity against conv4_silu + gdn_step_sigmoid @@ -863,6 +1778,7 @@ int main() { ck(g::stream_create(&s)); int bad = 0; bad += test_gr(s); + bench_gr_decode(s); bad += test_ple(s); bad += test_qsa(s); bad += test_mtp_split_and_gdn(s); diff --git a/engine/metal/src/poly/quantized.cpp b/engine/metal/src/poly/quantized.cpp index 57aff936f..0d4630a35 100644 --- a/engine/metal/src/poly/quantized.cpp +++ b/engine/metal/src/poly/quantized.cpp @@ -45,6 +45,12 @@ struct GArgs { // mm.metal's GemmArgs int m=0,n=0,k=0,pad=0; }; static_assert(sizeof(GArgs)==40); +struct GuSwigluArgs { // quantized.metal's GuSwigluArgs + const void* p[5]{}; + uint64_t xstride=0,offset_g=0,offset_u=0; + int ni=0,n_ff=0,count=0,every=1; +}; +static_assert(sizeof(GuSwigluArgs)==80); // The fp16 copy of a dense matrix (poly_dq) that poly_gemm reads: grown to the largest one, kept; older slabs // remain valid in retired until process exit so live GraphExec ICB args_buf pointers never dangle. Larger matrices // than kDqMax bytes of halves (an output head) and calls of fewer than kDqRows rows stay with poly_mm. @@ -366,6 +372,46 @@ bool native_mmvq_ids(int t,const MmvqIds& a,int count,int ni,int no,void* s) { } qrun(std::string("poly_mul_")+quant_name(t),q,s,{uint32_t(no),uint32_t(count),1});return true; } +bool native_mmvq_ids_gu_swiglu_q8_supported(int t) { + return t==12 || t==17 || t==18 || t==22 || t==40; +} +bool native_mmvq_ids_gu_swiglu_q8(int t,const MmvqIdsGuSwiglu& a,int count,int ni,int n_ff,void* s) { + if(!native_mmvq_ids_gu_swiglu_q8_supported(t) || count<0 || ni<=0 || n_ff<=0 || + (ni%block_values(t))!=0 || (n_ff%32)!=0 || a.x_every<=0 || + !a.table || !a.ids || !a.x || !a.q8_out || !gpu::metal::optimize()) + return false; + if(!count) return true; + static const auto source=quant_source(); + const bool grouped = a.group_buf && a.group_ready && count>1 && count<=64; + GuSwigluArgs g; + g.p[0]=a.table; + g.p[1]=a.x; + g.p[2]=a.q8_out; + g.p[3]=a.ids; + g.p[4]=grouped?a.group_buf:nullptr; + g.xstride=a.x_stride; + g.offset_g=a.gate_offset; + g.offset_u=a.up_offset; + g.ni=ni; + g.n_ff=n_ff; + g.count=count; + g.every=a.x_every; + if(__builtin_expect(gpu::metal::prof_level()>0,0)) { + const uint64_t x_rows=uint64_t((count-1)/a.x_every+1); + const uint64_t b=2ULL*uint64_t(quant::row_bytes(t,ni))*uint64_t(n_ff)*uint64_t(count)+ + native_q8_1_bytes(ni,int(x_rows))+native_q8_1_bytes(n_ff,count); + gpu::metal::prof_push_hint({gpu::metal::ProfCat::GemvDecode,b,4ULL*uint64_t(count)*uint64_t(ni)*uint64_t(n_ff)}); + } + const gpu::metal::Access modes[5]={gpu::metal::Access::R,gpu::metal::Access::R,gpu::metal::Access::W, + gpu::metal::Access::R,gpu::metal::Access::R}; + const size_t x_b=size_t((count-1)/a.x_every)*size_t(a.x_stride)+native_q8_1_bytes(ni,1); + const size_t sizes[5]={0,x_b,native_q8_1_bytes(n_ff,count),4ULL*size_t(count), + grouped?kMmvqIdsGroupBytes:0}; + const std::string k=std::string("poly_mul_")+quant_name(t)+(grouped?"_k1g_gu_swiglu_q8":"_k1_gu_swiglu_q8"); + dispatch("poly_quantized",source,k.c_str(),g,s,{uint32_t(n_ff/32),uint32_t(count),1},256, + {g.p,grouped?5u:4u,true,g.p[0],modes,sizes,true}); + return true; +} // Any type poly_mul has: the matrices' outputs one after another in one launch (kind 9), each output the sum // native_mmvq() gives it bool native_mmvq_many_fits(int t,const NativeMmvqMany& m,int ni) { @@ -465,7 +511,11 @@ Mmq::Mmq() { "poly_mul_nvfp4_k1","poly_mul_q4_K_k1", "poly_mul_iq2_s_k1","poly_mul_iq2_xs_k1","poly_mul_iq3_xxs_k1", "poly_mul_nvfp4_k1g","poly_mul_q4_K_k1g", - "poly_mul_iq2_s_k1g","poly_mul_iq2_xs_k1g","poly_mul_iq3_xxs_k1g"}) + "poly_mul_iq2_s_k1g","poly_mul_iq2_xs_k1g","poly_mul_iq3_xxs_k1g", + "poly_mul_nvfp4_k1_gu_swiglu_q8","poly_mul_q4_K_k1_gu_swiglu_q8", + "poly_mul_iq2_s_k1_gu_swiglu_q8","poly_mul_iq2_xs_k1_gu_swiglu_q8","poly_mul_iq3_xxs_k1_gu_swiglu_q8", + "poly_mul_nvfp4_k1g_gu_swiglu_q8","poly_mul_q4_K_k1g_gu_swiglu_q8", + "poly_mul_iq2_s_k1g_gu_swiglu_q8","poly_mul_iq2_xs_k1g_gu_swiglu_q8","poly_mul_iq3_xxs_k1g_gu_swiglu_q8"}) gpu::metal::pipeline("poly_quantized",source.c_str(),k,error); } Mmq::~Mmq() = default; diff --git a/engine/metal/src/poly/quantized.metal b/engine/metal/src/poly/quantized.metal index a312a16e0..fa306986f 100644 --- a/engine/metal/src/poly/quantized.metal +++ b/engine/metal/src/poly/quantized.metal @@ -726,6 +726,430 @@ kernel void poly_mul_k1g(constant QArgs& a [[buffer(0)]],uint3 group [[threadgro } #define MULK1G(name,QK) template [[host_name("poly_mul_" #name "_k1g")]] kernel decltype(poly_mul_k1g) poly_mul_k1g; MULK1G(nvfp4,64) MULK1G(q4_K,256) MULK1G(iq2_s,256) MULK1G(iq2_xs,256) MULK1G(iq3_xxs,256) + +// Threadgroup-staged LUT helpers for IQ2_XS (8 KiB + 128 B), IQ2_S (8 KiB), and IQ3_XXS (2 KiB + 128 B). +struct lut_none { + enum { kHasLut = 0 }; + struct Storage { uint dummy; }; + static inline void load(threadgroup Storage&, uint, uint) {} +}; +struct lut_iq2_xs { + enum { kHasLut = 1 }; + struct Storage { short4 grid_lo[512]; short4 grid_hi[512]; uchar signs[128]; }; + static inline void load(threadgroup Storage& s, uint tid, uint nthreads) { + for (uint i = tid; i < 512u; i += nthreads) { + const uint2 g = as_type(iq2xs_grid[i]); + s.grid_lo[i] = short4(as_type(g.x)); + s.grid_hi[i] = short4(as_type(g.y)); + } + for (uint i = tid; i < 128u; i += nthreads) s.signs[i] = ksigns_iq2xs[i]; + } +}; +struct lut_iq2_s { + enum { kHasLut = 1 }; + struct Storage { uint2 grid[1024]; }; + static inline void load(threadgroup Storage& s, uint tid, uint nthreads) { + for (uint i = tid; i < 1024u; i += nthreads) s.grid[i] = as_type(iq2s_grid[i]); + } +}; +struct lut_iq3_xxs { + enum { kHasLut = 1 }; + struct Storage { short4 grid[256]; uchar signs[128]; }; + static inline void load(threadgroup Storage& s, uint tid, uint nthreads) { + for (uint i = tid; i < 256u; i += nthreads) s.grid[i] = short4(as_type(iq3xxs_grid[i])); + for (uint i = tid; i < 128u; i += nthreads) s.signs[i] = ksigns_iq2xs[i]; + } +}; +// Exact 16-bit integer dot for 16 signed-grid elements against Q8_1 int8 codes: +// max |x| <= 128 and max grid byte <= 62 (iq2_xs/iq2_s: 43, iq3_xxs: 62), so 4 products per lane <= 31,744 <= 32,767. +static inline int signed_grid16_i16(uint2 g1, uint2 g2, uint s1, uint s2, + thread const short4* qv, thread const short4* nqv) { + const bool4 b0 = (ushort4(s1) & ushort4(1u, 2u, 4u, 8u)) != 0u; + const bool4 b1 = (ushort4(s1) & ushort4(16u, 32u, 64u, 128u)) != 0u; + const bool4 b2 = (ushort4(s2) & ushort4(1u, 2u, 4u, 8u)) != 0u; + const bool4 b3 = (ushort4(s2) & ushort4(16u, 32u, 64u, 128u)) != 0u; + const short4 p = select(qv[0], nqv[0], b0) * short4(as_type(g1.x)) + + select(qv[1], nqv[1], b1) * short4(as_type(g1.y)) + + select(qv[2], nqv[2], b2) * short4(as_type(g2.x)) + + select(qv[3], nqv[3], b3) * short4(as_type(g2.y)); + return (int(p.x) + int(p.y)) + (int(p.z) + int(p.w)); +} +static inline int signed_grid16_s4_i16(short4 g0, short4 g1, short4 g2, short4 g3, uint s1, uint s2, + thread const short4* qv, thread const short4* nqv) { + const bool4 b0 = (ushort4(s1) & ushort4(1u, 2u, 4u, 8u)) != 0u; + const bool4 b1 = (ushort4(s1) & ushort4(16u, 32u, 64u, 128u)) != 0u; + const bool4 b2 = (ushort4(s2) & ushort4(1u, 2u, 4u, 8u)) != 0u; + const bool4 b3 = (ushort4(s2) & ushort4(16u, 32u, 64u, 128u)) != 0u; + const short4 p = select(qv[0], nqv[0], b0) * g0 + select(qv[1], nqv[1], b1) * g1 + + select(qv[2], nqv[2], b2) * g2 + select(qv[3], nqv[3], b3) * g3; + return (int(p.x) + int(p.y)) + (int(p.z) + int(p.w)); +} +struct dot_nvfp4_tg { + enum { kSum = 0 }; + static inline float run(device const block_nvfp4* b, short il, float dx, thread const short4* qv, + thread const short4*, short, threadgroup const lut_none::Storage&) { + device const uint* q = reinterpret_cast(b->qs + 8 * il); + const uint lo = q[0], hi = q[1]; + const float4 w0 = float4(kvalues_nvfp4_f[(lo >> 0) & 15], kvalues_nvfp4_f[(lo >> 8) & 15], kvalues_nvfp4_f[(lo >> 16) & 15], kvalues_nvfp4_f[(lo >> 24) & 15]); + const float4 w1 = float4(kvalues_nvfp4_f[(hi >> 0) & 15], kvalues_nvfp4_f[(hi >> 8) & 15], kvalues_nvfp4_f[(hi >> 16) & 15], kvalues_nvfp4_f[(hi >> 24) & 15]); + const float4 w2 = float4(kvalues_nvfp4_f[(lo >> 4) & 15], kvalues_nvfp4_f[(lo >> 12) & 15], kvalues_nvfp4_f[(lo >> 20) & 15], kvalues_nvfp4_f[(lo >> 28) & 15]); + const float4 w3 = float4(kvalues_nvfp4_f[(hi >> 4) & 15], kvalues_nvfp4_f[(hi >> 12) & 15], kvalues_nvfp4_f[(hi >> 20) & 15], kvalues_nvfp4_f[(hi >> 28) & 15]); + return nvfp4_scale(b->d[il]) * (dot(w0, dx * float4(qv[0])) + dot(w1, dx * float4(qv[1])) + dot(w2, dx * float4(qv[2])) + dot(w3, dx * float4(qv[3]))); + } +}; +struct dot_q4_K_tg { + enum { kSum = 1 }; + static inline float run(device const block_q4_K* b, short il, float dx, thread const short4* qv, + thread const short4*, short xsum, threadgroup const lut_none::Storage&) { + const uchar2 sc = get_scale_min_k4_just2((il / 4) * 2, (il & 3) / 2, b->scales); + device const uint* q = reinterpret_cast(b->qs + (il / 4) * 32 + 16 * (il & 1)); + const uint sh = (il & 2) ? 4 : 0; + const short4 p = short4(as_type((q[0] >> sh) & 0x0F0F0F0Fu)) * qv[0] + + short4(as_type((q[1] >> sh) & 0x0F0F0F0Fu)) * qv[1] + + short4(as_type((q[2] >> sh) & 0x0F0F0F0Fu)) * qv[2] + + short4(as_type((q[3] >> sh) & 0x0F0F0F0Fu)) * qv[3]; + const short s = (p.x + p.y) + (p.z + p.w); + return dx * fma(float(b->d) * float(sc[0]), float(s), -float(b->dmin) * float(sc[1]) * float(xsum)); + } +}; +struct dot_iq2_s_tg { + enum { kSum = 0 }; + static inline float run(device const block_iq2_s* b, short il, float dx, thread const short4* qv, + thread const short4* nqv, short, threadgroup const lut_iq2_s::Storage& lut) { + const int ib32 = il >> 1, h = il & 1; + device const uint8_t* qs = b->qs + 4 * ib32 + 2 * h; + device const uint8_t* signs = qs + QK_K / 8; + const uint qh = uint(b->qh[ib32]) >> (4 * h); + const float dl = float(b->d) * (0.5f + float((b->scales[ib32] >> (4 * h)) & 0xf)) * 0.25f; + const uint2 g1 = lut.grid[uint(qs[0]) | ((qh << 8u) & 0x300u)]; + const uint2 g2 = lut.grid[uint(qs[1]) | ((qh << 6u) & 0x300u)]; + return (dl * dx) * float(signed_grid16_i16(g1, g2, signs[0], signs[1], qv, nqv)); + } +}; +struct dot_iq2_xs_tg { + enum { kSum = 0 }; + static inline float run(device const block_iq2_xs* b, short il, float dx, thread const short4* qv, + thread const short4* nqv, short, threadgroup const lut_iq2_xs::Storage& lut) { + const int ib32 = il >> 1, h = il & 1; + device const uint16_t* q2 = b->qs + 4 * ib32 + 2 * h; + const uint v0 = q2[0], v1 = q2[1]; + const uint idx0 = v0 & 511u, idx1 = v1 & 511u; + const float dl = float(b->d) * (0.5f + float((b->scales[ib32] >> (4 * h)) & 0xf)) * 0.25f; + return (dl * dx) * float(signed_grid16_s4_i16(lut.grid_lo[idx0], lut.grid_hi[idx0], lut.grid_lo[idx1], lut.grid_hi[idx1], + lut.signs[v0 >> 9u], lut.signs[v1 >> 9u], qv, nqv)); + } +}; +struct dot_iq3_xxs_tg { + enum { kSum = 0 }; + static inline float run(device const block_iq3_xxs* b, short il, float dx, thread const short4* qv, + thread const short4* nqv, short, threadgroup const lut_iq3_xxs::Storage& lut) { + const int ib32 = il >> 1, h = il & 1; + device const uint8_t* q3 = b->qs + 8 * ib32 + 4 * h; + device const uint16_t* gas = reinterpret_cast(b->qs + QK_K / 4) + 2 * ib32; + const uint aux32 = uint(gas[0]) | (uint(gas[1]) << 16u); + const float dl = float(b->d) * (0.5f + float(aux32 >> 28u)) * 0.5f; + const uint s1 = lut.signs[(aux32 >> (14 * h)) & 127u]; + const uint s2 = lut.signs[(aux32 >> (14 * h + 7)) & 127u]; + return (dl * dx) * float(signed_grid16_s4_i16(lut.grid[q3[0]], lut.grid[q3[1]], lut.grid[q3[2]], lut.grid[q3[3]], s1, s2, qv, nqv)); + } +}; +struct gu_split_nvfp4 { + static void decode(device const block_nvfp4* b, short il, thread float4* w, thread float& k, thread float& m, + threadgroup const lut_none::Storage&) { + grp_split_nvfp4::decode(b, il, w, k, m); + } + static float apply(thread const float4* w, float k, float m, float dx, device const char4* q) { + return grp_split_nvfp4::apply(w, k, m, dx, q); + } +}; +struct gu_split_q4_K { + static void decode(device const block_q4_K* b, short il, thread float4* w, thread float& k, thread float& m, + threadgroup const lut_none::Storage&) { + grp_split_q4_K::decode(b, il, w, k, m); + } + static float apply(thread const float4* w, float k, float m, float dx, device const char4* q) { + return grp_split_q4_K::apply(w, k, m, dx, q); + } +}; +struct gu_split_iq2_s { + static void decode(device const block_iq2_s* b, short il, thread float4* w, thread float& k, thread float& m, + threadgroup const lut_iq2_s::Storage& lut) { + const int ib32 = il >> 1, h = il & 1; + device const uint8_t* qs = b->qs + 4 * ib32 + 2 * h; + device const uint8_t* signs = qs + QK_K / 8; + const uint qh = uint(b->qh[ib32]) >> (4 * h); + k = float(b->d) * (0.5f + float((b->scales[ib32] >> (4 * h)) & 0xf)) * 0.25f; + m = 0.0f; + const uint2 g1 = lut.grid[uint(qs[0]) | ((qh << 8u) & 0x300u)]; + const uint2 g2 = lut.grid[uint(qs[1]) | ((qh << 6u) & 0x300u)]; + decode_signed_grid8(g1, signs[0], w[0], w[1]); + decode_signed_grid8(g2, signs[1], w[2], w[3]); + } + static float apply(thread const float4* w, float k, float m, float dx, device const char4* q) { + return grp_split_iq2_s::apply(w, k, m, dx, q); + } +}; +struct gu_split_iq2_xs { + static void decode(device const block_iq2_xs* b, short il, thread float4* w, thread float& k, thread float& m, + threadgroup const lut_iq2_xs::Storage& lut) { + const int ib32 = il >> 1, h = il & 1; + device const uint16_t* q2 = b->qs + 4 * ib32 + 2 * h; + const uint v0 = q2[0], v1 = q2[1]; + const uint idx0 = v0 & 511u, idx1 = v1 & 511u; + const uint s1 = lut.signs[v0 >> 9u], s2 = lut.signs[v1 >> 9u]; + k = float(b->d) * (0.5f + float((b->scales[ib32] >> (4 * h)) & 0xf)) * 0.25f; + m = 0.0f; + const float4 g0 = float4(lut.grid_lo[idx0]), g1 = float4(lut.grid_hi[idx0]); + const float4 g2 = float4(lut.grid_lo[idx1]), g3 = float4(lut.grid_hi[idx1]); + w[0] = select(g0, -g0, (ushort4(s1) & ushort4(1u, 2u, 4u, 8u)) != 0u); + w[1] = select(g1, -g1, (ushort4(s1) & ushort4(16u, 32u, 64u, 128u)) != 0u); + w[2] = select(g2, -g2, (ushort4(s2) & ushort4(1u, 2u, 4u, 8u)) != 0u); + w[3] = select(g3, -g3, (ushort4(s2) & ushort4(16u, 32u, 64u, 128u)) != 0u); + } + static float apply(thread const float4* w, float k, float m, float dx, device const char4* q) { + return grp_split_iq2_xs::apply(w, k, m, dx, q); + } +}; +struct gu_split_iq3_xxs { + static void decode(device const block_iq3_xxs* b, short il, thread float4* w, thread float& k, thread float& m, + threadgroup const lut_iq3_xxs::Storage& lut) { + const int ib32 = il >> 1, h = il & 1; + device const uint8_t* q3 = b->qs + 8 * ib32 + 4 * h; + device const uint16_t* gas = reinterpret_cast(b->qs + QK_K / 4) + 2 * ib32; + const uint aux32 = uint(gas[0]) | (uint(gas[1]) << 16u); + k = float(b->d) * (0.5f + float(aux32 >> 28u)) * 0.5f; + m = 0.0f; + const uint s1 = lut.signs[(aux32 >> (14 * h)) & 127u], s2 = lut.signs[(aux32 >> (14 * h + 7)) & 127u]; + const float4 g0 = float4(lut.grid[q3[0]]), g1 = float4(lut.grid[q3[1]]); + const float4 g2 = float4(lut.grid[q3[2]]), g3 = float4(lut.grid[q3[3]]); + w[0] = select(g0, -g0, (ushort4(s1) & ushort4(1u, 2u, 4u, 8u)) != 0u); + w[1] = select(g1, -g1, (ushort4(s1) & ushort4(16u, 32u, 64u, 128u)) != 0u); + w[2] = select(g2, -g2, (ushort4(s2) & ushort4(1u, 2u, 4u, 8u)) != 0u); + w[3] = select(g3, -g3, (ushort4(s2) & ushort4(16u, 32u, 64u, 128u)) != 0u); + } + static float apply(thread const float4* w, float k, float m, float dx, device const char4* q) { + return grp_split_iq3_xxs::apply(w, k, m, dx, q); + } +}; + +// Fused MoE routed-expert gate_up + SwiGLU + Q8_1 quantization (on-chip SRAM super-operator). +// Eliminates the FP32 g_ round-trip and separate swiglu_rows_quantize_q8_1 launch. +// Grid: {n_ff / 32, count, 1}, Threads: 256 (8 SIMD groups x 4 gate+up pairs -> 32 outputs = 1 Q8_1 block). +// Supports ids[row] < 0 by writing an exact zero Q8_1 block without dereferencing `table`. +struct GuSwigluArgs { + device void* p[5]; // table, x, q8_out, ids, group_buf + ulong xstride, offset_g, offset_u; + int ni, n_ff, count, every; +}; +static inline void write_q8_1_block(device uchar* dst, uint lane, float v) { + const float amax = simd_max(abs(v)); + float sum = v; + for (uint k = 16u; k > 0u; k >>= 1u) sum += simd_shuffle_xor(sum, k); + const float d0 = amax / 127.0f; + const float d = d0 > 65504.0f ? 65504.0f : d0; + char q = 0; + if (amax != 0.0f && d != 0.0f) { + q = char(clamp(round(v / d), -127.0f, 127.0f)); + } + reinterpret_cast(dst + 4)[lane] = q; + if (lane == 0u) { + reinterpret_cast(dst)[0] = half(d); + const float sf = abs(sum) > 65504.0f ? copysign(65504.0f, sum) : sum; + reinterpret_cast(dst)[1] = half(sf); + } +} +static inline void write_zero_q8_1_block(device uchar* dst, uint lane) { + reinterpret_cast(dst + 4)[lane] = 0; + if (lane == 0u) { + reinterpret_cast(dst)[0] = half(0.0f); + reinterpret_cast(dst)[1] = half(0.0f); + } +} +template +kernel void poly_mul_k1_gu_swiglu_q8(constant GuSwigluArgs& a [[buffer(0)]], + uint2 group [[threadgroup_position_in_grid]], + uint tid [[thread_index_in_threadgroup]]) { + const uint row = group.y; + const int id = static_cast(a.p[3])[row]; + device uchar* dst = static_cast(a.p[2]) + (ulong(row) * ulong(a.n_ff >> 5) + ulong(group.x)) * 36ul; + if (id < 0) { + if (tid < 32u) write_zero_q8_1_block(dst, tid); + return; + } + threadgroup typename Lut::Storage lut; + if (Lut::kHasLut) { + Lut::load(lut, tid, 256u); + threadgroup_barrier(mem_flags::mem_threadgroup); + } + device const uchar* base_w = static_cast(a.p[0])[id]; + device const uchar* wg = base_w + a.offset_g; + device const uchar* wu = base_w + a.offset_u; + device const uchar* x = static_cast(a.p[1]) + ulong(row / uint(a.every)) * a.xstride; + const uint warp = tid >> 5u; + const uint lane = tid & 31u; + const int o0 = int(group.x) * 32 + int(warp) * 4; + const ulong per = ulong(a.ni / QK); + device const Block* weights_g = reinterpret_cast(wg) + ulong(o0) * per; + device const Block* weights_u = reinterpret_cast(wu) + ulong(o0) * per; + float ag[4] = {0.f, 0.f, 0.f, 0.f}; + float au[4] = {0.f, 0.f, 0.f, 0.f}; + for (int start = int(lane) * 16; start < a.ni; start += 32 * 16) { + device const uchar* block = x + ulong(start >> 5) * 36ul; + const float dx = float(*reinterpret_cast(block)); + device const char4* q = reinterpret_cast(block + 4 + (start & 16)); + short4 qv[4], nqv[4]; + qv[0] = short4(q[0]); qv[1] = short4(q[1]); qv[2] = short4(q[2]); qv[3] = short4(q[3]); + if (Lut::kHasLut) { nqv[0] = -qv[0]; nqv[1] = -qv[1]; nqv[2] = -qv[2]; nqv[3] = -qv[3]; } + short xsum = 0; + if (DotTg::kSum) { + const short4 s = (qv[0] + qv[1]) + (qv[2] + qv[3]); + xsum = (s.x + s.y) + (s.z + s.w); + } + const short il = short((start % QK) >> 4); + const int sb = start / QK; + for (int r = 0; r < 4; ++r) { + ag[r] += DotTg::run(weights_g + ulong(r) * per + sb, il, dx, qv, nqv, xsum, lut); + au[r] += DotTg::run(weights_u + ulong(r) * per + sb, il, dx, qv, nqv, xsum, lut); + } + } + threadgroup float sh[32]; + for (int r = 0; r < 4; ++r) { + const float gv = simd_sum(ag[r]); + const float uv = simd_sum(au[r]); + if (lane == 0u) sh[warp * 4u + uint(r)] = (gv / (1.0f + exp(-gv))) * uv; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (tid < 32u) { + write_q8_1_block(dst, tid, sh[tid]); + } +} +template +kernel void poly_mul_k1g_gu_swiglu_q8(constant GuSwigluArgs& a [[buffer(0)]], + uint2 group [[threadgroup_position_in_grid]], + uint tid [[thread_index_in_threadgroup]]) { + device const MmvqIdsGroup* grp = static_cast(a.p[4]); + const int g = int(group.y); + if (g >= grp->n_groups) return; + const int eid = grp->expert_id[g]; + const int s0 = grp->start[g], s1 = grp->start[g + 1]; + const uint warp = tid >> 5u; + const uint lane = tid & 31u; + const ulong q8_row_blocks = ulong(a.n_ff >> 5); + device uchar* q8_base = static_cast(a.p[2]); + + if (eid < 0) { + if (tid < 32u) { + for (int c = s0; c < s1; ++c) { + const uint row = uint(grp->member[c]); + device uchar* dst = q8_base + (ulong(row) * q8_row_blocks + ulong(group.x)) * 36ul; + write_zero_q8_1_block(dst, tid); + } + } + return; + } + threadgroup typename Lut::Storage lut; + if (Lut::kHasLut) { + Lut::load(lut, tid, 256u); + threadgroup_barrier(mem_flags::mem_threadgroup); + } + + device const uchar* base_w = static_cast(a.p[0])[eid]; + device const uchar* wg = base_w + a.offset_g; + device const uchar* wu = base_w + a.offset_u; + device const uchar* xbase = static_cast(a.p[1]); + const int o0 = int(group.x) * 32 + int(warp) * 4; + const ulong per = ulong(a.ni / QK); + device const Block* weights_g = reinterpret_cast(wg) + ulong(o0) * per; + device const Block* weights_u = reinterpret_cast(wu) + ulong(o0) * per; + threadgroup float sh[8][32]; + + if (s1 - s0 == 1) { + const uint row = uint(grp->member[s0]); + device const uchar* x = xbase + ulong(row / uint(a.every)) * a.xstride; + float ag[4] = {0.f, 0.f, 0.f, 0.f}; + float au[4] = {0.f, 0.f, 0.f, 0.f}; + for (int start = int(lane) * 16; start < a.ni; start += 32 * 16) { + device const uchar* block = x + ulong(start >> 5) * 36ul; + const float dx = float(*reinterpret_cast(block)); + device const char4* q = reinterpret_cast(block + 4 + (start & 16)); + short4 qv[4], nqv[4]; + qv[0] = short4(q[0]); qv[1] = short4(q[1]); qv[2] = short4(q[2]); qv[3] = short4(q[3]); + if (Lut::kHasLut) { nqv[0] = -qv[0]; nqv[1] = -qv[1]; nqv[2] = -qv[2]; nqv[3] = -qv[3]; } + short xsum = 0; + if (DotTg::kSum) { + const short4 s = (qv[0] + qv[1]) + (qv[2] + qv[3]); + xsum = (s.x + s.y) + (s.z + s.w); + } + const short il = short((start % QK) >> 4); + const int sb = start / QK; + for (int r = 0; r < 4; ++r) { + ag[r] += DotTg::run(weights_g + ulong(r) * per + sb, il, dx, qv, nqv, xsum, lut); + au[r] += DotTg::run(weights_u + ulong(r) * per + sb, il, dx, qv, nqv, xsum, lut); + } + } + for (int r = 0; r < 4; ++r) { + const float gv = simd_sum(ag[r]); + const float uv = simd_sum(au[r]); + if (lane == 0u) sh[0][warp * 4u + uint(r)] = (gv / (1.0f + exp(-gv))) * uv; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (tid < 32u) { + device uchar* dst = q8_base + (ulong(row) * q8_row_blocks + ulong(group.x)) * 36ul; + write_q8_1_block(dst, tid, sh[0][tid]); + } + return; + } + + for (int c0 = s0; c0 < s1; c0 += 8) { + const int m = min(8, s1 - c0); + int slots[8]; + ulong xoffs[8]; + for (int c = 0; c < 8; ++c) { + if (c >= m) break; + slots[c] = grp->member[c0 + c]; + xoffs[c] = ulong(uint(slots[c]) / uint(a.every)) * a.xstride; + } + for (int r = 0; r < 4; ++r) { + float ag[8] = {0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f}; + float au[8] = {0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f}; + device const Block* wr_g = weights_g + ulong(r) * per; + device const Block* wr_u = weights_u + ulong(r) * per; + for (int start = int(lane) * 16; start < a.ni; start += 32 * 16) { + const short il = short((start % QK) >> 4); + const int sb = start / QK; + float4 wg4[4], wu4[4]; + float kg = 0.f, mg = 0.f, ku = 0.f, mu = 0.f; + Split::decode(wr_g + sb, il, wg4, kg, mg, lut); + Split::decode(wr_u + sb, il, wu4, ku, mu, lut); + for (int c = 0; c < 8; ++c) { + if (c >= m) break; + device const uchar* block = xbase + xoffs[c] + ulong(start >> 5) * 36ul; + const float dx = float(*reinterpret_cast(block)); + device const char4* q = reinterpret_cast(block + 4 + (start & 16)); + ag[c] += Split::apply(wg4, kg, mg, dx, q); + au[c] += Split::apply(wu4, ku, mu, dx, q); + } + } + for (int c = 0; c < 8; ++c) { + if (c >= m) break; + const float gv = simd_sum(ag[c]); + const float uv = simd_sum(au[c]); + if (lane == 0u) sh[c][warp * 4u + uint(r)] = (gv / (1.0f + exp(-gv))) * uv; + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (int(warp) < m) { + device uchar* dst = q8_base + (ulong(slots[warp]) * q8_row_blocks + ulong(group.x)) * 36ul; + write_q8_1_block(dst, lane, sh[warp][lane]); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + } +} +#define MULK1_GUSWIGLU(name,QK,LUT) \ + template [[host_name("poly_mul_" #name "_k1_gu_swiglu_q8")]] kernel decltype(poly_mul_k1_gu_swiglu_q8) poly_mul_k1_gu_swiglu_q8; \ + template [[host_name("poly_mul_" #name "_k1g_gu_swiglu_q8")]] kernel decltype(poly_mul_k1g_gu_swiglu_q8) poly_mul_k1g_gu_swiglu_q8; +MULK1_GUSWIGLU(nvfp4,64,lut_none) MULK1_GUSWIGLU(q4_K,256,lut_none) +MULK1_GUSWIGLU(iq2_s,256,lut_iq2_s) MULK1_GUSWIGLU(iq2_xs,256,lut_iq2_xs) MULK1_GUSWIGLU(iq3_xxs,256,lut_iq3_xxs) MULR2_(q6_K,256,split_q6_K,4,8,"") MULR2(nvfp4,64,split_nvfp4) #define MUL_(name,QK,DOT,NR,SUFFIX) template [[host_name("poly_mul_" #name SUFFIX)]] kernel decltype(poly_mul,DOT,NR>) poly_mul,DOT,NR>; \ diff --git a/engine/metal/src/poly/qwen4.cpp b/engine/metal/src/poly/qwen4.cpp index d68445161..5229702af 100644 --- a/engine/metal/src/poly/qwen4.cpp +++ b/engine/metal/src/poly/qwen4.cpp @@ -75,6 +75,13 @@ void q4_gr_norm_quant(const float* r, const float* w_norm, float* xn, void* xq, (xq ? uint64_t(sizes[3]) : 0ULL); gpu::metal::prof_push_hint({gpu::metal::ProfCat::NormElem, b, 4ULL * hc_rows * uint64_t(n_embd)}); } + const bool aligned16 = ((uintptr_t(r) | uintptr_t(w_norm) | uintptr_t(xn)) & 15u) == 0u; + const bool aligned_q = !xq || ((uintptr_t(xq) & 3u) == 0u); + if (n_embd > 0 && (n_embd & 3) == 0 && aligned16 && aligned_q) { + run(xq ? "q4_gr_norm_vec4_0_1" : "q4_gr_norm_vec4_0_0", a, stream, {uint32_t(rows * hc), 1, 1}, 256, + {refs, xq ? 4u : 3u, true, nullptr, modes, sizes}); + return; + } run(xq ? "q4_gr_norm_0_1" : "q4_gr_norm_0_0", a, stream, {uint32_t(rows * hc), 1, 1}, 256, {refs, xq ? 4u : 3u, true, nullptr, modes, sizes}); } @@ -132,6 +139,13 @@ void q4_gr_write_norm_quant(float* r, const float* block_out, const float* prev_ 12ULL * hc_rows * uint64_t(n_embd) + sizes[1] + sizes[3] + sizes[5], 6ULL * hc_rows * uint64_t(n_embd)}); } + const bool aligned16 = ((uintptr_t(r) | uintptr_t(block_out) | uintptr_t(w_norm) | uintptr_t(xn)) & 15u) == 0u; + const bool aligned_q = !xq || ((uintptr_t(xq) & 3u) == 0u); + if (n_embd > 0 && (n_embd & 3) == 0 && aligned16 && aligned_q) { + run(xq ? "q4_gr_norm_vec4_1_1" : "q4_gr_norm_vec4_1_0", a, stream, {uint32_t(rows * hc), 1, 1}, 256, + {a.p, xq ? 6u : 5u, true, nullptr, modes, sizes}); + return; + } run(xq ? "q4_gr_norm_1_1" : "q4_gr_norm_1_0", a, stream, {uint32_t(rows * hc), 1, 1}, 256, {a.p, xq ? 6u : 5u, true, nullptr, modes, sizes}); } @@ -178,7 +192,7 @@ void q4_gr_silu_quant(float* lo, void* lo_xq, int hc_lr, int hc, int rows, void* void q4_gr_gate_mean_quant(const float* xn, const float* gate, float* mixed, void* mixed_xq, int n_embd, int hc, int rows, void* stream) { - if (rows <= 0) return; + if (rows <= 0 || n_embd <= 0) return; if (mixed_xq && (n_embd % 32 != 0)) throw std::invalid_argument("q4_gr_gate_mean_quant: quantized path requires n_embd % 32 == 0"); Q4Args a; @@ -195,6 +209,22 @@ void q4_gr_gate_mean_quant(const float* xn, const float* gate, float* mixed, voi 4ULL * size_t(rows) * size_t(hc) * size_t(n_embd), 4ULL * size_t(rows) * size_t(n_embd), mixed_xq ? q8_bytes(n_embd, rows) : 0ULL}; + if (__builtin_expect(gpu::metal::prof_level() > 0, 0)) { + const uint64_t b = sizes[0] + sizes[1] + sizes[2] + sizes[3]; + const uint64_t fl = (3ULL * uint64_t(hc) + 1ULL) * uint64_t(rows) * uint64_t(n_embd); + gpu::metal::prof_push_hint({gpu::metal::ProfCat::NormElem, b, fl}); + } + const bool aligned16 = ((uintptr_t(xn) | uintptr_t(gate) | uintptr_t(mixed)) & 15u) == 0u; + const bool aligned_q = !mixed_xq || ((uintptr_t(mixed_xq) & 3u) == 0u); + if ((n_embd & 3) == 0 && aligned16 && aligned_q) { + const uint32_t n_embd4 = uint32_t(n_embd >> 2); + const uint32_t threads = (n_embd4 <= 64u) ? 64u : ((n_embd4 <= 128u) ? 128u : 256u); + const char* name = mixed_xq ? (hc == 4 ? "q4_gr_gate_mean_vec4_1_4" : "q4_gr_gate_mean_vec4_1_0") + : (hc == 4 ? "q4_gr_gate_mean_vec4_0_4" : "q4_gr_gate_mean_vec4_0_0"); + run(name, a, stream, {grid_div(size_t(n_embd4), threads), uint32_t(rows), 1}, threads, + {a.p, mixed_xq ? 4u : 3u, true, nullptr, modes, sizes}); + return; + } const char* name = mixed_xq ? (hc == 4 ? "q4_gr_gate_mean_1_4" : "q4_gr_gate_mean_1_0") : (hc == 4 ? "q4_gr_gate_mean_0_4" : "q4_gr_gate_mean_0_0"); run(name, a, stream, {uint32_t(rows), 1, 1}, 256, {a.p, mixed_xq ? 4u : 3u, true, nullptr, modes, sizes}); @@ -367,6 +397,7 @@ void q4_qsa_score(const float* idx_q, const float* idx_pool, float* score, int s a.n[2] = idx_heads; a.n[3] = idx_dim; a.n[4] = idx_block; + a.n[5] = rows; const gpu::metal::Access modes[4] = {gpu::metal::Access::R, gpu::metal::Access::R, gpu::metal::Access::W, gpu::metal::Access::R}; @@ -379,6 +410,14 @@ void q4_qsa_score(const float* idx_q, const float* idx_pool, float* score, int s const uint64_t fl = 2ULL * uint64_t(rows) * uint64_t(max_blocks) * uint64_t(idx_heads) * uint64_t(idx_dim); gpu::metal::prof_push_hint({gpu::metal::ProfCat::Attention, b, fl}); } + const bool aligned16 = ((uintptr_t(idx_q) | uintptr_t(idx_pool)) & 15u) == 0u; + if (gpu::metal::optimize() && at == nullptr && rows >= 4 && idx_dim == 128 && + idx_heads >= 1 && idx_heads <= 16 && idx_block > 0 && aligned16) { + run("q4_qsa_score_batch_mma", a, stream, + {grid_div(size_t(max_blocks), 32), grid_div(size_t(rows), 16), 1}, 128, + {a.p, 3, true, nullptr, modes, sizes}); + return; + } run("q4_qsa_score_kernel", a, stream, {grid_div(size_t(max_blocks), 8), uint32_t(rows), 1}, 256, {a.p, 4, true, nullptr, modes, sizes}); } @@ -522,7 +561,7 @@ void q4_mtp_eh_concat(const float* e, const float* h, const float* w_enorm, cons } void q4_split_2d(const float* in, float* out_a, float* out_b, int na, int nb, int rows, void* stream) { - if (rows <= 0) return; + if (rows <= 0 || na + nb <= 0) return; Q4Args a; a.p[0] = in; a.p[1] = out_a; @@ -531,10 +570,23 @@ void q4_split_2d(const float* in, float* out_a, float* out_b, int na, int nb, in a.n[1] = nb; a.n[2] = rows; - const size_t total = size_t(rows) * size_t(na + nb); + const size_t width = size_t(na) + size_t(nb); + const size_t total = size_t(rows) * width; const gpu::metal::Access modes[3] = {gpu::metal::Access::R, gpu::metal::Access::W, gpu::metal::Access::W}; const size_t sizes[3] = {4ULL * total, 4ULL * size_t(rows) * size_t(na), 4ULL * size_t(rows) * size_t(nb)}; - run("q4_split_2d_kernel", a, stream, {grid_div(total, 256), 1, 1}, 256, {a.p, 3, true, nullptr, modes, sizes}); + if (__builtin_expect(gpu::metal::prof_level() > 0, 0)) { + gpu::metal::prof_push_hint({gpu::metal::ProfCat::NormElem, 8ULL * uint64_t(total), 0ULL}); + } + const bool aligned16 = ((uintptr_t(in) | uintptr_t(out_a) | uintptr_t(out_b)) & 15u) == 0u; + if (na >= 0 && nb >= 0 && (na & 3) == 0 && (nb & 3) == 0 && aligned16) { + const size_t width4 = width >> 2; + const uint32_t threads = width4 < 256 ? uint32_t(((width4 + 31) / 32) * 32) : 256u; + run("q4_split_2d_vec4_kernel", a, stream, {grid_div(width4, threads), uint32_t(rows), 1}, threads, + {a.p, 3, true, nullptr, modes, sizes}); + return; + } + run("q4_split_2d_kernel", a, stream, {grid_div(width, 256), uint32_t(rows), 1}, 256, + {a.p, 3, true, nullptr, modes, sizes}); } // ---- 5. Fused GDN Decode ---- @@ -654,31 +706,34 @@ void q4_shexp_gate_mul(const float* w_gate, const float* xn, float* fo, int n_em run("q4_shexp_gate_mul_kernel", a, stream, {uint32_t(rows), 1, 1}, 256, {a.p, 3, true, nullptr, modes, sizes}); } -bool q4_gr_up_gate_mean_quant(const void* w_up, int w_type, const void* lo_q8, const float* gr_xn, - float* out, void* out_xq, int n_embd, int hc, int hc_lr, int rows, void* stream) { +bool q4_gr_up_gate_mean_quant(int w_type, const void* w_up, const void* lo_xq, const float* lo_f32, + const float* gr_xn, float* out, void* out_xq, unsigned* /*q8_cnt*/, + int n_embd, int hc, int hc_lr, int rows, void* stream) { if (rows <= 0 || rows > 8 || hc != 4 || hc_lr != 256 || n_embd <= 0 || (n_embd % 32) != 0) return false; - if (!w_up || !lo_q8 || !gr_xn || !out) return false; - const bool r8 = rows > 4; - const char* name = nullptr; + if (!w_up || (!lo_f32 && !lo_xq) || !gr_xn || !out) return false; + const bool use_f32 = (lo_f32 != nullptr); + + const char* wname = nullptr; size_t row_bytes = 0; if (w_type == 14) { - name = r8 ? (out_xq ? "q4_gr_up_q6_K_r8_1" : "q4_gr_up_q6_K_r8_0") - : (out_xq ? "q4_gr_up_q6_K_1" : "q4_gr_up_q6_K_0"); + wname = "q6_K"; row_bytes = 210ULL; } else if (w_type == 8) { - name = r8 ? (out_xq ? "q4_gr_up_q8_0_r8_1" : "q4_gr_up_q8_0_r8_0") - : (out_xq ? "q4_gr_up_q8_0_1" : "q4_gr_up_q8_0_0"); + wname = "q8_0"; row_bytes = 8ULL * 34ULL; } else if (w_type == 12) { - name = r8 ? (out_xq ? "q4_gr_up_q4_K_r8_1" : "q4_gr_up_q4_K_r8_0") - : (out_xq ? "q4_gr_up_q4_K_1" : "q4_gr_up_q4_K_0"); + wname = "q4_K"; row_bytes = 144ULL; } else { return false; } + + const char* rsuf = (rows == 1) ? "_r1_" : ((rows == 2) ? "_r2_" : ((rows <= 4) ? "_r4_" : "_r8_")); + const std::string kname = std::string("q4_gr_up_") + wname + rsuf + (out_xq ? "1" : "0"); + Q4Args a; a.p[0] = w_up; - a.p[1] = lo_q8; + a.p[1] = use_f32 ? static_cast(lo_f32) : lo_xq; a.p[2] = gr_xn; a.p[3] = out; a.p[4] = out_xq; @@ -686,12 +741,13 @@ bool q4_gr_up_gate_mean_quant(const void* w_up, int w_type, const void* lo_q8, c a.n[1] = hc; a.n[2] = hc_lr; a.n[3] = rows; + a.n[4] = use_f32 ? 1 : 0; const size_t w_b = row_bytes * size_t(hc) * size_t(n_embd); - const size_t lo_b = size_t(rows) * size_t(hc_lr / 32) * 36ULL; + const size_t lo_b = use_f32 ? (4ULL * size_t(rows) * size_t(hc_lr)) : q8_bytes(hc_lr, rows); const size_t xn_b = 4ULL * size_t(rows) * size_t(hc) * size_t(n_embd); const size_t out_b = 4ULL * size_t(rows) * size_t(n_embd); - const size_t xq_b = out_xq ? size_t(rows) * size_t(n_embd / 32) * 36ULL : 0ULL; + const size_t xq_b = out_xq ? q8_bytes(n_embd, rows) : 0ULL; if (__builtin_expect(gpu::metal::prof_level() > 0, 0)) { gpu::metal::prof_push_hint({gpu::metal::ProfCat::GemvDecode, w_b + lo_b + xn_b + out_b + xq_b, 2ULL * uint64_t(rows) * uint64_t(hc) * uint64_t(n_embd) * uint64_t(hc_lr)}); @@ -699,9 +755,112 @@ bool q4_gr_up_gate_mean_quant(const void* w_up, int w_type, const void* lo_q8, c const gpu::metal::Access modes[5] = {gpu::metal::Access::R, gpu::metal::Access::R, gpu::metal::Access::R, gpu::metal::Access::W, gpu::metal::Access::W}; const size_t sizes[5] = {w_b, lo_b, xn_b, out_b, xq_b}; - run(name, a, stream, {uint32_t(n_embd / 32), 1, 1}, 512, + run(kname.c_str(), a, stream, {uint32_t(n_embd / 32), 1, 1}, 256, {a.p, out_xq ? 5u : 4u, true, nullptr, modes, sizes}); return true; } +bool q4_gr_up_gate_mean_quant(const void* w_up, int w_type, const void* lo_q8, const float* gr_xn, + float* out, void* out_xq, int n_embd, int hc, int hc_lr, int rows, void* stream) { + return q4_gr_up_gate_mean_quant(w_type, w_up, lo_q8, nullptr, gr_xn, out, out_xq, nullptr, + n_embd, hc, hc_lr, rows, stream); +} + +bool q4_gr_down_silu_quant(int w_type, const void* w, const void* xn_xq, const float* /*xn_f32*/, + float* lo, void* lo_xq, float* inject, unsigned* /*q8_cnt*/, + int hc_dim, int hc_lr, int hc, bool has_inject, int rows, void* stream) { + if (rows < 1 || rows > 8 || hc < 1 || hc > 8 || hc_lr <= 0 || (hc_lr % 32) != 0 || hc_dim <= 0) + return false; + if (!w || !xn_xq || !lo) return false; + if (lo_xq != nullptr && lo_xq == xn_xq) return false; + + const char* wname = nullptr; + size_t row_bytes = 0; + if (w_type == 8) { + if ((hc_dim % 32) != 0) return false; + wname = "q8_0"; + row_bytes = size_t(hc_dim >> 5) * 34ULL; + } else if (w_type == 12) { + if ((hc_dim % 256) != 0) return false; + wname = "q4_K"; + row_bytes = size_t(hc_dim >> 8) * 144ULL; + } else if (w_type == 14) { + if ((hc_dim % 256) != 0) return false; + wname = "q6_K"; + row_bytes = size_t(hc_dim >> 8) * 210ULL; + } else { + return false; + } + + const int n_out = has_inject ? (hc_lr + hc) : hc_lr; + const char* rsuf = (rows == 1) ? "_r1" : ((rows == 2) ? "_r2" : ((rows <= 4) ? "_r4" : "_r8")); + const std::string kname = std::string("q4_gr_down_") + wname + rsuf; + + Q4Args a; + a.p[0] = w; + a.p[1] = xn_xq; + a.p[2] = lo; + a.p[3] = lo_xq; + a.p[4] = has_inject ? inject : nullptr; + a.n[0] = hc_dim; + a.n[1] = hc_lr; + a.n[2] = hc; + a.n[3] = rows; + a.n[4] = n_out; + + const size_t w_b = row_bytes * size_t(n_out); + const size_t xn_b = q8_bytes(hc_dim, rows); + const size_t lo_b = 4ULL * size_t(rows) * size_t(hc_lr); + const size_t inj_b = (has_inject && inject) ? 4ULL * size_t(rows) * size_t(hc) : 0ULL; + if (__builtin_expect(gpu::metal::prof_level() > 0, 0)) { + gpu::metal::prof_push_hint({gpu::metal::ProfCat::GemvDecode, w_b + xn_b + lo_b + inj_b, + 2ULL * uint64_t(rows) * uint64_t(n_out) * uint64_t(hc_dim)}); + } + const void* refs[4] = {w, xn_xq, lo, (has_inject && inject) ? inject : nullptr}; + const gpu::metal::Access modes[4] = { + gpu::metal::Access::R, gpu::metal::Access::R, gpu::metal::Access::W, gpu::metal::Access::W}; + const size_t sizes[4] = {w_b, xn_b, lo_b, inj_b}; + run(kname.c_str(), a, stream, {grid_div(size_t(n_out), 2u), 1, 1}, 128, + {refs, (has_inject && inject) ? 4u : 3u, true, nullptr, modes, sizes}); + + if (lo_xq != nullptr) { + const size_t lo_xq_b = q8_bytes(hc_lr, rows); + if (__builtin_expect(gpu::metal::prof_level() > 0, 0)) { + gpu::metal::prof_push_hint({gpu::metal::ProfCat::Quantize, lo_b + lo_xq_b, + 2ULL * uint64_t(rows) * uint64_t(hc_lr)}); + } + const void* qrefs[2] = {lo, lo_xq}; + const gpu::metal::Access qmodes[2] = {gpu::metal::Access::R, gpu::metal::Access::W}; + const size_t qsizes[2] = {lo_b, lo_xq_b}; + run("q4_gr_lo_q8_kernel", a, stream, {uint32_t(rows), 1, 1}, 256, + {qrefs, 2u, true, nullptr, qmodes, qsizes}); + } + return true; +} + +void q4_mul_sigmoid_q8_1(const float* att, const float* qg, void* q8, int head_dim, int n_head, int rows, void* stream) { + if (rows <= 0) return; + const int d_inner = n_head * head_dim; + if (d_inner <= 0 || (d_inner % 32) != 0) + throw std::invalid_argument("q4_mul_sigmoid_q8_1: requires n_head * head_dim % 32 == 0"); + Q4Args a; + a.p[0] = att; + a.p[1] = qg; + a.p[2] = q8; + a.n[0] = head_dim; + a.n[1] = n_head; + + const size_t att_b = 4ULL * size_t(rows) * size_t(d_inner); + const size_t qg_b = 8ULL * size_t(rows) * size_t(d_inner); + const size_t q8_b = q8_bytes(d_inner, rows); + if (__builtin_expect(gpu::metal::prof_level() > 0, 0)) { + gpu::metal::prof_push_hint({gpu::metal::ProfCat::Quantize, att_b * 2ULL + q8_b, + 3ULL * uint64_t(rows) * uint64_t(d_inner)}); + } + const gpu::metal::Access modes[3] = {gpu::metal::Access::R, gpu::metal::Access::R, gpu::metal::Access::W}; + const size_t sizes[3] = {att_b, qg_b, q8_b}; + run("q4_mul_sigmoid_q8_1_kernel", a, stream, {grid_div(size_t(d_inner), 256), uint32_t(rows), 1}, 256, + {a.p, 3u, true, nullptr, modes, sizes}); +} + } // namespace strata::poly diff --git a/engine/metal/src/poly/qwen4.metal b/engine/metal/src/poly/qwen4.metal index 7f5bd314a..8fce18151 100644 --- a/engine/metal/src/poly/qwen4.metal +++ b/engine/metal/src/poly/qwen4.metal @@ -21,6 +21,7 @@ constant int kQsaChunk = 64; constant float kHalfMax = 65504.0f; inline float q4_sig(float x) { return 1.0f / (1.0f + exp(-x)); } +inline float4 q4_sig4(float4 x) { return 1.0f / (1.0f + exp(-x)); } inline float q8_1_finite(float v) { return abs(v) > kHalfMax ? copysign(kHalfMax, v) : v; @@ -44,6 +45,31 @@ inline void q8_put(device uchar* row_q, int elem_idx, float xi) { } } +// 8-lane sub-warp Q8_1 quantization: 8 consecutive lanes hold 4 consecutive floats each (32 floats = 1 Q8_1 block). +inline void q8_put4(device uchar* row_q, uint blk_idx, uint lane8, float4 y) { + const float4 ay = abs(y); + float amax = max(max(ay.x, ay.y), max(ay.z, ay.w)); + amax = max(amax, simd_shuffle_xor(amax, 4u)); + amax = max(amax, simd_shuffle_xor(amax, 2u)); + amax = max(amax, simd_shuffle_xor(amax, 1u)); + float sum = (y.x + y.y) + (y.z + y.w); + sum += simd_shuffle_xor(sum, 4u); + sum += simd_shuffle_xor(sum, 2u); + sum += simd_shuffle_xor(sum, 1u); + const float d = q8_1_finite(amax / 127.0f); + char4 q = char4(0); + if (amax != 0.0f && d != 0.0f) { + const float inv_d = 1.0f / d; + const float4 rq = round(y * inv_d); + q = char4(clamp(rq, float4(-127.0f), float4(127.0f))); + } + device uchar* blk = row_q + ulong(blk_idx) * 36ul; + reinterpret_cast(blk + 4)[lane8] = q; + if (lane8 == 0u) { + reinterpret_cast(blk)[0] = half2(half(d), half(q8_1_finite(sum))); + } +} + inline float block_sum_128(float v, threadgroup float* part, uint tid) { const uint lane = tid & 31u; const uint warp = tid >> 5u; @@ -150,6 +176,101 @@ template [[host_name("q4_gr_norm_0_1")]] kernel decltype(q4_gr_norm_kernel) q4_gr_norm_kernel; template [[host_name("q4_gr_norm_1_1")]] kernel decltype(q4_gr_norm_kernel) q4_gr_norm_kernel; +template +inline float q4_gr_reduce_tg(float4 ss4, threadgroup float* part, uint tid) { + const uint lane = tid & 31u; + const uint warp = tid >> 5u; + const float ss = simd_sum((ss4.x + ss4.y) + (ss4.z + ss4.w)); + if (lane == 0u) part[warp] = ss; + threadgroup_barrier(mem_flags::mem_threadgroup); + float tot = 0.0f; +#pragma clang loop unroll(full) + for (uint w = 0u; w < NW; ++w) tot += part[w]; + return tot; +} + +// Vectorized float4 GR RMSNorm (+ optional fused residual write + optional 8-lane sub-warp Q8_1 quantization). +// Requires n_embd % 4 == 0 (and n_embd % 32 == 0 when QUANT == true), 16-byte aligned float buffers, 4-byte aligned xq. +// Grid: {rows * hc, 1, 1}, Threads: 256 (8 SIMD groups). +template +kernel void q4_gr_norm_vec4_kernel(constant Q4Args& a [[buffer(0)]], + uint b [[threadgroup_position_in_grid]], + uint tid [[thread_index_in_threadgroup]]) { + threadgroup float part[8]; + const int n_embd = a.n[0]; + const uint n4 = uint(n_embd) >> 2u; + const int hc = a.n[1]; + const float eps = a.f[0]; + const int t = int(b) / hc; + const int c = int(b) - t * hc; + const ulong row_off4 = (ulong(t) * ulong(hc) + ulong(c)) * ulong(n4); + const ulong w_off4 = ulong(c) * ulong(n4); + + device float4* r4 = static_cast(a.p[0]) + row_off4; + device const float4* wn4 = static_cast(a.p[3]) + w_off4; + device float4* xn4 = static_cast(a.p[4]) + row_off4; + + float gw = 0.0f; + device const float4* bo4 = nullptr; + if (WRITE_PREV) { + device const float* prev_inject = static_cast(a.p[2]); + gw = 2.0f * q4_sig(prev_inject[ulong(t) * ulong(hc) + ulong(c)] / float(hc)); + bo4 = static_cast(a.p[1]) + ulong(t) * ulong(n4); + } + + device uchar* q_base = nullptr; + if (QUANT) { + q_base = static_cast(a.p[5]) + + (ulong(t) * ulong(hc) + ulong(c)) * ulong(n_embd >> 5) * 36ul; + } + + const uint lane8 = tid & 7u; + float4 ss4 = float4(0.0f); + if (n4 <= 1024u) { + float4 cached[4]; + uint k = 0u; + for (uint i4 = tid; i4 < n4; i4 += 256u, ++k) { + float4 v = r4[i4]; + if (WRITE_PREV) { + v = fma(bo4[i4], gw, v); + r4[i4] = v; + } + cached[k] = v; + ss4 = fma(v, v, ss4); + } + const float total_ss = q4_gr_reduce_tg<8u>(ss4, part, tid); + const float inv = rsqrt(total_ss / float(n_embd) + eps); + k = 0u; + for (uint i4 = tid; i4 < n4; i4 += 256u, ++k) { + const float4 xi = (cached[k] * inv) * wn4[i4]; + xn4[i4] = xi; + if (QUANT) q8_put4(q_base, i4 >> 3u, lane8, xi); + } + return; + } + + for (uint i4 = tid; i4 < n4; i4 += 256u) { + float4 v = r4[i4]; + if (WRITE_PREV) { + v = fma(bo4[i4], gw, v); + r4[i4] = v; + } + ss4 = fma(v, v, ss4); + } + const float total_ss = q4_gr_reduce_tg<8u>(ss4, part, tid); + const float inv = rsqrt(total_ss / float(n_embd) + eps); + for (uint i4 = tid; i4 < n4; i4 += 256u) { + const float4 xi = (r4[i4] * inv) * wn4[i4]; + xn4[i4] = xi; + if (QUANT) q8_put4(q_base, i4 >> 3u, lane8, xi); + } +} + +template [[host_name("q4_gr_norm_vec4_0_0")]] kernel decltype(q4_gr_norm_vec4_kernel) q4_gr_norm_vec4_kernel; +template [[host_name("q4_gr_norm_vec4_0_1")]] kernel decltype(q4_gr_norm_vec4_kernel) q4_gr_norm_vec4_kernel; +template [[host_name("q4_gr_norm_vec4_1_0")]] kernel decltype(q4_gr_norm_vec4_kernel) q4_gr_norm_vec4_kernel; +template [[host_name("q4_gr_norm_vec4_1_1")]] kernel decltype(q4_gr_norm_vec4_kernel) q4_gr_norm_vec4_kernel; + kernel void q4_gr_write_kernel(constant Q4Args& a [[buffer(0)]], uint b [[threadgroup_position_in_grid]], uint tid [[thread_index_in_threadgroup]]) { @@ -234,6 +355,60 @@ template [[host_name("q4_gr_gate_mean_1_4")]] kernel decltype(q4_gr_gate_mean_ke template [[host_name("q4_gr_gate_mean_0_0")]] kernel decltype(q4_gr_gate_mean_kernel) q4_gr_gate_mean_kernel; template [[host_name("q4_gr_gate_mean_1_0")]] kernel decltype(q4_gr_gate_mean_kernel) q4_gr_gate_mean_kernel; +// Vectorized float4 GR gate-mean + optional 8-lane sub-warp Q8_1 quantization (requires n_embd % 4 == 0, +// and n_embd % 32 == 0 when QUANT == true, with 16-byte aligned float buffers). +// Grid: {ceil((n_embd / 4) / threads), rows, 1}, Threads: 64 / 128 / 256 (multiple of 32). +template +kernel void q4_gr_gate_mean_vec4_kernel(constant Q4Args& a [[buffer(0)]], + uint2 gid [[thread_position_in_grid]], + uint lane [[thread_index_in_simdgroup]]) { + const uint n_embd4 = uint(a.n[0]) >> 2u; + const uint c4 = gid.x; + if (c4 >= n_embd4) return; + const ulong t = ulong(gid.y); + const int H = HC_FIXED > 0 ? HC_FIXED : a.n[1]; + const float inv_hc = 1.0f / float(H); + const ulong s_stride = ulong(n_embd4); + const ulong base = t * ulong(H) * s_stride + ulong(c4); + + device const float4* xn4 = static_cast(a.p[0]); + device const float4* gate4 = static_cast(a.p[1]); + device float4* out4 = static_cast(a.p[2]) + t * s_stride; + + float4 acc; + if (HC_FIXED == 4) { + const float4 g0 = gate4[base + 0ul * s_stride]; + const float4 x0 = xn4[base + 0ul * s_stride]; + const float4 g1 = gate4[base + 1ul * s_stride]; + const float4 x1 = xn4[base + 1ul * s_stride]; + acc = fma(x0, q4_sig4(g0), float4(0.0f)); + const float4 g2 = gate4[base + 2ul * s_stride]; + const float4 x2 = xn4[base + 2ul * s_stride]; + acc = fma(x1, q4_sig4(g1), acc); + const float4 g3 = gate4[base + 3ul * s_stride]; + const float4 x3 = xn4[base + 3ul * s_stride]; + acc = fma(x2, q4_sig4(g2), acc); + acc = fma(x3, q4_sig4(g3), acc); + } else { + acc = float4(0.0f); + for (int c = 0; c < H; ++c) { + const ulong idx = base + ulong(c) * s_stride; + acc = fma(xn4[idx], q4_sig4(gate4[idx]), acc); + } + } + const float4 y = acc * inv_hc; + out4[c4] = y; + if (QUANT) { + device uchar* q_out = static_cast(a.p[3]) + t * ulong(uint(a.n[0]) >> 5u) * 36ul; + q8_put4(q_out, c4 >> 3u, lane & 7u, y); + } +} + +template [[host_name("q4_gr_gate_mean_vec4_0_4")]] kernel decltype(q4_gr_gate_mean_vec4_kernel) q4_gr_gate_mean_vec4_kernel; +template [[host_name("q4_gr_gate_mean_vec4_1_4")]] kernel decltype(q4_gr_gate_mean_vec4_kernel) q4_gr_gate_mean_vec4_kernel; +template [[host_name("q4_gr_gate_mean_vec4_0_0")]] kernel decltype(q4_gr_gate_mean_vec4_kernel) q4_gr_gate_mean_vec4_kernel; +template [[host_name("q4_gr_gate_mean_vec4_1_0")]] kernel decltype(q4_gr_gate_mean_vec4_kernel) q4_gr_gate_mean_vec4_kernel; + // ---- 2. PLE N-gram Engram Kernels ---- kernel void q4_ple_gate_norm_kernel(constant Q4Args& a [[buffer(0)]], @@ -542,6 +717,137 @@ kernel void q4_qsa_score_kernel(constant Q4Args& a [[buffer(0)]], if (lane == 0u) score[ulong(t) * ulong(score_stride) + ulong(b)] = total * inv_sqrt_d; } +// High-throughput simdgroup_matrix batch QSA indexer scoring for idx_dim == 128. +// 128 threads = 4 simdgroups (2x2 layout of 8x16 sub-tiles -> 16x32 tile per TG). +// Grid: {ceil(max_blocks / 32), ceil(rows / 16), 1}, Threads: 128. +// Total TG memory = 8,704 (sK) + 4,352 (sQ) + 2,048 (sDot) = 15,104 B (<= 16 KB -> 2 TGs/core on Apple9). +kernel void q4_qsa_score_batch_mma(constant Q4Args& a [[buffer(0)]], + uint2 group [[threadgroup_position_in_grid]], + uint tid [[thread_index_in_threadgroup]]) { + constexpr int kStride = 136; // 128 + 8 half -> 16-byte aligned rows, avoids TG bank conflicts + threadgroup uint4 sK_raw[(32 * kStride) / 8]; // 8,704 B -> sK[32][136] + threadgroup uint4 sQ_raw[(16 * kStride) / 8]; // 4,352 B -> sQ[16][136] + threadgroup float4 sDot_raw[(16 * 32) / 4]; // 2,048 B -> sDot[16][32] + + const int score_stride = a.n[0]; + const int max_blocks = a.n[1]; + const int idx_heads = a.n[2]; + const int idx_block = a.n[4]; + const int rows = a.n[5]; + + const int b0 = int(group.x * 32u); + const int t0 = int(group.y * 16u); + if (b0 >= max_blocks || t0 >= rows) return; + + const uint warp = tid >> 5u; + const uint lane = tid & 31u; + const uint sg_t = warp >> 1u; // 0..1 -> 8 token rows per simdgroup + const uint sg_b = warp & 1u; // 0..1 -> 16 block cols per simdgroup + const uint ti = sg_t * 8u + (lane >> 2u); + const uint bi = sg_b * 16u + (lane & 3u) * 4u; + + device float* score = static_cast(a.p[2]); + const int t_last = min(t0 + 16, rows) - 1; + const long nv_max = (a.pos + long(t_last) + 1l) / long(idx_block); + + // Causal early-out: entire tile lies beyond the last valid block for all rows in this tile. + if (long(b0) >= nv_max) { + const int t = t0 + int(ti); + if (t < rows) { + const ulong row_off = ulong(t) * ulong(score_stride); +#pragma clang loop unroll(full) + for (int k = 0; k < 4; ++k) { + const int b = b0 + int(bi) + k; + if (b < max_blocks) score[row_off + ulong(b)] = -INFINITY; + } + } + return; + } + + threadgroup half* sK = reinterpret_cast(sK_raw); + threadgroup half* sQ = reinterpret_cast(sQ_raw); + threadgroup float* sDot = reinterpret_cast(sDot_raw); + + device const float* q_ptr = static_cast(a.p[0]); + device const float* k_pool = static_cast(a.p[1]); + + // Cooperative coalesced load of K_tile [32, 128] once across all heads (8 rows per warp, 4 floats per lane). + // Zero-pad out-of-range or future causal blocks (b >= nv_max) so unwritten pool slots never inject NaN/Inf. +#pragma clang loop unroll(full) + for (uint r = 0u; r < 8u; ++r) { + const uint b_loc = warp * 8u + r; + const int b = b0 + int(b_loc); + half4 kh = half4(0.0h); + if (b < max_blocks && long(b) < nv_max) { + const float4 kv = *reinterpret_cast(k_pool + ulong(b) * 128ul + lane * 4u); + kh = half4(clamp(kv, float4(-kHalfMax), float4(kHalfMax))); + } + *reinterpret_cast(sK + b_loc * uint(kStride) + lane * 4u) = kh; + } + + const ulong q_row_stride = ulong(idx_heads) * 128ul; + threadgroup half* sq_sg = sQ + sg_t * 8u * uint(kStride); + threadgroup half* sk0_sg = sK + (sg_b * 16u) * uint(kStride); + threadgroup half* sk1_sg = sK + (sg_b * 16u + 8u) * uint(kStride); + threadgroup float* sdot_sg0 = sDot + (sg_t * 8u) * 32u + (sg_b * 16u); + threadgroup float* sdot_sg1 = sdot_sg0 + 8u; + + float4 tot = float4(0.0f); + for (int h = 0; h < idx_heads; ++h) { + // Cooperative coalesced load of Q_tile [16, 128] for head h (4 rows per warp, 4 floats per lane). +#pragma clang loop unroll(full) + for (uint r = 0u; r < 4u; ++r) { + const uint t_loc = warp * 4u + r; + const int t = t0 + int(t_loc); + half4 qh = half4(0.0h); + if (t < rows) { + const float4 qv = *reinterpret_cast( + q_ptr + ulong(t) * q_row_stride + ulong(h) * 128ul + lane * 4u); + qh = half4(clamp(qv, float4(-kHalfMax), float4(kHalfMax))); + } + *reinterpret_cast(sQ + t_loc * uint(kStride) + lane * 4u) = qh; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + + simdgroup_float8x8 acc0 = make_filled_simdgroup_matrix(0.0f); + simdgroup_float8x8 acc1 = make_filled_simdgroup_matrix(0.0f); +#pragma clang loop unroll(full) + for (int d = 0; d < 128; d += 8) { + simdgroup_half8x8 mq, mk0, mk1; + simdgroup_load(mq, sq_sg + d, kStride, ulong2(0, 0), false); + simdgroup_load(mk0, sk0_sg + d, kStride, ulong2(0, 0), true); + simdgroup_load(mk1, sk1_sg + d, kStride, ulong2(0, 0), true); + simdgroup_multiply_accumulate(acc0, mq, mk0, acc0); + simdgroup_multiply_accumulate(acc1, mq, mk1, acc1); + } + simdgroup_store(acc0, sdot_sg0, 32, ulong2(0, 0), false); + simdgroup_store(acc1, sdot_sg1, 32, ulong2(0, 0), false); + simdgroup_barrier(mem_flags::mem_threadgroup); + + const float4 d4 = *reinterpret_cast(sDot + ti * 32u + bi); + tot += select(float4(0.0f), d4, d4 > 0.0f); + + if (h + 1 < idx_heads) { + threadgroup_barrier(mem_flags::mem_threadgroup); + } + } + + const int t = t0 + int(ti); + if (t < rows) { + const float inv_sqrt_d = rsqrt(128.0f); + const long nv = (a.pos + long(t) + 1l) / long(idx_block); + const ulong row_off = ulong(t) * ulong(score_stride); + const float4 vals = tot * inv_sqrt_d; +#pragma clang loop unroll(full) + for (int k = 0; k < 4; ++k) { + const int b = b0 + int(bi) + k; + if (b < max_blocks) { + score[row_off + ulong(b)] = (long(b) >= nv) ? -INFINITY : vals[k]; + } + } + } +} + inline uint order_key(float s) { const float v = s + 0.0f; if (!(v == v)) return 0u; @@ -1340,18 +1646,29 @@ kernel void q4_mtp_eh_concat_kernel(constant Q4Args& a [[buffer(0)]], } kernel void q4_split_2d_kernel(constant Q4Args& a [[buffer(0)]], - uint idx [[thread_position_in_grid]]) { + uint2 gid [[thread_position_in_grid]]) { const int na = a.n[0]; const int nb = a.n[1]; - const int rows = a.n[2]; const int width = na + nb; - const ulong total = ulong(rows) * ulong(width); - if (ulong(idx) >= total) return; - const int r = int(ulong(idx) / ulong(width)); - const int c = int(ulong(idx) - ulong(r) * ulong(width)); - const float v = static_cast(a.p[0])[idx]; - if (c < na) static_cast(a.p[1])[ulong(r) * ulong(na) + ulong(c)] = v; - else static_cast(a.p[2])[ulong(r) * ulong(nb) + ulong(c - na)] = v; + const int c = int(gid.x); + if (c >= width) return; + const ulong r = ulong(gid.y); + const float v = static_cast(a.p[0])[r * ulong(width) + ulong(c)]; + if (c < na) static_cast(a.p[1])[r * ulong(na) + ulong(c)] = v; + else static_cast(a.p[2])[r * ulong(nb) + ulong(c - na)] = v; +} + +kernel void q4_split_2d_vec4_kernel(constant Q4Args& a [[buffer(0)]], + uint2 gid [[thread_position_in_grid]]) { + const uint na4 = uint(a.n[0]) >> 2u; + const uint nb4 = uint(a.n[1]) >> 2u; + const uint width4 = na4 + nb4; + const uint c4 = gid.x; + if (c4 >= width4) return; + const ulong r = ulong(gid.y); + const float4 v = static_cast(a.p[0])[r * ulong(width4) + ulong(c4)]; + if (c4 < na4) static_cast(a.p[1])[r * ulong(na4) + ulong(c4)] = v; + else static_cast(a.p[2])[r * ulong(nb4) + ulong(c4 - na4)] = v; } // ---- 5. Fused GDN Decode Kernels ---- @@ -1547,9 +1864,10 @@ kernel void q4_shexp_gate_mul_kernel(constant Q4Args& a [[buffer(0)]], for (int i = int(tid); i < n_embd; i += 256) fo[i] *= g; } -// ---- 7. Fused GR Up-Projection + Sigmoid Gate + HC-4 Mean + Q8_1 Quantization ---- -// Supports hc == 4, hc_lr == 256, rows in 1..4, n_embd % 32 == 0. -// Grid: {n_embd / 32, 1, 1}, Threads: 512 (16 SIMD groups = 32 half-warps of 16 lanes; 1 channel per half-warp). +// ---- 7. Fused GR Up-Projection + Sigmoid Gate + HC-4 Mean + Optional Q8_1 Quantization ---- +// Supports hc == 4, hc_lr == 256, rows in 1..8, n_embd % 32 == 0, w_type in {Q6_K (14), Q4_K (12), Q8_0 (8)}. +// Supports direct FP32 lo (a.n[4] != 0, eliminating Q8_1 quantization of lo) or legacy Q8_1 lo (a.n[4] == 0). +// Grid: {n_embd / 32, 1, 1}. Each TG covers 32 channels (1 full Q8_1 block) so Q8_1 output needs zero atomics/fences. struct q4_block_q8_0 { half d; @@ -1570,144 +1888,272 @@ struct q4_block_q6_K { half d; }; -static inline uchar2 q4_k4_scale_min(int j, int k, device const uchar* q) { - return j < 4 - ? uchar2(uchar(q[j + k] & 63u), uchar(q[j + 4 + k] & 63u)) - : uchar2(uchar((q[j + 4 + k] & 0xFu) | ((q[j - 4 + k] & 0xC0u) >> 2u)), - uchar((q[j + 4 + k] >> 4u) | ((q[j + k] & 0xC0u) >> 2u))); +// Decode (d, dmin) and (sc_lo, m_lo, sc_hi, m_hi) for 64-elem group j in 0..3 from ONE 128-bit header load. +static inline void q4_k4_hdr_decode(device const q4_block_q4_K* b, uint j, + thread float& dl_lo, thread float& ml_lo, + thread float& dl_hi, thread float& ml_hi) { + const uint4 hdr = uint4(*reinterpret_cast(b)); + const half2 dd = as_type(hdr.x); + const float d = float(dd.x), dmin = float(dd.y); + const uint sh16 = (j & 1u) * 16u; + const uint u0 = hdr.y >> sh16; + const uint u1 = hdr.z >> sh16; + const uint u2 = hdr.w >> sh16; + const uint sc_lo = (j < 2u) ? (u0 & 63u) : ((u2 & 0xFu) | ((u0 & 0xC0u) >> 2u)); + const uint m_lo = (j < 2u) ? (u1 & 63u) : (((u2 >> 4u) & 0xFu) | ((u1 & 0xC0u) >> 2u)); + const uint sc_hi = (j < 2u) ? ((u0 >> 8u) & 63u) : (((u2 >> 8u) & 0xFu) | ((u0 >> 10u) & 0x30u)); + const uint m_hi = (j < 2u) ? ((u1 >> 8u) & 63u) : (((u2 >> 12u) & 0xFu) | ((u1 >> 10u) & 0x30u)); + dl_lo = d * float(sc_lo); + ml_lo = -dmin * float(m_lo); + dl_hi = d * float(sc_hi); + ml_hi = -dmin * float(m_hi); +} + +// Helper: load one float4 of lo (from direct FP32 lo or legacy Q8_1 lo). +static inline float4 q4_load_lo4(device const uchar* lo_ptr, bool use_f32, uint t, uint idx4) { + if (use_f32) { + return float4(reinterpret_cast(lo_ptr)[ulong(t) * 64ul + ulong(idx4)]); + } + const uint blk = idx4 >> 3u; + const uint q4i = idx4 & 7u; + device const uchar* qb = lo_ptr + (ulong(t) * 8ul + ulong(blk)) * 36ul; + const float d = float(*reinterpret_cast(qb)); + const char4 q = reinterpret_cast(qb + 4u)[q4i]; + return d * float4(q); +} + +// Helper: accumulate one 8-element-per-quadrant (32-element total) Q6_K slice into part[0..rows-1] from TG slo4. +template +static inline void q4_q6k_dot_slice8(device const q4_block_q6_K* b, uint h, uint g, + threadgroup const float4 (*slo4)[64], int rows, + thread float* part) { + const uint is = g >> 1u; + const uint l0 = g * 8u; + const uint base4 = h * 32u + g * 2u; + const ushort4 ql0 = ushort4(*reinterpret_cast(b->ql + 64u * h + l0)); + const ushort4 ql1 = ushort4(*reinterpret_cast(b->ql + 64u * h + 32u + l0)); + const ushort4 qh0 = ushort4(*reinterpret_cast(b->qh + 32u * h + l0)); + const uint ql0_a = as_type(ql0.xy), ql0_b = as_type(ql0.zw); + const uint ql1_a = as_type(ql1.xy), ql1_b = as_type(ql1.zw); + const uint qh0_a = as_type(qh0.xy), qh0_b = as_type(qh0.zw); + const float d = float(b->d); + const float sc0 = d * float(b->scales[8u * h + is + 0u]); + const float sc2 = d * float(b->scales[8u * h + is + 2u]); + const float sc4 = d * float(b->scales[8u * h + is + 4u]); + const float sc6 = d * float(b->scales[8u * h + is + 6u]); + + { + const float4 wa = float4(as_type((ql0_a & 0x0F0F0F0Fu) | ((qh0_a & 0x03030303u) << 4u)) - char4(32)); + const float4 wb = float4(as_type((ql0_b & 0x0F0F0F0Fu) | ((qh0_b & 0x03030303u) << 4u)) - char4(32)); +#pragma clang loop unroll(full) + for (int t = 0; t < MAXR; ++t) { + if (t >= rows) break; + part[t] = fma(sc0, dot(wa, slo4[t][base4 + 0u]) + dot(wb, slo4[t][base4 + 1u]), part[t]); + } + } + { + const float4 wa = float4(as_type((ql1_a & 0x0F0F0F0Fu) | ((qh0_a & 0x0C0C0C0Cu) << 2u)) - char4(32)); + const float4 wb = float4(as_type((ql1_b & 0x0F0F0F0Fu) | ((qh0_b & 0x0C0C0C0Cu) << 2u)) - char4(32)); +#pragma clang loop unroll(full) + for (int t = 0; t < MAXR; ++t) { + if (t >= rows) break; + part[t] = fma(sc2, dot(wa, slo4[t][base4 + 8u]) + dot(wb, slo4[t][base4 + 9u]), part[t]); + } + } + { + const float4 wa = float4(as_type(((ql0_a >> 4u) & 0x0F0F0F0Fu) | (qh0_a & 0x30303030u)) - char4(32)); + const float4 wb = float4(as_type(((ql0_b >> 4u) & 0x0F0F0F0Fu) | (qh0_b & 0x30303030u)) - char4(32)); +#pragma clang loop unroll(full) + for (int t = 0; t < MAXR; ++t) { + if (t >= rows) break; + part[t] = fma(sc4, dot(wa, slo4[t][base4 + 16u]) + dot(wb, slo4[t][base4 + 17u]), part[t]); + } + } + { + const float4 wa = float4(as_type(((ql1_a >> 4u) & 0x0F0F0F0Fu) | ((qh0_a & 0xC0C0C0C0u) >> 2u)) - char4(32)); + const float4 wb = float4(as_type(((ql1_b >> 4u) & 0x0F0F0F0Fu) | ((qh0_b & 0xC0C0C0C0u) >> 2u)) - char4(32)); +#pragma clang loop unroll(full) + for (int t = 0; t < MAXR; ++t) { + if (t >= rows) break; + part[t] = fma(sc6, dot(wa, slo4[t][base4 + 24u]) + dot(wb, slo4[t][base4 + 25u]), part[t]); + } + } +} + +// Helper: accumulate one 16-byte Q4_K slice (16 low + 16 high elements) into part[0..rows-1] from TG slo4. +template +static inline void q4_q4k_dot_slice16(device const q4_block_q4_K* b, uint j, uint h, + float dl_lo, float ml_lo, float dl_hi, float ml_hi, + threadgroup const float4 (*slo4)[64], + threadgroup const float (*slo_sum16)[16], + int rows, thread float* part) { + const uint4 qv = uint4(*reinterpret_cast(b->qs + j * 32u + h * 16u)); + const uint base_lo = j * 16u + h * 4u; + const uint base_hi = base_lo + 8u; + const uint sidx_lo = j * 4u + h; + const uint sidx_hi = sidx_lo + 2u; + { + const float4 w0 = float4(as_type(qv.x & 0x0F0F0F0Fu)); + const float4 w1 = float4(as_type(qv.y & 0x0F0F0F0Fu)); + const float4 w2 = float4(as_type(qv.z & 0x0F0F0F0Fu)); + const float4 w3 = float4(as_type(qv.w & 0x0F0F0F0Fu)); +#pragma clang loop unroll(full) + for (int t = 0; t < MAXR; ++t) { + if (t >= rows) break; + const float sdot = dot(w0, slo4[t][base_lo + 0u]) + dot(w1, slo4[t][base_lo + 1u]) + + dot(w2, slo4[t][base_lo + 2u]) + dot(w3, slo4[t][base_lo + 3u]); + part[t] = fma(dl_lo, sdot, fma(ml_lo, slo_sum16[t][sidx_lo], part[t])); + } + } + { + const float4 w0 = float4(as_type((qv.x >> 4u) & 0x0F0F0F0Fu)); + const float4 w1 = float4(as_type((qv.y >> 4u) & 0x0F0F0F0Fu)); + const float4 w2 = float4(as_type((qv.z >> 4u) & 0x0F0F0F0Fu)); + const float4 w3 = float4(as_type((qv.w >> 4u) & 0x0F0F0F0Fu)); +#pragma clang loop unroll(full) + for (int t = 0; t < MAXR; ++t) { + if (t >= rows) break; + const float sdot = dot(w0, slo4[t][base_hi + 0u]) + dot(w1, slo4[t][base_hi + 1u]) + + dot(w2, slo4[t][base_hi + 2u]) + dot(w3, slo4[t][base_hi + 3u]); + part[t] = fma(dl_hi, sdot, fma(ml_hi, slo_sum16[t][sidx_hi], part[t])); + } + } +} + +// Helper: accumulate one full 32-element Q8_0 block into part[0..rows-1] from TG slo4. +template +static inline void q4_q80_dot_block(device const q4_block_q8_0* b, uint blk, + threadgroup const float4 (*slo4)[64], int rows, + thread float* part) { + const float dw = float(b->d); + device const packed_ushort4* qp = reinterpret_cast(b->qs); + const uint base4 = blk * 8u; + float lp[MAXR]; +#pragma clang loop unroll(full) + for (int t = 0; t < MAXR; ++t) lp[t] = 0.0f; +#pragma clang loop unroll(full) + for (uint h = 0u; h < 2u; ++h) { + const ushort4 u0 = ushort4(qp[2u * h + 0u]); + const ushort4 u1 = ushort4(qp[2u * h + 1u]); + const float4 w0 = float4(as_type(u0.xy)); + const float4 w1 = float4(as_type(u0.zw)); + const float4 w2 = float4(as_type(u1.xy)); + const float4 w3 = float4(as_type(u1.zw)); +#pragma clang loop unroll(full) + for (int t = 0; t < MAXR; ++t) { + if (t >= rows) break; + lp[t] += dot(w0, slo4[t][base4 + h * 4u + 0u]) + + dot(w1, slo4[t][base4 + h * 4u + 1u]) + + dot(w2, slo4[t][base4 + h * 4u + 2u]) + + dot(w3, slo4[t][base4 + h * 4u + 3u]); + } + } +#pragma clang loop unroll(full) + for (int t = 0; t < MAXR; ++t) { + if (t >= rows) break; + part[t] = fma(dw, lp[t], part[t]); + } } +// Fused GR up-projection + parallel 4-lane sigmoid gate + HC-4 mean + optional Q8_1 quantization. +// Grid: {n_embd / 32, 1, 1}, Threads: 256 (8 SIMD groups = 32 channels x 8 lanes/ch). +// Decouples w_up GEMV from gr_xn * sigmoid(gate): all 4 streams issue back-to-back with zero exp()/gr_xn stalls, +// then lanes lid = 0..3 evaluate all 4 streams' gr_xn * sigmoid(gate) in parallel and reduce in 2 shuffles. template kernel void q4_gr_up_gate_mean_kernel(constant Q4Args& a [[buffer(0)]], uint tg [[threadgroup_position_in_grid]], uint tid [[thread_index_in_threadgroup]]) { - threadgroup char4 sq[MAXR][64]; - threadgroup float sd[MAXR][8]; - threadgroup short sqs[MAXR][16]; + threadgroup float4 slo4[MAXR][64]; + threadgroup float slo_sum16[WTYPE == 12 ? MAXR : 1][16]; threadgroup float out_blk[MAXR][32]; const int n_embd = a.n[0]; const int rows = a.n[3]; + const bool use_f32 = (a.n[4] != 0); const int c0 = int(tg) * 32; device const uchar* w_up = static_cast(a.p[0]); - device const uchar* lo_q8 = static_cast(a.p[1]); + device const uchar* lo_ptr = static_cast(a.p[1]); device const float* gr_xn = static_cast(a.p[2]); device float* out = static_cast(a.p[3]); - // Step 1: Stage quantized Q8_1 codes (char4), scales (float), and 16-elem integer sums into TG memory (~3.5 KiB for MAXR=8). - if (tid < 256u) { - const uint blk = tid >> 5u; - const uint lane = tid & 31u; - const uint piece = tid >> 4u; - const uint p_lane = tid & 15u; - for (int t = 0; t < MAXR; ++t) { - if (t >= rows) break; - device const uchar* qb = lo_q8 + (ulong(t) * 8ul + ulong(blk)) * 36ul; - if (lane == 0u) sd[t][blk] = float(*reinterpret_cast(qb)); - if ((lane & 3u) == 0u) sq[t][tid >> 2u] = reinterpret_cast(qb + 4)[lane >> 2u]; - if (WTYPE == 14 || WTYPE == 12) { - int ps = int(reinterpret_cast(qb + 4)[lane]); - ps += simd_shuffle_xor(ps, 8u); - ps += simd_shuffle_xor(ps, 4u); - ps += simd_shuffle_xor(ps, 2u); - ps += simd_shuffle_xor(ps, 1u); - if (p_lane == 0u) sqs[t][piece] = short(ps); + // Step 1: Stage FP32 lo (1 KiB/row, or dequantized legacy Q8_1 lo) into threadgroup float4 slo4[MAXR][64]. + { + const uint idx4 = tid & 63u; + const uint t0 = tid >> 6u; + for (uint t = t0; t < uint(rows); t += 4u) { + const float4 v = q4_load_lo4(lo_ptr, use_f32, t, idx4); + slo4[t][idx4] = v; + if (WTYPE == 12) { + float s16 = (v.x + v.y) + (v.z + v.w); + s16 += simd_shuffle_xor(s16, 2u); + s16 += simd_shuffle_xor(s16, 1u); + if ((idx4 & 3u) == 0u) slo_sum16[t][idx4 >> 2u] = s16; } } } threadgroup_barrier(mem_flags::mem_threadgroup); - // Step 2: 32 half-warps of 16 lanes compute channels c0..c0+31 across all 4 streams & 1..MAXR rows using float4 FMA. - const uint ch = tid >> 4u; // 0..31 - const short il = short(tid & 15u); // 0..15 (16-element piece of the 256-element row) + // Step 2: Compute all 4 streams' gate projections back-to-back, routing stream s's dot to lane lid == s. + const uint ch = tid >> 3u; + const uint lid = tid & 7u; const int col = c0 + int(ch); - const uint qbase = uint(il) * 4u; - const uint blk_idx = uint(il >> 1); - float acc[MAXR]; - for (int t = 0; t < MAXR; ++t) acc[t] = 0.0f; - for (int s = 0; s < 4; ++s) { + float my_gate[MAXR]; +#pragma clang loop unroll(full) + for (int t = 0; t < MAXR; ++t) my_gate[t] = 0.0f; + + for (uint s = 0u; s < 4u; ++s) { const ulong r = ulong(s) * ulong(n_embd) + ulong(col); - float4 wv[4]; - float k_scale = 0.0f; - float k_min = 0.0f; + float part[MAXR]; +#pragma clang loop unroll(full) + for (int t = 0; t < MAXR; ++t) part[t] = 0.0f; - if (WTYPE == 14) { // Q6_K: 1 superblock (210 bytes) per output row + if (WTYPE == 14) { device const q4_block_q6_K* b = reinterpret_cast(w_up) + r; - device const ushort* ql = reinterpret_cast(b->ql) + 32 * (il / 8) + 16 * ((il / 2) & 1) + 8 * (il & 1); - device const ushort* qh = reinterpret_cast(b->qh) + 16 * (il / 8) + 8 * (il & 1); - const float sc = float(b->scales[(il & 1) + 2 * (il / 2)]); - const short kk = (il / 2) & 3; - const uint mask1 = kk > 1 ? (kk > 2 ? 0xC0C0C0C0u : 0x30303030u) : (kk > 0 ? 0x0C0C0C0Cu : 0x03030303u); - const uint mask2 = kk > 1 ? 0xF0F0F0F0u : 0x0F0F0F0Fu; - const uint shr_h = kk > 2 ? 2u : 0u; - const uint shl_h = kk > 1 ? 0u : (kk > 0 ? 2u : 4u); - const uint shr_l = kk > 1 ? 4u : 0u; - for (int i = 0; i < 4; ++i) { - const uint low = (uint(ql[2 * i]) | (uint(ql[2 * i + 1]) << 16u)) & mask2; - const uint high = (uint(qh[2 * i]) | (uint(qh[2 * i + 1]) << 16u)) & mask1; - wv[i] = float4(as_type(((high << shl_h) >> shr_h) | (low >> shr_l))); - } - k_scale = float(b->d) * sc; - } else if (WTYPE == 8) { // Q8_0: 8 blocks (272 bytes) per output row - device const q4_block_q8_0* b = reinterpret_cast(w_up) + r * 8ul + ulong(blk_idx); - device const ushort* q = reinterpret_cast(b->qs + 16 * (il & 1)); - for (int i = 0; i < 4; ++i) { - const char2 c0_b = as_type(q[2 * i]); - const char2 c1_b = as_type(q[2 * i + 1]); - wv[i] = float4(float(c0_b.x), float(c0_b.y), float(c1_b.x), float(c1_b.y)); - } - k_scale = float(b->d); - } else { // WTYPE == 12 (Q4_K): 1 superblock (144 bytes) per output row + q4_q6k_dot_slice8(b, lid >> 2u, lid & 3u, slo4, rows, part); + } else if (WTYPE == 12) { device const q4_block_q4_K* b = reinterpret_cast(w_up) + r; - const uchar2 sc = q4_k4_scale_min((il / 4) * 2, (il & 3) / 2, b->scales); - device const uint* q = reinterpret_cast(b->qs + (il / 4) * 32 + 16 * (il & 1)); - const uint sh = (il & 2) ? 4u : 0u; - for (int i = 0; i < 4; ++i) { - wv[i] = float4(as_type((q[i] >> sh) & 0x0F0F0F0Fu)); - } - k_scale = float(b->d) * float(sc[0]); - k_min = float(b->dmin) * float(sc[1]); + const uint j = lid >> 1u, h = lid & 1u; + float dl_lo, ml_lo, dl_hi, ml_hi; + q4_k4_hdr_decode(b, j, dl_lo, ml_lo, dl_hi, ml_hi); + q4_q4k_dot_slice16(b, j, h, dl_lo, ml_lo, dl_hi, ml_hi, slo4, slo_sum16, rows, part); + } else { // WTYPE == 8 (Q8_0) + device const q4_block_q8_0* br = reinterpret_cast(w_up) + r * 8ul; + q4_q80_dot_block(br + lid, lid, slo4, rows, part); } +#pragma clang loop unroll(full) for (int t = 0; t < MAXR; ++t) { if (t >= rows) break; - const float sdot = dot(wv[0], float4(sq[t][qbase + 0u])) + dot(wv[1], float4(sq[t][qbase + 1u])) + - dot(wv[2], float4(sq[t][qbase + 2u])) + dot(wv[3], float4(sq[t][qbase + 3u])); - const float dx = sd[t][blk_idx]; - float part; - if (WTYPE == 14) { - part = (k_scale * dx) * fma(-32.0f, float(sqs[t][il]), sdot); - } else if (WTYPE == 8) { - part = (k_scale * dx) * sdot; - } else { - part = dx * fma(k_scale, sdot, -k_min * float(sqs[t][il])); - } - part += simd_shuffle_xor(part, 8u); - part += simd_shuffle_xor(part, 4u); - part += simd_shuffle_xor(part, 2u); - part += simd_shuffle_xor(part, 1u); - if (il == 0) { - const float xv = gr_xn[(ulong(t) * 4ul + ulong(s)) * ulong(n_embd) + ulong(col)]; - acc[t] = fma(xv, q4_sig(part), acc[t]); - } + float p = part[t]; + p += simd_shuffle_xor(p, 4u); + p += simd_shuffle_xor(p, 2u); + p += simd_shuffle_xor(p, 1u); + if (lid == s) my_gate[t] = p; } } - if (il == 0) { + + // Parallel 4-lane sigmoid(gate) * gr_xn + 4-stream mean across lanes lid = 0..3. + if (lid < 4u) { +#pragma clang loop unroll(full) for (int t = 0; t < MAXR; ++t) { if (t >= rows) break; - out_blk[t][ch] = acc[t] * 0.25f; + const float xv = gr_xn[(ulong(t) * 4ul + ulong(lid)) * ulong(n_embd) + ulong(col)]; + float v = xv * q4_sig(my_gate[t]); + v += simd_shuffle_xor(v, 2u); + v += simd_shuffle_xor(v, 1u); + if (lid == 0u) out_blk[t][ch] = v * 0.25f; } } threadgroup_barrier(mem_flags::mem_threadgroup); - // Step 3: First `rows` SIMD groups write out[t, c0..c0+31] and (optionally) quantize to Q8_1. + // Step 3: Write out[t, c0..c0+31] and (optionally) quantize to Q8_1 with zero atomics/fences. const uint warp = tid >> 5u; const uint lane = tid & 31u; if (int(warp) < rows) { const float v = out_blk[warp][lane]; - out[ulong(warp) * ulong(n_embd) + ulong(c0) + lane] = v; + out[ulong(warp) * ulong(n_embd) + ulong(c0) + ulong(lane)] = v; if (QUANT) { device uchar* q_row = static_cast(a.p[4]) + ulong(warp) * ulong(n_embd >> 5) * 36ul; q8_put(q_row, c0 + int(lane), v); @@ -1715,15 +2161,536 @@ kernel void q4_gr_up_gate_mean_kernel(constant Q4Args& a [[buffer(0)]], } } -template [[host_name("q4_gr_up_q6_K_0")]] kernel decltype(q4_gr_up_gate_mean_kernel<14, false, 4>) q4_gr_up_gate_mean_kernel<14, false, 4>; -template [[host_name("q4_gr_up_q6_K_1")]] kernel decltype(q4_gr_up_gate_mean_kernel<14, true, 4>) q4_gr_up_gate_mean_kernel<14, true, 4>; -template [[host_name("q4_gr_up_q8_0_0")]] kernel decltype(q4_gr_up_gate_mean_kernel<8, false, 4>) q4_gr_up_gate_mean_kernel<8, false, 4>; -template [[host_name("q4_gr_up_q8_0_1")]] kernel decltype(q4_gr_up_gate_mean_kernel<8, true, 4>) q4_gr_up_gate_mean_kernel<8, true, 4>; -template [[host_name("q4_gr_up_q4_K_0")]] kernel decltype(q4_gr_up_gate_mean_kernel<12, false, 4>) q4_gr_up_gate_mean_kernel<12, false, 4>; -template [[host_name("q4_gr_up_q4_K_1")]] kernel decltype(q4_gr_up_gate_mean_kernel<12, true, 4>) q4_gr_up_gate_mean_kernel<12, true, 4>; -template [[host_name("q4_gr_up_q6_K_r8_0")]] kernel decltype(q4_gr_up_gate_mean_kernel<14, false, 8>) q4_gr_up_gate_mean_kernel<14, false, 8>; -template [[host_name("q4_gr_up_q6_K_r8_1")]] kernel decltype(q4_gr_up_gate_mean_kernel<14, true, 8>) q4_gr_up_gate_mean_kernel<14, true, 8>; -template [[host_name("q4_gr_up_q8_0_r8_0")]] kernel decltype(q4_gr_up_gate_mean_kernel<8, false, 8>) q4_gr_up_gate_mean_kernel<8, false, 8>; -template [[host_name("q4_gr_up_q8_0_r8_1")]] kernel decltype(q4_gr_up_gate_mean_kernel<8, true, 8>) q4_gr_up_gate_mean_kernel<8, true, 8>; -template [[host_name("q4_gr_up_q4_K_r8_0")]] kernel decltype(q4_gr_up_gate_mean_kernel<12, false, 8>) q4_gr_up_gate_mean_kernel<12, false, 8>; -template [[host_name("q4_gr_up_q4_K_r8_1")]] kernel decltype(q4_gr_up_gate_mean_kernel<12, true, 8>) q4_gr_up_gate_mean_kernel<12, true, 8>; +#define Q4_GR_UP_INST(name, wt) \ + template [[host_name("q4_gr_up_" #name "_r1_0")]] kernel decltype(q4_gr_up_gate_mean_kernel) q4_gr_up_gate_mean_kernel; \ + template [[host_name("q4_gr_up_" #name "_r1_1")]] kernel decltype(q4_gr_up_gate_mean_kernel) q4_gr_up_gate_mean_kernel; \ + template [[host_name("q4_gr_up_" #name "_r2_0")]] kernel decltype(q4_gr_up_gate_mean_kernel) q4_gr_up_gate_mean_kernel; \ + template [[host_name("q4_gr_up_" #name "_r2_1")]] kernel decltype(q4_gr_up_gate_mean_kernel) q4_gr_up_gate_mean_kernel; \ + template [[host_name("q4_gr_up_" #name "_r4_0")]] kernel decltype(q4_gr_up_gate_mean_kernel) q4_gr_up_gate_mean_kernel; \ + template [[host_name("q4_gr_up_" #name "_r4_1")]] kernel decltype(q4_gr_up_gate_mean_kernel) q4_gr_up_gate_mean_kernel; \ + template [[host_name("q4_gr_up_" #name "_r8_0")]] kernel decltype(q4_gr_up_gate_mean_kernel) q4_gr_up_gate_mean_kernel; \ + template [[host_name("q4_gr_up_" #name "_r8_1")]] kernel decltype(q4_gr_up_gate_mean_kernel) q4_gr_up_gate_mean_kernel; +Q4_GR_UP_INST(q6_K, 14) +Q4_GR_UP_INST(q8_0, 8) +Q4_GR_UP_INST(q4_K, 12) +#undef Q4_GR_UP_INST + +// ---- 8. Lock-Free, Fence-Free Fused GR Down(+Inject) GEMV + Split + SiLU(/hc) ---- +// Grid: {ceil(n_out / NR), 1, 1}, Threads: 128 (4 SIMD groups split-K across hc_dim). +// Shares xn_xq loads across NR output rows per TG and writes FP32 lo & inject with ZERO atomics/fences. +// When a caller also requests Q8_1 lo_xq, q4_gr_lo_q8_kernel runs as a tiny 1-TG-per-row follow-up kernel. + +template +static inline void q4_down_q8_piece_multi(device const q4_block_q8_0* w_row, ulong blk, uint half_off, + device const uchar* xn_xq, ulong xn_row_bytes, + int rows, thread float* acc) { + device const q4_block_q8_0* b = w_row + blk; + const float dw = float(b->d); + device const packed_ushort4* wp = reinterpret_cast(b->qs + half_off); + const ushort4 u0 = ushort4(wp[0]); + const ushort4 u1 = ushort4(wp[1]); + const float4 w0 = float4(as_type(u0.xy)); + const float4 w1 = float4(as_type(u0.zw)); + const float4 w2 = float4(as_type(u1.xy)); + const float4 w3 = float4(as_type(u1.zw)); + const ulong x_blk_off = blk * 36ul; +#pragma clang loop unroll(full) + for (int t = 0; t < MAX_T; ++t) { + if (t >= rows) break; + device const uchar* xb = xn_xq + ulong(t) * xn_row_bytes + x_blk_off; + const float dx = float(*reinterpret_cast(xb)); + const uint4 xu = uint4(*reinterpret_cast(xb + 4u + half_off)); + const float s = dot(w0, float4(as_type(xu.x))) + + dot(w1, float4(as_type(xu.y))) + + dot(w2, float4(as_type(xu.z))) + + dot(w3, float4(as_type(xu.w))); + acc[t] = fma(dw * dx, s, acc[t]); + } +} + +template +static inline void q4_down_q4k_row(device const q4_block_q4_K* b, uint blk, uint j, uint h, + device const uchar* xn_xq, ulong xn_row_bytes, + int rows, thread float* acc) { + float dl_lo, ml_lo, dl_hi, ml_hi; + q4_k4_hdr_decode(b, j, dl_lo, ml_lo, dl_hi, ml_hi); + const uint4 qv = uint4(*reinterpret_cast(b->qs + j * 32u + h * 16u)); + const ulong x_off_lo = ulong(blk * 8u + j * 2u) * 36ul; + const ulong x_off_hi = x_off_lo + 36ul; + { + const float4 w0 = float4(as_type(qv.x & 0x0F0F0F0Fu)); + const float4 w1 = float4(as_type(qv.y & 0x0F0F0F0Fu)); + const float4 w2 = float4(as_type(qv.z & 0x0F0F0F0Fu)); + const float4 w3 = float4(as_type(qv.w & 0x0F0F0F0Fu)); +#pragma clang loop unroll(full) + for (int t = 0; t < MAX_T; ++t) { + if (t >= rows) break; + device const uchar* xb = xn_xq + ulong(t) * xn_row_bytes + x_off_lo; + const float dx = float(*reinterpret_cast(xb)); + const uint4 xu = uint4(reinterpret_cast(xb + 4u)[h]); + const float4 x0 = float4(as_type(xu.x)), x1 = float4(as_type(xu.y)); + const float4 x2 = float4(as_type(xu.z)), x3 = float4(as_type(xu.w)); + const float xsum = dot((x0 + x1) + (x2 + x3), float4(1.0f)); + const float sdot = dot(w0, x0) + dot(w1, x1) + dot(w2, x2) + dot(w3, x3); + acc[t] = fma(dx, fma(dl_lo, sdot, ml_lo * xsum), acc[t]); + } + } + { + const float4 w0 = float4(as_type((qv.x >> 4u) & 0x0F0F0F0Fu)); + const float4 w1 = float4(as_type((qv.y >> 4u) & 0x0F0F0F0Fu)); + const float4 w2 = float4(as_type((qv.z >> 4u) & 0x0F0F0F0Fu)); + const float4 w3 = float4(as_type((qv.w >> 4u) & 0x0F0F0F0Fu)); +#pragma clang loop unroll(full) + for (int t = 0; t < MAX_T; ++t) { + if (t >= rows) break; + device const uchar* xb = xn_xq + ulong(t) * xn_row_bytes + x_off_hi; + const float dx = float(*reinterpret_cast(xb)); + const uint4 xu = uint4(reinterpret_cast(xb + 4u)[h]); + const float4 x0 = float4(as_type(xu.x)), x1 = float4(as_type(xu.y)); + const float4 x2 = float4(as_type(xu.z)), x3 = float4(as_type(xu.w)); + const float xsum = dot((x0 + x1) + (x2 + x3), float4(1.0f)); + const float sdot = dot(w0, x0) + dot(w1, x1) + dot(w2, x2) + dot(w3, x3); + acc[t] = fma(dx, fma(dl_hi, sdot, ml_hi * xsum), acc[t]); + } + } +} + +template +static inline void q4_down_q6k_row(device const q4_block_q6_K* b, uint blk, uint h, uint g, + device const uchar* xn_xq, ulong xn_row_bytes, + int rows, thread float* acc) { + const uint is = g >> 1u; + const uint l0 = g * 8u; + const ushort4 ql0 = ushort4(*reinterpret_cast(b->ql + 64u * h + l0)); + const ushort4 ql1 = ushort4(*reinterpret_cast(b->ql + 64u * h + 32u + l0)); + const ushort4 qh0 = ushort4(*reinterpret_cast(b->qh + 32u * h + l0)); + const uint ql0_a = as_type(ql0.xy), ql0_b = as_type(ql0.zw); + const uint ql1_a = as_type(ql1.xy), ql1_b = as_type(ql1.zw); + const uint qh0_a = as_type(qh0.xy), qh0_b = as_type(qh0.zw); + const float d = float(b->d); + const float sc0 = d * float(b->scales[8u * h + is + 0u]); + const float sc2 = d * float(b->scales[8u * h + is + 2u]); + const float sc4 = d * float(b->scales[8u * h + is + 4u]); + const float sc6 = d * float(b->scales[8u * h + is + 6u]); + const ulong xb_base = ulong(blk * 8u + h * 4u) * 36ul; + + { + const float4 wa = float4(as_type((ql0_a & 0x0F0F0F0Fu) | ((qh0_a & 0x03030303u) << 4u)) - char4(32)); + const float4 wb = float4(as_type((ql0_b & 0x0F0F0F0Fu) | ((qh0_b & 0x03030303u) << 4u)) - char4(32)); +#pragma clang loop unroll(full) + for (int t = 0; t < MAX_T; ++t) { + if (t >= rows) break; + device const uchar* xb = xn_xq + ulong(t) * xn_row_bytes + xb_base + 0ul; + const float dx = float(*reinterpret_cast(xb)); + const uint2 xu = uint2(*reinterpret_cast(xb + 4u + l0)); + acc[t] = fma(sc0 * dx, dot(wa, float4(as_type(xu.x))) + dot(wb, float4(as_type(xu.y))), acc[t]); + } + } + { + const float4 wa = float4(as_type((ql1_a & 0x0F0F0F0Fu) | ((qh0_a & 0x0C0C0C0Cu) << 2u)) - char4(32)); + const float4 wb = float4(as_type((ql1_b & 0x0F0F0F0Fu) | ((qh0_b & 0x0C0C0C0Cu) << 2u)) - char4(32)); +#pragma clang loop unroll(full) + for (int t = 0; t < MAX_T; ++t) { + if (t >= rows) break; + device const uchar* xb = xn_xq + ulong(t) * xn_row_bytes + xb_base + 36ul; + const float dx = float(*reinterpret_cast(xb)); + const uint2 xu = uint2(*reinterpret_cast(xb + 4u + l0)); + acc[t] = fma(sc2 * dx, dot(wa, float4(as_type(xu.x))) + dot(wb, float4(as_type(xu.y))), acc[t]); + } + } + { + const float4 wa = float4(as_type(((ql0_a >> 4u) & 0x0F0F0F0Fu) | (qh0_a & 0x30303030u)) - char4(32)); + const float4 wb = float4(as_type(((ql0_b >> 4u) & 0x0F0F0F0Fu) | (qh0_b & 0x30303030u)) - char4(32)); +#pragma clang loop unroll(full) + for (int t = 0; t < MAX_T; ++t) { + if (t >= rows) break; + device const uchar* xb = xn_xq + ulong(t) * xn_row_bytes + xb_base + 72ul; + const float dx = float(*reinterpret_cast(xb)); + const uint2 xu = uint2(*reinterpret_cast(xb + 4u + l0)); + acc[t] = fma(sc4 * dx, dot(wa, float4(as_type(xu.x))) + dot(wb, float4(as_type(xu.y))), acc[t]); + } + } + { + const float4 wa = float4(as_type(((ql1_a >> 4u) & 0x0F0F0F0Fu) | ((qh0_a & 0xC0C0C0C0u) >> 2u)) - char4(32)); + const float4 wb = float4(as_type(((ql1_b >> 4u) & 0x0F0F0F0Fu) | ((qh0_b & 0xC0C0C0C0u) >> 2u)) - char4(32)); +#pragma clang loop unroll(full) + for (int t = 0; t < MAX_T; ++t) { + if (t >= rows) break; + device const uchar* xb = xn_xq + ulong(t) * xn_row_bytes + xb_base + 108ul; + const float dx = float(*reinterpret_cast(xb)); + const uint2 xu = uint2(*reinterpret_cast(xb + 4u + l0)); + acc[t] = fma(sc6 * dx, dot(wa, float4(as_type(xu.x))) + dot(wb, float4(as_type(xu.y))), acc[t]); + } + } +} + +template +kernel void q4_gr_down_silu_kernel(constant Q4Args& a [[buffer(0)]], + uint tg [[threadgroup_position_in_grid]], + uint tid [[thread_index_in_threadgroup]]) { + const int hc_dim = a.n[0]; + const int hc_lr = a.n[1]; + const int hc = a.n[2]; + const int rows = a.n[3]; + const int n_out = a.n[4]; + const uint warp = tid >> 5u; + const uint lane = tid & 31u; + + const uint o0 = tg * uint(NR); + const int nr = min(NR, n_out - int(o0)); + + device const uchar* w = static_cast(a.p[0]); + device const uchar* xn_xq = static_cast(a.p[1]); + device float* lo = static_cast(a.p[2]); + device float* inject = static_cast(a.p[4]); + const ulong per = (WTYPE == 8) ? ulong(hc_dim >> 5) : ulong(hc_dim >> 8); + const ulong xn_row_bytes = ulong(hc_dim >> 5) * 36ul; + + float acc[NR][MAX_T]; +#pragma clang loop unroll(full) + for (int r = 0; r < NR; ++r) { +#pragma clang loop unroll(full) + for (int t = 0; t < MAX_T; ++t) acc[r][t] = 0.0f; + } + + if (WTYPE == 8) { + // Contiguous 16-element stride across 128 threads (544-byte dense SIMD wave, zero cache-line skipping). + device const q4_block_q8_0* w_q8 = reinterpret_cast(w) + ulong(o0) * per; + if (MAX_T == 1) { + for (int start = int(tid) * 16; start < hc_dim; start += 128 * 16) { + const ulong blk = ulong(start >> 5); + const uint half_off = uint(start & 16); + device const uchar* xb = xn_xq + blk * 36ul; + const float dx = float(*reinterpret_cast(xb)); + const uint4 xu = uint4(*reinterpret_cast(xb + 4u + half_off)); + const float4 x0 = float4(as_type(xu.x)); + const float4 x1 = float4(as_type(xu.y)); + const float4 x2 = float4(as_type(xu.z)); + const float4 x3 = float4(as_type(xu.w)); +#pragma clang loop unroll(full) + for (int r = 0; r < NR; ++r) { + if (r >= nr) break; + device const q4_block_q8_0* br = w_q8 + ulong(r) * per + blk; + device const packed_ushort4* wp = reinterpret_cast(br->qs + half_off); + const ushort4 u0 = ushort4(wp[0]); + const ushort4 u1 = ushort4(wp[1]); + const float s = dot(float4(as_type(u0.xy)), x0) + + dot(float4(as_type(u0.zw)), x1) + + dot(float4(as_type(u1.xy)), x2) + + dot(float4(as_type(u1.zw)), x3); + acc[r][0] = fma(float(br->d) * dx, s, acc[r][0]); + } + } + } else if (MAX_T == 2) { + for (int start = int(tid) * 16; start < hc_dim; start += 128 * 16) { + const ulong blk = ulong(start >> 5); + const uint half_off = uint(start & 16); + device const uchar* xb0 = xn_xq + blk * 36ul; + const float dx0 = float(*reinterpret_cast(xb0)); + const uint4 xu0 = uint4(*reinterpret_cast(xb0 + 4u + half_off)); + const float4 x00 = float4(as_type(xu0.x)), x01 = float4(as_type(xu0.y)); + const float4 x02 = float4(as_type(xu0.z)), x03 = float4(as_type(xu0.w)); + device const uchar* xb1 = xb0 + xn_row_bytes; + const float dx1 = float(*reinterpret_cast(xb1)); + const uint4 xu1 = uint4(*reinterpret_cast(xb1 + 4u + half_off)); + const float4 x10 = float4(as_type(xu1.x)), x11 = float4(as_type(xu1.y)); + const float4 x12 = float4(as_type(xu1.z)), x13 = float4(as_type(xu1.w)); +#pragma clang loop unroll(full) + for (int r = 0; r < NR; ++r) { + if (r >= nr) break; + device const q4_block_q8_0* br = w_q8 + ulong(r) * per + blk; + device const packed_ushort4* wp = reinterpret_cast(br->qs + half_off); + const ushort4 u0 = ushort4(wp[0]); + const ushort4 u1 = ushort4(wp[1]); + const float4 w0 = float4(as_type(u0.xy)); + const float4 w1 = float4(as_type(u0.zw)); + const float4 w2 = float4(as_type(u1.xy)); + const float4 w3 = float4(as_type(u1.zw)); + const float dw = float(br->d); + acc[r][0] = fma(dw * dx0, dot(w0, x00) + dot(w1, x01) + dot(w2, x02) + dot(w3, x03), acc[r][0]); + acc[r][1] = fma(dw * dx1, dot(w0, x10) + dot(w1, x11) + dot(w2, x12) + dot(w3, x13), acc[r][1]); + } + } + } else { + for (int start = int(tid) * 16; start < hc_dim; start += 128 * 16) { + const ulong blk = ulong(start >> 5); + const uint half_off = uint(start & 16); +#pragma clang loop unroll(full) + for (int r = 0; r < NR; ++r) { + if (r >= nr) break; + q4_down_q8_piece_multi(w_q8 + ulong(r) * per, blk, half_off, xn_xq, xn_row_bytes, rows, acc[r]); + } + } + } + } else if (WTYPE == 12) { + const uint nchunks = uint(hc_dim >> 5); // 8 chunks per 256-elem block + device const q4_block_q4_K* w_q4k = reinterpret_cast(w) + ulong(o0) * per; + if (MAX_T == 1) { + for (uint p = tid; p < nchunks; p += 128u) { + const uint blk = p >> 3u; + const uint j = (p >> 1u) & 3u; + const uint h = p & 1u; + const ulong x_off_lo = ulong(blk * 8u + j * 2u) * 36ul; + device const uchar* xbl = xn_xq + x_off_lo; + const float dxl = float(*reinterpret_cast(xbl)); + const uint4 xul = uint4(reinterpret_cast(xbl + 4u)[h]); + const float4 xl0 = float4(as_type(xul.x)), xl1 = float4(as_type(xul.y)); + const float4 xl2 = float4(as_type(xul.z)), xl3 = float4(as_type(xul.w)); + const float xsum_l = dot((xl0 + xl1) + (xl2 + xl3), float4(1.0f)); + + device const uchar* xbh = xbl + 36ul; + const float dxh = float(*reinterpret_cast(xbh)); + const uint4 xuh = uint4(reinterpret_cast(xbh + 4u)[h]); + const float4 xh0 = float4(as_type(xuh.x)), xh1 = float4(as_type(xuh.y)); + const float4 xh2 = float4(as_type(xuh.z)), xh3 = float4(as_type(xuh.w)); + const float xsum_h = dot((xh0 + xh1) + (xh2 + xh3), float4(1.0f)); + +#pragma clang loop unroll(full) + for (int r = 0; r < NR; ++r) { + if (r >= nr) break; + device const q4_block_q4_K* br = w_q4k + ulong(r) * per + ulong(blk); + float dl_l, ml_l, dl_h, ml_h; + q4_k4_hdr_decode(br, j, dl_l, ml_l, dl_h, ml_h); + const uint4 qv = uint4(*reinterpret_cast(br->qs + j * 32u + h * 16u)); + const float sdot_l = dot(float4(as_type(qv.x & 0x0F0F0F0Fu)), xl0) + + dot(float4(as_type(qv.y & 0x0F0F0F0Fu)), xl1) + + dot(float4(as_type(qv.z & 0x0F0F0F0Fu)), xl2) + + dot(float4(as_type(qv.w & 0x0F0F0F0Fu)), xl3); + const float sdot_h = dot(float4(as_type((qv.x >> 4u) & 0x0F0F0F0Fu)), xh0) + + dot(float4(as_type((qv.y >> 4u) & 0x0F0F0F0Fu)), xh1) + + dot(float4(as_type((qv.z >> 4u) & 0x0F0F0F0Fu)), xh2) + + dot(float4(as_type((qv.w >> 4u) & 0x0F0F0F0Fu)), xh3); + acc[r][0] = fma(dxl, fma(dl_l, sdot_l, ml_l * xsum_l), + fma(dxh, fma(dl_h, sdot_h, ml_h * xsum_h), acc[r][0])); + } + } + } else { + for (uint p = tid; p < nchunks; p += 128u) { + const uint blk = p >> 3u; + const uint j = (p >> 1u) & 3u; + const uint h = p & 1u; +#pragma clang loop unroll(full) + for (int r = 0; r < NR; ++r) { + if (r >= nr) break; + q4_down_q4k_row(w_q4k + ulong(r) * per + ulong(blk), blk, j, h, xn_xq, xn_row_bytes, rows, acc[r]); + } + } + } + } else { // WTYPE == 14 (Q6_K) + const uint nchunks = uint(hc_dim >> 5); // 8 chunks per 256-elem block + device const q4_block_q6_K* w_q6k = reinterpret_cast(w) + ulong(o0) * per; + if (MAX_T == 1) { + for (uint p = tid; p < nchunks; p += 128u) { + const uint blk = p >> 3u; + const uint sub = p & 7u; + const uint h = sub >> 2u; + const uint g = sub & 3u; + const uint is = g >> 1u; + const uint l0 = g * 8u; + const ulong xb_base = ulong(blk * 8u + h * 4u) * 36ul; + + device const uchar* xb0 = xn_xq + xb_base; + const float dx0 = float(*reinterpret_cast(xb0)); + const uint2 xu0 = uint2(*reinterpret_cast(xb0 + 4u + l0)); + device const uchar* xb1 = xb0 + 36ul; + const float dx1 = float(*reinterpret_cast(xb1)); + const uint2 xu1 = uint2(*reinterpret_cast(xb1 + 4u + l0)); + device const uchar* xb2 = xb0 + 72ul; + const float dx2 = float(*reinterpret_cast(xb2)); + const uint2 xu2 = uint2(*reinterpret_cast(xb2 + 4u + l0)); + device const uchar* xb3 = xb0 + 108ul; + const float dx3 = float(*reinterpret_cast(xb3)); + const uint2 xu3 = uint2(*reinterpret_cast(xb3 + 4u + l0)); + +#pragma clang loop unroll(full) + for (int r = 0; r < NR; ++r) { + if (r >= nr) break; + device const q4_block_q6_K* br = w_q6k + ulong(r) * per + ulong(blk); + const ushort4 ql0 = ushort4(*reinterpret_cast(br->ql + 64u * h + l0)); + const ushort4 ql1 = ushort4(*reinterpret_cast(br->ql + 64u * h + 32u + l0)); + const ushort4 qh0 = ushort4(*reinterpret_cast(br->qh + 32u * h + l0)); + const uint ql0_a = as_type(ql0.xy), ql0_b = as_type(ql0.zw); + const uint ql1_a = as_type(ql1.xy), ql1_b = as_type(ql1.zw); + const uint qh0_a = as_type(qh0.xy), qh0_b = as_type(qh0.zw); + const float d = float(br->d); + float psum = 0.0f; + psum = fma(d * float(br->scales[8u * h + is + 0u]) * dx0, + dot(float4(as_type((ql0_a & 0x0F0F0F0Fu) | ((qh0_a & 0x03030303u) << 4u)) - char4(32)), float4(as_type(xu0.x))) + + dot(float4(as_type((ql0_b & 0x0F0F0F0Fu) | ((qh0_b & 0x03030303u) << 4u)) - char4(32)), float4(as_type(xu0.y))), psum); + psum = fma(d * float(br->scales[8u * h + is + 2u]) * dx1, + dot(float4(as_type((ql1_a & 0x0F0F0F0Fu) | ((qh0_a & 0x0C0C0C0Cu) << 2u)) - char4(32)), float4(as_type(xu1.x))) + + dot(float4(as_type((ql1_b & 0x0F0F0F0Fu) | ((qh0_b & 0x0C0C0C0Cu) << 2u)) - char4(32)), float4(as_type(xu1.y))), psum); + psum = fma(d * float(br->scales[8u * h + is + 4u]) * dx2, + dot(float4(as_type(((ql0_a >> 4u) & 0x0F0F0F0Fu) | (qh0_a & 0x30303030u)) - char4(32)), float4(as_type(xu2.x))) + + dot(float4(as_type(((ql0_b >> 4u) & 0x0F0F0F0Fu) | (qh0_b & 0x30303030u)) - char4(32)), float4(as_type(xu2.y))), psum); + psum = fma(d * float(br->scales[8u * h + is + 6u]) * dx3, + dot(float4(as_type(((ql1_a >> 4u) & 0x0F0F0F0Fu) | ((qh0_a & 0xC0C0C0C0u) >> 2u)) - char4(32)), float4(as_type(xu3.x))) + + dot(float4(as_type(((ql1_b >> 4u) & 0x0F0F0F0Fu) | ((qh0_b & 0xC0C0C0C0u) >> 2u)) - char4(32)), float4(as_type(xu3.y))), psum); + acc[r][0] += psum; + } + } + } else if (MAX_T == 2) { + for (uint p = tid; p < nchunks; p += 128u) { + const uint blk = p >> 3u; + const uint sub = p & 7u; + const uint h = sub >> 2u; + const uint g = sub & 3u; + const uint is = g >> 1u; + const uint l0 = g * 8u; + const ulong xb_base = ulong(blk * 8u + h * 4u) * 36ul; + + device const uchar* xb0 = xn_xq + xb_base; + const float dx0_0 = float(*reinterpret_cast(xb0)); + const uint2 xu0_0 = uint2(*reinterpret_cast(xb0 + 4u + l0)); + const float dx1_0 = float(*reinterpret_cast(xb0 + 36ul)); + const uint2 xu1_0 = uint2(*reinterpret_cast(xb0 + 40u + l0)); + const float dx2_0 = float(*reinterpret_cast(xb0 + 72ul)); + const uint2 xu2_0 = uint2(*reinterpret_cast(xb0 + 76u + l0)); + const float dx3_0 = float(*reinterpret_cast(xb0 + 108ul)); + const uint2 xu3_0 = uint2(*reinterpret_cast(xb0 + 112u + l0)); + + device const uchar* xb1 = xb0 + xn_row_bytes; + const float dx0_1 = float(*reinterpret_cast(xb1)); + const uint2 xu0_1 = uint2(*reinterpret_cast(xb1 + 4u + l0)); + const float dx1_1 = float(*reinterpret_cast(xb1 + 36ul)); + const uint2 xu1_1 = uint2(*reinterpret_cast(xb1 + 40u + l0)); + const float dx2_1 = float(*reinterpret_cast(xb1 + 72ul)); + const uint2 xu2_1 = uint2(*reinterpret_cast(xb1 + 76u + l0)); + const float dx3_1 = float(*reinterpret_cast(xb1 + 108ul)); + const uint2 xu3_1 = uint2(*reinterpret_cast(xb1 + 112u + l0)); + +#pragma clang loop unroll(full) + for (int r = 0; r < NR; ++r) { + if (r >= nr) break; + device const q4_block_q6_K* br = w_q6k + ulong(r) * per + ulong(blk); + const ushort4 ql0 = ushort4(*reinterpret_cast(br->ql + 64u * h + l0)); + const ushort4 ql1 = ushort4(*reinterpret_cast(br->ql + 64u * h + 32u + l0)); + const ushort4 qh0 = ushort4(*reinterpret_cast(br->qh + 32u * h + l0)); + const uint ql0_a = as_type(ql0.xy), ql0_b = as_type(ql0.zw); + const uint ql1_a = as_type(ql1.xy), ql1_b = as_type(ql1.zw); + const uint qh0_a = as_type(qh0.xy), qh0_b = as_type(qh0.zw); + const float d = float(br->d); + { + const float sc = d * float(br->scales[8u * h + is + 0u]); + const float4 wa = float4(as_type((ql0_a & 0x0F0F0F0Fu) | ((qh0_a & 0x03030303u) << 4u)) - char4(32)); + const float4 wb = float4(as_type((ql0_b & 0x0F0F0F0Fu) | ((qh0_b & 0x03030303u) << 4u)) - char4(32)); + acc[r][0] = fma(sc * dx0_0, dot(wa, float4(as_type(xu0_0.x))) + dot(wb, float4(as_type(xu0_0.y))), acc[r][0]); + acc[r][1] = fma(sc * dx0_1, dot(wa, float4(as_type(xu0_1.x))) + dot(wb, float4(as_type(xu0_1.y))), acc[r][1]); + } + { + const float sc = d * float(br->scales[8u * h + is + 2u]); + const float4 wa = float4(as_type((ql1_a & 0x0F0F0F0Fu) | ((qh0_a & 0x0C0C0C0Cu) << 2u)) - char4(32)); + const float4 wb = float4(as_type((ql1_b & 0x0F0F0F0Fu) | ((qh0_b & 0x0C0C0C0Cu) << 2u)) - char4(32)); + acc[r][0] = fma(sc * dx1_0, dot(wa, float4(as_type(xu1_0.x))) + dot(wb, float4(as_type(xu1_0.y))), acc[r][0]); + acc[r][1] = fma(sc * dx1_1, dot(wa, float4(as_type(xu1_1.x))) + dot(wb, float4(as_type(xu1_1.y))), acc[r][1]); + } + { + const float sc = d * float(br->scales[8u * h + is + 4u]); + const float4 wa = float4(as_type(((ql0_a >> 4u) & 0x0F0F0F0Fu) | (qh0_a & 0x30303030u)) - char4(32)); + const float4 wb = float4(as_type(((ql0_b >> 4u) & 0x0F0F0F0Fu) | (qh0_b & 0x30303030u)) - char4(32)); + acc[r][0] = fma(sc * dx2_0, dot(wa, float4(as_type(xu2_0.x))) + dot(wb, float4(as_type(xu2_0.y))), acc[r][0]); + acc[r][1] = fma(sc * dx2_1, dot(wa, float4(as_type(xu2_1.x))) + dot(wb, float4(as_type(xu2_1.y))), acc[r][1]); + } + { + const float sc = d * float(br->scales[8u * h + is + 6u]); + const float4 wa = float4(as_type(((ql1_a >> 4u) & 0x0F0F0F0Fu) | ((qh0_a & 0xC0C0C0C0u) >> 2u)) - char4(32)); + const float4 wb = float4(as_type(((ql1_b >> 4u) & 0x0F0F0F0Fu) | ((qh0_b & 0xC0C0C0C0u) >> 2u)) - char4(32)); + acc[r][0] = fma(sc * dx3_0, dot(wa, float4(as_type(xu3_0.x))) + dot(wb, float4(as_type(xu3_0.y))), acc[r][0]); + acc[r][1] = fma(sc * dx3_1, dot(wa, float4(as_type(xu3_1.x))) + dot(wb, float4(as_type(xu3_1.y))), acc[r][1]); + } + } + } + } else { + for (uint p = tid; p < nchunks; p += 128u) { + const uint blk = p >> 3u; + const uint sub = p & 7u; + const uint h = sub >> 2u; + const uint g = sub & 3u; +#pragma clang loop unroll(full) + for (int r = 0; r < NR; ++r) { + if (r >= nr) break; + q4_down_q6k_row(w_q6k + ulong(r) * per + ulong(blk), blk, h, g, xn_xq, xn_row_bytes, rows, acc[r]); + } + } + } + } + + threadgroup float s_red[NR][MAX_T][4]; +#pragma clang loop unroll(full) + for (int r = 0; r < NR; ++r) { + if (r >= nr) break; +#pragma clang loop unroll(full) + for (int t = 0; t < MAX_T; ++t) { + if (t >= rows) break; + const float ws = simd_sum(acc[r][t]); + if (lane == 0u) s_red[r][t][warp] = ws; + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + + if (tid < uint(rows)) { + const float inv_hc = 1.0f / float(hc); +#pragma clang loop unroll(full) + for (int r = 0; r < NR; ++r) { + if (r >= nr) break; + const uint o = o0 + uint(r); + const float sum = (s_red[r][tid][0] + s_red[r][tid][1]) + (s_red[r][tid][2] + s_red[r][tid][3]); + if (o < uint(hc_lr)) { + const float v = sum * inv_hc; + lo[ulong(tid) * ulong(hc_lr) + ulong(o)] = v * q4_sig(v); + } else if (inject != nullptr) { + inject[ulong(tid) * ulong(hc) + ulong(o - uint(hc_lr))] = sum; + } + } + } +} + +// Tiny lock-free, fence-free follow-up kernel to quantize FP32 lo [rows, hc_lr] to Q8_1 when a caller requests lo_xq != nullptr. +// Grid: {rows, 1, 1}, Threads: 256 (8 SIMD groups calling q8_put directly). +kernel void q4_gr_lo_q8_kernel(constant Q4Args& a [[buffer(0)]], + uint t [[threadgroup_position_in_grid]], + uint tid [[thread_index_in_threadgroup]]) { + const int hc_lr = a.n[1]; + device const float* lo = static_cast(a.p[2]) + ulong(t) * ulong(hc_lr); + device uchar* lo_xq = static_cast(a.p[3]) + ulong(t) * ulong(hc_lr >> 5) * 36ul; + for (int k0 = 0; k0 < hc_lr; k0 += 256) { + const int k = k0 + int(tid); + if (k < hc_lr) { + q8_put(lo_xq, k, lo[k]); + } + } +} + +#define Q4_GR_DOWN_INST(name, wt) \ + template [[host_name("q4_gr_down_" #name "_r1")]] kernel decltype(q4_gr_down_silu_kernel) q4_gr_down_silu_kernel; \ + template [[host_name("q4_gr_down_" #name "_r2")]] kernel decltype(q4_gr_down_silu_kernel) q4_gr_down_silu_kernel; \ + template [[host_name("q4_gr_down_" #name "_r4")]] kernel decltype(q4_gr_down_silu_kernel) q4_gr_down_silu_kernel; \ + template [[host_name("q4_gr_down_" #name "_r8")]] kernel decltype(q4_gr_down_silu_kernel) q4_gr_down_silu_kernel; +Q4_GR_DOWN_INST(q8_0, 8) +Q4_GR_DOWN_INST(q4_K, 12) +Q4_GR_DOWN_INST(q6_K, 14) +#undef Q4_GR_DOWN_INST + +// ---- 9. Fused Attention Output Sigmoid Gate + Q8_1 Quantization ---- +// Mirrors q4_mul_sigmoid_q8_1_kernel in engine/src/poly/qwen4.cu. +// Grid: {ceil(n_head * head_dim / 256), rows, 1}, Threads: 256. + +kernel void q4_mul_sigmoid_q8_1_kernel(constant Q4Args& a [[buffer(0)]], + uint2 group [[threadgroup_position_in_grid]], + uint tid [[thread_index_in_threadgroup]]) { + const int head_dim = a.n[0]; + const int n_head = a.n[1]; + const int d_inner = n_head * head_dim; + const int idx = int(group.x * 256u + tid); + if (idx >= d_inner) return; + const int t = int(group.y); + const int h = idx / head_dim; + const int d = idx - h * head_dim; + device const float* att = static_cast(a.p[0]); + device const float* qg = static_cast(a.p[1]); + device uchar* q8 = static_cast(a.p[2]); + const ulong att_i = ulong(t) * ulong(d_inner) + ulong(idx); + const ulong g_i = (ulong(t) * ulong(n_head) + ulong(h)) * ulong(2 * head_dim) + ulong(head_dim + d); + const float y = att[att_i] / (1.0f + exp(-qg[g_i])); + q8_put(q8 + ulong(t) * ulong(d_inner >> 5) * 36ul, idx, y); +} diff --git a/engine/src/poly/engine.cpp b/engine/src/poly/engine.cpp index 0da6fe0bf..f8a951c1e 100644 --- a/engine/src/poly/engine.cpp +++ b/engine/src/poly/engine.cpp @@ -7588,39 +7588,50 @@ bool Engine::moe_card(Layer& L, int il, int n, bool defer_active, int prev_il, i void* const grp = (n > 1 && rr <= 64 && d_grp_) ? d_grp_ : nullptr; #endif if (grp) kernels::native_mmvq_ids_group(d_ids_, rr, grp, st_); - // a mixed layer's gate and up are each a matrix of n_ff rows of its own type, up's into the second half - const kernels::MmvqIds gate_up{table, d_ids_, 0, xq_, xq_row, n_used_, g_, 2 * ff, lane_slots_, grp, grp != nullptr}; - kernels::native_mmvq_ids((int) L.gu_type, gate_up, rr, n_embd_, L.mixed() ? n_ff_exp_ : 2 * n_ff_exp_, st_); - if (L.mixed()) { - const kernels::MmvqIds up{table, d_ids_, L.gu_bytes, xq_, xq_row, n_used_, g_ + ff, 2 * ff, lane_slots_, grp, - grp != nullptr}; - kernels::native_mmvq_ids((int) L.u_type, up, rr, n_embd_, n_ff_exp_, st_); - } - const ExpertScales es = expert_scales(L, d_ids_); -#if !defined(STRATA_GPU_METAL) - const bool fused_swiglu_q8 = swiglu_q8_ && !(situ_beta_ > 0) && !gelu_ && (n_ff_exp_ % 32 == 0); -#endif - // SiTU's rows come out quantized too (situ_rows()), the bytes native_quantize_q8_1() gives them bool fused_q8 = false; - if (situ_beta_ > 0) { - situ_rows(g_, h_, n_ff_exp_, rr, situ_beta_, situ_lb_, st_, q8_, &es); - fused_q8 = true; - } else if (gelu_) { - geglu_rows(g_, h_, n_ff_exp_, rr, st_, &es); - } else { #if defined(STRATA_GPU_METAL) - if ((!std::isfinite(clamp_exp_[(size_t) il]) || clamp_exp_[(size_t) il] <= 0.f) && - L.h_s_gate.empty() && L.h_s_up.empty() && (n_ff_exp_ % 32 == 0)) { - swiglu_rows_quantize_q8_1(g_, q8_, n_ff_exp_, rr, st_); + if (opt_.metal_optimize && !L.mixed() && !(situ_beta_ > 0) && !gelu_ && + (!std::isfinite(clamp_exp_[(size_t) il]) || clamp_exp_[(size_t) il] <= 0.f) && + L.h_s_gate.empty() && L.h_s_up.empty() && (n_ff_exp_ % 32 == 0)) { + const kernels::MmvqIdsGuSwiglu gu{table, d_ids_, 0, L.gu_bytes, xq_, xq_row, n_used_, + q8_, grp, grp != nullptr}; + fused_q8 = kernels::native_mmvq_ids_gu_swiglu_q8((int) L.gu_type, gu, rr, n_embd_, n_ff_exp_, st_); + } +#endif + if (!fused_q8) { + // a mixed layer's gate and up are each a matrix of n_ff rows of its own type, up's into the second half + const kernels::MmvqIds gate_up{table, d_ids_, 0, xq_, xq_row, n_used_, g_, 2 * ff, lane_slots_, grp, grp != nullptr}; + kernels::native_mmvq_ids((int) L.gu_type, gate_up, rr, n_embd_, L.mixed() ? n_ff_exp_ : 2 * n_ff_exp_, st_); + if (L.mixed()) { + const kernels::MmvqIds up{table, d_ids_, L.gu_bytes, xq_, xq_row, n_used_, g_ + ff, 2 * ff, lane_slots_, grp, + grp != nullptr}; + kernels::native_mmvq_ids((int) L.u_type, up, rr, n_embd_, n_ff_exp_, st_); + } + const ExpertScales es = expert_scales(L, d_ids_); +#if !defined(STRATA_GPU_METAL) + const bool fused_swiglu_q8 = swiglu_q8_ && !(situ_beta_ > 0) && !gelu_ && (n_ff_exp_ % 32 == 0); +#endif + // SiTU's rows come out quantized too (situ_rows()), the bytes native_quantize_q8_1() gives them + if (situ_beta_ > 0) { + situ_rows(g_, h_, n_ff_exp_, rr, situ_beta_, situ_lb_, st_, q8_, &es); fused_q8 = true; - } else + } else if (gelu_) { + geglu_rows(g_, h_, n_ff_exp_, rr, st_, &es); + } else { +#if defined(STRATA_GPU_METAL) + if ((!std::isfinite(clamp_exp_[(size_t) il]) || clamp_exp_[(size_t) il] <= 0.f) && + L.h_s_gate.empty() && L.h_s_up.empty() && (n_ff_exp_ % 32 == 0)) { + swiglu_rows_quantize_q8_1(g_, q8_, n_ff_exp_, rr, st_); + fused_q8 = true; + } else #else - if (fused_swiglu_q8) { - swiglu_clamp_q8_rows(g_, q8_, n_ff_exp_, rr, clamp_exp_[(size_t) il], st_, &es); - fused_q8 = true; - } else + if (fused_swiglu_q8) { + swiglu_clamp_q8_rows(g_, q8_, n_ff_exp_, rr, clamp_exp_[(size_t) il], st_, &es); + fused_q8 = true; + } else #endif - swiglu_clamp_rows(g_, h_, n_ff_exp_, rr, clamp_exp_[(size_t) il], st_, &es); + swiglu_clamp_rows(g_, h_, n_ff_exp_, rr, clamp_exp_[(size_t) il], st_, &es); + } } // the down product's scales on the weights; a family that sums the experts later multiplies them there moe_left_scale_ = moe_sum_later(n) && !L.h_s_down.empty() ? fp(L.s_down) : nullptr; diff --git a/engine/src/poly/qwen4.cpp b/engine/src/poly/qwen4.cpp index 73fb10286..c91e076d4 100644 --- a/engine/src/poly/qwen4.cpp +++ b/engine/src/poly/qwen4.cpp @@ -886,9 +886,9 @@ void Qwen4::alloc_caches() { (size_t) std::max({16, (hc_lr_ + 31) / 32, (n_embd_ + 31) / 32}) * sizeof(unsigned); gr_q8_cnt_ = (unsigned*) dmalloc(cnt_bytes, "GR Q8_1 counters"); zero_vram(gr_q8_cnt_, cnt_bytes); +#endif if (hc_lr_ % 32 == 0) gr_lo_q8_ = dmalloc(8 * kernels::native_q8_1_bytes(hc_lr_), "GR lo Q8_1 scratch"); -#endif upload_loop_adapter(); } @@ -1133,12 +1133,25 @@ void Qwen4::gr_finish(const GrWeights& w, bool q_first, float* out_mixed, void* return d.p && d.type != kTypeF32 && d.type != kTypeBF16 && !(mmq_ && n >= kStageRows && Mmq::fits((int) d.type, d.n_out, d.n_in)); }; +#if defined(STRATA_GPU_METAL) + const bool metal_up_f32 = + opt_.metal_optimize && n >= 1 && n <= 8 && hc_ == 4 && hc_lr_ == 256 && + n_embd_ > 0 && (n_embd_ % 32 == 0) && w.up.p && w.up.scale == 1.0f && + (w.up.type == 14u || w.up.type == 8u || w.up.type == 12u); + const bool q_up = !metal_up_f32 && needs_q8(w.up) && (hc_lr_ % 32 == 0); +#else const bool q_up = needs_q8(w.up) && (hc_lr_ % 32 == 0); +#endif void* lo_xq_buf = q_up ? q8_ : nullptr; -#if !defined(STRATA_GPU_METAL) bool down_done = false; - if (n >= 1 && n <= 8 && gr_q8_cnt_) { + const bool try_down = +#if defined(STRATA_GPU_METAL) + opt_.metal_optimize && (n >= 1 && n <= 8); +#else + (n >= 1 && n <= 8 && gr_q8_cnt_ != nullptr); +#endif + if (try_down) { void* const dst_lo_q8 = q_up ? gr_lo_q8_ : nullptr; if (w.down_inject.p && w.down_inject.scale == 1.0f && (!q_up || dst_lo_q8)) { down_done = q4_gr_down_silu_quant((int) w.down_inject.type, w.down_inject.p, @@ -1154,9 +1167,7 @@ void Qwen4::gr_finish(const GrWeights& w, bool q_first, float* out_mixed, void* if (down_done) lo_xq_buf = dst_lo_q8; } } - if (!down_done) -#endif - { + if (!down_done) { if (w.down_inject.p) { lin(w.down_inject, gr_xn_, gr_lo_inj_, n, q_first ? q8_ : nullptr); q4_gr_split_silu_quant(gr_lo_inj_, gr_lo_, lo_xq_buf, out_inj, hc_lr_, hc_, n, st_); @@ -1175,8 +1186,9 @@ void Qwen4::gr_finish(const GrWeights& w, bool q_first, float* out_mixed, void* return; } #else - if (q_up && w.up.scale == 1.0f && opt_.metal_optimize && - q4_gr_up_gate_mean_quant(w.up.p, (int) w.up.type, lo_xq_buf, gr_xn_, out_mixed, out_xq, n_embd_, hc_, hc_lr_, n, st_)) { + if (metal_up_f32 && + q4_gr_up_gate_mean_quant((int) w.up.type, w.up.p, nullptr, gr_lo_, gr_xn_, out_mixed, out_xq, nullptr, + n_embd_, hc_, hc_lr_, n, st_)) { return; } #endif @@ -2101,16 +2113,17 @@ void Qwen4::attn_run_stream(Block& B, CacheSlot& S, int slot_idx, int64_t pos, i } else { attn_stream_dense(S, slot_idx, pos, n, q_, att_); } -#if !defined(STRATA_GPU_METAL) - const bool q_wo = B.wo.p && B.wo.type != kTypeF32 && B.wo.type != kTypeBF16 && - !(mmq_ && n >= kStageRows && Mmq::fits((int) B.wo.type, B.wo.n_out, B.wo.n_in)) && - ((n_head_ * head_dim_) % 32 == 0); + const bool q_wo = +#if defined(STRATA_GPU_METAL) + opt_.metal_optimize && +#endif + B.wo.p && B.wo.type != kTypeF32 && B.wo.type != kTypeBF16 && + !(mmq_ && n >= kStageRows && Mmq::fits((int) B.wo.type, B.wo.n_out, B.wo.n_in)) && + ((n_head_ * head_dim_) % 32 == 0); if (q_wo) { q4_mul_sigmoid_q8_1(att_, qg_, q8_, head_dim_, n_head_, n, st_); lin(B.wo, att_, ao_, n, q8_); - } else -#endif - { + } else { mul_sigmoid(att_, qg_ + head_dim_, head_dim_, n * n_head_, 2 * head_dim_, false, st_); lin(B.wo, att_, ao_, n); } @@ -2292,16 +2305,17 @@ void Qwen4::attn_basinkv(Block& B, CacheSlot& S, int, int64_t pos, int n) { if (prime_cap > 0) basinkv_->submit_lookahead_f32(S.basin_layer, q_last, st_, prime_cap); } -#if !defined(STRATA_GPU_METAL) - const bool q_wo = B.wo.p && B.wo.type != kTypeF32 && B.wo.type != kTypeBF16 && - !(mmq_ && n >= kStageRows && Mmq::fits((int) B.wo.type, B.wo.n_out, B.wo.n_in)) && - ((n_head_ * head_dim_) % 32 == 0); + const bool q_wo = +#if defined(STRATA_GPU_METAL) + opt_.metal_optimize && +#endif + B.wo.p && B.wo.type != kTypeF32 && B.wo.type != kTypeBF16 && + !(mmq_ && n >= kStageRows && Mmq::fits((int) B.wo.type, B.wo.n_out, B.wo.n_in)) && + ((n_head_ * head_dim_) % 32 == 0); if (q_wo) { q4_mul_sigmoid_q8_1(att_, qg_, q8_, head_dim_, n_head_, n, st_); lin(B.wo, att_, ao_, n, q8_); - } else -#endif - { + } else { mul_sigmoid(att_, qg_ + head_dim_, head_dim_, n * n_head_, 2 * head_dim_, false, st_); lin(B.wo, att_, ao_, n); } @@ -2392,16 +2406,17 @@ void Qwen4::attn(Block& B, CacheSlot& S, int il, int64_t pos, int n) { 0, 0, false, at, at ? room(n) : 0, 0, kq8, vq8, nullptr, score_floats_); } -#if !defined(STRATA_GPU_METAL) - const bool q_wo = B.wo.p && B.wo.type != kTypeF32 && B.wo.type != kTypeBF16 && - !(mmq_ && n >= kStageRows && Mmq::fits((int) B.wo.type, B.wo.n_out, B.wo.n_in)) && - ((n_head_ * head_dim_) % 32 == 0); + const bool q_wo = +#if defined(STRATA_GPU_METAL) + opt_.metal_optimize && +#endif + B.wo.p && B.wo.type != kTypeF32 && B.wo.type != kTypeBF16 && + !(mmq_ && n >= kStageRows && Mmq::fits((int) B.wo.type, B.wo.n_out, B.wo.n_in)) && + ((n_head_ * head_dim_) % 32 == 0); if (q_wo) { q4_mul_sigmoid_q8_1(att_, qg_, q8_, head_dim_, n_head_, n, st_); lin(B.wo, att_, ao_, n, q8_); - } else -#endif - { + } else { mul_sigmoid(att_, qg_ + head_dim_, head_dim_, n * n_head_, 2 * head_dim_, false, st_); lin(B.wo, att_, ao_, n); } @@ -2534,16 +2549,17 @@ void Qwen4::attn_rows(Block& B, CacheSlot& S, int, int n) { n_kv_, attn_scale_, st_, 0, 0, false, ai, sized, 0, kq, vq); } } -#if !defined(STRATA_GPU_METAL) - const bool q_wo = B.wo.p && B.wo.type != kTypeF32 && B.wo.type != kTypeBF16 && - !(mmq_ && n >= kStageRows && Mmq::fits((int) B.wo.type, B.wo.n_out, B.wo.n_in)) && - ((n_head_ * head_dim_) % 32 == 0); + const bool q_wo = +#if defined(STRATA_GPU_METAL) + opt_.metal_optimize && +#endif + B.wo.p && B.wo.type != kTypeF32 && B.wo.type != kTypeBF16 && + !(mmq_ && n >= kStageRows && Mmq::fits((int) B.wo.type, B.wo.n_out, B.wo.n_in)) && + ((n_head_ * head_dim_) % 32 == 0); if (q_wo) { q4_mul_sigmoid_q8_1(att_, qg_, q8_, head_dim_, n_head_, n, st_); lin(B.wo, att_, ao_, n, q8_); - } else -#endif - { + } else { mul_sigmoid(att_, qg_ + head_dim_, head_dim_, n * n_head_, 2 * head_dim_, false, st_); lin(B.wo, att_, ao_, n); } diff --git a/engine/src/poly/qwen4_kernels.hpp b/engine/src/poly/qwen4_kernels.hpp index 6aab9ce81..737d53eb3 100644 --- a/engine/src/poly/qwen4_kernels.hpp +++ b/engine/src/poly/qwen4_kernels.hpp @@ -136,15 +136,39 @@ void q4_gdn_decode_fused(const float* qkv_gate, const float* beta_alpha, const f float eps, void* stream, float* snap_past = nullptr, float* snap_state = nullptr, size_t stride = 0, unsigned snaps = 0); +/// Fused GR down(+inject) GEMV + split + SiLU(/hc) + optional Q8_1 quantization of lo (rows in 1..8). +/// CUDA/HIP supports Q8_0 (8), Q6_K (14, hc_dim % 256 == 0), and BF16 (30, hc_dim % 8 == 0). +/// Metal supports Q8_0 (8), Q4_K (12, hc_dim % 256 == 0), and Q6_K (14, hc_dim % 256 == 0), lock- and fence-free. +/// On CUDA/HIP, when lo_xq != nullptr, q8_cnt must point to >= (hc_lr / 32) zero-initialized uint32 counters. +/// On Metal, q8_cnt is unused (lo_xq is quantized via a follow-up fence-free launch when non-null). +/// Returns false (nothing launched) if the weight type or geometry is outside the fused fast path. +bool q4_gr_down_silu_quant(int w_type, const void* w, const void* xn_xq, const float* xn_f32, + float* lo, void* lo_xq, float* inject, unsigned* q8_cnt, + int hc_dim, int hc_lr, int hc, bool has_inject, int rows, void* stream); + +/// Fused GR up GEMV + sigmoid gate + stream mean + optional Q8_1 quantization of mixed (rows in 1..8). +/// Eliminates the [rows, hc * n_embd] gr_gate_ DRAM round-trip and separate gate_mean launch. +/// CUDA/HIP supports Q6_K (14, hc_lr % 256 == 0), Q8_0 (8, hc_lr % 32 == 0), and BF16 (30, hc_lr % 8 == 0); +/// when mixed_xq != nullptr on CUDA/HIP, q8_cnt must point to >= (n_embd / 32) zero-initialized uint32 counters. +/// Metal supports hc == 4, hc_lr == 256, n_embd % 32 == 0, w_type in {Q6_K (14), Q8_0 (8), Q4_K (12)}, +/// preferring direct FP32 lo_f32 when non-null (eliminating lo Q8_1 quantization) and falling back to lo_xq; +/// q8_cnt is unused on Metal. +/// Returns false (nothing launched) if the weight type or geometry is outside the fused fast path. +bool q4_gr_up_gate_mean_quant(int w_type, const void* w_up, const void* lo_xq, const float* lo_f32, + const float* xn, float* mixed, void* mixed_xq, unsigned* q8_cnt, + int n_embd, int hc, int hc_lr, int rows, void* stream); + +/// Fused attention output gate (att * sigmoid(qg + head_dim)) + Q8_1 quantization directly into q8 for B.wo. +/// Bitwise identical to mul_sigmoid(att, qg + head_dim, head_dim, rows * n_head, 2 * head_dim, false) followed by +/// native_quantize_q8_1(att, q8, n_head * head_dim, rows). +void q4_mul_sigmoid_q8_1(const float* att, const float* qg, void* q8, int head_dim, int n_head, int rows, void* stream); + #if defined(STRATA_GPU_METAL) /// Fused shared-expert scalar gate + in-place scale: for each row t in [0, rows), computes /// s = sigmoid(dot(w_gate, xn[t])) and scales fo[t, :] *= s in one launch. void q4_shexp_gate_mul(const float* w_gate, const float* xn, float* fo, int n_embd, int rows, void* stream); -/// Fused GR up-projection + sigmoid gate + hc-stream mean + optional Q8_1 quantization on Metal: -/// replaces lin(w_up, gr_lo, gr_gate, rows, q_up) + q4_gr_gate_mean_quant(gr_xn, gr_gate, out, out_xq, ...). -/// Supported for hc == 4, hc_lr == 256, rows in 1..8, n_embd % 32 == 0, w_type in {Q6_K (14), Q8_0 (8), Q4_K (12)}. -/// Returns true if launched, false to fall back to separate lin + q4_gr_gate_mean_quant. +/// Legacy Metal overload taking quantized Q8_1 lo directly (forwards to the unified overload above). bool q4_gr_up_gate_mean_quant(const void* w_up, int w_type, const void* lo_q8, const float* gr_xn, float* out, void* out_xq, int n_embd, int hc, int hc_lr, int rows, void* stream); #else @@ -154,24 +178,6 @@ bool q4_gr_up_gate_mean_quant(const void* w_up, int w_type, const void* lo_q8, c /// Bitwise identical to swiglu_clamp(gate, up, h, rows * n, limit) followed by native_quantize_q8_1(h, q8, rows * n, 1). void q4_swiglu_clamp_q8_1(const float* gate, const float* up, void* q8, int n, int rows, float limit, void* stream); -/// Fused GR down(+inject) GEMV + split + SiLU(/hc) + optional Q8_1 quantization of lo (rows in 1..8). -/// Supports Q8_0 (type=8), Q6_K (type=14, hc_dim % 256 == 0), and BF16 (type=30, hc_dim % 8 == 0). -/// Returns false (nothing launched) if the weight type or geometry is outside the fused fast path. -/// When lo_xq != nullptr, q8_cnt must point to >= (hc_lr / 32) zero-initialized uint32 counters (self-resetting). -bool q4_gr_down_silu_quant(int w_type, const void* w, const void* xn_xq, const float* xn_f32, - float* lo, void* lo_xq, float* inject, unsigned* q8_cnt, - int hc_dim, int hc_lr, int hc, bool has_inject, int rows, void* stream); - -/// Fused GR up GEMV + sigmoid gate + stream mean + optional Q8_1 quantization of mixed (rows in 1..8). -/// Eliminates the [rows, hc * n_embd] gr_gate_ DRAM round-trip and separate gate_mean launch. -/// Uses 4 columns per block (n_embd / 4 blocks) to saturate high-SM GPUs (RTX 4090/5090). -/// Supports Q6_K (type=14, hc_lr % 256 == 0), Q8_0 (type=8, hc_lr % 32 == 0), and BF16 (type=30, hc_lr % 8 == 0). -/// When mixed_xq != nullptr, q8_cnt must point to >= (n_embd / 32) zero-initialized uint32 counters (self-resetting). -/// Returns false (nothing launched) if the weight type or geometry is outside the fused fast path. -bool q4_gr_up_gate_mean_quant(int w_type, const void* w_up, const void* lo_xq, const float* lo_f32, - const float* xn, float* mixed, void* mixed_xq, unsigned* q8_cnt, - int n_embd, int hc, int hc_lr, int rows, void* stream); - /// Fused MoE combine + GR tail write + optional DFlash2 HC mean tap: /// 1) fo_i = fo[t, i] * sigmoid(sg[t]) + sum_k (w[t,k] * down_scale[ids[t,k]]) * d[t,k,i] /// 2) r[t, c, i] = fmaf(fo_i, 2 * sigmoid(inject[t, c] / hc), r[t, c, i]) for c = 0..hc-1 @@ -182,11 +188,6 @@ void q4_moe_combine_gr_write(float* r, const float* fo, const float* sg, const f const float* inject, float* tap_out, int64_t tap_stride, int n_embd, int n_used, int hc, int rows, void* stream); -/// Fused attention output gate (att * sigmoid(qg + head_dim)) + Q8_1 quantization directly into q8 for B.wo. -/// Bitwise identical to mul_sigmoid(att, qg + head_dim, head_dim, rows * n_head, 2 * head_dim, false) followed by -/// native_quantize_q8_1(att, q8, n_head * head_dim, rows). -void q4_mul_sigmoid_q8_1(const float* att, const float* qg, void* q8, int head_dim, int n_head, int rows, void* stream); - // ---- 7. Opt-in Looped Qwen4 Cross-Pass Bridge Kernels (v3 & Open-Channel v4 delta_rms_match) ---- /// Prepares HCWorkspaceEntry inputs for [rows, hc, n_embd]: