Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.
C++
metal: simdgroup-matrix GEMV for windows (exact, measured slower; kept as a reference path)
Niko122179b98c82b7b0
diff --git a/metal/kernels/mma.metal b/metal/kernels/mma.metalnew file mode 100644index 000000000..00b4245c9--- /dev/null+++ b/metal/kernels/mma.metal@@ -0,0 +1,196 @@+// metal/kernels/mma.metal - a GEMV for windows of tokens on the simdgroup matrix units (after quant/units.metal).+//+// y[t][r] = W[r] . x[t] for NTOK (1..8) tokens: each simdgroup owns 8 rows; the K axis runs in chunks of 128. Per+// chunk the simdgroup decodes its 8 x 128 weights - with ref_quant's arithmetic, so a tile element is exactly the+// dequantized weight - into threadgroup memory, then 16 simdgroup_multiply_accumulate steps take A = the 8 x 8 weight+// tile and B = the 8 (k) x 8 (token) slice of x, loaded transposed straight from device memory (x has 8 rows: the+// tokens past the window are padding, and an output column depends only on its own token).+//+// Activations are the raw plane (no pre-scaling); n_in must be a multiple of 128. Every format's units sit inside+// one 128-wide chunk: Q4_K/Q5_K units span 64 positions, Q6_K units 128, the others are contiguous.++// ---- decoders to actual weights: w[UNIT] and the chunk offsets of its two halves (p0: w[0..H), p1: w[H..UNIT)) ----+template <int F> struct DW {+ // generic: w = s * q (quant.metal's deq is ref_quant's order: the scale times the code), contiguous+ static inline void run(device const uchar* row, int u, int k0, thread float* w, thread int& p0, thread int& p1,+ threadgroup const uint* tab) {+ constexpr int UNIT = fmt<F>::UNIT, UPB = fmt<F>::QK / UNIT;+ float q[UNIT];+ const float s = deq<F>(row + (u / UPB) * fmt<F>::BB, u % UPB, q, tab);+ for (int j = 0; j < UNIT; ++j) w[j] = q[j] * s;+ p0 = u * UNIT - k0;+ p1 = p0 + UNIT / 2;+ }+};+// Q2_0: (code - 1) * d+template <> struct DW<T_Q2_0> {+ static inline void run(device const uchar* row, int u, int k0, thread float* w, thread int& p0, thread int& p1,+ threadgroup const uint*) {+ device const uchar* b = row + (u >> 2) * 18;+ device const ushort* p = (device const ushort*)(b + 2 + 4 * (u & 3));+ const ushort a = p[0], c = p[1];+ const float d = rdh(b);+ for (int j = 0; j < 8; ++j) {+ w[j] = float(int((a >> (2 * j)) & 3) - 1) * d;+ w[8 + j] = float(int((c >> (2 * j)) & 3) - 1) * d;+ }+ p0 = 16 * u - k0;+ p1 = p0 + 8;+ }+};+template <> struct DW<T_BF16> {+ static inline void run(device const uchar* row, int u, int k0, thread float* w, thread int& p0, thread int& p1,+ threadgroup const uint*) {+ device const uint4* p = (device const uint4*)(row + 32 * u);+ const uint4 a = p[0], c = p[1];+ const uint v[8] = {a.x, a.y, a.z, a.w, c.x, c.y, c.z, c.w};+ for (int k = 0; k < 8; ++k) {+ w[2 * k] = as_type<float>(v[k] << 16);+ w[2 * k + 1] = as_type<float>(v[k] & 0xFFFF0000u);+ }+ p0 = 16 * u - k0;+ p1 = p0 + 8;+ }+};+// Q4_K / Q5_K: d1 * code - m1 (ref: d * sc, dmin * m), runs at 256b + 64c + 16m and + 32+template <> struct DW<T_Q4_K> {+ static inline void run(device const uchar* row, int u, int k0, thread float* w, thread int& p0, thread int& p1,+ threadgroup const uint*) {+ device const uchar* b = row + (u >> 3) * 144;+ const int c = (u >> 1) & 3, m = u & 1;+ const float d = rdh(b), dm = rdh(b + 2);+ float s1, m1, s2, m2;+ scale_min_k4(2 * c, b + 4, s1, m1);+ scale_min_k4(2 * c + 1, b + 4, s2, m2);+ const float d1 = d * s1, mm1 = dm * m1, d2 = d * s2, mm2 = dm * m2;+ device const uchar* q = b + 16 + 32 * c + 16 * m;+ for (int j = 0; j < 16; ++j) {+ w[j] = d1 * float(q[j] & 15) - mm1;+ w[16 + j] = d2 * float(q[j] >> 4) - mm2;+ }+ p0 = 256 * (u >> 3) + 64 * c + 16 * m - k0;+ p1 = p0 + 32;+ }+};+template <> struct DW<T_Q5_K> {+ static inline void run(device const uchar* row, int u, int k0, thread float* w, thread int& p0, thread int& p1,+ threadgroup const uint*) {+ device const uchar* b = row + (u >> 3) * 176;+ const int c = (u >> 1) & 3, m = u & 1;+ const float d = rdh(b), dm = rdh(b + 2);+ float s1, m1, s2, m2;+ scale_min_k4(2 * c, b + 4, s1, m1);+ scale_min_k4(2 * c + 1, b + 4, s2, m2);+ const float d1 = d * s1, mm1 = dm * m1, d2 = d * s2, mm2 = dm * m2;+ device const uchar* ql = b + 48 + 32 * c + 16 * m;+ device const uchar* qh = b + 16 + 16 * m;+ const uchar u1 = uchar(1 << (2 * c)), u2 = uchar(2 << (2 * c));+ for (int j = 0; j < 16; ++j) {+ w[j] = d1 * float((ql[j] & 15) + ((qh[j] & u1) ? 16 : 0)) - mm1;+ w[16 + j] = d2 * float((ql[j] >> 4) + ((qh[j] & u2) ? 16 : 0)) - mm2;+ }+ p0 = 256 * (u >> 3) + 64 * c + 16 * m - k0;+ p1 = p0 + 32;+ }+};+// Q6_K: d * sc * (code - 32), runs at 256b + 128n + 32p + 16m and + 64+template <> struct DW<T_Q6_K> {+ static inline void run(device const uchar* row, int u, int k0, thread float* w, thread int& p0, thread int& p1,+ threadgroup const uint*) {+ device const uchar* b = row + (u >> 3) * 210;+ const int n = (u >> 2) & 1, m = (u >> 1) & 1, p = u & 1;+ device const uchar* ql = b + 64 * n + 32 * p + 16 * m;+ device const uchar* qh = b + 128 + 32 * n + 16 * m;+ device const char* sc = (device const char*)(b + 192);+ const float d = rdh(b + 208);+ const float ds1 = d * float(sc[8 * n + m + 2 * p]), ds2 = d * float(sc[8 * n + m + 2 * p + 4]);+ for (int j = 0; j < 16; ++j) {+ const int c1 = int((ql[j] & 15) | (((qh[j] >> (2 * p)) & 3) << 4)) - 32;+ const int c2 = int((ql[j] >> 4) | (((qh[j] >> (2 * p + 4)) & 3) << 4)) - 32;+ w[j] = ds1 * float(c1);+ w[16 + j] = ds2 * float(c2);+ }+ p0 = 256 * (u >> 3) + 128 * n + 32 * p + 16 * m - k0;+ p1 = p0 + 64;+ }+};+// Q3_K: d_all * (sc - 32) * (code - (hbit ? 0 : 4)), contiguous 32+template <> struct DW<T_Q3_K> {+ static inline void run(device const uchar* row, int u, int k0, thread float* w, thread int& p0, thread int& p1,+ threadgroup const uint*) {+ device const uchar* b = row + (u >> 3) * 110;+ const int n = (u >> 2) & 1, j = u & 3;+ device const uchar* q = b + 32 + 32 * n;+ device const uchar* hm = b;+ device const uchar* s = b + 96;+ const int i1 = 8 * n + 2 * j, i2 = i1 + 1;+ const int l1 = (i1 < 8 ? s[i1] & 0xF : s[i1 - 8] >> 4) | (((s[8 + (i1 & 3)] >> (2 * (i1 >> 2))) & 3) << 4);+ const int l2 = (i2 < 8 ? s[i2] & 0xF : s[i2 - 8] >> 4) | (((s[8 + (i2 & 3)] >> (2 * (i2 >> 2))) & 3) << 4);+ const float d = rdh(b + 108);+ const float dl1 = d * float(l1 - 32), dl2 = d * float(l2 - 32);+ const uchar hb = uchar(1 << (4 * n + j));+ for (int l = 0; l < 16; ++l) {+ w[l] = dl1 * float(int((q[l] >> (2 * j)) & 3) - ((hm[l] & hb) ? 0 : 4));+ w[16 + l] = dl2 * float(int((q[l + 16] >> (2 * j)) & 3) - ((hm[l + 16] & hb) ? 0 : 4));+ }+ p0 = 32 * u - k0;+ p1 = p0 + 16;+ }+};++struct MmaArgs {+ uint n_in;+ uint n_out;+ uint row_bytes;+ uint x_stride; // floats between the 8 token rows of x+ uint y_stride;+};+constant int MMA_NTOK [[function_constant(4)]];++template <int F, int SG>+kernel void gemv_mma(device const uchar* W [[buffer(0)]], device const float* x [[buffer(1)]],+ device float* y [[buffer(2)]], constant MmaArgs& a [[buffer(3)]],+ uint3 tg [[threadgroup_position_in_grid]], ushort sg [[simdgroup_index_in_threadgroup]],+ ushort lane [[thread_index_in_simdgroup]], ushort tid [[thread_index_in_threadgroup]]) {+ constexpr int UNIT = fmt<F>::UNIT, UPC = 128 / UNIT, H = UNIT / 2;+ threadgroup float wt[SG][8 * 128];+ threadgroup float ct[SG][64];+ threadgroup uint tab[fmt<F>::TAB];+ load_tab<F>(tab, tid, SG * 32);+ threadgroup_barrier(mem_flags::mem_threadgroup);+ const int row0 = (int(tg.x) * SG + sg) * 8;+ simdgroup_float8x8 C = make_filled_simdgroup_matrix<float, 8, 8>(0.0f);+ threadgroup float* w8 = wt[sg];+ for (int k0 = 0; k0 < int(a.n_in); k0 += 128) {+ for (int it = lane; it < 8 * UPC; it += 32) {+ const int r = it / UPC, uu = it - r * UPC;+ const int rr = min(row0 + r, int(a.n_out) - 1);+ float w[UNIT];+ int p0, p1;+ DW<F>::run(W + ulong(rr) * a.row_bytes, k0 / UNIT + uu, k0, w, p0, p1, tab);+ for (int j = 0; j < H; ++j) {+ w8[r * 128 + p0 + j] = w[j];+ w8[r * 128 + p1 + j] = w[H + j];+ }+ }+ simdgroup_barrier(mem_flags::mem_threadgroup);+ for (int k8 = 0; k8 < 128; k8 += 8) {+ simdgroup_float8x8 A, B;+ simdgroup_load(A, w8 + k8, 128);+ simdgroup_load(B, x + k0 + k8, a.x_stride, ulong2(0, 0), true);+ simdgroup_multiply_accumulate(C, A, B, C);+ }+ simdgroup_barrier(mem_flags::mem_threadgroup);+ }+ simdgroup_store(C, ct[sg], 8);+ simdgroup_barrier(mem_flags::mem_threadgroup);+ for (int e = lane; e < 64; e += 32) {+ const int r = e >> 3, t = e & 7;+ if (t < MMA_NTOK && row0 + r < int(a.n_out)) y[t * int(a.y_stride) + row0 + r] = ct[sg][e];+ }+}++#define MM(F, S) template [[host_name("gemv_mma_" #F "_" #S)]] kernel decltype(gemv_mma<F, S>) gemv_mma<F, S>;+#define MM_SET(F) MM(F, 1) MM(F, 2) MM(F, 4)+MM_SET(T_BF16) MM_SET(T_Q8_0) MM_SET(T_Q4_0) MM_SET(T_Q5_0) MM_SET(T_IQ4_NL) MM_SET(T_IQ4_XS) MM_SET(T_Q2_0)+MM_SET(T_IQ3_S) MM_SET(T_Q3_K) MM_SET(T_Q4_K) MM_SET(T_Q5_K) MM_SET(T_Q6_K)diff --git a/metal/tests/mma_parity.cpp b/metal/tests/mma_parity.cppnew file mode 100644index 000000000..3181dbada--- /dev/null+++ b/metal/tests/mma_parity.cpp@@ -0,0 +1,178 @@+// metal/tests/mma_parity.cpp - the simdgroup-matrix GEMV (mma.metal): parity vs double for every dense format, each+// token of a window bitwise a one-token call, and its speed on the packs' shapes against the per-lane GEMV.+//+// mma_parity parity+// mma_parity --bench speed, 1 / 3 / 8 tokens+#include "mtl_rt.h"+#include "ref_quant.h"++#include <algorithm>+#include <cmath>+#include <cstdio>+#include <cstring>+#include <string>+#include <vector>++namespace {+struct MmaArgs { uint32_t n_in, n_out, row_bytes, x_stride, y_stride; };+struct GemvArgs { uint32_t n_in, n_out, n_tok, row_bytes, x_stride, y_stride; };+double median(std::vector<double> v) { std::sort(v.begin(), v.end()); return v[v.size() / 2]; }+int xkind(int t) {+ switch (t) {+ case ref::Q2_0: return 1;+ case ref::Q4_K: case ref::Q5_K: return 2;+ case ref::Q6_K: case ref::Q3_K: return 3;+ default: return 0;+ }+}+} // namespace++int main(int argc, char** argv) {+ const bool bench = argc > 1 && std::string(argv[1]) == "--bench";+ mtl::Context cx;+ const int lib = cx.compile({"quant.metal", "units.metal", "gemv.metal", "mma.metal"});+ std::printf("device %s\n", cx.device_name().c_str());+ const int MAXT = 8;+ mtl::Pipeline pprep = cx.pipeline(lib, "xprep");+ const std::vector<int> types = {ref::BF16, ref::Q8_0, ref::Q4_0, ref::Q5_0, ref::IQ4_NL, ref::IQ4_XS, ref::Q2_0,+ ref::IQ3_S, ref::Q3_K, ref::Q4_K, ref::Q5_K, ref::Q6_K};+ if (!bench) {+ int fails = 0;+ for (int t : types)+ for (int n_in : {2560, 640, 6144}) {+ if (n_in % ref::block_elems(t) || (n_in == 640 && ref::block_elems(t) == 256)) continue;+ const int n_out = 100;+ const size_t rb = ref::row_bytes(t, n_in);+ mtl::Buffer W = cx.alloc(rb * n_out), x = cx.alloc(4 * n_in * MAXT), y = cx.alloc(4 * n_out * MAXT),+ y1 = cx.alloc(4 * n_out * MAXT);+ ref::random_blocks(t, W.as<uint8_t>(), n_out, n_in, 41 + t, 0.02f);+ ref::Rng r(9);+ for (int i = 0; i < n_in * MAXT; ++i) x.as<float>()[i] = r.sym();+ std::vector<float> wf((size_t)n_in * n_out);+ ref::dequant(t, W.ptr, wf.data(), wf.size());+ for (int nt : {1, 3, 8}) {+ mtl::Pipeline p = cx.pipeline(lib, "gemv_mma_" + std::to_string(t) + "_2", mtl::Constants().i(4, nt));+ MmaArgs a{(uint32_t)n_in, (uint32_t)n_out, (uint32_t)rb, (uint32_t)n_in, (uint32_t)n_out};+ mtl::Dispatch d;+ d.p = &p;+ d.args = {mtl::Arg::B(W), mtl::Arg::B(x), mtl::Arg::B(y), mtl::Arg::V(a)};+ d.grid[0] = (n_out + 15) / 16;+ d.tg[0] = 64;+ cx.run({d});+ double se = 0, sr = 0;+ for (int tt = 0; tt < nt; ++tt)+ for (int o = 0; o < n_out; ++o) {+ double ref = 0;+ for (int k = 0; k < n_in; ++k) ref += (double)wf[(size_t)o * n_in + k] * x.as<float>()[tt * n_in + k];+ const double e = y.as<float>()[tt * n_out + o] - ref;+ se += e * e;+ sr += ref * ref;+ }+ // the window property: token tt's column vs a one-token call on x shifted to row 0+ int notex = 0;+ if (nt > 1) {+ mtl::Pipeline p1 = cx.pipeline(lib, "gemv_mma_" + std::to_string(t) + "_2", mtl::Constants().i(4, 1));+ for (int tt = 0; tt < nt; ++tt) {+ mtl::Dispatch d1 = d;+ d1.p = &p1;+ d1.args = {mtl::Arg::B(W), mtl::Arg::B(x, 4 * (size_t)tt * n_in), mtl::Arg::B(y1), mtl::Arg::V(a)};+ // rows past the window come from the following tokens' memory: padding only+ cx.run({d1});+ notex += std::memcmp(y1.ptr, y.as<float>() + tt * n_out, 4 * n_out) != 0;+ }+ }+ const double rel = std::sqrt(se / sr);+ const bool ok = rel < 1e-5 && notex == 0;+ fails += !ok;+ std::printf("mma parity %-7s n_in %5d ntok %d: rel L2 %.2e, window == one token: %s %s\n",+ ref::type_name(t), n_in, nt, rel, nt == 1 ? "-" : notex ? "NO" : "bitwise", ok ? "PASS" : "FAIL");+ }+ cx.free(W);+ cx.free(x);+ cx.free(y);+ cx.free(y1);+ }+ std::printf("%s\n", fails ? "SOME FAILED" : "ALL PASS");+ return fails ? 1 : 0;+ }+ struct Shape { const char* name; int type, n_in, n_out; };+ const std::vector<Shape> shapes = {{"gdn qkv", ref::IQ4_XS, 2560, 10240}, {"gdn qkv", ref::Q3_K, 2560, 10240},+ {"gdn qkv", ref::Q4_K, 2560, 10240}, {"gdn qkv", ref::Q6_K, 2560, 10240},+ {"gdn out", ref::Q5_K, 6144, 2560}, {"qsa q", ref::Q2_0, 2560, 12288},+ {"router", ref::BF16, 2560, 512}, {"lm head", ref::Q5_K, 2560, 248320}};+ std::printf("%-9s %-7s %5s | %9s %9s | %s\n", "shape", "type", "ntok", "lane us", "mma us", "mma GB/s (best SG)");+ for (const Shape& s : shapes) {+ const size_t rb = ref::row_bytes(s.type, s.n_in), mb = rb * s.n_out;+ const int copies = (int)std::max<size_t>(4, std::min<size_t>(64, (1ull << 30) / mb));+ mtl::Buffer W = cx.alloc(mb * copies), x = cx.alloc(4 * s.n_in * MAXT), y = cx.alloc(4 * (size_t)s.n_out * MAXT),+ xp = cx.alloc(4 * (4 * s.n_in * MAXT + s.n_in / 16 * MAXT));+ {+ std::vector<uint8_t> tmp(mb);+ ref::random_blocks(s.type, tmp.data(), s.n_out, s.n_in, 3, 0.02f);+ for (int c = 0; c < copies; ++c) std::memcpy(W.as<uint8_t>() + (size_t)c * mb, tmp.data(), mb);+ }+ ref::Rng r(5);+ for (int i = 0; i < s.n_in * MAXT; ++i) x.as<float>()[i] = r.sym();+ {+ mtl::Dispatch d;+ d.p = &pprep;+ const uint32_t n = s.n_in, nt = MAXT;+ d.args = {mtl::Arg::B(x), mtl::Arg::B(xp), mtl::Arg::V(n), mtl::Arg::V(nt)};+ d.tg[0] = 256;+ d.grid[0] = (s.n_in / 16 * MAXT + 255) / 256;+ cx.run({d});+ }+ const size_t plane = (size_t)4 * s.n_in * MAXT;+ for (int nt : {1, 3, 8}) {+ auto time = [&](std::vector<mtl::Dispatch>& ds) {+ cx.warm(ds, 0.1);+ std::vector<double> t;+ for (int i = 0; i < 5; ++i) t.push_back(cx.run(ds) / ds.size());+ return median(t);+ };+ // the per-lane GEMV with its usual tile+ const int L = s.n_in >= 6144 ? 32 : (s.n_out <= 640 || s.type == ref::Q2_0 || s.type == ref::BF16) ? 32 : 16;+ const int S = s.n_in >= 6144 ? 8 : 4, K = s.n_in >= 6144 ? 2 : 1;+ mtl::Pipeline pl = cx.pipeline(lib, "gemv_" + std::to_string(s.type) + "_" + std::to_string(L) + "_1_" ++ std::to_string(S) + "_" + std::to_string(K), mtl::Constants().i(0, nt));+ GemvArgs ga{(uint32_t)s.n_in, (uint32_t)s.n_out, (uint32_t)nt, (uint32_t)rb, (uint32_t)s.n_in, (uint32_t)s.n_out};+ std::vector<mtl::Dispatch> dl;+ for (int k = 0; k < std::max(copies, 16); ++k) {+ mtl::Dispatch d;+ d.p = &pl;+ d.args = {mtl::Arg::B(W, (size_t)(k % copies) * mb), mtl::Arg::B(xp, plane * xkind(s.type)),+ mtl::Arg::B(xp, plane * 4), mtl::Arg::B(y), mtl::Arg::V(ga)};+ const int rpt = (S / K) * (32 / L);+ d.grid[0] = (s.n_out + rpt - 1) / rpt;+ d.tg[0] = S * 32;+ dl.push_back(d);+ }+ const double tl = time(dl);+ double best = 1e9;+ int bsg = 0;+ for (int sgn : {1, 2, 4}) {+ mtl::Pipeline pm = cx.pipeline(lib, "gemv_mma_" + std::to_string(s.type) + "_" + std::to_string(sgn),+ mtl::Constants().i(4, nt));+ MmaArgs ma{(uint32_t)s.n_in, (uint32_t)s.n_out, (uint32_t)rb, (uint32_t)s.n_in, (uint32_t)s.n_out};+ std::vector<mtl::Dispatch> dm;+ for (int k = 0; k < std::max(copies, 16); ++k) {+ mtl::Dispatch d;+ d.p = ±+ d.args = {mtl::Arg::B(W, (size_t)(k % copies) * mb), mtl::Arg::B(x), mtl::Arg::B(y), mtl::Arg::V(ma)};+ d.grid[0] = (s.n_out + 8 * sgn - 1) / (8 * sgn);+ d.tg[0] = 32 * sgn;+ dm.push_back(d);+ }+ const double tm = time(dm);+ if (tm < best) { best = tm; bsg = sgn; }+ }+ std::printf("%-9s %-7s %5d | %9.2f %9.2f | %6.1f (SG %d) lane %6.1f GB/s\n", s.name, ref::type_name(s.type), nt,+ tl * 1e6, best * 1e6, mb / best / 1e9, bsg, mb / tl / 1e9);+ }+ cx.free(W);+ cx.free(x);+ cx.free(y);+ cx.free(xp);+ }+ return 0;+}diff --git a/metal/tests/token_chain.cpp b/metal/tests/token_chain.cppindex ffd16724c..0c7d6f1ba 100644--- a/metal/tests/token_chain.cpp+++ b/metal/tests/token_chain.cpp@@ -63,7 +63,7 @@ int main(int argc, char** argv) {std::string hc_mode = "3"; // 3: BF16, 3 dispatches; 2: BF16, 2 dispatches; q8: Q8_0 copies, 2 dispatchesbool fuse = false; // the GDN y prep in the step; no QSA score/top-k within the selection budgetbool fold_comb = false; // the MoE combine folded into the next 2-dispatch HC read (measured slower)- std::string only;+ std::string only, skip;for (int i = 2; i < argc; ++i) {std::string a = argv[i];if (a == "--ntok") ntok = std::atoi(argv[++i]);@@ -75,6 +75,7 @@ int main(int argc, char** argv) {else if (a == "--fuse") fuse = true;else if (a == "--fold-comb") fold_comb = true;else if (a == "--only") only = argv[++i];+ else if (a == "--skip") skip = argv[++i];}gguf::File f;std::string err;@@ -158,6 +159,7 @@ int main(int argc, char** argv) {d.barrier = !nb;nb = false;if (!only.empty() && c != only) return;+ if (!skip.empty() && c == skip) return;ds.push_back(d);cls.push_back(c);bytes_by[c] += bytes;