diff --git a/CHANGELOG.md b/CHANGELOG.md index b53a791f9df..b2d69652758 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 CUDA: EXL3 `mcg` routed experts load at any whole-bit width from 1 to 8, mixed by projection within a layer, where only 4-bit was admitted, and the prompt expert kernels gain a 3-bit form; the 4-bit path is unchanged (#2094, refs #2093). Thanks to @MiaAI-Lab. + - Qwen3.8-27B on Metal: a lone sampled stream's DFlash2 draft tree ranks its candidates with the stream's own keyed draw, so the drafts follow what the target samples; the target still decides every token, and greedy and multi-stream rounds are unchanged (#3978). Thanks to @hobbesd. diff --git a/zig/build/glm_family_host.zig b/zig/build/glm_family_host.zig index e20d136ad4b..747675eb46b 100644 --- a/zig/build/glm_family_host.zig +++ b/zig/build/glm_family_host.zig @@ -39,6 +39,7 @@ pub fn steps(b: *std.Build, cuda: *std.Build.Module, glm: *std.Build.Module, mod b.step("test-glm-thin-weights-host", "TF_GLM_LAYERS's admission bytes by tensor from synthetic shard headers").dependOn(&thin_run.step); step.dependOn(&thin_run.step); b.step("test-glm-tp3-host", "Uneven KDA head shares through actual projection and load planning, without devices").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = glm, .filters = &.{"GLM TP3:"} })).step); + b.step("test-glm-exl3-host", "GLM EXL3 admission, mixed-width expert loading and scratch sizing, without devices").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = glm, .filters = &.{"GLM EXL3:"} })).step); // TF_GLM_INDEX_CUDA: the launch rules, and (its own slower step) glm_index_*.cuh as host C++ against plain models const index_run = b.addRunArtifact(b.addTest(.{ .root_module = glm, .filters = &.{"GLM index:"} })); b.step("test-glm-index-host", "GLM's prompt indexer launch rules without devices").dependOn(&index_run.step); diff --git a/zig/exl3_prompt_host.zig b/zig/exl3_prompt_host.zig index 655ac1983cb..3cd2e5fbe39 100644 --- a/zig/exl3_prompt_host.zig +++ b/zig/exl3_prompt_host.zig @@ -17,8 +17,8 @@ const Capture = struct { 3 => &.{ 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4 }, 5 => &.{ 8, 8, 8, 8, 8, 8, 4, 4, 4, 4, 4 }, 11 => &.{ 8, 4, 8, 8, 4 }, - 12 => &.{ 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 4, 4, 4, 4, 4, 4 }, - 13 => &.{ 8, 8, 8, 8, 8, 8, 8, 4, 4, 4 }, + 12, 14 => &.{ 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 4, 4, 4, 4, 4, 4 }, + 13, 15 => &.{ 8, 8, 8, 8, 8, 8, 8, 4, 4, 4 }, else => &.{}, }; for (sizes, 0..) |size, j| { @@ -57,7 +57,7 @@ fn run(rows: usize, prompt: bool, shared: bool) !void { d.api.cuMemcpy2DAsync_v2 = Capture.copy; const s: cuda.Stream = .{ .d = &d, .handle = null }; var k: ex.Experts = .{ .mod = undefined, .group = function(&d, 1), .rot_in = function(&d, 2), .grouped = @splat(function(&d, 3)), .gateup = function(&d, 4), .down_combine = function(&d, 5) }; - if (comptime @hasField(ex.Experts, "prompt")) k.prompt = .{ .rotate = function(&d, 11), .gateup = function(&d, 12), .down = function(&d, 13) }; + if (comptime @hasField(ex.Experts, "prompt")) k.prompt = .{ .rotate = function(&d, 11), .gateup = function(&d, 12), .down = function(&d, 13), .gateup_k6 = function(&d, 14), .down_k6 = function(&d, 15) }; const ek: glm.experts.Kernels = .{ .nvfp4 = undefined, .b32 = null, .router = .{ .plan_small = function(&d, 20), .plan_rank = function(&d, 21), .plan_offsets = function(&d, 22), .plan_scatter = function(&d, 23), .plan_rows = function(&d, 24), .plan_rank_rows = function(&d, 25), .plan_scatter_rows = function(&d, 26) } }; const w: glm.exl3.Experts = .{ .gt = 100, .ut = 200, .dt = 300, .k2 = 400, .suh_g = 500, .suh_u = 600, .svh_g = 700, .svh_u = 800, .suh_d = 900, .svh_d = 1000, .shx = shared }; const sc: glm.exl3.Scratch = .{ .picks = 0x100000000, .xg = 0, .xu = 0, .z = 0 }; @@ -167,14 +167,26 @@ test "exl3 prompt: decode uses item plans and keeps slot and input offsets acros } } -test "exl3 prompt: the common dispatch requires verified mcg4 geometry and keeps every fallback" { +test "exl3 prompt: the common dispatch requires verified mcg3 or mcg4 geometry and keeps every fallback" { const P = ex.prompt; var l: ex.Layer = .{ .gate = 0, .up = 0, .down = 0, .gate_k2 = 0, .up_k2 = 0, .down_k2 = 0, .suh_g = 0, .suh_u = 0, .svh_g = 0, .svh_u = 0, .suh_d = 0, .svh_d = 0, .dims = 512, .width = 256, .experts = 9, .codebook = .mcg, .uniform_k2 = 8 }; try std.testing.expect(P.eligible(l)); l.uniform_k2 = 0; try std.testing.expect(!P.eligible(l)); l.uniform_k2 = 6; - try std.testing.expect(!P.eligible(l)); + try std.testing.expect(P.eligible(l)); + for ([_]u32{ 4, 5, 7, 10 }) |k2| { + l.uniform_k2 = k2; + try std.testing.expect(!P.eligible(l)); + } + l.uniform_k2 = 0; + for ([_][2]u32{ .{ 6, 0 }, .{ 0, 8 }, .{ 4, 8 }, .{ 6, 10 } }) |w| { + l.uniform_k2_gu = w[0]; + l.uniform_k2_d = w[1]; + try std.testing.expect(!P.eligible(l)); + } + l.uniform_k2_gu = 0; + l.uniform_k2_d = 0; l.uniform_k2 = 8; for ([_]ex.Codebook{ .inst3, .mul1 }) |cb| { l.codebook = cb; @@ -250,3 +262,41 @@ test "exl3 prompt: GLM admission facts through shared lanes keep drafted plain a for ([_]bool{ false, true }) |drafts| for ([_]usize{ 0, 1, 3, 7 }) |others| try std.testing.expectEqual(plain, try reply(drafts, others, seed)); } } + +test "exl3 prompt: each projection group launches the kernel of its own verified width, with the same arguments" { + var d: cuda.Driver = undefined; + d.api.cuLaunchKernel = Capture.launch; + const s: cuda.Stream = .{ .d = &d, .handle = null }; + var k: ex.Experts = .{ .mod = undefined, .group = function(&d, 1), .rot_in = function(&d, 2), .grouped = @splat(function(&d, 3)), .gateup = function(&d, 4), .down_combine = function(&d, 5) }; + k.prompt = .{ .rotate = function(&d, 11), .gateup = function(&d, 12), .down = function(&d, 13), .gateup_k6 = function(&d, 14), .down_k6 = function(&d, 15) }; + const router: cuda.grouped.Router = .{ .plan_small = function(&d, 20), .plan_rank = function(&d, 21), .plan_offsets = function(&d, 22), .plan_scatter = function(&d, 23), .plan_rows = function(&d, 24), .plan_rank_rows = function(&d, 25), .plan_scatter_rows = function(&d, 26) }; + const plan: cuda.grouped.Plan = .{ .items = 10000, .members = 20000, .counts = 30000, .rank = 40000, .hist = 50000 }; + var l: ex.Layer = .{ .gate = 100, .up = 200, .down = 300, .gate_k2 = 400, .up_k2 = 400, .down_k2 = 400, .suh_g = 500, .suh_u = 600, .svh_g = 700, .svh_u = 800, .suh_d = 900, .svh_d = 1000, .dims = 512, .width = 256, .experts = 9, .codebook = .mcg, .limit = 10, .shared_input = true }; + var want: [2]Capture.Call = undefined; // the 4-bit gate/up and down launches + for ([_][3]u32{ .{ 8, 0, 0 }, .{ 0, 6, 8 }, .{ 0, 6, 6 }, .{ 0, 8, 6 }, .{ 6, 0, 0 }, .{ 8, 8, 8 }, .{ 6, 6, 0 } }) |w| { + l.uniform_k2 = w[0]; + l.uniform_k2_gu = w[1]; + l.uniform_k2_d = w[2]; + const sc = try ex.prompt.scratch(0x1000, l, 40, 8); + Capture.reset(); + try k.prompt.run(&k, router, s, l, 0x200000000, 520, 0x300000000, 40, sc, plan, 0x400000000, 9); + const gu: usize = if ((if (w[1] != 0) w[1] else w[0]) == 6) 14 else 12; + const dn: usize = if ((if (w[2] != 0) w[2] else w[0]) == 6) 15 else 13; + try std.testing.expectEqual(@as(usize, 1), Capture.by(gu).len); + try std.testing.expectEqual(@as(usize, 1), Capture.by(dn).len); + try std.testing.expectEqual(@as(usize, 1), Capture.by(11).len); + for ([_]usize{ 12, 13, 14, 15 }) |id| if (id != gu and id != dn) try std.testing.expectEqual(@as(usize, 0), Capture.by(id).len); + const got = [2]Capture.Call{ Capture.by(gu)[0], Capture.by(dn)[0] }; + if (w[0] == 8 and w[1] == 0) want = got; + for (got, want) |g, x| { + try std.testing.expectEqual(x.grid, g.grid); + try std.testing.expectEqual(x.block, g.block); + try std.testing.expectEqual(x.args, g.args); + } + } + l.uniform_k2 = 8; + l.uniform_k2_gu = 6; // disagrees with every projection's 8: not verified, so no prompt launch + l.uniform_k2_d = 0; + try std.testing.expect(!ex.prompt.eligible(l)); + try std.testing.expectError(error.Exl3Shape, ex.prompt.scratch(0x1000, l, 40, 8)); +} diff --git a/zig/glm_exl3_prompt_host.zig b/zig/glm_exl3_prompt_host.zig index f0d067fab49..1308d03e361 100644 --- a/zig/glm_exl3_prompt_host.zig +++ b/zig/glm_exl3_prompt_host.zig @@ -81,7 +81,7 @@ fn run(rows: usize, prompt: bool, shared: bool, count: usize) !void { var k: glm.exl3.Kernels = undefined; inline for (.{ "group", "rot_in", "gateup", "down_combine" }, .{ 9, 5, 13, 14 }) |field, id| @field(k, field) = Record.function(&d, id); k.grouped = .{ Record.function(&d, 10), Record.function(&d, 11), Record.function(&d, 12) }; - k.prompt = .{ .rotate = Record.function(&d, 6), .gateup = Record.function(&d, 7), .down = Record.function(&d, 8) }; + k.prompt = .{ .rotate = Record.function(&d, 6), .gateup = Record.function(&d, 7), .down = Record.function(&d, 8), .gateup_k6 = Record.function(&d, 21), .down_k6 = Record.function(&d, 22) }; var ek: glm.experts.Kernels = undefined; inline for (.{ "plan_small", "plan_rows", "plan_rank", "plan_offsets", "plan_scatter", "plan_rank_rows", "plan_scatter_rows" }, .{ 1, 18, 2, 3, 4, 19, 20 }) |field, id| @field(ek.router, field) = Record.function(&d, id); const w = glm.exl3.Experts{ .gt = 101, .ut = 102, .dt = 103, .k2 = 104, .suh_g = 105, .suh_u = 106, .svh_g = 107, .svh_u = 108, .suh_d = 109, .svh_d = 110, .shx = shared }; @@ -169,12 +169,23 @@ fn guarded(text: []const u8, name: []const u8, payload: []const u8) bool { return guard < @min(load, member); } +/// Whether kernel `name`'s whole body is the call `call` (the guarded template at one width). +fn forwards(text: []const u8, name: []const u8, call: []const u8) bool { + const at = std.mem.indexOf(u8, text, name) orelse return false; + const tail = text[at..]; + const open = std.mem.indexOf(u8, tail, "{\n") orelse return false; + const end = std.mem.indexOf(u8, tail, "\n}") orelse return false; + return open < end and std.mem.startsWith(u8, std.mem.trim(u8, tail[open + 2 .. end], " "), call) and std.mem.count(u8, tail[open + 2 .. end], ";") == 1; +} + test "GLM EXL3 prompt: shared-id guards precede payload loads and late-guard controls are caught" { - try t.expect(guarded(source, "tf_exl3_prompt_gu(", "tgateup<")); - try t.expect(guarded(source, "tf_exl3_prompt_down(", "members[first")); + try t.expect(guarded(source, "void prompt_gu(", "tgateup<")); + try t.expect(guarded(source, "void prompt_down(", "members[first")); + for ([_][2][]const u8{ .{ "tf_exl3_prompt_gu(", "prompt_gu<8>(" }, .{ "tf_exl3_prompt_gu_k6(", "prompt_gu<6>(" }, .{ "tf_exl3_prompt_down(", "prompt_down<8>(" }, .{ "tf_exl3_prompt_down_k6(", "prompt_down<6>(" } }) |k| try t.expect(forwards(source, k[0], k[1])); + try t.expect(!forwards(source, "tf_exl3_prompt_gu(", "prompt_gu<6>(")); const bad = try std.mem.replaceOwned(u8, t.allocator, source, "if (e == skip) return;", "const volatile int control_member = members[items[3 * item + 1]];\n if (e == skip) return;"); defer t.allocator.free(bad); try t.expectEqual(@as(usize, 2), std.mem.count(u8, bad, "if (e == skip) return;")); - try t.expect(!guarded(bad, "tf_exl3_prompt_gu(", "tgateup<")); - try t.expect(!guarded(bad, "tf_exl3_prompt_down(", "members[first")); + try t.expect(!guarded(bad, "void prompt_gu(", "tgateup<")); + try t.expect(!guarded(bad, "void prompt_down(", "members[first")); } diff --git a/zig/kernels/cuda/exl3_experts.cu b/zig/kernels/cuda/exl3_experts.cu index 52ddf77dbf9..77ea3a7b6ff 100644 --- a/zig/kernels/cuda/exl3_experts.cu +++ b/zig/kernels/cuda/exl3_experts.cu @@ -282,7 +282,9 @@ extern "C" __global__ void tf_exl3_prompt_rotate(const __nv_bfloat16* __restrict for (int j = 0; j < 4; ++j) o[j] = __float2half_rn(v[j] * HAD_SCALE); } -extern "C" __global__ void __launch_bounds__(256, 2) tf_exl3_prompt_gu(const half* __restrict__ Xg, const half* __restrict__ Xu, +// Gate and up of one width K2 (8: 4 bits, 6: 3 bits), the shared expert skipped before any payload read. +template +__device__ __forceinline__ void prompt_gu(const half* __restrict__ Xg, const half* __restrict__ Xu, const uint64_t* __restrict__ Tg, const uint64_t* __restrict__ Tu, const int* __restrict__ items, const int* __restrict__ counts, const int* __restrict__ members, const half* __restrict__ svh_g, const half* __restrict__ svh_u, const half* __restrict__ suh_d, half* __restrict__ xd, int K, int N, int xdiv, float limit, int act_mode, int skip) { @@ -292,18 +294,34 @@ extern "C" __global__ void __launch_bounds__(256, 2) tf_exl3_prompt_gu(const hal const int e = items[3 * item]; if (e == skip) return; - __shared__ __align__(16) unsigned char smem_raw[tsmem_bytes()]; // one buffer for either instantiation + __shared__ __align__(16) unsigned char smem_raw[tsmem_bytes()]; // one buffer for either instantiation __shared__ int rows_sh[TPM]; - if (xdiv > 1) tgateup(Xg, Xu, Tg, Tu, items, counts, members, svh_g, svh_u, suh_d, xd, K, N, xdiv, limit, act_mode, smem_raw, rows_sh); - else tgateup<2 * TPM>(Xg, Xu, Tg, Tu, items, counts, members, svh_g, svh_u, suh_d, xd, K, N, 1, limit, act_mode, smem_raw, rows_sh); + if (xdiv > 1) tgateup(Xg, Xu, Tg, Tu, items, counts, members, svh_g, svh_u, suh_d, xd, K, N, xdiv, limit, act_mode, smem_raw, rows_sh); + else tgateup<2 * TPM, K2>(Xg, Xu, Tg, Tu, items, counts, members, svh_g, svh_u, suh_d, xd, K, N, 1, limit, act_mode, smem_raw, rows_sh); +} + +extern "C" __global__ void __launch_bounds__(256, 2) tf_exl3_prompt_gu(const half* __restrict__ Xg, const half* __restrict__ Xu, + const uint64_t* __restrict__ Tg, const uint64_t* __restrict__ Tu, const int* __restrict__ items, const int* __restrict__ counts, + const int* __restrict__ members, const half* __restrict__ svh_g, const half* __restrict__ svh_u, const half* __restrict__ suh_d, + half* __restrict__ xd, int K, int N, int xdiv, float limit, int act_mode, int skip) { + prompt_gu<8>(Xg, Xu, Tg, Tu, items, counts, members, svh_g, svh_u, suh_d, xd, K, N, xdiv, limit, act_mode, skip); +} + +// The same at 3 bits: gate and up both 3-bit mcg (tile_words<6>: 96-byte tiles), the arguments tf_exl3_prompt_gu's. +extern "C" __global__ void __launch_bounds__(256, 2) tf_exl3_prompt_gu_k6(const half* __restrict__ Xg, const half* __restrict__ Xu, + const uint64_t* __restrict__ Tg, const uint64_t* __restrict__ Tu, const int* __restrict__ items, const int* __restrict__ counts, + const int* __restrict__ members, const half* __restrict__ svh_g, const half* __restrict__ svh_u, const half* __restrict__ suh_d, + half* __restrict__ xd, int K, int N, int xdiv, float limit, int act_mode, int skip) { + prompt_gu<6>(Xg, Xu, Tg, Tu, items, counts, members, svh_g, svh_u, suh_d, xd, K, N, xdiv, limit, act_mode, skip); } // Block (256 model-width columns, item): y[row][slot][:] = the down epilogue of the item's pairs (this rank's share). -extern "C" __global__ void __launch_bounds__(256, 2) tf_exl3_prompt_down(const half* __restrict__ Xd, const uint64_t* __restrict__ Td, +template +__device__ __forceinline__ void prompt_down(const half* __restrict__ Xd, const uint64_t* __restrict__ Td, const int* __restrict__ items, const int* __restrict__ counts, const int* __restrict__ members, const half* __restrict__ svh_d, float* __restrict__ y, int K, int D, int skip) { - __shared__ __align__(16) unsigned char smem_raw[tsmem_bytes()]; + __shared__ __align__(16) unsigned char smem_raw[tsmem_bytes()]; __shared__ int rows_sh[TPM]; const int cb = blockIdx.x, item = blockIdx.y; if (item >= counts[0]) return; @@ -314,7 +332,7 @@ extern "C" __global__ void __launch_bounds__(256, 2) tf_exl3_prompt_down(const h __syncthreads(); const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31; float acc[TMT][TNB][4]; - tmain<1, TPM>(Xd, Xd, Td, Td, rows_sh, cnt, e, K, D >> 4, cb, 1, reinterpret_cast(smem_raw), acc); + tmain<1, TPM, K2>(Xd, Xd, Td, Td, rows_sh, cnt, e, K, D >> 4, cb, 1, reinterpret_cast(smem_raw), acc); float* Ed = reinterpret_cast(smem_raw); for (int hf = 0; hf < 2 && hf * TPH < cnt; ++hf) { if (hf) __syncthreads(); @@ -336,3 +354,16 @@ extern "C" __global__ void __launch_bounds__(256, 2) tf_exl3_prompt_down(const h } } } + +extern "C" __global__ void __launch_bounds__(256, 2) tf_exl3_prompt_down(const half* __restrict__ Xd, const uint64_t* __restrict__ Td, + const int* __restrict__ items, const int* __restrict__ counts, const int* __restrict__ members, const half* __restrict__ svh_d, + float* __restrict__ y, int K, int D, int skip) { + prompt_down<8>(Xd, Td, items, counts, members, svh_d, y, K, D, skip); +} + +// The same at 3 bits (3-bit mcg down), the arguments tf_exl3_prompt_down's. +extern "C" __global__ void __launch_bounds__(256, 2) tf_exl3_prompt_down_k6(const half* __restrict__ Xd, const uint64_t* __restrict__ Td, + const int* __restrict__ items, const int* __restrict__ counts, const int* __restrict__ members, const half* __restrict__ svh_d, + float* __restrict__ y, int K, int D, int skip) { + prompt_down<6>(Xd, Td, items, counts, members, svh_d, y, K, D, skip); +} diff --git a/zig/kernels/cuda/exl3_prompt.cuh b/zig/kernels/cuda/exl3_prompt.cuh index 9f93e276650..cbbf60d12ce 100644 --- a/zig/kernels/cuda/exl3_prompt.cuh +++ b/zig/kernels/cuda/exl3_prompt.cuh @@ -4,12 +4,14 @@ #include "common/qmm_frag.cuh" namespace tf_exl3_prompt { using namespace tf_exl3; +// One mcg tile of K2 half-bits a value (8: 4 bits, 6: 3 bits) from shared memory into this lane's B fragments. +template __device__ __forceinline__ void decode_tile_p(const uint32_t* tile, int lane, uint32_t (&b0)[2], uint32_t (&b1)[2]) { - uint32_t w[lane_words<8>()]; + uint32_t w[lane_words()]; int word, offset; - lane_start<8>(lane, word, offset); - for (int i = 0; i < lane_words<8>(); ++i) w[i] = tile[(word + i) % tile_words<8>()]; - decode_lane<8, CB_MCG>(w, lane, b0, b1); + lane_start(lane, word, offset); + for (int i = 0; i < lane_words(); ++i) w[i] = tile[(word + i) % tile_words()]; + decode_lane(w, lane, b0, b1); } __device__ __forceinline__ void cp_async16(void* dst, const void* src, bool valid) { tf_common::cp16z(dst, src, valid); @@ -22,12 +24,14 @@ namespace tf_exl3_prompt { constexpr int TPM = 64, TNW = 8, TMT = 16 / TNW, TNB = TPM / 8, TT = TNW * 32, TPH = TPM / 2; constexpr int TBK = 32, TKT = TBK / 16, TSTAGES = 3, TXS = TBK + 8; -constexpr int TWORDS = 16 * TKT * 32; +template +constexpr int twords() { return 16 * TKT * tile_words(); } // a stage's weight words: 16 tiles by TKT constexpr int GU_ES = 128 + 4, DN_ES = 256 + 4; // the epilogue sums' row strides (floats) -template -constexpr int tstage_halves() { return XR * TXS + 2 * TWORDS; } +template +constexpr int tstage_halves() { return XR * TXS + 2 * twords(); } +template constexpr int tsmem_bytes() { - const int gu = TSTAGES * tstage_halves<2 * TPM>() * 2; // gate and up rows apart (no shared rotation) + const int gu = TSTAGES * tstage_halves<2 * TPM, K2>() * 2; // gate and up rows apart (no shared rotation) const int ep = 2 * TPH * GU_ES * 4, dn = TPH * DN_ES * 4; return gu > ep ? (gu > dn ? gu : dn) : (ep > dn ? ep : dn); } @@ -40,11 +44,12 @@ __device__ __forceinline__ void ttile(int q, int cb, int& mat, int& nt) { } // Main loop: acc[i][nb] = warp tile i x members nb * 8 .. + 7 over K; XR rows a stage (TPM if X0 == X1, else 2 TPM). -template +template __device__ __forceinline__ void tmain(const half* __restrict__ X0, const half* __restrict__ X1, const uint64_t* __restrict__ tp0, const uint64_t* __restrict__ tp1, const int* rows_sh, int cnt, int e, int K, int NTILES, int cb, int xdiv, half* stage, float (&acc)[TMT][TNB][4]) { - constexpr int SH = tstage_halves(); + constexpr int SH = tstage_halves(); + constexpr int TW = tile_words(), PIECES = TW / 4; // a tile's 32-bit words and 16-byte pieces const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31; int mat, nt_unused; ttile(warp * TMT, cb, mat, nt_unused); @@ -69,12 +74,12 @@ __device__ __forceinline__ void tmain(const half* __restrict__ X0, const half* _ cp_async16(dst + ((size_t)m * TPM + i) * TXS + j * 8, src, r >= 0); } uint32_t* wdst = reinterpret_cast(dst + (size_t)XR * TXS); - for (int idx = threadIdx.x; idx < 16 * TKT * 8; idx += TT) { // 16-byte pieces of the 128-byte tile words - const int q = idx / (TKT * 8), kk = (idx / 8) % TKT, part = idx % 8; + for (int idx = threadIdx.x; idx < 16 * TKT * PIECES; idx += TT) { // 16-byte pieces of the tiles' words + const int q = idx / (TKT * PIECES), kk = (idx / PIECES) % TKT, part = idx % PIECES; int wm, nt; ttile(q, cb, wm, nt); - const uint32_t* src = (wm ? T1 : T0) + (((size_t)chunk * TKT + kk) * NTILES + nt) * 32 + part * 4; - cp_async16(wdst + ((size_t)q * TKT + kk) * 32 + part * 4, src, true); + const uint32_t* src = (wm ? T1 : T0) + (((size_t)chunk * TKT + kk) * NTILES + nt) * TW + part * 4; + cp_async16(wdst + ((size_t)q * TKT + kk) * TW + part * 4, src, true); } }; #pragma unroll @@ -96,7 +101,7 @@ __device__ __forceinline__ void tmain(const half* __restrict__ X0, const half* _ #pragma unroll for (int i = 0; i < TMT; ++i) { uint32_t b0[2], b1[2]; - decode_tile_p(ws + ((size_t)(warp * TMT + i) * TKT + kk) * 32, lane, b0, b1); + decode_tile_p(ws + ((size_t)(warp * TMT + i) * TKT + kk) * TW, lane, b0, b1); a[i][0] = b0[0]; a[i][1] = b1[0]; a[i][2] = b0[1]; a[i][3] = b1[1]; } #pragma unroll @@ -135,7 +140,7 @@ __device__ __forceinline__ void tspill(float* E, int ES, int col0, const float ( } } -template +template __device__ __forceinline__ void tgateup(const half* __restrict__ Xg, const half* __restrict__ Xu, const uint64_t* __restrict__ Tg, const uint64_t* __restrict__ Tu, const int* __restrict__ items, const int* __restrict__ counts, const int* __restrict__ members, const half* __restrict__ svh_g, const half* __restrict__ svh_u, const half* __restrict__ suh_d, half* __restrict__ xd, @@ -147,7 +152,7 @@ __device__ __forceinline__ void tgateup(const half* __restrict__ Xg, const half* __syncthreads(); const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31; float acc[TMT][TNB][4]; - tmain<2, XR>(Xg, Xu, Tg, Tu, rows_sh, cnt, e, K, N >> 4, cb, xdiv, reinterpret_cast(smem_raw), acc); + tmain<2, XR, K2>(Xg, Xu, Tg, Tu, rows_sh, cnt, e, K, N >> 4, cb, xdiv, reinterpret_cast(smem_raw), acc); float* Eg = reinterpret_cast(smem_raw); int mat, nt; ttile<2>(warp * TMT, cb, mat, nt); diff --git a/zig/src/core/contract/exl3_prompt_pending.zig b/zig/src/core/contract/exl3_prompt_pending.zig index aff7493ce36..7a4e979cbfa 100644 --- a/zig/src/core/contract/exl3_prompt_pending.zig +++ b/zig/src/core/contract/exl3_prompt_pending.zig @@ -5,6 +5,8 @@ const limits = @import("limits.zig"); pub const records = [_]registry.CudaRecord{ .{ .launch = .{ .name = "exl3_experts tf_exl3_prompt_gu", .symbol = "tf_exl3_prompt_gu", .image = "exl3_experts", .threads = 256 }, .usage = registry.none }, .{ .launch = .{ .name = "exl3_experts tf_exl3_prompt_down", .symbol = "tf_exl3_prompt_down", .image = "exl3_experts", .threads = 256 }, .usage = registry.none }, + .{ .launch = .{ .name = "exl3_experts tf_exl3_prompt_gu_k6", .symbol = "tf_exl3_prompt_gu_k6", .image = "exl3_experts", .threads = 256 }, .usage = registry.none }, + .{ .launch = .{ .name = "exl3_experts tf_exl3_prompt_down_k6", .symbol = "tf_exl3_prompt_down_k6", .image = "exl3_experts", .threads = 256 }, .usage = registry.none }, }; pub fn owns(name: []const u8) bool { @@ -16,5 +18,5 @@ test "EXL3 prompt: unmeasured compiler usage stays pending" { for (records) |r| for ([_]?limits.Nvcc{ null, .{ .major = 13, .minor = 0 }, .{ .major = 13, .minor = 1 }, .{ .major = 13, .minor = 2 }, .{ .major = 13, .minor = 3 } }) |version| { try std.testing.expectEqualDeep(registry.none, registry.usageFor(r, version)); }; - try std.testing.expectEqual(@as(usize, 10), try registry.checkCuda(std.testing.allocator, &records, true)); + try std.testing.expectEqual(@as(usize, 20), try registry.checkCuda(std.testing.allocator, &records, true)); } diff --git a/zig/src/cuda/exl3_experts.zig b/zig/src/cuda/exl3_experts.zig index b907b3a3044..861bb7151e9 100644 --- a/zig/src/cuda/exl3_experts.zig +++ b/zig/src/cuda/exl3_experts.zig @@ -35,6 +35,8 @@ pub const Layer = struct { width: usize, // I (expert width) codebook: Codebook, uniform_k2: u32 = 0, // nonzero only when the loader verified this half-bit width for every projection + uniform_k2_gu: u32 = 0, // nonzero when the loader verified this half-bit width for every gate and up matrix + uniform_k2_d: u32 = 0, // nonzero when the loader verified this half-bit width for every down matrix shared_input: bool = false, // the loader verified identical gate/up input scales across every expert gu_stride: usize = 0, // gate/up trellis row stride in tiles (0: contiguous per projection) limit: f32 = 0, // the SwiGLU clamp (0: none) diff --git a/zig/src/cuda/exl3_prompt.zig b/zig/src/cuda/exl3_prompt.zig index 4b1b7908764..8720cda6c78 100644 --- a/zig/src/cuda/exl3_prompt.zig +++ b/zig/src/cuda/exl3_prompt.zig @@ -9,8 +9,21 @@ const Stream = @import("stream.zig").Stream; pub const tile = 64; pub const Scratch = struct { xg: u64, xu: u64, xd: u64, rows: usize, slots: usize }; +/// A group's verified half-bit width: its own field, else uniform_k2; 0 when unverified or the two disagree. +fn verified(group: u32, uniform: u32) u32 { + if (group == 0) return uniform; + return if (uniform == 0 or uniform == group) group else 0; +} +/// The verified widths of gate/up and of down (0: unverified); the prompt kernels take 6 (3 bits) and 8 (4 bits). +pub fn widths(l: ex.Layer) struct { gu: u32, d: u32 } { + return .{ .gu = verified(l.uniform_k2_gu, l.uniform_k2), .d = verified(l.uniform_k2_d, l.uniform_k2) }; +} +fn built(k2: u32) bool { + return k2 == 6 or k2 == 8; +} pub fn eligible(l: ex.Layer) bool { - return l.codebook == .mcg and l.uniform_k2 == 8 and l.gu_stride == 0 and l.dims > 0 and l.width > 0 and l.dims % 256 == 0 and l.width % 128 == 0 and (l.act_mode == 0 or l.act_mode == 1); + const w = widths(l); + return l.codebook == .mcg and built(w.gu) and built(w.d) and l.gu_stride == 0 and l.dims > 0 and l.width > 0 and l.dims % 256 == 0 and l.width % 128 == 0 and (l.act_mode == 0 or l.act_mode == 1); } fn mul(a: usize, b: usize) !usize { return std.math.mul(usize, a, b) catch error.Exl3Shape; @@ -50,10 +63,18 @@ fn i(n: usize) i32 { } pub const Kernels = struct { rotate: Function, - gateup: Function, - down: Function, + gateup: Function, // 4-bit gate and up + down: Function, // 4-bit down + gateup_k6: Function, // 3-bit gate and up, gateup's arguments + down_k6: Function, // 3-bit down, down's arguments pub fn resolve(mod: Module) !Kernels { - return .{ .rotate = try mod.function("tf_exl3_prompt_rotate"), .gateup = try mod.function("tf_exl3_prompt_gu"), .down = try mod.function("tf_exl3_prompt_down") }; + return .{ + .rotate = try mod.function("tf_exl3_prompt_rotate"), + .gateup = try mod.function("tf_exl3_prompt_gu"), + .down = try mod.function("tf_exl3_prompt_down"), + .gateup_k6 = try mod.function("tf_exl3_prompt_gu_k6"), + .down_k6 = try mod.function("tf_exl3_prompt_down_k6"), + }; } /// `skip` is the shared expert's id, equal to the routed count; its output slot stays owned by the caller. pub fn run(k: Kernels, e: *const ex.Experts, router: grouped.Router, s: Stream, l: ex.Layer, x: u64, stride: usize, picks: u64, rows: usize, sc: Scratch, p: grouped.Plan, y: u64, skip: ?usize) !void { @@ -63,6 +84,7 @@ pub const Kernels = struct { const count = l.experts + @intFromBool(skip != null); const skip_id: i32 = if (skip) |id| i(id) else -1; const pairs = rows * sc.slots; + const w = widths(l); try router.route(s, picks, pairs, count, tile, p); if (l.shared_input) { try go(k.rotate, s, .{ rows, l.dims / 128, 1 }, 32, .{ x, i(stride), l.suh_g, sc.xg, i(l.dims) }); @@ -72,7 +94,28 @@ pub const Kernels = struct { try launch.launch(e.rot_in, .{ .grid = .{ .x = @intCast(pairs), .y = @intCast(l.dims / 128), .z = 2 }, .block = .{ .x = 32 } }, s, &args); } const items = grouped.maxItems(pairs, count, tile); - try go(k.gateup, s, .{ l.width / 128, items, 1 }, 256, .{ sc.xg, sc.xu, l.gate, l.up, p.items, p.counts, p.members, l.svh_g, l.svh_u, l.suh_d, sc.xd, i(l.dims), i(l.width), i(if (l.shared_input) sc.slots else 1), l.limit, l.act_mode, skip_id }); - try go(k.down, s, .{ l.dims / 256, items, 1 }, 256, .{ sc.xd, l.down, p.items, p.counts, p.members, l.svh_d, y, i(l.width), i(l.dims), skip_id }); + try go(if (w.gu == 6) k.gateup_k6 else k.gateup, s, .{ l.width / 128, items, 1 }, 256, .{ sc.xg, sc.xu, l.gate, l.up, p.items, p.counts, p.members, l.svh_g, l.svh_u, l.suh_d, sc.xd, i(l.dims), i(l.width), i(if (l.shared_input) sc.slots else 1), l.limit, l.act_mode, skip_id }); + try go(if (w.d == 6) k.down_k6 else k.down, s, .{ l.dims / 256, items, 1 }, 256, .{ sc.xd, l.down, p.items, p.counts, p.members, l.svh_d, y, i(l.width), i(l.dims), skip_id }); } }; + +test "per-projection widths: the group fields, else uniform_k2, and a disagreement unverified" { + var l: ex.Layer = .{ .gate = 0, .up = 0, .down = 0, .gate_k2 = 0, .up_k2 = 0, .down_k2 = 0, .suh_g = 0, .suh_u = 0, .svh_g = 0, .svh_u = 0, .suh_d = 0, .svh_d = 0, .experts = 9, .dims = 512, .width = 256, .codebook = .mcg, .uniform_k2 = 8 }; + try std.testing.expectEqual(@as(u32, 8), widths(l).gu); + try std.testing.expectEqual(@as(u32, 8), widths(l).d); + l.uniform_k2 = 0; + l.uniform_k2_gu = 6; + l.uniform_k2_d = 8; + try std.testing.expectEqual(@as(u32, 6), widths(l).gu); + try std.testing.expectEqual(@as(u32, 8), widths(l).d); + try std.testing.expect(eligible(l)); + l.uniform_k2_d = 0; + try std.testing.expectEqual(@as(u32, 0), widths(l).d); + try std.testing.expect(!eligible(l)); + l.uniform_k2 = 8; + l.uniform_k2_d = 0; + try std.testing.expectEqual(@as(u32, 0), widths(l).gu); // gate/up 6 against every projection 8: unverified + try std.testing.expect(!eligible(l)); + l.uniform_k2_gu = 8; + try std.testing.expect(eligible(l)); +} diff --git a/zig/src/families/glm/cuda_exl3.zig b/zig/src/families/glm/cuda_exl3.zig index 9c30d912979..fce0f2234d8 100644 --- a/zig/src/families/glm/cuda_exl3.zig +++ b/zig/src/families/glm/cuda_exl3.zig @@ -1,7 +1,8 @@ -//! GLM-5.3-Flash's EXL3 routed experts on CUDA (Mia-AiLab's checkpoint: 4-bit mcg trellis experts, the rest bf16). +//! GLM's EXL3 routed experts on CUDA: "mcg" trellis experts at any whole-bit width, mixed per projection; rest bf16. const std = @import("std"); -const modelopt = @import("core").modelopt; +const core = @import("core"); +const modelopt = core.modelopt; const Span = @import("cuda_shard.zig").Span; const cuda = @import("cuda"); const experts = @import("cuda_experts.zig"); @@ -23,7 +24,28 @@ pub fn isExl3(gpa: std.mem.Allocator, config_json: []const u8) bool { return m == .string and std.mem.eql(u8, m.string, "exl3"); } -/// The EXL3 checkpoints the kernels read: 4-bit routed experts on the "mcg" codebook (everything else bf16). +/// The half-bit widths (2 * bits) the grouped kernels decode on mcg: whole bits from 1 to 8 (odd halves are mul1's). +pub const min_k2 = 2; +pub const max_k2 = 16; + +/// A trellis's half-bit width from its last dimension (16 * bits int16 a tile), null if the kernels skip it. +pub fn halves(last: usize) ?u32 { + if (last % 8 != 0) return null; + const k2 = last / 8; + if (k2 < min_k2 or k2 > max_k2 or k2 % 2 != 0) return null; + return @intCast(k2); +} + +/// A JSON number as f64, or null. +fn number(v: std.json.Value) ?f64 { + return switch (v) { + .integer => |i| @floatFromInt(i), + .float => |f| f, + else => null, + }; +} + +/// The EXL3 the kernels read: "mcg" routed experts at 1 to 8 bits, each trellis's width taken from its shape. pub fn admit(gpa: std.mem.Allocator, config_json: []const u8, why: *modelopt.Why) !void { const parsed = try std.json.parseFromSlice(std.json.Value, gpa, config_json, .{}); defer parsed.deinit(); @@ -31,10 +53,21 @@ pub fn admit(gpa: std.mem.Allocator, config_json: []const u8, why: *modelopt.Why why.set("no quantization_config", .{}); return error.UnsupportedQuant; }; - const bits = q.get("bits") orelse std.json.Value{ .null = {} }; - if (bits != .integer or bits.integer != 4) { - why.set("EXL3 at {f} bits: the CUDA family reads 4-bit EXL3 experts", .{std.json.fmt(bits, .{})}); - return error.UnsupportedQuant; + const lo: f64 = min_k2 / 2; + const hi: f64 = max_k2 / 2; + if (q.get("bits")) |bits| { + const b = number(bits); + if (b == null or b.? != @floor(b.?) or !(b.? >= lo and b.? <= hi)) { + why.set("EXL3 at {f} bits: the CUDA family reads mcg experts of 1 to 8 whole bits", .{std.json.fmt(bits, .{})}); + return error.UnsupportedQuant; + } + } + if (q.get("avg_bits")) |avg| { + const b = number(avg); + if (b == null or !(b.? >= lo and b.? <= hi)) { + why.set("EXL3 averaging {f} bits: the CUDA family reads mcg experts of 1 to 8 bits", .{std.json.fmt(avg, .{})}); + return error.UnsupportedQuant; + } } const book = q.get("codebook") orelse std.json.Value{ .null = {} }; if (book != .string or !std.mem.eql(u8, book.string, "mcg")) { @@ -43,9 +76,9 @@ pub fn admit(gpa: std.mem.Allocator, config_json: []const u8, why: *modelopt.Why } } -/// One layer's EXL3 experts on a rank: trellis words [E][K/16][N/16][32] and fp16 scales (suh [E][K], svh [E][N]). +/// One layer's EXL3 experts on a rank: trellis words [E][K/16][N/16][8 * k2] and fp16 scales (suh [E][K], svh [E][N]). pub const Experts = struct { - gt: u64, + gt: u64, // int64 [E]: each expert's gate trellis ut: u64, dt: u64, suh_g: u64, @@ -54,18 +87,49 @@ pub const Experts = struct { svh_u: u64, suh_d: u64, svh_d: u64, - k2: u64, // independent per-expert projection widths in the common module + k2: u64, // int32 [E]: every expert's gate half-bit width (2 * bits); up's and down's too unless theirs are set + k2_up: u64 = 0, // int32 [E]: up's widths (0: k2's) + k2_down: u64 = 0, // int32 [E]: down's widths (0: k2's) + // Widths the loader found across gate/up and down (0: they differ); a literal is upstream's 4-bit, 8 half-bits. + uniform_gu: u32 = 8, + uniform_d: u32 = 8, shx: bool, // every expert's gate and up share one input rotation: a prompt rotates a row once, not once a pick + + /// The gate, up and down width tables. + pub fn tables(w: Experts) [3]u64 { + return .{ w.k2, if (w.k2_up != 0) w.k2_up else w.k2, if (w.k2_down != 0) w.k2_down else w.k2 }; + } }; -const tile = 128; // a 16 x 16 tile's bytes at 4 bits +/// A 16 x 16 tile's bytes at `k2` half-bits a value (128 at 4 bits, 96 at 3). +pub fn tileBytes(k2: u32) usize { + return 16 * @as(usize, k2); +} + +/// The width every entry of `k2s` has, or 0 when they differ (or there are none). +fn uniform(k2s: []const i32) u32 { + if (k2s.len == 0) return 0; + for (k2s) |k| if (k != k2s[0]) return 0; + return @intCast(k2s[0]); +} -/// Layer `i`'s EXL3 experts through `L` (cuda_weights' loader): gate, up by `cut`'s tile columns, down by its rows. +/// Why trellis `t` of a K x N projection is not one the kernels read, or null when it is. +pub fn refusal(t: core.checkpoint.Tensor, k: usize, n: usize) ?[]const u8 { + if (t.dtype != .i16 or t.rank != 3) return "not an int16 trellis [K/16, N/16, 16 * bits]"; + if (t.dim(0) != k / 16 or t.dim(1) != n / 16) return "its tiles do not cover the projection's K x N"; + if (halves(t.dim(2)) == null) return "a width other than 1 to 8 whole bits (16 to 128 int16 a tile)"; + if (t.bytes.len != t.numel() * 2) return "its bytes do not match its shape"; + return null; +} + +/// Layer `i`'s experts via `L`: gate and up by `cut`'s tile columns, down by rows, each at its own trellis width. pub fn load(L: anytype, i: u32, count: usize, dims: usize, inter: usize, cut: Span) !Experts { - if (dims % 128 != 0 or cut.lo % 128 != 0 or cut.hi % 128 != 0) return error.NotExl3Mcg4; + if (dims % 128 != 0 or cut.lo % 128 != 0 or cut.hi % 128 != 0) return error.UnreadableExl3; const width = cut.len(); var out: Experts = undefined; out.shx = true; + const k2s = try L.gpa.alloc(i32, 3 * count); // gate's, up's, down's by expert + defer L.gpa.free(k2s); const Mat = struct { k: usize, n: usize, by_cols: bool }; const mats = [_]Mat{ .{ .k = dims, .n = inter, .by_cols = true }, @@ -73,51 +137,77 @@ pub fn load(L: anytype, i: u32, count: usize, dims: usize, inter: usize, cut: Sp .{ .k = inter, .n = dims, .by_cols = false }, }; var first_suh: ?[]const u8 = null; - inline for (mats, .{ "gate_proj", "up_proj", "down_proj" }, .{ "gt", "ut", "dt" }, .{ "suh_g", "suh_u", "suh_d" }, .{ "svh_g", "svh_u", "svh_d" }) |m, proj, tw, su, sv| { + inline for (mats, .{ "gate_proj", "up_proj", "down_proj" }, .{ "gt", "ut", "dt" }, .{ "suh_g", "suh_u", "suh_d" }, .{ "svh_g", "svh_u", "svh_d" }, 0..) |m, proj, tw, su, sv, pi| { const kt = (if (m.by_cols) m.k else width) / 16; // the rank's tiles const nt = (if (m.by_cols) width else m.n) / 16; - for (0..count) |e| { + const mine = k2s[pi * count ..][0..count]; + for (0..count, mine) |e, *k2| { const t = try L.get("layers.{d}.mlp.experts.{d}." ++ proj ++ ".trellis", .{ i, e }); - if (t.dtype != .i16 or t.rank != 3 or t.dim(0) != m.k / 16 or t.dim(1) != m.n / 16 or t.dim(2) != 64) return error.NotExl3Mcg4; - const marker = L.get("layers.{d}.mlp.experts.{d}." ++ proj ++ ".mcg", .{ i, e }) catch return error.NotExl3Mcg4; + if (refusal(t, m.k, m.n)) |why| { + std.log.err("{s}: {s} (shape {any}); GLM's CUDA experts read mcg trellises of 1 to 8 bits", .{ L.last, why, t.shape[0..t.rank] }); + return error.UnreadableExl3; + } + const h = halves(t.dim(2)).?; + const tile = tileBytes(h); + const marker = L.get("layers.{d}.mlp.experts.{d}." ++ proj ++ ".mcg", .{ i, e }) catch return error.UnreadableExl3; if (marker.dtype != .i32 or marker.numel() != 1 or marker.bytes.len != 4 or - std.mem.readInt(u32, marker.bytes[0..4], .little) != @import("core").exl3_load.markers[0].value) - return error.NotExl3Mcg4; + std.mem.readInt(u32, marker.bytes[0..4], .little) != core.exl3_load.markers[0].value) + return error.UnreadableExl3; if (m.by_cols) { // every tile row, the rank's tile columns const row = (m.n / 16) * tile; for (0..kt) |r| try L.host.appendSlice(L.gpa, t.bytes[r * row + (cut.lo / 16) * tile ..][0 .. nt * tile]); } else try L.host.appendSlice(L.gpa, t.bytes[(cut.lo / 16) * nt * tile ..][0 .. kt * nt * tile]); // its tile rows + k2.* = @intCast(h); } const base = try L.put("layers.{d}.moe.exl3." ++ tw, .{i}); - for (0..count) |e| { - const ptr = base + e * kt * nt * tile; + var ptr: u64 = base; + for (mine) |k2| { // each expert's trellis follows the one before, at its own width try L.host.appendSlice(L.gpa, std.mem.asBytes(&ptr)); + ptr += kt * nt * tileBytes(@intCast(k2)); } @field(out, tw) = try L.put("layers.{d}.moe.exl3." ++ tw ++ "_ptrs", .{i}); for (0..count) |e| { // suh: the input's scales (gate, up: every input; down: the rank's) const t = try L.get("layers.{d}.mlp.experts.{d}." ++ proj ++ ".suh", .{ i, e }); - if (t.dtype != .f16 or t.numel() != m.k) return error.NotExl3Mcg4; - const mine = if (m.by_cols) t.bytes else t.bytes[cut.lo * 2 .. cut.hi * 2]; + if (t.dtype != .f16 or t.numel() != m.k) return error.UnreadableExl3; + const own = if (m.by_cols) t.bytes else t.bytes[cut.lo * 2 .. cut.hi * 2]; if (m.by_cols) { // one rotation shared by the layer's every gate and up input? - if (first_suh) |f| (if (!std.mem.eql(u8, f, mine)) { + if (first_suh) |f| (if (!std.mem.eql(u8, f, own)) { out.shx = false; - }) else first_suh = mine; + }) else first_suh = own; } - try L.host.appendSlice(L.gpa, mine); + try L.host.appendSlice(L.gpa, own); } @field(out, su) = try L.put("layers.{d}.moe.exl3." ++ su, .{i}); for (0..count) |e| { // svh: the output's scales (gate, up: the rank's; down: every output) const t = try L.get("layers.{d}.mlp.experts.{d}." ++ proj ++ ".svh", .{ i, e }); - if (t.dtype != .f16 or t.numel() != m.n) return error.NotExl3Mcg4; + if (t.dtype != .f16 or t.numel() != m.n) return error.UnreadableExl3; try L.host.appendSlice(L.gpa, if (m.by_cols) t.bytes[cut.lo * 2 .. cut.hi * 2] else t.bytes); } @field(out, sv) = try L.put("layers.{d}.moe.exl3." ++ sv, .{i}); } - for (0..count) |_| { - const bits: i32 = 8; - try L.host.appendSlice(L.gpa, std.mem.asBytes(&bits)); + out.uniform_gu = uniform(k2s[0 .. 2 * count]); + out.uniform_d = uniform(k2s[2 * count ..]); + const tabs = [3][]const i32{ k2s[0..count], k2s[count .. 2 * count], k2s[2 * count ..] }; + // one table, as a 4-bit layer has it + if (std.mem.eql(i32, tabs[0], tabs[1]) and std.mem.eql(i32, tabs[0], tabs[2])) { + try L.host.appendSlice(L.gpa, std.mem.sliceAsBytes(tabs[0])); + out.k2 = try L.put("layers.{d}.moe.exl3.k2", .{i}); + out.k2_up = out.k2; + out.k2_down = out.k2; + return out; + } + var ptrs: [3]u64 = undefined; + inline for (tabs, .{ "k2_gate", "k2_up", "k2_down" }, 0..) |tab, name, p| { // a table a distinct projection + var same: ?u64 = null; + for (tabs[0..p], ptrs[0..p]) |before, ptr| if (same == null and std.mem.eql(i32, before, tab)) { + same = ptr; + }; + ptrs[p] = same orelse blk: { + try L.host.appendSlice(L.gpa, std.mem.sliceAsBytes(tab)); + break :blk try L.put("layers.{d}.moe.exl3." ++ name, .{i}); + }; } - out.k2 = try L.put("layers.{d}.moe.exl3.k2", .{i}); + out.k2, out.k2_up, out.k2_down = ptrs; return out; } @@ -130,15 +220,35 @@ pub const top_k = 8; pub const chunk_rows = 1024; /// The prompt item plan has no decode grouper's shared-memory cap; one call covers a supported whole prompt pass. pub const prompt_rows = 4096; -fn layer(w: Experts, count: usize, dims: usize, width: usize, limit: f32) common.Layer { - return .{ .gate = w.gt, .up = w.ut, .down = w.dt, .gate_k2 = w.k2, .up_k2 = w.k2, .down_k2 = w.k2, .suh_g = w.suh_g, .suh_u = w.suh_u, .svh_g = w.svh_g, .svh_u = w.svh_u, .suh_d = w.suh_d, .svh_d = w.svh_d, .experts = count, .dims = dims, .width = width, .codebook = .mcg, .limit = limit, .act_mode = 0, .uniform_k2 = 8, .shared_input = w.shx }; -} -fn shape(dims: usize, width: usize) common.Layer { - const w: Experts = .{ .gt = 0, .ut = 0, .dt = 0, .k2 = 0, .suh_g = 0, .suh_u = 0, .svh_g = 0, .svh_u = 0, .suh_d = 0, .svh_d = 0, .shx = false }; - return layer(w, cuda.grouped.max_experts, dims, width, 0); +/// The common module's layer: a width table a projection, and the widths the loader found uniform. +pub fn layer(w: Experts, count: usize, dims: usize, width: usize, limit: f32) common.Layer { + return .{ + .gate = w.gt, + .up = w.ut, + .down = w.dt, + .gate_k2 = w.tables()[0], + .up_k2 = w.tables()[1], + .down_k2 = w.tables()[2], + .suh_g = w.suh_g, + .suh_u = w.suh_u, + .svh_g = w.svh_g, + .svh_u = w.svh_u, + .suh_d = w.suh_d, + .svh_d = w.svh_d, + .experts = count, + .dims = dims, + .width = width, + .codebook = .mcg, + .limit = limit, + .act_mode = 0, + .uniform_k2 = if (w.uniform_gu == w.uniform_d) w.uniform_gu else 0, + .uniform_k2_gu = w.uniform_gu, + .uniform_k2_d = w.uniform_d, + .shared_input = w.shx, + }; } /// A chunk's compacted picks ahead of the common scratch, 256-aligned; the usize keeps @min from narrowing to u7. -fn picksBytes(rows: usize) usize { +pub fn picksBytes(rows: usize) usize { const cap: usize = @min(rows, chunk_rows); return std.mem.alignForward(usize, cap * top_k * 4, 256); } @@ -146,12 +256,20 @@ fn picksBytes(rows: usize) usize { fn decodeBytes(l: common.Layer, n: usize) !usize { return @max(try common.scratchBytes(l, n, top_k), try common.fusedBytes(l, n, top_k + 1)); } -pub fn scratchBytes(rows: usize, dims: usize, width: usize, prefill: bool, shx: bool) [4]usize { - var l = shape(dims, width); - l.shared_input = shx; +/// The scratch `run` takes: the prompt kernels' when `prefill` and they take the layer, else the grouped path's. +pub fn scratchFor(rows: usize, dims: usize, width: usize, prefill: bool, w: Experts) [4]usize { + const l = layer(w, cuda.grouped.max_experts, dims, width, 0); if (prefill and common.prompt.eligible(l)) return .{ common.prompt.bytes(l, @min(rows, prompt_rows), top_k + 1) catch unreachable, 4, 4, 4 }; const n: usize = @min(rows, chunk_rows); - return .{ picksBytes(rows) + (decodeBytes(shape(dims, width), n) catch unreachable), 4, 4, 4 }; + return .{ picksBytes(rows) + (decodeBytes(l, n) catch unreachable), 4, 4, 4 }; +} +/// `scratchFor` a 4-bit layer (every projection 8 half-bits), `shx` its shared rotation. +pub fn scratchBytes(rows: usize, dims: usize, width: usize, prefill: bool, shx: bool) [4]usize { + return scratchFor(rows, dims, width, prefill, .{ .gt = 0, .ut = 0, .dt = 0, .k2 = 0, .suh_g = 0, .suh_u = 0, .svh_g = 0, .svh_u = 0, .suh_d = 0, .svh_d = 0, .uniform_gu = 8, .uniform_d = 8, .shx = shx }); +} +/// `most` raised to `w`'s scratch, entry by entry: buffers every layer's experts run in take the largest. +pub fn mostScratch(most: *[4]usize, rows: usize, dims: usize, width: usize, prefill: bool, w: Experts) void { + for (most, scratchFor(rows, dims, width, prefill, w)) |*m, v| m.* = @max(m.*, v); } /// `height` rows of `width` bytes, `spitch` apart at `src`, to `dpitch` apart at `dst`, in one call. fn copyRows(stream: cuda.Stream, dst: u64, dpitch: usize, src: u64, spitch: usize, width: usize, height: usize, what: []const u8) !void { @@ -161,7 +279,7 @@ fn copyRows(stream: cuda.Stream, dst: u64, dpitch: usize, src: u64, spitch: usiz pub fn run(k: *const Kernels, ek: *const experts.Kernels, stream: cuda.Stream, w: Experts, sc: Scratch, plan_buf: cuda.grouped.Plan, x: u64, x_stride: usize, picks: u64, slots: usize, rows: usize, count: usize, dims: usize, width: usize, limit: f32, prompt: bool, ey: u64, xd: u64) !void { _ = xd; if (slots != top_k + 1) return error.UnsupportedTopK; - if (dims % 256 != 0 or width % 128 != 0) return error.NotExl3Mcg4; + if (dims % 256 != 0 or width % 128 != 0) return error.UnreadableExl3; const l = layer(w, count, dims, width, limit); if (prompt and common.prompt.eligible(l)) { const scratch = try common.prompt.scratch(sc.picks, l, @min(rows, prompt_rows), slots); @@ -201,20 +319,8 @@ fn compact(k: *const Kernels, stream: cuda.Stream, w: Experts, sc: Scratch, x: u } } -test "EXL3 admission: Mia-AiLab's block passes; other widths and codebooks are refused by name" { - const gpa = std.testing.allocator; - const mia = - \\{"quantization_config": {"quant_method": "exl3", "bits": 4, "codebook": "mcg", "head_bits": 16}} - ; - try std.testing.expect(isExl3(gpa, mia)); - var why: modelopt.Why = .{}; - try admit(gpa, mia, &why); - try std.testing.expect(!isExl3(gpa, "{\"quantization_config\": {\"quant_method\": \"modelopt\"}}")); - try std.testing.expect(!isExl3(gpa, "{}")); - try std.testing.expectError(error.UnsupportedQuant, admit(gpa, "{\"quantization_config\": {\"quant_method\": \"exl3\", \"bits\": 3, \"codebook\": \"mcg\"}}", &why)); - try std.testing.expectEqualStrings("EXL3 at 3 bits: the CUDA family reads 4-bit EXL3 experts", why.text()); - try std.testing.expectError(error.UnsupportedQuant, admit(gpa, "{\"text_config\": {\"quantization_config\": {\"quant_method\": \"exl3\", \"bits\": 4, \"codebook\": \"mul1\"}}}", &why)); - try std.testing.expectEqualStrings("EXL3 codebook \"mul1\": the CUDA family reads \"mcg\"", why.text()); +test { + _ = @import("cuda_exl3_test.zig"); } test "a chunk's compacted picks end before the common scratch at every row count" { diff --git a/zig/src/families/glm/cuda_exl3_test.zig b/zig/src/families/glm/cuda_exl3_test.zig new file mode 100644 index 00000000000..92e6d02b649 --- /dev/null +++ b/zig/src/families/glm/cuda_exl3_test.zig @@ -0,0 +1,360 @@ +//! GLM EXL3: admission, trellis widths, the loader's uploads (mixed widths, 4-bit bytes as upstream's) and scratch. +const std = @import("std"); +const core = @import("core"); +const cuda = @import("cuda"); +const x3 = @import("cuda_exl3.zig"); +const modelopt = core.modelopt; +const Tensor = core.checkpoint.Tensor; +const Span = @import("cuda_shard.zig").Span; +const testing = std.testing; + +test "GLM EXL3: Mia-AiLab's 4-bit block and a mixed block without bits pass; other widths and codebooks are refused by name" { + const gpa = testing.allocator; + const mia = + \\{"quantization_config": {"quant_method": "exl3", "bits": 4, "codebook": "mcg", "head_bits": 16}} + ; + try testing.expect(x3.isExl3(gpa, mia)); + var why: modelopt.Why = .{}; + try x3.admit(gpa, mia, &why); + const mixed = // the 3.5 bpw checkpoint's: no "bits", its average instead + \\{"quantization_config": {"quant_method": "exl3", "avg_bits": 3.5039, "codebook": "mcg", "head_bits": 16, "scope": "glm53_routed_experts_only"}} + ; + try testing.expect(x3.isExl3(gpa, mixed)); + try x3.admit(gpa, mixed, &why); + try x3.admit(gpa, "{\"quantization_config\": {\"quant_method\": \"exl3\", \"bits\": 3, \"codebook\": \"mcg\"}}", &why); + try x3.admit(gpa, "{\"quantization_config\": {\"quant_method\": \"exl3\", \"bits\": 8.0, \"codebook\": \"mcg\"}}", &why); + try x3.admit(gpa, "{\"quantization_config\": {\"quant_method\": \"exl3\", \"codebook\": \"mcg\"}}", &why); + try testing.expect(!x3.isExl3(gpa, "{\"quantization_config\": {\"quant_method\": \"modelopt\"}}")); + try testing.expect(!x3.isExl3(gpa, "{}")); + try testing.expectError(error.UnsupportedQuant, x3.admit(gpa, "{\"quantization_config\": {\"quant_method\": \"exl3\", \"bits\": 9, \"codebook\": \"mcg\"}}", &why)); + try testing.expectEqualStrings("EXL3 at 9 bits: the CUDA family reads mcg experts of 1 to 8 whole bits", why.text()); + try testing.expectError(error.UnsupportedQuant, x3.admit(gpa, "{\"quantization_config\": {\"quant_method\": \"exl3\", \"bits\": 3.5, \"codebook\": \"mcg\"}}", &why)); + try testing.expectEqualStrings("EXL3 at 3.5 bits: the CUDA family reads mcg experts of 1 to 8 whole bits", why.text()); + try testing.expectError(error.UnsupportedQuant, x3.admit(gpa, "{\"quantization_config\": {\"quant_method\": \"exl3\", \"bits\": \"4\", \"codebook\": \"mcg\"}}", &why)); + try testing.expectError(error.UnsupportedQuant, x3.admit(gpa, "{\"quantization_config\": {\"quant_method\": \"exl3\", \"avg_bits\": 0.5, \"codebook\": \"mcg\"}}", &why)); + try testing.expectEqualStrings("EXL3 averaging 0.5 bits: the CUDA family reads mcg experts of 1 to 8 bits", why.text()); + try testing.expectError(error.UnsupportedQuant, x3.admit(gpa, "{\"text_config\": {\"quantization_config\": {\"quant_method\": \"exl3\", \"bits\": 4, \"codebook\": \"mul1\"}}}", &why)); + try testing.expectEqualStrings("EXL3 codebook \"mul1\": the CUDA family reads \"mcg\"", why.text()); + try testing.expectError(error.UnsupportedQuant, x3.admit(gpa, "{\"quantization_config\": {\"quant_method\": \"exl3\", \"avg_bits\": 3.5}}", &why)); + try testing.expectEqualStrings("EXL3 codebook null: the CUDA family reads \"mcg\"", why.text()); +} + +test "GLM EXL3: a trellis's last dimension gives whole-bit mcg widths from 1 to 8; half steps and wider are refused" { + for ([_][2]usize{ .{ 16, 2 }, .{ 32, 4 }, .{ 48, 6 }, .{ 64, 8 }, .{ 80, 10 }, .{ 96, 12 }, .{ 112, 14 }, .{ 128, 16 } }) |c| + try testing.expectEqual(@as(?u32, @as(u32, @intCast(c[1]))), x3.halves(c[0])); + for ([_]usize{ 0, 8, 24, 40, 56, 50, 136, 144 }) |last| try testing.expectEqual(@as(?u32, null), x3.halves(last)); + try testing.expectEqual(@as(usize, 128), x3.tileBytes(8)); + try testing.expectEqual(@as(usize, 96), x3.tileBytes(6)); +} + +/// A checkpoint in memory and device uploads recorded on the host, as cuda_weights' loader is to `load`. +const Mock = struct { + gpa: std.mem.Allocator, + arena: std.heap.ArenaAllocator, + tensors: std.StringHashMapUnmanaged(Tensor) = .empty, + host: std.ArrayList(u8) = .empty, + puts: std.ArrayList(Put) = .empty, + name_buf: [192]u8 = undefined, + last: []const u8 = "", + next: u64 = 0x7f00_0000_0000, + + const Put = struct { name: []const u8, bytes: []const u8, ptr: u64 }; + + fn init(gpa: std.mem.Allocator) Mock { + return .{ .gpa = gpa, .arena = .init(gpa) }; + } + fn deinit(m: *Mock) void { + m.host.deinit(m.gpa); + m.arena.deinit(); + } + pub fn get(m: *Mock, comptime fmt: []const u8, args: anytype) !Tensor { + m.last = try std.fmt.bufPrint(&m.name_buf, fmt, args); + return m.tensors.get(m.last) orelse error.MissingTensor; + } + pub fn put(m: *Mock, comptime fmt: []const u8, args: anytype) !u64 { + const a = m.arena.allocator(); + const ptr = m.next; + m.next += std.mem.alignForward(u64, m.host.items.len + 1, 1 << 20); + try m.puts.append(a, .{ .name = try std.fmt.allocPrint(a, fmt, args), .bytes = try a.dupe(u8, m.host.items), .ptr = ptr }); + m.host.clearRetainingCapacity(); + return ptr; + } + fn add(m: *Mock, name: []const u8, dtype: core.checkpoint.DType, shape: []const usize, bytes: []const u8) !void { + const a = m.arena.allocator(); + var t: Tensor = .{ .dtype = dtype, .rank = @intCast(shape.len), .shape = @splat(0), .bytes = try a.dupe(u8, bytes) }; + @memcpy(t.shape[0..shape.len], shape); + try m.tensors.put(a, try a.dupe(u8, name), t); + } + fn find(m: *const Mock, name: []const u8) ?Put { + for (m.puts.items) |p| if (std.mem.eql(u8, p.name, name)) return p; + return null; + } +}; + +const projs = [_][]const u8{ "gate_proj", "up_proj", "down_proj" }; + +/// Layer `i`'s experts: p of e at `k2s[p][e]` half-bits, random mcg words and scales; `shared`: one input scale. +fn synth(m: *Mock, rng: std.Random, i: u32, count: usize, dims: usize, inter: usize, k2s: [3][]const u32, shared: bool) !void { + const a = m.arena.allocator(); + const rot = try a.alloc(u8, dims * 2); + rng.bytes(rot); + for (projs, 0..) |proj, p| { + const k = if (p < 2) dims else inter; + const n = if (p < 2) inter else dims; + for (0..count) |e| { + var buf: [128]u8 = undefined; + const k2 = k2s[p][e]; + const words = try a.alloc(u8, k / 16 * (n / 16) * 16 * k2); + rng.bytes(words); + try m.add(try std.fmt.bufPrint(&buf, "layers.{d}.mlp.experts.{d}.{s}.trellis", .{ i, e, proj }), .i16, &.{ k / 16, n / 16, 8 * k2 }, words); + var marker: [4]u8 = undefined; + std.mem.writeInt(u32, &marker, core.exl3_load.markers[0].value, .little); + try m.add(try std.fmt.bufPrint(&buf, "layers.{d}.mlp.experts.{d}.{s}.mcg", .{ i, e, proj }), .i32, &.{1}, &marker); + const suh = try a.alloc(u8, k * 2); + if (shared and p < 2) @memcpy(suh, rot) else rng.bytes(suh); + try m.add(try std.fmt.bufPrint(&buf, "layers.{d}.mlp.experts.{d}.{s}.suh", .{ i, e, proj }), .f16, &.{k}, suh); + const svh = try a.alloc(u8, n * 2); + rng.bytes(svh); + try m.add(try std.fmt.bufPrint(&buf, "layers.{d}.mlp.experts.{d}.{s}.svh", .{ i, e, proj }), .f16, &.{n}, svh); + } + } +} + +/// The rank's tiles of projection `p`, tile by tile (gate/up: every tile row, `cut`'s cols; down: `cut`'s rows). +fn expectedTiles(m: *Mock, i: u32, count: usize, dims: usize, inter: usize, cut: Span, p: usize) ![]u8 { + var out: std.ArrayList(u8) = .empty; + const k = if (p < 2) dims else inter; + const n = if (p < 2) inter else dims; + for (0..count) |e| { + var buf: [128]u8 = undefined; + const t = m.tensors.get(try std.fmt.bufPrint(&buf, "layers.{d}.mlp.experts.{d}.{s}.trellis", .{ i, e, projs[p] })).?; + const tile = t.dim(2) * 2; + const rows: [2]usize = if (p < 2) .{ 0, k / 16 } else .{ cut.lo / 16, cut.hi / 16 }; + const cols: [2]usize = if (p < 2) .{ cut.lo / 16, cut.hi / 16 } else .{ 0, n / 16 }; + for (rows[0]..rows[1]) |r| for (cols[0]..cols[1]) |c| + try out.appendSlice(m.arena.allocator(), t.bytes[(r * (n / 16) + c) * tile ..][0..tile]); + } + return out.items; +} + +fn ptrsOf(bytes: []const u8) []align(1) const u64 { + return std.mem.bytesAsSlice(u64, bytes); +} + +/// Every projection's tiles, pointers and width table as `load` uploaded them, vs the checkpoint, tile by tile. +fn expectUploads(m: *Mock, w: x3.Experts, i: u32, count: usize, dims: usize, inter: usize, cut: Span, k2s: [3][]const u32) !void { + for ([_][]const u8{ "gt", "ut", "dt" }, [_]u64{ w.gt, w.ut, w.dt }, 0..) |tw, ptrs_at, p| { + var buf: [96]u8 = undefined; + const words = m.find(try std.fmt.bufPrint(&buf, "layers.{d}.moe.exl3.{s}", .{ i, tw })).?; + try testing.expectEqualSlices(u8, try expectedTiles(m, i, count, dims, inter, cut, p), words.bytes); + const ptrs = m.find(try std.fmt.bufPrint(&buf, "layers.{d}.moe.exl3.{s}_ptrs", .{ i, tw })).?; + try testing.expectEqual(ptrs.ptr, ptrs_at); + const tiles = if (p < 2) dims / 16 * (cut.len() / 16) else cut.len() / 16 * (dims / 16); + var at = words.ptr; + for (ptrsOf(ptrs.bytes), 0..) |ptr, e| { + try testing.expectEqual(at, ptr); + at += tiles * 16 * k2s[p][e]; + } + try testing.expectEqual(words.ptr + words.bytes.len, at); + const table = for (m.puts.items) |put| { + if (put.ptr == w.tables()[p]) break put; + } else return error.NoTable; + for (std.mem.bytesAsSlice(i32, table.bytes), k2s[p]) |got, want| try testing.expectEqual(@as(i32, @intCast(want)), got); + } +} + +test "GLM EXL3: a mixed layer (3-bit gate and up, 4-bit down) loads each width's tiles, pointers and tables on either rank" { + const gpa = testing.allocator; + var prng = std.Random.DefaultPrng.init(53); + const count = 5; + const dims = 256; + const inter = 512; + const gu: [count]u32 = @splat(6); + const dn: [count]u32 = @splat(8); + const k2s: [3][]const u32 = .{ &gu, &gu, &dn }; + for ([_]Span{ .{ .lo = 0, .hi = 256 }, .{ .lo = 256, .hi = 512 }, .{ .lo = 128, .hi = 384 } }) |cut| { + var m = Mock.init(gpa); + defer m.deinit(); + try synth(&m, prng.random(), 4, count, dims, inter, k2s, true); + const w = try x3.load(&m, 4, count, dims, inter, cut); + try expectUploads(&m, w, 4, count, dims, inter, cut, k2s); + try testing.expectEqual(@as(u32, 6), w.uniform_gu); + try testing.expectEqual(@as(u32, 8), w.uniform_d); + try testing.expect(w.shx); + try testing.expectEqual(w.k2, w.k2_up); // gate and up's widths agree: one table + try testing.expect(w.k2 != w.k2_down); + try testing.expect(m.find("layers.4.moe.exl3.k2_gate") != null and m.find("layers.4.moe.exl3.k2_down") != null); + try testing.expect(m.find("layers.4.moe.exl3.k2_up") == null and m.find("layers.4.moe.exl3.k2") == null); + const l = x3.layer(w, count, dims, cut.len(), 10); + try testing.expectEqual(@as(u32, 0), l.uniform_k2); // gate/up and down differ: no one width + try testing.expectEqual(@as(u32, 6), l.uniform_k2_gu); + try testing.expectEqual(@as(u32, 8), l.uniform_k2_d); + try testing.expect(l.gate_k2 == w.k2 and l.up_k2 == w.k2_up and l.down_k2 == w.k2_down); + } +} + +test "GLM EXL3: widths that differ by expert and projection keep their own offsets; no uniform width is claimed" { + const gpa = testing.allocator; + var prng = std.Random.DefaultPrng.init(7); + const count = 4; + const g = [count]u32{ 6, 8, 2, 16 }; + const u = [count]u32{ 8, 8, 8, 8 }; + const d = [count]u32{ 4, 6, 8, 12 }; + const k2s: [3][]const u32 = .{ &g, &u, &d }; + var m = Mock.init(gpa); + defer m.deinit(); + try synth(&m, prng.random(), 9, count, 256, 256, k2s, false); + const cut: Span = .{ .lo = 128, .hi = 256 }; + const w = try x3.load(&m, 9, count, 256, 256, cut); + try expectUploads(&m, w, 9, count, 256, 256, cut, k2s); + try testing.expectEqual(@as(u32, 0), w.uniform_gu); + try testing.expectEqual(@as(u32, 0), w.uniform_d); + try testing.expect(!w.shx); + try testing.expect(w.k2 != w.k2_up and w.k2_up != w.k2_down and w.k2 != w.k2_down); + const l = x3.layer(w, count, 256, 128, 10); + try testing.expect(l.uniform_k2 == 0 and l.uniform_k2_gu == 0 and l.uniform_k2_d == 0); + try testing.expect(!cuda.exl3_experts.prompt.eligible(l)); +} + +test "GLM EXL3: a trellis at a width the kernels do not read, or of the wrong shape, is refused with its reason" { + const bytes: [72 * 2 * 2 * 2]u8 = @splat(0); + var t: Tensor = .{ .dtype = .i16, .rank = 3, .shape = .{ 2, 2, 40, 0, 0 }, .bytes = bytes[0 .. 2 * 2 * 40 * 2] }; + try testing.expect(x3.refusal(t, 32, 32) != null); // 2.5 bits: mul1's half steps + t.shape[2] = 72; // 4.5 bits + t.bytes = bytes[0 .. 2 * 2 * 72 * 2]; + try testing.expect(x3.refusal(t, 32, 32) != null); + t.shape[2] = 64; + t.bytes = bytes[0 .. 2 * 2 * 64 * 2]; + try testing.expectEqual(@as(?[]const u8, null), x3.refusal(t, 32, 32)); + try testing.expect(x3.refusal(t, 48, 32) != null); // tiles that do not cover K + t.dtype = .i32; + try testing.expect(x3.refusal(t, 32, 32) != null); + t.dtype = .i16; + t.bytes = bytes[0..10]; + try testing.expect(x3.refusal(t, 32, 32) != null); +} + +/// Upstream's 4-bit loader (f350cd3e), verbatim but its result's type: a 4-bit layer uploads exactly these bytes. +const Upstream = struct { gt: u64, ut: u64, dt: u64, suh_g: u64, suh_u: u64, svh_g: u64, svh_u: u64, suh_d: u64, svh_d: u64, k2: u64, shx: bool }; +fn upstream4(L: anytype, i: u32, count: usize, dims: usize, inter: usize, cut: Span) !Upstream { + const tile = 128; + if (dims % 128 != 0 or cut.lo % 128 != 0 or cut.hi % 128 != 0) return error.NotExl3Mcg4; + const width = cut.len(); + var out: Upstream = undefined; + out.shx = true; + const Mat = struct { k: usize, n: usize, by_cols: bool }; + const mats = [_]Mat{ + .{ .k = dims, .n = inter, .by_cols = true }, + .{ .k = dims, .n = inter, .by_cols = true }, + .{ .k = inter, .n = dims, .by_cols = false }, + }; + var first_suh: ?[]const u8 = null; + inline for (mats, .{ "gate_proj", "up_proj", "down_proj" }, .{ "gt", "ut", "dt" }, .{ "suh_g", "suh_u", "suh_d" }, .{ "svh_g", "svh_u", "svh_d" }) |m, proj, tw, su, sv| { + const kt = (if (m.by_cols) m.k else width) / 16; + const nt = (if (m.by_cols) width else m.n) / 16; + for (0..count) |e| { + const t = try L.get("layers.{d}.mlp.experts.{d}." ++ proj ++ ".trellis", .{ i, e }); + if (t.dtype != .i16 or t.rank != 3 or t.dim(0) != m.k / 16 or t.dim(1) != m.n / 16 or t.dim(2) != 64) return error.NotExl3Mcg4; + const marker = L.get("layers.{d}.mlp.experts.{d}." ++ proj ++ ".mcg", .{ i, e }) catch return error.NotExl3Mcg4; + if (marker.dtype != .i32 or marker.numel() != 1 or marker.bytes.len != 4 or + std.mem.readInt(u32, marker.bytes[0..4], .little) != core.exl3_load.markers[0].value) + return error.NotExl3Mcg4; + if (m.by_cols) { + const row = (m.n / 16) * tile; + for (0..kt) |r| try L.host.appendSlice(L.gpa, t.bytes[r * row + (cut.lo / 16) * tile ..][0 .. nt * tile]); + } else try L.host.appendSlice(L.gpa, t.bytes[(cut.lo / 16) * nt * tile ..][0 .. kt * nt * tile]); + } + const base = try L.put("layers.{d}.moe.exl3." ++ tw, .{i}); + for (0..count) |e| { + const ptr = base + e * kt * nt * tile; + try L.host.appendSlice(L.gpa, std.mem.asBytes(&ptr)); + } + @field(out, tw) = try L.put("layers.{d}.moe.exl3." ++ tw ++ "_ptrs", .{i}); + for (0..count) |e| { + const t = try L.get("layers.{d}.mlp.experts.{d}." ++ proj ++ ".suh", .{ i, e }); + if (t.dtype != .f16 or t.numel() != m.k) return error.NotExl3Mcg4; + const mine = if (m.by_cols) t.bytes else t.bytes[cut.lo * 2 .. cut.hi * 2]; + if (m.by_cols) { + if (first_suh) |f| (if (!std.mem.eql(u8, f, mine)) { + out.shx = false; + }) else first_suh = mine; + } + try L.host.appendSlice(L.gpa, mine); + } + @field(out, su) = try L.put("layers.{d}.moe.exl3." ++ su, .{i}); + for (0..count) |e| { + const t = try L.get("layers.{d}.mlp.experts.{d}." ++ proj ++ ".svh", .{ i, e }); + if (t.dtype != .f16 or t.numel() != m.n) return error.NotExl3Mcg4; + try L.host.appendSlice(L.gpa, if (m.by_cols) t.bytes[cut.lo * 2 .. cut.hi * 2] else t.bytes); + } + @field(out, sv) = try L.put("layers.{d}.moe.exl3." ++ sv, .{i}); + } + for (0..count) |_| { + const bits: i32 = 8; + try L.host.appendSlice(L.gpa, std.mem.asBytes(&bits)); + } + out.k2 = try L.put("layers.{d}.moe.exl3.k2", .{i}); + return out; +} + +test "GLM EXL3: a 4-bit layer uploads upstream's bytes, names and pointers, and keeps one width (8) for every path" { + const gpa = testing.allocator; + for ([_]bool{ true, false }, [_]Span{ .{ .lo = 256, .hi = 512 }, .{ .lo = 0, .hi = 512 } }) |shared, cut| { + var prng = std.Random.DefaultPrng.init(4); + const count = 6; + const four: [count]u32 = @splat(8); + var m = Mock.init(gpa); + defer m.deinit(); + try synth(&m, prng.random(), 3, count, 256, 512, .{ &four, &four, &four }, shared); + var old = Mock.init(gpa); + defer old.deinit(); + old.tensors = m.tensors; + const want = try upstream4(&old, 3, count, 256, 512, cut); + const got = try x3.load(&m, 3, count, 256, 512, cut); + try testing.expectEqual(old.puts.items.len, m.puts.items.len); + for (old.puts.items, m.puts.items) |a, b| { + try testing.expectEqualStrings(a.name, b.name); + try testing.expectEqual(a.ptr, b.ptr); + try testing.expectEqualSlices(u8, a.bytes, b.bytes); + } + inline for (.{ "gt", "ut", "dt", "suh_g", "suh_u", "svh_g", "svh_u", "suh_d", "svh_d", "k2", "shx" }) |f| try testing.expectEqual(@field(want, f), @field(got, f)); + try testing.expectEqual([3]u64{ want.k2, want.k2, want.k2 }, got.tables()); + try testing.expect(got.uniform_gu == 8 and got.uniform_d == 8); + const l = x3.layer(got, count, 256, cut.len(), 10); + try testing.expect(l.uniform_k2 == 8 and l.uniform_k2_gu == 8 and l.uniform_k2_d == 8); + try testing.expect(l.shared_input == shared); + } +} + +test "GLM EXL3: scratch covers the path each layer takes: the prompt kernels' when they take it, else the grouped path's" { + const dims = 4096; + const width = 1024; + const four: x3.Experts = .{ .gt = 0, .ut = 0, .dt = 0, .suh_g = 0, .suh_u = 0, .svh_g = 0, .svh_u = 0, .suh_d = 0, .svh_d = 0, .k2 = 0, .uniform_gu = 8, .uniform_d = 8, .shx = true }; + var mixed = four; + mixed.uniform_gu = 6; + var any = four; + any.uniform_gu = 0; + any.uniform_d = 0; + const common = cuda.exl3_experts; + for ([_]usize{ 1, 8, 200, 1024, 2048, 4102 }) |rows| { + const n: usize = @min(rows, x3.chunk_rows); + const whole: usize = @min(rows, x3.prompt_rows); // the prompt kernels take a whole pass of top_k + 1 slots + for ([_]x3.Experts{ four, mixed, any }) |w| for ([_]bool{ false, true }) |prefill| { + const l = x3.layer(w, cuda.grouped.max_experts, dims, width, 0); + const prompt = prefill and common.prompt.eligible(l); + const need = if (prompt) try common.prompt.bytes(l, whole, x3.top_k + 1) else x3.picksBytes(rows) + try common.scratchBytes(l, n, x3.top_k); + try testing.expectEqual(need, x3.scratchFor(rows, dims, width, prefill, w)[0]); + }; + // a 4-bit layer's scratch is upstream's: the prompt kernels', or picks then the grouped path's + const upstream: common.Layer = .{ .gate = 0, .up = 0, .down = 0, .gate_k2 = 0, .up_k2 = 0, .down_k2 = 0, .suh_g = 0, .suh_u = 0, .svh_g = 0, .svh_u = 0, .suh_d = 0, .svh_d = 0, .experts = cuda.grouped.max_experts, .dims = dims, .width = width, .codebook = .mcg, .act_mode = 0, .uniform_k2 = 8, .shared_input = true }; + try testing.expectEqual(try common.prompt.bytes(upstream, whole, x3.top_k + 1), x3.scratchFor(rows, dims, width, true, four)[0]); + try testing.expectEqual(x3.picksBytes(rows) + try common.scratchBytes(upstream, n, x3.top_k), x3.scratchFor(rows, dims, width, false, four)[0]); + for ([_]bool{ false, true }) |prefill| try testing.expectEqual(x3.scratchFor(rows, dims, width, prefill, four), x3.scratchBytes(rows, dims, width, prefill, true)); + // buffers for every layer take the largest: a 4-bit layer's prompt arena grows to the mixed layer's grouped one + var most: [4]usize = @splat(4); + x3.mostScratch(&most, rows, dims, width, true, four); + x3.mostScratch(&most, rows, dims, width, true, any); + try testing.expectEqual(@max(x3.scratchFor(rows, dims, width, true, four)[0], x3.scratchFor(rows, dims, width, true, any)[0]), most[0]); + try testing.expectEqual([3]usize{ 4, 4, 4 }, most[1..4].*); + } +} diff --git a/zig/src/families/glm/cuda_native.zig b/zig/src/families/glm/cuda_native.zig index e933c6b4c81..783bddcac79 100644 --- a/zig/src/families/glm/cuda_native.zig +++ b/zig/src/families/glm/cuda_native.zig @@ -523,11 +523,9 @@ pub fn explain(_: ?*anyopaque, err: anyerror) ?[]const u8 { error.BadCopyPolicy => "TF_GLM_COPIES: expected 0 or 1 for verified root/context copies", error.InvalidEnvironment => "a TF_GLM_* setting is malformed: the error line before this one names it, its value and the accepted form", error.GlmKvHostNeedsPages => "TF_GLM_KV_HOST keeps the KV pool's pages in host memory: set TF_KV_PAGES=on (and --kv-cache bf16) as well", - error.TooManyRanks => std.fmt.comptimePrint( - "GLM-5.3-Flash on CUDA runs on at most {d} ranks: set TF_GLM_WORLD to {d} or fewer", - .{ ranks.max_world, ranks.max_world }, - ), - error.NotModelOpt, error.UnsupportedQuant => "GLM-5.3-Flash on CUDA reads ModelOpt NVFP4 and MIXED_PRECISION checkpoints (the log names what config.json has)", + error.TooManyRanks => std.fmt.comptimePrint("GLM-5.3-Flash on CUDA runs on at most {d} ranks: set TF_GLM_WORLD to {d} or fewer", .{ ranks.max_world, ranks.max_world }), + error.NotModelOpt, error.UnsupportedQuant => "GLM-5.3-Flash on CUDA reads ModelOpt NVFP4, MIXED_PRECISION and EXL3 mcg checkpoints (the log names what config.json has)", + error.UnreadableExl3 => "an EXL3 routed expert is not an mcg trellis of 1 to 8 bits with its marker and fp16 scales (the log names the tensor)", error.UnreadableFormat => "a projection is stored in a format GLM-5.3-Flash on CUDA does not read (the log names its module, recipe and tensors)", else => null, }; @@ -541,7 +539,7 @@ test "a place inside its world of at most 16 ranks serves; a larger world is ref } test "a checkpoint refused for its format, at the entry or by the loader, is explained" { - for ([_]anyerror{ error.NotModelOpt, error.UnsupportedQuant, error.UnreadableFormat }) |e| try std.testing.expect(explain(null, e) != null); + for ([_]anyerror{ error.NotModelOpt, error.UnsupportedQuant, error.UnreadableFormat, error.UnreadableExl3 }) |e| try std.testing.expect(explain(null, e) != null); } test "TF_KV_SHARE past the slots a startup plan holds is refused, and the refusal is explained" { diff --git a/zig/src/families/glm/cuda_state.zig b/zig/src/families/glm/cuda_state.zig index 5a5c8919a69..633ea2e06a9 100644 --- a/zig/src/families/glm/cuda_state.zig +++ b/zig/src/families/glm/cuda_state.zig @@ -247,7 +247,10 @@ pub const Buffers = struct { var mm: usize = 4; // windows under rows_from rows keep their K slices apart (a prompt's tail chunk on the prefill buffers too) for (b16Shapes(w)) |sh_| mm = @max(mm, b16.partBytes(@min(rows, b16.rows_from - 1), sh_[0], sh_[1])); - const x3: [4]usize = if (c.exl3) exl3.scratchBytes(rows, D, ew, prefill, w.exl3_shx) else @splat(4); + // EXL3 experts: each layer's path (the prompt kernels', or the grouped one) sizes it + var x3: [4]usize = @splat(4); + for (w.layers) |l| if (l.ffn == .moe) if (l.ffn.moe.exl3) |x| exl3.mostScratch(&x3, rows, D, ew, prefill, x); + if (w.mtp) |m| if (m.layer.ffn == .moe) if (m.layer.ffn.moe.exl3) |x| exl3.mostScratch(&x3, rows, D, ew, prefill, x); var split = false; // a KDA stack in two parts moves each part's rows through one more buffer for (w.layers) |l| split = split or (l.mixer == .kda and l.mixer.kda.proj == .split); const hist_len = if (pairs > cuda.grouped.small) (pairs + cuda.grouped.small - 1) / cuda.grouped.small * (count + 1) else 1; diff --git a/zig/src/families/glm/cuda_weights.zig b/zig/src/families/glm/cuda_weights.zig index 696a4238146..438c71d93ad 100644 --- a/zig/src/families/glm/cuda_weights.zig +++ b/zig/src/families/glm/cuda_weights.zig @@ -43,7 +43,6 @@ pub const Weights = struct { norm: glue.Norm = .{ .bf16 = 0 }, head: projection.Proj = .{ .bf16 = 0 }, // [share.vocab][dims]: bf16, or MXFP8 for the lane mtp: ?Mtp = null, - exl3_shx: bool = true, // EXL3: every layer's gate and up share one input rotation (a prompt rotates each row once) buffers: std.ArrayList(cuda.DeviceBuffer) = .empty, named: std.ArrayList(Named) = .empty, @@ -441,7 +440,6 @@ const Loader = struct { var x3: ?exl3.Experts = null; if (c.exl3) { // the MTP layer's experts too x3 = try exl3.load(L, i, count, d, c.moe_inter, cut); - if (!x3.?.shx) L.w.exl3_shx = false; } else routed = try L.nvfp4Experts(i); const sh = L.w.share.shared; const sw: []const formats.Format = if (i == c.layers) &.{ .bf16, .fp8_pb, .mxfp8 } else &.{ .bf16, .fp8_pb }; // MTP's MXFP8 diff --git a/zig/tests/cuda/exl3_commands.zig b/zig/tests/cuda/exl3_commands.zig new file mode 100644 index 00000000000..b8bbeade3b6 --- /dev/null +++ b/zig/tests/cuda/exl3_commands.zig @@ -0,0 +1,22 @@ +//! The CUDA runner's one-GPU EXL3 commands (exl3 and exl3-*; exl3-tp2 stays in main.zig with its argument checks). +const std = @import("std"); +const check = @import("check.zig"); +const plans = @import("exl3_plan_bench.zig"); + +const Command = enum { exl3, @"exl3-grouped-tile", @"exl3-tiles", @"exl3-shapes", @"exl3-midm", @"exl3-plans", @"exl3-contract", @"exl3-prompt-k6" }; + +/// Runs `cmd` when it is one of these commands; false leaves it to the runner's others (and its usage). +pub fn run(gpu: check.Gpu, cmd: []const u8, rest: []const [:0]const u8) !bool { + const first: ?[]const u8 = if (rest.len > 0) rest[0] else null; + switch (std.meta.stringToEnum(Command, cmd) orelse return false) { + .exl3 => try @import("exl3_tests.zig").run(gpu, first orelse "none"), + .@"exl3-grouped-tile" => try @import("exl3_grouped_tile_tests.zig").run(gpu), + .@"exl3-tiles" => try @import("exl3_candidate_tests.zig").run(gpu, first), + .@"exl3-shapes" => try plans.profileShapes(gpu, first), + .@"exl3-midm" => try plans.midm(gpu), + .@"exl3-plans" => try plans.run(gpu, first), + .@"exl3-contract" => try @import("contract_exl3.zig").run(gpu), + .@"exl3-prompt-k6" => try @import("exl3_prompt_k6_tests.zig").run(gpu, first orelse "none", if (rest.len > 1) rest[1] else null), + } + return true; +} diff --git a/zig/tests/cuda/exl3_prompt_k6_real.zig b/zig/tests/cuda/exl3_prompt_k6_real.zig new file mode 100644 index 00000000000..7d514ca0c05 --- /dev/null +++ b/zig/tests/cuda/exl3_prompt_k6_real.zig @@ -0,0 +1,115 @@ +//! A real GLM-5.3-Flash EXL3 layer's rank-0 TP-2 share through the prompt kernels: runSlots, float64 and time. +const std = @import("std"); +const core = @import("core"); +const check = @import("check.zig"); +const t = @import("exl3_prompt_k6_tests.zig"); +const st = core.safetensors; +const D = t.D; +const N = t.N; +const E = t.E; + +const layer_index = 4; // a layer with 3-bit gate and up and 4-bit down in the 3.5 bpw GLMQ checkpoint + +/// The checkpoint's shard files, opened once each. +const Shards = struct { + dir: []const u8, + map: std.json.ObjectMap, + open: std.StringHashMapUnmanaged(st.File) = .empty, + fn tensor(s: *Shards, c: *t.Ctx, name: []const u8) !st.Tensor { + const shard = (s.map.get(name) orelse return error.TensorNotInIndex).string; + const got = try s.open.getOrPut(c.a, shard); + if (!got.found_existing) got.value_ptr.* = try st.File.open(c.gpu.gpa, c.gpu.io, try std.fmt.allocPrint(c.a, "{s}/{s}", .{ s.dir, shard })); + return got.value_ptr.get(name) orelse error.TensorNotInShard; + } + fn close(s: *Shards, c: *t.Ctx) void { + var it = s.open.valueIterator(); + while (it.next()) |f| f.close(c.gpu.io); + } +}; + +/// Every expert's words of one projection: gate and up keep tile columns 0-63, down tile rows 0-63 (rank 0 of 2). +fn trellis(c: *t.Ctx, sh: *Shards, which: []const u8, k2: *u32) ![]const []const i16 { + const out = try c.a.alloc([]const i16, E); + var all: []i16 = &.{}; + for (0..E) |e| { + const tt = try sh.tensor(c, try std.fmt.allocPrint(c.a, "model.language_model.layers.{d}.mlp.experts.{d}.{s}_proj.trellis", .{ layer_index, e, which })); + const down = std.mem.eql(u8, which, "down"); + const tk: usize = if (down) 2 * N / 16 else D / 16; + const tn: usize = if (down) D / 16 else 2 * N / 16; + if (tt.dtype != .i16 or tt.rank != 3 or tt.dim(0) != tk or tt.dim(1) != tn or tt.dim(2) % 16 != 0) return error.UnexpectedTrellis; + const w: u32 = @intCast(tt.dim(2) / 8); + if (e == 0) { + k2.* = w; + all = try c.a.alloc(i16, E * t.words(w)); + } else if (w != k2.*) return error.MixedWidthsInProjection; + const src: []align(1) const i16 = std.mem.bytesAsSlice(i16, tt.bytes); + const dst = all[e * t.words(w) ..][0..t.words(w)]; + const tw = tt.dim(2); + if (down) { + @memcpy(dst, src[0..dst.len]); + } else for (0..D / 16) |r| @memcpy(dst[r * (N / 16) * tw ..][0 .. (N / 16) * tw], src[r * tn * tw ..][0 .. (N / 16) * tw]); + out[e] = dst; + } + return out; +} + +/// Each expert's fp16 scale vector `part` of a projection, its first `n` values (rank 0's share of a split one). +fn scale(c: *t.Ctx, sh: *Shards, which: []const u8, part: []const u8, n: usize) ![]f16 { + const out = try c.a.alloc(f16, E * n); + for (0..E) |e| { + const tt = try sh.tensor(c, try std.fmt.allocPrint(c.a, "model.language_model.layers.{d}.mlp.experts.{d}.{s}_proj.{s}", .{ layer_index, e, which, part })); + if (tt.dtype != .f16 or tt.numel() < n) return error.UnexpectedScale; + const src: []align(1) const f16 = std.mem.bytesAsSlice(f16, tt.bytes); + @memcpy(out[e * n ..][0..n], src[0..n]); + } + return out; +} + +fn upload(b: *t.Bufs, c: *t.Ctx, each: []const []const i16) !u64 { + const n = each[0].len; + const base = try b.alloc(E * n * 2); + const table = try c.a.alloc(u64, E); + for (each, 0..) |w, e| { + const buf: @import("cuda").DeviceBuffer = .{ .d = c.gpu.d, .ptr = base, .len = E * n * 2 }; + try buf.upload(e * n * 2, std.mem.sliceAsBytes(w)); + table[e] = base + e * n * 2; + } + return b.put(std.mem.sliceAsBytes(table)); +} + +pub fn run(c: *t.Ctx, dir: []const u8, rng: std.Random) !void { + const index_bytes = try std.Io.Dir.cwd().readFileAlloc(c.gpu.io, try std.fmt.allocPrint(c.a, "{s}/model.safetensors.index.json", .{dir}), c.a, .limited(64 << 20)); + const index = try std.json.parseFromSlice(std.json.Value, c.a, index_bytes, .{}); + var sh: Shards = .{ .dir = dir, .map = index.value.object.get("weight_map").?.object }; + defer sh.close(c); + var kg: u32 = 0; + var ku: u32 = 0; + var kd: u32 = 0; + const hg = try trellis(c, &sh, "gate", &kg); + const hu = try trellis(c, &sh, "up", &ku); + const hd = try trellis(c, &sh, "down", &kd); + try check.expect(kg == ku and (kg == 6 or kg == 8) and (kd == 6 or kd == 8), "real layer {d}: gate {d}, up {d}, down {d} half-bits", .{ layer_index, kg, ku, kd }); + const sg = try scale(c, &sh, "gate", "suh", D); + const su = try scale(c, &sh, "up", "suh", D); + const vg = try scale(c, &sh, "gate", "svh", N); + const vu = try scale(c, &sh, "up", "svh", N); + const sd = try scale(c, &sh, "down", "suh", N); + const vd = try scale(c, &sh, "down", "svh", D); + var shared = true; // the loader's check: one input scale vector for every gate and up + for (0..E) |e| shared = shared and std.mem.eql(u8, std.mem.sliceAsBytes(sg[e * D ..][0..D]), std.mem.sliceAsBytes(sg[0..D])) and std.mem.eql(u8, std.mem.sliceAsBytes(su[e * D ..][0..D]), std.mem.sliceAsBytes(sg[0..D])); + std.debug.print("INFO real layer {d} (rank 0 of 2): gate/up {d}-bit, down {d}-bit, input scales {s}\n", .{ layer_index, kg / 2, kd / 2, if (shared) "shared by every gate and up" else "per projection" }); + var b: t.Bufs = .{ .d = c.gpu.d, .gpa = c.gpu.gpa }; + defer b.deinit(); + const s: t.Set = .{ .gp = try upload(&b, c, hg), .up = try upload(&b, c, hu), .dp = try upload(&b, c, hd), .k2 = try t.widthTables(&b), .suh_g = try b.put(std.mem.sliceAsBytes(sg)), .suh_u = try b.put(std.mem.sliceAsBytes(su)), .svh_g = try b.put(std.mem.sliceAsBytes(vg)), .svh_u = try b.put(std.mem.sliceAsBytes(vu)), .suh_d = try b.put(std.mem.sliceAsBytes(sd)), .svh_d = try b.put(std.mem.sliceAsBytes(vd)), .shared = shared, .hg = hg, .hu = hu, .hd = hd, .sg = sg, .su = su, .vg = vg, .vu = vu, .sd = sd, .vd = vd }; + const in = try t.inputs(c, rng, 4096); + const dx = try b.put(std.mem.sliceAsBytes(in.x)); + const dpk = try b.put(std.mem.sliceAsBytes(in.pk)); + var m: t.Mats = .{}; + defer m.deinit(c.gpu.gpa); + for ([_]bool{ true, false }) |one| { + if (one and !shared) continue; + try t.widthsCase(c, &m, &s, kg, kd, one, if (one) &.{ 1, 64, 1000, 4096 } else &.{ 1, 64, 1000 }, in.x, in.pk, dx, dpk); + } + try t.timing(c, &s, dx, dpk, &.{.{ kg, kd }}, shared); + check.pass("exl3 prompt real layer {d}: gate/up {d}-bit, down {d}-bit against runSlots and float64", .{ layer_index, kg / 2, kd / 2 }); +} diff --git a/zig/tests/cuda/exl3_prompt_k6_tests.zig b/zig/tests/cuda/exl3_prompt_k6_tests.zig new file mode 100644 index 00000000000..ce452120cb4 --- /dev/null +++ b/zig/tests/cuda/exl3_prompt_k6_tests.zig @@ -0,0 +1,553 @@ +//! The common EXL3 prompt kernels at 3 and 4 bits (mcg) at GLM's shapes: runSlots, float64, row bytes and their time. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const check = @import("check.zig"); +const qr = @import("quant_ref_tests.zig"); +const Gpu = check.Gpu; +const ex = cuda.exl3_experts; +const fmt = core.exl3_format; +const h = qr.helpers; + +pub const D = 4096; // model width +pub const N = 1024; // one rank's expert width (TP 2 of GLM-5.3-Flash's 2048) +pub const E = 288; // routed experts +pub const K = 8; // picks a row +pub const limit: f32 = 10.0; // GLM-5.3-Flash's swiglu_limit +const chunk = 1024; // rows a call in GLM's dispatch (cuda_exl3.chunk_rows) +pub const tiles = (D / 16) * (N / 16); // 16x16 tiles of one matrix +/// int16 words of one matrix of k2 half-bits a value: 16 * bits a tile. +pub fn words(k2: u32) usize { + return tiles * 8 * @as(usize, k2); +} + +pub const Ctx = struct { + gpu: Gpu, + a: std.mem.Allocator, // an arena + s: cuda.Stream, + exp: *const ex.Experts, + router: cuda.grouped.Router, + worst: f64 = 0, // the float64 checks' largest difference as a fraction of its tolerance +}; + +/// Device buffers freed together. +pub const Bufs = struct { + d: *const cuda.Driver, + gpa: std.mem.Allocator, + list: std.ArrayList(cuda.DeviceBuffer) = .empty, + pub fn alloc(b: *Bufs, n: usize) !u64 { + const buf = try cuda.DeviceBuffer.alloc(b.d, @max(n, 16)); + try b.list.append(b.gpa, buf); + try buf.fill8(0xff, null); // a launch that writes nothing leaves NaN bytes + return buf.ptr; + } + pub fn put(b: *Bufs, bytes: []const u8) !u64 { + const buf = try cuda.DeviceBuffer.fromHost(b.d, bytes); + try b.list.append(b.gpa, buf); + return buf.ptr; + } + pub fn deinit(b: *Bufs) void { + for (b.list.items) |*buf| buf.free(); + b.list.deinit(b.gpa); + } +}; + +/// One layer's tensors: trellis pointer and width tables on the device, the same words and scales on the host. +pub const Set = struct { + gp: u64, // int64 [E] trellis pointers + up: u64, + dp: u64, + k2: [2]u64, // int32 [E] of 6, and of 8 + suh_g: u64, // fp16 [E, D] + suh_u: u64, + svh_g: u64, // fp16 [E, N] + svh_u: u64, + suh_d: u64, // fp16 [E, N] + svh_d: u64, // fp16 [E, D] + shared: bool, // one input scale vector for every gate and up + hg: []const []const i16, // each expert's words (at least those of the widths run) + hu: []const []const i16, + hd: []const []const i16, + sg: []const f16, + su: []const f16, + vg: []const f16, + vu: []const f16, + sd: []const f16, + vd: []const f16, + + pub fn layer(s: *const Set, gu: u32, d: u32, shared: bool) ex.Layer { + return .{ .gate = s.gp, .up = s.up, .down = s.dp, .gate_k2 = s.k2[(gu - 6) / 2], .up_k2 = s.k2[(gu - 6) / 2], .down_k2 = s.k2[(d - 6) / 2], .suh_g = s.suh_g, .suh_u = s.suh_u, .svh_g = s.svh_g, .svh_u = s.svh_u, .suh_d = s.suh_d, .svh_d = s.svh_d, .experts = E, .dims = D, .width = N, .codebook = .mcg, .uniform_k2_gu = gu, .uniform_k2_d = d, .shared_input = shared, .limit = limit, .act_mode = 0 }; + } +}; + +/// The int32 tables of 6 and 8 for every expert. +pub fn widthTables(b: *Bufs) ![2]u64 { + var out: [2]u64 = undefined; + for ([_]i32{ 6, 8 }, 0..) |v, i| { + const t: [E]i32 = @splat(v); + out[i] = try b.put(std.mem.sliceAsBytes(&t)); + } + return out; +} + +fn scales(c: *Ctx, rng: std.Random, n: usize, scale: f32) ![]f16 { + const out = try c.a.alloc(f16, n); + for (out) |*v| v.* = @floatCast((if (rng.boolean()) scale else -scale) * (0.5 + rng.float(f32))); + return out; +} + +/// Random words in 4-bit slots shared by both widths; `one` shares one input scale, `own` has each expert's. +fn synthetic(c: *Ctx, b: *Bufs, rng: std.Random) ![2]Set { + const slot = words(8); + var ptrs: [3]u64 = undefined; + var host: [3][]const []const i16 = undefined; + for (0..3) |m| { + const all = try c.a.alloc(i16, E * slot); + rng.bytes(std.mem.sliceAsBytes(all)); + const base = try b.put(std.mem.sliceAsBytes(all)); + const table = try c.a.alloc(u64, E); + const each = try c.a.alloc([]const i16, E); + for (0..E) |e| { + table[e] = base + e * slot * 2; + each[e] = all[e * slot ..][0..slot]; + } + ptrs[m] = try b.put(std.mem.sliceAsBytes(table)); + host[m] = each; + } + const k2 = try widthTables(b); + const one_suh = try scales(c, rng, D, 1.0); + const sg1 = try c.a.alloc(f16, E * D); + for (0..E) |e| @memcpy(sg1[e * D ..][0..D], one_suh); + const sg = try scales(c, rng, E * D, 1.0); + const su = try scales(c, rng, E * D, 1.0); + const vg = try scales(c, rng, E * N, 0.02); + const vu = try scales(c, rng, E * N, 0.02); + const sd = try scales(c, rng, E * N, 1.0); + const vd = try scales(c, rng, E * D, 0.02); + var one: Set = .{ .gp = ptrs[0], .up = ptrs[1], .dp = ptrs[2], .k2 = k2, .suh_g = try b.put(std.mem.sliceAsBytes(sg1)), .suh_u = 0, .svh_g = try b.put(std.mem.sliceAsBytes(vg)), .svh_u = try b.put(std.mem.sliceAsBytes(vu)), .suh_d = try b.put(std.mem.sliceAsBytes(sd)), .svh_d = try b.put(std.mem.sliceAsBytes(vd)), .shared = true, .hg = host[0], .hu = host[1], .hd = host[2], .sg = sg1, .su = sg1, .vg = vg, .vu = vu, .sd = sd, .vd = vd }; + one.suh_u = one.suh_g; + var own = one; + own.shared = false; + own.suh_g = try b.put(std.mem.sliceAsBytes(sg)); + own.suh_u = try b.put(std.mem.sliceAsBytes(su)); + own.sg = sg; + own.su = su; + return .{ one, own }; +} + +/// bf16 rows in [-1, 1) and each row's distinct picks; expert 0 in the first row's and expert 1 in the last row's. +pub fn inputs(c: *Ctx, rng: std.Random, rows: usize) !struct { x: []u16, pk: []i32 } { + const x = try c.a.alloc(u16, rows * D); + for (x) |*v| v.* = h.bf16Of((rng.float(f32) * 2 - 1)); + const pk = try c.a.alloc(i32, rows * K); + for (0..rows) |row| { + var seen: [E]bool = @splat(false); + for (0..K) |j| { + var e = rng.uintLessThan(usize, E); + while (seen[e]) e = rng.uintLessThan(usize, E); + seen[e] = true; + pk[row * K + j] = @intCast(e); + } + } + for ([_][2]usize{ .{ 0, 0 }, .{ rows - 1, 1 } }) |want| { + const r = pk[want[0] * K ..][0..K]; + if (std.mem.indexOfScalar(i32, r, @intCast(want[1])) == null) r[K - 1] = @intCast(want[1]); + } + return .{ .x = x, .pk = pk }; +} + +/// The plan's scratch for `pairs` pairs in items of the prompt tile (as glm_exl3_tests sizes it). +fn plan(b: *Bufs, pairs: usize) !cuda.grouped.Plan { + const wide = pairs > cuda.grouped.small; + return .{ .members = try b.alloc(pairs * 4), .items = try b.alloc(cuda.grouped.maxItems(pairs, E, ex.prompt.tile) * 12), .counts = try b.alloc(8), .rank = try b.alloc((if (wide) pairs else 1) * 4), .hist = try b.alloc((if (wide) (pairs + 1023) / 1024 * E else 1) * 4) }; +} + +fn download(c: *Ctx, ptr: u64, out: []f32) !void { + try c.s.synchronize(); + const buf: cuda.DeviceBuffer = .{ .d = c.gpu.d, .ptr = ptr, .len = out.len * 4 }; + try buf.download(0, std.mem.sliceAsBytes(out)); +} + +/// The prompt path over `rows` rows, `per` rows a call; go() downloads y [rows * K, D] when given somewhere to put it. +pub const Prompt = struct { + c: *Ctx, + l: ex.Layer, + x: u64, + pk: u64, + rows: usize, + per: usize, + b: Bufs, + sc: ex.prompt.Scratch, + p: cuda.grouped.Plan, + y: u64, // fp32 [rows][K][D]: the down kernels write each pair's slot row here + pub fn init(c: *Ctx, l: ex.Layer, x: u64, pk: u64, rows: usize, per: usize) !Prompt { + var b: Bufs = .{ .d = c.gpu.d, .gpa = c.gpu.gpa }; + errdefer b.deinit(); + const cap: usize = @min(rows, per); + const sc = try ex.prompt.scratch(try b.alloc(try ex.prompt.bytes(l, cap, K)), l, cap, K); + const p = try plan(&b, cap * K); + const y = try b.alloc(rows * K * D * 4); + return .{ .c = c, .l = l, .x = x, .pk = pk, .rows = rows, .per = per, .b = b, .sc = sc, .p = p, .y = y }; + } + pub fn deinit(p: *Prompt) void { + p.b.deinit(); + } + pub fn go(p: *const Prompt, out: ?[]f32) !void { + var at: usize = 0; + while (at < p.rows) : (at += p.per) { + const n: usize = @min(p.per, p.rows - at); + try p.c.exp.prompt.run(p.c.exp, p.c.router, p.c.s, p.l, p.x + at * D * 2, D, p.pk + at * K * 4, n, p.sc, p.p, p.y + at * K * D * 4, null); + if (out) |o| try download(p.c, p.y + at * K * D * 4, o[at * K * D ..][0 .. n * K * D]); + } + } + /// The gate/up (which 0) or down (1) launch of the last call again, as run() makes it. + pub fn kernel(p: *const Prompt, which: u1) !void { + const k = p.c.exp.prompt; + const w = ex.prompt.widths(p.l); + const n: usize = @min(p.per, p.rows); + const items = cuda.grouped.maxItems(n * K, E, ex.prompt.tile); + var a: cuda.Args = .{}; + if (which == 0) { + inline for (.{ p.sc.xg, p.sc.xu, p.l.gate, p.l.up, p.p.items, p.p.counts, p.p.members, p.l.svh_g, p.l.svh_u, p.l.suh_d, p.sc.xd, @as(i32, D), @as(i32, N), @as(i32, if (p.l.shared_input) K else 1), p.l.limit, p.l.act_mode, @as(i32, -1) }) |v| a.add(v); + try cuda.launch.launch(if (w.gu == 6) k.gateup_k6 else k.gateup, .{ .grid = .{ .x = N / 128, .y = @intCast(items), .z = 1 }, .block = .{ .x = 256 } }, p.c.s, &a); + } else { + inline for (.{ p.sc.xd, p.l.down, p.p.items, p.p.counts, p.p.members, p.l.svh_d, p.y, @as(i32, N), @as(i32, D), @as(i32, -1) }) |v| a.add(v); + try cuda.launch.launch(if (w.d == 6) k.down_k6 else k.down, .{ .grid = .{ .x = D / 256, .y = @intCast(items), .z = 1 }, .block = .{ .x = 256 } }, p.c.s, &a); + } + } +}; + +/// The general grouped path (runSlots, any width) in GLM's 1024-row calls: the oracle, and the fallback's time. +pub const Slots = struct { + c: *Ctx, + l: ex.Layer, + x: u64, + pk: u64, + rows: usize, + b: Bufs, + sc: ex.Scratch, + pub fn init(c: *Ctx, l: ex.Layer, x: u64, pk: u64, rows: usize) !Slots { + var b: Bufs = .{ .d = c.gpu.d, .gpa = c.gpu.gpa }; + errdefer b.deinit(); + const cap: usize = @min(rows, chunk); + const sc = try ex.scratch(try b.alloc(try ex.scratchBytes(l, cap, K)), l, cap, K); + return .{ .c = c, .l = l, .x = x, .pk = pk, .rows = rows, .b = b, .sc = sc }; + } + pub fn deinit(s: *Slots) void { + s.b.deinit(); + } + pub fn go(s: *const Slots, out: ?[]f32) !void { + var at: usize = 0; + while (at < s.rows) : (at += chunk) { + const n: usize = @min(chunk, s.rows - at); + try s.c.exp.runSlots(s.c.s, s.l, s.x + at * D * 2, D, .bf16, s.pk + at * K * 4, n, s.sc); + if (out) |o| try download(s.c, s.sc.y, o[at * K * D ..][0 .. n * K * D]); + } + } +}; + +/// Prompt against runSlots: the largest difference, absolute and over its slot row's RMS, and the equal values. +pub const Stats = struct { max_abs: f64 = 0, max_norm: f64 = 0, max_rel: f64 = 0, equal: usize = 0, n: usize = 0, dd: f64 = 0, ww: f64 = 0 }; +pub fn compare(got: []const f32, want: []const f32) Stats { + var st: Stats = .{ .n = got.len }; + var at: usize = 0; + while (at < got.len) : (at += D) { + var ss: f64 = 0; + for (want[at..][0..D]) |v| ss += @as(f64, v) * v; + st.ww += ss; + const rms = @sqrt(ss / D) + 1e-30; + for (got[at..][0..D], want[at..][0..D]) |g, w| { + const d = @abs(@as(f64, g) - w); + st.dd += d * d; + if (@as(u32, @bitCast(g)) == @as(u32, @bitCast(w))) st.equal += 1; + if (!(d <= st.max_abs)) st.max_abs = d; // a NaN sticks + if (!(d / rms <= st.max_norm)) st.max_norm = d / rms; + if (@abs(w) >= rms and !(d / @abs(w) <= st.max_rel)) st.max_rel = d / @abs(w); + } + } + return st; +} +/// The 4-bit path's own distance from runSlots (fp32 sums reordered under bf16 roundings) is 2.7e-4 RMS, 2e-2 at most. +pub fn expectClose(name: []const u8, rows: usize, st: Stats) !void { + std.debug.print("RESULT {s} ({d} rows) vs runSlots: max |diff| {e:.3}, max |diff|/rms {e:.3}, max rel {e:.3}, rms diff/rms {e:.3}, {d:.2}% equal\n", .{ name, rows, st.max_abs, st.max_norm, st.max_rel, @sqrt(st.dd / st.ww), 100.0 * @as(f64, @floatFromInt(st.equal)) / @as(f64, @floatFromInt(st.n)) }); + try check.expect(st.max_norm <= 1.0 / 16.0 and @sqrt(st.dd / st.ww) <= 1e-3, "{s} ({d} rows): {e} of a slot row's RMS from runSlots, {e} in all", .{ name, rows, st.max_norm, @sqrt(st.dd / st.ww) }); +} + +/// GLM's SwiGLU as the kernels round it (glm_exl3_tests' act). +fn act(g: f64, u: f64) f64 { + const gg = @min(h.bfOf(h.bf16Of(@floatCast(g))), limit); + const uu = @max(@min(h.bfOf(h.bf16Of(@floatCast(u))), limit), -limit); + return h.bfOf(h.bf16Of(@floatCast(h.bfOf(h.bf16Of(@floatCast(gg / (1 + @exp(-gg))))) * uu))); +} + +/// Float64 matrices of the first `F` experts, decoded once per projection and width. +pub const F = 2; +pub const Mats = struct { + w: [F][3][2]?[]f64 = @splat(@splat(@splat(null))), + fn get(m: *Mats, c: *Ctx, s: *const Set, e: usize, which: usize, k2: u32) ![]f64 { + const slot = &m.w[e][which][(k2 - 6) / 2]; + if (slot.*) |w| return w; + const out = try c.gpu.gpa.alloc(f64, D * N); + const scratch = try c.gpu.gpa.alloc(f64, 2 * D * N); + defer c.gpu.gpa.free(scratch); + const width: fmt.Width = .{ .halves = @intCast(k2) }; + const tw = words(k2); + switch (which) { + 0 => fmt.dequantize(width, .mcg, s.hg[e][0..tw], D / 16, N / 16, s.sg[e * D ..][0..D], s.vg[e * N ..][0..N], out, scratch), + 1 => fmt.dequantize(width, .mcg, s.hu[e][0..tw], D / 16, N / 16, s.su[e * D ..][0..D], s.vu[e * N ..][0..N], out, scratch), + else => fmt.dequantize(width, .mcg, s.hd[e][0..tw], N / 16, D / 16, s.sd[e * N ..][0..N], s.vd[e * D ..][0..D], out, scratch), + } + slot.* = out; + return out; + } + pub fn deinit(m: *Mats, gpa: std.mem.Allocator) void { + for (&m.w) |*a| for (a) |*b| for (b) |*v| if (v.*) |w| gpa.free(w); + } +}; + +/// `outs` on pairs of the first F experts (at most `most` each) against float64: glm_exl3_tests' |a w| / 64 + 1e-6. +pub fn reference(c: *Ctx, m: *Mats, s: *const Set, gu: u32, d: u32, x: []const u16, pk: []const i32, outs: []const []const f32, names: []const []const u8, most: usize) !void { + const g = try c.a.alloc(f64, N); + const u = try c.a.alloc(f64, N); + const av = try c.a.alloc(f64, N); + const want = try c.a.alloc(f64, D); + const mag = try c.a.alloc(f64, D); + const swapped = try c.a.alloc(f64, D); // the planted control: gate and up swapped must fail the same tolerance + var control: f64 = 0; + var worst: [4]f64 = @splat(0); + var pairs: usize = 0; + for (0..F) |e| { + var taken: usize = 0; + for (pk, 0..) |pe, p| { + if (pe != @as(i32, @intCast(e)) or taken == most) continue; + taken += 1; + const wg = try m.get(c, s, e, 0, gu); + const wu = try m.get(c, s, e, 1, gu); + const wd = try m.get(c, s, e, 2, d); + const xr = x[(p / K) * D ..][0..D]; + @memset(g, 0); + @memset(u, 0); + for (0..D) |kk| { + const xv = h.bfOf(xr[kk]); + for (g, u, wg[kk * N ..][0..N], wu[kk * N ..][0..N]) |*gv, *uv, a, b| { + gv.* += xv * a; + uv.* += xv * b; + } + } + for (av, g, u) |*o, gv, uv| o.* = act(gv, uv); + @memset(want, 0); + @memset(mag, 0); + @memset(swapped, 0); + for (0..N) |kk| { + const sa = act(u[kk], g[kk]); + for (want, mag, swapped, wd[kk * D ..][0..D]) |*wv, *mv, *sv, wt| { + wv.* += av[kk] * wt; + mv.* += @abs(av[kk] * wt); + sv.* += sa * wt; + } + } + for (outs, 0..) |o, oi| for (0..D) |n| { + const tol = mag[n] / 64.0 + 1e-6; + const q = @abs(@as(f64, o[p * D + n]) - want[n]) / tol; + if (!(q <= worst[oi])) worst[oi] = q; + if (oi == 0) control = @max(control, @abs(@as(f64, o[p * D + n]) - swapped[n]) / tol); + }; + pairs += 1; + } + } + for (outs, 0..) |_, oi| { + std.debug.print("RESULT {s}: {d} pairs of experts 0-{d} against float64, largest difference {d:.4} of its tolerance\n", .{ names[oi], pairs, F - 1, worst[oi] }); + c.worst = @max(c.worst, worst[oi]); + try check.expect(worst[oi] <= 1 and pairs > 0, "{s}: {d} of its float64 tolerance over {d} pairs", .{ names[oi], worst[oi], pairs }); + } + std.debug.print("RESULT {s}: the planted control (gate and up swapped in the reference) reaches {d:.1} of its tolerance\n", .{ names[0], control }); + try check.expect(control > 1, "{s}: the planted control fails its tolerance", .{names[0]}); +} + +/// Median milliseconds of `reps` runs of `f(ctx)` after two warm-ups. +pub fn timed(c: *Ctx, reps: usize, ctx: anytype, comptime f: anytype) !f64 { + var t0 = try cuda.Event.init(c.gpu.d, true); + defer t0.deinit(); + var t1 = try cuda.Event.init(c.gpu.d, true); + defer t1.deinit(); + for (0..2) |_| try f(ctx); + const ms = try c.a.alloc(f64, reps); + for (ms) |*v| { + try t0.record(c.s); + try f(ctx); + try t1.record(c.s); + try t1.synchronize(); + v.* = try cuda.Event.elapsedMs(t0, t1); + } + return check.median(ms); +} +fn promptGo(p: *const Prompt) anyerror!void { + return p.go(null); +} +fn slotsGo(s: *const Slots) anyerror!void { + return s.go(null); +} +fn gateUp(p: *const Prompt) anyerror!void { + return p.kernel(0); +} +fn downOnly(p: *const Prompt) anyerror!void { + return p.kernel(1); +} + +/// One layer's widths through the prompt path and runSlots at every row count, float64 on its sampled pairs. +pub fn widthsCase(c: *Ctx, m: *Mats, s: *const Set, gu: u32, d: u32, shared: bool, row_counts: []const usize, x: []const u16, pk: []const i32, dx: u64, dpk: u64) !void { + const l = s.layer(gu, d, shared); + var name_buf: [96]u8 = undefined; + const name = try std.fmt.bufPrint(&name_buf, "exl3 prompt gate/up {d}-bit, down {d}-bit, {s}", .{ gu / 2, d / 2, if (shared) "one rotation" else "a rotation a pick" }); + for (row_counts) |rows| { + const got = try c.gpu.gpa.alloc(f32, rows * K * D); + defer c.gpu.gpa.free(got); + const want = try c.gpu.gpa.alloc(f32, rows * K * D); + defer c.gpu.gpa.free(want); + { + var p = try Prompt.init(c, l, dx, dpk, rows, rows); + defer p.deinit(); + try p.go(got); + } + { + var o = try Slots.init(c, l, dx, dpk, rows); + defer o.deinit(); + try o.go(want); + } + try expectClose(name, rows, compare(got, want)); + var pn: [128]u8 = undefined; + var on: [128]u8 = undefined; + const names = [_][]const u8{ try std.fmt.bufPrint(&pn, "{s}, {d} rows, prompt", .{ name, rows }), try std.fmt.bufPrint(&on, "{s}, {d} rows, runSlots", .{ name, rows }) }; + try reference(c, m, s, gu, d, x[0 .. rows * D], pk[0 .. rows * K], &.{ got, want }, &names, 48); + } +} + +pub fn run(gpu: Gpu, dir: []const u8, base: ?[]const u8) !void { + var arena: std.heap.ArenaAllocator = .init(gpu.gpa); + defer arena.deinit(); + var stream = try cuda.Stream.init(gpu.d, false); + defer stream.deinit(); + var exp = try ex.Experts.load(gpu.d); + defer exp.unload(); + var pm = try cuda.Module.load(gpu.d, cuda.kernels.experts); + defer pm.unload(); + var c: Ctx = .{ .gpu = gpu, .a = arena.allocator(), .s = stream, .exp = &exp, .router = try cuda.grouped.Router.resolve(pm) }; + var prng = std.Random.DefaultPrng.init(0x3b17); + const rng = prng.random(); + { + var b: Bufs = .{ .d = gpu.d, .gpa = gpu.gpa }; + defer b.deinit(); + const sets = try synthetic(&c, &b, rng); + var m: Mats = .{}; + defer m.deinit(gpu.gpa); + const in = try inputs(&c, rng, 4096); + const dx = try b.put(std.mem.sliceAsBytes(in.x)); + const dpk = try b.put(std.mem.sliceAsBytes(in.pk)); + const all = [_]usize{ 1, 64, 1000, 4096 }; + for ([_][2]u32{ .{ 6, 8 }, .{ 6, 6 }, .{ 8, 8 }, .{ 8, 6 } }) |w| try widthsCase(&c, &m, &sets[0], w[0], w[1], true, &all, in.x, in.pk, dx, dpk); + var m2: Mats = .{}; + defer m2.deinit(gpu.gpa); + for ([_][2]u32{ .{ 6, 8 }, .{ 6, 6 } }) |w| try widthsCase(&c, &m2, &sets[1], w[0], w[1], false, all[0..3], in.x, in.pk, dx, dpk); + try invariance(&c, &sets[0], dx, dpk); + if (base) |path| try baseline(&c, &sets[0], &sets[1], dx, dpk, path); + try timing(&c, &sets[0], dx, dpk, &.{ .{ 6, 8 }, .{ 6, 6 }, .{ 8, 8 } }, true); + } + if (!std.mem.eql(u8, dir, "none")) try @import("exl3_prompt_k6_real.zig").run(&c, dir, rng); + check.pass("exl3-prompt-k6: 3- and 4-bit prompt kernels within 1e-3 RMS (1/16 a slot row) of runSlots, {d:.4} of float64's tolerance", .{c.worst}); +} + +/// A row's bytes: one 4096-row call, GLM's 1024-row calls, and with a rotation a pick, all the same. +fn invariance(c: *Ctx, s: *const Set, dx: u64, dpk: u64) !void { + const rows = 4096; + const one = try c.gpu.gpa.alloc(f32, rows * K * D); + defer c.gpu.gpa.free(one); + const other = try c.gpu.gpa.alloc(f32, rows * K * D); + defer c.gpu.gpa.free(other); + for ([_][2]u32{ .{ 6, 8 }, .{ 6, 6 } }) |w| { + { + var p = try Prompt.init(c, s.layer(w[0], w[1], true), dx, dpk, rows, rows); + defer p.deinit(); + try p.go(one); + } + { + var p = try Prompt.init(c, s.layer(w[0], w[1], true), dx, dpk, rows, chunk); + defer p.deinit(); + try p.go(other); + } + try check.sameBytes("exl3 prompt k6: 4096 rows in one call and in 1024-row calls", std.mem.sliceAsBytes(other), std.mem.sliceAsBytes(one)); + { + var p = try Prompt.init(c, s.layer(w[0], w[1], false), dx, dpk, 1000, 1000); + defer p.deinit(); + try p.go(other[0 .. 1000 * K * D]); + } + try check.sameBytes("exl3 prompt k6: one rotation a row and a rotation a pick", std.mem.sliceAsBytes(other[0 .. 1000 * K * D]), std.mem.sliceAsBytes(one[0 .. 1000 * K * D])); + check.pass("exl3 prompt gate/up {d}-bit, down {d}-bit: a row's bytes in one call, in 1024-row calls and with a rotation a pick", .{ w[0] / 2, w[1] / 2 }); + } +} + +/// An exl3_experts image built before a change (BASE): its 4-bit prompt kernels give this build's bytes. +fn baseline(c: *Ctx, one: *const Set, own: *const Set, dx: u64, dpk: u64, path: []const u8) !void { + const image = try std.Io.Dir.cwd().readFileAlloc(c.gpu.io, path, c.gpu.gpa, .limited(1 << 28)); + defer c.gpu.gpa.free(image); + var mod = try cuda.Module.load(c.gpu.d, image); + defer mod.unload(); + var old = c.exp.*; + old.rot_in = try mod.function("tf_exl3_experts_rot_in"); + old.prompt.rotate = try mod.function("tf_exl3_prompt_rotate"); + old.prompt.gateup = try mod.function("tf_exl3_prompt_gu"); + old.prompt.down = try mod.function("tf_exl3_prompt_down"); + var oc = c.*; + oc.exp = &old; + const got = try c.gpu.gpa.alloc(f32, 4096 * K * D); + defer c.gpu.gpa.free(got); + const want = try c.gpu.gpa.alloc(f32, 4096 * K * D); + defer c.gpu.gpa.free(want); + for ([_]struct { *const Set, bool, usize }{ .{ one, true, 4096 }, .{ own, false, 1000 }, .{ one, true, 1 } }) |case| { + const l = case[0].layer(8, 8, case[1]); + const n = case[2] * K * D; + for ([_]*Ctx{ c, &oc }, [_][]f32{ got[0..n], want[0..n] }) |ctx, out| { + var p = try Prompt.init(ctx, l, dx, dpk, case[2], case[2]); + defer p.deinit(); + try p.go(out); + } + try check.sameBytes("exl3 prompt 4-bit: this build against the BASE image", std.mem.sliceAsBytes(got[0..n]), std.mem.sliceAsBytes(want[0..n])); + check.pass("exl3 prompt gate/up 4-bit, down 4-bit, {s}, {d} rows: the BASE image's bytes", .{ if (case[1]) "one rotation" else "a rotation a pick", case[2] }); + } +} + +/// One layer at 4096 rows by widths: prompt (one call, 1024-row calls), runSlots; rounds interleave (a shared device). +pub fn timing(c: *Ctx, s: *const Set, dx: u64, dpk: u64, cases: []const [2]u32, shared: bool) !void { + const rows = 4096; + const reps = 5; + const rounds = 5; + const ms = try c.a.alloc([5][rounds]f64, cases.len); + for (0..rounds) |round| for (cases, ms) |w, *m| { + const l = s.layer(w[0], w[1], shared); + { + var p = try Prompt.init(c, l, dx, dpk, rows, rows); + defer p.deinit(); + m[0][round] = try timed(c, reps, &p, promptGo); + m[1][round] = try timed(c, reps, &p, gateUp); + m[2][round] = try timed(c, reps, &p, downOnly); + } + { + var q = try Prompt.init(c, l, dx, dpk, rows, chunk); + defer q.deinit(); + m[3][round] = try timed(c, reps, &q, promptGo); + } + var o = try Slots.init(c, l, dx, dpk, rows); + defer o.deinit(); + m[4][round] = try timed(c, reps, &o, slotsGo); + }; + std.debug.print("TIME one layer, {d} rows, top-{d} of {d} experts, D {d}, N {d}: ms, best / median of {d} rounds\n", .{ rows, K, E, D, N, rounds }); + std.debug.print("TIME widths (gate/up, down) | prompt, one call | its gate/up | its down | prompt, 1024-row calls | runSlots, 1024-row calls\n", .{}); + for (cases, ms) |w, *m| { + var best: [5]f64 = undefined; + var mid: [5]f64 = undefined; + for (m, 0..) |*col, j| { + mid[j] = check.median(col); + best[j] = col[0]; + } + std.debug.print("TIME {d}-bit, {d}-bit | {d:.3} / {d:.3} | {d:.3} / {d:.3} | {d:.3} / {d:.3} | {d:.3} / {d:.3} | {d:.3} / {d:.3}\n", .{ w[0] / 2, w[1] / 2, best[0], mid[0], best[1], mid[1], best[2], mid[2], best[3], mid[3], best[4], mid[4] }); + } +} diff --git a/zig/tests/cuda/glm_exl3_compact.zig b/zig/tests/cuda/glm_exl3_compact.zig index b02ed09b04e..5b427c0138d 100644 --- a/zig/tests/cuda/glm_exl3_compact.zig +++ b/zig/tests/cuda/glm_exl3_compact.zig @@ -9,9 +9,7 @@ const Scratch = glm.exl3.Scratch; const experts = glm.experts; const top_k = glm.exl3.top_k; const chunk_rows = glm.exl3.chunk_rows; -fn layer(w: Experts, count: usize, dims: usize, width: usize, limit: f32) common.Layer { - return .{ .gate = w.gt, .up = w.ut, .down = w.dt, .gate_k2 = w.k2, .up_k2 = w.k2, .down_k2 = w.k2, .suh_g = w.suh_g, .suh_u = w.suh_u, .svh_g = w.svh_g, .svh_u = w.svh_u, .suh_d = w.suh_d, .svh_d = w.svh_d, .experts = count, .dims = dims, .width = width, .codebook = .mcg, .limit = limit, .act_mode = 0, .uniform_k2 = 8, .shared_input = w.shx }; -} +const layer = glm.exl3.layer; // each projection's own width table and verified widths, as serving reads them fn shape(dims: usize, width: usize) common.Layer { const w: Experts = .{ .gt = 0, .ut = 0, .dt = 0, .k2 = 0, .suh_g = 0, .suh_u = 0, .svh_g = 0, .svh_u = 0, .suh_d = 0, .svh_d = 0, .shx = false }; return layer(w, cuda.grouped.max_experts, dims, width, 0); diff --git a/zig/tests/cuda/glm_exl3_layer_tests.zig b/zig/tests/cuda/glm_exl3_layer_tests.zig new file mode 100644 index 00000000000..ceae5edb2f8 --- /dev/null +++ b/zig/tests/cuda/glm_exl3_layer_tests.zig @@ -0,0 +1,326 @@ +//! One real GLM layer's EXL3 experts through the family loader, decode and prompt, against float64 unpacks. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const glm = @import("glm_cuda"); +const check = @import("check.zig"); +const qr = @import("quant_ref_tests.zig"); +const Gpu = check.Gpu; + +const fmt = core.exl3_format; +const h = qr.helpers; +const Rig = qr.RigT; +const prefix = "model.language_model."; +const slots = glm.exl3.top_k + 1; +const pool = 16; // the experts the rows pick from: the float64 matrices are decoded for these alone + +/// cuda_weights' loader as cuda_exl3.load sees it: tensors by name, the host bytes gathered, each upload kept. +const Loader = struct { + gpa: std.mem.Allocator, + d: *const cuda.Driver, + ck: *core.Checkpoint, + host: std.ArrayList(u8) = .empty, + name_buf: [192]u8 = undefined, + last: []const u8 = "", + bufs: std.ArrayList(cuda.DeviceBuffer) = .empty, + bytes: usize = 0, + + pub fn get(L: *Loader, comptime f: []const u8, args: anytype) !core.checkpoint.Tensor { + L.last = try std.fmt.bufPrint(&L.name_buf, prefix ++ f, args); + return L.ck.get(L.last); + } + pub fn put(L: *Loader, comptime f: []const u8, args: anytype) !u64 { + _ = f; + _ = args; + const b = try cuda.DeviceBuffer.fromHost(L.d, L.host.items); + errdefer { + var x = b; + x.free(); + } + try L.bufs.append(L.gpa, b); + L.bytes += L.host.items.len; + L.host.clearRetainingCapacity(); + return b.ptr; + } + fn deinit(L: *Loader) void { + for (L.bufs.items) |*b| b.free(); + L.bufs.deinit(L.gpa); + L.host.deinit(L.gpa); + } +}; + +/// Rotate each 128-value block along `axis` of the row-major [rows, cols] matrix: fmt.rotate's transform, in n log n. +fn rotate(x: []f64, rows: usize, cols: usize, axis: usize) void { + const hd = fmt.hadamard_dim; + const inv = 1.0 / std.math.sqrt(@as(f64, hd)); + if (axis == 0) { // whole rows at a time: rows r and r + half of each block's butterflies + var b: usize = 0; + while (b < rows) : (b += hd) { + var half: usize = 1; + while (half < hd) : (half *= 2) { + var i: usize = 0; + while (i < hd) : (i += 2 * half) for (i..i + half) |j| { + const p = x[(b + j) * cols ..][0..cols]; + const q = x[(b + j + half) * cols ..][0..cols]; + for (p, q) |*u, *v| { + const s = u.* + v.*; + v.* = u.* - v.*; + u.* = s; + } + }; + } + for (x[b * cols ..][0 .. hd * cols]) |*v| v.* *= inv; + } + } else for (0..rows) |r| { + var b: usize = 0; + while (b < cols) : (b += hd) { + const blk = x[r * cols + b ..][0..hd]; + var half: usize = 1; + while (half < hd) : (half *= 2) { + var i: usize = 0; + while (i < hd) : (i += 2 * half) for (i..i + half) |j| { + const s = blk[j] + blk[j + half]; + blk[j + half] = blk[j] - blk[j + half]; + blk[j] = s; + }; + } + for (blk) |*v| v.* *= inv; + } + } +} + +fn halfs(a: std.mem.Allocator, t: core.checkpoint.Tensor) ![]f16 { + const out = try a.alloc(f16, t.bytes.len / 2); + @memcpy(std.mem.sliceAsBytes(out), t.bytes); + return out; +} + +/// Expert `e`'s projection as the rank holds it, float64: gate/up cols [lo,hi), down rows; unpack, cut, scale. +fn matrix(a: std.mem.Allocator, ck: *core.Checkpoint, layer: u32, e: usize, comptime proj: []const u8, k: usize, n: usize, lo: usize, hi: usize, by_cols: bool) ![]f64 { + var buf: [160]u8 = undefined; + const t = try ck.get(try std.fmt.bufPrint(&buf, prefix ++ "layers.{d}.mlp.experts.{d}." ++ proj ++ ".trellis", .{ layer, e })); + const words = try a.alloc(i16, t.bytes.len / 2); + defer a.free(words); + @memcpy(std.mem.sliceAsBytes(words), t.bytes); + const wq = try a.alloc(f16, k * n); + defer a.free(wq); + fmt.unpack(.{ .halves = @intCast(t.dim(2) / 8) }, .mcg, words, k / 16, n / 16, wq); + const suh = try halfs(a, try ck.get(try std.fmt.bufPrint(&buf, prefix ++ "layers.{d}.mlp.experts.{d}." ++ proj ++ ".suh", .{ layer, e }))); + defer a.free(suh); + const svh = try halfs(a, try ck.get(try std.fmt.bufPrint(&buf, prefix ++ "layers.{d}.mlp.experts.{d}." ++ proj ++ ".svh", .{ layer, e }))); + defer a.free(svh); + const rk = if (by_cols) k else hi - lo; + const rn = if (by_cols) hi - lo else n; + const w = try a.alloc(f64, rk * rn); + for (0..rk) |r| { + const src = if (by_cols) wq[r * n + lo ..][0..rn] else wq[(lo + r) * n ..][0..rn]; + for (w[r * rn ..][0..rn], src) |*d, s| d.* = @floatCast(s); + } + rotate(w, rk, rn, 0); + for (0..rk) |r| { + const s: f64 = @floatCast(suh[if (by_cols) r else lo + r]); + for (w[r * rn ..][0..rn]) |*v| v.* *= s; + } + rotate(w, rk, rn, 1); + for (0..rk) |r| for (w[r * rn ..][0..rn], 0..) |*v, c| { + v.* *= @as(f64, @floatCast(svh[if (by_cols) lo + c else c])); + }; + return w; +} + +/// The kernels' SwiGLU: gate and up rounded to bf16 and limited, silu to bf16, the product to bf16. +fn act(g: f64, u: f64, limit: f32) f64 { + const gg = @min(h.bfOf(h.bf16Of(@floatCast(g))), limit); + const uu = @max(@min(h.bfOf(h.bf16Of(@floatCast(u))), limit), -limit); + return h.bfOf(h.bf16Of(@floatCast(h.bfOf(h.bf16Of(@floatCast(gg / (1 + @exp(-gg))))) * uu))); +} + +const Case = struct { rows: usize, prompt: bool }; + +/// `glm-exl3-layer `: the layer's experts at the rank's share, all within tolerance. +pub fn run(gpu: Gpu, dir: []const u8, layer_s: []const u8, rank_s: []const u8, world_s: []const u8) !void { + try checkRotation(gpu.gpa); + const layer = try std.fmt.parseInt(u32, layer_s, 10); + const rank = try std.fmt.parseInt(usize, rank_s, 10); + const world = try std.fmt.parseInt(usize, world_s, 10); + var arena: std.heap.ArenaAllocator = .init(gpu.gpa); + defer arena.deinit(); + const a = arena.allocator(); + const text = try std.Io.Dir.cwd().readFileAlloc(gpu.io, try std.fs.path.join(a, &.{ dir, "config.json" }), a, .limited(1 << 24)); + var why: core.modelopt.Why = .{}; + if (!glm.exl3.isExl3(gpu.gpa, text)) return error.NotExl3; + glm.exl3.admit(gpu.gpa, text, &why) catch |err| { + std.debug.print("FAIL admission: {s}\n", .{why.text()}); + return err; + }; + const c = try glm.config.parse(gpu.gpa, text); + const cut = (try glm.shard.Share.of(&c, rank, world)).moe; + const D: usize = c.hidden; + const W = cut.len(); + const E: usize = c.experts; + const limit = c.swiglu_limit; + var ck = try core.Checkpoint.openModelPrefix(gpu.gpa, gpu.io, dir, prefix); + defer ck.close(); + + var stream = try cuda.Stream.init(gpu.d, false); + defer stream.deinit(); + var prng = std.Random.DefaultPrng.init(layer * 131 + rank); + var r: Rig = .{ .gpu = gpu, .a = a, .s = stream, .rng = prng.random() }; + defer { + for (r.bufs.items) |*b| b.free(); + r.bufs.deinit(gpu.gpa); + } + var L: Loader = .{ .gpa = gpu.gpa, .d = gpu.d, .ck = &ck }; + defer L.deinit(); + const w = try glm.exl3.load(&L, layer, E, D, c.moe_inter, cut); + try stream.synchronize(); + std.debug.print("glm-exl3-layer: layer {d}, rank {d} of {d} (columns {d}..{d}): {d:.2} GiB uploaded; widths gate/up {d}, down {d} half-bits (0: mixed); one rotation {}\n", .{ layer, rank, world, cut.lo, cut.hi, @as(f64, @floatFromInt(L.bytes)) / (1 << 30), w.uniform_gu, w.uniform_d, w.shx }); + var k2s: [3][]i32 = undefined; + for (&k2s, w.tables()) |*t, ptr| { + t.* = try a.alloc(i32, E); + const b: cuda.DeviceBuffer = .{ .d = gpu.d, .ptr = ptr, .len = E * 4 }; + try b.download(0, std.mem.sliceAsBytes(t.*)); + } + std.debug.print("glm-exl3-layer: expert 0's half-bits gate {d}, up {d}, down {d}\n", .{ k2s[0][0], k2s[1][0], k2s[2][0] }); + const l = glm.exl3.layer(w, E, D, W, limit); + std.debug.print("glm-exl3-layer: prompt kernels take the layer: {}\n", .{cuda.exl3_experts.prompt.eligible(l)}); + + var pm = try cuda.Module.load(gpu.d, cuda.kernels.experts); + defer pm.unload(); + var k = try glm.exl3.Kernels.load(gpu.d); + defer k.unload(); + var ek = try glm.experts.Kernels.load(gpu.d, pm, @intCast(try gpu.ctx.attribute(.multiprocessor_count)), null); + defer ek.unload(); + + // the pool: the first and last experts and 14 more, distinct + var ids: [pool]usize = undefined; + ids[0] = 0; + ids[1] = E - 1; + var n_ids: usize = 2; + while (n_ids < pool) { + const e = r.rng.uintLessThan(usize, E); + if (std.mem.indexOfScalar(usize, ids[0..n_ids], e) == null) { + ids[n_ids] = e; + n_ids += 1; + } + } + const cases = [_]Case{ .{ .rows = 1, .prompt = false }, .{ .rows = 3, .prompt = false }, .{ .rows = 8, .prompt = false }, .{ .rows = 24, .prompt = true } }; + var xs: [cases.len][]u16 = undefined; + var pks: [cases.len][]i32 = undefined; + var outs: [cases.len][]u8 = undefined; + for (cases, &xs, &pks, &outs) |cs, *x, *pk, *out| { + x.* = try r.bfs(cs.rows * D, 1.0); + pk.* = try a.alloc(i32, cs.rows * slots); + for (0..cs.rows) |row| { + var seen: [pool]bool = @splat(false); + for (0..slots - 1) |j| { + var p = r.rng.uintLessThan(usize, pool); + while (seen[p]) p = r.rng.uintLessThan(usize, pool); + seen[p] = true; + pk.*[row * slots + j] = @intCast(ids[p]); + } + pk.*[row * slots + slots - 1] = @intCast(E); // the shared expert's slot, filled apart + } + const P = cs.rows * glm.exl3.top_k; + const tile: usize = if (cs.prompt) glm.experts.staged_tile else glm.experts.tile; + const wide = P > cuda.grouped.small; + const plan: cuda.grouped.Plan = .{ + .members = try r.zeros(P * 4), + .items = try r.zeros(cuda.grouped.maxItems(P, E, tile) * 12), + .counts = try r.zeros(8), + .rank = try r.zeros((if (wide) P else 1) * 4), + .hist = try r.zeros((if (wide) (P + 1023) / 1024 * E else 1) * 4), + }; + const sz = glm.exl3.scratchFor(cs.rows, D, W, cs.prompt, w); + const sc: glm.exl3.Scratch = .{ .picks = try r.zeros(sz[0]), .xg = try r.zeros(sz[1]), .xu = try r.zeros(sz[2]), .z = try r.zeros(sz[3]) }; + const ey = try r.zeros(cs.rows * slots * D * 4); + try glm.exl3.run(&k, &ek, stream, w, sc, plan, try r.dev(std.mem.sliceAsBytes(x.*)), D, try r.dev(std.mem.sliceAsBytes(pk.*)), slots, cs.rows, E, D, W, limit, cs.prompt, ey, 0); + out.* = try r.back(ey, cs.rows * slots * D * 4); + } + + // float64, one pool expert at a time: its three matrices at the rank's share, then every pick of it + var worst: [cases.len]f64 = @splat(0); + const g = try a.alloc(f64, W); + const u = try a.alloc(f64, W); + const act_v = try a.alloc(f64, W); + const swapped = try a.alloc(f64, W); // the planted control: gate and up swapped must fail the same tolerance + var control: f64 = 0; + for (ids, 0..) |e, done| { + const wg = try matrix(gpu.gpa, &ck, layer, e, "gate_proj", D, c.moe_inter, cut.lo, cut.hi, true); + defer gpu.gpa.free(wg); + const wu = try matrix(gpu.gpa, &ck, layer, e, "up_proj", D, c.moe_inter, cut.lo, cut.hi, true); + defer gpu.gpa.free(wu); + const wd = try matrix(gpu.gpa, &ck, layer, e, "down_proj", c.moe_inter, D, cut.lo, cut.hi, false); + defer gpu.gpa.free(wd); + ck.release(); + for (cases, xs, pks, outs, &worst) |cs, x, pk, out, *most| for (0..cs.rows) |row| for (0..slots - 1) |j| { + if (pk[row * slots + j] != @as(i32, @intCast(e))) continue; + @memset(g, 0); + @memset(u, 0); + for (0..D) |kk| { + const xv = h.bfOf(x[row * D + kk]); + for (g, u, wg[kk * W ..][0..W], wu[kk * W ..][0..W]) |*gv, *uv, a_, b_| { + gv.* += xv * a_; + uv.* += xv * b_; + } + } + for (act_v, swapped, g, u) |*v, *sv, gv, uv| { + v.* = act(gv, uv, limit); + sv.* = act(uv, gv, limit); + } + for (0..D) |n| { + var y: f64 = 0; + var mag: f64 = 0; + var y_swapped: f64 = 0; + for (0..W) |kk| { + const p = act_v[kk] * wd[kk * D + n]; + y += p; + mag += @abs(p); + y_swapped += swapped[kk] * wd[kk * D + n]; + } + const tol = mag * (1.0 / 64.0) + 1e-6; // fp16 rotated inputs, bf16 activations, fp16 down inputs + const at = (row * slots + j) * D + n; + const got: f64 = @as(f32, @bitCast(std.mem.readInt(u32, out[at * 4 ..][0..4], .little))); + const q = @abs(got - y) / tol; + control = @max(control, @abs(got - y_swapped) / tol); + if (!(q <= most.*)) { + most.* = q; + if (!(q <= 1)) std.debug.print(" {s} {d} rows: row {d} slot {d} (expert {d}) column {d}: {e} against {e} (tolerance {e})\n", .{ if (cs.prompt) "prompt" else "decode", cs.rows, row, j, e, n, got, y, tol }); + } + } + }; + if (done % 4 == 3) std.debug.print("glm-exl3-layer: {d} of {d} experts checked\n", .{ done + 1, pool }); + } + for (cases, outs) |cs, out| for (0..cs.rows) |row| { // the shared slot keeps the fill's bytes + const bits = std.mem.readInt(u32, out[((row * slots + slots - 1) * D) * 4 ..][0..4], .little); + try check.expect(bits == 0xffffffff, "glm-exl3-layer: the shared slot left alone", .{}); + }; + std.debug.print("glm-exl3-layer: the planted control (gate and up swapped in the reference) reaches {d:.1} of its tolerance\n", .{control}); + try check.expect(control > 1, "glm-exl3-layer: the planted control fails its tolerance", .{}); + var all: f64 = 0; + for (cases, worst) |cs, most| { + std.debug.print("RESULT glm-exl3-layer {d} {s} ({d} rows): largest difference {d:.3} of its tolerance\n", .{ layer, if (cs.prompt) "prompt" else "decode", cs.rows, most }); + all = @max(all, most); + } + try check.expect(all <= 1, "glm-exl3-layer: layer {d} within its float64 tolerance", .{layer}); + check.pass("glm-exl3-layer: layer {d} rank {d} of {d}, decode and prompt slot rows within {d:.3} of their float64 tolerance", .{ layer, rank, world, all }); +} + +/// The n log n rotation against core's on a random matrix, both axes. +fn checkRotation(gpa: std.mem.Allocator) !void { + var prng = std.Random.DefaultPrng.init(1); + const x = try gpa.alloc(f64, 256 * 384); + defer gpa.free(x); + const y = try gpa.alloc(f64, x.len); + defer gpa.free(y); + const z = try gpa.alloc(f64, x.len); + defer gpa.free(z); + for (x) |*v| v.* = prng.random().float(f64) * 2 - 1; + for ([_]usize{ 0, 1 }) |axis| { + @memcpy(y, x); + fmt.rotate(y, 256, 384, axis); + @memcpy(z, x); + rotate(z, 256, 384, axis); + for (y, z) |p, q| try check.expect(@abs(p - q) <= 1e-12, "glm-exl3-layer: the n log n rotation is core's (axis {d})", .{axis}); + } +} diff --git a/zig/tests/cuda/glm_exl3_tests.zig b/zig/tests/cuda/glm_exl3_tests.zig index 690559ecd37..43a1b72685b 100644 --- a/zig/tests/cuda/glm_exl3_tests.zig +++ b/zig/tests/cuda/glm_exl3_tests.zig @@ -30,13 +30,21 @@ const Set = struct { suh_d: u64, svh_d: u64, k2: u64, + k2_up: u64, + k2_down: u64, + halves: [3]u16, // gate's, up's and down's half-bit widths (every expert alike) shx: bool, wg: []f64, // [E][D][N] wu: []f64, wd: []f64, // [E][N][D] fn experts(s: Set) glm.exl3.Experts { - return .{ .k2 = s.k2, .gt = s.gt, .ut = s.ut, .dt = s.dt, .suh_g = s.suh_g, .suh_u = s.suh_u, .svh_g = s.svh_g, .svh_u = s.svh_u, .suh_d = s.suh_d, .svh_d = s.svh_d, .shx = s.shx }; + const gu: u32 = if (s.halves[0] == s.halves[1]) s.halves[0] else 0; + return .{ .k2 = s.k2, .k2_up = s.k2_up, .k2_down = s.k2_down, .uniform_gu = gu, .uniform_d = s.halves[2], .gt = s.gt, .ut = s.ut, .dt = s.dt, .suh_g = s.suh_g, .suh_u = s.suh_u, .svh_g = s.svh_g, .svh_u = s.svh_u, .suh_d = s.suh_d, .svh_d = s.svh_d, .shx = s.shx }; + } + + fn name(s: Set) []const u8 { + return if (s.halves[0] == 8 and s.halves[1] == 8 and s.halves[2] == 8) "4-bit" else if (s.halves[0] == s.halves[1]) "3-bit gate/up, 4-bit down" else "2/3/4-bit gate/up/down"; } }; @@ -46,9 +54,9 @@ fn signs(r: *Rig, n: usize, scale: f16) ![]f16 { return out; } -/// `E` random K x N matrices: trellis words, suh (shared by every expert when `one`), svh; device copies and float64. -fn matrices(r: *Rig, k: usize, n: usize, shared_suh: ?[]const f16, out_suh: *u64, out_svh: *u64, w: []f64) !u64 { - const words = k / 16 * (n / 16) * 64; +/// `E` random K x N matrices at `halves` half-bits: trellis words, suh (`one` shares), svh; device and f64 copies. +fn matrices(r: *Rig, k: usize, n: usize, halves: u16, shared_suh: ?[]const f16, out_suh: *u64, out_svh: *u64, w: []f64) !u64 { + const words = k / 16 * (n / 16) * 8 * @as(usize, halves); const tr = try r.a.alloc(i16, E * words); for (tr) |*v| v.* = r.rng.int(i16); const suh = try r.a.alloc(f16, E * k); @@ -57,7 +65,7 @@ fn matrices(r: *Rig, k: usize, n: usize, shared_suh: ?[]const f16, out_suh: *u64 for (0..E) |e| { if (shared_suh) |s| @memcpy(suh[e * k ..][0..k], s) else @memcpy(suh[e * k ..][0..k], try signs(r, k, 1.0)); @memcpy(svh[e * n ..][0..n], try signs(r, n, 0.02)); - fmt.dequantize(.{ .halves = 8 }, .mcg, tr[e * words ..][0..words], k / 16, n / 16, suh[e * k ..][0..k], svh[e * n ..][0..n], w[e * k * n ..][0 .. k * n], scratch); + fmt.dequantize(.{ .halves = halves }, .mcg, tr[e * words ..][0..words], k / 16, n / 16, suh[e * k ..][0..k], svh[e * n ..][0..n], w[e * k * n ..][0 .. k * n], scratch); } out_suh.* = try r.dev(std.mem.sliceAsBytes(suh)); out_svh.* = try r.dev(std.mem.sliceAsBytes(svh)); @@ -67,18 +75,22 @@ fn matrices(r: *Rig, k: usize, n: usize, shared_suh: ?[]const f16, out_suh: *u64 return r.dev(std.mem.sliceAsBytes(ptrs)); } -fn weights(r: *Rig, one: bool) !Set { +/// A weight set with gate, up and down at `halves` half-bits, each projection its own width table. +fn weights(r: *Rig, one: bool, halves: [3]u16) !Set { var s: Set = undefined; s.shx = one; - const k2: [E]i32 = @splat(8); - s.k2 = try r.dev(std.mem.sliceAsBytes(&k2)); + s.halves = halves; + for ([_]*u64{ &s.k2, &s.k2_up, &s.k2_down }, halves) |t, hb| { + const k2: [E]i32 = @splat(hb); + t.* = try r.dev(std.mem.sliceAsBytes(&k2)); + } s.wg = try r.a.alloc(f64, E * D * N); s.wu = try r.a.alloc(f64, E * D * N); s.wd = try r.a.alloc(f64, E * N * D); const rot = if (one) try signs(r, D, 1.0) else null; // one input rotation for every gate and up - s.gt = try matrices(r, D, N, rot, &s.suh_g, &s.svh_g, s.wg); - s.ut = try matrices(r, D, N, rot, &s.suh_u, &s.svh_u, s.wu); - s.dt = try matrices(r, N, D, null, &s.suh_d, &s.svh_d, s.wd); + s.gt = try matrices(r, D, N, halves[0], rot, &s.suh_g, &s.svh_g, s.wg); + s.ut = try matrices(r, D, N, halves[1], rot, &s.suh_u, &s.svh_u, s.wu); + s.dt = try matrices(r, N, D, halves[2], null, &s.suh_d, &s.svh_d, s.wd); return s; } @@ -116,7 +128,7 @@ fn runMode(r: *Rig, k: *const glm.exl3.Kernels, ek: *const glm.experts.Kernels, .rank = try r.zeros((if (wide) P else 1) * 4), .hist = try r.zeros((if (wide) (P + 1023) / 1024 * (E + 1) else 1) * 4), }; - const sz: [4]usize = if (legacy) .{ compact_prompt.scratchBytes(rows, D, N, s.shx), 4, 4, 4 } else glm.exl3.scratchBytes(rows, D, N, prompt, s.shx); + const sz: [4]usize = if (legacy) .{ compact_prompt.scratchBytes(rows, D, N, s.shx), 4, 4, 4 } else glm.exl3.scratchFor(rows, D, N, prompt, s.experts()); const sc: glm.exl3.Scratch = .{ .picks = try r.zeros(sz[0]), .xg = try r.zeros(sz[1]), .xu = try r.zeros(sz[2]), .z = try r.zeros(sz[3]) }; const ey = if (sentinel) |value| blk: { const words = try r.a.alloc(u32, rows * slots * D); @@ -243,9 +255,12 @@ pub fn run_(gpu: Gpu) !void { defer k.unload(); var ek = try glm.experts.Kernels.load(gpu.d, pm, @intCast(try gpu.ctx.attribute(.multiprocessor_count)), null); defer ek.unload(); - for ([_]bool{ true, false }) |one| { - const s = try weights(&r, one); - try largeBytes(&r, &k, &ek, s); + // Mia-AiLab's 4-bit experts, a mixed checkpoint's 3-bit gate and up over 4-bit down, and three widths at once + for ([_][3]u16{ .{ 8, 8, 8 }, .{ 6, 6, 8 }, .{ 4, 6, 8 } }) |halves| for ([_]bool{ true, false }) |one| { + const s = try weights(&r, one, halves); + std.debug.print("glm-exl3: {s} experts, {s}\n", .{ s.name(), if (one) "one rotation" else "a rotation an expert" }); + // widths the prompt kernels do not take run the compact path both ways: nothing to compare + if (cuda.exl3_experts.prompt.eligible(glm.exl3.layer(s.experts(), E, D, N, limit))) try largeBytes(&r, &k, &ek, s); for ([_]usize{ 1, 3, 8 }) |rows| { // decode windows const x = try r.bfs(rows * D, 1.0); const pk = try picks(&r, rows); @@ -274,9 +289,10 @@ pub fn run_(gpu: Gpu) !void { } } } - } - { // a NaN in one row's input: that row's routed slots NaN, every other row finite - const s = try weights(&r, true); + }; + // a NaN in one row's input: that row's routed slots NaN, every other row finite + for ([_][3]u16{ .{ 8, 8, 8 }, .{ 6, 6, 8 } }) |halves| { + const s = try weights(&r, true, halves); const rows = 4; const x = try r.bfs(rows * D, 1.0); x[2 * D + 17] = 0x7fc0; diff --git a/zig/tests/cuda/main.zig b/zig/tests/cuda/main.zig index 3626882aaaf..3b20c3dbacc 100644 --- a/zig/tests/cuda/main.zig +++ b/zig/tests/cuda/main.zig @@ -36,8 +36,6 @@ const glm_index_check = @import("glm_index_check.zig"); const carveout_tests = @import("carveout_tests.zig"); const nvfp4_tests = @import("nvfp4_tests.zig"); const modelopt_tests = @import("modelopt_tests.zig"); -const exl3_tests = @import("exl3_tests.zig"); -const exl3_plan_bench = @import("exl3_plan_bench.zig"); const experts3_tests = @import("experts3_tests.zig"); const moe_tests = @import("moe_tests.zig"); const ck_tests = @import("ck_tests.zig"); @@ -244,6 +242,7 @@ fn run(gpu: check.Gpu, cmd: []const u8, rest: []const [:0]const u8) !void { if (std.mem.eql(u8, cmd, "w4a8")) return w4a8_tests.run(gpu); if (std.mem.eql(u8, cmd, "glm-exl3") or std.mem.eql(u8, cmd, "glm-exl3-items")) return glm_exl3_tests.runCmd(gpu, cmd); if (std.mem.eql(u8, cmd, "glm-kda-pad-split")) return glm_kda_pad_check.run(gpu); + if (std.mem.eql(u8, cmd, "glm-exl3-layer")) return @import("glm_exl3_layer_tests.zig").run(gpu, try arg(rest, 0), try arg(rest, 1), try arg(rest, 2), try arg(rest, 3)); if (std.mem.eql(u8, cmd, "glm-mm-fixed")) return @import("glm_mm_fixed_tests.zig").run(gpu); if (std.mem.eql(u8, cmd, "glm-mm-bench")) return @import("glm_mm_bench.zig").run(gpu); if (std.mem.eql(u8, cmd, "glm-pdl-order")) return @import("glm_pdl_order.zig").run(gpu, if (rest.len > 0) rest[0] else null); @@ -261,13 +260,7 @@ fn run(gpu: check.Gpu, cmd: []const u8, rest: []const [:0]const u8) !void { if (std.mem.eql(u8, cmd, "exlr8")) return exlr8_tests.run(gpu); if (std.mem.eql(u8, cmd, "exlr8-dense")) return exlr8_dense_tests.run(gpu, if (rest.len > 0) rest[0] else null); if (std.mem.eql(u8, cmd, "exlr8-bench")) return exlr8_tests.bench(gpu, try arg(rest, 0), if (rest.len > 1) rest[1] else "home", if (rest.len > 2) try std.fmt.parseInt(u16, rest[2], 10) else 40, if (rest.len > 3) try std.fmt.parseInt(usize, rest[3], 10) else 4); - if (std.mem.eql(u8, cmd, "exl3")) return exl3_tests.run(gpu, if (rest.len > 0) rest[0] else "none"); - if (std.mem.eql(u8, cmd, "exl3-grouped-tile")) return @import("exl3_grouped_tile_tests.zig").run(gpu); - if (std.mem.eql(u8, cmd, "exl3-tiles")) return @import("exl3_candidate_tests.zig").run(gpu, if (rest.len > 0) rest[0] else null); - if (std.mem.eql(u8, cmd, "exl3-shapes")) return exl3_plan_bench.profileShapes(gpu, if (rest.len > 0) rest[0] else null); - if (std.mem.eql(u8, cmd, "exl3-midm")) return exl3_plan_bench.midm(gpu); - if (std.mem.eql(u8, cmd, "exl3-plans")) return exl3_plan_bench.run(gpu, if (rest.len > 0) rest[0] else null); - if (std.mem.eql(u8, cmd, "exl3-contract")) return @import("contract_exl3.zig").run(gpu); + if (try @import("exl3_commands.zig").run(gpu, cmd, rest)) return; if (std.mem.eql(u8, cmd, "exl3-tp2")) return @import("exl3_tp2_tests.zig").run(gpu, try arg(rest, 0), try arg(rest, 1), if (rest.len > 2) rest[2] else "none"); if (std.mem.eql(u8, cmd, "qwen35-tp-cut")) return @import("qwen35_tp_cut_tests.zig").run(gpu, try arg(rest, 0), if (rest.len > 1) rest[1] else "1"); if (std.mem.eql(u8, cmd, "sample")) return sample_tests.draws(gpu); diff --git a/zig/tests/cuda/main_usage.zig b/zig/tests/cuda/main_usage.zig index c3dcff072e4..817792de607 100644 --- a/zig/tests/cuda/main_usage.zig +++ b/zig/tests/cuda/main_usage.zig @@ -129,6 +129,7 @@ pub const usage = \\ exl3-tp2 [dir] EXL3 tensor parallel: rank shards vs the Python engine's, all-gathered (dir none skips them) \\ exl3-tiles [DIR] EXL3's tile candidate: codebooks and tiles bit-equal, FP64, rows through qlinear and Dense \\ qwen35-tp-cut PACK [STEP] the 27B's EXL3 weights cut for two ranks at the whole plan: each rank's columns, one run's bytes + \\ exl3-prompt-k6 [DIR|none] [BASE] EXL3 prompt kernels at 3 and 4 bits, GLM's shapes: runSlots, FP64, row bytes, time; DIR adds a real layer, BASE (an earlier exl3_experts fatbin) its 4-bit bytes \\ train-pack MODEL EXAMPLES [COUNT] training passes holding several sequences against one a pass: differences, time \\ kernel-contract [WORD...] the contract's gates, each planted control red (-Dnvcc); WORDs: kernels named so \\ qmm-prefill-many-contract the GB10 bit-exact multi-projection prompt launch against separate launches @@ -157,6 +158,7 @@ pub const usage = \\ idol-contract Idol's denoiser glue and head-64 attention through gates 1-4, controls red \\ glm-exl3 | glm-exl3-items GLM's EXL3 routed experts, decode and prompt, against float64, and the item plan's decode against the plain decode, byte for byte (synthetic) \\ glm-kda-pad-split TF_GLM_KDA_PAD's padding of the bf16 and split KDA stacks at TP=3 (synthetic) + \\ glm-exl3-layer one checkpoint layer's EXL3 experts through the GLM loader, against float64 \\ glm-vision MODEL F32 BF16 IMG GLM's image tower and preparation against vision_ref.py's torch runs \\ glm-mm-fixed Prompt K policies: FP64, every row alone/batched, offsets and guarded tails \\ glm-mm-bench GLM's bf16 linears: b16.matmul against glm_mm, by rows (one GPU)