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: fused GDN layer step (conv, L2 norms, gates, delta rule, output norm) for a window, commit/verify

Niko122189edfd7c3b89
diff --git a/metal/kernels/gdn.metal b/metal/kernels/gdn.metal
new file mode 100644
index 000000000..e4260db92
--- /dev/null
+++ b/metal/kernels/gdn.metal
@@ -0,0 +1,128 @@
+// metal/kernels/gdn.metal - one GDN (gated delta-net) layer's recurrence for a window of tokens, fused end to end:
+//
+// conv (4 taps, history [channels][3] oldest first) -> SiLU, on q (16 heads), k (16), v (48 heads) of 128
+// q, k: L2 norm as native_gdn_l2_norm (rsqrt(sum/128 + eps/128), then x 1/sqrt(128), two roundings)
+// gate = exp(softplus(alpha + dt) * a) (softplus = v > 20 ? v : log1p(exp(v))), beta = sigmoid(beta)
+// kv_j = sum_i S[i][j] k[i]; delta_j = (v_j - gate * kv_j) * beta; S = gate * S + k[i] delta_j
+// o_j = (sum_i S[i][j] q[i]) / sqrt(128); y_j = o_j * rsqrt(mean(o^2) + eps) * gamma_j * sigmoid(z_j)
+//
+// State layout as Strata's: S[(i * h_v + h) * 128 + j]. Value head h reads q/k head h % h_k.
+// One threadgroup per value head, 512 threads = 16 simdgroups: simdgroup s holds columns j = 32 (s % 4) + lane and
+// rows i = 32 (s / 4) .. + 32 of the head's 128 x 128 state in registers. GDN_NTOK tokens run in order; with
+// `commit` the state and the conv history are written back after the last one (a verify window runs without commit,
+// the fold of m accepted tokens is the same kernel with GDN_NTOK = m and commit).
+
+constant int GDN_NTOK [[function_constant(2)]];
+
+struct GdnArgs {
+ uint h_k; // 16
+ uint h_v; // 48
+ uint channels; // 10240 = (2 h_k + h_v) * 128
+ uint commit;
+ float eps; // 1e-6
+};
+
+kernel void gdn_step(device float* state [[buffer(0)]], device float* hist [[buffer(1)]],
+ device const float* qkv [[buffer(2)]], device const float* alpha [[buffer(3)]],
+ device const float* beta [[buffer(4)]], device const float* z [[buffer(5)]],
+ device const float* conv_w [[buffer(6)]], device const float* dt [[buffer(7)]],
+ device const float* ssm_a [[buffer(8)]], device const float* gamma [[buffer(9)]],
+ device float* y [[buffer(10)]], constant GdnArgs& a [[buffer(11)]],
+ 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 S = 128;
+ threadgroup float qs[S], ks[S], vs[S];
+ threadgroup float red[4][S];
+ threadgroup float part[16];
+ threadgroup float gb[2];
+ const int h = int(tg.x), hk = h % int(a.h_k), hv = int(a.h_v);
+ const int cb = sg & 3, ib = sg >> 2;
+ const int j = 32 * cb + lane, i0 = 32 * ib;
+ const float scale = 1.0f / sqrt(float(S));
+
+ // the channel this thread convolves: 0..127 q of head hk, 128..255 k of head hk, 256..383 v of head h
+ int ch = -1;
+ if (tid < 128) ch = hk * S + tid;
+ else if (tid < 256) ch = int(a.h_k) * S + hk * S + (tid - 128);
+ else if (tid < 384) ch = 2 * int(a.h_k) * S + h * S + (tid - 256);
+ float hst[3] = {0.0f, 0.0f, 0.0f}, cw[4] = {0.0f, 0.0f, 0.0f, 0.0f};
+ if (ch >= 0) {
+ for (int k = 0; k < 3; ++k) hst[k] = hist[ch * 3 + k];
+ for (int k = 0; k < 4; ++k) cw[k] = conv_w[ch * 4 + k];
+ }
+ float st[32];
+ for (int r = 0; r < 32; ++r) st[r] = state[((i0 + r) * hv + h) * S + j];
+
+ for (int t = 0; t < GDN_NTOK; ++t) {
+ // conv + SiLU
+ float cv = 0.0f;
+ if (ch >= 0) {
+ const float in = qkv[t * int(a.channels) + ch];
+ const float vals[4] = {hst[0], hst[1], hst[2], in};
+ float s = 0.0f;
+ for (int k = 0; k < 4; ++k) s = fma(vals[k], cw[k], s);
+ s = s + 0.0f;
+ cv = s / (1.0f + exp(-s));
+ hst[0] = hst[1];
+ hst[1] = hst[2];
+ hst[2] = in;
+ }
+ // L2 norms of q (threads 0..127 = simdgroups 0..3) and k (128..255 = 4..7)
+ const float ssq = simd_sum(cv * cv);
+ if (lane == 0) part[sg] = ssq;
+ if (tid == 0) {
+ const float v = alpha[t * hv + h] + dt[h];
+ // log1p(e^v) (Kahan: log(u) * e / (u - 1), u = 1 + e; exact where 1 + e rounds to 1)
+ const float e = exp(v), u = 1.0f + e;
+ const float sp = v > 20.0f ? v : (u == 1.0f ? e : log(u) * e / (u - 1.0f));
+ gb[0] = exp(sp * ssm_a[h]);
+ gb[1] = 1.0f / (1.0f + exp(-beta[t * hv + h]));
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ if (tid < 256) {
+ const int base = tid < 128 ? 0 : 4;
+ const float tot = (part[base] + part[base + 1]) + (part[base + 2] + part[base + 3]);
+ const float rs = rsqrt(tot / float(S) + a.eps / float(S));
+ const float nv = (rs * cv) * scale;
+ if (tid < 128) qs[tid] = nv;
+ else ks[tid - 128] = nv;
+ } else if (tid < 384) {
+ vs[tid - 256] = cv;
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ const float g = gb[0], be = gb[1];
+ // kv_j
+ float kv = 0.0f;
+ for (int r = 0; r < 32; ++r) kv = fma(st[r], ks[i0 + r], kv);
+ red[ib][j] = kv;
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ kv = (red[0][j] + red[1][j]) + (red[2][j] + red[3][j]);
+ const float delta = (vs[j] - g * kv) * be;
+ float o = 0.0f;
+ for (int r = 0; r < 32; ++r) {
+ st[r] = fma(g, st[r], ks[i0 + r] * delta);
+ o = fma(st[r], qs[i0 + r], o);
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ red[ib][j] = o;
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ // the readout and the output norm: column j's o (every i-block thread of the column holds the same value)
+ o = ((red[0][j] + red[1][j]) + (red[2][j] + red[3][j])) * scale;
+ const float osq = ib == 0 ? simd_sum(o * o) : 0.0f;
+ if (ib == 0 && lane == 0) part[cb] = osq;
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ if (ib == 0) {
+ const float tot = (part[0] + part[1]) + (part[2] + part[3]);
+ const float rs = rsqrt(tot / float(S) + a.eps);
+ const float zz = z[t * hv * S + h * S + j];
+ y[t * hv * S + h * S + j] = ((rs * o) * gamma[j]) * (1.0f / (1.0f + exp(-zz)));
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ }
+ if (a.commit) {
+ for (int r = 0; r < 32; ++r) state[((i0 + r) * hv + h) * S + j] = st[r];
+ // q/k history: the threadgroups h < h_k own their q/k head (h == hk); v history: every head its own
+ if (ch >= 0 && (tid >= 256 || h < int(a.h_k)))
+ for (int k = 0; k < 3; ++k) hist[ch * 3 + k] = hst[k];
+ }
+}
diff --git a/metal/tests/gdn_parity.cpp b/metal/tests/gdn_parity.cpp
new file mode 100644
index 000000000..50af3e25a
--- /dev/null
+++ b/metal/tests/gdn_parity.cpp
@@ -0,0 +1,163 @@
+// metal/tests/gdn_parity.cpp - the fused GDN layer step (gdn.metal) against a double-precision CPU reference of the
+// native contract, the window properties, and its speed.
+//
+// gdn_parity parity for windows of 1..4 tokens: y, the committed state and conv history; a verify
+// window leaves the state untouched; its first m outputs are bitwise a fold of m
+// gdn_parity --bench GPU time per layer: 36 distinct layer states rotated (113 MB, beyond the SLC)
+#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 S = 128, HK = 16, HV = 48, C = (2 * HK + HV) * S, MAXT = 8;
+struct GdnArgs { uint32_t h_k, h_v, channels, commit; float eps; };
+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({"gdn.metal"}, "#define NO_GGML_COMMON 1\n");
+ std::printf("device %s\n", cx.device_name().c_str());
+ const int LAYERS = bench ? 36 : 1;
+ const size_t st_elems = (size_t)S * HV * S;
+ mtl::Buffer state = cx.alloc(4 * st_elems * LAYERS), st0 = cx.alloc(4 * st_elems), hist = cx.alloc(4 * C * 3 * LAYERS),
+ h0 = cx.alloc(4 * C * 3), qkv = cx.alloc(4 * C * MAXT), al = cx.alloc(4 * HV * MAXT),
+ be = cx.alloc(4 * HV * MAXT), z = cx.alloc(4 * HV * S * MAXT), cw = cx.alloc(4 * C * 4),
+ dt = cx.alloc(4 * HV), sa = cx.alloc(4 * HV), gm = cx.alloc(4 * S), y = cx.alloc(4 * HV * S * MAXT),
+ y2 = cx.alloc(4 * HV * S * MAXT);
+ ref::Rng r(17);
+ for (size_t i = 0; i < st_elems; ++i) st0.as<float>()[i] = r.sym() * 0.1f;
+ for (int i = 0; i < C * 3; ++i) h0.as<float>()[i] = r.sym();
+ for (int i = 0; i < C * MAXT; ++i) qkv.as<float>()[i] = r.sym() * 2.0f;
+ for (int i = 0; i < HV * MAXT; ++i) { al.as<float>()[i] = r.sym() * 2.0f; be.as<float>()[i] = r.sym() * 2.0f; }
+ for (int i = 0; i < HV * S * MAXT; ++i) z.as<float>()[i] = r.sym() * 2.0f;
+ for (int i = 0; i < C * 4; ++i) cw.as<float>()[i] = r.sym() * 0.5f;
+ for (int i = 0; i < HV; ++i) { dt.as<float>()[i] = r.sym(); sa.as<float>()[i] = -std::exp(r.sym()); }
+ for (int i = 0; i < S; ++i) gm.as<float>()[i] = 1.0f + 0.2f * r.sym();
+ for (int l = 0; l < LAYERS; ++l) {
+ std::memcpy(state.as<float>() + l * st_elems, st0.ptr, 4 * st_elems);
+ std::memcpy(hist.as<float>() + l * C * 3, h0.ptr, 4 * C * 3);
+ }
+ auto disp = [&](const mtl::Pipeline& p, int layer, int commit, const mtl::Buffer& out) {
+ GdnArgs a{HK, HV, C, (uint32_t)commit, 1e-6f};
+ mtl::Dispatch d;
+ d.p = &p;
+ d.args = {mtl::Arg::B(state, 4 * st_elems * layer), mtl::Arg::B(hist, 4 * (size_t)C * 3 * layer), mtl::Arg::B(qkv),
+ mtl::Arg::B(al), mtl::Arg::B(be), mtl::Arg::B(z), mtl::Arg::B(cw), mtl::Arg::B(dt), mtl::Arg::B(sa),
+ mtl::Arg::B(gm), mtl::Arg::B(out), mtl::Arg::V(a)};
+ d.grid[0] = HV;
+ d.tg[0] = 512;
+ return d;
+ };
+ if (bench) {
+ for (int nt : {1, 2, 3, 4}) {
+ mtl::Pipeline p = cx.pipeline(lib, "gdn_step", mtl::Constants().i(2, nt));
+ for (int commit : {1, 0}) {
+ std::vector<mtl::Dispatch> ds;
+ for (int k = 0; k < 72; ++k) ds.push_back(disp(p, k % LAYERS, commit, y));
+ cx.warm(ds, 0.1);
+ std::vector<double> t;
+ for (int i = 0; i < 7; ++i) t.push_back(cx.run(ds) / 72);
+ const double m = median(t), bytes = 4.0 * st_elems * (commit ? 2 : 1);
+ std::printf("gdn_step ntok %d %-7s %7.2f us per layer state %.1f MB at %6.1f GB/s (x36 layers: %.3f ms)\n",
+ nt, commit ? "commit" : "verify", m * 1e6, bytes / 1e6, bytes / m / 1e9, 36 * m * 1e3);
+ }
+ }
+ return 0;
+ }
+ int fails = 0;
+ for (int nt = 1; nt <= 4; ++nt) {
+ mtl::Pipeline p = cx.pipeline(lib, "gdn_step", mtl::Constants().i(2, nt));
+ // verify: state untouched
+ std::memcpy(state.ptr, st0.ptr, 4 * st_elems);
+ std::memcpy(hist.ptr, h0.ptr, 4 * C * 3);
+ cx.run({disp(p, 0, 0, y2)});
+ const bool untouched = std::memcmp(state.ptr, st0.ptr, 4 * st_elems) == 0 && std::memcmp(hist.ptr, h0.ptr, 4 * C * 3) == 0;
+ cx.run({disp(p, 0, 1, y)});
+ const bool same_y = std::memcmp(y.ptr, y2.ptr, 4 * HV * S * nt) == 0;
+ // the reference
+ std::vector<double> Sd(st_elems), Hd(C * 3);
+ for (size_t i = 0; i < st_elems; ++i) Sd[i] = st0.as<float>()[i];
+ for (int i = 0; i < C * 3; ++i) Hd[i] = h0.as<float>()[i];
+ Err ey, es, eh;
+ for (int t = 0; t < nt; ++t) {
+ std::vector<double> cv(C);
+ for (int c = 0; c < C; ++c) {
+ const double in = qkv.as<float>()[t * C + c];
+ double s = Hd[c * 3] * cw.as<float>()[c * 4] + Hd[c * 3 + 1] * cw.as<float>()[c * 4 + 1] +
+ Hd[c * 3 + 2] * cw.as<float>()[c * 4 + 2] + in * cw.as<float>()[c * 4 + 3];
+ cv[c] = s / (1.0 + std::exp(-s));
+ Hd[c * 3] = Hd[c * 3 + 1];
+ Hd[c * 3 + 1] = Hd[c * 3 + 2];
+ Hd[c * 3 + 2] = in;
+ }
+ for (int hh = 0; hh < 2 * HK; ++hh) {
+ double ss = 0;
+ for (int i = 0; i < S; ++i) ss += cv[hh * S + i] * cv[hh * S + i];
+ const double rs = 1.0 / std::sqrt(ss / S + 1e-6 / S);
+ for (int i = 0; i < S; ++i) cv[hh * S + i] = cv[hh * S + i] * rs / std::sqrt((double)S);
+ }
+ for (int h = 0; h < HV; ++h) {
+ const int hk = h % HK;
+ const double* q = &cv[hk * S];
+ const double* k = &cv[HK * S + hk * S];
+ const double* v = &cv[2 * HK * S + h * S];
+ const double av = (double)al.as<float>()[t * HV + h] + dt.as<float>()[h];
+ const double sp = av > 20 ? av : std::log1p(std::exp(av));
+ const double g = std::exp(sp * sa.as<float>()[h]);
+ const double b = 1.0 / (1.0 + std::exp(-(double)be.as<float>()[t * HV + h]));
+ std::vector<double> o(S);
+ for (int jj = 0; jj < S; ++jj) {
+ double kv = 0;
+ for (int i = 0; i < S; ++i) kv += Sd[((size_t)i * HV + h) * S + jj] * k[i];
+ const double delta = (v[jj] - g * kv) * b;
+ double acc = 0;
+ for (int i = 0; i < S; ++i) {
+ double& sv = Sd[((size_t)i * HV + h) * S + jj];
+ sv = g * sv + k[i] * delta;
+ acc += sv * q[i];
+ }
+ o[jj] = acc / std::sqrt((double)S);
+ }
+ double ss = 0;
+ for (int jj = 0; jj < S; ++jj) ss += o[jj] * o[jj];
+ const double rs = 1.0 / std::sqrt(ss / S + 1e-6);
+ for (int jj = 0; jj < S; ++jj) {
+ const double zz = z.as<float>()[t * HV * S + h * S + jj];
+ ey.add(y.as<float>()[t * HV * S + h * S + jj], o[jj] * rs * gm.as<float>()[jj] / (1.0 + std::exp(-zz)));
+ }
+ }
+ }
+ for (size_t i = 0; i < st_elems; ++i) es.add(state.as<float>()[i], Sd[i]);
+ for (int i = 0; i < C * 3; ++i) eh.add(hist.as<float>()[i], Hd[i]);
+ // fold property: a window of nt + 1 tokens (no commit) gives bitwise the same first nt outputs
+ bool prefix = true;
+ if (nt < 4) {
+ mtl::Pipeline p2 = cx.pipeline(lib, "gdn_step", mtl::Constants().i(2, nt + 1));
+ std::memcpy(state.ptr, st0.ptr, 4 * st_elems);
+ std::memcpy(hist.ptr, h0.ptr, 4 * C * 3);
+ cx.run({disp(p2, 0, 0, y2)});
+ prefix = std::memcmp(y.ptr, y2.ptr, 4 * HV * S * nt) == 0;
+ }
+ const bool ok = untouched && same_y && prefix && ey.l2() < 1e-5 && es.l2() < 1e-5 && eh.l2() == 0;
+ fails += !ok;
+ std::printf("gdn parity ntok %d: y rel L2 %.2e, state %.2e, history %.1e; verify leaves state: %s, verify y == "
+ "commit y: %s, first %d of a longer window bitwise: %s %s\n", nt, ey.l2(), es.l2(), eh.l2(),
+ untouched ? "yes" : "NO", same_y ? "yes" : "NO", nt, prefix ? "yes" : "NO", ok ? "PASS" : "FAIL");
+ }
+ std::printf("%s\n", fails ? "SOME FAILED" : "ALL PASS");
+ return fails ? 1 : 0;
+}