Skip to content

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: dense GEMV for every pack format, prepared activations, window-size specialisation

Niko12217b022f1fb874
diff --git a/metal/kernels/alu_bench.metal b/metal/kernels/alu_bench.metal
new file mode 100644
index 000000000..e34890a05
--- /dev/null
+++ b/metal/kernels/alu_bench.metal
@@ -0,0 +1,181 @@
+// metal/kernels/alu_bench.metal - instruction-rate probes (alu_bench.cpp): each thread runs ITER iterations of 8
+// independent chains of one operation; the result is written so nothing is eliminated.
+#define ITER 1024
+
+kernel void a_fma32(device float* out [[buffer(0)]], constant float& k [[buffer(1)]], uint gid [[thread_position_in_grid]]) {
+ float a0 = gid, a1 = gid + 1, a2 = gid + 2, a3 = gid + 3, a4 = gid + 4, a5 = gid + 5, a6 = gid + 6, a7 = gid + 7;
+ for (int i = 0; i < ITER; ++i) {
+ a0 = fma(a0, k, 0.5f); a1 = fma(a1, k, 0.5f); a2 = fma(a2, k, 0.5f); a3 = fma(a3, k, 0.5f);
+ a4 = fma(a4, k, 0.5f); a5 = fma(a5, k, 0.5f); a6 = fma(a6, k, 0.5f); a7 = fma(a7, k, 0.5f);
+ }
+ out[gid] = a0 + a1 + a2 + a3 + a4 + a5 + a6 + a7;
+}
+
+kernel void a_fma16(device float* out [[buffer(0)]], constant float& kf [[buffer(1)]], uint gid [[thread_position_in_grid]]) {
+ const half k = half(kf);
+ half a0 = gid & 7, a1 = 1, a2 = 2, a3 = 3, a4 = 4, a5 = 5, a6 = 6, a7 = 7;
+ for (int i = 0; i < ITER; ++i) {
+ a0 = fma(a0, k, half(0.5)); a1 = fma(a1, k, half(0.5)); a2 = fma(a2, k, half(0.5)); a3 = fma(a3, k, half(0.5));
+ a4 = fma(a4, k, half(0.5)); a5 = fma(a5, k, half(0.5)); a6 = fma(a6, k, half(0.5)); a7 = fma(a7, k, half(0.5));
+ }
+ out[gid] = float(a0 + a1 + a2 + a3 + a4 + a5 + a6 + a7);
+}
+
+// float accumulator, half operands (does the conversion come free?)
+kernel void a_fmamix(device float* out [[buffer(0)]], constant float& kf [[buffer(1)]], uint gid [[thread_position_in_grid]]) {
+ half h0 = half(gid & 7), h1 = h0 + half(1);
+ float a0 = gid, a1 = 1, a2 = 2, a3 = 3, a4 = 4, a5 = 5, a6 = 6, a7 = 7;
+ for (int i = 0; i < ITER; ++i) {
+ a0 = fma(float(h0), kf, a0); a1 = fma(float(h1), kf, a1); a2 = fma(float(h0), kf, a2); a3 = fma(float(h1), kf, a3);
+ a4 = fma(float(h0), kf, a4); a5 = fma(float(h1), kf, a5); a6 = fma(float(h0), kf, a6); a7 = fma(float(h1), kf, a7);
+ h0 = h0 * half(0.999); h1 = h1 * half(0.999);
+ }
+ out[gid] = a0 + a1 + a2 + a3 + a4 + a5 + a6 + a7;
+}
+
+kernel void a_iand(device float* out [[buffer(0)]], constant uint& k [[buffer(1)]], uint gid [[thread_position_in_grid]]) {
+ uint a0 = gid, a1 = gid + 1, a2 = gid + 2, a3 = gid + 3, a4 = gid + 4, a5 = gid + 5, a6 = gid + 6, a7 = gid + 7;
+ for (int i = 0; i < ITER; ++i) {
+ a0 = (a0 ^ k) + 1; a1 = (a1 ^ k) + 1; a2 = (a2 ^ k) + 1; a3 = (a3 ^ k) + 1;
+ a4 = (a4 ^ k) + 1; a5 = (a5 ^ k) + 1; a6 = (a6 ^ k) + 1; a7 = (a7 ^ k) + 1;
+ }
+ out[gid] = float(a0 + a1 + a2 + a3 + a4 + a5 + a6 + a7);
+}
+
+kernel void a_shift(device float* out [[buffer(0)]], constant uint& k [[buffer(1)]], uint gid [[thread_position_in_grid]]) {
+ uint a0 = gid, a1 = gid + 1, a2 = gid + 2, a3 = gid + 3, a4 = gid + 4, a5 = gid + 5, a6 = gid + 6, a7 = gid + 7;
+ for (int i = 0; i < ITER; ++i) {
+ a0 = (a0 >> k) | k; a1 = (a1 >> k) | k; a2 = (a2 >> k) | k; a3 = (a3 >> k) | k;
+ a4 = (a4 >> k) | k; a5 = (a5 >> k) | k; a6 = (a6 >> k) | k; a7 = (a7 >> k) | k;
+ }
+ out[gid] = float(a0 + a1 + a2 + a3 + a4 + a5 + a6 + a7);
+}
+
+// int -> float conversion + fma
+kernel void a_cvt(device float* out [[buffer(0)]], constant uint& k [[buffer(1)]], uint gid [[thread_position_in_grid]]) {
+ uint u = gid;
+ float a0 = 0, a1 = 0, a2 = 0, a3 = 0, a4 = 0, a5 = 0, a6 = 0, a7 = 0;
+ for (int i = 0; i < ITER; ++i) {
+ u += k;
+ a0 += float(u & 3); a1 += float(u & 12); a2 += float(u & 48); a3 += float(u & 192);
+ a4 += float(u & 768); a5 += float(u & 3072); a6 += float(u & 12288); a7 += float(u & 49152);
+ }
+ out[gid] = a0 + a1 + a2 + a3 + a4 + a5 + a6 + a7;
+}
+
+// threadgroup memory loads: random-ish 8-byte reads from a 4 KB table
+kernel void a_tgload(device float* out [[buffer(0)]], constant uint& k [[buffer(1)]], uint gid [[thread_position_in_grid]],
+ ushort tid [[thread_index_in_threadgroup]]) {
+ threadgroup uint2 tab[512];
+ for (int i = tid; i < 512; i += 256) tab[i] = uint2(i, i * 3);
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ uint u = gid * 2654435761u;
+ uint2 s0 = 0, s1 = 0, s2 = 0, s3 = 0;
+ for (int i = 0; i < ITER; ++i) {
+ s0 += tab[(u >> 3) & 511]; s1 += tab[(u >> 7) & 511]; s2 += tab[(u >> 11) & 511]; s3 += tab[(u >> 15) & 511];
+ u += k;
+ }
+ out[gid] = float(s0.x + s1.x + s2.x + s3.x + s0.y + s1.y + s2.y + s3.y);
+}
+
+// select (sign application)
+kernel void a_sel(device float* out [[buffer(0)]], constant uint& k [[buffer(1)]], uint gid [[thread_position_in_grid]]) {
+ uint u = gid;
+ float a0 = 1, a1 = 2, a2 = 3, a3 = 4, a4 = 5, a5 = 6, a6 = 7, a7 = 8;
+ for (int i = 0; i < ITER; ++i) {
+ u ^= k;
+ a0 = (u & 1) ? -a0 : a0; a1 = (u & 2) ? -a1 : a1; a2 = (u & 4) ? -a2 : a2; a3 = (u & 8) ? -a3 : a3;
+ a4 = (u & 16) ? -a4 : a4; a5 = (u & 32) ? -a5 : a5; a6 = (u & 64) ? -a6 : a6; a7 = (u & 128) ? -a7 : a7;
+ }
+ out[gid] = a0 + a1 + a2 + a3 + a4 + a5 + a6 + a7;
+}
+
+// dot-shaped: acc_i += q_i * x_i with loop-carried accumulators only (q, x vary slowly)
+kernel void a_dot32(device float* out [[buffer(0)]], constant float& k [[buffer(1)]], uint gid [[thread_position_in_grid]]) {
+ float q[8], x[8], a[8];
+ for (int j = 0; j < 8; ++j) { q[j] = float(gid + j); x[j] = k * j; a[j] = 0; }
+ for (int i = 0; i < ITER; ++i) {
+ for (int j = 0; j < 8; ++j) a[j] = fma(q[j], x[j], a[j]);
+ q[0] += 1.0f;
+ }
+ float s = 0;
+ for (int j = 0; j < 8; ++j) s += a[j];
+ out[gid] = s;
+}
+kernel void a_dot16(device float* out [[buffer(0)]], constant float& k [[buffer(1)]], uint gid [[thread_position_in_grid]]) {
+ half q[8], x[8], a[8];
+ for (int j = 0; j < 8; ++j) { q[j] = half(gid + j); x[j] = half(k * j); a[j] = 0; }
+ for (int i = 0; i < ITER; ++i) {
+ for (int j = 0; j < 8; ++j) a[j] = fma(q[j], x[j], a[j]);
+ q[0] += half(1.0f);
+ }
+ float s = 0;
+ for (int j = 0; j < 8; ++j) s += float(a[j]);
+ out[gid] = s;
+}
+kernel void a_dotmix(device float* out [[buffer(0)]], constant float& k [[buffer(1)]], uint gid [[thread_position_in_grid]]) {
+ half q[8];
+ float x[8], a[8];
+ for (int j = 0; j < 8; ++j) { q[j] = half(gid + j); x[j] = k * j; a[j] = 0; }
+ for (int i = 0; i < ITER; ++i) {
+ for (int j = 0; j < 8; ++j) a[j] = fma(float(q[j]), x[j], a[j]);
+ q[0] += half(1.0f);
+ }
+ float s = 0;
+ for (int j = 0; j < 8; ++j) s += a[j];
+ out[gid] = s;
+}
+kernel void a_fma32x16(device float* out [[buffer(0)]], constant float& k [[buffer(1)]], uint gid [[thread_position_in_grid]]) {
+ float a[16];
+ for (int j = 0; j < 16; ++j) a[j] = gid + j;
+ for (int i = 0; i < ITER / 2; ++i)
+ for (int j = 0; j < 16; ++j) a[j] = fma(a[j], k, 0.5f);
+ float s = 0;
+ for (int j = 0; j < 16; ++j) s += a[j];
+ out[gid] = s;
+}
+
+// 8-byte gathers from a 4 KB table in device memory (L1-resident) and in the constant address space
+kernel void a_devload(device float* out [[buffer(0)]], constant uint& k [[buffer(1)]], device const uint2* tab [[buffer(2)]],
+ uint gid [[thread_position_in_grid]]) {
+ uint u = gid * 2654435761u;
+ uint2 s0 = 0, s1 = 0, s2 = 0, s3 = 0;
+ for (int i = 0; i < ITER; ++i) {
+ s0 += tab[(u >> 3) & 511]; s1 += tab[(u >> 7) & 511]; s2 += tab[(u >> 11) & 511]; s3 += tab[(u >> 15) & 511];
+ u += k;
+ }
+ out[gid] = float(s0.x + s1.x + s2.x + s3.x + s0.y + s1.y + s2.y + s3.y);
+}
+kernel void a_cstload(device float* out [[buffer(0)]], constant uint& k [[buffer(1)]], constant uint2* tab [[buffer(2)]],
+ uint gid [[thread_position_in_grid]]) {
+ uint u = gid * 2654435761u;
+ uint2 s0 = 0, s1 = 0, s2 = 0, s3 = 0;
+ for (int i = 0; i < ITER; ++i) {
+ s0 += tab[(u >> 3) & 511]; s1 += tab[(u >> 7) & 511]; s2 += tab[(u >> 11) & 511]; s3 += tab[(u >> 15) & 511];
+ u += k;
+ }
+ out[gid] = float(s0.x + s1.x + s2.x + s3.x + s0.y + s1.y + s2.y + s3.y);
+}
+// 4-byte gathers from a 1 KB threadgroup table (IQ3_XXS's grid)
+kernel void a_tgload4(device float* out [[buffer(0)]], constant uint& k [[buffer(1)]], uint gid [[thread_position_in_grid]],
+ ushort tid [[thread_index_in_threadgroup]]) {
+ threadgroup uint tab[256];
+ for (int i = tid; i < 256; i += 256) tab[i] = i * 3;
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ uint u = gid * 2654435761u;
+ uint s0 = 0, s1 = 0, s2 = 0, s3 = 0;
+ for (int i = 0; i < ITER; ++i) {
+ s0 += tab[(u >> 3) & 255]; s1 += tab[(u >> 7) & 255]; s2 += tab[(u >> 11) & 255]; s3 += tab[(u >> 15) & 255];
+ u += k;
+ }
+ out[gid] = float(s0 + s1 + s2 + s3);
+}
+// popcount parity (computed ksigns)
+kernel void a_popc(device float* out [[buffer(0)]], constant uint& k [[buffer(1)]], uint gid [[thread_position_in_grid]]) {
+ uint u = gid, s0 = 0, s1 = 0, s2 = 0, s3 = 0;
+ for (int i = 0; i < ITER; ++i) {
+ s0 += popcount(u & 127); s1 += popcount((u >> 7) & 127); s2 += popcount((u >> 14) & 127); s3 += popcount((u >> 21) & 127);
+ u += k;
+ }
+ out[gid] = float(s0 + s1 + s2 + s3);
+}
diff --git a/metal/kernels/gemv.metal b/metal/kernels/gemv.metal
new file mode 100644
index 000000000..9d3294417
--- /dev/null
+++ b/metal/kernels/gemv.metal
@@ -0,0 +1,82 @@
+// metal/kernels/gemv.metal - y[t][r] = W[r] . x[t] for a window of 1..8 tokens (dense projections, the shared
+// expert, the LM head), any format of quant.metal/units.metal.
+//
+// Shape of a threadgroup: SG simdgroups; KS of them split the row's units (KS = 1: no split), the other SG/KS cover
+// different rows. In a simdgroup, LPR lanes share a row and 32/LPR rows run side by side; each lane holds NR rows.
+// The weights of a unit are decoded once and applied to every token. Partial sums of a K split are added in a
+// fixed order (deterministic).
+
+struct GemvArgs {
+ uint n_in;
+ uint n_out;
+ uint n_tok;
+ uint row_bytes;
+ uint x_stride; // floats between tokens' x rows
+ uint y_stride; // floats between tokens' y rows
+};
+
+constant int NTOK [[function_constant(0)]]; // tokens of the window (1..8): the token loops are specialised
+
+template <int F, int LPR, int NR, int SG, int KS>
+kernel void gemv(device const uchar* W [[buffer(0)]], device const float* xp [[buffer(1)]],
+ device const float* s16 [[buffer(2)]], device float* y [[buffer(3)]], constant GemvArgs& 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]]) {
+ constexpr int UNIT = fmt<F>::UNIT, RS = SG / KS, RG = 32 / LPR;
+ threadgroup uint tab[fmt<F>::TAB];
+ threadgroup float red[KS > 1 ? KS * RS * RG * NR * 8 : 1];
+ load_tab<F>(tab, tid, SG * 32);
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ const int ks = sg / RS, rs = sg % RS;
+ const int li = lane % LPR;
+ const int lrow0 = (rs * RG + lane / LPR) * NR;
+ const int row0 = int(tg.x) * RS * RG * NR + lrow0;
+ const int U = int(a.n_in) / UNIT;
+ const int u0 = ks * U / KS, u1 = (ks + 1) * U / KS;
+ float acc[NR][8];
+ for (int r = 0; r < NR; ++r)
+ for (int t = 0; t < NTOK; ++t) acc[r][t] = 0.0f;
+ device const uchar* rp[NR];
+ for (int r = 0; r < NR; ++r) rp[r] = W + (ulong)min(row0 + r, int(a.n_out) - 1) * a.row_bytes;
+ const int s16n = int(a.n_in) / 16;
+ for (int u = u0 + li; u < u1; u += LPR) {
+ float q[NR][UNIT];
+ float4 sc[NR];
+ for (int r = 0; r < NR; ++r) Dec<F>::run(rp[r], u, q[r], sc[r], tab);
+ for (int t = 0; t < NTOK; ++t) {
+ float xs[UNIT], xsum[2];
+ X<F>::load(xp + t * int(a.x_stride), s16 + t * s16n, u, xs, xsum);
+ for (int r = 0; r < NR; ++r) acc[r][t] += unit_combine<UNIT>(q[r], sc[r], xs, xsum);
+ }
+ }
+ constexpr int RPT = RS * RG * NR;
+ for (int r = 0; r < NR; ++r)
+ for (int t = 0; t < NTOK; ++t) {
+ const float v = lane_sum<LPR>(acc[r][t]);
+ if (KS == 1) {
+ if (li == 0 && row0 + r < int(a.n_out)) y[t * int(a.y_stride) + row0 + r] = v;
+ } else if (li == 0) {
+ red[(ks * RPT + lrow0 + r) * 8 + t] = v;
+ }
+ }
+ if (KS > 1) {
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ if (ks == 0 && li == 0)
+ for (int r = 0; r < NR; ++r)
+ for (int t = 0; t < NTOK; ++t) {
+ float v = 0.0f;
+ for (int k = 0; k < KS; ++k) v += red[(k * RPT + lrow0 + r) * 8 + t];
+ if (row0 + r < int(a.n_out)) y[t * int(a.y_stride) + row0 + r] = v;
+ }
+ }
+}
+
+#define GV(F, L, R, S, K) template [[host_name("gemv_" #F "_" #L "_" #R "_" #S "_" #K)]] kernel decltype(gemv<F, L, R, S, K>) gemv<F, L, R, S, K>;
+#define GV_SET(F) GV(F, 32, 1, 4, 1) GV(F, 32, 2, 4, 1) GV(F, 16, 1, 4, 1) GV(F, 16, 2, 4, 1) GV(F, 8, 1, 4, 1) \
+ GV(F, 8, 2, 4, 1) GV(F, 4, 2, 4, 1) GV(F, 4, 1, 4, 1) GV(F, 32, 1, 4, 4) GV(F, 32, 2, 4, 2) \
+ GV(F, 32, 1, 8, 8) GV(F, 16, 1, 8, 4) GV(F, 32, 1, 8, 2) GV(F, 8, 1, 8, 1) GV(F, 1, 1, 4, 1) GV(F, 1, 2, 4, 1) GV(F, 2, 1, 4, 1) GV(F, 2, 2, 4, 1) GV(F, 1, 1, 2, 1) GV(F, 4, 4, 4, 1)
+#ifndef GEMV_TYPES
+#define GEMV_TYPES GV_SET(T_BF16) GV_SET(T_Q8_0) GV_SET(T_Q4_0) GV_SET(T_Q5_0) GV_SET(T_IQ4_NL) GV_SET(T_IQ4_XS) \
+ GV_SET(T_Q2_0) GV_SET(T_IQ3_S) GV_SET(T_Q3_K) GV_SET(T_Q4_K) GV_SET(T_Q5_K) GV_SET(T_Q6_K)
+#endif
+GEMV_TYPES
diff --git a/metal/kernels/moe.metal b/metal/kernels/moe.metal
index 9609a95aa..c5bbd4ff4 100644
--- a/metal/kernels/moe.metal
+++ b/metal/kernels/moe.metal
@@ -85,97 +85,104 @@ kernel void moe_plan(device const int* ids [[buffer(0)]], device const float* w
}
// ---- 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;
- }
-}
-
+// One pass over a group's rows for all its entries (at most 8: an expert appears once per token).
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)]],
+ constant MoeArgs& a [[buffer(4)]], device const float* xs16 [[buffer(5)]],
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, RG = 32 / LPR;
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];
+ const int c = plan[P_GSTART + g], ne = plan[P_GSTART + g + 1] - c;
+ device const float* xt[8];
+ device const float* st[8];
+ for (int t = 0; t < 8; ++t) {
+ const int tok = plan[P_ETOK + c + min(t, ne - 1)];
+ xt[t] = x + tok * int(a.n_embd);
+ st[t] = xs16 + tok * int(a.n_embd / 16);
+ }
+ float ag[NR][8], au[NR][8];
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 t = 0; t < 8; ++t) ag[r][t] = au[r][t] = 0.0f;
+ 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>(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);
+ float qg[NR][UNIT], qu[NR][UNIT];
+ float4 cg[NR], cu[NR];
+ for (int r = 0; r < NR; ++r) {
+ Dec<F>::run(g0 + r * a.gu_row, u, qg[r], cg[r], tab);
+ Dec<F>::run(u0 + r * a.gu_row, u, qu[r], cu[r], tab);
+ }
+ for (int t = 0; t < 8; ++t) {
+ if (t < ne) {
+ float xs[UNIT], xsum[2];
+ X<F>::load(xt[t], st[t], u, xs, xsum);
+ for (int r = 0; r < NR; ++r) {
+ ag[r][t] += unit_combine<UNIT>(qg[r], cg[r], xs, xsum);
+ au[r][t] += unit_combine<UNIT>(qu[r], cu[r], xs, xsum);
+ }
+ }
+ }
}
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;
+ for (int t = 0; t < 8; ++t) {
+ if (t < ne) {
+ const float gv = lane_sum<LPR>(ag[r][t]), uv = lane_sum<LPR>(au[r][t]);
+ if (li == 0) h[(c + t) * int(a.n_ff) + row0 + r] = gv / (1.0f + exp(-gv)) * uv;
+ }
}
}
+// ---- down ---------------------------------------------------------------------------------------------------------
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)]],
+ constant MoeArgs& a [[buffer(4)]], device const float* hs16 [[buffer(5)]],
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, RG = 32 / LPR;
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);
+ const int c = plan[P_GSTART + g], ne = plan[P_GSTART + g + 1] - c;
+ float ac[NR][8];
+ for (int r = 0; r < NR; ++r)
+ for (int t = 0; t < 8; ++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 q[NR][UNIT];
+ float4 sc[NR];
+ for (int r = 0; r < NR; ++r) Dec<F>::run(d0 + r * a.d_row, u, q[r], sc[r], tab);
+ for (int t = 0; t < 8; ++t) {
+ if (t < ne) {
+ float xs[UNIT], xsum[2];
+ X<F>::load(h + (c + t) * int(a.n_ff), hs16 + (c + t) * int(a.n_ff / 16), u, xs, xsum);
+ for (int r = 0; r < NR; ++r) ac[r][t] += unit_combine<UNIT>(q[r], sc[r], xs, xsum);
+ }
+ }
+ }
+ for (int r = 0; r < NR; ++r)
+ for (int t = 0; t < 8; ++t) {
+ if (t < ne) {
+ 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;
+ }
+ }
}
kernel void moe_combine(device const float* ye [[buffer(0)]], device float* y [[buffer(1)]],
diff --git a/metal/kernels/quant.metal b/metal/kernels/quant.metal
index 867cf36b0..3c7bc8cb9 100644
--- a/metal/kernels/quant.metal
+++ b/metal/kernels/quant.metal
@@ -11,6 +11,8 @@
// ushorts.
#define T_Q4_0 2
+#define T_Q3_K 11
+#define T_BF16 30
#define T_Q5_0 6
#define T_Q8_0 8
#define T_Q4_K 12
@@ -33,8 +35,13 @@ template <> struct fmt<T_IQ2_XXS> { enum { QK = 256, BB = 66, UNIT = 16, TAB =
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_IQ4_NL> { enum { QK = 32, BB = 18, UNIT = 32, TAB = 256 }; };
+template <> struct fmt<T_IQ4_XS> { enum { QK = 256, BB = 136, UNIT = 32, TAB = 256 }; };
+template <> struct fmt<T_Q3_K> { enum { QK = 256, BB = 110, UNIT = 32, TAB = 1 }; };
+template <> struct fmt<T_Q4_K> { enum { QK = 256, BB = 144, UNIT = 32, TAB = 1 }; };
+template <> struct fmt<T_Q5_K> { enum { QK = 256, BB = 176, UNIT = 32, TAB = 1 }; };
+template <> struct fmt<T_Q6_K> { enum { QK = 256, BB = 210, UNIT = 32, TAB = 1 }; };
+template <> struct fmt<T_BF16> { enum { QK = 16, BB = 32, UNIT = 16, TAB = 1 }; };
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 }; };
@@ -53,6 +60,11 @@ 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) {}
+template <> inline void load_tab<T_Q3_K>(threadgroup uint*, ushort, ushort) {}
+template <> inline void load_tab<T_Q4_K>(threadgroup uint*, ushort, ushort) {}
+template <> inline void load_tab<T_Q5_K>(threadgroup uint*, ushort, ushort) {}
+template <> inline void load_tab<T_Q6_K>(threadgroup uint*, ushort, ushort) {}
+template <> inline void load_tab<T_BF16>(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);
@@ -78,9 +90,10 @@ template <> inline void load_tab<T_IQ2_S>(threadgroup uint* tab, ushort tid, ush
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);
}
+// IQ4: a byte -> (codebook[low nibble], codebook[high nibble]) as half2, so one lookup gives two weights
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]);
+ for (int i = tid; i < 256; i += nth)
+ tab[i] = as_type<uint>(half2(half(kvalues_iq4nl[i & 15]), half(kvalues_iq4nl[i >> 4])));
}
template <> inline void load_tab<T_IQ4_XS>(threadgroup uint* tab, ushort tid, ushort nth) {
load_tab<T_IQ4_NL>(tab, tid, nth);
@@ -186,30 +199,30 @@ template <> inline float deq<T_IQ3_S>(device const uchar* b, int ui, thread floa
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.
+// IQ4_NL: 32 = 1 unit; low nibbles are elements 0..15, high 16..31 (one half2 lookup per byte).
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];
+ const half2 w0 = as_type<half2>(tab[v & 255]), w1 = as_type<half2>(tab[v >> 8]);
+ q[2 * j] = float(w0.x);
+ q[2 * j + 16] = float(w0.y);
+ q[2 * j + 1] = float(w1.x);
+ q[2 * j + 17] = float(w1.y);
}
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 half2 w0 = as_type<half2>(tab[v & 255]), w1 = as_type<half2>(tab[v >> 8]);
+ q[2 * j] = float(w0.x);
+ q[2 * j + 16] = float(w0.y);
+ q[2 * j + 1] = float(w1.x);
+ q[2 * j + 17] = float(w1.y);
}
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);
@@ -252,33 +265,6 @@ template <> inline float deq<T_Q5_0>(device const uchar* b, int, thread float* q
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) {
diff --git a/metal/kernels/units.metal b/metal/kernels/units.metal
new file mode 100644
index 000000000..c78b01684
--- /dev/null
+++ b/metal/kernels/units.metal
@@ -0,0 +1,257 @@
+// metal/kernels/units.metal - the dot of one unit with the window's tokens (after quant.metal).
+//
+// X<F>::load(xrow, u, xs, xsum) prepares unit u's x slice of one token (xrow = the token's row start), once per unit
+// and shared by every weight row the lane reads: the UNIT x values in the order the decoder produces weights, and
+// up to two partial sums (for the formats with an offset or a min). Where the codes are read with the mask trick
+// (an AND keeps a field in place, so the code arrives multiplied by 2^k), the x values are pre-scaled by 2^-k here:
+// exact in float.
+
+static inline void load16(device const float* p, thread float* xs) {
+ device const float4* v = (device const float4*)p;
+ for (int j = 0; j < 4; ++j) {
+ const float4 a = v[j];
+ xs[4 * j] = a.x;
+ xs[4 * j + 1] = a.y;
+ xs[4 * j + 2] = a.z;
+ xs[4 * j + 3] = a.w;
+ }
+}
+
+// ---- prepared x (xprep): XP holds, per token row of n floats, the kinds
+// XK_RAW x (every format without the mask trick)
+// XK_Q2 x * 4^-(i % 8) (Q2_0: 2-bit fields in place in a 16-bit word)
+// XK_P4 x * 2^-(8 (i % 4)) (Q4_K, Q5_K: byte fields in place in a 32-bit word)
+// XK_P2 x * 2^-(8 (i % 2)) (Q6_K, Q3_K: byte fields in place in a 16-bit word)
+// and S16 = the sum of every 16 consecutive raw x (the formats with an offset or a min).
+#define XK_RAW 0
+#define XK_Q2 1
+#define XK_P4 2
+#define XK_P2 3
+template <int F> struct XKind { enum { K = XK_RAW }; };
+template <> struct XKind<T_Q2_0> { enum { K = XK_Q2 }; };
+template <> struct XKind<T_Q4_K> { enum { K = XK_P4 }; };
+template <> struct XKind<T_Q5_K> { enum { K = XK_P4 }; };
+template <> struct XKind<T_Q6_K> { enum { K = XK_P2 }; };
+template <> struct XKind<T_Q3_K> { enum { K = XK_P2 }; };
+
+// X<F>::load(xp, s16, u, xs, xsum): unit u's prepared x (xp = the token's row of the format's kind, s16 = its sums)
+template <int F> struct X {
+ static inline void load(device const float* xp, device const float*, int u, thread float* xs, thread float* xsum) {
+ constexpr int UNIT = fmt<F>::UNIT;
+ for (int k = 0; k < UNIT; k += 16) load16(xp + u * UNIT + k, xs + k);
+ xsum[0] = xsum[1] = 0.0f;
+ }
+};
+template <> struct X<T_Q2_0> {
+ static inline void load(device const float* xp, device const float* s16, int u, thread float* xs, thread float* xsum) {
+ load16(xp + 16 * u, xs);
+ xsum[0] = s16[u];
+ xsum[1] = 0.0f;
+ }
+};
+// Q4_K / Q5_K: unit (block b, chunk c, half m): run0 at 256b + 64c + 16m, run1 = run0 + 32
+template <> struct X<T_Q4_K> {
+ static inline void load(device const float* xp, device const float* s16, int u, thread float* xs, thread float* xsum) {
+ const int p0 = 256 * (u >> 3) + 64 * ((u >> 1) & 3) + 16 * (u & 1);
+ load16(xp + p0, xs);
+ load16(xp + p0 + 32, xs + 16);
+ xsum[0] = s16[p0 >> 4];
+ xsum[1] = s16[(p0 >> 4) + 2];
+ }
+};
+template <> struct X<T_Q5_K> {
+ static inline void load(device const float* xp, device const float* s16, int u, thread float* xs, thread float* xsum) {
+ X<T_Q4_K>::load(xp, s16, u, xs, xsum);
+ }
+};
+// Q6_K: unit (block b, half n, m, p): run0 at 256b + 128n + 32p + 16m, run1 = run0 + 64
+template <> struct X<T_Q6_K> {
+ static inline void load(device const float* xp, device const float* s16, int u, thread float* xs, thread float* xsum) {
+ const int p0 = 256 * (u >> 3) + 128 * ((u >> 2) & 1) + 32 * (u & 1) + 16 * ((u >> 1) & 1);
+ load16(xp + p0, xs);
+ load16(xp + p0 + 64, xs + 16);
+ xsum[0] = s16[p0 >> 4];
+ xsum[1] = s16[(p0 >> 4) + 4];
+ }
+};
+// Q3_K: 32 contiguous, sums per 16
+template <> struct X<T_Q3_K> {
+ static inline void load(device const float* xp, device const float* s16, int u, thread float* xs, thread float* xsum) {
+ load16(xp + 32 * u, xs);
+ load16(xp + 32 * u + 16, xs + 16);
+ xsum[0] = s16[2 * u];
+ xsum[1] = s16[2 * u + 1];
+ }
+};
+
+// xprep: one thread per 16 consecutive values of one token row; XP = [4 kinds][n_tok][n] then S16 [n_tok][n / 16]
+kernel void xprep(device const float* x [[buffer(0)]], device float* xp [[buffer(1)]], constant uint& n [[buffer(2)]],
+ constant uint& n_tok [[buffer(3)]], uint gid [[thread_position_in_grid]]) {
+ const uint per = n / 16;
+ if (gid >= per * n_tok) return;
+ const uint t = gid / per, i = gid % per;
+ device const float* src = x + t * n + 16 * i;
+ const uint plane = n_tok * n;
+ device float* raw = xp + t * n + 16 * i;
+ float v[16];
+ load16(src, v);
+ float s0 = 0, s1 = 0;
+ for (int j = 0; j < 16; j += 2) { s0 += v[j]; s1 += v[j + 1]; }
+ const float q2s[8] = {1.0f, 0.25f, 0.0625f, 0.015625f, 0.00390625f, 0.0009765625f, 0.000244140625f, 0.00006103515625f};
+ const float p4s[4] = {1.0f, 0.00390625f, 1.52587890625e-05f, 5.9604644775390625e-08f};
+ for (int j = 0; j < 16; ++j) {
+ raw[j] = v[j];
+ raw[plane + j] = v[j] * q2s[j & 7];
+ raw[2 * plane + j] = v[j] * p4s[j & 3];
+ raw[3 * plane + j] = (j & 1) ? v[j] * 0.00390625f : v[j];
+ }
+ xp[4 * plane + t * per + i] = s0 + s1;
+}
+
+// ---- decoders: Dec<F>::run(row, u, q, sc) decodes unit u of a row into q[UNIT] and sc = (d1, d2, m1, m2), so that
+// for any token: dot = d1 * sum_{j < UNIT/2} q[j] xs[j] + d2 * sum_{j >= UNIT/2} q[j] xs[j] - (m1 xsum0 + m2 xsum1)
+// with xs, xsum from X<F>::load. A unit's weights are decoded once per row and applied to every token.
+template <int F> struct Dec {
+ static inline void run(device const uchar* row, int u, thread float* q, thread float4& sc, threadgroup const uint* tab) {
+ constexpr int UNIT = fmt<F>::UNIT, UPB = fmt<F>::QK / UNIT;
+ const float s = deq<F>(row + (u / UPB) * fmt<F>::BB, u % UPB, q, tab);
+ sc = float4(s, s, 0.0f, 0.0f);
+ }
+};
+
+template <> struct Dec<T_Q2_0> {
+ static inline void run(device const uchar* row, int u, thread float* q, thread float4& sc, 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];
+ for (int j = 0; j < 8; ++j) {
+ q[j] = float(a & ushort(3u << (2 * j)));
+ q[8 + j] = float(c & ushort(3u << (2 * j)));
+ }
+ const float d = rdh(b);
+ sc = float4(d, d, d, 0.0f);
+ }
+};
+
+static inline void scale_min_k4(int j, device const uchar* q, thread float& d, thread float& m) {
+ if (j < 4) {
+ d = float(q[j] & 63);
+ m = float(q[j + 4] & 63);
+ } else {
+ d = float((q[j + 4] & 0xF) | ((q[j - 4] >> 6) << 4));
+ m = float((q[j + 4] >> 4) | ((q[j] >> 6) << 4));
+ }
+}
+static inline void bytes4(uint w, thread float* q) {
+ q[0] = float(w & 0xFFu);
+ q[1] = float(w & 0xFF00u);
+ q[2] = float(w & 0xFF0000u);
+ q[3] = float(w & 0xFF000000u);
+}
+static inline void bytes2(ushort w, thread float* q) {
+ q[0] = float(w & 0xFF);
+ q[1] = float(w & 0xFF00);
+}
+
+template <> struct Dec<T_Q4_K> {
+ static inline void run(device const uchar* row, int u, thread float* q, thread float4& sc, 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);
+ device const uint* qp = (device const uint*)(b + 16 + 32 * c + 16 * m);
+ for (int w = 0; w < 4; ++w) {
+ const uint v = qp[w];
+ bytes4(v & 0x0F0F0F0Fu, q + 4 * w);
+ bytes4((v >> 4) & 0x0F0F0F0Fu, q + 16 + 4 * w);
+ }
+ sc = float4(d * s1, d * s2, dm * m1, dm * m2);
+ }
+};
+
+template <> struct Dec<T_Q5_K> {
+ static inline void run(device const uchar* row, int u, thread float* q, thread float4& sc, 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);
+ device const uint* qp = (device const uint*)(b + 48 + 32 * c + 16 * m);
+ device const uint* hp = (device const uint*)(b + 16 + 16 * m);
+ for (int w = 0; w < 4; ++w) {
+ const uint v = qp[w], h = hp[w];
+ bytes4((v & 0x0F0F0F0Fu) | (((h >> (2 * c)) & 0x01010101u) << 4), q + 4 * w);
+ bytes4(((v >> 4) & 0x0F0F0F0Fu) | (((h >> (2 * c + 1)) & 0x01010101u) << 4), q + 16 + 4 * w);
+ }
+ sc = float4(d * s1, d * s2, dm * m1, dm * m2);
+ }
+};
+
+template <> struct Dec<T_Q6_K> {
+ static inline void run(device const uchar* row, int u, thread float* q, thread float4& sc, 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 ushort* ql = (device const ushort*)(b + 64 * n + 32 * p + 16 * m);
+ device const ushort* qh = (device const ushort*)(b + 128 + 32 * n + 16 * m);
+ device const char* scs = (device const char*)(b + 192);
+ const float d = rdh(b + 208);
+ for (int w = 0; w < 8; ++w) {
+ const ushort l = ql[w], h = qh[w];
+ bytes2((l & 0x0F0F) | (((h >> (2 * p)) & 0x0303) << 4), q + 2 * w);
+ bytes2(((l >> 4) & 0x0F0F) | (((h >> (2 * p + 4)) & 0x0303) << 4), q + 16 + 2 * w);
+ }
+ const float d1 = d * float(scs[8 * n + m + 2 * p]), d2 = d * float(scs[8 * n + m + 2 * p + 4]);
+ sc = float4(d1, d2, 32.0f * d1, 32.0f * d2);
+ }
+};
+
+template <> struct Dec<T_Q3_K> {
+ static inline void run(device const uchar* row, int u, thread float* q, thread float4& sc, threadgroup const uint*) {
+ device const uchar* b = row + (u >> 3) * 110;
+ const int n = (u >> 2) & 1, j = u & 3;
+ device const ushort* qq = (device const ushort*)(b + 32 + 32 * n);
+ device const ushort* hm = (device const ushort*)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 int hs = 4 * n + j;
+ for (int w = 0; w < 8; ++w) {
+ bytes2(((qq[w] >> (2 * j)) & 0x0303) | (((hm[w] >> hs) & 0x0101) << 2), q + 2 * w);
+ bytes2(((qq[w + 8] >> (2 * j)) & 0x0303) | (((hm[w + 8] >> hs) & 0x0101) << 2), q + 16 + 2 * w);
+ }
+ const float d1 = d * float(l1 - 32), d2 = d * float(l2 - 32);
+ sc = float4(d1, d2, 4.0f * d1, 4.0f * d2);
+ }
+};
+
+template <> struct Dec<T_BF16> {
+ static inline void run(device const uchar* row, int u, thread float* q, thread float4& sc, 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) {
+ q[2 * k] = as_type<float>(v[k] << 16);
+ q[2 * k + 1] = as_type<float>(v[k] & 0xFFFF0000u);
+ }
+ sc = float4(1.0f, 1.0f, 0.0f, 0.0f);
+ }
+};
+
+// acc += unit dot of decoded q / sc with one token's prepared slice
+template <int UNIT>
+static inline float unit_combine(thread const float* q, float4 sc, thread const float* xs, thread const float* xsum) {
+ constexpr int H = UNIT / 2;
+ float s0 = 0, s1 = 0, s2 = 0, s3 = 0;
+ for (int j = 0; j < H; j += 2) {
+ s0 = fma(q[j], xs[j], s0);
+ s1 = fma(q[j + 1], xs[j + 1], s1);
+ s2 = fma(q[H + j], xs[H + j], s2);
+ s3 = fma(q[H + j + 1], xs[H + j + 1], s3);
+ }
+ return sc.x * (s0 + s1) + sc.y * (s2 + s3) - (sc.z * xsum[0] + sc.w * xsum[1]);
+}
diff --git a/metal/src/mtl_rt.h b/metal/src/mtl_rt.h
index 060489351..b933f06e1 100644
--- a/metal/src/mtl_rt.h
+++ b/metal/src/mtl_rt.h
@@ -70,7 +70,8 @@ public:
// 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);
+ // Safe math unless STRATA_METAL_MATH=fast (the argument is ignored; kept for callers).
+ int compile(const std::vector<std::string>& files, const std::string& prelude = "", bool fast_math = false);
Pipeline pipeline(int lib, const std::string& fn, const Constants& c = {});
Buffer alloc(size_t bytes); // shared storage, zeroed
diff --git a/metal/src/mtl_rt.mm b/metal/src/mtl_rt.mm
index b66c1d16f..f876dd2ae 100644
--- a/metal/src/mtl_rt.mm
+++ b/metal/src/mtl_rt.mm
@@ -74,6 +74,10 @@ int Context::compile(const std::vector<std::string>& files, const std::string& p
src += "#line 1 \"" + f + "\"\n" + read_file(p) + "\n";
}
MTLCompileOptions* o = [MTLCompileOptions new];
+ // Safe math by default: no reassociation, so every token of a window is bitwise what a one-token call gives
+ // (the kernels write their contractions as explicit fma). Measured free on the M5 Max.
+ fast_math = false;
+ if (const char* m = std::getenv("STRATA_METAL_MATH")) fast_math = std::string(m) == "fast";
if (@available(macOS 15.0, *)) {
o.mathMode = fast_math ? MTLMathModeFast : MTLMathModeSafe;
} else {
diff --git a/metal/tests/alu_bench.cpp b/metal/tests/alu_bench.cpp
new file mode 100644
index 000000000..235760718
--- /dev/null
+++ b/metal/tests/alu_bench.cpp
@@ -0,0 +1,39 @@
+// metal/tests/alu_bench.cpp - per-operation instruction rates of the GPU (Gops/s, one op = one lane-operation).
+#include "mtl_rt.h"
+
+#include <algorithm>
+#include <cstdio>
+#include <vector>
+
+int main() {
+ mtl::Context cx;
+ const int lib = cx.compile({"alu_bench.metal"}, "#define NO_GGML_COMMON 1\n");
+ const uint32_t groups = 2560, tg = 256, n = groups * tg;
+ mtl::Buffer out = cx.alloc(4 * n), tab = cx.alloc(4096);
+ for (int i = 0; i < 1024; ++i) tab.as<uint32_t>()[i] = i * 7;
+ struct K { const char* name; double ops_per_iter; } ks[] = {
+ {"a_fma32", 8}, {"a_fma16", 8}, {"a_fmamix", 8}, {"a_iand", 16}, {"a_shift", 16}, {"a_cvt", 16},
+ {"a_tgload", 4}, {"a_sel", 8}, {"a_dot32", 8}, {"a_dot16", 8}, {"a_dotmix", 8}, {"a_fma32x16", 8}, {"a_devload", 4}, {"a_cstload", 4}, {"a_tgload4", 4}, {"a_popc", 4}};
+ std::printf("device %s\n", cx.device_name().c_str());
+ for (const K& k : ks) {
+ mtl::Pipeline p = cx.pipeline(lib, k.name);
+ mtl::Dispatch d;
+ d.p = &p;
+ const float kf = 0.999f;
+ const uint32_t ku = 3;
+ d.args = {mtl::Arg::B(out), std::string(k.name) == "a_fma32" || std::string(k.name) == "a_fma16" ||
+ std::string(k.name) == "a_fmamix" || std::string(k.name).rfind("a_dot", 0) == 0 || std::string(k.name) == "a_fma32x16"
+ ? mtl::Arg::V(kf)
+ : mtl::Arg::V(ku)};
+ if (std::string(k.name) == "a_devload" || std::string(k.name) == "a_cstload") d.args.push_back(mtl::Arg::B(tab));
+ d.grid[0] = groups;
+ d.tg[0] = tg;
+ cx.run({d});
+ std::vector<double> t;
+ for (int i = 0; i < 7; ++i) t.push_back(cx.run({d}));
+ std::sort(t.begin(), t.end());
+ const double ops = (double)n * 1024 * k.ops_per_iter;
+ std::printf("%-10s %8.1f Gops/s (%.3f ms)\n", k.name, ops / t[3] / 1e9, t[3] * 1e3);
+ }
+ return 0;
+}
diff --git a/metal/tests/expert_parity.cpp b/metal/tests/expert_parity.cpp
index a2e23662b..fa50bdc3f 100644
--- a/metal/tests/expert_parity.cpp
+++ b/metal/tests/expert_parity.cpp
@@ -93,14 +93,40 @@ void random_routing(ref::Rng& r, int ntok, int n_expert, std::vector<int>& ids,
}
struct Kernels {
- mtl::Pipeline plan, gu, dn, comb;
+ mtl::Pipeline plan, gu, dn, comb, prep;
Cfg cgu, cdn;
};
+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;
+ }
+}
+constexpr int CAPE = 8 * TOPK; // entries capacity of h
+// prepared buffers: x [8][N_EMBD] -> XPX, h [CAPE][N_FF] -> XPH (4 planes + S16)
+constexpr size_t PLANE_X = 8 * N_EMBD, PLANE_H = (size_t)CAPE * N_FF;
+
+mtl::Dispatch prep_dispatch(const mtl::Pipeline& p, const mtl::Buffer& x, const mtl::Buffer& xp, uint32_t n, uint32_t nt) {
+ mtl::Dispatch d;
+ d.p = &p;
+ 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] = (n / 16 * nt + 255) / 256;
+ return d;
+}
+
+int g_gu_type = 0, g_dn_type = 0;
+const mtl::Buffer* g_xpx = nullptr;
+const mtl::Buffer* g_xph = nullptr;
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) {
+ const mtl::Buffer& XPX = *g_xpx;
+ const mtl::Buffer& XPH = *g_xph;
if (with_plan) {
mtl::Dispatch d;
d.p = &K.plan;
@@ -111,16 +137,20 @@ void encode_layer(std::vector<mtl::Dispatch>& ds, const Kernels& K, const mtl::B
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.args = {mtl::Arg::B(W, w_off), mtl::Arg::B(XPX, 4 * PLANE_X * xkind(g_gu_type)), mtl::Arg::B(h),
+ mtl::Arg::B(plan, plan_off), mtl::Arg::V(a), mtl::Arg::B(XPX, 4 * PLANE_X * 4)};
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) {
+ if (xkind(g_dn_type)) ds.push_back(prep_dispatch(K.prep, h, XPH, N_FF, CAPE));
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.args = {mtl::Arg::B(W, w_off),
+ xkind(g_dn_type) ? mtl::Arg::B(XPH, 4 * PLANE_H * xkind(g_dn_type)) : mtl::Arg::B(h), mtl::Arg::B(ye),
+ mtl::Arg::B(plan, plan_off), mtl::Arg::V(a), mtl::Arg::B(XPH, 4 * PLANE_H * 4)};
d.tg[0] = K.cdn.S * 32;
d.indirect = &plan;
d.ind_off = plan_off + P_IDN * 4;
@@ -180,7 +210,7 @@ int main(int argc, char** argv) {
(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 int lib = cx.compile({"quant.metal", "units.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);
@@ -188,6 +218,7 @@ int main(int argc, char** argv) {
auto make = [&](Cfg a, Cfg b) {
Kernels K;
K.plan = cx.pipeline(lib, "moe_plan");
+ K.prep = cx.pipeline(lib, "xprep");
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));
@@ -214,8 +245,17 @@ int main(int argc, char** argv) {
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);
+ mtl::Buffer XPX = cx.alloc(4 * (4 * PLANE_X + PLANE_X / 16)), XPH = cx.alloc(4 * (4 * PLANE_H + PLANE_H / 16));
+ g_xpx = &XPX;
+ g_xph = &XPH;
+ g_gu_type = gu;
+ g_dn_type = dn;
ref::Rng rng(12345);
for (int i = 0; i < 8 * N_EMBD; ++i) x.as<float>()[i] = rng.sym();
+ {
+ mtl::Pipeline pp = cx.pipeline(lib, "xprep");
+ cx.run({prep_dispatch(pp, x, XPX, N_EMBD, 8)});
+ }
if (!bench) {
// ---------------- parity ----------------
@@ -340,10 +380,10 @@ int main(int argc, char** argv) {
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]);
+ for (auto& z : d) dd.push_back(z);
dall.push_back(one[0]);
dall.push_back(g[0]);
- dall.push_back(d[0]);
+ for (auto& z : d) dall.push_back(z);
}
cx.run(dp); // plans in place
std::vector<double> tp, tg, td, ta;
diff --git a/metal/tests/gemv_parity.cpp b/metal/tests/gemv_parity.cpp
new file mode 100644
index 000000000..e2d3583c2
--- /dev/null
+++ b/metal/tests/gemv_parity.cpp
@@ -0,0 +1,258 @@
+// metal/tests/gemv_parity.cpp - the dense GEMV (gemv.metal) per format: parity against double, and speed per tile
+// shape on the model's projection shapes.
+//
+// gemv_parity parity: every format, n_in 2560/640/10240, 1..8 tokens
+// gemv_parity --bench [--pack Q2_0|IQ3_XXS] [--ntok N] [--all] speed on the pack's shapes (best tile per shape)
+// gemv_parity --one TYPE NIN NOUT [--ntok N] sweep one shape
+#include "mtl_rt.h"
+#include "ref_quant.h"
+
+#include <algorithm>
+#include <cmath>
+#include <cstdio>
+#include <cstdlib>
+#include <cstring>
+#include <string>
+#include <vector>
+
+namespace {
+
+struct GemvArgs { uint32_t n_in, n_out, n_tok, row_bytes, x_stride, y_stride; };
+struct Cfg { int L, R, S, K; };
+const std::vector<Cfg> kCfgs = {{32, 1, 4, 1}, {32, 2, 4, 1}, {16, 1, 4, 1}, {16, 2, 4, 1}, {8, 1, 4, 1},
+ {8, 2, 4, 1}, {4, 2, 4, 1}, {4, 1, 4, 1}, {32, 1, 4, 4}, {32, 2, 4, 2},
+ {32, 1, 8, 8}, {16, 1, 8, 4}, {32, 1, 8, 2}, {8, 1, 8, 1}, {1, 1, 4, 1},
+ {1, 2, 4, 1}, {2, 1, 4, 1}, {2, 2, 4, 1}, {1, 1, 2, 1}, {4, 4, 4, 1}};
+int rows_per_tg(Cfg c) { return (c.S / c.K) * (32 / c.L) * c.R; }
+int unit_of(int t) {
+ switch (t) {
+ case ref::Q2_0: case ref::IQ3_S: case ref::IQ3_XXS: case ref::IQ2_XXS: case ref::IQ2_XS: case ref::IQ2_S:
+ case ref::BF16: return 16;
+ default: return 32;
+ }
+}
+bool cfg_ok(Cfg c, int type, int n_in) {
+ const int U = n_in / unit_of(type);
+ return U % c.K == 0 && U / c.K >= c.L / 2;
+}
+std::string kname(int t, Cfg c) {
+ return "gemv_" + std::to_string(t) + "_" + std::to_string(c.L) + "_" + std::to_string(c.R) + "_" +
+ std::to_string(c.S) + "_" + std::to_string(c.K);
+}
+double median(std::vector<double> v) { std::sort(v.begin(), v.end()); return v[v.size() / 2]; }
+// which prepared x a format reads (units.metal XK_*)
+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;
+ }
+}
+// x [MAXT][n] -> XP [4][MAXT][n] + S16 [MAXT][n/16]
+mtl::Dispatch xprep_dispatch(const mtl::Pipeline& p, const mtl::Buffer& x, const mtl::Buffer& xp, uint32_t n, uint32_t nt) {
+ mtl::Dispatch d;
+ d.p = &p;
+ 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] = (n / 16 * nt + 255) / 256;
+ return d;
+}
+
+int type_of(const std::string& s) {
+ 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::IQ4_NL,
+ ref::IQ4_XS, ref::IQ3_S, ref::BF16})
+ if (s == ref::type_name(t)) return t;
+ std::fprintf(stderr, "unknown type %s\n", s.c_str());
+ std::exit(2);
+}
+
+struct Shape { const char* name; int type, n_in, n_out, per_token; }; // per_token: calls per decoded token
+
+} // namespace
+
+int main(int argc, char** argv) {
+ bool bench = false, all = false;
+ int ntok = 1;
+ std::string pack = "Q2_0";
+ std::vector<Shape> one;
+ for (int i = 1; i < argc; ++i) {
+ std::string a = argv[i];
+ if (a == "--bench") bench = true;
+ else if (a == "--all") all = true;
+ else if (a == "--ntok") ntok = std::atoi(argv[++i]);
+ else if (a == "--pack") pack = argv[++i];
+ else if (a == "--one") {
+ const int t = type_of(argv[i + 1]);
+ one.push_back({"one", t, std::atoi(argv[i + 2]), std::atoi(argv[i + 3]), 1});
+ i += 3;
+ bench = true;
+ all = true;
+ } else { std::fprintf(stderr, "unknown argument %s\n", a.c_str()); return 2; }
+ }
+ mtl::Context cx;
+ const int lib = cx.compile({"quant.metal", "units.metal", "gemv.metal"});
+ std::printf("device %s\n", cx.device_name().c_str());
+ const int MAXT = 8;
+ mtl::Pipeline pprep = cx.pipeline(lib, "xprep");
+
+ if (!bench) {
+ int fails = 0;
+ for (int t : {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}) {
+ for (int n_in : {2560, 640, 10240}) {
+ if (n_in % ref::block_elems(t)) continue;
+ const int n_out = 100; // not a multiple of the rows per threadgroup on purpose
+ 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);
+ mtl::Buffer xp = cx.alloc(4 * (4 * n_in * MAXT + n_in / 16 * MAXT));
+ ref::random_blocks(t, W.as<uint8_t>(), n_out, n_in, 31 + t + n_in);
+ ref::Rng r(7 + n_in);
+ for (int i = 0; i < n_in * MAXT; ++i) x.as<float>()[i] = r.sym();
+ cx.run({xprep_dispatch(pprep, x, xp, n_in, MAXT)});
+ const size_t plane = (size_t)4 * n_in * MAXT;
+ 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}) {
+ double worst = 0;
+ int not_exact = 0;
+ std::string worst_cfg;
+ for (Cfg c : kCfgs) {
+ if (!cfg_ok(c, t, n_in)) continue;
+ mtl::Pipeline p = cx.pipeline(lib, kname(t, c), mtl::Constants().i(0, nt));
+ GemvArgs a{(uint32_t)n_in, (uint32_t)n_out, (uint32_t)nt, (uint32_t)rb, (uint32_t)n_in,
+ (uint32_t)n_out};
+ std::memset(y.ptr, 0, y.bytes);
+ mtl::Dispatch d;
+ d.p = &p;
+ d.args = {mtl::Arg::B(W), mtl::Arg::B(xp, plane * xkind(t)), mtl::Arg::B(xp, plane * 4),
+ mtl::Arg::B(y), mtl::Arg::V(a)};
+ d.grid[0] = (n_out + rows_per_tg(c) - 1) / rows_per_tg(c);
+ d.tg[0] = c.S * 32;
+ 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;
+ }
+ const double rel = std::sqrt(se / sr);
+ if (rel > worst) { worst = rel; worst_cfg = kname(t, c); }
+ if (nt > 1) {
+ // every token of a window must be bitwise what a one-token call gives
+ std::vector<float> ywin((float*)y.ptr, (float*)y.ptr + nt * n_out);
+ mtl::Pipeline p1 = cx.pipeline(lib, kname(t, c), mtl::Constants().i(0, 1));
+ GemvArgs a1 = a;
+ a1.n_tok = 1;
+ for (int tt = 0; tt < nt; ++tt) {
+ mtl::Dispatch d1 = d;
+ d1.p = &p1;
+ d1.args = {mtl::Arg::B(W), mtl::Arg::B(xp, plane * xkind(t) + 4 * (size_t)tt * n_in),
+ mtl::Arg::B(xp, plane * 4 + 4 * (size_t)tt * (n_in / 16)), mtl::Arg::B(y),
+ mtl::Arg::V(a1)};
+ cx.run({d1});
+ if (std::memcmp(y.ptr, ywin.data() + tt * n_out, 4 * n_out) != 0) ++not_exact;
+ }
+ }
+ }
+ const bool ok = worst < 1e-5 && not_exact == 0;
+ fails += !ok;
+ std::printf("parity %-7s n_in %5d ntok %d: worst rel L2 over %zu tiles %.2e (%s), window == one "
+ "token: %s %s\n",
+ ref::type_name(t), n_in, nt, kCfgs.size(), worst, worst_cfg.c_str(),
+ nt == 1 ? "-" : not_exact ? "NO" : "bitwise", ok ? "PASS" : "FAIL");
+ }
+ cx.free(W);
+ cx.free(x);
+ cx.free(y);
+ cx.free(xp);
+ }
+ }
+ std::printf("%s\n", fails ? "SOME FAILED" : "ALL PASS");
+ return fails ? 1 : 0;
+ }
+
+ // ---- bench
+ std::vector<Shape> shapes = one;
+ if (shapes.empty()) {
+ if (pack == "Q2_0")
+ shapes = {
+ {"hc down (x4/layer)", ref::BF16, 10240, 320, 4 * 48}, {"hc up (x4/layer)", ref::BF16, 320, 10240, 4 * 48},
+ {"router", ref::BF16, 2560, 512, 48}, {"gdn qkv", ref::IQ4_XS, 2560, 10240, 13},
+ {"gdn qkv", ref::Q3_K, 2560, 10240, 18}, {"gdn qkv", ref::Q4_K, 2560, 10240, 4},
+ {"gdn gate", ref::Q3_K, 2560, 6144, 25}, {"gdn out", ref::IQ4_XS, 6144, 2560, 17},
+ {"gdn out", ref::Q4_K, 6144, 2560, 11}, {"qsa q", ref::Q3_K, 2560, 12288, 6},
+ {"qsa out", ref::Q5_K, 6144, 2560, 4}, {"qsa k", ref::Q3_K, 2560, 512, 3},
+ {"shexp gate", ref::Q2_0, 2560, 640, 21}, {"shexp down", ref::Q4_0, 640, 2560, 16},
+ {"shexp down", ref::Q2_0, 640, 2560, 16}, {"indexer q", ref::BF16, 2560, 512, 12},
+ {"ssm alpha", ref::BF16, 2560, 48, 36}, {"lm head", ref::Q5_K, 2560, 248320, 1},
+ {"gdn qkv", ref::Q6_K, 2560, 10240, 1},
+ };
+ else
+ shapes = {
+ {"hc down (x4/layer)", ref::BF16, 10240, 320, 4 * 48}, {"hc up (x4/layer)", ref::BF16, 320, 10240, 4 * 48},
+ {"gdn qkv", ref::IQ4_XS, 2560, 10240, 11}, {"gdn qkv", ref::Q6_K, 2560, 10240, 14},
+ {"gdn qkv", ref::Q4_K, 2560, 10240, 8}, {"gdn out", ref::Q6_K, 6144, 2560, 19},
+ {"gdn gate", ref::IQ3_S, 2560, 6144, 10}, {"gdn gate", ref::IQ4_XS, 2560, 6144, 11},
+ {"qsa out", ref::Q6_K, 6144, 2560, 10}, {"qsa q", ref::IQ4_XS, 2560, 12288, 4},
+ {"shexp down", ref::IQ4_NL, 640, 2560, 40}, {"shexp up", ref::IQ3_S, 2560, 640, 27},
+ {"lm head", ref::Q5_K, 2560, 248320, 1},
+ };
+ }
+ std::vector<int> ntoks = {ntok};
+ std::printf("%-20s %-7s %6s %7s %5s %9s %9s %8s %s\n", "shape", "type", "n_in", "n_out", "ntok", "us", "GB/s",
+ "MB", "best tile (L,R,S,K)");
+ 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>(256, (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);
+ {
+ std::vector<uint8_t> tmp(mb);
+ ref::random_blocks(s.type, tmp.data(), s.n_out, s.n_in, 99);
+ 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::Buffer xp = cx.alloc(4 * (4 * s.n_in * MAXT + s.n_in / 16 * MAXT));
+ cx.run({xprep_dispatch(pprep, x, xp, s.n_in, MAXT)});
+ const size_t plane = (size_t)4 * s.n_in * MAXT;
+ for (int nt : ntoks) {
+ double best = 1e9;
+ Cfg bc{};
+ for (Cfg c : kCfgs) {
+ if (!cfg_ok(c, s.type, s.n_in)) continue;
+ if (!all && !(c.K == 1 || s.n_in >= 6144)) continue;
+ mtl::Pipeline p = cx.pipeline(lib, kname(s.type, c), mtl::Constants().i(0, nt));
+ GemvArgs a{(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> ds;
+ const int R = std::max(copies, 16);
+ for (int k = 0; k < R; ++k) {
+ mtl::Dispatch d;
+ d.p = &p;
+ 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(a)};
+ d.grid[0] = (s.n_out + rows_per_tg(c) - 1) / rows_per_tg(c);
+ d.tg[0] = c.S * 32;
+ ds.push_back(d);
+ }
+ cx.run(ds);
+ std::vector<double> t;
+ for (int i = 0; i < 5; ++i) t.push_back(cx.run(ds) / R);
+ const double m = median(t);
+ if (one.size()) std::printf(" tile %2d,%d,%d,%d: %8.2f us %6.1f GB/s\n", c.L, c.R, c.S, c.K, m * 1e6, mb / m / 1e9);
+ if (m < best) { best = m; bc = c; }
+ }
+ std::printf("%-20s %-7s %6d %7d %5d %9.2f %9.1f %8.2f %d,%d,%d,%d\n", s.name, ref::type_name(s.type), s.n_in,
+ s.n_out, nt, best * 1e6, mb / best / 1e9, mb / 1e6, bc.L, bc.R, bc.S, bc.K);
+ }
+ cx.free(W);
+ cx.free(x);
+ cx.free(y);
+ cx.free(xp);
+ }
+ return 0;
+}
diff --git a/metal/tests/rt_bench.cpp b/metal/tests/rt_bench.cpp
index ec95c9df6..9fc49ff7a 100644
--- a/metal/tests/rt_bench.cpp
+++ b/metal/tests/rt_bench.cpp
@@ -127,6 +127,40 @@ static void bw(mtl::Context& cx, int lib, size_t mib) {
cx.free(out);
}
+// A read of `kib` from DRAM per dispatch (each dispatch a different, uncached chunk of a 4 GiB buffer), dependent
+// dispatches in one serial encoder: the bound for a kernel that streams that much once.
+static void bwsize(mtl::Context& cx, int lib) {
+ const size_t big = 4ull << 30;
+ mtl::Buffer src = cx.alloc(big), out = cx.alloc(64u << 20);
+ mtl::Pipeline pr = cx.pipeline(lib, "k_read");
+ std::printf("%10s %8s %10s %10s\n", "chunk KiB", "tg x grp", "us/disp", "GB/s");
+ for (size_t kib : {1152ul, 2304ul, 4500ul, 9000ul, 13500ul, 18000ul, 36000ul, 72000ul}) {
+ const size_t bytes = kib * 1024;
+ const int R = (int)std::min<size_t>(400, big / bytes);
+ double bestt = 1e9;
+ uint32_t bg = 0, btg = 0;
+ for (uint32_t tg : {256u, 1024u})
+ for (uint32_t groups : {80u, 160u, 320u, 640u, 1280u}) {
+ std::vector<mtl::Dispatch> ds;
+ const uint32_t n = (uint32_t)(bytes / 16);
+ for (int r = 0; r < R; ++r) {
+ mtl::Dispatch d;
+ d.p = &pr;
+ d.args = {mtl::Arg::B(src, (size_t)r * ((big / R) & ~4095ull)), mtl::Arg::B(out), mtl::Arg::V(n)};
+ d.grid[0] = groups;
+ d.tg[0] = tg;
+ ds.push_back(d);
+ }
+ double med, best;
+ timed(1, 5, [&] { return cx.run(ds) / R; }, med, best);
+ if (med < bestt) { bestt = med; bg = groups; btg = tg; }
+ }
+ std::printf("%10zu %4ux%-4u %10.2f %10.1f\n", kib, btg, bg, bestt * 1e6, bytes / bestt / 1e9);
+ }
+ 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");
@@ -199,5 +233,6 @@ int main(int argc, char** argv) {
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);
+ if (mode == "bwsize" || mode == "all") bwsize(cx, lib);
return 0;
}