diff --git a/CHANGELOG.md b/CHANGELOG.md index d5930a0e429..e43dd23b524 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 +- Metal contracts, Qwen3.5 CUDA drafts and Qwen27 lanes: four more busy 600-line sources split into their own files, leaving room under the cap; no call site changes (#5595). + - Inkling 2 Small EXL3 on Metal: the non-looped 48-layer forward, its Metal ops with kernel-contract gates and launch-limit records, and disk-pack loader and oracle tests; Inkling 2 Mini is unchanged (#5105). Thanks to @trozzelle. - Qwen3.8-27B on Metal: prompt-attention threadgroups whose keys all lie past the causal edge write empty partials and return before any barrier, and other chunks stop their key loop at that row's last 32-key tile, so a prompt pass stops reading keys every row masks out; partials, mixer bytes and outputs match the old kernels' (#2926). @@ -26,8 +28,6 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - Prompt cache: each finished request's done line names why its prompt resumed no further (`cache=` of 18, with `at= lost=`), and /metrics adds `tensorfold:prompt_cache_lookups_total{reason}` and `tensorfold:prompt_cache_lost_tokens_total{reason}`; opt-in `TF_CACHE_WHY=1` also adds `tensorfold.prompt_cache` to each reply, off by default because the reason is measured against every client's kept prompts, so it suits a single-user server. The paged radix store and DeepSeek-V4.1's session store follow in step 2 (#3703, for #3686). - - - Tests: `metal_limits.zig`'s family resolver arms move into `metal_family_limits.zig` to stay under the 600-line cap; every launch resolves as before (#5571). - Metal Qwen3.8-27B: `TF_METAL4=1` now also sends the Qwen3.8-27B decode round (target verify and DFlash2 draft) through Metal 4 command buffers and argument tables on macOS 26, with the same kernels in the same order (#4563). diff --git a/zig/src/families/qwen3_5/cuda_draft.zig b/zig/src/families/qwen3_5/cuda_draft.zig index 8de8f068fcf..f2ce7bcae5d 100644 --- a/zig/src/families/qwen3_5/cuda_draft.zig +++ b/zig/src/families/qwen3_5/cuda_draft.zig @@ -15,14 +15,12 @@ const E = engine.Engine; const DeviceBuffer = cuda.DeviceBuffer; const dr = lanes.drafter; const absorbs = @import("cuda_draft_absorb.zig"); +const support = @import("cuda_draft_support.zig"); const Stream = lanes.Stream; -/// Rows an absorb runs at once (the target's prompt chunks are at most this). -const max_rows = engine.most_verify; // taps absorbed at most this many rows a call (a prompt chunk's in pieces) -/// The logprob row's words (sample.cu's LP_WORDS) and its best-token capacity. -const lp_words = 3 + 2 * 20; -/// A hold's rows: the reference's 16-row blocks (dflash2.block), past the 8 the checkpoint was trained with. -const lp_top = 20; +const max_rows = support.max_rows; +const lp_words = support.lp_words; +const lp_top = support.lp_top; pub const Config = @import("cuda_draft_config.zig").Config; pub const frame = @import("cuda_draft_frame.zig"); @@ -34,27 +32,8 @@ const Fns = struct { gather_taps: cuda.Function, gather_rows: cuda.Function, dyn /// qwen35_draft.cu's TapRows. pub const TapRows = extern struct { n: c_int, rows: [engine.most_window]c_int }; -/// A stream's context: its layers' key and value rings over [begin, end), and the drafts it holds (a chain or tree). -pub const Ctx = struct { - ring: DeviceBuffer, - begin: u64 = 0, - end: u64 = 0, - held: [engine.most_window]u32 = undefined, - held_n: usize = 0, - // a grown tree's parents (-1: the pending token) and nodes' log-chances under them; 0 nodes: a chain - parents: [engine.most_window]i32 = undefined, - own: [engine.most_window]f64 = undefined, - grown: usize = 0, - trace_active: bool = false, - trace_base: usize = 0, - trace_snapshot: trace.Snapshot((engine.most_window + 1) * lanes.draft_tree.branch) = .{}, - // the stream's tokens draft_frame has read, and whether one lay outside its spans (then drafts take the whole head) - scanned: usize = 0, - wide: bool = false, -}; -pub fn fullHeadEnabled() bool { - return platform.environment.read(bool, "TF_QWEN_DRAFT_FULL_HEAD", true) catch true; -} +pub const Ctx = support.Ctx; +pub const fullHeadEnabled = support.fullHeadEnabled; pub const Draft = struct { gpa: std.mem.Allocator, io: std.Io, @@ -128,8 +107,8 @@ pub const Draft = struct { /// all: every stream is a pool lane (TF_QWEN_KV_PAGES_ALL), so the drafter keeps no ring of its own. pub const RingOf = struct { ctx: *anyopaque, ring: *const fn (*anyopaque, *Stream) ?u64, all: bool = false }; const words_at = frame.words_at; - const hp_at = frame.hp_at; - const stagedLen = frame.stagedLen; + pub const hp_at = frame.hp_at; + pub const stagedLen = frame.stagedLen; pub fn init(gpa: std.mem.Allocator, io: std.Io, e: *E, dir: []const u8) !*Draft { const nodes = try tree.nodes(); const started = profile.now(io); @@ -530,70 +509,11 @@ pub const Draft = struct { } }; -/// The dense 27B's copy match beside DSpine; DFlash2 keeps long_match (see the commit for the measurements). -pub const copy_match_beside_dspine = 12; - -/// The copy match beside a drafter: the dense 27B leaves short copies to its drafts, others keep the target's (0). -pub fn copyMatch(g: anytype, kind: Config.Kind) i64 { - if (!@import("cuda_geometry.zig").dense27(g)) return 0; - return switch (kind) { - .dflash2 => lanes.windows.long_match, - .dspine => copy_match_beside_dspine, - }; -} - -/// The copy match a loaded drafter reports in its facts: its target's geometry and its own kind. -pub fn factsCopyMatch(d: anytype) i64 { - return copyMatch(d.e.g, d.c.kind); -} - -/// TF_TIMING=1: each call's wall time on stderr. -pub fn timing(what: []const u8, io: std.Io, t0: std.Io.Timestamp) void { - if (!(platform.environment.read(bool, "TF_TIMING", false) catch false)) return; - const now = std.Io.Clock.awake.now(io); - const ns: f64 = @floatFromInt(t0.durationTo(now).toNanoseconds()); - const at: f64 = @floatFromInt(@mod(now.toNanoseconds(), 1_000_000_000_000)); - std.debug.print("[timing] {s} {d:.2} ms at {d:.1}\n", .{ what, ns / 1e6, at / 1e6 }); -} +pub const copy_match_beside_dspine = support.copy_match_beside_dspine; +pub const copyMatch = support.copyMatch; +pub const factsCopyMatch = support.factsCopyMatch; +pub const timing = support.timing; test { - _ = tree; - _ = @import("cuda_draft_copy_test.zig"); -} - -test "a drafter config with a zero divisor is refused, and any admitted rank's selector rows fit the staging area" { - const gpa = std.testing.allocator; - const target: engine.Geometry = .{ .hidden = 5120, .intermediate = 17408, .layers = 64, .vocab = 248320, .k_heads = 16, .v_heads = 48, .q_heads = 24, .kv_heads = 4, .eps = 1e-6, .tied = false, .context = 262144, .linear = @splat(false) }; - const text = - \\{"dflash_config":{"block_size":8,"conv_group_size":16,"conv_kernel_size":2,"mask_token_id":248070,"selector_rank":256, - \\ "selector_top_k":16,"target_layer_ids":[5,19,33,47,61]},"head_dim":128,"hidden_size":5120,"intermediate_size":17408, - \\ "num_attention_heads":32,"num_hidden_layers":5,"num_key_value_heads":8,"rms_norm_eps":1e-06, - \\ "rope_parameters":{"rope_theta":10000000},"sliding_window":2048,"vocab_size":248320,"use_sliding_window":true, - \\ "layer_types":["sliding_attention","sliding_attention","sliding_attention","sliding_attention","sliding_attention"]} - ; - try std.testing.expectEqual(@as(usize, 256), (try Config.parse(gpa, text, target)).rank); - for ([_][2][]const u8{ .{ "\"conv_group_size\":16", "\"conv_group_size\":0" }, .{ "\"num_key_value_heads\":8", "\"num_key_value_heads\":0" } }) |r| { - const bad = try std.mem.replaceOwned(u8, gpa, text, r[0], r[1]); - defer gpa.free(bad); - try std.testing.expectError(error.BadDraftConfig, Config.parse(gpa, bad, target)); - } - // the kernels rope with theta alone: a scaled rope is refused, an explicit default one is read - for ([_][2][]const u8{ .{ "{\"rope_theta\"", "{\"rope_type\":\"yarn\",\"factor\":4.0,\"rope_theta\"" }, .{ "{\"rope_theta\"", "{\"type\":\"yarn\",\"rope_theta\"" }, .{ "\"sliding_window\"", "\"rope_scaling\":{\"type\":\"yarn\"},\"sliding_window\"" } }) |r| { - const scaled = try std.mem.replaceOwned(u8, gpa, text, r[0], r[1]); - defer gpa.free(scaled); - try std.testing.expectError(error.UnsupportedDraftConfig, Config.parse(gpa, scaled, target)); - } - const plain = try std.mem.replaceOwned(u8, gpa, text, "{\"rope_theta\"", "{\"rope_type\":\"default\",\"rope_theta\""); - defer gpa.free(plain); - try std.testing.expectEqual(@as(usize, 256), (try Config.parse(gpa, plain, target)).rank); - const wide = try std.mem.replaceOwned(u8, gpa, text, "\"selector_rank\":256", "\"selector_rank\":1024"); - defer gpa.free(wide); - const c = try Config.parse(gpa, wide, target); - try std.testing.expect(Draft.stagedLen(c.rank) >= Draft.hp_at + (c.block - 1) * c.rank * 2); -} - -test "TF_TIMING: the platform parses unset, valid and malformed text" { - try std.testing.expectEqual(@as(?u64, null), try platform.environment.parse("TF_TIMING", null)); - try std.testing.expectEqual(@as(?u64, 1), try platform.environment.parse("TF_TIMING", "1")); - try std.testing.expectError(error.InvalidEnvironment, platform.environment.parse("TF_TIMING", "on")); + _ = @import("cuda_draft_support.zig"); } diff --git a/zig/src/families/qwen3_5/cuda_draft_support.zig b/zig/src/families/qwen3_5/cuda_draft_support.zig new file mode 100644 index 00000000000..c2239e0d6fa --- /dev/null +++ b/zig/src/families/qwen3_5/cuda_draft_support.zig @@ -0,0 +1,108 @@ +//! Stream context, sizing constants and shared helpers for the CUDA drafter. +const std = @import("std"); +const platform = @import("sys"); +const cuda = @import("cuda"); +const lanes = @import("lanes"); +const engine = @import("cuda_engine.zig"); +const DeviceBuffer = cuda.DeviceBuffer; +const trace = @import("cuda_draft_trace.zig"); +const Config = @import("cuda_draft_config.zig").Config; +const Draft = @import("cuda_draft.zig").Draft; +const tree = @import("cuda_draft_tree.zig"); + +/// Rows an absorb runs at once (the target's prompt chunks are at most this). +pub const max_rows = engine.most_verify; // taps absorbed at most this many rows a call (a prompt chunk's in pieces) +/// The logprob row's words (sample.cu's LP_WORDS) and its best-token capacity. +pub const lp_words = 3 + 2 * 20; +/// A hold's rows: the reference's 16-row blocks (dflash2.block), past the 8 the checkpoint was trained with. +pub const lp_top = 20; + +/// A stream's context: its layers' key and value rings over [begin, end), and the drafts it holds (a chain or tree). +pub const Ctx = struct { + ring: DeviceBuffer, + begin: u64 = 0, + end: u64 = 0, + held: [engine.most_window]u32 = undefined, + held_n: usize = 0, + // a grown tree's parents (-1: the pending token) and nodes' log-chances under them; 0 nodes: a chain + parents: [engine.most_window]i32 = undefined, + own: [engine.most_window]f64 = undefined, + grown: usize = 0, + trace_active: bool = false, + trace_base: usize = 0, + trace_snapshot: trace.Snapshot((engine.most_window + 1) * lanes.draft_tree.branch) = .{}, + // the stream's tokens draft_frame has read, and whether one lay outside its spans (then drafts take the whole head) + scanned: usize = 0, + wide: bool = false, +}; +pub fn fullHeadEnabled() bool { + return platform.environment.read(bool, "TF_QWEN_DRAFT_FULL_HEAD", true) catch true; +} + +/// The dense 27B's copy match beside DSpine; DFlash2 keeps long_match (see the commit for the measurements). +pub const copy_match_beside_dspine = 12; + +/// The copy match beside a drafter: the dense 27B leaves short copies to its drafts, others keep the target's (0). +pub fn copyMatch(g: anytype, kind: Config.Kind) i64 { + if (!@import("cuda_geometry.zig").dense27(g)) return 0; + return switch (kind) { + .dflash2 => lanes.windows.long_match, + .dspine => copy_match_beside_dspine, + }; +} + +/// The copy match a loaded drafter reports in its facts: its target's geometry and its own kind. +pub fn factsCopyMatch(d: anytype) i64 { + return copyMatch(d.e.g, d.c.kind); +} + +/// TF_TIMING=1: each call's wall time on stderr. +pub fn timing(what: []const u8, io: std.Io, t0: std.Io.Timestamp) void { + if (!(platform.environment.read(bool, "TF_TIMING", false) catch false)) return; + const now = std.Io.Clock.awake.now(io); + const ns: f64 = @floatFromInt(t0.durationTo(now).toNanoseconds()); + const at: f64 = @floatFromInt(@mod(now.toNanoseconds(), 1_000_000_000_000)); + std.debug.print("[timing] {s} {d:.2} ms at {d:.1}\n", .{ what, ns / 1e6, at / 1e6 }); +} + +test { + _ = tree; + _ = @import("cuda_draft_copy_test.zig"); +} + +test "a drafter config with a zero divisor is refused, and any admitted rank's selector rows fit the staging area" { + const gpa = std.testing.allocator; + const target: engine.Geometry = .{ .hidden = 5120, .intermediate = 17408, .layers = 64, .vocab = 248320, .k_heads = 16, .v_heads = 48, .q_heads = 24, .kv_heads = 4, .eps = 1e-6, .tied = false, .context = 262144, .linear = @splat(false) }; + const text = + \\{"dflash_config":{"block_size":8,"conv_group_size":16,"conv_kernel_size":2,"mask_token_id":248070,"selector_rank":256, + \\ "selector_top_k":16,"target_layer_ids":[5,19,33,47,61]},"head_dim":128,"hidden_size":5120,"intermediate_size":17408, + \\ "num_attention_heads":32,"num_hidden_layers":5,"num_key_value_heads":8,"rms_norm_eps":1e-06, + \\ "rope_parameters":{"rope_theta":10000000},"sliding_window":2048,"vocab_size":248320,"use_sliding_window":true, + \\ "layer_types":["sliding_attention","sliding_attention","sliding_attention","sliding_attention","sliding_attention"]} + ; + try std.testing.expectEqual(@as(usize, 256), (try Config.parse(gpa, text, target)).rank); + for ([_][2][]const u8{ .{ "\"conv_group_size\":16", "\"conv_group_size\":0" }, .{ "\"num_key_value_heads\":8", "\"num_key_value_heads\":0" } }) |r| { + const bad = try std.mem.replaceOwned(u8, gpa, text, r[0], r[1]); + defer gpa.free(bad); + try std.testing.expectError(error.BadDraftConfig, Config.parse(gpa, bad, target)); + } + // the kernels rope with theta alone: a scaled rope is refused, an explicit default one is read + for ([_][2][]const u8{ .{ "{\"rope_theta\"", "{\"rope_type\":\"yarn\",\"factor\":4.0,\"rope_theta\"" }, .{ "{\"rope_theta\"", "{\"type\":\"yarn\",\"rope_theta\"" }, .{ "\"sliding_window\"", "\"rope_scaling\":{\"type\":\"yarn\"},\"sliding_window\"" } }) |r| { + const scaled = try std.mem.replaceOwned(u8, gpa, text, r[0], r[1]); + defer gpa.free(scaled); + try std.testing.expectError(error.UnsupportedDraftConfig, Config.parse(gpa, scaled, target)); + } + const plain = try std.mem.replaceOwned(u8, gpa, text, "{\"rope_theta\"", "{\"rope_type\":\"default\",\"rope_theta\""); + defer gpa.free(plain); + try std.testing.expectEqual(@as(usize, 256), (try Config.parse(gpa, plain, target)).rank); + const wide = try std.mem.replaceOwned(u8, gpa, text, "\"selector_rank\":256", "\"selector_rank\":1024"); + defer gpa.free(wide); + const c = try Config.parse(gpa, wide, target); + try std.testing.expect(Draft.stagedLen(c.rank) >= Draft.hp_at + (c.block - 1) * c.rank * 2); +} + +test "TF_TIMING: the platform parses unset, valid and malformed text" { + try std.testing.expectEqual(@as(?u64, null), try platform.environment.parse("TF_TIMING", null)); + try std.testing.expectEqual(@as(?u64, 1), try platform.environment.parse("TF_TIMING", "1")); + try std.testing.expectError(error.InvalidEnvironment, platform.environment.parse("TF_TIMING", "on")); +} diff --git a/zig/src/native/qwen27_lane_backend.zig b/zig/src/native/qwen27_lane_backend.zig new file mode 100644 index 00000000000..7c7c9f2c809 --- /dev/null +++ b/zig/src/native/qwen27_lane_backend.zig @@ -0,0 +1,219 @@ +//! The 27B lane backend's stream vtable and held-tree handling. +const std = @import("std"); +const mtl = @import("metal"); +const tf = @import("tensorfold"); +const q = tf.qwen27; +const lanes = tf.lanes; +const be = lanes.backend; +const lb = @import("qwen27_lanes.zig"); +const Metal = lb.Metal; +const self = Metal.self; +const slots = @import("qwen27_slots.zig"); +const Round = q.round_plan.Round; +const Tree = q.dflash.selector.Tree; +const max_streams = lb.max_streams; +const batch_rows = lb.batch_rows; +const max_rows = lb.max_rows; + +fn encodeArgmaxTail(ptr: *anyopaque, e: mtl.ComputeEncoder) anyerror!void { + try self(ptr).encodeArgmaxRange(e, 0, self(ptr).rows); +} + +// -- the vtable --------------------------------------------------------------------------------------------- + +pub fn prefillFn(ptr: *anyopaque, s: *lanes.Stream) anyerror!void { + const b = self(ptr); + b.settle() catch {}; + b.dropRound(); + slots.promoteDue(b); + const slot = try slots.bind(b, s); + errdefer b.owners[slot] = null; + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + try b.prefillSlot(s, slot); +} + +pub fn firstFn(ptr: *anyopaque, s: *lanes.Stream, position: u64) anyerror!u64 { + const b = self(ptr); + _ = try b.slotFor(s); + var token: [1]u32 = undefined; + try b.draw(s, 0, 1, &.{position}, &token, &.{}, false); // a reply's first token: no count yet + return b.push(token[0]); +} + +pub fn firstMaskedFn(ptr: *anyopaque, s: *lanes.Stream, position: u64, mask: []const u32) anyerror!u64 { + const b = self(ptr); + _ = try b.slotFor(s); + var token: [1]u32 = undefined; + try b.draw(s, 0, 1, &.{position}, &token, mask, false); + return b.push(token[0]); +} + +pub fn queueFn(ptr: *anyopaque, s: *lanes.Stream, feed: be.Feed, position: u64) anyerror!u64 { + const b = self(ptr); + try b.settle(); + slots.promoteDue(b); + const slot = try b.slotFor(s); + const token = try b.value(feed); + const before = b.runner.gpu_seconds; + if (b.drafter(slot)) |d| try d.advance(token) else { + try (q.session.Session{ .runner = b.runner, .slot = slot }).step(token); + if (b.ringOf(slot)) |g| try b.ringChunk(g, 1); + } + slots.charge(b, s, before); + var next: [1]u32 = undefined; + b.pens.clear(); + try b.pens.stageOne(b.gpa, s, @intCast(position - 1), token, 0); // the reply before the fed token, then it + try b.draw(s, 0, 1, &.{position}, &next, &.{}, b.pens.len() > 0); + return b.push(next[0]); +} + +pub fn readFn(ptr: *anyopaque, handle: u64) anyerror!u32 { + return self(ptr).value(.{ .handle = handle }); +} + +/// Every stream's window (pending token, then its drafts as a chain or tree) in one forward, every row drawn. +pub fn verifyFn(ptr: *anyopaque, windows: []const be.Window, out: []be.Verified) anyerror!void { + const b = self(ptr); + if (windows.len == 0 or windows.len > b.runner.slots or windows.len != out.len) return error.BadWindows; + try b.settle(); + slots.promoteDue(b); + const r = b.runner; + var inputs: [max_streams]q.round_plan.Input = undefined; + var total: usize = 0; + b.from_tree = 0; + var plain = b.draft == null; // every window one undrafted row: the verify keeps it, as a prompt's rows are + for (windows, 0..) |w, i| { + if (w.rows() != 1 or w.held != 0) plain = false; + const slot = try b.slotFor(w.stream); + if (w.held > 0 and w.tokens.len > 0) return error.HeldAndHostDrafts; + if (w.held > 0 and !b.draftsOwn(slot)) return error.HeldWithoutDrafter; + const rows = w.rows(); + const words = (r.model.config.vocab + 31) / 32; + if (w.masks.len != 0 and w.masks.len != rows * words) return error.InvalidQwenMasks; + if (rows > b.window or total + rows > batch_rows) return error.WindowTooWide; + const ids = b.ids[total..][0..rows]; + ids[0] = w.pending; + if (w.held > 0) b.heldChain(slot, ids[1..], w.pending) else @memcpy(ids[1..], w.tokens); + if (slot == 0 and windows.len == 1) b.from_tree = b.treeRows(w); + const parents = b.parents[total..][0..rows]; + if (w.parents) |p| @memcpy(parents, p) else for (parents, 0..) |*p, row| { + p.* = @as(i32, @intCast(row)) - 1; + } + inputs[i] = .{ .slot = slot, .start = r.offsets[slot], .capacity = r.capacity, .ids = ids, .parents = parents }; + b.windows[i] = slot; + b.widths[i] = @intCast(rows); + total += rows; + } + // every tree held is spent by this round, alone or shared + if (windows.len > 1) b.dropTree(); + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + b.round = try Round.init(b.gpa, inputs[0..windows.len], @intCast(r.model.config.conv_kernel), r.slots, @intCast(r.model.config.vocab)); + b.count = windows.len; + errdefer b.dropRound(); + b.rows = total; + if (b.pass_profile and windows.len == 1) std.log.info("q27_offer width={d} rows={d} tree_nodes={d} copy_rows={d}", .{ b.window, total, b.from_tree, total - 1 - b.from_tree }); + b.pens.clear(); // each penalized window's rows: the reply, its pending token, then the row's own path + for (windows, b.round.?.firsts) |w, first| try b.pens.stageWindow(b.gpa, w, b.ids[first + 1 ..][0 .. w.rows() - 1], first); + const fused = windows.len == 1 and b.windows[0] == 0 and b.draft != null and total > 1 and windows[0].stream.sampling == null and windows[0].masks.len == 0 and b.pens.len() == 0; + // every greedy window's rows from one argmax over the round; a sampled window draws on the host + var greedy = false; + for (windows) |w| greedy = greedy or (w.stream.sampling == null and w.masks.len == 0 and !w.stream.penalties.active()); + const tail_argmax = r.model.config.looped and !fused and greedy and r.reduce == null; + std.debug.assert(r.tail == null); + if (fused) r.tail = .{ .ptr = b, .encode = @import("qwen27_keep.zig").encodeTail } else if (tail_argmax) r.tail = .{ .ptr = b, .encode = encodeArgmaxTail }; + defer r.tail = null; + if (b.phase_trace) |t| @import("qwen27_phase_trace.zig").begin(t, windows, r.owned.items.len); + var trace_complete = false; + defer if (b.phase_trace) |t| t.end(trace_complete); + if (b.phase_trace) |t| t.kind = .target; + const before = r.gpu_seconds; + if (plain) try r.advance(&b.round.?, .all) else try r.verifyHead(&b.round.?, .all); + if (b.phase_trace) |t| t.kind = .other; + try @import("sensenova_features.zig").recordVerify(b, windows, inputs[0..windows.len]); + for (windows) |w| slots.charge(b, w.stream, before); // a shared round counts whole in each reply + b.advanced = plain; + b.rows = total; + if (fused) try @import("qwen27_keep.zig").finishPrefetch(b) else if (greedy and !tail_argmax) try b.argmaxRows(0, total); + for (windows, out, b.round.?.firsts) |w, o, first| { + const rows = w.rows(); + const pens = w.stream.penalties.active(); + if (w.stream.sampling != null or w.masks.len > 0 or pens) try b.draw(w.stream, first, rows, w.positions, o.sampled, w.masks, pens) else try b.picked(first, rows, o.sampled); + @memcpy(o.drafts, b.ids[first + 1 ..][0 .. rows - 1]); + } + trace_complete = true; + if (windows.len == 1) @memcpy(b.sampled[0..b.rows], out[0].sampled); +} + +/// How many drafts are the held tree's first nodes with their own parents (0: copies, fills or a chain). +pub fn treeRows(b: *const Metal, w: be.Window) usize { + const t = b.trees[0] orelse return 0; + if (w.held > 0) return 0; + const n = @min(w.tokens.len, t.tokens.len); + var prefix: usize = 0; + for (w.tokens[0..n], t.tokens[0..n], 0..) |token, draft, i| { + const parent = if (w.parents) |ps| ps[i + 1] - 1 else @as(i32, @intCast(i)) - 1; + if (token != draft or parent != t.parents[i]) break; + prefix += 1; + } + return prefix; +} + +fn isChain(parents: []const i32) bool { + for (parents, 0..) |p, i| if (p != @as(i32, @intCast(i)) - 1) return false; + return true; +} + +/// A node's own log-probability under the drafter (its path score less its parent's). +pub fn local(t: Tree, i: usize) f64 { + const parent = t.parents[i]; + return t.scores[i] - (if (parent >= 0) t.scores[@intCast(parent)] else 0); +} + +/// Count every proposed node whose parent row was kept, and those the target drew, by own log-probability. +pub fn observe(b: *Metal, path: []const u32) void { + const t = b.trees[0] orelse return; + if (b.from_tree == 0) return; + const stream = b.owners[0] orelse return; + if (!stream.shared_round) b.draft_block.observe(@intFromPtr(stream), @import("qwen27_draft_block.zig").landed(path, b.from_tree)); + var kept: [max_rows]bool = @splat(false); + for (path) |r| kept[r] = true; + for (t.tokens, t.parents, 0..) |token, parent, i| { + const parent_row: usize = @intCast(parent + 1); + if (parent_row > b.from_tree or !kept[parent_row]) continue; + b.landing.observeFor(stream.shared_round, stream.sampling != null, local(t, i), token == b.sampled[parent_row]); + } +} + +/// Held drafts the core reads as a chain (a first round): the tree's first-child path, last token repeated. +pub fn heldChain(b: *const Metal, slot: u32, out: []u32, pending: u32) void { + var n: usize = 0; + if (b.trees[slot]) |t| { + var parent: i32 = -1; + for (t.tokens, t.parents, 0..) |token, p, i| { + if (n == out.len) break; + if (p != parent) continue; + out[n] = token; + n += 1; + parent = @intCast(i); + } + } + const fill = if (n > 0) out[n - 1] else pending; + for (out[n..]) |*x| x.* = fill; +} + +pub fn keepFn(ptr: *anyopaque, windows: []const be.Window, paths: []const []const u32) anyerror!void { + const b = self(ptr); + if (b.round == null or windows.len != b.count) return error.NothingToKeep; + for (windows, paths, b.windows[0..b.count]) |w, path, slot| if (path.len == 0 or path[0] != 0 or b.slotOf(w.stream) != slot) return error.NothingToKeep; + try b.keepPaths(paths); + @import("sensenova_features.zig").recordKeep(b, windows, paths); +} + +pub fn releaseFn(ptr: *anyopaque, s: *lanes.Stream) void { + const b = self(ptr); + if (b.slotOf(s)) |slot| b.features_state.clearSlot(slot); + slots.endFill(b, s); + b.unbind(s); +} diff --git a/zig/src/native/qwen27_lanes.zig b/zig/src/native/qwen27_lanes.zig index c3b648065ee..35842bf6e10 100644 --- a/zig/src/native/qwen27_lanes.zig +++ b/zig/src/native/qwen27_lanes.zig @@ -11,6 +11,7 @@ pub const Draft = @import("qwen27_draft.zig").Draft; const slots = @import("qwen27_slots.zig"); const draft_fns = @import("qwen27_drafts.zig"); const features = @import("qwen27_features.zig"); +const backend_fns = @import("qwen27_lane_backend.zig"); const Round = q.round_plan.Round; const Tree = q.dflash.selector.Tree; const Ring = q.tap_ring.Ring; @@ -164,10 +165,10 @@ pub const Metal = struct { b.gpa.destroy(b); } pub const lone = slots.lone; - const prefillSlot = slots.prefill; + pub const prefillSlot = slots.prefill; const freeSlot = slots.free; - const ringChunk = slots.ringChunk; - const unbind = slots.unbind; + pub const ringChunk = slots.ringChunk; + pub const unbind = slots.unbind; const ready = slots.ready; pub const refill = slots.refill; pub fn backend(b: *Metal) be.Backend { @@ -217,7 +218,7 @@ pub const Metal = struct { pub fn slotFor(b: *const Metal, s: *const lanes.Stream) !u32 { return b.slotOf(s) orelse error.UnknownStream; } - fn push(b: *Metal, token: u32) u64 { + pub fn push(b: *Metal, token: u32) u64 { b.drawn[b.next % ring] = token; b.next += 1; return b.next - 1; @@ -255,7 +256,7 @@ pub const Metal = struct { } /// Rows [first, first + rows) drawn at their positions: GPU argmax, else on the host (sampled, masked or `pens`). - fn draw(b: *Metal, s: *const lanes.Stream, first: usize, rows: usize, positions: []const u64, out: []u32, masks: []const u32, pens: bool) !void { + pub fn draw(b: *Metal, s: *const lanes.Stream, first: usize, rows: usize, positions: []const u64, out: []u32, masks: []const u32, pens: bool) !void { const logits = b.runner.model.frame.get(.logits); const vocab: u32 = @intCast(b.runner.model.config.vocab); const width = (@as(usize, vocab) + 31) / 32; @@ -276,7 +277,7 @@ pub const Metal = struct { pens.applyRow(row, logits); } - fn encodeArgmaxRange(b: *const Metal, e: mtl.ComputeEncoder, first: usize, rows: usize) !void { + pub fn encodeArgmaxRange(b: *const Metal, e: mtl.ComputeEncoder, first: usize, rows: usize) !void { const logits = b.runner.model.frame.get(.logits); const vocab: u32 = @intCast(b.runner.model.config.vocab); var at = first; @@ -286,12 +287,8 @@ pub const Metal = struct { } } - fn encodeArgmaxTail(ptr: *anyopaque, e: mtl.ComputeEncoder) anyerror!void { - try self(ptr).encodeArgmaxRange(e, 0, self(ptr).rows); - } - /// Rows [first, first + rows)'s greedy picks into `picks` at the same rows: one command buffer and one wait. - fn argmaxRows(b: *Metal, first: usize, rows: usize) !void { + pub fn argmaxRows(b: *Metal, first: usize, rows: usize) !void { if (b.phase_trace) |t| t.kind = .argmax; defer if (b.phase_trace) |t| { t.kind = .other; @@ -310,7 +307,7 @@ pub const Metal = struct { } /// The tokens argmaxRows picked for rows [first, first + rows). - fn picked(b: *const Metal, first: usize, rows: usize, out: []u32) !void { + pub fn picked(b: *const Metal, first: usize, rows: usize, out: []u32) !void { const picks: [*]const contract.Pick = @ptrCast(@alignCast(b.picks.contents())); for (out[0..rows], picks[first..][0..rows]) |*t, p| { if (p.token == contract.invalid_token or p.nonfinite != 0) return error.NonfiniteLogits; @@ -319,7 +316,7 @@ pub const Metal = struct { } /// Keep the last verify's rows on `paths`: slot 0 alone keeps on the GPU with its taps, else the runner and rings. - fn keepPaths(b: *Metal, paths: []const []const u32) !void { + pub fn keepPaths(b: *Metal, paths: []const []const u32) !void { defer mtl.pass_metrics.end(); const metric = mtl.pass_metrics.phase(.keep); defer metric.end(); @@ -398,202 +395,18 @@ pub const Metal = struct { // -- the vtable --------------------------------------------------------------------------------------------- - fn prefillFn(ptr: *anyopaque, s: *lanes.Stream) anyerror!void { - const b = self(ptr); - b.settle() catch {}; - b.dropRound(); - slots.promoteDue(b); - const slot = try slots.bind(b, s); - errdefer b.owners[slot] = null; - const pool = mtl.objc.Pool.push(); - defer pool.pop(); - try b.prefillSlot(s, slot); - } - - fn firstFn(ptr: *anyopaque, s: *lanes.Stream, position: u64) anyerror!u64 { - const b = self(ptr); - _ = try b.slotFor(s); - var token: [1]u32 = undefined; - try b.draw(s, 0, 1, &.{position}, &token, &.{}, false); // a reply's first token: no count yet - return b.push(token[0]); - } - - fn firstMaskedFn(ptr: *anyopaque, s: *lanes.Stream, position: u64, mask: []const u32) anyerror!u64 { - const b = self(ptr); - _ = try b.slotFor(s); - var token: [1]u32 = undefined; - try b.draw(s, 0, 1, &.{position}, &token, mask, false); - return b.push(token[0]); - } - - fn queueFn(ptr: *anyopaque, s: *lanes.Stream, feed: be.Feed, position: u64) anyerror!u64 { - const b = self(ptr); - try b.settle(); - slots.promoteDue(b); - const slot = try b.slotFor(s); - const token = try b.value(feed); - const before = b.runner.gpu_seconds; - if (b.drafter(slot)) |d| try d.advance(token) else { - try (q.session.Session{ .runner = b.runner, .slot = slot }).step(token); - if (b.ringOf(slot)) |g| try b.ringChunk(g, 1); - } - slots.charge(b, s, before); - var next: [1]u32 = undefined; - b.pens.clear(); - try b.pens.stageOne(b.gpa, s, @intCast(position - 1), token, 0); // the reply before the fed token, then it - try b.draw(s, 0, 1, &.{position}, &next, &.{}, b.pens.len() > 0); - return b.push(next[0]); - } - - fn readFn(ptr: *anyopaque, handle: u64) anyerror!u32 { - return self(ptr).value(.{ .handle = handle }); - } - - /// Every stream's window (pending token, then its drafts as a chain or tree) in one forward, every row drawn. - fn verifyFn(ptr: *anyopaque, windows: []const be.Window, out: []be.Verified) anyerror!void { - const b = self(ptr); - if (windows.len == 0 or windows.len > b.runner.slots or windows.len != out.len) return error.BadWindows; - try b.settle(); - slots.promoteDue(b); - const r = b.runner; - var inputs: [max_streams]q.round_plan.Input = undefined; - var total: usize = 0; - b.from_tree = 0; - var plain = b.draft == null; // every window one undrafted row: the verify keeps it, as a prompt's rows are - for (windows, 0..) |w, i| { - if (w.rows() != 1 or w.held != 0) plain = false; - const slot = try b.slotFor(w.stream); - if (w.held > 0 and w.tokens.len > 0) return error.HeldAndHostDrafts; - if (w.held > 0 and !b.draftsOwn(slot)) return error.HeldWithoutDrafter; - const rows = w.rows(); - const words = (r.model.config.vocab + 31) / 32; - if (w.masks.len != 0 and w.masks.len != rows * words) return error.InvalidQwenMasks; - if (rows > b.window or total + rows > batch_rows) return error.WindowTooWide; - const ids = b.ids[total..][0..rows]; - ids[0] = w.pending; - if (w.held > 0) b.heldChain(slot, ids[1..], w.pending) else @memcpy(ids[1..], w.tokens); - if (slot == 0 and windows.len == 1) b.from_tree = b.treeRows(w); - const parents = b.parents[total..][0..rows]; - if (w.parents) |p| @memcpy(parents, p) else for (parents, 0..) |*p, row| { - p.* = @as(i32, @intCast(row)) - 1; - } - inputs[i] = .{ .slot = slot, .start = r.offsets[slot], .capacity = r.capacity, .ids = ids, .parents = parents }; - b.windows[i] = slot; - b.widths[i] = @intCast(rows); - total += rows; - } - // every tree held is spent by this round, alone or shared - if (windows.len > 1) b.dropTree(); - const pool = mtl.objc.Pool.push(); - defer pool.pop(); - b.round = try Round.init(b.gpa, inputs[0..windows.len], @intCast(r.model.config.conv_kernel), r.slots, @intCast(r.model.config.vocab)); - b.count = windows.len; - errdefer b.dropRound(); - b.rows = total; - if (b.pass_profile and windows.len == 1) std.log.info("q27_offer width={d} rows={d} tree_nodes={d} copy_rows={d}", .{ b.window, total, b.from_tree, total - 1 - b.from_tree }); - b.pens.clear(); // each penalized window's rows: the reply, its pending token, then the row's own path - for (windows, b.round.?.firsts) |w, first| try b.pens.stageWindow(b.gpa, w, b.ids[first + 1 ..][0 .. w.rows() - 1], first); - const fused = windows.len == 1 and b.windows[0] == 0 and b.draft != null and total > 1 and windows[0].stream.sampling == null and windows[0].masks.len == 0 and b.pens.len() == 0; - // every greedy window's rows from one argmax over the round; a sampled window draws on the host - var greedy = false; - for (windows) |w| greedy = greedy or (w.stream.sampling == null and w.masks.len == 0 and !w.stream.penalties.active()); - const tail_argmax = r.model.config.looped and !fused and greedy and r.reduce == null; - std.debug.assert(r.tail == null); - if (fused) r.tail = .{ .ptr = b, .encode = @import("qwen27_keep.zig").encodeTail } else if (tail_argmax) r.tail = .{ .ptr = b, .encode = encodeArgmaxTail }; - defer r.tail = null; - if (b.phase_trace) |t| @import("qwen27_phase_trace.zig").begin(t, windows, r.owned.items.len); - var trace_complete = false; - defer if (b.phase_trace) |t| t.end(trace_complete); - if (b.phase_trace) |t| t.kind = .target; - const before = r.gpu_seconds; - if (plain) try r.advance(&b.round.?, .all) else try r.verifyHead(&b.round.?, .all); - if (b.phase_trace) |t| t.kind = .other; - try @import("sensenova_features.zig").recordVerify(b, windows, inputs[0..windows.len]); - for (windows) |w| slots.charge(b, w.stream, before); // a shared round counts whole in each reply - b.advanced = plain; - b.rows = total; - if (fused) try @import("qwen27_keep.zig").finishPrefetch(b) else if (greedy and !tail_argmax) try b.argmaxRows(0, total); - for (windows, out, b.round.?.firsts) |w, o, first| { - const rows = w.rows(); - const pens = w.stream.penalties.active(); - if (w.stream.sampling != null or w.masks.len > 0 or pens) try b.draw(w.stream, first, rows, w.positions, o.sampled, w.masks, pens) else try b.picked(first, rows, o.sampled); - @memcpy(o.drafts, b.ids[first + 1 ..][0 .. rows - 1]); - } - trace_complete = true; - if (windows.len == 1) @memcpy(b.sampled[0..b.rows], out[0].sampled); - } - - /// How many drafts are the held tree's first nodes with their own parents (0: copies, fills or a chain). - pub fn treeRows(b: *const Metal, w: be.Window) usize { - const t = b.trees[0] orelse return 0; - if (w.held > 0) return 0; - const n = @min(w.tokens.len, t.tokens.len); - var prefix: usize = 0; - for (w.tokens[0..n], t.tokens[0..n], 0..) |token, draft, i| { - const parent = if (w.parents) |ps| ps[i + 1] - 1 else @as(i32, @intCast(i)) - 1; - if (token != draft or parent != t.parents[i]) break; - prefix += 1; - } - return prefix; - } - - fn isChain(parents: []const i32) bool { - for (parents, 0..) |p, i| if (p != @as(i32, @intCast(i)) - 1) return false; - return true; - } - - /// A node's own log-probability under the drafter (its path score less its parent's). - pub fn local(t: Tree, i: usize) f64 { - const parent = t.parents[i]; - return t.scores[i] - (if (parent >= 0) t.scores[@intCast(parent)] else 0); - } - - /// Count every proposed node whose parent row was kept, and those the target drew, by own log-probability. - fn observe(b: *Metal, path: []const u32) void { - const t = b.trees[0] orelse return; - if (b.from_tree == 0) return; - const stream = b.owners[0] orelse return; - if (!stream.shared_round) b.draft_block.observe(@intFromPtr(stream), @import("qwen27_draft_block.zig").landed(path, b.from_tree)); - var kept: [max_rows]bool = @splat(false); - for (path) |r| kept[r] = true; - for (t.tokens, t.parents, 0..) |token, parent, i| { - const parent_row: usize = @intCast(parent + 1); - if (parent_row > b.from_tree or !kept[parent_row]) continue; - b.landing.observeFor(stream.shared_round, stream.sampling != null, local(t, i), token == b.sampled[parent_row]); - } - } - - /// Held drafts the core reads as a chain (a first round): the tree's first-child path, last token repeated. - fn heldChain(b: *const Metal, slot: u32, out: []u32, pending: u32) void { - var n: usize = 0; - if (b.trees[slot]) |t| { - var parent: i32 = -1; - for (t.tokens, t.parents, 0..) |token, p, i| { - if (n == out.len) break; - if (p != parent) continue; - out[n] = token; - n += 1; - parent = @intCast(i); - } - } - const fill = if (n > 0) out[n - 1] else pending; - for (out[n..]) |*x| x.* = fill; - } - - fn keepFn(ptr: *anyopaque, windows: []const be.Window, paths: []const []const u32) anyerror!void { - const b = self(ptr); - if (b.round == null or windows.len != b.count) return error.NothingToKeep; - for (windows, paths, b.windows[0..b.count]) |w, path, slot| if (path.len == 0 or path[0] != 0 or b.slotOf(w.stream) != slot) return error.NothingToKeep; - try b.keepPaths(paths); - @import("sensenova_features.zig").recordKeep(b, windows, paths); - } - - fn releaseFn(ptr: *anyopaque, s: *lanes.Stream) void { - const b = self(ptr); - if (b.slotOf(s)) |slot| b.features_state.clearSlot(slot); - slots.endFill(b, s); - b.unbind(s); - } + const prefillFn = backend_fns.prefillFn; + const firstFn = backend_fns.firstFn; + const firstMaskedFn = backend_fns.firstMaskedFn; + const queueFn = backend_fns.queueFn; + const readFn = backend_fns.readFn; + const verifyFn = backend_fns.verifyFn; + pub const treeRows = backend_fns.treeRows; + pub const local = backend_fns.local; + const observe = backend_fns.observe; + pub const heldChain = backend_fns.heldChain; + const keepFn = backend_fns.keepFn; + const releaseFn = backend_fns.releaseFn; }; /// Streams that draft their own trees in shared rounds, while no more are live (TF_Q27_DRAFT_SLOTS; 1: slot 0 alone). diff --git a/zig/tests/contract/metal_family_limits.zig b/zig/tests/contract/metal_family_limits.zig index 2dbe5a84bab..0f582ab7e2c 100644 --- a/zig/tests/contract/metal_family_limits.zig +++ b/zig/tests/contract/metal_family_limits.zig @@ -4,10 +4,10 @@ const mtl = @import("metal"); const tf = @import("tensorfold"); const sources = @import("kernel_sources"); const limits = @import("contract").limits; -const Launch = @import("metal_limits.zig").Launch; -const preM5 = @import("metal_limits.zig").preM5; -const attentionLaunch = @import("metal_limits.zig").attentionLaunch; -const pagedLaunch = @import("metal_limits.zig").pagedLaunch; +const Launch = @import("metal_launch_helpers.zig").Launch; +const preM5 = @import("metal_launch_helpers.zig").preM5; +const attentionLaunch = @import("metal_launch_helpers.zig").attentionLaunch; +const pagedLaunch = @import("metal_launch_helpers.zig").pagedLaunch; /// These families' launch sources, or null when the name belongs to another resolver. pub fn launchOf(a: std.mem.Allocator, device: mtl.Device, d: limits.MetalLaunch, fun: []const u8, comptime assemble: bool) !?Launch { diff --git a/zig/tests/contract/metal_inkling2_glue.zig b/zig/tests/contract/metal_inkling2_glue.zig index ae23d41756f..e5e207d0a11 100644 --- a/zig/tests/contract/metal_inkling2_glue.zig +++ b/zig/tests/contract/metal_inkling2_glue.zig @@ -23,8 +23,8 @@ fn fromBf(v: u16) f32 { return c.fromBf16(v); } -const segments_label = "metal inkling2 glue conv_dynamic_segs tf_inkling2_conv_dynamic_segs"; -const split_label = "metal inkling2 glue router split tf_inkling2_route_scores and tf_inkling2_route_select"; +pub const segments_label = "metal inkling2 glue conv_dynamic_segs tf_inkling2_conv_dynamic_segs"; +pub const split_label = "metal inkling2 glue router split tf_inkling2_route_scores and tf_inkling2_route_select"; /// Each dot opens with +B x0 - B x0 = 0 (B = 2^18, exact): any other summation order loses the low terms' bits. fn orderProbe(x: []f32, weight: []f32) void { @@ -483,118 +483,4 @@ pub const Probe = struct { } }; -pub const Suite = struct { - a: std.mem.Allocator, - device: mtl.Device, - queue: mtl.Queue, - kernels: *std.ArrayList(g.Kernel), - probes: std.ArrayList(*Probe) = .empty, - fused_probes: std.ArrayList(*fused.Probe) = .empty, - norm_probes: std.ArrayList(*norm_fused.Probe) = .empty, - - const InitCtx = struct { - s: *Suite, - kind: p.Kind, - text: []const u8, - split: bool = false, - - fn initProbe(ctx: InitCtx) !Probe { - return if (ctx.split) - Probe.initSplit(ctx.s.a, ctx.s.device, ctx.s.queue, ctx.text) - else - Probe.initSource(ctx.s.a, ctx.s.device, ctx.s.queue, ctx.kind, ctx.text); - } - - fn initFused(ctx: InitCtx) !fused.Probe { - return fused.Probe.initSource(ctx.s.a, ctx.s.device, ctx.s.queue, ctx.kind, ctx.text); - } - - fn initNormFused(ctx: InitCtx) !norm_fused.Probe { - return norm_fused.Probe.initSource(ctx.s.a, ctx.s.device, ctx.s.queue, ctx.kind, ctx.text); - } - - fn loadBase(ctx: InitCtx, probe: *Probe) !void { - probe.base_pipes = try host.Pipelines.load(ctx.s.device); - } - - fn markSegmented(_: InitCtx, probe: *Probe) !void { - probe.segmented = true; - } - }; - - fn add(s: *Suite, kind: p.Kind, control: bool, only: ?[]const u8) !void { - const name = if (control) controls.name(kind) else kind.label(); - if (only) |filter| if (std.mem.indexOf(u8, name, filter) == null) return; - const owned = if (control) try controls.source(s.a, sources.glue, kind) else null; - defer if (owned) |buf| s.a.free(buf); - const ctx: InitCtx = .{ .s = s, .kind = kind, .text = owned orelse sources.glue }; - const ctrl = if (control) name else null; - if (kind == .norm_bf16 or kind == .attn_partial_ar_norm or kind == .mlp_partial_ar_norm) { - try controls.addAcquired(norm_fused.Probe, InitCtx, s.a, &s.norm_probes, s.kernels, ctx, InitCtx.initNormFused, null, ctrl); - return; - } - if (kind == .cached_ar or kind == .block_inv_rms or kind == .attn_partial_ar or kind == .mlp_partial_ar) { - try controls.addAcquired(fused.Probe, InitCtx, s.a, &s.fused_probes, s.kernels, ctx, InitCtx.initFused, null, ctrl); - return; - } - const load_base: ?*const fn (InitCtx, *Probe) anyerror!void = if (control and kv_conv.isKvConv(kind)) InitCtx.loadBase else null; - try controls.addAcquired(Probe, InitCtx, s.a, &s.probes, s.kernels, ctx, InitCtx.initProbe, load_base, ctrl); - } - - fn addNanControl(s: *Suite, control: controls.NanControl, only: ?[]const u8) !void { - const name = controls.nanName(control); - if (only) |filter| if (std.mem.indexOf(u8, name, filter) == null) return; - const text = try controls.nanSource(s.a, sources.glue, control); - defer s.a.free(text); - try controls.addAcquired(Probe, InitCtx, s.a, &s.probes, s.kernels, .{ .s = s, .kind = .router, .text = text }, InitCtx.initProbe, null, name); - } - - fn addSplit(s: *Suite, control: ?split_controls.Control, only: ?[]const u8) !void { - const name = if (control) |x| split_controls.name(x) else split_label; - if (only) |filter| if (std.mem.indexOf(u8, name, filter) == null) return; - const owned = if (control) |x| try split_controls.source(s.a, sources.glue, x) else null; - defer if (owned) |buf| s.a.free(buf); - try controls.addAcquired(Probe, InitCtx, s.a, &s.probes, s.kernels, .{ .s = s, .kind = .router, .text = owned orelse sources.glue, .split = true }, InitCtx.initProbe, null, if (control != null) name else null); - } - - fn addSegments(s: *Suite, control: bool, only: ?[]const u8) !void { - const name = if (control) "control: " ++ segments_label else segments_label; - if (only) |text| if (std.mem.indexOf(u8, name, text) == null) return; - const from = "const uint r = global_r - seg.row0;"; - if (std.mem.count(u8, sources.glue, from) != 1) return error.ControlEditMissing; - const text = if (control) try std.mem.replaceOwned(u8, s.a, sources.glue, from, "const uint r = 0;") else try s.a.dupe(u8, sources.glue); - defer s.a.free(text); - try controls.addAcquired(Probe, InitCtx, s.a, &s.probes, s.kernels, .{ .s = s, .kind = .conv_dynamic, .text = text }, InitCtx.initProbe, InitCtx.markSegmented, if (control) name else null); - } - - pub fn collect(s: *Suite, only: ?[]const u8) !void { - for (std.enums.values(p.Kind)) |kind| { - try s.add(kind, false, only); - try s.add(kind, true, only); - } - try s.addSegments(false, only); - try s.addSegments(true, only); - try s.addSplit(null, only); - for (std.enums.values(controls.NanControl)) |control| try s.addNanControl(control, only); - try s.addSplit(.route_strided, only); - try s.addSplit(.route_index, only); - } - - pub fn deinit(s: *Suite) void { - for (s.probes.items) |probe| { - probe.deinit(); - s.a.destroy(probe); - } - s.probes.deinit(s.a); - for (s.fused_probes.items) |fp| { - fp.deinit(); - s.a.destroy(fp); - } - s.fused_probes.deinit(s.a); - for (s.norm_probes.items) |np| { - np.deinit(); - s.a.destroy(np); - } - s.norm_probes.deinit(s.a); - } -}; +pub const Suite = @import("metal_inkling2_glue_suite.zig").Suite; diff --git a/zig/tests/contract/metal_inkling2_glue_suite.zig b/zig/tests/contract/metal_inkling2_glue_suite.zig new file mode 100644 index 00000000000..d14a8adc7cd --- /dev/null +++ b/zig/tests/contract/metal_inkling2_glue_suite.zig @@ -0,0 +1,133 @@ +//! Inkling 2 Mini glue suite collection and probe lifetimes. +const std = @import("std"); +const mtl = @import("metal"); +const controls = @import("metal_inkling2_glue_controls.zig"); +const kv_conv = @import("metal_inkling2_glue_kv_conv.zig"); +const split_controls = @import("metal_inkling2_split_controls.zig"); +const fused = @import("metal_inkling2_glue_fused.zig"); +const norm_fused = @import("metal_inkling2_glue_norm.zig"); +const contract = @import("contract"); +const g = contract.gates; +const host = @import("tensorfold").inkling2_metal_host.glue; +const p = host.plan; +const sources = @import("inkling2_metal"); +const glue = @import("metal_inkling2_glue.zig"); +const Probe = glue.Probe; +const segments_label = glue.segments_label; +const split_label = glue.split_label; + +pub const Suite = struct { + a: std.mem.Allocator, + device: mtl.Device, + queue: mtl.Queue, + kernels: *std.ArrayList(g.Kernel), + probes: std.ArrayList(*Probe) = .empty, + fused_probes: std.ArrayList(*fused.Probe) = .empty, + norm_probes: std.ArrayList(*norm_fused.Probe) = .empty, + + const InitCtx = struct { + s: *Suite, + kind: p.Kind, + text: []const u8, + split: bool = false, + + fn initProbe(ctx: InitCtx) !Probe { + return if (ctx.split) + Probe.initSplit(ctx.s.a, ctx.s.device, ctx.s.queue, ctx.text) + else + Probe.initSource(ctx.s.a, ctx.s.device, ctx.s.queue, ctx.kind, ctx.text); + } + + fn initFused(ctx: InitCtx) !fused.Probe { + return fused.Probe.initSource(ctx.s.a, ctx.s.device, ctx.s.queue, ctx.kind, ctx.text); + } + + fn initNormFused(ctx: InitCtx) !norm_fused.Probe { + return norm_fused.Probe.initSource(ctx.s.a, ctx.s.device, ctx.s.queue, ctx.kind, ctx.text); + } + + fn loadBase(ctx: InitCtx, probe: *Probe) !void { + probe.base_pipes = try host.Pipelines.load(ctx.s.device); + } + + fn markSegmented(_: InitCtx, probe: *Probe) !void { + probe.segmented = true; + } + }; + + fn add(s: *Suite, kind: p.Kind, control: bool, only: ?[]const u8) !void { + const name = if (control) controls.name(kind) else kind.label(); + if (only) |filter| if (std.mem.indexOf(u8, name, filter) == null) return; + const owned = if (control) try controls.source(s.a, sources.glue, kind) else null; + defer if (owned) |buf| s.a.free(buf); + const ctx: InitCtx = .{ .s = s, .kind = kind, .text = owned orelse sources.glue }; + const ctrl = if (control) name else null; + if (kind == .norm_bf16 or kind == .attn_partial_ar_norm or kind == .mlp_partial_ar_norm) { + try controls.addAcquired(norm_fused.Probe, InitCtx, s.a, &s.norm_probes, s.kernels, ctx, InitCtx.initNormFused, null, ctrl); + return; + } + if (kind == .cached_ar or kind == .block_inv_rms or kind == .attn_partial_ar or kind == .mlp_partial_ar) { + try controls.addAcquired(fused.Probe, InitCtx, s.a, &s.fused_probes, s.kernels, ctx, InitCtx.initFused, null, ctrl); + return; + } + const load_base: ?*const fn (InitCtx, *Probe) anyerror!void = if (control and kv_conv.isKvConv(kind)) InitCtx.loadBase else null; + try controls.addAcquired(Probe, InitCtx, s.a, &s.probes, s.kernels, ctx, InitCtx.initProbe, load_base, ctrl); + } + + fn addNanControl(s: *Suite, control: controls.NanControl, only: ?[]const u8) !void { + const name = controls.nanName(control); + if (only) |filter| if (std.mem.indexOf(u8, name, filter) == null) return; + const text = try controls.nanSource(s.a, sources.glue, control); + defer s.a.free(text); + try controls.addAcquired(Probe, InitCtx, s.a, &s.probes, s.kernels, .{ .s = s, .kind = .router, .text = text }, InitCtx.initProbe, null, name); + } + + fn addSplit(s: *Suite, control: ?split_controls.Control, only: ?[]const u8) !void { + const name = if (control) |x| split_controls.name(x) else split_label; + if (only) |filter| if (std.mem.indexOf(u8, name, filter) == null) return; + const owned = if (control) |x| try split_controls.source(s.a, sources.glue, x) else null; + defer if (owned) |buf| s.a.free(buf); + try controls.addAcquired(Probe, InitCtx, s.a, &s.probes, s.kernels, .{ .s = s, .kind = .router, .text = owned orelse sources.glue, .split = true }, InitCtx.initProbe, null, if (control != null) name else null); + } + + fn addSegments(s: *Suite, control: bool, only: ?[]const u8) !void { + const name = if (control) "control: " ++ segments_label else segments_label; + if (only) |text| if (std.mem.indexOf(u8, name, text) == null) return; + const from = "const uint r = global_r - seg.row0;"; + if (std.mem.count(u8, sources.glue, from) != 1) return error.ControlEditMissing; + const text = if (control) try std.mem.replaceOwned(u8, s.a, sources.glue, from, "const uint r = 0;") else try s.a.dupe(u8, sources.glue); + defer s.a.free(text); + try controls.addAcquired(Probe, InitCtx, s.a, &s.probes, s.kernels, .{ .s = s, .kind = .conv_dynamic, .text = text }, InitCtx.initProbe, InitCtx.markSegmented, if (control) name else null); + } + + pub fn collect(s: *Suite, only: ?[]const u8) !void { + for (std.enums.values(p.Kind)) |kind| { + try s.add(kind, false, only); + try s.add(kind, true, only); + } + try s.addSegments(false, only); + try s.addSegments(true, only); + try s.addSplit(null, only); + for (std.enums.values(controls.NanControl)) |control| try s.addNanControl(control, only); + try s.addSplit(.route_strided, only); + try s.addSplit(.route_index, only); + } + + pub fn deinit(s: *Suite) void { + for (s.probes.items) |probe| { + probe.deinit(); + s.a.destroy(probe); + } + s.probes.deinit(s.a); + for (s.fused_probes.items) |fp| { + fp.deinit(); + s.a.destroy(fp); + } + s.fused_probes.deinit(s.a); + for (s.norm_probes.items) |np| { + np.deinit(); + s.a.destroy(np); + } + s.norm_probes.deinit(s.a); + } +}; diff --git a/zig/tests/contract/metal_inkling2_main.zig b/zig/tests/contract/metal_inkling2_main.zig index 22121937a8f..b27a2a39add 100644 --- a/zig/tests/contract/metal_inkling2_main.zig +++ b/zig/tests/contract/metal_inkling2_main.zig @@ -6,7 +6,7 @@ const g = @import("contract").gates; pub const Suites = struct { attention: @import("metal_inkling2_attention.zig").Suite, attention_gqa: @import("metal_inkling2_attention_gqa.zig").Suite, - glue: @import("metal_inkling2_glue.zig").Suite, + glue: @import("metal_inkling2_glue_suite.zig").Suite, logits: @import("metal_inkling2_logits.zig").Suite, experts: @import("metal_inkling2_experts.zig").Suite, mma: @import("metal_inkling2_mma.zig").Suite, diff --git a/zig/tests/contract/metal_launch_helpers.zig b/zig/tests/contract/metal_launch_helpers.zig new file mode 100644 index 00000000000..2c0fe55aaa9 --- /dev/null +++ b/zig/tests/contract/metal_launch_helpers.zig @@ -0,0 +1,101 @@ +const std = @import("std"); +const mtl = @import("metal"); +const tf = @import("tensorfold"); +const contract = @import("contract"); +const sources = @import("kernel_sources"); +const rig_ = @import("rig.zig"); + +const limits = contract.limits; + +/// A registered pipeline's declaration, function, source here and pre-M5 source (empty: the loader has none). +pub const Launch = struct { decl: limits.MetalLaunch, function: []const u8, here: []const u8, pre_m5: []const u8 }; + +/// The pre-M5 text of a source that includes nax.h (frags.source's branch for GPUs without tensor units). +pub fn preM5(a: std.mem.Allocator, head: []const u8, text: []const u8) ![]u8 { + const body = try std.mem.replaceOwned(u8, a, text, "#include \"../nax.h\"", sources.nax); + defer a.free(body); + return std.mem.concat(a, u8, &.{ head, "#define TF_SIMD_FRAGS 1\n", body }); +} + +/// A Bolt op's source: a norm by its key beside Lightning's, else the engine's prefill op file its label names. +pub fn boltSource(name: []const u8) ![]const u8 { + const in = std.mem.indexOf; + if (in(u8, name, " norm ") != null) { + const key = if (in(u8, name, " group norm ") != null) "group_norm_xs_bolt_16" else if (in(u8, name, "add_norm_moe") != null) "add_norm_moe_xs_bolt" else "add_norm_xs_bolt"; + for (sources.nemotron.all) |k| if (std.mem.eql(u8, k.key, key)) return k.source; + return error.UnknownLaunch; + } + const file = if (in(u8, name, " gemv ") != null) "gemv_ops" else if (in(u8, name, " combine ") != null) "elementwise" else if (in(u8, name, " route ") != null) "route" else return error.UnknownLaunch; + for (sources.prefill) |f| if (std.mem.eql(u8, f.name, file)) return f.text; + return error.UnknownLaunch; +} + +/// Main's Nemotron attention library as kernels.zig and prefill_kernels.zig build it here, and before the M5. +pub fn attentionLaunch(a: std.mem.Allocator, device: mtl.Device, d: limits.MetalLaunch, fun: []const u8) !Launch { + const tensor = device.tensorUnits(); + std.debug.print("FORM limits {s}: {s}\n", .{ d.name, if (tensor) "tensor-op source as written" else "SIMD rewrite" }); + if (std.mem.indexOf(u8, d.name, " partial ") != null or std.mem.indexOf(u8, d.name, " merge ") != null) { + const text = for (sources.nemotron.all) |k| { + if (std.mem.eql(u8, k.function, fun)) break k.source; + } else return error.UnknownLaunch; + const pre = if (std.mem.indexOf(u8, d.name, " partial ") != null) try tf.nemotron.simd_attention.layout(a, text) else text; + const here = if (tensor) text else if (std.mem.indexOf(u8, d.name, " partial ") != null) try tf.nemotron.simd_attention.forGeneration(a, device.generation(), text) else pre; + return .{ .decl = d, .function = fun, .here = here, .pre_m5 = pre }; + } + if (std.mem.indexOf(u8, d.name, " tree ") != null) { + const pre = try std.mem.concat(a, u8, &.{ "#define TF_SIMD_LAYOUT 1\n", sources.nemotron_tree }); + return .{ .decl = d, .function = fun, .here = if (tensor) sources.nemotron_tree else pre, .pre_m5 = pre }; + } + if (std.mem.indexOf(u8, d.name, " prompt ") != null) { + const file = if (std.mem.indexOf(u8, fun, "kv_put") != null) "glue" else "attention_nax"; + const text = for (sources.prefill) |f| { + if (std.mem.eql(u8, f.name, file)) break f.text; + } else return error.UnknownLaunch; + const pre = try preM5(a, "", text); + return .{ .decl = d, .function = fun, .here = if (tensor) try tf.frags.source(device, a, text) else pre, .pre_m5 = pre }; + } + return .{ .decl = d, .function = fun, .here = sources.nemotron_glue, .pre_m5 = sources.nemotron_glue }; +} + +/// A Nemotron paged twin's library as its loader would build it here, and before the M5. +pub fn pagedLaunch(a: std.mem.Allocator, device: mtl.Device, d: limits.MetalLaunch, fun: []const u8) !Launch { + const paged = sources.nemotron_paged; + const tensor = device.tensorUnits(); + std.debug.print("FORM limits {s}: {s}\n", .{ d.name, if (tensor) "tensor-op source as written" else "SIMD rewrite" }); + if (std.mem.indexOf(u8, d.name, " partial ") != null) { + const pre = try tf.nemotron.simd_attention.rewrite(a, paged.partial); + return .{ .decl = d, .function = fun, .here = if (tensor) paged.partial else pre, .pre_m5 = pre }; + } + if (std.mem.indexOf(u8, d.name, " tail ") != null) { + const pre = try std.mem.concat(a, u8, &.{ "#define TF_SIMD_LAYOUT 1\n", paged.tree }); + return .{ .decl = d, .function = fun, .here = if (tensor) paged.tree else pre, .pre_m5 = pre }; + } + if (std.mem.indexOf(u8, d.name, " prompt ") != null) { + const pre = try preM5(a, "", paged.prefill); + return .{ .decl = d, .function = fun, .here = if (tensor) try tf.frags.source(device, a, paged.prefill) else pre, .pre_m5 = pre }; + } + return .{ .decl = d, .function = fun, .here = paged.glue, .pre_m5 = paged.glue }; +} + +/// One launch on this GPU: the pipeline's own thread limit and threadgroup bytes against its declaration. +pub fn onThisGpu(a: std.mem.Allocator, device: mtl.Device, l: Launch, control: bool) !usize { + if (std.mem.indexOf(u8, l.here, "TF_ATTN_PV_FP32") != null) { + const full = std.mem.indexOf(u8, l.here, tf.frags.precision.define) != null; + std.debug.print("PRECISION limits {s}: shared P x V library {s}\n", .{ l.decl.name, if (full) "fp32" else "legacy" }); + } + const p = rig_.pipeline(device, l.here, l.function) catch |err| { + std.debug.print("{s} {s}: no pipeline on this GPU ({t})\n", .{ if (control) "RED " else "FAIL", l.decl.name, err }); + return 1; + }; + defer p.deinit(); + _ = a; + const most = p.maxThreads(); + const tg = rig_.tgMemory(p); + const cap = mtl.objc.msg(usize, device.id, "maxThreadgroupMemoryLength", .{}); + var n: usize = 0; + if (most < l.decl.threads and !l.decl.adapts) n += 1; + if (tg > l.decl.tg_memory or tg + l.decl.dynamic > cap) n += 1; + const word = if (n == 0) "PASS" else if (control) "RED " else "FAIL"; + std.debug.print("{s} limits here {s}: {d} threads launched, the pipeline takes {d}; {d} threadgroup bytes and {d} set (declared at most {d}, the GPU's most {d})\n", .{ word, l.decl.name, l.decl.threads, most, tg, l.decl.dynamic, l.decl.tg_memory, cap }); + return n; +} diff --git a/zig/tests/contract/metal_limits.zig b/zig/tests/contract/metal_limits.zig index f879f40dc2d..9b9736e206f 100644 --- a/zig/tests/contract/metal_limits.zig +++ b/zig/tests/contract/metal_limits.zig @@ -5,33 +5,19 @@ const tf = @import("tensorfold"); const contract = @import("contract"); const sources = @import("kernel_sources"); const topk_text = tf.bf16_topk_gpu.source; -const rig_ = @import("rig.zig"); const limits = contract.limits; const registry = contract.registry; -/// A registered pipeline's declaration, function, source here and pre-M5 source (empty: the loader has none). -pub const Launch = struct { decl: limits.MetalLaunch, function: []const u8, here: []const u8, pre_m5: []const u8 }; - -/// The pre-M5 text of a source that includes nax.h (frags.source's branch for GPUs without tensor units). -pub fn preM5(a: std.mem.Allocator, head: []const u8, text: []const u8) ![]u8 { - const body = try std.mem.replaceOwned(u8, a, text, "#include \"../nax.h\"", sources.nax); - defer a.free(body); - return std.mem.concat(a, u8, &.{ head, "#define TF_SIMD_FRAGS 1\n", body }); -} +const launch_helpers = @import("metal_launch_helpers.zig"); -/// A Bolt op's source: a norm by its key beside Lightning's, else the engine's prefill op file its label names. -fn boltSource(name: []const u8) ![]const u8 { - const in = std.mem.indexOf; - if (in(u8, name, " norm ") != null) { - const key = if (in(u8, name, " group norm ") != null) "group_norm_xs_bolt_16" else if (in(u8, name, "add_norm_moe") != null) "add_norm_moe_xs_bolt" else "add_norm_xs_bolt"; - for (sources.nemotron.all) |k| if (std.mem.eql(u8, k.key, key)) return k.source; - return error.UnknownLaunch; - } - const file = if (in(u8, name, " gemv ") != null) "gemv_ops" else if (in(u8, name, " combine ") != null) "elementwise" else if (in(u8, name, " route ") != null) "route" else return error.UnknownLaunch; - for (sources.prefill) |f| if (std.mem.eql(u8, f.name, file)) return f.text; - return error.UnknownLaunch; -} +/// A registered pipeline's declaration, function, source here and pre-M5 source (empty: the loader has none). +pub const Launch = launch_helpers.Launch; +const preM5 = launch_helpers.preM5; +const boltSource = launch_helpers.boltSource; +const attentionLaunch = launch_helpers.attentionLaunch; +const pagedLaunch = launch_helpers.pagedLaunch; +pub const onThisGpu = launch_helpers.onThisGpu; /// Each registration's function is its label's last word; the label's words say which source it compiles. pub fn launchOf(a: std.mem.Allocator, device: mtl.Device, d: limits.MetalLaunch) !Launch { @@ -402,76 +388,6 @@ fn resolve(a: std.mem.Allocator, device: mtl.Device, d: limits.MetalLaunch, comp return .{ .decl = d, .function = fun, .here = here, .pre_m5 = pre }; } -/// Main's Nemotron attention library as kernels.zig and prefill_kernels.zig build it here, and before the M5. -pub fn attentionLaunch(a: std.mem.Allocator, device: mtl.Device, d: limits.MetalLaunch, fun: []const u8) !Launch { - const tensor = device.tensorUnits(); - std.debug.print("FORM limits {s}: {s}\n", .{ d.name, if (tensor) "tensor-op source as written" else "SIMD rewrite" }); - if (std.mem.indexOf(u8, d.name, " partial ") != null or std.mem.indexOf(u8, d.name, " merge ") != null) { - const text = for (sources.nemotron.all) |k| { - if (std.mem.eql(u8, k.function, fun)) break k.source; - } else return error.UnknownLaunch; - const pre = if (std.mem.indexOf(u8, d.name, " partial ") != null) try tf.nemotron.simd_attention.layout(a, text) else text; - const here = if (tensor) text else if (std.mem.indexOf(u8, d.name, " partial ") != null) try tf.nemotron.simd_attention.forGeneration(a, device.generation(), text) else pre; - return .{ .decl = d, .function = fun, .here = here, .pre_m5 = pre }; - } - if (std.mem.indexOf(u8, d.name, " tree ") != null) { - const pre = try std.mem.concat(a, u8, &.{ "#define TF_SIMD_LAYOUT 1\n", sources.nemotron_tree }); - return .{ .decl = d, .function = fun, .here = if (tensor) sources.nemotron_tree else pre, .pre_m5 = pre }; - } - if (std.mem.indexOf(u8, d.name, " prompt ") != null) { - const file = if (std.mem.indexOf(u8, fun, "kv_put") != null) "glue" else "attention_nax"; - const text = for (sources.prefill) |f| { - if (std.mem.eql(u8, f.name, file)) break f.text; - } else return error.UnknownLaunch; - const pre = try preM5(a, "", text); - return .{ .decl = d, .function = fun, .here = if (tensor) try tf.frags.source(device, a, text) else pre, .pre_m5 = pre }; - } - return .{ .decl = d, .function = fun, .here = sources.nemotron_glue, .pre_m5 = sources.nemotron_glue }; -} - -/// A Nemotron paged twin's library as its loader would build it here, and before the M5. -pub fn pagedLaunch(a: std.mem.Allocator, device: mtl.Device, d: limits.MetalLaunch, fun: []const u8) !Launch { - const paged = sources.nemotron_paged; - const tensor = device.tensorUnits(); - std.debug.print("FORM limits {s}: {s}\n", .{ d.name, if (tensor) "tensor-op source as written" else "SIMD rewrite" }); - if (std.mem.indexOf(u8, d.name, " partial ") != null) { - const pre = try tf.nemotron.simd_attention.rewrite(a, paged.partial); - return .{ .decl = d, .function = fun, .here = if (tensor) paged.partial else pre, .pre_m5 = pre }; - } - if (std.mem.indexOf(u8, d.name, " tail ") != null) { - const pre = try std.mem.concat(a, u8, &.{ "#define TF_SIMD_LAYOUT 1\n", paged.tree }); - return .{ .decl = d, .function = fun, .here = if (tensor) paged.tree else pre, .pre_m5 = pre }; - } - if (std.mem.indexOf(u8, d.name, " prompt ") != null) { - const pre = try preM5(a, "", paged.prefill); - return .{ .decl = d, .function = fun, .here = if (tensor) try tf.frags.source(device, a, paged.prefill) else pre, .pre_m5 = pre }; - } - return .{ .decl = d, .function = fun, .here = paged.glue, .pre_m5 = paged.glue }; -} - -/// One launch on this GPU: the pipeline's own thread limit and threadgroup bytes against its declaration. -pub fn onThisGpu(a: std.mem.Allocator, device: mtl.Device, l: Launch, control: bool) !usize { - if (std.mem.indexOf(u8, l.here, "TF_ATTN_PV_FP32") != null) { - const full = std.mem.indexOf(u8, l.here, tf.frags.precision.define) != null; - std.debug.print("PRECISION limits {s}: shared P x V library {s}\n", .{ l.decl.name, if (full) "fp32" else "legacy" }); - } - const p = rig_.pipeline(device, l.here, l.function) catch |err| { - std.debug.print("{s} {s}: no pipeline on this GPU ({t})\n", .{ if (control) "RED " else "FAIL", l.decl.name, err }); - return 1; - }; - defer p.deinit(); - _ = a; - const most = p.maxThreads(); - const tg = rig_.tgMemory(p); - const cap = mtl.objc.msg(usize, device.id, "maxThreadgroupMemoryLength", .{}); - var n: usize = 0; - if (most < l.decl.threads and !l.decl.adapts) n += 1; - if (tg > l.decl.tg_memory or tg + l.decl.dynamic > cap) n += 1; - const word = if (n == 0) "PASS" else if (control) "RED " else "FAIL"; - std.debug.print("{s} limits here {s}: {d} threads launched, the pipeline takes {d}; {d} threadgroup bytes and {d} set (declared at most {d}, the GPU's most {d})\n", .{ word, l.decl.name, l.decl.threads, most, tg, l.decl.dynamic, l.decl.tg_memory, cap }); - return n; -} - /// Gate 5: declarations against every family, each pipeline on this GPU, and offline M1/M2 compiles when asked. pub fn gate(a: std.mem.Allocator, io: std.Io, device: mtl.Device, offline: ?[]const u8, only: ?[]const u8) !usize { var list: std.ArrayList(limits.MetalLaunch) = .empty;