diff --git a/CHANGELOG.md b/CHANGELOG.md index de86edf4173..5535fc7b4be 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased +- GLM on Metal: vectorized prompt, KDA and indexer kernels on Macs without tensor units cut cold prompt time 5.17% to 5.68% (2K to 64K tokens) with 0/64 token differences (#3921, refs #3152). Thanks to @gilby. + - MiniMax-H3-Image on Metal: `tf-h3-image` runs its transformer (MiniMax H3's, without the audio layers, on M5 tensor units) from a picture case through its six distilled steps, each with its own output head, beside the engine; the VAE's rules (config, tiles and blend, latent statistics, pixels) run on the host, and core/picture gains Pillow's Lanczos-3 resampling. Clip cases run as before (#2775). - Kernel contract: the GLM record for `df_sumn` under nvcc 13.3 (40 registers) is the one checked; a stale generic 33-register entry no longer overrides it (#4291). Thanks to @Bizuayeu. diff --git a/zig/build/glm_rows_contract.zig b/zig/build/glm_rows_contract.zig index b2be197e026..ba5099310af 100644 --- a/zig/build/glm_rows_contract.zig +++ b/zig/build/glm_rows_contract.zig @@ -14,5 +14,13 @@ pub fn host(b: *std.Build, sources: *std.Build.Module) *std.Build.Step { run.has_side_effects = true; const step = b.step("test-glm-window-contract-host", "Register and validate actual GLM replacement operators without a GPU"); step.dependOn(&run.step); + const ownership_metal = b.createModule(.{ .root_source_file = b.path("zig/glm_kernel_ownership_metal.zig"), .target = b.graph.host }); + const loader = b.createModule(.{ .root_source_file = b.path("zig/glm_rows_contract_family.zig"), .target = b.graph.host, .imports = &.{ .{ .name = "metal", .module = ownership_metal }, .{ .name = "kernel_sources", .module = sources } } }); + const ownership_root = b.createModule(.{ .root_source_file = b.path("zig/glm_kernel_ownership_host.zig"), .target = b.graph.host, .optimize = .debug, .link_libc = true, .imports = &.{ .{ .name = "metal", .module = ownership_metal }, .{ .name = "glm_kernels", .module = loader } } }); + const ownership_run = b.addRunArtifact(b.addTest(.{ .root_module = ownership_root, .filters = &.{"GLM kernel ownership:"} })); + ownership_run.has_side_effects = true; + const ownership_step = b.step("test-glm-kernel-ownership-host", "Actual GLM loader pipelines are all released once on both capability paths"); + ownership_step.dependOn(&ownership_run.step); + step.dependOn(ownership_step); return step; } diff --git a/zig/gemma4_shared_affine_test.zig b/zig/gemma4_shared_affine_test.zig index 6c2b89115f0..27303b25f3e 100644 --- a/zig/gemma4_shared_affine_test.zig +++ b/zig/gemma4_shared_affine_test.zig @@ -104,7 +104,7 @@ test "landed Metal source bytes are pinned without shader compilation" { var hash: [32]u8 = undefined; std.crypto.hash.sha2.Sha256.hash(ks.core_affine_mm, &hash, .{}); // Hy4-flash's mapped experts and rounded SiLU, both behind defines that are off for every other caller - try std.testing.expectEqualStrings("2cf4deb55455fda30efb4fce3043ef5d90052d71f48ce7660960e8b588478aca", &std.fmt.bytesToHex(hash, .lower)); + try std.testing.expectEqualStrings("9a01998f26f80c9faa511dce14d1f545264c9ab343d189d8f0f005d83cc632b7", &std.fmt.bytesToHex(hash, .lower)); } { var hash: [32]u8 = undefined; diff --git a/zig/glm_kernel_ownership_host.zig b/zig/glm_kernel_ownership_host.zig new file mode 100644 index 00000000000..3c8c22e70d5 --- /dev/null +++ b/zig/glm_kernel_ownership_host.zig @@ -0,0 +1,19 @@ +//! Exercise the actual GLM loader and destructor on both Metal capability paths. +const std = @import("std"); +const metal = @import("metal"); +const kernels = @import("glm_kernels").glm.kernels; +fn check(tensor: bool) !void { + metal.reset(); + const a = std.testing.allocator; + const k = try kernels.load(a, .{ .tensor = tensor }); + defer a.destroy(k); + k.deinit(); + try std.testing.expectEqual(metal.created.load(.monotonic), metal.released.load(.monotonic)); + try std.testing.expect(metal.created.load(.monotonic) > 0); +} +test "GLM kernel ownership: pre-M5 releases every compiled pipeline exactly once" { + try check(false); +} +test "GLM kernel ownership: M5 releases every compiled pipeline exactly once" { + try check(true); +} diff --git a/zig/glm_kernel_ownership_metal.zig b/zig/glm_kernel_ownership_metal.zig new file mode 100644 index 00000000000..ae1d50f2e07 --- /dev/null +++ b/zig/glm_kernel_ownership_metal.zig @@ -0,0 +1,56 @@ +//! Count loader pipeline ownership without a device, shader compiler or driver. +const std = @import("std"); +pub var created = std.atomic.Value(usize).init(0); +pub var released = std.atomic.Value(usize).init(0); +var ended: [4096]std.atomic.Value(bool) = @splat(std.atomic.Value(bool).init(false)); +pub fn reset() void { + created.store(0, .monotonic); + released.store(0, .monotonic); + for (&ended) |*v| v.store(false, .monotonic); +} +pub const Device = struct { + tensor: bool, + pub fn tensorUnits(d: Device) bool { + return d.tensor; + } + pub fn name(_: Device) [*:0]const u8 { + return "ownership fixture"; + } +}; +pub const CompileOptions = struct { + pub fn mlx() CompileOptions { + return .{}; + } +}; +pub const Library = struct { + pub fn fromSource(_: Device, _: []const u8, _: CompileOptions) !Library { + return .{}; + } + pub fn deinit(_: Library) void {} +}; +pub const Pipeline = struct { + id: usize, + pub fn init(_: Device, _: Library, _: [:0]const u8, _: bool) !Pipeline { + const id = created.fetchAdd(1, .monotonic); + std.debug.assert(id < ended.len); + return .{ .id = id }; + } + pub fn deinit(p: Pipeline) void { + std.debug.assert(!ended[p.id].swap(true, .monotonic)); + _ = released.fetchAdd(1, .monotonic); + } +}; +pub const Buffer = struct { + pub fn deinit(_: Buffer) void {} +}; +pub const ComputeEncoder = struct {}; +pub const Queue = struct {}; +pub const Size = @import("gemma4_recording_metal.zig").Size; +pub const objc = struct { + pub const Pool = struct { + pub fn push() Pool { + return .{}; + } + pub fn pop(_: Pool) void {} + }; +}; diff --git a/zig/glm_rows_contract_family.zig b/zig/glm_rows_contract_family.zig index f7f77134df5..b7ebe2d5b90 100644 --- a/zig/glm_rows_contract_family.zig +++ b/zig/glm_rows_contract_family.zig @@ -1,5 +1,6 @@ //! Shared GLM owners for recording-only contract tests. pub const glm = struct { + pub const kernels = @import("src/families/glm/kernels.zig"); pub const wide = @import("src/families/glm/wide.zig"); pub const affine = @import("src/families/glm/affine.zig"); }; diff --git a/zig/kernels/metal/core/affine_mm.metal b/zig/kernels/metal/core/affine_mm.metal index c5b94d93d98..2f138603938 100644 --- a/zig/kernels/metal/core/affine_mm.metal +++ b/zig/kernels/metal/core/affine_mm.metal @@ -152,6 +152,47 @@ inline void am_codes(thread const Codes& c, threadgroup bfloat* out) { #endif } +#if defined(TF_GLM_M3_FAST) && defined(TF_SIMD_FRAGS) +// GLM pre-M5: codes in [K=64][N=64] layout so frag_get reads transposed weights with zero bank conflict. +inline void am_codes_kn(thread const Codes& c, threadgroup bfloat* tile, int w_n, int w_kh) { +#if TF_BITS == 2 + TF_UNROLL + for (short i = 0; i < 2; i++) { + const uint w = c.v[i]; + TF_UNROLL + for (short j = 0; j < 16; j++) tile[(w_kh * 32 + i * 16 + j) * PAD + w_n] = bfloat(float((w >> (2 * j)) & 3u)); + } +#elif TF_BITS % 4 != 0 + TF_UNROLL + for (short j = 0; j < 32; j++) { + const short at = TF_BITS * j, word = at / 32, shift = at % 32; + uint v = c.v[word] >> shift; + if (shift + TF_BITS > 32) v |= c.v[word + 1] << (32 - shift); + tile[(w_kh * 32 + j) * PAD + w_n] = bfloat(float(v & ((1u << TF_BITS) - 1u))); + } +#elif TF_BITS == 4 + TF_UNROLL + for (short i = 0; i < 4; i++) { + const uint w = c.v[0][i]; + TF_UNROLL + for (short j = 0; j < 8; j++) { + tile[(w_kh * 32 + i * 8 + j) * PAD + w_n] = as_type(ushort(0x4300u | ((w >> (4 * j)) & 0xfu))); + } + } +#else + TF_UNROLL + for (short i = 0; i < 8; i++) { + const uchar4 f = as_type(c.v[i / 4][i % 4]); + const int b = w_kh * 32 + i * 4; + tile[b * PAD + w_n] = bfloat(float(f.x)); + tile[(b + 1) * PAD + w_n] = bfloat(float(f.y)); + tile[(b + 2) * PAD + w_n] = bfloat(float(f.z)); + tile[(b + 3) * PAD + w_n] = bfloat(float(f.w)); + } +#endif +} +#endif + // A block of the code tile as the transposed right operand: 8-byte loads on M5 (PAD rows, 16-column blocks). #ifndef TF_SIMD_FRAGS #define am_tile_frag frag_get_tg @@ -188,8 +229,13 @@ inline void am_step(thread frag (&acc)[TM][2], thread const AmRows& r TF_UNROLL for (short q = 0; q < 4; q++) { // the step's four 16-deep slices, every row fragment's chain interleaved frag b0, b1, a[TL]; +#if defined(TF_GLM_M3_FAST) && defined(TF_SIMD_FRAGS) + frag_get(b0, tile, PAD, 16 * q, tn, home); + frag_get(b1, tile, PAD, 16 * q, tn + 16, home); +#else am_tile_frag(b0, tile, PAD, tn, 16 * q, home); am_tile_frag(b1, tile, PAD, tn + 16, 16 * q, home); +#endif TF_UNROLL for (short m = 0; m < TL; m++) { a[m] = am_frag(rows.x[m][0], rows.x[m][1], k + 16 * q, home); @@ -231,8 +277,13 @@ inline void am_step128(thread frag (&acc)[TM][2], thread frag (&pa TF_UNROLL for (short q = 0; q < 4; q++) { frag b0, b1, a[TL]; +#if defined(TF_GLM_M3_FAST) && defined(TF_SIMD_FRAGS) + frag_get(b0, tile, PAD, 16 * q, tn, home); + frag_get(b1, tile, PAD, 16 * q, tn + 16, home); +#else frag_get_t(b0, tile, PAD, tn, 16 * q, home); frag_get_t(b1, tile, PAD, tn + 16, 16 * q, home); +#endif TF_UNROLL for (short m = 0; m < TL; m++) { a[m] = am_frag(rows.x[m][0], rows.x[m][1], k + 16 * q, home); @@ -268,7 +319,11 @@ template inline void am_k_loop(thread frag (&acc)[TM][2], thread const AmRows& rows, int K, int live, const device uchar* wq, const device bfloat* scales, const device bfloat* biases, threadgroup bfloat* tile, threadgroup float* sb, int tn, uint t, short2 home) { +#if defined(TF_GLM_M3_FAST) && defined(TF_SIMD_FRAGS) + const int w_n = int(t / 2), w_kh = int(t % 2); +#else threadgroup bfloat* mine = tile + (t / 2) * PAD + 32 * (t % 2); +#endif const int g_mine = TF_GROUP == 32 ? int(t % 2) : 0; // at g32 each thread of a pair takes one group's scale and bias #if TF_GROUP == 128 frag part[TM][2]; // a group's sums across its two steps @@ -280,7 +335,11 @@ inline void am_k_loop(thread frag (&acc)[TM][2], thread const AmRows& } for (int k = 0; k < K; k += 64) { threadgroup_barrier(mem_flags::mem_threadgroup); +#if defined(TF_GLM_M3_FAST) && defined(TF_SIMD_FRAGS) + am_codes_kn(am_load(wq), tile, w_n, w_kh); +#else am_codes(am_load(wq), mine); +#endif if (TF_GROUP == 32 || t % 2 == 0) { const float s = float(scales[g_mine]); sb[g_mine * 128 + t / 2] = s; @@ -417,9 +476,14 @@ inline void am_block(const device bfloat* x, int ldx, const device float* xs, in uint3 tg [[threadgroup_position_in_grid]]) { threadgroup bfloat tile[64 * PAD]; threadgroup float sb[NG * 128]; - const int row = int(tg.y) * 64, col = int(tg.x) * 64, b = int(tg.z); - am_block<64>(X + long(b) * st.x_batch, st.x_row, XS + long(b) * st.sums_batch * (a.k / TF_GROUP), - st.sums_row * (a.k / TF_GROUP), row, min(64, a.rows - row), a.k, st.y_row, col, +#if defined(TF_GLM_M3_FAST) && defined(TF_SIMD_FRAGS) + constexpr int BM = 32; +#else + constexpr int BM = 64; +#endif + const int row = int(tg.y) * BM, col = int(tg.x) * 64, b = int(tg.z); + am_block(X + long(b) * st.x_batch, st.x_row, XS + long(b) * st.sums_batch * (a.k / TF_GROUP), + st.sums_row * (a.k / TF_GROUP), row, min(BM, a.rows - row), a.k, st.y_row, col, long(b) * st.w_batch + col, W, S, B, Y + long(b) * st.y_batch, tile, sb, sg, lane); } @@ -468,80 +532,3 @@ TF_GATHER(64) } TF_GATHER_SCATTER(32) TF_GATHER_SCATTER(64) - -#ifdef TF_GLU_PLAIN -// mlx-lm's compiled SwiGLU on bf16 rows (LFM2): silu(g) * u, rounded to bf16 at each step; `limit` unused. -inline bfloat am_swiglu(float g, float u, float limit) { - const float gt = float(bfloat(g)); - const bfloat s = static_cast(1.0f / (1.0f + metal::precise::exp(-gt))); - const bfloat silu = static_cast(gt * float(s)); - return static_cast(float(silu) * float(bfloat(u))); -} -#else -// The glue's SwiGLU in bf16 (glm_act2): MLX's bf16 exp and abs, nn.silu's x*sigmoid(x), gate and up clipped at `limit`. -inline bfloat am_sigmoid(bfloat x) { - const bfloat e = bfloat(__metal_exp(float(bfloat(__metal_fabs(float(x), __METAL_MAYBE_FAST_MATH__))), __METAL_MAYBE_FAST_MATH__)); - const bfloat y = bfloat(1) / (bfloat(1) + e); - return (x < 0) ? y : (bfloat(1) - y); -} - -inline bfloat am_swiglu(float g, float u, float limit) { - const float lim = float(bfloat(limit)); - const bfloat gt = bfloat(metal::min(float(bfloat(g)), lim)); - const bfloat up = bfloat(metal::min(metal::max(float(bfloat(u)), -lim), lim)); -#ifdef TF_GLU_ROUND_SILU - const bfloat sl = bfloat(precise::divide(float(gt), 1.0f + precise::exp(-float(gt)))); -#else - const bfloat sl = gt * am_sigmoid(gt); -#endif - return sl * up; -} -#endif - -// A simdgroup's gate (j 0) and up (j 1) fragments as SwiGLU outputs into y (ld N), rows below live only. -template -inline void am_store_glu(thread const frag (&acc)[TM][2], device bfloat* y, int N, int live, short2 home, - float limit) { - TF_UNROLL - for (short i = 0; i < TM; i++) { - TF_UNROLL - for (short e = 0; e < 8; e++) { - const int r = 16 * i + home.y + (e >> 2) * 8; - if (r < live) y[long(r) * N + home.x + TF_COL(e)] = am_swiglu(acc[i][0][e], acc[i][1][e], limit); - } - } -} - -// The routed experts' gate and up over ORDER's token rows (pair / topk), SwiGLU'd to act [rows, n]: 32 columns a tile. -#define TF_GATHER_GLU(BM) \ - [[kernel]] void tf_affine_gather_glu_##BM( \ - const device bfloat* X [[buffer(0)]], const device uint32_t* WG [[buffer(1)]], \ - const device bfloat* SG [[buffer(2)]], const device bfloat* BG [[buffer(3)]], \ - const device float* XS [[buffer(4)]], constant MmArgs& a [[buffer(5)]], device bfloat* Y [[buffer(6)]], \ - const device int32_t* OFFS [[buffer(7)]], const device int32_t* ORDER [[buffer(8)]], \ - const device uint32_t* WU [[buffer(9)]], const device bfloat* SU [[buffer(10)]], \ - const device bfloat* BU [[buffer(11)]], constant float2& glu [[buffer(12)]], TF_AM_MAP_ARG \ - uint sg [[simdgroup_index_in_threadgroup]], uint lane [[thread_index_in_simdgroup]], \ - uint3 tg [[threadgroup_position_in_grid]]) { \ - constexpr int SM = BM / 2; \ - constexpr int TM = SM / 16; \ - threadgroup bfloat tile[64 * PAD]; \ - threadgroup float sb[NG * 128]; \ - int expert, row, rows; \ - if (!am_tile(OFFS, a.experts, a.rows, int(tg.y), lane, expert, row, rows)) return; \ - const int c0 = int(tg.x) * 32, t = int(sg) * 32 + int(lane), tr = t / 2; \ - const bool up = ((tr >> 4) & 1) != 0; \ - const long wrow = long(TF_AM_EXPERT(expert)) * a.n + c0 + (tr >> 5) * 16 + (tr & 15); \ - const int tm = SM * int(sg / 2), tn = 32 * int(sg % 2), live = clamp(rows - tm, 0, SM); \ - const short2 home = frag_home(ushort(lane)); \ - const AmRows starts = am_rows(X, a.k, XS, a.k / TF_GROUP, row, rows, tm, home, ORDER, int(glu.x)); \ - frag acc[TM][2]; \ - am_k_loop(acc, starts, a.k, live, \ - (const device uchar*)(up ? WU : WG) + wrow * (a.k * TF_BITS / 8) + HALF_BYTES * (t % 2), \ - (up ? SU : SG) + wrow * (a.k / TF_GROUP), (up ? BU : BG) + wrow * (a.k / TF_GROUP), tile, sb, tn, \ - uint(t), home); \ - am_store_glu(acc, Y + long(row + tm) * a.n + c0 + tn / 2, a.n, live, home, glu.y); \ - } -// Tile rows by 16: gate, up, gate, up for columns c0.., c0 + 16.. -TF_GATHER_GLU(32) -TF_GATHER_GLU(64) diff --git a/zig/kernels/metal/core/affine_mm_glu.metal b/zig/kernels/metal/core/affine_mm_glu.metal new file mode 100644 index 00000000000..8214549e7e2 --- /dev/null +++ b/zig/kernels/metal/core/affine_mm_glu.metal @@ -0,0 +1,77 @@ + +#ifdef TF_GLU_PLAIN +// mlx-lm's compiled SwiGLU on bf16 rows (LFM2): silu(g) * u, rounded to bf16 at each step; `limit` unused. +inline bfloat am_swiglu(float g, float u, float limit) { + const float gt = float(bfloat(g)); + const bfloat s = static_cast(1.0f / (1.0f + metal::precise::exp(-gt))); + const bfloat silu = static_cast(gt * float(s)); + return static_cast(float(silu) * float(bfloat(u))); +} +#else +// The glue's SwiGLU in bf16 (glm_act2): MLX's bf16 exp and abs, nn.silu's x*sigmoid(x), gate and up clipped at `limit`. +inline bfloat am_sigmoid(bfloat x) { + const bfloat e = bfloat(__metal_exp(float(bfloat(__metal_fabs(float(x), __METAL_MAYBE_FAST_MATH__))), __METAL_MAYBE_FAST_MATH__)); + const bfloat y = bfloat(1) / (bfloat(1) + e); + return (x < 0) ? y : (bfloat(1) - y); +} + +inline bfloat am_swiglu(float g, float u, float limit) { + const float lim = float(bfloat(limit)); + const bfloat gt = bfloat(metal::min(float(bfloat(g)), lim)); + const bfloat up = bfloat(metal::min(metal::max(float(bfloat(u)), -lim), lim)); +#ifdef TF_GLU_ROUND_SILU + const bfloat sl = bfloat(precise::divide(float(gt), 1.0f + precise::exp(-float(gt)))); +#else + const bfloat sl = gt * am_sigmoid(gt); +#endif + return sl * up; +} +#endif + +// A simdgroup's gate (j 0) and up (j 1) fragments as SwiGLU outputs into y (ld N), rows below live only. +template +inline void am_store_glu(thread const frag (&acc)[TM][2], device bfloat* y, int N, int live, short2 home, + float limit) { + TF_UNROLL + for (short i = 0; i < TM; i++) { + TF_UNROLL + for (short e = 0; e < 8; e++) { + const int r = 16 * i + home.y + (e >> 2) * 8; + if (r < live) y[long(r) * N + home.x + TF_COL(e)] = am_swiglu(acc[i][0][e], acc[i][1][e], limit); + } + } +} + +// The routed experts' gate and up over ORDER's token rows (pair / topk), SwiGLU'd to act [rows, n]: 32 columns a tile. +#define TF_GATHER_GLU(BM) \ + [[kernel]] void tf_affine_gather_glu_##BM( \ + const device bfloat* X [[buffer(0)]], const device uint32_t* WG [[buffer(1)]], \ + const device bfloat* SG [[buffer(2)]], const device bfloat* BG [[buffer(3)]], \ + const device float* XS [[buffer(4)]], constant MmArgs& a [[buffer(5)]], device bfloat* Y [[buffer(6)]], \ + const device int32_t* OFFS [[buffer(7)]], const device int32_t* ORDER [[buffer(8)]], \ + const device uint32_t* WU [[buffer(9)]], const device bfloat* SU [[buffer(10)]], \ + const device bfloat* BU [[buffer(11)]], constant float2& glu [[buffer(12)]], TF_AM_MAP_ARG \ + uint sg [[simdgroup_index_in_threadgroup]], uint lane [[thread_index_in_simdgroup]], \ + uint3 tg [[threadgroup_position_in_grid]]) { \ + constexpr int SM = BM / 2; \ + constexpr int TM = SM / 16; \ + threadgroup bfloat tile[64 * PAD]; \ + threadgroup float sb[NG * 128]; \ + int expert, row, rows; \ + if (!am_tile(OFFS, a.experts, a.rows, int(tg.y), lane, expert, row, rows)) return; \ + const int c0 = int(tg.x) * 32, t = int(sg) * 32 + int(lane), tr = t / 2; \ + const bool up = ((tr >> 4) & 1) != 0; \ + const long wrow = long(TF_AM_EXPERT(expert)) * a.n + c0 + (tr >> 5) * 16 + (tr & 15); \ + const int tm = SM * int(sg / 2), tn = 32 * int(sg % 2), live = clamp(rows - tm, 0, SM); \ + const short2 home = frag_home(ushort(lane)); \ + const AmRows starts = am_rows(X, a.k, XS, a.k / TF_GROUP, row, rows, tm, home, ORDER, int(glu.x)); \ + frag acc[TM][2]; \ + am_k_loop(acc, starts, a.k, live, \ + (const device uchar*)(up ? WU : WG) + wrow * (a.k * TF_BITS / 8) + HALF_BYTES * (t % 2), \ + (up ? SU : SG) + wrow * (a.k / TF_GROUP), (up ? BU : BG) + wrow * (a.k / TF_GROUP), tile, sb, tn, \ + uint(t), home); \ + am_store_glu(acc, Y + long(row + tm) * a.n + c0 + tn / 2, a.n, live, home, glu.y); \ + } +// Tile rows by 16: gate, up, gate, up for columns c0.., c0 + 16.. +TF_GATHER_GLU(32) +TF_GATHER_GLU(64) diff --git a/zig/kernels/metal/glm_index_nax.metal b/zig/kernels/metal/glm_index_nax.metal index 921845be010..e0e5c2c543d 100644 --- a/zig/kernels/metal/glm_index_nax.metal +++ b/zig/kernels/metal/glm_index_nax.metal @@ -10,10 +10,16 @@ struct GlmScoreArgs { uint p0, q_stride, w_stride, s_stride, rows; }; -// A fragment of q at column c from a lane's two row starts (8-byte loads on M5). +// A fragment of q at column c from a lane's two row starts (8-byte loads on M5, 4-byte on pre-M5 GLM). inline frag ix_frag(const device bfloat* r0, const device bfloat* r1, int c, short2 home) { #ifndef TF_SIMD_FRAGS return frag(*(const device bfloat4*)(r0 + c + home.x), *(const device bfloat4*)(r1 + c + home.x)); +#elif defined(TF_GLM_M3_FAST) + const bfloat2 a0 = *(const device bfloat2*)(r0 + c + home.x); + const bfloat2 a1 = *(const device bfloat2*)(r0 + c + home.x + 8); + const bfloat2 b0 = *(const device bfloat2*)(r1 + c + home.x); + const bfloat2 b1 = *(const device bfloat2*)(r1 + c + home.x + 8); + return frag(a0.x, a0.y, a1.x, a1.y, b0.x, b0.y, b1.x, b1.y); #else frag f; TF_UNROLL @@ -30,6 +36,64 @@ inline frag ix_frag(const device bfloat* r0, const device bfloat* r1, in constant GlmScoreArgs& a [[buffer(4)]], uint sg [[simdgroup_index_in_threadgroup]], uint lane [[thread_index_in_simdgroup]], uint3 tg [[threadgroup_position_in_grid]], uint sgs [[simdgroups_per_threadgroup]]) { +#if defined(TF_GLM_M3_FAST) && defined(TF_SIMD_FRAGS) + constexpr int TPAD = 64 + 8; + threadgroup bfloat tileT[DI * TPAD]; + const int b0 = int(tg.x) * 64, r0 = int(tg.y) * 32; + const int rows = min(32, int(a.rows) - r0); + if (rows <= 0 || b0 >= (int(a.p0) + r0 + rows) / 4) return; + const uint t = sg * 32 + lane; + for (uint i = t; i < 64 * (DI / 8); i += 128) { + const uint rr = i / (DI / 8), cc = (i % (DI / 8)) * 8; + const int b = min(b0 + int(rr), int(a.s_stride) - 1); + const uint4 v = *(const device uint4*)(pool + size_t(b) * DI + cc); + const bfloat2 p0 = as_type(v.x), p1 = as_type(v.y); + const bfloat2 p2 = as_type(v.z), p3 = as_type(v.w); + tileT[(cc + 0) * TPAD + rr] = p0.x; tileT[(cc + 1) * TPAD + rr] = p0.y; + tileT[(cc + 2) * TPAD + rr] = p1.x; tileT[(cc + 3) * TPAD + rr] = p1.y; + tileT[(cc + 4) * TPAD + rr] = p2.x; tileT[(cc + 5) * TPAD + rr] = p2.y; + tileT[(cc + 6) * TPAD + rr] = p3.x; tileT[(cc + 7) * TPAD + rr] = p3.y; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + const short2 home = frag_home(ushort(lane)); + const int tm = 16 * int(sg / 2), tn = 32 * int(sg % 2); + const device bfloat* qr[2]; + const device bfloat* wr[2]; + TF_UNROLL + for (short h = 0; h < 2; h++) { + const int r = tm + home.y + 8 * h; + const long at = long(r0 + (r < rows ? r : 0)); + qr[h] = iq + at * a.q_stride; + wr[h] = iw + at * a.w_stride; + } + frag total[2] = {frag(0), frag(0)}; + for (int hd = 0; hd < HI; hd++) { + frag s[2] = {frag(0), frag(0)}; + TF_UNROLL + for (short q = 0; q < DI / 16; q++) { + frag k0, k1; + frag_get(k0, tileT, TPAD, 16 * q, tn, home); + frag_get(k1, tileT, TPAD, 16 * q, tn + 16, home); + const frag qa = ix_frag(qr[0] + hd * DI, qr[1] + hd * DI, 16 * q, home); + mma_16x32(s[0], s[1], qa, k0, k1); + } + const float w0 = float(wr[0][hd]), w1 = float(wr[1][hd]); + TF_UNROLL + for (short j = 0; j < 2; j++) { + TF_UNROLL + for (short e = 0; e < 8; e++) total[j][e] = fma(e < 4 ? w0 : w1, metal::max(s[j][e], 0.0f), total[j][e]); + } + } + TF_UNROLL + for (short j = 0; j < 2; j++) { + TF_UNROLL + for (short e = 0; e < 8; e++) { + const int r = tm + home.y + (e >> 2) * 8; + const int b = b0 + tn + 16 * j + home.x + TF_COL(e); + if (r < rows && b < (int(a.p0) + r0 + r + 1) / 4) scores[size_t(r0 + r) * a.s_stride + b] = total[j][e]; + } + } +#else threadgroup bfloat tile[64 * PAD]; const int tile_rows = 16 * int(sgs); const int b0 = int(tg.x) * 64, r0 = int(tg.y) * tile_rows; @@ -87,6 +151,7 @@ inline frag ix_frag(const device bfloat* r0, const device bfloat* r1, in if (r < rows && b < (int(a.p0) + r0 + r + 1) / 4) scores[size_t(r0 + r) * a.s_stride + b] = total[j][e]; } } +#endif } // A transposed right operand's element e: key (a block, the op's column), dim (on M5 the op loads it as any operand). @@ -98,11 +163,69 @@ inline short ix_key(short e, short2 home) { return home.x + TF_COL(e); } inline short ix_dim(short e, short2 home) { return home.y + (e >> 2) * 8; } #endif -// Decode index scores, grid (128-tile blocks, rows) of 4 simdgroups: 32 heads, bf16 products, relu, weights, head sum. +// Decode index scores, grid (128-tile or 64-tile under TF_GLM_M3_FAST, rows) of 4 simdgroups: 32 heads, head sum. [[kernel]] void glm_index_decode(const device bfloat* iq [[buffer(0)]], const device bfloat* iw [[buffer(1)]], const device bfloat* pool [[buffer(2)]], device float* scores [[buffer(3)]], constant GlmScoreArgs& a [[buffer(4)]], uint sg [[simdgroup_index_in_threadgroup]], uint lane [[thread_index_in_simdgroup]], uint3 tg [[threadgroup_position_in_grid]]) { +#if defined(TF_GLM_M3_FAST) && defined(TF_SIMD_FRAGS) + constexpr int TPAD = 64 + 8; + threadgroup bfloat tileT[64 * TPAD]; + const int row = int(tg.y), blk0 = int(tg.x) * 64; + const int blocks = (int(a.p0) + row + 1) / 4; + if (blk0 >= blocks) return; + const uint t = sg * 32 + lane; + const short2 home = frag_home(ushort(lane)); + const int bs = blk0 + 16 * int(sg); + const device bfloat* q = iq + long(row) * a.q_stride; + frag s[2] = {frag(0), frag(0)}; + for (int kd = 0; kd < DI; kd += 64) { + threadgroup_barrier(mem_flags::mem_threadgroup); + for (uint i = t; i < 64u * 8u; i += 128u) { + const uint rr = i >> 3, cc = (i & 7u) * 8u; + const int bk = min(blk0 + int(rr), blocks - 1); + const uint4 v = *(const device uint4*)(pool + long(bk) * DI + kd + cc); + const bfloat2 p0 = as_type(v.x), p1 = as_type(v.y); + const bfloat2 p2 = as_type(v.z), p3 = as_type(v.w); + tileT[(cc + 0) * TPAD + rr] = p0.x; tileT[(cc + 1) * TPAD + rr] = p0.y; + tileT[(cc + 2) * TPAD + rr] = p1.x; tileT[(cc + 3) * TPAD + rr] = p1.y; + tileT[(cc + 4) * TPAD + rr] = p2.x; tileT[(cc + 5) * TPAD + rr] = p2.y; + tileT[(cc + 6) * TPAD + rr] = p3.x; tileT[(cc + 7) * TPAD + rr] = p3.y; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + if (bs < blocks) { + TF_UNROLL + for (short sub = 0; sub < 4; sub++) { + const int kq = (kd / 16) + sub; + frag k0; + frag_get(k0, tileT, TPAD, 16 * sub, 16 * int(sg), home); + const frag qa0 = ix_frag(q + home.y * DI, q + (home.y + 8) * DI, 16 * kq, home); + const frag qa1 = ix_frag(q + (16 + home.y) * DI, q + (24 + home.y) * DI, 16 * kq, home); + mma_16x16(s[0], qa0, k0); + mma_16x16(s[1], qa1, k0); + } + } + } + if (bs >= blocks) return; + float w[2][2]; + TF_UNROLL + for (short m = 0; m < 2; m++) { + w[m][0] = float(iw[long(row) * a.w_stride + 16 * m + home.y]); + w[m][1] = float(iw[long(row) * a.w_stride + 16 * m + home.y + 8]); + } + TF_UNROLL + for (short c = 0; c < 4; c++) { + float tv = w[0][0] * metal::max(s[0][c], 0.0f); + tv = fma(w[0][1], metal::max(s[0][4 + c], 0.0f), tv); + tv = fma(w[1][0], metal::max(s[1][c], 0.0f), tv); + tv = fma(w[1][1], metal::max(s[1][4 + c], 0.0f), tv); + tv += simd_shuffle_xor(tv, ushort(2)); + tv += simd_shuffle_xor(tv, ushort(4)); + tv += simd_shuffle_xor(tv, ushort(16)); + const int b = bs + home.x + TF_COL(c); + if (home.y == 0 && b < blocks) scores[long(row) * a.s_stride + b] = tv; + } +#else const int row = int(tg.y), b0 = int(tg.x) * 128 + 32 * int(sg); const int blocks = (int(a.p0) + row + 1) / 4; if (b0 >= blocks) return; @@ -156,4 +279,5 @@ inline short ix_dim(short e, short2 home) { return home.y + (e >> 2) * 8; } if (home.y == 0 && b < blocks) scores[long(row) * a.s_stride + b] = t; } } +#endif } diff --git a/zig/kernels/metal/glm_kda_prompt.metal b/zig/kernels/metal/glm_kda_prompt.metal index 79ced70bf9d..910fe908391 100644 --- a/zig/kernels/metal/glm_kda_prompt.metal +++ b/zig/kernels/metal/glm_kda_prompt.metal @@ -19,6 +19,50 @@ template const uint h = tg.y * (uint)HB + sg; const uint PS = (uint)P_shape[1]; const size_t at = (size_t)rl * W + h * (uint)D; +#ifdef TF_GLM_M3_FAST + const uint d = 4u * lane; + float4 sq = float4(0.0f), sk = float4(0.0f); + for (uint part = 0; part < 3u; ++part) { + const uint c = part * W + h * (uint)D + d; + float4 acc = float4(0.0f); + for (int j = 0; j < TAPS; ++j) { + const int e = r + j; + const bfloat4 xv = e < TAPS - 1 + ? *(const device bfloat4*)(CS + (size_t)e * C3 + c) + : *(const device bfloat4*)(P + (size_t)(e - (TAPS - 1)) * PS + c); + const float4 cw = *(const device float4*)(CW + (size_t)j * C3 + c); + const float4 term = float4(xv) * cw; + acc = j == 0 ? term : (acc + term); + } + const bfloat4 xb = bfloat4(acc); + bfloat4 sl; + sl.x = xb.x * mlx_sigmoid_precise(xb.x); + sl.y = xb.y * mlx_sigmoid_precise(xb.y); + sl.z = xb.z * mlx_sigmoid_precise(xb.z); + sl.w = xb.w * mlx_sigmoid_precise(xb.w); + if (part == 0u) sq = float4(sl); + else if (part == 1u) sk = float4(sl); + else *(device bfloat4*)(VO + at + d) = sl; + } + const float a_h = A[h], lb = LB[0]; + const float4 av = float4(*(const device bfloat4*)(FB + at + d)) + *(const device float4*)(DTB + h * (uint)D + d); + float4 go; + go.x = metal::precise::exp(lb * mlx_sigmoid_precise(a_h * av.x)); + go.y = metal::precise::exp(lb * mlx_sigmoid_precise(a_h * av.y)); + go.z = metal::precise::exp(lb * mlx_sigmoid_precise(a_h * av.z)); + go.w = metal::precise::exp(lb * mlx_sigmoid_precise(a_h * av.w)); + *(device float4*)(GO + at + d) = go; + if (lane == 0u) BETA[(size_t)rl * H + h] = float(mlx_sigmoid_precise(P[(size_t)r * PS + BO + h])); + float pq = 0.0f, pk = 0.0f; + pq = sq_acc(pq, sq.x); pq = sq_acc(pq, sq.y); pq = sq_acc(pq, sq.z); pq = sq_acc(pq, sq.w); + pk = sq_acc(pk, sk.x); pk = sq_acc(pk, sk.y); pk = sq_acc(pk, sk.z); pk = sq_acc(pk, sk.w); + pq = simd_sum(pq); + pk = simd_sum(pk); + const float rq = metal::precise::rsqrt(pq + 1.0e-6f), rk = metal::precise::rsqrt(pk + 1.0e-6f); + const float qscale = metal::precise::rsqrt(float(D)); + *(device bfloat4*)(QO + at + d) = bfloat4((sq * rq) * qscale); + *(device bfloat4*)(KO + at + d) = bfloat4(sk * rk); +#else float sq[NDK], sk[NDK]; for (uint part = 0; part < 3u; ++part) { for (int i = 0; i < NDK; ++i) { @@ -60,6 +104,7 @@ template QO[at + d] = bfloat((sq[i] * rq) * qscale); KO[at + d] = bfloat(sk[i] * rk); } +#endif } // Recurrence over R rows: 8 lanes a value column (16 key dims each, 8-way xor-shuffle sums), rows staged B at a time. @@ -81,6 +126,73 @@ template const int c = int(sg) * 4 + int(lane >> 3); // this lane's value column in the threadgroup const uint dv = tg.x * (uint)VC + (uint)c; const int k0 = NK * int(lane & 7u); +#ifdef TF_GLM_M3_FAST + const device float4* si4 = (const device float4*)(ST + ((size_t)h * D + dv) * D + k0); + float4 st4[4]; + for (int i = 0; i < 4; ++i) st4[i] = si4[i]; + for (int r0 = 0; r0 < R; r0 += B) { + const int n = min(B, R - r0); + threadgroup_barrier(mem_flags::mem_threadgroup); + for (int idx = int(tid); idx < n * (D / 8); idx += NT) { + const int b = idx / (D / 8), d8 = (idx % (D / 8)) * 8; + const size_t at = (size_t)(r0 + b) * W + h * (uint)D + (uint)d8; + *(threadgroup uint4*)(sqs + b * D + d8) = *(const device uint4*)(QO + at); + *(threadgroup uint4*)(sks + b * D + d8) = *(const device uint4*)(KO + at); + *(threadgroup float4*)(sgs + b * D + d8) = *(const device float4*)(GO + at); + *(threadgroup float4*)(sgs + b * D + d8 + 4) = *(const device float4*)(GO + at + 4); + } + for (int idx = int(tid); idx < n * (VC / 8); idx += NT) { + const int b = idx / (VC / 8), cc = (idx % (VC / 8)) * 8; + *(threadgroup uint4*)(svs + b * VC + cc) = *(const device uint4*)(VO + (size_t)(r0 + b) * W + h * (uint)D + tg.x * (uint)VC + (uint)cc); + } + if (int(tid) < n) sbs[tid] = BETA[(size_t)(r0 + int(tid)) * H + h]; + threadgroup_barrier(mem_flags::mem_threadgroup); + for (int b = 0; b < n; ++b) { + const threadgroup uint4* qv = (const threadgroup uint4*)(sqs + b * D + k0); + const threadgroup uint4* kv4 = (const threadgroup uint4*)(sks + b * D + k0); + const threadgroup float4* gv = (const threadgroup float4*)(sgs + b * D + k0); + const uint4 k_lo = kv4[0], k_hi = kv4[1]; + const uint4 q_lo = qv[0], q_hi = qv[1]; + float kv = 0.0f; + float4 kf[4]; + _Pragma("clang loop unroll(full)") + for (int j = 0; j < 4; ++j) { + const uint w0 = j < 2 ? k_lo[2 * j] : k_hi[2 * (j - 2)]; + const uint w1 = j < 2 ? k_lo[2 * j + 1] : k_hi[2 * (j - 2) + 1]; + const bfloat2 b0 = as_type(w0), b1 = as_type(w1); + kf[j] = float4(float(b0.x), float(b0.y), float(b1.x), float(b1.y)); + st4[j] = st4[j] * gv[j]; + kv += st4[j].x * kf[j].x; + kv += st4[j].y * kf[j].y; + kv += st4[j].z * kf[j].z; + kv += st4[j].w * kf[j].w; + } + kv += simd_shuffle_xor(kv, ushort(1)); + kv += simd_shuffle_xor(kv, ushort(2)); + kv += simd_shuffle_xor(kv, ushort(4)); + const float delta = (float(svs[b * VC + c]) - kv) * sbs[b]; + float o = 0.0f; + _Pragma("clang loop unroll(full)") + for (int j = 0; j < 4; ++j) { + const uint w0 = j < 2 ? q_lo[2 * j] : q_hi[2 * (j - 2)]; + const uint w1 = j < 2 ? q_lo[2 * j + 1] : q_hi[2 * (j - 2) + 1]; + const bfloat2 b0 = as_type(w0), b1 = as_type(w1); + const float4 qf = float4(float(b0.x), float(b0.y), float(b1.x), float(b1.y)); + st4[j] = st4[j] + kf[j] * delta; + o += st4[j].x * qf.x; + o += st4[j].y * qf.y; + o += st4[j].z * qf.z; + o += st4[j].w * qf.w; + } + o += simd_shuffle_xor(o, ushort(1)); + o += simd_shuffle_xor(o, ushort(2)); + o += simd_shuffle_xor(o, ushort(4)); + if ((lane & 7u) == 0u) SY[(size_t)(r0 + b) * W + h * (uint)D + dv] = bfloat(o); + } + } + device float4* so4 = (device float4*)(ST_OUT + ((size_t)h * D + dv) * D + k0); + for (int i = 0; i < 4; ++i) so4[i] = st4[i]; +#else device const float* si = ST + ((size_t)h * D + dv) * D + k0; float st[NK]; _Pragma("clang loop unroll(full)") @@ -130,6 +242,7 @@ template device float* so = ST_OUT + ((size_t)h * D + dv) * D + k0; _Pragma("clang loop unroll(full)") for (int i = 0; i < NK; ++i) so[i] = st[i]; +#endif } template @@ -137,10 +250,15 @@ template const device float* ONW [[buffer(2)]], const constant float* EPS [[buffer(3)]], device bfloat16_t* Y [[buffer(4)]], const device bfloat16_t* P [[buffer(5)]], const constant int* P_shape [[buffer(6)]], const device bfloat16_t* CS [[buffer(7)]], - device bfloat16_t* CS_OUT [[buffer(8)]], uint lane [[thread_index_in_simdgroup]], + device bfloat16_t* CS_OUT [[buffer(8)]], uint sg [[simdgroup_index_in_threadgroup]], + uint lane [[thread_index_in_simdgroup]], uint3 threadgroup_position_in_grid [[threadgroup_position_in_grid]]) { const int r = int(threadgroup_position_in_grid.x); +#ifdef TF_GLM_M3_FAST + const uint h = threadgroup_position_in_grid.y * 4u + sg; +#else const uint h = threadgroup_position_in_grid.y; +#endif constexpr int RBLK = D / 128; constexpr int REXTRA = D - RBLK * 128; constexpr uint W = (uint)(H * D); @@ -149,6 +267,25 @@ template const uint PS = (uint)P_shape[1]; const float eps = EPS[0]; const size_t at = (size_t)r * W + h * (uint)D; +#ifdef TF_GLM_M3_FAST + const uint base = 4u * lane; + const float4 sy4 = float4(*(const device bfloat4*)(SY + at + base)); + float po = 0.0f; + po = sq_acc(po, sy4.x); + po = sq_acc(po, sy4.y); + po = sq_acc(po, sy4.z); + po = sq_acc(po, sy4.w); + po = simd_sum(po); + const float rn = metal::precise::rsqrt(po / (float)D + eps); + const float4 onw = *(const device float4*)(ONW + base); + const float4 g4 = float4(*(const device bfloat4*)(GATE + at + base)); + float4 y4 = (sy4 * rn) * onw; + y4.x *= mlx_sigmoid_precise(g4.x); + y4.y *= mlx_sigmoid_precise(g4.y); + y4.z *= mlx_sigmoid_precise(g4.z); + y4.w *= mlx_sigmoid_precise(g4.w); + *(device bfloat4*)(Y + at + base) = bfloat4(y4); +#else float po = 0.0f; for (int blk = 0; blk < RBLK; ++blk) { const uint base = (uint)(blk * 128) + 4u * lane; @@ -164,6 +301,7 @@ template x = x * mlx_sigmoid_precise(float(GATE[at + d])); Y[at + d] = bfloat(x); } +#endif if (r != 0) return; for (uint idx = lane; idx < 3u * (uint)D * (uint)(TAPS - 1); idx += 32u) { // the next chunk's window: the last rows const uint m = idx / (3u * (uint)D); @@ -177,9 +315,17 @@ template } template [[host_name("glm_kda_prep")]] [[kernel]] decltype(glm_kda_prep<64, 128, 4, 4>) glm_kda_prep<64, 128, 4, 4>; +#ifdef TF_GLM_M3_FAST +template [[host_name("glm_kda_scan")]] [[kernel]] decltype(glm_kda_scan<64, 128, 4, 24>) glm_kda_scan<64, 128, 4, 24>; +#else template [[host_name("glm_kda_scan")]] [[kernel]] decltype(glm_kda_scan<64, 128, 16, 16>) glm_kda_scan<64, 128, 16, 16>; +#endif template [[host_name("glm_kda_post")]] [[kernel]] decltype(glm_kda_post<64, 128, 4, 32, 4, 4>) glm_kda_post<64, 128, 4, 32, 4, 4>; // TP2: one Mac's 32 heads template [[host_name("glm_kda_prep_tp")]] [[kernel]] decltype(glm_kda_prep<32, 128, 4, 4>) glm_kda_prep<32, 128, 4, 4>; +#ifdef TF_GLM_M3_FAST +template [[host_name("glm_kda_scan_tp")]] [[kernel]] decltype(glm_kda_scan<32, 128, 4, 24>) glm_kda_scan<32, 128, 4, 24>; +#else template [[host_name("glm_kda_scan_tp")]] [[kernel]] decltype(glm_kda_scan<32, 128, 16, 16>) glm_kda_scan<32, 128, 16, 16>; +#endif template [[host_name("glm_kda_post_tp")]] [[kernel]] decltype(glm_kda_post<32, 128, 4, 32, 4, 4>) glm_kda_post<32, 128, 4, 32, 4, 4>; diff --git a/zig/kernels/metal/nax.h b/zig/kernels/metal/nax.h index 210c6aaa4c0..341859f2cb7 100644 --- a/zig/kernels/metal/nax.h +++ b/zig/kernels/metal/nax.h @@ -1,6 +1,9 @@ // M5 tensor-unit fragments shared by every NAX kernel (ops and prefill): layout, loads, stores and the 16x32x16 op. #include #include +#if defined(TF_SIMD_FRAGS) && defined(TF_GLM_M3_FAST) +#include +#endif namespace tfp { using namespace metal; @@ -107,10 +110,15 @@ inline short2 frag_home(ushort l) { template inline void frag_get(thread frag& f, P p, int ld, int r, int c, short2 home) { const P q = p + (r + home.y) * ld + (c + home.x); +#ifdef TF_GLM_M3_FAST + f[0] = T(q[0]); f[1] = T(q[1]); f[2] = T(q[8]); f[3] = T(q[9]); + f[4] = T(q[8 * ld]); f[5] = T(q[8 * ld + 1]); f[6] = T(q[8 * ld + 8]); f[7] = T(q[8 * ld + 9]); +#else TF_UNROLL for (short e = 0; e < 8; e++) { f[e] = T(q[(e >> 2) * 8 * ld + TF_COL(e)]); } +#endif } template @@ -164,6 +172,55 @@ inline void frag_put_in(thread const frag& f, device O* p, int ld, int r, template inline void mma_16x32(thread frag& lo, thread frag& hi, thread const frag& a, thread const frag& b0, thread const frag& b1) { +#ifdef TF_GLM_M3_FAST + simdgroup_matrix a00, a01, a10, a11; + simdgroup_matrix b00, b01, b10, b11, c00, c01, c10, c11; + simdgroup_matrix d00, d01, d10, d11, e00, e01, e10, e11; + a00.thread_elements()[0] = a[0]; a00.thread_elements()[1] = a[1]; + a01.thread_elements()[0] = a[2]; a01.thread_elements()[1] = a[3]; + a10.thread_elements()[0] = a[4]; a10.thread_elements()[1] = a[5]; + a11.thread_elements()[0] = a[6]; a11.thread_elements()[1] = a[7]; + b00.thread_elements()[0] = b0[0]; b00.thread_elements()[1] = b0[1]; + b01.thread_elements()[0] = b0[2]; b01.thread_elements()[1] = b0[3]; + b10.thread_elements()[0] = b0[4]; b10.thread_elements()[1] = b0[5]; + b11.thread_elements()[0] = b0[6]; b11.thread_elements()[1] = b0[7]; + c00.thread_elements()[0] = b1[0]; c00.thread_elements()[1] = b1[1]; + c01.thread_elements()[0] = b1[2]; c01.thread_elements()[1] = b1[3]; + c10.thread_elements()[0] = b1[4]; c10.thread_elements()[1] = b1[5]; + c11.thread_elements()[0] = b1[6]; c11.thread_elements()[1] = b1[7]; + d00.thread_elements()[0] = lo[0]; d00.thread_elements()[1] = lo[1]; + d01.thread_elements()[0] = lo[2]; d01.thread_elements()[1] = lo[3]; + d10.thread_elements()[0] = lo[4]; d10.thread_elements()[1] = lo[5]; + d11.thread_elements()[0] = lo[6]; d11.thread_elements()[1] = lo[7]; + e00.thread_elements()[0] = hi[0]; e00.thread_elements()[1] = hi[1]; + e01.thread_elements()[0] = hi[2]; e01.thread_elements()[1] = hi[3]; + e10.thread_elements()[0] = hi[4]; e10.thread_elements()[1] = hi[5]; + e11.thread_elements()[0] = hi[6]; e11.thread_elements()[1] = hi[7]; + simdgroup_multiply_accumulate(d00, a00, b00, d00); + simdgroup_multiply_accumulate(d01, a00, b01, d01); + simdgroup_multiply_accumulate(d10, a10, b00, d10); + simdgroup_multiply_accumulate(d11, a10, b01, d11); + simdgroup_multiply_accumulate(e00, a00, c00, e00); + simdgroup_multiply_accumulate(e01, a00, c01, e01); + simdgroup_multiply_accumulate(e10, a10, c00, e10); + simdgroup_multiply_accumulate(e11, a10, c01, e11); + simdgroup_multiply_accumulate(d00, a01, b10, d00); + simdgroup_multiply_accumulate(d01, a01, b11, d01); + simdgroup_multiply_accumulate(d10, a11, b10, d10); + simdgroup_multiply_accumulate(d11, a11, b11, d11); + simdgroup_multiply_accumulate(e00, a01, c10, e00); + simdgroup_multiply_accumulate(e01, a01, c11, e01); + simdgroup_multiply_accumulate(e10, a11, c10, e10); + simdgroup_multiply_accumulate(e11, a11, c11, e11); + lo[0] = d00.thread_elements()[0]; lo[1] = d00.thread_elements()[1]; + lo[2] = d01.thread_elements()[0]; lo[3] = d01.thread_elements()[1]; + lo[4] = d10.thread_elements()[0]; lo[5] = d10.thread_elements()[1]; + lo[6] = d11.thread_elements()[0]; lo[7] = d11.thread_elements()[1]; + hi[0] = e00.thread_elements()[0]; hi[1] = e00.thread_elements()[1]; + hi[2] = e01.thread_elements()[0]; hi[3] = e01.thread_elements()[1]; + hi[4] = e10.thread_elements()[0]; hi[5] = e10.thread_elements()[1]; + hi[6] = e11.thread_elements()[0]; hi[7] = e11.thread_elements()[1]; +#else using namespace mpp::tensor_ops; constexpr auto shape = matmul2d_descriptor(16, 32, 16, TA, TB, true, matmul2d_descriptor::mode::multiply_accumulate); matmul2d op; @@ -187,8 +244,43 @@ inline void mma_16x32(thread frag& lo, thread frag& hi, thread const frag< lo[e] = acc[j]; hi[e] = acc[j + 4]; } +#endif +} + +#ifdef TF_GLM_M3_FAST +// Half-width 16x16 multiply-accumulate used by GLM's decode index kernel when TF_GLM_M3_FAST is active. +template +inline void mma_16x16(thread frag& d, thread const frag& a, thread const frag& b) { + simdgroup_matrix a00, a01, a10, a11; + simdgroup_matrix b00, b01, b10, b11; + simdgroup_matrix d00, d01, d10, d11; + a00.thread_elements()[0] = a[0]; a00.thread_elements()[1] = a[1]; + a01.thread_elements()[0] = a[2]; a01.thread_elements()[1] = a[3]; + a10.thread_elements()[0] = a[4]; a10.thread_elements()[1] = a[5]; + a11.thread_elements()[0] = a[6]; a11.thread_elements()[1] = a[7]; + b00.thread_elements()[0] = b[0]; b00.thread_elements()[1] = b[1]; + b01.thread_elements()[0] = b[2]; b01.thread_elements()[1] = b[3]; + b10.thread_elements()[0] = b[4]; b10.thread_elements()[1] = b[5]; + b11.thread_elements()[0] = b[6]; b11.thread_elements()[1] = b[7]; + d00.thread_elements()[0] = d[0]; d00.thread_elements()[1] = d[1]; + d01.thread_elements()[0] = d[2]; d01.thread_elements()[1] = d[3]; + d10.thread_elements()[0] = d[4]; d10.thread_elements()[1] = d[5]; + d11.thread_elements()[0] = d[6]; d11.thread_elements()[1] = d[7]; + simdgroup_multiply_accumulate(d00, a00, b00, d00); + simdgroup_multiply_accumulate(d01, a00, b01, d01); + simdgroup_multiply_accumulate(d10, a10, b00, d10); + simdgroup_multiply_accumulate(d11, a10, b01, d11); + simdgroup_multiply_accumulate(d00, a01, b10, d00); + simdgroup_multiply_accumulate(d01, a01, b11, d01); + simdgroup_multiply_accumulate(d10, a11, b10, d10); + simdgroup_multiply_accumulate(d11, a11, b11, d11); + d[0] = d00.thread_elements()[0]; d[1] = d00.thread_elements()[1]; + d[2] = d01.thread_elements()[0]; d[3] = d01.thread_elements()[1]; + d[4] = d10.thread_elements()[0]; d[5] = d10.thread_elements()[1]; + d[6] = d11.thread_elements()[0]; d[7] = d11.thread_elements()[1]; } #endif +#endif // frag_get from a block whose rows home.y and home.y + 8 start at r0 and r1; an unflagged row reads as zero. template diff --git a/zig/kernels/metal/sources.zig b/zig/kernels/metal/sources.zig index db94659e847..b07432e1270 100644 --- a/zig/kernels/metal/sources.zig +++ b/zig/kernels/metal/sources.zig @@ -202,7 +202,7 @@ pub const glm_select = @embedFile("glm_select.metal"); pub const glm_absorb_nax = @embedFile("glm_absorb_nax.metal"); /// A MoE layer's route in two launches (core/moe_route.zig): router logits, then the top-k and the expert groups. pub const core_moe_route = @embedFile("core/moe_route.metal"); -pub const core_affine_mm = @embedFile("core/affine_mm.metal"); +pub const core_affine_mm = @embedFile("core/affine_mm.metal") ++ @embedFile("core/affine_mm_glu.metal"); /// A hyper-connection block boundary in two launches (core/hc.zig). pub const core_hc_boundary = @embedFile("core/hc_boundary.metal"); /// MLX's precise row softmax and its embedding and RMS kernels, as the replicas in ops/ write them. diff --git a/zig/src/core/affine_mm.zig b/zig/src/core/affine_mm.zig index 3630543d02b..df0ec0108db 100644 --- a/zig/src/core/affine_mm.zig +++ b/zig/src/core/affine_mm.zig @@ -14,6 +14,7 @@ pub const Format = struct { group: u16 = 64, out_f32: bool = false, glu: Glu = .clipped, + glm_m3_fast: bool = false, /// Scatter and GLU gathers read this batch's active-to-global expert map. mapped_experts: bool = false, }; @@ -29,10 +30,11 @@ pub fn source(device: mtl.Device, a: std.mem.Allocator, f: Format) ![]u8 { .clipped_silu => "#define TF_GLU_ROUND_SILU 1\n", .clipped => "", }; + const m3 = if (f.glm_m3_fast and !device.tensorUnits()) "#define TF_GLM_M3_FAST 1\n" else ""; const map = if (f.mapped_experts) "#define TF_AM_MAPPED_EXPERTS 1\n" else ""; const out = if (f.out_f32) "float" else "bfloat"; - const head = "#define TF_BITS {d}\n#define TF_GROUP {d}\n#define TF_OUT_T {s}\n{s}{s}{s}"; - return std.fmt.allocPrint(a, head, .{ f.bits, f.group, out, glu, map, body }); + const head = "#define TF_BITS {d}\n#define TF_GROUP {d}\n#define TF_OUT_T {s}\n{s}{s}{s}{s}"; + return std.fmt.allocPrint(a, head, .{ f.bits, f.group, out, glu, map, m3, body }); } /// Entry points: row sums, dense matmul, tiled and scattering gathers, ordered expert gate/up into SwiGLU. @@ -66,12 +68,22 @@ pub fn rowSumsAt(e: mtl.ComputeEncoder, p: Pipes, group: u32, x: anytype, sums: /// y = x W^T using group `sums`; x is [rows, q.k], y is [rows, n], n = q.n rounded up to 64 (padded weights). pub fn dense(e: mtl.ComputeEncoder, p: Pipes, x: anytype, sums: anytype, q: anytype, y: anytype, rows: u32) void { + denseBm(e, p, x, sums, q, y, rows, 64); +} + +/// `dense` with an explicit row-tile height `bm` (32 when compiled with TF_GLM_M3_FAST, 64 otherwise). +pub fn denseBm(e: mtl.ComputeEncoder, p: Pipes, x: anytype, sums: anytype, q: anytype, y: anytype, rows: u32, bm: u32) void { const n = std.mem.alignForward(u32, q.n, 64); - denseBatch(e, p, x, sums, q, y, rows, 1, .{ .x_row = @intCast(q.k), .y_row = @intCast(n) }); + denseBatchBm(e, p, x, sums, q, y, rows, 1, .{ .x_row = @intCast(q.k), .y_row = @intCast(n) }, bm); } /// `batch` dense products over per-batch weight rows with strides `s`; q.n is a multiple of 64 (e.g. heads). pub fn denseBatch(e: mtl.ComputeEncoder, p: Pipes, x: anytype, sums: anytype, q: anytype, y: anytype, rows: u32, batch: u32, s: Strides) void { + denseBatchBm(e, p, x, sums, q, y, rows, batch, s, 64); +} + +/// `denseBatch` with an explicit row-tile height `bm` (32 when compiled with TF_GLM_M3_FAST, 64 otherwise). +pub fn denseBatchBm(e: mtl.ComputeEncoder, p: Pipes, x: anytype, sums: anytype, q: anytype, y: anytype, rows: u32, batch: u32, s: Strides, bm: u32) void { const n = std.mem.alignForward(u32, q.n, 64); e.setPipeline(p[1]); bind(e, 0, x); @@ -82,7 +94,7 @@ pub fn denseBatch(e: mtl.ComputeEncoder, p: Pipes, x: anytype, sums: anytype, q: e.setValue(Args{ .rows = @intCast(rows), .n = @intCast(n), .k = @intCast(q.k), .experts = 0 }, 5); bind(e, 6, y); e.setValue(s, 7); - e.dispatchGroups(mtl.Size.of(n / 64, (rows + 63) / 64, batch), mtl.Size.of(32, 2, 2)); + e.dispatchGroups(mtl.Size.of(n / 64, (rows + bm - 1) / bm, batch), mtl.Size.of(32, 2, 2)); } /// y [rows, q.n]: x times its row expert's W^T, rows expert-sorted (`offsets`: experts' first rows); q [experts, n, k]. diff --git a/zig/src/families/glm/checks.zig b/zig/src/families/glm/checks.zig index c2a5799a2c0..74f19290fbc 100644 --- a/zig/src/families/glm/checks.zig +++ b/zig/src/families/glm/checks.zig @@ -179,7 +179,7 @@ pub fn checkMatmul(e: *Engine, prompt: []const u32) !void { fwd.boundary(&x, b.enc, rows, false, L.hc.?[0], L.in_norm); fwd.qmv(&x, b.enc, e.k.qmv_kda_in, e.sc.normed, a.in_proj, out, rows); affine_mm.rowSums(b.enc, e.k.mm_bf16, 64, e.sc.normed, pr.sums, rows, a.in_proj.k); - affine_mm.dense(b.enc, e.k.mm_bf16, e.sc.normed, pr.sums, a.in_proj, pr.proj, rows); + affine_mm.denseBm(b.enc, e.k.mm_bf16, e.sc.normed, pr.sums, a.in_proj, pr.proj, rows, if (e.k.m3_fast) 32 else 64); try e.finish(b.cb, b.enc); const want: [*]const u16 = @ptrCast(@alignCast(out.addr())); const got: [*]const u16 = @ptrCast(@alignCast(pr.proj.addr())); diff --git a/zig/src/families/glm/forward.zig b/zig/src/families/glm/forward.zig index 105430e1dbf..ff367f519e6 100644 --- a/zig/src/families/glm/forward.zig +++ b/zig/src/families/glm/forward.zig @@ -441,7 +441,7 @@ pub fn selectKeys(x: *const Ctx, e: mtl.ComputeEncoder, mi: usize, iq: Ref, q_st e.setPipeline(k.index_decode); // a row's heads as the tensor op's rows (glm_index_nax.metal) bind(e, 0, .{ iq, iw, x.s.mla[mi].pool, scores }); e.setValue(ScoreArgs{ .p0 = p0, .q_stride = q_stride, .w_stride = c.i_heads, .s_stride = s_stride, .rows = n }, 4); - e.dispatchGroups(size((most + 127) / 128, n, 1), size(128, 1, 1)); + e.dispatchGroups(size(std.math.divCeil(u32, most, if (k.m3_fast) 64 else 128) catch unreachable, n, 1), size(128, 1, 1)); const sel = SelectArgs{ .p0 = p0, .top = c.i_topk / c.kpool, .width = c.keyWidth(), .s_stride = s_stride, .i_stride = c.keyWidth() }; if (most > select_cap and most <= select_marks) { // between them glm_index_select's one group a row is quicker e.setPipeline(k.index_select); diff --git a/zig/src/families/glm/kernels.zig b/zig/src/families/glm/kernels.zig index 5497de4d8f0..ee7e9ab2112 100644 --- a/zig/src/families/glm/kernels.zig +++ b/zig/src/families/glm/kernels.zig @@ -120,6 +120,7 @@ pub const Kernels = struct { mm_groups: mm_groups.Pipes, // the routed gathers walked in column groups (mm_groups.zig): mm_bf16's bits mm_f32: affine_mm.Pipes, // and with fp32 out: expert parallel by rows' down partials wide: ?wide.Pipes = null, // the products at other widths (wide.zig), for a checkpoint that has one + m3_fast: bool, // pre-M5 Metal dispatch geometry (32x64 affine_mm, 4-sg KDA scan, 32x64/64 index NAX) pub fn deinit(k: *Kernels) void { const info = @typeInfo(Kernels).@"struct"; @@ -279,7 +280,9 @@ pub fn visitSources(gpa: std.mem.Allocator, device: mtl.Device, visitor: anytype fn assemble(gpa: std.mem.Allocator, device: mtl.Device, k: *Kernels, visitor: anytype) !void { k.wide = null; - var jobs: [generated.len + 27]Job = undefined; + const m3_fast = !device.tensorUnits(); + k.m3_fast = m3_fast; + var jobs: [generated.len + 28]Job = undefined; inline for (generated, 0..) |g, i| { const src = comptime kernelOf(g.key); const FT = @FieldType(Kernels, g.field); @@ -317,12 +320,14 @@ fn assemble(gpa: std.mem.Allocator, device: mtl.Device, k: *Kernels, visitor: an jobs[generated.len + 6] = .{ .device = device, .source = igate_src, .names = &.{ moe_route.names[0], "glm_route_logits_one" }, .out = &igate_out }; const m16_src = try mm_groups.source(device, gpa); // affine_mm.names, then the column-group gathers defer gpa.free(m16_src); - const m32_src = try affine_mm.source(device, gpa, .{ .out_f32 = true }); + const m32_src = try affine_mm.source(device, gpa, .{ .out_f32 = true, .glm_m3_fast = m3_fast }); defer gpa.free(m32_src); var m16_out: [m16_names.len]mtl.Pipeline = undefined; - jobs[generated.len + 7] = .{ .device = device, .source = m16_src, .names = &m16_names, .out = &m16_out }; + const grouped_from: usize = if (m3_fast) affine_mm.names.len else 0; + jobs[generated.len + 7] = .{ .device = device, .source = m16_src, .names = m16_names[grouped_from..], .out = m16_out[grouped_from..] }; jobs[generated.len + 8] = .{ .device = device, .source = m32_src, .names = &affine_mm.names, .out = &k.mm_f32 }; - const kda_src = try std.mem.concat(gpa, u8, &.{ comptime kernelOf("kda_rows").source, sources.glm_kda_prompt, sources.glm_kda_window, sources.glm_kda_parts }); + const m3_def = if (m3_fast) "#define TF_GLM_M3_FAST 1\n" else ""; + const kda_src = try std.mem.concat(gpa, u8, &.{ comptime kernelOf("kda_rows").source, m3_def, sources.glm_kda_prompt, sources.glm_kda_window, sources.glm_kda_parts }); defer gpa.free(kda_src); var kda_out: [10]mtl.Pipeline = undefined; jobs[generated.len + 9] = .{ .device = device, .source = kda_src, .names = &.{ "glm_kda_prep", "glm_kda_scan", "glm_kda_post", "glm_kda_prep_tp", "glm_kda_scan_tp", "glm_kda_post_tp", "glm_kda_window", "glm_kda_window_tp", "glm_kda_parts", "glm_kda_norm" }, .out = &kda_out }; @@ -347,7 +352,9 @@ fn assemble(gpa: std.mem.Allocator, device: mtl.Device, k: *Kernels, visitor: an const absorb_tp_src = try frags.source(device, gpa, absorb_tp_raw); defer gpa.free(absorb_tp_src); jobs[generated.len + 14] = .{ .device = device, .source = absorb_tp_src, .names = &.{"glm_absorb_nax"}, .out = @as(*[1]mtl.Pipeline, &k.absorb_nax_tp) }; - const index_src = try frags.source(device, gpa, sources.glm_index_nax); + const index_raw = try std.mem.concat(gpa, u8, &.{ m3_def, sources.glm_index_nax }); + defer gpa.free(index_raw); + const index_src = try frags.source(device, gpa, index_raw); defer gpa.free(index_src); var index_out: [2]mtl.Pipeline = undefined; jobs[generated.len + 15] = .{ .device = device, .source = index_src, .names = &.{ "glm_index_scores_nax", "glm_index_decode" }, .out = &index_out }; @@ -387,12 +394,17 @@ fn assemble(gpa: std.mem.Allocator, device: mtl.Device, k: *Kernels, visitor: an 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 m3_src = if (m3_fast) try affine_mm.source(device, gpa, .{ .glm_m3_fast = 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 }; + const active_jobs = jobs[0 .. jobs.len - @intFromBool(!m3_fast)]; if (comptime @TypeOf(visitor) != void) { - for (jobs) |j| try visitor.raw("glm", j.names[0], j.source); + for (active_jobs) |j| try visitor.raw("glm", j.names[0], j.source); return; } var sources_seen = std.hash.Wyhash.init(0x6b); - for (jobs) |j| sources_seen.update(j.source); + for (active_jobs) |j| sources_seen.update(j.source); k.source_hash = sources_seen.final(); var next = std.atomic.Value(usize).init(0); const Worker = struct { @@ -405,17 +417,17 @@ fn assemble(gpa: std.mem.Allocator, device: mtl.Device, k: *Kernels, visitor: an } }; var threads: [8]?std.Thread = @splat(null); - for (&threads) |*t| t.* = std.Thread.spawn(.{}, Worker.run, .{ &jobs, &next }) catch null; - Worker.run(&jobs, &next); + for (&threads) |*t| t.* = std.Thread.spawn(.{}, Worker.run, .{ active_jobs, &next }) catch null; + Worker.run(active_jobs, &next); for (threads) |t| if (t) |th| th.join(); - for (jobs) |j| if (j.failed) return error.KernelCompile; + for (active_jobs) |j| if (j.failed) return error.KernelCompile; inline for (glue, 0..) |g, i| @field(k, g.field) = glue_out[i]; k.sample = sample_out[0]; // the shared sampler's own library: glm_glue's table never named it k.latent_scores = attn_out[0]; k.latent_values = attn_out[1]; k.latent_scores_rows = attn_out[2]; k.latent_values_rows = attn_out[3]; - k.mm_bf16 = m16_out[0..affine_mm.names.len].*; + k.mm_bf16 = if (m3_fast) m3_out else m16_out[0..affine_mm.names.len].*; k.mm_groups = m16_out[affine_mm.names.len..].*; k.route_logits = route_out[0]; k.route_select = route_out[1]; diff --git a/zig/src/families/glm/prompt.zig b/zig/src/families/glm/prompt.zig index c5444c56219..3cbbe242ffc 100644 --- a/zig/src/families/glm/prompt.zig +++ b/zig/src/families/glm/prompt.zig @@ -201,7 +201,7 @@ fn qmm(p: *const Prompt, e: mtl.ComputeEncoder, x: Ref, q: wts.Affine, y: Ref, M /// affine_mm's dense product at one batch: deep ones in column groups (mm_groups.zig, the same bits). fn denseOf(p: *const Prompt, e: mtl.ComputeEncoder, x: Ref, q: wts.Affine, y: Ref, M: u32, s: affine_mm.Strides) void { if (q.k >= mm_groups.dense_from) return mm_groups.dense(e, p.mm.mm_groups, x, p.sums, q, y, M, s); - affine_mm.denseBatch(e, p.mm.mm_bf16, x, p.sums, q, y, M, 1, s); + affine_mm.denseBatchBm(e, p.mm.mm_bf16, x, p.sums, q, y, M, 1, s, if (p.mm.m3_fast) 32 else 64); } /// `qmm` over x's rows `ld` elements apart (a slice of a wider row). @@ -221,7 +221,7 @@ fn qmmAt(p: *const Prompt, e: mtl.ComputeEncoder, x: Ref, ld: u32, q: wts.Affine /// `qmm` with fp32 out (TP2: one Mac's partial of a row-split projection). fn qmmF32(p: *const Prompt, e: mtl.ComputeEncoder, x: Ref, q: wts.Affine, y: Ref, M: u32) void { affine_mm.rowSums(e, p.mm.mm_bf16, 64, x, p.sums, M, q.k); - affine_mm.dense(e, p.mm.mm_f32, x, p.sums, q, y, M); + affine_mm.denseBm(e, p.mm.mm_f32, x, p.sums, q, y, M, if (p.mm.m3_fast) 32 else 64); } /// Routed experts' gate, up and SwiGLU into `act` ([n, gate.n]); `groups`: 4/64 in column groups (the same bits). @@ -397,7 +397,7 @@ fn kdaChunk(p: *const Prompt, x: *const fwd.Ctx, e: mtl.ComputeEncoder, ki: usiz e.setPipeline(if (tp) k.kda_scan_tp else k.kda_scan); bind(e, 0, .{ q, kk, v, g, beta, L.st[if (r0 == 0) cur else 1 - cur], L.st[1 - cur], sy }); e.setValue(@as(i32, @intCast(m)), 8); - e.dispatchGroups(size(c.kda_dim / 64, H, 1), size(512, 1, 1)); + if (x.k.m3_fast) e.dispatchGroups(size(c.kda_dim / 16, H, 1), size(128, 1, 1)) else e.dispatchGroups(size(c.kda_dim / 64, H, 1), size(512, 1, 1)); } if (!fwd.on(x, "kda_post")) continue; e.setPipeline(if (tp) k.kda_post_tp else k.kda_post); @@ -406,7 +406,7 @@ fn kdaChunk(p: *const Prompt, x: *const fwd.Ctx, e: mtl.ComputeEncoder, ki: usiz bind(e, 4, .{ p.y.at(@as(usize, r0) * W * 2), p.proj }); fwd.shape(e, 6, .{ M, pitch }); // every block writes the next chunk's conv window, the same rows bind(e, 7, .{ L.cs[cur], L.cs[1 - cur] }); - e.dispatchGroups(size(m, H, 1), size(32, 1, 1)); + if (x.k.m3_fast) e.dispatchGroups(size(m, H / 4, 1), size(128, 1, 1)) else e.dispatchGroups(size(m, H, 1), size(32, 1, 1)); } } @@ -431,7 +431,7 @@ fn unabsorb(p: *const Prompt, x: *const fwd.Ctx, e: mtl.ComputeEncoder, w: *cons q.b = q.b.at(@as(usize, c.nope) * (K / 64) * 2); q.n = c.v_dim; affine_mm.rowSums(e, p.mm.mm_bf16, 64, p.att, p.sums, M * H, K); - affine_mm.denseBatch(e, p.mm.mm_bf16, p.att, p.sums, q, p.vals, M, H, .{ .x_row = @intCast(H * K), .y_row = @intCast(H * c.v_dim), .sums_row = @intCast(H), .x_batch = @intCast(K), .y_batch = @intCast(c.v_dim), .sums_batch = 1, .w_batch = @intCast(per) }); + affine_mm.denseBatchBm(e, p.mm.mm_bf16, p.att, p.sums, q, p.vals, M, H, .{ .x_row = @intCast(H * K), .y_row = @intCast(H * c.v_dim), .sums_row = @intCast(H), .x_batch = @intCast(K), .y_batch = @intCast(c.v_dim), .sums_batch = 1, .w_batch = @intCast(per) }, if (p.mm.m3_fast) 32 else 64); } /// The index scores' tile rows: 128 (a row's queries read once for 64 blocks), 64 where that leaves the GPU half idle. @@ -447,8 +447,8 @@ fn selectKeys(p: *const Prompt, x: *const fwd.Ctx, e: mtl.ComputeEncoder, mi: us e.setPipeline(x.k.index_scores_nax); bind(e, 0, .{ iq, iw, x.s.mla[mi].pool, p.sscore }); e.setValue([5]u32{ p0, c.qrProj(), c.i_heads, s_stride, n }, 4); - const rows = scoreRows(most, n); - e.dispatchGroups(size((most + 63) / 64, (n + rows - 1) / rows, 1), size(2 * rows, 1, 1)); + const rows = if (x.k.m3_fast) 32 else scoreRows(most, n); + e.dispatchGroups(size((most + 63) / 64, (n + rows - 1) / rows, 1), size(if (x.k.m3_fast) 128 else 2 * rows, 1, 1)); e.setPipeline(x.k.index_select); bind(e, 0, .{ p.sscore, indices }); e.setValue([5]u32{ p0, c.i_topk / c.kpool, c.keyWidth(), s_stride, c.keyWidth() }, 2); diff --git a/zig/src/families/glm/wide.zig b/zig/src/families/glm/wide.zig index 52cc962efd4..b7cd74dbeb4 100644 --- a/zig/src/families/glm/wide.zig +++ b/zig/src/families/glm/wide.zig @@ -45,6 +45,7 @@ pub const Pipes = struct { mm6: affine_mm.Pipes, zeros: mtl.Buffer, // expert ids all 0: a dense GLU through the by-ids kernel (the shared expert) hash: u64, // every source compiled here + mm_bm: u32, // affine_mm dense row-tile height: 32 pre-M5 (TF_GLM_M3_FAST), 64 on M5 pub fn deinit(p: *Pipes) void { inline for (.{ @@ -188,11 +189,12 @@ fn build(gpa: std.mem.Allocator, device: mtl.Device, kda: []const u8, made: *Mad h.update(sources.ops_embed_norm); try lib(made, device, sources.ops_embed_norm, &.{ "tf_embed_b6_g64", "tf_embed_b8_g64" }, &p.embed); for ([_]u8{ 8, 2, 5, 6 }, [_]*affine_mm.Pipes{ &p.mm8, &p.mm2, &p.mm5, &p.mm6 }) |bits, out| { - const src = try affine_mm.source(device, gpa, .{ .bits = bits, .group = 64 }); + const src = try affine_mm.source(device, gpa, .{ .bits = bits, .group = 64, .glm_m3_fast = !device.tensorUnits() }); defer gpa.free(src); h.update(src); try lib(made, device, src, &affine_mm.names, out); } + p.mm_bm = if (device.tensorUnits()) 64 else 32; p.zeros = try device.buffer(64 * 4, mtl.ResourceOptions.shared); @memset(p.zeros.slice(i32, 64), 0); p.hash = h.final(); @@ -263,7 +265,7 @@ pub fn headsBatch(p: *const Pipes, e: mtl.ComputeEncoder, q: Affine, h: u32, io: var head = q; head.n = ny; affine_mm.rowSumsAt(e, pipes, 64, io.in, sums, io.rows, h * kx, io.ldx); // a head's sums one row apart - affine_mm.denseBatch(e, pipes, io.in, sums, head, io.out, io.rows, h, .{ + affine_mm.denseBatchBm(e, pipes, io.in, sums, head, io.out, io.rows, h, .{ .x_row = @intCast(io.ldx), .y_row = @intCast(io.ldo), .sums_row = @intCast(h), @@ -271,7 +273,7 @@ pub fn headsBatch(p: *const Pipes, e: mtl.ComputeEncoder, q: Affine, h: u32, io: .y_batch = @intCast(ny), .sums_batch = 1, .w_batch = @intCast(ny), - }); + }, p.mm_bm); } /// x [rows, k] through bf16 W [n, k]: scalar path, kept for tests / non-prefill callers (decode-side eh uses mtp.zig). @@ -470,17 +472,8 @@ pub fn denseMm(p: *const Pipes, e: mtl.ComputeEncoder, q: Affine, io: Io, sums: }; if (!summed) affine_mm.rowSumsAt(e, pipes, 64, io.in, sums, io.rows, q.k, io.ldx); // every member's: one k, g64 summed = true; - affine_mm.denseBatch( - e, - pipes, - io.in, - sums, - one, - part.out, - io.rows, - 1, - .{ .x_row = @intCast(io.ldx), .y_row = @intCast(io.ldo) }, - ); + const strides: affine_mm.Strides = .{ .x_row = @intCast(io.ldx), .y_row = @intCast(io.ldo) }; + affine_mm.denseBatchBm(e, pipes, io.in, sums, one, part.out, io.rows, 1, strides, p.mm_bm); } } diff --git a/zig/tests/contract/metal_affine.zig b/zig/tests/contract/metal_affine.zig index 8359fa44fa9..2ae78e13c6d 100644 --- a/zig/tests/contract/metal_affine.zig +++ b/zig/tests/contract/metal_affine.zig @@ -17,7 +17,20 @@ const lane = tf.lane_projection; pub const Kind = enum { row, affine_mm, simd, simd_half, simd_sums, simd_bits, lane, lane_reg }; /// One variant: kernel, code width and group, output, lane K slices; control: simd_half's or simd_sums' planted fault. -pub const Variant = struct { kind: Kind, bits: u8 = 4, group: usize = 64, f32_out: bool = false, sk: usize = 1, coop: bool = false, control: bool = false, served: ?[]const c.Shape = null, inline_sums: bool = false }; +pub const Variant = struct { kind: Kind, bits: u8 = 4, group: usize = 64, f32_out: bool = false, sk: usize = 1, coop: bool = false, glm_m3_fast: bool = false, control: bool = false, served: ?[]const c.Shape = null, inline_sums: bool = false }; +/// GLM-5.3-Flash's M3 fast tiles (#3921): row tile 32 a block where the plain path takes 64. +pub const glm_m3 = [_]Reg{ + .{ .v = .{ .kind = .affine_mm, .bits = 4, .group = 64, .glm_m3_fast = true }, .name = "metal affine_mm glm m3 q4 g64" }, + .{ .v = .{ .kind = .affine_mm, .bits = 4, .group = 64, .f32_out = true, .glm_m3_fast = true }, .name = "metal affine_mm glm m3 q4 g64 fp32 out" }, + .{ .v = .{ .kind = .affine_mm, .bits = 2, .group = 64, .glm_m3_fast = true }, .name = "metal affine_mm glm m3 q2 g64" }, + .{ .v = .{ .kind = .affine_mm, .bits = 5, .group = 64, .glm_m3_fast = true }, .name = "metal affine_mm glm m3 q5 g64" }, + .{ .v = .{ .kind = .affine_mm, .bits = 6, .group = 64, .glm_m3_fast = true }, .name = "metal affine_mm glm m3 q6 g64" }, + .{ .v = .{ .kind = .affine_mm, .bits = 8, .group = 64, .glm_m3_fast = true }, .name = "metal affine_mm glm m3 q8 g64" }, + .{ .v = .{ .kind = .affine_mm, .bits = 4, .group = 32, .glm_m3_fast = true }, .name = "metal affine_mm glm m3 q4 g32" }, + .{ .v = .{ .kind = .affine_mm, .bits = 4, .group = 128, .glm_m3_fast = true }, .name = "metal affine_mm glm m3 q4 g128" }, + .{ .v = .{ .kind = .affine_mm, .bits = 4, .group = 64, .glm_m3_fast = true, .control = true }, .name = "control: metal affine_mm glm m3 q4 g64, wrong row tile height" }, +}; + pub const Reg = struct { v: Variant, name: []const u8 }; /// The half-operand tiles, the chunk pairs on the prepass's sums, and their planted controls, beside simd_qmm's entry. pub const half = [_]Reg{ @@ -65,7 +78,7 @@ pub fn spec(v: Variant, name: []const u8) c.Spec { const step: usize = @max(16, v.group); return switch (v.kind) { .row => .{ .name = name, .accum = .f32, .depth = rowDepth, .out = out, .tiles = .{ .{ .size = 2 }, .{ .size = 8, .step = 8, .min = 8 }, .{ .size = 512, .step = step, .min = step } }, .served = &.{ .{ .rows = 16, .n = 2688, .k = 4096 }, .{ .rows = 3, .n = 4608, .k = 2688 } } }, - .affine_mm => .{ .name = name, .accum = .f32, .depth = groupDepth64, .out = out, .known = if (v.bits == 4) offset_inf else null, .tiles = .{ .{ .size = 64 }, .{ .size = 64, .step = 64, .min = 64 }, .{ .size = 128, .step = 64, .min = 64 } }, .served = if (v.bits == 8 and v.group == 64) &router_rows else &.{ .{ .rows = 128, .n = 2048, .k = 4096 }, .{ .rows = 65, .n = 1024, .k = 1024 } } }, + .affine_mm => .{ .name = name, .accum = .f32, .depth = groupDepth64, .out = out, .known = if (v.bits == 4) offset_inf else null, .tiles = .{ .{ .size = 64 }, .{ .size = 64, .step = 64, .min = 64 }, .{ .size = 128, .step = @max(64, v.group), .min = @max(64, v.group) } }, .served = if (v.bits == 8 and v.group == 64) &router_rows else &.{ .{ .rows = 128, .n = 2048, .k = 4096 }, .{ .rows = 65, .n = 1024, .k = 1024 } } }, .simd, .simd_bits => .{ .name = name, .accum = .f32, .depth = simdDepth, .out = out, .tiles = .{ .{ .size = 8 }, .{ .size = 32, .step = 8, .min = 8 }, .{ .size = 512, .step = 64, .min = 64 } }, .served = &.{ .{ .rows = 16, .n = 2688, .k = 4096 }, .{ .rows = 9, .n = 6400, .k = 256 } } }, // the 27B's norm-fed widths past 6,144 (8 chunks), as the prompt chunk's tiles and its 9-row tail take them .simd_half => .{ .name = name, .accum = .f32, .depth = simdDepth, .out = out, .replaces = "simd_qmm's fp32 tiles", .tiles = .{ .{ .size = 8 }, .{ .size = 32, .step = 8, .min = 8 }, .{ .size = 512, .step = 64, .min = 64 } }, .served = &.{ .{ .rows = 32, .n = 6240, .k = 512 }, .{ .rows = 9, .n = 12288, .k = 256 } } }, @@ -112,7 +125,7 @@ pub const Proj = struct { .simd, .simd_half, .simd_sums => p.sq_p = try sq.Pipelines.load(device), .simd_bits => p.sqb_p = try sqb.Pipelines.load(device), .affine_mm => { - const src = try mm.source(device, a, .{ .bits = v.bits, .group = @intCast(v.group), .out_f32 = v.f32_out }); + const src = try mm.source(device, a, .{ .bits = v.bits, .group = @intCast(v.group), .out_f32 = v.f32_out, .glm_m3_fast = v.glm_m3_fast }); defer a.free(src); const lib = try mtl.Library.fromSource(device, src, mtl.CompileOptions.mlx()); defer lib.deinit(); @@ -272,7 +285,8 @@ pub const Proj = struct { const xs = .{ .buf = p.sums.buf, .off = p.sums.off }; const q = .{ .w = .{ .buf = p.w.buf, .off = p.w.off }, .s = .{ .buf = p.s.buf, .off = p.s.off }, .b = .{ .buf = p.b.buf, .off = p.b.off }, .n = @as(u32, @intCast(shape.n)), .k = @as(u32, @intCast(shape.k)) }; mm.rowSums(e, p.mm_p.?, @intCast(p.v.group), x, xs, @intCast(shape.rows), @intCast(shape.k)); - mm.dense(e, p.mm_p.?, x, xs, q, .{ .buf = p.out.buf, .off = p.out.off }, @intCast(shape.rows)); + const bm: u32 = if (p.v.glm_m3_fast and p.v.control) 128 else if (p.v.glm_m3_fast and !p.rig.device.tensorUnits()) 32 else 64; + mm.denseBm(e, p.mm_p.?, x, xs, q, .{ .buf = p.out.buf, .off = p.out.off }, @intCast(shape.rows), bm); }, .lane, .lane_reg => try p.lane_p.?.encode(e, ref(p.x), ref(p.w), ref(p.s), ref(p.out), @intCast(shape.rows)), } diff --git a/zig/tests/contract/metal_affine_gather.zig b/zig/tests/contract/metal_affine_gather.zig index f977d501910..d3c52abe424 100644 --- a/zig/tests/contract/metal_affine_gather.zig +++ b/zig/tests/contract/metal_affine_gather.zig @@ -34,15 +34,18 @@ pub const Mutation = enum { }; /// One registered gather: the weights' bits (groups of 64), whether each output goes back to its row's own place. -pub const Variant = struct { bits: u8, scatter: bool, mutation: Mutation = .none }; +pub const Variant = struct { bits: u8, scatter: bool, glm_m3_fast: bool = false, mutation: Mutation = .none }; -/// The widths qwen27 admits for its routed experts on tensor units, each plain and scattering, and three controls. +/// The widths qwen27 admits for its routed experts on tensor units, each plain and scattering, and controls. pub const registered = [_]Variant{ .{ .bits = 4, .scatter = false }, .{ .bits = 4, .scatter = true }, .{ .bits = 8, .scatter = false }, .{ .bits = 8, .scatter = true }, + .{ .bits = 4, .scatter = false, .glm_m3_fast = true }, + .{ .bits = 8, .scatter = true, .glm_m3_fast = true }, .{ .bits = 4, .scatter = false, .mutation = .tail }, + .{ .bits = 4, .scatter = false, .glm_m3_fast = true, .mutation = .tail }, .{ .bits = 8, .scatter = false, .mutation = .expert }, .{ .bits = 4, .scatter = true, .mutation = .scatter }, }; @@ -50,10 +53,10 @@ pub const registered = [_]Variant{ pub fn name(v: Variant) []const u8 { return switch (v.mutation) { .none => switch (v.bits) { - 4 => if (v.scatter) "metal affine_mm q4 g64 gather scatter" else "metal affine_mm q4 g64 gather", - else => if (v.scatter) "metal affine_mm q8 g64 gather scatter" else "metal affine_mm q8 g64 gather", + 4 => if (v.glm_m3_fast) (if (v.scatter) "metal affine_mm glm m3 q4 g64 gather scatter" else "metal affine_mm glm m3 q4 g64 gather") else if (v.scatter) "metal affine_mm q4 g64 gather scatter" else "metal affine_mm q4 g64 gather", + else => if (v.glm_m3_fast) (if (v.scatter) "metal affine_mm glm m3 q8 g64 gather scatter" else "metal affine_mm glm m3 q8 g64 gather") else if (v.scatter) "metal affine_mm q8 g64 gather scatter" else "metal affine_mm q8 g64 gather", }, - .tail => "control: metal affine_mm gather q4 g64, each expert's last row dropped", + .tail => if (v.glm_m3_fast) "control: metal affine_mm glm m3 gather q4 g64, each expert's last row dropped" else "control: metal affine_mm gather q4 g64, each expert's last row dropped", .expert => "control: metal affine_mm gather q8 g64, a tile reads its neighbour expert's weights", .scatter => "control: metal affine_mm gather scatter q4 g64, outputs left in sorted order", }; @@ -93,7 +96,7 @@ pub const Gather = struct { out: rig_.Ref = undefined, pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, v: Variant) !Gather { - const plain = try mm.source(device, a, .{ .bits = v.bits, .group = 64 }); + const plain = try mm.source(device, a, .{ .bits = v.bits, .group = 64, .glm_m3_fast = v.glm_m3_fast }); defer a.free(plain); const src = if (v.mutation == .none) try a.dupe(u8, plain) else blk: { const e = v.mutation.edit(); diff --git a/zig/tests/contract/metal_glm_prompt.zig b/zig/tests/contract/metal_glm_prompt.zig new file mode 100644 index 00000000000..3577db06182 --- /dev/null +++ b/zig/tests/contract/metal_glm_prompt.zig @@ -0,0 +1,565 @@ +//! GLM-5.3-Flash M3 prompt index and KDA contracts: byte-exact against unvectorized baseline, plus planted controls. +const std = @import("std"); +const mtl = @import("metal"); +const tf = @import("tensorfold"); +const sources = @import("kernel_sources"); +const contract = @import("contract"); +const rig_ = @import("rig.zig"); + +const c = contract.spec; +const g = contract.gates; +const hi: usize = 32; +const di: usize = 128; +const d_kda: usize = 128; +const taps: usize = 4; + +const ScoreArgs = extern struct { p0: u32, q_stride: u32, w_stride: u32, s_stride: u32, rows: u32 }; + +fn bfVal(x: f32) u16 { + return c.toBf16(x); +} + +fn fillBf(dst: []u16, rng: std.Random, scale: f32) void { + for (dst) |*v| v.* = bfVal((rng.float(f32) * 2 - 1) * scale); +} + +fn fillF32(dst: []f32, rng: std.Random, lo: f32, hi_v: f32) void { + for (dst) |*v| v.* = lo + rng.float(f32) * (hi_v - lo); +} + +fn packRefs(a: std.mem.Allocator, rig: *const rig_.Rig, refs: []const rig_.Ref, lens: []const usize, out: *std.ArrayList(u8)) ![]const u8 { + out.clearRetainingCapacity(); + for (refs, lens) |r, len| try out.appendSlice(a, rig.bytes(r, len)); + return out.items; +} + +fn allocOutputSet(rig: *rig_.Rig, lens: []const usize, refs: []rig_.Ref, bases: []rig_.Ref) !void { + for (lens, 0..) |len, i| { + refs[i] = try rig.output(len); + bases[i] = try rig.scratch(len); + @memset(rig.bytes(bases[i], len), 0xff); + } +} + +pub const IndexKind = enum { scores, decode }; + +pub const Index = struct { + a: std.mem.Allocator, + rig: rig_.Rig, + kind: IndexKind, + control: bool, + name: []const u8, + pipe: mtl.Pipeline, + base_pipe: mtl.Pipeline, + rows: usize = 0, + p0: usize = 0, + most: usize = 0, + s_stride: usize = 0, + refs: [3]rig_.Ref = undefined, + out: rig_.Ref = undefined, + base: rig_.Ref = undefined, + bytes: std.ArrayList(u8) = .empty, + base_bytes: std.ArrayList(u8) = .empty, + + fn depth(s: c.Shape) usize { + _ = s; + return 0; + } + + pub fn spec(kind: IndexKind, control: bool, name: []const u8) c.Spec { + const served: []const c.Shape = switch (kind) { + .scores => &.{ .{ .rows = 1, .n = di, .k = 16 }, .{ .rows = 33, .n = di, .k = 128 }, .{ .rows = 65, .n = di, .k = 260 } }, + .decode => &.{ .{ .rows = 1, .n = di, .k = 16 }, .{ .rows = 4, .n = di, .k = 516 }, .{ .rows = 16, .n = di, .k = 1028 } }, + }; + const tiles: [3]c.Tile = switch (kind) { + .scores => .{ .{ .size = 32, .step = 1, .min = 1 }, .{ .size = di, .step = di, .min = di }, .{ .size = 256, .step = 4, .min = 16 } }, + .decode => .{ .{ .size = 4, .step = 1, .min = 1 }, .{ .size = di, .step = di, .min = di }, .{ .size = 256, .step = 4, .min = 16 } }, + }; + return .{ + .name = name, + .accum = .none, + .depth = depth, + .out = .f32, + .replaces = if (control) null else "unvectorized M3 glm_index_nax kernel", + .nan = .{ .stated = "every output bit matches the unvectorized baseline, non-finite inputs included" }, + .tiles = tiles, + .served = served, + .sums = .{ .why = "bit-preserving layout optimization; arithmetic and accumulation order match the baseline" }, + }; + } + + const vt = blk: { + var v = g.hooks(Index); + v.output = output; + v.intact = intact; + v.check = checkNonfinite; + break :blk v; + }; + + pub fn kernel(self: *Index) g.Kernel { + return .{ .spec = spec(self.kind, self.control, self.name), .ctx = self, .vt = &vt, .control = if (self.control) .shapes else null }; + } + + pub fn deinit(self: *Index) void { + self.rig.deinit(); + self.bytes.deinit(self.a); + self.base_bytes.deinit(self.a); + } + + pub fn prepare(self: *Index, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + self.rig.reset(); + if (shape.rows == 0 or shape.n != di or shape.k + shape.rows < 4) return false; + self.rows = shape.rows; + self.p0 = shape.k; + self.most = (self.p0 + self.rows) / 4; + const q_stride = hi * di + 64; + const w_stride = hi + 16; + self.s_stride = self.most + 5; + const iq = try self.a.alloc(u16, self.rows * q_stride); + defer self.a.free(iq); + const iw = try self.a.alloc(u16, self.rows * w_stride); + defer self.a.free(iw); + const pool = try self.a.alloc(u16, self.most * di); + defer self.a.free(pool); + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + fillBf(iq, rng, 1.5); + fillBf(iw, rng, 1.5); + fillBf(pool, rng, 1.5); + if (fill == .nonfinite) { + iq[0] = bfVal(std.math.nan(f32)); + iq[di + 3] = bfVal(std.math.inf(f32)); + iq[2 * di + 7] = bfVal(-std.math.inf(f32)); + iw[1] = bfVal(std.math.inf(f32)); + pool[0] = bfVal(std.math.nan(f32)); + pool[(self.most - 1) * di + 5] = bfVal(-std.math.inf(f32)); + } + self.refs[0] = try self.rig.input(std.mem.sliceAsBytes(iq)); + self.refs[1] = try self.rig.input(std.mem.sliceAsBytes(iw)); + self.refs[2] = try self.rig.input(std.mem.sliceAsBytes(pool)); + self.out = try self.rig.output(self.rows * self.s_stride * 4); + self.base = try self.rig.scratch(self.rows * self.s_stride * 4); + @memset(self.rig.bytes(self.base, self.rows * self.s_stride * 4), 0xff); + return true; + } + + fn encode(self: *const Index, e: mtl.ComputeEncoder, pipe: mtl.Pipeline, out_ref: rig_.Ref, rm: u32, bs: u32) void { + const q_stride: u32 = hi * di + 64; + const w_stride: u32 = hi + 16; + const n: u32 = @intCast(self.rows); + const most: u32 = @intCast(self.most); + e.setPipeline(pipe); + e.setBuffer(self.refs[0].buf, self.refs[0].off, 0); + e.setBuffer(self.refs[1].buf, self.refs[1].off, 1); + e.setBuffer(self.refs[2].buf, self.refs[2].off, 2); + e.setBuffer(out_ref.buf, out_ref.off, 3); + const args = ScoreArgs{ .p0 = @intCast(self.p0), .q_stride = q_stride, .w_stride = w_stride, .s_stride = @intCast(self.s_stride), .rows = n }; + e.setBytes(std.mem.asBytes(&args), 4); + const gx = if (self.kind == .scores) (most + 63) / 64 else (most + bs - 1) / bs; + const gy = if (self.kind == .scores) (n + rm - 1) / rm else n; + e.dispatchGroups(mtl.Size.of(gx, gy, 1), mtl.Size.of(128, 1, 1)); + } + + pub fn run(self: *Index) !void { + const p = self.rig.begin(); + const m3 = !self.rig.device.tensorUnits(); + const rm: u32 = if (self.control) (if (m3) 64 else 128) else if (m3) 32 else 64; + const bs: u32 = if (self.control) (if (m3) 128 else 256) else if (m3) 64 else 128; + self.encode(p.e, self.pipe, self.out, rm, bs); + try self.rig.finish(p); + } + + fn writtenCount(self: *const Index) usize { + var total: usize = 0; + for (0..self.rows) |r| total += (self.p0 + r + 1) / 4; + return total; + } + + pub fn count(self: *Index) usize { + return self.writtenCount(); + } + + fn pack(self: *const Index, from: rig_.Ref, dst: *std.ArrayList(u8)) ![]const u8 { + dst.clearRetainingCapacity(); + const raw = self.rig.bytes(from, self.rows * self.s_stride * 4); + for (0..self.rows) |r| { + const b = (self.p0 + r + 1) / 4; + try dst.appendSlice(self.a, raw[r * self.s_stride * 4 ..][0 .. b * 4]); + } + return dst.items; + } + + fn intact(ctx: *anyopaque) !bool { + const self: *Index = @ptrCast(@alignCast(ctx)); + if (!try self.rig.intact()) return false; + const raw = self.rig.bytes(self.out, self.rows * self.s_stride * 4); + for (0..self.rows) |r| { + const b = (self.p0 + r + 1) / 4; + for (raw[(r * self.s_stride + b) * 4 .. (r + 1) * self.s_stride * 4]) |byte| if (byte != 0xff) return false; + } + return true; + } + + fn output(ctx: *anyopaque) ![]const u8 { + const self: *Index = @ptrCast(@alignCast(ctx)); + if (!try intact(self)) return error.WroteOutsideOutputs; + return self.pack(self.out, &self.bytes); + } + + pub fn replaced(self: *Index) ![]const u8 { + const p = self.rig.begin(); + self.encode(p.e, self.base_pipe, self.base, 64, 128); + try self.rig.finish(p); + return self.pack(self.base, &self.base_bytes); + } + + fn checkNonfinite(ctx: *anyopaque, gate: g.Gate) !?[]const u8 { + const self: *Index = @ptrCast(@alignCast(ctx)); + const want = try self.replaced(); + const got = try output(self); + if (!std.mem.eql(u8, got, want)) { + return if (gate == .nonfinite) "index outputs differ from baseline on nonfinite inputs" else "index outputs differ from baseline"; + } + return null; + } + + pub fn reference(_: *Index, want: []f64, mag: []f64) !void { + @memset(want, 0); + @memset(mag, 0); + } +}; + +pub const KdaKind = enum { prep, scan, post }; + +pub const Kda = struct { + a: std.mem.Allocator, + rig: rig_.Rig, + kind: KdaKind, + heads: u32, + control: bool, + name: []const u8, + pipe: mtl.Pipeline, + base_pipe: mtl.Pipeline, + rows: usize = 0, + r0: usize = 0, + in_refs: [8]rig_.Ref = undefined, + out_refs: [5]rig_.Ref = undefined, + base_refs: [5]rig_.Ref = undefined, + out_lens: [5]usize = undefined, + n_outs: usize = 0, + bytes: std.ArrayList(u8) = .empty, + base_bytes: std.ArrayList(u8) = .empty, + + fn depth(s: c.Shape) usize { + _ = s; + return 0; + } + + fn kdaServed(comptime w: usize, kind: KdaKind) []const c.Shape { + return switch (kind) { + .prep => &.{ .{ .rows = 1, .n = w, .k = 0 }, .{ .rows = 5, .n = w, .k = 4 }, .{ .rows = 16, .n = w, .k = 0 } }, + .scan => &.{ .{ .rows = 1, .n = w, .k = d_kda }, .{ .rows = 24, .n = w, .k = d_kda }, .{ .rows = 25, .n = w, .k = d_kda } }, + .post => &.{ .{ .rows = 1, .n = w, .k = 0 }, .{ .rows = 2, .n = w, .k = 0 }, .{ .rows = 5, .n = w, .k = 0 } }, + }; + } + + pub fn spec(kind: KdaKind, heads: u32, control: bool, name: []const u8) c.Spec { + const w: usize = @as(usize, heads) * d_kda; + const served = if (heads == 32) kdaServed(32 * d_kda, kind) else kdaServed(64 * d_kda, kind); + const tiles: [3]c.Tile = switch (kind) { + .prep => .{ .{ .size = 8, .step = 1, .min = 1 }, .{ .size = w, .step = w, .min = w }, .{ .size = 4, .step = 4, .min = 0 } }, + .scan => .{ .{ .size = 24, .step = 1, .min = 1 }, .{ .size = w, .step = w, .min = w }, .{ .size = d_kda, .step = d_kda, .min = d_kda } }, + .post => .{ .{ .size = 4, .step = 1, .min = 1 }, .{ .size = w, .step = w, .min = w }, .{} }, + }; + return .{ + .name = name, + .accum = .none, + .depth = depth, + .out = .raw, + .replaces = if (control) null else "unvectorized M3 glm_kda_prompt kernel", + .nan = .{ .stated = "every output bit matches the unvectorized baseline, non-finite inputs included" }, + .tiles = tiles, + .served = served, + .sums = .{ .why = "bit-preserving layout optimization; arithmetic and recurrence order match the baseline" }, + }; + } + + const vt = blk: { + var v = g.hooks(Kda); + v.output = output; + v.check = checkNonfinite; + break :blk v; + }; + + pub fn kernel(self: *Kda) g.Kernel { + return .{ .spec = spec(self.kind, self.heads, self.control, self.name), .ctx = self, .vt = &vt, .control = if (self.control) .shapes else null }; + } + + pub fn deinit(self: *Kda) void { + self.rig.deinit(); + self.bytes.deinit(self.a); + self.base_bytes.deinit(self.a); + } + + fn allocBfIn(self: *Kda, len: usize, rng: std.Random, scale: f32, idx: usize, nf: bool) !void { + const buf = try self.a.alloc(u16, len); + defer self.a.free(buf); + fillBf(buf, rng, scale); + if (nf and len > 0) buf[0] = bfVal(std.math.nan(f32)); + if (nf and len > 4) buf[4] = bfVal(std.math.inf(f32)); + if (nf and len > 9) buf[9] = bfVal(-std.math.inf(f32)); + self.in_refs[idx] = try self.rig.input(std.mem.sliceAsBytes(buf)); + } + + fn allocF32In(self: *Kda, len: usize, rng: std.Random, lo: f32, hi_v: f32, idx: usize, nf: bool) !void { + const buf = try self.a.alloc(f32, len); + defer self.a.free(buf); + fillF32(buf, rng, lo, hi_v); + if (nf and len > 0) buf[0] = std.math.inf(f32); + if (nf and len > 3) buf[3] = std.math.nan(f32); + self.in_refs[idx] = try self.rig.input(std.mem.sliceAsBytes(buf)); + } + + pub fn prepare(self: *Kda, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + self.rig.reset(); + const w: usize = @as(usize, self.heads) * d_kda; + if (shape.rows == 0 or shape.n != w) return false; + self.rows = shape.rows; + self.r0 = if (self.kind == .prep) shape.k else 0; + const c3 = 3 * w; + const ps = c3 + 2 * d_kda + self.heads; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + const nf = fill == .nonfinite; + switch (self.kind) { + .prep => { + try self.allocBfIn((self.r0 + self.rows) * ps, rng, 0.5, 0, nf); + try self.allocBfIn((taps - 1) * c3, rng, 0.5, 1, nf); + try self.allocF32In(taps * c3, rng, -0.5, 0.5, 2, false); + try self.allocBfIn(self.rows * w, rng, 0.5, 3, nf); + try self.allocF32In(self.heads, rng, -1.5, -0.2, 4, nf); + try self.allocF32In(w, rng, -0.5, 0.5, 5, false); + self.out_lens[0..5].* = .{ self.rows * w * 2, self.rows * w * 2, self.rows * w * 2, self.rows * w * 4, self.rows * self.heads * 4 }; + self.n_outs = 5; + }, + .scan => { + for (0..3) |i| try self.allocBfIn(self.rows * w, rng, 0.4, i, nf); + try self.allocF32In(self.rows * w, rng, 0.5, 1.0, 3, nf); + try self.allocF32In(self.rows * self.heads, rng, 0.1, 0.9, 4, nf); + try self.allocF32In(@as(usize, self.heads) * d_kda * d_kda, rng, -0.5, 0.5, 5, nf); + self.out_lens[0..2].* = .{ @as(usize, self.heads) * d_kda * d_kda * 4, self.rows * w * 2 }; + self.n_outs = 2; + }, + .post => { + try self.allocBfIn(self.rows * w, rng, 0.8, 0, nf); + try self.allocBfIn(self.rows * w, rng, 0.8, 1, nf); + try self.allocF32In(d_kda, rng, 0.5, 1.5, 2, nf); + try self.allocBfIn(self.rows * ps, rng, 0.5, 3, nf); + try self.allocBfIn((taps - 1) * c3, rng, 0.5, 4, nf); + self.out_lens[0..2].* = .{ self.rows * w * 2, (taps - 1) * c3 * 2 }; + self.n_outs = 2; + }, + } + try allocOutputSet(&self.rig, self.out_lens[0..self.n_outs], self.out_refs[0..self.n_outs], self.base_refs[0..self.n_outs]); + return true; + } + + fn encode(self: *const Kda, e: mtl.ComputeEncoder, pipe: mtl.Pipeline, outs: []const rig_.Ref, m3: bool, ctrl: bool) void { + const w: usize = @as(usize, self.heads) * d_kda; + const ps: i32 = @intCast(3 * w + 2 * d_kda + self.heads); + e.setPipeline(pipe); + switch (self.kind) { + .prep => { + const shape = [3]i32{ @intCast(self.rows), ps, @intCast(self.r0) }; + const lb: f32 = -1.0; + e.setBuffer(self.in_refs[0].buf, self.in_refs[0].off, 0); + e.setBytes(std.mem.asBytes(&shape), 1); + for (self.in_refs[1..6], 2..) |r, idx| e.setBuffer(r.buf, r.off, idx); + e.setBytes(std.mem.asBytes(&lb), 7); + for (outs[0..5], 8..) |r, idx| e.setBuffer(r.buf, r.off, idx); + const gy: usize = if (ctrl) self.heads / 8 else self.heads / 4; + e.dispatchGroups(mtl.Size.of(self.rows, gy, 1), mtl.Size.of(128, 1, 1)); + }, + .scan => { + const r_val: i32 = @intCast(self.rows); + for (self.in_refs[0..6], 0..) |r, idx| e.setBuffer(r.buf, r.off, idx); + e.setBuffer(outs[0].buf, outs[0].off, 6); + e.setBuffer(outs[1].buf, outs[1].off, 7); + e.setBytes(std.mem.asBytes(&r_val), 8); + const sg_cols: usize = if (m3) 16 else 64; + const th: usize = if (m3) 128 else 512; + const gx = if (ctrl) (d_kda / sg_cols) / 2 else d_kda / sg_cols; + e.dispatchGroups(mtl.Size.of(gx, self.heads, 1), mtl.Size.of(th, 1, 1)); + }, + .post => { + const shape = [2]i32{ @intCast(self.rows), ps }; + const eps: f32 = 1e-5; + for (self.in_refs[0..3], 0..) |r, idx| e.setBuffer(r.buf, r.off, idx); + e.setBytes(std.mem.asBytes(&eps), 3); + e.setBuffer(outs[0].buf, outs[0].off, 4); + e.setBuffer(self.in_refs[3].buf, self.in_refs[3].off, 5); + e.setBytes(std.mem.asBytes(&shape), 6); + e.setBuffer(self.in_refs[4].buf, self.in_refs[4].off, 7); + e.setBuffer(outs[1].buf, outs[1].off, 8); + const hb: usize = if (m3) 4 else 1; + const th: usize = if (m3) 128 else 32; + const gy = if (ctrl) (self.heads / hb) / 2 else self.heads / hb; + e.dispatchGroups(mtl.Size.of(self.rows, gy, 1), mtl.Size.of(th, 1, 1)); + }, + } + } + + pub fn run(self: *Kda) !void { + const p = self.rig.begin(); + const m3 = !self.rig.device.tensorUnits(); + self.encode(p.e, self.pipe, self.out_refs[0..self.n_outs], m3, self.control); + try self.rig.finish(p); + } + + pub fn count(self: *Kda) usize { + var total: usize = 0; + for (self.out_lens[0..self.n_outs]) |len| total += len; + return total; + } + + fn output(ctx: *anyopaque) ![]const u8 { + const self: *Kda = @ptrCast(@alignCast(ctx)); + return packRefs(self.a, &self.rig, self.out_refs[0..self.n_outs], self.out_lens[0..self.n_outs], &self.bytes); + } + + pub fn replaced(self: *Kda) ![]const u8 { + const p = self.rig.begin(); + self.encode(p.e, self.base_pipe, self.base_refs[0..self.n_outs], false, false); + try self.rig.finish(p); + return packRefs(self.a, &self.rig, self.base_refs[0..self.n_outs], self.out_lens[0..self.n_outs], &self.base_bytes); + } + + fn checkNonfinite(ctx: *anyopaque, gate: g.Gate) !?[]const u8 { + const self: *Kda = @ptrCast(@alignCast(ctx)); + const want = try self.replaced(); + const got = try output(self); + if (!std.mem.eql(u8, got, want)) { + return if (gate == .nonfinite) "kda outputs differ from baseline on nonfinite inputs" else "kda outputs differ from baseline"; + } + return null; + } + + pub fn reference(_: *Kda, want: []f64, mag: []f64) !void { + @memset(want, 0); + @memset(mag, 0); + } +}; + +fn wanted(only: ?[]const u8, name: []const u8) bool { + const text = only orelse return true; + return std.mem.indexOf(u8, name, text) != null; +} + +const kda_specs = [_]struct { kind: KdaKind, heads: u32, fn_name: []const u8, control: bool, name: []const u8 }{ + .{ .kind = .prep, .heads = 64, .fn_name = "glm_kda_prep", .control = false, .name = "metal glm m3 kda_prep" }, + .{ .kind = .prep, .heads = 64, .fn_name = "glm_kda_prep", .control = true, .name = "control: metal glm m3 kda_prep, wrong head tile grid" }, + .{ .kind = .scan, .heads = 64, .fn_name = "glm_kda_scan", .control = false, .name = "metal glm m3 kda_scan" }, + .{ .kind = .scan, .heads = 64, .fn_name = "glm_kda_scan", .control = true, .name = "control: metal glm m3 kda_scan, half value-column grid" }, + .{ .kind = .scan, .heads = 32, .fn_name = "glm_kda_scan_tp", .control = false, .name = "metal glm m3 kda_scan_tp" }, + .{ .kind = .post, .heads = 64, .fn_name = "glm_kda_post", .control = false, .name = "metal glm m3 kda_post" }, + .{ .kind = .post, .heads = 64, .fn_name = "glm_kda_post", .control = true, .name = "control: metal glm m3 kda_post, wrong head tile grid" }, +}; + +const index_specs = [_]struct { kind: IndexKind, fn_name: []const u8, control: bool, name: []const u8 }{ + .{ .kind = .scores, .fn_name = "glm_index_scores_nax", .control = false, .name = "metal glm m3 index_scores_nax" }, + .{ .kind = .scores, .fn_name = "glm_index_scores_nax", .control = true, .name = "control: metal glm m3 index_scores_nax, wrong row tile height" }, + .{ .kind = .decode, .fn_name = "glm_index_decode", .control = false, .name = "metal glm m3 index_decode" }, + .{ .kind = .decode, .fn_name = "glm_index_decode", .control = true, .name = "control: metal glm m3 index_decode, wrong block tile width" }, +}; + +pub const Suite = struct { + a: std.mem.Allocator, + pipes: std.ArrayList(mtl.Pipeline) = .empty, + indices: [index_specs.len]Index = undefined, + index_made: usize = 0, + kdas: [kda_specs.len]Kda = undefined, + kda_made: usize = 0, + + pub fn create(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, out: *std.ArrayList(g.Kernel), only: ?[]const u8) !*Suite { + const s = try a.create(Suite); + s.* = .{ .a = a }; + errdefer s.destroy(); + var need_idx = false; + for (index_specs) |e| if (wanted(only, e.name)) { + need_idx = true; + }; + var need_kda = false; + for (kda_specs) |e| if (wanted(only, e.name)) { + need_kda = true; + }; + const m3_def = if (!device.tensorUnits()) "#define TF_GLM_M3_FAST 1\n" else ""; + if (need_idx) { + const idx_raw = try std.mem.concat(a, u8, &.{ m3_def, sources.glm_index_nax }); + defer a.free(idx_raw); + const idx_src = try tf.frags.source(device, a, idx_raw); + defer a.free(idx_src); + const idx_base_src = try tf.frags.source(device, a, sources.glm_index_nax); + defer a.free(idx_base_src); + const idx_lib = try mtl.Library.fromSource(device, idx_src, mtl.CompileOptions.mlx()); + defer idx_lib.deinit(); + const base_lib = try mtl.Library.fromSource(device, idx_base_src, mtl.CompileOptions.mlx()); + defer base_lib.deinit(); + for (index_specs) |e| { + if (!wanted(only, e.name)) continue; + const pipe = try mtl.Pipeline.init(device, idx_lib, e.fn_name, false); + try s.pipes.append(a, pipe); + const base_pipe = try mtl.Pipeline.init(device, base_lib, e.fn_name, false); + try s.pipes.append(a, base_pipe); + s.indices[s.index_made] = .{ + .a = a, + .rig = .{ .a = a, .device = device, .queue = queue }, + .kind = e.kind, + .control = e.control, + .name = e.name, + .pipe = pipe, + .base_pipe = base_pipe, + }; + try out.append(a, s.indices[s.index_made].kernel()); + s.index_made += 1; + } + } + if (need_kda) { + const kda_prefix = comptime tf.glm.kernels.generatedSource("kda_rows"); + const kda_src = try std.mem.concat(a, u8, &.{ kda_prefix, m3_def, sources.glm_kda_prompt }); + defer a.free(kda_src); + const kda_base_src = kda_prefix ++ sources.glm_kda_prompt; + const kda_lib = try mtl.Library.fromSource(device, kda_src, mtl.CompileOptions.mlx()); + defer kda_lib.deinit(); + const base_lib = try mtl.Library.fromSource(device, kda_base_src, mtl.CompileOptions.mlx()); + defer base_lib.deinit(); + for (kda_specs) |e| { + if (!wanted(only, e.name)) continue; + const pipe = try mtl.Pipeline.init(device, kda_lib, e.fn_name, false); + try s.pipes.append(a, pipe); + const base_pipe = try mtl.Pipeline.init(device, base_lib, e.fn_name, false); + try s.pipes.append(a, base_pipe); + s.kdas[s.kda_made] = .{ + .a = a, + .rig = .{ .a = a, .device = device, .queue = queue }, + .kind = e.kind, + .heads = e.heads, + .control = e.control, + .name = e.name, + .pipe = pipe, + .base_pipe = base_pipe, + }; + try out.append(a, s.kdas[s.kda_made].kernel()); + s.kda_made += 1; + } + } + return s; + } + + pub fn destroy(s: *Suite) void { + for (s.indices[0..s.index_made]) |*it| it.deinit(); + for (s.kdas[0..s.kda_made]) |*it| it.deinit(); + for (s.pipes.items) |p| p.deinit(); + s.pipes.deinit(s.a); + s.a.destroy(s); + } +}; diff --git a/zig/tests/contract/metal_limits.zig b/zig/tests/contract/metal_limits.zig index 5d4fc8929eb..790b720bb0f 100644 --- a/zig/tests/contract/metal_limits.zig +++ b/zig/tests/contract/metal_limits.zig @@ -372,11 +372,18 @@ fn resolve(a: std.mem.Allocator, device: mtl.Device, d: limits.MetalLaunch, comp text = sources.core_simd_qmm; } else if (has(d.name, "affine_mm")) { if (!assemble) return undefined; - const bits: u8 = if (has(d.name, "q8")) 8 else 4; - const group: u16 = if (has(d.name, "g32")) 32 else 64; - head = try std.fmt.allocPrint(a, "#define TF_BITS {d}\n#define TF_GROUP {d}\n#define TF_OUT_T bfloat\n", .{ bits, group }); - text = sources.core_affine_mm; - frags = true; + const bits: u8 = if (has(d.name, "q8")) 8 else if (has(d.name, "q6")) 6 else if (has(d.name, "q5")) 5 else if (has(d.name, "q2")) 2 else 4; + const group: u16 = if (has(d.name, "g128")) 128 else if (has(d.name, "g32")) 32 else 64; + const out_t: []const u8 = if (has(d.name, "fp32")) "float" else "bfloat"; + const m3_head: []const u8 = if (has(d.name, "glm m3")) "#define TF_GLM_M3_FAST 1\n" else ""; + head = try std.fmt.allocPrint(a, "#define TF_BITS {d}\n#define TF_GROUP {d}\n#define TF_OUT_T {s}\n", .{ bits, group, out_t }); + const pre_head = if (m3_head.len == 0) head else try std.mem.concat(a, u8, &.{ head, m3_head }); + const pre = try preM5(a, pre_head, sources.core_affine_mm); + const here = if (device.tensorUnits()) blk: { + const body = try tf.frags.source(device, a, sources.core_affine_mm); + break :blk try std.mem.concat(a, u8, &.{ head, body }); + } else pre; + return .{ .decl = d, .function = fun, .here = here, .pre_m5 = pre }; } else if (has(d.name, "lane projection")) { if (!assemble) return undefined; const sk: usize = if (has(d.name, "sk4")) 4 else 1; diff --git a/zig/tests/contract/metal_main.zig b/zig/tests/contract/metal_main.zig index f5b61da3f2d..eb44a76eab1 100644 --- a/zig/tests/contract/metal_main.zig +++ b/zig/tests/contract/metal_main.zig @@ -75,7 +75,7 @@ const common = [_]Reg{ .{ .v = .{ .kind = .simd_bits, .bits = 8, .group = 64 }, .name = "metal simd_qmm_bits q8 g64" }, .{ .v = .{ .kind = .lane, .bits = 6, .group = 32 }, .name = "metal lane projection q6 g32 sk1" }, .{ .v = .{ .kind = .lane, .bits = 6, .group = 32, .sk = 4, .f32_out = true }, .name = "metal lane projection q6 g32 sk4 fp32 out" }, -} ++ affine_k.half; +} ++ affine_k.half ++ affine_k.glm_m3; /// The lane kernel takes every format on the M5's tensor units, and 6-bit groups of 32 alone before them. const m5_only = @import("metal_lane_variants.zig").m5; @@ -377,14 +377,15 @@ pub fn main(init: std.process.Init) !u8 { } gathers.deinit(a); } - if (tensor) for (gather_k.registered) |v| { + for (gather_k.registered) |v| { + if (!tensor and !v.glm_m3_fast) continue; if (!wanted(o, gather_k.name(v))) continue; const p = try a.create(gather_k.Gather); errdefer a.destroy(p); p.* = try gather_k.Gather.init(a, device, queue, v); try gathers.append(a, p); try kernels.append(a, p.kernel()); - }; + } var h3_list: std.ArrayList(*h3_k.H3) = .empty; defer for (h3_list.items) |x| x.deinit(); var qwen3_heads: @import("metal_qwen3_heads.zig").Suite = .{}; @@ -572,6 +573,8 @@ pub fn main(init: std.process.Init) !u8 { defer idol_decoder.destroy(); const idol_vae = try @import("metal_idol_vae.zig").Suite.create(a, device, queue, &kernels, o.only); defer idol_vae.destroy(); + const glm_prompt = try @import("metal_glm_prompt.zig").Suite.create(a, device, queue, &kernels, o.only); + defer glm_prompt.destroy(); var t: g.Tally = .{}; const t0 = std.Io.Clock.awake.now(init.io); if (o.gates) { @@ -581,9 +584,7 @@ pub fn main(init: std.process.Init) !u8 { } const t1 = std.Io.Clock.awake.now(init.io); var lim: usize = 0; - if (o.limits) { - lim = try @import("metal_limits_all.zig").gate(a, init.io, device, o.offline, o.only); - } + if (o.limits) lim = try @import("metal_limits_all.zig").gate(a, init.io, device, o.offline, o.only); const t2 = std.Io.Clock.awake.now(init.io); const ms = struct { fn of(x: std.Io.Timestamp, y: std.Io.Timestamp) i64 { diff --git a/zig/tests/glm_rows_batch.zig b/zig/tests/glm_rows_batch.zig index d7e0de77358..eb63df441c1 100644 --- a/zig/tests/glm_rows_batch.zig +++ b/zig/tests/glm_rows_batch.zig @@ -64,7 +64,7 @@ pub fn headsCheck(g: *const Gpu, mm: affine_mm.Pipes, bits: u8, n: usize, k: usi bs[3].slice(u16, m * k)[i * k ..][0..k], bs[0].slice(u16, m * ldx)[i * ldx + h * k ..][0..k], ); - try g.run(mmDense, .{ mm, w.part(h, nh), ref(bs[3]), ref(bs[1]), ref(bs[4]), @as(u32, m) }); + try g.run(mmDense, .{ mm, g.p.mm_bm, w.part(h, nh), ref(bs[3]), ref(bs[1]), ref(bs[4]), @as(u32, m) }); for (0..m) |i| try eql(all[(i * nh + h) * n ..][0..n], bs[4].slice(u16, m * n)[i * n ..][0..n]); t.pairs += m * n; } @@ -117,7 +117,7 @@ pub fn splitMmCheck(g: *const Gpu, k: usize, ns: []const usize, bits: []const u8 for (ms[0..ns.len], 0..) |x, i| { const run = q.run(i); if (wide.mm(&g.p, x.q) != null and run.n % 64 == 0) { - try g.run(mmDense, .{ wide.mm(&g.p, x.q).?, x.q, ref(bs[0]), ref(bs[1]), ref(bs[3]), @as(u32, m) }); + try g.run(mmDense, .{ wide.mm(&g.p, x.q).?, g.p.mm_bm, x.q, ref(bs[0]), ref(bs[1]), ref(bs[3]), @as(u32, m) }); on_mm += 1; } else try g.run( dense, diff --git a/zig/tests/glm_rows_check.zig b/zig/tests/glm_rows_check.zig index fefe0d2c2cd..1cc09572bd3 100644 --- a/zig/tests/glm_rows_check.zig +++ b/zig/tests/glm_rows_check.zig @@ -310,6 +310,7 @@ fn partsCheck(g: *const Gpu, m: Mat, up: Mat, t: *Tally) !void { pub fn mmDense( e: mtl.ComputeEncoder, mm: affine_mm.Pipes, + bm: u32, q: affine.Affine, x: Ref, sums: Ref, @@ -317,7 +318,7 @@ pub fn mmDense( n_rows: u32, ) void { affine_mm.rowSums(e, mm, 64, x, sums, n_rows, q.k); - affine_mm.dense(e, mm, x, sums, q, y, n_rows); + affine_mm.denseBm(e, mm, x, sums, q, y, n_rows, bm); } /// dims: x rows, sorted pairs, experts, picks a row. @@ -365,7 +366,8 @@ fn gatherCheck(g: *const Gpu, m: Mat, up: Mat, t: *Tally) !void { upq.n = @intCast(r); // every expert's gate and up, dense on every x row: [2][parts][rows, r] for (0..parts) |e| for ([2]Mat{ m, up }, 0..) |w, j| { - try g.run(mmDense, .{ mm, w.part(e, parts), ref(m.x()), sums, ref(bs[1]).at(((j * parts + e) * rows * r) * 2), @as(u32, rows) }); + const y_at = ref(bs[1]).at(((j * parts + e) * rows * r) * 2); + try g.run(mmDense, .{ mm, g.p.mm_bm, w.part(e, parts), ref(m.x()), sums, y_at, @as(u32, rows) }); }; const dg = bs[1].slice(u16, 2 * parts * rows * r); const gu = bs[2].slice(u16, slots * 2 * r); @@ -384,7 +386,10 @@ fn gatherCheck(g: *const Gpu, m: Mat, up: Mat, t: *Tally) !void { for (order, 0..) |o, i| @memcpy(xs[i * k ..][0..k], m.x().slice(u16, rows * k)[@as(usize, @intCast(o)) * k ..][0..k]); const y = bs[5].slice(u16, (parts + 1) * slots * r); try g.run(mmDown, .{ mm, gate, ref(bs[4]), sums, sorted, ref(bs[5]), @as(u32, slots), @as(u32, parts) }); - for (0..parts) |e| try g.run(mmDense, .{ mm, m.part(e, parts), ref(bs[4]), sums, ref(bs[5]).at((1 + e) * slots * r * 2), @as(u32, slots) }); + for (0..parts) |e| { + const y_at = ref(bs[5]).at((1 + e) * slots * r * 2); + try g.run(mmDense, .{ mm, g.p.mm_bm, m.part(e, parts), ref(bs[4]), sums, y_at, @as(u32, slots) }); + } for (order, 0..) |o, i| { const e: usize = @intCast(picks[@intCast(o)]); try eql(y[@as(usize, @intCast(o)) * r ..][0..r], y[((1 + e) * slots + i) * r ..][0..r]); diff --git a/zig/tests/glm_rows_classes.zig b/zig/tests/glm_rows_classes.zig index 4b9f99d4f6e..978ea2eed01 100644 --- a/zig/tests/glm_rows_classes.zig +++ b/zig/tests/glm_rows_classes.zig @@ -123,11 +123,11 @@ fn rowsLaunch(e: mtl.ComputeEncoder, p: *const wide.Pipes, q: affine.Affine, x: wide.dense(p, e, q, .{ .in = (affine.Ref{ .buf = x }).at(at), .ldx = q.k, .out = .{ .buf = out }, .ldo = q.n, .rows = m }); } -fn mmLaunch(e: mtl.ComputeEncoder, mm: affine_mm.Pipes, q: affine.Affine, x: mtl.Buffer, sums: mtl.Buffer, out: mtl.Buffer, m: u32) void { +fn mmLaunch(e: mtl.ComputeEncoder, mm: affine_mm.Pipes, bm: u32, q: affine.Affine, x: mtl.Buffer, sums: mtl.Buffer, out: mtl.Buffer, m: u32) void { const xr: affine.Ref = .{ .buf = x }; const sr: affine.Ref = .{ .buf = sums }; affine_mm.rowSums(e, mm, 64, xr, sr, m, q.k); - affine_mm.dense(e, mm, xr, sr, q, affine.Ref{ .buf = out }, m); + affine_mm.denseBm(e, mm, xr, sr, q, affine.Ref{ .buf = out }, m, bm); } /// Each class at its widths (g64): decode rows (alone == windowed) and the prompt's product vs fp64, every column. @@ -167,7 +167,7 @@ pub fn check(p: *const wide.Pipes, device: mtl.Device, queue: mtl.Queue) !Tally // prompt: the chunk's product at rows 0 and 32; on the row kernels every row's bits equal the decode's const mm: ?affine_mm.Pipes = wide.mm(p, q); // prompt.zig's (2: the routed experts' gathers) const on_mm = mm != null; - if (mm) |pipes| try submit(queue, mmLaunch, .{ pipes, q, bufs[3], bufs[6], bufs[5], prompt_rows }) else try submit(queue, rowsLaunch, .{ p, q, bufs[3], 0, bufs[5], prompt_rows }); + if (mm) |pipes| try submit(queue, mmLaunch, .{ pipes, p.mm_bm, q, bufs[3], bufs[6], bufs[5], prompt_rows }) else try submit(queue, rowsLaunch, .{ p, q, bufs[3], 0, bufs[5], prompt_rows }); t.worst = 0; const pitch = if (on_mm) np else n; for ([_]usize{ 0, prompt_rows - 1 }) |i| try against(q, w, s, b, x, bufs[5].slice(u16, prompt_rows * pitch), pitch, i, &t, 1); diff --git a/zig/tests/glm_rows_speed_prompt.zig b/zig/tests/glm_rows_speed_prompt.zig index 0aab170c6ec..55cab5c132f 100644 --- a/zig/tests/glm_rows_speed_prompt.zig +++ b/zig/tests/glm_rows_speed_prompt.zig @@ -25,11 +25,11 @@ fn headsRows(e: mtl.ComputeEncoder, i: usize, p: *const wide.Pipes, pool: Pool, wide.perHead(p, e, q, H, .{ .in = rf(io.x), .ldx = ldx, .out = rf(io.y), .ldo = q.n, .rows = PM }, kx, q.n / H); } /// The same as one affine_mm batch (prompt.zig headsMm). -fn headsMm(e: mtl.ComputeEncoder, i: usize, mm: tf.affine_mm.Pipes, pool: Pool, io: Io, ldx: u32, kx: u32) void { +fn headsMm(e: mtl.ComputeEncoder, i: usize, mm: tf.affine_mm.Pipes, bm: u32, pool: Pool, io: Io, ldx: u32, kx: u32) void { var head = pool.at(i); head.n /= H; tf.affine_mm.rowSumsAt(e, mm, 64, rf(io.x), rf(io.z), PM, H * kx, ldx); - tf.affine_mm.denseBatch(e, mm, rf(io.x), rf(io.z), head, rf(io.y), PM, H, .{ + tf.affine_mm.denseBatchBm(e, mm, rf(io.x), rf(io.z), head, rf(io.y), PM, H, .{ .x_row = @intCast(ldx), .y_row = @intCast(H * head.n), .sums_row = H, @@ -37,7 +37,7 @@ fn headsMm(e: mtl.ComputeEncoder, i: usize, mm: tf.affine_mm.Pipes, pool: Pool, .y_batch = @intCast(head.n), .sums_batch = 1, .w_batch = @intCast(head.n), - }); + }, bm); } fn ehRows(e: mtl.ComputeEncoder, i: usize, p: *const wide.Pipes, eh: mtl.Buffer, io: Io) void { _ = i; @@ -49,10 +49,10 @@ fn chunkRows(e: mtl.ComputeEncoder, i: usize, p: *const wide.Pipes, pool: Pool, const q = pool.at(i); wide.dense(p, e, q, .{ .in = rf(io.x), .ldx = q.k, .out = rf(io.y), .ldo = q.n, .rows = PM }); } -fn chunkMm(e: mtl.ComputeEncoder, i: usize, mm: tf.affine_mm.Pipes, pool: Pool, io: Io) void { +fn chunkMm(e: mtl.ComputeEncoder, i: usize, mm: tf.affine_mm.Pipes, bm: u32, pool: Pool, io: Io) void { const q = pool.at(i); tf.affine_mm.rowSums(e, mm, 64, rf(io.x), rf(io.z), PM, q.k); - tf.affine_mm.dense(e, mm, rf(io.x), rf(io.z), q, rf(io.y), PM); + tf.affine_mm.denseBm(e, mm, rf(io.x), rf(io.z), q, rf(io.y), PM, bm); } /// A prompt chunk's products where oQ's paths differ from uniform's, ms a chunk of 2048 rows. @@ -64,13 +64,13 @@ pub fn prompt(b: *Bench, k: *const kernels.Kernels, p: *const wide.Pipes) !void defer eq.deinit(); std.debug.print(" embed_q q8 per-head rows {d:8.2} affine_mm batch {d:8.2} (x11 a chunk)\n", .{ try b.time(headsRows, .{ p, eq, b.io, @as(u32, QR), @as(u32, 256) }) / 1e3, - try b.time(headsMm, .{ p.mm8, eq, b.io, @as(u32, QR), @as(u32, 256) }) / 1e3, + try b.time(headsMm, .{ p.mm8, p.mm_bm, eq, b.io, @as(u32, QR), @as(u32, 256) }) / 1e3, }); const uo = try Pool.init(b.device, H * 256, 512, 8, 1, 2); defer uo.deinit(); std.debug.print(" unembed_out q8 per-head rows {d:8.2} affine_mm batch {d:8.2} (x11 a chunk)\n", .{ try b.time(headsRows, .{ p, uo, b.io, @as(u32, H * 512), @as(u32, 512) }) / 1e3, - try b.time(headsMm, .{ p.mm8, uo, b.io, @as(u32, H * 512), @as(u32, 512) }) / 1e3, + try b.time(headsMm, .{ p.mm8, p.mm_bm, uo, b.io, @as(u32, H * 512), @as(u32, 512) }) / 1e3, }); { // the MTP head's bf16 eh_proj [4096, 8192] over the chunk (prompt.zig mtp) const eh = try buf(b.device, D * 2 * D * 2); @@ -86,12 +86,13 @@ pub fn prompt(b: *Bench, k: *const kernels.Kernels, p: *const wide.Pipes) !void defer m8.deinit(); const m4 = try Pool.init(b.device, s[0], s[1], 4, 1, 2); defer m4.deinit(); - const t8 = try b.time(chunkMm, .{ p.mm8, m8, b.io }); - const t4 = try b.time(chunkMm, .{ k.mm_bf16, m4, b.io }); + const t8 = try b.time(chunkMm, .{ p.mm8, p.mm_bm, m8, b.io }); + const k_bm: u32 = if (k.m3_fast) 32 else 64; + const t4 = try b.time(chunkMm, .{ k.mm_bf16, k_bm, m4, b.io }); for ([_]u8{ 5, 6 }) |bits| { const m = try Pool.init(b.device, s[0], s[1], bits, 1, 2); defer m.deinit(); - const on_mm = if (wide.mm(p, m.at(0))) |mm| try b.time(chunkMm, .{ mm, m, b.io }) else 0; + const on_mm = if (wide.mm(p, m.at(0))) |mm| try b.time(chunkMm, .{ mm, p.mm_bm, m, b.io }) else 0; std.debug.print( " [{d}, {d}] q{d} rows {d:8.2} affine_mm {d:8.2} (affine_mm q8 {d:.2}, q4 {d:.2})\n", .{ s[0], s[1], bits, try b.time(chunkRows, .{ p, m, b.io }) / 1e3, on_mm / 1e3, t8 / 1e3, t4 / 1e3 },