diff --git a/CHANGELOG.md b/CHANGELOG.md index 4a3ca111d97..3f271b82470 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 +- HIP: a routed prompt plan keeps the stacked shared expert whole up to the GEMM tile instead of cutting it into 8-row items, and on gfx1151 a prompt pass of 33 rows or more takes the GEMM tile for every expert; decode, lane rounds and the MTP draft head keep the 8-row tile, and outputs keep their bytes (#3521, fixes #3161). Thanks to @AbrahamCete. + - CUDA: the Windows Qwen3.5 diagnostic build compiles again, with named refusals where a POSIX stage or pipe is needed; 5/5 Windows GNU cross-build steps pass (#4112, refs #4105). Thanks to @AIFlowML. - Tests: the serve-config fixtures no longer depend on a group-friendly umask, while the permission refusals stay; 39/39 host tests pass under umask 002 and 022 on Linux and macOS (#4115, fixes #4113). Thanks to @AIFlowML. diff --git a/zig/kernels/hip/ops/moe.hpp b/zig/kernels/hip/ops/moe.hpp index 4971dd70278..84806929c36 100644 --- a/zig/kernels/hip/ops/moe.hpp +++ b/zig/kernels/hip/ops/moe.hpp @@ -6,9 +6,11 @@ namespace { -// Stable-sorts the pairs by expert into members and cuts items of at most `tile` pairs; one block, counted per segment. -extern "C" __global__ void tf_moe_route(const int* picks, int pairs, int experts, int tile, int* members, int* items, - int capacity) { +// Stable-sorts the pairs by expert into members and cuts items of at most `tile` pairs, the `shared_expert`'s of at +// most `shared_tile` (-1: none); one block, counted per segment. +extern "C" __global__ void tf_moe_route(const int* picks, int pairs, int experts, int tile, int shared_expert, + int shared_tile, int* members, int* items, int capacity) { + const auto cut = [=](int e) { return e == shared_expert ? shared_tile : tile; }; extern __shared__ int shared[]; int* counts = shared; int* starts = shared + experts; @@ -42,7 +44,7 @@ extern "C" __global__ void tf_moe_route(const int* picks, int pairs, int experts int own_c = 0, own_n = 0; for (int e = lo; e < hi; ++e) { own_c += counts[e]; - own_n += (counts[e] + tile - 1) / tile; + own_n += (counts[e] + cut(e) - 1) / cut(e); } scan_c[t] = own_c; scan_n[t] = own_n; @@ -58,7 +60,7 @@ extern "C" __global__ void tf_moe_route(const int* picks, int pairs, int experts for (int e = lo; e < hi; ++e) { starts[e] = start; start += counts[e]; - end += (counts[e] + tile - 1) / tile; + end += (counts[e] + cut(e) - 1) / cut(e); ends[e] = end; } __syncthreads(); @@ -77,12 +79,13 @@ extern "C" __global__ void tf_moe_route(const int* picks, int pairs, int experts else hi = mid; } int e = lo < experts - 1 ? lo : experts - 1; - int reps = (counts[e] + tile - 1) / tile; + const int te = cut(e); + int reps = (counts[e] + te - 1) / te; int within = slot - (ends[e] - reps); - int count = counts[e] - within * tile; + int count = counts[e] - within * te; items[slot * 3] = e; - items[slot * 3 + 1] = starts[e] + within * tile; - items[slot * 3 + 2] = count < 0 ? 0 : (count > tile ? tile : count); + items[slot * 3 + 1] = starts[e] + within * te; + items[slot * 3 + 2] = count < 0 ? 0 : (count > te ? te : count); } } diff --git a/zig/src/core/contract/hip_records_router.zig b/zig/src/core/contract/hip_records_router.zig index 37ef179ea86..40ba3f28173 100644 --- a/zig/src/core/contract/hip_records_router.zig +++ b/zig/src/core/contract/hip_records_router.zig @@ -1,4 +1,4 @@ -//! Gate 5's records of the router over the stored bf16 rows (decode.hip: tf_router_bf16). +//! Gate 5's records of the router over the stored bf16 rows (decode.hip: tf_router_bf16) and the route (ops.hip). const std = @import("std"); const limits = @import("limits.zig"); const Record = @import("hip_records.zig").Record; @@ -16,8 +16,19 @@ fn routeTile(comptime name: []const u8, comptime symbol: []const u8) Record { }; } -/// The same launch in bf16, whose weights are the wider activation's rows. -pub const records = [2]Record{ +/// The route plan's one block: the launcher's most LDS, 1,024 experts' counts, starts and ends, 16 segments, the scan. +const plan: Record = .{ + .launch = .{ .name = "moe route tf_moe_route", .symbol = "tf_moe_route", .image = "ops", .threads = 256, .dynamic = 3 * 1024 * 4 + 16 * 1024 * 2 + 2 * 256 * 4 }, + .usage = .{ + .{ .vgprs = 63, .sgprs = 28, .lds = 0, .private = 0, .bound = 1024, .wave = 32 }, + .{ .vgprs = 63, .sgprs = 28, .lds = 0, .private = 0, .bound = 1024, .wave = 32 }, + .{ .vgprs = 63, .sgprs = 28, .lds = 0, .private = 0, .bound = 1024, .wave = 32 }, + .{ .vgprs = 64, .sgprs = 27, .lds = 0, .private = 0, .bound = 1024, .wave = 32 }, + }, +}; + +/// The same launch in bf16, whose weights are the wider activation's rows; then the route plan the picks feed. +pub const records = [3]Record{ routeTile("router tf_router_bf16_f16", "tf_router_bf16_f16"), .{ .launch = .{ .name = "router tf_router_bf16", .symbol = "tf_router_bf16", .image = "decode", .threads = 128 }, @@ -28,4 +39,5 @@ pub const records = [2]Record{ .{ .vgprs = 36, .sgprs = 65, .lds = 0, .private = 0, .bound = 128, .wave = 32 }, }, }, + plan, }; diff --git a/zig/src/hip/kernel_tests.zig b/zig/src/hip/kernel_tests.zig index 7bd77d23ec3..5c743941f86 100644 --- a/zig/src/hip/kernel_tests.zig +++ b/zig/src/hip/kernel_tests.zig @@ -49,6 +49,7 @@ test { _ = @import("kernel_tests/gdn_window.zig"); _ = @import("kernel_tests/mamba.zig"); _ = @import("kernel_tests/decode.zig"); + _ = @import("kernel_tests/route.zig"); _ = @import("kernel_tests/tail_pin.zig"); _ = @import("kernel_tests/chain.zig"); _ = @import("kernel_tests/attention.zig"); diff --git a/zig/src/hip/kernel_tests/affine/cells.zig b/zig/src/hip/kernel_tests/affine/cells.zig index 7a0ae15f892..01276eecc16 100644 --- a/zig/src/hip/kernel_tests/affine/cells.zig +++ b/zig/src/hip/kernel_tests/affine/cells.zig @@ -171,7 +171,7 @@ pub fn routedShape(c: Class, template: registry.Shape, tokens: usize) registry.S s.items = @intCast(selectorCount(c, tokens)); s.plan_pairs = @intCast(tokens * c.slots); s.expert_rows = moe.expertRows(tokens, routedSlots(c), c.experts); - s.m = @intCast(@min(moe.tileOf(tokens, false), tokens)); + s.m = @intCast(@min(moe.itemRowsOf(tokens, false, true, c.shared, moe.card_prompt_from), tokens)); return s; } diff --git a/zig/src/hip/kernel_tests/affine/product.zig b/zig/src/hip/kernel_tests/affine/product.zig index 2baeeaa27a3..e51cc091288 100644 --- a/zig/src/hip/kernel_tests/affine/product.zig +++ b/zig/src/hip/kernel_tests/affine/product.zig @@ -120,7 +120,10 @@ pub const Product = struct { fn planExperts(p: *Product, pairs: usize) !void { const c = p.c; // served: serving's tile, and the capacity it sizes the plan for (one token: an item a slot) - const tile = if (c.served) moe.tileOf(c.rows, false) else c.item_rows; + const tile = if (c.served) moe.tileOf(c.rows, false, c.path == .prefill, moe.card_prompt_from) else c.item_rows; + // served: the stacked shared expert (the last id) takes serving's own tile, whole below 64 rows in a prompt + const shared: ?u32 = if (c.served and c.shared) @intCast(c.experts) else null; + const shared_tile = if (c.served) moe.sharedTileOf(c.rows, false, c.path == .prefill) else tile; const size = if (c.exact) c.rows else moe.bucket(c.rows); const cap = if (c.served and c.rows > 1) moe.capacity(size * c.slots, c.experts + @intFromBool(c.shared)) else 0; const order = try gpa.alloc(i32, pairs); @@ -144,7 +147,8 @@ pub const Product = struct { while (i < pairs) { const e = p.expert_of[@intCast(order[i])]; var j = i; - while (j < pairs and j - i < tile and p.expert_of[@intCast(order[j])] == e) j += 1; + const cut = if (shared != null and shared.? == e) shared_tile else tile; + while (j < pairs and j - i < cut and p.expert_of[@intCast(order[j])] == e) j += 1; items[count * 3 ..][0..3].* = .{ @intCast(e), @intCast(i), @intCast(j - i) }; p.max_rows = @max(p.max_rows, j - i); count += 1; @@ -154,7 +158,7 @@ pub const Product = struct { std.debug.assert(cap == 0 or count <= cap); std.debug.assert(!slot_order or count == pairs); p.items = @max(count, cap); - if (c.served) p.max_rows = @min(tile, c.rows); + if (c.served) p.max_rows = @min(moe.itemRowsOf(c.rows, false, c.path == .prefill, shared != null, moe.card_prompt_from), c.rows); p.plan = try Buffer.fromHost(p.rig.base, items[0 .. p.items * 3]); errdefer { p.plan.?.free(); diff --git a/zig/src/hip/kernel_tests/ops.zig b/zig/src/hip/kernel_tests/ops.zig index f530a87f88e..e0ef4757b68 100644 --- a/zig/src/hip/kernel_tests/ops.zig +++ b/zig/src/hip/kernel_tests/ops.zig @@ -208,66 +208,6 @@ test "argmax and top-k follow torch's order: the larger value, then the lower in try std.testing.expectEqual(@as(i32, -1), gi[2 * stride]); } -test "the MoE route sorts pairs by expert, stably, into items of at most a tile" { - const t = try Rig.open(1 << 20); - defer t.close(); - const o = t.ops(&t.on); - var rng: rig.Rng = .{ .state = 0x2017E }; - for ([_][3]usize{ - .{ 257, 512, 16 }, - .{ 128, 37, 4 }, - .{ 64, 1000, 64 }, - .{ 513, 11, 8 }, - .{ 513, 2816, 8 }, - }) |shape| { - const experts = shape[0]; - const pairs = shape[1]; - const tile = shape[2]; - const picks = try gpa.alloc(i32, pairs); - defer gpa.free(picks); - // a skewed pick so some experts fill several tiles and others none - for (picks) |*p| p.* = @intCast(@min(experts - 1, (rng.next() >> 40) % 16 * (rng.next() >> 50) % experts)); - const counts = try gpa.alloc(usize, experts); - defer gpa.free(counts); - @memset(counts, 0); - for (picks) |p| counts[@intCast(p)] += 1; - var capacity: usize = 0; - for (counts) |c| capacity += (c + tile - 1) / tile; - capacity += 3; - var dev_picks = try t.upload(picks); - defer dev_picks.free(); - var members = try t.alloc(pairs * 4); - defer members.free(); - var items = try t.alloc(capacity * 12); - defer items.free(); - try o.moeRoute(at(dev_picks), pairs, experts, tile, at(members), at(items), capacity); - try t.stream.synchronize(); - const gm = try rig.download(i32, members); - defer gpa.free(gm); - const gi = try rig.download(i32, items); - defer gpa.free(gi); - var place: usize = 0; - var slot: usize = 0; - for (0..experts) |e| { - const start = place; - for (picks, 0..) |p, i| if (p == e) { - try std.testing.expectEqual(@as(i32, @intCast(i)), gm[place]); - place += 1; - }; - var left = counts[e]; - var first = start; - while (left > 0) : (slot += 1) { - const take = @min(left, tile); - try std.testing.expectEqualSlices(i32, &.{ @intCast(e), @intCast(first), @intCast(take) }, gi[slot * 3 ..][0..3]); - first += take; - left -= take; - } - } - // the slots past the plan are empty items - for (slot..capacity) |s| try std.testing.expectEqual(@as(i32, 0), gi[s * 3 + 2]); - } -} - fn silu(x: f64) f64 { return x / (1 + @exp(-x)); } diff --git a/zig/src/hip/kernel_tests/route.zig b/zig/src/hip/kernel_tests/route.zig new file mode 100644 index 00000000000..0bdd9f165e9 --- /dev/null +++ b/zig/src/hip/kernel_tests/route.zig @@ -0,0 +1,177 @@ +//! tf_moe_route's plans: each expert's pairs cut into items of its tile, the stacked shared expert's of its own. +const std = @import("std"); +const rig = @import("rig.zig"); +const Rig = rig.Rig; +const gpa = rig.gpa; +const at = rig.at; +const moe_plan = @import("../moe.zig"); + +/// tf_moe_route's plan of `picks`, checked: pairs in pick order, items of at most each expert's tile, then empty. +fn expectRoute(t: anytype, o: anytype, picks: []const i32, experts: usize, tile: usize, shared: ?usize, shared_tile: usize, capacity: usize) ![]i32 { + const pairs = picks.len; + var dev_picks = try t.upload(picks); + defer dev_picks.free(); + var members = try t.alloc(pairs * 4); + defer members.free(); + var items = try t.alloc(capacity * 12); + defer items.free(); + try o.moeRoute(at(dev_picks), pairs, experts, tile, shared, shared_tile, at(members), at(items), capacity); + try t.stream.synchronize(); + const gm = try rig.download(i32, members); + defer gpa.free(gm); + const gi = try rig.download(i32, items); + errdefer gpa.free(gi); + var place: usize = 0; + var slot: usize = 0; + for (0..experts) |e| { + const start = place; + var left: usize = 0; + for (picks, 0..) |p, i| if (p == e) { + try std.testing.expectEqual(@as(i32, @intCast(i)), gm[place]); + place += 1; + left += 1; + }; + const cut = if (shared != null and shared.? == e) shared_tile else tile; + var first = start; + while (left > 0) : (slot += 1) { + const take = @min(left, cut); + try std.testing.expectEqualSlices(i32, &.{ @intCast(e), @intCast(first), @intCast(take) }, gi[slot * 3 ..][0..3]); + first += take; + left -= take; + } + } + // the slots past the plan are empty items + try std.testing.expect(slot <= capacity); + for (slot..capacity) |s| try std.testing.expectEqual(@as(i32, 0), gi[s * 3 + 2]); + return gi; +} + +test "the MoE route sorts pairs by expert, stably, into items of at most a tile, the shared expert's of its own" { + const t = try Rig.open(1 << 20); + defer t.close(); + const o = t.ops(&t.on); + var rng: rig.Rng = .{ .state = 0x2017E }; + const none = std.math.maxInt(usize); + // experts, pairs, tile, the shared expert (`none`: every expert takes the tile) and its tile + for ([_][5]usize{ + .{ 257, 512, 16, none, 0 }, + .{ 128, 37, 4, none, 0 }, + .{ 64, 1000, 64, none, 0 }, + .{ 513, 11, 8, none, 0 }, + .{ 513, 2816, 8, none, 0 }, + // expert 0 fills most: a shared tile above and below the routed one; the last id, where empty slots clamp + .{ 257, 512, 8, 0, 128 }, + .{ 513, 2816, 32, 0, 16 }, + .{ 257, 512, 8, 256, 128 }, + }) |shape| { + const experts = shape[0]; + const pairs = shape[1]; + const tile = shape[2]; + const shared: ?usize = if (shape[3] == none) null else shape[3]; + const shared_tile = if (shared == null) tile else shape[4]; + const picks = try gpa.alloc(i32, pairs); + defer gpa.free(picks); + // a skewed pick so some experts fill several tiles and others none + for (picks) |*p| p.* = @intCast(@min(experts - 1, (rng.next() >> 40) % 16 * (rng.next() >> 50) % experts)); + const counts = try gpa.alloc(usize, experts); + defer gpa.free(counts); + @memset(counts, 0); + for (picks) |p| counts[@intCast(p)] += 1; + var capacity: usize = 0; + for (counts, 0..) |c, e| { + const cut = if (shared != null and shared.? == e) shared_tile else tile; + capacity += (c + cut - 1) / cut; + } + capacity += 3; + gpa.free(try expectRoute(t, o, picks, experts, tile, shared, shared_tile, capacity)); + } +} + +/// Each row's top-k distinct routed experts, half from six hot ones, then the shared one, as tf_moe_select writes them. +fn drawPicks(rng: *rig.Rng, picks: []i32, routed: usize, top_k: usize) void { + const slots = top_k + 1; + for (0..picks.len / slots) |r| { + const row = picks[r * slots ..][0..slots]; + for (row[0..top_k], 0..) |*e, k| { + const pool: u64 = if (k < top_k / 2) 6 else routed; + while (true) { + e.* = @intCast(rng.next() % pool); + if (std.mem.indexOfScalar(i32, row[0..k], e.*) == null) break; + } + } + row[top_k] = @intCast(routed); + } +} + +/// The most rows an item of the plan holds, and how many items the routed experts and the shared one fill. +const Items = struct { most: usize = 0, routed: usize = 0, shared: usize = 0 }; + +fn itemsOf(gi: []const i32, capacity: usize, shared: usize) Items { + var n: Items = .{}; + for (0..capacity) |s| { + const count: usize = @intCast(@max(gi[s * 3 + 2], 0)); + if (count == 0) continue; + n.most = @max(n.most, count); + if (gi[s * 3] == shared) n.shared += 1 else n.routed += 1; + } + return n; +} + +/// The items the routed experts of `picks` fill at `tile` pairs an item. +fn cutsAt(picks: []const i32, routed: usize, tile: usize) usize { + var n: usize = 0; + for (0..routed) |e| n += (std.mem.count(i32, picks, &.{@intCast(e)}) + tile - 1) / tile; + return n; +} + +test "a 33 to 63 row prompt plan: every expert whole where the GEMM tile starts at 33, routed 8-row items at 64" { + const t = try Rig.open(1 << 20); + defer t.close(); + var o = t.ops(&t.on); + var rng: rig.Rng = .{ .state = 0x3161 }; + const gemm_rows = 128; + // routed experts, top-k and the prompt's rows: the 35B-A3B's 256 below 64 rows and past, Flash Next's 512 + for ([_][3]usize{ .{ 256, 8, 33 }, .{ 256, 8, 40 }, .{ 256, 8, 56 }, .{ 256, 8, 63 }, .{ 256, 8, 64 }, .{ 256, 8, 130 }, .{ 512, 10, 41 } }) |shape| { + const routed = shape[0]; + const top_k = shape[1]; + const rows = shape[2]; + const experts = routed + 1; + const slots = top_k + 1; + const picks = try gpa.alloc(i32, rows * slots); + defer gpa.free(picks); + drawPicks(&rng, picks, routed, top_k); + // the hot experts hold more than 8 pairs, so the two starts plan differently below 64 rows + const used = cutsAt(picks, routed, rows); + try std.testing.expect(cutsAt(picks, routed, 8) > used); + const capacity = moe_plan.capacity(moe_plan.bucket(rows) * slots, experts); + // a prompt pass on a card that starts the GEMM tile at 33 (gfx1151) and on one left at 64 + o.prefill = true; + for ([_]usize{ 33, 64 }) |from| { + const tile = moe_plan.tileOf(rows, false, true, from); + try std.testing.expectEqual(@as(usize, if (rows < from) 8 else gemm_rows), tile); + if (from == moe_plan.card_prompt_from) try std.testing.expectEqual(tile, moe_plan.tileFor(o, rows)); + const gi = try expectRoute(t, o, picks, experts, tile, routed, moe_plan.sharedTileFor(o, rows), capacity); + defer gpa.free(gi); + const n = itemsOf(gi, capacity, routed); + try std.testing.expectEqual(cutsAt(picks, routed, tile), n.routed); + // from the start up to 127 rows every routed expert is one item; the shared one is whole on both cards + if (rows >= from and rows < gemm_rows) try std.testing.expectEqual(used, n.routed); + try std.testing.expectEqual((rows + gemm_rows - 1) / gemm_rows, n.shared); + // the launches' m is the most rows an item holds + try std.testing.expectEqual(n.most, @min(moe_plan.itemRowsOf(rows, false, true, true, from), rows)); + } + // decode and the MTP draft head (neither switch) and a lane round keep the 8-row tile below 64, shared too + o.prefill = false; + for ([_]bool{ false, true }) |window| { + o.window = window; + const tile = moe_plan.tileFor(o, rows); + try std.testing.expectEqual(@as(usize, if (rows < 64 or window) 8 else gemm_rows), tile); + try std.testing.expectEqual(tile, moe_plan.sharedTileFor(o, rows)); + const gi = try expectRoute(t, o, picks, experts, tile, routed, tile, capacity); + defer gpa.free(gi); + const n = itemsOf(gi, capacity, routed); + try std.testing.expectEqual(n.most, @min(moe_plan.itemRowsFor(o, rows, true), rows)); + } + o.window = false; + } +} diff --git a/zig/src/hip/launches/moe.zig b/zig/src/hip/launches/moe.zig index ae1d7f7afbe..67c87989f21 100644 --- a/zig/src/hip/launches/moe.zig +++ b/zig/src/hip/launches/moe.zig @@ -133,12 +133,14 @@ pub fn tf_moe_combine_gate(l: *const Launcher, y: CF, wts: CF, shared: CF, out: try l.go(l.moe_combine_gate, dim(cdiv(d, 256), r, 1), dim(256, 1, 1), 0, s, &a); } -pub fn tf_moe_route(l: *const Launcher, picks: CI, pairs: c_int, experts: c_int, tile: c_int, members: I, items: I, capacity: c_int, s: S) Error!void { +pub fn tf_moe_route(l: *const Launcher, picks: CI, pairs: c_int, experts: c_int, tile: c_int, shared: c_int, shared_tile: c_int, members: I, items: I, capacity: c_int, s: S) Error!void { var a: Args = .{}; try a.add(ad(picks)); try a.add(pairs); try a.add(experts); try a.add(tile); + try a.add(shared); + try a.add(shared_tile); try a.add(ad(members)); try a.add(ad(items)); try a.add(capacity); diff --git a/zig/src/hip/moe.zig b/zig/src/hip/moe.zig index 5ead1118201..0716143c854 100644 --- a/zig/src/hip/moe.zig +++ b/zig/src/hip/moe.zig @@ -2,6 +2,8 @@ const std = @import("std"); const ops = @import("ops/ops.zig"); +const kernels = @import("kernels.zig"); +const tuning = @import("tuning/tuning.zig"); const Ops = ops.Ops; const Tensor = ops.Tensor; @@ -65,14 +67,41 @@ pub fn capacity(pairs: usize, experts: usize) usize { return @min(pairs, experts) + pairs / @min(TILE, LANE_ROWS); } -/// tile_for: the decode tile below BLOCK_FROM rows, the GEMM tile from there; a lane round's rows keep the decode tile. +/// The fewest rows a prompt pass cuts at the GEMM tile on this build's card: its tuning table's, else BLOCK_FROM. +pub const card_prompt_from: usize = tuning.promptBlockFrom(kernels.arch) orelse BLOCK_FROM; + +/// tile_for: the decode tile below the GEMM tile's start, the GEMM tile from there; a lane round keeps the decode tile. pub fn tileFor(o: Ops, rows: usize) usize { - return tileOf(rows, o.window); + return tileOf(rows, o.window, o.prefill, card_prompt_from); +} + +/// tile_for's rule on its own, for a fixture that plans as serving does: a prompt pass's tile starts at `prompt_from`. +pub fn tileOf(rows: usize, window: bool, prefill: bool, prompt_from: usize) usize { + // decode and the MTP draft head keep BLOCK_FROM: a card's start is gated on the prompt pass + const from = if (prefill) prompt_from else BLOCK_FROM; + return if (rows < from or window) LANE_ROWS else BLOCK_ROWS; } -/// tile_for's rule on its own, for a fixture that plans as serving does. -pub fn tileOf(rows: usize, window: bool) usize { - return if (rows < BLOCK_FROM or window) LANE_ROWS else BLOCK_ROWS; +/// The stacked shared expert's tile: it holds every row, so a prompt pass never cuts it below the GEMM tile. +pub fn sharedTileFor(o: Ops, rows: usize) usize { + return sharedTileOf(rows, o.window, o.prefill); +} + +/// sharedTileFor's rule on its own, for a fixture that plans as serving does. +pub fn sharedTileOf(rows: usize, window: bool, prefill: bool) usize { + // decode and lane rounds keep tile_for's: their launches take m as the most rows an item holds + return if (prefill and !window) BLOCK_ROWS else tileOf(rows, window, prefill, BLOCK_FROM); +} + +/// The routed launches' m before the rows cap it: the most rows a plan's item holds, the shared one's where it stacks. +pub fn itemRowsFor(o: Ops, rows: usize, shared: bool) usize { + return itemRowsOf(rows, o.window, o.prefill, shared, card_prompt_from); +} + +/// itemRowsFor's rule on its own, for a fixture that plans as serving does. +pub fn itemRowsOf(rows: usize, window: bool, prefill: bool, shared: bool, prompt_from: usize) usize { + const tile = tileOf(rows, window, prefill, prompt_from); + return if (shared) @max(tile, sharedTileOf(rows, window, prefill)) else tile; } /// The average rows an expert of `experts` takes of `rows` tokens' `top_k` routed slots, rounded up; 0 without experts. @@ -83,7 +112,7 @@ pub fn expertRows(rows: usize, top_k: usize, experts: usize) u32 { /// `x` (rows, D) to (rows, D) in its dtype: the top-k experts plus the shared one; a tp rank returns its fp32 share. pub fn run(o: Ops, kind: Kind, r: Routed, x: Tensor, rows: usize, prefill: bool) ops.Error!Tensor { - _ = prefill; // the affine experts' arithmetic does not depend on it (the plan's tile comes from tile_for) + _ = prefill; // the affine experts' arithmetic does not depend on it (the plan's tiles come from `o`) const ex = r.experts; const slots = r.top_k + 1; const size = planRows(o, r.exact, rows); @@ -103,7 +132,8 @@ pub fn run(o: Ops, kind: Kind, r: Routed, x: Tensor, rows: usize, prefill: bool) const local = try o.arena.of(i32, size * slots); try o.moeLocalize(pick, r.remap, local, pairs, ex.count); tile = tileFor(o, rows); - try o.moeRoute(local, pairs, r.rows, tile, members, items, cap); + // a rank's local ids don't name the shared expert: every expert keeps the routed tile + try o.moeRoute(local, pairs, r.rows, tile, null, tile, members, items, cap); try o.moeForeignItems(items, cap, ex.count); const expert_rows = expertRows(rows, r.top_k, r.count()); const both = try o.projectRouted(x, ex.fused, items, count, members, pairs, slots, @min(tile, rows), expert_rows); @@ -174,7 +204,11 @@ fn expertParts(o: Ops, kind: Kind, r: Routed, x: Tensor, rows: usize, logits: u6 } else { try o.moeSelect(logits, pick, wts, null, 0, rows, r.count(), r.top_k); tile = tileFor(o, rows); - try o.moeRoute(pick, pairs, r.rows, tile, members, items, cap); + // the stacked shared expert is the last id; beside the stack its items are zeroed below, so it keeps the tile + const shared: ?usize = if (ex.shared == null) r.count() else null; + try o.moeRoute(pick, pairs, r.rows, tile, shared, sharedTileFor(o, rows), members, items, cap); + // the launches' m: the most rows an item holds, the shared expert's whole item in a prompt pass + tile = itemRowsFor(o, rows, shared != null); } // beside the stack the shared pair's id is the stack's first id past its experts: zero its item, never read its row if (ex.shared != null) try o.moeForeignItems(items, count, ex.count); @@ -227,3 +261,48 @@ test "planRows keeps RDNA3.5 lane rounds exact while leaving non-RDNA3.5 and non try std.testing.expectEqual(@as(usize, 3), planRows(window, true, 3)); } } + +test "the shared expert takes the GEMM tile in a prompt pass at any row count, the routed tile in decode and lane rounds" { + const o: Ops = .{ .l = undefined, .bf16 = true, .stream = undefined, .arena = undefined }; + var prompt = o; + prompt.prefill = true; + var round = o; + round.window = true; + for ([_]usize{ 2, 33, BLOCK_FROM - 1, BLOCK_FROM, 2048 }) |rows| { + try std.testing.expectEqual(@as(usize, BLOCK_ROWS), sharedTileFor(prompt, rows)); + // on a card that starts the GEMM tile at 64 the routed experts keep tile_for's in the same prompt pass + try std.testing.expectEqual(tileFor(o, rows), tileOf(rows, false, true, BLOCK_FROM)); + try std.testing.expectEqual(tileFor(o, rows), sharedTileFor(o, rows)); + try std.testing.expectEqual(@as(usize, LANE_ROWS), sharedTileFor(round, rows)); + // the launches' m holds the plan's largest item: the shared one only where it stacks in a prompt pass + try std.testing.expectEqual(@as(usize, BLOCK_ROWS), itemRowsFor(prompt, rows, true)); + try std.testing.expectEqual(tileFor(prompt, rows), itemRowsFor(prompt, rows, false)); + try std.testing.expectEqual(tileFor(o, rows), itemRowsFor(o, rows, true)); + try std.testing.expectEqual(@as(usize, LANE_ROWS), itemRowsFor(round, rows, true)); + try std.testing.expectEqual(tileOf(rows, false, true, BLOCK_FROM), itemRowsOf(rows, false, true, false, BLOCK_FROM)); + } +} + +test "a card's start moves a prompt pass's GEMM tile to 33 rows; decode, lane rounds and the MTP draft head keep 64" { + // decode and the MTP draft head run with neither switch, a lane round with `window` + const o: Ops = .{ .l = undefined, .bf16 = true, .stream = undefined, .arena = undefined }; + var round = o; + round.window = true; + for ([_]usize{ 2, 9, 32, 33, 40, 56, 63, 64, 65, 128 }) |rows| { + const gemm_at_33: usize = if (rows >= 33) BLOCK_ROWS else LANE_ROWS; + const gemm_at_64: usize = if (rows >= BLOCK_FROM) BLOCK_ROWS else LANE_ROWS; + // a prompt pass on a card that starts at 33, and on one left at 64 + try std.testing.expectEqual(gemm_at_33, tileOf(rows, false, true, 33)); + try std.testing.expectEqual(gemm_at_64, tileOf(rows, false, true, BLOCK_FROM)); + // whatever the card: decode and the draft head at 64, a lane round at the decode tile + try std.testing.expectEqual(gemm_at_64, tileOf(rows, false, false, 33)); + try std.testing.expectEqual(gemm_at_64, tileFor(o, rows)); + try std.testing.expectEqual(@as(usize, LANE_ROWS), tileOf(rows, true, true, 33)); + try std.testing.expectEqual(@as(usize, LANE_ROWS), tileFor(round, rows)); + // the launches' m follows: the routed tile, or the shared expert's whole item where it stacks in a prompt + try std.testing.expectEqual(gemm_at_33, itemRowsOf(rows, false, true, false, 33)); + try std.testing.expectEqual(@as(usize, BLOCK_ROWS), itemRowsOf(rows, false, true, true, 33)); + try std.testing.expectEqual(gemm_at_64, itemRowsOf(rows, false, false, true, 33)); + try std.testing.expectEqual(@as(usize, LANE_ROWS), itemRowsOf(rows, true, true, true, 33)); + } +} diff --git a/zig/src/hip/moe_nemotron.zig b/zig/src/hip/moe_nemotron.zig index f672619b8d2..8f31a9e0fd1 100644 --- a/zig/src/hip/moe_nemotron.zig +++ b/zig/src/hip/moe_nemotron.zig @@ -105,7 +105,7 @@ pub fn expertRows(o: Ops, l: Layer, x: Tensor, rows: usize) ops.Error!Ops.MoeRow o.stream, ); } - try o.moeRoute(local, pairs, plan_experts, tile, members, items, cap); + try o.moeRoute(local, pairs, plan_experts, tile, null, tile, members, items, cap); if (!l.whole()) try o.moeForeignItems(items, cap, l.own); } const act: Tensor = .{ .ptr = try o.arena.take(pairs * ni * kind.size()), .kind = kind }; diff --git a/zig/src/hip/ops/moe.zig b/zig/src/hip/ops/moe.zig index 2b4bf4a53b0..2b5bacc1d9b 100644 --- a/zig/src/hip/ops/moe.zig +++ b/zig/src/hip/ops/moe.zig @@ -38,8 +38,9 @@ pub fn moeSelect(o: Ops, logits: u64, pick: u64, wts: u64, plan: ?struct { items try o.l.tf_moe_select(f(logits), i(pick), f(wts), if (plan) |pl| i(pl.items) else null, if (plan) |pl| i(pl.members) else null, int(capacity), int(r), int(experts), int(top_k), o.stream); } -pub fn moeRoute(o: Ops, picks: u64, pairs: usize, experts: usize, tile: usize, members: u64, items: u64, capacity: usize) Error!void { - try o.l.tf_moe_route(@ptrFromInt(picks), int(pairs), int(experts), int(tile), i(members), i(items), int(capacity), o.stream); +/// The plan: pairs by expert in items of at most `tile` pairs, the `shared` expert's of at most `shared_tile`. +pub fn moeRoute(o: Ops, picks: u64, pairs: usize, experts: usize, tile: usize, shared: ?usize, shared_tile: usize, members: u64, items: u64, capacity: usize) Error!void { + try o.l.tf_moe_route(@ptrFromInt(picks), int(pairs), int(experts), int(tile), if (shared) |e| int(e) else -1, int(shared_tile), i(members), i(items), int(capacity), o.stream); } pub fn moeAct(o: Ops, both: u64, out: Tensor, pairs: usize, width: usize, limit: f32) Error!void { diff --git a/zig/src/hip/tuning/gfx1151.zon b/zig/src/hip/tuning/gfx1151.zon index a4941e41a04..61b4edc5600 100644 --- a/zig/src/hip/tuning/gfx1151.zon +++ b/zig/src/hip/tuning/gfx1151.zon @@ -15,8 +15,11 @@ // The 64-row routed tile's items of 8 rows or fewer take its K-parallel passes (measured on gfx1151). // A plain prompt of 1 or 2 rows takes the 2-row K-parallel tile (measured on gfx1151), // but 1 row of 2-bit or 3-bit codes keeps the 1-row tile, which is ahead there. +// prompt_block_from: the fewest rows a prompt pass's routed plan cuts at the 128-row GEMM tile (64 where unset); +// it serves only the chip the table is named after (measured on gfx1151). .{ .gfx = "gfx1151", + .prompt_block_from = 33, .entries = .{ // a lane round or a call of few rows: the stream tile takes what it can; matrix cores take 16 rows and up .{ .id = "mlx.project.decode.stream", .cost = 1, .rows = 16, .rows_matrix = 15 }, diff --git a/zig/src/hip/tuning/tuning.zig b/zig/src/hip/tuning/tuning.zig index f39e4f27518..6ccea4bf692 100644 --- a/zig/src/hip/tuning/tuning.zig +++ b/zig/src/hip/tuning/tuning.zig @@ -13,6 +13,30 @@ pub const gfx1100 = tuning.build(@import("gfx1100.zon")); pub const gfx1151 = tuning.build(@import("gfx1151.zon")); pub const gfx1201 = tuning.build(@import("gfx1201.zon")); +/// The tables' documents, for the fields a table sets beside its rows. +const docs = .{ @import("gfx1030.zon"), @import("gfx1100.zon"), @import("gfx1151.zon"), @import("gfx1201.zon") }; + +/// The fewest rows a prompt's routed plan cuts at the GEMM tile on `chip`: its own table's, null where none sets it. +pub fn promptBlockFrom(chip: []const u8) ?usize { + inline for (docs) |doc| { + // a generation's other chips share its costs, not this measured start + if (@hasField(@TypeOf(doc), "prompt_block_from") and std.mem.eql(u8, chip, doc.gfx)) return doc.prompt_block_from; + } + return null; +} + +test "only gfx1151 starts a prompt's routed GEMM tile below 64 rows, and only on that chip" { + try std.testing.expectEqual(@as(?usize, 33), promptBlockFrom("gfx1151")); + // the generation's other chips and the other tables keep the default; so does a build without kernels + for ([_][]const u8{ "gfx1150", "gfx1152", "gfx1153", "gfx1030", "gfx1100", "gfx1101", "gfx1201", "" }) |chip| { + try std.testing.expectEqual(@as(?usize, null), promptBlockFrom(chip)); + } + // a table's start lies past the decode tile's 8 rows and at most at the default's 64 + inline for (docs) |doc| if (@hasField(@TypeOf(doc), "prompt_block_from")) { + try std.testing.expect(doc.prompt_block_from > 8 and doc.prompt_block_from <= 64); + }; +} + test "only a routed prompt row bounds its pairs per item, by a finite number from 0 to 256" { for ([_]*const Table{ &gfx1030, &gfx1100, &gfx1151, &gfx1201 }) |t| for (t.rows) |r| { try std.testing.expect(std.math.isFinite(r.pairs_per_item) and r.pairs_per_item >= 0 and r.pairs_per_item <= 256); diff --git a/zig/tests/hip/contract_main.zig b/zig/tests/hip/contract_main.zig index 8b07e4a4d4e..34a466f3f2d 100644 --- a/zig/tests/hip/contract_main.zig +++ b/zig/tests/hip/contract_main.zig @@ -30,6 +30,7 @@ const dense12_k = @import("contract_dense_wmma12.zig"); const silu_k = @import("contract_silu_fuse.zig"); const gate_k = @import("contract_moe_gate.zig"); const router_k = @import("contract_router.zig"); +const route_k = @import("contract_route.zig"); const kit = @import("contract_kit.zig"); const item_k = @import("contract_wmma_item.zig"); const embed_k = @import("contract_embed.zig"); @@ -313,6 +314,11 @@ fn run(a: std.mem.Allocator, io: std.Io) !usize { for (&routers, [_]kit.Kind{ .f16, .bf16 }) |*x, k| x.* = router_k.Router.init(a, &r, s, &l, k); defer for (&routers) |*x| x.deinit(); for (&routers) |*x| try kernels.append(a, x.kernel()); + // the route plan in each mode the engine asks it, then a control on each rule of its cut + var routes: [route_k.cases.len]route_k.Route = undefined; + for (&routes, route_k.cases) |*x, case| x.* = .init(a, &r, s, &l, case); + defer for (&routes) |*x| x.deinit(); + for (&routes) |*x| try kernels.append(a, x.kernel()); // the few-row matrix-core tiles run on gfx11's matrix cores only const matrix = if (hip.Caps.of(arch)) |v| v.matrix == .wmma11 else false; // the last one is the few-row passes' control, on its case's geometry diff --git a/zig/tests/hip/contract_route.zig b/zig/tests/hip/contract_route.zig new file mode 100644 index 00000000000..7a96a5d8c39 --- /dev/null +++ b/zig/tests/hip/contract_route.zig @@ -0,0 +1,298 @@ +//! The MoE route plan under the contract on HIP: tf_moe_route's members and items, exactly, in each mode it serves. +const std = @import("std"); +const hip = @import("hip"); +const core = @import("core"); +const rig_ = @import("contract_rig.zig"); + +const contract = core.contract; +const c = contract.spec; +const g = contract.gates; +const moe = hip.moe; + +/// Who asks for the plan: a prompt pass (GEMM tile from 33 or 64 rows, or no stacked shared expert), decode, a lane. +pub const Mode = enum { prompt_33, prompt_64, apart, decode, lane }; + +/// The real launch, or a control's: the shared expert cut at the routed tile, or a start of 33 planned from 64. +pub const Fault = enum { none, shared_cut, start_64 }; + +pub const Case = struct { mode: Mode, fault: Fault = .none }; + +/// Each mode, then a control on each rule: a prompt's stacked shared expert whole, and gfx1151's start at 33. +pub const cases = [_]Case{ + .{ .mode = .prompt_33 }, + .{ .mode = .prompt_64 }, + .{ .mode = .apart }, + .{ .mode = .decode }, + .{ .mode = .lane }, + .{ .mode = .prompt_64, .fault = .shared_cut }, + .{ .mode = .prompt_33, .fault = .start_64 }, +}; + +fn none(_: c.Shape) usize { + return 0; +} + +const rule = "int32 ids in and out, nothing to be NaN, infinite or summed: each expert's pairs in pick order, " ++ + "cut into items of its tile in expert order, then empty items of the last expert"; + +fn name(case: Case) []const u8 { + return switch (case.fault) { + .shared_cut => "control: tf_moe_route cuts a prompt pass's stacked shared expert at the routed 8-row tile", + .start_64 => "control: tf_moe_route plans a prompt pass from 64 rows where the GEMM tile starts at 33", + .none => switch (case.mode) { + .prompt_33 => "hip tf_moe_route (a prompt pass, the GEMM tile from 33 rows)", + .prompt_64 => "hip tf_moe_route (a prompt pass, the GEMM tile from 64 rows)", + .apart => "hip tf_moe_route (a prompt pass, no shared expert stacked)", + .decode => "hip tf_moe_route (decode and the MTP draft head)", + .lane => "hip tf_moe_route (a lane round)", + }, + }; +} + +/// Rows around the GEMM tile's starts and its 128 rows: the 35B-A3B's 256 experts and the shared one, top 8. +const prompt = [_]c.Shape{ + .{ .rows = 40, .n = 257, .k = 9 }, + .{ .rows = 9, .n = 257, .k = 9 }, + .{ .rows = 32, .n = 257, .k = 9 }, + .{ .rows = 33, .n = 257, .k = 9 }, + .{ .rows = 56, .n = 257, .k = 9 }, + .{ .rows = 63, .n = 257, .k = 9 }, + .{ .rows = 64, .n = 257, .k = 9 }, + .{ .rows = 127, .n = 257, .k = 9 }, + .{ .rows = 128, .n = 257, .k = 9 }, + .{ .rows = 130, .n = 257, .k = 9 }, + // Flash Next: 512 experts and the shared one, top 10 + .{ .rows = 33, .n = 513, .k = 11 }, + .{ .rows = 41, .n = 513, .k = 11 }, + .{ .rows = 63, .n = 513, .k = 11 }, + .{ .rows = 64, .n = 513, .k = 11 }, +}; + +/// No shared expert stacked: Nemotron's 128 experts, top 6, and the 35B-A3B's 257 ids as a tp rank plans them. +const apart = [_]c.Shape{ + .{ .rows = 40, .n = 128, .k = 6 }, + .{ .rows = 9, .n = 128, .k = 6 }, + .{ .rows = 32, .n = 128, .k = 6 }, + .{ .rows = 33, .n = 128, .k = 6 }, + .{ .rows = 63, .n = 128, .k = 6 }, + .{ .rows = 64, .n = 128, .k = 6 }, + .{ .rows = 130, .n = 128, .k = 6 }, + .{ .rows = 40, .n = 257, .k = 9 }, +}; + +/// Decode rounds and the MTP draft head, a few streams' rows to wide rounds: 8-row items below 64, shared too. +const decode = [_]c.Shape{ + .{ .rows = 8, .n = 257, .k = 9 }, + .{ .rows = 2, .n = 257, .k = 9 }, + .{ .rows = 4, .n = 257, .k = 9 }, + .{ .rows = 16, .n = 257, .k = 9 }, + .{ .rows = 40, .n = 257, .k = 9 }, + .{ .rows = 63, .n = 257, .k = 9 }, + .{ .rows = 64, .n = 257, .k = 9 }, + .{ .rows = 8, .n = 513, .k = 11 }, + .{ .rows = 41, .n = 513, .k = 11 }, +}; + +/// A lane round's rows: 8-row items at every count, the shared expert's too. +const lane = [_]c.Shape{ + .{ .rows = 40, .n = 257, .k = 9 }, + .{ .rows = 2, .n = 257, .k = 9 }, + .{ .rows = 9, .n = 257, .k = 9 }, + .{ .rows = 63, .n = 257, .k = 9 }, + .{ .rows = 64, .n = 257, .k = 9 }, + .{ .rows = 130, .n = 257, .k = 9 }, + .{ .rows = 41, .n = 513, .k = 11 }, +}; + +/// rows: the prompt's or round's rows; n: the experts the plan cuts, a stacked shared one last; k: pairs a row. +pub fn spec(case: Case) c.Spec { + return .{ + .name = name(case), + .accum = .none, + .depth = none, + .out = .raw, + .nan = .{ .stated = rule }, + .sums = .{ .f16 = 0, .bf16 = 0, .why = "integer ids and counts: there are no sums to round" }, + // rows around the GEMM tile's default start, and experts where the kernel's 64 count segments become 16 + .tiles = .{ .{ .size = 64, .min = 2 }, .{ .size = 256, .min = 16 }, .{} }, + .served = switch (case.mode) { + .prompt_33, .prompt_64 => &prompt, + .apart => &apart, + .decode => &decode, + .lane => &lane, + }, + }; +} + +/// The cut the engine asks of the route in the mode, by moe.zig's rules: the routed experts' tile, the shared one's. +fn asked(mode: Mode, rows: usize) [2]usize { + const start = moe.card_prompt_from; + return switch (mode) { + .prompt_33 => .{ moe.tileOf(rows, false, true, 33), moe.sharedTileOf(rows, false, true) }, + .prompt_64 => .{ moe.tileOf(rows, false, true, 64), moe.sharedTileOf(rows, false, true) }, + .apart => .{ moe.tileOf(rows, false, true, start), moe.tileOf(rows, false, true, start) }, + .decode => .{ moe.tileOf(rows, false, false, start), moe.sharedTileOf(rows, false, false) }, + .lane => .{ moe.tileOf(rows, true, false, start), moe.sharedTileOf(rows, true, false) }, + }; +} + +/// The cut this contract states: 8-row items below the GEMM tile's start, 128 from it; a prompt's shared expert at 128. +fn wanted(mode: Mode, rows: usize) [2]usize { + const from: usize = switch (mode) { + .prompt_33 => 33, + .prompt_64, .decode => 64, + .apart => moe.card_prompt_from, + .lane => std.math.maxInt(usize), + }; + const tile: usize = if (rows < from) 8 else 128; + return .{ tile, if (mode == .prompt_33 or mode == .prompt_64) 128 else tile }; +} + +fn word(bytes: []const u8, i: usize) i32 { + return std.mem.readInt(i32, bytes[4 * i ..][0..4], .little); +} + +/// shape.rows rows of shape.k picks over shape.n experts: the members [pairs] and items [capacity][3] they plan. +pub const Route = struct { + rig: rig_.Rig, + l: *const hip.Launcher, + case: Case, + arena: std.heap.ArenaAllocator, + shape: c.Shape = undefined, + picks: []i32 = &.{}, + capacity: usize = 0, + in: u64 = 0, + members: u64 = 0, + items: u64 = 0, + msg: [240]u8 = undefined, + + pub fn init(a: std.mem.Allocator, rt: *const hip.Runtime, s: hip.Stream, l: *const hip.Launcher, case: Case) Route { + return .{ .rig = .{ .a = a, .r = rt, .s = s }, .l = l, .case = case, .arena = .init(a) }; + } + + pub fn deinit(self: *Route) void { + self.arena.deinit(); + self.rig.deinit(); + } + + /// A control keeps its mode's spec under its own name and must go red at gate 3's exact compare. + pub fn kernel(self: *Route) g.Kernel { + const control: ?g.Gate = if (self.case.fault != .none) .shapes else null; + return .{ .spec = spec(self.case), .ctx = self, .vt = &vt, .control = control }; + } + + const vt = g.hooks(Route); + + /// The shared expert stacks as the last id, and every row's last pick. + fn stacked(self: *const Route) bool { + return self.case.mode != .apart; + } + + /// Distinct picks a row, half from six hot experts so some fill several 8-row items; gate 1: the id range's edges. + pub fn prepare(self: *Route, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + const hot = 6; + const routed = if (self.stacked()) shape.n -| 1 else shape.n; + const top = if (self.stacked()) shape.k -| 1 else shape.k; + // the launcher plans up to 1,024 experts; the plan's route starts at 2 rows (one row takes the select's) + if (shape.rows < 2 or shape.n > 1024 or top < 2 or top / 2 > hot or routed < top + hot) return false; + self.rig.reset(); + _ = self.arena.reset(.retain_capacity); + self.shape = shape; + const a = self.arena.allocator(); + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + self.picks = try a.alloc(i32, shape.rows * shape.k); + for (0..shape.rows) |r| { + const row = self.picks[r * shape.k ..][0..shape.k]; + for (row[0..top], 0..) |*e, j| { + if (fill == .nonfinite) { + e.* = @intCast(if (j < top / 2) j else routed - top + j); + continue; + } + const pool: usize = if (j < top / 2) hot else routed; + while (true) { + e.* = @intCast(rng.uintLessThan(usize, pool)); + if (std.mem.indexOfScalar(i32, row[0..j], e.*) == null) break; + } + } + if (self.stacked()) row[top] = @intCast(routed); + } + self.in = try self.rig.input(std.mem.sliceAsBytes(self.picks)); + // as serving sizes it: the bucket's pairs at the 8-row cut, an upper bound on any plan's items + self.capacity = moe.capacity(moe.bucket(shape.rows) * shape.k, shape.n); + self.members = try self.rig.output(self.picks.len * 4); + self.items = try self.rig.output(self.capacity * 12); + return true; + } + + pub fn run(self: *Route) !void { + const s = self.shape; + var tile, var shared_tile = asked(self.case.mode, s.rows); + switch (self.case.fault) { + .none => {}, + .shared_cut => shared_tile = tile, + .start_64 => tile = moe.tileOf(s.rows, false, true, 64), + } + try self.l.tf_moe_route( + @ptrFromInt(self.in), + @intCast(self.picks.len), + @intCast(s.n), + @intCast(tile), + if (self.stacked()) @intCast(s.n - 1) else -1, + @intCast(shared_tile), + @ptrFromInt(self.members), + @ptrFromInt(self.items), + @intCast(self.capacity), + self.rig.s.handle, + ); + try self.rig.s.synchronize(); + } + + pub fn count(self: *Route) usize { + return self.picks.len + 3 * self.capacity; + } + + pub fn reference(_: *Route, want: []f64, mag: []f64) !void { + @memset(want, 0); + @memset(mag, 0); + } + + fn say(self: *Route, comptime fmt: []const u8, args: anytype) !?[]const u8 { + return try std.fmt.bufPrint(&self.msg, fmt, args); + } + + /// Every member and every item's expert, first and count against the plan this contract states, then the rest. + pub fn check(self: *Route, _: g.Gate) !?[]const u8 { + const s = self.shape; + const members = try self.arena.allocator().dupe(u8, try self.rig.bytes(self.members, self.picks.len * 4)); + const items = try self.rig.bytes(self.items, self.capacity * 12); + const tile, const shared_tile = wanted(self.case.mode, s.rows); + var place: usize = 0; + var slot: usize = 0; + for (0..s.n) |e| { + const first = place; + for (self.picks, 0..) |p, pair| if (p == e) { + const got = word(members, place); + if (got != pair) return self.say("member {d} is pair {d}; expert {d}'s in pick order is {d}", .{ place, got, e, pair }); + place += 1; + }; + const cut = if (self.stacked() and e == s.n - 1) shared_tile else tile; + var at = first; + while (at < place) : (slot += 1) { + if (slot == self.capacity) return self.say("expert {d}'s items run past {d} slots", .{ e, self.capacity }); + const want = [3]usize{ e, at, @min(place - at, cut) }; + for (want, 0..) |v, f| { + const got = word(items, 3 * slot + f); + if (got != v) return self.say("item {d} field {d} is {d}, the plan's {d} (expert {d}, {d} pairs an item)", .{ slot, f, got, v, e, cut }); + } + at += want[2]; + } + } + for (slot..self.capacity) |x| { + const e = word(items, 3 * x); + const pairs = word(items, 3 * x + 2); + if (e != s.n - 1 or pairs != 0) return self.say("empty item {d} is expert {d} with {d} pairs, not the last with none", .{ x, e, pairs }); + } + return null; + } +};