From 280885fda0f7af37289bcb4251a64cad63d5175e Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 30 Oct 2026 00:49:57 +0100 Subject: [PATCH 1/5] Metal: GDN prompt scan benchmark (sequential vs chunked), extra gdn_scanr TB instantiations, opt-in STRATA_METAL_GDN_SCAN --- metal/kernels/gdn_prompt.metal | 6 + metal/src/engine/prompt_chain.inc | 2 +- metal/src/engine/window.cpp | 14 +- metal/tests/gdn_chunk_bench.cpp | 282 ++++++++++++++++++++++++++++++ 4 files changed, 302 insertions(+), 2 deletions(-) create mode 100644 metal/tests/gdn_chunk_bench.cpp diff --git a/metal/kernels/gdn_prompt.metal b/metal/kernels/gdn_prompt.metal index b2d530b1..31bb0ce4 100644 --- a/metal/kernels/gdn_prompt.metal +++ b/metal/kernels/gdn_prompt.metal @@ -321,6 +321,12 @@ template [[host_name("gdn_scanr_2")]] kernel decltype(gdn_scan_r<2, 16>) gdn_sca template [[host_name("gdn_scanr_4")]] kernel decltype(gdn_scan_r<4, 16>) gdn_scan_r<4, 16>; template [[host_name("gdn_scanr_8")]] kernel decltype(gdn_scan_r<8, 16>) gdn_scan_r<8, 16>; template [[host_name("gdn_scanr_4_8")]] kernel decltype(gdn_scan_r<4, 8>) gdn_scan_r<4, 8>; +template [[host_name("gdn_scanr_4_4")]] kernel decltype(gdn_scan_r<4, 4>) gdn_scan_r<4, 4>; +template [[host_name("gdn_scanr_4_2")]] kernel decltype(gdn_scan_r<4, 2>) gdn_scan_r<4, 2>; +template [[host_name("gdn_scanr_8_8")]] kernel decltype(gdn_scan_r<8, 8>) gdn_scan_r<8, 8>; +template [[host_name("gdn_scanr_8_4")]] kernel decltype(gdn_scan_r<8, 4>) gdn_scan_r<8, 4>; +template [[host_name("gdn_scanr_2_8")]] kernel decltype(gdn_scan_r<2, 8>) gdn_scan_r<2, 8>; +template [[host_name("gdn_scanr_2_4")]] kernel decltype(gdn_scan_r<2, 4>) gdn_scan_r<2, 4>; // ---- the chunked form (chunks of GC = 32 tokens), the WY / UT form of the gated delta rule. With G_t the product // of the chunk's gates up to t (log space: lg_t) and S0 the state entering the chunk: diff --git a/metal/src/engine/prompt_chain.inc b/metal/src/engine/prompt_chain.inc index f9b24133..cf1d487d 100644 --- a/metal/src/engine/prompt_chain.inc +++ b/metal/src/engine/prompt_chain.inc @@ -207,7 +207,7 @@ bool Window::pc_chunk(const int64_t* tokens, int nT, int64_t pos0, std::string& mtl::Arg::B(W_, T(bl + "ssm_a").offset), mtl::Arg::B(b.gqn), mtl::Arg::B(b.gkn), mtl::Arg::B(b.gvc), mtl::Arg::B(b.ggb), mtl::Arg::B(b.gkq), mtl::Arg::B(ghist_[1 - hp][(size_t) gi]), mtl::Arg::V(ga)}, 16 + 24, nT, 256); - D(P_(b.lgdn, "gdn_scanr_4", mtl::Constants().i(6, 0)), + D(P_(b.lgdn, gdn_scan_name(), mtl::Constants().i(6, 0)), {mtl::Arg::B(gst_[(size_t) gi]), mtl::Arg::B(b.gqn), mtl::Arg::B(b.gkn), mtl::Arg::B(b.gvc), mtl::Arg::B(b.ggb), mtl::Arg::B(b.gkq), mtl::Arg::B(b.go), mtl::Arg::V(ga)}, 48 * 4, 1, 32 * 4); diff --git a/metal/src/engine/window.cpp b/metal/src/engine/window.cpp index add35c0e..70758170 100644 --- a/metal/src/engine/window.cpp +++ b/metal/src/engine/window.cpp @@ -50,6 +50,18 @@ namespace strata::gpu { uint64_t purge_device_allocations(size_t min_bytes); } namespace strata::metal_engine { +// The prompt GDN scan kernel. STRATA_METAL_GDN_SCAN names an instantiation of gdn_scan_r in gdn_prompt.metal +// (gdn_scanr_4_8, gdn_scanr_4_4, ...): IB simdgroups a threadgroup (the thread count is read from the name), TB tokens staged. +// Unset: gdn_scanr_4 (IB 4, TB 16), the production default. Only the four-simdgroup names are accepted here. +static const char* gdn_scan_name() { + static const std::string name = [] { + const char* e = std::getenv("STRATA_METAL_GDN_SCAN"); + const std::string s = e ? e : ""; + return (s == "gdn_scanr_4_8" || s == "gdn_scanr_4_4" || s == "gdn_scanr_4_2") ? s : std::string("gdn_scanr_4"); + }(); + return name.c_str(); +} + namespace { constexpr int N = 2560, HC = 4, LR = 320, NFF = 640, TOPK = 10, NEXP = 512, MAXT = 8, NVOCAB_MAX = 248320; @@ -2358,7 +2370,7 @@ bool Window::prompt_chunk(const int32_t* tokens, int Tn, int64_t pos0, std::stri mtl::Arg::B(p.al), mtl::Arg::B(p.be), mtl::Arg::B(W_, TN(b + "ssm_dt.bias").offset), mtl::Arg::B(W_, TN(b + "ssm_a").offset), mtl::Arg::B(p.gqn), mtl::Arg::B(p.gkn), mtl::Arg::B(p.gvc), mtl::Arg::B(p.ggb), mtl::Arg::B(p.gkq), mtl::Arg::B(ghist_[1 - hp_][(size_t) gi]), mtl::Arg::V(ga)}, 16 + 24, T, 256); - D(PP(p.lgdn, "gdn_scanr_4", mtl::Constants().i(6, 0), "gdn_scanr_4"), + D(PP(p.lgdn, gdn_scan_name(), mtl::Constants().i(6, 0), gdn_scan_name()), {mtl::Arg::B(gst_[(size_t) gi]), mtl::Arg::B(p.gqn), mtl::Arg::B(p.gkn), mtl::Arg::B(p.gvc), mtl::Arg::B(p.ggb), mtl::Arg::B(p.gkq), mtl::Arg::B(p.go), mtl::Arg::V(ga)}, 48 * 4, 1, 32 * 4); D(PP(p.lgdn, "gdn_post"), {mtl::Arg::B(p.go), mtl::Arg::B(p.z), mtl::Arg::B(W_, TN(b + "ssm_norm.weight").offset), diff --git a/metal/tests/gdn_chunk_bench.cpp b/metal/tests/gdn_chunk_bench.cpp new file mode 100644 index 00000000..870baa9c --- /dev/null +++ b/metal/tests/gdn_chunk_bench.cpp @@ -0,0 +1,282 @@ +// metal/tests/gdn_chunk_bench.cpp - GDN prompt stage microbenchmark and numerical check (30 Oct GDN-M, phase 1). +// The sequential scans of gdn_prompt.metal (gdn_scanr_2/4/8, production = gdn_scanr_4) against the chunked C = 32 form +// (gdn_cprep -> gdn_cstate -> gdn_cout) at the real Flash-Next shape (h_k 16, h_v 48, S 128, 10240 conv channels), +// T = 512 .. 32768, with the same gdn_pre in front and gdn_post behind (the whole GDN stage). Checks against an FP64 +// sequential oracle on a few heads (output o and final state), the pipeline thread limits, and continuation (a call +// split in two, chunked or sequential on either side, the second call on buffer offsets). +// gdn_chunk_bench [--T 512,2048,..] [--check] [--regime normal|strong] [--heads 0,17,47] [--reps 5] [--noscan] +#include "mtl_rt.h" +#include "ref_quant.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace { +constexpr int HK = 16, HV = 48, CH = 10240, S = 128, GC = 32, NSC = 14; +struct GdnPArgs { uint32_t n_tok, h_k, h_v, channels; float eps; uint32_t f32; }; +double median(std::vector v) { std::sort(v.begin(), v.end()); return v[v.size() / 2]; } +std::vector ints(const char* s) { + std::vector r; + for (const char* p = s; *p;) { r.push_back(std::atoi(p)); while (*p && *p != ',') ++p; if (*p) ++p; } + return r; +} +} // namespace + +int main(int argc, char** argv) { + std::vector Ts = {512, 1024, 2048, 4096, 8192, 16384, 32768}, heads = {0, 17, 47}; + bool check = false, noscan = false, strong = false; + int reps = 5; + for (int i = 1; i < argc; ++i) { + std::string a = argv[i]; + if (a == "--T") Ts = ints(argv[++i]); + else if (a == "--heads") heads = ints(argv[++i]); + else if (a == "--check") check = true; + else if (a == "--noscan") noscan = true; + else if (a == "--regime") strong = std::string(argv[++i]) == "strong"; + else if (a == "--reps") reps = std::atoi(argv[++i]); + } + const int TMAX = *std::max_element(Ts.begin(), Ts.end()); + mtl::Context cx; + const int lib = cx.compile({"gdn_prompt.metal"}, "#define NO_GGML_COMMON 1\n"); + std::printf("device %s, regime %s, TMAX %d\n", cx.device_name().c_str(), strong ? "strong-decay" : "normal", TMAX); + auto F = [&](size_t n) { return cx.alloc(4 * n); }; + const size_t NCM = (TMAX + GC - 1) / GC; + mtl::Buffer qkv = F((size_t)TMAX * CH), al = F((size_t)TMAX * HV), be = F((size_t)TMAX * HV), z = F((size_t)TMAX * HV * S), + cw = F(CH * 4), dt = F(HV), sa = F(HV), gam = F(S), st0 = F((size_t)S * HV * S), stX = F((size_t)S * HV * S), + stRef = F((size_t)S * HV * S), h0 = F(CH * 3), hOut = F(CH * 3), yh = cx.alloc(2 * (size_t)TMAX * HV * S), + yB = F((size_t)TMAX * HV * S), qn = F((size_t)TMAX * HK * S), kn = F((size_t)TMAX * HK * S), + vc = F((size_t)TMAX * HV * S), gb = F(2 * (size_t)TMAX * HV), kq = F((size_t)TMAX * HK), + o = F((size_t)TMAX * HV * S), oRef = F((size_t)TMAX * HV * S), cU = F((size_t)HV * NCM * GC * S), + cW = F((size_t)HV * NCM * GC * S), clg = F((size_t)HV * NCM * GC), cD = F((size_t)HV * NCM * GC * S); + ref::Rng r(21); + for (size_t i = 0; i < (size_t)TMAX * CH; ++i) qkv.as()[i] = r.sym() * 2.0f; + for (size_t i = 0; i < (size_t)TMAX * HV; ++i) { al.as()[i] = r.sym() * 3.0f; be.as()[i] = r.sym() * 2.0f; } + for (size_t i = 0; i < (size_t)TMAX * HV * S; ++i) z.as()[i] = r.sym() * 2.0f; + for (int i = 0; i < CH * 4; ++i) cw.as()[i] = r.sym() * 0.6f; + for (int i = 0; i < HV; ++i) { dt.as()[i] = r.sym(); sa.as()[i] = strong ? -5.0f - r.uni() * 25.0f : -0.2f - r.uni() * 2.0f; } + for (int i = 0; i < S; ++i) gam.as()[i] = 0.5f + r.uni(); + for (int i = 0; i < S * HV * S; ++i) st0.as()[i] = r.sym() * 0.1f; + for (int i = 0; i < CH * 3; ++i) h0.as()[i] = r.sym(); + + mtl::Pipeline pre = cx.pipeline(lib, "gdn_pre"), post = cx.pipeline(lib, "gdn_post"); + // the existing sequential scans: {name, threadgroups, threads}; index 1 = gdn_scanr_4 = production + struct Sv { const char* nm; int grid, tg; }; + const Sv svs[NSC] = {{"gdn_scanr_2", HV * 4, 64}, {"gdn_scanr_4", HV * 4, 128}, {"gdn_scanr_8", HV * 4, 256}, + {"gdn_scanr_4_8", HV * 4, 128}, {"gdn_scan_v", HV * 4, 256}, {"gdn_scan_1", HV * 4, 32}, + {"gdn_scan_2", HV * 2, 64}, {"gdn_scan_4", HV, 128}, + {"gdn_scanr_4_4", HV * 4, 128}, {"gdn_scanr_4_2", HV * 4, 128}, {"gdn_scanr_8_8", HV * 4, 256}, + {"gdn_scanr_8_4", HV * 4, 256}, {"gdn_scanr_2_8", HV * 4, 64}, {"gdn_scanr_2_4", HV * 4, 64}}; + std::vector scan; + for (const Sv& v : svs) scan.push_back(cx.pipeline(lib, v.nm, std::string(v.nm) == "gdn_scan_v" || std::string(v.nm).find("scanr") != std::string::npos ? mtl::Constants().i(6, 0) : mtl::Constants())); + mtl::Pipeline pcp = cx.pipeline(lib, "gdn_cprep"), pcs = cx.pipeline(lib, "gdn_cstate"), pco = cx.pipeline(lib, "gdn_cout"); + std::printf("pipeline limits (max threads / simd / static tg mem; threads asked):"); + for (size_t i = 0; i < scan.size(); ++i) std::printf(" %s %d/%d/%d (%d)", svs[i].nm, scan[i].max_threads, scan[i].simd_width, scan[i].static_tg_mem, svs[i].tg); + std::printf("\n pre %d/%d/%d (256) cprep %d/%d/%d (256) cstate %d/%d/%d (256) cout %d/%d/%d (128) post %d/%d/%d (128)\n", + pre.max_threads, pre.simd_width, pre.static_tg_mem, pcp.max_threads, pcp.simd_width, pcp.static_tg_mem, pcs.max_threads, + pcs.simd_width, pcs.static_tg_mem, pco.max_threads, pco.simd_width, pco.static_tg_mem, post.max_threads, post.simd_width, + post.static_tg_mem); + std::printf("scratch at T: U+W+delta+lg = %.1f KB per token (%.0f MB at T 2048, %.0f MB at T 4096)\n", + (3.0 * HV * S * 4 + HV * 4) / 1024.0, (3.0 * HV * S * 4 + HV * 4) * 2048 / 1e6, + (3.0 * HV * S * 4 + HV * 4) * 4096 / 1e6); + + // token range [t0, t0 + n) as buffer offsets + auto pre_d = [&](int t0, int n, std::vector& ds, bool first) { + GdnPArgs a{(uint32_t)n, HK, HV, CH, 1e-6f, 1u}; + mtl::Dispatch d; + d.p = ⪯ + // history: the chunk reads hist (h0 for the first call, hOut afterwards), writes hOut + d.args = {mtl::Arg::B(qkv, (size_t)t0 * CH * 4), mtl::Arg::B(first ? h0 : hOut), mtl::Arg::B(cw), + mtl::Arg::B(al, (size_t)t0 * HV * 4), mtl::Arg::B(be, (size_t)t0 * HV * 4), mtl::Arg::B(dt), mtl::Arg::B(sa), + mtl::Arg::B(qn, (size_t)t0 * HK * S * 4), mtl::Arg::B(kn, (size_t)t0 * HK * S * 4), + mtl::Arg::B(vc, (size_t)t0 * HV * S * 4), mtl::Arg::B(gb, (size_t)t0 * HV * 8), mtl::Arg::B(kq, (size_t)t0 * HK * 4), + mtl::Arg::B(hOut), mtl::Arg::V(a)}; + d.grid[0] = HK + HV / 2; d.grid[1] = n; d.tg[0] = 256; + ds.push_back(d); + }; + auto scan_d = [&](int which, int t0, int n, const mtl::Buffer& st, const mtl::Buffer& out, std::vector& ds) { + GdnPArgs a{(uint32_t)n, HK, HV, CH, 1e-6f, 1u}; + mtl::Dispatch d; + d.p = &scan[which]; + d.args = {mtl::Arg::B(st), mtl::Arg::B(qn, (size_t)t0 * HK * S * 4), mtl::Arg::B(kn, (size_t)t0 * HK * S * 4), + mtl::Arg::B(vc, (size_t)t0 * HV * S * 4), mtl::Arg::B(gb, (size_t)t0 * HV * 8), mtl::Arg::B(kq, (size_t)t0 * HK * 4), + mtl::Arg::B(out, (size_t)t0 * HV * S * 4), mtl::Arg::V(a)}; + d.grid[0] = svs[which].grid; d.tg[0] = svs[which].tg; + ds.push_back(d); + }; + auto chunk_d = [&](int t0, int n, const mtl::Buffer& st, const mtl::Buffer& out, std::vector& ds) { + GdnPArgs a{(uint32_t)n, HK, HV, CH, 1e-6f, 1u}; + const uint32_t nc = (n + GC - 1) / GC; + mtl::Dispatch e1; e1.p = &pcp; + e1.args = {mtl::Arg::B(qn, (size_t)t0 * HK * S * 4), mtl::Arg::B(kn, (size_t)t0 * HK * S * 4), + mtl::Arg::B(vc, (size_t)t0 * HV * S * 4), mtl::Arg::B(gb, (size_t)t0 * HV * 8), mtl::Arg::B(cU), mtl::Arg::B(cW), + mtl::Arg::B(clg), mtl::Arg::V(a)}; + e1.grid[0] = HV; e1.grid[1] = nc; e1.tg[0] = 256; ds.push_back(e1); + mtl::Dispatch e2; e2.p = &pcs; + e2.args = {mtl::Arg::B(st), mtl::Arg::B(qn, (size_t)t0 * HK * S * 4), mtl::Arg::B(kn, (size_t)t0 * HK * S * 4), + mtl::Arg::B(cU), mtl::Arg::B(cW), mtl::Arg::B(clg), mtl::Arg::B(cD), mtl::Arg::B(out, (size_t)t0 * HV * S * 4), + mtl::Arg::V(a)}; + e2.grid[0] = HV * 4; e2.tg[0] = 256; ds.push_back(e2); + mtl::Dispatch e3; e3.p = &pco; + e3.args = {mtl::Arg::B(qn, (size_t)t0 * HK * S * 4), mtl::Arg::B(kn, (size_t)t0 * HK * S * 4), mtl::Arg::B(cD), + mtl::Arg::B(clg), mtl::Arg::B(out, (size_t)t0 * HV * S * 4), mtl::Arg::V(a)}; + e3.grid[0] = HV; e3.grid[1] = nc; e3.tg[0] = 128; ds.push_back(e3); + }; + auto post_d = [&](int t0, int n, const mtl::Buffer& out, std::vector& ds) { + GdnPArgs a{(uint32_t)n, HK, HV, CH, 1e-6f, 1u}; + mtl::Dispatch d; + d.p = &post; + d.args = {mtl::Arg::B(out, (size_t)t0 * HV * S * 4), mtl::Arg::B(z, (size_t)t0 * HV * S * 4), mtl::Arg::B(gam), + mtl::Arg::B(yh, (size_t)t0 * HV * S * 2), mtl::Arg::B(yB, (size_t)t0 * HV * S * 4), mtl::Arg::V(a)}; + d.grid[0] = HV; d.grid[1] = n; d.tg[0] = 128; + ds.push_back(d); + }; + auto timeit = [&](const std::vector& ds) { + cx.warm(ds, 0.3); + std::vector t; + for (int i = 0; i < reps; ++i) t.push_back(cx.run(ds)); + return median(t) * 1e3; + }; + auto copy_st0 = [&](mtl::Buffer& dst) { std::memcpy(dst.ptr, st0.ptr, (size_t)S * HV * S * 4); }; + + // FP64 oracle for head h over tokens [t0, t0 + n) from the prepared tensors; state in/out [S][S] (i, j) + auto oracle = [&](int h, int t0, int n, std::vector& St, std::vector& out) { + const int hk = h % HK; + out.assign((size_t)n * S, 0.0); + std::vector a(S), b(S); + for (int t = t0; t < t0 + n; ++t) { + const float* k = kn.as() + ((size_t)t * HK + hk) * S; + const float* q = qn.as() + ((size_t)t * HK + hk) * S; + const float* v = vc.as() + ((size_t)t * HV + h) * S; + const double g = gb.as()[((size_t)t * HV + h) * 2], bt = gb.as()[((size_t)t * HV + h) * 2 + 1]; + double kqv = 0; + for (int i = 0; i < S; ++i) kqv += (double)k[i] * q[i]; + std::fill(a.begin(), a.end(), 0.0); std::fill(b.begin(), b.end(), 0.0); + for (int i = 0; i < S; ++i) { + const double* row = &St[(size_t)i * S]; + const double ki = k[i], qi = q[i]; + for (int j = 0; j < S; ++j) { a[j] += row[j] * ki; b[j] += row[j] * qi; } + } + std::vector dl(S); + for (int j = 0; j < S; ++j) { + dl[j] = (v[j] - g * a[j]) * bt; + out[(size_t)(t - t0) * S + j] = (g * b[j] + dl[j] * kqv) / std::sqrt((double)S); + } + for (int i = 0; i < S; ++i) { + double* row = &St[(size_t)i * S]; + for (int j = 0; j < S; ++j) row[j] = g * row[j] + (double)k[i] * dl[j]; + } + } + }; + auto initial = [&](int h, std::vector& St) { + St.resize((size_t)S * S); + for (int i = 0; i < S; ++i) for (int j = 0; j < S; ++j) St[(size_t)i * S + j] = st0.as()[((size_t)i * HV + h) * S + j]; + }; + struct Err { double l2, mx; int nonfinite; }; + auto cmp_o = [&](const mtl::Buffer& ob, int h, int t0, int n, const std::vector& ro) { + double se = 0, sr = 0, mx = 0, rmax = 0; int nf = 0; + for (int t = 0; t < n; ++t) for (int j = 0; j < S; ++j) { + const float x = ob.as()[((size_t)(t0 + t) * HV + h) * S + j]; + if (!std::isfinite(x)) { ++nf; continue; } + const double e = x - ro[(size_t)t * S + j]; + se += e * e; sr += ro[(size_t)t * S + j] * ro[(size_t)t * S + j]; mx = std::max(mx, std::fabs(e)); rmax = std::max(rmax, std::fabs(ro[(size_t)t * S + j])); + } + return Err{std::sqrt(se / std::max(sr, 1e-30)), mx / std::max(rmax, 1e-30), nf}; + }; + auto cmp_s = [&](const mtl::Buffer& sb, int h, const std::vector& rs) { + double se = 0, sr = 0, mx = 0, rmax = 0; int nf = 0; + for (int i = 0; i < S; ++i) for (int j = 0; j < S; ++j) { + const float x = sb.as()[((size_t)i * HV + h) * S + j]; + if (!std::isfinite(x)) { ++nf; continue; } + const double e = x - rs[(size_t)i * S + j]; + se += e * e; sr += rs[(size_t)i * S + j] * rs[(size_t)i * S + j]; mx = std::max(mx, std::fabs(e)); rmax = std::max(rmax, std::fabs(rs[(size_t)i * S + j])); + } + return Err{std::sqrt(se / std::max(sr, 1e-30)), mx / std::max(rmax, 1e-30), nf}; + }; + + // prepared tensors once for all TMAX tokens (gdn_pre per call carries the history; here one call, the tokens independent + // of the scan variant). For the continuation check the pre runs per split below. + { + std::vector ds; + // gdn_pre on a very long T reads hist only for the first 3 tokens; one call over TMAX is the same as pieces + pre_d(0, TMAX, ds, true); + cx.run(ds); + } + int fails = 0; + if (check) { + std::printf("== numerical checks vs FP64 oracle (rel L2 / max-abs over max|ref|, per head)\n"); + for (int T : Ts) { + // the variants, each from st0, over tokens [0, T) + struct V { const char* name; int kind; }; // kind: 0..2 scanr IB 2/4/8, 10 chunked + for (V v : {V{"scanr_4", 1}, V{"chunked", 10}}) { + copy_st0(stX); + std::vector ds; + if (v.kind == 10) chunk_d(0, T, stX, o, ds); else scan_d(v.kind, 0, T, stX, o, ds); + cx.run(ds); + for (int h : heads) { + std::vector St, ro; initial(h, St); oracle(h, 0, T, St, ro); + Err eo = cmp_o(o, h, 0, T, ro), es = cmp_s(stX, h, St); + const bool ok = eo.l2 < 3e-3 && es.l2 < 3e-3 && !eo.nonfinite && !es.nonfinite; + fails += !ok; + std::printf("T %5d %-8s head %2d: o rel %.2e (max %.2e) state rel %.2e (max %.2e) nonfinite %d %s\n", T, v.name, + h, eo.l2, eo.mx, es.l2, es.mx, eo.nonfinite + es.nonfinite, ok ? "PASS" : "FAIL"); + if (T > 8192) break; // one head at the largest sizes (oracle cost) + } + } + } + // continuation: T = A + B, second call on offsets and the first call's state; every pairing + std::printf("== continuation (state carried across two calls, 2nd call on buffer offsets) vs oracle over the whole range\n"); + const std::pair splits[] = {{37, 963}, {1024, 1024}, {2048, 2047}, {31, 33}, {1, 4095}}; + for (auto [A, B] : splits) { + if (A + B > TMAX) continue; + const char* nm[4] = {"chunk+chunk", "scan+chunk", "chunk+scan", "scan+scan"}; + for (int m = 0; m < 4; ++m) { + copy_st0(stX); + std::vector d1, d2; + if (m == 0 || m == 2) chunk_d(0, A, stX, o, d1); else scan_d(1, 0, A, stX, o, d1); + if (m == 0 || m == 1) chunk_d(A, B, stX, o, d2); else scan_d(1, A, B, stX, o, d2); + cx.run(d1); cx.run(d2); + for (int h : {heads[0], heads.back()}) { + std::vector St, ro; initial(h, St); oracle(h, 0, A + B, St, ro); + Err eo = cmp_o(o, h, 0, A + B, ro), es = cmp_s(stX, h, St); + const bool ok = eo.l2 < 3e-3 && es.l2 < 3e-3 && !eo.nonfinite && !es.nonfinite; + fails += !ok; + std::printf("split %5d + %5d %-12s head %2d: o rel %.2e state rel %.2e %s\n", A, B, nm[m], h, eo.l2, es.l2, ok ? "PASS" : "FAIL"); + } + } + } + std::printf("%s\n", fails ? "SOME FAILED" : "ALL PASS"); + } + // timing: gdn_pre, the scan variants, chunked parts, gdn_post; the stage = pre + scan + post + std::printf("== timing (GPU ms per call, median of %d; stage = pre + scan + post)\n", reps); + std::printf("%6s | %7s %7s |", "T", "pre", "post"); + for (const Sv& v : svs) std::printf(" %s", v.nm + 4); + std::printf(" | chunked (cprep cstate cout) | stage scanr_4 / chunked / x\n"); + for (int T : Ts) { + std::vector dp, dpo, dc; + pre_d(0, T, dp, true); + post_d(0, T, o, dpo); + const double tp = timeit(dp), tpo = timeit(dpo); + std::printf("%6d | %7.3f %7.3f |", T, tp, tpo); + double ts1 = 0, tbest = 1e30; + int wbest = 1; + for (int w = 0; w < NSC; ++w) { + std::vector d1; + double t = 0; + if (!noscan) { scan_d(w, 0, T, stX, o, d1); t = timeit(d1); } + if (w == 1) ts1 = t; + if (t > 0 && t < tbest) { tbest = t; wbest = w; } + std::printf(" %8.3f", t); + } + chunk_d(0, T, stX, o, dc); + const double tc = timeit(dc), tc1 = timeit({dc[0]}), tc2 = timeit({dc[1]}), tc3 = timeit({dc[2]}); + const double base = tp + ts1 + tpo, ch = tp + tc + tpo; + std::printf(" | %8.3f (%7.3f %7.3f %7.3f) | %8.3f %8.3f %5.2f | best %s stage %.3f = x%.3f (scan x%.3f)\n", tc, tc1, tc2, tc3, base, ch, base / ch, svs[wbest].nm, tp + tbest + tpo, base / (tp + tbest + tpo), ts1 / tbest); + std::fflush(stdout); + } + return fails ? 1 : 0; +} From 2cf3fd181f197caa84f4c3b19907dd1bb106957d Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 30 Oct 2026 01:22:28 +0100 Subject: [PATCH 2/5] Metal: gdn_scan_f (scan + gdn_post fused, bit-identical, slower: kept as a measured negative), bench --- metal/kernels/gdn_prompt.metal | 101 ++++++++++++++++++++++++++++++++ metal/tests/gdn_chunk_bench.cpp | 39 ++++++++++++ 2 files changed, 140 insertions(+) diff --git a/metal/kernels/gdn_prompt.metal b/metal/kernels/gdn_prompt.metal index 31bb0ce4..fc906180 100644 --- a/metal/kernels/gdn_prompt.metal +++ b/metal/kernels/gdn_prompt.metal @@ -328,6 +328,107 @@ template [[host_name("gdn_scanr_8_4")]] kernel decltype(gdn_scan_r<8, 4>) gdn_sc template [[host_name("gdn_scanr_2_8")]] kernel decltype(gdn_scan_r<2, 8>) gdn_scan_r<2, 8>; template [[host_name("gdn_scanr_2_4")]] kernel decltype(gdn_scan_r<2, 4>) gdn_scan_r<2, 4>; +// ---- gdn_scanf: gdn_scan_r<4, TB> with gdn_post folded in. One threadgroup a value head (grid h_v), 16 simdgroups = +// 4 column blocks x 4 row blocks, 512 threads. The scan is gdn_scan_r's, token for token (the same operations in the +// same order, so o is the same bits); a column block's row-block-0 simdgroup holds o for its 32 columns, writes them and +// their simd_sum of squares to threadgroup memory, and once every TB tokens the whole threadgroup runs gdn_post's +// arithmetic on those tokens (the sum of the four partials in gdn_post's order: the same bits as gdn_post). Outputs: +// y (fp16) and, with `f32`, fp32 y; o itself never reaches device memory. +template +kernel void gdn_scan_f(device float* state [[buffer(0)]], device const float4* qn [[buffer(1)]], + device const float4* kn [[buffer(2)]], device const float* vc [[buffer(3)]], + device const float2* gb [[buffer(4)]], device const float* kq [[buffer(5)]], + device const float* z [[buffer(6)]], device const float* gamma [[buffer(7)]], + device half* yh [[buffer(8)]], device float* y32 [[buffer(9)]], constant GdnPArgs& a [[buffer(10)]], + 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, IB = 4, R = S / IB, R4 = R / 4; + threadgroup float4 qs[TB][32], ks[TB][32]; + threadgroup float2 red[2][16][32]; + threadgroup float vs[TB][128]; + threadgroup float4 gk[TB]; + threadgroup float ot[TB][128]; + threadgroup float osq[TB][4]; + const int h = int(tg.x), hk = h % int(a.h_k), hv = int(a.h_v), hkn = int(a.h_k); + const int cb = sg >> 2, ib = sg & 3; + const int j = cb * 32 + lane, i0 = ib * R; + const int T = int(a.n_tok); + const float scale = 1.0f / sqrt(float(S)); + float st[R]; +#pragma clang loop unroll(full) + for (int i = 0; i < R; ++i) st[i] = state[((i0 + i) * hv + h) * S + j]; + for (int t0 = 0; t0 < T; t0 += TB) { + const int nb = min(TB, T - t0); + threadgroup_barrier(mem_flags::mem_threadgroup); + for (int idx = tid; idx < nb * 32; idx += 512) { + const int tt = idx >> 5, w = idx & 31; + qs[tt][w] = qn[((t0 + tt) * hkn + hk) * 32 + w]; + ks[tt][w] = kn[((t0 + tt) * hkn + hk) * 32 + w]; + } + for (int idx = tid; idx < nb * 128; idx += 512) { + const int tt = idx >> 7, w = idx & 127; + vs[tt][w] = vc[((t0 + tt) * hv + h) * S + w]; + } + for (int tt = tid; tt < nb; tt += 512) { + const float2 g_b = gb[(t0 + tt) * hv + h]; + gk[tt] = float4(g_b.x, g_b.y, kq[(t0 + tt) * hkn + hk], 0.0f); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (int tt = 0; tt < nb; ++tt) { + const int t = t0 + tt, slot = t & 1; + float ka = 0.0f, qa = 0.0f; +#pragma clang loop unroll(full) + for (int w = 0; w < R4; ++w) { + const float4 k4 = ks[tt][i0 / 4 + w], q4 = qs[tt][i0 / 4 + w]; + ka = fma(st[4 * w], k4.x, ka); ka = fma(st[4 * w + 1], k4.y, ka); + ka = fma(st[4 * w + 2], k4.z, ka); ka = fma(st[4 * w + 3], k4.w, ka); + qa = fma(st[4 * w], q4.x, qa); qa = fma(st[4 * w + 1], q4.y, qa); + qa = fma(st[4 * w + 2], q4.z, qa); qa = fma(st[4 * w + 3], q4.w, qa); + } + const float4 g_b = gk[tt]; + const float v = vs[tt][j]; + red[slot][sg][lane] = float2(ka, qa); + threadgroup_barrier(mem_flags::mem_threadgroup); + float2 s = red[slot][cb * 4][lane]; +#pragma clang loop unroll(full) + for (int b = 1; b < IB; ++b) s += red[slot][cb * 4 + b][lane]; + const float g = g_b.x; + const float delta = (v - g * s.x) * g_b.y; + if (ib == 0) { + const float ov = fma(g, s.y, delta * g_b.z) * scale; + ot[tt][j] = ov; + const float ss = simd_sum(ov * ov); + if (lane == 0) osq[tt][cb] = ss; + } +#pragma clang loop unroll(full) + for (int w = 0; w < R4; ++w) { + const float4 k4 = ks[tt][i0 / 4 + w]; + st[4 * w] = fma(g, st[4 * w], k4.x * delta); + st[4 * w + 1] = fma(g, st[4 * w + 1], k4.y * delta); + st[4 * w + 2] = fma(g, st[4 * w + 2], k4.z * delta); + st[4 * w + 3] = fma(g, st[4 * w + 3], k4.w * delta); + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + // gdn_post for these tokens + for (int idx = tid; idx < nb * 128; idx += 512) { + const int tt = idx >> 7, c = idx & 127; + const float tot = (osq[tt][0] + osq[tt][1]) + (osq[tt][2] + osq[tt][3]); + const float rs = rsqrt(tot / 128.0f + a.eps); + const ulong i = ulong((t0 + tt) * hv + h) * 128 + c; + const float ov = ot[tt][c]; + const float yv = ((rs * ov) * gamma[c]) * (1.0f / (1.0f + exp(-z[i]))); + yh[i] = half(yv); + if (a.f32) y32[i] = yv; + } + } +#pragma clang loop unroll(full) + for (int i = 0; i < R; ++i) state[((i0 + i) * hv + h) * S + j] = st[i]; +} +template [[host_name("gdn_scanf_8")]] kernel decltype(gdn_scan_f<8>) gdn_scan_f<8>; +template [[host_name("gdn_scanf_4")]] kernel decltype(gdn_scan_f<4>) gdn_scan_f<4>; +template [[host_name("gdn_scanf_2")]] kernel decltype(gdn_scan_f<2>) gdn_scan_f<2>; + // ---- the chunked form (chunks of GC = 32 tokens), the WY / UT form of the gated delta rule. With G_t the product // of the chunk's gates up to t (log space: lg_t) and S0 the state entering the chunk: // (I + A) D = B, A_ts = beta_t (k_t . k_s) G_t / G_s (s < t), B = [beta v | beta G k] -> D = [U | W] diff --git a/metal/tests/gdn_chunk_bench.cpp b/metal/tests/gdn_chunk_bench.cpp index 870baa9c..2ec86f45 100644 --- a/metal/tests/gdn_chunk_bench.cpp +++ b/metal/tests/gdn_chunk_bench.cpp @@ -135,6 +135,20 @@ int main(int argc, char** argv) { d.grid[0] = HV; d.grid[1] = n; d.tg[0] = 128; ds.push_back(d); }; + mtl::Pipeline pf[3] = {cx.pipeline(lib, "gdn_scanf_4"), cx.pipeline(lib, "gdn_scanf_8"), cx.pipeline(lib, "gdn_scanf_2")}; + std::printf("fused scan+post pipelines (max threads / static tg mem; 512 asked): TB4 %d/%d TB8 %d/%d TB2 %d/%d\n", pf[0].max_threads, + pf[0].static_tg_mem, pf[1].max_threads, pf[1].static_tg_mem, pf[2].max_threads, pf[2].static_tg_mem); + auto fused_d = [&](int which, int t0, int n, const mtl::Buffer& st, std::vector& ds) { + GdnPArgs a{(uint32_t)n, HK, HV, CH, 1e-6f, 1u}; + mtl::Dispatch d; + d.p = &pf[which]; + d.args = {mtl::Arg::B(st), mtl::Arg::B(qn, (size_t)t0 * HK * S * 4), mtl::Arg::B(kn, (size_t)t0 * HK * S * 4), + mtl::Arg::B(vc, (size_t)t0 * HV * S * 4), mtl::Arg::B(gb, (size_t)t0 * HV * 8), mtl::Arg::B(kq, (size_t)t0 * HK * 4), + mtl::Arg::B(z, (size_t)t0 * HV * S * 4), mtl::Arg::B(gam), mtl::Arg::B(yh, (size_t)t0 * HV * S * 2), + mtl::Arg::B(yB, (size_t)t0 * HV * S * 4), mtl::Arg::V(a)}; + d.grid[0] = HV; d.tg[0] = 512; + ds.push_back(d); + }; auto timeit = [&](const std::vector& ds) { cx.warm(ds, 0.3); std::vector t; @@ -249,6 +263,25 @@ int main(int argc, char** argv) { } } } + std::printf("== fused scan+post vs pre/scanr_4/post: y rel L2, fp16 y mismatches, state rel L2\n"); + for (int T : Ts) { + if (T > 8192) continue; + copy_st0(stX); + std::vector d0; scan_d(1, 0, T, stX, o, d0); post_d(0, T, o, d0); cx.run(d0); + std::vector yref(yB.as(), yB.as() + (size_t)T * HV * S), sref(stX.as(), stX.as() + (size_t)S * HV * S); + std::vector href(yh.as(), yh.as() + (size_t)T * HV * S); + for (int w = 0; w < 3; ++w) { + copy_st0(stX); + std::memset(yB.ptr, 0, (size_t)T * HV * S * 4); + std::vector d1; fused_d(w, 0, T, stX, d1); cx.run(d1); + double se = 0, sr = 0, ss = 0, ssr = 0; size_t hm = 0; + for (size_t i = 0; i < (size_t)T * HV * S; ++i) { const double e = yB.as()[i] - yref[i]; se += e * e; sr += (double)yref[i] * yref[i]; hm += yh.as()[i] != href[i]; } + for (size_t i = 0; i < (size_t)S * HV * S; ++i) { const double e = stX.as()[i] - sref[i]; ss += e * e; ssr += (double)sref[i] * sref[i]; } + const bool ok = std::sqrt(se / sr) < 1e-5 && std::sqrt(ss / ssr) < 1e-5; + fails += !ok; + std::printf("T %5d fused TB%-2d: y rel %.2e, fp16 mismatches %zu, state rel %.2e %s\n", T, w == 0 ? 4 : w == 1 ? 8 : 2, std::sqrt(se / sr), hm, std::sqrt(ss / ssr), ok ? "PASS" : "FAIL"); + } + } std::printf("%s\n", fails ? "SOME FAILED" : "ALL PASS"); } // timing: gdn_pre, the scan variants, chunked parts, gdn_post; the stage = pre + scan + post @@ -276,6 +309,12 @@ int main(int argc, char** argv) { const double tc = timeit(dc), tc1 = timeit({dc[0]}), tc2 = timeit({dc[1]}), tc3 = timeit({dc[2]}); const double base = tp + ts1 + tpo, ch = tp + tc + tpo; std::printf(" | %8.3f (%7.3f %7.3f %7.3f) | %8.3f %8.3f %5.2f | best %s stage %.3f = x%.3f (scan x%.3f)\n", tc, tc1, tc2, tc3, base, ch, base / ch, svs[wbest].nm, tp + tbest + tpo, base / (tp + tbest + tpo), ts1 / tbest); + { + double tf[3]; + for (int w = 0; w < 3; ++w) { std::vector d1; fused_d(w, 0, T, stX, d1); tf[w] = timeit(d1); } + const double fb = tp + std::min(tf[0], std::min(tf[1], tf[2])); + std::printf(" fused scan+post TB4 %.3f TB8 %.3f TB2 %.3f ms; stage pre+fused best %.3f = x%.3f vs scanr_4 stage\n", tf[0], tf[1], tf[2], fb, base / fb); + } std::fflush(stdout); } return fails ? 1 : 0; From 095464152cde9e41d9ae07649e2b3055ff56257a Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 30 Oct 2026 01:24:05 +0100 Subject: [PATCH 3/5] Metal: GDN prompt scan chosen per chip (M4 scanr_4_8, M5 Max scanr_4_4 from T 4096), bit-identical --- metal/src/engine/prompt_chain.inc | 2 +- metal/src/engine/window.cpp | 23 +++++++++++++++-------- 2 files changed, 16 insertions(+), 9 deletions(-) diff --git a/metal/src/engine/prompt_chain.inc b/metal/src/engine/prompt_chain.inc index cf1d487d..2a0e7592 100644 --- a/metal/src/engine/prompt_chain.inc +++ b/metal/src/engine/prompt_chain.inc @@ -207,7 +207,7 @@ bool Window::pc_chunk(const int64_t* tokens, int nT, int64_t pos0, std::string& mtl::Arg::B(W_, T(bl + "ssm_a").offset), mtl::Arg::B(b.gqn), mtl::Arg::B(b.gkn), mtl::Arg::B(b.gvc), mtl::Arg::B(b.ggb), mtl::Arg::B(b.gkq), mtl::Arg::B(ghist_[1 - hp][(size_t) gi]), mtl::Arg::V(ga)}, 16 + 24, nT, 256); - D(P_(b.lgdn, gdn_scan_name(), mtl::Constants().i(6, 0)), + D(P_(b.lgdn, gdn_scan_name(cx_->device_name(), nT), mtl::Constants().i(6, 0)), {mtl::Arg::B(gst_[(size_t) gi]), mtl::Arg::B(b.gqn), mtl::Arg::B(b.gkn), mtl::Arg::B(b.gvc), mtl::Arg::B(b.ggb), mtl::Arg::B(b.gkq), mtl::Arg::B(b.go), mtl::Arg::V(ga)}, 48 * 4, 1, 32 * 4); diff --git a/metal/src/engine/window.cpp b/metal/src/engine/window.cpp index 70758170..c18bf9bc 100644 --- a/metal/src/engine/window.cpp +++ b/metal/src/engine/window.cpp @@ -50,16 +50,23 @@ namespace strata::gpu { uint64_t purge_device_allocations(size_t min_bytes); } namespace strata::metal_engine { -// The prompt GDN scan kernel. STRATA_METAL_GDN_SCAN names an instantiation of gdn_scan_r in gdn_prompt.metal -// (gdn_scanr_4_8, gdn_scanr_4_4, ...): IB simdgroups a threadgroup (the thread count is read from the name), TB tokens staged. -// Unset: gdn_scanr_4 (IB 4, TB 16), the production default. Only the four-simdgroup names are accepted here. -static const char* gdn_scan_name() { - static const std::string name = [] { +// The prompt GDN scan kernel, chosen by chip and prompt length (gdn_prompt.metal, gdn_scan_r; every choice is +// bit-identical to gdn_scanr_4: the token order and the arithmetic are the same, only the staged block size TB changes, which +// changes the threadgroup memory a core can hold at once). Measured by metal/tests/gdn_chunk_bench: +// Apple M4 (the base chip): gdn_scanr_4_8, 1.16x on the scan, 1.11x on the GDN prompt stage, T 512..32K +// Apple M5 Max: gdn_scanr_4_4 from T >= 4096 (1.04x at 4K, 1.10x at 16K); below that the default is as fast +// anything else (other chips, unknown names): gdn_scanr_4 as before +// STRATA_METAL_GDN_SCAN= forces a kernel (A/B and diagnosis). +static const char* gdn_scan_name(const std::string& device, int T) { + static const std::string forced = [] { const char* e = std::getenv("STRATA_METAL_GDN_SCAN"); const std::string s = e ? e : ""; - return (s == "gdn_scanr_4_8" || s == "gdn_scanr_4_4" || s == "gdn_scanr_4_2") ? s : std::string("gdn_scanr_4"); + return (s == "gdn_scanr_4" || s == "gdn_scanr_4_8" || s == "gdn_scanr_4_4" || s == "gdn_scanr_4_2") ? s : std::string(); }(); - return name.c_str(); + if (!forced.empty()) return forced.c_str(); + if (device == "Apple M4") return "gdn_scanr_4_8"; + if (device == "Apple M5 Max" && T >= 4096) return "gdn_scanr_4_4"; + return "gdn_scanr_4"; } namespace { @@ -2370,7 +2377,7 @@ bool Window::prompt_chunk(const int32_t* tokens, int Tn, int64_t pos0, std::stri mtl::Arg::B(p.al), mtl::Arg::B(p.be), mtl::Arg::B(W_, TN(b + "ssm_dt.bias").offset), mtl::Arg::B(W_, TN(b + "ssm_a").offset), mtl::Arg::B(p.gqn), mtl::Arg::B(p.gkn), mtl::Arg::B(p.gvc), mtl::Arg::B(p.ggb), mtl::Arg::B(p.gkq), mtl::Arg::B(ghist_[1 - hp_][(size_t) gi]), mtl::Arg::V(ga)}, 16 + 24, T, 256); - D(PP(p.lgdn, gdn_scan_name(), mtl::Constants().i(6, 0), gdn_scan_name()), + D(PP(p.lgdn, gdn_scan_name(cx_->device_name(), T), mtl::Constants().i(6, 0), gdn_scan_name(cx_->device_name(), T)), {mtl::Arg::B(gst_[(size_t) gi]), mtl::Arg::B(p.gqn), mtl::Arg::B(p.gkn), mtl::Arg::B(p.gvc), mtl::Arg::B(p.ggb), mtl::Arg::B(p.gkq), mtl::Arg::B(p.go), mtl::Arg::V(ga)}, 48 * 4, 1, 32 * 4); D(PP(p.lgdn, "gdn_post"), {mtl::Arg::B(p.go), mtl::Arg::B(p.z), mtl::Arg::B(W_, TN(b + "ssm_norm.weight").offset), From cea3057e2c1392142e9c49a73852e22c145e34b9 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 30 Oct 2026 01:42:07 +0100 Subject: [PATCH 4/5] Metal: GDN chunked v2 (measured, slower), M5 GEMM tiles + fused GDN input projections (bit-identical), layer bench --- metal/kernels/dense_mm.metal | 8 ++ metal/kernels/gdn_prompt.metal | 207 +++++++++++++++++++++++++++++- metal/src/engine/prompt_chain.inc | 77 ++++++++--- metal/src/engine/window.cpp | 22 +++- metal/tests/gdn_chunk_bench.cpp | 75 +++++++++-- metal/tests/gdn_layer_bench.cpp | 184 ++++++++++++++++++++++++++ 6 files changed, 534 insertions(+), 39 deletions(-) create mode 100644 metal/tests/gdn_layer_bench.cpp diff --git a/metal/kernels/dense_mm.metal b/metal/kernels/dense_mm.metal index 45e29ace..3e149bfb 100644 --- a/metal/kernels/dense_mm.metal +++ b/metal/kernels/dense_mm.metal @@ -67,3 +67,11 @@ template [[host_name("gemm_f16_64_64_4")]] kernel decltype(gemm_f16<64, 64, 4>) template [[host_name("gemm_f16_128_64_4")]] kernel decltype(gemm_f16<128, 64, 4>) gemm_f16<128, 64, 4>; template [[host_name("gemm_f16_64_128_4")]] kernel decltype(gemm_f16<64, 128, 4>) gemm_f16<64, 128, 4>; template [[host_name("gemm_f16_64_32_4")]] kernel decltype(gemm_f16<64, 32, 4>) gemm_f16<64, 32, 4>; +template [[host_name("gemm_f16_128_128_4")]] kernel decltype(gemm_f16<128, 128, 4>) gemm_f16<128, 128, 4>; +template [[host_name("gemm_f16_128_128_8")]] kernel decltype(gemm_f16<128, 128, 8>) gemm_f16<128, 128, 8>; +template [[host_name("gemm_f16_128_64_8")]] kernel decltype(gemm_f16<128, 64, 8>) gemm_f16<128, 64, 8>; +template [[host_name("gemm_f16_64_64_8")]] kernel decltype(gemm_f16<64, 64, 8>) gemm_f16<64, 64, 8>; +template [[host_name("gemm_f16_256_64_8")]] kernel decltype(gemm_f16<256, 64, 8>) gemm_f16<256, 64, 8>; +template [[host_name("gemm_f16_64_256_8")]] kernel decltype(gemm_f16<64, 256, 8>) gemm_f16<64, 256, 8>; +template [[host_name("gemm_f16_128_32_4")]] kernel decltype(gemm_f16<128, 32, 4>) gemm_f16<128, 32, 4>; +template [[host_name("gemm_f16_32_128_4")]] kernel decltype(gemm_f16<32, 128, 4>) gemm_f16<32, 128, 4>; diff --git a/metal/kernels/gdn_prompt.metal b/metal/kernels/gdn_prompt.metal index fc906180..43b42aa4 100644 --- a/metal/kernels/gdn_prompt.metal +++ b/metal/kernels/gdn_prompt.metal @@ -23,6 +23,12 @@ struct GdnPArgs { uint f32; // gdn_post: also write fp32 y }; +// function constant 7 (optional): the row stride in floats of ONE fused output [qkv | z | alpha | beta] of the four input +// projections (16480). gdn_pre then reads qkv / alpha / beta and gdn_post reads z at that stride (the buffers bound at offsets); +// undefined (every other caller): the separate buffers of channels / h_v / h_v * 128 floats a row. +constant int GDN_LD [[function_constant(7)]]; +constant bool gdn_ld_on = is_function_constant_defined(GDN_LD); + static inline float gp_conv(device const float* qkv, device const float* hist, device const float* cw, int ch, int t, int channels) { float s = 0.0f; @@ -52,11 +58,12 @@ kernel void gdn_pre(device const float* qkv [[buffer(0)]], device const float* h int ch; if (x < hk_n) ch = tid < 128 ? x * S + tid : hk_n * S + x * S + (tid - 128); else ch = 2 * hk_n * S + (2 * (x - hk_n) + (tid >> 7)) * S + (tid & 127); - const float cv = gp_conv(qkv, hist, conv_w, ch, t, C); + const int QL = gdn_ld_on ? GDN_LD : C; + const float cv = gp_conv(qkv, hist, conv_w, ch, t, QL); if (t == T - 1) for (int k = 0; k < 3; ++k) { const int src = T - 3 + k; - hist_out[ch * 3 + k] = src >= 0 ? qkv[src * C + ch] : hist[ch * 3 + (src + 3)]; + hist_out[ch * 3 + k] = src >= 0 ? qkv[src * QL + ch] : hist[ch * 3 + (src + 3)]; } if (x < hk_n) { const float ssq = simd_sum(cv * cv); @@ -82,10 +89,11 @@ kernel void gdn_pre(device const float* qkv [[buffer(0)]], device const float* h const int h = 2 * (x - hk_n) + (tid >> 7); vc[(t * hv + h) * S + (tid & 127)] = cv; if ((tid & 127) == 0) { - const float v = alpha[t * hv + h] + dt[h]; + const int AL = gdn_ld_on ? GDN_LD : hv; + const float v = alpha[t * AL + h] + dt[h]; 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[t * hv + h] = float2(exp(sp * ssm_a[h]), 1.0f / (1.0f + exp(-beta[t * hv + h]))); + gb[t * hv + h] = float2(exp(sp * ssm_a[h]), 1.0f / (1.0f + exp(-beta[t * AL + h]))); } } } @@ -309,7 +317,8 @@ kernel void gdn_post(device const float* o [[buffer(0)]], device const float* z threadgroup_barrier(mem_flags::mem_threadgroup); const float tot = (part[0] + part[1]) + (part[2] + part[3]); const float rs = rsqrt(tot / 128.0f + a.eps); - const float yv = ((rs * ov) * gamma[tid]) * (1.0f / (1.0f + exp(-z[i]))); + const float zv = gdn_ld_on ? z[uint(t) * uint(GDN_LD) + uint(h) * 128u + tid] : z[i]; + const float yv = ((rs * ov) * gamma[tid]) * (1.0f / (1.0f + exp(-zv))); yh[i] = half(yv); if (a.f32) y[i] = yv; } @@ -590,3 +599,191 @@ kernel void gdn_cout(device const float* qn [[buffer(0)]], device const float* k o[((t0 + t) * hv + h) * S + j] = s * scale; } } + +// ---- the chunked form v2: the same algebra as gdn_cprep / gdn_cstate / gdn_cout (WY / UT, chunks of GC = 32), organised for the +// GPU. Staging the chunk's k in threadgroup memory removes the redundant device loads of gdn_cprep, the state update, the +// inter-chunk and the intra-chunk products run as 8x8 simdgroup_matrix products (fp32), and the intra-chunk part is folded into +// the state kernel (no gdn_cout, no delta buffer). The chunk's q.k matrix M (with the decay factors) comes from the prep. +// gdn_cprep2 per (head, chunk): lg, A, the forward substitution for U and W, and M_ts = (q_t . k_s) G_t / G_s (s <= t) +// gdn_cstate2 per (head, 32 state columns): the chunks in order - delta = U - W S, o = (G q S + M delta) / sqrt(128), +// S = G_L S + sum_s (G_L / G_s) k_s delta_s^T. The q and k rows of the last chunk's 32 tokens are read in +// full (rows past n_tok are read and multiplied by zero): the caller's buffers hold a multiple of 32 rows. +kernel void gdn_cprep2(device const float* qn [[buffer(0)]], device const float* kn [[buffer(1)]], + device const float* vc [[buffer(2)]], device const float2* gb [[buffer(3)]], + device float* U [[buffer(4)]], device float* W [[buffer(5)]], device float* lgo [[buffer(6)]], + device float* Mo [[buffer(7)]], constant GdnPArgs& a [[buffer(8)]], + uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]]) { + constexpr int S = 128; + threadgroup float4 Ks[GC * 32]; + threadgroup float4 A4[GC * 8]; + threadgroup float* A = (threadgroup float*)A4; + threadgroup float lg[GC], bt[GC]; + const int h = int(tg.x), c = int(tg.y), hv = int(a.h_v), hkn = int(a.h_k), hk = h % hkn, T = int(a.n_tok); + const int NC = (T + GC - 1) / GC, t0 = c * GC, nb = min(GC, T - t0); + if (tid == 0) { + float s = 0.0f; + for (int t = 0; t < GC; ++t) { + if (t < nb) s += max(log(gb[(t0 + t) * hv + h].x), -80.0f); + lg[t] = s; + bt[t] = t < nb ? gb[(t0 + t) * hv + h].y : 0.0f; + } + } + device const float4* kn4 = (device const float4*)kn; + for (int idx = tid; idx < GC * 32; idx += 256) { + const int t = idx >> 5, w = idx & 31; + Ks[idx] = t < nb ? kn4[((t0 + t) * hkn + hk) * 32 + w] : float4(0.0f); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (int idx = tid; idx < GC * GC; idx += 256) { + const int t = idx / GC, s = idx % GC; + float av = 0.0f, mv = 0.0f; + if (t < nb && s <= t && gdn_probe != 1) { + device const float4* qt = (device const float4*)(qn + ((t0 + t) * hkn + hk) * S); + float dm = 0.0f, da = 0.0f; + for (int i = 0; i < S / 4; ++i) { + const float4 ks = Ks[s * 32 + i]; + dm += dot(qt[i], ks); + da += dot(Ks[t * 32 + i], ks); + } + const float f = exp(lg[t] - lg[s]); + mv = dm * f; + if (s < t) av = bt[t] * da * f; + } + A[t * GC + s] = av; + Mo[((ulong(h) * NC + c) * GC + t) * GC + s] = mv; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + const int j = tid & 127; + const bool isw = tid >= 128; + threadgroup const float* Kf = (threadgroup const float*)Ks; + float x[GC]; +#pragma clang loop unroll(full) + for (int t = 0; t < GC; ++t) x[t] = 0.0f; +#pragma clang loop unroll(full) + for (int t = 0; t < GC; ++t) { + float b = 0.0f; + if (t < nb) b = isw ? bt[t] * exp(lg[t]) * Kf[t * S + j] : bt[t] * vc[((t0 + t) * hv + h) * S + j]; +#pragma clang loop unroll(full) + for (int s4 = 0; s4 < (t + 3) / 4; ++s4) { + const float4 ar = A4[t * 8 + s4]; + b = fma(-ar.x, x[4 * s4], b); + b = fma(-ar.y, x[4 * s4 + 1], b); + b = fma(-ar.z, x[4 * s4 + 2], b); + b = fma(-ar.w, x[4 * s4 + 3], b); + } + x[t] = b; + } + device float* o = (isw ? W : U) + (ulong(h) * NC + c) * GC * S + j; +#pragma clang loop unroll(full) + for (int t = 0; t < GC; ++t) o[t * S] = x[t]; + if (tid < GC) lgo[(h * NC + c) * GC + tid] = lg[tid]; +} + + +// grid (h_v * 4), 128 threads = 4 simdgroups. A simdgroup owns rows 32 sg .. 32 sg + 31 of the 128 x 32 state block as 4 x 4 +// simdgroup matrices that stay in registers for the whole call; each chunk the block is stored to threadgroup memory (Sm) once, +// where the two products that need all 128 rows (W S and Q S, sharing the S tiles) read it. +kernel void gdn_cstate2(device float* state [[buffer(0)]], device const float* qn [[buffer(1)]], + device const float* kn [[buffer(2)]], device const float* U [[buffer(3)]], + device const float* W [[buffer(4)]], device const float* lgo [[buffer(5)]], + device const float* Mo [[buffer(6)]], device float* o [[buffer(7)]], constant GdnPArgs& a [[buffer(8)]], + uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]], + ushort sg [[simdgroup_index_in_threadgroup]]) { + constexpr int S = 128; + threadgroup float Sm[S][32]; + threadgroup float Dl[GC][32]; + threadgroup float X[GC][32]; + threadgroup float Y[GC][32]; + const int h = int(tg.x) / 4, hv = int(a.h_v), hkn = int(a.h_k), hk = h % hkn, T = int(a.n_tok); + const int NC = (T + GC - 1) / GC, j0 = (int(tg.x) % 4) * 32; + const float scale = 1.0f / sqrt(float(S)); + simdgroup_float8x8 st[4][4]; + for (int rt = 0; rt < 4; ++rt) + for (int jt = 0; jt < 4; ++jt) + simdgroup_load(st[rt][jt], state + ((32 * sg + 8 * rt) * hv + h) * S + j0 + 8 * jt, hv * S); + for (int c = 0; c < NC; ++c) { + const int t0 = c * GC, nb = min(GC, T - t0); + device const float* Uc = U + (ulong(h) * NC + c) * GC * S; + device const float* Wc = W + (ulong(h) * NC + c) * GC * S; + device const float* Mc = Mo + (ulong(h) * NC + c) * GC * GC; + device const float* lg = lgo + (h * NC + c) * GC; + for (int rt = 0; rt < 4; ++rt) + for (int jt = 0; jt < 4; ++jt) simdgroup_store(st[rt][jt], &Sm[32 * sg + 8 * rt][8 * jt], 32); + threadgroup_barrier(mem_flags::mem_threadgroup); + // P1 = W S0 (into X) and P2 = Q S0 (into Y), the S tiles read once for both + simdgroup_float8x8 acc1[4], acc2[4]; + for (int jt = 0; jt < 4; ++jt) { + acc1[jt] = make_filled_simdgroup_matrix(0.0f); + acc2[jt] = make_filled_simdgroup_matrix(0.0f); + } + device const float* qrow = qn + ((t0 + 8 * sg) * hkn + hk) * S; + if (gdn_probe != 1) +#pragma clang loop unroll(full) + for (int kb = 0; kb < 16; ++kb) { + simdgroup_float8x8 aw, aq, bs; + simdgroup_load(aw, Wc + (8 * sg) * S + 8 * kb, S); + simdgroup_load(aq, qrow + 8 * kb, hkn * S); + for (int jt = 0; jt < 4; ++jt) { + simdgroup_load(bs, &Sm[8 * kb][8 * jt], 32); + simdgroup_multiply_accumulate(acc1[jt], aw, bs, acc1[jt]); + simdgroup_multiply_accumulate(acc2[jt], aq, bs, acc2[jt]); + } + } + for (int jt = 0; jt < 4; ++jt) { + simdgroup_store(acc1[jt], &X[8 * sg][8 * jt], 32); + simdgroup_store(acc2[jt], &Y[8 * sg][8 * jt], 32); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (int idx = tid; idx < GC * 32; idx += 128) { + const int t = idx >> 5, j = idx & 31; + Dl[t][j] = t < nb ? Uc[t * S + j0 + j] - X[t][j] : 0.0f; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + // intra = M delta (into X) + for (int jt = 0; jt < 4; ++jt) acc1[jt] = make_filled_simdgroup_matrix(0.0f); + if (gdn_probe != 2) +#pragma clang loop unroll(full) + for (int kb = 0; kb < 4; ++kb) { + simdgroup_float8x8 am, bd; + simdgroup_load(am, Mc + (8 * sg) * GC + 8 * kb, GC); + for (int jt = 0; jt < 4; ++jt) { + simdgroup_load(bd, &Dl[8 * kb][8 * jt], 32); + simdgroup_multiply_accumulate(acc1[jt], am, bd, acc1[jt]); + } + } + for (int jt = 0; jt < 4; ++jt) simdgroup_store(acc1[jt], &X[8 * sg][8 * jt], 32); + threadgroup_barrier(mem_flags::mem_threadgroup); + const float lgl = lg[nb - 1], gl = exp(lgl); + if (gdn_probe != 4) + for (int idx = tid; idx < GC * 32; idx += 128) { + const int t = idx >> 5, j = idx & 31; + if (t < nb) { + o[((t0 + t) * hv + h) * S + j0 + j] = fma(exp(lg[t]), Y[t][j], X[t][j]) * scale; + Dl[t][j] *= exp(lgl - lg[t]); + } else { + Dl[t][j] = 0.0f; + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + // S = G_L S + K^T delta' + for (int rt = 0; rt < 4; ++rt) + for (int jt = 0; jt < 4; ++jt) { + st[rt][jt].thread_elements()[0] *= gl; + st[rt][jt].thread_elements()[1] *= gl; + } + if (gdn_probe != 3) +#pragma clang loop unroll(full) + for (int kb = 0; kb < 4; ++kb) { + simdgroup_float8x8 bd[4]; + for (int jt = 0; jt < 4; ++jt) simdgroup_load(bd[jt], &Dl[8 * kb][8 * jt], 32); + for (int rt = 0; rt < 4; ++rt) { + simdgroup_float8x8 ak; + simdgroup_load(ak, kn + ((t0 + 8 * kb) * hkn + hk) * S + 32 * sg + 8 * rt, hkn * S, ulong2(0, 0), true); + for (int jt = 0; jt < 4; ++jt) simdgroup_multiply_accumulate(st[rt][jt], ak, bd[jt], st[rt][jt]); + } + } + } + for (int rt = 0; rt < 4; ++rt) + for (int jt = 0; jt < 4; ++jt) + simdgroup_store(st[rt][jt], state + ((32 * sg + 8 * rt) * hv + h) * S + j0 + 8 * jt, hv * S); +} diff --git a/metal/src/engine/prompt_chain.inc b/metal/src/engine/prompt_chain.inc index 2a0e7592..2e3b1604 100644 --- a/metal/src/engine/prompt_chain.inc +++ b/metal/src/engine/prompt_chain.inc @@ -68,7 +68,14 @@ bool Window::pc_setup(int C) { auto F16 = [&](size_t n) { return cx_->alloc(2 * n); }; b.R = F32(MT * HC * N); b.bo = F32(MT * N); b.inj[0] = F32(MT * HC); b.inj[1] = F32(MT * HC); b.xn = F32(MT * HC * N); b.xnh = F16(MT * HC * N); b.V = F32(MT * (LR + HC)); b.loh = F16(MT * LR); b.mixed = F32(MT * N); b.mixh = F16(MT * N); - b.qkv = F32(MT * 10240); b.z = F32(MT * 6144); b.al = F32(MT * 48); b.be = F32(MT * 48); b.yg = F32(MT * 6144); + b.fused = gdn_fused_inputs(cx_->device_name()); + if (b.fused) { // the four GDN input projections as one GEMM: [qkv | z | alpha | beta] rows of 16480 floats + b.yf = F32(MT * 16480); + b.qkv = F32(1); b.z = F32(1); b.al = F32(1); b.be = F32(1); + } else { + b.qkv = F32(MT * 10240); b.z = F32(MT * 6144); b.al = F32(MT * 48); b.be = F32(MT * 48); + } + b.yg = F32(MT * 6144); b.ygh = F16(MT * 6144); b.gqn = F32(MT * 16 * 128); b.gkn = F32(MT * 16 * 128); b.gvc = F32(MT * 6144); b.ggb = F32(MT * 48 * 2); b.gkq = F32(MT * 16); b.go = F32(MT * 6144); b.qfull = F32(MT * 12288); b.kcur = F32(MT * 512); b.vcur = F32(MT * 512); b.iqr = F32(MT * 512); b.ikr = F32(MT * 128); @@ -81,8 +88,14 @@ bool Window::pc_setup(int C) { b.stok = cx_->alloc(4 * (size_t) b.maxrows); b.sw = F32(b.maxrows); b.pos = cx_->alloc(4 * MT * TOPK); b.XS = F16((size_t) b.maxrows * N); b.HS = F16((size_t) b.maxrows * NFF); b.YE = F32((size_t) b.maxrows * N); b.yr = F32(MT * N); b.gsh = F32(MT * NFF); b.ush = F32(MT * NFF); b.hh = F16(MT * NFF); b.ys = F32(MT * N); b.sgv = F32(MT); - b.WD = F16((size_t) (LR + HC) * HC * N); b.WU = F16((size_t) HC * N * LR); b.Wqkv = F16((size_t) 10240 * N); - b.Wz = F16((size_t) 6144 * N); b.Wal = F16((size_t) 48 * N); b.Wbe = F16((size_t) 48 * N); b.Wout = F16((size_t) N * 6144); + b.WD = F16((size_t) (LR + HC) * HC * N); b.WU = F16((size_t) HC * N * LR); + if (b.fused) { + b.Wcat = F16((size_t) 16480 * N); + b.Wqkv = F16(1); b.Wz = F16(1); b.Wal = F16(1); b.Wbe = F16(1); + } else { + b.Wqkv = F16((size_t) 10240 * N); b.Wz = F16((size_t) 6144 * N); b.Wal = F16((size_t) 48 * N); b.Wbe = F16((size_t) 48 * N); + } + b.Wout = F16((size_t) N * 6144); b.Wq = F16((size_t) 12288 * N); b.Wk = F16((size_t) 512 * N); b.Wv = F16((size_t) 512 * N); b.Wiq = F16((size_t) 512 * N); b.Wik = F16((size_t) 128 * N); b.Wr = F16((size_t) NEXP * N); b.Wsg = F16((size_t) N); b.Wshg = F16((size_t) NFF * N); b.Wshu = F16((size_t) NFF * N); b.Wshd = F16((size_t) N * NFF); @@ -150,7 +163,8 @@ bool Window::pc_chunk(const int64_t* tokens, int nT, int64_t pos0, std::string& ds.push_back(std::move(d)); }; auto gemm = [&](const mtl::Buffer& A, const mtl::Buffer& B, const mtl::Buffer& Y, int M, int Nn, int K) { - const int tm = 64, tn = Nn <= 64 ? 32 : 64; + int tm = 64, tn = Nn <= 64 ? 32 : 64; + gemm_tile(cx_->device_name(), Nn, K, tm, tn); const std::string fn = "gemm_f16_" + std::to_string(tm) + "_" + std::to_string(tn) + "_4"; PcGemmArgs g{M, Nn, K, 0}; D(P_(b.lib, fn), {mtl::Arg::B(A), mtl::Arg::B(B), mtl::Arg::B(Y), mtl::Arg::V(g)}, (Nn + tn - 1) / tn, (M + tm - 1) / tm, 128); @@ -191,29 +205,50 @@ bool Window::pc_chunk(const int64_t* tokens, int nT, int64_t pos0, std::string& const std::string bl = "blk." + std::to_string(l) + "."; hc_read(bl + "hc_attn", l > 0 && !(l == 1 && ple_on_)); if (l % 4 != 3) { - dq(T(bl + "attn_qkv.weight"), b.Wqkv); - dq(T(bl + "attn_gate.weight"), b.Wz); - dq(T(bl + "ssm_alpha.weight"), b.Wal); - dq(T(bl + "ssm_beta.weight"), b.Wbe); dq(T(bl + "ssm_out.weight"), b.Wout); - gemm(b.mixh, b.Wqkv, b.qkv, nT, 10240, N); - gemm(b.mixh, b.Wz, b.z, nT, 6144, N); - gemm(b.mixh, b.Wal, b.al, nT, 48, N); - gemm(b.mixh, b.Wbe, b.be, nT, 48, N); PcGdnPArgs ga{(uint32_t) nT, 16, 48, 10240, eps_, 0}; - D(P_(b.lgdn, "gdn_pre"), - {mtl::Arg::B(b.qkv), mtl::Arg::B(ghist_[hp][(size_t) gi]), mtl::Arg::B(W_, T(bl + "ssm_conv1d.weight").offset), - mtl::Arg::B(b.al), mtl::Arg::B(b.be), mtl::Arg::B(W_, T(bl + "ssm_dt.bias").offset), - mtl::Arg::B(W_, T(bl + "ssm_a").offset), mtl::Arg::B(b.gqn), mtl::Arg::B(b.gkn), mtl::Arg::B(b.gvc), - mtl::Arg::B(b.ggb), mtl::Arg::B(b.gkq), mtl::Arg::B(ghist_[1 - hp][(size_t) gi]), mtl::Arg::V(ga)}, - 16 + 24, nT, 256); + if (b.fused) { + dq(T(bl + "attn_qkv.weight"), b.Wcat, 0); + dq(T(bl + "attn_gate.weight"), b.Wcat, (size_t) 2 * 10240 * N); + dq(T(bl + "ssm_alpha.weight"), b.Wcat, (size_t) 2 * (10240 + 6144) * N); + dq(T(bl + "ssm_beta.weight"), b.Wcat, (size_t) 2 * (10240 + 6144 + 48) * N); + gemm(b.mixh, b.Wcat, b.yf, nT, 16480, N); + D(P_(b.lgdn, "gdn_pre", mtl::Constants().i(7, 16480), "gdn_pre_f"), + {mtl::Arg::B(b.yf), mtl::Arg::B(ghist_[hp][(size_t) gi]), mtl::Arg::B(W_, T(bl + "ssm_conv1d.weight").offset), + mtl::Arg::B(b.yf, (size_t) 4 * (10240 + 6144)), mtl::Arg::B(b.yf, (size_t) 4 * (10240 + 6144 + 48)), + mtl::Arg::B(W_, T(bl + "ssm_dt.bias").offset), mtl::Arg::B(W_, T(bl + "ssm_a").offset), mtl::Arg::B(b.gqn), + mtl::Arg::B(b.gkn), mtl::Arg::B(b.gvc), mtl::Arg::B(b.ggb), mtl::Arg::B(b.gkq), + mtl::Arg::B(ghist_[1 - hp][(size_t) gi]), mtl::Arg::V(ga)}, + 16 + 24, nT, 256); + } else { + dq(T(bl + "attn_qkv.weight"), b.Wqkv); + dq(T(bl + "attn_gate.weight"), b.Wz); + dq(T(bl + "ssm_alpha.weight"), b.Wal); + dq(T(bl + "ssm_beta.weight"), b.Wbe); + gemm(b.mixh, b.Wqkv, b.qkv, nT, 10240, N); + gemm(b.mixh, b.Wz, b.z, nT, 6144, N); + gemm(b.mixh, b.Wal, b.al, nT, 48, N); + gemm(b.mixh, b.Wbe, b.be, nT, 48, N); + D(P_(b.lgdn, "gdn_pre"), + {mtl::Arg::B(b.qkv), mtl::Arg::B(ghist_[hp][(size_t) gi]), mtl::Arg::B(W_, T(bl + "ssm_conv1d.weight").offset), + mtl::Arg::B(b.al), mtl::Arg::B(b.be), mtl::Arg::B(W_, T(bl + "ssm_dt.bias").offset), + mtl::Arg::B(W_, T(bl + "ssm_a").offset), mtl::Arg::B(b.gqn), mtl::Arg::B(b.gkn), mtl::Arg::B(b.gvc), + mtl::Arg::B(b.ggb), mtl::Arg::B(b.gkq), mtl::Arg::B(ghist_[1 - hp][(size_t) gi]), mtl::Arg::V(ga)}, + 16 + 24, nT, 256); + } D(P_(b.lgdn, gdn_scan_name(cx_->device_name(), nT), mtl::Constants().i(6, 0)), {mtl::Arg::B(gst_[(size_t) gi]), mtl::Arg::B(b.gqn), mtl::Arg::B(b.gkn), mtl::Arg::B(b.gvc), mtl::Arg::B(b.ggb), mtl::Arg::B(b.gkq), mtl::Arg::B(b.go), mtl::Arg::V(ga)}, 48 * 4, 1, 32 * 4); - D(P_(b.lgdn, "gdn_post"), {mtl::Arg::B(b.go), mtl::Arg::B(b.z), mtl::Arg::B(W_, T(bl + "ssm_norm.weight").offset), - mtl::Arg::B(b.ygh), mtl::Arg::B(b.yg), mtl::Arg::V(ga)}, - 48, nT, 128); + if (b.fused) + D(P_(b.lgdn, "gdn_post", mtl::Constants().i(7, 16480), "gdn_post_f"), + {mtl::Arg::B(b.go), mtl::Arg::B(b.yf, (size_t) 4 * 10240), mtl::Arg::B(W_, T(bl + "ssm_norm.weight").offset), + mtl::Arg::B(b.ygh), mtl::Arg::B(b.yg), mtl::Arg::V(ga)}, + 48, nT, 128); + else + D(P_(b.lgdn, "gdn_post"), {mtl::Arg::B(b.go), mtl::Arg::B(b.z), mtl::Arg::B(W_, T(bl + "ssm_norm.weight").offset), + mtl::Arg::B(b.ygh), mtl::Arg::B(b.yg), mtl::Arg::V(ga)}, + 48, nT, 128); gemm(b.ygh, b.Wout, b.bo, nT, N, 6144); ++gi; } else { diff --git a/metal/src/engine/window.cpp b/metal/src/engine/window.cpp index c18bf9bc..5ca6d226 100644 --- a/metal/src/engine/window.cpp +++ b/metal/src/engine/window.cpp @@ -69,6 +69,23 @@ static const char* gdn_scan_name(const std::string& device, int T) { return "gdn_scanr_4"; } +// The M5 family's dense GEMM tiles for the prompt (bit-identical to the 64 x 64 tile: the tile only splits the output; measured on +// an M5 Max, T = 2048 / 4096): the GDN out projection (N 2560, K 6144) 64 x 128 (1.17 -> 0.99 ms), the wide input projections +// (N >= 6144) 128 x 64. Other chips keep 64 x 64 (M4: no gain). STRATA_METAL_GEMM_TILES=0 keeps the old tiles everywhere. +static void gemm_tile(const std::string& device, int Nn, int K, int& tm, int& tn) { + static const bool off = [] { const char* e = std::getenv("STRATA_METAL_GEMM_TILES"); return e && std::string(e) == "0"; }(); + if (off || device.rfind("Apple M5", 0) != 0) return; + if (Nn == 2560 && K == 6144) { tm = 64; tn = 128; } + else if (Nn >= 6144) { tm = 128; tn = 64; } +} +// The four GDN input projections (qkv, z, alpha, beta) as ONE GEMM with a 16480 float output row (M5 family: 3.09 -> 2.87 ms a layer at +// T = 2048; gdn_pre / gdn_post read the pieces at that stride, function constant 7). Bit-identical to the separate GEMMs. +// STRATA_METAL_GDN_FUSE=0 keeps the separate ones. +static bool gdn_fused_inputs(const std::string& device) { + static const bool off = [] { const char* e = std::getenv("STRATA_METAL_GDN_FUSE"); return e && std::string(e) == "0"; }(); + return !off && device.rfind("Apple M5", 0) == 0; +} + namespace { constexpr int N = 2560, HC = 4, LR = 320, NFF = 640, TOPK = 10, NEXP = 512, MAXT = 8, NVOCAB_MAX = 248320; @@ -118,14 +135,15 @@ double now_ms() { return std::chrono::duration(std::chrono:: struct PromptBufs { int lib = -1, lgdn = -1, lqsa = -1; bool k4 = false; - bool v3e = false; // the M5's expert kernels (v3): not for the trellis types, which have only v2 + bool v3e = false; + bool fused = false; // the GDN input projections as one GEMM (gdn_fused_inputs) // the M5's expert kernels (v3): not for the trellis types, which have only v2 int C = 0, maxrows = 0; double gpu_ms = 0, host_ms = 0, mtp_ms = 0; int gu3[4] = {}, dn3[4] = {}; mtl::Buffer R, bo, inj[2], xn, xnh, V, loh, mixed, mixh, qkv, z, al, be, yg, ygh, gqn, gkn, gvc, ggb, gkq, go, qfull, kcur, vcur, iqr, ikr, qcur, qcurh, qidx, scores, qids, part, XQ, xqh, logits, ids, wts, bcnt, boff, eoff, tiles, meta, stok, sw, pos, XS, HS, YE, yr, gsh, ush, hh, ys, sgv, WD, WU, Wqkv, Wz, Wal, Wbe, Wout, Wq, Wk, Wv, Wiq, Wik, Wr, - Wsg, Wshg, Wshu, Wshd, pemb, pembh, pkey, pval, keyn, qn, gated, normW, Wpk, Wpv, mixr; + Wsg, Wshg, Wshu, Wshd, yf, Wcat, pemb, pembh, pkey, pval, keyn, qn, gated, normW, Wpk, Wpv, mixr; }; // The vision path (--vision, GENI requests), from the shared host code: the image rows of the prompt being read diff --git a/metal/tests/gdn_chunk_bench.cpp b/metal/tests/gdn_chunk_bench.cpp index 2ec86f45..c439c10a 100644 --- a/metal/tests/gdn_chunk_bench.cpp +++ b/metal/tests/gdn_chunk_bench.cpp @@ -49,10 +49,10 @@ int main(int argc, char** argv) { mtl::Buffer qkv = F((size_t)TMAX * CH), al = F((size_t)TMAX * HV), be = F((size_t)TMAX * HV), z = F((size_t)TMAX * HV * S), cw = F(CH * 4), dt = F(HV), sa = F(HV), gam = F(S), st0 = F((size_t)S * HV * S), stX = F((size_t)S * HV * S), stRef = F((size_t)S * HV * S), h0 = F(CH * 3), hOut = F(CH * 3), yh = cx.alloc(2 * (size_t)TMAX * HV * S), - yB = F((size_t)TMAX * HV * S), qn = F((size_t)TMAX * HK * S), kn = F((size_t)TMAX * HK * S), + yB = F((size_t)TMAX * HV * S), qn = F((size_t)(TMAX + 32) * HK * S), kn = F((size_t)(TMAX + 32) * HK * S), vc = F((size_t)TMAX * HV * S), gb = F(2 * (size_t)TMAX * HV), kq = F((size_t)TMAX * HK), o = F((size_t)TMAX * HV * S), oRef = F((size_t)TMAX * HV * S), cU = F((size_t)HV * NCM * GC * S), - cW = F((size_t)HV * NCM * GC * S), clg = F((size_t)HV * NCM * GC), cD = F((size_t)HV * NCM * GC * S); + cW = F((size_t)HV * NCM * GC * S), clg = F((size_t)HV * NCM * GC), cD = F((size_t)HV * NCM * GC * S), cM = F((size_t)HV * NCM * GC * GC); ref::Rng r(21); for (size_t i = 0; i < (size_t)TMAX * CH; ++i) qkv.as()[i] = r.sym() * 2.0f; for (size_t i = 0; i < (size_t)TMAX * HV; ++i) { al.as()[i] = r.sym() * 3.0f; be.as()[i] = r.sym() * 2.0f; } @@ -73,7 +73,8 @@ int main(int argc, char** argv) { {"gdn_scanr_8_4", HV * 4, 256}, {"gdn_scanr_2_8", HV * 4, 64}, {"gdn_scanr_2_4", HV * 4, 64}}; std::vector scan; for (const Sv& v : svs) scan.push_back(cx.pipeline(lib, v.nm, std::string(v.nm) == "gdn_scan_v" || std::string(v.nm).find("scanr") != std::string::npos ? mtl::Constants().i(6, 0) : mtl::Constants())); - mtl::Pipeline pcp = cx.pipeline(lib, "gdn_cprep"), pcs = cx.pipeline(lib, "gdn_cstate"), pco = cx.pipeline(lib, "gdn_cout"); + mtl::Pipeline pcp = cx.pipeline(lib, "gdn_cprep"), pcs = cx.pipeline(lib, "gdn_cstate"), pco = cx.pipeline(lib, "gdn_cout"), pcp2 = cx.pipeline(lib, "gdn_cprep2"), pcs2 = cx.pipeline(lib, "gdn_cstate2"); + bool v2 = false; // chunk_d builds the v2 chunked form (gdn_cprep2 + gdn_cstate2) std::printf("pipeline limits (max threads / simd / static tg mem; threads asked):"); for (size_t i = 0; i < scan.size(); ++i) std::printf(" %s %d/%d/%d (%d)", svs[i].nm, scan[i].max_threads, scan[i].simd_width, scan[i].static_tg_mem, svs[i].tg); std::printf("\n pre %d/%d/%d (256) cprep %d/%d/%d (256) cstate %d/%d/%d (256) cout %d/%d/%d (128) post %d/%d/%d (128)\n", @@ -111,6 +112,19 @@ int main(int argc, char** argv) { auto chunk_d = [&](int t0, int n, const mtl::Buffer& st, const mtl::Buffer& out, std::vector& ds) { GdnPArgs a{(uint32_t)n, HK, HV, CH, 1e-6f, 1u}; const uint32_t nc = (n + GC - 1) / GC; + if (v2) { + mtl::Dispatch f1; f1.p = &pcp2; + f1.args = {mtl::Arg::B(qn, (size_t)t0 * HK * S * 4), mtl::Arg::B(kn, (size_t)t0 * HK * S * 4), + mtl::Arg::B(vc, (size_t)t0 * HV * S * 4), mtl::Arg::B(gb, (size_t)t0 * HV * 8), mtl::Arg::B(cU), mtl::Arg::B(cW), + mtl::Arg::B(clg), mtl::Arg::B(cM), mtl::Arg::V(a)}; + f1.grid[0] = HV; f1.grid[1] = nc; f1.tg[0] = 256; ds.push_back(f1); + mtl::Dispatch f2; f2.p = &pcs2; + f2.args = {mtl::Arg::B(st), mtl::Arg::B(qn, (size_t)t0 * HK * S * 4), mtl::Arg::B(kn, (size_t)t0 * HK * S * 4), + mtl::Arg::B(cU), mtl::Arg::B(cW), mtl::Arg::B(clg), mtl::Arg::B(cM), mtl::Arg::B(out, (size_t)t0 * HV * S * 4), + mtl::Arg::V(a)}; + f2.grid[0] = HV * 4; f2.tg[0] = 128; ds.push_back(f2); + return; + } mtl::Dispatch e1; e1.p = &pcp; e1.args = {mtl::Arg::B(qn, (size_t)t0 * HK * S * 4), mtl::Arg::B(kn, (size_t)t0 * HK * S * 4), mtl::Arg::B(vc, (size_t)t0 * HV * S * 4), mtl::Arg::B(gb, (size_t)t0 * HV * 8), mtl::Arg::B(cU), mtl::Arg::B(cW), @@ -226,10 +240,10 @@ int main(int argc, char** argv) { for (int T : Ts) { // the variants, each from st0, over tokens [0, T) struct V { const char* name; int kind; }; // kind: 0..2 scanr IB 2/4/8, 10 chunked - for (V v : {V{"scanr_4", 1}, V{"chunked", 10}}) { + for (V v : {V{"scanr_4", 1}, V{"chunked", 10}, V{"chunked2", 11}}) { copy_st0(stX); std::vector ds; - if (v.kind == 10) chunk_d(0, T, stX, o, ds); else scan_d(v.kind, 0, T, stX, o, ds); + v2 = v.kind == 11; if (v.kind >= 10) chunk_d(0, T, stX, o, ds); else scan_d(v.kind, 0, T, stX, o, ds); v2 = false; cx.run(ds); for (int h : heads) { std::vector St, ro; initial(h, St); oracle(h, 0, T, St, ro); @@ -247,22 +261,39 @@ int main(int argc, char** argv) { const std::pair splits[] = {{37, 963}, {1024, 1024}, {2048, 2047}, {31, 33}, {1, 4095}}; for (auto [A, B] : splits) { if (A + B > TMAX) continue; - const char* nm[4] = {"chunk+chunk", "scan+chunk", "chunk+scan", "scan+scan"}; - for (int m = 0; m < 4; ++m) { + const char* nm[8] = {"chunk+chunk", "scan+chunk", "chunk+scan", "scan+scan", "chunk2+chunk2", "scan+chunk2", "chunk2+scan", "-"}; + for (int m = 0; m < 8; ++m) { + v2 = m >= 4; + if (v2 && m == 7) continue; // scan+scan has no chunked part copy_st0(stX); std::vector d1, d2; - if (m == 0 || m == 2) chunk_d(0, A, stX, o, d1); else scan_d(1, 0, A, stX, o, d1); - if (m == 0 || m == 1) chunk_d(A, B, stX, o, d2); else scan_d(1, A, B, stX, o, d2); - cx.run(d1); cx.run(d2); + if (m % 4 == 0 || m % 4 == 2) chunk_d(0, A, stX, o, d1); else scan_d(1, 0, A, stX, o, d1); + if (m % 4 == 0 || m % 4 == 1) chunk_d(A, B, stX, o, d2); else scan_d(1, A, B, stX, o, d2); + cx.run(d1); cx.run(d2); v2 = false; for (int h : {heads[0], heads.back()}) { std::vector St, ro; initial(h, St); oracle(h, 0, A + B, St, ro); Err eo = cmp_o(o, h, 0, A + B, ro), es = cmp_s(stX, h, St); const bool ok = eo.l2 < 3e-3 && es.l2 < 3e-3 && !eo.nonfinite && !es.nonfinite; fails += !ok; - std::printf("split %5d + %5d %-12s head %2d: o rel %.2e state rel %.2e %s\n", A, B, nm[m], h, eo.l2, es.l2, ok ? "PASS" : "FAIL"); + std::printf("split %5d + %5d %-14s head %2d: o rel %.2e state rel %.2e %s\n", A, B, nm[m], h, eo.l2, es.l2, ok ? "PASS" : "FAIL"); } } } + std::printf("== bitwise: gdn_scanr_4_8 / _4_4 / _4_2 / _8_8 / _2_8 o and state vs gdn_scanr_4\n"); + for (int T : Ts) { + if (T > 16384) continue; + copy_st0(stX); + std::vector d0; scan_d(1, 0, T, stX, o, d0); cx.run(d0); + std::vector oref(o.as(), o.as() + (size_t)T * HV * S), sref(stX.as(), stX.as() + (size_t)S * HV * S); + for (int w : {3, 8, 9, 10, 12}) { + copy_st0(stX); + std::memset(o.ptr, 0, (size_t)T * HV * S * 4); + std::vector d1; scan_d(w, 0, T, stX, o, d1); cx.run(d1); + const bool eq = std::memcmp(o.ptr, oref.data(), oref.size() * 4) == 0 && std::memcmp(stX.ptr, sref.data(), sref.size() * 4) == 0; + fails += !eq; + std::printf("T %5d %-14s %s\n", T, svs[w].nm, eq ? "BITWISE EQUAL" : "DIFFERS"); + } + } std::printf("== fused scan+post vs pre/scanr_4/post: y rel L2, fp16 y mismatches, state rel L2\n"); for (int T : Ts) { if (T > 8192) continue; @@ -309,6 +340,28 @@ int main(int argc, char** argv) { const double tc = timeit(dc), tc1 = timeit({dc[0]}), tc2 = timeit({dc[1]}), tc3 = timeit({dc[2]}); const double base = tp + ts1 + tpo, ch = tp + tc + tpo; std::printf(" | %8.3f (%7.3f %7.3f %7.3f) | %8.3f %8.3f %5.2f | best %s stage %.3f = x%.3f (scan x%.3f)\n", tc, tc1, tc2, tc3, base, ch, base / ch, svs[wbest].nm, tp + tbest + tpo, base / (tp + tbest + tpo), ts1 / tbest); + { + v2 = true; + std::vector dc2; + chunk_d(0, T, stX, o, dc2); + const double t2 = timeit(dc2), t2a = timeit({dc2[0]}), t2b = timeit({dc2[1]}); + v2 = false; + std::printf(" chunked v2 %.3f (cprep2 %.3f cstate2 %.3f); stage pre+v2+post %.3f = x%.3f vs scanr_4 stage (scan x%.3f)\n", t2, t2a, t2b, + tp + t2 + tpo, base / (tp + t2 + tpo), ts1 / t2); + } + if (std::getenv("GDN_PROBE_RUN")) { + v2 = true; + std::vector dd; + chunk_d(0, T, stX, o, dd); + for (int pr = 1; pr <= 3; ++pr) { + mtl::Pipeline a1 = cx.pipeline(lib, "gdn_cprep2", mtl::Constants().i(6, pr)), a2 = cx.pipeline(lib, "gdn_cstate2", mtl::Constants().i(6, pr)); + mtl::Dispatch d1 = dd[0], d2 = dd[1]; + d1.p = &a1; d2.p = &a2; + const double x1 = timeit({d1}), x2 = timeit({d2}); + std::printf(" probe %d: cprep2 %.3f cstate2 %.3f ms\n", pr, x1, x2); + } + v2 = false; + } { double tf[3]; for (int w = 0; w < 3; ++w) { std::vector d1; fused_d(w, 0, T, stX, d1); tf[w] = timeit(d1); } diff --git a/metal/tests/gdn_layer_bench.cpp b/metal/tests/gdn_layer_bench.cpp new file mode 100644 index 00000000..f9455f8c --- /dev/null +++ b/metal/tests/gdn_layer_bench.cpp @@ -0,0 +1,184 @@ +// metal/tests/gdn_layer_bench.cpp - one Flash-Next GDN layer's prompt cost, piece by piece (30 Oct GDN-M phase 2). +// Real shapes (N 2560, qkv 10240, z 6144, alpha/beta 48, out 2560 x 6144), a chunk of T rows (the engine's prompt chunk is +// 2048): dq (Q6_K -> fp16 weights), the four input GEMMs separate and fused into one, tile choices, gdn_pre, the scan, gdn_post, +// the out GEMM; each alone (GPU time) and the layer in order, plus the TFLOP/s of every GEMM. Random weights: a timing +// of the byte and FLOP stream, not a numerical check. +// gdn_layer_bench [--T 2048] [--reps 7] [--scan gdn_scanr_4] +#include "mtl_rt.h" +#include "ref_quant.h" + +#include +#include +#include +#include +#include +#include + +namespace { +constexpr int N = 2560, HK = 16, HV = 48, CH = 10240, ZD = 6144, S = 128, TQ6K = 14; +struct GemmArgs { int M, N, K, pad; }; +struct DqArgs { uint32_t n_in, n_out, row_bytes, perm; }; +struct GdnPArgs { uint32_t n_tok, h_k, h_v, channels; float eps; uint32_t f32; }; +double median(std::vector v) { std::sort(v.begin(), v.end()); return v[v.size() / 2]; } +} // namespace + +int main(int argc, char** argv) { + int T = 2048, reps = 7; + std::string scan_name = "gdn_scanr_4"; + for (int i = 1; i < argc; ++i) { + std::string a = argv[i]; + if (a == "--T") T = std::atoi(argv[++i]); + else if (a == "--reps") reps = std::atoi(argv[++i]); + else if (a == "--scan") scan_name = argv[++i]; + } + mtl::Context cx; + const int lib = cx.compile({"quant.metal", "units.metal", "mma.metal", "dense_mm.metal"}); + const int lgdn = cx.compile({"gdn.metal", "gdn_prompt.metal"}, "#define NO_GGML_COMMON 1\n"); + std::printf("device %s, chunk T %d, scan %s\n", cx.device_name().c_str(), T, scan_name.c_str()); + ref::Rng r(5); + auto fill_half = [&](mtl::Buffer& b, size_t n, float sc) { + for (size_t i = 0; i < n; ++i) b.as()[i] = ref::f32_to_f16(r.sym() * sc); + }; + const int rows[5] = {CH, ZD, 48, 48, N}; // qkv, z, alpha, beta, out + const int kin[5] = {N, N, N, N, ZD}; + mtl::Buffer mixh = cx.alloc(2 * (size_t)T * N), ygh = cx.alloc(2 * (size_t)T * ZD); + fill_half(mixh, (size_t)T * N, 1.0f); + fill_half(ygh, (size_t)T * ZD, 1.0f); + mtl::Buffer Wq[5], Wh[5], Y[5]; + mtl::Buffer qsrc[5]; + for (int i = 0; i < 5; ++i) { + Wh[i] = cx.alloc(2 * (size_t)rows[i] * kin[i]); + fill_half(Wh[i], (size_t)rows[i] * kin[i], 0.03f); + Y[i] = cx.alloc(4 * (size_t)T * rows[i]); + const size_t rb = ref::row_bytes(TQ6K, kin[i]); + qsrc[i] = cx.alloc(rb * rows[i]); + for (size_t j = 0; j < rb * rows[i]; ++j) qsrc[i].as()[j] = (uint8_t)(r.uni() * 255.0f); + // keep the fp16 scale of each Q6_K block sane (the last two bytes of a 210 byte block) + for (size_t j = 0; j + 210 <= rb * rows[i]; j += 210) { qsrc[i].as()[(j + 208) / 2] = ref::f32_to_f16(0.01f); } + } + const int NF = CH + ZD + 48 + 48; + mtl::Buffer WF = cx.alloc(2 * (size_t)NF * N), YF = cx.alloc(4 * (size_t)T * NF); + fill_half(WF, (size_t)NF * N, 0.03f); + + auto timeit = [&](const std::vector& ds) { + cx.warm(ds, 0.3); + std::vector t; + for (int i = 0; i < reps; ++i) t.push_back(cx.run(ds)); + return median(t) * 1e3; + }; + auto dq_d = [&](int i) { + DqArgs a{(uint32_t)kin[i], (uint32_t)rows[i], (uint32_t)ref::row_bytes(TQ6K, kin[i]), 0}; + static mtl::Pipeline p = cx.pipeline(lib, "dq_f16_14"); + mtl::Dispatch d; d.p = &p; + d.args = {mtl::Arg::B(qsrc[i]), mtl::Arg::B(Wh[i]), mtl::Arg::V(a)}; + d.grid[0] = (kin[i] / 32 + 63) / 64; d.grid[1] = rows[i]; d.tg[0] = 64; + return d; + }; + auto gemm_d = [&](const mtl::Buffer& A, const mtl::Buffer& B, const mtl::Buffer& Yb, int M, int Nn, int K, int tm, int tn, int sgn = 4) { + static std::vector> cache; + const std::string fn = "gemm_f16_" + std::to_string(tm) + "_" + std::to_string(tn) + "_" + std::to_string(sgn); + mtl::Pipeline* p = nullptr; + for (auto& c : cache) if (c.first == fn) p = c.second; + if (!p) { p = new mtl::Pipeline(cx.pipeline(lib, fn)); cache.push_back({fn, p}); } + GemmArgs g{M, Nn, K, 0}; + mtl::Dispatch d; d.p = p; + d.args = {mtl::Arg::B(A), mtl::Arg::B(B), mtl::Arg::B(Yb), mtl::Arg::V(g)}; + d.grid[0] = (Nn + tn - 1) / tn; d.grid[1] = (M + tm - 1) / tm; d.tg[0] = 32 * sgn; + return d; + }; + auto tfl = [&](int Nn, int K, double ms) { return 2.0 * T * Nn * K / (ms * 1e-3) / 1e12; }; + + std::printf("== dq (Q6_K -> fp16), ms: qkv %.3f z %.3f alpha %.3f beta %.3f out %.3f\n", timeit({dq_d(0)}), timeit({dq_d(1)}), + timeit({dq_d(2)}), timeit({dq_d(3)}), timeit({dq_d(4)})); + std::printf("== GEMMs (tile TMxTN, 4 simdgroups): ms and TFLOP/s\n"); + struct Sh { const char* nm; int i; }; + struct Tl { int tm, tn, sg; }; + const std::vector tiles = {{64, 32, 4}, {64, 64, 4}, {128, 64, 4}, {64, 128, 4}, {128, 128, 4}, {128, 128, 8}, {128, 64, 8}, + {64, 64, 8}, {256, 64, 8}, {64, 256, 8}, {128, 32, 4}, {32, 128, 4}}; + for (Sh s : {Sh{"qkv", 0}, Sh{"z", 1}, Sh{"alpha", 2}, Sh{"out", 4}}) { + std::printf("%-6s N %5d K %4d:", s.nm, rows[s.i], kin[s.i]); + const mtl::Buffer& A = s.i == 4 ? ygh : mixh; + for (const Tl& tl : tiles) { + if (rows[s.i] <= 64 && tl.tn > 32) continue; + const double ms = timeit({gemm_d(A, Wh[s.i], Y[s.i], T, rows[s.i], kin[s.i], tl.tm, tl.tn, tl.sg)}); + std::printf(" %dx%d/%d %.3f (%.0f)", tl.tm, tl.tn, tl.sg, ms, tfl(rows[s.i], kin[s.i], ms)); + } + std::printf("\n"); + } + std::printf("fused qkv+z+alpha+beta N %d:", NF); + double best_f = 1e9; + for (const Tl& tl : tiles) { + const double ms = timeit({gemm_d(mixh, WF, YF, T, NF, N, tl.tm, tl.tn, tl.sg)}); + best_f = std::min(best_f, ms); + std::printf(" %dx%d/%d %.3f (%.0f)", tl.tm, tl.tn, tl.sg, ms, tfl(NF, N, ms)); + } + std::printf("\n"); + // the four input GEMMs as the engine runs them, in order + const double sep = timeit({gemm_d(mixh, Wh[0], Y[0], T, CH, N, 64, 64), gemm_d(mixh, Wh[1], Y[1], T, ZD, N, 64, 64), + gemm_d(mixh, Wh[2], Y[2], T, 48, N, 64, 32), gemm_d(mixh, Wh[3], Y[3], T, 48, N, 64, 32)}); + std::printf("== input projections: separate (engine tiles) %.3f ms, fused best %.3f ms\n", sep, best_f); + + // pre / scan / post + mtl::Buffer qkv = Y[0], z = Y[1], al = Y[2], be = Y[3], cw = cx.alloc(4 * CH * 4), dt = cx.alloc(4 * HV), sa = cx.alloc(4 * HV), + gam = cx.alloc(4 * S), st = cx.alloc(4 * (size_t)S * HV * S), h0 = cx.alloc(4 * CH * 3), h1 = cx.alloc(4 * CH * 3), + qn = cx.alloc(4 * (size_t)T * HK * S), kn = cx.alloc(4 * (size_t)T * HK * S), vc = cx.alloc(4 * (size_t)T * HV * S), + gb = cx.alloc(8 * (size_t)T * HV), kq = cx.alloc(4 * (size_t)T * HK), o = cx.alloc(4 * (size_t)T * HV * S), + yh = cx.alloc(2 * (size_t)T * HV * S), y32 = cx.alloc(4); + for (int i = 0; i < CH * 4; ++i) cw.as()[i] = r.sym() * 0.6f; + for (int i = 0; i < HV; ++i) { dt.as()[i] = r.sym(); sa.as()[i] = -0.2f - r.uni() * 2.0f; } + for (int i = 0; i < S; ++i) gam.as()[i] = 0.5f + r.uni(); + for (size_t i = 0; i < (size_t)T * CH; ++i) qkv.as()[i] = r.sym() * 2.0f; + for (size_t i = 0; i < (size_t)T * HV; ++i) { al.as()[i] = r.sym() * 3.0f; be.as()[i] = r.sym() * 2.0f; } + for (size_t i = 0; i < (size_t)T * ZD; ++i) z.as()[i] = r.sym() * 2.0f; + mtl::Pipeline pre = cx.pipeline(lgdn, "gdn_pre"), post = cx.pipeline(lgdn, "gdn_post"), + scan = cx.pipeline(lgdn, scan_name, mtl::Constants().i(6, 0)); + GdnPArgs ga{(uint32_t)T, HK, HV, CH, 1e-6f, 0}; + mtl::Dispatch dpre; dpre.p = ⪯ + dpre.args = {mtl::Arg::B(qkv), mtl::Arg::B(h0), mtl::Arg::B(cw), mtl::Arg::B(al), mtl::Arg::B(be), mtl::Arg::B(dt), mtl::Arg::B(sa), + mtl::Arg::B(qn), mtl::Arg::B(kn), mtl::Arg::B(vc), mtl::Arg::B(gb), mtl::Arg::B(kq), mtl::Arg::B(h1), mtl::Arg::V(ga)}; + dpre.grid[0] = HK + HV / 2; dpre.grid[1] = T; dpre.tg[0] = 256; + mtl::Dispatch dscan; dscan.p = &scan; + dscan.args = {mtl::Arg::B(st), mtl::Arg::B(qn), mtl::Arg::B(kn), mtl::Arg::B(vc), mtl::Arg::B(gb), mtl::Arg::B(kq), mtl::Arg::B(o), + mtl::Arg::V(ga)}; + dscan.grid[0] = HV * 4; dscan.tg[0] = 128; + mtl::Dispatch dpost; dpost.p = &post; + dpost.args = {mtl::Arg::B(o), mtl::Arg::B(z), mtl::Arg::B(gam), mtl::Arg::B(yh), mtl::Arg::B(y32), mtl::Arg::V(ga)}; + dpost.grid[0] = HV; dpost.grid[1] = T; dpost.tg[0] = 128; + const double tpre = timeit({dpre}), tscan = timeit({dscan}), tpost = timeit({dpost}); + std::printf("== gdn_pre %.3f, scan %.3f, gdn_post %.3f ms (stage %.3f)\n", tpre, tscan, tpost, tpre + tscan + tpost); + { // the fused-stride kernels (function constant 7) against the separate ones: bit for bit + for (int t = 0; t < T; ++t) { + std::memcpy(YF.as() + (size_t)t * NF, qkv.as() + (size_t)t * CH, 4 * CH); + std::memcpy(YF.as() + (size_t)t * NF + CH, z.as() + (size_t)t * ZD, 4 * ZD); + std::memcpy(YF.as() + (size_t)t * NF + CH + ZD, al.as() + (size_t)t * 48, 4 * 48); + std::memcpy(YF.as() + (size_t)t * NF + CH + ZD + 48, be.as() + (size_t)t * 48, 4 * 48); + } + std::memset(h1.ptr, 0, 4 * CH * 3); + cx.run({dpre, dscan, dpost}); + std::vector rqn((char*)qn.ptr, (char*)qn.ptr + 4 * (size_t)T * HK * S), rvc((char*)vc.ptr, (char*)vc.ptr + 4 * (size_t)T * HV * S), + rgb((char*)gb.ptr, (char*)gb.ptr + 8 * (size_t)T * HV), ryh((char*)yh.ptr, (char*)yh.ptr + 2 * (size_t)T * HV * S), + rh((char*)h1.ptr, (char*)h1.ptr + 4 * CH * 3); + mtl::Pipeline preF = cx.pipeline(lgdn, "gdn_pre", mtl::Constants().i(7, NF)), postF = cx.pipeline(lgdn, "gdn_post", mtl::Constants().i(7, NF)); + mtl::Dispatch fpre = dpre, fpost = dpost; + fpre.p = &preF; fpost.p = &postF; + fpre.args[0] = mtl::Arg::B(YF, 0); + fpre.args[3] = mtl::Arg::B(YF, 4 * (size_t)(CH + ZD)); + fpre.args[4] = mtl::Arg::B(YF, 4 * (size_t)(CH + ZD + 48)); + fpost.args[1] = mtl::Arg::B(YF, 4 * (size_t)CH); + std::memset(qn.ptr, 0, rqn.size()); std::memset(vc.ptr, 0, rvc.size()); std::memset(gb.ptr, 0, rgb.size()); + std::memset(yh.ptr, 0, ryh.size()); std::memset(h1.ptr, 0, rh.size()); + cx.run({fpre, dscan, fpost}); + std::printf("fused-stride gdn_pre/gdn_post vs separate: qn %s, vc %s, gate/beta %s, history %s, fp16 y %s\n", + std::memcmp(qn.ptr, rqn.data(), rqn.size()) == 0 ? "equal" : "DIFFER", std::memcmp(vc.ptr, rvc.data(), rvc.size()) == 0 ? "equal" : "DIFFER", + std::memcmp(gb.ptr, rgb.data(), rgb.size()) == 0 ? "equal" : "DIFFER", std::memcmp(h1.ptr, rh.data(), rh.size()) == 0 ? "equal" : "DIFFER", + std::memcmp(yh.ptr, ryh.data(), ryh.size()) == 0 ? "equal" : "DIFFER"); + const double tF = timeit({fpre}) + timeit({fpost}); + std::printf("fused-stride pre + post %.3f ms (separate %.3f)\n", tF, tpre + tpost); + } + const double tout = timeit({gemm_d(ygh, Wh[4], Y[4], T, N, ZD, 64, 64)}); + double dqall = 0; + for (int i = 0; i < 5; ++i) dqall += timeit({dq_d(i)}); + std::printf("== layer in engine order (GPU ms): dq %.3f + input GEMMs %.3f + pre/scan/post %.3f + out GEMM %.3f = %.3f (sum of parts)\n", + dqall, sep, tpre + tscan + tpost, tout, dqall + sep + tpre + tscan + tpost + tout); + return 0; +} From 3484572236b0c73ecae5bf2dda7cae8559ec0d37 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 30 Oct 2026 01:50:15 +0100 Subject: [PATCH 5/5] Metal: tensor-op chunk-state probe, layer bench with before/after, A/B driver --- metal/kernels/gdn_tprobe.metal | 75 +++++++++++++++++++++++++++++++++ metal/tests/gdn_layer_bench.cpp | 12 +++++- metal/tests/gdn_tprobe.cpp | 36 ++++++++++++++++ 3 files changed, 122 insertions(+), 1 deletion(-) create mode 100644 metal/kernels/gdn_tprobe.metal create mode 100644 metal/tests/gdn_tprobe.cpp diff --git a/metal/kernels/gdn_tprobe.metal b/metal/kernels/gdn_tprobe.metal new file mode 100644 index 00000000..841609c4 --- /dev/null +++ b/metal/kernels/gdn_tprobe.metal @@ -0,0 +1,75 @@ +// metal/kernels/gdn_tprobe.metal - go / no-go probe for a tensor-op (MPP matmul2d) chunk-state kernel: the five products of one GDN +// chunk step (W S, Q S, M delta, K^T delta' accumulated into S) on fp16 operands, S kept in fp32 threadgroup memory, 64 chunk steps +// a threadgroup, grid h_v * 4 (the shape of gdn_cstate2). No numerics: timing only. +#include +using namespace metal; +using namespace mpp::tensor_ops; + +constant int PROBE [[function_constant(0)]]; +constant int probe = is_function_constant_defined(PROBE) ? PROBE : 0; // 1 = skip the products (SIMT parts only) + +kernel void gdn_tprobe(device float* out [[buffer(0)]], device half* Wh [[buffer(1)]], device half* Qh [[buffer(2)]], + device half* Kh [[buffer(3)]], device half* Mh [[buffer(4)]], constant int& NC [[buffer(5)]], + uint3 tg [[threadgroup_position_in_grid]], ushort tid [[thread_index_in_threadgroup]]) { + threadgroup half Sh[128 * 32]; + threadgroup half Dh[32 * 32]; + threadgroup float X[32 * 32], Y[32 * 32], Z[32 * 32]; + tensor, tensor_inline> tSh(Sh, dextents(32, 128)); + tensor, tensor_inline> tDh(Dh, dextents(32, 32)); + tensor, tensor_inline> tX(X, dextents(32, 32)); + tensor, tensor_inline> tY(Y, dextents(32, 32)); + tensor, tensor_inline> tZ(Z, dextents(32, 32)); + constexpr auto d_ws = matmul2d_descriptor(32, 32, 128, false, false, false); // [32 x 128] . [128 x 32] + constexpr auto d_md = matmul2d_descriptor(32, 32, 32, false, false, false); // [32 x 32] . [32 x 32] + constexpr auto d_up = matmul2d_descriptor(128, 32, 32, true, false, false, matmul2d_descriptor::mode::multiply_accumulate); // K^T delta' + matmul2d> op_ws; + matmul2d> op_md; + matmul2d> op_up; + const ulong hb = ulong(tg.x) / 4; + using KT = tensor, tensor_inline>; + using DT = tensor, tensor_inline>; + auto cS = op_up.get_destination_cooperative_tensor(); +#pragma clang loop unroll(full) + for (uint16_t i = 0; i < cS.get_capacity(); ++i) + if (cS.is_valid_element(i)) cS[i] = 0.001f * float(i & 15); + for (int c = 0; c < NC; ++c) { + const ulong cb = (hb * NC + c); +#pragma clang loop unroll(full) + for (uint16_t i = 0; i < cS.get_capacity(); ++i) + if (cS.is_valid_element(i)) { + auto ids = cS.get_multidimensional_index(i); + Sh[ids[1] * 32 + ids[0]] = half(cS[i]); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (probe != 1) { + tensor, tensor_inline> tW(Wh + cb * 32 * 128, dextents(128, 32)); + tensor, tensor_inline> tQ(Qh + cb * 32 * 128, dextents(128, 32)); + op_ws.run(tW, tSh, tX); + op_ws.run(tQ, tSh, tY); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (int i = tid; i < 32 * 32; i += 128) Dh[i] = half(0.01f * X[i]); + threadgroup_barrier(mem_flags::mem_threadgroup); + if (probe != 1) { + tensor, tensor_inline> tM(Mh + cb * 32 * 32, dextents(32, 32)); + op_md.run(tM, tDh, tZ); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + for (int i = tid; i < 32 * 32; i += 128) Dh[i] = half(Z[i] + 0.01f * Y[i]); +#pragma clang loop unroll(full) + for (uint16_t i = 0; i < cS.get_capacity(); ++i) + if (cS.is_valid_element(i)) cS[i] *= 0.99f; + threadgroup_barrier(mem_flags::mem_threadgroup); + if (probe != 1) { + tensor, tensor_inline> tK(Kh + cb * 32 * 128, dextents(128, 32)); + op_up.run(tK, tDh, cS); + } + threadgroup_barrier(mem_flags::mem_threadgroup); + } +#pragma clang loop unroll(full) + for (uint16_t i = 0; i < cS.get_capacity(); ++i) + if (cS.is_valid_element(i)) { + auto ids = cS.get_multidimensional_index(i); + out[ulong(tg.x) * 4096 + ids[1] * 32 + ids[0]] = cS[i]; + } +} diff --git a/metal/tests/gdn_layer_bench.cpp b/metal/tests/gdn_layer_bench.cpp index f9455f8c..c8893236 100644 --- a/metal/tests/gdn_layer_bench.cpp +++ b/metal/tests/gdn_layer_bench.cpp @@ -146,6 +146,7 @@ int main(int argc, char** argv) { dpost.grid[0] = HV; dpost.grid[1] = T; dpost.tg[0] = 128; const double tpre = timeit({dpre}), tscan = timeit({dscan}), tpost = timeit({dpost}); std::printf("== gdn_pre %.3f, scan %.3f, gdn_post %.3f ms (stage %.3f)\n", tpre, tscan, tpost, tpre + tscan + tpost); + double tF = 0; { // the fused-stride kernels (function constant 7) against the separate ones: bit for bit for (int t = 0; t < T; ++t) { std::memcpy(YF.as() + (size_t)t * NF, qkv.as() + (size_t)t * CH, 4 * CH); @@ -172,7 +173,7 @@ int main(int argc, char** argv) { std::memcmp(qn.ptr, rqn.data(), rqn.size()) == 0 ? "equal" : "DIFFER", std::memcmp(vc.ptr, rvc.data(), rvc.size()) == 0 ? "equal" : "DIFFER", std::memcmp(gb.ptr, rgb.data(), rgb.size()) == 0 ? "equal" : "DIFFER", std::memcmp(h1.ptr, rh.data(), rh.size()) == 0 ? "equal" : "DIFFER", std::memcmp(yh.ptr, ryh.data(), ryh.size()) == 0 ? "equal" : "DIFFER"); - const double tF = timeit({fpre}) + timeit({fpost}); + tF = timeit({fpre}) + timeit({fpost}); std::printf("fused-stride pre + post %.3f ms (separate %.3f)\n", tF, tpre + tpost); } const double tout = timeit({gemm_d(ygh, Wh[4], Y[4], T, N, ZD, 64, 64)}); @@ -180,5 +181,14 @@ int main(int argc, char** argv) { for (int i = 0; i < 5; ++i) dqall += timeit({dq_d(i)}); std::printf("== layer in engine order (GPU ms): dq %.3f + input GEMMs %.3f + pre/scan/post %.3f + out GEMM %.3f = %.3f (sum of parts)\n", dqall, sep, tpre + tscan + tpost, tout, dqall + sep + tpre + tscan + tpost + tout); + { // the layer as the engine now runs it on the M5 family: fused input GEMM, fused-stride pre/post, tiled out GEMM + double tout_best = 1e9; + for (auto [tm, tn] : std::vector>{{64, 64}, {128, 64}, {64, 128}}) + tout_best = std::min(tout_best, timeit({gemm_d(ygh, Wh[4], Y[4], T, N, ZD, tm, tn)})); + const double base_l = dqall + sep + tpre + tscan + tpost + tout; + const double new_l = dqall + best_f + tF + tscan + tout_best; + std::printf("== layer: before %.3f ms, after (fused input GEMM %.3f, fused-stride pre+post %.3f, scan %.3f, out GEMM %.3f) %.3f ms = x%.3f\n", + base_l, best_f, tF, tscan, tout_best, new_l, base_l / new_l); + } return 0; } diff --git a/metal/tests/gdn_tprobe.cpp b/metal/tests/gdn_tprobe.cpp new file mode 100644 index 00000000..80622554 --- /dev/null +++ b/metal/tests/gdn_tprobe.cpp @@ -0,0 +1,36 @@ +// metal/tests/gdn_tprobe.cpp - times kernels/gdn_tprobe.metal: the five MPP matmul2d products of a GDN chunk step, NC chunk steps a +// threadgroup, 192 threadgroups (h_v * 4). Compare with gdn_scanr_4's stage (chunks of 32 -> T = 32 * NC). +// gdn_tprobe [NC] +#include "mtl_rt.h" +#include "ref_quant.h" + +#include +#include +#include +#include + +int main(int argc, char** argv) { + const int NC = argc > 1 ? std::atoi(argv[1]) : 64; + mtl::Context cx; + const int lib = cx.compile({"gdn_tprobe.metal"}, "#define NO_GGML_COMMON 1\n"); + std::printf("device %s, NC %d (T %d)\n", cx.device_name().c_str(), NC, NC * 32); + const size_t NB = (size_t)48 * NC; + mtl::Buffer out = cx.alloc(4 * 192 * 4096), W = cx.alloc(2 * NB * 32 * 128), Q = cx.alloc(2 * NB * 32 * 128), + K = cx.alloc(2 * NB * 32 * 128), M = cx.alloc(2 * NB * 32 * 32); + ref::Rng r(3); + for (auto* b : {&W, &Q, &K}) for (size_t i = 0; i < NB * 32 * 128; ++i) b->as()[i] = ref::f32_to_f16(r.sym() * 0.1f); + for (size_t i = 0; i < NB * 32 * 32; ++i) M.as()[i] = ref::f32_to_f16(r.sym() * 0.1f); + for (int pr : {0, 1}) { + mtl::Pipeline p = cx.pipeline(lib, "gdn_tprobe", pr ? mtl::Constants().i(0, pr) : mtl::Constants()); + mtl::Dispatch d; d.p = &p; + d.args = {mtl::Arg::B(out), mtl::Arg::B(W), mtl::Arg::B(Q), mtl::Arg::B(K), mtl::Arg::B(M), mtl::Arg::V(NC)}; + d.grid[0] = 192; d.tg[0] = 128; + cx.warm({d}, 0.3); + std::vector t; + for (int i = 0; i < 7; ++i) t.push_back(cx.run({d}) * 1e3); + std::sort(t.begin(), t.end()); + std::printf("probe %d (%s): %.3f ms for %d chunk steps x 192 threadgroups (max threads %d, tg mem %d)\n", pr, + pr ? "SIMT parts only" : "with the five products", t[3], NC, p.max_threads, p.static_tg_mem); + } + return 0; +}