From aba4365c0c8597b5349f213e35fd9e68ba849be0 Mon Sep 17 00:00:00 2001 From: Kevin Gilbertson <880013+gilby@users.noreply.github.com> Date: Fri, 20 Nov 2026 21:32:18 +0100 Subject: [PATCH 1/4] glm metal: fuse 8-bit/64 shared expert with 4-bit/64 routed MoE Extend the fused Metal MoE gather/down kernels (moe_gateup_0_sh8, moe_down_0_sh8, _one, and _pick) via uint4 8-bit/64 shared-expert loads so mixed 4/64 routed + 8/64 shared layers stay on the single fused path instead of falling back to unfused wide launches. Includes M1/M2 512-thread reservation, contract gates/controls/records, and bit-exact parity unit test. Refs #3152 --- zig/src/core/contract/glm_sh8_records.zig | 16 + zig/src/core/contract/registry_joins.zig | 1 + zig/src/families/glm/glm.zig | 1 + zig/src/families/glm/kernels.zig | 79 +++- zig/src/families/glm/moe.zig | 24 +- zig/src/families/glm/sh8_moe_test.zig | 180 +++++++++ zig/tests/contract/metal_glm_sh8.zig | 423 ++++++++++++++++++++++ zig/tests/contract/metal_limits.zig | 10 + zig/tests/contract/metal_main.zig | 2 + 9 files changed, 728 insertions(+), 8 deletions(-) create mode 100644 zig/src/core/contract/glm_sh8_records.zig create mode 100644 zig/src/families/glm/sh8_moe_test.zig create mode 100644 zig/tests/contract/metal_glm_sh8.zig diff --git a/zig/src/core/contract/glm_sh8_records.zig b/zig/src/core/contract/glm_sh8_records.zig new file mode 100644 index 00000000000..b5afee98100 --- /dev/null +++ b/zig/src/core/contract/glm_sh8_records.zig @@ -0,0 +1,16 @@ +//! GLM-5.3-Flash mixed 4/64 routed + 8/64 shared fused MoE launches on Metal. +const std = @import("std"); +const M = @import("limits.zig").MetalLaunch; + +pub const records = [_]M{ + .{ .name = "glm sh8 two glm_moe_gateup_0_sh8_one", .threads = 128, .tg_memory = 0, .reserved = 512, .m1 = 512, .m2 = 512 }, + .{ .name = "glm sh8 two glm_moe_down_0_sh8_one", .threads = 32, .tg_memory = 0, .m1 = 896, .m2 = 896 }, + .{ .name = "glm sh8 four glm_moe_gateup_0_sh8", .threads = 512, .tg_memory = 0, .reserved = 512, .m1 = 512, .m2 = 512 }, + .{ .name = "glm sh8 four glm_moe_down_0_sh8", .threads = 512, .tg_memory = 0, .m1 = 832, .m2 = 832 }, + .{ .name = "glm sh8 pick glm_moe_gateup_0_sh8_pick", .threads = 32, .tg_memory = 0, .reserved = 512, .m1 = 512, .m2 = 512 }, + .{ .name = "glm sh8 pick glm_moe_down_0_sh8_pick", .threads = 32, .tg_memory = 0, .m1 = 896, .m2 = 896 }, +}; + +test "the GLM sh8 MoE launches fit every Apple family" { + try std.testing.expectEqual(@as(usize, 0), try @import("registry.zig").checkMetal(std.testing.allocator, &records, true)); +} diff --git a/zig/src/core/contract/registry_joins.zig b/zig/src/core/contract/registry_joins.zig index e92bbfe6697..c13cc55c5d2 100644 --- a/zig/src/core/contract/registry_joins.zig +++ b/zig/src/core/contract/registry_joins.zig @@ -95,6 +95,7 @@ pub const all_metal = @import("penalties_records.zig").records ++ @import("glm_launch_records.zig").records ++ @import("glm_tap_records.zig").records ++ @import("glm_dflash_records.zig").records ++ + @import("glm_sh8_records.zig").records ++ @import("row_wide_records.zig").records ++ @import("weight_only_records.zig").metal ++ @import("grouped_records.zig").metal ++ diff --git a/zig/src/families/glm/glm.zig b/zig/src/families/glm/glm.zig index 736eb6fc14d..8874eeab478 100644 --- a/zig/src/families/glm/glm.zig +++ b/zig/src/families/glm/glm.zig @@ -60,6 +60,7 @@ test { _ = @import("../../core/copy_index.zig"); _ = @import("attn_check.zig"); _ = @import("eh_check.zig"); + _ = @import("sh8_moe_test.zig"); _ = @import("launch_check.zig"); _ = @import("load_plan.zig"); _ = @import("page_cache.zig"); diff --git a/zig/src/families/glm/kernels.zig b/zig/src/families/glm/kernels.zig index b4e2c6fca5a..29c3726127b 100644 --- a/zig/src/families/glm/kernels.zig +++ b/zig/src/families/glm/kernels.zig @@ -61,6 +61,12 @@ pub const Kernels = struct { moe_down_0_one: mtl.Pipeline, moe_gateup_pick: mtl.Pipeline, // one row: each routed group replays the route select's picks, no select launch moe_down_pick: mtl.Pipeline, // and the down projections of the picks in pick order + moe_gateup_0_sh8: mtl.Pipeline, // 4/64 routed experts fused with an 8/64 shared expert + moe_down_0_sh8: mtl.Pipeline, + moe_gateup_0_sh8_one: mtl.Pipeline, + moe_down_0_sh8_one: mtl.Pipeline, + moe_gateup_sh8_pick: mtl.Pipeline, + moe_down_sh8_pick: mtl.Pipeline, combine_0: mtl.Pipeline, // their combine: the shared expert's row read from the last slot moe_gateup_2: mtl.Pipeline, moe_down_2: mtl.Pipeline, @@ -257,17 +263,17 @@ pub fn instance(comptime key: []const u8, comptime params: []const u8, comptime /// Generated kernel `key`'s source. pub fn generatedSource(comptime key: []const u8) []const u8 { - return kernelOf(key).source; + return comptime kernelOf(key).source; } /// Generated kernel `key`'s first function. pub fn generatedFunction(comptime key: []const u8) [:0]const u8 { - return kernelOf(key).functions[0]; + return comptime kernelOf(key).functions[0]; } fn kernelOf(comptime key: []const u8) sources.glm.Kernel { @setEvalBranchQuota(20000); - for (sources.glm.all) |k| if (comptime std.mem.eql(u8, k.key, key)) return k; + for (sources.glm.all) |k| if (std.mem.eql(u8, k.key, key)) return k; @compileError("no generated GLM kernel " ++ key); } @@ -299,6 +305,47 @@ fn pickSources(gpa: std.mem.Allocator, route_core: []const u8, gu: []const u8, d return .{ gate_up, try edit(gpa, down, member, by_pick) }; } +/// Rewrite a fused 4/64 MoE source so its shared expert reads packed 8/64 weights with `uint4` loads. +pub fn sh8Source(gpa: std.mem.Allocator, base: []const u8, is_gateup: bool, params_from: []const u8, params_to: []const u8, name: []const u8) ![]u8 { + const q8_from = + \\template <> inline float qdotv<8, 16>(const device uint8_t* w, const thread float* xt, float scale, float bias, + \\ float sum) { + \\ float accum = 0.0f; + \\ for (int i = 0; i < 16; i++) accum += xt[i] * w[i]; + \\ return scale * accum + sum * bias; + \\} + ; + const q8_to = + \\template <> inline float qdotv<8, 16>(const device uint8_t* w, const thread float* xt, float scale, float bias, + \\ float sum) { + \\ const uint4 raw = *(const device uint4*)w; + \\ float accum = 0.0f; + \\ for (int i = 0; i < 4; i++) { + \\ const uchar4 q = as_type(raw[i]); + \\ accum += (xt[4 * i] * float(q.x) + xt[4 * i + 1] * float(q.y) + + \\ xt[4 * i + 2] * float(q.z) + xt[4 * i + 3] * float(q.w)); + \\ } + \\ return scale * accum + sum * bias; + \\} + ; + const s1 = try edit(gpa, base, q8_from, q8_to); + defer gpa.free(s1); + const cond_to = if (is_gateup) "if (SB != 4 && (PART == 1 || int(threadgroup_position_in_grid.z) == int(X_shape[0]) * TOPK)) {" else "if (SB != 4 && (PART == 1 || int(threadgroup_position_in_grid.z) == int(ACT_shape[0]) * TOPK)) {"; + const s2 = try edit(gpa, s1, "if (PART == 1 && SB != 4) {", cond_to); + defer gpa.free(s2); + const io_from = if (is_gateup) "ACT[size_t(r) * N + row0 + j] = sl * up;" else "Y[size_t(r) * N + row0 + j] = bfloat(v);"; + const io_to = if (is_gateup) "ACT[(PART == 0 ? size_t(r) * (TOPK + 1) + TOPK : size_t(r)) * N + row0 + j] = sl * up;" else "Y[(PART == 0 ? size_t(r) * (TOPK + 1) + TOPK : size_t(r)) * N + row0 + j] = bfloat(v);"; + const s3 = try edit(gpa, s2, io_from, io_to); + defer gpa.free(s3); + const s4 = if (is_gateup) try edit(gpa, s3, "[[kernel]] void custom_kernel_tf_glm5_fused_moe_gateup", "[[max_total_threads_per_threadgroup(512)]] [[kernel]] void custom_kernel_tf_glm5_fused_moe_gateup") else try edit(gpa, s3, "const device bfloat* x = ACT + size_t(r) * K + lane * SV;", "const device bfloat* x = ACT + (PART == 0 ? size_t(r) * (TOPK + 1) + TOPK : size_t(r)) * K + lane * SV;"); + defer gpa.free(s4); + if (std.mem.count(u8, s4, params_from) != 2) return error.KernelCompile; + const s5 = try std.mem.replaceOwned(u8, gpa, s4, params_from, params_to); + defer gpa.free(s5); + const old_n = if (is_gateup) "glm_moe_gateup_0" else "glm_moe_down_0"; + return edit(gpa, s5, old_n, name); +} + const m16_names = affine_mm.names ++ mm_groups.names; /// Compile every library on worker threads. @@ -319,7 +366,7 @@ fn assemble(gpa: std.mem.Allocator, device: mtl.Device, k: *Kernels, visitor: an k.wide = null; const m3_fast = !device.tensorUnits(); k.m3_fast = m3_fast; - var jobs: [generated.len + 28]Job = undefined; + var jobs: [generated.len + 34]Job = undefined; inline for (generated, 0..) |g, i| { const src = comptime kernelOf(g.key); const FT = @FieldType(Kernels, g.field); @@ -430,11 +477,33 @@ fn assemble(gpa: std.mem.Allocator, device: mtl.Device, k: *Kernels, visitor: an jobs[generated.len + 23] = .{ .device = device, .source = sources.glm_select, .names = &.{ "glm_select_mark", "glm_select_merge" }, .out = &select_out }; const softmax_rows_src = comptime sources.ops_softmax ++ sources.glm_softmax_rows; jobs[generated.len + 24] = .{ .device = device, .source = softmax_rows_src, .names = &.{"glm_softmax_rows"}, .out = @as(*[1]mtl.Pipeline, &k.softmax_rows) }; + const gu_from = "4096, 2048, 4, 8, 16, 128, 0, 4, 16, 8"; + const dn_from = "2048, 4096, 4, 8, 16, 128, 0, 4, 16, 8"; + const gu_one_from = "4096, 2048, 2, 8, 16, 128, 0, 4, 16, 8"; + const dn_one_from = "2048, 4096, 2, 8, 16, 128, 0, 4, 16, 8"; + const gu_sh8 = try sh8Source(gpa, gu0_src, true, gu_from, "4096, 2048, 4, 8, 16, 128, 0, 8, 16, 16", "glm_moe_gateup_0_sh8"); + defer gpa.free(gu_sh8); + const dn_sh8 = try sh8Source(gpa, down0_src, false, dn_from, "2048, 4096, 4, 8, 16, 128, 0, 8, 16, 16", "glm_moe_down_0_sh8"); + defer gpa.free(dn_sh8); + const gu_sh8_one = try sh8Source(gpa, gu0_src, true, gu_from, "4096, 2048, 2, 8, 16, 128, 0, 8, 16, 16", "glm_moe_gateup_0_sh8_one"); + defer gpa.free(gu_sh8_one); + const dn_sh8_one = try sh8Source(gpa, down0_src, false, dn_from, "2048, 4096, 2, 8, 16, 128, 0, 8, 16, 16", "glm_moe_down_0_sh8_one"); + defer gpa.free(dn_sh8_one); + const gu_sh8_pick = try sh8Source(gpa, picks[0], true, gu_one_from, "4096, 2048, 2, 8, 16, 128, 0, 8, 16, 16", "glm_moe_gateup_0_sh8_pick"); + defer gpa.free(gu_sh8_pick); + const dn_sh8_pick = try sh8Source(gpa, picks[1], false, dn_one_from, "2048, 4096, 2, 8, 16, 128, 0, 8, 16, 16", "glm_moe_down_0_sh8_pick"); + defer gpa.free(dn_sh8_pick); + jobs[generated.len + 27] = .{ .device = device, .source = gu_sh8, .names = &.{"glm_moe_gateup_0_sh8"}, .out = @as(*[1]mtl.Pipeline, &k.moe_gateup_0_sh8) }; + jobs[generated.len + 28] = .{ .device = device, .source = dn_sh8, .names = &.{"glm_moe_down_0_sh8"}, .out = @as(*[1]mtl.Pipeline, &k.moe_down_0_sh8) }; + jobs[generated.len + 29] = .{ .device = device, .source = gu_sh8_one, .names = &.{"glm_moe_gateup_0_sh8_one"}, .out = @as(*[1]mtl.Pipeline, &k.moe_gateup_0_sh8_one) }; + jobs[generated.len + 30] = .{ .device = device, .source = dn_sh8_one, .names = &.{"glm_moe_down_0_sh8_one"}, .out = @as(*[1]mtl.Pipeline, &k.moe_down_0_sh8_one) }; + jobs[generated.len + 31] = .{ .device = device, .source = gu_sh8_pick, .names = &.{"glm_moe_gateup_0_sh8_pick"}, .out = @as(*[1]mtl.Pipeline, &k.moe_gateup_sh8_pick) }; + jobs[generated.len + 32] = .{ .device = device, .source = dn_sh8_pick, .names = &.{"glm_moe_down_0_sh8_pick"}, .out = @as(*[1]mtl.Pipeline, &k.moe_down_sh8_pick) }; const m3_src = if (m3_fast) try affine_mm.source(device, gpa, .{ .glm_m3_fast = true, .exact_nonfinite = true }) else try gpa.dupe(u8, ""); defer gpa.free(m3_src); var m3_out: affine_mm.Pipes = undefined; - if (m3_fast) jobs[generated.len + 27] = .{ .device = device, .source = m3_src, .names = &affine_mm.names, .out = &m3_out }; + if (m3_fast) jobs[generated.len + 33] = .{ .device = device, .source = m3_src, .names = &affine_mm.names, .out = &m3_out }; const active_jobs = jobs[0 .. jobs.len - @intFromBool(!m3_fast)]; if (comptime @TypeOf(visitor) != void) { for (active_jobs) |j| try visitor.raw("glm", j.names[0], j.source); diff --git a/zig/src/families/glm/moe.zig b/zig/src/families/glm/moe.zig index 205ad2f756c..b308b21f811 100644 --- a/zig/src/families/glm/moe.zig +++ b/zig/src/families/glm/moe.zig @@ -85,7 +85,7 @@ pub fn block(x: *const Ctx, e: mtl.ComputeEncoder, w: *const wts.Moe, x_in: Ref, }, rows, c.topk, c.experts, c.swiglu_limit); if (full) return false; } - } else if (native(w, .both) and s & (Class.shared | Class.routed) == 0) { + } else if (canBoth(w) and s & (Class.shared | Class.routed) == 0) { const one = rows == 1 and x.fused_route; // the gate/up groups replay the select: the logits alone if (s & Class.route == 0 and one and on(x, "r_router")) logits(x, e, w, x_in, rows); if (s & Class.route == 0 and !one) route(x, e, w, x_in, rows); @@ -181,6 +181,17 @@ pub fn native(w: *const wts.Moe, which: enum { shared, routed, both }) bool { }; } +/// Whether the shared expert uses 8/64 single-matrix weights (compatible with fused moe_gateup_0_sh8). +pub fn shared8(w: *const wts.Moe) bool { + return w.sh_gate_up.more == 0 and w.sh_gate_up.bits == 8 and w.sh_gate_up.group == 64 and + w.sh_down.more == 0 and w.sh_down.bits == 8 and w.sh_down.group == 64; +} + +/// Whether both routed and shared experts run in the single fused gather launch (`both`). +pub fn canBoth(w: *const wts.Moe) bool { + return native(w, .routed) and (native(w, .shared) or shared8(w)); +} + /// Part 1: the shared expert into `ys`; part 2: the routed experts of `group` (unique ids, members, count) into `ye`. fn experts(x: *const Ctx, e: mtl.ComputeEncoder, w: *const wts.Moe, x_in: Ref, rows: u32, part: u32, group: [3]Ref) void { const c = x.c; @@ -213,8 +224,12 @@ fn both(x: *const Ctx, e: mtl.ComputeEncoder, w: *const wts.Moe, x_in: Ref, rows // Two outputs a simdgroup (more reads in flight, the same sums): gate/up to 4 rows, down at one (M5 Ultra). const gu_two = rows <= 4; const rps: u32 = if (gu_two) 2 else 4; + const sh8 = shared8(w); if (on(x, "e_gateup")) { // a profile's knock-outs leave out one launch of this path, never the path - e.setPipeline(if (one) k.moe_gateup_pick else if (gu_two) k.moe_gateup_0_one else k.moe_gateup_0); + const pick_p = if (sh8) k.moe_gateup_sh8_pick else k.moe_gateup_pick; + const one_p = if (sh8) k.moe_gateup_0_sh8_one else k.moe_gateup_0_one; + const four_p = if (sh8) k.moe_gateup_0_sh8 else k.moe_gateup_0; + e.setPipeline(if (one) pick_p else if (gu_two) one_p else four_p); bind(e, 0, .{x_in}); shape(e, 1, .{ rows, D }); bind(e, 2, .{ w.gate.w, w.gate.s, w.gate.b, w.up.w, w.up.s, w.up.b, w.sh_gate_up.w, w.sh_gate_up.s, w.sh_gate_up.b }); @@ -227,7 +242,10 @@ fn both(x: *const Ctx, e: mtl.ComputeEncoder, w: *const wts.Moe, x_in: Ref, rows } if (!on(x, "e_down")) return; const down_rps: u32 = if (rows == 1) 2 else 4; - e.setPipeline(if (one) k.moe_down_pick else if (rows == 1) k.moe_down_0_one else k.moe_down_0); + const pick_d = if (sh8) k.moe_down_sh8_pick else k.moe_down_pick; + const one_d = if (sh8) k.moe_down_0_sh8_one else k.moe_down_0_one; + const four_d = if (sh8) k.moe_down_0_sh8 else k.moe_down_0; + e.setPipeline(if (one) pick_d else if (rows == 1) one_d else four_d); bind(e, 0, .{sc.act}); shape(e, 1, .{ rows, c.topk + 1, N }); bind(e, 2, .{ w.down.w, w.down.s, w.down.b, w.sh_down.w, w.sh_down.s, w.sh_down.b }); diff --git a/zig/src/families/glm/sh8_moe_test.zig b/zig/src/families/glm/sh8_moe_test.zig new file mode 100644 index 00000000000..42e3e213b10 --- /dev/null +++ b/zig/src/families/glm/sh8_moe_test.zig @@ -0,0 +1,180 @@ +//! Synthetic GPU parity tests for mixed 4/64 routed + 8/64 shared fused MoE (batch and pick paths). +const std = @import("std"); +const mtl = @import("metal"); +const cfg = @import("config.zig"); +const wts = @import("weights.zig"); +const st = @import("state.zig"); +const fwd = @import("forward.zig"); +const kernels = @import("kernels.zig"); +const moe = @import("moe.zig"); +const wide = @import("wide.zig"); +const moe_route = @import("../../core/moe_route.zig"); + +const bf16_round = @import("bf16_round"); +const bf16 = bf16_round.bits; +fn ref(b: mtl.Buffer) wts.Ref { + return .{ .buf = b }; +} + +fn fillAffine(rnd: std.Random, w_buf: mtl.Buffer, s_buf: mtl.Buffer, b_buf: mtl.Buffer, n: usize, k: usize, bits: usize) void { + rnd.bytes(w_buf.slice(u8, n * k * bits / 8)); + const div: f32 = if (bits == 8) 512.0 else 32.0; + for (s_buf.slice(u16, n * (k / 64)), b_buf.slice(u16, n * (k / 64))) |*s, *b| { + s.* = bf16((rnd.float(f32) + 0.5) / div); + b.* = bf16(-(rnd.float(f32) + 0.5) * 0.15); + } +} + +test "mixed 4/64 routed + 8/64 shared moe_0_sh8 (and pick at row 1) matches wide + moe_2 bit-for-bit" { + const device = mtl.Device.init() catch return error.SkipZigTest; + defer device.deinit(); + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const queue = try device.queue(); + defer queue.deinit(); + const a = std.testing.allocator; + const k = try kernels.load(a, device); + defer { + k.deinit(); + a.destroy(k); + } + try k.widen(a, device); + const D: usize = 4096; + const N: usize = 2048; + const E: usize = 8; + const MAXE: usize = kernels.route_shape.experts; + const TOPK: usize = 8; + const MAXR: usize = 16; + const opts = mtl.ResourceOptions.shared; + const g_w = try device.buffer(E * N * D / 2, opts); + const g_s = try device.buffer(E * N * (D / 64) * 2, opts); + const g_b = try device.buffer(E * N * (D / 64) * 2, opts); + const u_w = try device.buffer(E * N * D / 2, opts); + const u_s = try device.buffer(E * N * (D / 64) * 2, opts); + const u_b = try device.buffer(E * N * (D / 64) * 2, opts); + const d_w = try device.buffer(E * D * N / 2, opts); + const d_s = try device.buffer(E * D * (N / 64) * 2, opts); + const d_b = try device.buffer(E * D * (N / 64) * 2, opts); + const sg_w = try device.buffer(2 * N * D, opts); + const sg_s = try device.buffer(2 * N * (D / 64) * 2, opts); + const sg_b = try device.buffer(2 * N * (D / 64) * 2, opts); + const sd_w = try device.buffer(D * N, opts); + const sd_s = try device.buffer(D * (N / 64) * 2, opts); + const sd_b = try device.buffer(D * (N / 64) * 2, opts); + const bufs = [_]mtl.Buffer{ g_w, g_s, g_b, u_w, u_s, u_b, d_w, d_s, d_b, sg_w, sg_s, sg_b, sd_w, sd_s, sd_b }; + defer for (bufs) |b| b.deinit(); + var prng = std.Random.DefaultPrng.init(0x5802); + const rnd = prng.random(); + fillAffine(rnd, g_w, g_s, g_b, E * N, D, 4); + fillAffine(rnd, u_w, u_s, u_b, E * N, D, 4); + fillAffine(rnd, d_w, d_s, d_b, E * D, N, 4); + fillAffine(rnd, sg_w, sg_s, sg_b, 2 * N, D, 8); + fillAffine(rnd, sd_w, sd_s, sd_b, D, N, 8); + const x_in = try device.buffer(MAXR * D * 2, opts); + const logits_r = try device.buffer(MAXR * MAXE * 4, opts); + const bias = try device.buffer(MAXE * 4, opts); + const rl = try device.buffer(TOPK * MAXR * 4 * 2 + 128, opts); + const uids = try device.buffer(MAXE * 4, opts); + const umem = try device.buffer(MAXE * MAXR * 4, opts); + const ucount = try device.buffer(64, opts); + const pick = try device.buffer(MAXR * TOPK * 4, opts); + const wts_b = try device.buffer(MAXR * TOPK * 4, opts); + const act = try device.buffer(MAXR * (TOPK + 1) * N * 2, opts); + const acts = try device.buffer(MAXR * N * 2, opts); + const ye = try device.buffer(MAXR * (TOPK + 1) * D * 2, opts); + const ys = try device.buffer(MAXR * D * 2, opts); + const out_fused = try device.buffer(MAXR * D * 2, opts); + const out_ref = try device.buffer(MAXR * D * 2, opts); + const gu = try device.buffer(MAXR * 2 * N * 2, opts); + const sc_bufs = [_]mtl.Buffer{ x_in, logits_r, bias, rl, uids, umem, ucount, pick, wts_b, act, acts, ye, ys, out_fused, out_ref, gu }; + defer for (sc_bufs) |b| b.deinit(); + for (x_in.slice(u16, MAXR * D)) |*v| v.* = bf16(rnd.float(f32) * 2 - 1); + for (wts_b.slice(f32, MAXR * TOPK)) |*v| v.* = rnd.float(f32) * 0.25 + 0.05; + for (logits_r.slice(f32, MAXE)) |*v| v.* = rnd.float(f32) * 2.0 - 1.0; + const bi = bias.slice(f32, MAXE); + @memset(bi, -std.math.inf(f32)); + for (bi[0..E]) |*v| v.* = rnd.float(f32) * 0.1; + const c_cfg = cfg.Config{ .layers = 45, .run = 45, .tp = 1, .experts = MAXE }; + const moe_w: wts.Moe = .{ + .router = ref(uids), + .bias = ref(bias), + .gate = .{ .w = ref(g_w), .s = ref(g_s), .b = ref(g_b), .n = N, .k = D, .bits = 4, .group = 64 }, + .up = .{ .w = ref(u_w), .s = ref(u_s), .b = ref(u_b), .n = N, .k = D, .bits = 4, .group = 64 }, + .down = .{ .w = ref(d_w), .s = ref(d_s), .b = ref(d_b), .n = D, .k = N, .bits = 4, .group = 64 }, + .sh_gate_up = .{ .w = ref(sg_w), .s = ref(sg_s), .b = ref(sg_b), .n = 2 * N, .k = D, .bits = 8, .group = 64 }, + .sh_down = .{ .w = ref(sd_w), .s = ref(sd_s), .b = ref(sd_b), .n = D, .k = N, .bits = 8, .group = 64 }, + }; + try std.testing.expect(moe.canBoth(&moe_w)); + for ([_]bool{ false, true }) |fused_pick| { + const row_cases: []const u32 = if (fused_pick) &.{1} else &.{ 1, 2, 5, 8, 15 }; + for (row_cases) |rows| { + const ui = uids.slice(i32, E); + const um = umem.slice(i32, MAXE * MAXR); + @memset(um, -1); + for (0..E) |e| { + ui[e] = @intCast(e); + for (0..rows) |r| um[e * MAXR + r] = @intCast(r * TOPK + e); + } + ucount.slice(i32, 1)[0] = @intCast(E); + const pk = pick.slice(i32, rows * TOPK); + for (0..rows) |r| for (0..TOPK) |s| { + pk[r * TOPK + s] = @intCast(s); + }; + var sc: st.Scratch = undefined; + sc.logits_r = ref(logits_r); + sc.rl = ref(rl); + sc.uids = ref(uids); + sc.umem = ref(umem); + sc.ucount = ref(ucount); + sc.pick = ref(pick); + sc.wts = ref(wts_b); + sc.act = ref(act); + sc.acts = ref(acts); + sc.ye = ref(ye); + sc.ys = ref(ys); + sc.gu = ref(gu); + sc.branch = ref(out_fused); + sc.none = ref(ucount); + var state_stub: st.State = .{ .cap = 128 }; + var ctx = fwd.Ctx{ .k = k, .c = &c_cfg, .w = undefined, .s = &state_stub, .sc = &sc, .skip = fwd.Class.route, .fused_route = fused_pick }; + const cb = queue.commandBuffer(); + const enc = cb.compute(.serial); + moe.moe(&ctx, enc, &moe_w, ref(x_in), rows); + enc.end(); + cb.commit(); + cb.wait(); + try std.testing.expect(cb.failure() == null); + const wp = &k.wide.?; + const cb2 = queue.commandBuffer(); + const enc2 = cb2.compute(.serial); + if (fused_pick) { + const T: usize = TOPK * MAXR * 4; + moe_route.select(enc2, k.route_select, ref(logits_r), ref(bias), c_cfg.routed_scale, rows, .{ 0, MAXE }, .{ .pick = ref(pick), .wts = ref(wts_b), .ids = ref(uids), .members = ref(umem), .count = ref(ucount), .mine = ref(rl), .theirs = ref(rl).at(T), .counts = ref(rl).at(2 * T), .word = ref(rl).at(2 * T + 64) }); + } + wide.glu(wp, enc2, moe_w.sh_gate_up, N, ref(x_in), ref(acts), rows, c_cfg.swiglu_limit); + wide.dense(wp, enc2, moe_w.sh_down, .{ .in = ref(acts), .ldx = N, .out = ref(ys), .ldo = D, .rows = rows }); + enc2.setPipeline(k.moe_gateup_2); + fwd.bind(enc2, 0, .{ref(x_in)}); + fwd.shape(enc2, 1, .{ rows, D }); + fwd.bind(enc2, 2, .{ moe_w.gate.w, moe_w.gate.s, moe_w.gate.b, moe_w.up.w, moe_w.up.s, moe_w.up.b, moe_w.sh_gate_up.w, moe_w.sh_gate_up.s, moe_w.sh_gate_up.b, ref(uids), ref(umem), ref(ucount) }); + enc2.setValue(c_cfg.swiglu_limit, 14); + fwd.bind(enc2, 15, .{ref(act)}); + enc2.dispatchThreads(fwd.size(32 * rows, N / 4, rows * TOPK), fwd.size(32 * rows, 1, 1)); + enc2.setPipeline(k.moe_down_2); + fwd.bind(enc2, 0, .{ref(act)}); + fwd.shape(enc2, 1, .{ rows, TOPK, N }); + fwd.bind(enc2, 2, .{ moe_w.down.w, moe_w.down.s, moe_w.down.b, moe_w.sh_down.w, moe_w.sh_down.s, moe_w.sh_down.b, ref(uids), ref(umem), ref(ucount), ref(ye) }); + enc2.dispatchThreads(fwd.size(32 * rows, D / 4, rows * TOPK), fwd.size(32 * rows, 1, 1)); + enc2.setPipeline(k.moe_combine); + fwd.bind(enc2, 0, .{ ref(ys), ref(ye), ref(wts_b) }); + fwd.shape(enc2, 3, .{ rows, TOPK }); + fwd.bind(enc2, 4, .{ref(out_ref)}); + enc2.dispatchThreads(fwd.size(rows * D, 1, 1), fwd.size(256, 1, 1)); + enc2.end(); + cb2.commit(); + cb2.wait(); + try std.testing.expect(cb2.failure() == null); + try std.testing.expectEqualSlices(u16, out_ref.slice(u16, rows * D), out_fused.slice(u16, rows * D)); + } + } +} diff --git a/zig/tests/contract/metal_glm_sh8.zig b/zig/tests/contract/metal_glm_sh8.zig new file mode 100644 index 00000000000..2155e136123 --- /dev/null +++ b/zig/tests/contract/metal_glm_sh8.zig @@ -0,0 +1,423 @@ +//! GLM mixed 4/64 routed + 8/64 shared fused MoE kernels under gates 1-4, controls, and bit-exact predecessor check. +const std = @import("std"); +const mtl = @import("metal"); +const tf = @import("tensorfold"); +const contract = @import("contract"); +const rig_ = @import("rig.zig"); + +const c = contract.spec; +const g = contract.gates; +const kernels = tf.glm.kernels; +const moe_route = tf.moe_route; + +const E = 10; +const D = 4096; +const N = 2048; +const TOPK = 8; +const MAXR = 16; +const MAX_EXPERTS = kernels.route_shape.experts; +const swiglu_limit: f32 = 10.0; +const routed_scale: f32 = 2.5; +const pick_slot = "const int u = PART == 1 ? MAXU : int(threadgroup_position_in_grid.z);"; + +pub const Kind = enum { batch, pick }; +const Variant = struct { kind: Kind, control: bool = false }; + +const batch_served = [_]c.Shape{ .{ .rows = 4, .n = N, .k = D }, .{ .rows = 1, .n = N, .k = D }, .{ .rows = 2, .n = N, .k = D }, .{ .rows = 5, .n = N, .k = D }, .{ .rows = 8, .n = N, .k = D } }; +const pick_served = [_]c.Shape{.{ .rows = 1, .n = N, .k = D }}; + +pub fn entryName(v: Variant) []const u8 { + return switch (v.kind) { + .batch => if (v.control) "control: glm sh8 fused MoE takes shared slot one early" else "glm sh8 four/two glm_moe_gateup_0_sh8 and glm_moe_down_0_sh8", + .pick => if (v.control) "control: glm sh8 pick takes wrong routed expert" else "glm sh8 pick glm_moe_gateup_0_sh8_pick and glm_moe_down_0_sh8_pick", + }; +} + +pub fn buildSources(a: std.mem.Allocator) ![8][]u8 { + const gu = comptime kernels.generatedSource("moe_gateup_2") ++ kernels.instance("moe_gateup_2", "4096, 2048, 4, 8, 16, 128, 0, 4, 16, 8", "glm_moe_gateup_0"); + const dn = comptime kernels.generatedSource("moe_down_2") ++ kernels.instance("moe_down_2", "2048, 4096, 4, 8, 16, 128, 0, 4, 16, 8", "glm_moe_down_0"); + const gu0 = try std.mem.replaceOwned(u8, a, gu, pick_slot, "const int u = PART == 1 ? MAXU : (int(threadgroup_position_in_grid.z) == int(X_shape[0]) * TOPK ? MAXU : int(threadgroup_position_in_grid.z));"); + defer a.free(gu0); + const dn0 = try std.mem.replaceOwned(u8, a, dn, pick_slot, "const int u = PART == 1 ? MAXU : (int(threadgroup_position_in_grid.z) == int(ACT_shape[0]) * TOPK ? MAXU : int(threadgroup_position_in_grid.z));"); + defer a.free(dn0); + const gu0_one = try std.mem.replaceOwned(u8, a, gu0, "<4096, 2048, 4, 8, 16, 128, 0, 4, 16, 8>", "<4096, 2048, 2, 8, 16, 128, 0, 4, 16, 8>"); + defer a.free(gu0_one); + const dn0_one = try std.mem.replaceOwned(u8, a, dn0, "<2048, 4096, 4, 8, 16, 128, 0, 4, 16, 8>", "<2048, 4096, 2, 8, 16, 128, 0, 4, 16, 8>"); + defer a.free(dn0_one); + const member = " if (!shared && u >= UCOUNT[0]) return;\n const int pick = shared ? (m < R ? m * TOPK : -1) : UMEM[u * MAXR + m];"; + const by_pick = " const int pick = shared ? (m < R ? m * TOPK : -1) : u;"; + const rc = try moe_route.source(a, kernels.route_shape); + defer a.free(rc); + const g1 = try std.mem.replaceOwned(u8, a, gu0_one, member, by_pick); + defer a.free(g1); + const g2 = try std.mem.replaceOwned(u8, a, g1, " const size_t e = shared ? 0 : size_t(UIDS[u]);", " const size_t e = shared ? 0 : size_t(tf_route_pick_at(RLOGITS, RBIAS, u, lane, u == TOPK - 1 && threadgroup_position_in_grid.y == 0, RPICK, RWTS, RSCALE));"); + defer a.free(g2); + const g3 = try std.mem.replaceOwned(u8, a, g2, " const device int32_t* UIDS [[buffer(11)]],\n const device int32_t* UMEM [[buffer(12)]],\n const device int32_t* UCOUNT [[buffer(13)]],", " const device float* RLOGITS [[buffer(11)]],\n const device float* RBIAS [[buffer(12)]],\n device int32_t* RPICK [[buffer(13)]],"); + defer a.free(g3); + const g4 = try std.mem.replaceOwned(u8, a, g3, " device bfloat16_t* ACT [[buffer(15)]],", " device bfloat16_t* ACT [[buffer(15)]],\n device float* RWTS [[buffer(16)]],\n constant float& RSCALE [[buffer(17)]],"); + defer a.free(g4); + const p_gu = try std.mem.concat(a, u8, &.{ rc, g4 }); + defer a.free(p_gu); + const p_dn = try std.mem.replaceOwned(u8, a, dn0_one, member, by_pick); + defer a.free(p_dn); + const gu_from = "4096, 2048, 4, 8, 16, 128, 0, 4, 16, 8"; + const dn_from = "2048, 4096, 4, 8, 16, 128, 0, 4, 16, 8"; + const gu_one_from = "4096, 2048, 2, 8, 16, 128, 0, 4, 16, 8"; + const dn_one_from = "2048, 4096, 2, 8, 16, 128, 0, 4, 16, 8"; + const s0 = try kernels.sh8Source(a, gu0, true, gu_from, "4096, 2048, 4, 8, 16, 128, 0, 8, 16, 16", "glm_moe_gateup_0_sh8"); + errdefer a.free(s0); + const s1 = try kernels.sh8Source(a, dn0, false, dn_from, "2048, 4096, 4, 8, 16, 128, 0, 8, 16, 16", "glm_moe_down_0_sh8"); + errdefer a.free(s1); + const s2 = try kernels.sh8Source(a, gu0, true, gu_from, "4096, 2048, 2, 8, 16, 128, 0, 8, 16, 16", "glm_moe_gateup_0_sh8_one"); + errdefer a.free(s2); + const s3 = try kernels.sh8Source(a, dn0, false, dn_from, "2048, 4096, 2, 8, 16, 128, 0, 8, 16, 16", "glm_moe_down_0_sh8_one"); + errdefer a.free(s3); + const s4 = try kernels.sh8Source(a, p_gu, true, gu_one_from, "4096, 2048, 2, 8, 16, 128, 0, 8, 16, 16", "glm_moe_gateup_0_sh8_pick"); + errdefer a.free(s4); + const s5 = try kernels.sh8Source(a, p_dn, false, dn_one_from, "2048, 4096, 2, 8, 16, 128, 0, 8, 16, 16", "glm_moe_down_0_sh8_pick"); + errdefer a.free(s5); + const comb = comptime kernels.generatedSource("moe_combine") ++ ""; + const ca = try std.mem.replaceOwned(u8, a, comb, "const device bfloat* y = Y + size_t(r) * TOPK * D + d;", "const device bfloat* y = Y + size_t(r) * (TOPK + 1) * D + d;"); + defer a.free(ca); + const s6 = try std.mem.replaceOwned(u8, a, ca, "+ YS[size_t(r) * D + d];", "+ y[size_t(TOPK) * D];"); + errdefer a.free(s6); + const s7 = try a.dupe(u8, rc); + return .{ s0, s1, s2, s3, s4, s5, s6, s7 }; +} + +fn pipeFrom(device: mtl.Device, text: []const u8, sym: [:0]const u8) !mtl.Pipeline { + const lib = try mtl.Library.fromSource(device, text, mtl.CompileOptions.mlx()); + defer lib.deinit(); + return mtl.Pipeline.init(device, lib, sym, false); +} + +fn depth(_: c.Shape) usize { + return 0; +} + +fn spec(v: Variant) c.Spec { + return .{ + .name = entryName(v), + .accum = .none, + .depth = depth, + .out = .bf16, + .replaces = "moe_2_and_wide_q8", + .nan = .propagate, + .tiles = .{ .{ .size = 16 }, .{ .size = 64, .step = 1, .min = 1 }, .{ .size = 512, .step = 64, .min = 64 } }, + .served = if (v.kind == .batch) &batch_served else &pick_served, + }; +} + +pub const Probe = struct { + a: std.mem.Allocator, + rig: rig_.Rig, + v: Variant, + gu4: mtl.Pipeline, + dn4: mtl.Pipeline, + gu2: mtl.Pipeline, + dn2: mtl.Pipeline, + gu_pick: mtl.Pipeline, + dn_pick: mtl.Pipeline, + comb0: mtl.Pipeline, + base_gu: mtl.Pipeline, + base_dn: mtl.Pipeline, + base_comb: mtl.Pipeline, + route_sel: mtl.Pipeline, + wide: tf.glm.wide.Pipes, + shape: c.Shape = undefined, + refs: [27]rig_.Ref = undefined, + acts_ref: rig_.Ref = undefined, + ys_ref: rig_.Ref = undefined, + base_y: rig_.Ref = undefined, + out_bytes: std.ArrayList(u8) = .empty, + + pub fn deinit(p: *Probe) void { + p.rig.deinit(); + p.out_bytes.deinit(p.a); + inline for (.{ p.gu4, p.dn4, p.gu2, p.dn2, p.gu_pick, p.dn_pick, p.comb0, p.base_gu, p.base_dn, p.base_comb, p.route_sel }) |pp| pp.deinit(); + p.wide.deinit(); + } + + pub fn kernel(p: *Probe) g.Kernel { + return .{ .spec = spec(p.v), .ctx = p, .vt = &vt, .control = if (p.v.control) .shapes else null }; + } + + const vt = g.hooks(Probe); + + pub fn check(p: *Probe, _: g.Gate) !?[]const u8 { + const got = try p.rig.outputBytes(); + const want = try p.replaced(); + if (!std.mem.eql(u8, got, want)) return "sh8 fused MoE bytes differ from predecessor"; + return null; + } + + pub fn prepare(p: *Probe, s: c.Shape, f: g.Fill, seed: u64) !bool { + p.rig.reset(); + if (s.n != N or s.k != D or s.rows == 0 or s.rows > 8) return false; + p.shape = s; + const n_exp: usize = E; + const mspecs = [_][3]usize{ + .{ n_exp * N, D, 4 }, .{ n_exp * N, D, 4 }, .{ 2 * N, D, 8 }, .{ n_exp * D, N, 4 }, .{ D, N, 8 }, + }; + var prng = std.Random.DefaultPrng.init(seed); + const rnd = prng.random(); + const xb = try p.a.alloc(u16, s.rows * D); + defer p.a.free(xb); + for (xb) |*v| v.* = c.toBf16((rnd.float(f32) - 0.5) * 2.0); + if (f == .nonfinite) { + xb[0] = 0x7fc0; + if (s.rows > 1) xb[D + 5] = 0x7f80; + } + p.refs[0] = try p.rig.input(std.mem.sliceAsBytes(xb)); + for (mspecs, 0..) |ms, mi| { + const wb = try p.a.alloc(u8, ms[0] * ms[1] * ms[2] / 8); + defer p.a.free(wb); + rnd.bytes(wb); + const sb = try p.a.alloc(u16, ms[0] * (ms[1] / 64)); + defer p.a.free(sb); + const bb = try p.a.alloc(u16, ms[0] * (ms[1] / 64)); + defer p.a.free(bb); + const div: f32 = if (ms[2] == 8) 512.0 else 32.0; + for (sb, bb) |*sv, *bv| { + sv.* = c.toBf16((rnd.float(f32) + 0.5) / div); + bv.* = c.toBf16(-(rnd.float(f32) + 0.5) * 0.1); + } + p.refs[1 + mi * 3] = try p.rig.input(wb); + p.refs[2 + mi * 3] = try p.rig.input(std.mem.sliceAsBytes(sb)); + p.refs[3 + mi * 3] = try p.rig.input(std.mem.sliceAsBytes(bb)); + } + const ids = try p.a.alloc(i32, MAX_EXPERTS); + defer p.a.free(ids); + const mem = try p.a.alloc(i32, MAX_EXPERTS * MAXR); + defer p.a.free(mem); + const pk = try p.a.alloc(i32, MAXR * TOPK); + defer p.a.free(pk); + const lg = try p.a.alloc(f32, s.rows * MAX_EXPERTS); + defer p.a.free(lg); + const bi = try p.a.alloc(f32, MAX_EXPERTS); + defer p.a.free(bi); + const wt = try p.a.alloc(f32, MAXR * TOPK); + defer p.a.free(wt); + @memset(ids, 0); + @memset(mem, -1); + @memset(lg, 0); + @memset(bi, -std.math.inf(f32)); + for (0..E) |ei| bi[ei] = rnd.float(f32) * 0.1; + for (0..s.rows) |r| { + var k: usize = 0; + while (k < TOPK) { + const ev: i32 = @intCast(rnd.uintLessThan(usize, E)); + if (std.mem.indexOfScalar(i32, pk[r * TOPK ..][0..k], ev) == null) { + pk[r * TOPK + k] = ev; + wt[r * TOPK + k] = 0.05 + rnd.float(f32) * 0.2; + k += 1; + } + } + for (0..E) |ei| lg[r * MAX_EXPERTS + ei] = rnd.float(f32) * 2.0 - 1.0; + } + var n_u: usize = 0; + for (0..E) |ei| { + var m: usize = 0; + for (pk[0 .. s.rows * TOPK], 0..) |pv, pi| if (pv == @as(i32, @intCast(ei))) { + mem[n_u * MAXR + m] = @intCast(pi); + m += 1; + }; + if (m > 0) { + ids[n_u] = @intCast(ei); + n_u += 1; + } + } + const uc: [1]i32 = .{@intCast(n_u)}; + const rl_sz = TOPK * MAXR * 4; + if (p.v.kind == .pick) { + p.refs[16] = try p.rig.scratch(MAX_EXPERTS * 4); + p.refs[17] = try p.rig.scratch(MAX_EXPERTS * MAXR * 4); + p.refs[18] = try p.rig.scratch(64); + p.refs[19] = try p.rig.scratch(MAXR * (TOPK + 1) * N * 2); + p.refs[20] = try p.rig.scratch(MAXR * (TOPK + 1) * D * 2); + p.refs[21] = try p.rig.scratch(MAXR * TOPK * 4); + } else { + p.refs[16] = try p.rig.input(std.mem.sliceAsBytes(ids)); + p.refs[17] = try p.rig.input(std.mem.sliceAsBytes(mem)); + p.refs[18] = try p.rig.input(std.mem.asBytes(&uc)); + p.refs[19] = try p.rig.scratch(MAXR * (TOPK + 1) * N * 2); + p.refs[20] = try p.rig.scratch(MAXR * (TOPK + 1) * D * 2); + p.refs[21] = try p.rig.input(std.mem.sliceAsBytes(wt)); + } + p.refs[22] = try p.rig.output(s.rows * D * 2); + p.refs[23] = try p.rig.input(std.mem.sliceAsBytes(lg)); + p.refs[24] = try p.rig.input(std.mem.sliceAsBytes(bi)); + p.refs[25] = try p.rig.scratch(MAXR * TOPK * 4); + p.refs[26] = try p.rig.scratch(rl_sz * 2 + 128); + p.acts_ref = try p.rig.scratch(s.rows * N * 2); + p.ys_ref = try p.rig.scratch(s.rows * D * 2); + p.base_y = try p.rig.scratch(s.rows * D * 2); + return true; + } + + pub fn run(p: *Probe) !void { + const pass = p.rig.begin(); + const e = pass.e; + const rows: u32 = @intCast(p.shape.rows); + const zs = rows * TOPK + 1; + const gu_two = rows <= 4; + const gu_rps: u32 = if (gu_two) 2 else 4; + const dn_rps: u32 = if (rows == 1) 2 else 4; + const is_pick = p.v.kind == .pick; + if (is_pick) { + for (0..rows) |row| { + e.setPipeline(p.gu_pick); + e.setBuffer(p.refs[0].buf, p.refs[0].off + row * D * 2, 0); + e.setBytes(std.mem.asBytes(&[2]i32{ 1, D }), 1); + for (1..10, 2..) |j, slot| e.setBuffer(p.refs[j].buf, p.refs[j].off, slot); + e.setBuffer(p.refs[23].buf, p.refs[23].off + row * MAX_EXPERTS * 4, 11); + e.setBuffer(p.refs[24].buf, p.refs[24].off, 12); + e.setBuffer(p.refs[25].buf, p.refs[25].off + row * TOPK * 4, 13); + e.setValue(swiglu_limit, 14); + e.setBuffer(p.refs[19].buf, p.refs[19].off + row * (TOPK + 1) * N * 2, 15); + e.setBuffer(p.refs[21].buf, p.refs[21].off + row * TOPK * 4, 16); + e.setValue(routed_scale, 17); + e.dispatchThreads(mtl.Size.of(32, N / 2, TOPK + 1), mtl.Size.of(32, 1, 1)); + e.setPipeline(p.dn_pick); + e.setBuffer(p.refs[19].buf, p.refs[19].off + row * (TOPK + 1) * N * 2, 0); + e.setBytes(std.mem.asBytes(&[3]i32{ 1, TOPK + 1, N }), 1); + for (10..16, 2..) |j, slot| e.setBuffer(p.refs[j].buf, p.refs[j].off, slot); + e.setBuffer(p.refs[25].buf, p.refs[25].off + row * TOPK * 4, 8); + e.setBuffer(p.refs[25].buf, p.refs[25].off + row * TOPK * 4, 9); + e.setBuffer(p.refs[25].buf, p.refs[25].off + row * TOPK * 4, 10); + e.setBuffer(p.refs[20].buf, p.refs[20].off + row * (TOPK + 1) * D * 2, 11); + e.dispatchThreads(mtl.Size.of(32, D / 2, TOPK + 1), mtl.Size.of(32, 1, 1)); + } + } else { + e.setPipeline(if (gu_two) p.gu2 else p.gu4); + e.setBuffer(p.refs[0].buf, p.refs[0].off, 0); + e.setBytes(std.mem.asBytes(&[2]i32{ @intCast(rows), D }), 1); + for (1..10, 2..) |j, slot| e.setBuffer(p.refs[j].buf, p.refs[j].off, slot); + for (16..19, 11..) |j, slot| e.setBuffer(p.refs[j].buf, p.refs[j].off, slot); + e.setValue(swiglu_limit, 14); + e.setBuffer(p.refs[19].buf, p.refs[19].off, 15); + e.dispatchThreads(mtl.Size.of(32 * rows, N / gu_rps, zs), mtl.Size.of(32 * rows, 1, 1)); + e.setPipeline(if (rows == 1) p.dn2 else p.dn4); + e.setBuffer(p.refs[19].buf, p.refs[19].off, 0); + e.setBytes(std.mem.asBytes(&[3]i32{ @intCast(rows), TOPK + 1, N }), 1); + for (10..16, 2..) |j, slot| e.setBuffer(p.refs[j].buf, p.refs[j].off, slot); + for (16..19, 8..) |j, slot| e.setBuffer(p.refs[j].buf, p.refs[j].off, slot); + e.setBuffer(p.refs[20].buf, p.refs[20].off, 11); + e.dispatchThreads(mtl.Size.of(32 * rows, D / dn_rps, zs), mtl.Size.of(32 * rows, 1, 1)); + } + e.setPipeline(p.comb0); + e.setBuffer(p.refs[20].buf, p.refs[20].off, 0); + e.setBuffer(p.refs[20].buf, p.refs[20].off, 1); + e.setBuffer(p.refs[21].buf, p.refs[21].off, 2); + e.setBytes(std.mem.asBytes(&[2]i32{ @intCast(rows), TOPK }), 3); + e.setBuffer(p.refs[22].buf, p.refs[22].off, 4); + e.dispatchThreads(mtl.Size.of(rows * D, 1, 1), mtl.Size.of(256, 1, 1)); + try p.rig.finish(pass); + } + + pub fn replaced(p: *Probe) ![]const u8 { + const rows: u32 = @intCast(p.shape.rows); + const rl_sz = TOPK * MAXR * 4; + const pass = p.rig.begin(); + const e = pass.e; + const sh_gu: tf.glm.weights.Affine = .{ .w = .{ .buf = p.refs[7].buf, .off = p.refs[7].off }, .s = .{ .buf = p.refs[8].buf, .off = p.refs[8].off }, .b = .{ .buf = p.refs[9].buf, .off = p.refs[9].off }, .n = 2 * N, .k = D, .bits = 8, .group = 64 }; + const sh_dn: tf.glm.weights.Affine = .{ .w = .{ .buf = p.refs[13].buf, .off = p.refs[13].off }, .s = .{ .buf = p.refs[14].buf, .off = p.refs[14].off }, .b = .{ .buf = p.refs[15].buf, .off = p.refs[15].off }, .n = D, .k = N, .bits = 8, .group = 64 }; + const acts = p.acts_ref; + const ys = p.ys_ref; + if (p.v.kind == .pick) { + const rl = p.refs[26]; + moe_route.select(e, p.route_sel, .{ .buf = p.refs[23].buf, .off = p.refs[23].off }, .{ .buf = p.refs[24].buf, .off = p.refs[24].off }, routed_scale, rows, .{ 0, MAX_EXPERTS }, .{ .pick = .{ .buf = p.refs[25].buf, .off = p.refs[25].off }, .wts = .{ .buf = p.refs[21].buf, .off = p.refs[21].off }, .ids = .{ .buf = p.refs[16].buf, .off = p.refs[16].off }, .members = .{ .buf = p.refs[17].buf, .off = p.refs[17].off }, .count = .{ .buf = p.refs[18].buf, .off = p.refs[18].off }, .mine = .{ .buf = rl.buf, .off = rl.off }, .theirs = .{ .buf = rl.buf, .off = rl.off + rl_sz }, .counts = .{ .buf = rl.buf, .off = rl.off + 2 * rl_sz }, .word = .{ .buf = rl.buf, .off = rl.off + 2 * rl_sz + 64 } }); + } + tf.glm.wide.glu(&p.wide, e, sh_gu, N, .{ .buf = p.refs[0].buf, .off = p.refs[0].off }, .{ .buf = acts.buf, .off = acts.off }, rows, swiglu_limit); + tf.glm.wide.dense(&p.wide, e, sh_dn, .{ .in = .{ .buf = acts.buf, .off = acts.off }, .ldx = N, .out = .{ .buf = ys.buf, .off = ys.off }, .ldo = D, .rows = rows }); + e.setPipeline(p.base_gu); + e.setBuffer(p.refs[0].buf, p.refs[0].off, 0); + e.setBytes(std.mem.asBytes(&[2]i32{ @intCast(rows), D }), 1); + for (1..10, 2..) |j, slot| e.setBuffer(p.refs[j].buf, p.refs[j].off, slot); + for (16..19, 11..) |j, slot| e.setBuffer(p.refs[j].buf, p.refs[j].off, slot); + e.setValue(swiglu_limit, 14); + e.setBuffer(p.refs[19].buf, p.refs[19].off, 15); + e.dispatchThreads(mtl.Size.of(32 * rows, N / 4, rows * TOPK), mtl.Size.of(32 * rows, 1, 1)); + e.setPipeline(p.base_dn); + e.setBuffer(p.refs[19].buf, p.refs[19].off, 0); + e.setBytes(std.mem.asBytes(&[3]i32{ @intCast(rows), TOPK, N }), 1); + for (10..16, 2..) |j, slot| e.setBuffer(p.refs[j].buf, p.refs[j].off, slot); + for (16..19, 8..) |j, slot| e.setBuffer(p.refs[j].buf, p.refs[j].off, slot); + e.setBuffer(p.refs[20].buf, p.refs[20].off, 11); + e.dispatchThreads(mtl.Size.of(32 * rows, D / 4, rows * TOPK), mtl.Size.of(32 * rows, 1, 1)); + e.setPipeline(p.base_comb); + e.setBuffer(ys.buf, ys.off, 0); + e.setBuffer(p.refs[20].buf, p.refs[20].off, 1); + e.setBuffer(p.refs[21].buf, p.refs[21].off, 2); + e.setBytes(std.mem.asBytes(&[2]i32{ @intCast(rows), TOPK }), 3); + e.setBuffer(p.base_y.buf, p.base_y.off, 4); + e.dispatchThreads(mtl.Size.of(rows * D, 1, 1), mtl.Size.of(256, 1, 1)); + try p.rig.finish(pass); + return p.rig.bytes(p.base_y, p.shape.rows * D * 2); + } + + pub fn count(p: *Probe) usize { + return p.shape.rows * D; + } + + pub fn reference(_: *Probe, want: []f64, mag: []f64) !void { + @memset(want, 0); + @memset(mag, 0); + } +}; + +pub const Suite = struct { + a: std.mem.Allocator, + probes: std.ArrayList(*Probe) = .empty, + + const list = [_]Variant{ .{ .kind = .batch }, .{ .kind = .pick }, .{ .kind = .batch, .control = true }, .{ .kind = .pick, .control = true } }; + + pub fn create(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, ks: *std.ArrayList(g.Kernel), only: ?[]const u8) !*Suite { + const s = try a.create(Suite); + s.* = .{ .a = a }; + var srcs: ?[8][]u8 = null; + defer if (srcs) |ss| for (ss) |txt| a.free(txt); + for (list) |v| { + if (only) |text| if (std.mem.indexOf(u8, entryName(v), text) == null) continue; + if (srcs == null) srcs = try buildSources(a); + const ss = srcs.?; + const bad_gu = if (v.control and v.kind == .batch) + try std.mem.replaceOwned(u8, a, ss[2], "int(threadgroup_position_in_grid.z) == int(X_shape[0]) * TOPK", "int(threadgroup_position_in_grid.z) == int(X_shape[0]) * TOPK - 1") + else if (v.control and v.kind == .pick) + try std.mem.replaceOwned(u8, a, ss[4], "tf_route_pick_at(RLOGITS, RBIAS, u, lane,", "tf_route_pick_at(RLOGITS, RBIAS, (u + 1) % TOPK, lane,") + else + try a.dupe(u8, ss[if (v.kind == .batch) 2 else 4]); + defer a.free(bad_gu); + const p = try a.create(Probe); + p.* = .{ + .a = a, + .rig = .{ .a = a, .device = device, .queue = queue }, + .v = v, + .gu4 = try pipeFrom(device, ss[0], "glm_moe_gateup_0_sh8"), + .dn4 = try pipeFrom(device, ss[1], "glm_moe_down_0_sh8"), + .gu2 = try pipeFrom(device, if (v.kind == .batch) bad_gu else ss[2], "glm_moe_gateup_0_sh8_one"), + .dn2 = try pipeFrom(device, ss[3], "glm_moe_down_0_sh8_one"), + .gu_pick = try pipeFrom(device, if (v.kind == .pick) bad_gu else ss[4], "glm_moe_gateup_0_sh8_pick"), + .dn_pick = try pipeFrom(device, ss[5], "glm_moe_down_0_sh8_pick"), + .comb0 = try pipeFrom(device, ss[6], kernels.generatedFunction("moe_combine")), + .base_gu = try pipeFrom(device, kernels.generatedSource("moe_gateup_2"), kernels.generatedFunction("moe_gateup_2")), + .base_dn = try pipeFrom(device, kernels.generatedSource("moe_down_2"), kernels.generatedFunction("moe_down_2")), + .base_comb = try pipeFrom(device, kernels.generatedSource("moe_combine"), kernels.generatedFunction("moe_combine")), + .route_sel = try pipeFrom(device, ss[7], moe_route.names[1]), + .wide = try tf.glm.wide.load(a, device), + }; + try s.probes.append(a, p); + try ks.append(a, p.kernel()); + } + return s; + } + + pub fn destroy(s: *Suite) void { + for (s.probes.items) |p| { + p.deinit(); + s.a.destroy(p); + } + s.probes.deinit(s.a); + s.a.destroy(s); + } +}; diff --git a/zig/tests/contract/metal_limits.zig b/zig/tests/contract/metal_limits.zig index bbcce7afaf5..10d30179175 100644 --- a/zig/tests/contract/metal_limits.zig +++ b/zig/tests/contract/metal_limits.zig @@ -355,6 +355,16 @@ fn resolve(a: std.mem.Allocator, device: mtl.Device, d: limits.MetalLaunch, comp } else if (std.mem.startsWith(u8, d.name, "h3 ")) { if (!assemble) return undefined; text = @import("h3_kernels").source; + } else if (std.mem.startsWith(u8, d.name, "glm sh8 ")) { + if (!assemble) return undefined; + const t = try @import("metal_glm_sh8.zig").buildSources(a); + defer for (t) |x| a.free(x); + const idx: usize = if (std.mem.indexOf(u8, d.name, " pick ") != null) + (if (std.mem.endsWith(u8, d.name, "_pick") and std.mem.indexOf(u8, d.name, "down") != null) 5 else 4) + else if (std.mem.indexOf(u8, d.name, " two ") != null) + (if (std.mem.indexOf(u8, d.name, "down") != null) 3 else 2) + else if (std.mem.indexOf(u8, d.name, "down") != null) 1 else 0; + return .{ .decl = d, .function = fun, .here = try a.dupe(u8, t[idx]), .pre_m5 = try a.dupe(u8, t[idx]) }; } else if (std.mem.startsWith(u8, d.name, "glm gather ") or std.mem.startsWith(u8, d.name, "glm rows ") or std.mem.startsWith(u8, d.name, "glm moe rows ")) { if (!assemble) return undefined; text = tf.glm.wide.gather_source; diff --git a/zig/tests/contract/metal_main.zig b/zig/tests/contract/metal_main.zig index be80f98e870..78ebaad3b44 100644 --- a/zig/tests/contract/metal_main.zig +++ b/zig/tests/contract/metal_main.zig @@ -390,6 +390,8 @@ pub fn main(init: std.process.Init) !u8 { var glm_dflash_follow: @import("metal_glm_dflash_follow.zig").Suite = .{ .a = a, .device = device, .queue = queue, .kernels = &kernels }; defer glm_dflash_follow.deinit(); try glm_dflash_follow.collect(o.only); + var glm_sh8 = try @import("metal_glm_sh8.zig").Suite.create(a, device, queue, &kernels, o.only); + defer glm_sh8.destroy(); var flint: @import("metal_flint.zig").Suite = .{ .a = a, .device = device, .queue = queue, .kernels = &kernels }; defer flint.deinit(); try flint.collect(o.only); From 78abb487a73e264e1abd51207531ccd13e92725d Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sat, 28 Nov 2026 11:52:37 +0000 Subject: [PATCH 2/4] adapt: keep GLM SH8 Metal limits within line cap --- zig/tests/contract/metal_limits.zig | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/zig/tests/contract/metal_limits.zig b/zig/tests/contract/metal_limits.zig index 10d30179175..4be9f930412 100644 --- a/zig/tests/contract/metal_limits.zig +++ b/zig/tests/contract/metal_limits.zig @@ -356,14 +356,9 @@ fn resolve(a: std.mem.Allocator, device: mtl.Device, d: limits.MetalLaunch, comp if (!assemble) return undefined; text = @import("h3_kernels").source; } else if (std.mem.startsWith(u8, d.name, "glm sh8 ")) { - if (!assemble) return undefined; - const t = try @import("metal_glm_sh8.zig").buildSources(a); + const t = if (assemble) try @import("metal_glm_sh8.zig").buildSources(a) else return undefined; defer for (t) |x| a.free(x); - const idx: usize = if (std.mem.indexOf(u8, d.name, " pick ") != null) - (if (std.mem.endsWith(u8, d.name, "_pick") and std.mem.indexOf(u8, d.name, "down") != null) 5 else 4) - else if (std.mem.indexOf(u8, d.name, " two ") != null) - (if (std.mem.indexOf(u8, d.name, "down") != null) 3 else 2) - else if (std.mem.indexOf(u8, d.name, "down") != null) 1 else 0; + const idx: usize = if (has(d.name, " pick ")) (if (std.mem.endsWith(u8, d.name, "_pick") and has(d.name, "down")) 5 else 4) else if (has(d.name, " two ")) (if (has(d.name, "down")) 3 else 2) else if (has(d.name, "down")) 1 else 0; return .{ .decl = d, .function = fun, .here = try a.dupe(u8, t[idx]), .pre_m5 = try a.dupe(u8, t[idx]) }; } else if (std.mem.startsWith(u8, d.name, "glm gather ") or std.mem.startsWith(u8, d.name, "glm rows ") or std.mem.startsWith(u8, d.name, "glm moe rows ")) { if (!assemble) return undefined; From 436ef0832bf2e55d90aac62693036e4c3dd18115 Mon Sep 17 00:00:00 2001 From: Kevin Gilbertson <880013+gilby@users.noreply.github.com> Date: Tue, 1 Dec 2026 21:18:48 +0100 Subject: [PATCH 3/4] glm metal: use transactional contract registration for sh8 suite and update source origins --- zig/src/families/glm/kernels.zig | 8 +-- zig/tests/contract/metal_glm_sh8.zig | 92 ++++++++++++++++++++++------ 2 files changed, 77 insertions(+), 23 deletions(-) diff --git a/zig/src/families/glm/kernels.zig b/zig/src/families/glm/kernels.zig index 0a4223f13c2..605721263df 100644 --- a/zig/src/families/glm/kernels.zig +++ b/zig/src/families/glm/kernels.zig @@ -512,7 +512,7 @@ fn assemble(gpa: std.mem.Allocator, device: mtl.Device, k: *Kernels, visitor: an generated.len + 4 => &.{ sources.glm_attn, sources.nax }, generated.len + 5, generated.len + 6 => &.{ sources.core_moe_route, sources.glm_route_one }, generated.len + 7 => &.{ sources.core_affine_mm, sources.core_affine_nonfinite, sources.glm_mm_groups, sources.nax }, - generated.len + 8, generated.len + 27 => &.{ sources.core_affine_mm, sources.core_affine_nonfinite, sources.nax }, + generated.len + 8, generated.len + 33 => &.{ sources.core_affine_mm, sources.core_affine_nonfinite, sources.nax }, generated.len + 9 => &.{ comptime kernelOf("kda_rows").source, sources.glm_kda_prompt, sources.glm_kda_window, sources.glm_kda_parts }, generated.len + 10, generated.len + 13 => &.{ sources.glm_sparse_nax, sources.nax }, generated.len + 11, generated.len + 14 => &.{ sources.glm_absorb_nax, sources.nax }, @@ -520,11 +520,11 @@ fn assemble(gpa: std.mem.Allocator, device: mtl.Device, k: *Kernels, visitor: an generated.len + 15 => &.{ sources.glm_index_nax, sources.nax }, generated.len + 16 => &.{comptime kernelOf("moe_gateup_1").source}, generated.len + 17 => &.{comptime kernelOf("moe_down_1").source}, - generated.len + 18, generated.len + 20 => &.{comptime kernelOf("moe_gateup_2").source}, - generated.len + 19, generated.len + 21 => &.{comptime kernelOf("moe_down_2").source}, + generated.len + 18, generated.len + 20, generated.len + 27, generated.len + 29 => &.{comptime kernelOf("moe_gateup_2").source}, + generated.len + 19, generated.len + 21, generated.len + 28, generated.len + 30, generated.len + 32 => &.{comptime kernelOf("moe_down_2").source}, generated.len + 22 => &.{comptime kernelOf("moe_combine").source}, generated.len + 24 => &.{ sources.ops_softmax, sources.glm_softmax_rows }, - generated.len + 25 => &.{ sources.core_moe_route, comptime kernelOf("moe_gateup_2").source }, + generated.len + 25, generated.len + 31 => &.{ sources.core_moe_route, comptime kernelOf("moe_gateup_2").source }, generated.len + 26 => &.{comptime kernelOf("moe_down_2").source}, else => &.{j.source}, }; diff --git a/zig/tests/contract/metal_glm_sh8.zig b/zig/tests/contract/metal_glm_sh8.zig index 2155e136123..e07832a7c29 100644 --- a/zig/tests/contract/metal_glm_sh8.zig +++ b/zig/tests/contract/metal_glm_sh8.zig @@ -131,6 +131,46 @@ pub const Probe = struct { base_y: rig_.Ref = undefined, out_bytes: std.ArrayList(u8) = .empty, + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, v: Variant, ss: [8][]u8, bad_gu: []const u8) !Probe { + const specs = [_]struct { src: []const u8, sym: [:0]const u8 }{ + .{ .src = ss[0], .sym = "glm_moe_gateup_0_sh8" }, + .{ .src = ss[1], .sym = "glm_moe_down_0_sh8" }, + .{ .src = if (v.kind == .batch) bad_gu else ss[2], .sym = "glm_moe_gateup_0_sh8_one" }, + .{ .src = ss[3], .sym = "glm_moe_down_0_sh8_one" }, + .{ .src = if (v.kind == .pick) bad_gu else ss[4], .sym = "glm_moe_gateup_0_sh8_pick" }, + .{ .src = ss[5], .sym = "glm_moe_down_0_sh8_pick" }, + .{ .src = ss[6], .sym = kernels.generatedFunction("moe_combine") }, + .{ .src = kernels.generatedSource("moe_gateup_2"), .sym = kernels.generatedFunction("moe_gateup_2") }, + .{ .src = kernels.generatedSource("moe_down_2"), .sym = kernels.generatedFunction("moe_down_2") }, + .{ .src = kernels.generatedSource("moe_combine"), .sym = kernels.generatedFunction("moe_combine") }, + .{ .src = ss[7], .sym = moe_route.names[1] }, + }; + var pipes: [11]mtl.Pipeline = undefined; + var made: usize = 0; + errdefer for (pipes[0..made]) |pp| pp.deinit(); + for (specs) |sp| { + pipes[made] = try pipeFrom(device, sp.src, sp.sym); + made += 1; + } + return .{ + .a = a, + .rig = .{ .a = a, .device = device, .queue = queue }, + .v = v, + .gu4 = pipes[0], + .dn4 = pipes[1], + .gu2 = pipes[2], + .dn2 = pipes[3], + .gu_pick = pipes[4], + .dn_pick = pipes[5], + .comb0 = pipes[6], + .base_gu = pipes[7], + .base_dn = pipes[8], + .base_comb = pipes[9], + .route_sel = pipes[10], + .wide = try tf.glm.wide.load(a, device), + }; + } + pub fn deinit(p: *Probe) void { p.rig.deinit(); p.out_bytes.deinit(p.a); @@ -373,8 +413,11 @@ pub const Suite = struct { const list = [_]Variant{ .{ .kind = .batch }, .{ .kind = .pick }, .{ .kind = .batch, .control = true }, .{ .kind = .pick, .control = true } }; pub fn create(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, ks: *std.ArrayList(g.Kernel), only: ?[]const u8) !*Suite { + const base_len = ks.items.len; + errdefer ks.items.len = base_len; const s = try a.create(Suite); s.* = .{ .a = a }; + errdefer s.destroy(); var srcs: ?[8][]u8 = null; defer if (srcs) |ss| for (ss) |txt| a.free(txt); for (list) |v| { @@ -389,25 +432,10 @@ pub const Suite = struct { try a.dupe(u8, ss[if (v.kind == .batch) 2 else 4]); defer a.free(bad_gu); const p = try a.create(Probe); - p.* = .{ - .a = a, - .rig = .{ .a = a, .device = device, .queue = queue }, - .v = v, - .gu4 = try pipeFrom(device, ss[0], "glm_moe_gateup_0_sh8"), - .dn4 = try pipeFrom(device, ss[1], "glm_moe_down_0_sh8"), - .gu2 = try pipeFrom(device, if (v.kind == .batch) bad_gu else ss[2], "glm_moe_gateup_0_sh8_one"), - .dn2 = try pipeFrom(device, ss[3], "glm_moe_down_0_sh8_one"), - .gu_pick = try pipeFrom(device, if (v.kind == .pick) bad_gu else ss[4], "glm_moe_gateup_0_sh8_pick"), - .dn_pick = try pipeFrom(device, ss[5], "glm_moe_down_0_sh8_pick"), - .comb0 = try pipeFrom(device, ss[6], kernels.generatedFunction("moe_combine")), - .base_gu = try pipeFrom(device, kernels.generatedSource("moe_gateup_2"), kernels.generatedFunction("moe_gateup_2")), - .base_dn = try pipeFrom(device, kernels.generatedSource("moe_down_2"), kernels.generatedFunction("moe_down_2")), - .base_comb = try pipeFrom(device, kernels.generatedSource("moe_combine"), kernels.generatedFunction("moe_combine")), - .route_sel = try pipeFrom(device, ss[7], moe_route.names[1]), - .wide = try tf.glm.wide.load(a, device), - }; - try s.probes.append(a, p); - try ks.append(a, p.kernel()); + errdefer a.destroy(p); + p.* = try Probe.init(a, device, queue, v, ss, bad_gu); + errdefer p.deinit(); + try contract.register(a, &s.probes, ks, p, p.kernel()); } return s; } @@ -421,3 +449,29 @@ pub const Suite = struct { s.a.destroy(s); } }; + +test "glm sh8 suite: a failed allocation at each step of create frees all it took" { + const device = mtl.Device.init() catch return error.SkipZigTest; + defer device.deinit(); + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const queue = try device.queue(); + defer queue.deinit(); + var fail_index: usize = 0; + while (true) : (fail_index += 1) { + var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{ .fail_index = fail_index }); + const a = failing.allocator(); + var ks: std.ArrayList(g.Kernel) = .empty; + defer ks.deinit(a); + const s = Suite.create(a, device, queue, &ks, "pick") catch |err| { + try std.testing.expectEqual(error.OutOfMemory, err); + try std.testing.expectEqual(@as(usize, 0), ks.items.len); + continue; + }; + defer s.destroy(); + try std.testing.expectEqual(@as(usize, 2), s.probes.items.len); + try std.testing.expectEqual(@as(usize, 2), ks.items.len); + try std.testing.expect(fail_index >= 5); + break; + } +} From 7513e6671a945df370543ba6648c938e15874adf Mon Sep 17 00:00:00 2001 From: Kevin Gilbertson <880013+gilby@users.noreply.github.com> Date: Fri, 4 Dec 2026 04:56:09 +0100 Subject: [PATCH 4/4] glm metal: add M3 Ultra GLM-5.3-Flash-oQ4e-mtp performance receipt --- .../glm-metal-moe-sh8/perf-receipt.json | 188 ++++++++++++++++++ 1 file changed, 188 insertions(+) create mode 100644 docs/receipts/glm-metal-moe-sh8/perf-receipt.json diff --git a/docs/receipts/glm-metal-moe-sh8/perf-receipt.json b/docs/receipts/glm-metal-moe-sh8/perf-receipt.json new file mode 100644 index 00000000000..acd7c51fcf3 --- /dev/null +++ b/docs/receipts/glm-metal-moe-sh8/perf-receipt.json @@ -0,0 +1,188 @@ +{ + "schema": 1, + "pack_id": "tf-receipt-v1", + "pack_sha256": "ab2a5d0ff262007e3ef4714fa46e62b2b2454b3f97b652ca18da49e4e0583c42", + "generated_at_utc": "2026-12-04T03:54:00Z", + "claim": "Fuse 8-bit/64 shared expert with 4-bit/64 routed MoE on Metal", + "git": { + "base_sha": "9cd11ef068adf656f9a84dd7014ae3b64d230887", + "head_sha": "ba662f20305179afd364aa527f52eb5b591923f8" + }, + "environment": { + "chip": "apple-m3-ultra", + "os": "darwin", + "arch": "arm64", + "checkpoint_id": "Jundot/GLM-5.3-Flash-oQ4e-mtp", + "draft": true, + "base_binary_sha256": "65a6b05d7abeeeb7b0f8a1ca05e6719ac944bc37d772ef6f4d486dafe320bb84", + "head_binary_sha256": "2cc903024a67b3b97340ea0087b8277970647e8fcf08cae07bd4238ab20d3da8" + }, + "control": { + "prompt_id": "prose_seeded", + "seed_a": 424242, + "seed_b": 989898, + "base_token_sha256": "bdaf94e247b8dab05a726f7c25bd0994b0658c3155d6d76aeeafc02f81c6a0cc", + "alt_token_sha256": "d443925eb6f2beb617638a36d07747264d37c0a8543db8d0e216ae790d2480b2", + "diverged": true + }, + "draft_check": { + "prompt_id": "prose_greedy", + "plain_token_sha256": "a6faf066863cd535f96ed84b54124ee937b2bfcc7580e8faf32ea8444a6e970f", + "draft_token_sha256": "a6faf066863cd535f96ed84b54124ee937b2bfcc7580e8faf32ea8444a6e970f", + "equal": true + }, + "order": [ + "base", + "head", + "head", + "base", + "base", + "head", + "head", + "base" + ], + "rounds": [ + { + "index": 0, + "arm": "base", + "agg_tok_s": 58.342 + }, + { + "index": 1, + "arm": "head", + "agg_tok_s": 59.723 + }, + { + "index": 2, + "arm": "head", + "agg_tok_s": 59.449 + }, + { + "index": 3, + "arm": "base", + "agg_tok_s": 58.086 + }, + { + "index": 4, + "arm": "base", + "agg_tok_s": 58.169 + }, + { + "index": 5, + "arm": "head", + "agg_tok_s": 59.722 + }, + { + "index": 6, + "arm": "head", + "agg_tok_s": 60.609 + }, + { + "index": 7, + "arm": "base", + "agg_tok_s": 57.879 + } + ], + "summary": { + "mean_base_tok_s": 58.119, + "mean_head_tok_s": 59.876, + "gain_pct": 3.023, + "base_noise_pct": 0.8 + }, + "prompts": { + "prose_greedy": { + "base": { + "tokens": 128, + "prompt_tokens": 32, + "cached_tokens": 0, + "complete": true, + "token_sha256": "a6faf066863cd535f96ed84b54124ee937b2bfcc7580e8faf32ea8444a6e970f", + "output_sha256": "f90d69b6b489f033c102d14a8a6140f93e815a015b0846a261c9effc49934ffa", + "tok_s": 52.485, + "ttft_s": 0.2643 + }, + "head": { + "tokens": 128, + "prompt_tokens": 32, + "cached_tokens": 0, + "complete": true, + "token_sha256": "a6faf066863cd535f96ed84b54124ee937b2bfcc7580e8faf32ea8444a6e970f", + "output_sha256": "f90d69b6b489f033c102d14a8a6140f93e815a015b0846a261c9effc49934ffa", + "tok_s": 57.932, + "ttft_s": 0.2641 + }, + "token_equal": true + }, + "code_greedy": { + "base": { + "tokens": 128, + "prompt_tokens": 38, + "cached_tokens": 0, + "complete": true, + "token_sha256": "2dd6efe66ce35ae24f61b8b62c2033e6e1f09aa06de7da8a0a11cb59b46c7778", + "output_sha256": "adf3285e8009af1c127a83015266ae82455430b913a900bee4fa3088a303ead2", + "tok_s": 55.187, + "ttft_s": 0.2963 + }, + "head": { + "tokens": 128, + "prompt_tokens": 38, + "cached_tokens": 0, + "complete": true, + "token_sha256": "2dd6efe66ce35ae24f61b8b62c2033e6e1f09aa06de7da8a0a11cb59b46c7778", + "output_sha256": "adf3285e8009af1c127a83015266ae82455430b913a900bee4fa3088a303ead2", + "tok_s": 55.8, + "ttft_s": 0.2966 + }, + "token_equal": true + }, + "reasoning_greedy": { + "base": { + "tokens": 128, + "prompt_tokens": 47, + "cached_tokens": 0, + "complete": true, + "token_sha256": "822e08b8ebf69c562c5f43ae3500eb7d9bfdf0d04b9dbca1fec0eb81bb245ec2", + "output_sha256": "e6b1e83c187cfe456547603d0a0f8bb8df521d37dc0db167a3b8e835af06fa5a", + "tok_s": 65.148, + "ttft_s": 0.3198 + }, + "head": { + "tokens": 128, + "prompt_tokens": 47, + "cached_tokens": 0, + "complete": true, + "token_sha256": "822e08b8ebf69c562c5f43ae3500eb7d9bfdf0d04b9dbca1fec0eb81bb245ec2", + "output_sha256": "e6b1e83c187cfe456547603d0a0f8bb8df521d37dc0db167a3b8e835af06fa5a", + "tok_s": 68.229, + "ttft_s": 0.3201 + }, + "token_equal": true + }, + "prose_seeded": { + "base": { + "tokens": 64, + "prompt_tokens": 25, + "cached_tokens": 0, + "complete": true, + "token_sha256": "bdaf94e247b8dab05a726f7c25bd0994b0658c3155d6d76aeeafc02f81c6a0cc", + "output_sha256": "2543d8ca727db7bb1a6e125e1ccfca68cfdbec7606cdebe71bdaaa530b549498", + "tok_s": 62.91, + "ttft_s": 0.234 + }, + "head": { + "tokens": 64, + "prompt_tokens": 25, + "cached_tokens": 0, + "complete": true, + "token_sha256": "bdaf94e247b8dab05a726f7c25bd0994b0658c3155d6d76aeeafc02f81c6a0cc", + "output_sha256": "2543d8ca727db7bb1a6e125e1ccfca68cfdbec7606cdebe71bdaaa530b549498", + "tok_s": 63.232, + "ttft_s": 0.234 + }, + "token_equal": true + } + }, + "exactness_sha256": "142d8d9479751bcc3b33ae7cc0224231758c22566a94af6d0d118ab16ab7d359", + "receipt_sha256": "534f236f726c0c7602b1e3ef9c952c977258dff3d73264e755995b12f559cfb3" +}