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: two-dispatch hyper-connection read (per-stream norm in the down kernel), Q8_0 HC option

Niko12213c6eeb00494a
diff --git a/metal/kernels/gr2.metal b/metal/kernels/gr2.metal
new file mode 100644
index 000000000..c0e502f25
--- /dev/null
+++ b/metal/kernels/gr2.metal
@@ -0,0 +1,282 @@
+// metal/kernels/gr2.metal - the hyper-connection read in TWO dispatches (after quant/units/gr.metal), for BF16 HC
+// weights (the exact path) or a Q8_0 copy of them (the STRATA_HC_Q8 option):
+//
+// gr_down3 grid (row blocks, hc streams). The RMSNorm is per stream, so a threadgroup owns one stream c: it forms
+// R'_c = R_c + bo * 2 sigmoid(inj_prev_c / hc) (10 KB a token), its sum of squares and rs_c itself,
+// stages xn_c = (R'_c * w_norm_c) * rs_c in threadgroup memory once, and every simdgroup dots its rows'
+// stream-c quarter with it: D[t][row][c]. Row block 0 also writes R'_c to R_out (ping-pong, never in
+// place) and rs_c. Rows 0..hc_lr-1 are w_down, hc_lr.. the inject rows.
+// gr_up3 lo[k] = silu(sum_c D[t][k][c] / hc) formed in threadgroup memory, then as gr_up with xn = R' * w_norm
+// * rs on the fly, writing the prepared activations.
+// inj_prev of the NEXT read = sum_c D[t][hc_lr + c'][c] of this one (gr_down3 sums it, in c order).
+//
+// Per element the arithmetic is gr_norm's (fma(bo, g, R), then (R' * w) * rs); the K order differs (per stream, then
+// the 4 streams in order).
+
+struct GrArgs3 {
+ uint n_embd;
+ uint hc;
+ uint hc_lr;
+ uint n_tok; // the prepared planes' row count (the plane stride)
+ uint apply;
+ float eps;
+ uint rb_down; // bytes per row of w_down / w_inject
+ uint rb_up; // bytes per row of w_up
+};
+
+template <int F, int TT, int RPS>
+kernel void gr_down3(device const uchar* w_down [[buffer(0)]], device const uchar* w_inject [[buffer(1)]],
+ device const float* Rin [[buffer(2)]], device float* Rout [[buffer(3)]],
+ device const float* bo [[buffer(4)]], device const float* Dprev [[buffer(5)]],
+ device const float* wn [[buffer(6)]], device float* D [[buffer(7)]],
+ device float* rs_out [[buffer(8)]], constant GrArgs3& a [[buffer(9)]],
+ uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]],
+ ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) {
+ constexpr int UNIT = fmt<F>::UNIT;
+ threadgroup float xs_tg[TT][2560];
+ threadgroup float part[8][TT];
+ threadgroup float g_tg[TT], rs_tg[TT];
+ threadgroup uint tab[fmt<F>::TAB];
+ load_tab<F>(tab, tid, 256);
+ const int n = int(a.n_embd), hc = int(a.hc), NIN = hc * n, c = int(tg.y);
+ const int nrows = int(a.hc_lr) + hc;
+ for (int t0 = 0; t0 < GR_NTOK; t0 += TT) {
+ const int T = min(TT, GR_NTOK - t0);
+ if (tid < T) {
+ float g = 0.0f;
+ if (a.apply) {
+ device const float* dp = Dprev + ((t0 + tid) * nrows + int(a.hc_lr) + c) * hc;
+ const float ip = ((dp[0] + dp[1]) + dp[2]) + dp[3];
+ g = 2.0f / (1.0f + exp(-ip / float(hc)));
+ }
+ g_tg[tid] = g;
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ for (int t = 0; t < T; ++t) {
+ device const float* rt = Rin + (t0 + t) * NIN + c * n;
+ float ss = 0.0f;
+ for (int d = tid; d < n; d += 256) {
+ float v = rt[d];
+ if (a.apply) v = fma(bo[(t0 + t) * n + d], g_tg[t], v);
+ xs_tg[t][d] = v;
+ ss = fma(v, v, ss);
+ if (tg.x == 0) Rout[(t0 + t) * NIN + c * n + d] = v;
+ }
+ ss = simd_sum(ss);
+ if (lane == 0) part[sg][t] = ss;
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ if (tid < T) {
+ float tot = 0.0f;
+ for (int k = 0; k < 8; ++k) tot += part[k][tid];
+ const float rsv = rsqrt(tot / float(n) + a.eps);
+ rs_tg[tid] = rsv;
+ if (tg.x == 0) rs_out[(t0 + tid) * hc + c] = rsv;
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ for (int t = 0; t < T; ++t)
+ for (int d = tid; d < n; d += 256) xs_tg[t][d] = xs_tg[t][d] * wn[c * n + d] * rs_tg[t];
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ // the rows: simdgroup sg holds RPS rows; lanes split the stream's units
+ int rows[RPS];
+ device const uchar* wr[RPS];
+ for (int k = 0; k < RPS; ++k) {
+ rows[k] = (int(tg.x) * 8 + sg) * RPS + k;
+ const int rr = min(rows[k], nrows - 1);
+ wr[k] = rr < int(a.hc_lr) ? w_down + ulong(rr) * a.rb_down : w_inject + ulong(rr - int(a.hc_lr)) * a.rb_down;
+ }
+ float acc[RPS][TT];
+ for (int k = 0; k < RPS; ++k)
+ for (int t = 0; t < TT; ++t) acc[k][t] = 0.0f;
+ const int U = n / UNIT, u0 = c * U;
+ for (int u = lane; u < U; u += 32) {
+ float q[RPS][UNIT];
+ float4 sc[RPS];
+ for (int k = 0; k < RPS; ++k) Dec<F>::run(wr[k], u0 + u, q[k], sc[k], tab);
+ for (int t = 0; t < T; ++t) {
+ float xs[UNIT], xsum[2] = {0.0f, 0.0f};
+ for (int e = 0; e < UNIT; ++e) xs[e] = xs_tg[t][u * UNIT + e];
+ for (int k = 0; k < RPS; ++k) acc[k][t] += unit_combine<UNIT>(q[k], sc[k], xs, xsum);
+ }
+ }
+ for (int k = 0; k < RPS; ++k)
+ for (int t = 0; t < T; ++t) {
+ const float v = simd_sum(acc[k][t]);
+ if (lane == 0 && rows[k] < nrows) D[((t0 + t) * nrows + rows[k]) * hc + c] = v;
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ }
+}
+
+// grid (n_embd / 16), 256 threads.
+template <int F>
+kernel void gr_up3(device const uchar* w_up [[buffer(0)]], device const float* D [[buffer(1)]],
+ device const float* Rn [[buffer(2)]], device float* xp [[buffer(3)]],
+ constant GrArgs3& a [[buffer(4)]], device const float* wn [[buffer(5)]],
+ device const float* rs [[buffer(6)]],
+ 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;
+ threadgroup float lo_tg[8][320];
+ threadgroup float gate[8][4][16];
+ threadgroup float msum[8][16];
+ threadgroup uint tab[fmt<F>::TAB];
+ load_tab<F>(tab, tid, 256);
+ const int n = int(a.n_embd), hc = int(a.hc), lr = int(a.hc_lr), nrows = lr + hc;
+ for (int e = tid; e < GR_NTOK * lr; e += 256) {
+ const int t = e / lr, k = e - t * lr;
+ device const float* dp = D + (t * nrows + k) * hc;
+ const float z = (((dp[0] + dp[1]) + dp[2]) + dp[3]) / float(hc);
+ lo_tg[t][k] = z / (1.0f + exp(-z));
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ const int c = sg >> 1, dl = 8 * (sg & 1) + lane / 4, li = lane & 3;
+ const int d = int(tg.x) * 16 + dl;
+ device const uchar* w = w_up + ulong(c * n + d) * a.rb_up;
+ const int U = lr / UNIT;
+ float acc[8];
+ for (int t = 0; t < 8; ++t) acc[t] = 0.0f;
+ for (int u = li; u < U; u += 4) {
+ float q[UNIT];
+ float4 sc;
+ Dec<F>::run(w, u, q, sc, tab);
+ for (int t = 0; t < GR_NTOK; ++t) {
+ float xs[UNIT], xsum[2] = {0.0f, 0.0f};
+ for (int e = 0; e < UNIT; ++e) xs[e] = lo_tg[t][UNIT * u + e];
+ acc[t] += unit_combine<UNIT>(q, sc, xs, xsum);
+ }
+ }
+ for (int t = 0; t < GR_NTOK; ++t) {
+ const float v = lane_sum<4>(acc[t]);
+ if (li == 0) gate[t][c][dl] = 1.0f / (1.0f + exp(-v));
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ const int t = tid / 16, j = tid & 15;
+ if (t < GR_NTOK) {
+ const int dd = int(tg.x) * 16 + j;
+ float m = 0.0f;
+ for (int cc = 0; cc < hc; ++cc) {
+ const float xn = Rn[(t * hc + cc) * n + dd] * wn[cc * n + dd] * rs[t * hc + cc];
+ m = fma(xn, gate[t][cc][j], m);
+ }
+ m = m / float(hc);
+ const uint plane = a.n_tok * uint(n);
+ device float* raw = xp + t * n + dd;
+ 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};
+ raw[0] = m;
+ raw[plane] = m * q2s[j & 7];
+ raw[2 * plane] = m * p4s[j & 3];
+ raw[3 * plane] = (j & 1) ? m * 0.00390625f : m;
+ msum[t][j] = m;
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ if (t < GR_NTOK && j == 0) {
+ float s0 = 0.0f, s1 = 0.0f;
+ for (int k = 0; k < 16; k += 2) { s0 += msum[t][k]; s1 += msum[t][k + 1]; }
+ xp[4 * a.n_tok * uint(n) + t * (n / 16) + tg.x] = s0 + s1;
+ }
+}
+
+#define GD3(F, T, R) template [[host_name("gr_down3_" #F "_" #T "_" #R)]] kernel decltype(gr_down3<F, T, R>) gr_down3<F, T, R>;
+GD3(30, 1, 1) GD3(30, 2, 1) GD3(30, 3, 1) GD3(30, 1, 2) GD3(30, 2, 2) GD3(30, 3, 2)
+GD3(8, 1, 1) GD3(8, 2, 1) GD3(8, 3, 1) GD3(8, 1, 2) GD3(8, 2, 2) GD3(8, 3, 2)
+template [[host_name("gr_up3_30")]] kernel decltype(gr_up3<T_BF16>) gr_up3<T_BF16>;
+template [[host_name("gr_up3_8")]] kernel decltype(gr_up3<T_Q8_0>) gr_up3<T_Q8_0>;
+
+// BF16 only: as gr_down3, but each lane loads its rows' weights (5 units of 16 per row and lane: 2560 = 160 units)
+// into registers before the norm phase, so the weight stream is in flight while the threadgroup forms xn.
+template <int TT, int RPS>
+kernel void gr_down3b(device const uchar* w_down [[buffer(0)]], device const uchar* w_inject [[buffer(1)]],
+ device const float* Rin [[buffer(2)]], device float* Rout [[buffer(3)]],
+ device const float* bo [[buffer(4)]], device const float* Dprev [[buffer(5)]],
+ device const float* wn [[buffer(6)]], device float* D [[buffer(7)]],
+ device float* rs_out [[buffer(8)]], constant GrArgs3& a [[buffer(9)]],
+ uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]],
+ ushort sg [[simdgroup_index_in_threadgroup]], ushort lane [[thread_index_in_simdgroup]]) {
+ threadgroup float xs_tg[TT][2560];
+ threadgroup float part[8][TT];
+ threadgroup float g_tg[TT], rs_tg[TT];
+ const int n = int(a.n_embd), hc = int(a.hc), NIN = hc * n, c = int(tg.y);
+ const int nrows = int(a.hc_lr) + hc;
+ int rows[RPS];
+ uint4 wr[RPS][5][2];
+ for (int k = 0; k < RPS; ++k) {
+ rows[k] = (int(tg.x) * 8 + sg) * RPS + k;
+ const int rr = min(rows[k], nrows - 1);
+ device const uchar* w = rr < int(a.hc_lr) ? w_down + ulong(rr) * a.rb_down : w_inject + ulong(rr - int(a.hc_lr)) * a.rb_down;
+ device const uint4* p = (device const uint4*)(w + 2 * (c * n));
+ for (int i = 0; i < 5; ++i) {
+ wr[k][i][0] = p[2 * (lane + 32 * i)];
+ wr[k][i][1] = p[2 * (lane + 32 * i) + 1];
+ }
+ }
+ for (int t0 = 0; t0 < GR_NTOK; t0 += TT) {
+ const int T = min(TT, GR_NTOK - t0);
+ if (tid < T) {
+ float g = 0.0f;
+ if (a.apply) {
+ device const float* dp = Dprev + ((t0 + tid) * nrows + int(a.hc_lr) + c) * hc;
+ const float ip = ((dp[0] + dp[1]) + dp[2]) + dp[3];
+ g = 2.0f / (1.0f + exp(-ip / float(hc)));
+ }
+ g_tg[tid] = g;
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ for (int t = 0; t < T; ++t) {
+ device const float* rt = Rin + (t0 + t) * NIN + c * n;
+ float ss = 0.0f;
+ for (int d = tid; d < n; d += 256) {
+ float v = rt[d];
+ if (a.apply) v = fma(bo[(t0 + t) * n + d], g_tg[t], v);
+ xs_tg[t][d] = v;
+ ss = fma(v, v, ss);
+ if (tg.x == 0) Rout[(t0 + t) * NIN + c * n + d] = v;
+ }
+ ss = simd_sum(ss);
+ if (lane == 0) part[sg][t] = ss;
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ if (tid < T) {
+ float tot = 0.0f;
+ for (int k = 0; k < 8; ++k) tot += part[k][tid];
+ const float rsv = rsqrt(tot / float(n) + a.eps);
+ rs_tg[tid] = rsv;
+ if (tg.x == 0) rs_out[(t0 + tid) * hc + c] = rsv;
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ for (int t = 0; t < T; ++t)
+ for (int d = tid; d < n; d += 256) xs_tg[t][d] = xs_tg[t][d] * wn[c * n + d] * rs_tg[t];
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ float acc[RPS][TT];
+ for (int k = 0; k < RPS; ++k)
+ for (int t = 0; t < TT; ++t) acc[k][t] = 0.0f;
+ for (int i = 0; i < 5; ++i) {
+ const int u = lane + 32 * i;
+ for (int k = 0; k < RPS; ++k) {
+ const uint v[8] = {wr[k][i][0].x, wr[k][i][0].y, wr[k][i][0].z, wr[k][i][0].w,
+ wr[k][i][1].x, wr[k][i][1].y, wr[k][i][1].z, wr[k][i][1].w};
+ float q[16];
+ for (int e = 0; e < 8; ++e) {
+ q[2 * e] = as_type<float>(v[e] << 16);
+ q[2 * e + 1] = as_type<float>(v[e] & 0xFFFF0000u);
+ }
+ const float4 sc = float4(1.0f, 1.0f, 0.0f, 0.0f);
+ for (int t = 0; t < T; ++t) {
+ float xs[16], xsum[2] = {0.0f, 0.0f};
+ for (int e = 0; e < 16; ++e) xs[e] = xs_tg[t][u * 16 + e];
+ acc[k][t] += unit_combine<16>(q, sc, xs, xsum);
+ }
+ }
+ }
+ for (int k = 0; k < RPS; ++k)
+ for (int t = 0; t < T; ++t) {
+ const float v = simd_sum(acc[k][t]);
+ if (lane == 0 && rows[k] < nrows) D[((t0 + t) * nrows + rows[k]) * hc + c] = v;
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ }
+}
+#define GD3B(T, R) template [[host_name("gr_down3b_" #T "_" #R)]] kernel decltype(gr_down3b<T, R>) gr_down3b<T, R>;
+GD3B(1, 1) GD3B(2, 1) GD3B(3, 1) GD3B(1, 2) GD3B(2, 2) GD3B(3, 2)
diff --git a/metal/src/ref_quant.cpp b/metal/src/ref_quant.cpp
index bc0219267..1f64489f9 100644
--- a/metal/src/ref_quant.cpp
+++ b/metal/src/ref_quant.cpp
@@ -3,6 +3,7 @@
// 32-blocks from Strata's include/strata/artifact/dequant.hpp (themselves transcribed from the same commit).
#include "ref_quant.h"
+#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstdlib>
@@ -378,6 +379,19 @@ void dequant(int t, const void* src, float* dst, size_t n) {
for (size_t i = 0; i < n / be; ++i) deq_block(t, s + i * bb, dst + i * be);
}
+void quantize_q8_0(const float* x, size_t n, uint8_t* out) {
+ for (size_t b = 0; b < n / 32; ++b) {
+ float amax = 0.0f;
+ for (int j = 0; j < 32; ++j) amax = std::max(amax, std::fabs(x[b * 32 + j]));
+ const float d = amax / 127.0f, id = d != 0.0f ? 1.0f / d : 0.0f;
+ const uint16_t h = f32_to_f16(d);
+ uint8_t* o = out + b * 34;
+ o[0] = (uint8_t)h;
+ o[1] = (uint8_t)(h >> 8);
+ for (int j = 0; j < 32; ++j) o[2 + j] = (uint8_t)(int8_t)std::roundf(x[b * 32 + j] * id);
+ }
+}
+
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) {
diff --git a/metal/src/ref_quant.h b/metal/src/ref_quant.h
index fc2fc9bbd..c53f28bee 100644
--- a/metal/src/ref_quant.h
+++ b/metal/src/ref_quant.h
@@ -28,6 +28,9 @@ 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);
+// ggml's quantize_row_q8_0_ref: per 32 values d = max|x| / 127 (stored fp16), q = roundf(x * (1 / d)).
+void quantize_q8_0(const float* x, size_t n, uint8_t* out);
+
// 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);
diff --git a/metal/tests/gr2_parity.cpp b/metal/tests/gr2_parity.cpp
new file mode 100644
index 000000000..d2d3c78de
--- /dev/null
+++ b/metal/tests/gr2_parity.cpp
@@ -0,0 +1,246 @@
+// metal/tests/gr2_parity.cpp - the two-dispatch hyper-connection read (gr2.metal: gr_down3 + gr_up3), BF16 and Q8_0
+// weights, against a double-precision reference of fused_gr.hpp's formulas on the SAME weights (the Q8_0 copy
+// dequantized for its own check), plus how far the Q8_0 read lands from the BF16 one; and the speed.
+//
+// gr2_parity parity: 1, 3 and 8 tokens, with and without the folded write, BF16 and Q8_0
+// gr2_parity --bench GPU time of the 2 dispatches (48 weight sets rotated) per tile, vs the 3-dispatch read
+#include "mtl_rt.h"
+#include "ref_quant.h"
+
+#include <algorithm>
+#include <cmath>
+#include <cstdio>
+#include <cstdlib>
+#include <cstring>
+#include <string>
+#include <vector>
+
+namespace {
+constexpr int N = 2560, HC = 4, LR = 320, NIN = HC * N, NR = LR + HC, MAXT = 8;
+struct GrArgs { uint32_t n_embd, hc, hc_lr, n_tok, apply; float eps; };
+struct GrArgs3 { uint32_t n_embd, hc, hc_lr, n_tok, apply; float eps; uint32_t rb_down, rb_up; };
+double median(std::vector<double> v) { std::sort(v.begin(), v.end()); return v[v.size() / 2]; }
+struct Err {
+ double se = 0, sr = 0;
+ void add(double g, double r) { se += (g - r) * (g - r); sr += r * r; }
+ double l2() const { return sr > 0 ? std::sqrt(se / sr) : std::sqrt(se); }
+};
+} // namespace
+
+int main(int argc, char** argv) {
+ const bool bench = argc > 1 && std::string(argv[1]) == "--bench";
+ mtl::Context cx;
+ const int lib = cx.compile({"quant.metal", "units.metal", "gr.metal", "gr2.metal"});
+ std::printf("device %s\n", cx.device_name().c_str());
+ const int SETS = bench ? 48 : 1;
+ const size_t bd = (size_t)LR * NIN * 2, bi = (size_t)HC * NIN * 2, bu = (size_t)NIN * LR * 2;
+ const size_t qd = (size_t)LR * NIN / 32 * 34, qi = (size_t)HC * NIN / 32 * 34, qu = (size_t)NIN * LR / 32 * 34;
+ const size_t set = bd + bi + bu + qd + qi + qu + NIN * 4;
+ mtl::Buffer W = cx.alloc(set * SETS);
+ ref::Rng rng(3);
+ {
+ uint8_t* b = W.as<uint8_t>();
+ ref::random_blocks(ref::BF16, b, LR, NIN, 11, 0.02f);
+ ref::random_blocks(ref::BF16, b + bd, HC, NIN, 22, 0.02f);
+ ref::random_blocks(ref::BF16, b + bd + bi, NIN, LR, 33, 0.1f);
+ std::vector<float> f((size_t)LR * NIN);
+ ref::dequant(ref::BF16, b, f.data(), (size_t)LR * NIN);
+ ref::quantize_q8_0(f.data(), (size_t)LR * NIN, b + bd + bi + bu);
+ ref::dequant(ref::BF16, b + bd, f.data(), (size_t)HC * NIN);
+ ref::quantize_q8_0(f.data(), (size_t)HC * NIN, b + bd + bi + bu + qd);
+ ref::dequant(ref::BF16, b + bd + bi, f.data(), (size_t)NIN * LR);
+ ref::quantize_q8_0(f.data(), (size_t)NIN * LR, b + bd + bi + bu + qd + qi);
+ float* wn = (float*)(b + bd + bi + bu + qd + qi + qu);
+ for (int i = 0; i < NIN; ++i) wn[i] = 1.0f + 0.1f * rng.sym();
+ for (int s = 1; s < SETS; ++s) std::memcpy(b + s * set, b, set);
+ }
+ mtl::Buffer R0 = cx.alloc(4 * MAXT * NIN), Rout = cx.alloc(4 * MAXT * NIN), bo = cx.alloc(4 * MAXT * N),
+ inj = cx.alloc(4 * MAXT * HC), Dprev = cx.alloc(4 * MAXT * NR * HC), D = cx.alloc(4 * MAXT * NR * HC),
+ rs = cx.alloc(4 * MAXT * HC), xp = cx.alloc(4 * (4 * MAXT * N + MAXT * N / 16)),
+ xr = cx.alloc(4 * (4 * MAXT * N + MAXT * N / 16)), xpb = cx.alloc(4 * 2 * MAXT * N),
+ R3 = cx.alloc(4 * MAXT * NIN), xn = cx.alloc(4 * MAXT * NIN), lo = cx.alloc(4 * MAXT * LR),
+ injo = cx.alloc(4 * MAXT * HC);
+ for (int i = 0; i < MAXT * NIN; ++i) R0.as<float>()[i] = rng.sym() * 2.0f;
+ for (int i = 0; i < MAXT * N; ++i) bo.as<float>()[i] = rng.sym();
+ for (int i = 0; i < MAXT * HC; ++i) inj.as<float>()[i] = rng.sym() * 3.0f;
+ // the previous read's inject partials: stream 0 carries the whole value
+ for (int t = 0; t < MAXT; ++t)
+ for (int c = 0; c < HC; ++c) Dprev.as<float>()[(t * NR + LR + c) * HC] = inj.as<float>()[t * HC + c];
+ mtl::Pipeline pprep = cx.pipeline(lib, "xprep");
+ int fails = 0;
+ for (int nt : bench ? std::vector<int>{1, 3} : std::vector<int>{1, 3, 8}) {
+ for (int qq = 0; qq < 2; ++qq) {
+ const int q8 = std::getenv("GR_Q8FIRST") ? 1 - qq : qq;
+ const int F = q8 ? 8 : 30;
+ for (int tt : bench ? std::vector<int>{1, 2, 3} : std::vector<int>{3}) {
+ for (int rps : bench ? std::vector<int>{1, 2} : std::vector<int>{1}) {
+ if (bench && tt > nt) continue;
+ const char* pre = (!q8 && std::getenv("GR_PRELOAD")) ? "gr_down3b_" : "gr_down3_";
+ const std::string dn = !q8 && std::getenv("GR_PRELOAD")
+ ? std::string(pre) + std::to_string(tt) + "_" + std::to_string(rps)
+ : std::string(pre) + std::to_string(F) + "_" + std::to_string(tt) + "_" + std::to_string(rps);
+ mtl::Pipeline pd = cx.pipeline(lib, dn, mtl::Constants().i(1, nt)),
+ pu = cx.pipeline(lib, "gr_up3_" + std::to_string(F), mtl::Constants().i(1, nt));
+ for (int apply = 0; apply < 2; ++apply) {
+ if (bench && !apply) continue;
+ GrArgs3 a{N, HC, LR, MAXT, (uint32_t)apply, 1e-6f, (uint32_t)(q8 ? NIN / 32 * 34 : NIN * 2),
+ (uint32_t)(q8 ? LR / 32 * 34 : LR * 2)};
+ auto enc = [&](int s, std::vector<mtl::Dispatch>& ds) {
+ const size_t o = (size_t)s * set;
+ const size_t od = q8 ? o + bd + bi + bu : o, oi = q8 ? o + bd + bi + bu + qd : o + bd,
+ ou = q8 ? o + bd + bi + bu + qd + qi : o + bd + bi,
+ ow = o + bd + bi + bu + qd + qi + qu;
+ mtl::Dispatch d;
+ d.p = &pd;
+ d.args = {mtl::Arg::B(W, od), mtl::Arg::B(W, oi), mtl::Arg::B(R0), mtl::Arg::B(Rout), mtl::Arg::B(bo),
+ mtl::Arg::B(Dprev), mtl::Arg::B(W, ow), mtl::Arg::B(D), mtl::Arg::B(rs), mtl::Arg::V(a)};
+ d.grid[0] = (NR + 8 * rps - 1) / (8 * rps);
+ d.grid[1] = HC;
+ d.tg[0] = 256;
+ ds.push_back(d);
+ mtl::Dispatch u;
+ u.p = &pu;
+ u.args = {mtl::Arg::B(W, ou), mtl::Arg::B(D), mtl::Arg::B(Rout), mtl::Arg::B(xp), mtl::Arg::V(a),
+ mtl::Arg::B(W, ow), mtl::Arg::B(rs)};
+ u.grid[0] = N / 16;
+ u.tg[0] = 256;
+ ds.push_back(u);
+ };
+ if (bench) {
+ std::vector<mtl::Dispatch> ds;
+ for (int k = 0; k < 96; ++k) enc(k % SETS, ds);
+ if (const char* only = std::getenv("GR_ONLY")) {
+ std::vector<mtl::Dispatch> o;
+ for (size_t i = (std::string(only) == "up"); i < ds.size(); i += 2) o.push_back(ds[i]);
+ ds = o;
+ }
+ cx.warm(ds, 0.1);
+ std::vector<double> t;
+ for (int i = 0; i < 7; ++i) t.push_back(cx.run(ds) / 96);
+ const double bytes = q8 ? qd + qi + qu : bd + bi + bu;
+ std::printf("bench ntok %d %-4s TT %d RPS %d: 2 dispatches %7.2f us %6.1f GB/s (%.2f MB)\n", nt,
+ q8 ? "Q8_0" : "BF16", tt, rps, median(t) * 1e6, bytes / median(t) / 1e9, bytes / 1e6);
+ continue;
+ }
+ std::vector<mtl::Dispatch> ds;
+ enc(0, ds);
+ cx.run(ds);
+ const uint8_t* b = W.as<uint8_t>();
+ std::vector<float> wd((size_t)LR * NIN), wi((size_t)HC * NIN), wu((size_t)NIN * LR);
+ const int ty = q8 ? ref::Q8_0 : ref::BF16;
+ ref::dequant(ty, b + (q8 ? bd + bi + bu : 0), wd.data(), wd.size());
+ ref::dequant(ty, b + (q8 ? bd + bi + bu + qd : bd), wi.data(), wi.size());
+ ref::dequant(ty, b + (q8 ? bd + bi + bu + qd + qi : bd + bi), wu.data(), wu.size());
+ const float* wn = (const float*)(b + bd + bi + bu + qd + qi + qu);
+ Err eR, elo, einj, emix;
+ for (int t = 0; t < nt; ++t) {
+ std::vector<double> r(NIN), x(NIN);
+ for (int c = 0; c < HC; ++c) {
+ const double g = apply ? 2.0 / (1.0 + std::exp(-(double)inj.as<float>()[t * HC + c] / HC)) : 0.0;
+ double ss = 0;
+ for (int d = 0; d < N; ++d) {
+ double v = R0.as<float>()[t * NIN + c * N + d];
+ if (apply) v += bo.as<float>()[t * N + d] * g;
+ r[c * N + d] = v;
+ ss += v * v;
+ }
+ const double rsv = 1.0 / std::sqrt(ss / N + 1e-6);
+ for (int d = 0; d < N; ++d) x[c * N + d] = r[c * N + d] * wn[c * N + d] * rsv;
+ }
+ for (int i = 0; i < NIN; ++i) eR.add(Rout.as<float>()[t * NIN + i], r[i]);
+ std::vector<float> lg(LR);
+ for (int k = 0; k < LR; ++k) {
+ double s = 0;
+ for (int i = 0; i < NIN; ++i) s += (double)wd[(size_t)k * NIN + i] * x[i];
+ const double z = s / HC;
+ const float* dp = D.as<float>() + (t * NR + k) * HC;
+ const float zg = (((dp[0] + dp[1]) + dp[2]) + dp[3]) / (float)HC;
+ lg[k] = zg / (1.0f + std::exp(-zg));
+ elo.add(lg[k], z / (1.0 + std::exp(-z)));
+ }
+ for (int c = 0; c < HC; ++c) {
+ double s = 0;
+ for (int i = 0; i < NIN; ++i) s += (double)wi[(size_t)c * NIN + i] * x[i];
+ const float* dp = D.as<float>() + (t * NR + LR + c) * HC;
+ einj.add(((dp[0] + dp[1]) + dp[2]) + dp[3], s);
+ }
+ for (int d = 0; d < N; ++d) {
+ double m = 0;
+ for (int c = 0; c < HC; ++c) {
+ double s = 0;
+ for (int k = 0; k < LR; ++k) s += (double)wu[(size_t)(c * N + d) * LR + k] * lg[k];
+ m += x[c * N + d] / (1.0 + std::exp(-s));
+ }
+ emix.add(xp.as<float>()[t * N + d], m / HC);
+ }
+ }
+ {
+ mtl::Dispatch d;
+ d.p = &pprep;
+ const uint32_t n = N, ntt = MAXT;
+ d.args = {mtl::Arg::B(xp), mtl::Arg::B(xr), mtl::Arg::V(n), mtl::Arg::V(ntt)};
+ d.tg[0] = 256;
+ d.grid[0] = (N / 16 * MAXT + 255) / 256;
+ cx.run({d});
+ }
+ bool planes = true;
+ for (int k = 0; k < 4; ++k)
+ planes = planes && std::memcmp(xp.as<float>() + (size_t)k * MAXT * N,
+ xr.as<float>() + (size_t)k * MAXT * N, 4 * (size_t)nt * N) == 0;
+ planes = planes && std::memcmp(xp.as<float>() + 4 * MAXT * N, xr.as<float>() + 4 * MAXT * N,
+ 4 * nt * N / 16) == 0;
+ double qdiff = -1;
+ if (q8) {
+ Err e;
+ for (int i = 0; i < nt * N; ++i) e.add(xp.as<float>()[i], xpb.as<float>()[apply * MAXT * N + i]);
+ qdiff = e.l2();
+ } else {
+ std::memcpy(xpb.as<float>() + apply * MAXT * N, xp.ptr, 4 * (size_t)MAXT * N);
+ }
+ const bool ok = eR.l2() < 1e-6 && elo.l2() < 1e-5 && einj.l2() < 1e-5 && emix.l2() < 1e-5 && planes;
+ fails += !ok;
+ char extra[96] = "";
+ if (qdiff >= 0) std::snprintf(extra, sizeof extra, ", mixed vs the BF16 read %.2e", qdiff);
+ std::printf("parity ntok %d %-4s apply %d: R' %.2e, lo %.2e, inject %.2e, mixed %.2e, planes %s%s %s\n",
+ nt, q8 ? "Q8_0" : "BF16", apply, eR.l2(), elo.l2(), einj.l2(), emix.l2(),
+ planes ? "bitwise" : "NO", extra, ok ? "PASS" : "FAIL");
+ }
+ }
+ }
+ }
+ }
+ if (bench) {
+ mtl::Pipeline pn = cx.pipeline(lib, "gr_norm"), pd = cx.pipeline(lib, "gr_down_8_8", mtl::Constants().i(1, 1)),
+ pu = cx.pipeline(lib, "gr_up", mtl::Constants().i(1, 1));
+ GrArgs a{N, HC, LR, 1, 1, 1e-6f};
+ std::vector<mtl::Dispatch> ds;
+ for (int k = 0; k < 96; ++k) {
+ const size_t o = (size_t)(k % SETS) * set;
+ mtl::Dispatch d1, d2, d3;
+ d1.p = &pn;
+ d1.args = {mtl::Arg::B(R3), mtl::Arg::B(bo), mtl::Arg::B(inj), mtl::Arg::B(W, o + bd + bi + bu + qd + qi + qu),
+ mtl::Arg::B(xn), mtl::Arg::V(a)};
+ d1.grid[0] = HC;
+ d1.tg[0] = 256;
+ d2.p = &pd;
+ d2.args = {mtl::Arg::B(W, o), mtl::Arg::B(W, o + bd), mtl::Arg::B(xn), mtl::Arg::B(lo), mtl::Arg::B(injo),
+ mtl::Arg::V(a)};
+ d2.grid[0] = LR + HC;
+ d2.tg[0] = 256;
+ d3.p = &pu;
+ d3.args = {mtl::Arg::B(W, o + bd + bi), mtl::Arg::B(lo), mtl::Arg::B(xn), mtl::Arg::B(xp), mtl::Arg::V(a)};
+ d3.grid[0] = N / 16;
+ d3.tg[0] = 256;
+ ds.push_back(d1);
+ ds.push_back(d2);
+ ds.push_back(d3);
+ }
+ cx.warm(ds, 0.1);
+ std::vector<double> t;
+ for (int i = 0; i < 7; ++i) t.push_back(cx.run(ds) / 96);
+ std::printf("bench ntok 1 BF16 3-dispatch read (gr.metal): %.2f us\n", median(t) * 1e6);
+ return 0;
+ }
+ std::printf("%s\n", fails ? "SOME FAILED" : "ALL PASS");
+ return fails ? 1 : 0;
+}
diff --git a/metal/tests/token_chain.cpp b/metal/tests/token_chain.cpp
index 4e80f6d40..f0c19673a 100644
--- a/metal/tests/token_chain.cpp
+++ b/metal/tests/token_chain.cpp
@@ -27,6 +27,7 @@ constexpr int P_MAXE = 128, P_GEXP = 16, P_GSTART = P_GEXP + P_MAXE, P_ETOK = P_
P_EW = P_ETOK + P_MAXE, P_TOKENT = P_EW + P_MAXE, P_INTS = P_TOKENT + P_MAXE, P_IGU = 4, P_IDN = 8;
struct GemvArgs { uint32_t n_in, n_out, n_tok, row_bytes, x_stride, y_stride; };
struct GrArgs { uint32_t n_embd, hc, hc_lr, n_tok, apply; float eps; };
+struct GrArgs3 { uint32_t n_embd, hc, hc_lr, n_tok, apply; float eps; uint32_t rb_down, rb_up; };
struct MoeArgs {
uint64_t gate_off, up_off, down_off, gu_stride, d_stride;
uint32_t gu_row, d_row, n_embd, n_ff, n_tok, topk, n_expert, gx_gu, gx_dn, pad;
@@ -59,6 +60,7 @@ int main(int argc, char** argv) {
if (argc < 2) { std::fprintf(stderr, "usage: token_chain <shard-1.gguf> [--ntok N] [--ctx P] [--reps R]\n"); return 2; }
int ntok = 1, ctx = 1000, reps = 10;
bool skip_qsa = false, graph = false;
+ std::string hc_mode = "3"; // 3: BF16, 3 dispatches; 2: BF16, 2 dispatches; q8: Q8_0 copies, 2 dispatches
std::string only;
for (int i = 2; i < argc; ++i) {
std::string a = argv[i];
@@ -67,6 +69,7 @@ int main(int argc, char** argv) {
else if (a == "--reps") reps = std::atoi(argv[++i]);
else if (a == "--skip-qsa") skip_qsa = true;
else if (a == "--graph") graph = true;
+ else if (a == "--hc") hc_mode = argv[++i];
else if (a == "--only") only = argv[++i];
}
gguf::File f;
@@ -90,7 +93,7 @@ int main(int argc, char** argv) {
return *t;
};
- const int lib = cx.compile({"quant.metal", "units.metal", "moe.metal", "gemv.metal", "gr.metal", "glue.metal"});
+ const int lib = cx.compile({"quant.metal", "units.metal", "moe.metal", "gemv.metal", "gr.metal", "gr2.metal", "glue.metal"});
const int lgdn = cx.compile({"gdn.metal"}, "#define NO_GGML_COMMON 1\n");
const int lqsa = cx.compile({"qsa.metal"}, "#define NO_GGML_COMMON 1\n");
const int lsmp = cx.compile({"sample.metal"}, "#define NO_GGML_COMMON 1\n");
@@ -196,8 +199,72 @@ int main(int argc, char** argv) {
const mtl::Pipeline* pam1 = Pn(lsmp, "argmax_part", "argmax_part", {});
const mtl::Pipeline* pam2 = Pn(lsmp, "argmax_final", "argmax_final", {});
+ // the 2-dispatch read: residual and partial-dot ping-pong buffers, rs; the Q8_0 copies of the HC matrices
+ mtl::Buffer Rb[2] = {R, cx.alloc(4 * MAXT * HC * N)}, Db[2] = {cx.alloc(4 * MAXT * (LR + HC) * HC), cx.alloc(4 * MAXT * (LR + HC) * HC)},
+ rsb = cx.alloc(4 * MAXT * HC);
+ int cur_r = 0, cur_d = 0;
+ std::map<std::string, size_t> q8off;
+ mtl::Buffer Q8;
+ if (hc_mode == "q8") {
+ size_t tot = 0;
+ for (const auto& kv : f.tensors) {
+ const gguf::Tensor& t = kv.second;
+ if (t.type != ref::BF16 || t.name.find("hc_") == std::string::npos || t.name.find("_norm") != std::string::npos) continue;
+ uint64_t ne = 1;
+ for (uint64_t d : t.shape) ne *= d;
+ q8off[t.name] = tot;
+ tot += ne / 32 * 34;
+ }
+ Q8 = cx.alloc((tot + 4095) / 4096 * 4096);
+ const double t0 = mtl::now_s();
+ std::vector<float> tmp;
+ for (const auto& kv : q8off) {
+ const gguf::Tensor& t = *f.find(kv.first);
+ uint64_t ne = 1;
+ for (uint64_t d : t.shape) ne *= d;
+ tmp.resize(ne);
+ ref::dequant(ref::BF16, (const uint8_t*)f.map + t.offset, tmp.data(), ne);
+ ref::quantize_q8_0(tmp.data(), ne, Q8.as<uint8_t>() + kv.second);
+ }
+ std::printf("HC Q8_0 copies: %zu tensors, %.1f MB, quantized in %.1f s\n", q8off.size(), tot / 1e6, mtl::now_s() - t0);
+ }
int cur_inj = 0;
auto gr_read = [&](const std::string& pre, bool apply, const Act& out, bool final_) {
+ if (hc_mode != "3") {
+ const bool q8 = hc_mode == "q8";
+ const gguf::Tensor& tn = T(pre + "_norm.weight");
+ const gguf::Tensor& tdn = T(pre + "_down.weight");
+ const gguf::Tensor& tup = T(pre + "_up.weight");
+ const gguf::Tensor& tin = final_ ? tdn : T(pre + "_inject.weight");
+ const int tt = std::min(ntok, 3);
+ const std::string dn = std::string("gr_down3_") + (q8 ? "8_" : "30_") + std::to_string(tt) + "_2";
+ const std::string up = std::string("gr_up3_") + (q8 ? "8" : "30");
+ GrArgs3 a{N, HC, LR, MAXT, apply ? 1u : 0u, 1e-6f, (uint32_t)(q8 ? HC * N / 32 * 34 : HC * N * 2),
+ (uint32_t)(q8 ? LR / 32 * 34 : LR * 2)};
+ const mtl::Buffer& WB = q8 ? Q8 : W;
+ const size_t od = q8 ? q8off.at(tdn.name) : tdn.offset, oi = q8 ? q8off.at(tin.name) : tin.offset,
+ ou = q8 ? q8off.at(tup.name) : tup.offset;
+ mtl::Dispatch d;
+ d.p = Pn(lib, dn, dn + "#" + std::to_string(ntok), mtl::Constants().i(1, ntok));
+ d.args = {mtl::Arg::B(WB, od), mtl::Arg::B(WB, oi), mtl::Arg::B(Rb[cur_r]), mtl::Arg::B(Rb[1 - cur_r]),
+ mtl::Arg::B(bo), mtl::Arg::B(Db[cur_d]), mtl::Arg::B(W, tn.offset), mtl::Arg::B(Db[1 - cur_d]),
+ mtl::Arg::B(rsb), mtl::Arg::V(a)};
+ d.grid[0] = (LR + HC + 15) / 16;
+ d.grid[1] = HC;
+ d.tg[0] = 256;
+ const double wb = q8 ? (tdn.bytes + (final_ ? 0 : tin.bytes)) * 34.0 / 64.0 : (double)tdn.bytes + (final_ ? 0 : tin.bytes);
+ push(d, "hc", wb);
+ cur_r = 1 - cur_r;
+ cur_d = 1 - cur_d;
+ mtl::Dispatch u;
+ u.p = Pn(lib, up, up + "#" + std::to_string(ntok), mtl::Constants().i(1, ntok));
+ u.args = {mtl::Arg::B(WB, ou), mtl::Arg::B(Db[cur_d]), mtl::Arg::B(Rb[cur_r]), mtl::Arg::B(out.b), mtl::Arg::V(a),
+ mtl::Arg::B(W, tn.offset), mtl::Arg::B(rsb)};
+ u.grid[0] = N / 16;
+ u.tg[0] = 256;
+ push(u, "hc", q8 ? tup.bytes * 34.0 / 64.0 : (double)tup.bytes);
+ return;
+ }
const gguf::Tensor& tn = T(pre + "_norm.weight");
const gguf::Tensor& tdn = T(pre + "_down.weight");
const gguf::Tensor& tup = T(pre + "_up.weight");
@@ -433,6 +500,7 @@ int main(int argc, char** argv) {
while (mtl::now_s() - tw < 1.0) run();
std::vector<double> t;
for (int i = 0; i < reps; ++i) t.push_back(run());
+ std::printf("HC read: %s\n", hc_mode == "3" ? "BF16, 3 dispatches" : hc_mode == "2" ? "BF16, 2 dispatches" : "Q8_0, 2 dispatches");
std::printf("encoding: %s\n", graph ? "concurrent encoder, barriers at dependencies" : "serial encoder");
const double m = median(t);
std::printf("decode step (%d token(s)): GPU %.3f ms (min %.3f, max %.3f) -> %.1f GB/s effective; %.1f tok/s if "