diff --git a/CHANGELOG.md b/CHANGELOG.md index 25e67b0297c..8774e7310ce 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-5.3-Flash on Metal: routed experts stored in the official FP8 checkpoint's format (E4M3 codes, 128 x 128 f32 block scales) load as stored, and a combined checkpoint can point at whole FP8 shards, since a shard's tensors are read only where the index maps them. On an M5 Ultra, FP8 experts beside the 8-bit backbone decode prose at 60.8 tok/s against 55.7 with MLX 8-bit experts, with the same per-token loss (#3682). + - Qwen3.8-27B on Metal before M5: a drafted window's rows run the decode attention in pairs over the keys below the window, so at a 32K prompt on an M3 Ultra drafted decode is 24% faster at one stream and 29% at eight with every reply unchanged; `TF_QWEN27_JOIN=0` keeps the unpaired pipelines (#3661). - App: opening an Approvals task whose conversation is archived, deleted or not loaded yet shows a clear "Conversation unavailable" view instead of a blank Thread window (#3393, fixes #3387). Thanks to @sx4im. diff --git a/zig/kernels/metal/glm_rows.metal b/zig/kernels/metal/glm_rows.metal index feff030cdb1..0acc3d1ecb0 100644 --- a/zig/kernels/metal/glm_rows.metal +++ b/zig/kernels/metal/glm_rows.metal @@ -33,6 +33,56 @@ inline void glm_rows_pass(const device uint8_t* w, const device bfloat* s, const for (int j = 0; j < cols; j++) o0[size_t(m + r) * d.ldo + j] = bfloat(acc[r][j]); } +// Two E4M3 codes of a word (bytes 0 and 2) as a half2 of value / 256, exact: the magnitude bits as a half's, the sign. +inline half2 glm_f8_h2(uint word) { return as_type(((word & 0x007F007Fu) << 7) | ((word & 0x00800080u) << 8)); } + +// RPS rows of E4M3 codes at w (K a row) with sc their 128-row block's f32 scales: tf_rp_rows_at's lanes and sums. +template +inline void glm_f8_rows(const device uint8_t* w, const device float* sc, const device bfloat* x, int K, uint lane, + thread float (*acc)[RPS]) { + const int FULL = K / 512 * 512; + w += lane * 16; + sc += lane / 8; + const int xl = int(lane) * 16; + for (int j = 0; j < RPS; j++) acc[0][j] = 0.0f; + for (int k0 = 0; k0 <= FULL; k0 += 512) { + if (k0 == FULL && !(FULL < K && int(lane) < (K - FULL) / 16)) break; + float xt[16]; + for (int i = 0; i < 16; i++) xt[i] = float(x[xl + k0 + i]); + const float s = sc[0] * 256.0f; + for (int j = 0; j < RPS; j++) { + const uint4 raw = *(const device uint4*)(w + j * K); + float q[16]; + for (int i = 0; i < 4; i++) { + const half2 a = glm_f8_h2(raw[i]), b = glm_f8_h2(raw[i] >> 8); + q[4 * i] = float(a.x); q[4 * i + 1] = float(b.x); q[4 * i + 2] = float(a.y); q[4 * i + 3] = float(b.y); + } + float accum = 0.0f; + for (int i = 0; i < 4; i++) + accum += (xt[4 * i] * q[4 * i] + xt[4 * i + 1] * q[4 * i + 1] + xt[4 * i + 2] * q[4 * i + 2] + + xt[4 * i + 3] * q[4 * i + 3]); + acc[0][j] += s * accum; + } + w += 512; + sc += 4; + } + for (int j = 0; j < RPS; j++) acc[0][j] = simd_sum(acc[0][j]); +} + +// Expert e's rows [row0, row0 + RPS) of a stack [experts, n, K]: affine (S, B bf16 at `group`), or F8 (S f32 blocks). +template +inline void glm_expert_rows(const device uint32_t* W, const device bfloat* S, const device bfloat* B, int e, int n, + int row0, const device bfloat* x, int K, int group, uint lane, thread float (*acc)[RPS]) { + const size_t at = size_t(e) * n + row0; + if (F8) { + const device float* sc = (const device float*)S + (size_t(e) * (n / 128) + row0 / 128) * (K / 128); + glm_f8_rows((const device uint8_t*)W + at * K, sc, x, K, lane, acc); + } else { + const size_t kb = size_t(K) * BITS / 8, kg = size_t(K / group); + tf_rp_rows((const device uint8_t*)W + at * kb, S + at * kg, B + at * kg, x, K, group, lane, acc); + } +} + // The three-row passes before a window's pairs and last row: four rows take two pairs, not a three and a one. inline int glm_threes(int rows) { return rows / 3 - (rows % 3 == 1 && rows > 3 ? 1 : 0); } @@ -71,7 +121,7 @@ template } // Slot y through expert ids[y] on x row y / repeat (GLU: gate W and up W2, SwiGLU'd); grid (n / 8, slots). -template +template [[kernel]] void glm_rows_ids(const device bfloat* X [[buffer(0)]], const device uint32_t* W [[buffer(1)]], const device bfloat* S [[buffer(2)]], const device bfloat* B [[buffer(3)]], constant GlmPickDims& d [[buffer(4)]], device bfloat* OUT [[buffer(5)]], @@ -89,14 +139,12 @@ template if (int(lane) < cols) out[lane] = bfloat(0.0f); return; } - const size_t at = size_t(expert) * d.n + row0; - const size_t kb = size_t(d.k) * BITS / 8, kg = size_t(d.k / d.group); const device bfloat* x = X + size_t(slot / d.repeat) * d.k; float acc[1][4]; - tf_rp_rows<4, 1, BITS, false>((const device uint8_t*)W + at * kb, S + at * kg, B + at * kg, x, d.k, d.group, lane, acc); + glm_expert_rows<4, BITS, F8>(W, S, B, expert, d.n, row0, x, d.k, d.group, lane, acc); if (GLU) { float up[1][4]; - tf_rp_rows<4, 1, BITS, false>((const device uint8_t*)W2 + at * kb, S2 + at * kg, B2 + at * kg, x, d.k, d.group, lane, up); + glm_expert_rows<4, BITS, F8>(W2, S2, B2, expert, d.n, row0, x, d.k, d.group, lane, up); if (lane == 0) for (int j = 0; j < cols; j++) out[j] = glm_rows_glu(acc[0][j], up[0][j], d.lim); } else if (lane == 0) { @@ -104,8 +152,8 @@ template } } -// Slots as glm_rows_ids (BITS), then X2's rows through the shared expert (SBITS; GLU: gate then up rows) into OUT2. -template // RPS columns a simdgroup; KC: k compiled in +// Slots as glm_rows_ids (BITS, or F8), then X2's rows through the shared expert (SBITS; GLU: gate then up) into OUT2. +template // RPS columns a simdgroup; KC: k [[kernel]] void glm_moe_rows(const device bfloat* X [[buffer(0)]], const device uint32_t* W [[buffer(1)]], const device bfloat* S [[buffer(2)]], const device bfloat* B [[buffer(3)]], constant GlmPickDims& d [[buffer(4)]], device bfloat* OUT [[buffer(5)]], @@ -133,16 +181,12 @@ template // RPS columns if (int(lane) < cols) out[lane] = bfloat(0.0f); return; } - const size_t at = size_t(expert) * d.n + row0; - const size_t kb = size_t(K) * BITS / 8; x = X + size_t(y / d.repeat) * K; float acc[1][RPS]; - tf_rp_rows((const device uint8_t*)W + at * kb, S + at * kg, B + at * kg, x, K, d.group, lane, - acc); + glm_expert_rows(W, S, B, expert, d.n, row0, x, K, d.group, lane, acc); if (GLU) { float up[1][RPS]; - tf_rp_rows((const device uint8_t*)W2 + at * kb, S2 + at * kg, B2 + at * kg, x, K, d.group, - lane, up); + glm_expert_rows(W2, S2, B2, expert, d.n, row0, x, K, d.group, lane, up); if (lane == 0) for (int j = 0; j < cols; j++) out[j] = glm_rows_glu(acc[0][j], up[0][j], d.lim); } else if (lane == 0) { @@ -172,7 +216,7 @@ template // RPS columns // glm_moe_rows by unique expert (uids, umem, ucount): a simdgroup a pick, z = slots the shared; glm_moe_rows's sums. #define GLM_MAXR 16 -template +template [[max_total_threads_per_threadgroup(32 * GLM_MAXR)]] [[kernel]] void glm_moe_rows_u(const device bfloat* X [[buffer(0)]], const device uint32_t* W [[buffer(1)]], const device bfloat* S [[buffer(2)]], const device bfloat* B [[buffer(3)]], @@ -197,16 +241,12 @@ template const int pick = umem[z * GLM_MAXR + m]; if (pick < 0) return; device bfloat* out = OUT + size_t(pick) * d.ldo + row0; - const size_t at = size_t(uids[z]) * d.n + row0; - const size_t kb = size_t(K) * BITS / 8; const device bfloat* x = X + size_t(pick / d.repeat) * K; float acc[1][RPS]; - tf_rp_rows((const device uint8_t*)W + at * kb, S + at * kg, B + at * kg, x, K, d.group, lane, - acc); + glm_expert_rows(W, S, B, uids[z], d.n, row0, x, K, d.group, lane, acc); if (GLU) { float up[1][RPS]; - tf_rp_rows((const device uint8_t*)W2 + at * kb, S2 + at * kg, B2 + at * kg, x, K, d.group, - lane, up); + glm_expert_rows(W2, S2, B2, uids[z], d.n, row0, x, K, d.group, lane, up); if (lane == 0) for (int j = 0; j < cols; j++) out[j] = glm_rows_glu(acc[0][j], up[0][j], d.lim); } else if (lane == 0) { @@ -236,7 +276,7 @@ template } // Expert e's sorted pairs: GLU x row order[i] / repeat to out row i, else x row i to row order[i]; grid (n / 8, e). -template +template [[kernel]] void glm_rows_sorted(const device bfloat* X [[buffer(0)]], const device uint32_t* W [[buffer(1)]], const device bfloat* S [[buffer(2)]], const device bfloat* B [[buffer(3)]], constant GlmPickDims& d [[buffer(4)]], device bfloat* OUT [[buffer(5)]], @@ -249,20 +289,17 @@ template if (row0 >= d.n) return; const int e = int(tg.y); const int lo = offsets[e], hi = e + 1 < d.experts ? offsets[e + 1] : d.slots; - const size_t at = size_t(e) * d.n + row0; - const size_t kb = size_t(d.k) * BITS / 8, kg = size_t(d.k / d.group); - const device uint8_t* w = (const device uint8_t*)W + at * kb; const int cols = metal::min(4, d.n - row0); #pragma clang loop unroll(disable) for (int i = lo; i < hi; i++) { const int src = GLU ? order[i] / d.repeat : i; const int dst = GLU ? i : order[i]; float acc[1][4]; - tf_rp_rows<4, 1, BITS, false>(w, S + at * kg, B + at * kg, X + size_t(src) * d.k, d.k, d.group, lane, acc); + glm_expert_rows<4, BITS, F8>(W, S, B, e, d.n, row0, X + size_t(src) * d.k, d.k, d.group, lane, acc); device bfloat* out = OUT + size_t(dst) * d.ldo + row0; if (GLU) { float up[1][4]; - tf_rp_rows<4, 1, BITS, false>((const device uint8_t*)W2 + at * kb, S2 + at * kg, B2 + at * kg, X + size_t(src) * d.k, d.k, d.group, lane, up); + glm_expert_rows<4, BITS, F8>(W2, S2, B2, e, d.n, row0, X + size_t(src) * d.k, d.k, d.group, lane, up); if (lane == 0) for (int j = 0; j < cols; j++) out[j] = glm_rows_glu(acc[0][j], up[0][j], d.lim); } else if (lane == 0) { @@ -402,3 +439,19 @@ GLM_MOE_AT(4) GLM_MOE_AT(5) GLM_MOE_AT(6) GLM_MOE_AT(8) + +// The FP8 checkpoint's routed experts (E4M3, 128 x 128 f32 scales) beside the 8-bit shared expert. +template [[host_name("glm_rows_ids_f8")]] [[kernel]] decltype(glm_rows_ids<8, false, true>) glm_rows_ids<8, false, true>; +template [[host_name("glm_rows_glu_ids_f8")]] [[kernel]] decltype(glm_rows_ids<8, true, true>) glm_rows_ids<8, true, true>; +template [[host_name("glm_rows_sorted_f8")]] [[kernel]] + decltype(glm_rows_sorted<8, false, true>) glm_rows_sorted<8, false, true>; +template [[host_name("glm_rows_glu_sorted_f8")]] [[kernel]] + decltype(glm_rows_sorted<8, true, true>) glm_rows_sorted<8, true, true>; +template [[host_name("glm_moe_rows_f8_s8")]] [[kernel]] + decltype(glm_moe_rows<8, 8, false, 4, 0, true>) glm_moe_rows<8, 8, false, 4, 0, true>; +template [[host_name("glm_moe_rows_glu_f8_s8")]] [[kernel]] + decltype(glm_moe_rows<8, 8, true, 4, 0, true>) glm_moe_rows<8, 8, true, 4, 0, true>; +template [[host_name("glm_moe_rows_u_f8_s8")]] [[kernel]] + decltype(glm_moe_rows_u<8, 8, false, 4, true>) glm_moe_rows_u<8, 8, false, 4, true>; +template [[host_name("glm_moe_rows_glu_u_f8_s8")]] [[kernel]] + decltype(glm_moe_rows_u<8, 8, true, 4, true>) glm_moe_rows_u<8, 8, true, 4, true>; diff --git a/zig/src/core/contract/glm_rows_records.zig b/zig/src/core/contract/glm_rows_records.zig index ed6250b307a..2c6d16f6ae3 100644 --- a/zig/src/core/contract/glm_rows_records.zig +++ b/zig/src/core/contract/glm_rows_records.zig @@ -26,6 +26,8 @@ pub const records = [_]M{ .{ .name = "glm moe rows glu u q6 glm_moe_rows_glu_u_q6_s8", .threads = 512, .tg_memory = 0, .reserved = 512 }, .{ .name = "glm moe rows u q8 glm_moe_rows_u_q8_s8", .threads = 512, .tg_memory = 0, .reserved = 512 }, .{ .name = "glm moe rows glu u q8 glm_moe_rows_glu_u_q8_s8", .threads = 512, .tg_memory = 0, .reserved = 512 }, + .{ .name = "glm moe rows u f8 glm_moe_rows_u_f8_s8", .threads = 512, .tg_memory = 0, .reserved = 512 }, + .{ .name = "glm moe rows glu u f8 glm_moe_rows_glu_u_f8_s8", .threads = 512, .tg_memory = 0, .reserved = 512 }, }; test "the GLM row launches fit every Apple family" { diff --git a/zig/src/families/glm/affine.zig b/zig/src/families/glm/affine.zig index cd80ddbb1c0..9fded397eaa 100644 --- a/zig/src/families/glm/affine.zig +++ b/zig/src/families/glm/affine.zig @@ -24,7 +24,7 @@ pub const max_runs = 6; /// A run of a split stack: one member (0.6.6 calls each apart), rows [row, row + n) of the fused output, bytes its own. pub const Run = struct { w: Ref, s: Ref, b: Ref, row: u32, n: u32, bits: u8, group: u16 }; -/// An MLX affine matrix: w [n, k bits / 32] u32, s and b [n, k / group] bf16 (stacked: [e, n, ...]). +/// An MLX affine matrix: w [n, k bits / 32] u32, s and b [n, k / group] bf16 (stacked: [e, n, ...]); or `fp8`. pub const Affine = struct { w: Ref, s: Ref, @@ -35,6 +35,7 @@ pub const Affine = struct { group: u16, more: u8 = 0, // runs past the first, whose bytes and width are the matrix's own: 0 for one width runs: [max_runs - 1]Run = undefined, + fp8: bool = false, // the FP8 checkpoint's E4M3 codes [n, k], s its f32 scales [n / 128, k / 128], no b pub fn width(q: Affine) Width { return .{ .bits = q.bits, .group = q.group }; @@ -62,6 +63,20 @@ pub fn bytes(n: usize, k: usize, w: Width) usize { return wBytes(n, k, w) + 2 * sBytes(n, k, w); } +/// The FP8 checkpoint's square scale blocks: a scale for each 128 rows by 128 columns. +pub const fp8_block = 128; + +/// Bytes of an FP8 [n, k]'s f32 scales, [n / 128, k / 128]; null unless n and k are whole blocks. +pub fn fp8Scales(n: usize, k: usize) ?usize { + if (n == 0 or k == 0 or n % fp8_block != 0 or k % fp8_block != 0) return null; + return (n / fp8_block) * (k / fp8_block) * 4; +} + +/// Bytes of an FP8 [n, k]: a byte a code, then its scales. +pub fn fp8Bytes(n: usize, k: usize) usize { + return n * k + (fp8Scales(n, k) orelse 0); +} + /// [n, k]'s stored shapes at `w`: u32 words [n, k bits / 32], bf16 tables [n, k / group]; null when k does not pack. pub fn shapes(n: usize, k: usize, w: Width) ?[2][2]usize { if (k == 0 or k % w.group != 0 or k * w.bits % 32 != 0) return null; @@ -77,10 +92,15 @@ pub fn cut(lo: usize, k: usize, w: Width) ?[2][2]usize { /// Matrices (each run of a split stack) by width, for a plan's summary. pub const Tally = struct { count: [9][3]u32 = @splat(@splat(0)), // by bits, then group 32, 64, 128 + fp8: u32 = 0, pub fn add(t: *Tally, v: anytype) void { const T = @TypeOf(v); if (T == Affine) { + if (v.fp8) { + t.fp8 += 1; + return; + } for (0..@as(usize, v.more) + 1) |i| { const r = v.run(i); if (r.n > 0 and r.bits > 0) t.count[r.bits][std.math.log2_int(u16, r.group) - 5] += 1; @@ -105,6 +125,7 @@ pub const Tally = struct { const sep = if (n == 0) "" else ", "; n += (std.fmt.bufPrint(buf[n..], "{s}{d}-bit/{d} x{d}", .{ sep, bits, @as(u32, 32) << @intCast(gi), x }) catch return buf[0..n]).len; }; + if (t.fp8 > 0) n += (std.fmt.bufPrint(buf[n..], "{s}FP8 E4M3/128x128 x{d}", .{ if (n == 0) "" else ", ", t.fp8 }) catch return buf[0..n]).len; return buf[0..n]; } }; diff --git a/zig/src/families/glm/fp8.zig b/zig/src/families/glm/fp8.zig new file mode 100644 index 00000000000..12a872680d0 --- /dev/null +++ b/zig/src/families/glm/fp8.zig @@ -0,0 +1,52 @@ +//! The FP8 checkpoint's routed experts as stored (E4M3 codes, f32 128 x 128 block scales): loading and kernels. +const std = @import("std"); +const affine = @import("affine.zig"); +const quant = @import("quant.zig"); +const prefix = @import("weights.zig").prefix; + +/// glm_rows.metal's FP8 routed-expert kernels, in `names` order. +pub const Kernel = enum { moe, moe_glu, moe_u, moe_glu_u, sorted, glu_sorted, ids, glu_ids }; +pub const names = [_][:0]const u8{ + "glm_moe_rows_f8_s8", "glm_moe_rows_glu_f8_s8", "glm_moe_rows_u_f8_s8", "glm_moe_rows_glu_u_f8_s8", + "glm_rows_sorted_f8", "glm_rows_glu_sorted_f8", "glm_rows_ids_f8", "glm_rows_glu_ids_f8", +}; + +/// Whether layer i's expert e's `proj` is stored as the FP8 checkpoint's codes and block scales. +pub fn isExpert(l: anytype, i: usize, e: usize, proj: []const u8) bool { + return l.has(prefix ++ "layers.{d}.mlp.experts.{d}.{s}.weight_scale_inv", .{ i, e, proj }); +} + +/// Experts [lo, lo + e) of layer i's `proj` [n, k]: codes stacked [e, n, k], then scales [e, n / 128, k / 128]. +pub fn experts(l: anytype, i: usize, proj: []const u8, n: usize, k: usize, whole: bool, lo: usize, e: usize) !affine.Affine { + var first: [200]u8 = undefined; + const name0 = try std.fmt.bufPrint(&first, prefix ++ "layers.{d}.mlp.experts.{d}.{s}", .{ i, lo, proj }); + if (!whole) { + quant.say("glm: {s} is FP8, which loads whole on one Mac", .{name0}); + return error.UnsupportedWidth; + } + const sb = affine.fp8Scales(n, k) orelse { + quant.say("glm: {s} is [{d}, {d}], not whole 128 x 128 scale blocks", .{ name0, n, k }); + return error.UnexpectedTensor; + }; + const w = l.take(e * n * k); + const out: affine.Affine = .{ .w = w, .s = l.take(e * sb), .b = l.take(0), .n = @intCast(n), .k = @intCast(k), .bits = 8, .group = affine.fp8_block, .fp8 = true }; + for (0..e) |x| { + var buf: [200]u8 = undefined; + const module = try std.fmt.bufPrint(&buf, prefix ++ "layers.{d}.mlp.experts.{d}.{s}", .{ i, lo + x, proj }); + if (!isExpert(l, i, lo + x, proj)) { + quant.say("glm: {s} is FP8 and {s} is not; one stack holds both", .{ name0, module }); + return error.MixedWidths; + } + var a: [240]u8 = undefined; + var b: [240]u8 = undefined; + const wn = try std.fmt.bufPrint(&a, "{s}.weight", .{module}); + const sn = try std.fmt.bufPrint(&b, "{s}.weight_scale_inv", .{module}); + const ws = l.names.get(wn) orelse return error.MissingTensor; + const ss = l.names.get(sn).?; + try @TypeOf(l.*).expect(ws, wn, .f8_e4m3, &.{ n, k }); + try @TypeOf(l.*).expect(ss, sn, .f32, &.{ n / affine.fp8_block, k / affine.fp8_block }); + try l.copyTo(ws, out.w.at(x * n * k)); + try l.copyTo(ss, out.s.at(x * sb)); + } + return out; +} diff --git a/zig/src/families/glm/load_plan.zig b/zig/src/families/glm/load_plan.zig index b677fe2c5c8..bbcc943c53f 100644 --- a/zig/src/families/glm/load_plan.zig +++ b/zig/src/families/glm/load_plan.zig @@ -80,10 +80,16 @@ pub fn expertBytes(l: anytype, i: usize) !usize { const every = i == c.layers; const m: usize = if (every) c.moe_inter else c.inter[1] - c.inter[0]; const lo: usize = if (every) 0 else c.own[0]; - const per = affine.bytes(m, D, try l.widths.expert(i, lo, "gate_proj")) + affine.bytes(m, D, try l.widths.expert(i, lo, "up_proj")) + affine.bytes(D, m, try l.widths.expert(i, lo, "down_proj")); + const per = try projBytes(l, i, lo, "gate_proj", m, D) + try projBytes(l, i, lo, "up_proj", m, D) + try projBytes(l, i, lo, "down_proj", D, m); return (if (every) c.experts else c.own[1] - c.own[0]) * per + 9 * 256; } +/// An expert's `proj` [n, k]: the FP8 checkpoint's codes and scales, else its affine width's. +fn projBytes(l: anytype, i: usize, e: usize, proj: []const u8, n: usize, k: usize) !usize { + if (@import("fp8.zig").isExpert(l, i, e, proj)) return affine.fp8Bytes(n, k); + return affine.bytes(n, k, try l.widths.expert(i, e, proj)); +} + /// A stack's bytes: its rows, padded to `pad` a run (a part each once widths differ), at the costliest bytes a row. fn stackBytes(l: anytype, comptime fmt: []const u8, args: anytype, parts: []const []const u8, rows: usize, k: usize, pad: usize) !usize { var name: [200]u8 = undefined; diff --git a/zig/src/families/glm/names.zig b/zig/src/families/glm/names.zig index 1294fcf8846..f84d34248f5 100644 --- a/zig/src/families/glm/names.zig +++ b/zig/src/families/glm/names.zig @@ -42,7 +42,8 @@ pub fn read(gpa: std.mem.Allocator, arena: std.mem.Allocator, dir: []const u8, m if (f.size > st.index.max_bytes) return error.BadIndex; const doc = try std.json.parseFromSliceLeaky(std.json.Value, arena, f.bytes[0..f.size], .{ .allocate = .alloc_always }); var files: std.StringArrayHashMapUnmanaged(void) = .empty; - var it = (try st.index.weightMap(doc)).iterator(); + const map = try st.index.weightMap(doc); + var it = map.iterator(); while (it.next()) |kv| try files.put(arena, kv.value_ptr.string, {}); for (files.keys(), 0..) |name, si| { const full = try std.fmt.allocPrintSentinel(arena, "{s}/{s}", .{ dir, name }, 0); @@ -61,6 +62,9 @@ pub fn read(gpa: std.mem.Allocator, arena: std.mem.Allocator, dir: []const u8, m const data = 8 + hlen; const entries = try st.parseHeaderPrefixes(arena, header, size - data, &.{ lm, "language_model.", "lm_head." }); for (entries.keys(), entries.values()) |name_in_file, entry| { + // the index's shard only: a combined checkpoint's shards hold tensors it takes from elsewhere + const listed = map.get(name_in_file) orelse continue; + if (listed != .string or !std.mem.eql(u8, listed.string, name)) continue; var buf: [240]u8 = undefined; const tensor = (try original(&buf, name_in_file, mtp_layer)) orelse continue; const got = try names.getOrPut(arena, try arena.dupe(u8, tensor)); diff --git a/zig/src/families/glm/weights.zig b/zig/src/families/glm/weights.zig index a2c7fdd0e8a..f90a06c437b 100644 --- a/zig/src/families/glm/weights.zig +++ b/zig/src/families/glm/weights.zig @@ -8,6 +8,7 @@ const quant = @import("quant.zig"); const affine = @import("affine.zig"); const layout = @import("names.zig"); const load_plan = @import("load_plan.zig"); +const fp8 = @import("fp8.zig"); pub const Width = quant.Width; @@ -104,7 +105,7 @@ const Loader = struct { }; } - fn expect(s: Src, name: []const u8, dtype: st.DType, shape: []const usize) !void { + pub fn expect(s: Src, name: []const u8, dtype: st.DType, shape: []const usize) !void { if (s.dtype == dtype and s.rank == shape.len and std.mem.eql(usize, s.shape[0..s.rank], shape)) return; quant.say("glm: {s} is {t} {any}; the kernels read {t} {any}", .{ name, s.dtype, s.shape[0..s.rank], dtype, shape }); return error.UnexpectedTensor; @@ -137,14 +138,14 @@ const Loader = struct { l.w.bytes += len; } - fn take(l: *Loader, len: usize) Ref { + pub fn take(l: *Loader, len: usize) Ref { const at = l.cur_at; l.cur_at = std.mem.alignForward(usize, at + len, 256); if (l.cur_at > l.cur_len) std.debug.panic("glm: a weights buffer of {d} bytes is too small for {d}", .{ l.cur_len, l.cur_at }); return .{ .buf = l.cur orelse .{ .id = undefined }, .off = at }; } - fn copyTo(l: *Loader, s: Src, dst: Ref) !void { + pub fn copyTo(l: *Loader, s: Src, dst: Ref) !void { if (l.dry) return; try l.copies.append(l.gpa, .{ .shard = s.shard, .off = s.off, .len = s.len, .dst = dst.addr() }); } @@ -328,6 +329,7 @@ const Loader = struct { const every = i == l.c.layers; // the MTP layer: every expert whole on every Mac (its drafts need no exchange) const lo = if (every) 0 else l.c.own[0]; const e = (if (every) l.c.experts else l.c.own[1]) - lo; + if (fp8.isExpert(l, i, lo, proj)) return fp8.experts(l, i, proj, n_all, k_all, part == .whole, lo, e); const in_lo: usize = l.c.inter[0]; const in_n: usize = l.c.inter[1] - l.c.inter[0]; const n = if (part == .rows) in_n else n_all; @@ -489,7 +491,7 @@ const Loader = struct { const by_rows = c.byRows() and i != c.layers; moe.gate = try l.experts(i, "gate_proj", c.moe_inter, D, if (by_rows) .rows else .whole); moe.up = try l.experts(i, "up_proj", c.moe_inter, D, if (by_rows) .rows else .whole); - if (!std.meta.eql(moe.gate.width(), moe.up.width())) { // one launch takes both, SwiGLU'd + if (!std.meta.eql(moe.gate.width(), moe.up.width()) or moe.gate.fp8 != moe.up.fp8) { // one launch, SwiGLU'd var buf: [96]u8 = undefined; return mixed(try std.fmt.bufPrint(&buf, "layer {d}'s routed gate_proj", .{i}), moe.gate.width(), "up_proj", moe.up.width()); } diff --git a/zig/src/families/glm/wide.zig b/zig/src/families/glm/wide.zig index 2d1508b103c..52cc962efd4 100644 --- a/zig/src/families/glm/wide.zig +++ b/zig/src/families/glm/wide.zig @@ -5,6 +5,7 @@ const sources = @import("kernel_sources"); const affine = @import("affine.zig"); const affine_mm = @import("../../core/affine_mm.zig"); const kernels = @import("kernels.zig"); +const fp8 = @import("fp8.zig"); pub const gather = @import("gather.zig"); const Affine = affine.Affine; const Ref = affine.Ref; @@ -31,6 +32,7 @@ pub const Pipes = struct { moe_glu: [nw]mtl.Pipeline, // the same through gate and up, SwiGLU'd moe_u: [nw]mtl.Pipeline, // `moe` by unique expert (2+ rows): an expert's weights read once for the rows that picked it moe_glu_u: [nw]mtl.Pipeline, + f8: [fp8.names.len]mtl.Pipeline, // FP8 routed experts (Affine.fp8), by fp8.Kernel gather: [2]mtl.Pipeline, // four gathered rows sharing the sorted row arithmetic bf16: mtl.Pipeline, // an unquantized matrix (the MTP head's eh_proj, scalar path; decode-side path keeps this) bf16_nax: ?mtl.Pipeline, // bf16 GEMM on tensor units: prefill-side eh_proj replacement for `bf16` (null: `bf16` serves) @@ -57,6 +59,7 @@ pub const Pipes = struct { &p.moe_glu, &p.moe_u, &p.moe_glu_u, + &p.f8, &p.embed, &p.kda_fg, }) |set| for (set) |x| x.deinit(); @@ -112,7 +115,7 @@ pub const gather_source = sources.core_row_projection ++ glue_math ++ sources.gl /// The pipelines built so far: a failed compile releases them all. const Made = struct { - list: [nw * 11 + 7 + 4 * affine_mm.names.len]mtl.Pipeline = undefined, // 11 a width (rows .. moe_glu_u, kda_fg) + list: [nw * 11 + 7 + fp8.names.len + 4 * affine_mm.names.len]mtl.Pipeline = undefined, // 11 a width, then f8 n: usize = 0, released: usize = 0, @@ -166,6 +169,7 @@ fn build(gpa: std.mem.Allocator, device: mtl.Device, kda: []const u8, made: *Mad p.moe_u[i] = try made.add(device, l, "glm_moe_rows_u" ++ q ++ "_s8"); p.moe_glu_u[i] = try made.add(device, l, "glm_moe_rows_glu_u" ++ q ++ "_s8"); } + for (fp8.names, &p.f8) |name, *pipe| pipe.* = try made.add(device, l, name); p.bf16 = try made.add(device, l, "glm_rows_bf16"); for (gather.names, &p.gather) |name, *pipe| pipe.* = try made.add(device, l, name); p.bf16_nax = if (!eh_tile) null else made.add(device, l, "glm_rows_bf16_nax") catch blk: { @@ -305,7 +309,7 @@ fn pickDims(m: Picks, slots: u32, ldo: u32) PickDims { /// Slot y [0, slots) through expert ids[y] (i32) on x row y / repeat, into out row y. pub fn byIds(p: *const Pipes, e: mtl.ComputeEncoder, m: Picks, x: Ref, ids: Ref, out: Ref, slots: u32) void { const u = m.up orelse m.w; - e.setPipeline(if (m.up != null) p.glu_ids[at(m.w.bits)] else p.ids[at(m.w.bits)]); + e.setPipeline(if (m.w.fp8) p.f8[@backingInt(@as(fp8.Kernel, if (m.up != null) .glu_ids else .ids))] else if (m.up != null) p.glu_ids[at(m.w.bits)] else p.ids[at(m.w.bits)]); bind(e, 0, .{ x, m.w.w, m.w.s, m.w.b }); e.setValue(pickDims(m, slots, m.w.n), 4); bind(e, 5, .{ out, ids, u.w, u.s, u.b }); @@ -327,10 +331,11 @@ pub fn glu(p: *const Pipes, e: mtl.ComputeEncoder, gu: Affine, n: u32, x: Ref, o /// A MoE block's routed experts and shared expert (`sh`: [gate; up] one run, then down), all g64, the shared at 8 bits. pub const Moe = struct { gate: Affine, up: Affine, down: Affine, sh_gate_up: Affine, sh_down: Affine }; -/// Whether `m` takes `moe`: every matrix one run, g64, the routed of one width (not 4/64), the shared at 8 bits. +/// Whether `m` takes `moe`: one run each, g64 or the routed all FP8, the routed one width (not 4/64), the shared 8/64. pub fn moeOne(m: Moe) bool { if (native(m.gate) and native(m.up) and native(m.down)) return false; // routed 4/64 keeps the generated gathers - for ([_]Affine{ m.gate, m.up, m.down, m.sh_gate_up, m.sh_down }) |q| if (q.more != 0 or q.group != 64) return false; + if (m.sh_gate_up.fp8 or m.sh_down.fp8 or m.up.fp8 != m.gate.fp8 or m.down.fp8 != m.gate.fp8) return false; + for ([_]Affine{ m.gate, m.up, m.down, m.sh_gate_up, m.sh_down }) |q| if (q.more != 0 or (q.group != 64 and !q.fp8)) return false; return m.up.bits == m.gate.bits and m.down.bits == m.gate.bits and m.sh_gate_up.bits == 8 and m.sh_down.bits == 8; } @@ -368,7 +373,7 @@ pub fn moe( repeat: u32, }{ .{ - .pipe = p.moe_glu[at(m.gate.bits)], + .pipe = if (m.gate.fp8) p.f8[@backingInt(fp8.Kernel.moe_glu)] else p.moe_glu[at(m.gate.bits)], .w = m.gate, .up = m.up, .sh = g, @@ -379,7 +384,7 @@ pub fn moe( .repeat = topk, }, .{ - .pipe = p.moe[at(m.down.bits)], + .pipe = if (m.gate.fp8) p.f8[@backingInt(fp8.Kernel.moe)] else p.moe[at(m.down.bits)], .w = m.down, .up = null, .sh = m.sh_down, @@ -392,7 +397,7 @@ pub fn moe( }; for (steps, 0..) |s, si| { const uw = s.up orelse s.w; - const pipe = if (!by_expert) s.pipe else if (si == 0) p.moe_glu_u[at(m.gate.bits)] else p.moe_u[at(m.down.bits)]; + const pipe = if (!by_expert) s.pipe else if (m.gate.fp8) p.f8[@backingInt(@as(fp8.Kernel, if (si == 0) .moe_glu_u else .moe_u))] else if (si == 0) p.moe_glu_u[at(m.gate.bits)] else p.moe_u[at(m.down.bits)]; e.setPipeline(pipe); bind(e, 0, .{ s.x, s.w.w, s.w.s, s.w.b }); e.setValue(PickDims{ @@ -432,7 +437,7 @@ pub fn bySorted( pairs: u32, ) void { const u = m.up orelse m.w; - e.setPipeline(if (m.up != null) p.glu_sorted[at(m.w.bits)] else p.sorted[at(m.w.bits)]); + e.setPipeline(if (m.w.fp8) p.f8[@backingInt(@as(fp8.Kernel, if (m.up != null) .glu_sorted else .sorted))] else if (m.up != null) p.glu_sorted[at(m.w.bits)] else p.sorted[at(m.w.bits)]); bind(e, 0, .{ x, m.w.w, m.w.s, m.w.b }); e.setValue(pickDims(m, pairs, ldo), 4); bind(e, 5, .{ out, offsets, order, u.w, u.s, u.b }); @@ -521,7 +526,7 @@ test "a failed compile releases every pipeline built before it; a load counts ea defer device.deinit(); var made: Made = .{}; try std.testing.expectError(error.KernelCompile, build(gpa, device, "", &made)); // after the row kernels - try std.testing.expectEqual(@as(usize, nw * 8 + 4), made.released); + try std.testing.expectEqual(@as(usize, nw * 10 + 4 + fp8.names.len), made.released); try std.testing.expectEqual(@as(usize, 0), made.n); var all: Made = .{}; var p = try build(gpa, device, comptime kernels.generatedSource("kda_rows"), &all); diff --git a/zig/tests/glm_rows_check.zig b/zig/tests/glm_rows_check.zig index d73948083b9..fefe0d2c2cd 100644 --- a/zig/tests/glm_rows_check.zig +++ b/zig/tests/glm_rows_check.zig @@ -547,6 +547,7 @@ pub fn main() !void { all.pairs += try batch.sharedGluCheck(&g); all.pairs += try @import("glm_rows_moe.zig").check(&g); all.pairs += try @import("glm_rows_moe.zig").checkUnique(&g); + all.pairs += try @import("glm_rows_fp8.zig").check(&g); all.values += try @import("glm_rows_kda.zig").bf16Check(&g.p, device, queue, &all.worst); all.values += try @import("glm_rows_kda.zig").embedCheck(&g.p, device, queue, &all.worst); const cl = try @import("glm_rows_classes.zig").check(&g.p, device, queue); diff --git a/zig/tests/glm_rows_fp8.zig b/zig/tests/glm_rows_fp8.zig new file mode 100644 index 00000000000..bd2413fbf1b --- /dev/null +++ b/zig/tests/glm_rows_fp8.zig @@ -0,0 +1,191 @@ +//! glm_rows_check's FP8 routed experts (E4M3, 128 x 128 f32 scales): launches agree bit for bit, near float64. +const std = @import("std"); +const mtl = @import("metal"); +const tf = @import("tensorfold"); +const wide = tf.glm.wide; +const affine = tf.glm.affine; +const rc = @import("glm_rows_check.zig"); +const Ref = affine.Ref; + +/// E4M3 code `c` as a value; 0x7F and 0xFF (NaN) are never drawn. +fn e4m3(c: u8) f64 { + const e: i32 = (c >> 3) & 15; + const m: f64 = @floatFromInt(c & 7); + const v = if (e == 0) m / 8.0 * std.math.pow(f64, 2, -6) else (1 + m / 8.0) * std.math.pow(f64, 2, @floatFromInt(e - 7)); + return if (c & 0x80 != 0) -v else v; +} + +fn fromBf(v: u16) f64 { + return @as(f32, @bitCast(@as(u32, v) << 16)); +} + +/// A stack [E, n, k] of random codes (no NaN) and block scales in [2^-9, 2^-5]. +const Stack = struct { + codes: mtl.Buffer, + scales: mtl.Buffer, + q: affine.Affine, + + fn init(device: mtl.Device, E: usize, n: usize, k: usize, r: std.Random) !Stack { + const codes = try rc.buf(device, E * n * k); + errdefer codes.deinit(); + const sb = affine.fp8Scales(n, k).?; + const scales = try rc.buf(device, E * sb); + for (codes.slice(u8, E * n * k)) |*c| { + c.* = r.int(u8); + if (c.* & 0x7F == 0x7F) c.* ^= 1; + } + for (scales.slice(f32, E * sb / 4)) |*s| s.* = std.math.pow(f32, 2, -9 + 4 * r.float(f32)); + const w = rc.ref(codes); + return .{ .codes = codes, .scales = scales, .q = .{ .w = w, .s = rc.ref(scales), .b = w, .n = @intCast(n), .k = @intCast(k), .bits = 8, .group = affine.fp8_block, .fp8 = true } }; + } + + fn deinit(s: Stack) void { + s.codes.deinit(); + s.scales.deinit(); + } + + fn value(s: Stack, e: usize, row: usize, col: usize) f64 { + const n: usize = s.q.n; + const k: usize = s.q.k; + const code = s.codes.slice(u8, (e + 1) * n * k)[(e * n + row) * k + col]; + const sb = affine.fp8Scales(n, k).? / 4; + const scale = s.scales.slice(f32, (e + 1) * sb)[e * sb + (row / 128) * (k / 128) + col / 128]; + return e4m3(code) * scale; + } +}; + +fn moeLaunch(e: mtl.ComputeEncoder, p: *const wide.Pipes, m: wide.Moe, experts: u32, io: wide.MoeIo, rows: u32, u: ?wide.Unique) void { + wide.moe(p, e, m, experts, 8, 0.75, io, rows, u); +} + +fn sortedLaunch(e: mtl.ComputeEncoder, p: *const wide.Pipes, m: wide.Picks, x: Ref, offsets: Ref, order: Ref, out: Ref, ldo: u32, pairs: u32) void { + wide.bySorted(p, e, m, x, offsets, order, out, ldo, pairs); +} + +fn bfRows(device: mtl.Device, count: usize, r: std.Random) !mtl.Buffer { + const b = try rc.buf(device, count * 2); + for (b.slice(u16, count)) |*v| v.* = rc.toBf(r.float(f32) * 2 - 1); + return b; +} + +pub fn check(g: *const rc.Gpu) !usize { + const n = 256; // gate/up rows, down's input + const k = 512; // gate/up's input, down's rows + const E = 16; + const top = 8; + var prng = std.Random.DefaultPrng.init(7330); + const r = prng.random(); + const st = [3]Stack{ try Stack.init(g.device, E, n, k, r), try Stack.init(g.device, E, n, k, r), try Stack.init(g.device, E, k, n, r) }; + defer for (st) |s| s.deinit(); + const sh = [2]rc.Mat{ try rc.Mat.init(g.device, 2 * n, k, 8, 64, 7340), try rc.Mat.init(g.device, k, n, 8, 64, 7341) }; + defer for (sh) |mm| mm.deinit(); + const m: wide.Moe = .{ .gate = st[0].q, .up = st[1].q, .down = st[2].q, .sh_gate_up = sh[0].q, .sh_down = sh[1].q }; + if (!wide.moeOne(m)) return error.NotOneLaunch; + var pairs: usize = 0; + var worst: f64 = 0; + for ([_]u32{ 1, 2, 4, 16 }) |rows| { + const slots = top * rows; + const x = try bfRows(g.device, rows * k, r); + defer x.deinit(); + const bs = [_]mtl.Buffer{ + try rc.buf(g.device, slots * 4), // picks + try rc.buf(g.device, 3 * slots * n * 2), // act: by expert, by pick, by ids + try rc.buf(g.device, 2 * rows * n * 2), // acts + try rc.buf(g.device, 3 * slots * k * 2), // ye: by expert, by pick, by ids + try rc.buf(g.device, 2 * rows * k * 2), // ys + try rc.buf(g.device, slots * 4), // unique ids + try rc.buf(g.device, slots * wide.max_members * 4), // their picks + try rc.buf(g.device, 4), // their count + try rc.buf(g.device, 2 * slots * n * 2), // sorted gate/up out, then the act rows in sorted order + try rc.buf(g.device, slots * k * 2), // sorted down out + try rc.buf(g.device, E * 4), // offsets + try rc.buf(g.device, slots * 4), // order + }; + defer for (bs) |b| b.deinit(); + const picks = bs[0].slice(i32, slots); + for (0..rows) |row| { + var order: [E]i32 = undefined; + for (&order, 0..) |*o, i| o.* = @intCast(i); + r.shuffle(i32, &order); + @memcpy(picks[row * top ..][0..top], order[0..top]); + } + const uids = bs[5].slice(i32, slots); + const umem = bs[6].slice(i32, slots * wide.max_members); + @memset(umem, -1); + const offsets = bs[10].slice(i32, E); + const order = bs[11].slice(i32, slots); + var count: usize = 0; + var at: usize = 0; + for (0..E) |ex| { // experts ascending, each one's picks ascending: moe_route's order and the prompt's sort + offsets[ex] = @intCast(at); + var j: usize = 0; + for (picks, 0..) |pk, pi| if (pk == @as(i32, @intCast(ex))) { + umem[count * wide.max_members + j] = @intCast(pi); + order[at] = @intCast(pi); + j += 1; + at += 1; + }; + if (j == 0) continue; + uids[count] = @intCast(ex); + count += 1; + } + bs[7].slice(i32, 1)[0] = @intCast(count); + const half = [5]usize{ 0, slots * n, rows * n, slots * k, rows * k }; + const io: wide.MoeIo = .{ .x = rc.ref(x), .ids = rc.ref(bs[0]), .act = rc.ref(bs[1]), .acts = rc.ref(bs[2]), .ye = rc.ref(bs[3]), .ys = rc.ref(bs[4]) }; + const by_pick: wide.MoeIo = .{ .x = io.x, .ids = io.ids, .act = io.act.at(half[1] * 2), .acts = io.acts.at(half[2] * 2), .ye = io.ye.at(half[3] * 2), .ys = io.ys.at(half[4] * 2) }; + const u: wide.Unique = .{ .ids = rc.ref(bs[5]), .members = rc.ref(bs[6]), .count = rc.ref(bs[7]) }; + if (rows >= 2) try g.run(moeLaunch, .{ &g.p, m, @as(u32, E), io, rows, u }); + try g.run(moeLaunch, .{ &g.p, m, @as(u32, E), by_pick, rows, null }); + if (rows >= 2) { // by unique expert == by pick + for (bs[1..5], half[1..]) |b, h| { + const v = b.slice(u16, 2 * h); + try rc.eql(v[0..h], v[h..]); + pairs += h; + } + } + // by pick == byIds through the same experts (gate/up SwiGLU'd, then down from the by-pick act) + const ids_act = io.act.at(2 * half[1] * 2); + const ids_ye = io.ye.at(2 * half[3] * 2); + try g.run(rc.byIds, .{ &g.p, wide.Picks{ .w = st[0].q, .up = st[1].q, .experts = E, .repeat = top, .lim = 0.75 }, io.x, io.ids, ids_act, @as(u32, slots) }); + try g.run(rc.byIds, .{ &g.p, wide.Picks{ .w = st[2].q, .experts = E, .repeat = 1 }, by_pick.act, io.ids, ids_ye, @as(u32, slots) }); + const act = bs[1].slice(u16, 3 * half[1]); + const ye = bs[3].slice(u16, 3 * half[3]); + try rc.eql(act[2 * half[1] ..], act[half[1] .. 2 * half[1]]); + try rc.eql(ye[2 * half[3] ..], ye[half[3] .. 2 * half[3]]); + pairs += half[1] + half[3]; + // sorted pairs == byIds: gate/up to pair i from x row order[i] / top, down from act row i to order[i] + try g.run(sortedLaunch, .{ &g.p, wide.Picks{ .w = st[0].q, .up = st[1].q, .experts = E, .repeat = top, .lim = 0.75 }, io.x, rc.ref(bs[10]), rc.ref(bs[11]), rc.ref(bs[8]), @as(u32, n), @as(u32, slots) }); + const sorted = bs[8].slice(u16, 2 * slots * n); + for (0..slots) |i| { + const o: usize = @intCast(order[i]); + try rc.eql(sorted[i * n ..][0..n], act[half[1] + o * n ..][0..n]); + @memcpy(sorted[slots * n + i * n ..][0..n], act[half[1] + o * n ..][0..n]); // by-pick act rows, sorted + } + try g.run(sortedLaunch, .{ &g.p, wide.Picks{ .w = st[2].q, .experts = E, .repeat = 1 }, rc.ref(bs[8]).at(slots * n * 2), rc.ref(bs[10]), rc.ref(bs[11]), rc.ref(bs[9]), @as(u32, k), @as(u32, slots) }); + try rc.eql(bs[9].slice(u16, slots * k), ye[half[3] .. 2 * half[3]]); + pairs += 2 * slots * n / 2 + slots * k; + // byIds down against float64 of the decoded codes: within the bf16 output's rounding and fp32 sums + for (0..slots) |s| { + const e: usize = @intCast(picks[s]); + for (0..k) |row| { + var want: f64 = 0; + var mag: f64 = 0; + for (0..n) |c| { + const t = fromBf(act[half[1] + s * n + c]) * st[2].value(e, row, c); + want += t; + mag += @abs(t); + } + const got = fromBf(ye[2 * half[3] + s * k + row]); + const bound = @abs(want) * std.math.pow(f64, 2, -8) + mag * 1e-6 + 1e-30; + worst = @max(worst, @abs(got - want) / bound); + if (@abs(got - want) > bound) { + std.debug.print("fp8 down slot {d} row {d}: {d} vs float64 {d}\n", .{ s, row, got, want }); + return error.OutOfBound; + } + } + } + } + std.debug.print("FP8 routed experts by unique expert, by pick, by ids and sorted pairs at 1, 2, 4 and 16 rows: " ++ + "{d} bit-equal values; byIds within bf16 of float64 (worst err/bound {d:.4})\n", .{ pairs, worst }); + return pairs; +}