diff --git a/CHANGELOG.md b/CHANGELOG.md index 219c86994a4..2d4dff7783f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,10 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased +- Qwen3.5 on CUDA: MTP admission charges the target tap ring once per stream, and native inference reserves only its 64-row recurrent log unless slide learning needs rollback snapshots, so the admission bound matches what the engine allocates (fixes #5134). Thanks to @tacosta for the report. + +- Metal: Inkling 2 with a DFlash 2 drafter now saves and restores the drafter's lane state in the prompt cache, so warm cache hits restore the drafter alongside the target (#5032, thanks @gilby). + - Qwen3.8-27B on Metal: Q and K head norm and RoPE run as one `q27_qk_norm_rope` dispatch instead of two head-norm launches, the barrier between them and two RoPE launches, on every chip and pass, keys-only prompt tails included; on an M5 Ultra every cache row and `qa` byte and the served replies match the previous path (#2955, part of #2940). - CUDA: drafted Qwen3.8-27B now sends a draft hold with any wide stream through the full head in one pass by default, winning back the 1.3.7 loss at 4 greedy streams (+2.3% to +3.1% on two GB10s) with identical tokens; `TF_QWEN_DRAFT_FULL_HEAD=0` restores the split path (#5490, fixes #4439). diff --git a/zig/build/cuda_family_host.zig b/zig/build/cuda_family_host.zig index 5970805ef3e..7ea6261baa3 100644 --- a/zig/build/cuda_family_host.zig +++ b/zig/build/cuda_family_host.zig @@ -255,7 +255,7 @@ pub fn steps(b: *std.Build, cuda: *std.Build.Module, mods: anytype, step: *std.B const mtp_lifecycle = b.addRunArtifact(b.addTest(.{ .root_module = mods.qwen35, .filters = &.{"MTP context lifecycle:"} })); b.step("test-qwen35-mtp-lifecycle-host", "MTP stream release and pooled context reset after interruption without devices").dependOn(&mtp_lifecycle.step); step.dependOn(&mtp_lifecycle.step); - const mtp_memory = b.addRunArtifact(b.addTest(.{ .root_module = mods.qwen35, .filters = &.{"MTP startup peak"} })); + const mtp_memory = b.addRunArtifact(b.addTest(.{ .root_module = mods.qwen35, .filters = &.{ "MTP startup peak", "MTP on a pool lane: admission includes the target tap ring exactly once" } })); b.step("test-qwen35-mtp-memory-host", "MTP startup device-memory accounting and overflow guards without a GPU").dependOn(&mtp_memory.step); step.dependOn(&mtp_memory.step); } diff --git a/zig/qwen35_recurrent_host.zig b/zig/qwen35_recurrent_host.zig index c3f719b0f79..46f8c9880fb 100644 --- a/zig/qwen35_recurrent_host.zig +++ b/zig/qwen35_recurrent_host.zig @@ -81,6 +81,7 @@ fn engine(e: *q.engine.Engine, d: *cuda.Driver) void { e.stream = .{ .d = d, .handle = @ptrFromInt(17) }; e.g = .{ .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) }; for (&e.g.linear, 0..) |*linear, i| linear.* = i < 64 and (i + 1) % 4 != 0; + if (comptime @hasField(q.engine.Engine, "rollback_capable")) e.rollback_capable = true; e.n_taps = 0; e.kv8 = false; e.geo = .{ .hid = 5120, .nk = 16, .nv = 48, .qh = 24, .kvh = 4, .nl = 48 }; diff --git a/zig/qwen35_shared_host.zig b/zig/qwen35_shared_host.zig index 9a23ff5e611..d88e5539a1c 100644 --- a/zig/qwen35_shared_host.zig +++ b/zig/qwen35_shared_host.zig @@ -48,6 +48,7 @@ fn engine(d: *cuda.Driver) q.engine.Engine { e.d = d; e.stream = .{ .d = d, .handle = null }; e.g = .{ .hidden = 256, .intermediate = 256, .layers = 1, .vocab = 32, .k_heads = 1, .v_heads = 1, .q_heads = 1, .kv_heads = 1, .eps = 1e-6, .tied = true, .context = 256, .linear = @splat(true) }; + if (comptime @hasField(q.engine.Engine, "rollback_capable")) e.rollback_capable = true; e.n_taps = 0; e.kv8 = false; e.geo = .{ .hid = 256, .nk = 1, .nv = 1, .qh = 1, .kvh = 1, .nl = 1 }; @@ -59,6 +60,36 @@ fn buffer(d: *cuda.Driver, data: []u8) cuda.DeviceBuffer { return .{ .d = d, .ptr = @intFromPtr(data.ptr), .len = data.len, .borrowed = true }; } +test "Shared verification: inference reserves 64 log rows without a before-state" { + var d: cuda.Driver = undefined; + var e = engine(&d); + if (comptime @hasField(q.engine.Engine, "rollback_capable")) e.rollback_capable = false; + e.rec_scratch = q.engine.recurrent.Pool.init(a, @intFromPtr(&e)); + e.rec_scratch.cap = q.engine.recurrent.bound(&e); + Owners.setup(&d, 0, 0); + defer Owners.balanced() catch unreachable; + const b: cuda.DeviceBuffer = .{ .d = &d, .ptr = 1, .len = e.g.stateBytes(), .borrowed = true }; + var cache: q.engine.Cache = .{ .owner = &e.rec_scratch, .scratch = q.engine.recurrent.bound(&e), .state = b, .kv = b, .log = b, .cap = 256, .logits = &.{} }; + defer { + q.engine.recurrent.release(&cache); + q.engine.recurrent.shutdown(&e); + } + try std.testing.expectEqual(e.g.logBytes(64), q.engine.recurrent.bound(&e)); + const undo = if (comptime @hasField(q.engine.Engine, "rollback_capable")) e.rollback_capable else true; + try q.engine.recurrent.prepare(&e, &cache, 1, true, undo); + try std.testing.expect(cache.before == null); + try std.testing.expectEqual(e.g.logBytes(1), cache.log.len); + try q.engine.recurrent.mark(&cache, false); + cache.advanced(1, true, false); + q.engine.recurrent.completed(&e); + try q.engine.recurrent.prepare(&e, &cache, 64, true, undo); + try std.testing.expect(cache.before == null); + try std.testing.expectEqual(e.g.logBytes(64), cache.log.len); + try q.engine.recurrent.mark(&cache, false); + cache.advanced(64, true, true); + q.engine.recurrent.completed(&e); +} + test "Shared verification: empty keep restores every byte of an in-place advanced recurrence and conv tail" { var d: cuda.Driver = undefined; var e = engine(&d); @@ -81,6 +112,26 @@ test "Shared verification: empty keep restores every byte of an in-place advance try std.testing.expectEqual(@as(usize, 0), Driver.launches); } +test "Shared verification: rollback-capable empty keep restores its snapshot" { + var d: cuda.Driver = undefined; + var e = engine(&d); + if (comptime @hasField(q.engine.Engine, "rollback_capable")) e.rollback_capable = true; + try std.testing.expectEqual(e.g.stateBytes() + e.g.logBytes(64), q.engine.recurrent.bound(&e)); + const before = try a.alloc(u8, e.g.stateBytes()); + defer a.free(before); + const state = try a.alloc(u8, before.len); + defer a.free(state); + for (before, 0..) |*x, i| x.* = @truncate(i *% 29 +% 47); + @memset(state, 0xdd); + const b = buffer(&d, state); + var cache: q.engine.Cache = .{ .state = b, .kv = b, .log = b, .cap = 256, .len = 17, .logits = &.{} }; + cache.before = buffer(&d, before); + cache.advanced(1, true, true); + try cache.keep(&e, &.{}); + try std.testing.expectEqualSlices(u8, before, state); + try std.testing.expectEqual(@as(usize, 17), cache.len); +} + test "Shared verification: keeping an advanced one-row slot does not apply the recurrence twice" { var d: cuda.Driver = undefined; var e = engine(&d); diff --git a/zig/src/core/lanes/accept.zig b/zig/src/core/lanes/accept.zig index b13fb5ed175..ee99d17496d 100644 --- a/zig/src/core/lanes/accept.zig +++ b/zig/src/core/lanes/accept.zig @@ -94,6 +94,13 @@ test "accept path follows matching children" { try std.testing.expectEqualSlices(i32, &.{ -1, 0, 1 }, chain); } +test "accept path keeps root when every draft differs" { + const gpa = std.testing.allocator; + const path = try acceptPath(gpa, &.{ 5, 6, 7, 8 }, &.{ -1, 0, 0, 1 }, &.{ 9, 9, 9, 9 }); + defer gpa.free(path); + try std.testing.expectEqualSlices(u32, &.{0}, path); +} + test "sanitize drops orphans" { const gpa = std.testing.allocator; const t = try sanitizeTree(gpa, &.{ 1, 2, 3, 4 }, &.{ -1, 0, 5, 2 }, 4); diff --git a/zig/src/families/inkling2/metal/backend.zig b/zig/src/families/inkling2/metal/backend.zig index 85d45568c3a..c4e802a90dc 100644 --- a/zig/src/families/inkling2/metal/backend.zig +++ b/zig/src/families/inkling2/metal/backend.zig @@ -8,18 +8,15 @@ const fwd = @import("forward.zig"); const Model = @import("model.zig").Model; const snapshot = @import("snapshot.zig"); const img = @import("images.zig"); -const dspark = @import("dspark.zig"); -const dspark_state = @import("dspark_state.zig"); +const drafter_snap = @import("drafter_snap.zig"); const cfg = @import("../config.zig"); const draws = @import("draw.zig"); const flight = @import("flight.zig"); const sample = @import("sample.zig"); const be = lanes.backend; -const SavedSnap = struct { - target: snapshot.Snap, - dspark: ?dspark_state.Snap = null, -}; +pub const DrafterHandle = drafter_snap.Drafter; +pub const SavedSnap = drafter_snap.Saved; pub const Options = struct { capacity: usize, streams: u32 = 4, budget: u64, images: ?img.Encoder = null, gpu_tokens: bool = false }; const shared_widths = [_]usize{ 24, 32, 48, 64 }; @@ -54,7 +51,7 @@ pub const Metal = struct { shared: [shared_widths.len]lanes.config.Cost = undefined, shared_timed: usize = 0, tap_gen: u64 = 0, - drafter: ?*dspark.Drafter = null, + drafter: ?DrafterHandle = null, verify_gen: u64 = 0, pub var fail_first_draw_for_test: if (builtin.is_test) bool else void = if (builtin.is_test) false else {}; @@ -253,8 +250,8 @@ pub const Metal = struct { try self.feed(cache, ids[cache.len..], stream, &pictures); } - fn restoreSnap(self: *Metal, cache: *st.Cache, stream: *lanes.Stream, snap: *const SavedSnap) !void { - if (self.drafter) |d| try d.restoreSnap(stream, if (snap.dspark) |*ds| ds else null, snap.target.at); + pub fn restoreSnap(self: *Metal, cache: *st.Cache, stream: *lanes.Stream, snap: *const SavedSnap) !void { + if (self.drafter) |d| try d.restoreSnap(stream, if (snap.drafter) |*dr| dr else null, snap.target.at); try snapshot.restore(cache, self.model.queue, &snap.target); } @@ -548,7 +545,7 @@ pub const Metal = struct { pub fn snapBytes(ptr: *anyopaque, at: u32) u64 { const self = cast(ptr); - return snapshot.bytes(at) + if (self.drafter != null) dspark_state.Snap.bytes(at) else 0; + return snapshot.bytes(at) + if (self.drafter) |d| d.snapBytes(at) else 0; } fn syncQueue(self: *Metal) !void { @@ -578,7 +575,7 @@ pub const Metal = struct { snap.* = .{ .target = try snapshot.save(self.model.device, self.model.queue, cache) }; errdefer snap.target.free(); if (self.drafter) |d| { - snap.dspark = try d.saveSnap(stream, at, cache.tap, self.tap_gen); + snap.drafter = try d.saveSnap(stream, at, cache.tap, self.tap_gen); } return snap; } @@ -589,8 +586,7 @@ pub const Metal = struct { pub fn snapDrop(ptr: *anyopaque, saved: *anyopaque) void { const snap: *SavedSnap = @ptrCast(@alignCast(saved)); - if (snap.dspark) |*ds| ds.free(); - snap.target.free(); + snap.free(); cast(ptr).gpa.destroy(snap); } }; diff --git a/zig/src/families/inkling2/metal/dflash2.zig b/zig/src/families/inkling2/metal/dflash2.zig index 66d1b5d9f79..75a9682c477 100644 --- a/zig/src/families/inkling2/metal/dflash2.zig +++ b/zig/src/families/inkling2/metal/dflash2.zig @@ -8,14 +8,17 @@ const Model = @import("model.zig").Model; const fwd = @import("forward.zig"); const w = @import("dflash2_weights.zig"); const k = @import("dflash2_kernels.zig"); +const state = @import("dflash2_state.zig"); +const st = @import("state.zig"); const dr = lanes.drafter; const Stream = lanes.Stream; const Ref = k.Ref; const tap_list = [_]u32{ 5, 23, 41, 48 }; const draft_prior = [_]f64{ 0.85, 0.80, 0.75, 0.70, 0.65, 0.60, 0.55 }; -const absorb_rows: usize = 256; -const max_chunks: usize = (w.window_size + w.block_size + 127) / 128; + +pub const scratchBytes = state.scratchBytes; +pub const streamBytes = state.streamBytes; fn at(buf: mtl.Buffer, off: usize) Ref { return .{ .buf = buf, .off = off }; @@ -38,149 +41,13 @@ fn failed(cb: mtl.CommandBuffer, what: []const u8) !void { } } -const scratch_fields = [_][]const u8{ - "ids", "resid", "x", "xc", "dyn", "q_raw", "k_raw", "v_raw", "q", "kb", "vb", "part", - "attn", "y", "yc", "gate", "up", "act", "logits", "hid", "tval", "tid", "seq", "fcx", - "hctx", "ck", "cv", -}; - -fn scratchSizes() [scratch_fields.len]usize { - const n = w.block_size; - const d = n - 1; - const a = absorb_rows; - const bf = 2; - return .{ - n * 4, - n * w.hidden * 4, - n * w.hidden * bf, - n * w.hidden * bf, - n * w.dyn_width * bf, - n * w.query_width * bf, - n * w.kv_width * bf, - n * w.kv_width * bf, - n * w.query_width * bf, - n * w.kv_width * bf, - n * w.kv_width * bf, - n * w.q_heads * max_chunks * 132 * 4, - n * w.query_width * bf, - n * w.hidden * bf, - n * w.hidden * bf, - n * w.intermediate * bf, - n * w.intermediate * bf, - n * w.intermediate * bf, - d * w.padded_vocab * bf, - d * w.rank * bf, - d * w.top_k * 4, - d * w.top_k * 4, - n * 4, - a * w.hidden * bf, - a * w.hidden * bf, - a * w.kv_width * bf, - a * w.kv_width * bf, - }; -} - -pub fn scratchBytes() u64 { - var total: u64 = 0; - for (scratchSizes()) |s| total += s; - return total; -} - -pub fn streamBytes() u64 { - return @as(u64, w.layers_n) * 2 * w.ring_size * w.kv_width * 2; -} - -const Scratch = struct { - ids: mtl.Buffer, - resid: mtl.Buffer, - x: mtl.Buffer, - xc: mtl.Buffer, - dyn: mtl.Buffer, - q_raw: mtl.Buffer, - k_raw: mtl.Buffer, - v_raw: mtl.Buffer, - q: mtl.Buffer, - kb: mtl.Buffer, - vb: mtl.Buffer, - part: mtl.Buffer, - attn: mtl.Buffer, - y: mtl.Buffer, - yc: mtl.Buffer, - gate: mtl.Buffer, - up: mtl.Buffer, - act: mtl.Buffer, - logits: mtl.Buffer, - hid: mtl.Buffer, - tval: mtl.Buffer, - tid: mtl.Buffer, - seq: mtl.Buffer, - fcx: mtl.Buffer, - hctx: mtl.Buffer, - ck: mtl.Buffer, - cv: mtl.Buffer, - - fn init(device: mtl.Device) !Scratch { - @setEvalBranchQuota(10_000); - const ns = scratchSizes(); - var s: Scratch = undefined; - var made: usize = 0; - errdefer inline for (scratch_fields, 0..) |f, i| if (i < made) @field(s, f).deinit(); - inline for (scratch_fields, 0..) |f, i| { - @field(s, f) = try device.buffer(@max(ns[i], 16), mtl.ResourceOptions.shared); - made += 1; - } - return s; - } - - fn deinit(s: *Scratch) void { - inline for (scratch_fields) |f| @field(s, f).deinit(); - s.* = undefined; - } -}; - -const Lane = struct { - k: [w.layers_n]mtl.Buffer, - v: [w.layers_n]mtl.Buffer, - from: u64 = 0, - end: u64 = 0, - held: [w.block_size - 1]u32 = @splat(0), - held_len: u32 = 0, - - fn init(device: mtl.Device) !Lane { - var l: Lane = .{ .k = undefined, .v = undefined }; - const bytes = w.ring_size * w.kv_width * 2; - var made: usize = 0; - errdefer for (0..made) |i| { - l.k[i].deinit(); - l.v[i].deinit(); - }; - for (0..w.layers_n) |i| { - l.k[i] = try device.buffer(bytes, mtl.ResourceOptions.private); - l.v[i] = device.buffer(bytes, mtl.ResourceOptions.private) catch |err| { - l.k[i].deinit(); - return err; - }; - made += 1; - } - return l; - } - - fn deinit(l: *Lane) void { - for (0..w.layers_n) |i| { - l.k[i].deinit(); - l.v[i].deinit(); - } - l.* = undefined; - } -}; - pub const Drafter = struct { gpa: std.mem.Allocator, target: *const Model, loaded: w.Loaded, pipelines: k.Pipelines, - scratch: Scratch, - contexts: std.AutoHashMapUnmanaged(*Stream, Lane) = .empty, + scratch: state.Scratch, + contexts: std.AutoHashMapUnmanaged(*Stream, state.Lane) = .empty, pending: ?mtl.CommandBuffer = null, step_ms: f64 = 0, use_embed_norm: bool = true, @@ -200,7 +67,7 @@ pub const Drafter = struct { errdefer d.loaded.deinit(); d.pipelines = try k.Pipelines.load(device); errdefer d.pipelines.deinit(); - d.scratch = try Scratch.init(device); + d.scratch = try state.Scratch.init(device); errdefer d.scratch.deinit(); try d.warm(); std.log.info("inkling2_loop DFlash2: loaded {s} (block={d}, top_k={d}, block_ms={d:.2})", .{ @@ -228,6 +95,41 @@ pub const Drafter = struct { return .{ .kind = "DFlash2", .ptr = d, .vtable = &.{ .taps = tapsFn, .facts = factsFn, .open = openFn, .absorb = absorbFn, .hold = holdFn, .held = heldFn, .release = releaseFn } }; } + pub fn saveSnap(d: *Drafter, stream: *Stream, at_pos: u32, tap: st.Tap, tap_gen: u64) !?state.Snap { + const lane = d.contexts.getPtr(stream) orelse return null; + try d.settle(); + const tail = try state.resolveTailTap(tap, at_pos, lane.end, tap_gen); + return try state.Snap.save(d.target.device, d.target.queue, lane, tail); + } + + pub fn restoreSnap(d: *Drafter, stream: *Stream, snap: ?*const state.Snap, at_pos: usize) !void { + const lane = d.contexts.getPtr(stream) orelse return; + const s = snap orelse return error.DFlash2SnapshotMissing; + const expected_end = std.math.add(u64, s.end, if (s.tail_off != null) @as(u64, 1) else 0) catch return error.DFlash2SnapshotGeometry; + if (expected_end != at_pos or expected_end > state.max_context) return error.DFlash2SnapshotGeometry; + try d.settle(); + try state.Snap.restore(lane, d.target.queue, s); + if (s.tail_off) |tail_off| { + errdefer state.clearLane(lane); + const buf = s.buf orelse return error.DFlash2SnapshotGeometry; + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const cb = d.target.queue.commandBuffer(); + const e = cb.compute(.serial); + d.absorbRows(e, lane, at(buf, tail_off), s.end, 1); + e.end(); + cb.commit(); + try failed(cb, "restore tail"); + lane.end = s.end + 1; + lane.held_len = 0; + } + } + + pub fn resetLane(d: *Drafter, stream: *Stream) void { + d.settle() catch {}; + if (d.contexts.getPtr(stream)) |lane| state.clearLane(lane); + } + fn cast(ptr: *anyopaque) *Drafter { return @ptrCast(@alignCast(ptr)); } @@ -241,7 +143,7 @@ pub const Drafter = struct { return .{ .fixed_block = true, .depth = w.block_size - 1, .step_ms = d.step_ms, .prior = &draft_prior, .plain_guard = false, .stream_bytes = @intCast(streamBytes()) }; } - fn settle(d: *Drafter) !void { + pub fn settle(d: *Drafter) !void { const cb = d.pending orelse return; d.pending = null; defer cb.release(); @@ -251,7 +153,7 @@ pub const Drafter = struct { fn openFn(ptr: *anyopaque, stream: *Stream) anyerror!void { const d = cast(ptr); if (d.contexts.contains(stream)) return error.DraftStreamOpen; - var lane = try Lane.init(d.target.device); + var lane = try state.Lane.init(d.target.device); errdefer lane.deinit(); try d.contexts.put(d.gpa, stream, lane); } @@ -274,7 +176,7 @@ pub const Drafter = struct { } } - fn absorbRows(d: *Drafter, e: mtl.ComputeEncoder, lane: *const Lane, taps: Ref, start: u64, rows: usize) void { + pub fn absorbRows(d: *Drafter, e: mtl.ComputeEncoder, lane: *const state.Lane, taps: Ref, start: u64, rows: usize) void { const c = &d.loaded.config; const s = &d.scratch; fwd.dense(d.target, e, d.loaded.weights.fc, taps, at(s.fcx, 0), rows); @@ -292,14 +194,18 @@ pub const Drafter = struct { } } + fn promptHorizon(stream: *const Stream, start: u64) u64 { + var horizon: u64 = stream.prompt_len; + for (stream.reuse.marks) |m| { + if (m > start and m < horizon) horizon = m; + } + return horizon; + } + fn absorbFn(ptr: *anyopaque, items: []const dr.Absorb) anyerror!void { const d = cast(ptr); try d.settle(); if (items.len == 0) return; - const pool = mtl.objc.Pool.push(); - defer pool.pop(); - const cb = d.target.queue.commandBuffer(); - const e = cb.compute(.serial); const row_bytes = w.taps_n * w.hidden * 2; const keep_window: u64 = w.window_size + w.block_size; for (items) |item| { @@ -307,16 +213,26 @@ pub const Drafter = struct { const features = item.features; if (features.space != .device or features.dtype != .bf16 or features.row_bytes != row_bytes) return error.DraftFeaturesUnsupported; if (item.rows != null) return error.TreesNotBuilt; - if (features.rows == 0 or features.rows > 1048576) return error.DraftFeaturesUnsupported; - if (item.start < lane.end) return error.DraftContextGap; + if (features.rows == 0 or features.rows > state.max_context) return error.DraftFeaturesUnsupported; + if (item.start < lane.end or item.start > state.max_context or features.rows > state.max_context - item.start) return error.DraftContextGap; + } + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const cb = d.target.queue.commandBuffer(); + const e = cb.compute(.serial); + for (items) |item| { + const lane = d.contexts.getPtr(item.stream).?; + const features = item.features; if (item.start > lane.end) lane.from = item.start; const end = item.start + features.rows; - const keep_from = if (item.prompt) @max(item.start, item.stream.prompt_len -| keep_window) else item.start; - if (keep_from > lane.from and keep_from > lane.end) lane.from = keep_from; + const horizon = if (item.prompt) promptHorizon(item.stream, item.start) else end; + const keep_from = if (item.prompt) @max(item.start, horizon -| keep_window) else item.start; + const next_from = @min(keep_from, end); + if (next_from > lane.from and next_from > lane.end) lane.from = next_from; const source = mtl.Buffer{ .id = @ptrFromInt(features.buffer) }; var position = keep_from; while (position < end) { - const rows: usize = @intCast(@min(absorb_rows, end - position)); + const rows: usize = @intCast(@min(state.absorb_rows, end - position)); const offset = features.offset + @as(usize, @intCast(position - item.start)) * row_bytes; d.absorbRows(e, lane, at(source, offset), position, rows); position += rows; @@ -329,7 +245,7 @@ pub const Drafter = struct { d.pending = cb.retain(); } - fn encodeBlock(d: *Drafter, e: mtl.ComputeEncoder, lane: *const Lane, pending: u32, anchor: u64) void { + pub fn encodeBlock(d: *Drafter, e: mtl.ComputeEncoder, lane: *const state.Lane, pending: u32, anchor: u64) void { const c = &d.loaded.config; const s = &d.scratch; const n = w.block_size; @@ -415,7 +331,7 @@ pub const Drafter = struct { } fn warm(d: *Drafter) !void { - var lane = try Lane.init(d.target.device); + var lane = try state.Lane.init(d.target.device); defer lane.deinit(); var ms: f64 = 0; for (0..3) |run| { @@ -433,9 +349,3 @@ pub const Drafter = struct { d.step_ms = ms / @as(f64, @floatFromInt(w.block_size - 1)); } }; - -test "DFlash2 stream and scratch accounting fit fixed ring geometry" { - try std.testing.expectEqual(@as(usize, 2176), w.ring_size); - try std.testing.expectEqual(@as(u64, 5 * 2 * 2176 * 1024 * 2), streamBytes()); - try std.testing.expect(scratchBytes() > 0); -} diff --git a/zig/src/families/inkling2/metal/dflash2_snap_test.zig b/zig/src/families/inkling2/metal/dflash2_snap_test.zig new file mode 100644 index 00000000000..9bbfae325f2 --- /dev/null +++ b/zig/src/families/inkling2/metal/dflash2_snap_test.zig @@ -0,0 +1,592 @@ +//! Metal tests for DFlash 2 prompt-cache snapshots: multi-stream slot >= 1, wrap-around, warm == cold, zero leaks. +const std = @import("std"); +const mtl = @import("metal"); +const lanes = @import("lanes"); +const api = @import("engine_api"); +const sources = @import("kernel_sources"); +const ck = @import("../../../core/checkpoint_metal.zig"); +const layer_plan = @import("../plan.zig"); +const model_file = @import("model.zig"); +const st = @import("state.zig"); +const snapshot = @import("snapshot.zig"); +const backend = @import("backend.zig"); +const w = @import("dflash2_weights.zig"); +const k = @import("dflash2_kernels.zig"); +const state = @import("dflash2_state.zig"); +const dflash2 = @import("dflash2.zig"); + +const gpa = std.testing.allocator; + +const SyntheticEnv = struct { + device: mtl.Device, + queue: mtl.Queue, + model: model_file.Model, + drafter: dflash2.Drafter, + vocab_buf: mtl.Buffer, + cb_buf: mtl.Buffer, + layer_buf: mtl.Buffer, + taps_buf: mtl.Buffer, + + fn makeTensor(buf: mtl.Buffer, off: usize, dims: []const usize) ck.Tensor { + var count: usize = 1; + var shape: @TypeOf(@as(ck.Tensor, undefined).shape) = @splat(1); + for (dims, 0..) |d, i| { + shape[i] = d; + count *= d; + } + return .{ .buffer = buf, .offset = off, .bytes = count * 2, .dtype = .bf16, .shape = shape, .rank = dims.len }; + } + + fn bf16FromF32(v: f32) u16 { + const bits: u32 = @bitCast(v); + return @truncate((bits +% 0x7fff +% ((bits >> 16) & 1)) >> 16); + } + + fn init(tap_rows: usize) !SyntheticEnv { + const device = mtl.Device.init() catch return error.SkipZigTest; + errdefer device.deinit(); + const queue = try device.queue(); + errdefer queue.deinit(); + + const lib = try mtl.Library.fromSource(device, sources.spark25_glue, .{ .language = mtl.CompileOptions.mlx().language, .math_functions = .precise }); + defer lib.deinit(); + var dense: [6]mtl.Pipeline = undefined; + var made_dense: usize = 0; + errdefer for (dense[0..made_dense]) |p| p.deinit(); + for ([_]u32{ 1, 2, 4, 8, 16, 32 }, 0..) |rows, i| { + var buf: [32]u8 = undefined; + const name = try std.fmt.bufPrintSentinel(&buf, "sp_matvec_{d}", .{rows}, 0); + dense[i] = try mtl.Pipeline.init(device, lib, name, false); + made_dense += 1; + } + + const seed_bytes: usize = 4 << 20; + const seed_buf = try device.buffer(seed_bytes, mtl.ResourceOptions.shared); + defer seed_buf.deinit(); + var prng = std.Random.DefaultPrng.init(20261124); + const rng = prng.random(); + for (seed_buf.slice(u16, seed_bytes / 2)) |*dst| { + dst.* = bf16FromF32((rng.float(f32) - 0.5) * 0.08); + } + + const vocab_bytes = w.padded_vocab * w.hidden * 2; + const cb_bytes = w.padded_vocab * w.rank * 2; + const layer_bytes = 128 << 20; + const vocab_buf = try device.buffer(vocab_bytes, mtl.ResourceOptions.private); + errdefer vocab_buf.deinit(); + const cb_buf = try device.buffer(cb_bytes, mtl.ResourceOptions.private); + errdefer cb_buf.deinit(); + const layer_buf = try device.buffer(layer_bytes, mtl.ResourceOptions.private); + errdefer layer_buf.deinit(); + + { + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const cb = queue.commandBuffer(); + const e = cb.blit(); + for ([_]struct { dst: mtl.Buffer, total: usize }{ + .{ .dst = vocab_buf, .total = vocab_bytes }, + .{ .dst = cb_buf, .total = cb_bytes }, + .{ .dst = layer_buf, .total = layer_bytes }, + }) |target| { + var off: usize = 0; + var phase: usize = 0; + while (off < target.total) { + const src_off = (phase * 65536) % (seed_bytes / 2); + const n = @min(seed_bytes - src_off, target.total - off); + e.copy(seed_buf, src_off, target.dst, off, n); + off += n; + phase += 1; + } + } + e.end(); + cb.commit(); + cb.wait(); + if (cb.failure() != null) return error.GpuFailed; + } + + const taps_bytes = tap_rows * w.taps_n * w.hidden * 2; + const taps_buf = try device.buffer(taps_bytes, mtl.ResourceOptions.shared); + errdefer taps_buf.deinit(); + for (taps_buf.slice(u16, taps_bytes / 2)) |*dst| { + dst.* = bf16FromF32((rng.float(f32) - 0.5) * 0.25); + } + + var env: SyntheticEnv = .{ + .device = device, + .queue = queue, + .model = undefined, + .drafter = undefined, + .vocab_buf = vocab_buf, + .cb_buf = cb_buf, + .layer_buf = layer_buf, + .taps_buf = taps_buf, + }; + env.model = .{ + .gpa = gpa, + .device = device, + .queue = queue, + .config = .{ + .text = .{ + .hidden = 2304, + .layers = 24, + .vocab = 201024, + .unpadded_vocab = 200058, + .local = .{ .q = 24, .kv = 8, .dim = 128 }, + .global = .{ .q = 24, .kv = 8, .dim = 128 }, + .window = 1024, + .d_rel = 16, + .rel_extent = 1024, + .log_floor = 8192, + .log_alpha = 0.1, + .eps = 1e-6, + .qk_clip = 22.627416997969522, + .rel_clip = 8, + .block = 6, + .experts = 128, + .topk = 8, + .expert_inter = 1152, + .route_scale = 8, + .gate_cap = 4, + .up_cap = 25, + .logit_cap = 30, + .max_context = 1048576, + .loop = .{ .core_start = 6, .core_end = 18, .passes = 3, .gate_rank = 64 }, + }, + .vision = undefined, + .mtp = null, + .eos = 200055, + .image_token = 200054, + }, + .checkpoint = ck.Checkpoint.init(gpa), + .weights = undefined, + .weight_plan = undefined, + .attention = undefined, + .glue = undefined, + .experts = undefined, + .loop = undefined, + .tree = undefined, + .dense = dense, + .norm = dense[0], + .dense_mma = null, + .dense_tiled = null, + .runtime = undefined, + .sample = undefined, + }; + env.model.weights.embed = makeTensor(vocab_buf, 0, &.{ w.padded_vocab, w.hidden }); + env.model.weights.embed_norm = makeTensor(layer_buf, 0, &.{w.hidden}); + env.model.weights.unembed = makeTensor(vocab_buf, 0, &.{ w.padded_vocab, w.hidden }); + + var precision: [24]layer_plan.Precision = @splat(.nvfp4); + for (precision[4..]) |*p| p.* = .mxfp8; + env.model.weight_plan = try layer_plan.build(&env.model.config.text, &precision); + + var off: usize = 40 << 20; + const allocTensor = struct { + fn next(buf: mtl.Buffer, cursor: *usize, dims: []const usize) ck.Tensor { + const t = makeTensor(buf, cursor.*, dims); + cursor.* = std.mem.alignForward(usize, cursor.* + t.bytes, 256); + return t; + } + }.next; + var layers: [w.layers_n]w.Layer = undefined; + for (&layers, 0..) |*l, i| { + const base_off = i * 4096; + l.* = .{ + .in_norm = makeTensor(layer_buf, base_off, &.{w.hidden}), + .post_norm = makeTensor(layer_buf, base_off + 256, &.{w.hidden}), + .q_norm = makeTensor(layer_buf, base_off + 512, &.{w.head_dim}), + .k_norm = makeTensor(layer_buf, base_off + 768, &.{w.head_dim}), + .q_proj = makeTensor(layer_buf, base_off + 1024, &.{ w.query_width, w.hidden }), + .k_proj = makeTensor(layer_buf, base_off + 2048, &.{ w.kv_width, w.hidden }), + .v_proj = makeTensor(layer_buf, base_off + 4096, &.{ w.kv_width, w.hidden }), + .o_proj = makeTensor(layer_buf, base_off + 8192, &.{ w.hidden, w.query_width }), + .gate_proj = makeTensor(layer_buf, base_off + 16384, &.{ w.intermediate, w.hidden }), + .up_proj = makeTensor(layer_buf, base_off + 32768, &.{ w.intermediate, w.hidden }), + .down_proj = makeTensor(layer_buf, base_off + 65536, &.{ w.hidden, w.intermediate }), + .attn_conv = .{ + .base = makeTensor(layer_buf, base_off + 131072, &.{ 2, 2, w.hidden }), + .proj = makeTensor(layer_buf, base_off + 196608, &.{ w.dyn_width, w.hidden }), + }, + .mlp_conv = .{ + .base = makeTensor(layer_buf, base_off + 262144, &.{ 2, 2, w.hidden }), + .proj = makeTensor(layer_buf, base_off + 327680, &.{ w.dyn_width, w.hidden }), + }, + }; + } + const weights: w.Weights = .{ + .fc = allocTensor(layer_buf, &off, &.{ w.hidden, w.taps_n * w.hidden }), + .hidden_norm = allocTensor(layer_buf, &off, &.{w.hidden}), + .norm = allocTensor(layer_buf, &off, &.{w.hidden}), + .hidden_proj = allocTensor(layer_buf, &off, &.{ w.rank, w.hidden }), + .pred_cb = makeTensor(cb_buf, 0, &.{ w.padded_vocab, w.rank }), + .succ_cb = makeTensor(cb_buf, 0, &.{ w.padded_vocab, w.rank }), + .layers = layers, + }; + + const pipes = try k.Pipelines.load(device); + errdefer { + var owned = pipes; + owned.deinit(); + } + const scratch = try state.Scratch.init(device); + env.drafter = .{ + .gpa = gpa, + .target = &env.model, + .loaded = .{ .checkpoint = ck.Checkpoint.init(gpa), .config = .{}, .weights = weights }, + .pipelines = pipes, + .scratch = scratch, + }; + return env; + } + + fn deinit(env: *SyntheticEnv) void { + env.drafter.settle() catch {}; + var it = env.drafter.contexts.valueIterator(); + while (it.next()) |lane| lane.deinit(); + env.drafter.contexts.deinit(gpa); + env.drafter.scratch.deinit(); + env.drafter.pipelines.deinit(); + env.drafter.loaded.deinit(); + env.model.checkpoint.deinit(); + for (env.model.dense) |p| p.deinit(); + env.taps_buf.deinit(); + env.layer_buf.deinit(); + env.cb_buf.deinit(); + env.vocab_buf.deinit(); + env.queue.deinit(); + env.device.deinit(); + } +}; + +fn readRingActive(queue: mtl.Queue, device: mtl.Device, lane: *const state.Lane, lo: u64, end: u64) ![]u8 { + const rows: usize = @intCast(end - lo); + const total = rows * state.layer_row_bytes; + const flat = try device.buffer(total, mtl.ResourceOptions.shared); + defer flat.deinit(); + const start_slot: usize = @intCast(lo % w.ring_size); + const first_rows = @min(rows, w.ring_size - start_slot); + const second_rows = rows - first_rows; + const first_bytes = first_rows * state.row_bytes; + const second_bytes = second_rows * state.row_bytes; + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const cb = queue.commandBuffer(); + const e = cb.blit(); + var at: usize = 0; + for (0..w.layers_n) |i| { + for ([_]mtl.Buffer{ lane.k[i], lane.v[i] }) |rb| { + e.copy(rb, start_slot * state.row_bytes, flat, at, first_bytes); + if (second_bytes > 0) e.copy(rb, 0, flat, at + first_bytes, second_bytes); + at += first_bytes + second_bytes; + } + } + e.end(); + cb.commit(); + cb.wait(); + if (cb.failure() != null) return error.GpuFailed; + return try gpa.dupe(u8, flat.slice(u8, total)); +} + +fn absorbSlice(dr: lanes.drafter.Drafter, s: *lanes.Stream, taps: mtl.Buffer, src_base: usize, start: u64, rows: usize, prompt_mode: bool) !void { + const follow = try gpa.alloc(u32, rows); + defer gpa.free(follow); + for (follow, 0..) |*f, i| f.* = @intCast((start + i + 1) % w.valid_vocab); + var pos: usize = 0; + while (pos < rows) { + const n = @min(st.prompt_rows, rows - pos); + const f: lanes.backend.Features = .{ + .buffer = @intFromPtr(taps.id), + .offset = (src_base + @as(usize, @intCast(start)) + pos) * state.tap_row_bytes, + .rows = @intCast(n), + .row_bytes = state.tap_row_bytes, + .space = .device, + .dtype = .bf16, + }; + try dr.absorb(&.{.{ .stream = s, .features = f, .start = start + pos, .follow = follow[pos..][0..n], .prompt = prompt_mode }}); + pos += n; + } +} + +test "DFlash2 multi-stream save/restore at slot >= 1 preserves slot 0 and matches cold bit-identically" { + var env = try SyntheticEnv.init(2400); + defer env.deinit(); + const dr = env.drafter.drafter(); + + const len1: usize = 2310; + const snap1_at: u32 = 2296; + const len2: usize = 2260; + const snap2_at: u32 = 2240; + const ids = try gpa.alloc(u32, len1); + defer gpa.free(ids); + for (ids, 0..) |*id, i| id.* = @intCast(10 + (i * 13) % 500); + const marks1 = [_]u32{snap1_at}; + const marks2 = [_]u32{snap2_at}; + + var slot0 = try lanes.Stream.init(gpa, .{ .id = "slot0", .prompt = ids[0..120], .max_new = 16 }); + defer slot0.deinit(gpa); + var slot1 = try lanes.Stream.init(gpa, .{ .id = "slot1", .prompt = ids, .max_new = 16, .reuse = .{ .marks = &marks1 } }); + defer slot1.deinit(gpa); + var slot2 = try lanes.Stream.init(gpa, .{ .id = "slot2", .prompt = ids[0..len2], .max_new = 16, .reuse = .{ .marks = &marks2 } }); + defer slot2.deinit(gpa); + var cold1 = try lanes.Stream.init(gpa, .{ .id = "cold1", .prompt = ids, .max_new = 16, .reuse = .{ .marks = &marks1 } }); + defer cold1.deinit(gpa); + var cold2 = try lanes.Stream.init(gpa, .{ .id = "cold2", .prompt = ids[0..len2], .max_new = 16, .reuse = .{ .marks = &marks2 } }); + defer cold2.deinit(gpa); + + try dr.open(&slot0); + defer dr.release(&slot0); + try dr.open(&slot1); + var slot1_open = true; + defer if (slot1_open) dr.release(&slot1); + try dr.open(&slot2); + var slot2_open = true; + defer if (slot2_open) dr.release(&slot2); + try dr.open(&cold1); + defer dr.release(&cold1); + try dr.open(&cold2); + defer dr.release(&cold2); + + // Populate slot 0 and hold drafts so we can prove peer saves/restores never clobber slot 0. + try absorbSlice(dr, &slot0, env.taps_buf, 0, 0, 120, true); + try dr.hold(&.{.{ .stream = &slot0, .pending = 11, .position = 121, .depth = 7 }}); + var slot0_held_before: [7]u32 = undefined; + try dr.held(&.{&slot0}, &.{&slot0_held_before}); + const slot0_ring_before = try readRingActive(env.queue, env.device, env.drafter.contexts.getPtr(&slot0).?, 0, 120); + defer gpa.free(slot0_ring_before); + + // Slot 1 saves across ring_size = 2176; slot 2 saves with an unabsorbed tail tap at a non-zero shared offset. + try absorbSlice(dr, &slot1, env.taps_buf, 0, 0, snap1_at, true); + try absorbSlice(dr, &cold1, env.taps_buf, 0, 0, snap1_at, true); + try absorbSlice(dr, &slot2, env.taps_buf, 32, 0, snap2_at - 1, true); + try absorbSlice(dr, &cold2, env.taps_buf, 32, 0, snap2_at, true); + + var snap1 = (try env.drafter.saveSnap(&slot1, snap1_at, .{}, 0)).?; + defer snap1.free(); + try std.testing.expectEqual(@as(u64, snap1_at - w.window_size), snap1.from); + try std.testing.expectEqual(@as(u64, snap1_at), snap1.end); + + const shared_tap: st.Tap = .{ + .buf = env.taps_buf, + .off = (32 + snap2_at - 2) * state.tap_row_bytes, + .start = snap2_at - 2, + .rows = 2, + .gen = 5, + }; + var snap2 = (try env.drafter.saveSnap(&slot2, snap2_at, shared_tap, 5)).?; + defer snap2.free(); + try std.testing.expectEqual(@as(u64, snap2_at - 1 - w.window_size), snap2.from); + try std.testing.expectEqual(@as(u64, snap2_at - 1), snap2.end); + try std.testing.expect(snap2.tail_off != null); + + // Release slots 1 and 2 and open fresh warm streams at slot >= 1 while slot 0 remains live. + dr.release(&slot1); + slot1_open = false; + dr.release(&slot2); + slot2_open = false; + + var warm1 = try lanes.Stream.init(gpa, .{ .id = "warm1", .prompt = ids, .max_new = 16 }); + defer warm1.deinit(gpa); + var warm2 = try lanes.Stream.init(gpa, .{ .id = "warm2", .prompt = ids[0..len2], .max_new = 16 }); + defer warm2.deinit(gpa); + try dr.open(&warm1); + defer dr.release(&warm1); + try dr.open(&warm2); + defer dr.release(&warm2); + + try env.drafter.restoreSnap(&warm1, &snap1, snap1_at); + try env.drafter.restoreSnap(&warm2, &snap2, snap2_at); + + // Verify slot 0 ring bytes, metadata, and held drafts are completely untouched. + const slot0_lane = env.drafter.contexts.getPtr(&slot0).?; + try std.testing.expectEqual(@as(u64, 0), slot0_lane.from); + try std.testing.expectEqual(@as(u64, 120), slot0_lane.end); + try std.testing.expectEqual(@as(u32, 7), slot0_lane.held_len); + var slot0_held_after: [7]u32 = undefined; + try dr.held(&.{&slot0}, &.{&slot0_held_after}); + try std.testing.expectEqualSlices(u32, &slot0_held_before, &slot0_held_after); + const slot0_ring_after = try readRingActive(env.queue, env.device, slot0_lane, 0, 120); + defer gpa.free(slot0_ring_after); + try std.testing.expectEqualSlices(u8, slot0_ring_before, slot0_ring_after); + + // Continue both restored streams alongside their cold references through prompt tail, hold, and decode. + try absorbSlice(dr, &cold1, env.taps_buf, 0, snap1_at, len1 - snap1_at, true); + try absorbSlice(dr, &warm1, env.taps_buf, 0, snap1_at, len1 - snap1_at, true); + try absorbSlice(dr, &cold2, env.taps_buf, 32, snap2_at, len2 - snap2_at, true); + try absorbSlice(dr, &warm2, env.taps_buf, 32, snap2_at, len2 - snap2_at, true); + try dr.hold(&.{ + .{ .stream = &cold1, .pending = 42, .position = len1 + 1, .depth = 7 }, + .{ .stream = &warm1, .pending = 42, .position = len1 + 1, .depth = 7 }, + .{ .stream = &cold2, .pending = 63, .position = len2 + 1, .depth = 7 }, + .{ .stream = &warm2, .pending = 63, .position = len2 + 1, .depth = 7 }, + }); + + var h_c1: [7]u32 = undefined; + var h_w1: [7]u32 = undefined; + var h_c2: [7]u32 = undefined; + var h_w2: [7]u32 = undefined; + try dr.held(&.{ &cold1, &warm1, &cold2, &warm2 }, &.{ &h_c1, &h_w1, &h_c2, &h_w2 }); + try std.testing.expectEqualSlices(u32, &h_c1, &h_w1); + try std.testing.expectEqualSlices(u32, &h_c2, &h_w2); + + const lo1: u64 = (len1 + 1) - w.window_size; + const c1_ring = try readRingActive(env.queue, env.device, env.drafter.contexts.getPtr(&cold1).?, lo1, len1); + defer gpa.free(c1_ring); + const w1_ring = try readRingActive(env.queue, env.device, env.drafter.contexts.getPtr(&warm1).?, lo1, len1); + defer gpa.free(w1_ring); + try std.testing.expectEqualSlices(u8, c1_ring, w1_ring); + + const lo2: u64 = (len2 + 1) - w.window_size; + const c2_ring = try readRingActive(env.queue, env.device, env.drafter.contexts.getPtr(&cold2).?, lo2, len2); + defer gpa.free(c2_ring); + const w2_ring = try readRingActive(env.queue, env.device, env.drafter.contexts.getPtr(&warm2).?, lo2, len2); + defer gpa.free(w2_ring); + try std.testing.expectEqualSlices(u8, c2_ring, w2_ring); + + try absorbSlice(dr, &cold1, env.taps_buf, 0, len1, 3, false); + try absorbSlice(dr, &warm1, env.taps_buf, 0, len1, 3, false); + try absorbSlice(dr, &cold2, env.taps_buf, 32, len2, 3, false); + try absorbSlice(dr, &warm2, env.taps_buf, 32, len2, 3, false); + try dr.hold(&.{ + .{ .stream = &cold1, .pending = 77, .position = len1 + 4, .depth = 7 }, + .{ .stream = &warm1, .pending = 77, .position = len1 + 4, .depth = 7 }, + .{ .stream = &cold2, .pending = 88, .position = len2 + 4, .depth = 7 }, + .{ .stream = &warm2, .pending = 88, .position = len2 + 4, .depth = 7 }, + }); + try dr.held(&.{ &cold1, &warm1, &cold2, &warm2 }, &.{ &h_c1, &h_w1, &h_c2, &h_w2 }); + try std.testing.expectEqualSlices(u32, &h_c1, &h_w1); + try std.testing.expectEqualSlices(u32, &h_c2, &h_w2); +} + +test "DFlash2 prompt marks below prompt_len - window stay intact for shorter resumed prompts" { + var env = try SyntheticEnv.init(2500); + defer env.deinit(); + const dr = env.drafter.drafter(); + + const long_len: usize = 2500; + const short_len: usize = 300; + const mark: u32 = 256; + const long_ids = try gpa.alloc(u32, long_len); + defer gpa.free(long_ids); + for (long_ids, 0..) |*id, i| id.* = @intCast(50 + i % 100); + const marks = [_]u32{mark}; + + var slot0 = try lanes.Stream.init(gpa, .{ .id = "slot0", .prompt = long_ids[0..64], .max_new = 4 }); + defer slot0.deinit(gpa); + var saver = try lanes.Stream.init(gpa, .{ .id = "saver", .prompt = long_ids, .max_new = 8, .reuse = .{ .marks = &marks } }); + defer saver.deinit(gpa); + var warm = try lanes.Stream.init(gpa, .{ .id = "warm", .prompt = long_ids[0..short_len], .max_new = 8 }); + defer warm.deinit(gpa); + var cold = try lanes.Stream.init(gpa, .{ .id = "cold", .prompt = long_ids[0..short_len], .max_new = 8 }); + defer cold.deinit(gpa); + + try dr.open(&slot0); + defer dr.release(&slot0); + try dr.open(&saver); + defer dr.release(&saver); + try dr.open(&warm); + defer dr.release(&warm); + try dr.open(&cold); + defer dr.release(&cold); + + try absorbSlice(dr, &saver, env.taps_buf, 0, 0, mark, true); + var snap = (try env.drafter.saveSnap(&saver, mark, .{}, 0)).?; + defer snap.free(); + try std.testing.expectEqual(@as(u64, 0), snap.from); + try std.testing.expectEqual(@as(u64, mark), snap.end); + + try env.drafter.restoreSnap(&warm, &snap, mark); + try absorbSlice(dr, &warm, env.taps_buf, 0, mark, short_len - mark, true); + try absorbSlice(dr, &cold, env.taps_buf, 0, 0, short_len, true); + + try dr.hold(&.{ + .{ .stream = &cold, .pending = 19, .position = short_len + 1, .depth = 7 }, + .{ .stream = &warm, .pending = 19, .position = short_len + 1, .depth = 7 }, + }); + var cold_held: [7]u32 = undefined; + var warm_held: [7]u32 = undefined; + try dr.held(&.{ &cold, &warm }, &.{ &cold_held, &warm_held }); + try std.testing.expectEqualSlices(u32, &cold_held, &warm_held); +} + +test "backend.Metal snapSave, restoreSnap, and snapDrop with DFlash2 at slot >= 1 leak zero memory" { + var env = try SyntheticEnv.init(160); + defer env.deinit(); + const m = try backend.Metal.init(gpa, &env.model, .{ .capacity = 512, .streams = 3, .budget = 2 << 30 }); + defer m.deinit(); + m.drafter = .{ .dflash2 = &env.drafter }; + m.prepared = true; + + const ids: [128]u32 = @splat(1); + var s0 = try lanes.Stream.init(gpa, .{ .id = "s0", .prompt = &ids, .max_new = 4 }); + defer s0.deinit(gpa); + var s1 = try lanes.Stream.init(gpa, .{ .id = "s1", .prompt = &ids, .max_new = 4 }); + defer s1.deinit(gpa); + var s2 = try lanes.Stream.init(gpa, .{ .id = "s2", .prompt = &ids, .max_new = 4 }); + defer s2.deinit(gpa); + var caches: [3]*st.Cache = undefined; + for ([_]*lanes.Stream{ &s0, &s1, &s2 }, 0..) |stream, idx| { + const cache = try m.createCache(256); + errdefer { + cache.deinit(); + gpa.destroy(cache); + } + try m.caches.put(gpa, stream, cache); + caches[idx] = cache; + } + const c0 = caches[0]; + const c1 = caches[1]; + const c2 = caches[2]; + c0.len = 64; + c1.len = 128; + + const dr = env.drafter.drafter(); + try dr.open(&s0); + defer dr.release(&s0); + try dr.open(&s1); + defer dr.release(&s1); + try dr.open(&s2); + defer dr.release(&s2); + try absorbSlice(dr, &s0, env.taps_buf, 0, 0, 64, true); + try absorbSlice(dr, &s1, env.taps_buf, 16, 0, 128, true); + + const want_bytes = snapshot.bytes(128) + state.Snap.bytes(128); + try std.testing.expectEqual(want_bytes, backend.Metal.snapBytes(m, 128)); + try std.testing.expect(want_bytes > snapshot.bytes(128)); + + // Store keeps and drops snapshots saved from slot 1 via snapSave and snapDrop under std.testing.allocator. + const rules: api.prompt_cache.Rules = .{ .lookahead = 0, .planned = true, .grid = st.prompt_rows, .min_prompt = 0 }; + var store = api.prompt_cache.Store.init(gpa, .{ + .ptr = m, + .vtable = &.{ .bytes = backend.Metal.snapBytes, .save = backend.Metal.snapSave, .restore = backend.Metal.snapRestore, .drop = backend.Metal.snapDrop }, + }, rules, want_bytes); + defer store.deinit(); + try std.testing.expect(store.keep(&ids, 128, &s1, &.{}, &.{})); + try std.testing.expectEqual(@as(usize, 1), store.entries.items.len); + const saved = store.entries.items[0].saved; + + // Restore into slot 2 (s2) while slot 0 (s0) stays live; verify both target cache and DFlash2 lane. + try std.testing.expectError(error.BackendRestores, backend.Metal.snapRestore(m, &s2, saved)); + const snap_ptr: *const backend.SavedSnap = @ptrCast(@alignCast(saved)); + try m.restoreSnap(c2, &s2, snap_ptr); + try std.testing.expectEqual(@as(usize, 128), c2.len); + try std.testing.expectEqual(@as(u64, 128), env.drafter.contexts.getPtr(&s2).?.end); + try std.testing.expectEqual(@as(u64, 64), env.drafter.contexts.getPtr(&s0).?.end); + + // Negative controls: active-lane restore refusal, out-of-step at_pos refusal, and drafter-less snapshot refusal. + try std.testing.expectError(error.DFlash2SnapshotGeometry, m.restoreSnap(c2, &s2, snap_ptr)); + c2.len = 0; + env.drafter.resetLane(&s2); + try std.testing.expectError(error.DFlash2SnapshotGeometry, env.drafter.restoreSnap(&s2, &snap_ptr.drafter.?.dflash2, 129)); + try std.testing.expectEqual(@as(u64, 0), env.drafter.contexts.getPtr(&s2).?.end); + + m.drafter = null; + const plain_saved = try backend.Metal.snapSave(m, &s1, 128); + defer backend.Metal.snapDrop(m, plain_saved); + m.drafter = .{ .dflash2 = &env.drafter }; + const plain_ptr: *const backend.SavedSnap = @ptrCast(@alignCast(plain_saved)); + try std.testing.expectError(error.DFlash2SnapshotMissing, m.restoreSnap(c2, &s2, plain_ptr)); + env.drafter.resetLane(&s2); + try std.testing.expectEqual(@as(u64, 0), env.drafter.contexts.getPtr(&s2).?.end); + try std.testing.expectEqual(@as(u64, 64), env.drafter.contexts.getPtr(&s0).?.end); +} diff --git a/zig/src/families/inkling2/metal/dflash2_state.zig b/zig/src/families/inkling2/metal/dflash2_state.zig new file mode 100644 index 00000000000..94b3de8ca59 --- /dev/null +++ b/zig/src/families/inkling2/metal/dflash2_state.zig @@ -0,0 +1,563 @@ +//! Fixed DFlash 2 scratch, per-stream sliding K/V rings, and GPU-private prompt-cache snapshots. +const std = @import("std"); +const mtl = @import("metal"); +const w = @import("dflash2_weights.zig"); +const st = @import("state.zig"); + +pub const absorb_rows: usize = 256; +pub const max_chunks: usize = (w.window_size + w.block_size + 127) / 128; +pub const max_context: u64 = 1048576; +pub const tap_row_bytes: usize = st.feature_row_bytes; +pub const row_bytes: usize = w.kv_width * 2; +pub const layer_row_bytes: u64 = @as(u64, w.layers_n) * 2 * row_bytes; +pub const Tail = struct { buf: mtl.Buffer, off: usize = 0 }; + +const scratch_fields = [_][]const u8{ + "ids", "resid", "x", "xc", "dyn", "q_raw", "k_raw", "v_raw", "q", "kb", "vb", "part", + "attn", "y", "yc", "gate", "up", "act", "logits", "hid", "tval", "tid", "seq", "fcx", + "hctx", "ck", "cv", +}; + +fn scratchSizes() [scratch_fields.len]usize { + const n = w.block_size; + const d = n - 1; + const a = absorb_rows; + const bf = 2; + return .{ + n * 4, + n * w.hidden * 4, + n * w.hidden * bf, + n * w.hidden * bf, + n * w.dyn_width * bf, + n * w.query_width * bf, + n * w.kv_width * bf, + n * w.kv_width * bf, + n * w.query_width * bf, + n * w.kv_width * bf, + n * w.kv_width * bf, + n * w.q_heads * max_chunks * 132 * 4, + n * w.query_width * bf, + n * w.hidden * bf, + n * w.hidden * bf, + n * w.intermediate * bf, + n * w.intermediate * bf, + n * w.intermediate * bf, + d * w.padded_vocab * bf, + d * w.rank * bf, + d * w.top_k * 4, + d * w.top_k * 4, + n * 4, + a * w.hidden * bf, + a * w.hidden * bf, + a * w.kv_width * bf, + a * w.kv_width * bf, + }; +} + +pub fn scratchBytes() u64 { + var total: u64 = 0; + for (scratchSizes()) |s| total += s; + return total; +} + +pub fn streamBytes() u64 { + return @as(u64, w.layers_n) * 2 * w.ring_size * row_bytes; +} + +pub const Scratch = struct { + ids: mtl.Buffer, + resid: mtl.Buffer, + x: mtl.Buffer, + xc: mtl.Buffer, + dyn: mtl.Buffer, + q_raw: mtl.Buffer, + k_raw: mtl.Buffer, + v_raw: mtl.Buffer, + q: mtl.Buffer, + kb: mtl.Buffer, + vb: mtl.Buffer, + part: mtl.Buffer, + attn: mtl.Buffer, + y: mtl.Buffer, + yc: mtl.Buffer, + gate: mtl.Buffer, + up: mtl.Buffer, + act: mtl.Buffer, + logits: mtl.Buffer, + hid: mtl.Buffer, + tval: mtl.Buffer, + tid: mtl.Buffer, + seq: mtl.Buffer, + fcx: mtl.Buffer, + hctx: mtl.Buffer, + ck: mtl.Buffer, + cv: mtl.Buffer, + + pub fn init(device: mtl.Device) !Scratch { + @setEvalBranchQuota(10_000); + const ns = scratchSizes(); + var s: Scratch = undefined; + var made: usize = 0; + errdefer inline for (scratch_fields, 0..) |f, i| if (i < made) @field(s, f).deinit(); + inline for (scratch_fields, 0..) |f, i| { + @field(s, f) = try device.buffer(@max(ns[i], 16), mtl.ResourceOptions.shared); + made += 1; + } + return s; + } + + pub fn deinit(s: *Scratch) void { + inline for (scratch_fields) |f| @field(s, f).deinit(); + s.* = undefined; + } +}; + +pub const Lane = struct { + k: [w.layers_n]mtl.Buffer, + v: [w.layers_n]mtl.Buffer, + from: u64 = 0, + end: u64 = 0, + held: [w.block_size - 1]u32 = @splat(0), + held_len: u32 = 0, + + pub fn init(device: mtl.Device) !Lane { + var l: Lane = .{ .k = undefined, .v = undefined }; + const bytes = w.ring_size * row_bytes; + var made: usize = 0; + errdefer for (0..made) |i| { + l.k[i].deinit(); + l.v[i].deinit(); + }; + for (0..w.layers_n) |i| { + l.k[i] = try device.buffer(bytes, mtl.ResourceOptions.private); + l.v[i] = device.buffer(bytes, mtl.ResourceOptions.private) catch |err| { + l.k[i].deinit(); + return err; + }; + made += 1; + } + return l; + } + + pub fn deinit(l: *Lane) void { + for (0..w.layers_n) |i| { + l.k[i].deinit(); + l.v[i].deinit(); + } + l.* = undefined; + } +}; + +/// Reset a lane back to position zero with no held drafts after a reset or failed restore. +pub fn clearLane(lane: *Lane) void { + lane.from = 0; + lane.end = 0; + lane.held_len = 0; +} + +/// Resolve an unabsorbed prompt-end or multi-stream tail tap row when `lane_end + 1 == at_pos`. +pub fn resolveTailTap(tap: st.Tap, at_pos: u32, lane_end: u64, tap_gen: u64) !?Tail { + if (lane_end == at_pos) return null; + if (lane_end + 1 != at_pos) return error.SnapshotOutOfStep; + const buf = tap.buf orelse return error.SnapshotOutOfStep; + if (tap.gen) |g| if (g != tap_gen) return error.StaleInkling2Taps; + if (lane_end < tap.start) return error.SnapshotOutOfStep; + const rows_before = std.math.cast(usize, lane_end - tap.start) orelse return error.SnapshotOutOfStep; + if (rows_before >= tap.rows) return error.SnapshotOutOfStep; + const delta = std.math.mul(usize, rows_before, tap_row_bytes) catch return error.SnapshotOutOfStep; + const src_off = std.math.add(usize, tap.off, delta) catch return error.SnapshotOutOfStep; + const src_end = std.math.add(usize, src_off, tap_row_bytes) catch return error.SnapshotOutOfStep; + if (src_end > buf.length()) return error.SnapshotOutOfStep; + return .{ .buf = buf, .off = src_off }; +} + +pub fn exactSnapBytes(rows: usize, has_tail: bool) u64 { + return @as(u64, rows) * layer_row_bytes + if (has_tail) @as(u64, tap_row_bytes) else 0; +} + +/// Upper bound on GPU-private snapshot bytes at `at` tokens (includes optional unabsorbed prompt-end tap row). +pub fn snapBytes(at: usize) u64 { + return exactSnapBytes(@min(at, w.window_size), true); +} + +/// Compact GPU-private snapshot of DFlash 2's active sliding K/V window [from, end) and optional tail tap. +pub const Snap = struct { + buf: ?mtl.Buffer = null, + from: u64, + end: u64, + bytes_held: u64, + tail_off: ?usize = null, + freed: bool = false, + follow: ?mtl.ResidencySet.Follow = null, + + pub fn bytes(at: usize) u64 { + return snapBytes(at); + } + + pub fn free(s: *Snap) void { + if (!s.freed) { + s.setResident(null); + if (s.buf) |b| b.deinit(); + s.buf = null; + s.freed = true; + } + } + + pub fn deinit(s: *Snap) void { + s.free(); + } + + pub fn setResident(s: *Snap, hook: ?mtl.ResidencySet.Follow) void { + if (s.freed) return; + const b = s.buf orelse return; + if (s.follow) |f| f.leave(f.ctx, b); + s.follow = hook; + if (hook) |f| f.join(f.ctx, b); + } + + pub fn save(device: mtl.Device, queue: mtl.Queue, lane: *const Lane, tail: ?Tail) !Snap { + if (lane.from > lane.end or lane.end > max_context) return error.DFlash2SnapshotGeometry; + for (0..w.layers_n) |i| { + if (lane.k[i].length() < w.ring_size * row_bytes or lane.v[i].length() < w.ring_size * row_bytes) { + return error.DFlash2SnapshotGeometry; + } + } + if (tail) |t| { + const tap_end = std.math.add(usize, t.off, tap_row_bytes) catch return error.DFlash2SnapshotGeometry; + if (tap_end > t.buf.length()) return error.DFlash2SnapshotGeometry; + } + const save_from: u64 = @max(lane.from, lane.end -| w.window_size); + const live_u64 = lane.end - save_from; + if (live_u64 > w.window_size) return error.DFlash2SnapshotGeometry; + const live_rows: usize = @intCast(live_u64); + const has_tail = tail != null; + const size = exactSnapBytes(live_rows, has_tail); + if (size == 0) { + return .{ .buf = null, .from = save_from, .end = lane.end, .bytes_held = 0, .tail_off = null }; + } + const tail_off: ?usize = if (has_tail) @intCast(size - tap_row_bytes) else null; + const buf = try device.buffer(@intCast(size), mtl.ResourceOptions.private); + errdefer buf.deinit(); + try blitSnap(queue, lane, buf, save_from, live_rows, tail, tail_off, false, "save"); + return .{ .buf = buf, .from = save_from, .end = lane.end, .bytes_held = size, .tail_off = tail_off }; + } + + pub fn restore(lane: *Lane, queue: mtl.Queue, snap: *const Snap) !void { + if (snap.freed or lane.end != 0 or lane.from != 0 or snap.from > snap.end or snap.end > max_context) { + return error.DFlash2SnapshotGeometry; + } + const live_u64 = snap.end - snap.from; + if (live_u64 > w.window_size) return error.DFlash2SnapshotGeometry; + const live_rows: usize = @intCast(live_u64); + const kv_bytes = exactSnapBytes(live_rows, false); + const need = exactSnapBytes(live_rows, snap.tail_off != null); + if (snap.bytes_held < need) return error.DFlash2SnapshotGeometry; + for (0..w.layers_n) |i| { + if (lane.k[i].length() < w.ring_size * row_bytes or lane.v[i].length() < w.ring_size * row_bytes) { + return error.DFlash2SnapshotGeometry; + } + } + if (need > 0) { + const buf = snap.buf orelse return error.DFlash2SnapshotGeometry; + if (buf.length() < need) return error.DFlash2SnapshotGeometry; + if (snap.tail_off) |to| { + if (to < kv_bytes) return error.DFlash2SnapshotGeometry; + const tail_end = std.math.add(usize, to, tap_row_bytes) catch return error.DFlash2SnapshotGeometry; + if (tail_end > snap.bytes_held or tail_end > buf.length()) return error.DFlash2SnapshotGeometry; + } + if (live_rows > 0) { + try blitSnap(queue, lane, buf, snap.from, live_rows, null, null, true, "restore"); + } + } else if (snap.tail_off != null) { + return error.DFlash2SnapshotGeometry; + } + lane.from = snap.from; + lane.end = snap.end; + lane.held_len = 0; + } +}; + +fn blitSnap( + queue: mtl.Queue, + lane: *const Lane, + snap_buf: mtl.Buffer, + save_from: u64, + live_rows: usize, + tail: ?Tail, + tail_off: ?usize, + restoring: bool, + comptime what: []const u8, +) !void { + if (live_rows == 0 and (restoring or tail == null)) return; + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const cb = queue.commandBuffer(); + const e = cb.blit(); + var at: usize = 0; + if (live_rows > 0) { + const start_slot: usize = @intCast(save_from % w.ring_size); + const first_rows = @min(live_rows, w.ring_size - start_slot); + const second_rows = live_rows - first_rows; + const first_off = start_slot * row_bytes; + const first_bytes = first_rows * row_bytes; + const second_bytes = second_rows * row_bytes; + for (0..w.layers_n) |i| { + for ([_]mtl.Buffer{ lane.k[i], lane.v[i] }) |ring_buf| { + if (restoring) { + e.copy(snap_buf, at, ring_buf, first_off, first_bytes); + if (second_bytes > 0) e.copy(snap_buf, at + first_bytes, ring_buf, 0, second_bytes); + } else { + e.copy(ring_buf, first_off, snap_buf, at, first_bytes); + if (second_bytes > 0) e.copy(ring_buf, 0, snap_buf, at + first_bytes, second_bytes); + } + at += first_bytes + second_bytes; + } + } + } + if (!restoring) { + if (tail) |t| e.copy(t.buf, t.off, snap_buf, tail_off.?, tap_row_bytes); + } + e.end(); + cb.commit(); + cb.wait(); + if (cb.failure()) |msg| { + std.log.err("inkling2_loop DFlash2 snapshot {s}: {s}", .{ what, msg }); + return error.GpuFailed; + } +} + +comptime { + if (w.window_size != 2048 or w.ring_size != 2176 or layer_row_bytes != 20480) { + @compileError("DFlash2 ring geometry drift"); + } + if (st.feature_row_bytes != tap_row_bytes) { + @compileError("DFlash2 tail tap row bytes mismatch"); + } +} + +test "DFlash2 stream, scratch, and snapshot byte accounting fit fixed ring geometry" { + try std.testing.expectEqual(@as(usize, 2176), w.ring_size); + try std.testing.expectEqual(@as(u64, 5 * 2 * 2176 * 1024 * 2), streamBytes()); + try std.testing.expect(scratchBytes() > 0); + try std.testing.expect(Snap.bytes(0) >= exactSnapBytes(0, true)); + try std.testing.expect(Snap.bytes(64) >= exactSnapBytes(64, false)); + try std.testing.expect(Snap.bytes(2048) >= exactSnapBytes(2048, true)); + try std.testing.expect(Snap.bytes(4096) >= exactSnapBytes(w.window_size, true)); + try std.testing.expectEqual(exactSnapBytes(w.window_size, true), Snap.bytes(2048)); + try std.testing.expectEqual(Snap.bytes(2048), Snap.bytes(8192)); +} + +test "DFlash2 resolveTailTap preserves non-first-stream tap offset and validates generation and bounds" { + const device = mtl.Device.init() catch return error.SkipZigTest; + const buf = try device.buffer(6 * tap_row_bytes, mtl.ResourceOptions.shared); + defer buf.deinit(); + const shared_tap: st.Tap = .{ .buf = buf, .off = 2 * tap_row_bytes, .start = 10, .rows = 3, .gen = 7 }; + try std.testing.expectEqual(@as(?Tail, null), try resolveTailTap(shared_tap, 13, 13, 7)); + const tail = (try resolveTailTap(shared_tap, 13, 12, 7)).?; + try std.testing.expectEqual(buf.id, tail.buf.id); + try std.testing.expectEqual(4 * tap_row_bytes, tail.off); + const stable_tap: st.Tap = .{ .buf = buf, .off = 2 * tap_row_bytes, .start = 10, .rows = 3, .gen = null }; + try std.testing.expectEqual(4 * tap_row_bytes, (try resolveTailTap(stable_tap, 13, 12, 99)).?.off); + try std.testing.expectError(error.StaleInkling2Taps, resolveTailTap(shared_tap, 13, 12, 8)); + try std.testing.expectError(error.SnapshotOutOfStep, resolveTailTap(shared_tap, 14, 13, 7)); + try std.testing.expectError(error.SnapshotOutOfStep, resolveTailTap(shared_tap, 13, 11, 7)); + try std.testing.expectError(error.SnapshotOutOfStep, resolveTailTap(shared_tap, 10, 9, 7)); + const truncated: st.Tap = .{ .buf = buf, .off = 5 * tap_row_bytes + 1, .start = 10, .rows = 1, .gen = 7 }; + try std.testing.expectError(error.SnapshotOutOfStep, resolveTailTap(truncated, 11, 10, 7)); +} + +fn blitCopy(queue: mtl.Queue, src: mtl.Buffer, src_off: usize, dst: mtl.Buffer, dst_off: usize, bytes: usize) !void { + if (bytes == 0) return; + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const cb = queue.commandBuffer(); + const e = cb.blit(); + e.copy(src, src_off, dst, dst_off, bytes); + e.end(); + cb.commit(); + cb.wait(); + if (cb.failure() != null) return error.GpuFailed; +} + +fn copyRingSpan( + queue: mtl.Queue, + ring_buf: mtl.Buffer, + flat: mtl.Buffer, + flat_off: usize, + from: u64, + rows: usize, + to_ring: bool, +) !void { + if (rows == 0) return; + const start_slot: usize = @intCast(from % w.ring_size); + const first_rows = @min(rows, w.ring_size - start_slot); + const second_rows = rows - first_rows; + const first_off = start_slot * row_bytes; + const first_bytes = first_rows * row_bytes; + const second_bytes = second_rows * row_bytes; + if (to_ring) { + try blitCopy(queue, flat, flat_off, ring_buf, first_off, first_bytes); + try blitCopy(queue, flat, flat_off + first_bytes, ring_buf, 0, second_bytes); + } else { + try blitCopy(queue, ring_buf, first_off, flat, flat_off, first_bytes); + try blitCopy(queue, ring_buf, 0, flat, flat_off + first_bytes, second_bytes); + } +} + +test "DFlash2 snapshot preserves ring wrap-around, non-first-stream tail tap, and rejects active lanes" { + const device = mtl.Device.init() catch return error.SkipZigTest; + const queue = try device.queue(); + defer queue.deinit(); + var from = try Lane.init(device); + defer from.deinit(); + var to = try Lane.init(device); + defer to.deinit(); + + const start_pos: u64 = 2100; + const end_pos: u64 = 2300; + const rows: usize = @intCast(end_pos - start_pos); + const total_bytes = rows * layer_row_bytes; + const want = try device.buffer(total_bytes, mtl.ResourceOptions.shared); + defer want.deinit(); + const got = try device.buffer(total_bytes, mtl.ResourceOptions.shared); + defer got.deinit(); + var prng = std.Random.DefaultPrng.init(31); + prng.random().bytes(want.slice(u8, total_bytes)); + + // Poison destination ring bytes while metadata stays cleared to prove restore overwrites active slots cleanly. + const dirty = try device.buffer(w.ring_size * row_bytes, mtl.ResourceOptions.shared); + defer dirty.deinit(); + @memset(dirty.slice(u8, w.ring_size * row_bytes), 0xa5); + for (0..w.layers_n) |i| { + try blitCopy(queue, dirty, 0, from.k[i], 0, w.ring_size * row_bytes); + try blitCopy(queue, dirty, 0, from.v[i], 0, w.ring_size * row_bytes); + try blitCopy(queue, dirty, 0, to.k[i], 0, w.ring_size * row_bytes); + try blitCopy(queue, dirty, 0, to.v[i], 0, w.ring_size * row_bytes); + } + var off: usize = 0; + for (0..w.layers_n) |i| { + try copyRingSpan(queue, from.k[i], want, off, start_pos, rows, true); + off += rows * row_bytes; + try copyRingSpan(queue, from.v[i], want, off, start_pos, rows, true); + off += rows * row_bytes; + } + from.from = start_pos; + from.end = end_pos; + + const taps = try device.buffer(5 * tap_row_bytes, mtl.ResourceOptions.shared); + defer taps.deinit(); + const tap_bytes = taps.slice(u8, 5 * tap_row_bytes); + prng.random().bytes(tap_bytes); + const tail_off_src = 3 * tap_row_bytes; + try std.testing.expect(!std.mem.eql(u8, tap_bytes[0..tap_row_bytes], tap_bytes[tail_off_src..][0..tap_row_bytes])); + + var snap = try Snap.save(device, queue, &from, .{ .buf = taps, .off = tail_off_src }); + defer snap.free(); + try std.testing.expectEqual(start_pos, snap.from); + try std.testing.expectEqual(end_pos, snap.end); + try std.testing.expectEqual(exactSnapBytes(rows, true), snap.bytes_held); + try std.testing.expectEqual(@as(?usize, @intCast(total_bytes)), snap.tail_off); + + // Restoring into an active lane is refused; after clearLane it succeeds bit-identically. + to.end = 17; + try std.testing.expectError(error.DFlash2SnapshotGeometry, Snap.restore(&to, queue, &snap)); + clearLane(&to); + try Snap.restore(&to, queue, &snap); + try std.testing.expectEqual(start_pos, to.from); + try std.testing.expectEqual(end_pos, to.end); + try std.testing.expectEqual(@as(u32, 0), to.held_len); + + off = 0; + for (0..w.layers_n) |i| { + try copyRingSpan(queue, to.k[i], got, off, start_pos, rows, false); + off += rows * row_bytes; + try copyRingSpan(queue, to.v[i], got, off, start_pos, rows, false); + off += rows * row_bytes; + } + try std.testing.expectEqualSlices(u8, want.slice(u8, total_bytes), got.slice(u8, total_bytes)); + + const got_tail = try device.buffer(tap_row_bytes, mtl.ResourceOptions.shared); + defer got_tail.deinit(); + try blitCopy(queue, snap.buf.?, snap.tail_off.?, got_tail, 0, tap_row_bytes); + try std.testing.expectEqualSlices(u8, tap_bytes[tail_off_src..][0..tap_row_bytes], got_tail.slice(u8, tap_row_bytes)); + try std.testing.expect(!std.mem.eql(u8, tap_bytes[0..tap_row_bytes], got_tail.slice(u8, tap_row_bytes))); + try std.testing.expectError(error.DFlash2SnapshotGeometry, Snap.save(device, queue, &from, .{ .buf = taps, .off = 4 * tap_row_bytes + 1 })); +} + +test "DFlash2 snapshot clamps retention to window_size across wrap-around and validates geometry" { + const device = mtl.Device.init() catch return error.SkipZigTest; + const queue = try device.queue(); + defer queue.deinit(); + var from = try Lane.init(device); + defer from.deinit(); + var to = try Lane.init(device); + defer to.deinit(); + + // Empty lane snapshot works cleanly without GPU buffer allocation. + from.from = 128; + from.end = 128; + var empty = try Snap.save(device, queue, &from, null); + defer empty.free(); + try std.testing.expect(empty.buf == null); + try std.testing.expectEqual(@as(u64, 0), empty.bytes_held); + try Snap.restore(&to, queue, &empty); + try std.testing.expectEqual(@as(u64, 128), to.from); + try std.testing.expectEqual(@as(u64, 128), to.end); + clearLane(&to); + + // End past ring_size with from == 0 saves [2300 - 2048 .. 2300) = [252 .. 2300) wrapping ring_size = 2176. + const save_from: u64 = 2300 - w.window_size; + const full_bytes = w.window_size * layer_row_bytes; + const want = try device.buffer(full_bytes, mtl.ResourceOptions.shared); + defer want.deinit(); + const got = try device.buffer(full_bytes, mtl.ResourceOptions.shared); + defer got.deinit(); + var prng = std.Random.DefaultPrng.init(77); + prng.random().bytes(want.slice(u8, full_bytes)); + var off: usize = 0; + for (0..w.layers_n) |i| { + try copyRingSpan(queue, from.k[i], want, off, save_from, w.window_size, true); + off += w.window_size * row_bytes; + try copyRingSpan(queue, from.v[i], want, off, save_from, w.window_size, true); + off += w.window_size * row_bytes; + } + from.from = 0; + from.end = 2300; + var snap = try Snap.save(device, queue, &from, null); + defer snap.free(); + try std.testing.expectEqual(save_from, snap.from); + try std.testing.expectEqual(@as(u64, 2300), snap.end); + try std.testing.expectEqual(exactSnapBytes(w.window_size, false), snap.bytes_held); + try Snap.restore(&to, queue, &snap); + try std.testing.expectEqual(save_from, to.from); + try std.testing.expectEqual(@as(u64, 2300), to.end); + off = 0; + for (0..w.layers_n) |i| { + try copyRingSpan(queue, to.k[i], got, off, save_from, w.window_size, false); + off += w.window_size * row_bytes; + try copyRingSpan(queue, to.v[i], got, off, save_from, w.window_size, false); + off += w.window_size * row_bytes; + } + try std.testing.expectEqualSlices(u8, want.slice(u8, full_bytes), got.slice(u8, full_bytes)); + + // Geometry error guards: bad lane bounds, truncated bytes, overlapping tail_off, out-of-range end, and freed snap. + from.from = 500; + from.end = 400; + try std.testing.expectError(error.DFlash2SnapshotGeometry, Snap.save(device, queue, &from, null)); + from.from = 0; + from.end = max_context + 1; + try std.testing.expectError(error.DFlash2SnapshotGeometry, Snap.save(device, queue, &from, null)); + clearLane(&to); + var bad = snap; + bad.bytes_held -= 1; + try std.testing.expectError(error.DFlash2SnapshotGeometry, Snap.restore(&to, queue, &bad)); + var bad_tail = snap; + bad_tail.tail_off = 0; + try std.testing.expectError(error.DFlash2SnapshotGeometry, Snap.restore(&to, queue, &bad_tail)); + var bad_end = snap; + bad_end.from = max_context; + bad_end.end = max_context + 1; + try std.testing.expectError(error.DFlash2SnapshotGeometry, Snap.restore(&to, queue, &bad_end)); + snap.free(); + try std.testing.expectError(error.DFlash2SnapshotGeometry, Snap.restore(&to, queue, &snap)); +} diff --git a/zig/src/families/inkling2/metal/drafter_snap.zig b/zig/src/families/inkling2/metal/drafter_snap.zig new file mode 100644 index 00000000000..1c99d494966 --- /dev/null +++ b/zig/src/families/inkling2/metal/drafter_snap.zig @@ -0,0 +1,83 @@ +//! Unified prompt-cache snapshot adapter for Inkling 2 Mini drafters (DSpark and DFlash 2). +const mtl = @import("metal"); +const lanes = @import("lanes"); +const st = @import("state.zig"); +const snapshot = @import("snapshot.zig"); +const dspark = @import("dspark.zig"); +const dspark_state = @import("dspark_state.zig"); +const dflash2 = @import("dflash2.zig"); +const dflash2_state = @import("dflash2_state.zig"); + +pub const Drafter = union(enum) { + dspark: *dspark.Drafter, + dflash2: *dflash2.Drafter, + + pub fn snapBytes(d: Drafter, at: usize) u64 { + return switch (d) { + .dspark => dspark_state.Snap.bytes(at), + .dflash2 => dflash2_state.Snap.bytes(at), + }; + } + + pub fn saveSnap(d: Drafter, stream: *lanes.Stream, at: u32, tap: st.Tap, tap_gen: u64) !?Snap { + return switch (d) { + .dspark => |ds| if (try ds.saveSnap(stream, at, tap, tap_gen)) |s| .{ .dspark = s } else null, + .dflash2 => |df| if (try df.saveSnap(stream, at, tap, tap_gen)) |s| .{ .dflash2 = s } else null, + }; + } + + pub fn restoreSnap(d: Drafter, stream: *lanes.Stream, snap: ?*const Snap, at: usize) !void { + switch (d) { + .dspark => |ds| { + const s: ?*const dspark_state.Snap = if (snap) |dr| switch (dr.*) { + .dspark => |*x| x, + .dflash2 => return error.DSparkSnapshotMissing, + } else null; + try ds.restoreSnap(stream, s, at); + }, + .dflash2 => |df| { + const s: ?*const dflash2_state.Snap = if (snap) |dr| switch (dr.*) { + .dflash2 => |*x| x, + .dspark => return error.DFlash2SnapshotMissing, + } else null; + try df.restoreSnap(stream, s, at); + }, + } + } + + pub fn resetLane(d: Drafter, stream: *lanes.Stream) void { + switch (d) { + .dspark => |ds| ds.resetLane(stream), + .dflash2 => |df| df.resetLane(stream), + } + } +}; + +pub const Snap = union(enum) { + dspark: dspark_state.Snap, + dflash2: dflash2_state.Snap, + + pub fn free(s: *Snap) void { + switch (s.*) { + .dspark => |*ds| ds.free(), + .dflash2 => |*df| df.free(), + } + } + + pub fn setResident(s: *Snap, hook: ?mtl.ResidencySet.Follow) void { + switch (s.*) { + .dspark => |*ds| ds.setResident(hook), + .dflash2 => |*df| df.setResident(hook), + } + } +}; + +pub const Saved = struct { + target: snapshot.Snap, + drafter: ?Snap = null, + + pub fn free(s: *Saved) void { + if (s.drafter) |*dr| dr.free(); + s.target.free(); + } +}; diff --git a/zig/src/families/inkling2/metal/host_test.zig b/zig/src/families/inkling2/metal/host_test.zig index 87097e6791b..dbc332bccee 100644 --- a/zig/src/families/inkling2/metal/host_test.zig +++ b/zig/src/families/inkling2/metal/host_test.zig @@ -21,7 +21,10 @@ test { _ = @import("dense_test.zig"); _ = @import("dflash2_weights.zig"); _ = @import("dflash2_kernels.zig"); + _ = @import("dflash2_state.zig"); + _ = @import("drafter_snap.zig"); _ = @import("dflash2.zig"); + _ = @import("dflash2_snap_test.zig"); _ = @import("backend.zig"); _ = @import("images.zig"); _ = @import("vision_image_test.zig"); diff --git a/zig/src/families/qwen3_5/cuda.zig b/zig/src/families/qwen3_5/cuda.zig index 23921c7e707..3ba5f5d83c4 100644 --- a/zig/src/families/qwen3_5/cuda.zig +++ b/zig/src/families/qwen3_5/cuda.zig @@ -62,6 +62,7 @@ test { _ = @import("cuda_kv_host_test.zig"); _ = @import("cuda_pages_lifetime_test.zig"); _ = @import("cuda_mtp_area_test.zig"); + _ = @import("cuda_mtp_paged_test.zig"); _ = @import("cuda_prefix.zig"); _ = @import("cuda_prefix_fault_test.zig"); _ = @import("cuda_pend_test.zig"); diff --git a/zig/src/families/qwen3_5/cuda_engine.zig b/zig/src/families/qwen3_5/cuda_engine.zig index 029a735d13a..e4ca5f1bce6 100644 --- a/zig/src/families/qwen3_5/cuda_engine.zig +++ b/zig/src/families/qwen3_5/cuda_engine.zig @@ -69,6 +69,7 @@ pub const Engine = struct { dir: []const u8, pockets: pocket.Pockets, learning: ?*const hooks.Keep = null, + rollback_capable: bool = true, mlp: ?hooks.MlpAdd = null, taught: u64 = 0, d: *const cuda.Driver, @@ -187,6 +188,7 @@ pub const Engine = struct { e.pockets = try pocket.Pockets.init(gpa, d, g.hidden, g.layers); errdefer e.pockets.deinit(); e.learning = null; + e.rollback_capable = true; e.mlp = null; e.taught = 0; e.kit = null; @@ -337,12 +339,10 @@ pub const Engine = struct { e.stream.deinit(); e.gpa.destroy(e); } - /// A stream's device bytes at a `cap`-token window: recurrences, convolution tails, keys and values, taps, log. pub fn streamBytes(e: *const Engine, cap: usize) usize { return e.streamBytesWithTaps(cap, e.n_taps); } - /// The same allocation plan for a tap count known before `setTaps` mutates the engine. pub fn streamBytesWithTaps(e: *const Engine, cap: usize, taps: usize) usize { const c = @import("cuda_cache.zig"); @@ -487,11 +487,11 @@ pub const Engine = struct { try p.cache.settle(e); // pending kept rows ride in a recorded slot scan; any other pass reads the state as written if (!(record and keep != .hidden)) try p.cache.flush(e); - try recurrent.prepare(e, p.cache, p.rows, record, p.undo); + try recurrent.prepare(e, p.cache, p.rows, record, recurrent.effectiveUndo(e, p)); } var row0: usize = 0; for (parts, 0..) |p, i| { - segs[i] = stagedSeg(p.cache, e, p.cache.len, row0, p.rows, p.undo); + segs[i] = stagedSeg(p.cache, e, p.cache.len, row0, p.rows, recurrent.effectiveUndo(e, p)); row0 += p.rows; } if (keep == .draws) { @@ -524,7 +524,7 @@ pub const Engine = struct { if (!record and taps_active) shape.tap_from = e.mtp_prompt.tapFrom(parts[0].cache.len, total); if (record) for (parts) |p| { try recurrent.mark(p.cache, false); - if (p.rows == 1 and p.undo) try recurrent.mark(p.cache, true); + if (p.rows == 1 and recurrent.effectiveUndo(e, p)) try recurrent.mark(p.cache, true); }; shape.hidden = keep == .hidden; shape.rows = keep == .rows; @@ -539,7 +539,7 @@ pub const Engine = struct { e.features = if (images) |im| im.features else 0; defer e.features = 0; if (g.whole == 0) try e.launchShape(shape) else try stage_fwd.run(e, shape, total); - for (parts) |p| p.cache.advanced(p.rows, record, p.undo); + for (parts) |p| p.cache.advanced(p.rows, record, recurrent.effectiveUndo(e, p)); if (!g.heads) return recurrent.completed(e); // a stage without the head: no logits to keep if (e.held) |h| return h.hold(st, shape, total); // rank 0 with rounds in flight: its head runs at `land` try e.land(parts, keep, total); diff --git a/zig/src/families/qwen3_5/cuda_mtp.zig b/zig/src/families/qwen3_5/cuda_mtp.zig index 888c1c49b97..fee8df1e692 100644 --- a/zig/src/families/qwen3_5/cuda_mtp.zig +++ b/zig/src/families/qwen3_5/cuda_mtp.zig @@ -224,6 +224,7 @@ pub const Mtp = struct { const max_c_int: usize = @intCast(std.math.maxInt(c_int)); if (d.capacity == 0 or d.capacity > max_c_int) return error.UnsupportedMtpGeometry; const hidden_bytes = try weights.checkedMul(d.e.g.hidden, 2); + const target_tap_bytes = try weights.checkedMul(try weights.checkedMul(d.taps().len, d.e.tapRows()), hidden_bytes); const kv_width = try weights.checkedMul(d.e.g.kv_heads, head_dim); d.ring_bytes = try arrayBytes(try weights.checkedMul(2, d.capacity), kv_width, 2); const aligned_ring = try weights.checkedAligned(d.ring_bytes); @@ -232,6 +233,7 @@ pub const Mtp = struct { d.area_bytes = try weights.checkedAdd(d.area_bytes, try weights.checkedMul(max_lanes, 4)); d.stream_bytes = try weights.checkedAdd(d.ring_bytes, try weights.checkedMul(2, hidden_bytes)); d.stream_bytes = try weights.checkedAdd(d.stream_bytes, try weights.checkedMul(max_lanes, 4)); + d.stream_bytes = try weights.checkedAdd(d.stream_bytes, target_tap_bytes); d.scratch_bytes = try d.layout(false); } diff --git a/zig/src/families/qwen3_5/cuda_mtp_area_test.zig b/zig/src/families/qwen3_5/cuda_mtp_area_test.zig index 59fba5efe03..2ebdc3ae691 100644 --- a/zig/src/families/qwen3_5/cuda_mtp_area_test.zig +++ b/zig/src/families/qwen3_5/cuda_mtp_area_test.zig @@ -18,6 +18,7 @@ const Runs = struct { test "MTP on a pool lane borrows its run's area: ring, then 256-aligned states, given back with the lane" { var e: E = undefined; e.d = undefined; + e.scratch_rows = 4096; e.g.kv_heads = 2; e.g.hidden = 2048; e.g.intermediate = 128; @@ -136,3 +137,31 @@ test "MTP context lifecycle: release returns an interrupted stream's context res try t.expectEqual(@as(usize, 0), d.streams.count()); try t.expectEqual(@as(usize, 1), d.pool.items.len); } + +test "MTP on a pool lane: admission includes the target tap ring exactly once" { + var e: E = undefined; + e.d = undefined; + e.scratch_rows = 4096; + e.g.hidden = 5120; + e.g.intermediate = 17408; + e.g.layers = 64; + e.g.q_heads = 24; + e.g.vocab = 248320; + e.g.kv_heads = 4; + e.g.experts = 0; + var d: mtp.Mtp = undefined; + d.e = &e; + d.capacity = 6144; + d.tap = .{63}; + try d.initializeMemorySizes(); + const hidden_bytes = e.g.hidden * 2; + const tap_bytes = 6144 * hidden_bytes; + const expected = d.ring_bytes + 2 * hidden_bytes + mtp.max_lanes * 4 + tap_bytes; + try t.expectEqual(@as(usize, 60 * 1024 * 1024), tap_bytes); + try t.expectEqual(expected, d.stream_bytes); + const first = d.stream_bytes; + try d.initializeMemorySizes(); + try t.expectEqual(first, d.stream_bytes); + const target_baseline: usize = 1024 * 1024; + try t.expectEqual(target_baseline + expected, target_baseline + d.stream_bytes); +} diff --git a/zig/src/families/qwen3_5/cuda_mtp_paged_test.zig b/zig/src/families/qwen3_5/cuda_mtp_paged_test.zig new file mode 100644 index 00000000000..0a9cd19efd9 --- /dev/null +++ b/zig/src/families/qwen3_5/cuda_mtp_paged_test.zig @@ -0,0 +1,44 @@ +//! Paged MTP admission: the target tap is in the lane's run, never an additional fixed charge. +const std = @import("std"); +const mtp = @import("cuda_mtp.zig"); +const native = @import("cuda_native.zig"); +const Cache = @import("cuda_cache.zig").Cache; +const E = @import("cuda_engine.zig").Engine; +const t = std.testing; + +test "MTP on a pool lane: admission includes the target tap ring exactly once, paged fixed bytes" { + var e: E = undefined; + e.d = undefined; + e.scratch_rows = 4096; + e.g.hidden = 5120; + e.g.intermediate = 17408; + e.g.layers = 64; + e.g.q_heads = 24; + e.g.vocab = 248320; + e.g.kv_heads = 4; + e.g.k_heads = 1; + e.g.v_heads = 1; + e.g.experts = 0; + e.g.first = 0; + e.g.linear = @splat(false); + var d: mtp.Mtp = undefined; + d.e = &e; + d.capacity = 6144; + d.tap = .{63}; + try d.initializeMemorySizes(); + const tap_bytes = 6144 * e.g.hidden * 2; + try t.expectEqual(@as(usize, 60 * 1024 * 1024), tap_bytes); + + e.n_taps = d.taps().len; + e.rollback_capable = false; + var l: native.Lanes = .{ .gpa = t.allocator, .io = undefined, .e = &e, .capacity = d.capacity, .page_tokens = 256, .target = undefined, .mtp = &d }; + e.n_taps = 0; + const run_without_tap = Cache.runBytes(&e, l.ringBytes()); + e.n_taps = d.taps().len; + const run_with_tap = Cache.runBytes(&e, l.ringBytes()); + try t.expectEqual(run_without_tap + tap_bytes, run_with_tap); + const paged = native.pagedLayout(&l, d.stream_bytes).?; + const table_bytes = ((d.capacity + native.window_rows + 255) / 256) * 4; + try t.expectEqual(table_bytes, paged.fixed_bytes); + try t.expectEqual(run_with_tap, paged.run_bytes); +} diff --git a/zig/src/families/qwen3_5/cuda_native.zig b/zig/src/families/qwen3_5/cuda_native.zig index cdc74fc66c2..d95d90fd408 100644 --- a/zig/src/families/qwen3_5/cuda_native.zig +++ b/zig/src/families/qwen3_5/cuda_native.zig @@ -116,12 +116,12 @@ pub const Loaded = struct { pub const cacheBytes = plan.cacheBytes; pub const cacheBytesWithTaps = plan.cacheBytesWithTaps; -/// The pool's layout with a drafter (`extra` bytes a stream): DFlash2's ring and taps in the run, the rest fixed. +/// The pool's layout with a drafter (`extra` bytes a stream): its ring and target taps in the run, the rest fixed. pub fn pagedLayout(p: *anyopaque, extra: u64) ?kv_pool.Layout { const l: *Lanes = @ptrCast(@alignCast(p)); if (l.page_tokens == 0) return null; const ring = l.ringBytes(); - const in_run = ring + if (l.draft != null) l.e.tapBytes() else 0; // DFlash2 counts the target's taps as its own + const in_run = ring + if (l.draft != null or l.mtp != null) l.e.tapBytes() else 0; // DFlash2 and MTP count the target's taps as their own l.extra = @intCast(extra -| in_run); return pages_mod.layout(l.e, l.capacity, l.page_tokens, ring, l.extra); } @@ -177,7 +177,6 @@ pub fn open(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: [ loaded.readouts = j.readout().info; return loaded; } - /// `open` without the decision-only refusals: the runners open a BF16 backbone with a test readout through it. pub fn openLanes(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: []const u8, kernels: ?[]const u8, o: Options) !Loaded { if (kernels != null) return error.QwenHasNoCapturedKernels; @@ -195,6 +194,7 @@ pub fn openLanes(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, d if (share_snaps > 0 and page_tokens == 0) return error.QwenShareNeedsPages; if (kv_host_mod.onHost() and share_snaps == 0) std.log.warn("TF_QWEN_KV_HOST pins the KV pages in host memory; the prompt cache would pin more beside them: set --prompt-cache-gib to bound it", .{}); const e = try E.Engine.init(gpa, io, ctx, dir, o.kv8, fitOf(o), o.context); + e.rollback_capable = o.slide; errdefer e.deinit(); if (o.rope_yarn) |f| { // --rope-yarn over the downloaded config: its table, and the window it allows var arena = std.heap.ArenaAllocator.init(gpa); diff --git a/zig/src/families/qwen3_5/cuda_recurrent.zig b/zig/src/families/qwen3_5/cuda_recurrent.zig index 3cf10c14322..6a58b20e707 100644 --- a/zig/src/families/qwen3_5/cuda_recurrent.zig +++ b/zig/src/families/qwen3_5/cuda_recurrent.zig @@ -64,6 +64,11 @@ pub fn prepare(e: *Engine, c: *Cache, rows: usize, record: bool, undo: bool) !vo if (rows == 1 and undo) try ensure(e, c, true, e.g.stateBytes(), false); } +/// Whether the forward actually stages rollback state for this part. +pub fn effectiveUndo(e: *const Engine, p: @import("cuda_engine.zig").Part) bool { + return p.undo and e.rollback_capable; +} + pub fn mark(c: *Cache, before: bool) !void { const pool = c.owner orelse return; const lease = if (before) c.before_lease else c.log_lease; @@ -82,9 +87,9 @@ pub fn idle(e: *Engine) void { e.rec_scratch.collect(@intFromPtr(e), Provider{ .e = e }) catch unreachable; } -/// What one scratch-owning cache may hold at once: a rollback copy and a widest window's log (1.1.1's own two). +/// What one scratch-owning cache may hold at once: a rollback copy when capable and a widest window's log. pub fn bound(e: *const Engine) usize { - return e.g.stateBytes() + e.g.logBytes(@import("cuda_engine.zig").most_window); + return (if (e.rollback_capable) e.g.stateBytes() else 0) + e.g.logBytes(@import("cuda_engine.zig").most_window); } pub fn shutdown(e: *Engine) void { diff --git a/zig/src/native/inkling2.zig b/zig/src/native/inkling2.zig index 37b03d397c2..96abbc590b8 100644 --- a/zig/src/native/inkling2.zig +++ b/zig/src/native/inkling2.zig @@ -10,7 +10,9 @@ const dspark = @import("../families/inkling2/metal/dspark.zig"); const admit = @import("../families/inkling2/metal/admit.zig"); const vision = @import("../families/inkling2/metal/vision.zig"); const dflash2 = @import("../families/inkling2/metal/dflash2.zig"); +const dflash2_state = @import("../families/inkling2/metal/dflash2_state.zig"); const dflash2_weights = @import("../families/inkling2/metal/dflash2_weights.zig"); +const snapshot = @import("../families/inkling2/metal/snapshot.zig"); const AttachedDrafter = union(enum) { dspark: *dspark.Drafter, @@ -255,9 +257,9 @@ pub fn open(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, o: api.Ope switch (d) { .dspark => |ds| { try ds.warm(@intCast(streams)); - h.metal.drafter = ds; + h.metal.drafter = .{ .dspark = ds }; }, - .dflash2 => {}, + .dflash2 => |df| h.metal.drafter = .{ .dflash2 = df }, } h.drafted = try lanes.drafted.Drafted.init(gpa, h.metal.backend(), d.iface()); h.drafted.?.first_rows = true; @@ -272,7 +274,7 @@ pub fn open(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, o: api.Ope h.host = api.LaneHost.init(gpa, io, &h.core, .{ .lanes = o.lanes, .context_window = @intCast(window), .prefill_step = st.prompt_rows, .decode_share = o.decode_share, .structures = true, .logprobs = true, .draft_sources = .{ .drafter = if (drafter) |d| .{ .kind = d.kind(), .name = o.drafter_name orelse drafter_dir.? } else null } }); if (o.vision) |v| h.host.info_.vision = .{ .ctx = h, .prepare = Host.prepare, .image_token = model.config.image_token, .markers = &h.markers, .part_type = "image", .image_tokens = v.image_tokens, .max_images = v.max_images, .explain = vision.problem }; h.cache = null; - h.cache_cap = if (o.prompt_cache_gib) |g| @intFromFloat(g * (1 << 30)) else budget; + h.cache_cap = promptCacheCap(o.prompt_cache_gib, budget); if (h.cache_cap > 0) { const M = backend.Metal; const rules: api.prompt_cache.Rules = .{ .lookahead = 0, .planned = true, .grid = st.prompt_rows, .min_prompt = 0 }; @@ -321,6 +323,10 @@ fn longest(bytes: u64, most: u32, streams: u64, draft_fixed: u64, draft_token: u return lo; } +fn promptCacheCap(prompt_cache_gib: ?f64, budget: u64) u64 { + return if (prompt_cache_gib) |g| @intFromFloat(g * (1 << 30)) else budget; +} + fn fitCache(ctx: *anyopaque, bytes: u64, restoring: ?*anyopaque, prompt: []const u32) void { const h: *Host = @ptrCast(@alignCast(ctx)); const store = if (h.cache) |*owned| owned else return; @@ -466,3 +472,56 @@ test "Inkling native longest context accounts target, streams and shared draft s const shared = dspark.Drafter.scoreBytes(1) - dspark.Drafter.scoreBytes(0); try std.testing.expectEqual(@as(usize, 262144), longest(36 << 30, 262144, 8, fixed, token, shared)); } + +test "Inkling native DFlash2 reservation, prompt_cache_gib bounds, and fitCache eviction" { + const df: AttachedDrafter = .{ .dflash2 = undefined }; + try std.testing.expectEqual(dflash2.streamBytes(), df.streamFixed()); + try std.testing.expectEqual(@as(u64, 0), df.streamToken()); + try std.testing.expectEqual(@as(u64, 0), df.sharedToken()); + try std.testing.expectEqual(4 * dflash2.streamBytes(), df.reservedBytes(4, 16384)); + + const budget = st.cacheBytes(128) + 2 * df.streamFixed(); + try std.testing.expectEqual(@as(usize, 128), longest(budget, 256, 2, df.streamFixed(), df.streamToken(), df.sharedToken())); + try std.testing.expectEqual(@as(u64, 0), promptCacheCap(0, budget)); + try std.testing.expectEqual(@as(u64, 2 << 30), promptCacheCap(2.0, budget)); + try std.testing.expectEqual(budget, promptCacheCap(null, budget)); + + const SnapMock = struct { + dropped: usize = 0, + fn bytes(_: *anyopaque, at: u32) u64 { + return snapshot.bytes(at) + dflash2_state.Snap.bytes(at); + } + fn save(ptr: *anyopaque, _: ?*anyopaque, _: u32) anyerror!*anyopaque { + return ptr; + } + fn restore(_: *anyopaque, _: ?*anyopaque, _: *anyopaque) anyerror!void {} + fn drop(ptr: *anyopaque, _: *anyopaque) void { + const self: *@This() = @ptrCast(@alignCast(ptr)); + self.dropped += 1; + } + }; + var mock: SnapMock = .{}; + const snap_128 = SnapMock.bytes(&mock, 128); + const snap_256 = SnapMock.bytes(&mock, 256); + var host: Host = undefined; + host.cache_cap = snap_128 + snap_256; + const rules: api.prompt_cache.Rules = .{ .lookahead = 0, .planned = true, .grid = st.prompt_rows, .min_prompt = 0 }; + host.cache = api.prompt_cache.Store.init(std.testing.allocator, .{ + .ptr = &mock, + .vtable = &.{ .bytes = SnapMock.bytes, .save = SnapMock.save, .restore = SnapMock.restore, .drop = SnapMock.drop }, + }, rules, host.cache_cap); + defer host.cache.?.deinit(); + + var p1: [192]u32 = undefined; + var p2: [320]u32 = undefined; + for (&p1, 0..) |*t, i| t.* = @intCast(i + 1); + for (&p2, 0..) |*t, i| t.* = @intCast(i + 1000); + try std.testing.expect(host.cache.?.keep(&p1, 128, null, &.{}, &.{})); + try std.testing.expect(host.cache.?.keep(&p2, 256, null, &.{}, &.{})); + try std.testing.expectEqual(snap_128 + snap_256, host.cache.?.held); + + // Tightening available budget triggers fitCache eviction and calls snapDrop cleanly. + fitCache(&host, snap_256, null, &.{}); + try std.testing.expectEqual(@as(usize, 1), mock.dropped); + try std.testing.expect(host.cache.?.held <= snap_256); +}