From 7917bb05d3ad362c6dcf3fe8dba2af3529a530ea Mon Sep 17 00:00:00 2001 From: Tiago Goncalves <27917082+tacosta@users.noreply.github.com> Date: Sat, 21 Nov 2026 14:24:38 +0000 Subject: [PATCH] qwen3_5: split mixed-width draft head batches Fixes #3460. --- docs/optimization-ledger.md | 2 + zig/qwen35_draft_frame_host.zig | 54 +- zig/qwen35_draft_frame_mixed_host.zig | 300 +++++++++++ zig/src/families/qwen3_5/cuda.zig | 1 + zig/src/families/qwen3_5/cuda_draft_frame.zig | 210 +++++++- .../families/qwen3_5/cuda_dspine_frame.zig | 486 +++++++++++++++++- 6 files changed, 1033 insertions(+), 20 deletions(-) create mode 100644 zig/qwen35_draft_frame_mixed_host.zig diff --git a/docs/optimization-ledger.md b/docs/optimization-ledger.md index 21a820266ba..e00f6acb226 100644 --- a/docs/optimization-ledger.md +++ b/docs/optimization-ledger.md @@ -466,6 +466,8 @@ below; these are estimates for planning a port, not results. tree) a step. It needs a trained drafter for each target; see [training a drafter](recipes/training-a-drafter.md). Qwen27 Metal retains its target-verified long-copy tail for an eligible lone greedy request at the M5 16-row default; sampled and shared requests keep the lane core ([#3013](https://github.com/ashhart/TensorFold/issues/3013)). + Qwen3.5 CUDA mixed-width batches project narrow and wide contexts through their own DFlash2/DSpine head paths + ([#3460](https://github.com/ashhart/TensorFold/issues/3460)); hardware timing and token-identity receipts are pending. 17. **DSpark drafters.** A drafter that ships with the release (DeepSeek-V4.1's `mtp.i` blocks, MiniMax-M3.1's, Kimi K3's) drafts from the target's taps with a confidence schedule. Applies wherever a DSpark drafter exists for the diff --git a/zig/qwen35_draft_frame_host.zig b/zig/qwen35_draft_frame_host.zig index 0a0be850906..3c3d119c640 100644 --- a/zig/qwen35_draft_frame_host.zig +++ b/zig/qwen35_draft_frame_host.zig @@ -83,6 +83,7 @@ test "Draft frames: a common frame stages each stream's own ring positions and p } const Record = struct { + const HeadProjection = struct { columns: c_int, rows: c_int }; var counts: [16]usize = @splat(0); var max_rows: u32 = 0; var uploads: usize = 0; @@ -91,11 +92,24 @@ const Record = struct { var fail: bool = false; var last_norm_input: u64 = 0; var block: usize = 8; + var head_projections: [8]HeadProjection = undefined; + var head_projection_count: usize = 0; fn launch(f: cuda.abi.Function, x: c_uint, _: c_uint, z: c_uint, threads: c_uint, _: c_uint, _: c_uint, _: c_uint, _: cuda.abi.Stream, args: ?[*]?*anyopaque, _: ?[*]?*anyopaque) callconv(.c) cuda.abi.Result { const id = @intFromPtr(f); if (id < counts.len) counts[id] += 1; if (id == 13) last_norm_input = @as(*const u64, @ptrCast(@alignCast(args.?[0].?))).*; if (id == 1) max_rows = @max(max_rows, x); + if (id == 14) { + const parts = @as(*const cuda.qlinear.Parts, @ptrCast(@alignCast(args.?[2].?))).*; + const columns = parts.p[0].n; + if (columns > 256) { + head_projections[head_projection_count] = .{ + .columns = columns, + .rows = @as(*const c_int, @ptrCast(@alignCast(args.?[3].?))).*, + }; + head_projection_count += 1; + } + } if (id == 5) { std.debug.assert(z == 9 and threads == 128); if (fail) return cuda.abi.error_not_ready; @@ -106,6 +120,12 @@ const Record = struct { uploads += 1; return cuda.abi.success; } + fn copyDevice(_: u64, _: u64, _: usize, _: cuda.abi.Stream) callconv(.c) cuda.abi.Result { + return cuda.abi.success; + } + fn copy2d(_: *const cuda.abi.Memcpy2D, _: cuda.abi.Stream) callconv(.c) cuda.abi.Result { + return cuda.abi.success; + } fn download(dst: ?*anyopaque, _: u64, bytes: usize, _: cuda.abi.Stream) callconv(.c) cuda.abi.Result { const data = @as([*]u8, @ptrCast(dst.?))[0..bytes]; @memset(data, 0); @@ -133,7 +153,7 @@ fn weight() cuda.qlinear.Affine4 { return .{ .w = 1, .s = 2, .b = 3, .n = 256, .k = 256, .npad = 256 }; } -test "Draft frames: the real hold adapter emits one frame for every stream and invalidates drafts on failure" { +test "Draft frames: actual holds group mixed head widths and invalidate drafts on failure" { for ([_]usize{ 8, 16 }) |block| try actualFrame(block); } fn actualFrame(block: usize) !void { @@ -143,6 +163,8 @@ fn actualFrame(block: usize) !void { driver.api.cuLaunchKernel = Record.launch; driver.api.cuMemcpyHtoDAsync_v2 = Record.upload; driver.api.cuMemcpyDtoHAsync_v2 = Record.download; + driver.api.cuMemcpyDtoDAsync_v2 = Record.copyDevice; + driver.api.cuMemcpy2DAsync_v2 = Record.copy2d; driver.api.cuStreamSynchronize = Record.wait; var e: q.engine.Engine = undefined; e.kit = null; @@ -272,10 +294,40 @@ fn actualFrame(block: usize) !void { try std.testing.expectEqual(@as(usize, 0), ctx.held_n); try std.testing.expectEqual(@as(usize, 0), ctx.grown); } + + // The pre-fix hold path sends both contexts through the full head. + e.head = .{ .a4 = .{ .w = 1, .s = 2, .b = 3, .n = 248320, .k = 256, .npad = 248320 } }; + d.c.vocab = 248320; + d.scratch.len = try d.layout(false); + _ = try d.layout(true); + contexts[0].wide = false; + contexts[1].wide = true; + e.affine.group_fn = function(&driver, 14); + Record.downloads = 0; + Record.head_projection_count = 0; + Record.fail = false; + try d.drafter().hold(holds[0..2]); + + const per = block - 1; + var narrow_rows: usize = 0; + var tail_rows: usize = 0; + var full_rows: usize = 0; + for (Record.head_projections[0..Record.head_projection_count]) |projection| { + switch (projection.columns) { + 98304 => narrow_rows += @intCast(projection.rows), + 320 => tail_rows += @intCast(projection.rows), + 248320 => full_rows += @intCast(projection.rows), + else => unreachable, + } + } + try std.testing.expectEqual(per, full_rows); + try std.testing.expectEqual(per, narrow_rows); + try std.testing.expectEqual(per, tail_rows); } test { _ = @import("qwen35_draft_equality.zig"); + _ = @import("qwen35_draft_frame_mixed_host.zig"); _ = @import("qwen35_draft_graphs_host.zig"); } diff --git a/zig/qwen35_draft_frame_mixed_host.zig b/zig/qwen35_draft_frame_mixed_host.zig new file mode 100644 index 00000000000..3a3e7ca72f9 --- /dev/null +++ b/zig/qwen35_draft_frame_mixed_host.zig @@ -0,0 +1,300 @@ +//! Host launch tests for mixed Qwen3.5 draft head widths. +const std = @import("std"); +const q = @import("qwen35"); +const cuda = @import("cuda"); + +fn config() q.draft.Config { + return .{ .hidden = 256, .intermediate = 256, .layers = 1, .vocab = 256, .heads = 2, .kv_heads = 1, .head_dim = 128, .block = 8, .mask = 255, .window = 2048, .group = 16, .rank = 2, .topk = 2, .eps = 1e-6, .theta = 10000000, .taps = @splat(0), .n_taps = 1 }; +} +fn function(d: *const cuda.Driver, id: usize) cuda.Function { + return .{ .d = d, .handle = @ptrFromInt(id) }; +} +fn weight() cuda.qlinear.Affine4 { + return .{ .w = 1, .s = 2, .b = 3, .n = 256, .k = 256, .npad = 256 }; +} + +test "Draft frames: mixed affine-4 head rebuilds sums after row compaction" { + const F = q.draft.frame; + const Trace = struct { + const Event = enum { compact, sums, project }; + const Copy = struct { dst: u64, src: u64, bytes: usize }; + const Sum = struct { x: u64, xs: u64, k: c_int, rows: usize, grid: [3]usize }; + const Projection = struct { x: u64, xs: u64, rows: usize, members: usize, sums: bool }; + var events: [6]Event = undefined; + var event_count: usize = 0; + var copies: [2]Copy = undefined; + var copy_count: usize = 0; + var sums: [2]Sum = undefined; + var sum_count: usize = 0; + var projections: [2]Projection = undefined; + var projection_count: usize = 0; + + fn record(event: Event) void { + events[event_count] = event; + event_count += 1; + } + + fn copyDevice(dst: u64, src: u64, bytes: usize, _: cuda.abi.Stream) callconv(.c) cuda.abi.Result { + copies[copy_count] = .{ .dst = dst, .src = src, .bytes = bytes }; + copy_count += 1; + record(.compact); + return cuda.abi.success; + } + + fn copyHost(_: ?*anyopaque, _: u64, _: usize, _: cuda.abi.Stream) callconv(.c) cuda.abi.Result { + return cuda.abi.success; + } + + fn copy2d(_: *const cuda.abi.Memcpy2D, _: cuda.abi.Stream) callconv(.c) cuda.abi.Result { + return cuda.abi.success; + } + }; + const Draws = struct { + pub fn topkRows(_: *@This(), _: cuda.Stream, _: u64, _: usize, _: u8, _: u64, _: u64, _: usize) !void {} + }; + const E = struct { + d: *cuda.Driver, + stream: cuda.Stream, + head: q.engine.Proj, + affine: struct { pdl: bool }, + fns: struct { sums: cuda.Function }, + draws: Draws, + + pub fn run(_: *@This(), f: cuda.Function, grid: [3]usize, _: [3]usize, args: anytype) !void { + if (f.handle) |handle| { + if (@intFromPtr(handle) == 1) { + Trace.sums[Trace.sum_count] = .{ .x = args[0], .xs = args[1], .k = @intCast(args[2]), .rows = grid[0], .grid = grid }; + Trace.sum_count += 1; + Trace.record(.sums); + } + } + } + + pub fn projSums(_: *@This(), _: q.engine.Proj, x: u64, xs: u64, _: u64, rows: usize, _: bool, _: u64) !void { + Trace.projections[Trace.projection_count] = .{ .x = x, .xs = xs, .rows = rows, .members = 1, .sums = false }; + Trace.projection_count += 1; + Trace.record(.project); + } + + pub fn projManySums(_: *@This(), ls: []const q.engine.Proj, x: u64, xs: u64, _: []const u64, rows: usize, sums: bool, _: u64) !void { + Trace.projections[Trace.projection_count] = .{ .x = x, .xs = xs, .rows = rows, .members = ls.len, .sums = sums }; + Trace.projection_count += 1; + Trace.record(.project); + } + }; + const C = struct { block: usize, hidden: usize, vocab: usize, topk: usize }; + const D = struct { + e: *E, + c: C, + x: u64, + h2: u64, + logits: u64, + xs: u64, + parts: u64, + words: u64, + }; + + var driver: cuda.Driver = undefined; + driver.api.cuMemcpyDtoDAsync_v2 = Trace.copyDevice; + driver.api.cuMemcpyDtoHAsync_v2 = Trace.copyHost; + driver.api.cuMemcpy2DAsync_v2 = Trace.copy2d; + const c: C = .{ .block = 8, .hidden = 64, .vocab = 248320, .topk = 2 }; + const affine_head: cuda.qlinear.Affine4 = .{ .w = 0x8000, .s = 0x9000, .b = 0xa000, .n = c.vocab, .k = c.hidden, .npad = c.vocab }; + var e = E{ + .d = &driver, + .stream = .{ .d = &driver, .handle = null }, + .head = .{ .a4 = affine_head }, + .affine = .{ .pdl = true }, + .fns = .{ .sums = .{ .d = &driver, .handle = @ptrFromInt(1) } }, + .draws = .{}, + }; + const d = D{ .e = &e, .c = c, .x = 0x100000, .h2 = 0x200000, .logits = 0x300000, .xs = 0x400000, .parts = 0x500000, .words = 0x600000 }; + var contexts: [2]q.draft.Ctx = .{ .{ .ring = undefined, .wide = true }, .{ .ring = undefined } }; + const refs = [_]*q.draft.Ctx{ &contexts[0], &contexts[1] }; + var storage: [F.stagedLen(2)]u8 align(8) = undefined; + Trace.event_count = 0; + Trace.copy_count = 0; + Trace.sum_count = 0; + Trace.projection_count = 0; + + try F.mixedHead(&d, &refs, &storage); + + const rows = c.block - 1; + const input_bytes = rows * c.hidden * 2; + try std.testing.expectEqual(@as(usize, 2), Trace.copy_count); + try std.testing.expectEqual(d.h2, Trace.copies[0].dst); + try std.testing.expectEqual(d.x + input_bytes, Trace.copies[0].src); + try std.testing.expectEqual(input_bytes, Trace.copies[0].bytes); + try std.testing.expectEqual(d.h2, Trace.copies[1].dst); + try std.testing.expectEqual(d.x, Trace.copies[1].src); + try std.testing.expectEqual(input_bytes, Trace.copies[1].bytes); + try std.testing.expectEqual(@as(usize, 2), Trace.sum_count); + for (Trace.sums) |sum| { + try std.testing.expectEqual(d.h2, sum.x); + try std.testing.expectEqual(d.xs, sum.xs); + try std.testing.expectEqual(@as(c_int, @intCast(c.hidden)), sum.k); + try std.testing.expectEqual(rows, sum.rows); + try std.testing.expectEqual([_]usize{ rows, 1, 1 }, sum.grid); + } + try std.testing.expectEqual(@as(usize, 2), Trace.projection_count); + for (Trace.projections) |projection| { + try std.testing.expectEqual(d.h2, projection.x); + try std.testing.expectEqual(d.xs, projection.xs); + try std.testing.expectEqual(rows, projection.rows); + } + try std.testing.expectEqual(@as(usize, 2), Trace.projections[0].members); + try std.testing.expect(!Trace.projections[0].sums); + try std.testing.expectEqual(@as(usize, 1), Trace.projections[1].members); + try std.testing.expectEqual([_]Trace.Event{ .compact, .sums, .project, .compact, .sums, .project }, Trace.events); +} + +test "Qwen CUDA contracts: mixed-width heads launch by class and restore stream rows" { + for ([_]usize{ 8, 16 }) |block| { + try mixedHeadContract(block, false); + try mixedHeadContract(block, true); + } +} + +fn mixedHeadContract(block: usize, wide_even: bool) !void { + const Trace = struct { + const Copy = struct { dst: u64, src: u64, bytes: usize }; + var gathered: [5]Copy = undefined; + var fetched: [5]Copy = undefined; + var np: usize = 0; + var nf: usize = 0; + var heads: [2]struct { columns: u32, rows: u32 } = undefined; + var nh: usize = 0; + var copies2d: usize = 0; + fn launch(f: cuda.abi.Function, _: c_uint, gy: c_uint, _: c_uint, _: c_uint, _: c_uint, _: c_uint, _: c_uint, _: cuda.abi.Stream, args: ?[*]?*anyopaque, _: ?[*]?*anyopaque) callconv(.c) cuda.abi.Result { + if (@intFromPtr(f) == 1) { + heads[nh] = .{ .columns = @as(*const u32, @ptrCast(@alignCast(args.?[1].?))).*, .rows = gy }; + nh += 1; + } + return cuda.abi.success; + } + fn copyDevice(dst: u64, src: u64, bytes: usize, _: cuda.abi.Stream) callconv(.c) cuda.abi.Result { + gathered[np] = .{ .dst = dst, .src = src, .bytes = bytes }; + np += 1; + return cuda.abi.success; + } + fn copyHost(dst: ?*anyopaque, src: u64, bytes: usize, _: cuda.abi.Stream) callconv(.c) cuda.abi.Result { + fetched[nf] = .{ .dst = @intFromPtr(dst.?), .src = src, .bytes = bytes }; + nf += 1; + return cuda.abi.success; + } + fn copy2d(_: *const cuda.abi.Memcpy2D, _: cuda.abi.Stream) callconv(.c) cuda.abi.Result { + copies2d += 1; + return cuda.abi.success; + } + }; + var driver: cuda.Driver = undefined; + driver.api.cuLaunchKernel = Trace.launch; + driver.api.cuMemcpyDtoDAsync_v2 = Trace.copyDevice; + driver.api.cuMemcpyDtoHAsync_v2 = Trace.copyHost; + driver.api.cuMemcpy2DAsync_v2 = Trace.copy2d; + var e: q.engine.Engine = undefined; + e.d = &driver; + e.stream = .{ .d = &driver, .handle = null }; + e.kit = null; + e.affine.split = null; + e.affine.mlp128 = false; + e.affine.pdl = false; + e.affine.wide_verify = false; + e.affine.group_fn = function(&driver, 4); + e.fns.sums = function(&driver, 3); + e.draws.topk_slices_fn = function(&driver, 1); + e.draws.topk_merge_fn = function(&driver, 2); + var head = weight(); + head.n = 248320; + head.npad = head.n; + e.head = .{ .a4 = head }; + var d: q.draft.Draft = undefined; + d.e = &e; + d.c = config(); + d.c.block = block; + d.c.vocab = 248320; + d.x = 0x100000; + d.h2 = 0x200000; + d.logits = 0x300000; + d.xs = 0x400000; + d.words = 0x500000; + d.parts = 0x600000; + var contexts: [5]q.draft.Ctx = undefined; + var refs: [5]*q.draft.Ctx = undefined; + for (&contexts, &refs, 0..) |*ctx, *ref, i| { + ctx.* = .{ .ring = undefined, .wide = if (wide_even) i % 2 == 0 else i % 2 == 1 }; + ref.* = ctx; + } + var storage: [q.draft.frame.stagedLen(2)]u8 align(8) = undefined; + Trace.np = 0; + Trace.nf = 0; + Trace.nh = 0; + Trace.copies2d = 0; + try std.testing.expect(q.draft.frame.mixedHeadEligible(e.head, &refs)); + const all_rows = contexts.len * (d.c.block - 1); + const baseline = try q.draft.frame.logitsOf(&d, &refs, d.x, d.logits, all_rows); + try std.testing.expect(baseline == null); + try e.draws.topkRows(e.stream, baseline orelse d.logits, q.draft.frame.columns(baseline != null, d.c.vocab), @intCast(d.c.topk), d.parts, d.words, all_rows); + try std.testing.expectEqual(@as(usize, 1), Trace.nh); + try std.testing.expectEqual(@as(u32, 248320), Trace.heads[0].columns); + try std.testing.expectEqual(@as(u32, @intCast(all_rows)), Trace.heads[0].rows); + Trace.nh = 0; + try q.draft.frame.mixedHead(&d, &refs, &storage); + try std.testing.expectEqual(@as(usize, 5), Trace.np); + try std.testing.expectEqual(@as(usize, 5), Trace.nf); + try std.testing.expectEqual(@as(usize, 2), Trace.nh); + try std.testing.expectEqual(@as(usize, 2), Trace.copies2d); + const narrow_count: usize = if (wide_even) 2 else 3; + const wide_count = contexts.len - narrow_count; + const per = d.c.block - 1; + try std.testing.expectEqual(@as(u32, 98592), Trace.heads[0].columns); + try std.testing.expectEqual(@as(u32, @intCast(narrow_count * per)), Trace.heads[0].rows); + try std.testing.expectEqual(@as(u32, 248320), Trace.heads[1].columns); + try std.testing.expectEqual(@as(u32, @intCast(wide_count * per)), Trace.heads[1].rows); + const input_bytes = per * 256 * 2; + const word_bytes = per * 43 * 4; + const order = if (wide_even) [_]usize{ 1, 3, 0, 2, 4 } else [_]usize{ 0, 2, 4, 1, 3 }; + for (order, 0..) |original, i| { + const group_index = if (i < narrow_count) i else i - narrow_count; + try std.testing.expectEqual(d.x + original * input_bytes, Trace.gathered[i].src); + try std.testing.expectEqual(d.h2 + group_index * input_bytes, Trace.gathered[i].dst); + try std.testing.expectEqual(@as(usize, input_bytes), Trace.gathered[i].bytes); + try std.testing.expectEqual(d.words + group_index * word_bytes, Trace.fetched[i].src); + try std.testing.expectEqual(@intFromPtr(&storage) + q.draft.frame.words_at + original * word_bytes, Trace.fetched[i].dst); + try std.testing.expectEqual(@as(usize, word_bytes), Trace.fetched[i].bytes); + } + try std.testing.expectEqual(@as(usize, 98592), q.draft.frame.columns(true, 248320)); + try std.testing.expectEqual(@as(usize, 248320), q.draft.frame.columns(false, 248320)); + try std.testing.expectEqual(@as(u32, 248032), q.draft.frame.columnId(98304)); + try std.testing.expectEqual(@as(u32, 248319), q.draft.frame.columnId(98591)); +} + +test "Qwen CUDA contracts: mixed-width eligibility covers A4 and EXL3, not homogeneous batches" { + var narrow: q.draft.Ctx = .{ .ring = undefined }; + var wide: q.draft.Ctx = .{ .ring = undefined, .wide = true }; + var refs = [_]*q.draft.Ctx{ &narrow, &wide }; + var e: q.engine.Engine = undefined; + var a4 = weight(); + a4.n = 248320; + a4.npad = a4.n; + e.head = .{ .a4 = a4 }; + try std.testing.expect(q.draft.frame.mixedHeadEligible(e.head, &refs)); + wide.wide = false; + try std.testing.expect(!q.draft.frame.mixedHeadEligible(e.head, &refs)); + narrow.wide = true; + wide.wide = true; + try std.testing.expect(!q.draft.frame.mixedHeadEligible(e.head, &refs)); + + narrow.wide = false; + wide.wide = true; + const x3 = cuda.exl3; + const st = x3.strides(5120, 248320, 12, false); + const x3_head: x3.Weight = .{ .trellis = 0x1000, .suh = 0x2000, .svh = 0x3000, .k = 5120, .n = 248320, .halves = 12, .codebook = .mul1, .stride_k = st.k, .stride_nb = st.nb }; + e.head = .{ .x3 = x3_head }; + try std.testing.expect(q.draft.frame.mixedHeadEligible(e.head, &refs)); + wide.wide = false; + try std.testing.expect(!q.draft.frame.mixedHeadEligible(e.head, &refs)); + narrow.wide = true; + wide.wide = true; + try std.testing.expect(!q.draft.frame.mixedHeadEligible(e.head, &refs)); +} diff --git a/zig/src/families/qwen3_5/cuda.zig b/zig/src/families/qwen3_5/cuda.zig index 4d3375563b5..2f084806fae 100644 --- a/zig/src/families/qwen3_5/cuda.zig +++ b/zig/src/families/qwen3_5/cuda.zig @@ -48,6 +48,7 @@ test { _ = @import("cuda_draft_config.zig"); _ = @import("cuda_drafter_open.zig"); _ = draft; + _ = draft.spine; _ = @import("cuda_draft_absorb.zig"); _ = vision; _ = @import("cuda_vision_prompt.zig"); diff --git a/zig/src/families/qwen3_5/cuda_draft_frame.zig b/zig/src/families/qwen3_5/cuda_draft_frame.zig index efd48d89744..a654260a75f 100644 --- a/zig/src/families/qwen3_5/cuda_draft_frame.zig +++ b/zig/src/families/qwen3_5/cuda_draft_frame.zig @@ -91,13 +91,18 @@ pub fn forward(d: anytype, items: []const dr.Hold, contexts: []const *draft.Ctx) try e.d.check(e.d.api.cuMemcpyHtoDAsync_v2(d.ids, st.ptr, B * 4, e.stream.handle), "cuMemcpyHtoDAsync"); try e.d.check(e.d.api.cuMemcpyHtoDAsync_v2(d.segments, st.ptr + segments_at, items.len * @sizeOf(Segment), e.stream.handle), "cuMemcpyHtoDAsync"); const rows = items.len * (c.block - 1); - const spanned = try draft.graphs.hold(d, items.len, contexts, narrow(contexts), kernels); - try e.d.check(e.d.api.cuMemcpyDtoHAsync_v2(st.ptr + words_at, d.words, rows * lp_words * 4, e.stream.handle), "cuMemcpyDtoHAsync"); + const mixed = mixedHeadEligible(e.head, contexts); + // The graph key does not include the mixed-width row mask; mixed batches must run eagerly. + const spanned = if (mixed) try kernels(d, items.len, contexts) else try draft.graphs.hold(d, items.len, contexts, narrow(contexts), kernels); + if (!mixed) try e.d.check(e.d.api.cuMemcpyDtoHAsync_v2(st.ptr + words_at, d.words, rows * lp_words * 4, e.stream.handle), "cuMemcpyDtoHAsync"); try e.d.check(e.d.api.cuMemcpyDtoHAsync_v2(st.ptr + hp_at, d.hp, rows * c.rank * 2, e.stream.handle), "cuMemcpyDtoHAsync"); try e.stream.synchronize(); - if (spanned != null) for (0..rows) |r| { - const w = std.mem.bytesAsSlice(u32, st[words_at + r * lp_words * 4 ..][0 .. lp_words * 4]); - for (w[2..][0..c.topk]) |*id| id.* = columnId(id.*); + if (spanned != null or mixed) for (contexts, 0..) |ctx, i| if (spanned != null or !ctx.wide) { + for (0..c.block - 1) |r| { + const row = i * (c.block - 1) + r; + const w = std.mem.bytesAsSlice(u32, st[words_at + row * lp_words * 4 ..][0 .. lp_words * 4]); + for (w[2..][0..c.topk]) |*id| id.* = columnId(id.*); + } }; try publish(d, items, contexts); } @@ -133,12 +138,203 @@ fn kernels(d: anytype, streams: usize, contexts: []const *draft.Ctx) !?u64 { masked = d.h2; } try d.norm(masked, d.w.final_norm, d.x, rows); - const spanned = try logitsOf(d, contexts, d.x, d.logits, rows); - try e.draws.topkRows(e.stream, spanned orelse d.logits, if (spanned != null) span_width else c.vocab, @intCast(c.topk), d.parts, d.words, rows); + const mixed = mixedHeadEligible(e.head, contexts); + const spanned = if (mixed) blk: { + try mixedHead(d, contexts, d.staged.bytes); + break :blk null; + } else try logitsOf(d, contexts, d.x, d.logits, rows); + if (!mixed) try e.draws.topkRows(e.stream, spanned orelse d.logits, if (spanned != null) span_width else c.vocab, @intCast(c.topk), d.parts, d.words, rows); try d.proj(d.w.selector, d.x, d.hp, rows); return spanned; } +/// Mixed contexts use the same head-width class as an otherwise identical homogeneous frame. +pub fn mixedHeadEligible(h: layers.Proj, contexts: []const *draft.Ctx) bool { + const supported = switch (h) { + .a4 => |q| q.n == spans[1][1] and q.k % 64 == 0, + .x3 => |q| q.n == spans[1][1] and q.k % 128 == 0, + .an, .ql, .bf => false, + }; + if (!supported) return false; + var wide = false; + var has_narrow = false; + for (contexts) |ctx| if (ctx.wide) { + wide = true; + } else { + has_narrow = true; + }; + return wide and has_narrow; +} + +/// Stream indices in their original order for one vocabulary-width class. +pub fn headGroup(contexts: []const *draft.Ctx, wide: bool, out: *[max_streams]usize) []const usize { + var n: usize = 0; + for (contexts, 0..) |ctx, i| if (ctx.wide == wide) { + out[n] = i; + n += 1; + }; + return out[0..n]; +} + +/// Rebuild affine-4 group sums when a frame compacts rows; EXL3 projections do not consume `xs`. +pub fn rebuildProjectionSums(d: anytype, x: u64, rows: usize) !void { + switch (d.e.head) { + .a4 => {}, + else => return, + } + const k = d.c.hidden; + try d.e.run(d.e.fns.sums, .{ rows, (k / 64 + 63) / 64, 1 }, .{ 64, 1, 1 }, .{ x, d.xs, @as(c_int, @intCast(k)), @as(u64, 0) }); +} + +/// Project and pick each width class separately, returning words to their original staging rows. +pub fn mixedHead(d: anytype, contexts: []const *draft.Ctx, st: []u8) !void { + const e = d.e; + const c = d.c; + const per = c.block - 1; + const input_bytes = per * c.hidden * 2; + const word_bytes = per * lp_words * 4; + for ([_]bool{ false, true }) |wide| { + var indices: [max_streams]usize = undefined; + const group = headGroup(contexts, wide, &indices); + for (group, 0..) |i, at| try e.d.check(e.d.api.cuMemcpyDtoDAsync_v2(d.h2 + at * input_bytes, d.x + i * input_bytes, input_bytes, e.stream.handle), "cuMemcpyDtoDAsync"); + const rows = group.len * per; + try rebuildProjectionSums(d, d.h2, rows); + const spanned = if (wide) try full(d, d.h2, d.logits, rows) else try head(d, d.h2, d.logits, rows); + try e.draws.topkRows(e.stream, spanned orelse d.logits, if (spanned != null) span_width else c.vocab, @intCast(c.topk), d.parts, d.words, rows); + for (group, 0..) |i, at| try e.d.check(e.d.api.cuMemcpyDtoHAsync_v2(st.ptr + words_at + i * word_bytes, d.words + at * word_bytes, word_bytes, e.stream.handle), "cuMemcpyDtoHAsync"); + } +} + +test "DFlash mixed EXL3 head projects both spans and restores reversed stream order" { + const Trace = struct { + const Copy = struct { dst: u64, src: u64, bytes: usize }; + const Projection = struct { n: usize, k: usize, rows: usize, x: u64, out: u64 }; + const Topk = struct { logits: u64, columns: usize, rows: usize, out: u64 }; + var device: [2]Copy = undefined; + var device_count: usize = 0; + var host: [2]Copy = undefined; + var host_count: usize = 0; + var projections: [3]Projection = undefined; + var projection_count: usize = 0; + var topks: [2]Topk = undefined; + var topk_count: usize = 0; + var copies2d: usize = 0; + + fn copyDevice(dst: u64, src: u64, bytes: usize, _: cuda.abi.Stream) callconv(.c) cuda.abi.Result { + device[device_count] = .{ .dst = dst, .src = src, .bytes = bytes }; + device_count += 1; + return cuda.abi.success; + } + fn copyHost(dst: ?*anyopaque, src: u64, bytes: usize, _: cuda.abi.Stream) callconv(.c) cuda.abi.Result { + host[host_count] = .{ .dst = @intFromPtr(dst.?), .src = src, .bytes = bytes }; + host_count += 1; + return cuda.abi.success; + } + fn copy2d(_: *const cuda.abi.Memcpy2D, _: cuda.abi.Stream) callconv(.c) cuda.abi.Result { + copies2d += 1; + return cuda.abi.success; + } + }; + const Draws = struct { + fn topkRows(_: *@This(), _: cuda.Stream, logits: u64, column_count: usize, _: u8, _: u64, out: u64, rows: usize) !void { + Trace.topks[Trace.topk_count] = .{ .logits = logits, .columns = column_count, .rows = rows, .out = out }; + Trace.topk_count += 1; + } + }; + const E = struct { + d: *cuda.Driver, + stream: cuda.Stream, + head: layers.Proj, + affine: struct { pdl: bool }, + fns: struct { sums: cuda.Function }, + draws: Draws, + + pub fn run(_: *@This(), _: cuda.Function, _: [3]usize, _: [3]usize, _: anytype) !void {} + + pub fn projSums(_: *@This(), l: layers.Proj, x: u64, _: u64, out: u64, rows: usize, _: bool, _: u64) !void { + const q = switch (l) { + .x3 => |weight| weight, + else => unreachable, + }; + Trace.projections[Trace.projection_count] = .{ .n = q.n, .k = q.k, .rows = rows, .x = x, .out = out }; + Trace.projection_count += 1; + } + + pub fn projManySums(_: *@This(), _: []const layers.Proj, _: u64, _: u64, _: []const u64, _: usize, _: bool, _: u64) !void {} + }; + const D = struct { + e: *E, + c: struct { block: usize, hidden: usize, vocab: usize, topk: usize }, + x: u64, + h2: u64, + logits: u64, + xs: u64, + parts: u64, + words: u64, + }; + var driver: cuda.Driver = undefined; + driver.api.cuMemcpyDtoDAsync_v2 = Trace.copyDevice; + driver.api.cuMemcpyDtoHAsync_v2 = Trace.copyHost; + driver.api.cuMemcpy2DAsync_v2 = Trace.copy2d; + const q = cuda.exl3; + const st = q.strides(5120, 248320, 12, false); + const weight: q.Weight = .{ .trellis = 0x8000, .suh = 0x9000, .svh = 0xa000, .k = 5120, .n = 248320, .halves = 12, .codebook = .mul1, .stride_k = st.k, .stride_nb = st.nb }; + var e = E{ .d = &driver, .stream = .{ .d = &driver, .handle = null }, .head = .{ .x3 = weight }, .affine = .{ .pdl = false }, .fns = .{ .sums = .{ .d = &driver, .handle = null } }, .draws = .{} }; + const d = D{ .e = &e, .c = .{ .block = 8, .hidden = 64, .vocab = 248320, .topk = 2 }, .x = 0x100000, .h2 = 0x200000, .logits = 0x300000, .xs = 0x400000, .parts = 0x500000, .words = 0x600000 }; + var contexts: [2]draft.Ctx = .{ .{ .ring = undefined, .wide = true }, .{ .ring = undefined } }; + const refs = [_]*draft.Ctx{ &contexts[0], &contexts[1] }; + var storage: [stagedLen(2)]u8 align(8) = undefined; + Trace.device_count = 0; + Trace.host_count = 0; + Trace.projection_count = 0; + Trace.topk_count = 0; + Trace.copies2d = 0; + try mixedHead(&d, &refs, &storage); + + const rows = d.c.block - 1; + const tail_n = spans[1][1] - x3_tail_at; + const span_logits = d.logits + rows * (spans[0][1] + tail_n) * 2; + const input_bytes = rows * d.c.hidden * 2; + const word_bytes = rows * 43 * 4; + const views = try x3Views(weight); + try std.testing.expectEqual(@as(usize, 2), Trace.device_count); + try std.testing.expectEqual(@as(usize, 2), Trace.host_count); + try std.testing.expectEqual(@as(usize, 3), Trace.projection_count); + try std.testing.expectEqual(@as(usize, 2), Trace.topk_count); + try std.testing.expectEqual(@as(usize, 2), Trace.copies2d); + try std.testing.expectEqual(spans[0][1], Trace.projections[0].n); + try std.testing.expectEqual(views.first.k, Trace.projections[0].k); + try std.testing.expectEqual(views.tail.n, Trace.projections[1].n); + try std.testing.expectEqual(views.tail.k, Trace.projections[1].k); + try std.testing.expectEqual(weight.n, Trace.projections[2].n); + try std.testing.expectEqual(d.logits, Trace.projections[0].out); + try std.testing.expectEqual(d.logits + rows * spans[0][1] * 2, Trace.projections[1].out); + try std.testing.expectEqual(d.logits, Trace.projections[2].out); + for (Trace.projections) |projection| { + try std.testing.expectEqual(rows, projection.rows); + try std.testing.expectEqual(d.h2, projection.x); + } + try std.testing.expectEqual(span_logits, Trace.topks[0].logits); + try std.testing.expectEqual(span_width, Trace.topks[0].columns); + try std.testing.expectEqual(d.logits, Trace.topks[1].logits); + try std.testing.expectEqual(d.c.vocab, Trace.topks[1].columns); + for (Trace.topks) |topk| { + try std.testing.expectEqual(rows, topk.rows); + try std.testing.expectEqual(d.words, topk.out); + } + try std.testing.expectEqual(d.h2, Trace.device[0].dst); + try std.testing.expectEqual(d.x + input_bytes, Trace.device[0].src); + try std.testing.expectEqual(input_bytes, Trace.device[0].bytes); + try std.testing.expectEqual(d.h2, Trace.device[1].dst); + try std.testing.expectEqual(d.x, Trace.device[1].src); + try std.testing.expectEqual(input_bytes, Trace.device[1].bytes); + for ([_]usize{ 1, 0 }, 0..) |stream, group| { + try std.testing.expectEqual(d.words, Trace.host[group].src); + try std.testing.expectEqual(@intFromPtr(&storage) + words_at + stream * word_bytes, Trace.host[group].dst); + try std.testing.expectEqual(word_bytes, Trace.host[group].bytes); + } +} + /// A lane stream's prompt and reply tokens since the last scan: one outside the spans marks the stream wide. pub fn scan(ctx: *draft.Ctx, toks: []const u32) void { if (!ctx.wide) for (toks[@min(ctx.scanned, toks.len)..]) |t| if (t >= spans[0][1] and t < spans[1][0]) { diff --git a/zig/src/families/qwen3_5/cuda_dspine_frame.zig b/zig/src/families/qwen3_5/cuda_dspine_frame.zig index 6ebb3111b36..5845c0747ce 100644 --- a/zig/src/families/qwen3_5/cuda_dspine_frame.zig +++ b/zig/src/families/qwen3_5/cuda_dspine_frame.zig @@ -4,6 +4,7 @@ const cuda = @import("cuda"); const dr = @import("lanes").drafter; const draft = @import("cuda_draft.zig"); const frame = @import("cuda_draft_frame.zig"); +const layer_mod = @import("cuda_layers.zig"); const bridge = @import("cuda_dspine_weights.zig"); const Config = @import("cuda_draft_config.zig").Config; @@ -89,22 +90,474 @@ fn layers(d: anytype, s: *Spine, b: Bufs, B: usize, rows: usize) !void { } /// The second pass: each head row's candidates scored after each of the row before's (its anchor for the first). -fn table(d: anytype, s: *Spine, b: Bufs, rows: usize, logits: u64, spanned: bool) !void { +const TableRows = struct { ids: u64, raw: u64, rms: u64, q: u64, words: u64, out: u64 }; + +fn table(d: anytype, s: *Spine, b: Bufs, rows: usize, logits: u64, spanned: bool, input: TableRows, logits_offset: usize) !void { const c = d.c; const e = d.e; const w = &s.w; const P = rows * c.topk; const sp = frame.split(spanned); const sqrt_c: f32 = @floatCast(@sqrt(@as(f64, @floatFromInt(c.code)))); - try e.run(s.fns.senders, .{ rows, 1, 1 }, .{ 32, 1, 1 }, .{ d.words, d.ids, b.sids, int(c.topk), int(c.block), int(lp_words), sp[0], sp[1] }); + try e.run(s.fns.senders, .{ rows, 1, 1 }, .{ 32, 1, 1 }, .{ input.words, input.ids, b.sids, int(c.topk), int(c.block), int(lp_words), sp[0], sp[1] }); try e.run(s.fns.bridge_code, .{ P, 1, 1 }, .{ 256, 1, 1 }, .{ @as(u64, 0), w.codebook, b.sids, b.code, int(c.code), int(1), sqrt_c, c.bridge_eps }); try d.proj(w.pv, b.code, b.sv, P); - try e.run(s.fns.sender_message, .{ P, 1, 1 }, .{ 256, 1, 1 }, .{ b.q, b.sv, w.gate_b, b.msg, int(c.rank), int(c.topk), int(c.block) }); + try e.run(s.fns.sender_message, .{ P, 1, 1 }, .{ 256, 1, 1 }, .{ input.q, b.sv, w.gate_b, b.msg, int(c.rank), int(c.topk), int(c.block) }); try d.proj(w.write[c.layers - 1], b.msg, b.wm, P); const cols = frame.columns(spanned, c.vocab); - try e.run(s.fns.table, .{ P, 1, 1 }, .{ 256, 1, 1 }, .{ d.xin, b.rms, b.msg, b.wm, w.tg, logits, d.words, b.table, int(c.hidden), int(c.rank), int(c.topk), int(c.block), int(rows), int(cols), int(lp_words), sp[0], sp[1], c.eps }); + try e.run(s.fns.table, .{ P, 1, 1 }, .{ 256, 1, 1 }, .{ input.raw, input.rms, b.msg, b.wm, w.tg, logits, input.words, input.out, int(c.hidden), int(c.rank), int(c.topk), int(c.block), int(logits_offset), int(cols), int(lp_words), sp[0], sp[1], c.eps }); +} + +const MixedScratch = struct { ids: u64, raw: u64, rms: u64, q: u64, words: u64, table: u64 }; + +fn scratchAt(at: *usize, size: usize) !usize { + const start = (try std.math.add(usize, at.*, 255)) & ~@as(usize, 255); + at.* = try std.math.add(usize, start, size); + return start; +} + +fn mixedScratch(b: Bufs, c: Config, streams: usize) !MixedScratch { + const rows = try std.math.mul(usize, streams, c.block - 1); + const blocks = try std.math.mul(usize, streams, c.block); + var at: usize = 0; + const ids = try scratchAt(&at, try std.math.mul(usize, blocks, 4)); + const raw = try scratchAt(&at, try std.math.mul(usize, try std.math.mul(usize, blocks, c.hidden), 2)); + const rms = try scratchAt(&at, try std.math.mul(usize, blocks, 4)); + const q = try scratchAt(&at, try std.math.mul(usize, try std.math.mul(usize, blocks, c.rank), 2)); + const words = try scratchAt(&at, try std.math.mul(usize, try std.math.mul(usize, rows, lp_words), 4)); + const table_bytes = try std.math.mul(usize, try std.math.mul(usize, try std.math.mul(usize, rows, c.topk), c.topk), 4); + const table_offset = try scratchAt(&at, table_bytes); + const capacity = try std.math.mul(usize, try std.math.mul(usize, rows, c.vocab), 4); + if (at > capacity or b.end - b.logits < capacity) return error.BadDraftFrame; + return .{ .ids = b.logits + ids, .raw = b.logits + raw, .rms = b.logits + rms, .q = b.logits + q, .words = b.logits + words, .table = b.logits + table_offset }; +} + +fn groupLogits(d: anytype, contexts: []const *draft.Ctx, group: []const usize, source: u64) !?u64 { + const c = d.c; + const per = c.block - 1; + const row_bytes = c.hidden * 2; + const stream_bytes = per * row_bytes; + var refs: [frame.max_streams]*draft.Ctx = undefined; + for (group, 0..) |stream, at| { + refs[at] = contexts[stream]; + try d.e.d.check(d.e.d.api.cuMemcpyDtoDAsync_v2(d.h2 + at * stream_bytes, source + stream * stream_bytes, stream_bytes, d.e.stream.handle), "cuMemcpyDtoDAsync"); + } + try frame.rebuildProjectionSums(d, d.h2, group.len * per); + return frame.logitsOf(d, refs[0..group.len], d.h2, d.logits, group.len * per); +} + +fn packTableRows(d: anytype, b: Bufs, scratch: MixedScratch, group: []const usize) !TableRows { + const c = d.c; + const id_bytes = c.block * 4; + const raw_bytes = c.block * c.hidden * 2; + const rms_bytes = c.block * 4; + const q_bytes = c.block * c.rank * 2; + for (group, 0..) |stream, at| { + try d.e.d.check(d.e.d.api.cuMemcpyDtoDAsync_v2(scratch.ids + at * id_bytes, d.ids + stream * id_bytes, id_bytes, d.e.stream.handle), "cuMemcpyDtoDAsync"); + try d.e.d.check(d.e.d.api.cuMemcpyDtoDAsync_v2(scratch.raw + at * raw_bytes, d.xin + stream * raw_bytes, raw_bytes, d.e.stream.handle), "cuMemcpyDtoDAsync"); + try d.e.d.check(d.e.d.api.cuMemcpyDtoDAsync_v2(scratch.rms + at * rms_bytes, b.rms + stream * rms_bytes, rms_bytes, d.e.stream.handle), "cuMemcpyDtoDAsync"); + try d.e.d.check(d.e.d.api.cuMemcpyDtoDAsync_v2(scratch.q + at * q_bytes, b.q + stream * q_bytes, q_bytes, d.e.stream.handle), "cuMemcpyDtoDAsync"); + } + return .{ .ids = scratch.ids, .raw = scratch.raw, .rms = scratch.rms, .q = scratch.q, .words = d.words, .out = b.table }; +} + +/// Run the head and second pass by width class, then restore every row to its original stream slot. +fn mixedHead(d: anytype, s: *Spine, b: Bufs, contexts: []const *draft.Ctx, rows: usize) !void { + const c = d.c; + const e = d.e; + const per = c.block - 1; + const scratch = try mixedScratch(b, c, contexts.len); + var group_start: usize = 0; + for ([_]bool{ false, true }) |wide| { + var indices: [frame.max_streams]usize = undefined; + const group = frame.headGroup(contexts, wide, &indices); + if (group.len == 0) continue; + const group_rows = group.len * per; + const first = try groupLogits(d, contexts, group, b.hx); + try e.draws.topkRows(e.stream, first orelse d.logits, frame.columns(first != null, c.vocab), @intCast(c.topk), d.parts, d.words, group_rows); + const input = try packTableRows(d, b, scratch, group); + const second = try groupLogits(d, contexts, group, b.hx + rows * c.hidden * 2); + // Each group's second-plane logits start at row zero in the compact projection buffer. + try table(d, s, b, group_rows, second orelse d.logits, second != null, input, 0); + const row_at = group_start * per; + try e.d.check(e.d.api.cuMemcpyDtoDAsync_v2(scratch.words + row_at * lp_words * 4, d.words, group_rows * lp_words * 4, e.stream.handle), "cuMemcpyDtoDAsync"); + try e.d.check(e.d.api.cuMemcpyDtoDAsync_v2(scratch.table + row_at * c.topk * c.topk * 4, b.table, group_rows * c.topk * c.topk * 4, e.stream.handle), "cuMemcpyDtoDAsync"); + group_start += group.len; + } + group_start = 0; + for ([_]bool{ false, true }) |wide| { + var indices: [frame.max_streams]usize = undefined; + const group = frame.headGroup(contexts, wide, &indices); + for (group, 0..) |stream, at| { + const source_row = (group_start + at) * per; + const target_row = stream * per; + try e.d.check(e.d.api.cuMemcpyDtoDAsync_v2(d.words + target_row * lp_words * 4, scratch.words + source_row * lp_words * 4, per * lp_words * 4, e.stream.handle), "cuMemcpyDtoDAsync"); + try e.d.check(e.d.api.cuMemcpyDtoDAsync_v2(b.table + target_row * c.topk * c.topk * 4, scratch.table + source_row * c.topk * c.topk * 4, per * c.topk * c.topk * 4, e.stream.handle), "cuMemcpyDtoDAsync"); + } + group_start += group.len; + } } +test "DSpine mixed width: both head passes, table groups, and scatter keep stream rows" { + const Trace = struct { + const Copy = struct { dst: u64, src: u64, bytes: usize }; + const Projection = struct { columns: usize, rows: usize, x: u64, out: u64 }; + const Sum = struct { x: u64, xs: u64, k: c_int, rows: usize, grid: [3]usize }; + const Event = enum { compact, sums, projection }; + const Topk = struct { logits: u64, columns: usize, rows: usize, out: u64 }; + const Table = struct { logits: u64, words: u64, out: u64, grid: usize, offset: c_int, columns: c_int }; + var copies: [48]Copy = undefined; + var copy_count: usize = 0; + var projections: [8]Projection = undefined; + var projection_count: usize = 0; + var many_projection_calls: usize = 0; + var sums: [4]Sum = undefined; + var sum_count: usize = 0; + var events: [32]Event = undefined; + var event_count: usize = 0; + var compact_base: u64 = 0; + var compact_stream_bytes: usize = 0; + var topks: [4]Topk = undefined; + var topk_count: usize = 0; + var tables: [4]Table = undefined; + var table_count: usize = 0; + fn copy(dst: u64, src: u64, copy_bytes: usize, _: cuda.abi.Stream) callconv(.c) cuda.abi.Result { + copies[copy_count] = .{ .dst = dst, .src = src, .bytes = copy_bytes }; + copy_count += 1; + if (dst >= compact_base and dst < compact_base + 2 * compact_stream_bytes and copy_bytes == compact_stream_bytes) record(.compact); + return cuda.abi.success; + } + fn copy2d(_: *const cuda.abi.Memcpy2D, _: cuda.abi.Stream) callconv(.c) cuda.abi.Result { + return cuda.abi.success; + } + fn record(event: Event) void { + events[event_count] = event; + event_count += 1; + } + fn projection(l: layer_mod.Proj, x: u64, out: u64, rows: usize) void { + const columns = switch (l) { + .a4 => |q| q.n, + .x3 => |q| q.n, + else => unreachable, + }; + projections[projection_count] = .{ .columns = columns, .rows = rows, .x = x, .out = out }; + projection_count += 1; + record(.projection); + } + }; + const Draws = struct { + fn topkRows(_: *@This(), _: cuda.Stream, logits: u64, columns: usize, _: u8, _: u64, out: u64, rows: usize) !void { + Trace.topks[Trace.topk_count] = .{ .logits = logits, .columns = columns, .rows = rows, .out = out }; + Trace.topk_count += 1; + } + }; + const E = struct { + d: *cuda.Driver, + stream: cuda.Stream, + head: layer_mod.Proj, + affine: struct { pdl: bool }, + fns: struct { sums: cuda.Function }, + draws: Draws, + pub fn projSums(_: *@This(), l: layer_mod.Proj, x: u64, _: u64, out: u64, rows: usize, _: bool, _: u64) !void { + Trace.projection(l, x, out, rows); + } + pub fn projManySums(_: *@This(), ls: []const layer_mod.Proj, x: u64, _: u64, outs: []const u64, rows: usize, _: bool, _: u64) !void { + Trace.many_projection_calls += 1; + for (ls, outs) |l, out| Trace.projection(l, x, out, rows); + } + pub fn run(_: *@This(), f: cuda.Function, grid: [3]usize, _: [3]usize, args: anytype) !void { + if (f.handle) |handle| if (@intFromPtr(handle) == 9) { + Trace.sums[Trace.sum_count] = .{ .x = args[0], .xs = args[1], .k = @intCast(args[2]), .rows = grid[0], .grid = grid }; + Trace.sum_count += 1; + Trace.record(.sums); + return; + }; + if (comptime @typeInfo(@TypeOf(args)).@"struct".field_names.len >= 14) { + if (f.handle) |handle| if (@intFromPtr(handle) == 7) { + Trace.tables[Trace.table_count] = .{ + .logits = args[5], + .words = args[6], + .out = args[7], + .grid = grid[0], + .offset = args[12], + .columns = args[13], + }; + Trace.table_count += 1; + }; + } + } + }; + const D = struct { + e: *E, + c: Config, + h2: u64, + logits: u64, + xs: u64, + parts: u64, + words: u64, + ids: u64, + xin: u64, + fn proj(_: *const @This(), _: cuda.qlinear.Affine4, _: u64, _: u64, _: usize) !void {} + }; + const c: Config = .{ + .hidden = 128, + .intermediate = 128, + .layers = 1, + .vocab = 248320, + .heads = 1, + .kv_heads = 1, + .head_dim = 128, + .block = 16, + .mask = 0, + .window = 16, + .group = 16, + .rank = 8, + .topk = 2, + .eps = 1e-6, + .theta = 1, + .taps = @splat(0), + .n_taps = 1, + .kind = .dspine, + }; + var driver: cuda.Driver = undefined; + driver.api.cuMemcpyDtoDAsync_v2 = Trace.copy; + driver.api.cuMemcpy2DAsync_v2 = Trace.copy2d; + var e = E{ .d = &driver, .stream = .{ .d = &driver, .handle = null }, .head = undefined, .affine = .{ .pdl = true }, .fns = .{ .sums = .{ .d = &driver, .handle = @ptrFromInt(9) } }, .draws = .{} }; + const head: cuda.qlinear.Affine4 = .{ .w = 1, .s = 2, .b = 3, .n = c.vocab, .k = c.hidden, .npad = c.vocab }; + e.head = .{ .a4 = head }; + const function = struct { + fn get(d: *cuda.Driver, id: usize) cuda.Function { + return .{ .d = d, .handle = @ptrFromInt(id) }; + } + }.get; + var s: Spine = undefined; + s.fns = .{ + .bridge_read = function(&driver, 1), + .bridge_code = function(&driver, 2), + .bridge_message = function(&driver, 3), + .bridge_write = function(&driver, 4), + .senders = function(&driver, 5), + .sender_message = function(&driver, 6), + .table = function(&driver, 7), + .transpose = function(&driver, 8), + }; + s.w.pv = head; + s.w.write[0] = head; + s.w.codebook = 0x900000; + s.w.gate_b = 0xa00000; + s.w.tg = 0xb00000; + const rows = 4 * (c.block - 1); + const capacity = rows * c.vocab * 4; + // Draft.layout allocates d.logits before its DSpine `ds` region, where b.logits lives. + const projection_base: u64 = 0x1000000; + const projection_capacity = 4 * c.block * c.vocab * 2; + const base: u64 = 0x3000000; + const b: Bufs = .{ + .rms = 0x200000, + .p = 0x210000, + .code = 0x220000, + .q = 0x230000, + .sv = 0x240000, + .msg = 0x250000, + .wm = 0x260000, + .hx = 0x270000, + .logits = base, + .sids = base + capacity, + .table = base + capacity + 0x10000, + .end = base + capacity + 0x20000, + }; + const d = D{ .e = &e, .c = c, .h2 = 0x300000, .logits = projection_base, .xs = 0x310000, .parts = 0x320000, .words = 0x330000, .ids = 0x340000, .xin = 0x350000 }; + Trace.compact_base = d.h2; + Trace.compact_stream_bytes = (c.block - 1) * c.hidden * 2; + const scratch = try mixedScratch(b, c, 4); + const projection_end = d.logits + projection_capacity; + const scratch_end = b.logits + capacity; + // `d.logits` is the earlier Draft.layout allocation; mixed scratch occupies `b.logits` in `ds`. + try std.testing.expect(projection_end <= b.logits); + const scratch_sizes = [_]usize{ + 4 * c.block * 4, + 4 * c.block * c.hidden * 2, + 4 * c.block * 4, + 4 * c.block * c.rank * 2, + rows * lp_words * 4, + rows * c.topk * c.topk * 4, + }; + const scratch_starts = [_]u64{ scratch.ids, scratch.raw, scratch.rms, scratch.q, scratch.words, scratch.table }; + for (scratch_starts, scratch_sizes) |start, size| { + try std.testing.expect(start >= b.logits); + try std.testing.expect(start + size <= scratch_end); + } + var contexts: [4]draft.Ctx = undefined; + var refs: [4]*draft.Ctx = undefined; + for (&contexts, &refs, 0..) |*ctx, *ref, i| { + ctx.* = .{ .ring = undefined, .wide = i % 2 == 1 }; + ref.* = ctx; + } + Trace.copy_count = 0; + Trace.projection_count = 0; + Trace.many_projection_calls = 0; + Trace.sum_count = 0; + Trace.event_count = 0; + Trace.topk_count = 0; + Trace.table_count = 0; + try mixedHead(&d, &s, b, &refs, rows); + const per = c.block - 1; + const group_rows = 2 * per; + const stream_bytes = per * c.hidden * 2; + const narrow_logits = d.logits + group_rows * (98304 + 320) * 2; + try std.testing.expectEqual(@as(usize, 36), Trace.copy_count); + const input_groups = [_]struct { start: usize, streams: [2]usize }{ + .{ .start = 2, .streams = .{ 0, 2 } }, + .{ .start = 16, .streams = .{ 1, 3 } }, + }; + const input_sources = [_]u64{ d.ids, d.xin, b.rms, b.q }; + const input_targets = [_]u64{ scratch.ids, scratch.raw, scratch.rms, scratch.q }; + const input_sizes = [_]usize{ c.block * 4, c.block * c.hidden * 2, c.block * 4, c.block * c.rank * 2 }; + const compact_groups = [_]struct { start: usize, source: u64, streams: [2]usize }{ + .{ .start = 0, .source = b.hx, .streams = .{ 0, 2 } }, + .{ .start = 10, .source = b.hx + rows * c.hidden * 2, .streams = .{ 0, 2 } }, + .{ .start = 14, .source = b.hx, .streams = .{ 1, 3 } }, + .{ .start = 24, .source = b.hx + rows * c.hidden * 2, .streams = .{ 1, 3 } }, + }; + for (compact_groups) |group| { + for (group.streams, 0..) |stream, at| { + const copy = Trace.copies[group.start + at]; + try std.testing.expectEqual(d.h2 + at * stream_bytes, copy.dst); + try std.testing.expectEqual(group.source + stream * stream_bytes, copy.src); + try std.testing.expectEqual(stream_bytes, copy.bytes); + } + } + for (input_groups) |group| { + for (group.streams, 0..) |stream, at| { + for (input_sources, input_targets, input_sizes, 0..) |src, dst, copy_len, plane| { + const copy = Trace.copies[group.start + at * 4 + plane]; + try std.testing.expectEqual(dst + at * copy_len, copy.dst); + try std.testing.expectEqual(src + stream * copy_len, copy.src); + try std.testing.expectEqual(copy_len, copy.bytes); + } + } + } + try std.testing.expectEqual(@as(usize, 6), Trace.projection_count); + try std.testing.expectEqual(@as(usize, 2), Trace.many_projection_calls); + try std.testing.expectEqual(@as(usize, 4), Trace.sum_count); + for (Trace.sums) |sum| { + try std.testing.expectEqual(d.h2, sum.x); + try std.testing.expectEqual(d.xs, sum.xs); + try std.testing.expectEqual(@as(c_int, @intCast(c.hidden)), sum.k); + try std.testing.expectEqual(group_rows, sum.rows); + try std.testing.expectEqual([_]usize{ group_rows, 1, 1 }, sum.grid); + } + const expected_events = [_]Trace.Event{ + .compact, .compact, .sums, .projection, .projection, + .compact, .compact, .sums, .projection, .projection, + .compact, .compact, .sums, .projection, .compact, + .compact, .sums, .projection, + }; + try std.testing.expectEqual(expected_events.len, Trace.event_count); + try std.testing.expectEqualSlices(Trace.Event, &expected_events, Trace.events[0..Trace.event_count]); + try std.testing.expectEqual(@as(usize, 2), Trace.topk_count); + try std.testing.expectEqual(@as(usize, 2), Trace.table_count); + for (Trace.projections[0..Trace.projection_count], [_]usize{ 98304, 320, 98304, 320, c.vocab, c.vocab }) |p, columns| { + try std.testing.expectEqual(columns, p.columns); + try std.testing.expectEqual(group_rows, p.rows); + try std.testing.expectEqual(d.h2, p.x); + const bytes_written = p.rows * p.columns * 2; + try std.testing.expect(p.out >= d.logits); + try std.testing.expect(p.out + bytes_written <= projection_end); + try std.testing.expect(p.out + bytes_written <= b.logits); + } + try std.testing.expectEqual(d.logits, Trace.projections[0].out); + try std.testing.expectEqual(d.logits + group_rows * 98304 * 2, Trace.projections[1].out); + for (Trace.topks[0..Trace.topk_count], [_]usize{ frame.columns(true, c.vocab), c.vocab }) |topk, columns| { + try std.testing.expectEqual(columns, topk.columns); + try std.testing.expectEqual(group_rows, topk.rows); + try std.testing.expectEqual(d.words, topk.out); + const bytes_read = topk.rows * topk.columns * 2; + try std.testing.expect(topk.logits >= d.logits); + try std.testing.expect(topk.logits + bytes_read <= projection_end); + try std.testing.expect(topk.logits + bytes_read <= b.logits); + } + try std.testing.expectEqual(narrow_logits, Trace.topks[0].logits); + try std.testing.expectEqual(d.logits, Trace.topks[1].logits); + for (Trace.tables[0..Trace.table_count], [_]usize{ frame.columns(true, c.vocab), c.vocab }) |call, columns| { + try std.testing.expectEqual(group_rows * c.topk, call.grid); + try std.testing.expectEqual(d.words, call.words); + try std.testing.expectEqual(b.table, call.out); + try std.testing.expectEqual(@as(c_int, 0), call.offset); + try std.testing.expectEqual(@as(c_int, @intCast(columns)), call.columns); + } + try std.testing.expectEqual(narrow_logits, Trace.tables[0].logits); + try std.testing.expectEqual(d.logits, Trace.tables[1].logits); + for ([_]usize{ 0, 2 }, 0..) |stream, at| { + for ([_]usize{ 0, 10 }, 0..) |copy_base, plane| { + const copy_at = copy_base + at; + const source = b.hx + plane * rows * c.hidden * 2 + stream * stream_bytes; + try std.testing.expectEqual(d.h2 + at * stream_bytes, Trace.copies[copy_at].dst); + try std.testing.expectEqual(source, Trace.copies[copy_at].src); + try std.testing.expectEqual(stream_bytes, Trace.copies[copy_at].bytes); + } + } + for ([_]usize{ 1, 3 }, 0..) |stream, at| { + for ([_]usize{ 14, 24 }, 0..) |copy_base, plane| { + const copy_at = copy_base + at; + const source = b.hx + plane * rows * c.hidden * 2 + stream * stream_bytes; + try std.testing.expectEqual(d.h2 + at * stream_bytes, Trace.copies[copy_at].dst); + try std.testing.expectEqual(source, Trace.copies[copy_at].src); + try std.testing.expectEqual(stream_bytes, Trace.copies[copy_at].bytes); + } + } + try std.testing.expectEqual(scratch.words, Trace.copies[12].dst); + try std.testing.expectEqual(d.words, Trace.copies[12].src); + try std.testing.expectEqual(group_rows * lp_words * 4, Trace.copies[12].bytes); + try std.testing.expectEqual(scratch.table, Trace.copies[13].dst); + try std.testing.expectEqual(b.table, Trace.copies[13].src); + try std.testing.expectEqual(group_rows * c.topk * c.topk * 4, Trace.copies[13].bytes); + const wide_row_at = group_rows; + try std.testing.expectEqual(scratch.words + wide_row_at * lp_words * 4, Trace.copies[26].dst); + try std.testing.expectEqual(d.words, Trace.copies[26].src); + try std.testing.expectEqual(scratch.table + wide_row_at * c.topk * c.topk * 4, Trace.copies[27].dst); + try std.testing.expectEqual(b.table, Trace.copies[27].src); + for ([_]usize{ 0, 2, 1, 3 }, 0..) |stream, at| { + const scatter_at = 28 + at * 2; + try std.testing.expectEqual(d.words + stream * per * lp_words * 4, Trace.copies[scatter_at].dst); + try std.testing.expectEqual(scratch.words + at * per * lp_words * 4, Trace.copies[scatter_at].src); + try std.testing.expectEqual(per * lp_words * 4, Trace.copies[scatter_at].bytes); + try std.testing.expectEqual(b.table + stream * per * c.topk * c.topk * 4, Trace.copies[scatter_at + 1].dst); + try std.testing.expectEqual(scratch.table + at * per * c.topk * c.topk * 4, Trace.copies[scatter_at + 1].src); + try std.testing.expectEqual(per * c.topk * c.topk * 4, Trace.copies[scatter_at + 1].bytes); + } + // EXL3 stages its tail through the same d.logits allocation; its ranges must stay clear of `ds` scratch too. + const x3 = cuda.exl3; + const x3_strides = x3.strides(c.hidden, c.vocab, 12, false); + const x3_weight: x3.Weight = .{ .trellis = 0xc00000, .suh = 0xd00000, .svh = 0xe00000, .k = c.hidden, .n = c.vocab, .halves = 12, .codebook = .mul1, .stride_k = x3_strides.k, .stride_nb = x3_strides.nb }; + e.head = .{ .x3 = x3_weight }; + Trace.copy_count = 0; + Trace.projection_count = 0; + Trace.topk_count = 0; + Trace.table_count = 0; + try mixedHead(&d, &s, b, &refs, rows); + const x3_views = try frame.x3Views(x3_weight); + const x3_columns = [_]usize{ 98304, x3_views.tail.n, 98304, x3_views.tail.n, c.vocab, c.vocab }; + try std.testing.expectEqual(@as(usize, 6), Trace.projection_count); + try std.testing.expectEqual(@as(usize, 2), Trace.topk_count); + try std.testing.expectEqual(@as(usize, 2), Trace.table_count); + for (Trace.projections[0..Trace.projection_count], x3_columns) |p, columns| { + try std.testing.expectEqual(columns, p.columns); + try std.testing.expectEqual(group_rows, p.rows); + const bytes_written = p.rows * p.columns * 2; + try std.testing.expect(p.out >= d.logits); + try std.testing.expect(p.out + bytes_written <= projection_end); + try std.testing.expect(p.out + bytes_written <= b.logits); + } + for (Trace.topks[0..Trace.topk_count], [_]usize{ frame.columns(true, c.vocab), c.vocab }) |topk, columns| { + const bytes_read = topk.rows * topk.columns * 2; + try std.testing.expectEqual(columns, topk.columns); + try std.testing.expectEqual(group_rows, topk.rows); + try std.testing.expect(topk.logits >= d.logits); + try std.testing.expect(topk.logits + bytes_read <= projection_end); + try std.testing.expect(topk.logits + bytes_read <= b.logits); + } +} /// One DSpine frame for `items`: block, bridge, head over the drafted rows and final_norm * raw rows, table, selection. pub fn forward(d: anytype, s: *Spine, items: []const dr.Hold, contexts: []const *draft.Ctx) !void { const c = d.c; @@ -123,16 +576,25 @@ pub fn forward(d: anytype, s: *Spine, items: []const dr.Hold, contexts: []const try e.d.check(e.d.api.cuMemcpyHtoDAsync_v2(d.segments, st.ptr + frame.segments_at, items.len * @sizeOf(frame.Segment), e.stream.handle), "cuMemcpyHtoDAsync"); try layers(d, s, b, B, rows); try e.run(e.fns.sums, .{ 2 * rows, (c.hidden / 64 + 63) / 64, 1 }, .{ 64, 1, 1 }, .{ b.hx, d.xs, int(c.hidden), @as(u64, 0) }); - const spanned = try frame.logitsOf(d, contexts, b.hx, b.logits, 2 * rows); - const logits = spanned orelse b.logits; - try e.draws.topkRows(e.stream, logits, frame.columns(spanned != null, c.vocab), @intCast(c.topk), d.parts, d.words, rows); - try table(d, s, b, rows, logits, spanned != null); + const mixed = frame.mixedHeadEligible(e.head, contexts); + var spanned: ?u64 = null; + if (mixed) { + try mixedHead(d, s, b, contexts, rows); + } else { + spanned = try frame.logitsOf(d, contexts, b.hx, b.logits, 2 * rows); + const logits = spanned orelse b.logits; + try e.draws.topkRows(e.stream, logits, frame.columns(spanned != null, c.vocab), @intCast(c.topk), d.parts, d.words, rows); + try table(d, s, b, rows, logits, spanned != null, .{ .ids = d.ids, .raw = d.xin, .rms = b.rms, .q = b.q, .words = d.words, .out = b.table }, rows); + } try e.d.check(e.d.api.cuMemcpyDtoHAsync_v2(st.ptr + frame.words_at, d.words, rows * lp_words * 4, e.stream.handle), "cuMemcpyDtoHAsync"); try e.d.check(e.d.api.cuMemcpyDtoHAsync_v2(st.ptr + frame.hp_at, b.table, rows * c.topk * c.topk * 4, e.stream.handle), "cuMemcpyDtoHAsync"); try e.stream.synchronize(); - for (0..rows) |r| { - const words = std.mem.bytesAsSlice(u32, st[frame.words_at + r * lp_words * 4 ..][0 .. lp_words * 4]); - for (words[2..][0..c.topk]) |*id| id.* = if (spanned != null) frame.columnId(id.*) else id.*; - } + for (contexts, 0..) |ctx, i| if (spanned != null or (mixed and !ctx.wide)) { + for (0..c.block - 1) |r| { + const row = i * (c.block - 1) + r; + const words = std.mem.bytesAsSlice(u32, st[frame.words_at + row * lp_words * 4 ..][0 .. lp_words * 4]); + for (words[2..][0..c.topk]) |*id| id.* = frame.columnId(id.*); + } + }; try frame.publish(d, items, contexts); }