From fcb0728dcbff46be905a898996efa97198680157 Mon Sep 17 00:00:00 2001 From: shoudi zheng <434782114@qq.com> Date: Sun, 6 Dec 2026 13:55:31 +0800 Subject: [PATCH] [Engine] metal: high-bandwidth short4/TG-LUT decode GEMV for Q5_K/Q6_K/Q4_K/IQ2/IQ3 --- engine/metal/poly_tests/mv_bench.cpp | 146 ++- engine/metal/poly_tests/mv_parity.cpp | 17 +- engine/metal/poly_tests/quantized_parity.cpp | 241 ++++- engine/metal/src/poly/quantized.cpp | 105 ++- engine/metal/src/poly/quantized.metal | 914 +++++++++++++++++-- 5 files changed, 1338 insertions(+), 85 deletions(-) diff --git a/engine/metal/poly_tests/mv_bench.cpp b/engine/metal/poly_tests/mv_bench.cpp index f43b78e2f3..ff3e649255 100644 --- a/engine/metal/poly_tests/mv_bench.cpp +++ b/engine/metal/poly_tests/mv_bench.cpp @@ -1,6 +1,6 @@ // metal/poly_tests/mv_bench.cpp - one token's quantized products (poly_mul) on the shapes of a decode step: the experts // of a token (8 of them, by expert ids) and a dense projection, for every type poly_mul has. Not a test: run by hand. -// poly_mv_bench [reps (at least; enough for 20 ms a column), default 200 [types "8,22,19,..." [shapes inkling|qwen|sweep|dense|prompt|many, +// poly_mv_bench [reps (at least; enough for 20 ms a column), default 200 [types "8,22,19,..." [shapes inkling|qwen|qwen4|sweep|dense|prompt|many, // default inkling and qwen [rounds, default 5]]]] // inkling: Inkling 2 Mini (2,304 wide, experts of 2,304 x 1,152 with their gate and up in one call, downs of 1,152); // qwen: Qwen3.6-35B-A3B (2,048 wide, experts of 2,048 x 512). Each call reads other experts or another copy of the @@ -46,6 +46,150 @@ int main(int argc,char** argv){ const std::string source=blocks+"#define MV_DEQ\n"+md::read_source(STRATA_POLY_QUANT_SOURCE); const std::string old_source=old?blocks+"#define NVFP4_ROWS 4\n"+md::read_source(old):""; g::Stream s;ck(g::stream_create(&s));g::metal::set_optimize(true); + if(only=="qwen4"){ + auto make_quant_rows=[](int type,int ni,int no){ + const size_t rb=k::native_mmvq_weight_bytes(type,ni,1); + const int sample=std::min(no,512); + std::vector head(rb*sample); + if(type==40){ + std::mt19937 rng(40); + for(size_t i=0;i wf(size_t(sample)*ni); + for(size_t i=0;i imp(ni,1.0f); + ggml_quantize_chunk(gt,wf.data(),head.data(),0,sample,ni,imp.data()); + } + std::vector out(rb*no); + for(int r=0;r64 MiB). + const int copies=per>(64ull<<20)?1:std::clamp(int((40ull<<20)/std::max(per,1)),2,16); + auto one=make_quant_rows(c.type,c.ni,c.no); + Buffer dw(per*copies); + for(int e=0;e(dw.ptr)+per*e,one.data(),per,g::kHostToDevice)); + Buffer dx(values(size_t(c.rows)*c.ni)),q(k::native_q8_1_bytes(c.ni,c.rows)),y(size_t(c.rows)*c.no*4); + k::native_quantize_q8_1(dx.as(),q.ptr,c.ni,c.rows,s); + ck(g::stream_synchronize(s)); + auto run_one=[&](bool opt,int i){ + g::metal::set_optimize(opt); + const void* w=static_cast(dw.ptr)+per*(i%copies); + k::native_mmvq(c.type,w,q.ptr,y.as(),c.ni,c.no,c.rows,s); + }; + // Warmup & parity check opt=0 vs opt=1 + run_one(false,0);ck(g::stream_synchronize(s)); + auto ref=y.read(size_t(c.rows)*c.no); + run_one(true,0);ck(g::stream_synchronize(s)); + auto got=y.read(size_t(c.rows)*c.no); + float top=0,mdiff=0; + for(size_t i=0;i=25 ms + int reps=std::max(10,std::min(reps0,200)); + const auto t0=std::chrono::steady_clock::now(); + for(int i=0;i(std::chrono::steady_clock::now()-t0).count(); + if(us0<25000) reps=std::min(kMaxReps,int(reps*25000.0/std::max(us0,1.0))+1); + else if(us0>100000) reps=std::max(8,int(reps*40000.0/us0)); + double best[2]={1e30,1e30}; + for(int r=0;r(std::chrono::steady_clock::now()-a0).count()/reps); + } + const double bytes=double(per)+double(k::native_q8_1_bytes(c.ni,c.rows))+4.0*double(c.no)*c.rows; + char sh[32];std::snprintf(sh,sizeof sh,"%d->%d r=%d",c.ni,c.no,c.rows); + std::printf("%-10s %-20s %8.1f %8.1f %9.2f %9.2f %7s\n", + ggml_type_name(ggml_type(c.type)),sh,best[0],best[1], + bytes/best[0]/1e3,bytes/best[1]/1e3,ok?"OK":"FAIL"); + std::fflush(stdout); + } + // MoE k1 (count=8, [512->2048] down & [2048->512] gate/up) + std::printf("\n%-10s %-20s %8s %8s %9s %9s %7s\n", + "type","moe shape","opt0 us","opt1 us","opt0 GB/s","opt1 GB/s","check"); + for(int type:{17,22,18,12}){ + if(!want_type(type)) continue; + struct MoeCase{const char* tag;int ni,no,count;}; + const MoeCase mcs[]={ + {"k1 512->2048 c=8",512,2048,8}, + {"k1 2048->512 c=8",2048,512,8}, + }; + for(const MoeCase& mc:mcs){ + const size_t per=k::native_mmvq_weight_bytes(type,mc.ni,mc.no); + const int copies=std::clamp(int((40ull<<20)/std::max(per,1)),16,128); + auto one=make_quant_rows(type,mc.ni,mc.no); + Buffer dw(per*copies); + for(int e=0;e(dw.ptr)+per*e,one.data(),per,g::kHostToDevice)); + std::vector table(copies); + for(int e=0;e(dw.ptr)+per*e; + Buffer tab(copies*sizeof(void*)),di(size_t(kMaxReps+2)*mc.count*4); + tab.put(table.data(),copies*sizeof(void*)); + std::vector ids(size_t(kMaxReps+2)*mc.count); + for(size_t i=0;i(),di.as()+size_t(i)*mc.count,0,q.ptr, + k::native_q8_1_bytes(mc.ni),1,y.as(),size_t(mc.no)}; + k::native_mmvq_ids(type,a,mc.count,mc.ni,mc.no,s); + }; + run_moe(false,0);ck(g::stream_synchronize(s)); + auto ref=y.read(size_t(mc.count)*mc.no); + run_moe(true,0);ck(g::stream_synchronize(s)); + auto got=y.read(size_t(mc.count)*mc.no); + float top=0,mdiff=0; + for(size_t i=0;i(std::chrono::steady_clock::now()-t0).count(); + if(us0<25000) reps=std::min(kMaxReps,int(reps*25000.0/std::max(us0,1.0))+1); + double best[2]={1e30,1e30}; + for(int r=0;r(std::chrono::steady_clock::now()-a0).count()/reps); + } + const double bytes=double(per)*mc.count+double(k::native_q8_1_bytes(mc.ni,mc.count))+4.0*double(mc.no)*mc.count; + std::printf("%-10s %-20s %8.1f %8.1f %9.2f %9.2f %7s\n", + ggml_type_name(ggml_type(type)),mc.tag,best[0],best[1], + bytes/best[0]/1e3,bytes/best[1]/1e3,ok?"OK":"FAIL"); + std::fflush(stdout); + } + } + ck(g::stream_destroy(s));ggml_quantize_free();return 0; + } struct Shape{const char* model;const char* name;int ni,no,used,copies,xr=1;}; // used 0: a dense matrix; xr: the rows of x const Shape ink[]={{"inkling","experts gate|up",2304,2304,8,64},{"inkling","experts down",1152,2304,8,64}, {"inkling","dense 2304->4096",2304,4096,0,32},{"inkling","dense 4096->2304",4096,2304,0,32}}; diff --git a/engine/metal/poly_tests/mv_parity.cpp b/engine/metal/poly_tests/mv_parity.cpp index 8a61ebe18a..443b96a845 100644 --- a/engine/metal/poly_tests/mv_parity.cpp +++ b/engine/metal/poly_tests/mv_parity.cpp @@ -70,12 +70,17 @@ int main(int argc,char** argv){ } } } - // native_mmvq_many: five matrices of a type (Inkling 2's q, k, v, relative positions' and gate's outputs, and a - // launch of fewer outputs), three inputs among them, in one launch, against the five native_mmvq() calls: the same - // bits. Q8_0 also at Inkling 2's width. - for(int type:types)for(int ni:{256,2304})for(bool big:{true,false}){ + // native_mmvq_many: five matrices of a type (Inkling 2's q, k, v, relative positions' and gate's outputs, a launch + // of fewer outputs, and an unaligned-tail launch crossing NR=2/NR=4 thresholds), three inputs among them, in one + // launch, against the five native_mmvq() calls: the same bits. Q8_0 also at Inkling 2's width. + for(int type:types)for(int ni:{256,2304})for(int mode:{0,1,2}){ if(ni%int(ggml_blck_size(ggml_type(type))) || (ni==2304 && type!=8))continue; - const int outs[5]={big?3072:96,big?1024:32,big?1024:32,big?384:12,big?3072:96},from[5]={0,1,2,0,0}; + if(mode==2 && ni==2304)continue; + const int outs[5]={mode==0?3072:(mode==1?96:2052), mode==0?1024:(mode==1?32:516), + mode==0?1024:(mode==1?32:13), mode==0?384:(mode==1?12:7), + mode==0?3072:(mode==1?96:1)}; + const int from[5]={0,1,2,0,0}; + const int total_out=outs[0]+outs[1]+outs[2]+outs[3]+outs[4]; k::NativeMmvqMany m{};std::vector> keep; auto xs=values(3*ni,.8f);Buffer dx(xs),qx(3*k::native_q8_1_bytes(ni)); k::native_quantize_q8_1(dx.as(),qx.ptr,ni,3,stream); @@ -97,7 +102,7 @@ int main(int argc,char** argv){ for(int j=0;j<5;++j){auto got=ys[j]->read(outs[j]),want=refs[j]->read(outs[j]);n+=got.size(); for(int i=0;i +#include +#include namespace k=strata::kernels; namespace p=strata::poly; // The rows' values as Mmq::mul() saw them: q8_1 decoded, or fp16 on the matrix-unit path @@ -419,7 +421,7 @@ int main(){ std::memcpy(&d, sqb.data() + (i / 32) * 36, 2); sxq[i] = float(d) * reinterpret_cast(sqb.data())[(i / 32) * 36 + 4 + i % 32]; } - for (int stype : {8, 13, 14}) { // q8_0, q5_K, q6_K + for (int stype : {8, 12, 13, 14}) { // q8_0, q4_K, q5_K, q6_K auto st = ggml_type(stype); ggml_quantize_init(st); const size_t sb = k::native_mmvq_weight_bytes(stype, sni, sno); @@ -447,6 +449,243 @@ int main(){ } } } + + // High-bandwidth Metal GEMV parity: unaligned tail outputs (no = 516, 2052, 2053, 63, 1), + // rows = 1, 2, 4, 8, kind = 0 / 1 / 9, y_stride guard sentinels across Q5_K, Q6_K, Q4_K, + // IQ2_XS, IQ2_S, and IQ3_XXS, plus Q8_0 k4/nr=4 grid-size NaN-sentinel regressions. + { + g::metal::set_optimize(true); + p::metal_detail::allow_mm_rows(false); + + // (a) Dense kind=0 (rows=1,2,4,8) & kind=9 native_mmvq_many / native_mmvq_many_rows with unaligned tails + for (int t : {12, 13, 14}) { + auto gt = ggml_type(t); + ggml_quantize_init(gt); + const int tni = 512; + std::vector timp(tni, 1.0f); + auto xs = values(size_t(8) * tni, 0.7f); + Buffer dxs(xs), qxs(k::native_q8_1_bytes(tni, 8)); + k::native_quantize_q8_1(dxs.as(), qxs.ptr, tni, 8, stream); + ck(g::stream_synchronize(stream)); + auto qb_raw = qxs.read(k::native_q8_1_bytes(tni, 8)); + std::vector xqf(xs.size()); + for (size_t i = 0; i < xs.size(); ++i) { + _Float16 d; std::memcpy(&d, qb_raw.data() + (i / 32) * 36, 2); + xqf[i] = float(d) * reinterpret_cast(qb_raw.data())[(i / 32) * 36 + 4 + i % 32]; + } + for (int tno : {1, 63, 516, 2052, 2053}) { + auto wf = values(size_t(tno) * tni, 0.4f); + const size_t wb = k::native_mmvq_weight_bytes(t, tni, tno); + std::vector packed(wb); + ggml_quantize_chunk(gt, wf.data(), packed.data(), 0, tno, tni, timp.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 r : {1, 2, 4, 8}) { + Buffer dy(size_t(r) * tno * 4); + k::native_mmvq(t, dw.ptr, qxs.ptr, dy.as(), tni, tno, r, stream); + ck(g::stream_synchronize(stream)); + std::vector ref(size_t(r) * tno); + for (int rr = 0; rr < r; ++rr) + for (int o = 0; o < tno; ++o) { + double acc = 0.0; + for (int i = 0; i < tni; ++i) acc += double(dwf[size_t(o) * tni + i]) * xqf[size_t(rr) * tni + i]; + ref[size_t(rr) * tno + o] = float(acc); + } + char lbl[96]; + std::snprintf(lbl, sizeof(lbl), "fast tail %s %dx%d r=%d", ggml_type_name(gt), tno, tni, r); + bad += compare(dy.read(size_t(r) * tno), ref, lbl, 1e-3f); + } + } + // kind=9 native_mmvq_many (r=1, bit-exact) & native_mmvq_many_rows (r=2,4,8) with unaligned n_out & distinct x + const int mouts[4] = {2052, 516, 13, 7}; + const int xidx[4] = {0, 1, 0, 2}; + std::vector> mw; + for (int j = 0; j < 4; ++j) { + auto wf = values(size_t(mouts[j]) * tni, 0.35f + 0.05f * j); + const size_t wb = k::native_mmvq_weight_bytes(t, tni, mouts[j]); + std::vector packed(wb); + ggml_quantize_chunk(gt, wf.data(), packed.data(), 0, mouts[j], tni, timp.data()); + mw.push_back(std::make_unique(wb)); + mw.back()->put(packed.data(), wb); + } + Buffer qx3(k::native_q8_1_bytes(tni, 3 * 8)); + auto xs3 = values(size_t(3 * 8) * tni, 0.65f); + Buffer dxs3(xs3); + k::native_quantize_q8_1(dxs3.as(), qx3.ptr, tni, 3 * 8, stream); + for (int r : {1, 2, 4, 8}) { + k::NativeMmvqMany m{}; + m.count = 4; + std::vector> gy, ry; + for (int j = 0; j < 4; ++j) { + gy.push_back(std::make_unique(size_t(r) * mouts[j] * 4)); + ry.push_back(std::make_unique(size_t(r) * mouts[j] * 4)); + m.w[j] = mw[j]->ptr; + m.x_q8_1[j] = static_cast(qx3.ptr) + size_t(xidx[j]) * k::native_q8_1_bytes(tni, 8); + m.y[j] = gy.back()->as(); + m.n_out[j] = mouts[j]; + k::native_mmvq(t, m.w[j], m.x_q8_1[j], ry.back()->as(), tni, mouts[j], r, stream); + } + if (r == 1) k::native_mmvq_many(t, m, tni, stream); + else { + if (!k::native_mmvq_many_rows_fits(t, m, tni, r)) { ++bad; continue; } + k::native_mmvq_many_rows(t, m, tni, r, stream); + } + ck(g::stream_synchronize(stream)); + for (int j = 0; j < 4; ++j) { + auto got = gy[j]->read(size_t(r) * mouts[j]); + auto want = ry[j]->read(size_t(r) * mouts[j]); + char lbl[96]; + std::snprintf(lbl, sizeof(lbl), "fast many %s r=%d m%d(%d)", ggml_type_name(gt), r, j, mouts[j]); + bad += compare(got, want, lbl, r == 1 ? 0.0f : 1e-4f); + } + } + } + + // (b) MoE kind=1 (_k1 & _k1g) on unaligned tails (no=516, no=2052) with duplicate experts and y_stride guard columns + for (auto [mni, mno, mcnt] : {std::tuple{512, 516, 8}, std::tuple{512, 2052, 4}}) { + const int n_exp = 3; + const int y_pad = 7; + const size_t ystride = size_t(mno + y_pad); + auto mwf = values(size_t(n_exp) * mno * mni, 0.45f); + auto mx = values(size_t(mcnt) * mni, 0.7f); + std::vector mimp(mni, 1.0f); + Buffer dmx(mx), mqx(k::native_q8_1_bytes(mni, mcnt)); + k::native_quantize_q8_1(dmx.as(), mqx.ptr, mni, mcnt, stream); + ck(g::stream_synchronize(stream)); + auto mqb = mqx.read(k::native_q8_1_bytes(mni, mcnt)); + std::vector mxq(mx.size()); + for (size_t i = 0; i < mx.size(); ++i) { + _Float16 d; std::memcpy(&d, mqb.data() + (i / 32) * 36, 2); + mxq[i] = float(d) * reinterpret_cast(mqb.data())[(i / 32) * 36 + 4 + i % 32]; + } + std::vector mids = mcnt == 8 ? std::vector{0, 2, 1, 2, 0, 2, 1, 1} + : std::vector{0, 1, 2, 0}; + Buffer dmids(mcnt * 4), dmgrp(k::kMmvqIdsGroupBytes); + dmids.put(mids.data(), mcnt * 4); + k::native_mmvq_ids_group(dmids.as(), mcnt, dmgrp.ptr, stream); + constexpr float kGuard = 777.5f; + std::vector poison(size_t(mcnt) * ystride, kGuard); + + for (int t : {12, 17, 18, 22}) { // q4_K, iq2_xs, iq3_xxs, iq2_s + auto gt = ggml_type(t); + ggml_quantize_init(gt); + const size_t eb = k::native_mmvq_weight_bytes(t, mni, mno); + std::vector packed(eb * n_exp); + ggml_quantize_chunk(gt, mwf.data(), packed.data(), 0, n_exp * mno, mni, mimp.data()); + std::vector dwf(mwf.size()); + ggml_get_type_traits(gt)->to_float(packed.data(), dwf.data(), dwf.size()); + Buffer dmw(packed.size()); dmw.put(packed.data(), packed.size()); + std::vector tab(n_exp); + for (int e = 0; e < n_exp; ++e) tab[e] = static_cast(dmw.ptr) + size_t(e) * eb; + Buffer dtab(n_exp * sizeof(void*)); dtab.put(tab.data(), n_exp * sizeof(void*)); + std::vector ref(size_t(mcnt) * ystride, kGuard); + for (int r = 0; r < mcnt; ++r) { + for (int o = 0; o < mno; ++o) { + double acc = 0.0; + for (int i = 0; i < mni; ++i) + acc += double(dwf[(size_t(mids[r]) * mno + o) * mni + i]) * mxq[size_t(r) * mni + i]; + ref[size_t(r) * ystride + o] = float(acc); + } + } + Buffer dy(size_t(mcnt) * ystride * 4); + for (bool grp : {false, true}) { + dy.put(poison.data(), poison.size() * 4); + k::MmvqIds a{dtab.as(), dmids.as(), 0, mqx.ptr, + k::native_q8_1_bytes(mni), 1, dy.as(), ystride}; + if (grp) { a.group_buf = dmgrp.ptr; a.group_ready = true; } + k::native_mmvq_ids(t, a, mcnt, mni, mno, stream); + ck(g::stream_synchronize(stream)); + auto got = dy.read(size_t(mcnt) * ystride); + int oob = 0; + for (int r = 0; r < mcnt; ++r) + for (int p = 0; p < y_pad; ++p) + if (got[size_t(r) * ystride + mno + p] != kGuard) ++oob; + if (oob) { std::printf("FAIL: %s %s no=%d wrote %d OOB guard floats\n", ggml_type_name(gt), grp ? "k1g" : "k1", mno, oob); bad += oob; } + char lbl[96]; + std::snprintf(lbl, sizeof(lbl), "moe tail %s %s no=%d c=%d", ggml_type_name(gt), grp ? "k1g" : "k1", mno, mcnt); + bad += compare(got, ref, lbl, 1e-3f); + } + } + } + + // (c) Q8_0 rows=1 regression for nr=4 vs poly_mul_q8_0_k4 grid-size gating (ni=2048, + // no in {1024, 2048, 3072, 4096} for kind=0 and {512,512}, {1024,1024}, {2048,2048} for kind=9): + // pre-fills destinations with NaN so any unwritten output element fails immediately. + { + const int qni = 2048, qno_max = 4096; + auto qt = GGML_TYPE_Q8_0; + ggml_quantize_init(qt); + std::vector qimp(qni, 1.0f); + auto qx = values(size_t(2) * qni, 0.65f); + Buffer dqx(qx), qq(k::native_q8_1_bytes(qni, 2)); + k::native_quantize_q8_1(dqx.as(), qq.ptr, qni, 2, stream); + ck(g::stream_synchronize(stream)); + auto qqb = qq.read(k::native_q8_1_bytes(qni, 2)); + std::vector qxq(qx.size()); + for (size_t i = 0; i < qx.size(); ++i) { + _Float16 d; std::memcpy(&d, qqb.data() + (i / 32) * 36, 2); + qxq[i] = float(d) * reinterpret_cast(qqb.data())[(i / 32) * 36 + 4 + i % 32]; + } + auto qwf = values(size_t(qno_max) * qni, 0.35f); + const size_t qwb_max = k::native_mmvq_weight_bytes(GGML_TYPE_Q8_0, qni, qno_max); + const size_t qrow_bytes = qwb_max / size_t(qno_max); + std::vector qpacked(qwb_max); + ggml_quantize_chunk(qt, qwf.data(), qpacked.data(), 0, qno_max, qni, qimp.data()); + std::vector qdwf(qwf.size()); + ggml_get_type_traits(qt)->to_float(qpacked.data(), qdwf.data(), qdwf.size()); + Buffer dqw(qwb_max); + dqw.put(qpacked.data(), qwb_max); + + auto cpu_ref = [&](int row_off, int n_out, int x_row) { + std::vector ref(static_cast(n_out)); + for (int o = 0; o < n_out; ++o) { + double acc = 0.0; + for (int i = 0; i < qni; ++i) + acc += double(qdwf[size_t(row_off + o) * qni + i]) * qxq[size_t(x_row) * qni + i]; + ref[size_t(o)] = float(acc); + } + return ref; + }; + + for (int qno : {1024, 2048, 3072, 4096}) { + std::vector nan_fill(size_t(qno), NAN); + Buffer dy(size_t(qno) * 4); + dy.put(nan_fill.data(), nan_fill.size() * 4); + k::native_mmvq(GGML_TYPE_Q8_0, dqw.ptr, qq.ptr, dy.as(), qni, qno, 1, stream); + ck(g::stream_synchronize(stream)); + char lbl[96]; + std::snprintf(lbl, sizeof(lbl), "q8_0 nr4/k4 kind=0 %dx%d r=1", qno, qni); + bad += compare(dy.read(size_t(qno)), cpu_ref(0, qno, 0), lbl, 1e-3f); + } + + const size_t x_row_bytes = k::native_q8_1_bytes(qni, 1); + for (auto [n0, n1] : {std::pair{512, 512}, std::pair{1024, 1024}, std::pair{2048, 2048}}) { + std::vector nan0(size_t(n0), NAN), nan1(size_t(n1), NAN); + Buffer dy0(size_t(n0) * 4), dy1(size_t(n1) * 4); + dy0.put(nan0.data(), nan0.size() * 4); + dy1.put(nan1.data(), nan1.size() * 4); + k::NativeMmvqMany m{}; + m.count = 2; + m.w[0] = dqw.ptr; + m.w[1] = static_cast(dqw.ptr) + size_t(n0) * qrow_bytes; + m.x_q8_1[0] = qq.ptr; + m.x_q8_1[1] = static_cast(qq.ptr) + x_row_bytes; + m.y[0] = dy0.as(); + m.y[1] = dy1.as(); + m.n_out[0] = n0; + m.n_out[1] = n1; + k::native_mmvq_many(GGML_TYPE_Q8_0, m, qni, stream); + ck(g::stream_synchronize(stream)); + char lbl[96]; + std::snprintf(lbl, sizeof(lbl), "q8_0 nr4/k4 kind=9 {%d,%d}x%d m0", n0, n1, qni); + bad += compare(dy0.read(size_t(n0)), cpu_ref(0, n0, 0), lbl, 1e-3f); + std::snprintf(lbl, sizeof(lbl), "q8_0 nr4/k4 kind=9 {%d,%d}x%d m1", n0, n1, qni); + bad += compare(dy1.read(size_t(n1)), cpu_ref(n0, n1, 1), lbl, 1e-3f); + } + } + } + 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/src/poly/quantized.cpp b/engine/metal/src/poly/quantized.cpp index 57aff936f4..af214d6318 100644 --- a/engine/metal/src/poly/quantized.cpp +++ b/engine/metal/src/poly/quantized.cpp @@ -11,6 +11,7 @@ #include #include #include +#include #include namespace strata::poly::metal_detail { namespace { @@ -33,6 +34,13 @@ bool mm_ready() { }(); return ready; } +bool is_apple10() { + static const bool a10=[] { + gpu::DeviceProp p{}; + return gpu::get_device_properties(&p,0)==gpu::kSuccess && std::string_view(p.gcnArchName)=="apple10"; + }(); + return a10; +} struct MmTile { int tm=64,tn=64,tk=64,sg=4; }; // mm.metal's tile: rows, outputs, values a step, SIMD groups struct MArgs { // mm.metal's MmArgs const void* p[6]{}; @@ -157,14 +165,29 @@ void to_half(const float* x,void* out_h,int64_t cols,int64_t ld,int64_t rows,voi dispatch("poly_quantized",source,"poly_tohalf",a,s,{uint32_t((cols/4+threads-1)/threads),uint32_t(rows),1},threads, {a.p,2,true,nullptr,modes,sizes}); } +uint32_t fast_grid_x(const QArgs& a,uint32_t nr,uint32_t nsg) { + uint32_t total_sg=0; + if(a.kind==9) { + const uint64_t packed[4]={a.stride,a.xstride,a.ystride,a.offset}; + for(int j=0;j>(32*(j%2))); + total_sg+=(nj+nr-1u)/nr; + } + } else { + total_sg=(uint32_t(a.no)+nr-1u)/nr; + } + return (total_sg+nsg-1u)/nsg; +} void qrun(const std::string& name,const QArgs& a,void* s,gpu::metal::Grid groups,size_t w_bytes) { static const auto source=quant_source(); std::string kernel=name; const bool mul=name.starts_with("poly_mul_"); - // groups.x: the outputs. 4 a threadgroup where the launch has 8,192 outputs or more; fewer leave the GPU too few - // threadgroups (a dense 2,304 x 4,096 matrix: 13% slower on the M5 Ultra), so there 1 (poly_mv_bench). Q5_1 - // always 1: its 4 were 8% slower on Qwen3.6's experts and no faster on Inkling 2's. - const int nr=mul && name!="poly_mul_q5_1" && uint64_t(groups.x)*groups.y*groups.z>=8192?4:1; + const uint64_t total_outputs=uint64_t(groups.x)*groups.y*groups.z; + // groups.x: the outputs. 4 a threadgroup where the launch has 8,192 outputs or more on Apple10 (M5 Ultra, where + // fewer leave the GPU too few threadgroups: a dense 2,304 x 4,096 matrix was 13% slower), or 2,048 on Apple9 + // (10-core M4). Q5_1 always 1: its 4 were 8% slower on Qwen3.6's experts and no faster on Inkling 2's. + const uint64_t nr4_thresh=is_apple10()?8192ULL:2048ULL; + const int nr=mul && name!="poly_mul_q5_1" && total_outputs>=nr4_thresh?4:1; if(mul && nr==1) kernel+="_1"; const uint64_t packed[4]={a.stride,a.xstride,a.ystride,a.offset}; if(mul && a.kind==9) { // native_mmvq_many: each matrix's outputs in groups of nr @@ -209,8 +232,15 @@ void qrun(const std::string& name,const QArgs& a,void* s,gpu::metal::Grid groups } } uint32_t threads = 32; - if(name=="poly_mul_q8_0" && (a.kind==0 || a.kind==9) && a.rows==1 && groups.y==1 && groups.z==1 && - a.ni>=2048 && (a.ni%2048)==0 && groups.x<=1024 && gpu::metal::optimize()) { + if((name=="poly_mul_q5_K" || name=="poly_mul_q6_K" || name=="poly_mul_q4_K") && + (a.kind==0 || a.kind==9) && a.rows==1 && groups.y==1 && groups.z==1 && gpu::metal::optimize()) { + const uint32_t nr_f = total_outputs>=nr4_thresh ? 4u : 2u; + const uint32_t nsg_f = (nr_f==4u && name!="poly_mul_q5_K") ? 4u : 2u; + kernel = name + (nr_f==4u ? "_fast4" : "_fast"); + groups.x = fast_grid_x(a,nr_f,nsg_f); + threads = nsg_f * 32u; + } else if(name=="poly_mul_q8_0" && (a.kind==0 || a.kind==9) && a.rows==1 && groups.y==1 && groups.z==1 && + nr==1 && a.ni>=2048 && (a.ni%2048)==0 && total_outputs<=1024 && gpu::metal::optimize()) { kernel="poly_mul_q8_0_k4"; threads=128; } @@ -222,13 +252,13 @@ void qrun(const std::string& name,const QArgs& a,void* s,gpu::metal::Grid groups bool mulr2_type(int t) { switch(t) { case 8: case 14: case 40: // q8_0, q6_K, nvfp4 - case 2: case 3: case 6: case 7: case 39: case 10: case 11: case 13: // q4_0 q4_1 q5_0 q5_1 mxfp4 q2_K q3_K q5_K + case 2: case 3: case 6: case 7: case 39: case 10: case 11: case 12: case 13: // q4_0 q4_1 q5_0 q5_1 mxfp4 q2_K q3_K q4_K q5_K case 17: case 18: case 20: case 21: case 23: case 29: return true; // iq2_xs iq3_xxs iq4_nl iq3_s iq4_xs iq1_m default: return false; } } -// native_mmvq() of 2 to 8 rows: uses MAXR=4 (1r4 for q8_0/q6_K, 2r4 for large q5_K) for rows<=4 to halve accumulator -// register pressure while preserving high TG occupancy. +// native_mmvq() of 2 to 8 rows: uses MAXR=4 (1r4 for q8_0/q6_K, fast multi-SG for Q4_K/Q5_K/Q6_K) for rows<=4 +// to halve accumulator register pressure while preserving high TG occupancy. void mulr_run(int type,const QArgs& a,void* s,size_t w_bytes) { static const auto source=quant_source(); const gpu::metal::Access modes[6]={gpu::metal::Access::R,gpu::metal::Access::R,gpu::metal::Access::W, @@ -236,12 +266,33 @@ void mulr_run(int type,const QArgs& a,void* s,size_t w_bytes) { const size_t sizes[6]={w_bytes,size_t(a.ni/32)*36ULL*size_t(a.rows),4ULL*size_t(a.no)*size_t(a.rows),0,0,0}; const bool r2=mulr2_type(type); // Bit-exact 64-K tiled simdgroup_half8x8 -> simdgroup_float8x8 MMA for Q5_K rows=5..8 & large n_out (>= 2048): - // measured 4.10 TFLOP/s (18.1 ms vs 20.4 ms scalar) on M5 Ultra; keeps _1r4 for rows<=4 and Q6_K/Q8_0 on fast float4. + // measured 4.10 TFLOP/s (18.1 ms vs 20.4 ms scalar) on M5 Ultra; keeps fast_r4 for rows<=4. if(type==13 && a.rows>=5 && a.rows<=8 && gpu::metal::optimize() && a.no>=2048 && (a.ni%64)==0) { dispatch("poly_quantized",source,"poly_mulr2_q5_K_mma",a,s,{uint32_t((a.no+31)/32),1,1},128u, {a.p,6,true,nullptr,modes,sizes,true}); return; } + if(type==13 && a.rows<=4 && gpu::metal::optimize()) { + dispatch("poly_quantized",source,"poly_mulr2_q5_K_fast_r4",a,s,{fast_grid_x(a,2u,4u),1,1},128u, + {a.p,6,true,nullptr,modes,sizes,true}); + return; + } + if(type==14 && a.rows<=8 && gpu::metal::optimize()) { + const bool r4=a.rows<=4; + const char* kname=r4?"poly_mulr2_q6_K_fast_r4":"poly_mulr2_q6_K_fast_r8"; + const uint32_t nr_f=r4?4u:2u; + dispatch("poly_quantized",source,kname,a,s,{fast_grid_x(a,nr_f,2u),1,1},64u, + {a.p,6,true,nullptr,modes,sizes,true}); + return; + } + if(type==12 && a.rows<=8 && gpu::metal::optimize()) { + const bool r4=a.rows<=4; + const char* kname=r4?"poly_mulr2_q4_K_fast_r4":"poly_mulr2_q4_K_fast_r8"; + const uint32_t nsg_f=r4?4u:2u; + dispatch("poly_quantized",source,kname,a,s,{fast_grid_x(a,2u,nsg_f),1,1},nsg_f*32u, + {a.p,6,true,nullptr,modes,sizes,true}); + return; + } if(type==8 && a.rows<=8) { const bool k4 = a.ni>=2048 && (a.ni%2048)==0 && a.no<=1024 && gpu::metal::optimize(); const char* kname = k4 ? (a.rows<=4 ? "poly_mulr2_q8_0_k4r4" : "poly_mulr2_q8_0_k4r8") @@ -250,7 +301,7 @@ void mulr_run(int type,const QArgs& a,void* s,size_t w_bytes) { k4?128u:32u,{a.p,6,true,nullptr,modes,sizes,true}); return; } - if((type==13 || type==14) && a.rows<=4) { + if((type==12 || type==13 || type==14) && a.rows<=4) { const std::string k=std::string("poly_mulr2_")+quant_name(type)+"_1r4"; dispatch("poly_quantized",source,k.c_str(),a,s,{uint32_t(a.no),1,1},32, {a.p,6,true,nullptr,modes,sizes,true}); @@ -351,7 +402,8 @@ bool native_mmvq_ids(int t,const MmvqIds& a,int count,int ni,int no,void* s) { const uint64_t b=uint64_t(quant::row_bytes(t,ni))*no*uint64_t(count)+native_q8_1_bytes(ni,count)+4ULL*uint64_t(no)*count; gpu::metal::prof_push_hint({gpu::metal::ProfCat::GemvDecode,b,2ULL*uint64_t(count)*ni*no}); } - if((t==40 || t==12 || t==17 || t==18 || t==22) && no%4==0 && gpu::metal::optimize() && uint64_t(no)*count>=8192) { + const uint64_t k1_thresh = is_apple10() ? 8192ULL : 2048ULL; + if((t==40 || t==12 || t==17 || t==18 || t==22) && no%4==0 && gpu::metal::optimize() && uint64_t(no)*count>=k1_thresh) { static const auto source=quant_source(); const bool grouped = a.group_buf && a.group_ready && count>1 && count<=64; if(grouped) q.p[4]=a.group_buf; @@ -359,9 +411,13 @@ bool native_mmvq_ids(int t,const MmvqIds& a,int count,int ni,int no,void* s) { gpu::metal::Access::R,gpu::metal::Access::R,gpu::metal::Access::R}; const size_t sizes[6]={0,0,4ULL*((size_t(count-1)*size_t(a.y_stride))+size_t(no)),4ULL*size_t(count), grouped?kMmvqIdsGroupBytes:0,0}; + const uint32_t nsg_k1 = (t==40) ? 1u : (t==12 ? 4u : 8u); + const uint32_t nr_k1 = (t==17 || t==18 || t==22) ? 8u : 4u; + const uint32_t out_per_tg = nsg_k1 * nr_k1; const std::string k=std::string("poly_mul_")+quant_name(t)+(grouped?"_k1g":"_k1"); dispatch("poly_quantized",source,k.c_str(),q,s, - {uint32_t(no/4),uint32_t(count),1},32,{q.p,6,true,q.p[0],modes,sizes,true}); + {uint32_t((uint32_t(no)+out_per_tg-1u)/out_per_tg),uint32_t(count),1},nsg_k1*32u, + {q.p,6,true,q.p[0],modes,sizes,true}); return true; } qrun(std::string("poly_mul_")+quant_name(t),q,s,{uint32_t(no),uint32_t(count),1});return true; @@ -420,6 +476,21 @@ void native_mmvq_many_rows(int t,const NativeMmvqMany& m,int ni,int rows,void* s kernel="poly_mulr2_q5_K_mma"; threads=128; gx=(total+31)/32; + } else if(t==13 && rows<=4 && gpu::metal::optimize()) { + kernel="poly_mulr2_q5_K_fast_r4"; + threads=128; + gx=fast_grid_x(q,2u,4u); + } else if(t==14 && rows<=8 && gpu::metal::optimize()) { + const bool r4=rows<=4; + kernel=r4?"poly_mulr2_q6_K_fast_r4":"poly_mulr2_q6_K_fast_r8"; + threads=64; + gx=fast_grid_x(q,r4?4u:2u,2u); + } else if(t==12 && rows<=8 && gpu::metal::optimize()) { + const bool r4=rows<=4; + kernel=r4?"poly_mulr2_q4_K_fast_r4":"poly_mulr2_q4_K_fast_r8"; + const uint32_t nsg_f=r4?4u:2u; + threads=nsg_f*32u; + gx=fast_grid_x(q,2u,nsg_f); } else if(t==8 && rows<=8) { if(ni>=2048 && (ni%2048)==0 && total<=1024 && gpu::metal::optimize()) { kernel = rows<=4 ? "poly_mulr2_q8_0_k4r4" : "poly_mulr2_q8_0_k4r8"; @@ -429,7 +500,7 @@ void native_mmvq_many_rows(int t,const NativeMmvqMany& m,int ni,int rows,void* s } for(int j=0;j0,0)) { @@ -459,7 +530,13 @@ Mmq::Mmq() { gpu::metal::pipeline("poly_quantized",source.c_str(),(std::string("poly_mul_")+quant_name(t)+tile).c_str(),error); for(const char* k:{"poly_mul_q8_0_k4","poly_mulr2_q8_0_k4r4","poly_mulr2_q8_0_k4r8", "poly_mulr2_q8_0_1r4","poly_mulr2_q8_0_1", + "poly_mul_q4_K_fast","poly_mul_q4_K_fast4", + "poly_mulr2_q4_K_fast_r4","poly_mulr2_q4_K_fast_r8", + "poly_mulr2_q4_K_1r4","poly_mulr2_q4_K_1", + "poly_mul_q5_K_fast","poly_mul_q5_K_fast4","poly_mulr2_q5_K_fast_r4", "poly_mulr2_q5_K_1r4","poly_mulr2_q5_K_1","poly_mulr2_q5_K_mma", + "poly_mul_q6_K_fast","poly_mul_q6_K_fast4", + "poly_mulr2_q6_K_fast_r4","poly_mulr2_q6_K_fast_r8", "poly_mulr2_q6_K_1r4","poly_mulr2_q6_K_1", "poly_mmvq_ids_group", "poly_mul_nvfp4_k1","poly_mul_q4_K_k1", diff --git a/engine/metal/src/poly/quantized.metal b/engine/metal/src/poly/quantized.metal index a312a16e03..44774276e8 100644 --- a/engine/metal/src/poly/quantized.metal +++ b/engine/metal/src/poly/quantized.metal @@ -83,8 +83,8 @@ struct dot_q4_K { const uint sh=(il&2)?4:0; float s=0; for(int i=0;i<4;++i) { - const uchar4 c=as_type((q[i]>>sh)&0x0F0F0F0Fu); - s+=float(c[0])*xv[4*i]+float(c[1])*xv[4*i+1]+float(c[2])*xv[4*i+2]+float(c[3])*xv[4*i+3]; + const float4 c=float4(as_type((q[i]>>sh)&0x0F0F0F0Fu)); + s+=dot(c,float4(xv[4*i+0],xv[4*i+1],xv[4*i+2],xv[4*i+3])); } return float(b->d)*float(sc[0])*s-float(b->dmin)*float(sc[1])*xs; } @@ -108,15 +108,16 @@ struct dot_q6_K { // dequantize_q6_K's 6-bit codes, four a word, minus 32 } }; // eight grid bytes (two words) times xv with the signs' bits flipping xv's (vectorized float4 dot) -static inline float signed_grid8(uint2 g,uint signs,thread const float* xv) { +static inline float signed_grid8_v4(uint2 g,uint signs,float4 x0,float4 x1) { const float4 g0=float4(as_type(g.x)); const float4 g1=float4(as_type(g.y)); - const float4 x0=float4(xv[0],xv[1],xv[2],xv[3]); - const float4 x1=float4(xv[4],xv[5],xv[6],xv[7]); - const bool4 s0=bool4((signs&1u)!=0u,(signs&2u)!=0u,(signs&4u)!=0u,(signs&8u)!=0u); - const bool4 s1=bool4((signs&16u)!=0u,(signs&32u)!=0u,(signs&64u)!=0u,(signs&128u)!=0u); + const bool4 s0=(uint4(signs)&uint4(1u,2u,4u,8u))!=0u; + const bool4 s1=(uint4(signs)&uint4(16u,32u,64u,128u))!=0u; return dot(g0,select(x0,-x0,s0))+dot(g1,select(x1,-x1,s1)); } +static inline float signed_grid8(uint2 g,uint signs,thread const float* xv) { + return signed_grid8_v4(g,signs,float4(xv[0],xv[1],xv[2],xv[3]),float4(xv[4],xv[5],xv[6],xv[7])); +} struct dot_iq2_s { enum { kSum=0 }; static float run(device const block_iq2_s* b,short il,thread const float* xv,float) { @@ -450,39 +451,180 @@ struct split_nvfp4 { // dot_nvfp4's #define MULR2_(name,QK,SPLIT,NR,MAXR,SUFFIX) template [[host_name("poly_mulr2_" #name SUFFIX)]] kernel decltype(poly_mulr2) poly_mulr2; #define MULR2(name,QK,SPLIT) MULR2_(name,QK,SPLIT,4,8,"") MULR2_(name,QK,SPLIT,1,8,"_1") MULR2_(q8_0,32,split_q8_0,4,8,"") -// Dedicated low-register MoE indirect matvec (kind 1, NR = 4): strips all kind!=1 dispatch logic +// 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)); + } +}; +// Dedicated low-register MoE indirect matvec (kind 1): multi-SIMDgroup with optional threadgroup LUT staging // for iq2_s, iq2_xs, iq3_xxs, q4_K, and nvfp4 routed experts. -template +template kernel void poly_mul_k1(constant QArgs& a [[buffer(0)]],uint3 group [[threadgroup_position_in_grid]], - uint lane [[thread_index_in_threadgroup]]) { - constexpr int NR=4; - const uint row=group.y,gx=group.x; - device const uchar* w=static_cast(a.p[0])[static_cast(a.p[3])[row]]+a.offset; + uint tid [[thread_index_in_threadgroup]]) { + const uint warp=tid>>5u, lane=tid&31u; + const uint row=group.y; + const int eid=static_cast(a.p[3])[row]; device float* out_y=static_cast(a.p[2]); + const int o0=(int(group.x)*NSG+int(warp))*NR; + threadgroup typename Lut::Storage lut; + if(Lut::kHasLut) { + Lut::load(lut,tid,uint(NSG*32)); + threadgroup_barrier(mem_flags::mem_threadgroup); + } + if(o0>=a.no) return; + device const uchar* w=static_cast(a.p[0])[eid]+a.offset; device const uchar* x=static_cast(a.p[1])+ulong(row/a.every)*a.xstride; - const int o0=int(gx)*NR; const ulong per=ulong(a.ni/QK); - device const Block* weights=reinterpret_cast(w)+ulong(o0)*per; - float acc[NR]={0.f,0.f,0.f,0.f}; + device const Block* w_base=reinterpret_cast(w); + device const Block* w_row[NR]; + for(int r=0;r>5)*36ul; - const float d=float(*reinterpret_cast(block)); + const float dx=float(*reinterpret_cast(block)); device const char4* q=reinterpret_cast(block+4+(start&16)); - for(int j=0;j<4;++j) { const float4 v=d*float4(q[j]); xv[4*j]=v[0];xv[4*j+1]=v[1];xv[4*j+2]=v[2];xv[4*j+3]=v[3]; } - float xs=0.f; - if(Dot::kSum) for(int j=0;j<16;++j) xs+=xv[j]; + 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) poly_mul_k1; -MULK1(nvfp4,64) MULK1(q4_K,256) MULK1(iq2_s,256) MULK1(iq2_xs,256) MULK1(iq3_xxs,256) +#define MULK1(name,QK,LUT,NSG,NR) template [[host_name("poly_mul_" #name "_k1")]] kernel decltype(poly_mul_k1) poly_mul_k1; +MULK1(nvfp4,64,lut_none,1,4) MULK1(q4_K,256,lut_none,4,4) +MULK1(iq2_s,256,lut_iq2_s,8,8) MULK1(iq2_xs,256,lut_iq2_xs,8,8) MULK1(iq3_xxs,256,lut_iq3_xxs,8,8) // GPU expert deduplication table (776 B <= kMmvqIdsGroupBytes = 1024 B) for multi-token verify (MTP & DFlash2). struct MmvqIdsGroup { @@ -567,7 +709,8 @@ static inline void decode_signed_grid8(uint2 g, uint signs, thread float4& r0, t } struct grp_split_nvfp4 { enum { kSum=0 }; - static void decode(device const block_nvfp4* b, short il, thread float4* w, thread float& k, thread float& m) { + static void decode(device const block_nvfp4* b, short il, thread float4* w, thread float& k, thread float& m, + threadgroup const lut_none::Storage&) { device const uint* q=reinterpret_cast(b->qs+8*il); const uint lo=q[0],hi=q[1]; w[0]=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]); @@ -584,7 +727,8 @@ struct grp_split_nvfp4 { }; struct grp_split_q4_K { enum { kSum=1 }; - static void decode(device const block_q4_K* b, short il, thread float4* w, thread float& k, thread float& m) { + 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&) { 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; @@ -602,14 +746,16 @@ struct grp_split_q4_K { }; struct grp_split_iq2_s { enum { kSum=0 }; - static void decode(device const block_iq2_s* b, short il, thread float4* w, thread float& k, thread float& m) { - const int ib32=il/2, h=il%2; + 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 uint8_t qh=b->qh[ib32]>>4*h; - k = float(b->d)*(0.5f+((b->scales[ib32]>>4*h)&0xf))*0.25f; + 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=as_type(iq2s_grid[qs[0]|((qh<<8)&0x300)]), g2=as_type(iq2s_grid[qs[1]|((qh<<6)&0x300)]); + 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]); } @@ -620,14 +766,21 @@ struct grp_split_iq2_s { }; struct grp_split_iq2_xs { enum { kSum=0 }; - static void decode(device const block_iq2_xs* b, short il, thread float4* w, thread float& k, thread float& m) { - const int ib32=il/2, h=il%2; + 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; - k = float(b->d)*(0.5f+((b->scales[ib32]>>4*h)&0xf))*0.25f; + 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 uint2 g1=as_type(iq2xs_grid[q2[0]&511]), g2=as_type(iq2xs_grid[q2[1]&511]); - decode_signed_grid8(g1, ksigns_iq2xs[q2[0]>>9], w[0], w[1]); - decode_signed_grid8(g2, ksigns_iq2xs[q2[1]>>9], w[2], w[3]); + 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, float dx, device const char4* q) { const float s = dot(w[0],float4(q[0]))+dot(w[1],float4(q[1]))+dot(w[2],float4(q[2]))+dot(w[3],float4(q[3])); @@ -636,62 +789,82 @@ struct grp_split_iq2_xs { }; struct grp_split_iq3_xxs { enum { kSum=0 }; - static void decode(device const block_iq3_xxs* b, short il, thread float4* w, thread float& k, thread float& m) { - const int ib32=il/2, h=il%2; + 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])<<16); - k = float(b->d)*(0.5f+(aux32>>28))*0.5f; + 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 uint2 g1=uint2(iq3xxs_grid[q3[0]],iq3xxs_grid[q3[1]]), g2=uint2(iq3xxs_grid[q3[2]],iq3xxs_grid[q3[3]]); - decode_signed_grid8(g1, ksigns_iq2xs[(aux32>>(14*h))&127], w[0], w[1]); - decode_signed_grid8(g2, ksigns_iq2xs[(aux32>>(14*h+7))&127], w[2], w[3]); + 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, float dx, device const char4* q) { const float s = dot(w[0],float4(q[0]))+dot(w[1],float4(q[1]))+dot(w[2],float4(q[2]))+dot(w[3],float4(q[3])); return (k*dx)*s; } }; -// Grouped MoE indirect matvec (kind 1, NR = 4): reads each unique expert weight ONCE across all duplicate tokens! -template +// Grouped MoE indirect matvec (kind 1): reads each unique expert weight ONCE across all duplicate tokens, +// with multi-SIMDgroup execution and threadgroup-staged LUTs for IQ2_XS / IQ2_S / IQ3_XXS. +template kernel void poly_mul_k1g(constant QArgs& a [[buffer(0)]],uint3 group [[threadgroup_position_in_grid]], - uint lane [[thread_index_in_threadgroup]]) { - constexpr int NR=4; + uint tid [[thread_index_in_threadgroup]]) { + const uint warp=tid>>5u, lane=tid&31u; 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]; - device const uchar* w=static_cast(a.p[0])[eid]+a.offset; device float* out_y=static_cast(a.p[2]); + const int o0=(int(group.x)*NSG+int(warp))*NR; + threadgroup typename Lut::Storage lut; + if(Lut::kHasLut) { + Lut::load(lut,tid,uint(NSG*32)); + threadgroup_barrier(mem_flags::mem_threadgroup); + } + if(o0>=a.no) return; + device const uchar* w=static_cast(a.p[0])[eid]+a.offset; device const uchar* xbase=static_cast(a.p[1]); - const int o0=int(group.x)*NR; const ulong per=ulong(a.ni/QK); - device const Block* weights=reinterpret_cast(w)+ulong(o0)*per; + device const Block* w_base=reinterpret_cast(w); if(s1-s0==1) { const uint row=uint(grp->member[s0]); device const uchar* x=xbase+ulong(row/a.every)*a.xstride; - float acc[NR]={0.f,0.f,0.f,0.f}; + device const Block* w_row[NR]; + for(int r=0;r>5)*36ul; - const float d=float(*reinterpret_cast(block)); + const float dx=float(*reinterpret_cast(block)); device const char4* q=reinterpret_cast(block+4+(start&16)); - for(int j=0;j<4;++j) { const float4 v=d*float4(q[j]); xv[4*j]=v[0];xv[4*j+1]=v[1];xv[4*j+2]=v[2];xv[4*j+3]=v[3]; } - float xs=0.f; - if(Dot::kSum) for(int j=0;j<16;++j) xs+=xv[j]; + 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=a.no) break; float acc[8]={0.f,0.f,0.f,0.f,0.f,0.f,0.f,0.f}; device const Block* wr=weights+ulong(r)*per; for(int start=int(lane)*16;start>4); float4 w4[4]; float kw=0.f, mw=0.f; - Split::decode(wr+(start/QK),il,w4,kw,mw); + Split::decode(wr+(start/QK),il,w4,kw,mw,lut); for(int c=0;c<8;++c) { if(c>=m) break; device const uchar* block=xbase+xoffs[c]+ulong(start>>5)*36ul; @@ -724,8 +898,9 @@ 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) +#define MULK1G(name,QK,LUT,NSG,NR) template [[host_name("poly_mul_" #name "_k1g")]] kernel decltype(poly_mul_k1g) poly_mul_k1g; +MULK1G(nvfp4,64,lut_none,1,4) MULK1G(q4_K,256,lut_none,4,4) +MULK1G(iq2_s,256,lut_iq2_s,8,8) MULK1G(iq2_xs,256,lut_iq2_xs,8,8) MULK1G(iq3_xxs,256,lut_iq3_xxs,8,8) 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>; \ @@ -978,12 +1153,625 @@ struct split_q5_K_fast { return s; } }; +struct split_q4_K { + enum { kSum=0 }; + static void decode(device const block_q4_K* b,short il,thread float* w,thread float& k) { + const uchar2 sc=get_scale_min_k4_just2((il/4)*2,(il&3)/2,b->scales); + const float dl=float(b->d)*float(sc[0]), ml=float(b->dmin)*float(sc[1]); + device const uint* q=reinterpret_cast(b->qs+(il/4)*32+16*(il&1)); + const uint sh=(il&2)?4:0; + for(int i=0;i<4;++i) { + const float4 fv=fma(dl,float4(as_type((q[i]>>sh)&0x0F0F0F0Fu)),-ml); + w[4*i+0]=fv[0]; w[4*i+1]=fv[1]; w[4*i+2]=fv[2]; w[4*i+3]=fv[3]; + } + k=1.0f; + } + static float apply(thread const float* w,float,thread const float* xv,float) { + float s=0.0f; + for(int i=0;i<4;++i) + s+=dot(float4(w[4*i+0],w[4*i+1],w[4*i+2],w[4*i+3]), + float4(xv[4*i+0],xv[4*i+1],xv[4*i+2],xv[4*i+3])); + return s; + } +}; MULR2_(q8_0,32,split_q8_0,1,8,"_1") MULR2_(q8_0,32,split_q8_0,1,4,"_1r4") MULR2_(q6_K,256,split_q6_K,1,8,"_1") MULR2_(q6_K,256,split_q6_K,1,4,"_1r4") MULR2(q5_K,256,split_q5_K_fast) MULR2_(q5_K,256,split_q5_K_fast,1,4,"_1r4") +MULR2(q4_K,256,split_q4_K) +MULR2_(q4_K,256,split_q4_K,1,4,"_1r4") + +// High-bandwidth multi-SIMDgroup decode GEMV for Q5_K, Q6_K, and Q4_K (kind == 0 and kind == 9, rows=1 and rows=2..8). +// Uses ggml-metal's superblock-aligned lane layouts so each weight byte (qs/ql/qh/scales) is loaded ONCE per superblock +// instead of 2-8x, with branchless 32-bit bitwise unpacking and vectorized short4/float4 Q8_1 loads. +static inline bool map_fast_group(constant QArgs& a, uint gsg, uint nr, + thread device const uchar*& w0, thread device const uchar*& x0, + thread device float*& out_y, thread int& no, thread int& o0, + thread ulong& xstride, thread ulong& ystride) { + if (a.kind == 9) { + constant uint* outputs = reinterpret_cast(&a.stride); + uint mj = 0; + while (mj < uint(a.count)) { + const uint nsg_j = (outputs[mj] + nr - 1u) / nr; + if (gsg < nsg_j) break; + gsg -= nsg_j; + ++mj; + } + if (mj >= uint(a.count)) return false; + w0 = static_cast(a.p[3 * mj]); + x0 = static_cast(a.p[3 * mj + 1]); + out_y = static_cast(a.p[3 * mj + 2]); + no = int(outputs[mj]); + o0 = int(gsg * nr); + xstride = ulong(a.ni >> 5) * 36ul; + ystride = ulong(no); + return true; + } + w0 = static_cast(a.p[0]); + x0 = static_cast(a.p[1]); + out_y = static_cast(a.p[2]); + no = a.no; + o0 = int(gsg * nr); + xstride = a.xstride; + ystride = a.ystride; + return o0 < no; +} + +static inline void unpack_k4_scales(device const uint8_t* scales, uint iq, + thread float& sc0, thread float& sc1, thread float& sc2, thread float& sc3, + thread float& mn0, thread float& mn1, thread float& mn2, thread float& mn3) { + device const ushort* a_sc = reinterpret_cast(scales) + iq; + const ushort a0 = a_sc[0], a2 = a_sc[2], a4 = a_sc[4]; + const ushort s01 = a0 & 0x3f3fu; + const ushort m01 = a2 & 0x3f3fu; + const ushort s45 = (a4 & 0x0f0fu) | ((a0 & 0xc0c0u) >> 2u); + const ushort m45 = ((a4 >> 4u) & 0x0f0fu) | ((a2 & 0xc0c0u) >> 2u); + sc0 = float(s01 & 0xffu); sc1 = float(s01 >> 8u); + mn0 = float(m01 & 0xffu); mn1 = float(m01 >> 8u); + sc2 = float(s45 & 0xffu); sc3 = float(s45 >> 8u); + mn2 = float(m45 & 0xffu); mn3 = float(m45 >> 8u); +} + +template +kernel void poly_mul_q5_K_fast_t(constant QArgs& a [[buffer(0)]], uint3 group [[threadgroup_position_in_grid]], + uint tid [[thread_index_in_threadgroup]]) { + const uint sg = tid >> 5u, lane = tid & 31u; + device const uchar* w0 = nullptr; + device const uchar* x0 = nullptr; + device float* out_y = nullptr; + int no = 0, o0 = 0; + ulong xstride = 0, ystride = 0; + if (!map_fast_group(a, group.x * uint(NSG) + sg, uint(NR), w0, x0, out_y, no, o0, xstride, ystride)) return; + + const int nb = a.ni >> 8; + const uint ltid = lane >> 2u; // 0..7 + const uint ix = lane & 3u; // 0..3 (4 superblocks in parallel across SIMD group) + const uint iq = ltid >> 2u; // 0..1 + const uint ir = ltid & 3u; // 0..3 + const uint l0 = 8u * ir; + const uint q_off = 32u * iq + l0; + const uint sh_h = 2u * iq; + + device const block_q5_K* w_base = reinterpret_cast(w0); + device const block_q5_K* w_row[NR]; + for (int r = 0; r < NR; ++r) w_row[r] = w_base + ulong(min(o0 + r, no - 1)) * ulong(nb); + + float sumf[NR]; + for (int r = 0; r < NR; ++r) sumf[r] = 0.0f; + + for (int ib = int(ix); ib < nb; ib += 4) { + device const uchar* xb0 = x0 + ulong(ib) * 288ul + ulong(2u * iq) * 36ul; + device const uchar* xb1 = xb0 + 36ul; + device const uchar* xb2 = xb0 + 144ul; + device const uchar* xb3 = xb0 + 180ul; + const float4 dx = float4( + float(*reinterpret_cast(xb0)), + float(*reinterpret_cast(xb1)), + float(*reinterpret_cast(xb2)), + float(*reinterpret_cast(xb3))); + device const char4* qx0 = reinterpret_cast(xb0 + 4u + l0); + device const char4* qx1 = reinterpret_cast(xb1 + 4u + l0); + device const char4* qx2 = reinterpret_cast(xb2 + 4u + l0); + device const char4* qx3 = reinterpret_cast(xb3 + 4u + l0); + const short4 q0a = short4(qx0[0]), q0b = short4(qx0[1]); + const short4 q1a = short4(qx1[0]), q1b = short4(qx1[1]); + const short4 q2a = short4(qx2[0]), q2b = short4(qx2[1]); + const short4 q3a = short4(qx3[0]), q3b = short4(qx3[1]); + const short4 s0 = q0a + q0b, s1 = q1a + q1b, s2 = q2a + q2b, s3 = q3a + q3b; + const float4 sy = dx * float4( + float((s0.x + s0.y) + (s0.z + s0.w)), + float((s1.x + s1.y) + (s1.z + s1.w)), + float((s2.x + s2.y) + (s2.z + s2.w)), + float((s3.x + s3.y) + (s3.z + s3.w))); + + for (int r = 0; r < NR; ++r) { + device const block_q5_K* blk = w_row[r] + ib; + float sc0, sc1, sc2, sc3, mn0, mn1, mn2, mn3; + unpack_k4_scales(blk->scales, iq, sc0, sc1, sc2, sc3, mn0, mn1, mn2, mn3); + device const uint* q1_u = reinterpret_cast(blk->qs + q_off); + device const uint* q2_u = q1_u + 16; + device const uint* qh_u = reinterpret_cast(blk->qh + l0); + const uint q1w0 = q1_u[0], q1w1 = q1_u[1]; + const uint q2w0 = q2_u[0], q2w1 = q2_u[1]; + const uint h0 = qh_u[0] >> sh_h, h1 = qh_u[1] >> sh_h; + + // Exact 16-bit integer dot: max 8 * 31 * 128 = 31,744 <= 32,767 (overflow-impossible in short). + const short4 p0 = short4(as_type((q1w0 & 0x0F0F0F0Fu) | ((h0 << 4u) & 0x10101010u))) * q0a + + short4(as_type((q1w1 & 0x0F0F0F0Fu) | ((h1 << 4u) & 0x10101010u))) * q0b; + const short4 p1 = short4(as_type(((q1w0 >> 4u) & 0x0F0F0F0Fu) | ((h0 << 3u) & 0x10101010u))) * q1a + + short4(as_type(((q1w1 >> 4u) & 0x0F0F0F0Fu) | ((h1 << 3u) & 0x10101010u))) * q1b; + const short4 p2 = short4(as_type((q2w0 & 0x0F0F0F0Fu) | (h0 & 0x10101010u))) * q2a + + short4(as_type((q2w1 & 0x0F0F0F0Fu) | (h1 & 0x10101010u))) * q2b; + const short4 p3 = short4(as_type(((q2w0 >> 4u) & 0x0F0F0F0Fu) | ((h0 >> 1u) & 0x10101010u))) * q3a + + short4(as_type(((q2w1 >> 4u) & 0x0F0F0F0Fu) | ((h1 >> 1u) & 0x10101010u))) * q3b; + + const float4 av = dx * float4( + float((p0.x + p0.y) + (p0.z + p0.w)), + float((p1.x + p1.y) + (p1.z + p1.w)), + float((p2.x + p2.y) + (p2.z + p2.w)), + float((p3.x + p3.y) + (p3.z + p3.w))); + sumf[r] += float(blk->d) * dot(float4(sc0, sc1, sc2, sc3), av) + - float(blk->dmin) * dot(float4(mn0, mn1, mn2, mn3), sy); + } + } + + for (int r = 0; r < NR; ++r) { + const float tot = simd_sum(sumf[r]); + if (lane == 0u && o0 + r < no) out_y[o0 + r] = tot; + } +} + +template +kernel void poly_mulr2_q5_K_fast_t(constant QArgs& a [[buffer(0)]], uint3 group [[threadgroup_position_in_grid]], + uint tid [[thread_index_in_threadgroup]]) { + const uint sg = tid >> 5u, lane = tid & 31u; + device const uchar* w0 = nullptr; + device const uchar* x0 = nullptr; + device float* out_y = nullptr; + int no = 0, o0 = 0; + ulong xstride = 0, ystride = 0; + if (!map_fast_group(a, group.x * uint(NSG) + sg, uint(NR), w0, x0, out_y, no, o0, xstride, ystride)) return; + + const int rows = a.rows; + const int nb = a.ni >> 8; + const uint ltid = lane >> 2u; + const uint ix = lane & 3u; + const uint iq = ltid >> 2u; + const uint ir = ltid & 3u; + const uint l0 = 8u * ir; + const uint q_off = 32u * iq + l0; + const uint sh_h = 2u * iq; + + device const block_q5_K* w_base = reinterpret_cast(w0); + device const block_q5_K* w_row[NR]; + for (int r = 0; r < NR; ++r) w_row[r] = w_base + ulong(min(o0 + r, no - 1)) * ulong(nb); + + float sumf[MAXR][NR]; + for (int t = 0; t < MAXR; ++t) for (int r = 0; r < NR; ++r) sumf[t][r] = 0.0f; + + for (int ib = int(ix); ib < nb; ib += 4) { + short4 w0a[NR], w0b[NR], w1a[NR], w1b[NR], w2a[NR], w2b[NR], w3a[NR], w3b[NR]; + float4 dl[NR], ml[NR]; + for (int r = 0; r < NR; ++r) { + device const block_q5_K* blk = w_row[r] + ib; + float sc0, sc1, sc2, sc3, mn0, mn1, mn2, mn3; + unpack_k4_scales(blk->scales, iq, sc0, sc1, sc2, sc3, mn0, mn1, mn2, mn3); + dl[r] = float(blk->d) * float4(sc0, sc1, sc2, sc3); + ml[r] = float(blk->dmin) * float4(mn0, mn1, mn2, mn3); + device const uint* q1_u = reinterpret_cast(blk->qs + q_off); + device const uint* q2_u = q1_u + 16; + device const uint* qh_u = reinterpret_cast(blk->qh + l0); + const uint q1w0 = q1_u[0], q1w1 = q1_u[1]; + const uint q2w0 = q2_u[0], q2w1 = q2_u[1]; + const uint h0 = qh_u[0] >> sh_h, h1 = qh_u[1] >> sh_h; + w0a[r] = short4(as_type((q1w0 & 0x0F0F0F0Fu) | ((h0 << 4u) & 0x10101010u))); + w0b[r] = short4(as_type((q1w1 & 0x0F0F0F0Fu) | ((h1 << 4u) & 0x10101010u))); + w1a[r] = short4(as_type(((q1w0 >> 4u) & 0x0F0F0F0Fu) | ((h0 << 3u) & 0x10101010u))); + w1b[r] = short4(as_type(((q1w1 >> 4u) & 0x0F0F0F0Fu) | ((h1 << 3u) & 0x10101010u))); + w2a[r] = short4(as_type((q2w0 & 0x0F0F0F0Fu) | (h0 & 0x10101010u))); + w2b[r] = short4(as_type((q2w1 & 0x0F0F0F0Fu) | (h1 & 0x10101010u))); + w3a[r] = short4(as_type(((q2w0 >> 4u) & 0x0F0F0F0Fu) | ((h0 >> 1u) & 0x10101010u))); + w3b[r] = short4(as_type(((q2w1 >> 4u) & 0x0F0F0F0Fu) | ((h1 >> 1u) & 0x10101010u))); + } + for (int t = 0; t < MAXR; ++t) { + if (t >= rows) break; + device const uchar* xb0 = x0 + ulong(t) * xstride + ulong(ib) * 288ul + ulong(2u * iq) * 36ul; + device const uchar* xb1 = xb0 + 36ul; + device const uchar* xb2 = xb0 + 144ul; + device const uchar* xb3 = xb0 + 180ul; + const float4 dx = float4( + float(*reinterpret_cast(xb0)), + float(*reinterpret_cast(xb1)), + float(*reinterpret_cast(xb2)), + float(*reinterpret_cast(xb3))); + device const char4* qx0 = reinterpret_cast(xb0 + 4u + l0); + device const char4* qx1 = reinterpret_cast(xb1 + 4u + l0); + device const char4* qx2 = reinterpret_cast(xb2 + 4u + l0); + device const char4* qx3 = reinterpret_cast(xb3 + 4u + l0); + const short4 q0a = short4(qx0[0]), q0b = short4(qx0[1]); + const short4 q1a = short4(qx1[0]), q1b = short4(qx1[1]); + const short4 q2a = short4(qx2[0]), q2b = short4(qx2[1]); + const short4 q3a = short4(qx3[0]), q3b = short4(qx3[1]); + const short4 s0 = q0a + q0b, s1 = q1a + q1b, s2 = q2a + q2b, s3 = q3a + q3b; + const float4 sy = dx * float4( + float((s0.x + s0.y) + (s0.z + s0.w)), + float((s1.x + s1.y) + (s1.z + s1.w)), + float((s2.x + s2.y) + (s2.z + s2.w)), + float((s3.x + s3.y) + (s3.z + s3.w))); + for (int r = 0; r < NR; ++r) { + const short4 p0 = w0a[r] * q0a + w0b[r] * q0b; + const short4 p1 = w1a[r] * q1a + w1b[r] * q1b; + const short4 p2 = w2a[r] * q2a + w2b[r] * q2b; + const short4 p3 = w3a[r] * q3a + w3b[r] * q3b; + const float4 av = dx * float4( + float((p0.x + p0.y) + (p0.z + p0.w)), + float((p1.x + p1.y) + (p1.z + p1.w)), + float((p2.x + p2.y) + (p2.z + p2.w)), + float((p3.x + p3.y) + (p3.z + p3.w))); + sumf[t][r] += dot(dl[r], av) - dot(ml[r], sy); + } + } + } + + for (int t = 0; t < MAXR; ++t) { + if (t >= rows) break; + for (int r = 0; r < NR; ++r) { + const float tot = simd_sum(sumf[t][r]); + if (lane == 0u && o0 + r < no) out_y[ulong(t) * ystride + ulong(o0 + r)] = tot; + } + } +} + +template +kernel void poly_mul_q6_K_fast_t(constant QArgs& a [[buffer(0)]], uint3 group [[threadgroup_position_in_grid]], + uint tid [[thread_index_in_threadgroup]]) { + const uint sg = tid >> 5u, lane = tid & 31u; + device const uchar* w0 = nullptr; + device const uchar* x0 = nullptr; + device float* out_y = nullptr; + int no = 0, o0 = 0; + ulong xstride = 0, ystride = 0; + if (!map_fast_group(a, group.x * uint(NSG) + sg, uint(NR), w0, x0, out_y, no, o0, xstride, ystride)) return; + + const int nb = a.ni >> 8; + const uint ltid = lane >> 1u; // 0..15 + const uint ix = lane & 1u; // 0..1 (2 superblocks in parallel across SIMD group) + const uint ip = ltid >> 3u; // 0..1 + const uint il = ltid & 7u; // 0..7 + const uint l0 = 4u * il; // 0, 4, ..., 28 + const uint is = 8u * ip + (l0 >> 4u); + const uint q_off_l = 64u * ip + l0; + const uint q_off_h = 32u * ip + l0; + + device const block_q6_K* w_base = reinterpret_cast(w0); + device const block_q6_K* w_row[NR]; + for (int r = 0; r < NR; ++r) w_row[r] = w_base + ulong(min(o0 + r, no - 1)) * ulong(nb); + + float sumf[NR]; + for (int r = 0; r < NR; ++r) sumf[r] = 0.0f; + + for (int ib = int(ix); ib < nb; ib += 2) { + device const uchar* xb0 = x0 + ulong(ib) * 288ul + ulong(4u * ip) * 36ul; + device const uchar* xb1 = xb0 + 36ul; + device const uchar* xb2 = xb0 + 72ul; + device const uchar* xb3 = xb0 + 108ul; + const float4 dx = float4( + float(*reinterpret_cast(xb0)), + float(*reinterpret_cast(xb1)), + float(*reinterpret_cast(xb2)), + float(*reinterpret_cast(xb3))); + const short4 q0 = short4(*reinterpret_cast(xb0 + 4u + l0)); + const short4 q1 = short4(*reinterpret_cast(xb1 + 4u + l0)); + const short4 q2 = short4(*reinterpret_cast(xb2 + 4u + l0)); + const short4 q3 = short4(*reinterpret_cast(xb3 + 4u + l0)); + + for (int r = 0; r < NR; ++r) { + device const block_q6_K* blk = w_row[r] + ib; + // block_q6_K is 210 bytes (2-byte aligned); packed_ushort2 loads 4 bytes safely with 2-byte alignment. + const uint q1w = as_type(ushort2(*reinterpret_cast(blk->ql + q_off_l))); + const uint q2w = as_type(ushort2(*reinterpret_cast(blk->ql + q_off_l + 32u))); + const uint qhw = as_type(ushort2(*reinterpret_cast(blk->qh + q_off_h))); + // Exact 16-bit integer dot: max 4 * 32 * 128 = 16,384 <= 32,767. + const short4 p0 = (short4(as_type((q1w & 0x0F0F0F0Fu) | ((qhw & 0x03030303u) << 4u))) - short4(32)) * q0; + const short4 p1 = (short4(as_type((q2w & 0x0F0F0F0Fu) | ((qhw & 0x0C0C0C0Cu) << 2u))) - short4(32)) * q1; + const short4 p2 = (short4(as_type(((q1w >> 4u) & 0x0F0F0F0Fu) | (qhw & 0x30303030u))) - short4(32)) * q2; + const short4 p3 = (short4(as_type(((q2w >> 4u) & 0x0F0F0F0Fu) | ((qhw & 0xC0C0C0C0u) >> 2u))) - short4(32)) * q3; + device const int8_t* sc = blk->scales + is; + const float4 av = dx * float4( + float((p0.x + p0.y) + (p0.z + p0.w)), + float((p1.x + p1.y) + (p1.z + p1.w)), + float((p2.x + p2.y) + (p2.z + p2.w)), + float((p3.x + p3.y) + (p3.z + p3.w))); + sumf[r] += float(blk->d) * dot(float4(float(sc[0]), float(sc[2]), float(sc[4]), float(sc[6])), av); + } + } + + for (int r = 0; r < NR; ++r) { + const float tot = simd_sum(sumf[r]); + if (lane == 0u && o0 + r < no) out_y[o0 + r] = tot; + } +} + +template +kernel void poly_mulr2_q6_K_fast_t(constant QArgs& a [[buffer(0)]], uint3 group [[threadgroup_position_in_grid]], + uint tid [[thread_index_in_threadgroup]]) { + const uint sg = tid >> 5u, lane = tid & 31u; + device const uchar* w0 = nullptr; + device const uchar* x0 = nullptr; + device float* out_y = nullptr; + int no = 0, o0 = 0; + ulong xstride = 0, ystride = 0; + if (!map_fast_group(a, group.x * uint(NSG) + sg, uint(NR), w0, x0, out_y, no, o0, xstride, ystride)) return; + + const int rows = a.rows; + const int nb = a.ni >> 8; + const uint ltid = lane >> 1u; + const uint ix = lane & 1u; + const uint ip = ltid >> 3u; + const uint il = ltid & 7u; + const uint l0 = 4u * il; + const uint is = 8u * ip + (l0 >> 4u); + const uint q_off_l = 64u * ip + l0; + const uint q_off_h = 32u * ip + l0; + + device const block_q6_K* w_base = reinterpret_cast(w0); + device const block_q6_K* w_row[NR]; + for (int r = 0; r < NR; ++r) w_row[r] = w_base + ulong(min(o0 + r, no - 1)) * ulong(nb); + + float sumf[MAXR][NR]; + for (int t = 0; t < MAXR; ++t) for (int r = 0; r < NR; ++r) sumf[t][r] = 0.0f; + + for (int ib = int(ix); ib < nb; ib += 2) { + short4 wv0[NR], wv1[NR], wv2[NR], wv3[NR]; + float4 ds[NR]; + for (int r = 0; r < NR; ++r) { + device const block_q6_K* blk = w_row[r] + ib; + const uint q1w = as_type(ushort2(*reinterpret_cast(blk->ql + q_off_l))); + const uint q2w = as_type(ushort2(*reinterpret_cast(blk->ql + q_off_l + 32u))); + const uint qhw = as_type(ushort2(*reinterpret_cast(blk->qh + q_off_h))); + wv0[r] = short4(as_type((q1w & 0x0F0F0F0Fu) | ((qhw & 0x03030303u) << 4u))) - short4(32); + wv1[r] = short4(as_type((q2w & 0x0F0F0F0Fu) | ((qhw & 0x0C0C0C0Cu) << 2u))) - short4(32); + wv2[r] = short4(as_type(((q1w >> 4u) & 0x0F0F0F0Fu) | (qhw & 0x30303030u))) - short4(32); + wv3[r] = short4(as_type(((q2w >> 4u) & 0x0F0F0F0Fu) | ((qhw & 0xC0C0C0C0u) >> 2u))) - short4(32); + device const int8_t* sc = blk->scales + is; + ds[r] = float(blk->d) * float4(float(sc[0]), float(sc[2]), float(sc[4]), float(sc[6])); + } + for (int t = 0; t < MAXR; ++t) { + if (t >= rows) break; + device const uchar* xb0 = x0 + ulong(t) * xstride + ulong(ib) * 288ul + ulong(4u * ip) * 36ul; + device const uchar* xb1 = xb0 + 36ul; + device const uchar* xb2 = xb0 + 72ul; + device const uchar* xb3 = xb0 + 108ul; + const float4 dx = float4( + float(*reinterpret_cast(xb0)), + float(*reinterpret_cast(xb1)), + float(*reinterpret_cast(xb2)), + float(*reinterpret_cast(xb3))); + const short4 q0 = short4(*reinterpret_cast(xb0 + 4u + l0)); + const short4 q1 = short4(*reinterpret_cast(xb1 + 4u + l0)); + const short4 q2 = short4(*reinterpret_cast(xb2 + 4u + l0)); + const short4 q3 = short4(*reinterpret_cast(xb3 + 4u + l0)); + for (int r = 0; r < NR; ++r) { + const short4 p0 = wv0[r] * q0; + const short4 p1 = wv1[r] * q1; + const short4 p2 = wv2[r] * q2; + const short4 p3 = wv3[r] * q3; + const float4 av = dx * float4( + float((p0.x + p0.y) + (p0.z + p0.w)), + float((p1.x + p1.y) + (p1.z + p1.w)), + float((p2.x + p2.y) + (p2.z + p2.w)), + float((p3.x + p3.y) + (p3.z + p3.w))); + sumf[t][r] += dot(ds[r], av); + } + } + } + + for (int t = 0; t < MAXR; ++t) { + if (t >= rows) break; + for (int r = 0; r < NR; ++r) { + const float tot = simd_sum(sumf[t][r]); + if (lane == 0u && o0 + r < no) out_y[ulong(t) * ystride + ulong(o0 + r)] = tot; + } + } +} + +template +kernel void poly_mul_q4_K_fast_t(constant QArgs& a [[buffer(0)]], uint3 group [[threadgroup_position_in_grid]], + uint tid [[thread_index_in_threadgroup]]) { + const uint sg = tid >> 5u, lane = tid & 31u; + device const uchar* w0 = nullptr; + device const uchar* x0 = nullptr; + device float* out_y = nullptr; + int no = 0, o0 = 0; + ulong xstride = 0, ystride = 0; + if (!map_fast_group(a, group.x * uint(NSG) + sg, uint(NR), w0, x0, out_y, no, o0, xstride, ystride)) return; + + const int nb = a.ni >> 8; + const uint ltid = lane >> 2u; + const uint ix = lane & 3u; + const uint iq = ltid >> 2u; + const uint ir = ltid & 3u; + const uint l0 = 8u * ir; + const uint q_off = 32u * iq + l0; + + device const block_q4_K* w_base = reinterpret_cast(w0); + device const block_q4_K* w_row[NR]; + for (int r = 0; r < NR; ++r) w_row[r] = w_base + ulong(min(o0 + r, no - 1)) * ulong(nb); + + float sumf[NR]; + for (int r = 0; r < NR; ++r) sumf[r] = 0.0f; + + for (int ib = int(ix); ib < nb; ib += 4) { + device const uchar* xb0 = x0 + ulong(ib) * 288ul + ulong(2u * iq) * 36ul; + device const uchar* xb1 = xb0 + 36ul; + device const uchar* xb2 = xb0 + 144ul; + device const uchar* xb3 = xb0 + 180ul; + const float4 dx = float4( + float(*reinterpret_cast(xb0)), + float(*reinterpret_cast(xb1)), + float(*reinterpret_cast(xb2)), + float(*reinterpret_cast(xb3))); + device const char4* qx0 = reinterpret_cast(xb0 + 4u + l0); + device const char4* qx1 = reinterpret_cast(xb1 + 4u + l0); + device const char4* qx2 = reinterpret_cast(xb2 + 4u + l0); + device const char4* qx3 = reinterpret_cast(xb3 + 4u + l0); + const short4 q0a = short4(qx0[0]), q0b = short4(qx0[1]); + const short4 q1a = short4(qx1[0]), q1b = short4(qx1[1]); + const short4 q2a = short4(qx2[0]), q2b = short4(qx2[1]); + const short4 q3a = short4(qx3[0]), q3b = short4(qx3[1]); + const short4 s0 = q0a + q0b, s1 = q1a + q1b, s2 = q2a + q2b, s3 = q3a + q3b; + const float4 sy = dx * float4( + float((s0.x + s0.y) + (s0.z + s0.w)), + float((s1.x + s1.y) + (s1.z + s1.w)), + float((s2.x + s2.y) + (s2.z + s2.w)), + float((s3.x + s3.y) + (s3.z + s3.w))); + + for (int r = 0; r < NR; ++r) { + device const block_q4_K* blk = w_row[r] + ib; + float sc0, sc1, sc2, sc3, mn0, mn1, mn2, mn3; + unpack_k4_scales(blk->scales, iq, sc0, sc1, sc2, sc3, mn0, mn1, mn2, mn3); + device const uint* q1_u = reinterpret_cast(blk->qs + q_off); + device const uint* q2_u = q1_u + 16; + const uint q1w0 = q1_u[0], q1w1 = q1_u[1]; + const uint q2w0 = q2_u[0], q2w1 = q2_u[1]; + + // Exact 16-bit integer dot: max 8 * 15 * 128 = 15,360 <= 32,767. + const short4 p0 = short4(as_type(q1w0 & 0x0F0F0F0Fu)) * q0a + + short4(as_type(q1w1 & 0x0F0F0F0Fu)) * q0b; + const short4 p1 = short4(as_type((q1w0 >> 4u) & 0x0F0F0F0Fu)) * q1a + + short4(as_type((q1w1 >> 4u) & 0x0F0F0F0Fu)) * q1b; + const short4 p2 = short4(as_type(q2w0 & 0x0F0F0F0Fu)) * q2a + + short4(as_type(q2w1 & 0x0F0F0F0Fu)) * q2b; + const short4 p3 = short4(as_type((q2w0 >> 4u) & 0x0F0F0F0Fu)) * q3a + + short4(as_type((q2w1 >> 4u) & 0x0F0F0F0Fu)) * q3b; + + const float4 av = dx * float4( + float((p0.x + p0.y) + (p0.z + p0.w)), + float((p1.x + p1.y) + (p1.z + p1.w)), + float((p2.x + p2.y) + (p2.z + p2.w)), + float((p3.x + p3.y) + (p3.z + p3.w))); + sumf[r] += float(blk->d) * dot(float4(sc0, sc1, sc2, sc3), av) + - float(blk->dmin) * dot(float4(mn0, mn1, mn2, mn3), sy); + } + } + + for (int r = 0; r < NR; ++r) { + const float tot = simd_sum(sumf[r]); + if (lane == 0u && o0 + r < no) out_y[o0 + r] = tot; + } +} + +template +kernel void poly_mulr2_q4_K_fast_t(constant QArgs& a [[buffer(0)]], uint3 group [[threadgroup_position_in_grid]], + uint tid [[thread_index_in_threadgroup]]) { + const uint sg = tid >> 5u, lane = tid & 31u; + device const uchar* w0 = nullptr; + device const uchar* x0 = nullptr; + device float* out_y = nullptr; + int no = 0, o0 = 0; + ulong xstride = 0, ystride = 0; + if (!map_fast_group(a, group.x * uint(NSG) + sg, uint(NR), w0, x0, out_y, no, o0, xstride, ystride)) return; + + const int rows = a.rows; + const int nb = a.ni >> 8; + const uint ltid = lane >> 2u; + const uint ix = lane & 3u; + const uint iq = ltid >> 2u; + const uint ir = ltid & 3u; + const uint l0 = 8u * ir; + const uint q_off = 32u * iq + l0; + + device const block_q4_K* w_base = reinterpret_cast(w0); + device const block_q4_K* w_row[NR]; + for (int r = 0; r < NR; ++r) w_row[r] = w_base + ulong(min(o0 + r, no - 1)) * ulong(nb); + + float sumf[MAXR][NR]; + for (int t = 0; t < MAXR; ++t) for (int r = 0; r < NR; ++r) sumf[t][r] = 0.0f; + + for (int ib = int(ix); ib < nb; ib += 4) { + short4 w0a[NR], w0b[NR], w1a[NR], w1b[NR], w2a[NR], w2b[NR], w3a[NR], w3b[NR]; + float4 dl[NR], ml[NR]; + for (int r = 0; r < NR; ++r) { + device const block_q4_K* blk = w_row[r] + ib; + float sc0, sc1, sc2, sc3, mn0, mn1, mn2, mn3; + unpack_k4_scales(blk->scales, iq, sc0, sc1, sc2, sc3, mn0, mn1, mn2, mn3); + dl[r] = float(blk->d) * float4(sc0, sc1, sc2, sc3); + ml[r] = float(blk->dmin) * float4(mn0, mn1, mn2, mn3); + device const uint* q1_u = reinterpret_cast(blk->qs + q_off); + device const uint* q2_u = q1_u + 16; + const uint q1w0 = q1_u[0], q1w1 = q1_u[1]; + const uint q2w0 = q2_u[0], q2w1 = q2_u[1]; + w0a[r] = short4(as_type(q1w0 & 0x0F0F0F0Fu)); + w0b[r] = short4(as_type(q1w1 & 0x0F0F0F0Fu)); + w1a[r] = short4(as_type((q1w0 >> 4u) & 0x0F0F0F0Fu)); + w1b[r] = short4(as_type((q1w1 >> 4u) & 0x0F0F0F0Fu)); + w2a[r] = short4(as_type(q2w0 & 0x0F0F0F0Fu)); + w2b[r] = short4(as_type(q2w1 & 0x0F0F0F0Fu)); + w3a[r] = short4(as_type((q2w0 >> 4u) & 0x0F0F0F0Fu)); + w3b[r] = short4(as_type((q2w1 >> 4u) & 0x0F0F0F0Fu)); + } + for (int t = 0; t < MAXR; ++t) { + if (t >= rows) break; + device const uchar* xb0 = x0 + ulong(t) * xstride + ulong(ib) * 288ul + ulong(2u * iq) * 36ul; + device const uchar* xb1 = xb0 + 36ul; + device const uchar* xb2 = xb0 + 144ul; + device const uchar* xb3 = xb0 + 180ul; + const float4 dx = float4( + float(*reinterpret_cast(xb0)), + float(*reinterpret_cast(xb1)), + float(*reinterpret_cast(xb2)), + float(*reinterpret_cast(xb3))); + device const char4* qx0 = reinterpret_cast(xb0 + 4u + l0); + device const char4* qx1 = reinterpret_cast(xb1 + 4u + l0); + device const char4* qx2 = reinterpret_cast(xb2 + 4u + l0); + device const char4* qx3 = reinterpret_cast(xb3 + 4u + l0); + const short4 q0a = short4(qx0[0]), q0b = short4(qx0[1]); + const short4 q1a = short4(qx1[0]), q1b = short4(qx1[1]); + const short4 q2a = short4(qx2[0]), q2b = short4(qx2[1]); + const short4 q3a = short4(qx3[0]), q3b = short4(qx3[1]); + const short4 s0 = q0a + q0b, s1 = q1a + q1b, s2 = q2a + q2b, s3 = q3a + q3b; + const float4 sy = dx * float4( + float((s0.x + s0.y) + (s0.z + s0.w)), + float((s1.x + s1.y) + (s1.z + s1.w)), + float((s2.x + s2.y) + (s2.z + s2.w)), + float((s3.x + s3.y) + (s3.z + s3.w))); + for (int r = 0; r < NR; ++r) { + const short4 p0 = w0a[r] * q0a + w0b[r] * q0b; + const short4 p1 = w1a[r] * q1a + w1b[r] * q1b; + const short4 p2 = w2a[r] * q2a + w2b[r] * q2b; + const short4 p3 = w3a[r] * q3a + w3b[r] * q3b; + const float4 av = dx * float4( + float((p0.x + p0.y) + (p0.z + p0.w)), + float((p1.x + p1.y) + (p1.z + p1.w)), + float((p2.x + p2.y) + (p2.z + p2.w)), + float((p3.x + p3.y) + (p3.z + p3.w))); + sumf[t][r] += dot(dl[r], av) - dot(ml[r], sy); + } + } + } + + for (int t = 0; t < MAXR; ++t) { + if (t >= rows) break; + for (int r = 0; r < NR; ++r) { + const float tot = simd_sum(sumf[t][r]); + if (lane == 0u && o0 + r < no) out_y[ulong(t) * ystride + ulong(o0 + r)] = tot; + } + } +} + +template [[host_name("poly_mul_q5_K_fast")]] kernel decltype(poly_mul_q5_K_fast_t<2, 2>) poly_mul_q5_K_fast_t<2, 2>; +template [[host_name("poly_mul_q5_K_fast4")]] kernel decltype(poly_mul_q5_K_fast_t<2, 4>) poly_mul_q5_K_fast_t<2, 4>; +template [[host_name("poly_mulr2_q5_K_fast_r4")]] kernel decltype(poly_mulr2_q5_K_fast_t<4, 2, 4>) poly_mulr2_q5_K_fast_t<4, 2, 4>; +template [[host_name("poly_mul_q6_K_fast")]] kernel decltype(poly_mul_q6_K_fast_t<2, 2>) poly_mul_q6_K_fast_t<2, 2>; +template [[host_name("poly_mul_q6_K_fast4")]] kernel decltype(poly_mul_q6_K_fast_t<4, 4>) poly_mul_q6_K_fast_t<4, 4>; +template [[host_name("poly_mulr2_q6_K_fast_r4")]] kernel decltype(poly_mulr2_q6_K_fast_t<2, 4, 4>) poly_mulr2_q6_K_fast_t<2, 4, 4>; +template [[host_name("poly_mulr2_q6_K_fast_r8")]] kernel decltype(poly_mulr2_q6_K_fast_t<2, 2, 8>) poly_mulr2_q6_K_fast_t<2, 2, 8>; +template [[host_name("poly_mul_q4_K_fast")]] kernel decltype(poly_mul_q4_K_fast_t<2, 2>) poly_mul_q4_K_fast_t<2, 2>; +template [[host_name("poly_mul_q4_K_fast4")]] kernel decltype(poly_mul_q4_K_fast_t<4, 4>) poly_mul_q4_K_fast_t<4, 4>; +template [[host_name("poly_mulr2_q4_K_fast_r4")]] kernel decltype(poly_mulr2_q4_K_fast_t<4, 2, 4>) poly_mulr2_q4_K_fast_t<4, 2, 4>; +template [[host_name("poly_mulr2_q4_K_fast_r8")]] kernel decltype(poly_mulr2_q4_K_fast_t<2, 2, 8>) poly_mulr2_q4_K_fast_t<2, 2, 8>; #ifdef MV_DEQ // poly_mv_bench's: poly_mul__deq4 and _deq1, every type from its block decoder template struct BenchDot { enum { kSum=0 };