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: standalone Metal kernel tree - runtime face, bandwidth/dispatch probes, grouped routed-expert kernels
Niko1221ad9eb8907995
diff --git a/metal/CMakeLists.txt b/metal/CMakeLists.txtnew file mode 100644index 000000000..b33536e52--- /dev/null+++ b/metal/CMakeLists.txt@@ -0,0 +1,38 @@+# metal/ - Strata's Metal (Apple Silicon) kernels, standalone for now: the runtime face (src/mtl_rt.*), the MSL+# kernels (kernels/*.metal, compiled at run time), CPU references (src/ref_*.cpp) and the parity / bench programs+# (tests/). Nothing here is used by the CUDA / HIP / SYCL builds.+#+# cmake -S metal -B build-metal -G Ninja -DCMAKE_BUILD_TYPE=Release && ninja -C build-metal+cmake_minimum_required(VERSION 3.20)+project(strata_metal LANGUAGES C CXX OBJCXX)++if(NOT APPLE)+ message(FATAL_ERROR "metal/ builds on macOS only")+endif()++set(CMAKE_CXX_STANDARD 20)+set(CMAKE_CXX_STANDARD_REQUIRED ON)+set(CMAKE_OBJCXX_STANDARD 20)+if(NOT CMAKE_BUILD_TYPE)+ set(CMAKE_BUILD_TYPE Release)+endif()+set(CMAKE_CXX_FLAGS_RELEASE "-O2")+set(CMAKE_OBJCXX_FLAGS_RELEASE "-O2")++get_filename_component(STRATA_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/.." ABSOLUTE)+set(GGML_COMMON "${STRATA_ROOT}/third_party/ggml/ggml-common.h")++add_library(mtl_rt STATIC src/mtl_rt.mm src/ref_quant.cpp)+target_include_directories(mtl_rt PUBLIC src ${STRATA_ROOT}/third_party/ggml)+target_compile_options(mtl_rt PRIVATE $<$<COMPILE_LANGUAGE:OBJCXX>:-fobjc-arc>)+target_compile_definitions(mtl_rt PRIVATE+ STRATA_GGML_COMMON_DEFAULT="${GGML_COMMON}"+ STRATA_METAL_KERNELS_DEFAULT="${CMAKE_CURRENT_SOURCE_DIR}/kernels")+target_link_libraries(mtl_rt PUBLIC "-framework Metal" "-framework Foundation")++file(GLOB STRATA_METAL_TESTS CONFIGURE_DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/tests/*.cpp)+foreach(src ${STRATA_METAL_TESTS})+ get_filename_component(t ${src} NAME_WE)+ add_executable(${t} ${src})+ target_link_libraries(${t} PRIVATE mtl_rt)+endforeach()diff --git a/metal/kernels/moe.metal b/metal/kernels/moe.metalnew file mode 100644index 000000000..9609a95aa--- /dev/null+++ b/metal/kernels/moe.metal@@ -0,0 +1,205 @@+// metal/kernels/moe.metal - routed experts of one layer for a verify window of 1..8 tokens, grouped by expert:+//+// moe_plan one threadgroup: the window's top-k ids -> groups (distinct experts, by id) with their entries+// (token, weight), each (token, k)'s entry index, and the indirect grid sizes of the next two kernels.+// Deterministic (no atomics).+// moe_gu per group, a block of FFN rows: gate and up rows read once, applied to every entry of the group+// (the shared input x is read from cache), h = silu(gate) * up per entry.+// moe_down per group, a block of output rows: ye[entry] = weight * (down . h[entry]).+// moe_combine y[token] = sum over k of ye[entry(token, k)], in k order.+//+// The plan is one int buffer (see P_* below). The arena is one layer's experts, blob e at e * blob_bytes:+// [gate rows | up rows | down rows] in GGUF blocks (tools/iq_pack.py's experts.bin layout).++#define P_NG 0+#define P_IGU 4+#define P_IDN 8+#define P_MAXE 128+#define P_GEXP 16+#define P_GSTART (P_GEXP + P_MAXE)+#define P_ETOK (P_GSTART + P_MAXE + 4)+#define P_EW (P_ETOK + P_MAXE)+#define P_TOKENT (P_EW + P_MAXE)+#define P_INTS (P_TOKENT + P_MAXE)++struct MoeArgs {+ ulong blob_bytes;+ ulong up_off;+ ulong down_off;+ uint gu_row; // bytes per gate/up row+ uint d_row; // bytes per down row+ uint n_embd;+ uint n_ff;+ uint n_tok;+ uint topk;+ uint n_expert;+ uint gx_gu; // threadgroups along the rows for moe_gu (n_ff / rows per threadgroup)+ uint gx_dn; // ... for moe_down (n_embd / rows per threadgroup)+ uint pad;+};++kernel void moe_plan(device const int* ids [[buffer(0)]], device const float* w [[buffer(1)]],+ device int* plan [[buffer(2)]], constant MoeArgs& a [[buffer(3)]],+ ushort tid [[thread_position_in_threadgroup]], ushort nth [[threads_per_threadgroup]],+ ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) {+ threadgroup int s_grp[32], s_ent[32];+ const int ne = int(a.n_tok * a.topk);+ // one thread per expert id (nth == n_expert, at most 1024)+ const int e = tid;+ int cnt = 0;+ if (e < int(a.n_expert))+ for (int i = 0; i < ne; ++i) cnt += ids[i] == e;+ const int has = cnt > 0;+ const int pg = simd_prefix_exclusive_sum(has), pe = simd_prefix_exclusive_sum(cnt);+ if (lane == 31) { s_grp[sg] = pg + has; s_ent[sg] = pe + cnt; }+ threadgroup_barrier(mem_flags::mem_threadgroup);+ if (tid == 0) {+ int og = 0, oe = 0;+ const int nsg = (nth + 31) / 32;+ for (int i = 0; i < nsg; ++i) {+ const int g = s_grp[i], n = s_ent[i];+ s_grp[i] = og;+ s_ent[i] = oe;+ og += g;+ oe += n;+ }+ plan[P_NG] = og;+ plan[P_IGU] = int(a.gx_gu); plan[P_IGU + 1] = og; plan[P_IGU + 2] = 1;+ plan[P_IDN] = int(a.gx_dn); plan[P_IDN + 1] = og; plan[P_IDN + 2] = 1;+ plan[P_GSTART + og] = oe;+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);+ if (has) {+ const int gi = s_grp[sg] + pg, off = s_ent[sg] + pe;+ plan[P_GEXP + gi] = e;+ plan[P_GSTART + gi] = off;+ int j = 0;+ for (int i = 0; i < ne; ++i)+ if (ids[i] == e) {+ plan[P_ETOK + off + j] = i / int(a.topk);+ plan[P_EW + off + j] = as_type<int>(w[i]);+ plan[P_TOKENT + i] = off + j;+ ++j;+ }+ }+}++// ---- gate + up + SwiGLU -------------------------------------------------------------------------------------------+template <int F, int LPR, int NR, int NT>+static inline void gu_rows(device const uchar* blob, device const float* x, device float* h, device const int* plan,+ int c, int row0, int li, constant MoeArgs& a, threadgroup const uint* tab) {+ constexpr int UNIT = fmt<F>::UNIT;+ float ag[NR][NT], au[NR][NT];+ for (int r = 0; r < NR; ++r)+ for (int t = 0; t < NT; ++t) ag[r][t] = au[r][t] = 0.0f;+ device const float* xt[NT];+ for (int t = 0; t < NT; ++t) xt[t] = x + plan[P_ETOK + c + t] * int(a.n_embd);+ device const uchar* g0 = blob + (ulong)row0 * a.gu_row;+ device const uchar* u0 = blob + a.up_off + (ulong)row0 * a.gu_row;+ const int U = int(a.n_embd) / UNIT;+ for (int u = li; u < U; u += LPR) {+ float xs[NT][UNIT];+ for (int t = 0; t < NT; ++t) load_x<UNIT>(xt[t] + u * UNIT, xs[t]);+ for (int r = 0; r < NR; ++r) {+ unit_dot<F, NT>(g0 + r * a.gu_row, u, xs, ag[r], tab);+ unit_dot<F, NT>(u0 + r * a.gu_row, u, xs, au[r], tab);+ }+ }+ for (int r = 0; r < NR; ++r)+ for (int t = 0; t < NT; ++t) {+ const float g = lane_sum<LPR>(ag[r][t]), v = lane_sum<LPR>(au[r][t]);+ if (li == 0) h[(c + t) * int(a.n_ff) + row0 + r] = g / (1.0f + exp(-g)) * v;+ }+}++template <int F, int LPR, int NR, int SG>+kernel void moe_gu(device const uchar* W [[buffer(0)]], device const float* x [[buffer(1)]],+ device float* h [[buffer(2)]], device const int* plan [[buffer(3)]],+ constant MoeArgs& a [[buffer(4)]],+ uint3 tg [[threadgroup_position_in_grid]], ushort sg [[simdgroup_index_in_threadgroup]],+ ushort lane [[thread_index_in_simdgroup]], ushort tid [[thread_index_in_threadgroup]]) {+ threadgroup uint tab[fmt<F>::TAB];+ load_tab<F>(tab, tid, SG * 32);+ threadgroup_barrier(mem_flags::mem_threadgroup);+ const int g = int(tg.y);+ if (g >= plan[P_NG]) return;+ constexpr int RG = 32 / LPR;+ const int li = lane % LPR;+ const int row0 = ((int(tg.x) * SG + sg) * RG + lane / LPR) * NR;+ device const uchar* blob = W + (ulong)plan[P_GEXP + g] * a.blob_bytes;+ const int e1 = plan[P_GSTART + g + 1];+ int c = plan[P_GSTART + g];+ for (; e1 - c >= 4; c += 4) gu_rows<F, LPR, NR, 4>(blob, x, h, plan, c, row0, li, a, tab);+ if (e1 - c >= 2) { gu_rows<F, LPR, NR, 2>(blob, x, h, plan, c, row0, li, a, tab); c += 2; }+ if (e1 - c >= 1) gu_rows<F, LPR, NR, 1>(blob, x, h, plan, c, row0, li, a, tab);+}++// ---- down ---------------------------------------------------------------------------------------------------------+template <int F, int LPR, int NR, int NT>+static inline void dn_rows(device const uchar* blob, device const float* h, device float* ye, device const int* plan,+ int c, int row0, int li, constant MoeArgs& a, threadgroup const uint* tab) {+ constexpr int UNIT = fmt<F>::UNIT;+ float ac[NR][NT];+ for (int r = 0; r < NR; ++r)+ for (int t = 0; t < NT; ++t) ac[r][t] = 0.0f;+ device const uchar* d0 = blob + a.down_off + (ulong)row0 * a.d_row;+ const int U = int(a.n_ff) / UNIT;+ for (int u = li; u < U; u += LPR) {+ float xs[NT][UNIT];+ for (int t = 0; t < NT; ++t) load_x<UNIT>(h + (c + t) * int(a.n_ff) + u * UNIT, xs[t]);+ for (int r = 0; r < NR; ++r) unit_dot<F, NT>(d0 + r * a.d_row, u, xs, ac[r], tab);+ }+ for (int r = 0; r < NR; ++r)+ for (int t = 0; t < NT; ++t) {+ const float v = lane_sum<LPR>(ac[r][t]);+ if (li == 0) ye[(c + t) * int(a.n_embd) + row0 + r] = as_type<float>(plan[P_EW + c + t]) * v;+ }+}++template <int F, int LPR, int NR, int SG>+kernel void moe_down(device const uchar* W [[buffer(0)]], device const float* h [[buffer(1)]],+ device float* ye [[buffer(2)]], device const int* plan [[buffer(3)]],+ constant MoeArgs& a [[buffer(4)]],+ uint3 tg [[threadgroup_position_in_grid]], ushort sg [[simdgroup_index_in_threadgroup]],+ ushort lane [[thread_index_in_simdgroup]], ushort tid [[thread_index_in_threadgroup]]) {+ threadgroup uint tab[fmt<F>::TAB];+ load_tab<F>(tab, tid, SG * 32);+ threadgroup_barrier(mem_flags::mem_threadgroup);+ const int g = int(tg.y);+ if (g >= plan[P_NG]) return;+ constexpr int RG = 32 / LPR;+ const int li = lane % LPR;+ const int row0 = ((int(tg.x) * SG + sg) * RG + lane / LPR) * NR;+ device const uchar* blob = W + (ulong)plan[P_GEXP + g] * a.blob_bytes;+ const int e1 = plan[P_GSTART + g + 1];+ int c = plan[P_GSTART + g];+ for (; e1 - c >= 4; c += 4) dn_rows<F, LPR, NR, 4>(blob, h, ye, plan, c, row0, li, a, tab);+ if (e1 - c >= 2) { dn_rows<F, LPR, NR, 2>(blob, h, ye, plan, c, row0, li, a, tab); c += 2; }+ if (e1 - c >= 1) dn_rows<F, LPR, NR, 1>(blob, h, ye, plan, c, row0, li, a, tab);+}++kernel void moe_combine(device const float* ye [[buffer(0)]], device float* y [[buffer(1)]],+ device const int* plan [[buffer(2)]], constant MoeArgs& a [[buffer(3)]],+ uint gid [[thread_position_in_grid]]) {+ const uint t = gid / a.n_embd, k = gid % a.n_embd;+ if (t >= a.n_tok) return;+ float s = 0.0f;+ for (uint j = 0; j < a.topk; ++j) s += ye[plan[P_TOKENT + t * a.topk + j] * int(a.n_embd) + k];+ y[gid] = s;+}++// ---- instantiations: moe_gu_<type>_<LPR>_<NR>_<SG>, moe_down_<type>_<LPR>_<NR>_<SG> -------------------------------+#define GU(F, L, R, S) template [[host_name("moe_gu_" #F "_" #L "_" #R "_" #S)]] kernel decltype(moe_gu<F, L, R, S>) moe_gu<F, L, R, S>;+#define DN(F, L, R, S) template [[host_name("moe_down_" #F "_" #L "_" #R "_" #S)]] kernel decltype(moe_down<F, L, R, S>) moe_down<F, L, R, S>;+#define GU_SET(F) GU(F, 32, 1, 4) GU(F, 32, 2, 4) GU(F, 32, 4, 4) GU(F, 32, 2, 2) GU(F, 32, 2, 8) GU(F, 32, 1, 8) \+ GU(F, 16, 1, 4) GU(F, 16, 2, 4) GU(F, 8, 1, 4) GU(F, 8, 2, 4) GU(F, 8, 1, 2)+#define DN_SET(F) DN(F, 8, 1, 4) DN(F, 8, 2, 4) DN(F, 8, 4, 4) DN(F, 8, 1, 8) DN(F, 8, 2, 8) DN(F, 4, 1, 4) DN(F, 4, 2, 4) \+ DN(F, 4, 4, 4) DN(F, 16, 1, 4) DN(F, 16, 2, 4) DN(F, 32, 1, 4) DN(F, 2, 2, 4)+GU_SET(T_Q2_0)+GU_SET(T_IQ3_XXS)+GU_SET(T_IQ2_XXS)+GU_SET(T_IQ2_XS)+GU_SET(T_IQ2_S)+GU_SET(T_IQ3_S)+DN_SET(T_Q2_0)+DN_SET(T_IQ4_NL)diff --git a/metal/kernels/quant.metal b/metal/kernels/quant.metalnew file mode 100644index 000000000..867cf36b0--- /dev/null+++ b/metal/kernels/quant.metal@@ -0,0 +1,288 @@+// metal/kernels/quant.metal - the weight formats as "units": a unit is UNIT consecutive weights of one row that one+// SIMD lane decodes at a time into raw values q[0..UNIT) and one scale s, so that the unit's dot with x is+// s * sum(q[j] * x[j]). Every GEMV kernel (moe.metal, gemv.metal) is written once over these.+//+// Decode rules transcribed from ggml-quants.c dequantize_row_* (3cf03257) and Strata's Q2_0 contract+// (docs/q2_0-contract.md); the grids and sign tables are ggml-common.h's (prepended by the runtime). The tables a+// format needs are copied to threadgroup memory once per threadgroup (constant-memory lookups with divergent indices+// serialise on Apple GPUs).+//+// Blocks start at 2-byte aligned addresses (18, 66, 74, 82, 98, 110 bytes), so every multi-byte field is read as+// ushorts.++#define T_Q4_0 2+#define T_Q5_0 6+#define T_Q8_0 8+#define T_Q4_K 12+#define T_Q5_K 13+#define T_Q6_K 14+#define T_IQ2_XXS 16+#define T_IQ2_XS 17+#define T_IQ3_XXS 18+#define T_IQ4_NL 20+#define T_IQ3_S 21+#define T_IQ2_S 22+#define T_IQ4_XS 23+#define T_Q2_0 42++template <int F> struct fmt;+// QK block elements, BB block bytes, UNIT weights per unit, TAB words of threadgroup table+template <> struct fmt<T_Q2_0> { enum { QK = 64, BB = 18, UNIT = 16, TAB = 1 }; };+template <> struct fmt<T_IQ3_XXS> { enum { QK = 256, BB = 98, UNIT = 16, TAB = 256 + 32 }; };+template <> struct fmt<T_IQ2_XXS> { enum { QK = 256, BB = 66, UNIT = 16, TAB = 512 + 32 }; };+template <> struct fmt<T_IQ2_XS> { enum { QK = 256, BB = 74, UNIT = 16, TAB = 1024 + 32 }; };+template <> struct fmt<T_IQ2_S> { enum { QK = 256, BB = 82, UNIT = 16, TAB = 2048 + 32 }; };+template <> struct fmt<T_IQ3_S> { enum { QK = 256, BB = 110, UNIT = 16, TAB = 512 + 32 }; };+template <> struct fmt<T_IQ4_NL> { enum { QK = 32, BB = 18, UNIT = 32, TAB = 16 }; };+template <> struct fmt<T_IQ4_XS> { enum { QK = 256, BB = 136, UNIT = 32, TAB = 16 }; };+template <> struct fmt<T_Q8_0> { enum { QK = 32, BB = 34, UNIT = 32, TAB = 1 }; };+template <> struct fmt<T_Q4_0> { enum { QK = 32, BB = 18, UNIT = 32, TAB = 1 }; };+template <> struct fmt<T_Q5_0> { enum { QK = 32, BB = 22, UNIT = 32, TAB = 1 }; };++static inline uint rd32(device const uchar* p) {+ device const ushort* s = (device const ushort*)p;+ return uint(s[0]) | (uint(s[1]) << 16);+}+static inline float rdh(device const uchar* p) { return float(*(device const half*)p); }++// ---- threadgroup tables -------------------------------------------------------------------------------------------+// layout in `tab` (uint words): [0, G) the grid, [G, G + 32) ksigns_iq2xs as bytes; IQ4_NL/XS: 16 floats.+template <int F> static inline void load_tab(threadgroup uint* tab, ushort tid, ushort nth);++template <> inline void load_tab<T_Q2_0>(threadgroup uint*, ushort, ushort) {}+template <> inline void load_tab<T_Q8_0>(threadgroup uint*, ushort, ushort) {}+template <> inline void load_tab<T_Q4_0>(threadgroup uint*, ushort, ushort) {}+template <> inline void load_tab<T_Q5_0>(threadgroup uint*, ushort, ushort) {}++static inline void load_signs(threadgroup uint* tab, int at, ushort tid, ushort nth) {+ threadgroup uchar* s = (threadgroup uchar*)(tab + at);+ for (int i = tid; i < 128; i += nth) s[i] = ksigns_iq2xs[i];+}+template <> inline void load_tab<T_IQ3_XXS>(threadgroup uint* tab, ushort tid, ushort nth) {+ for (int i = tid; i < 256; i += nth) tab[i] = iq3xxs_grid[i];+ load_signs(tab, 256, tid, nth);+}+template <> inline void load_tab<T_IQ3_S>(threadgroup uint* tab, ushort tid, ushort nth) {+ for (int i = tid; i < 512; i += nth) tab[i] = iq3s_grid[i];+ load_signs(tab, 512, tid, nth);+}+template <> inline void load_tab<T_IQ2_XXS>(threadgroup uint* tab, ushort tid, ushort nth) {+ for (int i = tid; i < 256; i += nth) { tab[2 * i] = uint(iq2xxs_grid[i]); tab[2 * i + 1] = uint(iq2xxs_grid[i] >> 32); }+ load_signs(tab, 512, tid, nth);+}+template <> inline void load_tab<T_IQ2_XS>(threadgroup uint* tab, ushort tid, ushort nth) {+ for (int i = tid; i < 512; i += nth) { tab[2 * i] = uint(iq2xs_grid[i]); tab[2 * i + 1] = uint(iq2xs_grid[i] >> 32); }+ load_signs(tab, 1024, tid, nth);+}+template <> inline void load_tab<T_IQ2_S>(threadgroup uint* tab, ushort tid, ushort nth) {+ for (int i = tid; i < 1024; i += nth) { tab[2 * i] = uint(iq2s_grid[i]); tab[2 * i + 1] = uint(iq2s_grid[i] >> 32); }+ load_signs(tab, 2048, tid, nth);+}+template <> inline void load_tab<T_IQ4_NL>(threadgroup uint* tab, ushort tid, ushort nth) {+ threadgroup float* kv = (threadgroup float*)tab;+ for (int i = tid; i < 16; i += nth) kv[i] = float(kvalues_iq4nl[i]);+}+template <> inline void load_tab<T_IQ4_XS>(threadgroup uint* tab, ushort tid, ushort nth) {+ load_tab<T_IQ4_NL>(tab, tid, nth);+}++// ---- unit decoders: return s, fill q[UNIT] ------------------------------------------------------------------------+// ui = unit index inside the block (0 .. QK/UNIT - 1).+template <int F> static inline float deq(device const uchar* b, int ui, thread float* q, threadgroup const uint* tab);++// Q2_0: 64 = 4 units of 16; code c (2 bits, LSB first) -> c - 1; scale d.+template <> inline float deq<T_Q2_0>(device const uchar* b, int ui, thread float* q, threadgroup const uint*) {+ device const ushort* p = (device const ushort*)(b + 2 + 4 * ui);+ const ushort a = p[0], c = p[1];+ for (int j = 0; j < 8; ++j) {+ q[j] = float((a >> (2 * j)) & 3) - 1.0f;+ q[8 + j] = float((c >> (2 * j)) & 3) - 1.0f;+ }+ return rdh(b);+}++// 8 signed grid bytes from a 4-byte grid word pair helper+static inline void put_signed4(thread float* q, uint g, uint s) {+ const uchar4 v = as_type<uchar4>(g);+ q[0] = (s & 1) ? -float(v[0]) : float(v[0]);+ q[1] = (s & 2) ? -float(v[1]) : float(v[1]);+ q[2] = (s & 4) ? -float(v[2]) : float(v[2]);+ q[3] = (s & 8) ? -float(v[3]) : float(v[3]);+}++// IQ3_XXS: 256 = 8 x 32; unit = half of a 32 (two grid pairs).+template <> inline float deq<T_IQ3_XXS>(device const uchar* b, int ui, thread float* q, threadgroup const uint* tab) {+ const int ib = ui >> 1, h = ui & 1;+ const uint aux = rd32(b + 2 + 64 + 4 * ib);+ threadgroup const uchar* ks = (threadgroup const uchar*)(tab + 256);+ device const uchar* qs = b + 2 + 8 * ib + 4 * h;+ for (int l2 = 0; l2 < 2; ++l2) {+ const int l = 2 * h + l2;+ const uint s = ks[(aux >> (7 * l)) & 127];+ put_signed4(q + 8 * l2, tab[qs[2 * l2]], s);+ put_signed4(q + 8 * l2 + 4, tab[qs[2 * l2 + 1]], s >> 4);+ }+ return rdh(b) * (0.5f + float(aux >> 28)) * 0.5f;+}++// IQ2_XXS: per 32: two u32 (4 grid indices, then 4 x 7 sign bits + 4-bit scale).+template <> inline float deq<T_IQ2_XXS>(device const uchar* b, int ui, thread float* q, threadgroup const uint* tab) {+ const int ib = ui >> 1, h = ui & 1;+ const uint a0 = rd32(b + 2 + 8 * ib), a1 = rd32(b + 2 + 8 * ib + 4);+ threadgroup const uchar* ks = (threadgroup const uchar*)(tab + 512);+ for (int l2 = 0; l2 < 2; ++l2) {+ const int l = 2 * h + l2;+ const uint idx = (a0 >> (8 * l)) & 255;+ const uint s = ks[(a1 >> (7 * l)) & 127];+ put_signed4(q + 8 * l2, tab[2 * idx], s);+ put_signed4(q + 8 * l2 + 4, tab[2 * idx + 1], s >> 4);+ }+ return rdh(b) * (0.5f + float(a1 >> 28)) * 0.25f;+}++// IQ2_XS: uint16 qs[32] (9-bit grid index + 7-bit sign index), scales[8] nibbles.+template <> inline float deq<T_IQ2_XS>(device const uchar* b, int ui, thread float* q, threadgroup const uint* tab) {+ const int ib = ui >> 1, h = ui & 1;+ device const ushort* qs = (device const ushort*)(b + 2);+ threadgroup const uchar* ks = (threadgroup const uchar*)(tab + 1024);+ for (int l2 = 0; l2 < 2; ++l2) {+ const uint v = qs[4 * ib + 2 * h + l2];+ const uint idx = v & 511, s = ks[v >> 9];+ put_signed4(q + 8 * l2, tab[2 * idx], s);+ put_signed4(q + 8 * l2 + 4, tab[2 * idx + 1], s >> 4);+ }+ const uint sc = b[66 + ib];+ return rdh(b) * (0.5f + float((sc >> (4 * h)) & 15)) * 0.25f;+}++// IQ2_S: qs[32] low 8 bits of the 10-bit index, signs[32], qh[8] (2 high bits per group of 8), scales[8].+template <> inline float deq<T_IQ2_S>(device const uchar* b, int ui, thread float* q, threadgroup const uint* tab) {+ const int ib = ui >> 1, h = ui & 1;+ const uint qh = b[66 + ib];+ for (int l2 = 0; l2 < 2; ++l2) {+ const int l = 2 * h + l2;+ const uint idx = uint(b[2 + 4 * ib + l]) | ((qh << (8 - 2 * l)) & 0x300);+ const uint s = b[2 + 32 + 4 * ib + l];+ put_signed4(q + 8 * l2, tab[2 * idx], s);+ put_signed4(q + 8 * l2 + 4, tab[2 * idx + 1], s >> 4);+ }+ const uint sc = b[74 + ib];+ return rdh(b) * (0.5f + float((sc >> (4 * h)) & 15)) * 0.25f;+}++// IQ3_S: qs[64] low 8 bits of 9-bit indices, qh[8], signs[32], scales[4] (nibble per 32).+template <> inline float deq<T_IQ3_S>(device const uchar* b, int ui, thread float* q, threadgroup const uint* tab) {+ const int ib = ui >> 1, h = ui & 1;+ const uint qh = b[66 + ib];+ for (int l2 = 0; l2 < 2; ++l2) {+ const int l = 2 * h + l2;+ const uint i1 = uint(b[2 + 8 * ib + 2 * l]) | ((qh << (8 - 2 * l)) & 256);+ const uint i2 = uint(b[2 + 8 * ib + 2 * l + 1]) | ((qh << (7 - 2 * l)) & 256);+ const uint s = b[74 + 4 * ib + l];+ put_signed4(q + 8 * l2, tab[i1], s);+ put_signed4(q + 8 * l2 + 4, tab[i2], s >> 4);+ }+ const uint sc = b[106 + (ib >> 1)];+ return rdh(b) * float(1 + 2 * ((sc >> (4 * (ib & 1))) & 15));+}++// IQ4_NL: 32 = 1 unit; low nibbles are elements 0..15, high 16..31.+template <> inline float deq<T_IQ4_NL>(device const uchar* b, int, thread float* q, threadgroup const uint* tab) {+ threadgroup const float* kv = (threadgroup const float*)tab;+ device const ushort* p = (device const ushort*)(b + 2);+ for (int j = 0; j < 8; ++j) {+ const ushort v = p[j];+ q[2 * j] = kv[v & 15];+ q[2 * j + 16] = kv[(v >> 4) & 15];+ q[2 * j + 1] = kv[(v >> 8) & 15];+ q[2 * j + 17] = kv[v >> 12];+ }+ return rdh(b);+}++// IQ4_XS: 256 = 8 units of 32; 6-bit scale from scales_l nibble + 2 bits of scales_h, minus 32.+template <> inline float deq<T_IQ4_XS>(device const uchar* b, int ui, thread float* q, threadgroup const uint* tab) {+ threadgroup const float* kv = (threadgroup const float*)tab;+ device const ushort* p = (device const ushort*)(b + 8 + 16 * ui);+ for (int j = 0; j < 8; ++j) {+ const ushort v = p[j];+ q[2 * j] = kv[v & 15];+ q[2 * j + 16] = kv[(v >> 4) & 15];+ q[2 * j + 1] = kv[(v >> 8) & 15];+ q[2 * j + 17] = kv[v >> 12];+ }+ const uint sh = *(device const ushort*)(b + 2);+ const int ls = int((b[4 + (ui >> 1)] >> (4 * (ui & 1))) & 15) | int(((sh >> (2 * ui)) & 3) << 4);+ return rdh(b) * float(ls - 32);+}++template <> inline float deq<T_Q8_0>(device const uchar* b, int, thread float* q, threadgroup const uint*) {+ device const ushort* p = (device const ushort*)(b + 2);+ for (int j = 0; j < 16; ++j) {+ const ushort v = p[j];+ q[2 * j] = float(as_type<char>(uchar(v & 255)));+ q[2 * j + 1] = float(as_type<char>(uchar(v >> 8)));+ }+ return rdh(b);+}++template <> inline float deq<T_Q4_0>(device const uchar* b, int, thread float* q, threadgroup const uint*) {+ device const ushort* p = (device const ushort*)(b + 2);+ for (int j = 0; j < 8; ++j) {+ const ushort v = p[j];+ q[2 * j] = float(v & 15) - 8.0f;+ q[2 * j + 16] = float((v >> 4) & 15) - 8.0f;+ q[2 * j + 1] = float((v >> 8) & 15) - 8.0f;+ q[2 * j + 17] = float(v >> 12) - 8.0f;+ }+ return rdh(b);+}++template <> inline float deq<T_Q5_0>(device const uchar* b, int, thread float* q, threadgroup const uint*) {+ const uint hb = rd32(b + 2);+ device const ushort* p = (device const ushort*)(b + 6);+ for (int j = 0; j < 8; ++j) {+ const ushort v = p[j];+ const int j0 = 2 * j, j1 = 2 * j + 1;+ q[j0] = float(int(v & 15) | int(((hb >> j0) & 1) << 4)) - 16.0f;+ q[j0 + 16] = float(int((v >> 4) & 15) | int(((hb >> (j0 + 16)) & 1) << 4)) - 16.0f;+ q[j1] = float(int((v >> 8) & 15) | int(((hb >> j1) & 1) << 4)) - 16.0f;+ q[j1 + 16] = float(int(v >> 12) | int(((hb >> (j1 + 16)) & 1) << 4)) - 16.0f;+ }+ return rdh(b);+}++// ---- the dot of one unit with NT token slices ----------------------------------------------------------------------+// The weights of unit `u` of `row` (u counts units along the row) dotted with x[t][u*UNIT ..], accumulated into acc[t].+template <int F, int NT>+static inline void unit_dot(device const uchar* row, int u, thread const float (*xs)[fmt<F>::UNIT], thread float* acc,+ 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 t = 0; t < NT; ++t) {+ float d = 0.0f;+ for (int j = 0; j < UNIT; ++j) d = fma(q[j], xs[t][j], d);+ acc[t] = fma(s, d, acc[t]);+ }+}++template <int UNIT>+static inline void load_x(device const float* x, thread float* xs) {+ device const float4* p = (device const float4*)x;+ for (int j = 0; j < UNIT / 4; ++j) {+ const float4 v = p[j];+ xs[4 * j] = v.x;+ xs[4 * j + 1] = v.y;+ xs[4 * j + 2] = v.z;+ xs[4 * j + 3] = v.w;+ }+}++// sum over groups of LPR consecutive lanes (LPR = 1, 2, 4, 8, 16 or 32); the result is valid in every lane+template <int LPR>+static inline float lane_sum(float v) {+ if (LPR == 32) return simd_sum(v);+ for (ushort o = LPR / 2; o > 0; o >>= 1) v += simd_shuffle_xor(v, o);+ return v;+}diff --git a/metal/kernels/rt_bench.metal b/metal/kernels/rt_bench.metalnew file mode 100644index 000000000..bdce780ac--- /dev/null+++ b/metal/kernels/rt_bench.metal@@ -0,0 +1,67 @@+// metal/kernels/rt_bench.metal - bandwidth and dispatch-cost probes (rt_bench.cpp).++// Grid-stride streaming read: thread i reads src[i], src[i + nt], ... (coalesced across the grid).+kernel void k_read(device const uint4* src [[buffer(0)]], device uint* out [[buffer(1)]],+ constant uint& n [[buffer(2)]],+ uint gid [[thread_position_in_grid]], uint nt [[threads_per_grid]]) {+ uint4 a = 0;+ for (uint i = gid; i < n; i += nt) a += src[i];+ out[gid] = a.x ^ a.y ^ a.z ^ a.w;+}++// The same, 4 independent loads in flight per iteration.+kernel void k_read_u4(device const uint4* src [[buffer(0)]], device uint* out [[buffer(1)]],+ constant uint& n [[buffer(2)]],+ uint gid [[thread_position_in_grid]], uint nt [[threads_per_grid]]) {+ uint4 a = 0, b = 0, c = 0, d = 0;+ uint i = gid;+ for (; i + 3 * nt < n; i += 4 * nt) {+ a += src[i];+ b += src[i + nt];+ c += src[i + 2 * nt];+ d += src[i + 3 * nt];+ }+ for (; i < n; i += nt) a += src[i];+ a += b + c + d;+ out[gid] = a.x ^ a.y ^ a.z ^ a.w;+}++// Contiguous chunk per threadgroup (how a GEMV row block reads): threadgroup g reads [g*chunk, (g+1)*chunk).+kernel void k_read_chunk(device const uint4* src [[buffer(0)]], device uint* out [[buffer(1)]],+ constant uint& n [[buffer(2)]], constant uint& chunk [[buffer(3)]],+ uint tid [[thread_position_in_threadgroup]], uint tgs [[threads_per_threadgroup]],+ uint g [[threadgroup_position_in_grid]], uint gid [[thread_position_in_grid]]) {+ uint4 a = 0, b = 0;+ const uint base = g * chunk, end = min(base + chunk, n);+ uint i = base + tid;+ for (; i + tgs < end; i += 2 * tgs) {+ a += src[i];+ b += src[i + tgs];+ }+ for (; i < end; i += tgs) a += src[i];+ a += b;+ out[gid] = a.x ^ a.y ^ a.z ^ a.w;+}++// Read + write (a state update): dst[i] = src[i] * 1.0001 for float4.+kernel void k_copy(device const float4* src [[buffer(0)]], device float4* dst [[buffer(1)]],+ constant uint& n [[buffer(2)]],+ uint gid [[thread_position_in_grid]], uint nt [[threads_per_grid]]) {+ for (uint i = gid; i < n; i += nt) dst[i] = src[i] * 1.0001f;+}++// Dispatch-cost probes.+kernel void k_empty(device uint* out [[buffer(0)]], uint gid [[thread_position_in_grid]]) {+ if (gid == 0xFFFFFFFFu) out[0] = 1;+}++// A dependent chain: each dispatch reads what the previous one wrote.+kernel void k_chain(device uint* buf [[buffer(0)]], uint gid [[thread_position_in_grid]]) {+ if (gid == 0) buf[0] = buf[0] + 1;+}++// A small but real kernel: 2560 floats read, 2560 written (an elementwise op on one token).+kernel void k_small(device const float* x [[buffer(0)]], device float* y [[buffer(1)]],+ uint gid [[thread_position_in_grid]]) {+ if (gid < 2560) y[gid] = x[gid] * 0.5f + y[gid];+}diff --git a/metal/src/mtl_rt.h b/metal/src/mtl_rt.hnew file mode 100644index 000000000..060489351--- /dev/null+++ b/metal/src/mtl_rt.h@@ -0,0 +1,101 @@+// metal/src/mtl_rt.h - a thin C++ face over Metal for the standalone kernel programs (parity, benches).+//+// The implementation (mtl_rt.mm) is the only Objective-C++ file; every program and test is plain C++ against this+// header. Kernels are MSL source files compiled at run time (newLibraryWithSource): the Command Line Tools have no+// offline `metal` compiler, and the runtime compiler is part of the OS. ggml-common.h (MIT, third_party/ggml) is+// prepended for the i-quant grids and block structs.+#pragma once++#include <cstddef>+#include <cstdint>+#include <cstring>+#include <string>+#include <vector>++namespace mtl {++struct Buffer {+ void* handle = nullptr; // id<MTLBuffer> (retained)+ void* ptr = nullptr; // CPU address (shared storage)+ size_t bytes = 0;+ template <class T> T* as() const { return static_cast<T*>(ptr); }+};++struct Pipeline {+ void* handle = nullptr; // id<MTLComputePipelineState>+ int max_threads = 0; // maxTotalThreadsPerThreadgroup+ int simd_width = 0; // threadExecutionWidth+ int static_tg_mem = 0; // staticThreadgroupMemoryLength+};++// A function-constant value set (index -> int / bool / uint).+struct Constants {+ struct V { int index; int type; uint32_t v; }; // type 0 int, 1 bool, 2 uint, 3 short, 4 ushort+ std::vector<V> vals;+ Constants& i(int idx, int v) { vals.push_back({idx, 0, (uint32_t)v}); return *this; }+ Constants& b(int idx, bool v) { vals.push_back({idx, 1, (uint32_t)v}); return *this; }+ Constants& u(int idx, uint32_t v) { vals.push_back({idx, 2, v}); return *this; }+};++struct Arg { // one argument of a dispatch: a buffer (+ offset) or inline bytes+ const Buffer* buf = nullptr;+ size_t off = 0;+ std::vector<uint8_t> bytes;+ static Arg B(const Buffer& b, size_t off = 0) { Arg a; a.buf = &b; a.off = off; return a; }+ template <class T> static Arg V(const T& v) {+ Arg a; a.bytes.resize(sizeof(T)); std::memcpy(a.bytes.data(), &v, sizeof(T)); return a;+ }+};++struct Dispatch {+ const Pipeline* p = nullptr;+ std::vector<Arg> args;+ uint32_t grid[3] = {1, 1, 1}; // threadgroups+ uint32_t tg[3] = {32, 1, 1}; // threads per threadgroup+ uint32_t tg_mem = 0; // dynamic threadgroup memory at index 0 (bytes)+ const Buffer* indirect = nullptr; // grid from a GPU buffer (3 x uint32 threadgroup counts) at ind_off+ size_t ind_off = 0;+};++class Context {+public:+ Context();+ ~Context();+ std::string device_name() const;+ bool has_family_apple(int n) const; // MTLGPUFamilyApple<n>+ bool supports_metal4() const;+ uint64_t recommended_working_set() const;+ uint64_t max_buffer_length() const;++ // Compiles a library from MSL source files (paths), prepended by `prelude` (defines) and, if include_ggml,+ // ggml-common.h with GGML_COMMON_DECL_METAL/IMPL_METAL. Returns a library id (index); aborts with the+ // compiler log on error.+ int compile(const std::vector<std::string>& files, const std::string& prelude = "", bool fast_math = true);+ Pipeline pipeline(int lib, const std::string& fn, const Constants& c = {});++ Buffer alloc(size_t bytes); // shared storage, zeroed+ Buffer wrap(void* page_aligned, size_t bytes); // no-copy wrap (page-aligned, size multiple of page)+ void free(Buffer& b);++ // Encodes `ds` into ONE compute encoder (serial or concurrent dispatch type) and ONE command buffer, `reps`+ // times over; commits and waits. Returns the GPU time (GPUEndTime - GPUStartTime) in seconds.+ double run(const std::vector<Dispatch>& ds, int reps = 1, bool concurrent = false, bool barrier_between = false);+ // One command buffer per `run_cb` call, empty or not: measures commit+wait round trips.+ double run_wall(const std::vector<Dispatch>& ds, int reps, double* gpu_seconds = nullptr);++ // Indirect command buffer: the dispatches recorded once, executed `reps` times in one command buffer.+ // Buffers are bound per command (setKernelBuffer); inline bytes are not allowed (use buffers).+ double run_icb(const std::vector<Dispatch>& ds, int reps, bool barrier_between);++ std::string ggml_common_path; // where ggml-common.h is read from+ std::string kernel_dir; // where relative kernel paths resolve++private:+ struct Impl;+ Impl* impl_;+};++double now_s(); // monotonic wall clock (seconds)+std::string read_file(const std::string& path);++} // namespace mtldiff --git a/metal/src/mtl_rt.mm b/metal/src/mtl_rt.mmnew file mode 100644index 000000000..b66c1d16f--- /dev/null+++ b/metal/src/mtl_rt.mm@@ -0,0 +1,276 @@+// metal/src/mtl_rt.mm - see mtl_rt.h. Built with ARC (-fobjc-arc).+#import <Foundation/Foundation.h>+#import <Metal/Metal.h>++#include "mtl_rt.h"++#include <chrono>+#include <cstdio>+#include <cstdlib>+#include <fstream>+#include <sstream>++namespace mtl {++double now_s() {+ return std::chrono::duration<double>(std::chrono::steady_clock::now().time_since_epoch()).count();+}++std::string read_file(const std::string& path) {+ std::ifstream f(path, std::ios::binary);+ if (!f) {+ std::fprintf(stderr, "mtl: cannot read %s\n", path.c_str());+ std::exit(2);+ }+ std::stringstream ss;+ ss << f.rdbuf();+ return ss.str();+}++struct Context::Impl {+ id<MTLDevice> dev;+ id<MTLCommandQueue> q;+ std::vector<id<MTLLibrary>> libs;+};++static inline id<MTLBuffer> B(const Buffer& b) { return (__bridge id<MTLBuffer>)b.handle; }+static inline id<MTLComputePipelineState> P(const Pipeline* p) { return (__bridge id<MTLComputePipelineState>)p->handle; }++Context::Context() : impl_(new Impl) {+ impl_->dev = MTLCreateSystemDefaultDevice();+ if (!impl_->dev) {+ std::fprintf(stderr, "mtl: no Metal device\n");+ std::exit(2);+ }+ impl_->q = [impl_->dev newCommandQueue];+ const char* g = std::getenv("STRATA_GGML_COMMON");+ ggml_common_path = g ? g : STRATA_GGML_COMMON_DEFAULT;+ const char* k = std::getenv("STRATA_METAL_KERNELS");+ kernel_dir = k ? k : STRATA_METAL_KERNELS_DEFAULT;+}++Context::~Context() { delete impl_; }++std::string Context::device_name() const { return [[impl_->dev name] UTF8String]; }+bool Context::has_family_apple(int n) const {+ return [impl_->dev supportsFamily:(MTLGPUFamily)(MTLGPUFamilyApple1 + (n - 1))];+}+bool Context::supports_metal4() const {+ if (@available(macOS 26.0, *)) return [impl_->dev supportsFamily:MTLGPUFamilyMetal4];+ return false;+}+uint64_t Context::recommended_working_set() const { return [impl_->dev recommendedMaxWorkingSetSize]; }+uint64_t Context::max_buffer_length() const { return [impl_->dev maxBufferLength]; }++int Context::compile(const std::vector<std::string>& files, const std::string& prelude, bool fast_math) {+ std::string src = prelude + "\n#include <metal_stdlib>\nusing namespace metal;\n";+ if (!ggml_common_path.empty() && prelude.find("NO_GGML_COMMON") == std::string::npos) {+ src += "#define GGML_COMMON_DECL_METAL\n#define GGML_COMMON_IMPL_METAL\n";+ src += read_file(ggml_common_path);+ src += "\n";+ }+ for (const auto& f : files) {+ std::string p = (f.size() && f[0] == '/') ? f : kernel_dir + "/" + f;+ src += "#line 1 \"" + f + "\"\n" + read_file(p) + "\n";+ }+ MTLCompileOptions* o = [MTLCompileOptions new];+ if (@available(macOS 15.0, *)) {+ o.mathMode = fast_math ? MTLMathModeFast : MTLMathModeSafe;+ } else {+ o.fastMathEnabled = fast_math;+ }+ NSError* err = nil;+ id<MTLLibrary> lib = [impl_->dev newLibraryWithSource:[NSString stringWithUTF8String:src.c_str()] options:o error:&err];+ if (!lib) {+ std::fprintf(stderr, "mtl: compile failed:\n%s\n", [[err localizedDescription] UTF8String]);+ std::exit(3);+ }+ impl_->libs.push_back(lib);+ return (int)impl_->libs.size() - 1;+}++Pipeline Context::pipeline(int lib, const std::string& fn, const Constants& c) {+ NSError* err = nil;+ id<MTLFunction> f;+ NSString* name = [NSString stringWithUTF8String:fn.c_str()];+ if (c.vals.empty()) {+ f = [impl_->libs[lib] newFunctionWithName:name];+ } else {+ MTLFunctionConstantValues* cv = [MTLFunctionConstantValues new];+ for (const auto& v : c.vals) {+ int32_t iv = (int32_t)v.v;+ bool bv = v.v != 0;+ uint32_t uv = v.v;+ switch (v.type) {+ case 0: [cv setConstantValue:&iv type:MTLDataTypeInt atIndex:v.index]; break;+ case 1: [cv setConstantValue:&bv type:MTLDataTypeBool atIndex:v.index]; break;+ default: [cv setConstantValue:&uv type:MTLDataTypeUInt atIndex:v.index]; break;+ }+ }+ f = [impl_->libs[lib] newFunctionWithName:name constantValues:cv error:&err];+ }+ if (!f) {+ std::fprintf(stderr, "mtl: no function %s %s\n", fn.c_str(), err ? [[err localizedDescription] UTF8String] : "");+ std::exit(3);+ }+ MTLComputePipelineDescriptor* d = [MTLComputePipelineDescriptor new];+ d.computeFunction = f;+ d.supportIndirectCommandBuffers = YES;+ id<MTLComputePipelineState> ps = [impl_->dev newComputePipelineStateWithDescriptor:d+ options:MTLPipelineOptionNone+ reflection:nil+ error:&err];+ if (!ps) {+ std::fprintf(stderr, "mtl: pipeline %s: %s\n", fn.c_str(), [[err localizedDescription] UTF8String]);+ std::exit(3);+ }+ Pipeline p;+ p.handle = (__bridge_retained void*)ps;+ p.max_threads = (int)ps.maxTotalThreadsPerThreadgroup;+ p.simd_width = (int)ps.threadExecutionWidth;+ p.static_tg_mem = (int)ps.staticThreadgroupMemoryLength;+ return p;+}++Buffer Context::alloc(size_t bytes) {+ id<MTLBuffer> b = [impl_->dev newBufferWithLength:bytes options:MTLResourceStorageModeShared];+ if (!b) {+ std::fprintf(stderr, "mtl: alloc %zu failed\n", bytes);+ std::exit(4);+ }+ std::memset([b contents], 0, bytes);+ Buffer r;+ r.handle = (__bridge_retained void*)b;+ r.ptr = [b contents];+ r.bytes = bytes;+ return r;+}++Buffer Context::wrap(void* p, size_t bytes) {+ id<MTLBuffer> b = [impl_->dev newBufferWithBytesNoCopy:p length:bytes options:MTLResourceStorageModeShared deallocator:nil];+ if (!b) {+ std::fprintf(stderr, "mtl: wrap %zu failed\n", bytes);+ std::exit(4);+ }+ Buffer r;+ r.handle = (__bridge_retained void*)b;+ r.ptr = p;+ r.bytes = bytes;+ return r;+}++void Context::free(Buffer& b) {+ if (b.handle) {+ id<MTLBuffer> x = (__bridge_transfer id<MTLBuffer>)b.handle;+ x = nil;+ }+ b = Buffer{};+}++static void encode(id<MTLComputeCommandEncoder> enc, const Dispatch& d) {+ [enc setComputePipelineState:P(d.p)];+ for (size_t i = 0; i < d.args.size(); ++i) {+ const Arg& a = d.args[i];+ if (a.buf)+ [enc setBuffer:B(*a.buf) offset:a.off atIndex:i];+ else+ [enc setBytes:a.bytes.data() length:a.bytes.size() atIndex:i];+ }+ if (d.tg_mem) [enc setThreadgroupMemoryLength:(d.tg_mem + 15) / 16 * 16 atIndex:0];+ if (d.indirect)+ [enc dispatchThreadgroupsWithIndirectBuffer:B(*d.indirect)+ indirectBufferOffset:d.ind_off+ threadsPerThreadgroup:MTLSizeMake(d.tg[0], d.tg[1], d.tg[2])];+ else+ [enc dispatchThreadgroups:MTLSizeMake(d.grid[0], d.grid[1], d.grid[2])+ threadsPerThreadgroup:MTLSizeMake(d.tg[0], d.tg[1], d.tg[2])];+}++double Context::run(const std::vector<Dispatch>& ds, int reps, bool concurrent, bool barrier_between) {+ @autoreleasepool {+ id<MTLCommandBuffer> cb = [impl_->q commandBufferWithUnretainedReferences];+ id<MTLComputeCommandEncoder> enc =+ [cb computeCommandEncoderWithDispatchType:concurrent ? MTLDispatchTypeConcurrent : MTLDispatchTypeSerial];+ for (int r = 0; r < reps; ++r)+ for (const auto& d : ds) {+ encode(enc, d);+ if (barrier_between) [enc memoryBarrierWithScope:MTLBarrierScopeBuffers];+ }+ [enc endEncoding];+ [cb commit];+ [cb waitUntilCompleted];+ if (cb.status != MTLCommandBufferStatusCompleted) {+ std::fprintf(stderr, "mtl: command buffer failed: %s\n", [[cb.error localizedDescription] UTF8String]);+ std::exit(5);+ }+ return cb.GPUEndTime - cb.GPUStartTime;+ }+}++double Context::run_wall(const std::vector<Dispatch>& ds, int reps, double* gpu_seconds) {+ double gpu = 0;+ const double t0 = now_s();+ for (int r = 0; r < reps; ++r) {+ @autoreleasepool {+ id<MTLCommandBuffer> cb = [impl_->q commandBufferWithUnretainedReferences];+ id<MTLComputeCommandEncoder> enc = [cb computeCommandEncoder];+ for (const auto& d : ds) encode(enc, d);+ [enc endEncoding];+ [cb commit];+ [cb waitUntilCompleted];+ gpu += cb.GPUEndTime - cb.GPUStartTime;+ }+ }+ if (gpu_seconds) *gpu_seconds = gpu;+ return now_s() - t0;+}++double Context::run_icb(const std::vector<Dispatch>& ds, int reps, bool barrier_between) {+ @autoreleasepool {+ size_t maxb = 1;+ for (const auto& d : ds) maxb = std::max(maxb, d.args.size());+ MTLIndirectCommandBufferDescriptor* desc = [MTLIndirectCommandBufferDescriptor new];+ desc.commandTypes = MTLIndirectCommandTypeConcurrentDispatch;+ desc.inheritBuffers = NO;+ desc.inheritPipelineState = NO;+ desc.maxKernelBufferBindCount = maxb;+ id<MTLIndirectCommandBuffer> icb = [impl_->dev newIndirectCommandBufferWithDescriptor:desc+ maxCommandCount:ds.size()+ options:0];+ NSMutableSet* used = [NSMutableSet new];+ for (size_t i = 0; i < ds.size(); ++i) {+ const Dispatch& d = ds[i];+ id<MTLIndirectComputeCommand> c = [icb indirectComputeCommandAtIndex:i];+ [c setComputePipelineState:P(d.p)];+ for (size_t a = 0; a < d.args.size(); ++a) {+ if (!d.args[a].buf) {+ std::fprintf(stderr, "mtl: run_icb needs buffer arguments only\n");+ std::exit(5);+ }+ [c setKernelBuffer:B(*d.args[a].buf) offset:d.args[a].off atIndex:a];+ [used addObject:B(*d.args[a].buf)];+ }+ if (d.tg_mem) [c setThreadgroupMemoryLength:(d.tg_mem + 15) / 16 * 16 atIndex:0];+ [c concurrentDispatchThreadgroups:MTLSizeMake(d.grid[0], d.grid[1], d.grid[2])+ threadsPerThreadgroup:MTLSizeMake(d.tg[0], d.tg[1], d.tg[2])];+ if (barrier_between) [c setBarrier];+ }+ id<MTLCommandBuffer> cb = [impl_->q commandBufferWithUnretainedReferences];+ id<MTLComputeCommandEncoder> enc = [cb computeCommandEncoderWithDispatchType:MTLDispatchTypeConcurrent];+ for (id<MTLBuffer> b in used) [enc useResource:b usage:MTLResourceUsageRead | MTLResourceUsageWrite];+ for (int r = 0; r < reps; ++r) {+ [enc executeCommandsInBuffer:icb withRange:NSMakeRange(0, ds.size())];+ if (barrier_between) [enc memoryBarrierWithScope:MTLBarrierScopeBuffers];+ }+ [enc endEncoding];+ [cb commit];+ [cb waitUntilCompleted];+ if (cb.status != MTLCommandBufferStatusCompleted) {+ std::fprintf(stderr, "mtl: icb command buffer failed: %s\n", [[cb.error localizedDescription] UTF8String]);+ std::exit(5);+ }+ return cb.GPUEndTime - cb.GPUStartTime;+ }+}++} // namespace mtldiff --git a/metal/src/ref_quant.cpp b/metal/src/ref_quant.cppnew file mode 100644index 000000000..bc0219267--- /dev/null+++ b/metal/src/ref_quant.cpp@@ -0,0 +1,418 @@+// metal/src/ref_quant.cpp - see ref_quant.h. The i-quant loops are transcribed from ggml-quants.c+// (dequantize_row_iq2_xxs / iq2_xs / iq2_s / iq3_xxs / iq3_s / iq4_nl / iq4_xs) at 3cf03257; the K-quants and the+// 32-blocks from Strata's include/strata/artifact/dequant.hpp (themselves transcribed from the same commit).+#include "ref_quant.h"++#include <cmath>+#include <cstdio>+#include <cstdlib>+#include <cstring>++#define GGML_COMMON_DECL_CPP+#define GGML_COMMON_IMPL_CPP+#include "ggml-common.h"++namespace ref {++const char* type_name(int t) {+ switch (t) {+ case F32: return "F32"; case F16: return "F16"; case BF16: return "BF16";+ case Q4_0: return "Q4_0"; case Q5_0: return "Q5_0"; case Q8_0: return "Q8_0";+ case Q3_K: return "Q3_K"; case Q4_K: return "Q4_K"; case Q5_K: return "Q5_K"; case Q6_K: return "Q6_K";+ case IQ2_XXS: return "IQ2_XXS"; case IQ2_XS: return "IQ2_XS"; case IQ2_S: return "IQ2_S";+ case IQ3_XXS: return "IQ3_XXS"; case IQ3_S: return "IQ3_S"; case IQ4_NL: return "IQ4_NL";+ case IQ4_XS: return "IQ4_XS"; case Q2_0: return "Q2_0";+ }+ return "?";+}++int block_elems(int t) {+ switch (t) {+ case F32: case F16: case BF16: return 1;+ case Q4_0: case Q5_0: case Q8_0: case IQ4_NL: return 32;+ case Q2_0: return 64;+ default: return 256;+ }+}++int block_bytes(int t) {+ switch (t) {+ case F32: return 4; case F16: case BF16: return 2;+ case Q4_0: return 18; case Q5_0: return 22; case Q8_0: return 34; case IQ4_NL: return 18; case Q2_0: return 18;+ case Q3_K: return 110; case Q4_K: return 144; case Q5_K: return 176; case Q6_K: return 210;+ case IQ2_XXS: return 66; case IQ2_XS: return 74; case IQ2_S: return 82; case IQ3_XXS: return 98;+ case IQ3_S: return 110; case IQ4_XS: return 136;+ }+ std::fprintf(stderr, "ref: unknown type %d\n", t);+ std::exit(2);+}++float f16_to_f32(uint16_t h) {+ const uint32_t sign = (uint32_t)(h >> 15) & 1u;+ uint32_t exp = (h >> 10) & 0x1Fu, man = h & 0x3FFu, f;+ if (exp == 0) {+ if (man == 0)+ f = sign << 31;+ else {+ exp = 127 - 15 + 1;+ while (!(man & 0x400u)) { man <<= 1; --exp; }+ man &= 0x3FFu;+ f = (sign << 31) | (exp << 23) | (man << 13);+ }+ } else if (exp == 31)+ f = (sign << 31) | 0x7F800000u | (man << 13);+ else+ f = (sign << 31) | ((exp - 15 + 127) << 23) | (man << 13);+ float out;+ std::memcpy(&out, &f, 4);+ return out;+}++uint16_t f32_to_f16(float f) {+ _Float16 h = (_Float16)f;+ uint16_t r;+ std::memcpy(&r, &h, 2);+ return r;+}++float bf16_to_f32(uint16_t h) {+ const uint32_t f = (uint32_t)h << 16;+ float out;+ std::memcpy(&out, &f, 4);+ return out;+}++uint16_t f32_to_bf16(float f) {+ uint32_t u;+ std::memcpy(&u, &f, 4);+ u += 0x7FFFu + ((u >> 16) & 1u);+ return (uint16_t)(u >> 16);+}++static inline uint16_t rd16(const uint8_t* p) { return (uint16_t)(p[0] | (p[1] << 8)); }++static void get_scale_min_k4(int j, const uint8_t* q, uint8_t& d, uint8_t& m) {+ if (j < 4) {+ d = q[j] & 63;+ m = q[j + 4] & 63;+ } else {+ d = (q[j + 4] & 0x0F) | ((q[j - 4] >> 6) << 4);+ m = (q[j + 4] >> 4) | ((q[j - 0] >> 6) << 4);+ }+}++static void deq_block(int t, const uint8_t* b, float* y) {+ switch (t) {+ case Q2_0: {+ const float d = f16_to_f32(rd16(b));+ for (int j = 0; j < 64; ++j) y[j] = (float)(((b[2 + j / 4] >> ((j % 4) * 2)) & 3) - 1) * d;+ return;+ }+ case Q8_0: {+ const float d = f16_to_f32(rd16(b));+ for (int j = 0; j < 32; ++j) y[j] = (float)(int8_t)b[2 + j] * d;+ return;+ }+ case Q4_0: {+ const float d = f16_to_f32(rd16(b));+ for (int j = 0; j < 16; ++j) {+ y[j] = (float)((b[2 + j] & 15) - 8) * d;+ y[j + 16] = (float)((b[2 + j] >> 4) - 8) * d;+ }+ return;+ }+ case Q5_0: {+ const float d = f16_to_f32(rd16(b));+ uint32_t h;+ std::memcpy(&h, b + 2, 4);+ const uint8_t* qs = b + 6;+ for (int j = 0; j < 16; ++j) {+ const int x0 = (qs[j] & 15) | (((h >> j) & 1) << 4), x1 = (qs[j] >> 4) | (((h >> (j + 16)) & 1) << 4);+ y[j] = (float)(x0 - 16) * d;+ y[j + 16] = (float)(x1 - 16) * d;+ }+ return;+ }+ case IQ4_NL: {+ const float d = f16_to_f32(rd16(b));+ for (int j = 0; j < 16; ++j) {+ y[j] = d * kvalues_iq4nl[b[2 + j] & 15];+ y[j + 16] = d * kvalues_iq4nl[b[2 + j] >> 4];+ }+ return;+ }+ case IQ4_XS: {+ const float d = f16_to_f32(rd16(b));+ const uint16_t sh = rd16(b + 2);+ const uint8_t* sl = b + 4;+ const uint8_t* qs = b + 8;+ for (int ib = 0; ib < 8; ++ib) {+ const int ls = ((sl[ib / 2] >> (4 * (ib % 2))) & 15) | (((sh >> (2 * ib)) & 3) << 4);+ const float dl = d * (ls - 32);+ for (int j = 0; j < 16; ++j) {+ y[j] = dl * kvalues_iq4nl[qs[j] & 15];+ y[j + 16] = dl * kvalues_iq4nl[qs[j] >> 4];+ }+ y += 32;+ qs += 16;+ }+ return;+ }+ case Q6_K: {+ const uint8_t* ql = b;+ const uint8_t* qh = b + 128;+ const int8_t* sc = (const int8_t*)(b + 192);+ const float d = f16_to_f32(rd16(b + 208));+ for (int n = 0; n < 256; n += 128) {+ for (int l = 0; l < 32; ++l) {+ const int is = l / 16;+ const int q1 = (int)((ql[l] & 15) | (((qh[l] >> 0) & 3) << 4)) - 32;+ const int q2 = (int)((ql[l + 32] & 15) | (((qh[l] >> 2) & 3) << 4)) - 32;+ const int q3 = (int)((ql[l] >> 4) | (((qh[l] >> 4) & 3) << 4)) - 32;+ const int q4 = (int)((ql[l + 32] >> 4) | (((qh[l] >> 6) & 3) << 4)) - 32;+ y[l] = d * sc[is] * q1;+ y[l + 32] = d * sc[is + 2] * q2;+ y[l + 64] = d * sc[is + 4] * q3;+ y[l + 96] = d * sc[is + 6] * q4;+ }+ y += 128;+ ql += 64;+ qh += 32;+ sc += 8;+ }+ return;+ }+ case Q4_K: {+ const float d = f16_to_f32(rd16(b)), mn = f16_to_f32(rd16(b + 2));+ const uint8_t* sc = b + 4;+ const uint8_t* q = b + 16;+ int is = 0;+ for (int j = 0; j < 256; j += 64) {+ uint8_t s, m;+ get_scale_min_k4(is, sc, s, m);+ const float d1 = d * s, m1 = mn * m;+ get_scale_min_k4(is + 1, sc, s, m);+ const float d2 = d * s, m2 = mn * m;+ for (int l = 0; l < 32; ++l) *y++ = d1 * (q[l] & 15) - m1;+ for (int l = 0; l < 32; ++l) *y++ = d2 * (q[l] >> 4) - m2;+ q += 32;+ is += 2;+ }+ return;+ }+ case Q5_K: {+ const float d = f16_to_f32(rd16(b)), mn = f16_to_f32(rd16(b + 2));+ const uint8_t* sc = b + 4;+ const uint8_t* qh = b + 16;+ const uint8_t* ql = b + 48;+ int is = 0;+ uint8_t u1 = 1, u2 = 2;+ for (int j = 0; j < 256; j += 64) {+ uint8_t s, m;+ get_scale_min_k4(is, sc, s, m);+ const float d1 = d * s, m1 = mn * m;+ get_scale_min_k4(is + 1, sc, s, m);+ const float d2 = d * s, m2 = mn * m;+ for (int l = 0; l < 32; ++l) *y++ = d1 * ((ql[l] & 15) + ((qh[l] & u1) ? 16 : 0)) - m1;+ for (int l = 0; l < 32; ++l) *y++ = d2 * ((ql[l] >> 4) + ((qh[l] & u2) ? 16 : 0)) - m2;+ ql += 32;+ is += 2;+ u1 <<= 2;+ u2 <<= 2;+ }+ return;+ }+ case Q3_K: {+ const uint8_t* hm = b;+ const uint8_t* q = b + 32;+ const float d_all = f16_to_f32(rd16(b + 108));+ const uint32_t kmask1 = 0x03030303u, kmask2 = 0x0f0f0f0fu;+ uint32_t aux[4] = {0, 0, 0, 0};+ std::memcpy(aux, b + 96, 12);+ const uint32_t tmp = aux[2];+ aux[2] = ((aux[0] >> 4) & kmask2) | (((tmp >> 4) & kmask1) << 4);+ aux[3] = ((aux[1] >> 4) & kmask2) | (((tmp >> 6) & kmask1) << 4);+ aux[0] = (aux[0] & kmask2) | (((tmp >> 0) & kmask1) << 4);+ aux[1] = (aux[1] & kmask2) | (((tmp >> 2) & kmask1) << 4);+ const int8_t* scales = (const int8_t*)aux;+ int is = 0;+ uint8_t m = 1;+ for (int n = 0; n < 256; n += 128) {+ int shift = 0;+ for (int j = 0; j < 4; ++j) {+ float dl = d_all * (scales[is++] - 32);+ for (int l = 0; l < 16; ++l) *y++ = dl * ((int8_t)((q[l] >> shift) & 3) - ((hm[l] & m) ? 0 : 4));+ dl = d_all * (scales[is++] - 32);+ for (int l = 0; l < 16; ++l)+ *y++ = dl * ((int8_t)((q[l + 16] >> shift) & 3) - ((hm[l + 16] & m) ? 0 : 4));+ shift += 2;+ m <<= 1;+ }+ q += 32;+ }+ return;+ }+ case IQ2_XXS: {+ const float d = f16_to_f32(rd16(b));+ const uint8_t* qs = b + 2;+ for (int ib32 = 0; ib32 < 8; ++ib32) {+ uint32_t aux32[2];+ std::memcpy(aux32, qs + 8 * ib32, 8);+ const uint8_t* aux8 = (const uint8_t*)aux32;+ const float db = d * (0.5f + (aux32[1] >> 28)) * 0.25f;+ for (int l = 0; l < 4; ++l) {+ const uint8_t* grid = (const uint8_t*)(iq2xxs_grid + aux8[l]);+ const uint8_t signs = ksigns_iq2xs[(aux32[1] >> 7 * l) & 127];+ for (int j = 0; j < 8; ++j) y[j] = db * grid[j] * (signs & kmask_iq2xs[j] ? -1.f : 1.f);+ y += 8;+ }+ }+ return;+ }+ case IQ2_XS: {+ const float d = f16_to_f32(rd16(b));+ const uint8_t* q8 = b + 2;+ const uint8_t* scales = b + 66;+ for (int ib32 = 0; ib32 < 8; ++ib32) {+ const float db0 = d * (0.5f + (scales[ib32] & 15)) * 0.25f;+ const float db1 = d * (0.5f + (scales[ib32] >> 4)) * 0.25f;+ for (int l = 0; l < 4; ++l) {+ const uint16_t q = rd16(q8 + 2 * (4 * ib32 + l));+ const uint8_t* grid = (const uint8_t*)(iq2xs_grid + (q & 511));+ const uint8_t signs = ksigns_iq2xs[q >> 9];+ const float db = l < 2 ? db0 : db1;+ for (int j = 0; j < 8; ++j) y[j] = db * grid[j] * (signs & kmask_iq2xs[j] ? -1.f : 1.f);+ y += 8;+ }+ }+ return;+ }+ case IQ2_S: {+ const float d = f16_to_f32(rd16(b));+ const uint8_t* qs = b + 2;+ const uint8_t* qh = b + 66;+ const uint8_t* scales = b + 74;+ const uint8_t* signs = qs + 32;+ for (int ib32 = 0; ib32 < 8; ++ib32) {+ const float db0 = d * (0.5f + (scales[ib32] & 15)) * 0.25f;+ const float db1 = d * (0.5f + (scales[ib32] >> 4)) * 0.25f;+ for (int l = 0; l < 4; ++l) {+ const float dl = l < 2 ? db0 : db1;+ const uint8_t* grid = (const uint8_t*)(iq2s_grid + (qs[l] | ((qh[ib32] << (8 - 2 * l)) & 0x300)));+ for (int j = 0; j < 8; ++j) y[j] = dl * grid[j] * (signs[l] & kmask_iq2xs[j] ? -1.f : 1.f);+ y += 8;+ }+ qs += 4;+ signs += 4;+ }+ return;+ }+ case IQ3_XXS: {+ const float d = f16_to_f32(rd16(b));+ const uint8_t* qs = b + 2;+ const uint8_t* sas = b + 2 + 64;+ for (int ib32 = 0; ib32 < 8; ++ib32) {+ uint32_t aux32;+ std::memcpy(&aux32, sas + 4 * ib32, 4);+ const float db = d * (0.5f + (aux32 >> 28)) * 0.5f;+ for (int l = 0; l < 4; ++l) {+ const uint8_t signs = ksigns_iq2xs[(aux32 >> 7 * l) & 127];+ const uint8_t* g1 = (const uint8_t*)(iq3xxs_grid + qs[2 * l + 0]);+ const uint8_t* g2 = (const uint8_t*)(iq3xxs_grid + qs[2 * l + 1]);+ for (int j = 0; j < 4; ++j) {+ y[j + 0] = db * g1[j] * (signs & kmask_iq2xs[j + 0] ? -1.f : 1.f);+ y[j + 4] = db * g2[j] * (signs & kmask_iq2xs[j + 4] ? -1.f : 1.f);+ }+ y += 8;+ }+ qs += 8;+ }+ return;+ }+ case IQ3_S: {+ const float d = f16_to_f32(rd16(b));+ const uint8_t* qs = b + 2;+ const uint8_t* qh = b + 66;+ const uint8_t* signs = b + 74;+ const uint8_t* scales = b + 106;+ for (int ib32 = 0; ib32 < 8; ib32 += 2) {+ const float db1 = d * (1 + 2 * (scales[ib32 / 2] & 15));+ const float db2 = d * (1 + 2 * (scales[ib32 / 2] >> 4));+ for (int l = 0; l < 4; ++l) {+ const uint8_t* g1 = (const uint8_t*)(iq3s_grid + (qs[2 * l + 0] | ((qh[0] << (8 - 2 * l)) & 256)));+ const uint8_t* g2 = (const uint8_t*)(iq3s_grid + (qs[2 * l + 1] | ((qh[0] << (7 - 2 * l)) & 256)));+ for (int j = 0; j < 4; ++j) {+ y[j + 0] = db1 * g1[j] * (signs[l] & kmask_iq2xs[j + 0] ? -1.f : 1.f);+ y[j + 4] = db1 * g2[j] * (signs[l] & kmask_iq2xs[j + 4] ? -1.f : 1.f);+ }+ y += 8;+ }+ qs += 8;+ signs += 4;+ for (int l = 0; l < 4; ++l) {+ const uint8_t* g1 = (const uint8_t*)(iq3s_grid + (qs[2 * l + 0] | ((qh[1] << (8 - 2 * l)) & 256)));+ const uint8_t* g2 = (const uint8_t*)(iq3s_grid + (qs[2 * l + 1] | ((qh[1] << (7 - 2 * l)) & 256)));+ for (int j = 0; j < 4; ++j) {+ y[j + 0] = db2 * g1[j] * (signs[l] & kmask_iq2xs[j + 0] ? -1.f : 1.f);+ y[j + 4] = db2 * g2[j] * (signs[l] & kmask_iq2xs[j + 4] ? -1.f : 1.f);+ }+ y += 8;+ }+ qh += 2;+ qs += 8;+ signs += 4;+ }+ return;+ }+ }+ std::fprintf(stderr, "ref: dequant of %s not implemented\n", type_name(t));+ std::exit(2);+}++void dequant(int t, const void* src, float* dst, size_t n) {+ const uint8_t* s = (const uint8_t*)src;+ if (t == F32) { std::memcpy(dst, s, n * 4); return; }+ if (t == F16) { for (size_t i = 0; i < n; ++i) dst[i] = f16_to_f32(rd16(s + 2 * i)); return; }+ if (t == BF16) { for (size_t i = 0; i < n; ++i) dst[i] = bf16_to_f32(rd16(s + 2 * i)); return; }+ const int be = block_elems(t), bb = block_bytes(t);+ for (size_t i = 0; i < n / be; ++i) deq_block(t, s + i * bb, dst + i * be);+}++static void put16(uint8_t* p, uint16_t v) { p[0] = (uint8_t)v; p[1] = (uint8_t)(v >> 8); }++void random_blocks(int t, uint8_t* dst, int rows, int cols, uint64_t seed, float scale) {+ Rng r(seed);+ const size_t n = (size_t)rows * cols;+ if (t == F32 || t == F16 || t == BF16) {+ for (size_t i = 0; i < n; ++i) {+ const float v = r.sym() * scale * 2.0f;+ if (t == F32) std::memcpy(dst + 4 * i, &v, 4);+ else put16(dst + 2 * i, t == F16 ? f32_to_f16(v) : f32_to_bf16(v));+ }+ return;+ }+ const int be = block_elems(t), bb = block_bytes(t);+ const size_t nb = n / be;+ for (size_t i = 0; i < nb; ++i) {+ uint8_t* b = dst + i * bb;+ for (int k = 0; k < bb; ++k) b[k] = (uint8_t)r.next();+ // the scale fields: magnitude so that |w| ~ scale. Typical code magnitudes differ per type.+ const float u = 0.5f + r.uni();+ switch (t) {+ case Q2_0: put16(b, f32_to_f16(scale * u)); break;+ case Q8_0: put16(b, f32_to_f16(scale * u / 64)); break;+ case Q4_0: case IQ4_NL: put16(b, f32_to_f16(scale * u / (t == Q4_0 ? 4 : 64))); break;+ case Q5_0: put16(b, f32_to_f16(scale * u / 8)); break;+ case IQ4_XS: put16(b, f32_to_f16(scale * u / 64 / 16)); break;+ case Q4_K: case Q5_K: put16(b, f32_to_f16(scale * u / 32 / 8)); put16(b + 2, f32_to_f16(scale * u / 32 / 2)); break;+ case Q6_K: put16(b + 208, f32_to_f16(scale * u / 32 / 64)); break;+ case Q3_K: put16(b + 108, f32_to_f16(scale * u / 32 / 2)); break;+ case IQ2_XXS: case IQ2_XS: case IQ2_S: put16(b, f32_to_f16(scale * u / 4)); break;+ case IQ3_XXS: put16(b, f32_to_f16(scale * u / 8)); break;+ case IQ3_S: put16(b, f32_to_f16(scale * u / 64)); break;+ default: break;+ }+ }+}++} // namespace refdiff --git a/metal/src/ref_quant.h b/metal/src/ref_quant.hnew file mode 100644index 000000000..fc2fc9bbd--- /dev/null+++ b/metal/src/ref_quant.h@@ -0,0 +1,43 @@+// metal/src/ref_quant.h - CPU reference dequantizers for the parity programs, transcribed from ggml's+// dequantize_row_* (ggml-quants.c at the pinned 3cf03257) and Strata's src/artifact/dequant.hpp (Q2_0), plus a+// deterministic generator of random-but-valid blocks for synthetic weights.+#pragma once++#include <cstddef>+#include <cstdint>+#include <vector>++namespace ref {++// GGML type ids (stable, as in native_mmvq.hpp)+enum : int {+ F32 = 0, F16 = 1, Q4_0 = 2, Q5_0 = 6, Q8_0 = 8, Q3_K = 11, Q4_K = 12, Q5_K = 13, Q6_K = 14,+ IQ2_XXS = 16, IQ2_XS = 17, IQ3_XXS = 18, IQ3_S = 21, IQ2_S = 22, IQ4_NL = 20, IQ4_XS = 23, BF16 = 30, Q2_0 = 42,+};++const char* type_name(int t);+int block_elems(int t);+int block_bytes(int t);+inline size_t row_bytes(int t, int n) { return (size_t)n / block_elems(t) * block_bytes(t); }++float f16_to_f32(uint16_t h);+uint16_t f32_to_f16(float f);+float bf16_to_f32(uint16_t h);+uint16_t f32_to_bf16(float f); // round to nearest even++// Dequantizes `n` elements (a whole number of blocks) of type t.+void dequant(int t, const void* src, float* dst, size_t n);++// Fills `bytes` with random valid blocks of type t for a matrix of rows x cols: random codes, block scales drawn so+// that the weights have roughly unit-free magnitude `scale` (the d fields are finite FP16).+void random_blocks(int t, uint8_t* dst, int rows, int cols, uint64_t seed, float scale = 0.02f);++struct Rng {+ uint64_t s;+ explicit Rng(uint64_t seed) : s(seed * 0x9E3779B97F4A7C15ull + 1) {}+ uint64_t next() { s ^= s << 13; s ^= s >> 7; s ^= s << 17; return s; }+ float uni() { return (next() >> 40) * (1.0f / 16777216.0f); } // [0,1)+ float sym() { return uni() * 2.0f - 1.0f; } // [-1,1)+};++} // namespace refdiff --git a/metal/tests/expert_parity.cpp b/metal/tests/expert_parity.cppnew file mode 100644index 000000000..a2e23662b--- /dev/null+++ b/metal/tests/expert_parity.cpp@@ -0,0 +1,399 @@+// metal/tests/expert_parity.cpp - the grouped routed-expert kernels (moe.metal) against a double-precision CPU+// reference, and their speed.+//+// expert_parity [--gu Q2_0] [--dn Q2_0] [--ntok 1..8] [--gucfg L,R,S] [--dncfg L,R,S] parity (synthetic)+// expert_parity --bench [--gu ..] [--dn ..] [--ntok N] [--layers 8] [--reps 96] [--sweep] speed+//+// Parity: random valid blocks for 64 experts, random activations x ~ U(-1,1), random distinct top-10 per token,+// weights summing to 1. Checked: the plan (groups by expert id, entries in (token, k) order), h = silu(gate) * up+// per entry and y = sum_k w * down . h, each against double; reported as max |err| / max |ref| and relative L2.+// Bench: `layers` distinct copies of a 512-expert arena (no reuse across reps beyond chance; the SLC is ~32 MB),+// a different random routing per rep; GB/s = bytes of the distinct experts the kernel must read / GPU time.+#include "mtl_rt.h"+#include "ref_quant.h"++#include <algorithm>+#include <cmath>+#include <cstdio>+#include <cstdlib>+#include <cstring>+#include <map>+#include <set>+#include <string>+#include <vector>++namespace {++constexpr int N_EMBD = 2560, N_FF = 640, TOPK = 10;+// plan layout (moe.metal)+constexpr int P_NG = 0, P_IGU = 4, P_IDN = 8, P_MAXE = 128, P_GEXP = 16, P_GSTART = P_GEXP + P_MAXE,+ P_ETOK = P_GSTART + P_MAXE + 4, P_EW = P_ETOK + P_MAXE, P_TOKENT = P_EW + P_MAXE,+ P_INTS = P_TOKENT + P_MAXE;++struct MoeArgs {+ uint64_t blob_bytes, up_off, down_off;+ uint32_t gu_row, d_row, n_embd, n_ff, n_tok, topk, n_expert, gx_gu, gx_dn, pad;+};++int type_of(const std::string& s) {+ for (int t : {ref::Q2_0, ref::IQ3_XXS, ref::IQ2_XXS, ref::IQ2_XS, ref::IQ2_S, ref::IQ3_S, ref::IQ4_NL})+ if (s == ref::type_name(t)) return t;+ std::fprintf(stderr, "unknown type %s\n", s.c_str());+ std::exit(2);+}++struct Cfg { int L, R, S; };+Cfg parse_cfg(const char* s) {+ Cfg c{};+ if (std::sscanf(s, "%d,%d,%d", &c.L, &c.R, &c.S) != 3) { std::fprintf(stderr, "bad cfg %s\n", s); std::exit(2); }+ return c;+}+std::string kname(const char* k, int t, Cfg c) {+ return std::string(k) + "_" + std::to_string(t) + "_" + std::to_string(c.L) + "_" + std::to_string(c.R) + "_" ++ std::to_string(c.S);+}+int rows_per_tg(Cfg c) { return c.S * (32 / c.L) * c.R; }++struct Layout {+ int gu, dn;+ size_t gu_row, d_row, up_off, down_off, blob;+};+Layout layout(int gu, int dn) {+ Layout L{gu, dn};+ L.gu_row = ref::row_bytes(gu, N_EMBD);+ L.d_row = ref::row_bytes(dn, N_FF);+ L.up_off = (size_t)N_FF * L.gu_row;+ L.down_off = 2 * L.up_off;+ L.blob = L.down_off + (size_t)N_EMBD * L.d_row;+ return L;+}++void random_routing(ref::Rng& r, int ntok, int n_expert, std::vector<int>& ids, std::vector<float>& w,+ double share = 0.0, const std::vector<int>* prev = nullptr) {+ ids.assign(ntok * TOPK, 0);+ w.assign(ntok * TOPK, 0.0f);+ for (int t = 0; t < ntok; ++t) {+ std::set<int> used;+ float sum = 0;+ for (int k = 0; k < TOPK; ++k) {+ int e;+ do {+ // with probability `share`, reuse an expert of the previous token (verify windows share experts)+ if (t > 0 && share > 0 && r.uni() < share) e = ids[(t - 1) * TOPK + (r.next() % TOPK)];+ else e = (int)(r.next() % n_expert);+ } while (used.count(e));+ used.insert(e);+ ids[t * TOPK + k] = e;+ w[t * TOPK + k] = 0.2f + r.uni();+ sum += w[t * TOPK + k];+ }+ for (int k = 0; k < TOPK; ++k) w[t * TOPK + k] /= sum;+ }+ (void)prev;+}++struct Kernels {+ mtl::Pipeline plan, gu, dn, comb;+ Cfg cgu, cdn;+};++void encode_layer(std::vector<mtl::Dispatch>& ds, const Kernels& K, const mtl::Buffer& W, size_t w_off,+ const mtl::Buffer& x, const mtl::Buffer& h, const mtl::Buffer& ye, const mtl::Buffer& y,+ const mtl::Buffer& ids, const mtl::Buffer& wts, const mtl::Buffer& plan, size_t plan_off,+ const MoeArgs& a, bool with_plan, bool with_gu, bool with_dn, bool with_comb) {+ if (with_plan) {+ mtl::Dispatch d;+ d.p = &K.plan;+ d.args = {mtl::Arg::B(ids), mtl::Arg::B(wts), mtl::Arg::B(plan, plan_off), mtl::Arg::V(a)};+ d.tg[0] = 512;+ ds.push_back(d);+ }+ if (with_gu) {+ mtl::Dispatch d;+ d.p = &K.gu;+ d.args = {mtl::Arg::B(W, w_off), mtl::Arg::B(x), mtl::Arg::B(h), mtl::Arg::B(plan, plan_off), mtl::Arg::V(a)};+ d.tg[0] = K.cgu.S * 32;+ d.indirect = &plan;+ d.ind_off = plan_off + P_IGU * 4;+ ds.push_back(d);+ }+ if (with_dn) {+ mtl::Dispatch d;+ d.p = &K.dn;+ d.args = {mtl::Arg::B(W, w_off), mtl::Arg::B(h), mtl::Arg::B(ye), mtl::Arg::B(plan, plan_off), mtl::Arg::V(a)};+ d.tg[0] = K.cdn.S * 32;+ d.indirect = &plan;+ d.ind_off = plan_off + P_IDN * 4;+ ds.push_back(d);+ }+ if (with_comb) {+ mtl::Dispatch d;+ d.p = &K.comb;+ d.args = {mtl::Arg::B(ye), mtl::Arg::B(y), mtl::Arg::B(plan, plan_off), mtl::Arg::V(a)};+ d.tg[0] = 256;+ d.grid[0] = (a.n_tok * N_EMBD + 255) / 256;+ ds.push_back(d);+ }+}++struct Err {+ double max_abs = 0, max_ref = 0, se = 0, sr = 0;+ void add(double got, double ref) {+ max_abs = std::max(max_abs, std::fabs(got - ref));+ max_ref = std::max(max_ref, std::fabs(ref));+ se += (got - ref) * (got - ref);+ sr += ref * ref;+ }+ double rel_max() const { return max_ref > 0 ? max_abs / max_ref : max_abs; }+ double rel_l2() const { return sr > 0 ? std::sqrt(se / sr) : std::sqrt(se); }+};++double median(std::vector<double> v) {+ std::sort(v.begin(), v.end());+ return v[v.size() / 2];+}++} // namespace++int main(int argc, char** argv) {+ int gu = ref::Q2_0, dn = ref::Q2_0, ntok = 1, layers = 8, reps = 96;+ Cfg cgu{32, 2, 4}, cdn{8, 2, 4};+ bool bench = false, sweep = false;+ double share = 0.0;+ bool cfg_gu_set = false, cfg_dn_set = false;+ for (int i = 1; i < argc; ++i) {+ std::string a = argv[i];+ auto nx = [&] { return i + 1 < argc ? argv[++i] : (std::fprintf(stderr, "%s needs a value\n", a.c_str()), std::exit(2), (char*)nullptr); };+ if (a == "--gu") gu = type_of(nx());+ else if (a == "--dn") dn = type_of(nx());+ else if (a == "--ntok") ntok = std::atoi(nx());+ else if (a == "--gucfg") { cgu = parse_cfg(nx()); cfg_gu_set = true; }+ else if (a == "--dncfg") { cdn = parse_cfg(nx()); cfg_dn_set = true; }+ else if (a == "--bench") bench = true;+ else if (a == "--sweep") sweep = true;+ else if (a == "--layers") layers = std::atoi(nx());+ else if (a == "--reps") reps = std::atoi(nx());+ else if (a == "--share") share = std::atof(nx());+ else { std::fprintf(stderr, "unknown argument %s\n", a.c_str()); return 2; }+ }+ (void)cfg_gu_set;+ (void)cfg_dn_set;+ if (dn == ref::IQ4_NL && cdn.L == 8 && !cfg_dn_set) cdn = {4, 2, 4};+ mtl::Context cx;+ const int lib = cx.compile({"quant.metal", "moe.metal"});+ const Layout L = layout(gu, dn);+ std::printf("device %s; gate/up %s, down %s, blob %zu bytes; %d token(s)\n", cx.device_name().c_str(),+ ref::type_name(gu), ref::type_name(dn), L.blob, ntok);++ auto make = [&](Cfg a, Cfg b) {+ Kernels K;+ K.plan = cx.pipeline(lib, "moe_plan");+ K.comb = cx.pipeline(lib, "moe_combine");+ K.gu = cx.pipeline(lib, kname("moe_gu", gu, a));+ K.dn = cx.pipeline(lib, kname("moe_down", dn, b));+ K.cgu = a;+ K.cdn = b;+ return K;+ };+ auto args_for = [&](const Kernels& K, int nt, int n_expert) {+ MoeArgs a{};+ a.blob_bytes = L.blob;+ a.up_off = L.up_off;+ a.down_off = L.down_off;+ a.gu_row = (uint32_t)L.gu_row;+ a.d_row = (uint32_t)L.d_row;+ a.n_embd = N_EMBD;+ a.n_ff = N_FF;+ a.n_tok = nt;+ a.topk = TOPK;+ a.n_expert = n_expert;+ a.gx_gu = N_FF / rows_per_tg(K.cgu);+ a.gx_dn = N_EMBD / rows_per_tg(K.cdn);+ return a;+ };++ mtl::Buffer x = cx.alloc(4 * 8 * N_EMBD), h = cx.alloc(4 * 8 * TOPK * N_FF), ye = cx.alloc(4 * 8 * TOPK * N_EMBD),+ y = cx.alloc(4 * 8 * N_EMBD);+ ref::Rng rng(12345);+ for (int i = 0; i < 8 * N_EMBD; ++i) x.as<float>()[i] = rng.sym();++ if (!bench) {+ // ---------------- parity ----------------+ const int NE = 64;+ mtl::Buffer W = cx.alloc(L.blob * NE);+ for (int e = 0; e < NE; ++e) {+ uint8_t* b = W.as<uint8_t>() + e * L.blob;+ ref::random_blocks(gu, b, 2 * N_FF, N_EMBD, 1000 + e);+ ref::random_blocks(dn, b + L.down_off, N_EMBD, N_FF, 5000 + e);+ }+ std::vector<int> ids;+ std::vector<float> w;+ random_routing(rng, ntok, NE, ids, w, 0.3);+ mtl::Buffer bid = cx.alloc(4 * ids.size()), bw = cx.alloc(4 * w.size()), plan = cx.alloc(4 * P_INTS);+ std::memcpy(bid.ptr, ids.data(), 4 * ids.size());+ std::memcpy(bw.ptr, w.data(), 4 * w.size());+ Kernels K = make(cgu, cdn);+ MoeArgs a = args_for(K, ntok, 512);+ std::vector<mtl::Dispatch> ds;+ encode_layer(ds, K, W, 0, x, h, ye, y, bid, bw, plan, 0, a, true, true, true, true);+ cx.run(ds);+ // the plan+ const int* P = plan.as<int>();+ std::set<int> distinct(ids.begin(), ids.end());+ bool plan_ok = P[P_NG] == (int)distinct.size() && P[P_IGU + 1] == P[P_NG] && P[P_IDN + 1] == P[P_NG];+ {+ int gi = 0;+ for (int e : distinct) {+ if (P[P_GEXP + gi] != e) plan_ok = false;+ int j = P[P_GSTART + gi];+ for (int i = 0; i < ntok * TOPK; ++i)+ if (ids[i] == e) {+ if (P[P_ETOK + j] != i / TOPK || P[P_TOKENT + i] != j) plan_ok = false;+ float fw;+ std::memcpy(&fw, &P[P_EW + j], 4);+ if (fw != w[i]) plan_ok = false;+ ++j;+ }+ if (j != P[P_GSTART + gi + 1]) plan_ok = false;+ ++gi;+ }+ }+ // the reference+ Err eh, ey;+ std::vector<float> wg(N_FF * N_EMBD), wu(N_FF * N_EMBD), wd(N_EMBD * N_FF);+ std::vector<double> yref(ntok * N_EMBD, 0.0);+ for (int i = 0; i < ntok * TOPK; ++i) {+ const int e = ids[i], t = i / TOPK;+ const uint8_t* b = W.as<uint8_t>() + e * L.blob;+ ref::dequant(gu, b, wg.data(), wg.size());+ ref::dequant(gu, b + L.up_off, wu.data(), wu.size());+ ref::dequant(dn, b + L.down_off, wd.data(), wd.size());+ const float* xt = x.as<float>() + t * N_EMBD;+ std::vector<double> hr(N_FF);+ const int ent = P[P_TOKENT + i];+ for (int r = 0; r < N_FF; ++r) {+ double g = 0, u = 0;+ for (int k = 0; k < N_EMBD; ++k) {+ g += (double)wg[r * N_EMBD + k] * xt[k];+ u += (double)wu[r * N_EMBD + k] * xt[k];+ }+ hr[r] = g / (1.0 + std::exp(-g)) * u;+ eh.add(h.as<float>()[ent * N_FF + r], hr[r]);+ }+ for (int r = 0; r < N_EMBD; ++r) {+ double s = 0;+ // the reference down uses the GPU's h (float) so that the y check isolates the down kernel ...+ for (int k = 0; k < N_FF; ++k) s += (double)wd[r * N_FF + k] * h.as<float>()[ent * N_FF + k];+ yref[t * N_EMBD + r] += w[i] * s;+ }+ }+ for (int i = 0; i < ntok * N_EMBD; ++i) ey.add(y.as<float>()[i], yref[i]);+ const bool ok = plan_ok && eh.rel_l2() < 1e-5 && ey.rel_l2() < 1e-5 && eh.rel_max() < 1e-4 && ey.rel_max() < 1e-4;+ std::printf("parity %s/%s ntok %d gu %d,%d,%d dn %d,%d,%d: plan %s (%d groups), h rel L2 %.2e max %.2e, "+ "y rel L2 %.2e max %.2e %s\n",+ ref::type_name(gu), ref::type_name(dn), ntok, cgu.L, cgu.R, cgu.S, cdn.L, cdn.R, cdn.S,+ plan_ok ? "ok" : "WRONG", P[P_NG], eh.rel_l2(), eh.rel_max(), ey.rel_l2(), ey.rel_max(),+ ok ? "PASS" : "FAIL");+ return ok ? 0 : 1;+ }++ // ---------------- bench ----------------+ const int NE = 512;+ const size_t layer_bytes = L.blob * NE;+ std::printf("arena: %d layers x %d experts = %.2f GB (max buffer %.1f GB)\n", layers, NE, layers * layer_bytes / 1e9,+ cx.max_buffer_length() / 1e9);+ mtl::Buffer W = cx.alloc(layer_bytes * layers);+ {+ // 64 distinct random experts, copied over the arena+ std::vector<uint8_t> tmp(L.blob * 64);+ for (int e = 0; e < 64; ++e) {+ ref::random_blocks(gu, tmp.data() + e * L.blob, 2 * N_FF, N_EMBD, 1000 + e);+ ref::random_blocks(dn, tmp.data() + e * L.blob + L.down_off, N_EMBD, N_FF, 5000 + e);+ }+ for (size_t e = 0; e < (size_t)NE * layers; ++e)+ std::memcpy(W.as<uint8_t>() + e * L.blob, tmp.data() + (e % 64) * L.blob, L.blob);+ }+ std::vector<std::vector<int>> rids(reps);+ std::vector<std::vector<float>> rw(reps);+ mtl::Buffer bid = cx.alloc(4 * 8 * TOPK * reps), bw = cx.alloc(4 * 8 * TOPK * reps), plan = cx.alloc(4 * P_INTS * reps);+ auto set_routing = [&](int nt) {+ double groups = 0;+ for (int r = 0; r < reps; ++r) {+ random_routing(rng, nt, NE, rids[r], rw[r], share);+ std::memcpy(bid.as<int>() + r * 8 * TOPK, rids[r].data(), 4 * rids[r].size());+ std::memcpy(bw.as<float>() + r * 8 * TOPK, rw[r].data(), 4 * rw[r].size());+ groups += std::set<int>(rids[r].begin(), rids[r].end()).size();+ }+ return groups / reps;+ };+ auto run_cfg = [&](const Kernels& K, int nt, double groups, bool print) {+ const MoeArgs a = args_for(K, nt, NE);+ std::vector<mtl::Dispatch> dp, dg, dd, dall;+ for (int r = 0; r < reps; ++r) {+ const size_t woff = (size_t)(r % layers) * layer_bytes;+ std::vector<mtl::Dispatch> one;+ encode_layer(one, K, W, woff, x, h, ye, y, bid, bw, plan, (size_t)r * P_INTS * 4, a, true, false, false, false);+ one[0].args[0] = mtl::Arg::B(bid, (size_t)r * 8 * TOPK * 4);+ one[0].args[1] = mtl::Arg::B(bw, (size_t)r * 8 * TOPK * 4);+ dp.push_back(one[0]);+ std::vector<mtl::Dispatch> g, d;+ encode_layer(g, K, W, woff, x, h, ye, y, bid, bw, plan, (size_t)r * P_INTS * 4, a, false, true, false, false);+ encode_layer(d, K, W, woff, x, h, ye, y, bid, bw, plan, (size_t)r * P_INTS * 4, a, false, false, true, false);+ dg.push_back(g[0]);+ dd.push_back(d[0]);+ dall.push_back(one[0]);+ dall.push_back(g[0]);+ dall.push_back(d[0]);+ }+ cx.run(dp); // plans in place+ std::vector<double> tp, tg, td, ta;+ for (int it = 0; it < 7; ++it) {+ tp.push_back(cx.run(dp) / reps);+ tg.push_back(cx.run(dg) / reps);+ td.push_back(cx.run(dd) / reps);+ ta.push_back(cx.run(dall) / reps);+ }+ const double mp = median(tp), mg = median(tg), md = median(td), ma = median(ta);+ const double bg = groups * 2.0 * N_FF * L.gu_row, bd = groups * N_EMBD * L.d_row;+ if (print)+ std::printf("ntok %d groups %5.1f | gu %2d,%d,%d %7.1f us %6.1f GB/s | dn %2d,%d,%d %7.1f us %6.1f GB/s | "+ "plan %5.1f us | layer %7.1f us = %6.1f GB/s (%4.1f%% of 585)\n",+ nt, groups, K.cgu.L, K.cgu.R, K.cgu.S, mg * 1e6, bg / mg / 1e9, K.cdn.L, K.cdn.R, K.cdn.S,+ md * 1e6, bd / md / 1e9, mp * 1e6, ma * 1e6, (bg + bd) / ma / 1e9,+ (bg + bd) / ma / 1e9 / 585 * 100);+ return std::make_pair(mg, md);+ };+ const std::vector<Cfg> gus = {{32, 1, 4}, {32, 2, 4}, {32, 4, 4}, {32, 2, 2}, {32, 2, 8}, {32, 1, 8},+ {16, 1, 4}, {16, 2, 4}, {8, 1, 4}, {8, 2, 4}, {8, 1, 2}};+ const std::vector<Cfg> dns = {{8, 1, 4}, {8, 2, 4}, {8, 4, 4}, {8, 1, 8}, {8, 2, 8}, {4, 1, 4},+ {4, 2, 4}, {4, 4, 4}, {16, 1, 4}, {16, 2, 4}, {32, 1, 4}, {2, 2, 4}};+ std::vector<int> ntoks = {ntok};+ if (sweep) ntoks = {1, 2, 3, 4, 8};+ for (int nt : ntoks) {+ const double groups = set_routing(nt);+ if (sweep) {+ // gate/up sweep with the default down, then down sweep with the best gate/up+ Cfg bgu = cgu, bdn = cdn;+ double best = 1e9;+ for (Cfg c : gus) {+ if (N_FF % rows_per_tg(c)) continue;+ auto t = run_cfg(make(c, cdn), nt, groups, false);+ std::printf(" gu %2d,%d,%d: %7.1f us %6.1f GB/s\n", c.L, c.R, c.S, t.first * 1e6,+ groups * 2.0 * N_FF * L.gu_row / t.first / 1e9);+ if (t.first < best) { best = t.first; bgu = c; }+ }+ best = 1e9;+ for (Cfg c : dns) {+ if (N_EMBD % rows_per_tg(c)) continue;+ auto t = run_cfg(make(bgu, c), nt, groups, false);+ std::printf(" dn %2d,%d,%d: %7.1f us %6.1f GB/s\n", c.L, c.R, c.S, t.second * 1e6,+ groups * N_EMBD * L.d_row / t.second / 1e9);+ if (t.second < best) { best = t.second; bdn = c; }+ }+ run_cfg(make(bgu, bdn), nt, groups, true);+ } else {+ run_cfg(make(cgu, cdn), nt, groups, true);+ }+ }+ return 0;+}diff --git a/metal/tests/ref_dump.cpp b/metal/tests/ref_dump.cppnew file mode 100644index 000000000..3cce42e6b--- /dev/null+++ b/metal/tests/ref_dump.cpp@@ -0,0 +1,30 @@+// metal/tests/ref_dump.cpp - writes random blocks of every type ref_quant knows and their CPU-reference dequant, so+// that the reference itself can be checked against gguf-py (metal/tools/check_ref.py):+// ref_dump <dir> -> <dir>/<TYPE>.bin (raw blocks, 16 rows x 2560) and <dir>/<TYPE>.f32+#include "ref_quant.h"++#include <cstdio>+#include <string>+#include <vector>++int main(int argc, char** argv) {+ const std::string dir = argc > 1 ? argv[1] : ".";+ const int rows = 16, cols = 2560;+ for (int t : {ref::Q2_0, ref::Q4_0, ref::Q5_0, ref::Q8_0, ref::Q3_K, ref::Q4_K, ref::Q5_K, ref::Q6_K, ref::IQ2_XXS,+ ref::IQ2_XS, ref::IQ2_S, ref::IQ3_XXS, ref::IQ3_S, ref::IQ4_NL, ref::IQ4_XS, ref::BF16, ref::F16}) {+ const size_t rb = ref::row_bytes(t, cols);+ std::vector<uint8_t> raw(rb * rows);+ ref::random_blocks(t, raw.data(), rows, cols, 77 + t);+ std::vector<float> f((size_t)rows * cols);+ ref::dequant(t, raw.data(), f.data(), f.size());+ const std::string n = dir + "/" + ref::type_name(t);+ FILE* a = std::fopen((n + ".bin").c_str(), "wb");+ FILE* b = std::fopen((n + ".f32").c_str(), "wb");+ std::fwrite(raw.data(), 1, raw.size(), a);+ std::fwrite(f.data(), 4, f.size(), b);+ std::fclose(a);+ std::fclose(b);+ }+ std::printf("wrote %s\n", dir.c_str());+ return 0;+}diff --git a/metal/tests/rt_bench.cpp b/metal/tests/rt_bench.cppnew file mode 100644index 000000000..ec95c9df6--- /dev/null+++ b/metal/tests/rt_bench.cpp@@ -0,0 +1,203 @@+// metal/tests/rt_bench.cpp - the M-series GPU's achievable read bandwidth and the cost of a dispatch.+//+// rt_bench bw [MiB] streaming read kernels over a buffer (default 2048 MiB, far beyond the SLC), per+// threadgroup size and grid size; read+write (copy); small sizes (cache-resident)+// rt_bench dispatch empty / dependent / small kernels: N dispatches in one serial or concurrent encoder,+// with or without barriers, through an indirect command buffer, and one command buffer+// per dispatch (commit + wait round trip)+#include "mtl_rt.h"++#include <algorithm>+#include <cstdio>+#include <cstdlib>+#include <cstring>+#include <string>+#include <vector>++static double median(std::vector<double> v) {+ std::sort(v.begin(), v.end());+ return v[v.size() / 2];+}++template <class F> static void timed(int warm, int reps, F f, double& med, double& best) {+ for (int i = 0; i < warm; ++i) f();+ std::vector<double> t;+ for (int i = 0; i < reps; ++i) t.push_back(f());+ med = median(t);+ best = *std::min_element(t.begin(), t.end());+}++static void bw(mtl::Context& cx, int lib, size_t mib) {+ const size_t bytes = mib << 20;+ mtl::Buffer src = cx.alloc(bytes);+ for (size_t i = 0; i < bytes / 4; ++i) src.as<uint32_t>()[i] = (uint32_t)(i * 2654435761u);+ mtl::Buffer out = cx.alloc(64u << 20);+ const uint32_t n = (uint32_t)(bytes / 16);+ mtl::Pipeline pr = cx.pipeline(lib, "k_read"), pu = cx.pipeline(lib, "k_read_u4"),+ pc = cx.pipeline(lib, "k_read_chunk");+ std::printf("buffer %zu MiB; k_read max threads %d, simd width %d\n", mib, pr.max_threads, pr.simd_width);+ std::printf("%-12s %6s %8s %10s %10s\n", "kernel", "tg", "groups", "GB/s med", "GB/s best");+ double best_all = 0;+ std::string best_cfg;+ for (const mtl::Pipeline* p : {&pr, &pu}) {+ for (uint32_t tg : {64u, 128u, 256u, 512u, 1024u}) {+ if ((int)tg > p->max_threads) continue;+ for (uint32_t groups : {80u, 160u, 320u, 640u, 1280u, 2560u, 5120u}) {+ if ((size_t)groups * tg * 4 > out.bytes) continue;+ mtl::Dispatch d;+ d.p = p;+ d.args = {mtl::Arg::B(src), mtl::Arg::B(out), mtl::Arg::V(n)};+ d.grid[0] = groups;+ d.tg[0] = tg;+ double med, best;+ timed(2, 7, [&] { return cx.run({d}); }, med, best);+ const double gm = bytes / med / 1e9, gb = bytes / best / 1e9;+ std::printf("%-12s %6u %8u %10.1f %10.1f\n", p == &pr ? "read" : "read_u4", tg, groups, gm, gb);+ if (gm > best_all) {+ best_all = gm;+ best_cfg = std::string(p == &pr ? "read" : "read_u4") + " tg " + std::to_string(tg) + " groups " ++ std::to_string(groups);+ }+ }+ }+ }+ // contiguous chunk per threadgroup+ for (uint32_t tg : {256u, 512u, 1024u}) {+ for (uint32_t chunk_kib : {16u, 64u, 256u, 1024u}) {+ const uint32_t chunk = chunk_kib * 1024 / 16;+ const uint32_t groups = (n + chunk - 1) / chunk;+ if ((size_t)groups * tg * 4 > out.bytes) continue;+ mtl::Dispatch d;+ d.p = &pc;+ d.args = {mtl::Arg::B(src), mtl::Arg::B(out), mtl::Arg::V(n), mtl::Arg::V(chunk)};+ d.grid[0] = groups;+ d.tg[0] = tg;+ double med, best;+ timed(2, 7, [&] { return cx.run({d}); }, med, best);+ const double gm = bytes / med / 1e9;+ std::printf("chunk %4uK %6u %8u %10.1f %10.1f\n", chunk_kib, tg, groups, gm, bytes / best / 1e9);+ if (gm > best_all) {+ best_all = gm;+ best_cfg = "chunk " + std::to_string(chunk_kib) + "K tg " + std::to_string(tg);+ }+ }+ }+ std::printf("BEST read: %.1f GB/s (%s)\n", best_all, best_cfg.c_str());++ // read + write+ {+ mtl::Buffer dst = cx.alloc(bytes / 2);+ mtl::Pipeline pk = cx.pipeline(lib, "k_copy");+ const uint32_t nn = (uint32_t)(bytes / 2 / 16);+ double bestc = 0;+ for (uint32_t tg : {256u, 1024u})+ for (uint32_t groups : {640u, 2560u}) {+ mtl::Dispatch d;+ d.p = &pk;+ d.args = {mtl::Arg::B(src), mtl::Arg::B(dst), mtl::Arg::V(nn)};+ d.grid[0] = groups;+ d.tg[0] = tg;+ double med, best;+ timed(2, 7, [&] { return cx.run({d}); }, med, best);+ bestc = std::max(bestc, (double)bytes / med / 1e9);+ }+ std::printf("BEST copy (read+write, both counted): %.1f GB/s\n", bestc);+ cx.free(dst);+ }+ // cache-resident sizes: the same kernel on a small prefix+ for (size_t kib : {1024ul, 4096ul, 16384ul, 32768ul, 65536ul, 131072ul, 262144ul}) {+ if (kib * 1024 > bytes) break;+ const uint32_t nn = (uint32_t)(kib * 1024 / 16);+ double bestg = 0;+ for (uint32_t groups : {160u, 640u, 2560u}) {+ mtl::Dispatch d;+ d.p = &pu;+ d.args = {mtl::Arg::B(src), mtl::Arg::B(out), mtl::Arg::V(nn)};+ d.grid[0] = groups;+ d.tg[0] = 256;+ // many repetitions in one command buffer, so the launch is amortised+ const int reps = (int)std::max<size_t>(1, (256ul << 10) / kib * 4);+ double med, best;+ timed(1, 5, [&] { return cx.run({d}, reps) / reps; }, med, best);+ bestg = std::max(bestg, kib * 1024.0 / med / 1e9);+ }+ std::printf("resident %7zu KiB: %.1f GB/s\n", kib, bestg);+ }+ cx.free(src);+ cx.free(out);+}++static void dispatch(mtl::Context& cx, int lib) {+ mtl::Buffer buf = cx.alloc(1 << 20), x = cx.alloc(4 * 2560), y = cx.alloc(4 * 2560);+ mtl::Pipeline pe = cx.pipeline(lib, "k_empty"), pch = cx.pipeline(lib, "k_chain"), ps = cx.pipeline(lib, "k_small");+ auto mk = [&](const mtl::Pipeline& p, int kind) {+ mtl::Dispatch d;+ d.p = &p;+ if (kind == 2) {+ d.args = {mtl::Arg::B(x), mtl::Arg::B(y)};+ d.grid[0] = 10;+ d.tg[0] = 256;+ } else {+ d.args = {mtl::Arg::B(buf)};+ d.grid[0] = 1;+ d.tg[0] = 32;+ }+ return d;+ };+ const int N = 2000;+ struct K { const char* name; const mtl::Pipeline* p; int kind; } ks[] = {+ {"empty", &pe, 0}, {"chain", &pch, 1}, {"small", &ps, 2}};+ std::printf("%-8s %-36s %10s\n", "kernel", "mode", "us/dispatch");+ for (const K& k : ks) {+ std::vector<mtl::Dispatch> ds(N, mk(*k.p, k.kind));+ double med, best;+ timed(2, 7, [&] { return cx.run(ds, 1, false, false); }, med, best);+ std::printf("%-8s %-36s %10.2f\n", k.name, "serial encoder", med / N * 1e6);+ timed(2, 7, [&] { return cx.run(ds, 1, true, false); }, med, best);+ std::printf("%-8s %-36s %10.2f\n", k.name, "concurrent encoder, no barrier", med / N * 1e6);+ timed(2, 7, [&] { return cx.run(ds, 1, true, true); }, med, best);+ std::printf("%-8s %-36s %10.2f\n", k.name, "concurrent encoder + barrier each", med / N * 1e6);+ timed(2, 7, [&] { return cx.run(ds, 1, false, true); }, med, best);+ std::printf("%-8s %-36s %10.2f\n", k.name, "serial encoder + barrier each", med / N * 1e6);+ timed(2, 7, [&] { return cx.run_icb(ds, 1, false); }, med, best);+ std::printf("%-8s %-36s %10.2f\n", k.name, "ICB, no barrier", med / N * 1e6);+ timed(2, 7, [&] { return cx.run_icb(ds, 1, true); }, med, best);+ std::printf("%-8s %-36s %10.2f\n", k.name, "ICB + barrier each", med / N * 1e6);+ }+ // command buffer round trips+ {+ std::vector<mtl::Dispatch> one(1, mk(pe, 0));+ double gpu = 0;+ const int R = 300;+ cx.run_wall(one, 20);+ const double wall = cx.run_wall(one, R, &gpu);+ std::printf("%-8s %-36s %10.2f (GPU %.2f us)\n", "empty", "1 cmdbuf/dispatch, commit+wait wall", wall / R * 1e6,+ gpu / R * 1e6);+ std::vector<mtl::Dispatch> d100(100, mk(pe, 0));+ const double wall2 = cx.run_wall(d100, 100, &gpu);+ std::printf("%-8s %-36s %10.2f (GPU %.2f us)\n", "empty", "100 dispatches/cmdbuf, wall per cb", wall2 / 100 * 1e6,+ gpu / 100 * 1e6);+ }+ // the fixed cost of one command buffer as seen by the GPU timer (1 dispatch)+ {+ std::vector<mtl::Dispatch> one(1, mk(pe, 0));+ double med, best;+ timed(5, 21, [&] { return cx.run(one); }, med, best);+ std::printf("%-8s %-36s %10.2f\n", "empty", "single dispatch cmdbuf GPU time", med * 1e6);+ }+ cx.free(buf);+ cx.free(x);+ cx.free(y);+}++int main(int argc, char** argv) {+ mtl::Context cx;+ std::printf("device: %s apple9 %d apple10 %d metal4 %d working set %.1f GiB\n", cx.device_name().c_str(),+ cx.has_family_apple(9), cx.has_family_apple(10), cx.supports_metal4(),+ cx.recommended_working_set() / 1073741824.0);+ const int lib = cx.compile({"rt_bench.metal"}, "#define NO_GGML_COMMON 1\n");+ const std::string mode = argc > 1 ? argv[1] : "all";+ if (mode == "bw" || mode == "all") bw(cx, lib, argc > 2 ? std::strtoul(argv[2], nullptr, 10) : 2048);+ if (mode == "dispatch" || mode == "all") dispatch(cx, lib);+ return 0;+}diff --git a/metal/tools/check_ref.py b/metal/tools/check_ref.pynew file mode 100644index 000000000..71da92903--- /dev/null+++ b/metal/tools/check_ref.py@@ -0,0 +1,34 @@+"""metal/tools/check_ref.py - checks metal/src/ref_quant.cpp's dequantizers against gguf-py's (and Q2_0 against+tools/gguf_writer.py's codec) on the files tests/ref_dump wrote:++ python metal/tools/check_ref.py <dir>++Prints the max |difference| per type; the reference passes when every one is 0 (bitwise: both decode to float32).+"""+import pathlib+import sys++import numpy as np++ROOT = pathlib.Path(__file__).resolve().parents[2]+sys.path.insert(0, str(ROOT / "tools"))+from gguf.quants import dequantize # noqa: E402+from gguf.constants import GGMLQuantizationType as Q # noqa: E402++ROWS, COLS = 16, 2560+d = pathlib.Path(sys.argv[1] if len(sys.argv) > 1 else ".")+bad = 0+for name in ("Q2_0", "Q4_0", "Q5_0", "Q8_0", "Q3_K", "Q4_K", "Q5_K", "Q6_K", "IQ2_XXS", "IQ2_XS", "IQ2_S", "IQ3_XXS",+ "IQ3_S", "IQ4_NL", "IQ4_XS", "BF16", "F16"):+ raw = np.fromfile(d / f"{name}.bin", dtype=np.uint8)+ ref = np.fromfile(d / f"{name}.f32", dtype=np.float32).reshape(ROWS, COLS)+ if name == "Q2_0":+ from gguf_writer import dequantize_q2_0 # noqa: E402+ got = np.asarray(dequantize_q2_0(raw.tobytes()), dtype=np.float32).reshape(ROWS, COLS)+ else:+ got = dequantize(raw.reshape(ROWS, -1), Q[name]).astype(np.float32).reshape(ROWS, COLS)+ diff = float(np.max(np.abs(got - ref)))+ scale = float(np.max(np.abs(got)))+ print(f"{name:8s} max |ref_quant - gguf-py| = {diff:.3e} (max |w| {scale:.3e}) {'ok' if diff == 0 else 'DIFF'}")+ bad += diff != 0+sys.exit(1 if bad else 0)