From 9ccfbc1f2199274ae932c50d52c8a413e828d322 Mon Sep 17 00:00:00 2001 From: Kevin Gilbertson <880013+gilby@users.noreply.github.com> Date: Fri, 30 Oct 2026 18:16:19 +0100 Subject: [PATCH 01/15] dsv41 metal: the lane target, the prompt cache and the native server over Metal target.zig is the lanes' verify target: a slot's prompt, its windows of rows for several slots in one launch, keeps and rewinds, and kept prompt states (the prompt cache) whose resumed rows the reply reports as cached_tokens. boot.zig loads a release checkpoint folder and entry.zig serves it as tensorfold-dsv41 (dsv41-metal-serve). Tests serve the tiny model through LaneHost: concurrent equals solo equals serial, drafted equals draft:false, cache hits equal fresh runs, seeds and cancels. --- zig/build/dsv41_metal.zig | 32 +- zig/src/families/deepseek_v41/draft/iface.zig | 7 + zig/src/families/deepseek_v41/draft/lanes.zig | 1 + zig/src/families/deepseek_v41/metal/boot.zig | 144 ++++++ zig/src/families/deepseek_v41/metal/entry.zig | 44 ++ zig/src/families/deepseek_v41/metal/metal.zig | 8 +- zig/src/families/deepseek_v41/metal/pass.zig | 57 +++ zig/src/families/deepseek_v41/metal/serve.zig | 121 +++++ .../families/deepseek_v41/metal/snapshots.zig | 154 +++++++ .../families/deepseek_v41/metal/target.zig | 418 ++++++++++++++++++ .../families/deepseek_v41/phases_timed.zig | 6 +- zig/tests/dsv41_metal/boot_test.zig | 171 +++++++ zig/tests/dsv41_metal/fixture_serve.zig | 69 +++ zig/tests/dsv41_metal/layer_test.zig | 1 + zig/tests/dsv41_metal/multi_test.zig | 219 +++++++++ zig/tests/dsv41_metal/serve_test.zig | 267 +++++++++++ 16 files changed, 1716 insertions(+), 3 deletions(-) create mode 100644 zig/src/families/deepseek_v41/metal/boot.zig create mode 100644 zig/src/families/deepseek_v41/metal/entry.zig create mode 100644 zig/src/families/deepseek_v41/metal/pass.zig create mode 100644 zig/src/families/deepseek_v41/metal/serve.zig create mode 100644 zig/src/families/deepseek_v41/metal/snapshots.zig create mode 100644 zig/src/families/deepseek_v41/metal/target.zig create mode 100644 zig/tests/dsv41_metal/boot_test.zig create mode 100644 zig/tests/dsv41_metal/fixture_serve.zig create mode 100644 zig/tests/dsv41_metal/multi_test.zig create mode 100644 zig/tests/dsv41_metal/serve_test.zig diff --git a/zig/build/dsv41_metal.zig b/zig/build/dsv41_metal.zig index 1ee5d6bd149..3eb2207ab1a 100644 --- a/zig/build/dsv41_metal.zig +++ b/zig/build/dsv41_metal.zig @@ -4,7 +4,7 @@ const std = @import("std"); /// The package over the family's neutral host module; `metal` and `sources` are the engine's own modules. pub fn package(b: *std.Build, metal: *std.Build.Module, sources: *std.Build.Module, optimize: std.builtin.OptimizeMode) struct { pkg: *std.Build.Module, host: *std.Build.Module } { const host = @import("dsv41_shared.zig").moduleAt(b, b.graph.host, optimize, "neutral.zig"); - // the lanes and the engine API the backend's modules import + // the lanes, the engine API and the served engine (serve_lanes) the backend's target and pass plug into @import("dsv41_draft.zig").addImportsAt(b, host, b.graph.host, optimize); const pkg = b.createModule(.{ .root_source_file = b.path("zig/src/families/deepseek_v41/metal/metal.zig"), @@ -16,6 +16,20 @@ pub fn package(b: *std.Build, metal: *std.Build.Module, sources: *std.Build.Modu return .{ .pkg = pkg, .host = host }; } +/// The native server's engine over the package: metal/entry.zig, the family's own serving modules beside it. +pub fn engine(b: *std.Build, metal: *std.Build.Module, sources: *std.Build.Module, optimize: std.builtin.OptimizeMode) *std.Build.Module { + const p = package(b, metal, sources, optimize); + const m = b.createModule(.{ + .root_source_file = b.path("zig/src/families/deepseek_v41/metal/entry.zig"), + .target = b.graph.host, + .optimize = optimize, + .link_libc = true, + .imports = &.{ .{ .name = "dsv41_metal", .module = p.pkg }, .{ .name = "dsv41", .module = p.host }, .{ .name = "metal", .module = metal } }, + }); + for ([_][]const u8{ "engine_api", "core", "tokenizer", "dsv41_serve", "lanes", "json" }) |name| m.addImport(name, p.host.import_table.get(name).?); + return m; +} + /// `test-dsv41-metal`: package, layer and forward checks on this GPU; `test-dsv41-metal-real`: a TF_DSV41_REAL layer. pub fn steps(b: *std.Build, metal: *std.Build.Module, sources: *std.Build.Module, test_step: *std.Build.Step) void { const p = package(b, metal, sources, .Debug); @@ -32,6 +46,19 @@ pub fn steps(b: *std.Build, metal: *std.Build.Module, sources: *std.Build.Module const run = b.addRunArtifact(b.addTest(.{ .root_module = tests })); run.has_side_effects = true; // a device run: never cached step.dependOn(&run.step); + // the served engine over the tiny model: LaneHost replies, drafts, the prompt cache, seeds, cancels + const serve = b.createModule(.{ + .root_source_file = b.path("zig/tests/dsv41_metal/serve_test.zig"), + .target = b.graph.host, + .optimize = .Debug, + .link_libc = true, + .imports = &.{ .{ .name = "dsv41_metal", .module = p.pkg }, .{ .name = "metal", .module = metal }, .{ .name = "dsv41", .module = p.host } }, + }); + serve.addImport("dsv41_serve_fixtures", p.host.import_table.get("dsv41_serve").?.import_table.get("dsv41_serve_fixtures").?); + const serve_run = b.addRunArtifact(b.addTest(.{ .root_module = serve })); + serve_run.has_side_effects = true; + step.dependOn(&serve_run.step); + b.step("test-dsv41-metal-serve", "DeepSeek-V4.1 Metal served through LaneHost: concurrent, drafted, cached, seeded, cancelled").dependOn(&serve_run.step); test_step.dependOn(pkg_run); // the package's host checks only; the device run stays in its own step const fast = package(b, metal, sources, .ReleaseSafe); const real = b.createModule(.{ @@ -66,4 +93,7 @@ pub fn steps(b: *std.Build, metal: *std.Build.Module, sources: *std.Build.Module const ptime_run = b.addRunArtifact(b.addTest(.{ .root_module = ptime })); ptime_run.has_side_effects = true; b.step("test-dsv41-metal-prompt-time", "DeepSeek-V4.1 Metal: ms a stage of one release layer's prompt chunks (TF_DSV41_REAL)").dependOn(&ptime_run.step); + // tensorfold-dsv41 over Metal: the native server with this family's lane engine (the CUDA pair's macOS twin) + const exe = @import("dsv41_draft.zig").serverOn(b, b.graph.host, .ReleaseSafe, engine(b, metal, sources, .ReleaseFast)); + b.step("dsv41-metal-serve", "Install tensorfold-dsv41 over Metal (DeepSeek-V4.1 release checkpoints on this Mac)").dependOn(&b.addInstallArtifact(exe, .{}).step); } diff --git a/zig/src/families/deepseek_v41/draft/iface.zig b/zig/src/families/deepseek_v41/draft/iface.zig index 39aa01f4717..f8bfae834e6 100644 --- a/zig/src/families/deepseek_v41/draft/iface.zig +++ b/zig/src/families/deepseek_v41/draft/iface.zig @@ -46,8 +46,15 @@ pub const Target = struct { replays: ?*const fn (ptr: *anyopaque, list: []const Final) anyerror!void = null, /// Engram reads ahead of the next window (TF_DSV41_ENGRAM_WARM); reads only, window bits are unaffected. warm: ?*const fn (ptr: *anyopaque, asks: []const Warm) void = null, + /// After `prefill`: the prompt rows the slot took from kept state (its first row computed is this one). + resumed: ?*const fn (ptr: *anyopaque, slot: u32) u64 = null, }; + /// The prompt rows the slot's last `prefill` took from kept state (0: none, or a target that keeps none). + pub fn resumedRows(t: Target, slot: u32) u64 { + return if (t.vtable.resumed) |f| f(t.ptr, slot) else 0; + } + /// A slot's whole prompt whose rows but the last are in (its `finish` / `tail` follows). pub const Final = struct { slot: u32, ids: []const u32 }; diff --git a/zig/src/families/deepseek_v41/draft/lanes.zig b/zig/src/families/deepseek_v41/draft/lanes.zig index 2f875c9715e..dec67d5e17a 100644 --- a/zig/src/families/deepseek_v41/draft/lanes.zig +++ b/zig/src/families/deepseek_v41/draft/lanes.zig @@ -188,6 +188,7 @@ pub const Lanes = struct { const ids = s.prompt(); x.target.admit(slot, s.max_new); st.first = try x.target.prefill(slot, ids, s.sampling, ids.len); + s.cached = @intCast(x.target.resumedRows(slot)); st.len = ids.len; _ = x.scratch.reset(.retain_capacity); // the taps hold the prompt's last rows (after a verify-tail prompt only that row), at their positions diff --git a/zig/src/families/deepseek_v41/metal/boot.zig b/zig/src/families/deepseek_v41/metal/boot.zig new file mode 100644 index 00000000000..157552c6d26 --- /dev/null +++ b/zig/src/families/deepseek_v41/metal/boot.zig @@ -0,0 +1,144 @@ +//! A release checkpoint folder on this Mac: config, kernels, mapped weights, DSpark, Engram rows; the served model. +const std = @import("std"); +const mtl = @import("metal"); +const host = @import("dsv41"); +const pipelines = @import("pipelines.zig"); +const model_weights = @import("model_weights.zig"); +const dspark = @import("dspark.zig"); +const rope = @import("rope.zig"); +const scratch = @import("scratch.zig"); +const forward = @import("forward.zig"); +const serve = @import("serve.zig"); +const target_ = @import("target.zig"); + +const Config = host.config.Config; +const eh = host.engram_host; +const er = host.engram_rows; +const Allocator = std.mem.Allocator; + +/// The files a boot reads beside the shards: the Engram token map (here or under TF_DSV41_ASSETS). +pub const token_map = "engram-token-map.bin"; + +pub const Options = struct { + slots: u32 = 4, + /// positions a slot holds (null: 262,144, at most the checkpoint's) + context: ?u64 = null, + drafts: bool = true, + cache_bytes: u64 = 4 << 30, + /// a checkpoint of the release's format at other shapes (TF_DSV41_SMALL=1: the smoke test's tiny model) + small: bool = false, + /// Engram row shards (null: TF_DSV41_ENGRAM_DIR, else the config's engram_table_dir beside the checkpoint) + engram_dir: ?[]const u8 = null, +}; + +/// Everything a served model borrows, owned here and closed after the model's target and pass. +pub const Boot = struct { + a: Allocator, + c: Config, + device: mtl.Device, + queue: mtl.Queue, + p: pipelines.Pipelines, + w: *model_weights.Model, + ds: ?dspark.Weights = null, + tables: rope.Tables, + s: scratch.Scratch, + map_bytes: []align(4) u8 = &.{}, + lbuf: [eh.max_layers]u32 = undefined, + eng: eh.Host = undefined, + rows: ?*er.Rows = null, + + /// The checkpoint in `dir` loaded and served by a `serve.Metal` (the caller's `serve_lanes.Served` closes it). + pub fn open(a: Allocator, io: std.Io, dir: []const u8, o: Options) !*serve.Metal { + const b = try a.create(Boot); + errdefer a.destroy(b); + b.a = a; + b.ds = null; + b.map_bytes = &.{}; + b.rows = null; + b.c = try readConfig(a, io, dir, o.small); + const c = &b.c; + const limit: u32 = @intCast(@min(o.context orelse 262144, c.rope.max_positions)); + b.device = try mtl.Device.init(); + errdefer b.device.deinit(); + b.queue = try b.device.queue(); + errdefer b.queue.deinit(); + b.p = try pipelines.Pipelines.load(a, b.device, c); + errdefer b.p.deinit(); + var pack = try host.pack.Pack.open(a, io, dir); + defer pack.deinit(); + b.w = try model_weights.Model.load(a, io, b.device, b.queue, &pack, c, null); + errdefer b.w.deinit(); + if (o.drafts and c.mtp_layers > 0) b.ds = try dspark.loadWeights(a, io, b.device, &pack, c); + errdefer if (b.ds) |*w| w.deinit(); + b.tables = try rope.Tables.init(b.device, c, limit); + errdefer b.tables.deinit(); + b.s = try scratch.Scratch.init(b.device, c, limit); + errdefer b.s.deinit(); + const lookup = try b.engram(io, dir, o); + errdefer b.closeEngram(); + const r = b.w.report(); + std.log.info("dsv41 metal: {d} layers, {d} shards ({d} MiB mapped, {d} MiB copied), {d} slots of {d} positions, DSpark {s}", .{ c.layers, r.shards, r.shard_bytes >> 20, r.arena_bytes >> 20, o.slots, limit, if (b.ds != null) "on" else "off" }); + const env: target_.Env = .{ .device = b.device, .queue = b.queue, .c = c, .p = &b.p, .tables = &b.tables, .s = &b.s, .model = b.w.view(), .lookup = lookup }; + return serve.Metal.open(a, .{ .env = env, .top = &b.w.top, .dspark = if (b.ds) |*w| w else null, .owner = .{ .ctx = b, .close = close } }, .{ .slots = o.slots, .limit = limit, .drafts = o.drafts, .cache_bytes = o.cache_bytes }); + } + + fn readConfig(a: Allocator, io: std.Io, dir: []const u8, small: bool) !Config { + if (!small) return Config.read(a, io, dir); + const path = try std.fs.path.join(a, &.{ dir, "config.json" }); + defer a.free(path); + const bytes = try std.Io.Dir.cwd().readFileAlloc(io, path, a, .limited(1 << 24)); + defer a.free(bytes); + return Config.parseShapes(a, bytes); + } + + /// The Engram hashes (the canonical token map) and the packed row shards; null without Engram layers. + fn engram(b: *Boot, io: std.Io, dir: []const u8, o: Options) !?forward.Lookup { + const c = &b.c; + if (c.engram_layers.len == 0) return null; + const assets = if (std.c.getenv("TF_DSV41_ASSETS")) |v| std.mem.span(v) else dir; + const path = try std.fs.path.join(b.a, &.{ assets, token_map }); + defer b.a.free(path); + b.map_bytes = std.Io.Dir.cwd().readFileAllocOptions(io, path, b.a, .limited(1 << 26), .@"4", null) catch |e| { + std.log.err("dsv41 metal: the Engram token map {s} ({t}): put it beside the checkpoint or under TF_DSV41_ASSETS", .{ path, e }); + return error.EngramTokenMap; + }; + errdefer b.a.free(b.map_bytes); + b.eng = try eh.Host.load(b.map_bytes, c.engram_heads, c.engram_pad, c.engram_vocab, &b.lbuf); + const rows_dir = try b.rowsDir(dir, o); + defer b.a.free(rows_dir); + const cap: u32 = if (std.c.getenv("TF_DSV41_ENGRAM_CACHE")) |v| try std.fmt.parseInt(u32, std.mem.span(v), 10) else 65536; + b.rows = try er.Rows.open(b.a, rows_dir, 0, 1, b.eng.layer_ids, cap); + std.log.info("dsv41 metal: Engram rows from {s} ({d} records a layer cached)", .{ rows_dir, cap }); + return .{ .a = b.a, .host = &b.eng, .source = b.rows.?.source() }; + } + + /// The row shards' folder: the option, TF_DSV41_ENGRAM_DIR, else engram_table_dir (relative to the checkpoint). + fn rowsDir(b: *Boot, dir: []const u8, o: Options) ![]u8 { + if (o.engram_dir) |d| return b.a.dupe(u8, d); + if (std.c.getenv("TF_DSV41_ENGRAM_DIR")) |v| return b.a.dupe(u8, std.mem.span(v)); + const t = b.c.engram_table_dir.items(); + if (t.len == 0) return error.EngramRowsUnset; + if (std.fs.path.isAbsolute(t)) return b.a.dupe(u8, t); + return std.fs.path.join(b.a, &.{ dir, t }); + } + + fn closeEngram(b: *Boot) void { + if (b.rows) |r| r.close(); + b.rows = null; + if (b.map_bytes.len > 0) b.a.free(b.map_bytes); + b.map_bytes = &.{}; + } + + fn close(ctx: *anyopaque) void { + const b: *Boot = @ptrCast(@alignCast(ctx)); + b.closeEngram(); + b.s.deinit(); + b.tables.deinit(); + if (b.ds) |*w| w.deinit(); + b.w.deinit(); + b.p.deinit(); + b.queue.deinit(); + b.device.deinit(); + b.a.destroy(b); + } +}; diff --git a/zig/src/families/deepseek_v41/metal/entry.zig b/zig/src/families/deepseek_v41/metal/entry.zig new file mode 100644 index 00000000000..7eb864254b5 --- /dev/null +++ b/zig/src/families/deepseek_v41/metal/entry.zig @@ -0,0 +1,44 @@ +//! DeepSeek-V4.1's Metal entry point for the native server: a release checkpoint served through the lane core. +const std = @import("std"); +const api = @import("engine_api"); +const pkg = @import("dsv41_metal"); +const host = @import("dsv41"); + +const serve_lanes = host.serve_lanes; +const Allocator = std.mem.Allocator; + +pub const backends: []const []const u8 = &.{"metal"}; +pub const families: []const api.Family = &.{.{ .model_type = "deepseek_v41", .formats = &.{"fp8"}, .raw_text = false }}; + +pub fn chip(_: Allocator) ?[]const u8 { + return null; +} + +/// The engine for `o.dir`, or null with `problem` set (the native_engines contract). +pub fn open(a: Allocator, gpa: Allocator, io: std.Io, o: api.Open, problem: *[]const u8) !?api.Opened { + if (@import("sys").experimental.refusal(o.model_type, @import("sys").getenv("TF_EXPERIMENTAL")) != null) { + problem.* = "DeepSeek-V4.1 on Metal is experimental: its served lanes have no whole-model gate yet; set TF_EXPERIMENTAL=deepseek to opt in"; + return null; + } + if (!std.mem.eql(u8, o.model_type, "deepseek_v41")) { + problem.* = try std.fmt.allocPrint(a, "this build serves deepseek_v41 checkpoints only, not {s}", .{o.model_type}); + return null; + } + const opts: pkg.boot.Options = .{ + .slots = @max(1, @min(o.lanes, 16)), + .context = if (o.context) |c| @intCast(@max(c, 1)) else null, + .drafts = o.drafts, + .cache_bytes = if (o.prompt_cache_gib) |g| @intFromFloat(@max(g, 0) * (1 << 30)) else 4 << 30, + .small = if (std.c.getenv("TF_DSV41_SMALL")) |v| std.mem.eql(u8, std.mem.span(v), "1") else false, + }; + const m = pkg.boot.Boot.open(gpa, io, o.dir, opts) catch |e| { + problem.* = try std.fmt.allocPrint(a, "the DeepSeek-V4.1 Metal engine cannot load {s} ({s})", .{ o.dir, @errorName(e) }); + return null; + }; + const s = serve_lanes.Served.open(gpa, io, m.model(), o.dir, o.context) catch |e| { + m.model().close(m); + problem.* = try std.fmt.allocPrint(a, "the DeepSeek-V4.1 Metal engine cannot start its lanes ({s})", .{@errorName(e)}); + return null; + }; + return .{ .engine = s.engine(), .close = serve_lanes.Served.close, .ctx = s, .halt = serve_lanes.Served.halt }; +} diff --git a/zig/src/families/deepseek_v41/metal/metal.zig b/zig/src/families/deepseek_v41/metal/metal.zig index 55f4e533334..bec87c2930a 100644 --- a/zig/src/families/deepseek_v41/metal/metal.zig +++ b/zig/src/families/deepseek_v41/metal/metal.zig @@ -1,4 +1,4 @@ -//! DeepSeek V4.1 on Metal, the backend package: the decode forward (1-16 rows), the prompt path and DSpark. +//! DeepSeek V4.1 on Metal, the backend package: the decode forward (1-16 rows), the prompt path, the served lanes. const std = @import("std"); pub const host = @import("dsv41"); @@ -25,6 +25,11 @@ pub const dspark_plan = @import("dspark_plan.zig"); pub const dspark_stage = @import("dspark_stage.zig"); pub const dspark_weights = @import("dspark_weights.zig"); pub const engram = pipelines.engram; +pub const snapshots = @import("snapshots.zig"); +pub const target = @import("target.zig"); +pub const pass = @import("pass.zig"); +pub const serve = @import("serve.zig"); +pub const boot = @import("boot.zig"); test { std.testing.refAllDecls(@This()); @@ -34,4 +39,5 @@ test { _ = prompt_scratch; _ = dspark; _ = dspark_plan; + _ = pass; } diff --git a/zig/src/families/deepseek_v41/metal/pass.zig b/zig/src/families/deepseek_v41/metal/pass.zig new file mode 100644 index 00000000000..520be10a3e8 --- /dev/null +++ b/zig/src/families/deepseek_v41/metal/pass.zig @@ -0,0 +1,57 @@ +//! DSpark's pass for the lanes (iface.Pass) over the Metal drafter: the target's taps in, blocks of drafts out. +const std = @import("std"); +const host = @import("dsv41"); +const dspark = @import("dspark.zig"); +const target_ = @import("target.zig"); + +const iface = host.iface; + +pub const Pass = struct { + x: *dspark.Pass, + /// the target whose taps the ingests name (by address) + t: *const target_.Target, + passes: u64 = 0, + ingests: u64 = 0, + + pub fn pass(p: *Pass) iface.Pass { + return .{ .ptr = p, .vtable = &.{ .ingest = ingest, .propose = propose, .reset = reset, .markov = markov } }; + } + + fn self(ptr: *anyopaque) *Pass { + return @ptrCast(@alignCast(ptr)); + } + + fn ingest(ptr: *anyopaque, slot: u32, start: u64, taps: iface.Taps, rows: []const u32) anyerror!void { + const p = self(ptr); + if (rows.len == 0) return; + const at = p.t.bufferOf(taps.address) orelse return error.UnknownTaps; + p.ingests += 1; + try p.x.ingest(slot, start, .{ .buf = at.buf, .off = at.off, .rows = taps.rows }, rows); + } + + fn propose(ptr: *anyopaque, asks: []const iface.Ask, out: []iface.Proposal) anyerror!void { + const p = self(ptr); + var xs: [16]dspark.Ask = undefined; + var ys: [16]dspark.Proposal = undefined; + if (asks.len > xs.len or out.len != asks.len) return error.TooManySlots; + for (asks, out, xs[0..asks.len], ys[0..asks.len]) |a, o, *x, *y| { + x.* = .{ .slot = a.slot, .anchor = a.anchor, .start = a.start, .params = a.params }; + y.* = .{ .drafts = o.drafts, .conf = o.conf, .cand = o.cand, .base = o.base }; + } + p.passes += 1; + try p.x.propose(xs[0..asks.len], ys[0..asks.len]); + } + + fn reset(ptr: *anyopaque, slot: u32) void { + self(ptr).x.reset(slot); + } + + fn markov(ptr: *anyopaque) ?host.dspark.Markov { + return self(ptr).x.markov(); + } +}; + +test "the pass's asks and proposals are the drafter's, field for field" { + try std.testing.expectEqual(@sizeOf(iface.Ask), @sizeOf(dspark.Ask)); + try std.testing.expectEqual(@sizeOf(iface.Proposal), @sizeOf(dspark.Proposal)); +} diff --git a/zig/src/families/deepseek_v41/metal/serve.zig b/zig/src/families/deepseek_v41/metal/serve.zig new file mode 100644 index 00000000000..b0d03fc2f11 --- /dev/null +++ b/zig/src/families/deepseek_v41/metal/serve.zig @@ -0,0 +1,121 @@ +//! DeepSeek-V4.1 on Metal as the lanes serve it (serve_lanes.Model): the target, DSpark's pass, costs and hooks. +const std = @import("std"); +const mtl = @import("metal"); +const host = @import("dsv41"); +const weights = @import("weights.zig"); +const dspark = @import("dspark.zig"); +const prompt = @import("prompt.zig"); +const target_ = @import("target.zig"); +const pass_ = @import("pass.zig"); +const pipelines = @import("pipelines.zig"); + +const serve_lanes = host.serve_lanes; +const iface = host.iface; +const api = host.api; +const Allocator = std.mem.Allocator; + +/// The parts a served model borrows; `owner` (boot.zig's model, or a test's rig) is closed after them. +pub const Parts = struct { + env: target_.Env, + top: *const weights.Top, + /// the drafter's weights (null: serial windows, no drafts) + dspark: ?*const dspark.Weights, + owner: ?Owner = null, +}; + +pub const Owner = struct { ctx: *anyopaque, close: *const fn (ctx: *anyopaque) void }; + +pub const Options = struct { + slots: u32 = 4, + limit: u32, + /// DSpark's pass when the checkpoint has one (false: serial windows through the same lanes) + drafts: bool = true, + cache_bytes: u64 = 0, + prompt: prompt.Opts = .{}, +}; + +/// A position's draft candidates the pass keeps (the shape the lanes size their buffers by). +const candidates = 64; + +pub const Metal = struct { + a: Allocator, + parts: Parts, + opt: Options, + t: *target_.Target, + dp: ?*dspark.Pass = null, + ad: pass_.Pass = undefined, + + pub fn open(a: Allocator, parts: Parts, opt: Options) !*Metal { + const m = try a.create(Metal); + errdefer a.destroy(m); + m.* = .{ .a = a, .parts = parts, .opt = opt, .t = undefined }; + m.t = try target_.Target.init(a, parts.env, .{ .slots = opt.slots, .limit = opt.limit, .prompt = opt.prompt, .cache_bytes = opt.cache_bytes }); + errdefer m.t.deinit(); + const e = parts.env; + if (opt.drafts) if (parts.dspark) |w| { + m.dp = try dspark.Pass.init(a, e.device, e.queue, e.c, e.p, e.s, e.tables, parts.top, w, .{ .slots = opt.slots, .candidates = @min(candidates, e.c.vocab) }); + m.ad = .{ .x = m.dp.?, .t = m.t }; + }; + return m; + } + + /// The lanes' view: one slot a stream, rows of 16 a forward, the release's DSpark shape on one device. + pub fn model(m: *Metal) serve_lanes.Model { + const c = m.parts.env.c; + const shape: host.dspark.Shape = .{ .block = c.dspark_block, .noise = c.dspark_noise_token, .window = c.window, .rank = c.dspark_markov_rank, .hidden = c.hidden, .candidates = @min(candidates, c.vocab) }; + return .{ + .ptr = m, + .name = "dsv41-metal", + .slots = m.opt.slots, + .limit = m.opt.limit, + .world = 1, + .prefill_step = m.opt.prompt.chunk, + .forward_rows = pipelines.max_rows, + .shape = shape, + .target = targetFn, + .pass = passFn, + .calibrate = calibrate, + .memory = .{ .ctx = m, .read = memory }, + .health = .{ .ctx = m, .read = healthy }, + .close = close, + // the default cost table: TF_DSV41_CALIB has nothing to time on Metal + .calib = .{ .mode = "default" }, + }; + } + + fn self(ctx: *anyopaque) *Metal { + return @ptrCast(@alignCast(ctx)); + } + + fn targetFn(ctx: *anyopaque) iface.Target { + return self(ctx).t.target(); + } + + fn passFn(ctx: *anyopaque) ?iface.Pass { + const m = self(ctx); + return if (m.dp != null) m.ad.pass() else null; + } + + fn calibrate(_: *anyopaque, _: Allocator, _: std.Io, _: []const u8, _: host.calib_env.Knobs, _: host.calib_env.Shape) anyerror!host.calib_lanes.Boot { + return error.Unmeasured; // the mode is "default": never asked to measure + } + + /// The device's allocated bytes now (the weights, slots, prompt buffers and kept-state host copies aside). + fn memory(ctx: ?*anyopaque, _: bool) ?api.Memory { + const m = self(ctx.?); + const used = m.parts.env.device.allocated(); + return .{ .active = used, .cache = m.t.cache.held, .peak = used }; + } + + fn healthy(ctx: *anyopaque) bool { + return !self(ctx).t.failed; + } + + fn close(ctx: *anyopaque) void { + const m = self(ctx); + if (m.dp) |p| p.deinit(); + m.t.deinit(); + if (m.parts.owner) |o| o.close(o.ctx); + m.a.destroy(m); + } +}; diff --git a/zig/src/families/deepseek_v41/metal/snapshots.zig b/zig/src/families/deepseek_v41/metal/snapshots.zig new file mode 100644 index 00000000000..dc14dd0b0d4 --- /dev/null +++ b/zig/src/families/deepseek_v41/metal/snapshots.zig @@ -0,0 +1,154 @@ +//! Kept prompt states on the host: a slot's regions up to its rows, its ids and DSpark taps, restored into any slot. +const std = @import("std"); +const mtl = @import("metal"); +const Config = @import("dsv41").config.Config; +const kv = @import("kv.zig"); + +/// One kept state: the slot after `ids` (every row run), and the choice's logits when it ended a prompt. +pub const Entry = struct { + ids: []u32, + /// each region's window, pool rows, index key rows and carry, in layer order + bytes: []u8, + /// the taps ring: position p's row at p % ring rows + taps: []u16, + logits: ?[]f32, + tick: u64 = 0, + + fn size(e: *const Entry) u64 { + return e.ids.len * 4 + e.bytes.len + e.taps.len * 2 + if (e.logits) |l| l.len * 4 else 0; + } + + fn free(e: *Entry, a: std.mem.Allocator) void { + a.free(e.ids); + a.free(e.bytes); + a.free(e.taps); + if (e.logits) |l| a.free(l); + a.destroy(e); + } +}; + +/// The pool and key rows a state of `len` positions has written at a KV source (and the row it may be filling). +pub fn poolRowsOf(c: *const Config, slot: *const kv.Slot, layer: u32, len: u64) usize { + const all = kv.poolRows(c, layer, slot.limit); + return @min(all, @as(usize, @intCast(len / c.compressRatio(layer))) + 1); +} + +/// Every region's bytes a state of `len` positions reads, as (buffer, bytes) runs in order. +fn runs(c: *const Config, slot: *const kv.Slot, len: u64, out: *[4 * 64]Run) []Run { + var n: usize = 0; + for (slot.regions, 0..) |r, l| { + out[n] = .{ .buf = r.window, .len = r.window.length() }; + n += 1; + if (r.pool) |p| { + const rows = poolRowsOf(c, slot, @intCast(l), len); + out[n] = .{ .buf = p, .len = rows * c.head_dim * 2 }; + out[n + 1] = .{ .buf = r.keys.?, .len = rows * kv.index_key_bytes }; + n += 2; + } + if (r.carry) |k| { + out[n] = .{ .buf = k, .len = k.length() }; + n += 1; + } + } + return out[0..n]; +} + +const Run = struct { buf: mtl.Buffer, len: usize }; + +/// Zeroes what a state of up to `high` positions may have written: a reused slot reads as a new one. +pub fn clear(c: *const Config, slot: *const kv.Slot, high: u64) void { + var buf: [4 * 64]Run = undefined; + for (runs(c, slot, high, &buf)) |r| @memset(r.buf.contents()[0..r.len], 0); + for (slot.regions) |*r| kv.resetCarry(r, c); +} + +pub const Store = struct { + a: std.mem.Allocator, + /// bytes the entries may hold (0: no prompt cache) + cap: u64, + held: u64 = 0, + tick: u64 = 0, + entries: std.ArrayList(*Entry) = .empty, + + pub fn deinit(st: *Store) void { + for (st.entries.items) |e| e.free(st.a); + st.entries.deinit(st.a); + } + + pub fn on(st: *const Store) bool { + return st.cap > 0; + } + + /// The longest entry that starts `ids`: shorter than them, or as long with the choice's logits. + pub fn best(st: *Store, ids: []const u32) ?*Entry { + var out: ?*Entry = null; + for (st.entries.items) |e| { + if (e.ids.len > ids.len or !std.mem.eql(u32, e.ids, ids[0..e.ids.len])) continue; + if (e.ids.len == ids.len and e.logits == null) continue; + if (out == null or e.ids.len > out.?.ids.len) out = e; + } + if (out) |e| { + st.tick += 1; + e.tick = st.tick; + } + return out; + } + + /// The slot's state after `ids` kept (the oldest entries make room); one entry a distinct `ids`. + pub fn save(st: *Store, c: *const Config, slot: *const kv.Slot, ids: []const u32, ring: []const u16, logits: ?[]const f32) !void { + if (!st.on() or ids.len == 0) return; + st.tick += 1; + for (st.entries.items) |e| if (std.mem.eql(u32, e.ids, ids)) { + e.tick = st.tick; + if (e.logits != null or logits == null) return; + e.logits = try st.a.dupe(f32, logits.?); + st.held += logits.?.len * 4; + return; + }; + var buf: [4 * 64]Run = undefined; + const rs = runs(c, slot, ids.len, &buf); + var total: usize = 0; + for (rs) |r| total += r.len; + const size = ids.len * 4 + total + ring.len * 2 + if (logits) |l| l.len * 4 else 0; + if (size > st.cap) return; + while (st.held + size > st.cap) st.evict(); + const e = try st.a.create(Entry); + errdefer st.a.destroy(e); + e.* = .{ .ids = try st.a.dupe(u32, ids), .bytes = undefined, .taps = undefined, .logits = null, .tick = st.tick }; + errdefer st.a.free(e.ids); + e.bytes = try st.a.alloc(u8, total); + errdefer st.a.free(e.bytes); + var at: usize = 0; + for (rs) |r| { + @memcpy(e.bytes[at..][0..r.len], r.buf.contents()[0..r.len]); + at += r.len; + } + e.taps = try st.a.dupe(u16, ring); + errdefer st.a.free(e.taps); + if (logits) |l| e.logits = try st.a.dupe(f32, l); + try st.entries.append(st.a, e); + st.held += e.size(); + } + + /// The entry's state into `slot` (cleared first up to `high`, its old rows) and its taps into `ring`. + pub fn restore(_: *const Store, c: *const Config, e: *const Entry, slot: *const kv.Slot, high: u64, ring: []u16) void { + clear(c, slot, high); + var buf: [4 * 64]Run = undefined; + var at: usize = 0; + for (runs(c, slot, e.ids.len, &buf)) |r| { + @memcpy(r.buf.contents()[0..r.len], e.bytes[at..][0..r.len]); + at += r.len; + } + @memcpy(ring, e.taps); + } + + fn evict(st: *Store) void { + var old: usize = 0; + for (st.entries.items, 0..) |e, i| if (e.tick < st.entries.items[old].tick) { + old = i; + }; + const e = st.entries.swapRemove(old); + st.held -= e.size(); + e.free(st.a); + } +}; diff --git a/zig/src/families/deepseek_v41/metal/target.zig b/zig/src/families/deepseek_v41/metal/target.zig new file mode 100644 index 00000000000..2e83b64b236 --- /dev/null +++ b/zig/src/families/deepseek_v41/metal/target.zig @@ -0,0 +1,418 @@ +//! The lanes' verify target on Metal: a slot's prompt (prompt.zig), its windows of rows (forward.zig), keeps and reuse. +const std = @import("std"); +const mtl = @import("metal"); +const host = @import("dsv41"); +const kv = @import("kv.zig"); +const rope = @import("rope.zig"); +const ctx_ = @import("ctx.zig"); +const scratch = @import("scratch.zig"); +const forward = @import("forward.zig"); +const prompt = @import("prompt.zig"); +const pipelines = @import("pipelines.zig"); +const snapshots = @import("snapshots.zig"); + +const iface = host.iface; +const lanes = host.lanes; +const Config = host.config.Config; +const Allocator = std.mem.Allocator; +const R = pipelines.max_rows; + +/// What the target reads and borrows: the device, kernels, RoPE tables, layer scratch, weights and Engram rows. +pub const Env = struct { + device: mtl.Device, + queue: mtl.Queue, + c: *const Config, + p: *const pipelines.Pipelines, + tables: *const rope.Tables, + s: *const scratch.Scratch, + model: forward.Model, + lookup: ?forward.Lookup, +}; + +pub const Options = struct { + slots: u32, + /// positions a slot holds (the context limit) + limit: u32, + prompt: prompt.Opts = .{}, + /// bytes of kept prompt states (0: no prompt cache) + cache_bytes: u64 = 0, +}; + +/// What the target did, for the tests and the logs. +pub const Stats = struct { prompts: u64 = 0, hits: u64 = 0, cached_rows: u64 = 0, windows: u64 = 0, rows: u64 = 0, rewinds: u64 = 0, launches: u64 = 0 }; + +/// A slot: its device state, prompt tail, ids (rows run, the last window's included until its keep) and taps. +const Slot = struct { + kv: kv.Slot, + tail: prompt.Tail, + hist: std.ArrayList(u32) = .empty, + /// the last window: its first position and rows; `open` until its keep + base: u64 = 0, + rows: u32 = 0, + open: bool = false, + /// the taps of the last `ring rows` positions, position p at row p % ring rows + ring: []u16, + /// the taps `taps` names after a prompt: its last rows in order + ptaps: mtl.Buffer, + ptaps_rows: u32 = 0, + after_prompt: bool = false, + /// the most positions any request wrote here since the slot was last cleared + high: u64 = 0, + live: bool = false, + /// every launch since the request began completed (a release keeps only a whole state) + whole: bool = false, + /// the rows the last prompt took from kept state + resumed: u32 = 0, +}; + +pub const Target = struct { + a: Allocator, + env: Env, + opt: Options, + b: forward.Bufs, + pr: prompt.Prompt, + slots: []Slot, + cache: snapshots.Store, + stats: Stats = .{}, + /// a command buffer failed: the device state is no longer trusted (the health hook) + failed: bool = false, + + pub fn init(a: Allocator, env: Env, opt: Options) !*Target { + const c = env.c; + if (opt.slots == 0 or opt.limit == 0 or opt.limit > env.tables.positions) return error.BadOptions; + _ = try prompt.check(c); + const t = try a.create(Target); + errdefer a.destroy(t); + t.* = .{ .a = a, .env = env, .opt = opt, .b = undefined, .pr = undefined, .slots = &.{}, .cache = .{ .a = a, .cap = opt.cache_bytes } }; + t.b = try forward.Bufs.init(env.device, c); + errdefer t.b.deinit(); + t.pr = try prompt.Prompt.init(env.device, c, opt.prompt, opt.limit); + errdefer t.pr.deinit(); + const slots = try a.alloc(Slot, opt.slots); + errdefer a.free(slots); + var made: usize = 0; + errdefer for (slots[0..made]) |*s| freeSlot(a, s); + const cap = try prompt.tailRows(c, opt.prompt); + const ptb = @max(4, @as(usize, ringRows(c)) * tapWidth(c) * 2); + for (slots) |*s| { + var st = try kv.Slot.init(a, env.device, c, opt.limit); + errdefer st.deinit(); + var tail = try prompt.Tail.init(env.device, c, cap); + errdefer tail.deinit(); + const ptaps = try env.device.buffer(ptb, mtl.ResourceOptions.shared); + errdefer ptaps.deinit(); + const ring = try a.alloc(u16, @as(usize, ringRows(c)) * tapWidth(c)); + @memset(ring, 0); + s.* = .{ .kv = st, .tail = tail, .ring = ring, .ptaps = ptaps }; + made += 1; + } + t.slots = slots; + return t; + } + + fn freeSlot(a: Allocator, s: *Slot) void { + s.kv.deinit(); + s.tail.deinit(); + s.ptaps.deinit(); + a.free(s.ring); + s.hist.deinit(a); + } + + pub fn deinit(t: *Target) void { + for (t.slots) |*s| freeSlot(t.a, s); + t.a.free(t.slots); + t.cache.deinit(); + t.pr.deinit(); + t.b.deinit(); + t.a.destroy(t); + } + + /// The taps ring's rows: the drafter's context window. + fn ringRows(c: *const Config) u32 { + return c.window; + } + + /// Values in a taps row: every target layer's hidden. + fn tapWidth(c: *const Config) usize { + return c.dspark_targets.len * c.hidden; + } + + pub fn target(t: *Target) iface.Target { + return .{ .ptr = t, .vtable = &.{ .prefill = prefill, .window = window, .keep = keep, .taps = taps, .release = release, .resumed = resumedFn } }; + } + + fn self(ptr: *anyopaque) *Target { + return @ptrCast(@alignCast(ptr)); + } + + /// The device buffer and offset of an address a `taps` named (the pass's ingest reads it there). + pub fn bufferOf(t: *const Target, address: u64) ?struct { buf: mtl.Buffer, off: usize } { + for (t.slots) |s| { + const bufs = [_]?mtl.Buffer{ s.ptaps, s.kv.taps }; + for (bufs) |ob| if (ob) |b| { + const lo = @intFromPtr(b.contents()); + if (address >= lo and address < lo + b.length()) return .{ .buf = b, .off = @intCast(address - lo) }; + }; + } + return null; + } + + // prompts ------------------------------------------------------------------------------------------------------ + + fn resumedFn(ptr: *anyopaque, slot: u32) u64 { + const t = self(ptr); + return if (slot < t.slots.len) t.slots[slot].resumed else 0; + } + + fn prefill(ptr: *anyopaque, slot: u32, ids: []const u32, smp: ?lanes.Sampling, draw: u64) anyerror!u32 { + const t = self(ptr); + if (slot >= t.slots.len) return error.NoSlot; + const s = &t.slots[slot]; + const c = t.env.c; + if (s.live) return error.SlotLive; + if (ids.len == 0) return error.EmptyPrompt; + if (ids.len >= t.opt.limit) return error.PastLimit; + for (ids) |id| if (id >= c.vocab) return error.BadToken; + s.whole = false; + s.open = false; + s.rows = 0; + t.stats.prompts += 1; + // a kept state that starts this prompt, else a cleared slot + const hit = if (t.cache.on()) t.cache.best(ids) else null; + const at: u32 = if (hit) |e| @intCast(e.ids.len) else 0; + if (hit) |e| { + t.cache.restore(c, e, &s.kv, s.high, s.ring); + t.stats.hits += 1; + t.stats.cached_rows += at; + } else snapshots.clear(c, &s.kv, s.high); + s.resumed = at; + s.tail.end = at; + s.tail.done = at; + s.hist.clearRetainingCapacity(); + try s.hist.appendSlice(t.a, ids); + s.high = @max(at, ids.len); + const n: u32 = @intCast(ids.len); + const V: usize = c.vocab; + var logits: []const f32 = undefined; + if (at == n) logits = hit.?.logits.? else { + t.pr.run(t.promptEnv(), &s.kv, &s.tail, ids) catch |e| return t.fail(e); + const all = t.pr.logits(c); + logits = all[(t.pr.head - 1) * V ..][0..V]; + const tr = t.pr.tapRows(c); + for (0..t.pr.taps) |i| t.ringPut(s, n - t.pr.taps + i, tr[i * tapWidth(c) ..][0..tapWidth(c)]); + } + t.promptTaps(s, n); + const choice = try t.choose(logits, draw, smp); + s.base = n; + s.live = true; + s.whole = true; + if (t.cache.on() and at < n) t.cache.save(c, &s.kv, ids, s.ring, logits) catch {}; + return choice; + } + + fn promptEnv(t: *const Target) prompt.Env { + const e = t.env; + return .{ .c = e.c, .p = e.p, .tables = e.tables, .model = e.model, .lookup = e.lookup, .queue = e.queue }; + } + + fn ringPut(t: *const Target, s: *Slot, pos: u64, row: []const u16) void { + const w = tapWidth(t.env.c); + if (w == 0) return; + const at: usize = @intCast(pos % ringRows(t.env.c)); + @memcpy(s.ring[at * w ..][0..w], row); + } + + /// The taps of the prompt's last rows (the ring's, up to `ring rows`) in order, for `taps` after a prefill. + fn promptTaps(t: *const Target, s: *Slot, n: u32) void { + const c = t.env.c; + const w = tapWidth(c); + s.after_prompt = true; + s.ptaps_rows = if (w == 0) 0 else @min(n, ringRows(c)); + const out = s.ptaps.slice(u16, @as(usize, s.ptaps_rows) * w); + for (0..s.ptaps_rows) |i| { + const pos = n - s.ptaps_rows + i; + @memcpy(out[i * w ..][0..w], s.ring[(pos % ringRows(c)) * w ..][0..w]); + } + } + + /// The keyed choice of a logits row over the whole vocabulary (greedy: the first maximum, ties to the lower id). + fn choose(t: *const Target, row: []const f32, draw: u64, smp: ?lanes.Sampling) !u32 { + const s = smp orelse return argmax(row); + if (s.temperature <= 0) return argmax(row); + const vals = try t.a.alloc(f64, row.len); + defer t.a.free(vals); + const ids = try t.a.alloc(u64, row.len); + defer t.a.free(ids); + for (vals, ids, row, 0..) |*v, *id, x, i| { + v.* = x; + id.* = i; + } + return @intCast(try lanes.sampling.choose(t.a, vals, ids, draw, s)); + } + + fn argmax(row: []const f32) u32 { + var best: usize = 0; + for (row, 0..) |x, i| if (x > row[best]) { + best = i; + }; + return @intCast(best); + } + + fn fail(t: *Target, e: anyerror) anyerror { + if (e == error.CommandBufferFailed) t.failed = true; + return e; + } + + // windows ------------------------------------------------------------------------------------------------------ + + /// A round's windows: slots' rows share a launch (up to R rows, a slot once), each launch one forward. + fn window(ptr: *anyopaque, segments: []const iface.Segment, choices: [][]u32) anyerror!void { + const t = self(ptr); + var from: usize = 0; + while (from < segments.len) { + var rows: usize = 0; + var to = from; + while (to < segments.len) : (to += 1) { + const g = segments[to]; + if (g.slot >= t.slots.len) return error.NoSlot; + if (to > from and (rows + g.tokens.len > R or dup(segments[from..to], g.slot))) break; + rows += g.tokens.len; + } + try t.windowGroup(segments[from..to], choices[from..to]); + from = to; + } + } + + fn dup(done: []const iface.Segment, slot: u32) bool { + for (done) |o| if (o.slot == slot) return true; + return false; + } + + /// One launch over the rows of these segments (distinct slots, at most R rows in all). + fn windowGroup(t: *Target, group: []const iface.Segment, choices: [][]u32) !void { + const c = t.env.c; + const V: usize = c.vocab; + var total: u32 = 0; + for (group, choices) |g, out| { + const s = &t.slots[g.slot]; + const n = g.tokens.len; + if (!s.live) return error.SlotNotLive; + if (g.start != s.hist.items.len) return error.PositionMismatch; + if (n == 0 or total + n > R or g.draws.len != n or out.len < n) return error.BadRows; + if (g.start + n > t.opt.limit) return error.PastLimit; + // the decode forward runs consecutive positions: a tree's rows must be one chain + if (g.parents) |ps| for (ps, 0..) |q, r| if (q != @as(i32, @intCast(r)) - 1) return error.TreeWindow; + for (g.tokens) |id| if (id >= c.vocab) return error.BadToken; + total += @intCast(n); + } + for (group) |g| { + const s = &t.slots[g.slot]; + s.whole = false; + try s.hist.appendSlice(t.a, g.tokens); + s.high = @max(s.high, s.hist.items.len); + } + t.launch(group) catch |e| return t.fail(e); + const lg = t.b.logitsOf(c, total); + const w = tapWidth(c); + var r0: usize = 0; + for (group, choices) |g, out| { + const s = &t.slots[g.slot]; + const n = g.tokens.len; + for (0..n) |r| out[r] = try t.choose(lg[(r0 + r) * V ..][0..V], g.draws[r], g.sampling); + if (s.kv.taps) |tb| for (0..n) |r| t.ringPut(s, g.start + r, tb.slice(u16, n * w)[r * w ..][0..w]); + s.base = g.start; + s.rows = @intCast(n); + s.open = true; + s.after_prompt = false; + s.tail.end = @intCast(s.hist.items.len); + s.tail.done = s.tail.end; + s.whole = true; + t.stats.windows += 1; + t.stats.rows += n; + r0 += n; + } + t.stats.launches += 1; + } + + /// One launch of the decode forward over the segments' rows, each slot's ids at its positions from `start`. + fn launch(t: *Target, group: []const iface.Segment) !void { + const e = t.env; + const c = e.c; + const look = c.engram_max_ngram - 1; + var pieces: [R]forward.Piece = undefined; + var spans: [R]scratch.Span = undefined; + var segs: [R]ctx_.Seg = undefined; + var r0: u32 = 0; + for (group, 0..) |g, i| { + const s = &t.slots[g.slot]; + const n: u32 = @intCast(g.tokens.len); + const start: u32 = @intCast(g.start); + pieces[i] = .{ .ids = g.tokens, .lookback = s.hist.items[start -| look..start] }; + spans[i] = .{ .p0 = start, .n = n }; + segs[i] = .{ .slot = &s.kv, .p0 = start, .r0 = r0, .n = n }; + r0 += n; + } + try forward.prepareSegs(&t.b, c, pieces[0..group.len], e.lookup); + try e.s.writeSpans(c, spans[0..group.len]); + const x: ctx_.Ctx = .{ .c = c, .p = e.p, .s = e.s, .slot = segs[0].slot, .tables = e.tables, .p0 = segs[0].p0, .rows = r0, .segs = segs[0..group.len] }; + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + try forward.run(&x, e.queue, e.model, &t.b); + } + + /// Keep the window's first rows (a chain from row 0): later rows' ids go, the compressor's carry rewinds. + fn keep(ptr: *anyopaque, slot: u32, path: []const u32) anyerror!void { + const t = self(ptr); + if (slot >= t.slots.len) return error.NoSlot; + const s = &t.slots[slot]; + if (!s.open) return error.NoWindow; + if (path.len == 0 or path.len > s.rows) return error.NotAPath; + for (path, 0..) |r, i| if (r != i) return error.NotAPath; + s.open = false; + const m: u32 = @intCast(path.len); + if (m == s.rows) return; + const len = s.base + m; + s.hist.shrinkRetainingCapacity(@intCast(len)); + for (s.kv.regions) |*r| kv.rewindCarry(r, t.env.c, s.base, m); + s.tail.end = @intCast(len); + s.tail.done = s.tail.end; + t.stats.rewinds += 1; + } + + fn taps(ptr: *anyopaque, slot: u32) iface.Taps { + const t = self(ptr); + const s = &t.slots[slot]; + const w: u32 = @intCast(tapWidth(t.env.c)); + if (s.after_prompt) return .{ .address = @intFromPtr(s.ptaps.contents()), .rows = s.ptaps_rows, .stride = w }; + const tb = s.kv.taps orelse return .{ .address = 0, .rows = 0, .stride = w }; + return .{ .address = @intFromPtr(tb.contents()), .rows = s.rows, .stride = w }; + } + + /// The request ended: its state is kept (the prompt cache) when every launch of it completed. + fn release(ptr: *anyopaque, slot: u32) void { + const t = self(ptr); + if (slot >= t.slots.len) return; + const s = &t.slots[slot]; + if (!s.live) return; + s.live = false; + s.open = false; + if (s.whole and t.cache.on()) t.cache.save(t.env.c, &s.kv, s.hist.items, s.ring, null) catch {}; + } + + /// The serial reference without lanes: the prompt, then one row a step, each drawn at its own position. + pub fn serial(t: *Target, slot: u32, ids: []const u32, n: usize, smp: ?lanes.Sampling) ![]u32 { + var out: std.ArrayList(u32) = .empty; + errdefer out.deinit(t.a); + var tok = try prefill(t, slot, ids, smp, ids.len); + while (out.items.len < n) { + try out.append(t.a, tok); + const at: u64 = ids.len + out.items.len - 1; + var ch: [1]u32 = undefined; + var cs = [_][]u32{&ch}; + try window(t, &.{.{ .slot = slot, .start = at, .tokens = &.{tok}, .parents = null, .draws = &.{at + 1}, .sampling = smp }}, &cs); + tok = ch[0]; + } + release(t, slot); + return out.toOwnedSlice(t.a); + } +}; diff --git a/zig/src/families/deepseek_v41/phases_timed.zig b/zig/src/families/deepseek_v41/phases_timed.zig index 5c195fbdbd2..b2c38fadaeb 100644 --- a/zig/src/families/deepseek_v41/phases_timed.zig +++ b/zig/src/families/deepseek_v41/phases_timed.zig @@ -17,7 +17,11 @@ pub const TimedTarget = struct { return .{ .ptr = t, .vtable = &vtable }; } - const vtable: iface.Target.VTable = .{ .prefill = prefill, .window = window, .keep = keep, .taps = taps, .release = release, .admit = admit, .begin = begin, .piece = piece, .finish = finish, .tail = tail, .pieces = pieces, .replays = replays, .warm = warm }; + const vtable: iface.Target.VTable = .{ .prefill = prefill, .window = window, .keep = keep, .taps = taps, .release = release, .admit = admit, .begin = begin, .piece = piece, .finish = finish, .tail = tail, .pieces = pieces, .replays = replays, .warm = warm, .resumed = resumed }; + + fn resumed(p: *anyopaque, slot: u32) u64 { + return self(p).inner.resumedRows(slot); + } fn admit(p: *anyopaque, slot: u32, max_new: u64) void { self(p).inner.admit(slot, max_new); diff --git a/zig/tests/dsv41_metal/boot_test.zig b/zig/tests/dsv41_metal/boot_test.zig new file mode 100644 index 00000000000..62f45a6ca43 --- /dev/null +++ b/zig/tests/dsv41_metal/boot_test.zig @@ -0,0 +1,171 @@ +//! A small release-format checkpoint folder booted the way the server boots one (boot.zig), and served a reply. +const std = @import("std"); +const pkg = @import("dsv41_metal"); +const host = @import("dsv41"); +const fixture = @import("fixture.zig"); +const fixtures = @import("dsv41_serve_fixtures"); + +const api = host.api; +const Served = host.serve_lanes.Served; +const Config = host.config.Config; +const testing = std.testing; + +/// The mini tokenizer's special tokens move from ids 1000 .. 1010 to right after its 266 byte-level ones. +const special0 = 266; + +/// The tiny drafted model without Engram, its vocabulary the mini tokenizer's (277 ids in 384; BOS 266, EOS 267). +pub fn config() Config { + var c = fixture.dsparkConfig(); + c.vocab = 384; + c.engram_layers = host.config.Ids.of(&.{}); + c.engram_rows = host.config.List(u64, 8).of(&.{}); + c.bos = special0; + c.eos = special0 + 1; + return c; +} + +/// The mini tokenizer with its special tokens at special0 .. +fn tokenizer(a: std.mem.Allocator) ![]u8 { + var text = try a.dupe(u8, fixtures.mini_tokenizer); + for (0..11) |i| { + var from: [16]u8 = undefined; + var to: [16]u8 = undefined; + const next = try std.mem.replaceOwned(u8, a, text, try std.fmt.bufPrint(&from, "\"id\": {d},", .{1000 + i}), try std.fmt.bufPrint(&to, "\"id\": {d},", .{special0 + i})); + a.free(text); + text = next; + } + return text; +} + +fn list(w: *std.Io.Writer, xs: anytype) !void { + try w.writeByte('['); + for (xs, 0..) |x, i| try w.print("{s}{d}", .{ if (i == 0) "" else ",", x }); + try w.writeByte(']'); +} + +/// config.json as a release checkpoint writes it, at `c`'s shapes. +fn configJson(a: std.mem.Allocator, c: *const Config) ![]u8 { + var out: std.Io.Writer.Allocating = .init(a); + defer out.deinit(); + const w = &out.writer; + try w.print("{{\"model_type\":\"deepseek_v41\",\"bos_token_id\":{d},\"eos_token_id\":{d},", .{ c.bos, c.eos }); + try w.writeAll("\"quantization_config\":{\"quant_method\":\"fp8\",\"weight_block_size\":[32,32],\"scale_fmt\":\"ue8m0\",\"expert_dtype\":\"fp4\"},"); + const ints = .{ + .{ "vocab_size", c.vocab }, .{ "hidden_size", c.hidden }, .{ "num_hidden_layers", c.layers }, + .{ "num_attention_heads", c.heads }, .{ "head_dim", c.head_dim }, .{ "qk_rope_head_dim", c.rope_dim }, + .{ "q_lora_rank", c.q_lora }, .{ "o_lora_rank", c.o_lora }, .{ "o_groups", c.o_groups }, + .{ "sliding_window", c.window }, .{ "n_routed_experts", c.experts }, .{ "n_shared_experts", c.shared_experts }, + .{ "num_experts_per_tok", c.topk }, .{ "moe_intermediate_size", c.expert_width }, .{ "index_n_heads", c.index_heads }, + .{ "index_head_dim", c.index_dim }, .{ "index_topk", c.index_topk }, .{ "candidate_source_layer_id", c.candidate_source }, + .{ "candidate_topk_blocks", c.candidate_blocks }, .{ "candidate_block_size", c.candidate_block_size }, .{ "hc_mult", c.hc_mult }, + .{ "hc_sinkhorn_iters", c.hc_sinkhorn_iters }, .{ "engram_max_ngram_size", c.engram_max_ngram }, .{ "engram_vocab_size", c.engram_vocab }, + .{ "engram_n_heads", c.engram_heads }, .{ "engram_head_dim", c.engram_head_dim }, .{ "engram_pad_token_id", c.engram_pad }, + .{ "engram_compressed_vocab_size", c.engram_compressed_vocab }, .{ "num_nextn_predict_layers", c.mtp_layers }, .{ "dspark_block_size", c.dspark_block }, + .{ "dspark_noise_token_id", c.dspark_noise_token }, .{ "dspark_markov_rank", c.dspark_markov_rank }, .{ "dspark_n_routed_experts", c.dspark_experts }, + .{ "dspark_num_experts_per_tok", c.dspark_topk }, .{ "num_key_value_heads", 1 }, .{ "max_position_embeddings", c.rope.max_positions }, + }; + inline for (ints) |p| try w.print("\"{s}\":{d},", .{ p[0], p[1] }); + const floats = .{ + .{ "rms_norm_eps", c.eps }, .{ "routed_scaling_factor", c.routed_scale }, .{ "swiglu_limit", c.swiglu_limit }, + .{ "hc_eps", c.hc_eps }, .{ "hc_post_alpha", c.hc_post_alpha }, .{ "engram_gate_clamp", c.engram_gate_clamp }, + .{ "rope_theta", c.rope.theta }, .{ "compress_rope_theta", c.rope.compress_theta }, + }; + inline for (floats) |p| try w.print("\"{s}\":{e},", .{ p[0], p[1] }); + const lists = .{ + .{ "compress_ratios", c.compress_ratios.items() }, .{ "kv_source_layer_ids", c.kv_sources.items() }, + .{ "index_source_layer_ids", c.index_sources.items() }, .{ "engram_layer_ids", c.engram_layers.items() }, + .{ "dspark_target_layer_ids", c.dspark_targets.items() }, .{ "engram_num_embeddings", c.engram_rows.items() }, + }; + inline for (lists) |p| { + try w.print("\"{s}\":", .{p[0]}); + try list(w, p[1]); + try w.writeByte(','); + } + try w.print("\"norm_topk_prob\":{},\"scoring_func\":\"sqrtsoftplus\",\"topk_method\":\"noaux_tc\",", .{c.norm_topk}); + try w.print("\"rope_scaling\":{{\"rope_type\":\"yarn\",\"factor\":{e},\"beta_fast\":{e},\"beta_slow\":{e},\"original_max_position_embeddings\":{d}}}}}", .{ c.rope.factor, c.rope.beta_fast, c.rope.beta_slow, c.rope.original_max_positions }); + return out.toOwnedSlice(); +} + +/// The folder: config.json, the weights (3 shards and their index), the mini tokenizer. +pub fn write(a: std.mem.Allocator, io: std.Io, dir: std.Io.Dir, seed: u64) !void { + var c = config(); + try c.validate(); + const json = try configJson(a, &c); + defer a.free(json); + try dir.writeFile(io, .{ .sub_path = "config.json", .data = json }); + const img = try fixture.image(a, &c, seed); + defer a.free(img); + try @import("shards.zig").write(a, io, dir, img, 3, 0); + const tok = try tokenizer(a); + defer a.free(tok); + try dir.writeFile(io, .{ .sub_path = "tokenizer.json", .data = tok }); +} + +test "dsv41 metal boot: a small checkpoint folder parses back to its config, boots and replies, drafted == draft:false" { + const a = testing.allocator; + const io = testing.io; + var tmp = testing.tmpDir(.{}); + defer tmp.cleanup(); + try write(a, io, tmp.dir, 81); + const dir = try tmp.dir.realPathFileAlloc(io, ".", a); + defer a.free(dir); + // TF_DSV41_SMOKE_DIR: the same folder written there too, for a server's smoke boot + if (std.c.getenv("TF_DSV41_SMOKE_DIR")) |d| { + var out = try std.Io.Dir.cwd().openDir(io, std.mem.span(d), .{}); + defer out.close(io); + try write(a, io, out, 81); + } + const want = config(); + const m = try pkg.boot.Boot.open(a, io, dir, .{ .slots = 2, .context = 1024, .small = true, .cache_bytes = 0 }); + const got = m.parts.env.c; + try testing.expectEqual(want.vocab, got.vocab); + try testing.expectEqualSlices(u32, want.compress_ratios.items(), got.compress_ratios.items()); + try testing.expectEqual(want.eos, got.eos); + const s = try Served.open(a, io, m.model(), dir, null); + defer Served.close(s); + const e = s.engine(); + const prompt = [_]u32{ special0, special0 + 5, 70, 71, 72, 73, special0 + 6 }; + var replies: [2][24]u32 = undefined; + for ([_]bool{ true, false }, &replies, 0..) |drafts, *r, i| { + var box: Box = .{}; + const req: api.Request = .{ .prompt = &prompt, .max_tokens = 24, .drafts = drafts }; + try e.submit(@intCast(900 + i), &req, .{ .ctx = &box, .event = Box.event }); + try box.wait(io); + try testing.expectEqual(@as(usize, 24), box.n); + r.* = box.out; + } + std.debug.print("{s} dsv41 metal boot: {d} layers from 3 shards, a reply of 24 tokens, drafted == draft:false\n", .{ if (std.mem.eql(u32, &replies[0], &replies[1])) "PASS" else "FAIL", got.layers }); + try testing.expectEqualSlices(u32, &replies[1], &replies[0]); +} + +const Box = struct { + mutex: std.Io.Mutex = .init, + out: [24]u32 = undefined, + n: usize = 0, + done: bool = false, + + fn event(ctx: *anyopaque, _: api.Id, e: *const api.Event) void { + const b: *Box = @ptrCast(@alignCast(ctx)); + b.mutex.lockUncancelable(testing.io); + defer b.mutex.unlock(testing.io); + switch (e.*) { + .tokens => |ts| for (ts) |t| if (b.n < b.out.len) { + b.out[b.n] = t; + b.n += 1; + }, + .finished => b.done = true, + else => {}, + } + } + + fn wait(b: *Box, io: std.Io) !void { + for (0..300_000) |_| { + b.mutex.lockUncancelable(io); + const done = b.done; + b.mutex.unlock(io); + if (done) return; + std.Io.sleep(io, .fromMilliseconds(1), .awake) catch {}; + } + return error.Timeout; + } +}; diff --git a/zig/tests/dsv41_metal/fixture_serve.zig b/zig/tests/dsv41_metal/fixture_serve.zig new file mode 100644 index 00000000000..8f276cc7c5d --- /dev/null +++ b/zig/tests/dsv41_metal/fixture_serve.zig @@ -0,0 +1,69 @@ +//! The tiny model served on Metal: prompt split, Engram before it, a DSpark drafter; its serve.Metal over the rig. +const std = @import("std"); +const pkg = @import("dsv41_metal"); +const host = @import("dsv41"); +const fixture = @import("fixture.zig"); +const ff = @import("fixture_fwd.zig"); + +pub const limit = 1280; + +/// The prompt model (ced's split at layer 4, Engram at 1 and 3) with fixture.dsparkConfig's drafter. +pub fn config() host.config.Config { + var c = fixture.promptConfig(); + const d = fixture.dsparkConfig(); + c.mtp_layers = d.mtp_layers; + c.dspark_block = d.dspark_block; + c.dspark_noise_token = d.dspark_noise_token; + c.dspark_markov_rank = d.dspark_markov_rank; + c.dspark_experts = d.dspark_experts; + c.dspark_topk = d.dspark_topk; + return c; +} + +/// The rig (weights, Engram rows and hashes) and the drafter's weights the served model borrows. +const Held = struct { + a: std.mem.Allocator, + f: *ff.Fwd, + w: pkg.dspark.Weights, + + fn close(ctx: *anyopaque) void { + const h: *Held = @ptrCast(@alignCast(ctx)); + h.w.deinit(); + h.f.deinit(); + h.a.destroy(h); + } +}; + +pub const Opts = struct { slots: u32 = 4, drafts: bool = true, cache_bytes: u64 = 0, chunk: u32 = 64 }; + +/// The tiny model from `seed` served on this GPU; the returned model owns the rig (closed with it). +pub fn open(a: std.mem.Allocator, io: std.Io, seed: u64, o: Opts) !*pkg.serve.Metal { + const h = try a.create(Held); + errdefer a.destroy(h); + h.a = a; + h.f = try ff.Fwd.initWith(a, io, config(), limit, seed); + errdefer h.f.deinit(); + const r = h.f.r; + { + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const img = try fixture.image(a, &r.c, seed); + defer a.free(img); + try tmp.dir.writeFile(io, .{ .sub_path = "model.safetensors", .data = img }); + const dir = try tmp.dir.realPathFileAlloc(io, ".", a); + defer a.free(dir); + var pack = try host.pack.Pack.open(a, io, dir); + defer pack.deinit(); + h.w = try pkg.dspark.loadWeights(a, io, r.device, &pack, &r.c); + } + errdefer h.w.deinit(); + const env: pkg.target.Env = .{ .device = r.device, .queue = r.queue, .c = &r.c, .p = &r.p, .tables = &r.tables, .s = &r.s, .model = h.f.model(), .lookup = h.f.lookup() }; + const parts: pkg.serve.Parts = .{ .env = env, .top = &r.top.?, .dspark = &h.w, .owner = .{ .ctx = h, .close = Held.close } }; + return pkg.serve.Metal.open(a, parts, .{ .slots = o.slots, .limit = limit, .drafts = o.drafts, .cache_bytes = o.cache_bytes, .prompt = .{ .chunk = o.chunk } }); +} + +/// Closes a model `open` made (the served engine closes its own through serve_lanes). +pub fn close(m: *pkg.serve.Metal) void { + const md = m.model(); + md.close(md.ptr); +} diff --git a/zig/tests/dsv41_metal/layer_test.zig b/zig/tests/dsv41_metal/layer_test.zig index 0cb448c3720..83ed237f9bb 100644 --- a/zig/tests/dsv41_metal/layer_test.zig +++ b/zig/tests/dsv41_metal/layer_test.zig @@ -17,6 +17,7 @@ test { _ = @import("zerocopy_test.zig"); _ = @import("prompt_test.zig"); _ = @import("dspark_test.zig"); + _ = @import("multi_test.zig"); } test "dsv41 metal: every stage of every layer kind within its float64 bound" { diff --git a/zig/tests/dsv41_metal/multi_test.zig b/zig/tests/dsv41_metal/multi_test.zig new file mode 100644 index 00000000000..4819c786c6d --- /dev/null +++ b/zig/tests/dsv41_metal/multi_test.zig @@ -0,0 +1,219 @@ +//! Rows of several slots in one decode launch equal each slot's rows launched alone, bit for bit. +const std = @import("std"); +const mtl = @import("metal"); +const pkg = @import("dsv41_metal"); +const host = @import("dsv41"); +const fixture = @import("fixture.zig"); +const ff = @import("fixture_fwd.zig"); +const fs = @import("fixture_serve.zig"); + +const testing = std.testing; +const fwd = pkg.forward; +const limit = 1280; +const look = 3; + +/// One slot's share of a launch: where it stands and the ids its rows carry (after `look` ids of lookback). +const Part = struct { p0: u32, hist: []u32, n: usize }; + +fn finish(r: *fixture.Rig, f: *ff.Fwd, x: *const pkg.ctx.Ctx, rows: u32) !void { + const pass = fixture.Pass.begin(r.queue); + try fwd.encode(x, pass.e, f.model(), &f.b); + try pass.finish(); + _ = rows; +} + +/// Each part's rows alone on its slot (the single-stream path): logits [rows][vocab] and taps per part, concatenated. +fn alone(a: std.mem.Allocator, f: *ff.Fwd, slots: []pkg.kv.Slot, parts: []const Part, logits: []f32, taps: []u16) !void { + const r = f.r; + const c = &r.c; + const V: usize = c.vocab; + const TH = c.dspark_targets.len * c.hidden; + _ = a; + var r0: usize = 0; + for (parts, slots) |pt, *sl| { + try fwd.prepare(&f.b, c, pt.hist[look..][0..pt.n], pt.hist[0..look], f.lookup()); + try r.s.writeRows(c, pt.p0, @intCast(pt.n)); + const x = r.ctx(sl, pt.p0, @intCast(pt.n)); + try finish(r, f, &x, @intCast(pt.n)); + @memcpy(logits[r0 * V ..][0 .. pt.n * V], f.b.logitsOf(c, pt.n)); + @memcpy(taps[r0 * TH ..][0 .. pt.n * TH], sl.taps.?.slice(u16, pt.n * TH)); + r0 += pt.n; + } +} + +/// All parts' rows in one launch; the taps are read back from each slot. +fn together(f: *ff.Fwd, slots: []pkg.kv.Slot, parts: []const Part, logits: []f32, taps: []u16) !void { + const r = f.r; + const c = &r.c; + const V: usize = c.vocab; + const TH = c.dspark_targets.len * c.hidden; + var pieces: [16]fwd.Piece = undefined; + var spans: [16]pkg.scratch.Span = undefined; + var segs: [16]pkg.ctx.Seg = undefined; + var r0: u32 = 0; + for (parts, slots, 0..) |pt, *sl, i| { + pieces[i] = .{ .ids = pt.hist[look..][0..pt.n], .lookback = pt.hist[0..look] }; + spans[i] = .{ .p0 = pt.p0, .n = @intCast(pt.n) }; + segs[i] = .{ .slot = sl, .p0 = pt.p0, .r0 = r0, .n = @intCast(pt.n) }; + r0 += @intCast(pt.n); + } + const k = parts.len; + try fwd.prepareSegs(&f.b, c, pieces[0..k], f.lookup()); + try r.s.writeSpans(c, spans[0..k]); + var x = r.ctx(&slots[0], parts[0].p0, r0); + x.segs = segs[0..k]; + try finish(r, f, &x, r0); + @memcpy(logits[0 .. r0 * V], f.b.logitsOf(c, r0)); + var at: usize = 0; + for (parts, slots) |pt, *sl| { + @memcpy(taps[at * TH ..][0 .. pt.n * TH], sl.taps.?.slice(u16, pt.n * TH)); + at += pt.n; + } +} + +fn reset(r: *fixture.Rig, to: *const pkg.kv.Slot, from: *const pkg.kv.Slot) !void { + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const cb = r.queue.commandBuffer(); + to.copyFrom(cb, from); + cb.commit(); + cb.wait(); + if (cb.failure() != null) return error.CommandBufferFailed; +} + +/// Bytes that differ between two slots' every region: window, pool, keys, carry and the carry's inputs. +fn stateDiff(x: *const pkg.kv.Slot, y: *const pkg.kv.Slot) usize { + var n: usize = 0; + for (x.regions, y.regions) |p, q| { + const pairs = [_][2]?mtl.Buffer{ .{ p.window, q.window }, .{ p.pool, q.pool }, .{ p.keys, q.keys }, .{ p.carry, q.carry }, .{ p.inputs, q.inputs } }; + for (pairs) |pr| if (pr[0]) |bx| { + const len = bx.length(); + for (bx.contents()[0..len], pr[1].?.contents()[0..len]) |s, t| n += @intFromBool(s != t); + }; + } + return n; +} + +/// Slots at `starts` with `rows` rows each: one launch of all vs one launch each, bit for bit. +fn compare(a: std.mem.Allocator, f: *ff.Fwd, starts: []const u32, rows: []const usize, seed: u64) !usize { + const r = f.r; + const c = &r.c; + const k = starts.len; + var pristine: [4]pkg.kv.Slot = undefined; + var one: [4]pkg.kv.Slot = undefined; + var many: [4]pkg.kv.Slot = undefined; + var parts: [4]Part = undefined; + var made: usize = 0; + defer for (0..made) |i| { + pristine[i].deinit(); + one[i].deinit(); + many[i].deinit(); + a.free(parts[i].hist); + }; + var total: usize = 0; + for (0..k) |i| { + pristine[i] = try pkg.kv.Slot.init(a, r.device, c, limit); + one[i] = try pkg.kv.Slot.init(a, r.device, c, limit); + many[i] = try pkg.kv.Slot.init(a, r.device, c, limit); + parts[i] = .{ .p0 = starts[i], .hist = try ff.ids(a, c, look + rows[i], seed + 10 * i), .n = rows[i] }; + made = i + 1; + fixture.fillPast(c, &pristine[i], starts[i], seed + 100 * i); + try reset(r, &one[i], &pristine[i]); + try reset(r, &many[i], &pristine[i]); + total += rows[i]; + } + const TH = c.dspark_targets.len * c.hidden; + const l1 = try a.alloc(f32, total * c.vocab); + defer a.free(l1); + const ln = try a.alloc(f32, total * c.vocab); + defer a.free(ln); + const t1 = try a.alloc(u16, total * TH); + defer a.free(t1); + const tn = try a.alloc(u16, total * TH); + defer a.free(tn); + try alone(a, f, one[0..k], parts[0..k], l1, t1); + try together(f, many[0..k], parts[0..k], ln, tn); + var bad: usize = 0; + for (l1, ln) |s, t| bad += @intFromBool(@as(u32, @bitCast(s)) != @as(u32, @bitCast(t))); + var tb: usize = 0; + for (t1, tn) |s, t| tb += @intFromBool(s != t); + var st: usize = 0; + for (0..k) |i| st += stateDiff(&one[i], &many[i]); + const word = if (bad + tb + st == 0) "PASS" else "FAIL"; + std.debug.print("{s} dsv41 metal multi-slot forward: {d} slots, {d} rows in one launch vs one launch a slot: {d} logits, {d} tap values, {d} state bytes differ\n", .{ word, k, total, bad, tb, st }); + return bad + tb + st; +} + +test "dsv41 metal multi-slot forward: rows of 2, 3 and 4 slots in one launch equal each slot's launch alone" { + const a = testing.allocator; + const f = try ff.Fwd.init(a, testing.io, limit, 61); + defer f.deinit(); + var bad: usize = 0; + // positions of both parities, a slot near the start and one past the window; ratio 2 pools complete on odd rows + bad += try compare(a, f, &.{ 1101, 1104 }, &.{ 3, 5 }, 300); + bad += try compare(a, f, &.{ 1103, 640, 1100 }, &.{ 1, 4, 2 }, 310); + bad += try compare(a, f, &.{ 1101, 1104, 1099, 97 }, &.{ 4, 4, 4, 4 }, 320); + bad += try compare(a, f, &.{ 1101, 1102, 1103, 1104 }, &.{ 1, 1, 1, 1 }, 330); + bad += try compare(a, f, &.{ 7, 128, 1101, 1279 - 6 }, &.{ 2, 6, 1, 7 }, 340); + try testing.expectEqual(@as(usize, 0), bad); +} + +/// A model with the tiny drafter's config and prompts of different lengths on its slots. +fn rounds(m: *pkg.serve.Metal, packed_: bool, out: *std.ArrayList(u32)) !void { + const a = testing.allocator; + const tg = m.t.target(); + const lens = [4]usize{ 150, 211, 64, 333 }; + var next: [4]u32 = undefined; + var prompts: [4][]u32 = undefined; + for (&prompts, 0..) |*p, i| p.* = try ff.ids(a, &fs.config(), lens[i], 400 + i); + defer for (prompts) |p| a.free(p); + for (0..4) |i| next[i] = try tg.prefill(@intCast(i), prompts[i], null, lens[i]); + var pos = lens; + // verify rounds of one anchor and three drafts a slot; the keep cuts back a different number each time + for (0..4) |round| { + var toks: [4][4]u32 = undefined; + var draws: [4][4]u64 = undefined; + var chs: [4][4]u32 = undefined; + var segs: [4]host.iface.Segment = undefined; + var cs: [4][]u32 = undefined; + for (0..4) |i| { + toks[i][0] = next[i]; + for (1..4) |j| toks[i][j] = @intCast((next[i] * 7 + j * 13 + round * 5 + i) % 200); + for (&draws[i], 0..) |*d, j| d.* = pos[i] + 1 + j; + segs[i] = .{ .slot = @intCast(i), .start = pos[i], .tokens = &toks[i], .parents = null, .draws = &draws[i], .sampling = null }; + cs[i] = &chs[i]; + } + if (packed_) try tg.window(&segs, &cs) else for (0..4) |i| try tg.window(segs[i .. i + 1], cs[i .. i + 1]); + for (0..4) |i| { + const kept: u32 = @intCast(1 + (i + round) % 4); + const path = [_]u32{ 0, 1, 2, 3 }; + try tg.keep(@intCast(i), path[0..kept]); + try out.appendSlice(a, &chs[i]); + pos[i] += kept; + next[i] = chs[i][kept - 1]; + } + } + for (0..4) |i| tg.release(@intCast(i)); +} + +test "dsv41 metal multi-slot forward: a 4-slot DSpark verify round in one launch equals per-slot launches" { + const a = testing.allocator; + const m1 = try fs.open(a, testing.io, 71, .{}); + defer fs.close(m1); + const m2 = try fs.open(a, testing.io, 71, .{}); + defer fs.close(m2); + var o1: std.ArrayList(u32) = .empty; + defer o1.deinit(a); + var o2: std.ArrayList(u32) = .empty; + defer o2.deinit(a); + try rounds(m1, true, &o1); + try rounds(m2, false, &o2); + var st: usize = 0; + for (m1.t.slots, m2.t.slots) |*x, *y| st += stateDiff(&x.kv, &y.kv); + const same = std.mem.eql(u32, o1.items, o2.items); + const word = if (same and st == 0) "PASS" else "FAIL"; + std.debug.print("{s} dsv41 metal multi-slot verify rounds: {d} choices, {d} launches in one vs {d} apart, {d} state bytes differ\n", .{ word, o1.items.len, m1.t.stats.launches, m2.t.stats.launches, st }); + try testing.expect(same); + try testing.expectEqual(@as(usize, 0), st); + try testing.expect(m1.t.stats.launches < m2.t.stats.launches); +} diff --git a/zig/tests/dsv41_metal/serve_test.zig b/zig/tests/dsv41_metal/serve_test.zig new file mode 100644 index 00000000000..9bf82fd51a5 --- /dev/null +++ b/zig/tests/dsv41_metal/serve_test.zig @@ -0,0 +1,267 @@ +//! The tiny model served on Metal through serve_lanes and LaneHost: replies equal the target's own serial decode. +const std = @import("std"); +const pkg = @import("dsv41_metal"); +const host = @import("dsv41"); +const fs = @import("fixture_serve.zig"); +const ff = @import("fixture_fwd.zig"); + +const api = host.api; +const Served = host.serve_lanes.Served; +const testing = std.testing; +const gpa = testing.allocator; +const io = testing.io; +const seed = 71; + +test { + _ = @import("boot_test.zig"); +} + +/// A reply's tokens and finish, written on LaneHost's thread and read on the test's. +const Box = struct { + mutex: std.Io.Mutex = .init, + out: std.ArrayList(u32) = .empty, + done: bool = false, + reason: ?api.Reason = null, + drafted: u64 = 0, + cached: u32 = 0, + + fn event(ctx: *anyopaque, _: api.Id, e: *const api.Event) void { + const b: *Box = @ptrCast(@alignCast(ctx)); + b.mutex.lockUncancelable(io); + defer b.mutex.unlock(io); + switch (e.*) { + .tokens => |ts| b.out.appendSlice(gpa, ts) catch {}, + .finished => |fin| { + b.done = true; + b.reason = fin.reason; + b.drafted = fin.stats.drafted; + }, + .prefilled => |n| b.cached = n, + else => {}, + } + } + + fn wait(b: *Box) !void { + for (0..600_000) |_| { + b.mutex.lockUncancelable(io); + const done = b.done; + b.mutex.unlock(io); + if (done) return; + std.Io.sleep(io, .fromMilliseconds(1), .awake) catch {}; + } + return error.Timeout; + } + + fn deinit(b: *Box) void { + b.out.deinit(gpa); + } +}; + +/// One request to send: its prompt, length, drafts and sampling. +const Ask = struct { prompt: []const u32, max: u32 = 24, drafts: bool = true, sampling: ?api.Sampling = null }; + +var next_id: api.Id = 1; +/// The prompt rows each reply of the last `serve` call took from kept state (its `prefilled` event), in ask order. +var cached_rows: [8]u32 = undefined; + +/// The asks sent together (or each after the last finished); each reply returned gpa-owned, the drafted rows summed. +fn serve(e: api.Engine, asks: []const Ask, together: bool, out: [][]u32, drafted: *u64) !void { + const boxes = try gpa.alloc(Box, asks.len); + defer gpa.free(boxes); + @memset(boxes, .{}); + defer for (boxes) |*b| b.deinit(); + const reqs = try gpa.alloc(api.Request, asks.len); + defer gpa.free(reqs); + for (reqs, asks) |*r, k| r.* = .{ .prompt = k.prompt, .max_tokens = k.max, .drafts = k.drafts, .sampling = k.sampling }; + for (reqs, boxes) |*r, *b| { + next_id += 1; + try e.submit(next_id, r, .{ .ctx = b, .event = Box.event }); + if (!together) try b.wait(); + } + for (boxes, out, asks, 0..) |*b, *o, k, i| { + try b.wait(); + try testing.expectEqual(api.Reason.length, b.reason.?); + try testing.expectEqual(@as(usize, k.max), b.out.items.len); + drafted.* += b.drafted; + cached_rows[i] = b.cached; + o.* = try b.out.toOwnedSlice(gpa); + } +} + +fn freeAll(xs: [][]u32) void { + for (xs) |x| gpa.free(x); +} + +/// The reference: the target's serial decode of each ask on a model of its own (no lanes, no cache, no drafts). +fn reference(asks: []const Ask, out: [][]u32) !void { + const m = try fs.open(gpa, io, seed, .{ .slots = 1, .drafts = false }); + defer fs.close(m); + for (asks, out) |k, *o| o.* = try m.t.serial(0, k.prompt, k.max, k.sampling); +} + +fn ids(n: usize, s: u64) ![]u32 { + return ff.ids(gpa, &fs.config(), n, s); +} + +fn say(ok: bool, comptime fmt: []const u8, args: anytype) void { + std.debug.print("{s} dsv41 metal serve: ", .{if (ok) "PASS" else "FAIL"}); + std.debug.print(fmt ++ "\n", args); +} + +fn same(want: []const []u32, got: []const []u32) usize { + var bad: usize = 0; + for (want, got) |w, g| bad += @intFromBool(!std.mem.eql(u32, w, g)); + return bad; +} + +test "dsv41 metal serve: (a) concurrent == solo == serial, (b) drafted == draft:false, through LaneHost" { + const p0 = try ids(150, 1); + defer gpa.free(p0); + const p1 = try ids(620, 2); + defer gpa.free(p1); + const asks = [_]Ask{ .{ .prompt = p0 }, .{ .prompt = p1 } }; + var want: [2][]u32 = undefined; + try reference(&asks, &want); + defer freeAll(&want); + const m = try fs.open(gpa, io, seed, .{}); + const s = try Served.open(gpa, io, m.model(), ".", null); + defer Served.close(s); + const e = s.engine(); + var drafted: u64 = 0; + var solo: [2][]u32 = undefined; + try serve(e, &asks, false, &solo, &drafted); + defer freeAll(&solo); + var both: [2][]u32 = undefined; + try serve(e, &asks, true, &both, &drafted); + defer freeAll(&both); + const plain_asks = [_]Ask{ .{ .prompt = p0, .drafts = false }, .{ .prompt = p1, .drafts = false } }; + var plain_drafted: u64 = 0; + var plain: [2][]u32 = undefined; + try serve(e, &plain_asks, true, &plain, &plain_drafted); + defer freeAll(&plain); + const bad = [3]usize{ same(&want, &solo), same(&want, &both), same(&want, &plain) }; + say(bad[0] == 0, "(a) solo vs serial: {d} of 2 replies differ", .{bad[0]}); + say(bad[1] == 0, "(a) together vs serial: {d} of 2 replies differ ({d} windows of {d} rows in all)", .{ bad[1], m.t.stats.windows, m.t.stats.rows }); + say(bad[2] == 0 and drafted > 0 and plain_drafted == 0, "(b) draft:false vs serial: {d} differ; drafted rows {d} (drafts on), {d} (off), {d} pass launches, {d} windows cut back", .{ bad[2], drafted, plain_drafted, m.ad.passes, m.t.stats.rewinds }); + try testing.expectEqual([3]usize{ 0, 0, 0 }, bad); + try testing.expect(drafted > 0 and m.t.stats.rewinds > 0); + try testing.expectEqual(@as(u64, 0), plain_drafted); +} + +test "dsv41 metal serve: (c) prompt-cache hits (the same prompt, a later turn) == fresh runs" { + const p = try ids(300, 3); + defer gpa.free(p); + const m = try fs.open(gpa, io, seed, .{ .cache_bytes = 1 << 30 }); + const s = try Served.open(gpa, io, m.model(), ".", null); + defer Served.close(s); + const e = s.engine(); + var drafted: u64 = 0; + var first: [1][]u32 = undefined; + try serve(e, &.{.{ .prompt = p, .max = 40 }}, false, &first, &drafted); + defer freeAll(&first); + const first_cached = cached_rows[0]; + // a later turn: the prompt, the reply but its last token, new ids; then the first prompt again + const extra = try ids(50, 4); + defer gpa.free(extra); + const turn = try std.mem.concat(gpa, u32, &.{ p, first[0][0..39], extra }); + defer gpa.free(turn); + const branch = try std.mem.concat(gpa, u32, &.{ p, extra }); + defer gpa.free(branch); + const asks = [_]Ask{ .{ .prompt = turn, .max = 30 }, .{ .prompt = p, .max = 40 }, .{ .prompt = branch, .max = 30 } }; + const hits0 = m.t.stats.hits; + var got: [3][]u32 = undefined; + try serve(e, &asks, false, &got, &drafted); + defer freeAll(&got); + const hits = m.t.stats.hits - hits0; + const reported = cached_rows[0..3].*; + var want: [3][]u32 = undefined; + try reference(&asks, &want); + defer freeAll(&want); + const bad = same(&want, &got); + say(bad == 0 and hits == 3, "(c) 3 cached prompts ({d} hits, {d} rows restored in all) vs fresh: {d} replies differ", .{ hits, m.t.stats.cached_rows, bad }); + try testing.expectEqual(@as(usize, 0), bad); + try testing.expectEqual(@as(u64, 3), hits); + // each reply reports the rows it resumed (prompt_tokens_details.cached_tokens) + say(reported[0] > p.len and reported[1] >= p.len and reported[2] >= p.len, "(c) cached rows reported {any} for prompts of {d}, {d} and {d} tokens", .{ reported, turn.len, p.len, branch.len }); + for (reported, [3]usize{ turn.len, p.len, branch.len }) |r, n| try testing.expect(r > 0 and r <= n); + try testing.expect(reported[0] > p.len and reported[1] >= p.len and reported[2] >= p.len); + try testing.expectEqual(@as(u32, 0), first_cached); + // the later turn resumed past the first prompt: its reply's rows came from the cache too + try testing.expect(m.t.stats.cached_rows >= 3 * p.len + 30); +} + +test "dsv41 metal serve: (d) sampled replies are their seed's: again, drafted or not, together, serial" { + const p0 = try ids(200, 5); + defer gpa.free(p0); + const p1 = try ids(90, 6); + defer gpa.free(p1); + const hot: api.Sampling = .{ .seed = 1234, .temperature = 0.9, .top_k = 0, .top_p = 1.0 }; + const nucleus: api.Sampling = .{ .seed = 99, .temperature = 0.7, .top_k = 40, .top_p = 0.9 }; + const asks = [_]Ask{ .{ .prompt = p0, .sampling = hot }, .{ .prompt = p1, .sampling = nucleus } }; + var want: [2][]u32 = undefined; + try reference(&asks, &want); + defer freeAll(&want); + const m = try fs.open(gpa, io, seed, .{}); + const s = try Served.open(gpa, io, m.model(), ".", null); + defer Served.close(s); + const e = s.engine(); + var drafted: u64 = 0; + var a1: [2][]u32 = undefined; + try serve(e, &asks, true, &a1, &drafted); + defer freeAll(&a1); + var a2: [2][]u32 = undefined; + try serve(e, &asks, false, &a2, &drafted); + defer freeAll(&a2); + const plain_asks = [_]Ask{ .{ .prompt = p0, .sampling = hot, .drafts = false }, .{ .prompt = p1, .sampling = nucleus, .drafts = false } }; + var a3: [2][]u32 = undefined; + try serve(e, &plain_asks, true, &a3, &drafted); + defer freeAll(&a3); + var other_seed = hot; + other_seed.seed = 1235; + var a4: [1][]u32 = undefined; + try serve(e, &.{.{ .prompt = p0, .sampling = other_seed }}, false, &a4, &drafted); + defer freeAll(&a4); + const bad = [3]usize{ same(&want, &a1), same(&want, &a2), same(&want, &a3) }; + const moved = !std.mem.eql(u32, a4[0], want[0]); + say(bad[0] + bad[1] + bad[2] == 0 and moved, "(d) together / again / draft:false vs serial: {d} / {d} / {d} differ; another seed's reply {s}", .{ bad[0], bad[1], bad[2], if (moved) "differs" else "is the same" }); + try testing.expectEqual([3]usize{ 0, 0, 0 }, bad); + try testing.expect(moved); +} + +test "dsv41 metal serve: (e) a request cancelled during its prompt leaves the slot and the next request valid" { + const long = try ids(1100, 7); + defer gpa.free(long); + const p0 = try ids(120, 8); + defer gpa.free(p0); + const p1 = try ids(140, 9); + defer gpa.free(p1); + const asks = [_]Ask{ .{ .prompt = p0, .max = 40 }, .{ .prompt = p1 } }; + var want: [2][]u32 = undefined; + try reference(&asks, &want); + defer freeAll(&want); + const m = try fs.open(gpa, io, seed, .{ .slots = 2, .cache_bytes = 1 << 30 }); + const s = try Served.open(gpa, io, m.model(), ".", null); + defer Served.close(s); + const e = s.engine(); + // a decoding stream, then the long prompt (cancelled as soon as it is submitted), then a new request + var bg: Box = .{}; + defer bg.deinit(); + const r0: api.Request = .{ .prompt = p0, .max_tokens = 40 }; + try e.submit(500, &r0, .{ .ctx = &bg, .event = Box.event }); + var gone: Box = .{}; + defer gone.deinit(); + const rl: api.Request = .{ .prompt = long, .max_tokens = 64 }; + try e.submit(501, &rl, .{ .ctx = &gone, .event = Box.event }); + e.cancel(501); + try gone.wait(); + var drafted: u64 = 0; + var after: [1][]u32 = undefined; + try serve(e, asks[1..], false, &after, &drafted); + defer freeAll(&after); + try bg.wait(); + const ok0 = std.mem.eql(u32, want[0], bg.out.items); + const ok1 = std.mem.eql(u32, want[1], after[0]); + say(ok0 and ok1, "(e) cancelled ({t}, {d} tokens out): the decoding reply {s}, the next request's {s} the serial one", .{ gone.reason.?, gone.out.items.len, if (ok0) "equals" else "differs from", if (ok1) "equals" else "differs from" }); + try testing.expect(gone.reason.? == .cancelled); + try testing.expect(ok0 and ok1); +} From b81e9fa036248218998740952e529042ebf25fb7 Mon Sep 17 00:00:00 2001 From: Kevin Gilbertson <880013+gilby@users.noreply.github.com> Date: Tue, 10 Nov 2026 21:21:46 +0100 Subject: [PATCH 02/15] dsv41 metal: decode plain at four or more active streams, where drafts lose --- CHANGELOG.md | 2 + .../families/deepseek_v41/draft/calib_env.zig | 6 ++ zig/src/families/deepseek_v41/draft/depth.zig | 1 + zig/src/families/deepseek_v41/draft/draft.zig | 1 + .../deepseek_v41/draft/lane_owner.zig | 9 ++- zig/src/families/deepseek_v41/draft/lanes.zig | 1 + .../deepseek_v41/draft/plain_streams_test.zig | 80 +++++++++++++++++++ .../families/deepseek_v41/draft/policy.zig | 4 + zig/src/families/deepseek_v41/serve_lanes.zig | 2 +- 9 files changed, 104 insertions(+), 2 deletions(-) create mode 100644 zig/src/families/deepseek_v41/draft/plain_streams_test.zig diff --git a/CHANGELOG.md b/CHANGELOG.md index a1126b73c5d..007e40ecce5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased +- DeepSeek-V4.1 on Metal: rounds with four or more active streams decode plain instead of drafting, since drafts lose there (#1720, part of #1676). + - Flash Next: twenty-nine `TF_FLASHNEXT_*` settings refuse a malformed value by name at startup, before any device work on CUDA, and a Metal load refuses them too; blank `TF_FLASHNEXT_KV_PAGE_TEST` and `TF_FLASHNEXT_KEEP_LATE` read as unset, and a non-finite confidence is refused (#2585, part of #2370). Thanks to @devopsfortunato. - Flash Next on CUDA: twenty-nine `TF_FLASHNEXT_*` settings refuse a malformed value by name at startup, before any device or checkpoint work, through the shared environment table: unset and blank keep the default, a valid value keeps diff --git a/zig/src/families/deepseek_v41/draft/calib_env.zig b/zig/src/families/deepseek_v41/draft/calib_env.zig index 9505e344ac3..187987d3ea8 100644 --- a/zig/src/families/deepseek_v41/draft/calib_env.zig +++ b/zig/src/families/deepseek_v41/draft/calib_env.zig @@ -225,6 +225,7 @@ pub fn depthSettings(get: *const fn ([*:0]const u8) ?[]const u8) !depth.Settings s.fair = try float(get("TF_DSV41_DEPTH_FAIR"), joint.fair, 0.0, 4.0); s.host_ms = try float(get("TF_DSV41_DEPTH_HOST_MS"), joint.host_ms, 0.0, 100.0); if (trimmed(get("TF_DSV41_GRAPH_ROWS_MAX"))) |v| s.max_rows = @max(1, @min(try std.fmt.parseInt(u64, v, 10), costs_mod.max_rows)); + if (trimmed(get("TF_DSV41_DRAFT_PLAIN_STREAMS"))) |v| s.plain_streams = try std.fmt.parseInt(usize, v, 10); return s; } @@ -245,6 +246,11 @@ pub fn env(name: [*:0]const u8) ?[]const u8 { return if (std.c.getenv(name)) |v| std.mem.span(v) else null; } +/// TF_DSV41_DRAFT_PLAIN_STREAMS as depthSettings reads it (set and non-blank). +pub fn plainStreamsSet() bool { + return trimmed(env("TF_DSV41_DRAFT_PLAIN_STREAMS")) != null; +} + fn trimmed(v: ?[]const u8) ?[]const u8 { const t = std.mem.trim(u8, v orelse return null, " \t\r\n"); return if (t.len == 0) null else t; diff --git a/zig/src/families/deepseek_v41/draft/depth.zig b/zig/src/families/deepseek_v41/draft/depth.zig index f1953f6cfa2..e07abfad2f3 100644 --- a/zig/src/families/deepseek_v41/draft/depth.zig +++ b/zig/src/families/deepseek_v41/draft/depth.zig @@ -22,6 +22,7 @@ pub const Settings = struct { max_rows: u64 = 64, code_accept: bool = false, // TF_DSV41_CODE_ACCEPT: expand high-acceptance short-context chains context_bucket: u64 = 2048, // TF_DSV41_GRAPH_BUCKET; short contexts only use its linear buckets + plain_streams: usize = 0, // TF_DSV41_DRAFT_PLAIN_STREAMS: a round with this many active streams or more decodes plain; 0 = off }; /// [E(0) .. E(len)]: tokens a round verifying k drafts commits on average, into `out` (len + 1). diff --git a/zig/src/families/deepseek_v41/draft/draft.zig b/zig/src/families/deepseek_v41/draft/draft.zig index 1cb2f6eee43..69559911c81 100644 --- a/zig/src/families/deepseek_v41/draft/draft.zig +++ b/zig/src/families/deepseek_v41/draft/draft.zig @@ -38,6 +38,7 @@ test { _ = branches; _ = calib_env; _ = @import("calib_env_test.zig"); + _ = @import("plain_streams_test.zig"); _ = calib_measure; _ = @import("calib_measure_test.zig"); _ = branches_oracle; diff --git a/zig/src/families/deepseek_v41/draft/lane_owner.zig b/zig/src/families/deepseek_v41/draft/lane_owner.zig index f9846c91977..d0957002833 100644 --- a/zig/src/families/deepseek_v41/draft/lane_owner.zig +++ b/zig/src/families/deepseek_v41/draft/lane_owner.zig @@ -5,12 +5,19 @@ const iface = @import("iface.zig"); const costs = @import("costs.zig"); const Policy = @import("policy.zig").Policy; const Spec = @import("spec.zig").Spec; -pub fn init(gpa: std.mem.Allocator, target: iface.Target, pass: iface.Pass, prices: costs.Costs, opts: ln.Options) !*ln.Lanes { +pub fn init(gpa: std.mem.Allocator, target: iface.Target, pass: iface.Pass, prices: costs.Costs, opts_in: ln.Options) !*ln.Lanes { + var opts = opts_in; const b = opts.shape.block; const c = opts.shape.candidates; if (b == 0 or b > ln.max_block or c == 0 or c > 1024 or opts.slots == 0 or opts.slots > 16 or opts.siblings > @import("tree.zig").max_siblings) return error.BadOptions; const x = try gpa.create(ln.Lanes); errdefer gpa.destroy(x); + const set = blk: { + var s = opts.depth; + if (!@import("calib_env.zig").plainStreamsSet() and s.plain_streams == 0) s.plain_streams = opts.plain_streams_default; + break :blk s; + }; + opts.depth = set; var policy = try Policy.init(gpa, prices, opts); errdefer policy.deinit(); const drafts = try gpa.alloc(u32, opts.slots * b); diff --git a/zig/src/families/deepseek_v41/draft/lanes.zig b/zig/src/families/deepseek_v41/draft/lanes.zig index dec67d5e17a..df344d2b76f 100644 --- a/zig/src/families/deepseek_v41/draft/lanes.zig +++ b/zig/src/families/deepseek_v41/draft/lanes.zig @@ -24,6 +24,7 @@ pub const Options = struct { dup: tree.Dup = .{}, // sibling pricing: TF_DSV41_TREE_DUP_MS a sibling, its pending row counted slots: u32 = 4, // streams at once spec: spec_mod.Settings = .{}, // the speculative pass (TF_DSV41_SPEC_DRAFT / _SPEC_NUCLEUS) + plain_streams_default: usize = 0, // depth.plain_streams when TF_DSV41_DRAFT_PLAIN_STREAMS is unset }; /// A stream's slot and what the backend holds for it between rounds. diff --git a/zig/src/families/deepseek_v41/draft/plain_streams_test.zig b/zig/src/families/deepseek_v41/draft/plain_streams_test.zig new file mode 100644 index 00000000000..19f6be10864 --- /dev/null +++ b/zig/src/families/deepseek_v41/draft/plain_streams_test.zig @@ -0,0 +1,80 @@ +//! TF_DSV41_DRAFT_PLAIN_STREAMS: the env knob, and a round with enough active windows decodes plain. +const std = @import("std"); +const lanes = @import("lanes"); +const twin = @import("twin.zig"); +const ln = @import("lanes.zig"); +const costs_mod = @import("costs.zig"); +const depth = @import("depth.zig"); +const calib_env = @import("calib_env.zig"); + +const gpa = std.testing.allocator; + +const Env = struct { + var pairs: []const [2][]const u8 = &.{}; + fn get(name: [*:0]const u8) ?[]const u8 { + for (pairs) |kv| if (std.mem.eql(u8, kv[0], std.mem.span(name))) return kv[1]; + return null; + } +}; + +test "TF_DSV41_DRAFT_PLAIN_STREAMS: parsed, 0 when unset, bad values error" { + Env.pairs = &.{}; + try std.testing.expectEqual(@as(usize, 0), (try calib_env.depthSettings(&Env.get)).plain_streams); + Env.pairs = &.{.{ "TF_DSV41_DRAFT_PLAIN_STREAMS", "4" }}; + try std.testing.expectEqual(@as(usize, 4), (try calib_env.depthSettings(&Env.get)).plain_streams); + Env.pairs = &.{.{ "TF_DSV41_DRAFT_PLAIN_STREAMS", "oops" }}; + try std.testing.expectError(error.InvalidCharacter, calib_env.depthSettings(&Env.get)); + Env.pairs = &.{}; +} + +fn runPlain(cases: []const []const u32, setup: Setup) !Run { + const dims: twin.Dims = .{ .bigram = 8.0, .head = 0.08 }; // a confident drafter (lanes_test's): drafts are chosen + const t = try twin.Twin.init(gpa, dims, cases.len + 1); + defer t.deinit(); + const d = try twin.Drafter.init(gpa, t, cases.len + 1); + defer d.deinit(); + var c = try costs_mod.defaults(gpa, 64); + defer c.deinit(gpa); + const x = try ln.Lanes.init(gpa, t.target(), d.pass(), c, .{ .shape = d.shape, .slots = 4, .depth = setup }); + defer x.deinit(); + var arena = std.heap.ArenaAllocator.init(gpa); + defer arena.deinit(); + var cfg = try lanes.Config.init(gpa, try x.model(arena.allocator(), 64), 16, 15); + defer cfg.deinit(gpa); + var clock: lanes.fake.FixedClock = .{}; + var e = lanes.Engine.init(gpa, &cfg, x.backend(), clock.clock()); + defer e.deinit(); + x.attach(&e); + const streams = try gpa.alloc(lanes.Stream, cases.len); + defer gpa.free(streams); + for (cases, streams) |p, *s| s.* = try lanes.Stream.init(gpa, .{ .id = "s", .prompt = p, .max_new = 40 }); + defer for (streams) |*s| s.deinit(gpa); + for (streams) |*s| try e.addStream(s); + while (e.activeCount() > 0) try e.step(); + var ok = true; + for (streams) |*s| ok = ok and s.emitted().len > 0; + return .{ .drafted = e.drafted, .ok = ok }; +} + +const Setup = depth.Settings; + +const Run = struct { drafted: u64, ok: bool }; + +const a1 = [_]u32{ 3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9, 3, 2, 3, 8, 4 }; + +test "a round with plain_streams or more active windows decodes plain; below it drafts; 0 keeps drafts" { + // identical prompts and greedy sampling keep every round a full 4-window round until the streams end together + const four = [_][]const u32{ &a1, &a1, &a1, &a1 }; + // 4 active, threshold 4: every drafted window is forced to count 0 + const plain = try runPlain(&four, .{ .plain_streams = 4 }); + try std.testing.expect(plain.ok); + try std.testing.expectEqual(@as(u64, 0), plain.drafted); + // 3 active, threshold 4: below it, drafts are kept + const below = try runPlain(four[0..3], .{ .plain_streams = 4 }); + try std.testing.expect(below.ok); + try std.testing.expect(below.drafted > 0); + // 4 active, threshold 0 (off): drafts are kept + const off = try runPlain(&four, .{}); + try std.testing.expect(off.ok); + try std.testing.expect(off.drafted > 0); +} diff --git a/zig/src/families/deepseek_v41/draft/policy.zig b/zig/src/families/deepseek_v41/draft/policy.zig index dff9d8efd6d..b403291194d 100644 --- a/zig/src/families/deepseek_v41/draft/policy.zig +++ b/zig/src/families/deepseek_v41/draft/policy.zig @@ -86,6 +86,10 @@ pub const Policy = struct { try asks.append(arena, .{ .slot = st.?.slot, .conf = conf, .most = main, .first = st.?.held[0], .position = st.?.start }); try at.append(arena, i); } + if (p.depth.set.plain_streams > 0 and windows.len >= p.depth.set.plain_streams) { + for (at.items) |i| out[i] = .{ .count = 0 }; + return; + } if (asks.items.len == 0) return; const single = alone and asks.items.len == 1 and other_windows == 0; if (single) { diff --git a/zig/src/families/deepseek_v41/serve_lanes.zig b/zig/src/families/deepseek_v41/serve_lanes.zig index 72e5f4408f0..3a49e2ec576 100644 --- a/zig/src/families/deepseek_v41/serve_lanes.zig +++ b/zig/src/families/deepseek_v41/serve_lanes.zig @@ -121,7 +121,7 @@ pub const Served = struct { } // draft trees (TF_DSV41_TREE / _DUP_MS / _ROWS; off by default): first-position siblings const trees = if (dspark_on) try tree.Settings.fromEnv() else tree.Settings{}; - s.x = try ln.Lanes.init(gpa, tgt, pass, s.costs, .{ .shape = backend.shape, .slots = backend.slots, .siblings = trees.siblings, .sib_rows = trees.sib_rows, .dup = trees.dup, .depth = try calib_env.depthSettings(&calib_env.env), .spec = if (dspark_on) try spec.Settings.fromEnv() else .{} }); + s.x = try ln.Lanes.init(gpa, tgt, pass, s.costs, .{ .shape = backend.shape, .slots = backend.slots, .siblings = trees.siblings, .sib_rows = trees.sib_rows, .dup = trees.dup, .depth = try calib_env.depthSettings(&calib_env.env), .spec = if (dspark_on) try spec.Settings.fromEnv() else .{}, .plain_streams_default = 4 }); s.arena = std.heap.ArenaAllocator.init(gpa); s.cfg = try lanes.Config.init(gpa, try s.x.model(s.arena.allocator(), 64), 16, 15); s.x.policy.depth.forward_rows = backend.forward_rows; From 4416f1468c09f2cd8a17b74522996dee5cb7e32d Mon Sep 17 00:00:00 2001 From: Kevin Gilbertson <880013+gilby@users.noreply.github.com> Date: Wed, 11 Nov 2026 05:19:48 +0100 Subject: [PATCH 03/15] dsv41 metal: decode plain from three active streams, not four --- .../deepseek_v41/draft/plain_streams_test.zig | 16 ++++++++++------ zig/src/families/deepseek_v41/serve_lanes.zig | 2 +- 2 files changed, 11 insertions(+), 7 deletions(-) diff --git a/zig/src/families/deepseek_v41/draft/plain_streams_test.zig b/zig/src/families/deepseek_v41/draft/plain_streams_test.zig index 19f6be10864..44abbbfa8dd 100644 --- a/zig/src/families/deepseek_v41/draft/plain_streams_test.zig +++ b/zig/src/families/deepseek_v41/draft/plain_streams_test.zig @@ -20,8 +20,8 @@ const Env = struct { test "TF_DSV41_DRAFT_PLAIN_STREAMS: parsed, 0 when unset, bad values error" { Env.pairs = &.{}; try std.testing.expectEqual(@as(usize, 0), (try calib_env.depthSettings(&Env.get)).plain_streams); - Env.pairs = &.{.{ "TF_DSV41_DRAFT_PLAIN_STREAMS", "4" }}; - try std.testing.expectEqual(@as(usize, 4), (try calib_env.depthSettings(&Env.get)).plain_streams); + Env.pairs = &.{.{ "TF_DSV41_DRAFT_PLAIN_STREAMS", "3" }}; + try std.testing.expectEqual(@as(usize, 3), (try calib_env.depthSettings(&Env.get)).plain_streams); Env.pairs = &.{.{ "TF_DSV41_DRAFT_PLAIN_STREAMS", "oops" }}; try std.testing.expectError(error.InvalidCharacter, calib_env.depthSettings(&Env.get)); Env.pairs = &.{}; @@ -65,12 +65,16 @@ const a1 = [_]u32{ 3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9, 3, 2, 3, 8, 4 }; test "a round with plain_streams or more active windows decodes plain; below it drafts; 0 keeps drafts" { // identical prompts and greedy sampling keep every round a full 4-window round until the streams end together const four = [_][]const u32{ &a1, &a1, &a1, &a1 }; - // 4 active, threshold 4: every drafted window is forced to count 0 - const plain = try runPlain(&four, .{ .plain_streams = 4 }); + // 4 active, threshold 3: every drafted window is forced to count 0 + const plain = try runPlain(&four, .{ .plain_streams = 3 }); try std.testing.expect(plain.ok); try std.testing.expectEqual(@as(u64, 0), plain.drafted); - // 3 active, threshold 4: below it, drafts are kept - const below = try runPlain(four[0..3], .{ .plain_streams = 4 }); + // 3 active, threshold 3: at it, plain too + const at = try runPlain(four[0..3], .{ .plain_streams = 3 }); + try std.testing.expect(at.ok); + try std.testing.expectEqual(@as(u64, 0), at.drafted); + // 2 active, threshold 3: below it, drafts are kept + const below = try runPlain(four[0..2], .{ .plain_streams = 3 }); try std.testing.expect(below.ok); try std.testing.expect(below.drafted > 0); // 4 active, threshold 0 (off): drafts are kept diff --git a/zig/src/families/deepseek_v41/serve_lanes.zig b/zig/src/families/deepseek_v41/serve_lanes.zig index 3a49e2ec576..2b526fc8eb2 100644 --- a/zig/src/families/deepseek_v41/serve_lanes.zig +++ b/zig/src/families/deepseek_v41/serve_lanes.zig @@ -121,7 +121,7 @@ pub const Served = struct { } // draft trees (TF_DSV41_TREE / _DUP_MS / _ROWS; off by default): first-position siblings const trees = if (dspark_on) try tree.Settings.fromEnv() else tree.Settings{}; - s.x = try ln.Lanes.init(gpa, tgt, pass, s.costs, .{ .shape = backend.shape, .slots = backend.slots, .siblings = trees.siblings, .sib_rows = trees.sib_rows, .dup = trees.dup, .depth = try calib_env.depthSettings(&calib_env.env), .spec = if (dspark_on) try spec.Settings.fromEnv() else .{}, .plain_streams_default = 4 }); + s.x = try ln.Lanes.init(gpa, tgt, pass, s.costs, .{ .shape = backend.shape, .slots = backend.slots, .siblings = trees.siblings, .sib_rows = trees.sib_rows, .dup = trees.dup, .depth = try calib_env.depthSettings(&calib_env.env), .spec = if (dspark_on) try spec.Settings.fromEnv() else .{}, .plain_streams_default = 3 }); s.arena = std.heap.ArenaAllocator.init(gpa); s.cfg = try lanes.Config.init(gpa, try s.x.model(s.arena.allocator(), 64), 16, 15); s.x.policy.depth.forward_rows = backend.forward_rows; From 7349fa2e78bc9f1aa0115e55bbe0c1e70fba727c Mon Sep 17 00:00:00 2001 From: Kevin Gilbertson <880013+gilby@users.noreply.github.com> Date: Wed, 11 Nov 2026 06:47:04 +0100 Subject: [PATCH 04/15] dsv41 metal: plain rounds skip the draft pass, and do not launch one for the next A shared round with the plain switch at it asked no drafts and ran no head pass (core Rule.plain_streams, threaded from the family's resolved setting: 0 on CUDA, so its rounds are unchanged), and the family's speculation no longer launches a pass for a round that wide (armSpec/speculate plainRound). --- zig/src/core/lanes/config.zig | 3 + zig/src/core/lanes/depth.zig | 9 ++- zig/src/core/lanes/engine.zig | 2 +- zig/src/families/deepseek_v41/draft/lanes.zig | 9 ++- .../deepseek_v41/draft/plain_streams_test.zig | 79 ++++++++++++++++--- 5 files changed, 88 insertions(+), 14 deletions(-) diff --git a/zig/src/core/lanes/config.zig b/zig/src/core/lanes/config.zig index a9af579d588..d4f38391290 100644 --- a/zig/src/core/lanes/config.zig +++ b/zig/src/core/lanes/config.zig @@ -45,6 +45,7 @@ pub const Model = struct { granted_depth: bool = false, // with draft_probabilities: every stream drafts its last grant plus a slack draft_slack: u32 = 0, // drafts past a stream's last grant, short or not (0: the Constants' own) draft_streams: bool = false, // the head drafts every stream of a shared round in one batch + plain_streams: u32 = 0, // a shared round with this many streams or more drafts none (0: off) copy_first: bool = false, // a copy ahead takes the round: the head holds no drafts for it (a drafter's own pass) hold_costs: []const @import("hold_price.zig").HoldCost = &.{}, // a drafter's own hold pass, timed at load head_trees: bool = false, // the head drafts trees of lanes (DraftRequest.lanes) and holds them @@ -79,6 +80,7 @@ pub const Config = struct { batch_streams: u32, node_probabilities: bool, granted_depth: bool = false, // Model.granted_depth + plain_streams: u32 = 0, // Model.plain_streams fill_lanes: u32 = 0, // rows a window may grow to with suffix-match branches (0: off; lanes/fill.zig) fill_match: u32 = 8, // context tokens a suffix-match branch must match (shorter ones are coincidental phrases) fill_floor: f64 = 0.35, // the share of grafted rows a stream must keep to go on reading its chain back every round @@ -166,6 +168,7 @@ pub const Config = struct { .batch_streams = if (streams) (if (m.max_streams != 0) m.max_streams else 32) else 1, .node_probabilities = m.draft_probabilities or m.draft_confidence != null, .granted_depth = m.granted_depth and m.draft_probabilities, + .plain_streams = m.plain_streams, .draft_streams = m.draft_streams, .head_trees = m.head_trees, .join_tail = m.join_tail, diff --git a/zig/src/core/lanes/depth.zig b/zig/src/core/lanes/depth.zig index c5bd764e86d..79285b3c260 100644 --- a/zig/src/core/lanes/depth.zig +++ b/zig/src/core/lanes/depth.zig @@ -4,9 +4,7 @@ const Allocator = std.mem.Allocator; const Table = @import("table.zig").Table; const alloc = @import("allocate.zig"); pub const pricedBatched = alloc.pricedBatched; - pub const Constants = @import("depth_constants.zig").Constants; - pub const HoldCost = @import("hold_price.zig").HoldCost; const holdMs = @import("hold_price.zig").holdMs; @@ -59,8 +57,9 @@ pub const Rule = struct { node_probabilities: bool, granted_depth: bool = false, // node_probabilities: a stream drafts its last grant plus draft_slack, lone ones too confidence_floor: ?f64 = null, + plain_streams: u32 = 0, // a shared round with this many streams or more drafts none (0: off; a family's switch) batch_rows: u32, - batched_heads: bool = false, // one batch drafts every stream of a shared round (its steps: the deepest stream's) + batched_heads: bool = false, // one batch drafts every stream of a shared round (steps: the deepest stream's) row_cost: @import("row_cost.zig").RowCost = .{}, // what a row costs past shared_costs here, under k.learn_rows round_ms: Table = .{}, // a round's wall time by drafts, every stream's: what sampled streams price by overhead: std.ArrayList(Overhead) = .empty, // a shared round's ms past its forward, by streams (insertion order) @@ -298,6 +297,10 @@ pub const Rule = struct { /// Head drafts for the streams of a shared round, sized by allocation over their chain chances. pub fn budgets(r: *Rule, whos: []Who, probe: Probe, sampled: bool, out: []i64) !void { + if (r.plain_streams > 0 and whos.len >= r.plain_streams) { // drafts lose here: none asked, no head pass + @memset(out, 0); + return; + } if (r.confidence_floor != null) { for (whos, out) |*w, *o| o.* = try r.headDepth(w, null, probe); return; diff --git a/zig/src/core/lanes/engine.zig b/zig/src/core/lanes/engine.zig index 018ae4a72eb..ced3f315aeb 100644 --- a/zig/src/core/lanes/engine.zig +++ b/zig/src/core/lanes/engine.zig @@ -53,7 +53,6 @@ pub const Engine = struct { grammar_workers: @import("grammar_parallel.zig").State = .{}, arena: std.heap.ArenaAllocator, // a round's temporaries unread: std.ArrayList(Unread) = .empty, // queued draws the log reads at the step's end - pub fn init(gpa: Allocator, cfg: *const Config, backend: be.Backend, clock: be.Clock) Engine { return .{ .gpa = gpa, @@ -74,6 +73,7 @@ pub const Engine = struct { .node_probabilities = cfg.node_probabilities, .granted_depth = cfg.granted_depth, .confidence_floor = cfg.draft_confidence, + .plain_streams = cfg.plain_streams, .batch_rows = cfg.batch_rows, .batched_heads = cfg.draft_streams, }, diff --git a/zig/src/families/deepseek_v41/draft/lanes.zig b/zig/src/families/deepseek_v41/draft/lanes.zig index df344d2b76f..0c63b82bace 100644 --- a/zig/src/families/deepseek_v41/draft/lanes.zig +++ b/zig/src/families/deepseek_v41/draft/lanes.zig @@ -120,7 +120,7 @@ pub const Lanes = struct { for (window, 0..) |*w, i| w.* = .{ .width = @intCast(i + 1), .ms = v[i] }; const shared = try arena.alloc(lanes.config.Cost, @min(v.len, batch_rows)); for (shared, 0..) |*w, i| w.* = .{ .width = @intCast(i + 1), .ms = v[i] }; - return .{ .exact_width = costs_mod.slot_rows, .mtp = true, .speculate = true, .speculate_early = false, .drafts = x.opts.shape.block, .window_costs = window, .mtp_step_ms = 0.0, .hidden_rows = true, .batch_rows = batch_rows, .max_streams = x.opts.slots, .shared_costs = shared, .draft_probabilities = true, .draft_streams = true, .join_tail = x.target.vtable.tail != null and try joinTail(), .piece_runs = try envOn("TF_DSV41_PIECE_RUNS"), .join_drafts = try envOn("TF_DSV41_JOIN_DRAFTS"), .replay_runs = try envOn("TF_DSV41_REPLAY_RUNS") }; + return .{ .exact_width = costs_mod.slot_rows, .mtp = true, .speculate = true, .speculate_early = false, .drafts = x.opts.shape.block, .window_costs = window, .mtp_step_ms = 0.0, .hidden_rows = true, .batch_rows = batch_rows, .max_streams = x.opts.slots, .shared_costs = shared, .draft_probabilities = true, .draft_streams = true, .plain_streams = @intCast(x.opts.depth.plain_streams), .join_tail = x.target.vtable.tail != null and try joinTail(), .piece_runs = try envOn("TF_DSV41_PIECE_RUNS"), .join_drafts = try envOn("TF_DSV41_JOIN_DRAFTS"), .replay_runs = try envOn("TF_DSV41_REPLAY_RUNS") }; } /// TF_DSV41_TAIL_JOIN=1: a prompt in pieces leaves its last token to its first round's shared window (default off). @@ -362,6 +362,7 @@ pub const Lanes = struct { nucleus = nucleus or spec_mod.isNucleus(w.stream.sampling); } if (!sp.roundAllowed(tree_round, nucleus)) return; + if (x.plainRound(windows)) return; // the plain switch: no pass runs for a round this wide for (windows, segs) |w, g| { const st = x.get(w.stream) catch continue; if (!dsparkRound(st, w) or !sp.wouldWant(st.slot)) continue; @@ -372,6 +373,11 @@ pub const Lanes = struct { } } + /// The plain switch fired: every drafted window of the round was cut to the pending row alone. + fn plainRound(x: *Lanes, windows: []const be.Window) bool { + return x.opts.depth.plain_streams > 0 and windows.len >= x.opts.depth.plain_streams; + } + /// A DSpark round: the window verifies the pass's drafts only (a prefix of the held chain counts too). fn dsparkRound(st: *const St, w: be.Window) bool { if (st.n == 0) return false; @@ -394,6 +400,7 @@ pub const Lanes = struct { nucleus = nucleus or spec_mod.isNucleus(w.stream.sampling); } if (!sp.roundAllowed(tree_round, nucleus)) return sp.clear(); + if (x.plainRound(windows)) return sp.clear(); // the plain switch: this round drafted none, the next will not want the drafts const cands = try a.alloc(spec_mod.Candidate, windows.len); var n: usize = 0; for (windows, segs, choices) |w, g, c| { diff --git a/zig/src/families/deepseek_v41/draft/plain_streams_test.zig b/zig/src/families/deepseek_v41/draft/plain_streams_test.zig index 44abbbfa8dd..e5e2f4cfec2 100644 --- a/zig/src/families/deepseek_v41/draft/plain_streams_test.zig +++ b/zig/src/families/deepseek_v41/draft/plain_streams_test.zig @@ -27,7 +27,7 @@ test "TF_DSV41_DRAFT_PLAIN_STREAMS: parsed, 0 when unset, bad values error" { Env.pairs = &.{}; } -fn runPlain(cases: []const []const u32, setup: Setup) !Run { +fn runPlain(cases: []const []const u32, setup: Setup, max_news: []const u32) !Run { const dims: twin.Dims = .{ .bigram = 8.0, .head = 0.08 }; // a confident drafter (lanes_test's): drafts are chosen const t = try twin.Twin.init(gpa, dims, cases.len + 1); defer t.deinit(); @@ -35,7 +35,7 @@ fn runPlain(cases: []const []const u32, setup: Setup) !Run { defer d.deinit(); var c = try costs_mod.defaults(gpa, 64); defer c.deinit(gpa); - const x = try ln.Lanes.init(gpa, t.target(), d.pass(), c, .{ .shape = d.shape, .slots = 4, .depth = setup }); + const x = try ln.Lanes.init(gpa, t.target(), d.pass(), c, .{ .shape = d.shape, .slots = 4, .depth = setup, .spec = .{ .on = true } }); defer x.deinit(); var arena = std.heap.ArenaAllocator.init(gpa); defer arena.deinit(); @@ -47,38 +47,99 @@ fn runPlain(cases: []const []const u32, setup: Setup) !Run { x.attach(&e); const streams = try gpa.alloc(lanes.Stream, cases.len); defer gpa.free(streams); - for (cases, streams) |p, *s| s.* = try lanes.Stream.init(gpa, .{ .id = "s", .prompt = p, .max_new = 40 }); + for (cases, streams, max_news) |p, *s, *n| s.* = try lanes.Stream.init(gpa, .{ .id = "s", .prompt = p, .max_new = n.* }); defer for (streams) |*s| s.deinit(gpa); for (streams) |*s| try e.addStream(s); while (e.activeCount() > 0) try e.step(); var ok = true; for (streams) |*s| ok = ok and s.emitted().len > 0; - return .{ .drafted = e.drafted, .ok = ok }; + return .{ .drafted = e.drafted, .ok = ok, .passes = d.passes, .out = blk: { + const out = try gpa.alloc([]u32, cases.len); + for (out, streams) |*o, *s| o.* = try gpa.dupe(u32, s.emitted()); + break :blk out; + } }; +} + +fn freeRun(r: *Run) void { + for (r.out) |o| gpa.free(o); + gpa.free(r.out); } const Setup = depth.Settings; -const Run = struct { drafted: u64, ok: bool }; +const Run = struct { drafted: u64, ok: bool, passes: u64, out: [][]u32 }; const a1 = [_]u32{ 3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9, 3, 2, 3, 8, 4 }; test "a round with plain_streams or more active windows decodes plain; below it drafts; 0 keeps drafts" { // identical prompts and greedy sampling keep every round a full 4-window round until the streams end together const four = [_][]const u32{ &a1, &a1, &a1, &a1 }; + const fours = [_]u32{ 40, 40, 40, 40 }; // 4 active, threshold 3: every drafted window is forced to count 0 - const plain = try runPlain(&four, .{ .plain_streams = 3 }); + const plain = try runPlain(&four, .{ .plain_streams = 3 }, &fours); + defer freeRun(@constCast(&plain)); try std.testing.expect(plain.ok); try std.testing.expectEqual(@as(u64, 0), plain.drafted); // 3 active, threshold 3: at it, plain too - const at = try runPlain(four[0..3], .{ .plain_streams = 3 }); + const at = try runPlain(four[0..3], .{ .plain_streams = 3 }, fours[0..3]); + defer freeRun(@constCast(&at)); try std.testing.expect(at.ok); try std.testing.expectEqual(@as(u64, 0), at.drafted); // 2 active, threshold 3: below it, drafts are kept - const below = try runPlain(four[0..2], .{ .plain_streams = 3 }); + const below = try runPlain(four[0..2], .{ .plain_streams = 3 }, fours[0..2]); + defer freeRun(@constCast(&below)); try std.testing.expect(below.ok); try std.testing.expect(below.drafted > 0); // 4 active, threshold 0 (off): drafts are kept - const off = try runPlain(&four, .{}); + const off = try runPlain(&four, .{}, &fours); + defer freeRun(@constCast(&off)); try std.testing.expect(off.ok); try std.testing.expect(off.drafted > 0); } + +test "plain rounds skip the draft pass; the replies stay the serial ones; drafting resumes below the threshold" { + const four = [_][]const u32{ &a1, &a1, &a1, &a1 }; + const dims: twin.Dims = .{ .bigram = 8.0, .head = 0.08 }; + const fours = [_]u32{ 40, 40, 40, 40 }; + // off, 4 streams: every round drafts, every round runs the pass + const off = try runPlain(&four, .{}, &fours); + defer freeRun(@constCast(&off)); + try std.testing.expect(off.passes > 0); + // at the threshold: shared rounds run no pass (the engine asks depth 0); the four opening asks stay + const on = try runPlain(&four, .{ .plain_streams = 3 }, &fours); + defer freeRun(@constCast(&on)); + try std.testing.expectEqual(@as(u64, 0), on.drafted); + try std.testing.expectEqual(@as(u64, 4), on.passes); + // tokens identical drafted or plain + for (off.out, on.out) |a, b| try std.testing.expectEqualSlices(u32, a, b); + // serial reference + { + const t = try twin.Twin.init(gpa, dims, 1); + defer t.deinit(); + for (on.out, four) |got, p| { + const want = try t.serial(0, p, 40, null, null); + defer gpa.free(want); + try std.testing.expectEqualSlices(u32, want, got); + } + } + // three streams, the first stops early: its last rounds run with 2 active, drafts resume (a pass again) + const threes = [_]u32{ 6, 40, 40 }; + const tail = [_][]const u32{ &a1, &a1, &a1 }; + const mixed = try runPlain(&tail, .{ .plain_streams = 3 }, &threes); + defer freeRun(@constCast(&mixed)); + try std.testing.expect(mixed.ok); + try std.testing.expect(mixed.drafted > 0); // after a stream finished, 2 active: drafts asked again + try std.testing.expect(mixed.passes > 4); // the three opening asks plus the resumed rounds + // stream 0 stops at 6: its 6 tokens must equal the off run's opening prefix; the others match in full + try std.testing.expectEqualSlices(u32, off.out[0][0..6], mixed.out[0]); + for (off.out[1..3], mixed.out[1..]) |a, b| try std.testing.expectEqualSlices(u32, a, b); + { + const t = try twin.Twin.init(gpa, dims, 1); + defer t.deinit(); + for (mixed.out, tail, &threes) |got, p, *n| { + const want = try t.serial(0, p, n.*, null, null); + defer gpa.free(want); + try std.testing.expectEqualSlices(u32, want, got); + } + } +} From a46c08756b8dd8729b3e2151b165cf2c4e6e532e Mon Sep 17 00:00:00 2001 From: Kevin Gilbertson <880013+gilby@users.noreply.github.com> Date: Wed, 11 Nov 2026 06:47:30 +0100 Subject: [PATCH 05/15] dsv41 metal: the plain switch line says three streams and the skipped pass --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 007e40ecce5..ab3bcb38dbe 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,7 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased -- DeepSeek-V4.1 on Metal: rounds with four or more active streams decode plain instead of drafting, since drafts lose there (#1720, part of #1676). +- DeepSeek-V4.1 on Metal: rounds with three or more active streams decode plain and skip the draft pass, since drafts lose there (#1720, part of #1676). - Flash Next: twenty-nine `TF_FLASHNEXT_*` settings refuse a malformed value by name at startup, before any device work on CUDA, and a Metal load refuses them too; blank `TF_FLASHNEXT_KV_PAGE_TEST` and `TF_FLASHNEXT_KEEP_LATE` read as unset, and a non-finite confidence is refused (#2585, part of #2370). Thanks to @devopsfortunato. - Flash Next on CUDA: twenty-nine `TF_FLASHNEXT_*` settings refuse a malformed value by name at startup, before any From c2e17ac67c07b0c24aaa748aadb7228f02dfc405 Mon Sep 17 00:00:00 2001 From: Kevin Gilbertson <880013+gilby@users.noreply.github.com> Date: Wed, 11 Nov 2026 10:31:19 +0100 Subject: [PATCH 06/15] dsv41 metal: a stream's first draft ask waits for its first round --- zig/src/families/deepseek_v41/draft/lanes.zig | 6 ++- .../deepseek_v41/draft/plain_streams_test.zig | 40 +++++++++++++------ 2 files changed, 32 insertions(+), 14 deletions(-) diff --git a/zig/src/families/deepseek_v41/draft/lanes.zig b/zig/src/families/deepseek_v41/draft/lanes.zig index 0c63b82bace..8ed2270ff9e 100644 --- a/zig/src/families/deepseek_v41/draft/lanes.zig +++ b/zig/src/families/deepseek_v41/draft/lanes.zig @@ -43,6 +43,7 @@ pub const St = struct { n_sib: u32 = 0, shown: std.ArrayList(u32) = .empty, // the drafts this round's window verifies (node indices, window order) shown_set: bool = false, + asked: bool = false, // a draft ask is made (the plain switch: the first ask stays plain) /// Node i of the held tree: the main chain's drafts, then each sibling's rows. pub fn nodes(st: *const St) u32 { @@ -466,7 +467,10 @@ pub const Lanes = struct { st.n = 0; st.n_sib = 0; st.start = at; + const first_ask = !st.asked; + st.asked = true; if (r.depth == 0) continue; + if (first_ask and x.opts.depth.plain_streams > 0) continue; // the plain switch: the stream's first round runs plain, the next ask drafts if (n == x.opts.slots) return error.TooManySlots; asks[n] = .{ .slot = st.slot, .anchor = anchor, .start = at, .params = dspark.Params.of(r.stream.sampling, at) }; whose[n] = st; @@ -526,7 +530,7 @@ pub const Lanes = struct { fn heldTree(ptr: *anyopaque, s: *Stream, gpa: Allocator) anyerror!?lanes.stream.Held { const x = self(ptr); const st = try x.get(s); - if (st.n == 0) return null; + if (st.n == 0) return .{ .count = 0 }; // the ask was skipped (the plain switch's first round): the engine plans a plain window const total = st.nodes(); const tokens = try gpa.alloc(u32, total); errdefer gpa.free(tokens); diff --git a/zig/src/families/deepseek_v41/draft/plain_streams_test.zig b/zig/src/families/deepseek_v41/draft/plain_streams_test.zig index e5e2f4cfec2..47ca916ca92 100644 --- a/zig/src/families/deepseek_v41/draft/plain_streams_test.zig +++ b/zig/src/families/deepseek_v41/draft/plain_streams_test.zig @@ -97,7 +97,7 @@ test "a round with plain_streams or more active windows decodes plain; below it try std.testing.expect(off.drafted > 0); } -test "plain rounds skip the draft pass; the replies stay the serial ones; drafting resumes below the threshold" { +test "a stream's first draft ask waits for its first round; the replies stay the serial ones" { const four = [_][]const u32{ &a1, &a1, &a1, &a1 }; const dims: twin.Dims = .{ .bigram = 8.0, .head = 0.08 }; const fours = [_]u32{ 40, 40, 40, 40 }; @@ -105,11 +105,11 @@ test "plain rounds skip the draft pass; the replies stay the serial ones; drafti const off = try runPlain(&four, .{}, &fours); defer freeRun(@constCast(&off)); try std.testing.expect(off.passes > 0); - // at the threshold: shared rounds run no pass (the engine asks depth 0); the four opening asks stay + // at the threshold: shared rounds run no pass and the opening asks are skipped, so no pass runs at all const on = try runPlain(&four, .{ .plain_streams = 3 }, &fours); defer freeRun(@constCast(&on)); try std.testing.expectEqual(@as(u64, 0), on.drafted); - try std.testing.expectEqual(@as(u64, 4), on.passes); + try std.testing.expectEqual(@as(u64, 0), on.passes); // tokens identical drafted or plain for (off.out, on.out) |a, b| try std.testing.expectEqualSlices(u32, a, b); // serial reference @@ -122,21 +122,35 @@ test "plain rounds skip the draft pass; the replies stay the serial ones; drafti try std.testing.expectEqualSlices(u32, want, got); } } - // three streams, the first stops early: its last rounds run with 2 active, drafts resume (a pass again) - const threes = [_]u32{ 6, 40, 40 }; - const tail = [_][]const u32{ &a1, &a1, &a1 }; - const mixed = try runPlain(&tail, .{ .plain_streams = 3 }, &threes); +} + +test "below the threshold a stream drafts on its first ask; drafting resumes once streams finish" { + const four = [_][]const u32{ &a1, &a1, &a1, &a1 }; + const dims: twin.Dims = .{ .bigram = 8.0, .head = 0.08 }; + const fours = [_]u32{ 40, 40, 40, 40 }; + // the threshold not reached (1-2 active): the first ask drafts as usual + const one = try runPlain(four[0..1], .{ .plain_streams = 3 }, fours[0..1]); + defer freeRun(@constCast(&one)); + try std.testing.expect(one.ok); + try std.testing.expect(one.drafted > 0); + try std.testing.expect(one.passes > 0); + const two = try runPlain(four[0..2], .{ .plain_streams = 3 }, fours[0..2]); + defer freeRun(@constCast(&two)); + try std.testing.expect(two.ok); + try std.testing.expect(two.drafted > 0); + try std.testing.expect(two.passes > 0); + // 4 streams, two finish early: the first asks are skipped, drafting resumes at 2 active + const twos = [_]u32{ 6, 6, 40, 40 }; + const mixed = try runPlain(&four, .{ .plain_streams = 3 }, &twos); defer freeRun(@constCast(&mixed)); try std.testing.expect(mixed.ok); - try std.testing.expect(mixed.drafted > 0); // after a stream finished, 2 active: drafts asked again - try std.testing.expect(mixed.passes > 4); // the three opening asks plus the resumed rounds - // stream 0 stops at 6: its 6 tokens must equal the off run's opening prefix; the others match in full - try std.testing.expectEqualSlices(u32, off.out[0][0..6], mixed.out[0]); - for (off.out[1..3], mixed.out[1..]) |a, b| try std.testing.expectEqualSlices(u32, a, b); + try std.testing.expect(mixed.drafted > 0); // after two streams finished, 2 active: drafts asked again + try std.testing.expect(mixed.passes > 0); // every pass is from the resumed rounds + // serial reference, each stream's own length { const t = try twin.Twin.init(gpa, dims, 1); defer t.deinit(); - for (mixed.out, tail, &threes) |got, p, *n| { + for (mixed.out, four, &twos) |got, p, *n| { const want = try t.serial(0, p, n.*, null, null); defer gpa.free(want); try std.testing.expectEqualSlices(u32, want, got); From 2538a002fe42b598cb266f8378641a7618e3d638 Mon Sep 17 00:00:00 2001 From: Kevin Gilbertson <880013+gilby@users.noreply.github.com> Date: Wed, 11 Nov 2026 19:32:12 +0100 Subject: [PATCH 07/15] dsv41 metal: a stream drafts nothing until its burst has formed --- zig/src/families/deepseek_v41/draft/lanes.zig | 18 +++-- .../deepseek_v41/draft/plain_streams_test.zig | 67 ++++++++++++++++++- 2 files changed, 77 insertions(+), 8 deletions(-) diff --git a/zig/src/families/deepseek_v41/draft/lanes.zig b/zig/src/families/deepseek_v41/draft/lanes.zig index 8ed2270ff9e..831f937e71b 100644 --- a/zig/src/families/deepseek_v41/draft/lanes.zig +++ b/zig/src/families/deepseek_v41/draft/lanes.zig @@ -43,7 +43,8 @@ pub const St = struct { n_sib: u32 = 0, shown: std.ArrayList(u32) = .empty, // the drafts this round's window verifies (node indices, window order) shown_set: bool = false, - asked: bool = false, // a draft ask is made (the plain switch: the first ask stays plain) + burst_seen: bool = false, // the plain switch: an ask batch reached plain_streams, the normal rules apply from then on + wide_asks: u8 = 0, // the plain switch: asks made while never wide, a lone stream drafts from its second /// Node i of the held tree: the main chain's drafts, then each sibling's rows. pub fn nodes(st: *const St) u32 { @@ -74,7 +75,6 @@ pub const Lanes = struct { by_slot: []?*St, retired: [16]bool = @splat(false), release_requested: [16]bool = @splat(false), - pub const init = @import("lane_owner.zig").init; pub const deinit = @import("lane_owner.zig").deinit; @@ -435,11 +435,16 @@ pub const Lanes = struct { } } + /// The hold before a stream's first draft (the plain switch): until its burst has formed or its second ask. + const lone_asks_before_draft = 2; // a stream admitted alone drafts from its second ask + fn draft(ptr: *anyopaque, requests: []const be.DraftRequest) anyerror!void { const x = self(ptr); try x.settle(); _ = x.scratch.reset(.retain_capacity); const a = x.scratch.allocator(); + const switch_on = x.opts.depth.plain_streams > 0; + const burst = switch_on and requests.len >= x.opts.depth.plain_streams; // the round's burst: the normal rules apply const asks = try a.alloc(iface.Ask, requests.len); const whose = try a.alloc(*St, requests.len); const depths = try a.alloc(u32, requests.len); @@ -453,7 +458,7 @@ pub const Lanes = struct { if (r.rows) |path| { if (r.start != st.base) return error.PositionMismatch; const done = if (x.spec) |*sp| sp.ingested(st.slot, r.start, path) else false; - if (!done) try x.ingest(st, r.start, path); // a shared round drafts before its keep: the path, not st.len + if (!done) try x.ingest(st, r.start, path); // the drafter's ring holds every committed row, drafted or not // a shared round drafts before its keep: the path, not st.len at = r.start + path.len; } if (r.position != at + 1) return error.PositionMismatch; @@ -467,10 +472,11 @@ pub const Lanes = struct { st.n = 0; st.n_sib = 0; st.start = at; - const first_ask = !st.asked; - st.asked = true; if (r.depth == 0) continue; - if (first_ask and x.opts.depth.plain_streams > 0) continue; // the plain switch: the stream's first round runs plain, the next ask drafts + if (switch_on) { + if (burst) st.burst_seen = true else st.wide_asks += 1; + if (!st.burst_seen and st.wide_asks < lone_asks_before_draft) continue; // the plain switch: the hold until its burst has formed or its second ask + } if (n == x.opts.slots) return error.TooManySlots; asks[n] = .{ .slot = st.slot, .anchor = anchor, .start = at, .params = dspark.Params.of(r.stream.sampling, at) }; whose[n] = st; diff --git a/zig/src/families/deepseek_v41/draft/plain_streams_test.zig b/zig/src/families/deepseek_v41/draft/plain_streams_test.zig index 47ca916ca92..3d0fa7239e7 100644 --- a/zig/src/families/deepseek_v41/draft/plain_streams_test.zig +++ b/zig/src/families/deepseek_v41/draft/plain_streams_test.zig @@ -124,11 +124,74 @@ test "a stream's first draft ask waits for its first round; the replies stay the } } +test "a stream drafts no round until its burst has formed or its second ask while never wide" { + // staggered arrival, plain_streams 3: the burst forms at the third stream, from which every stream drafts + const dims: twin.Dims = .{ .bigram = 8.0, .head = 0.08 }; + { + const t = try twin.Twin.init(gpa, dims, 5); + defer t.deinit(); + const d = try twin.Drafter.init(gpa, t, 5); + defer d.deinit(); + var c = try costs_mod.defaults(gpa, 64); + defer c.deinit(gpa); + const x = try ln.Lanes.init(gpa, t.target(), d.pass(), c, .{ .shape = d.shape, .slots = 4, .depth = .{ .plain_streams = 3 }, .spec = .{ .on = true } }); + defer x.deinit(); + var arena = std.heap.ArenaAllocator.init(gpa); + defer arena.deinit(); + var cfg = try lanes.Config.init(gpa, try x.model(arena.allocator(), 64), 16, 15); + defer cfg.deinit(gpa); + var clock: lanes.fake.FixedClock = .{}; + var e = lanes.Engine.init(gpa, &cfg, x.backend(), clock.clock()); + defer e.deinit(); + x.attach(&e); + const streams = try gpa.alloc(lanes.Stream, 4); + defer gpa.free(streams); + var i: usize = 0; + var steps: u64 = 0; + while (e.activeCount() > 0 or i < 4) { + try e.step(); + steps += 1; + if (i < 4) { + const s = &streams[i]; + s.* = try lanes.Stream.init(gpa, .{ .id = "s", .prompt = &a1, .max_new = 40 }); + try e.addStream(s); + i += 1; + } + if (steps > 400) return error.TooManySteps; + } + defer for (streams) |*s| s.deinit(gpa); + var ok = true; + for (streams) |*s| ok = ok and s.emitted().len > 0; + try std.testing.expect(ok); + try std.testing.expect(d.passes > 0); // the burst formed at three streams: the later rounds draft + try std.testing.expect(e.drafted > 0); + // tokens equal to the serial reference + for (streams) |*s| { + const want = try t.serial(0, &a1, 40, null, null); + defer gpa.free(want); + try std.testing.expectEqualSlices(u32, want, s.emitted()); + } + } + // the truly-lone control: one stream admitted alone drafts from its second ask + const lone = try runPlain(&.{&a1}, .{ .plain_streams = 3 }, &.{40}); + defer freeRun(@constCast(&lone)); + try std.testing.expect(lone.ok); + try std.testing.expect(lone.drafted > 0); + try std.testing.expect(lone.passes > 0); + { + const t = try twin.Twin.init(gpa, dims, 1); + defer t.deinit(); + const want = try t.serial(0, &a1, 40, null, null); + defer gpa.free(want); + try std.testing.expectEqualSlices(u32, want, lone.out[0]); + } +} + test "below the threshold a stream drafts on its first ask; drafting resumes once streams finish" { const four = [_][]const u32{ &a1, &a1, &a1, &a1 }; const dims: twin.Dims = .{ .bigram = 8.0, .head = 0.08 }; const fours = [_]u32{ 40, 40, 40, 40 }; - // the threshold not reached (1-2 active): the first ask drafts as usual + // the threshold not reached (1-2 active): the first ask is held, the second drafts const one = try runPlain(four[0..1], .{ .plain_streams = 3 }, fours[0..1]); defer freeRun(@constCast(&one)); try std.testing.expect(one.ok); @@ -139,7 +202,7 @@ test "below the threshold a stream drafts on its first ask; drafting resumes onc try std.testing.expect(two.ok); try std.testing.expect(two.drafted > 0); try std.testing.expect(two.passes > 0); - // 4 streams, two finish early: the first asks are skipped, drafting resumes at 2 active + // 4 streams, two finish early: admitted four-deep, the burst has formed from round one, so every ask drafts const twos = [_]u32{ 6, 6, 40, 40 }; const mixed = try runPlain(&four, .{ .plain_streams = 3 }, &twos); defer freeRun(@constCast(&mixed)); From 9d21b5053a58223689b0e2b81d19d617eaa5e66d Mon Sep 17 00:00:00 2001 From: Kevin Gilbertson <880013+gilby@users.noreply.github.com> Date: Wed, 11 Nov 2026 21:36:26 +0100 Subject: [PATCH 08/15] dsv41 metal: restore the engram manifest check, the serve-lane test steps and the forward try's --- zig/build/dsv41_metal.zig | 21 +++++++++++++++---- zig/src/families/deepseek_v41/metal/boot.zig | 15 +++++++++++++ .../families/deepseek_v41/metal/forward.zig | 4 ++-- zig/tests/dsv41_metal/timing_real.zig | 2 +- 4 files changed, 35 insertions(+), 7 deletions(-) diff --git a/zig/build/dsv41_metal.zig b/zig/build/dsv41_metal.zig index 3eb2207ab1a..1de16b75335 100644 --- a/zig/build/dsv41_metal.zig +++ b/zig/build/dsv41_metal.zig @@ -40,9 +40,18 @@ pub fn steps(b: *std.Build, metal: *std.Build.Module, sources: *std.Build.Module .link_libc = true, .imports = &.{ .{ .name = "dsv41_metal", .module = p.pkg }, .{ .name = "metal", .module = metal }, .{ .name = "dsv41", .module = p.host } }, }); + // the package's own checks run with the default test step; its device suites run from their named steps + test_step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = p.pkg })).step); const step = b.step("test-dsv41-metal", "DeepSeek-V4.1 Metal layer and forward: float64 stages, rows at once == one at a time"); - const pkg_run = &b.addRunArtifact(b.addTest(.{ .root_module = p.pkg })).step; - step.dependOn(pkg_run); + // serve_lanes over the CPU twin, checked here so no CUDA step has to depend on the neutral served engine + const lanes_test = b.createModule(.{ + .root_source_file = b.path("zig/src/families/deepseek_v41/serve_lanes_test.zig"), + .target = b.graph.host, + .optimize = .Debug, + .link_libc = true, + .imports = &.{ .{ .name = "core", .module = p.host.import_table.get("core").? }, .{ .name = "engine_api", .module = p.host.import_table.get("engine_api").? }, .{ .name = "lanes", .module = p.host.import_table.get("lanes").? }, .{ .name = "tokenizer", .module = p.host.import_table.get("tokenizer").? } }, + }); + test_step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = lanes_test })).step); const run = b.addRunArtifact(b.addTest(.{ .root_module = tests })); run.has_side_effects = true; // a device run: never cached step.dependOn(&run.step); @@ -58,8 +67,12 @@ pub fn steps(b: *std.Build, metal: *std.Build.Module, sources: *std.Build.Module const serve_run = b.addRunArtifact(b.addTest(.{ .root_module = serve })); serve_run.has_side_effects = true; step.dependOn(&serve_run.step); - b.step("test-dsv41-metal-serve", "DeepSeek-V4.1 Metal served through LaneHost: concurrent, drafted, cached, seeded, cancelled").dependOn(&serve_run.step); - test_step.dependOn(pkg_run); // the package's host checks only; the device run stays in its own step + const serve_step = b.step("test-dsv41-metal-serve", "DeepSeek-V4.1 Metal served through LaneHost: concurrent, drafted, cached, seeded, cancelled"); + serve_step.dependOn(&serve_run.step); + // the release-checkpoint steps (TF_DSV41_REAL) stay opt-in, so the umbrella holds the default device suites + const all = b.step("test-dsv41-metal-all", "DeepSeek-V4.1 Metal: every device test step on this GPU (layer, served)"); + all.dependOn(step); + all.dependOn(serve_step); const fast = package(b, metal, sources, .ReleaseSafe); const real = b.createModule(.{ .root_source_file = b.path("zig/tests/dsv41_metal/real_test.zig"), diff --git a/zig/src/families/deepseek_v41/metal/boot.zig b/zig/src/families/deepseek_v41/metal/boot.zig index 157552c6d26..88e3d53e2b7 100644 --- a/zig/src/families/deepseek_v41/metal/boot.zig +++ b/zig/src/families/deepseek_v41/metal/boot.zig @@ -106,6 +106,21 @@ pub const Boot = struct { b.eng = try eh.Host.load(b.map_bytes, c.engram_heads, c.engram_pad, c.engram_vocab, &b.lbuf); const rows_dir = try b.rowsDir(dir, o); defer b.a.free(rows_dir); + // a boot that serves Engram layers proves the tables match the release: the manifest, headers, sampled rows + const full = std.mem.eql(u8, std.mem.span(std.c.getenv("TF_DSV41_ENGRAM_VERIFY") orelse ""), "full"); + const em = host.engram_manifest; + const ck = em.check(b.a, io, dir, rows_dir, full) catch |e| { + switch (e) { + error.EngramManifestMissing => std.log.err("dsv41 metal: no {s} beside the Engram tables {s}: run tf-dsv41-engram-pack pack", .{ em.filename, rows_dir }), + error.EngramManifestBad => std.log.err("dsv41 metal: the Engram manifest {s}/{s} is missing or unreadable", .{ rows_dir, em.filename }), + error.EngramSourceMismatch => std.log.err("dsv41 metal: the release no longer matches the Engram tables in {s}: the shards moved or changed", .{rows_dir}), + error.EngramShardCorrupt => std.log.err("dsv41 metal: an Engram table in {s} is corrupt or does not match its manifest", .{rows_dir}), + error.EngramSampleMismatch => std.log.err("dsv41 metal: an Engram table in {s} differs from the release shards on a sampled row", .{rows_dir}), + else => std.log.err("dsv41 metal: the Engram tables in {s} cannot be verified ({s})", .{ rows_dir, @errorName(e) }), + } + return e; + }; + std.log.info("dsv41 metal: Engram tables checked against the release ({d} sampled rows{s})", .{ ck.samples, if (full) " and every byte" else "" }); const cap: u32 = if (std.c.getenv("TF_DSV41_ENGRAM_CACHE")) |v| try std.fmt.parseInt(u32, std.mem.span(v), 10) else 65536; b.rows = try er.Rows.open(b.a, rows_dir, 0, 1, b.eng.layer_ids, cap); std.log.info("dsv41 metal: Engram rows from {s} ({d} records a layer cached)", .{ rows_dir, cap }); diff --git a/zig/src/families/deepseek_v41/metal/forward.zig b/zig/src/families/deepseek_v41/metal/forward.zig index c6022aa34cb..622ec616b42 100644 --- a/zig/src/families/deepseek_v41/metal/forward.zig +++ b/zig/src/families/deepseek_v41/metal/forward.zig @@ -245,11 +245,11 @@ const max_buffers = 16; /// Layers lo .. hi of the forward, the embedding before layer 0 and the head after the last. fn encodeRange(x: *const Ctx, e: mtl.ComputeEncoder, m: Model, b: *const Bufs, lo: usize, hi: usize) !void { if (lo == 0) { - encodeEmbed(x, e, m, b); + try encodeEmbed(x, e, m, b); e.barrier(); } for (lo..hi) |i| try encodeLayer(x, e, m, b, i); - if (hi == m.layers.len) encodeHead(x, e, m, b); + if (hi == m.layers.len) try encodeHead(x, e, m, b); } test "a round's command buffers: one layer, then four even parts of the rest" { diff --git a/zig/tests/dsv41_metal/timing_real.zig b/zig/tests/dsv41_metal/timing_real.zig index 2243c25f6f7..5e41dbd0e09 100644 --- a/zig/tests/dsv41_metal/timing_real.zig +++ b/zig/tests/dsv41_metal/timing_real.zig @@ -340,7 +340,7 @@ fn rest(a: std.mem.Allocator, r: *fixture.Rig, junk: mtl.Buffer, n: usize) !void const Args = struct { r: *fixture.Rig, rows: u32, head: mtl.Buffer, logits: mtl.Buffer, ew: mtl.Buffer, es: mtl.Buffer, ex: mtl.Buffer, ekv: mtl.Buffer, k: u32, n: u32 }; const F = struct { fn headMv(x: Args, e: mtl.ComputeEncoder) !void { - pkg.pipelines.glue.mv(&x.r.p.glue, e, x.r.s.hn, .{ .buf = x.head }, .{ .buf = x.logits }, x.rows, x.r.c.hidden, x.r.c.vocab, true); + try pkg.pipelines.glue.mv(&x.r.p.glue, e, x.r.s.hn, .{ .buf = x.head }, .{ .buf = x.logits }, x.rows, x.r.c.hidden, x.r.c.vocab, true); } fn wkv(x: Args, e: mtl.ComputeEncoder) !void { const fp8 = pkg.pipelines.fp8; From 6cfe92a5a77cf30f575e74549958faec487a6bd0 Mon Sep 17 00:00:00 2001 From: Kevin Gilbertson <880013+gilby@users.noreply.github.com> Date: Wed, 11 Nov 2026 22:16:45 +0100 Subject: [PATCH 09/15] lanes: the plain-streams check in depth.zig on one line, so the file stays within 600 lines --- zig/src/core/lanes/depth.zig | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/zig/src/core/lanes/depth.zig b/zig/src/core/lanes/depth.zig index 79285b3c260..b6a371940c6 100644 --- a/zig/src/core/lanes/depth.zig +++ b/zig/src/core/lanes/depth.zig @@ -297,10 +297,8 @@ pub const Rule = struct { /// Head drafts for the streams of a shared round, sized by allocation over their chain chances. pub fn budgets(r: *Rule, whos: []Who, probe: Probe, sampled: bool, out: []i64) !void { - if (r.plain_streams > 0 and whos.len >= r.plain_streams) { // drafts lose here: none asked, no head pass - @memset(out, 0); - return; - } + // drafts lose here: none asked, no head pass + if (r.plain_streams > 0 and whos.len >= r.plain_streams) return @memset(out, 0); if (r.confidence_floor != null) { for (whos, out) |*w, *o| o.* = try r.headDepth(w, null, probe); return; From 46086298b1abe2dd635225cc2c3f515bb17347c6 Mon Sep 17 00:00:00 2001 From: Kevin Gilbertson <880013+gilby@users.noreply.github.com> Date: Wed, 11 Nov 2026 22:16:45 +0100 Subject: [PATCH 10/15] dsv41 metal: boot and entry read their settings through platform/environment.zig --- docs/environment.md | 5 +++++ zig/src/families/deepseek_v41/metal/boot.zig | 9 +++++---- zig/src/families/deepseek_v41/metal/entry.zig | 5 +++-- zig/src/platform/environment.zig | 5 +++++ zig/src/platform/environment_test.zig | 5 +++++ 5 files changed, 23 insertions(+), 6 deletions(-) diff --git a/docs/environment.md b/docs/environment.md index adb7c601377..84740d23b0e 100644 --- a/docs/environment.md +++ b/docs/environment.md @@ -46,6 +46,11 @@ Diagnostics quote and escape the supplied text so it cannot create another termi | `TF_FLASHNEXT_SCALE_INDEX` | Flash Next on Metal before tensor units: exactly `0` or `1`; `1` has the 4-bit expert kernels read each group's scale and bias through a 16-bit index into its tensor's table of pairs, the same values with fewer weight bytes; default 0 | | `TF_FLASHNEXT_GROUPED_ROWS` | Flash Next on Metal without tensor units: `0`, or the rows (`1` through `32`) from which a decode window runs its 4-bit experts grouped by expert, with the same output bits; default 5; ignored with `--ssd-experts` and in speed-up mode | | `GLM_EHPROJ_NAX` | GLM-5.3-Flash on Metal: exactly `0` or `1`; `0` serves the MTP head's prompt eh_proj on the scalar kernel; default 1, the tile kernel where it builds | +| `TF_DSV41_SMALL` | DeepSeek-V4.1 on Metal: exactly `0` or `1`; `1` reads the checkpoint's config at its own small shapes (the served smoke test's tiny model); default 0 | +| `TF_DSV41_ASSETS` | DeepSeek-V4.1 on Metal: a directory path without control characters that holds the Engram token map; unset or blank reads it beside the checkpoint | +| `TF_DSV41_ENGRAM_DIR` | DeepSeek-V4.1 on Metal: a directory path without control characters that holds the packed Engram tables; unset or blank takes the checkpoint's `engram_table_dir` | +| `TF_DSV41_ENGRAM_VERIFY` | DeepSeek-V4.1 on Metal: exactly `sample` or `full`; `full` also checks every byte of the Engram tables against their manifest at boot; default `sample` | +| `TF_DSV41_ENGRAM_CACHE` | DeepSeek-V4.1 on Metal: whole u32 count of Engram records a layer kept cached; default 65536 | | `XPU_A8_BITS` | Exactly `4` or `8`, for the XPU quantization study; unset keeps the study's existing setting | | `LFM3_FUSE` | Whole u32 fusion mask; default 7 | | `TF_SLIDE_POCKET_KEY` | Exactly `auto`, `reply`, `subject` or `both`; default `auto` | diff --git a/zig/src/families/deepseek_v41/metal/boot.zig b/zig/src/families/deepseek_v41/metal/boot.zig index 88e3d53e2b7..4c21cdf5c34 100644 --- a/zig/src/families/deepseek_v41/metal/boot.zig +++ b/zig/src/families/deepseek_v41/metal/boot.zig @@ -14,6 +14,7 @@ const target_ = @import("target.zig"); const Config = host.config.Config; const eh = host.engram_host; const er = host.engram_rows; +const environment = @import("sys").environment; const Allocator = std.mem.Allocator; /// The files a boot reads beside the shards: the Engram token map (here or under TF_DSV41_ASSETS). @@ -95,7 +96,7 @@ pub const Boot = struct { fn engram(b: *Boot, io: std.Io, dir: []const u8, o: Options) !?forward.Lookup { const c = &b.c; if (c.engram_layers.len == 0) return null; - const assets = if (std.c.getenv("TF_DSV41_ASSETS")) |v| std.mem.span(v) else dir; + const assets = try environment.path("TF_DSV41_ASSETS", environment.Process.get(.{}, "TF_DSV41_ASSETS")) orelse dir; const path = try std.fs.path.join(b.a, &.{ assets, token_map }); defer b.a.free(path); b.map_bytes = std.Io.Dir.cwd().readFileAllocOptions(io, path, b.a, .limited(1 << 26), .@"4", null) catch |e| { @@ -107,7 +108,7 @@ pub const Boot = struct { const rows_dir = try b.rowsDir(dir, o); defer b.a.free(rows_dir); // a boot that serves Engram layers proves the tables match the release: the manifest, headers, sampled rows - const full = std.mem.eql(u8, std.mem.span(std.c.getenv("TF_DSV41_ENGRAM_VERIFY") orelse ""), "full"); + const full = try environment.read(u32, "TF_DSV41_ENGRAM_VERIFY", 0) == 1; const em = host.engram_manifest; const ck = em.check(b.a, io, dir, rows_dir, full) catch |e| { switch (e) { @@ -121,7 +122,7 @@ pub const Boot = struct { return e; }; std.log.info("dsv41 metal: Engram tables checked against the release ({d} sampled rows{s})", .{ ck.samples, if (full) " and every byte" else "" }); - const cap: u32 = if (std.c.getenv("TF_DSV41_ENGRAM_CACHE")) |v| try std.fmt.parseInt(u32, std.mem.span(v), 10) else 65536; + const cap = try environment.read(u32, "TF_DSV41_ENGRAM_CACHE", 65536); b.rows = try er.Rows.open(b.a, rows_dir, 0, 1, b.eng.layer_ids, cap); std.log.info("dsv41 metal: Engram rows from {s} ({d} records a layer cached)", .{ rows_dir, cap }); return .{ .a = b.a, .host = &b.eng, .source = b.rows.?.source() }; @@ -130,7 +131,7 @@ pub const Boot = struct { /// The row shards' folder: the option, TF_DSV41_ENGRAM_DIR, else engram_table_dir (relative to the checkpoint). fn rowsDir(b: *Boot, dir: []const u8, o: Options) ![]u8 { if (o.engram_dir) |d| return b.a.dupe(u8, d); - if (std.c.getenv("TF_DSV41_ENGRAM_DIR")) |v| return b.a.dupe(u8, std.mem.span(v)); + if (try environment.path("TF_DSV41_ENGRAM_DIR", environment.Process.get(.{}, "TF_DSV41_ENGRAM_DIR"))) |v| return b.a.dupe(u8, v); const t = b.c.engram_table_dir.items(); if (t.len == 0) return error.EngramRowsUnset; if (std.fs.path.isAbsolute(t)) return b.a.dupe(u8, t); diff --git a/zig/src/families/deepseek_v41/metal/entry.zig b/zig/src/families/deepseek_v41/metal/entry.zig index 7eb864254b5..9efb4f120e8 100644 --- a/zig/src/families/deepseek_v41/metal/entry.zig +++ b/zig/src/families/deepseek_v41/metal/entry.zig @@ -5,6 +5,7 @@ const pkg = @import("dsv41_metal"); const host = @import("dsv41"); const serve_lanes = host.serve_lanes; +const env = @import("sys").environment; const Allocator = std.mem.Allocator; pub const backends: []const []const u8 = &.{"metal"}; @@ -16,7 +17,7 @@ pub fn chip(_: Allocator) ?[]const u8 { /// The engine for `o.dir`, or null with `problem` set (the native_engines contract). pub fn open(a: Allocator, gpa: Allocator, io: std.Io, o: api.Open, problem: *[]const u8) !?api.Opened { - if (@import("sys").experimental.refusal(o.model_type, @import("sys").getenv("TF_EXPERIMENTAL")) != null) { + if (@import("sys").experimental.refusal(o.model_type, env.Process.get(.{}, "TF_EXPERIMENTAL")) != null) { problem.* = "DeepSeek-V4.1 on Metal is experimental: its served lanes have no whole-model gate yet; set TF_EXPERIMENTAL=deepseek to opt in"; return null; } @@ -29,7 +30,7 @@ pub fn open(a: Allocator, gpa: Allocator, io: std.Io, o: api.Open, problem: *[]c .context = if (o.context) |c| @intCast(@max(c, 1)) else null, .drafts = o.drafts, .cache_bytes = if (o.prompt_cache_gib) |g| @intFromFloat(@max(g, 0) * (1 << 30)) else 4 << 30, - .small = if (std.c.getenv("TF_DSV41_SMALL")) |v| std.mem.eql(u8, std.mem.span(v), "1") else false, + .small = try env.read(bool, "TF_DSV41_SMALL", false), }; const m = pkg.boot.Boot.open(gpa, io, o.dir, opts) catch |e| { problem.* = try std.fmt.allocPrint(a, "the DeepSeek-V4.1 Metal engine cannot load {s} ({s})", .{ o.dir, @errorName(e) }); diff --git a/zig/src/platform/environment.zig b/zig/src/platform/environment.zig index 3ec84e66831..ebba43840e9 100644 --- a/zig/src/platform/environment.zig +++ b/zig/src/platform/environment.zig @@ -60,6 +60,11 @@ pub const rules = [_]Rule{ .{ .name = "TF_FLASHNEXT_SCALE_INDEX", .scope = .metal, .kind = .flag, .forms = "0 or 1 (1: Flash Next's 4-bit expert kernels read scales and biases through a 16-bit index)" }, .{ .name = "GLM_EHPROJ_NAX", .scope = .metal, .kind = .flag, .forms = "0 or 1 (0 serves GLM's MTP eh_proj on the scalar kernel)" }, .{ .name = "TF_FLASHNEXT_GROUPED_ROWS", .scope = .metal, .kind = .size, .forms = "0 (never) or the rows, 1 to 32, from which a window's experts run grouped", .max = 32 }, + .{ .name = "TF_DSV41_SMALL", .scope = .metal, .kind = .flag, .forms = "0 or 1 (1 reads a DeepSeek-V4.1 Metal checkpoint's config at its own small shapes)" }, + .{ .name = "TF_DSV41_ASSETS", .scope = .metal, .kind = .path, .forms = "a directory path without control characters holding DeepSeek-V4.1's Engram token map" }, + .{ .name = "TF_DSV41_ENGRAM_DIR", .scope = .metal, .kind = .path, .forms = "a directory path without control characters holding DeepSeek-V4.1's packed Engram tables" }, + .{ .name = "TF_DSV41_ENGRAM_VERIFY", .scope = .metal, .kind = .word, .words = &.{ "sample", "full" }, .forms = "sample or full (full also checks every byte of the Engram tables at boot)" }, + .{ .name = "TF_DSV41_ENGRAM_CACHE", .scope = .metal, .kind = .u32, .forms = "a whole Engram record count a layer from 0 to 4294967295 (default 65536)" }, .{ .name = "XPU_A8_BITS", .scope = .xpu, .kind = .bit_width, .forms = "4 or 8" }, .{ .name = "LFM3_FUSE", .scope = .xpu, .kind = .u32, .forms = "a whole fusion mask from 0 to 4294967295" }, .{ .name = "TF_SLIDE_POCKET_KEY", .scope = .slide, .kind = .word, .words = &.{ "auto", "reply", "subject", "both" }, .forms = "auto, reply, subject or both" }, diff --git a/zig/src/platform/environment_test.zig b/zig/src/platform/environment_test.zig index 3486fd05654..3d0ab62f724 100644 --- a/zig/src/platform/environment_test.zig +++ b/zig/src/platform/environment_test.zig @@ -99,6 +99,11 @@ const valid = [_]Case{ .{ .name = "TF_SLIDE_FIT_GIB", .raw = "4", .n = 4 }, .{ .name = "TF_SLIDE_POCKET_DUMP", .raw = "/tmp/pocket rows", .n = 0 }, .{ .name = "TF_SLIDE_FORGET_FAIL", .raw = " 0 ", .n = 0 }, + .{ .name = "TF_DSV41_SMALL", .raw = "1", .n = 1 }, + .{ .name = "TF_DSV41_ASSETS", .raw = "deepseek assets", .n = 0 }, + .{ .name = "TF_DSV41_ENGRAM_DIR", .raw = "engram-rows", .n = 0 }, + .{ .name = "TF_DSV41_ENGRAM_VERIFY", .raw = "full", .n = 1 }, + .{ .name = "TF_DSV41_ENGRAM_CACHE", .raw = "0", .n = 0 }, }; test "environment: valid forms remain raw numbers before existing consumer clamps and defaults" { From 957882ff6134525ae2e2e7e47dea87ad9a062e14 Mon Sep 17 00:00:00 2001 From: Kevin Gilbertson <880013+gilby@users.noreply.github.com> Date: Wed, 11 Nov 2026 22:43:49 +0100 Subject: [PATCH 11/15] dsv41 metal: TF_DSV41_DRAFT_PLAIN_STREAMS takes 0 to 16 and refuses anything else by name --- zig/src/families/deepseek_v41/draft/calib_env.zig | 8 +++++++- .../families/deepseek_v41/draft/plain_streams_test.zig | 8 +++++--- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/zig/src/families/deepseek_v41/draft/calib_env.zig b/zig/src/families/deepseek_v41/draft/calib_env.zig index 187987d3ea8..525d0a041b4 100644 --- a/zig/src/families/deepseek_v41/draft/calib_env.zig +++ b/zig/src/families/deepseek_v41/draft/calib_env.zig @@ -206,6 +206,9 @@ pub fn store(gpa: Allocator, io: std.Io, dir: []const u8, want: Shape, c: Costs, return path; } +/// TF_DSV41_DRAFT_PLAIN_STREAMS' largest value: the most slots a server runs (TF_DSV41_SLOTS). +pub const max_plain_streams = 16; + /// The depth's knobs (TF_DSV41_DEPTH, _DRAFT_DEPTH, _DRAFT_SKIP, _DEPTH_JOINT, _DEPTH_FAIR, _DEPTH_HOST_MS, rows cap). pub fn depthSettings(get: *const fn ([*:0]const u8) ?[]const u8) !depth.Settings { var s: depth.Settings = .{}; @@ -225,7 +228,10 @@ pub fn depthSettings(get: *const fn ([*:0]const u8) ?[]const u8) !depth.Settings s.fair = try float(get("TF_DSV41_DEPTH_FAIR"), joint.fair, 0.0, 4.0); s.host_ms = try float(get("TF_DSV41_DEPTH_HOST_MS"), joint.host_ms, 0.0, 100.0); if (trimmed(get("TF_DSV41_GRAPH_ROWS_MAX"))) |v| s.max_rows = @max(1, @min(try std.fmt.parseInt(u64, v, 10), costs_mod.max_rows)); - if (trimmed(get("TF_DSV41_DRAFT_PLAIN_STREAMS"))) |v| s.plain_streams = try std.fmt.parseInt(usize, v, 10); + if (trimmed(get("TF_DSV41_DRAFT_PLAIN_STREAMS"))) |v| { + s.plain_streams = std.fmt.parseInt(usize, v, 10) catch return error.DraftPlainStreams; + if (s.plain_streams > max_plain_streams) return error.DraftPlainStreams; + } return s; } diff --git a/zig/src/families/deepseek_v41/draft/plain_streams_test.zig b/zig/src/families/deepseek_v41/draft/plain_streams_test.zig index 3d0fa7239e7..64350155d6d 100644 --- a/zig/src/families/deepseek_v41/draft/plain_streams_test.zig +++ b/zig/src/families/deepseek_v41/draft/plain_streams_test.zig @@ -17,13 +17,15 @@ const Env = struct { } }; -test "TF_DSV41_DRAFT_PLAIN_STREAMS: parsed, 0 when unset, bad values error" { +test "TF_DSV41_DRAFT_PLAIN_STREAMS: parsed, 0 when unset, 0 to 16 taken, anything else refused by name" { Env.pairs = &.{}; try std.testing.expectEqual(@as(usize, 0), (try calib_env.depthSettings(&Env.get)).plain_streams); Env.pairs = &.{.{ "TF_DSV41_DRAFT_PLAIN_STREAMS", "3" }}; try std.testing.expectEqual(@as(usize, 3), (try calib_env.depthSettings(&Env.get)).plain_streams); - Env.pairs = &.{.{ "TF_DSV41_DRAFT_PLAIN_STREAMS", "oops" }}; - try std.testing.expectError(error.InvalidCharacter, calib_env.depthSettings(&Env.get)); + for ([_][]const u8{ "16", "17", "4294967296", "18446744073709551616", "-1", "oops", "3x" }) |raw| { + Env.pairs = &.{.{ "TF_DSV41_DRAFT_PLAIN_STREAMS", raw }}; + if (std.mem.eql(u8, raw, "16")) try std.testing.expectEqual(@as(usize, 16), (try calib_env.depthSettings(&Env.get)).plain_streams) else try std.testing.expectError(error.DraftPlainStreams, calib_env.depthSettings(&Env.get)); + } Env.pairs = &.{}; } From 6663f2517ee29a4bf7a4812ad3810d0fb001a08c Mon Sep 17 00:00:00 2001 From: Kevin Gilbertson <880013+gilby@users.noreply.github.com> Date: Wed, 11 Nov 2026 22:44:36 +0100 Subject: [PATCH 12/15] dsv41 metal: the plain switch holds a stream's ask only while plain_streams streams decode --- zig/src/families/deepseek_v41/draft/lanes.zig | 28 +- .../deepseek_v41/draft/plain_streams_test.zig | 274 +++++++----------- 2 files changed, 119 insertions(+), 183 deletions(-) diff --git a/zig/src/families/deepseek_v41/draft/lanes.zig b/zig/src/families/deepseek_v41/draft/lanes.zig index 831f937e71b..93ce5ce3f68 100644 --- a/zig/src/families/deepseek_v41/draft/lanes.zig +++ b/zig/src/families/deepseek_v41/draft/lanes.zig @@ -43,8 +43,6 @@ pub const St = struct { n_sib: u32 = 0, shown: std.ArrayList(u32) = .empty, // the drafts this round's window verifies (node indices, window order) shown_set: bool = false, - burst_seen: bool = false, // the plain switch: an ask batch reached plain_streams, the normal rules apply from then on - wide_asks: u8 = 0, // the plain switch: asks made while never wide, a lone stream drafts from its second /// Node i of the held tree: the main chain's drafts, then each sibling's rows. pub fn nodes(st: *const St) u32 { @@ -435,16 +433,23 @@ pub const Lanes = struct { } } - /// The hold before a stream's first draft (the plain switch): until its burst has formed or its second ask. - const lone_asks_before_draft = 2; // a stream admitted alone drafts from its second ask + /// The plain switch: plain_streams or more streams decoding (past their prompts), so the round's windows are plain. + fn wideRound(x: *const Lanes) bool { + const at = x.opts.depth.plain_streams; + if (at == 0) return false; + var n: usize = 0; + for (x.by_slot) |o| if (o) |st| { + n += @intFromBool(st.len > 0); + }; + return n >= at; + } fn draft(ptr: *anyopaque, requests: []const be.DraftRequest) anyerror!void { const x = self(ptr); try x.settle(); _ = x.scratch.reset(.retain_capacity); const a = x.scratch.allocator(); - const switch_on = x.opts.depth.plain_streams > 0; - const burst = switch_on and requests.len >= x.opts.depth.plain_streams; // the round's burst: the normal rules apply + const wide = x.wideRound(); const asks = try a.alloc(iface.Ask, requests.len); const whose = try a.alloc(*St, requests.len); const depths = try a.alloc(u32, requests.len); @@ -454,11 +459,12 @@ pub const Lanes = struct { var n: usize = 0; for (requests) |r| { const st = try x.get(r.stream); + const asks_now = r.depth > 0 and !wide; var at = st.len; if (r.rows) |path| { if (r.start != st.base) return error.PositionMismatch; const done = if (x.spec) |*sp| sp.ingested(st.slot, r.start, path) else false; - if (!done) try x.ingest(st, r.start, path); // the drafter's ring holds every committed row, drafted or not // a shared round drafts before its keep: the path, not st.len + if (!done) try x.ingest(st, r.start, path); // a shared round drafts before its keep: the path, not st.len at = r.start + path.len; } if (r.position != at + 1) return error.PositionMismatch; @@ -472,11 +478,7 @@ pub const Lanes = struct { st.n = 0; st.n_sib = 0; st.start = at; - if (r.depth == 0) continue; - if (switch_on) { - if (burst) st.burst_seen = true else st.wide_asks += 1; - if (!st.burst_seen and st.wide_asks < lone_asks_before_draft) continue; // the plain switch: the hold until its burst has formed or its second ask - } + if (!asks_now) continue; // no drafts asked, or the plain switch: a round this wide drafts none if (n == x.opts.slots) return error.TooManySlots; asks[n] = .{ .slot = st.slot, .anchor = anchor, .start = at, .params = dspark.Params.of(r.stream.sampling, at) }; whose[n] = st; @@ -536,7 +538,7 @@ pub const Lanes = struct { fn heldTree(ptr: *anyopaque, s: *Stream, gpa: Allocator) anyerror!?lanes.stream.Held { const x = self(ptr); const st = try x.get(s); - if (st.n == 0) return .{ .count = 0 }; // the ask was skipped (the plain switch's first round): the engine plans a plain window + if (st.n == 0) return .{ .count = 0 }; // no ask this round (the plain switch): the engine plans a plain window const total = st.nodes(); const tokens = try gpa.alloc(u32, total); errdefer gpa.free(tokens); diff --git a/zig/src/families/deepseek_v41/draft/plain_streams_test.zig b/zig/src/families/deepseek_v41/draft/plain_streams_test.zig index 64350155d6d..613d6166219 100644 --- a/zig/src/families/deepseek_v41/draft/plain_streams_test.zig +++ b/zig/src/families/deepseek_v41/draft/plain_streams_test.zig @@ -1,4 +1,4 @@ -//! TF_DSV41_DRAFT_PLAIN_STREAMS: the env knob, and a round with enough active windows decodes plain. +//! TF_DSV41_DRAFT_PLAIN_STREAMS: the env knob, and a round with enough decoding streams decodes plain. const std = @import("std"); const lanes = @import("lanes"); const twin = @import("twin.zig"); @@ -8,6 +8,7 @@ const depth = @import("depth.zig"); const calib_env = @import("calib_env.zig"); const gpa = std.testing.allocator; +const t_ = std.testing; const Env = struct { var pairs: []const [2][]const u8 = &.{}; @@ -17,19 +18,39 @@ const Env = struct { } }; -test "TF_DSV41_DRAFT_PLAIN_STREAMS: parsed, 0 when unset, 0 to 16 taken, anything else refused by name" { - Env.pairs = &.{}; - try std.testing.expectEqual(@as(usize, 0), (try calib_env.depthSettings(&Env.get)).plain_streams); - Env.pairs = &.{.{ "TF_DSV41_DRAFT_PLAIN_STREAMS", "3" }}; - try std.testing.expectEqual(@as(usize, 3), (try calib_env.depthSettings(&Env.get)).plain_streams); - for ([_][]const u8{ "16", "17", "4294967296", "18446744073709551616", "-1", "oops", "3x" }) |raw| { - Env.pairs = &.{.{ "TF_DSV41_DRAFT_PLAIN_STREAMS", raw }}; - if (std.mem.eql(u8, raw, "16")) try std.testing.expectEqual(@as(usize, 16), (try calib_env.depthSettings(&Env.get)).plain_streams) else try std.testing.expectError(error.DraftPlainStreams, calib_env.depthSettings(&Env.get)); - } +fn plainStreams(raw: []const u8) !usize { + Env.pairs = &.{.{ "TF_DSV41_DRAFT_PLAIN_STREAMS", raw }}; + defer Env.pairs = &.{}; + return (try calib_env.depthSettings(&Env.get)).plain_streams; +} + +test "TF_DSV41_DRAFT_PLAIN_STREAMS: 0 when unset, 0 to 16 taken, anything else refused by name" { Env.pairs = &.{}; + try t_.expectEqual(@as(usize, 0), (try calib_env.depthSettings(&Env.get)).plain_streams); + for ([_][]const u8{ "0", "3", " 16 " }, [_]usize{ 0, 3, 16 }) |raw, want| try t_.expectEqual(want, try plainStreams(raw)); + for ([_][]const u8{ "17", "4294967296", "18446744073709551616", "-1", "oops", "3x" }) |raw| + try t_.expectError(error.DraftPlainStreams, plainStreams(raw)); } -fn runPlain(cases: []const []const u32, setup: Setup, max_news: []const u32) !Run { +/// A run's settings: the switch, staggered arrivals, sampling. +pub const Opts = struct { set: depth.Settings = .{}, stagger: bool = false, sampling: ?lanes.Sampling = null }; + +pub const Run = struct { + drafted: u64, + accepted: u64, + ok: bool, + passes: u64, + ingests: u64, + out: [][]u32, + + pub fn deinit(r: Run) void { + for (r.out) |o| gpa.free(o); + gpa.free(r.out); + } +}; + +/// Streams of these prompts and lengths through the lanes over the twin; staggered: one added each step. +pub fn run(cases: []const []const u32, max_news: []const u32, o: Opts) !Run { const dims: twin.Dims = .{ .bigram = 8.0, .head = 0.08 }; // a confident drafter (lanes_test's): drafts are chosen const t = try twin.Twin.init(gpa, dims, cases.len + 1); defer t.deinit(); @@ -37,7 +58,7 @@ fn runPlain(cases: []const []const u32, setup: Setup, max_news: []const u32) !Ru defer d.deinit(); var c = try costs_mod.defaults(gpa, 64); defer c.deinit(gpa); - const x = try ln.Lanes.init(gpa, t.target(), d.pass(), c, .{ .shape = d.shape, .slots = 4, .depth = setup, .spec = .{ .on = true } }); + const x = try ln.Lanes.init(gpa, t.target(), d.pass(), c, .{ .shape = d.shape, .slots = 4, .depth = o.set, .spec = .{ .on = true } }); defer x.deinit(); var arena = std.heap.ArenaAllocator.init(gpa); defer arena.deinit(); @@ -49,176 +70,89 @@ fn runPlain(cases: []const []const u32, setup: Setup, max_news: []const u32) !Ru x.attach(&e); const streams = try gpa.alloc(lanes.Stream, cases.len); defer gpa.free(streams); - for (cases, streams, max_news) |p, *s, *n| s.* = try lanes.Stream.init(gpa, .{ .id = "s", .prompt = p, .max_new = n.* }); + for (cases, streams, max_news) |p, *s, n| s.* = try lanes.Stream.init(gpa, .{ .id = "s", .prompt = p, .max_new = n, .sampling = o.sampling }); defer for (streams) |*s| s.deinit(gpa); - for (streams) |*s| try e.addStream(s); - while (e.activeCount() > 0) try e.step(); + var added: usize = 0; + if (!o.stagger) { + for (streams) |*s| try e.addStream(s); + added = streams.len; + } + var steps: usize = 0; + while (e.activeCount() > 0 or added < streams.len) : (steps += 1) { + if (added < streams.len) { + try e.addStream(&streams[added]); + added += 1; + } + try e.step(); + if (steps > 1000) return error.TooManySteps; + } var ok = true; for (streams) |*s| ok = ok and s.emitted().len > 0; - return .{ .drafted = e.drafted, .ok = ok, .passes = d.passes, .out = blk: { - const out = try gpa.alloc([]u32, cases.len); - for (out, streams) |*o, *s| o.* = try gpa.dupe(u32, s.emitted()); - break :blk out; - } }; + const out = try gpa.alloc([]u32, cases.len); + for (out, streams) |*q, *s| q.* = try gpa.dupe(u32, s.emitted()); + return .{ .drafted = e.drafted, .accepted = e.accepted, .ok = ok, .passes = d.passes, .ingests = d.ingests, .out = out }; } -fn freeRun(r: *Run) void { - for (r.out) |o| gpa.free(o); - gpa.free(r.out); +/// Each reply is its prompt's serial decode at its own length. +pub fn expectSerial(r: Run, cases: []const []const u32, max_news: []const u32, sampling: ?lanes.Sampling) !void { + const t = try twin.Twin.init(gpa, .{ .bigram = 8.0, .head = 0.08 }, 1); + defer t.deinit(); + try t_.expect(r.ok); + for (r.out, cases, max_news) |got, p, n| { + const want = try t.serial(0, p, n, sampling, null); + defer gpa.free(want); + try t_.expectEqualSlices(u32, want, got); + } } -const Setup = depth.Settings; - -const Run = struct { drafted: u64, ok: bool, passes: u64, out: [][]u32 }; - -const a1 = [_]u32{ 3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9, 3, 2, 3, 8, 4 }; +pub const a1 = [_]u32{ 3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9, 3, 2, 3, 8, 4 }; +const four = [_][]const u32{ &a1, &a1, &a1, &a1 }; +const fours = [_]u32{ 40, 40, 40, 40 }; -test "a round with plain_streams or more active windows decodes plain; below it drafts; 0 keeps drafts" { - // identical prompts and greedy sampling keep every round a full 4-window round until the streams end together - const four = [_][]const u32{ &a1, &a1, &a1, &a1 }; - const fours = [_]u32{ 40, 40, 40, 40 }; - // 4 active, threshold 3: every drafted window is forced to count 0 - const plain = try runPlain(&four, .{ .plain_streams = 3 }, &fours); - defer freeRun(@constCast(&plain)); - try std.testing.expect(plain.ok); - try std.testing.expectEqual(@as(u64, 0), plain.drafted); - // 3 active, threshold 3: at it, plain too - const at = try runPlain(four[0..3], .{ .plain_streams = 3 }, fours[0..3]); - defer freeRun(@constCast(&at)); - try std.testing.expect(at.ok); - try std.testing.expectEqual(@as(u64, 0), at.drafted); - // 2 active, threshold 3: below it, drafts are kept - const below = try runPlain(four[0..2], .{ .plain_streams = 3 }, fours[0..2]); - defer freeRun(@constCast(&below)); - try std.testing.expect(below.ok); - try std.testing.expect(below.drafted > 0); - // 4 active, threshold 0 (off): drafts are kept - const off = try runPlain(&four, .{}, &fours); - defer freeRun(@constCast(&off)); - try std.testing.expect(off.ok); - try std.testing.expect(off.drafted > 0); +test "a round with plain_streams or more decoding streams decodes plain; below it drafts; 0 keeps drafts" { + // identical prompts and greedy sampling keep every round a full round until the streams end together + const plain = try run(&four, &fours, .{ .set = .{ .plain_streams = 3 } }); + defer plain.deinit(); + try t_.expectEqual(@as(u64, 0), plain.drafted); + const at = try run(four[0..3], fours[0..3], .{ .set = .{ .plain_streams = 3 } }); + defer at.deinit(); + try t_.expectEqual(@as(u64, 0), at.drafted); + const below = try run(four[0..2], fours[0..2], .{ .set = .{ .plain_streams = 3 } }); + defer below.deinit(); + try t_.expect(below.drafted > 0); + const off = try run(&four, &fours, .{}); + defer off.deinit(); + try t_.expect(off.drafted > 0); + for ([_]Run{ plain, at, below, off }, [_]usize{ 4, 3, 2, 4 }) |r, n| try expectSerial(r, four[0..n], fours[0..n], null); } -test "a stream's first draft ask waits for its first round; the replies stay the serial ones" { - const four = [_][]const u32{ &a1, &a1, &a1, &a1 }; - const dims: twin.Dims = .{ .bigram = 8.0, .head = 0.08 }; - const fours = [_]u32{ 40, 40, 40, 40 }; - // off, 4 streams: every round drafts, every round runs the pass - const off = try runPlain(&four, .{}, &fours); - defer freeRun(@constCast(&off)); - try std.testing.expect(off.passes > 0); - // at the threshold: shared rounds run no pass and the opening asks are skipped, so no pass runs at all - const on = try runPlain(&four, .{ .plain_streams = 3 }, &fours); - defer freeRun(@constCast(&on)); - try std.testing.expectEqual(@as(u64, 0), on.drafted); - try std.testing.expectEqual(@as(u64, 0), on.passes); - // tokens identical drafted or plain - for (off.out, on.out) |a, b| try std.testing.expectEqualSlices(u32, a, b); - // serial reference - { - const t = try twin.Twin.init(gpa, dims, 1); - defer t.deinit(); - for (on.out, four) |got, p| { - const want = try t.serial(0, p, 40, null, null); - defer gpa.free(want); - try std.testing.expectEqualSlices(u32, want, got); - } - } +test "below the threshold the switch changes nothing: 1 and 2 streams draft from their first ask as with it off" { + for ([_]usize{ 1, 2 }) |n| for ([_]bool{ false, true }) |stagger| { + const on = try run(four[0..n], fours[0..n], .{ .set = .{ .plain_streams = 3 }, .stagger = stagger }); + defer on.deinit(); + const off = try run(four[0..n], fours[0..n], .{ .stagger = stagger }); + defer off.deinit(); + try t_.expect(on.drafted > 0); + try t_.expectEqual(off.passes, on.passes); + try t_.expectEqual(off.drafted, on.drafted); + try t_.expectEqual(off.accepted, on.accepted); + try t_.expectEqual(off.ingests, on.ingests); + for (off.out, on.out) |a, b| try t_.expectEqualSlices(u32, a, b); + }; } -test "a stream drafts no round until its burst has formed or its second ask while never wide" { - // staggered arrival, plain_streams 3: the burst forms at the third stream, from which every stream drafts - const dims: twin.Dims = .{ .bigram = 8.0, .head = 0.08 }; - { - const t = try twin.Twin.init(gpa, dims, 5); - defer t.deinit(); - const d = try twin.Drafter.init(gpa, t, 5); - defer d.deinit(); - var c = try costs_mod.defaults(gpa, 64); - defer c.deinit(gpa); - const x = try ln.Lanes.init(gpa, t.target(), d.pass(), c, .{ .shape = d.shape, .slots = 4, .depth = .{ .plain_streams = 3 }, .spec = .{ .on = true } }); - defer x.deinit(); - var arena = std.heap.ArenaAllocator.init(gpa); - defer arena.deinit(); - var cfg = try lanes.Config.init(gpa, try x.model(arena.allocator(), 64), 16, 15); - defer cfg.deinit(gpa); - var clock: lanes.fake.FixedClock = .{}; - var e = lanes.Engine.init(gpa, &cfg, x.backend(), clock.clock()); - defer e.deinit(); - x.attach(&e); - const streams = try gpa.alloc(lanes.Stream, 4); - defer gpa.free(streams); - var i: usize = 0; - var steps: u64 = 0; - while (e.activeCount() > 0 or i < 4) { - try e.step(); - steps += 1; - if (i < 4) { - const s = &streams[i]; - s.* = try lanes.Stream.init(gpa, .{ .id = "s", .prompt = &a1, .max_new = 40 }); - try e.addStream(s); - i += 1; - } - if (steps > 400) return error.TooManySteps; - } - defer for (streams) |*s| s.deinit(gpa); - var ok = true; - for (streams) |*s| ok = ok and s.emitted().len > 0; - try std.testing.expect(ok); - try std.testing.expect(d.passes > 0); // the burst formed at three streams: the later rounds draft - try std.testing.expect(e.drafted > 0); - // tokens equal to the serial reference - for (streams) |*s| { - const want = try t.serial(0, &a1, 40, null, null); - defer gpa.free(want); - try std.testing.expectEqualSlices(u32, want, s.emitted()); - } - } - // the truly-lone control: one stream admitted alone drafts from its second ask - const lone = try runPlain(&.{&a1}, .{ .plain_streams = 3 }, &.{40}); - defer freeRun(@constCast(&lone)); - try std.testing.expect(lone.ok); - try std.testing.expect(lone.drafted > 0); - try std.testing.expect(lone.passes > 0); - { - const t = try twin.Twin.init(gpa, dims, 1); - defer t.deinit(); - const want = try t.serial(0, &a1, 40, null, null); - defer gpa.free(want); - try std.testing.expectEqualSlices(u32, want, lone.out[0]); - } +test "at the threshold only the asks made before plain_streams streams decode run a pass; replies unchanged" { + const on = try run(&four, &fours, .{ .set = .{ .plain_streams = 3 } }); + defer on.deinit(); + try t_.expectEqual(@as(u64, 0), on.drafted); + try t_.expect(on.passes <= 2); // the first two streams' opening asks, made while fewer than three decoded + try expectSerial(on, &four, &fours, null); } -test "below the threshold a stream drafts on its first ask; drafting resumes once streams finish" { - const four = [_][]const u32{ &a1, &a1, &a1, &a1 }; - const dims: twin.Dims = .{ .bigram = 8.0, .head = 0.08 }; - const fours = [_]u32{ 40, 40, 40, 40 }; - // the threshold not reached (1-2 active): the first ask is held, the second drafts - const one = try runPlain(four[0..1], .{ .plain_streams = 3 }, fours[0..1]); - defer freeRun(@constCast(&one)); - try std.testing.expect(one.ok); - try std.testing.expect(one.drafted > 0); - try std.testing.expect(one.passes > 0); - const two = try runPlain(four[0..2], .{ .plain_streams = 3 }, fours[0..2]); - defer freeRun(@constCast(&two)); - try std.testing.expect(two.ok); - try std.testing.expect(two.drafted > 0); - try std.testing.expect(two.passes > 0); - // 4 streams, two finish early: admitted four-deep, the burst has formed from round one, so every ask drafts - const twos = [_]u32{ 6, 6, 40, 40 }; - const mixed = try runPlain(&four, .{ .plain_streams = 3 }, &twos); - defer freeRun(@constCast(&mixed)); - try std.testing.expect(mixed.ok); - try std.testing.expect(mixed.drafted > 0); // after two streams finished, 2 active: drafts asked again - try std.testing.expect(mixed.passes > 0); // every pass is from the resumed rounds - // serial reference, each stream's own length - { - const t = try twin.Twin.init(gpa, dims, 1); - defer t.deinit(); - for (mixed.out, four, &twos) |got, p, *n| { - const want = try t.serial(0, p, n.*, null, null); - defer gpa.free(want); - try std.testing.expectEqualSlices(u32, want, got); - } - } +test "staggered arrivals: streams draft until plain_streams decode, plain after, drafting again as they end" { + const lens = [_]u32{ 40, 46, 52, 58 }; + const on = try run(&four, &lens, .{ .set = .{ .plain_streams = 3 }, .stagger = true }); + defer on.deinit(); + try t_.expect(on.passes > 0 and on.drafted > 0); + try expectSerial(on, &four, &lens, null); } From 52fc206b80d75bf1c3f83b916e50d606705a6253 Mon Sep 17 00:00:00 2001 From: Kevin Gilbertson <880013+gilby@users.noreply.github.com> Date: Wed, 11 Nov 2026 22:46:10 +0100 Subject: [PATCH 13/15] dsv41 metal: the taps ring takes a window's kept rows only, so it never holds a rejected draft's taps --- zig/src/families/deepseek_v41/metal/target.zig | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/zig/src/families/deepseek_v41/metal/target.zig b/zig/src/families/deepseek_v41/metal/target.zig index 2e83b64b236..7958b7924b4 100644 --- a/zig/src/families/deepseek_v41/metal/target.zig +++ b/zig/src/families/deepseek_v41/metal/target.zig @@ -50,7 +50,7 @@ const Slot = struct { base: u64 = 0, rows: u32 = 0, open: bool = false, - /// the taps of the last `ring rows` positions, position p at row p % ring rows + /// the taps of the last `ring rows` committed positions, position p at row p % ring rows ring: []u16, /// the taps `taps` names after a prompt: its last rows in order ptaps: mtl.Buffer, @@ -307,19 +307,18 @@ pub const Target = struct { } for (group) |g| { const s = &t.slots[g.slot]; + if (s.open) t.commitTaps(s, s.rows); // a window never kept keeps all its rows s.whole = false; try s.hist.appendSlice(t.a, g.tokens); s.high = @max(s.high, s.hist.items.len); } t.launch(group) catch |e| return t.fail(e); const lg = t.b.logitsOf(c, total); - const w = tapWidth(c); var r0: usize = 0; for (group, choices) |g, out| { const s = &t.slots[g.slot]; const n = g.tokens.len; for (0..n) |r| out[r] = try t.choose(lg[(r0 + r) * V ..][0..V], g.draws[r], g.sampling); - if (s.kv.taps) |tb| for (0..n) |r| t.ringPut(s, g.start + r, tb.slice(u16, n * w)[r * w ..][0..w]); s.base = g.start; s.rows = @intCast(n); s.open = true; @@ -370,6 +369,7 @@ pub const Target = struct { for (path, 0..) |r, i| if (r != i) return error.NotAPath; s.open = false; const m: u32 = @intCast(path.len); + t.commitTaps(s, m); if (m == s.rows) return; const len = s.base + m; s.hist.shrinkRetainingCapacity(@intCast(len)); @@ -379,6 +379,13 @@ pub const Target = struct { t.stats.rewinds += 1; } + /// The ring takes the first `m` rows of the slot's last window (its kept rows); rows not kept never land in it. + fn commitTaps(t: *const Target, s: *Slot, m: u32) void { + const tb = s.kv.taps orelse return; + const w = tapWidth(t.env.c); + for (0..m) |r| t.ringPut(s, s.base + r, tb.slice(u16, @as(usize, s.rows) * w)[r * w ..][0..w]); + } + fn taps(ptr: *anyopaque, slot: u32) iface.Taps { const t = self(ptr); const s = &t.slots[slot]; @@ -395,6 +402,7 @@ pub const Target = struct { const s = &t.slots[slot]; if (!s.live) return; s.live = false; + if (s.open) t.commitTaps(s, s.rows); s.open = false; if (s.whole and t.cache.on()) t.cache.save(t.env.c, &s.kv, s.hist.items, s.ring, null) catch {}; } From a43ad7b98d6d1269b9a5fe9b657a41eadaa3973d Mon Sep 17 00:00:00 2001 From: Kevin Gilbertson <880013+gilby@users.noreply.github.com> Date: Wed, 11 Nov 2026 22:46:17 +0100 Subject: [PATCH 14/15] dsv41 metal: plain rounds leave their rows in the target's history, and the next ask catches the drafter up --- CHANGELOG.md | 2 +- zig/src/families/deepseek_v41/draft/draft.zig | 1 + zig/src/families/deepseek_v41/draft/iface.zig | 11 ++++ .../deepseek_v41/draft/lane_ingest.zig | 39 +++++++++++++++ zig/src/families/deepseek_v41/draft/lanes.zig | 20 ++------ .../deepseek_v41/draft/plain_catchup_test.zig | 50 +++++++++++++++++++ .../deepseek_v41/draft/plain_streams_test.zig | 10 ++-- .../families/deepseek_v41/draft/spec_test.zig | 17 +++++-- zig/src/families/deepseek_v41/draft/twin.zig | 30 +++++++++++ .../families/deepseek_v41/metal/target.zig | 19 ++++++- zig/tests/dsv41_metal/serve_test.zig | 22 ++++++++ 11 files changed, 193 insertions(+), 28 deletions(-) create mode 100644 zig/src/families/deepseek_v41/draft/lane_ingest.zig create mode 100644 zig/src/families/deepseek_v41/draft/plain_catchup_test.zig diff --git a/CHANGELOG.md b/CHANGELOG.md index ab3bcb38dbe..b006a2d4936 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,7 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased -- DeepSeek-V4.1 on Metal: rounds with three or more active streams decode plain and skip the draft pass, since drafts lose there (#1720, part of #1676). +- DeepSeek-V4.1 on Metal: rounds with three or more decoding streams decode plain, with no draft pass and no drafter ingest, since drafts lose there; when fewer streams decode again the drafter takes the rows it missed from the target, so its drafts are the ones it would have made (#1720, part of #1676). - Flash Next: twenty-nine `TF_FLASHNEXT_*` settings refuse a malformed value by name at startup, before any device work on CUDA, and a Metal load refuses them too; blank `TF_FLASHNEXT_KV_PAGE_TEST` and `TF_FLASHNEXT_KEEP_LATE` read as unset, and a non-finite confidence is refused (#2585, part of #2370). Thanks to @devopsfortunato. - Flash Next on CUDA: twenty-nine `TF_FLASHNEXT_*` settings refuse a malformed value by name at startup, before any diff --git a/zig/src/families/deepseek_v41/draft/draft.zig b/zig/src/families/deepseek_v41/draft/draft.zig index 69559911c81..78f48ed0ae2 100644 --- a/zig/src/families/deepseek_v41/draft/draft.zig +++ b/zig/src/families/deepseek_v41/draft/draft.zig @@ -39,6 +39,7 @@ test { _ = calib_env; _ = @import("calib_env_test.zig"); _ = @import("plain_streams_test.zig"); + _ = @import("plain_catchup_test.zig"); _ = calib_measure; _ = @import("calib_measure_test.zig"); _ = branches_oracle; diff --git a/zig/src/families/deepseek_v41/draft/iface.zig b/zig/src/families/deepseek_v41/draft/iface.zig index f8bfae834e6..d63cae1b376 100644 --- a/zig/src/families/deepseek_v41/draft/iface.zig +++ b/zig/src/families/deepseek_v41/draft/iface.zig @@ -48,8 +48,19 @@ pub const Target = struct { warm: ?*const fn (ptr: *anyopaque, asks: []const Warm) void = null, /// After `prefill`: the prompt rows the slot took from kept state (its first row computed is this one). resumed: ?*const fn (ptr: *anyopaque, slot: u32) u64 = null, + /// Committed rows' taps for positions [start, start + rows), in order; null: not kept. null fn: none kept. + history: ?*const fn (ptr: *anyopaque, slot: u32, start: u64, rows: u32) ?Taps = null, }; + /// The target keeps committed rows' taps, so the drafter may take a plain round's rows later (`history`). + pub fn keepsHistory(t: Target) bool { + return t.vtable.history != null; + } + + pub fn history(t: Target, slot: u32, start: u64, rows: u32) ?Taps { + return if (t.vtable.history) |f| f(t.ptr, slot, start, rows) else null; + } + /// The prompt rows the slot's last `prefill` took from kept state (0: none, or a target that keeps none). pub fn resumedRows(t: Target, slot: u32) u64 { return if (t.vtable.resumed) |f| f(t.ptr, slot) else 0; diff --git a/zig/src/families/deepseek_v41/draft/lane_ingest.zig b/zig/src/families/deepseek_v41/draft/lane_ingest.zig new file mode 100644 index 00000000000..3adae056a8e --- /dev/null +++ b/zig/src/families/deepseek_v41/draft/lane_ingest.zig @@ -0,0 +1,39 @@ +//! The drafter's committed rows for the lanes: a window's kept rows, after any rows that were left for later. +const iface = @import("iface.zig"); +const branches = @import("branches.zig"); +const ln = @import("lanes.zig"); + +/// A round's kept rows into the drafter: first the rows a skipped absorb left out (`catchUp`), then these. +pub fn ingest(x: *ln.Lanes, st: *ln.St, start: u64, rows: []const u32) !void { + try catchUp(x, st, start, start + rows.len); + st.ring_end = start + rows.len; + const span = iface.ingestSpan(rows.len, x.opts.shape.window); + if (span.count == 0) return; + const taps = x.target.taps(st.slot); + const m = taps.map orelse return x.pass.ingest(st.slot, start + span.skip, taps, rows[span.skip..]); + // a tree resolved as chains: the path's rows in the taps of the chain that holds it + var mapped: [branches.max_rows]u32 = undefined; + if (span.count > mapped.len) return error.TreeRows; + for (rows[span.skip..], mapped[0..span.count]) |r, *o| { + if (r >= m.len or m[r] == branches.unrun) return error.TreeTaps; + o.* = m[r]; + } + try x.pass.ingest(st.slot, start + span.skip, taps, mapped[0..span.count]); +} + +/// Absorb skipped: the rows stay in the target's history, and the next ingest takes them from there. +pub fn deferred(x: *const ln.Lanes) bool { + return x.target.keepsHistory(); +} + +/// The committed rows between the drafter's end and `start`, the last `window` before `end` only (all it reads). +fn catchUp(x: *ln.Lanes, st: *ln.St, start: u64, end: u64) !void { + const from = st.ring_end orelse return; + const lo = @max(from, end -| x.opts.shape.window); + if (lo >= start) return; + const n: u32 = @intCast(start - lo); + const taps = x.target.history(st.slot, lo, n) orelse return error.HistoryLost; + const rows = try x.scratch.allocator().alloc(u32, n); + for (rows, 0..) |*r, i| r.* = @intCast(i); + try x.pass.ingest(st.slot, lo, taps, rows); +} diff --git a/zig/src/families/deepseek_v41/draft/lanes.zig b/zig/src/families/deepseek_v41/draft/lanes.zig index 93ce5ce3f68..70d176a0656 100644 --- a/zig/src/families/deepseek_v41/draft/lanes.zig +++ b/zig/src/families/deepseek_v41/draft/lanes.zig @@ -11,7 +11,6 @@ const depth = @import("depth.zig"); const calib = @import("calib.zig"); const costs_mod = @import("costs.zig"); const Policy = @import("policy.zig").Policy; -const branches = @import("branches.zig"); const spec_mod = @import("spec.zig"); pub const max_block = 16; @@ -43,6 +42,7 @@ pub const St = struct { n_sib: u32 = 0, shown: std.ArrayList(u32) = .empty, // the drafts this round's window verifies (node indices, window order) shown_set: bool = false, + ring_end: ?u64 = null, // the drafter holds the committed rows before this position (null: none yet) /// Node i of the held tree: the main chain's drafts, then each sibling's rows. pub fn nodes(st: *const St) u32 { @@ -151,20 +151,7 @@ pub const Lanes = struct { }; } - fn ingest(x: *Lanes, st: *St, start: u64, rows: []const u32) !void { - const span = iface.ingestSpan(rows.len, x.opts.shape.window); - if (span.count == 0) return; - const taps = x.target.taps(st.slot); - const m = taps.map orelse return x.pass.ingest(st.slot, start + span.skip, taps, rows[span.skip..]); - // a tree resolved as chains: the path's rows in the taps of the chain that holds it - var mapped: [branches.max_rows]u32 = undefined; - if (span.count > mapped.len) return error.TreeRows; - for (rows[span.skip..], mapped[0..span.count]) |r, *o| { - if (r >= m.len or m[r] == branches.unrun) return error.TreeTaps; - o.* = m[r]; - } - try x.pass.ingest(st.slot, start + span.skip, taps, mapped[0..span.count]); - } + const ingest = @import("lane_ingest.zig").ingest; fn prefill(ptr: *anyopaque, s: *Stream) anyerror!void { const x = self(ptr); @@ -464,7 +451,8 @@ pub const Lanes = struct { if (r.rows) |path| { if (r.start != st.base) return error.PositionMismatch; const done = if (x.spec) |*sp| sp.ingested(st.slot, r.start, path) else false; - if (!done) try x.ingest(st, r.start, path); // a shared round drafts before its keep: the path, not st.len + // a shared round drafts before its keep: the path, not st.len; no ask: the next ingest catches it up + if (!done and (asks_now or !@import("lane_ingest.zig").deferred(x))) try x.ingest(st, r.start, path); at = r.start + path.len; } if (r.position != at + 1) return error.PositionMismatch; diff --git a/zig/src/families/deepseek_v41/draft/plain_catchup_test.zig b/zig/src/families/deepseek_v41/draft/plain_catchup_test.zig new file mode 100644 index 00000000000..9ca0ff3cd52 --- /dev/null +++ b/zig/src/families/deepseek_v41/draft/plain_catchup_test.zig @@ -0,0 +1,50 @@ +//! Plain rounds absorb nothing into the drafter; the next ask catches it up from the target's history, exactly. +const std = @import("std"); +const lanes = @import("lanes"); +const ps = @import("plain_streams_test.zig"); + +const t_ = std.testing; +const warm: lanes.Sampling = .{ .seed = 5, .temperature = 1.0, .top_k = 20, .top_p = 0.95, .min_p = 0.02 }; +const four = [_][]const u32{ &ps.a1, &ps.a1, &ps.a1, &ps.a1 }; + +test "plain rounds run no ingest when the target keeps history; without it each round absorbs its rows" { + const lens = [_]u32{ 40, 40, 40, 40 }; + const kept = try ps.run(&four, &lens, .{ .set = .{ .plain_streams = 3 } }); + defer kept.deinit(); + const each = try ps.run(&four, &lens, .{ .set = .{ .plain_streams = 3 }, .history = false }); + defer each.deinit(); + try t_.expectEqual(@as(u64, 4), kept.ingests); // the four prompts' rows only + try t_.expect(each.ingests > 4 * 30); + for (kept.out, each.out) |a, b| try t_.expectEqualSlices(u32, a, b); + try ps.expectSerial(kept, &four, &lens, null); +} + +test "dropping below the threshold catches the drafter up: the same drafts as a drafter fed every round" { + // two streams end early: rounds turn plain to drafting; the long pair's gap is past the drafter's window (16) + const cases = [_][4]u32{ .{ 6, 6, 40, 40 }, .{ 30, 30, 70, 70 } }; + for (&cases) |*lens| for ([_]?lanes.Sampling{ null, warm }) |smp| { + const kept = try ps.run(&four, lens, .{ .set = .{ .plain_streams = 3 }, .check_ring = true, .sampling = smp }); + defer kept.deinit(); + const each = try ps.run(&four, lens, .{ .set = .{ .plain_streams = 3 }, .history = false, .check_ring = true, .sampling = smp }); + defer each.deinit(); + try t_.expect(kept.drafted > 0); + try t_.expectEqual(each.drafted, kept.drafted); + try t_.expectEqual(each.accepted, kept.accepted); + try t_.expectEqual(each.passes, kept.passes); + try t_.expect(kept.ingests < each.ingests); + for (kept.out, each.out) |a, b| try t_.expectEqualSlices(u32, a, b); + try ps.expectSerial(kept, &four, lens, smp); + }; +} + +test "a never-plain run and a run that went plain give the same replies, greedy and sampled" { + const lens = [_]u32{ 8, 12, 50, 50 }; + for ([_]?lanes.Sampling{ null, warm }) |smp| { + const never = try ps.run(&four, &lens, .{ .sampling = smp, .check_ring = true }); + defer never.deinit(); + const went = try ps.run(&four, &lens, .{ .set = .{ .plain_streams = 3 }, .sampling = smp, .check_ring = true }); + defer went.deinit(); + try t_.expect(never.drafted > 0 and went.drafted > 0); + for (never.out, went.out) |a, b| try t_.expectEqualSlices(u32, a, b); + } +} diff --git a/zig/src/families/deepseek_v41/draft/plain_streams_test.zig b/zig/src/families/deepseek_v41/draft/plain_streams_test.zig index 613d6166219..bc8151c1b30 100644 --- a/zig/src/families/deepseek_v41/draft/plain_streams_test.zig +++ b/zig/src/families/deepseek_v41/draft/plain_streams_test.zig @@ -32,8 +32,8 @@ test "TF_DSV41_DRAFT_PLAIN_STREAMS: 0 when unset, 0 to 16 taken, anything else r try t_.expectError(error.DraftPlainStreams, plainStreams(raw)); } -/// A run's settings: the switch, staggered arrivals, sampling. -pub const Opts = struct { set: depth.Settings = .{}, stagger: bool = false, sampling: ?lanes.Sampling = null }; +/// A run's settings: the switch, the target's history, the drafter's ring check, staggered arrivals, sampling. +pub const Opts = struct { set: depth.Settings = .{}, history: bool = true, check_ring: bool = false, stagger: bool = false, sampling: ?lanes.Sampling = null }; pub const Run = struct { drafted: u64, @@ -56,9 +56,11 @@ pub fn run(cases: []const []const u32, max_news: []const u32, o: Opts) !Run { defer t.deinit(); const d = try twin.Drafter.init(gpa, t, cases.len + 1); defer d.deinit(); + d.check_ring = o.check_ring; var c = try costs_mod.defaults(gpa, 64); defer c.deinit(gpa); - const x = try ln.Lanes.init(gpa, t.target(), d.pass(), c, .{ .shape = d.shape, .slots = 4, .depth = o.set, .spec = .{ .on = true } }); + const tgt = if (o.history) t.target() else t.targetNoHistory(); + const x = try ln.Lanes.init(gpa, tgt, d.pass(), c, .{ .shape = d.shape, .slots = 4, .depth = o.set, .spec = .{ .on = true } }); defer x.deinit(); var arena = std.heap.ArenaAllocator.init(gpa); defer arena.deinit(); @@ -151,7 +153,7 @@ test "at the threshold only the asks made before plain_streams streams decode ru test "staggered arrivals: streams draft until plain_streams decode, plain after, drafting again as they end" { const lens = [_]u32{ 40, 46, 52, 58 }; - const on = try run(&four, &lens, .{ .set = .{ .plain_streams = 3 }, .stagger = true }); + const on = try run(&four, &lens, .{ .set = .{ .plain_streams = 3 }, .stagger = true, .check_ring = true }); defer on.deinit(); try t_.expect(on.passes > 0 and on.drafted > 0); try expectSerial(on, &four, &lens, null); diff --git a/zig/src/families/deepseek_v41/draft/spec_test.zig b/zig/src/families/deepseek_v41/draft/spec_test.zig index fbeb227aee1..b42716cd9da 100644 --- a/zig/src/families/deepseek_v41/draft/spec_test.zig +++ b/zig/src/families/deepseek_v41/draft/spec_test.zig @@ -121,7 +121,7 @@ const Run = struct { const Mode = enum { off, sync, device }; -fn run(cases: []const Case, mode: Mode, settings: spec.Settings, siblings: u32) !Run { +fn run(cases: []const Case, mode: Mode, settings: spec.Settings, siblings: u32, history: bool) !Run { const dims: twin.Dims = .{}; const slots: u32 = 4; const t = try twin.Twin.init(gpa, dims, slots + 1); @@ -133,7 +133,7 @@ fn run(cases: []const Case, mode: Mode, settings: spec.Settings, siblings: u32) const pass = if (mode == .device) d.passAsync() else d.pass(); var set = settings; set.on = mode != .off; - const x = try ln.Lanes.init(gpa, t.target(), pass, c, .{ .shape = d.shape, .slots = slots, .siblings = siblings, .spec = set }); + const x = try ln.Lanes.init(gpa, if (history) t.target() else t.targetNoHistory(), pass, c, .{ .shape = d.shape, .slots = slots, .siblings = siblings, .spec = set }); defer x.deinit(); var arena = std.heap.ArenaAllocator.init(gpa); defer arena.deinit(); @@ -155,7 +155,14 @@ fn run(cases: []const Case, mode: Mode, settings: spec.Settings, siblings: u32) } fn expectSame(cases: []const Case, settings: spec.Settings, siblings: u32) ![3]spec.Stats { - const off = try run(cases, .off, settings, siblings); + var stats: [3]spec.Stats = undefined; + // with history an absorb without an ask waits for the next ingest, so ingest calls are counted without it + for ([_]bool{ true, false }) |history| stats = try expectSameAs(cases, settings, siblings, history); + return stats; +} + +fn expectSameAs(cases: []const Case, settings: spec.Settings, siblings: u32, history: bool) ![3]spec.Stats { + const off = try run(cases, .off, settings, siblings, history); defer off.deinit(); for (cases, off.out) |cs, got| { // the reference itself is the serial decode const t = try twin.Twin.init(gpa, .{}, 1); @@ -166,7 +173,7 @@ fn expectSame(cases: []const Case, settings: spec.Settings, siblings: u32) ![3]s } var stats: [3]spec.Stats = undefined; for ([_]Mode{ .sync, .device }, 1..) |m, i| { - const r = try run(cases, m, settings, siblings); + const r = try run(cases, m, settings, siblings, history); defer r.deinit(); for (off.out, r.out) |a, b| try std.testing.expectEqualSlices(u32, a, b); // the same drafts: the same windows, acceptance and kept counts as the run without speculation @@ -175,7 +182,7 @@ fn expectSame(cases: []const Case, settings: spec.Settings, siblings: u32) ![3]s try std.testing.expectEqualSlices(u64, &off.kept, &r.kept); // every used speculation replaced a pass, every launch ran one; skipped commits saved their ingests try std.testing.expectEqual(off.passes + r.stats.launched - r.stats.hit, r.passes); - try std.testing.expectEqual(off.ingests + r.stats.launched_slots, r.ingests + r.stats.ingests_skipped); + if (!history) try std.testing.expectEqual(off.ingests + r.stats.launched_slots, r.ingests + r.stats.ingests_skipped); stats[i] = r.stats; } stats[0] = .{}; diff --git a/zig/src/families/deepseek_v41/draft/twin.zig b/zig/src/families/deepseek_v41/draft/twin.zig index c665150483d..5380f891658 100644 --- a/zig/src/families/deepseek_v41/draft/twin.zig +++ b/zig/src/families/deepseek_v41/draft/twin.zig @@ -16,6 +16,7 @@ const Slot = struct { rows: std.ArrayList(f32) = .empty, // the last window's keys, values and taps [rows][3 dim] parents: std.ArrayList(i32) = .empty, taps: std.ArrayList(f32) = .empty, + hist: std.ArrayList(f32) = .empty, // committed rows' taps [len][dim] (Target.history) live: bool = false, fn deinit(s: *Slot, gpa: Allocator) void { @@ -24,6 +25,7 @@ const Slot = struct { s.rows.deinit(gpa); s.parents.deinit(gpa); s.taps.deinit(gpa); + s.hist.deinit(gpa); } fn len(s: Slot, d: usize) usize { @@ -174,6 +176,8 @@ pub const Twin = struct { choices[r] = try t.choose(a, row, draws[r], smp); } s.base = committed; + s.hist.shrinkRetainingCapacity(committed * d); + try s.hist.appendSlice(a, s.taps.items); for (0..n) |r| { // every row stays until keep (a chain that is never kept keeps them all) try s.k.appendSlice(a, s.rows.items[r * 2 * d ..][0..d]); try s.v.appendSlice(a, s.rows.items[r * 2 * d + d ..][0..d]); @@ -182,6 +186,11 @@ pub const Twin = struct { } pub fn target(t: *Twin) iface.Target { + return .{ .ptr = t, .vtable = &.{ .prefill = prefill, .window = window, .keep = keep, .taps = taps, .release = release, .history = history } }; + } + + /// The target without `history`: a plain round's rows are then absorbed in their own round. + pub fn targetNoHistory(t: *Twin) iface.Target { return .{ .ptr = t, .vtable = &.{ .prefill = prefill, .window = window, .keep = keep, .taps = taps, .release = release } }; } @@ -225,9 +234,11 @@ pub const Twin = struct { for (path[1..], path[0 .. path.len - 1]) |r, parent| if (s.parents.items[r] != @as(i32, @intCast(parent))) return error.NotAPath; s.k.shrinkRetainingCapacity(s.base * d); s.v.shrinkRetainingCapacity(s.base * d); + s.hist.shrinkRetainingCapacity(s.base * d); for (path) |r| { try s.k.appendSlice(t.gpa, s.rows.items[r * 2 * d ..][0..d]); try s.v.appendSlice(t.gpa, s.rows.items[r * 2 * d + d ..][0..d]); + try s.hist.appendSlice(t.gpa, s.taps.items[r * d ..][0..d]); } } @@ -236,6 +247,7 @@ pub const Twin = struct { const s = &t.slots[slot]; s.k.shrinkRetainingCapacity(s.base * t.dims.dim); s.v.shrinkRetainingCapacity(s.base * t.dims.dim); + s.hist.shrinkRetainingCapacity(s.base * t.dims.dim); } fn taps(ptr: *anyopaque, slot: u32) iface.Taps { @@ -244,6 +256,22 @@ pub const Twin = struct { return .{ .address = @intFromPtr(s.taps.items.ptr), .rows = @intCast(s.taps.items.len / t.dims.dim), .stride = t.dims.dim }; } + fn history(ptr: *anyopaque, slot: u32, start: u64, rows: u32) ?iface.Taps { + const t = self(ptr); + const s = &t.slots[slot]; + const d = t.dims.dim; + if (start + rows > s.hist.items.len / d) return null; + return .{ .address = @intFromPtr(s.hist.items[@intCast(start * d)..].ptr), .rows = rows, .stride = d }; + } + + /// A committed row's taps (what the drafter's ring should hold at `pos`), for the tests' ring check. + pub fn committedTaps(t: *const Twin, slot: u32, pos: u64) ?[]const f32 { + const s = &t.slots[slot]; + const d = t.dims.dim; + if (pos >= s.hist.items.len / d) return null; + return s.hist.items[@intCast(pos * d)..][0..d]; + } + fn release(ptr: *anyopaque, slot: u32) void { const t = self(ptr); t.slots[slot].live = false; @@ -286,6 +314,7 @@ pub const Drafter = struct { cw: []f32, passes: u64 = 0, ingests: u64 = 0, // ingest calls (tests) + check_ring: bool = false, // each context row must equal the target's committed taps at its position (tests) /// `begin` / `collect` (passAsync): the pass reads rings at `begin`, the host takes results at `collect`; all slots stash_drafts: []u32, stash_conf: []f32, @@ -435,6 +464,7 @@ pub const Drafter = struct { const pos = ctx.first + i; if (x.tags[ask.slot][pos % ring] != @as(i64, @intCast(pos))) return error.RingStale; const row = x.rings[ask.slot][(pos % ring) * d ..][0..d]; + if (x.check_ring and !std.mem.eql(f32, t.committedTaps(ask.slot, pos) orelse &.{}, row)) return error.RingWrong; t.project(t.wk, row, kbuf[i * 2 * d ..][0..d]); t.project(t.wv, row, kbuf[i * 2 * d + d ..][0..d]); keys[i] = kbuf[i * 2 * d ..][0..d]; diff --git a/zig/src/families/deepseek_v41/metal/target.zig b/zig/src/families/deepseek_v41/metal/target.zig index 7958b7924b4..ef832b6798d 100644 --- a/zig/src/families/deepseek_v41/metal/target.zig +++ b/zig/src/families/deepseek_v41/metal/target.zig @@ -39,7 +39,7 @@ pub const Options = struct { }; /// What the target did, for the tests and the logs. -pub const Stats = struct { prompts: u64 = 0, hits: u64 = 0, cached_rows: u64 = 0, windows: u64 = 0, rows: u64 = 0, rewinds: u64 = 0, launches: u64 = 0 }; +pub const Stats = struct { prompts: u64 = 0, hits: u64 = 0, cached_rows: u64 = 0, windows: u64 = 0, rows: u64 = 0, rewinds: u64 = 0, launches: u64 = 0, history_rows: u64 = 0 }; /// A slot: its device state, prompt tail, ids (rows run, the last window's included until its keep) and taps. const Slot = struct { @@ -138,7 +138,7 @@ pub const Target = struct { } pub fn target(t: *Target) iface.Target { - return .{ .ptr = t, .vtable = &.{ .prefill = prefill, .window = window, .keep = keep, .taps = taps, .release = release, .resumed = resumedFn } }; + return .{ .ptr = t, .vtable = &.{ .prefill = prefill, .window = window, .keep = keep, .taps = taps, .release = release, .resumed = resumedFn, .history = history } }; } fn self(ptr: *anyopaque) *Target { @@ -386,6 +386,21 @@ pub const Target = struct { for (0..m) |r| t.ringPut(s, s.base + r, tb.slice(u16, @as(usize, s.rows) * w)[r * w ..][0..w]); } + /// Committed rows' taps [start, start + rows) from the ring, in order, in the prompt-taps buffer. + fn history(ptr: *anyopaque, slot: u32, start: u64, rows: u32) ?iface.Taps { + const t = self(ptr); + if (slot >= t.slots.len) return null; + const s = &t.slots[slot]; + const c = t.env.c; + const w = tapWidth(c); + const end: u64 = if (s.open) s.base else s.hist.items.len; + if (w == 0 or s.after_prompt or rows == 0 or start + rows > end or start + ringRows(c) < end) return null; + const out = s.ptaps.slice(u16, @as(usize, rows) * w); + for (0..rows) |i| @memcpy(out[i * w ..][0..w], s.ring[((start + i) % ringRows(c)) * w ..][0..w]); + t.stats.history_rows += rows; + return .{ .address = @intFromPtr(s.ptaps.contents()), .rows = rows, .stride = @intCast(w) }; + } + fn taps(ptr: *anyopaque, slot: u32) iface.Taps { const t = self(ptr); const s = &t.slots[slot]; diff --git a/zig/tests/dsv41_metal/serve_test.zig b/zig/tests/dsv41_metal/serve_test.zig index 9bf82fd51a5..8a9a0b9de56 100644 --- a/zig/tests/dsv41_metal/serve_test.zig +++ b/zig/tests/dsv41_metal/serve_test.zig @@ -265,3 +265,25 @@ test "dsv41 metal serve: (e) a request cancelled during its prompt leaves the sl try testing.expect(gone.reason.? == .cancelled); try testing.expect(ok0 and ok1); } + +test "dsv41 metal serve: (f) plain rounds at four streams, drafts again at two from the target's history == serial" { + var ps: [4][]u32 = undefined; + for (&ps, 0..) |*p, i| p.* = try ids(90 + 40 * i, 20 + i); + defer for (ps) |p| gpa.free(p); + const asks = [_]Ask{ .{ .prompt = ps[0], .max = 12 }, .{ .prompt = ps[1], .max = 12 }, .{ .prompt = ps[2], .max = 60 }, .{ .prompt = ps[3], .max = 60 } }; + var want: [4][]u32 = undefined; + try reference(&asks, &want); + defer freeAll(&want); + const m = try fs.open(gpa, io, seed, .{}); + const s = try Served.open(gpa, io, m.model(), ".", null); + defer Served.close(s); + var drafted: u64 = 0; + var got: [4][]u32 = undefined; + try serve(s.engine(), &asks, true, &got, &drafted); + defer freeAll(&got); + const bad = same(&want, &got); + const caught = m.t.stats.history_rows; + say(bad == 0 and caught > 0 and drafted > 0, "(f) 4 together vs serial: {d} differ; {d} rows caught up from history, {d} drafted rows, {d} ingests", .{ bad, caught, drafted, m.ad.ingests }); + try testing.expectEqual(@as(usize, 0), bad); + try testing.expect(caught > 0 and drafted > 0); +} From fed6b631eb01b8a3473d871acf57aac53c41041c Mon Sep 17 00:00:00 2001 From: Kevin Gilbertson <880013+gilby@users.noreply.github.com> Date: Wed, 11 Nov 2026 23:26:21 +0100 Subject: [PATCH 15/15] dsv41 metal: warm the next window's Engram rows and join each layer's rows before its command buffer The Metal target now implements the lane core's warm hook with the host prefetch, so the commit and draft-end asks start the row reads early. A launch hashes both Engram layers' rows once, starts their reads together, and joins layer 1 and layer 14 only before the command buffer that holds them, so the reads overlap the GPU's earlier layers. A pending read is waited out on every error path. Rows and tokens are unchanged. --- CHANGELOG.md | 1 + zig/src/families/deepseek_v41/engram_host.zig | 7 +- .../deepseek_v41/metal/engram_stage.zig | 91 +++++++++ .../deepseek_v41/metal/engram_stage_test.zig | 175 ++++++++++++++++++ .../families/deepseek_v41/metal/forward.zig | 32 +++- zig/src/families/deepseek_v41/metal/metal.zig | 1 + .../families/deepseek_v41/metal/target.zig | 29 ++- zig/tests/dsv41_metal/serve_test.zig | 2 + 8 files changed, 323 insertions(+), 15 deletions(-) create mode 100644 zig/src/families/deepseek_v41/metal/engram_stage.zig create mode 100644 zig/src/families/deepseek_v41/metal/engram_stage_test.zig diff --git a/CHANGELOG.md b/CHANGELOG.md index b006a2d4936..ceaaf072243 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,7 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased +- DeepSeek-V4.1 on Metal: the lane core's Engram warms now start the next window's row reads early, and a launch joins each Engram layer's rows only before the command buffer that holds that layer, so the reads overlap the GPU's earlier layers; the rows read and the tokens are unchanged (#2953, part of #1676) - DeepSeek-V4.1 on Metal: rounds with three or more decoding streams decode plain, with no draft pass and no drafter ingest, since drafts lose there; when fewer streams decode again the drafter takes the rows it missed from the target, so its drafts are the ones it would have made (#1720, part of #1676). - Flash Next: twenty-nine `TF_FLASHNEXT_*` settings refuse a malformed value by name at startup, before any device work on CUDA, and a Metal load refuses them too; blank `TF_FLASHNEXT_KV_PAGE_TEST` and `TF_FLASHNEXT_KEEP_LATE` read as unset, and a non-finite confidence is refused (#2585, part of #2370). Thanks to @devopsfortunato. diff --git a/zig/src/families/deepseek_v41/engram_host.zig b/zig/src/families/deepseek_v41/engram_host.zig index 147cbccbdc9..af6764beced 100644 --- a/zig/src/families/deepseek_v41/engram_host.zig +++ b/zig/src/families/deepseek_v41/engram_host.zig @@ -120,8 +120,13 @@ pub const Host = struct { pub fn windowRows(h: *const Host, a: std.mem.Allocator, source: ?Source, ids: []const u32, lookback: []const u32, layer: u32, rank: u32, world: u32, dim: usize, out: []u16) !void { const idx = try h.shardIndex(a, ids, lookback, layer, rank, world); defer a.free(idx); + return h.readRows(source, layer, idx, dim, out); + } + + /// Engram layer `layer`'s rows `idx` (a `shardIndex` result) as bf16 [idx.len, dim]: from `source` or index rows. + pub fn readRows(h: *const Host, source: ?Source, layer: u32, idx: []const i64, dim: usize, out: []u16) !void { const s = source orelse return indexRows(idx, dim, out); - const li = std.mem.indexOfScalar(u32, h.layer_ids, layer).?; + const li = std.mem.indexOfScalar(u32, h.layer_ids, layer) orelse return error.NotEngram; return s.vtable.rows(s.ptr, li, idx, dim, out); } diff --git a/zig/src/families/deepseek_v41/metal/engram_stage.zig b/zig/src/families/deepseek_v41/metal/engram_stage.zig new file mode 100644 index 00000000000..3ad232cd7a5 --- /dev/null +++ b/zig/src/families/deepseek_v41/metal/engram_stage.zig @@ -0,0 +1,91 @@ +//! A launch's Engram rows read ahead and joined one layer at a time, just before the command buffer that needs them. +const std = @import("std"); +const host = @import("dsv41"); + +const eh = host.engram_host; +const Config = host.config.Config; + +/// One slot's ids of a launch and the ids before them (oldest first; short: the slot's start). +pub const Piece = struct { ids: []const u32, lookback: []const u32 }; + +/// Most pieces (slots) in a launch. +pub const max_pieces = 16; + +/// A launch's row reads: `begin` starts every Engram layer's, `join` lands one layer's, `deinit` leaves none pending. +pub const Stage = struct { + a: std.mem.Allocator, + host: ?*const eh.Host, + source: ?eh.Source, + layers: []const u32 = &.{}, + pieces: []const Piece = &.{}, + /// per Engram layer and piece: the table rows, hashed once at `begin` + idx: [eh.max_layers][max_pieces]?[]i64 = @splat(@splat(null)), + /// per Engram layer: its rows' destination [rows][cols * head_dim] bf16, and whether they have landed + out: [eh.max_layers][]u16 = @splat(&.{}), + joined: [eh.max_layers]bool = @splat(true), + dim: usize = 0, + cols: usize = 0, + + /// A launch without Engram layers: nothing to read. + pub const none: Stage = .{ .a = std.heap.page_allocator, .host = null, .source = null }; + + /// Hashes every layer's rows and starts reading them; `out[li]` receives layer li's rows at `join` (all pieces). + pub fn begin(a: std.mem.Allocator, c: *const Config, h: *const eh.Host, source: ?eh.Source, pieces: []const Piece, out: []const []u16) !Stage { + if (pieces.len > max_pieces or out.len < c.engram_layers.len) return error.BadRows; + var s: Stage = .{ .a = a, .host = h, .source = source, .layers = c.engram_layers.items(), .pieces = pieces, .dim = c.engram_head_dim, .cols = c.hashCols() }; + errdefer s.deinit(); + for (s.layers, 0..) |layer, li| { + s.out[li] = out[li]; + s.joined[li] = false; + for (pieces, 0..) |pc, pi| s.idx[li][pi] = try h.shardIndex(a, pc.ids, pc.lookback, layer, 0, 1); + } + s.issue(); + return s; + } + + /// Starts the reads the source can start early; a failure only means `join` reads them itself. + fn issue(s: *const Stage) void { + const src = s.source orelse return; + for (s.layers, 0..) |_, li| { + const hl = std.mem.indexOfScalar(u32, s.host.?.layer_ids, s.layers[li]) orelse continue; + for (s.idx[li][0..s.pieces.len]) |q| src.vtable.issue(src.ptr, hl, q.?) catch {}; + } + } + + /// Layer index `li`'s rows into its destination, pieces in row order (waits for reads still in flight). + pub fn join(s: *Stage, li: usize) !void { + if (s.joined[li]) return; + s.joined[li] = true; // a failed join is not retried: its error ends the launch + const K = s.cols * s.dim; + var r0: usize = 0; + for (s.pieces, s.idx[li][0..s.pieces.len]) |pc, q| { + try s.host.?.readRows(s.source, s.layers[li], q.?, s.dim, s.out[li][r0 * K ..][0 .. pc.ids.len * K]); + r0 += pc.ids.len; + } + } + + /// Joins the Engram layers whose index is in [lo, hi) of the backbone (the ones one command buffer holds). + pub fn joinRange(s: *Stage, lo: usize, hi: usize) !void { + for (s.layers, 0..) |layer, li| if (layer >= lo and layer < hi) try s.join(li); + } + + pub fn joinAll(s: *Stage) !void { + for (0..s.layers.len) |li| try s.join(li); + } + + /// Frees the hashed rows; a layer never joined has its reads waited out first, so none outlives the launch. + pub fn deinit(s: *Stage) void { + for (s.layers, 0..) |layer, li| { + for (s.idx[li][0..s.pieces.len]) |*slot| { + const q = slot.* orelse continue; + defer s.a.free(q); + slot.* = null; + if (s.joined[li]) continue; + const buf = s.a.alloc(u16, q.len * s.dim) catch continue; + defer s.a.free(buf); + s.host.?.readRows(s.source, layer, q, s.dim, buf) catch {}; + } + s.joined[li] = true; + } + } +}; diff --git a/zig/src/families/deepseek_v41/metal/engram_stage_test.zig b/zig/src/families/deepseek_v41/metal/engram_stage_test.zig new file mode 100644 index 00000000000..5efbcc6e622 --- /dev/null +++ b/zig/src/families/deepseek_v41/metal/engram_stage_test.zig @@ -0,0 +1,175 @@ +//! The staged Engram reads: same rows as the synchronous path, warm or not, and nothing left pending on a failure. +const std = @import("std"); +const host = @import("dsv41"); +const stage = @import("engram_stage.zig"); + +const eh = host.engram_host; +const Config = host.config.Config; +const Stage = stage.Stage; +const testing = std.testing; + +/// A source over index rows that logs what was issued and joined, and can fail a layer's join. +const Mock = struct { + pending: [2]i32 = .{ 0, 0 }, + issued: std.ArrayList(i64) = .empty, + joins: [64]usize = undefined, + n_joins: usize = 0, + fail_layer: ?usize = null, + + fn source(m: *Mock) eh.Source { + return .{ .ptr = m, .vtable = &.{ .issue = issue, .rows = rows } }; + } + + fn issue(p: *anyopaque, li: usize, idx: []const i64) anyerror!void { + const m: *Mock = @ptrCast(@alignCast(p)); + m.pending[li] += 1; + try m.issued.appendSlice(testing.allocator, idx); + } + + fn rows(p: *anyopaque, li: usize, idx: []const i64, dim: usize, out: []u16) anyerror!void { + const m: *Mock = @ptrCast(@alignCast(p)); + m.pending[li] = 0; + m.joins[m.n_joins] = li; + m.n_joins += 1; + if (m.fail_layer == li) return error.EngramReadFailed; + const shifted = try testing.allocator.alloc(i64, idx.len); + defer testing.allocator.free(shifted); + for (shifted, idx) |*o, i| o.* = i + @as(i64, @intCast(li)) * 7919; + eh.indexRows(shifted, dim, out); + } +}; + +const Rig = struct { + c: Config = .{}, + map: [1000]u32 = undefined, + ids_buf: [eh.max_layers]u32 = undefined, + h: eh.Host = undefined, + + fn init(r: *Rig) void { + for (&r.map, 0..) |*v, i| v.* = @intCast((i * 37) % 97); + r.ids_buf[0..2].* = .{ 1, 14 }; + r.h = .{ .layer_ids = r.ids_buf[0..2], .max_ngram = r.c.engram_max_ngram, .heads = r.c.engram_heads, .token_map = &r.map, .pad_id = 2 }; + for (0..2) |li| for (0..r.c.engram_max_ngram) |s| { + r.h.mult[li][s] = @intCast(1000003 + 7 * li + s); + }; + r.h.layout(1000); + } + + fn rowsLen(r: *const Rig, n: usize) usize { + return n * r.c.hashCols() * r.c.engram_head_dim; + } +}; + +const ids_a = [_]u32{ 5, 9, 11 }; +const look_a = [_]u32{ 3, 4, 8 }; +const ids_b = [_]u32{ 17, 23 }; +const look_b = [_]u32{ 1, 2, 6 }; +const pieces = [_]stage.Piece{ .{ .ids = &ids_a, .lookback = &look_a }, .{ .ids = &ids_b, .lookback = &look_b } }; + +/// The synchronous reference: `windowRows` per layer and piece, as the forward read them before staging. +fn reference(r: *const Rig, src: ?eh.Source, out: *[2][]u16) !void { + const K = r.c.hashCols() * r.c.engram_head_dim; + for (r.c.engram_layers.items(), 0..) |layer, li| { + var r0: usize = 0; + for (pieces) |pc| { + try r.h.windowRows(testing.allocator, src, pc.ids, pc.lookback, layer, 0, 1, r.c.engram_head_dim, out[li][r0 * K ..][0 .. pc.ids.len * K]); + r0 += pc.ids.len; + } + } +} + +fn alloc2(r: *const Rig) ![2][]u16 { + const a = try testing.allocator.alloc(u16, r.rowsLen(5)); + errdefer testing.allocator.free(a); + return .{ a, try testing.allocator.alloc(u16, r.rowsLen(5)) }; +} + +fn free2(o: [2][]u16) void { + for (o) |s| testing.allocator.free(s); +} + +test "staged rows are byte-equal to the synchronous read, unwarmed, warmed and warmed wrong" { + var rig: Rig = .{}; + rig.init(); + var m: Mock = .{}; + defer m.issued.deinit(testing.allocator); + const want = try alloc2(&rig); + defer free2(want); + try reference(&rig, m.source(), @constCast(&want)); + const wrong_ids = [_]u32{ 40, 41, 42, 43 }; + for ([_]enum { cold, right, wrong }{ .cold, .right, .wrong }) |kind| { + const got = try alloc2(&rig); + defer free2(got); + switch (kind) { + .cold => {}, + .right => for (pieces) |pc| rig.h.prefetch(testing.allocator, m.source(), pc.ids, pc.lookback, 0, 1), + .wrong => rig.h.prefetch(testing.allocator, m.source(), &wrong_ids, &look_a, 0, 1), + } + var st = try Stage.begin(testing.allocator, &rig.c, &rig.h, m.source(), &pieces, &got); + defer st.deinit(); + try st.joinAll(); + for (want, got) |w, g| try testing.expectEqualSlices(u16, w, g); + } +} + +test "a layer's rows are read only when its command buffer comes: layer 1 before 12, layer 14 before 23" { + var rig: Rig = .{}; + rig.init(); + var m: Mock = .{}; + defer m.issued.deinit(testing.allocator); + const got = try alloc2(&rig); + defer free2(got); + var st = try Stage.begin(testing.allocator, &rig.c, &rig.h, m.source(), &pieces, &got); + defer st.deinit(); + // both layers' reads started at once, none joined + try testing.expectEqual([2]i32{ 2, 2 }, m.pending); + try testing.expectEqual(@as(usize, 0), m.n_joins); + try st.joinRange(0, 1); + try testing.expectEqual(@as(usize, 0), m.n_joins); + try st.joinRange(1, 12); + try testing.expectEqualSlices(usize, &.{ 0, 0 }, m.joins[0..m.n_joins]); + try testing.expectEqual([2]i32{ 0, 2 }, m.pending); + try st.joinRange(12, 23); + try testing.expectEqualSlices(usize, &.{ 0, 0, 1, 1 }, m.joins[0..m.n_joins]); + try st.joinRange(12, 23); // joined once only + try testing.expectEqual(@as(usize, 4), m.n_joins); +} + +test "a failed join leaves no read pending and nothing allocated" { + var rig: Rig = .{}; + rig.init(); + var m: Mock = .{ .fail_layer = 0 }; + defer m.issued.deinit(testing.allocator); + const got = try alloc2(&rig); + defer free2(got); + { + var st = try Stage.begin(testing.allocator, &rig.c, &rig.h, m.source(), &pieces, &got); + defer st.deinit(); + try testing.expectError(error.EngramReadFailed, st.joinRange(0, 12)); + try testing.expectEqual(@as(i32, 2), m.pending[1]); // layer 14's reads still out: deinit waits them out + } + try testing.expectEqual([2]i32{ 0, 0 }, m.pending); + // the next launch reads the same rows as ever + m.fail_layer = null; + const again = try alloc2(&rig); + defer free2(again); + var st = try Stage.begin(testing.allocator, &rig.c, &rig.h, m.source(), &pieces, &again); + defer st.deinit(); + try st.joinAll(); + const want = try alloc2(&rig); + defer free2(want); + try reference(&rig, m.source(), @constCast(&want)); + for (want, again) |w, g| try testing.expectEqualSlices(u16, w, g); +} + +test "a begin that fails part-way frees its hashed rows and waits out what it started" { + var rig: Rig = .{}; + rig.init(); + var m: Mock = .{}; + defer m.issued.deinit(testing.allocator); + const got = try alloc2(&rig); + defer free2(got); + var fa = std.testing.FailingAllocator.init(testing.allocator, .{ .fail_index = 3 }); + try testing.expectError(error.OutOfMemory, Stage.begin(fa.allocator(), &rig.c, &rig.h, m.source(), &pieces, &got)); + try testing.expectEqual([2]i32{ 0, 0 }, m.pending); +} diff --git a/zig/src/families/deepseek_v41/metal/forward.zig b/zig/src/families/deepseek_v41/metal/forward.zig index 622ec616b42..477ff06686b 100644 --- a/zig/src/families/deepseek_v41/metal/forward.zig +++ b/zig/src/families/deepseek_v41/metal/forward.zig @@ -6,6 +6,7 @@ const ctx_ = @import("ctx.zig"); const weights = @import("weights.zig"); const pipelines = @import("pipelines.zig"); const layer = @import("layer.zig"); +const stage_ = @import("engram_stage.zig"); const Config = host.config.Config; const Ctx = ctx_.Ctx; @@ -103,10 +104,17 @@ pub fn prepare(b: *const Bufs, c: *const Config, ids: []const u32, lookback: []c } /// One slot's ids of a launch and the ids before them (oldest first; short: the slot's start). -pub const Piece = struct { ids: []const u32, lookback: []const u32 }; +pub const Piece = stage_.Piece; /// `prepare` for several slots' rows, pieces one after another in row order. pub fn prepareSegs(b: *const Bufs, c: *const Config, pieces: []const Piece, lk: ?Lookup) !void { + var st = try stageSegs(b, c, pieces, lk); + defer st.deinit(); + try st.joinAll(); +} + +/// The ids into the launch's buffer and every Engram layer's row reads started; `Stage.join` lands them (`runStaged`). +pub fn stageSegs(b: *const Bufs, c: *const Config, pieces: []const Piece, lk: ?Lookup) !stage_.Stage { var n: usize = 0; for (pieces) |pc| { if (pc.ids.len == 0) return error.BadRows; @@ -120,17 +128,12 @@ pub fn prepareSegs(b: *const Bufs, c: *const Config, pieces: []const Piece, lk: @memcpy(all[at..][0..pc.ids.len], pc.ids); at += pc.ids.len; } - if (c.engram_layers.len == 0) return; + if (c.engram_layers.len == 0) return stage_.Stage.none; const l = lk orelse return error.EngramLookupMissing; const K = c.hashCols() * c.engram_head_dim; - for (c.engram_layers.items(), 0..) |id, li| { - const out: []u16 = @alignCast(std.mem.bytesAsSlice(u16, b.bytes(b.rows[li], 2 * n * K))); - var r0: usize = 0; - for (pieces) |pc| { - try l.host.windowRows(l.a, l.source, pc.ids, pc.lookback, id, 0, 1, c.engram_head_dim, out[r0 * K ..][0 .. pc.ids.len * K]); - r0 += pc.ids.len; - } - } + var outs: [host.engram_host.max_layers][]u16 = undefined; + for (c.engram_layers.items(), 0..) |_, li| outs[li] = @alignCast(std.mem.bytesAsSlice(u16, b.bytes(b.rows[li], 2 * n * K))); + return stage_.Stage.begin(l.a, c, l.host, l.source, pieces, &outs); } /// The tokens' embedding rows into all four streams of streams[0], and the one-hot pre mix. @@ -210,6 +213,11 @@ pub fn chunkEnd(lo: usize, n: usize) usize { /// The decode forward in about `buffers` command buffers, each committed once encoded; waits for the last. pub fn run(x: *const Ctx, q: mtl.Queue, m: Model, b: *const Bufs) !void { + return runStaged(x, q, m, b, null); +} + +/// `run` with the Engram rows of `st` joined layer by layer, each just before the command buffer holding its layer. +pub fn runStaged(x: *const Ctx, q: mtl.Queue, m: Model, b: *const Bufs, st: ?*stage_.Stage) !void { if (m.layers.len != x.c.layers) return error.LayerOrder; if (x.rows == 0 or x.rows > R or x.rows != x.total()) return error.BadRows; var cbs: [max_buffers]mtl.CommandBuffer = undefined; @@ -219,6 +227,10 @@ pub fn run(x: *const Ctx, q: mtl.Queue, m: Model, b: *const Bufs) !void { while (true) { const hi = chunkEnd(lo, m.layers.len); if (n == max_buffers) return error.TooManyBuffers; + if (st) |s| s.joinRange(lo, hi) catch |err| { + if (n > 0) cbs[n - 1].wait(); + return err; + }; const cb = q.commandBuffer(); const e = cb.compute(.concurrent); const ok = encodeRange(x, e, m, b, lo, hi); diff --git a/zig/src/families/deepseek_v41/metal/metal.zig b/zig/src/families/deepseek_v41/metal/metal.zig index bec87c2930a..ec397bb116e 100644 --- a/zig/src/families/deepseek_v41/metal/metal.zig +++ b/zig/src/families/deepseek_v41/metal/metal.zig @@ -35,6 +35,7 @@ test { std.testing.refAllDecls(@This()); _ = ctx; _ = forward; + _ = @import("engram_stage_test.zig"); _ = prompt; _ = prompt_scratch; _ = dspark; diff --git a/zig/src/families/deepseek_v41/metal/target.zig b/zig/src/families/deepseek_v41/metal/target.zig index ef832b6798d..eb83c30e31c 100644 --- a/zig/src/families/deepseek_v41/metal/target.zig +++ b/zig/src/families/deepseek_v41/metal/target.zig @@ -39,7 +39,7 @@ pub const Options = struct { }; /// What the target did, for the tests and the logs. -pub const Stats = struct { prompts: u64 = 0, hits: u64 = 0, cached_rows: u64 = 0, windows: u64 = 0, rows: u64 = 0, rewinds: u64 = 0, launches: u64 = 0, history_rows: u64 = 0 }; +pub const Stats = struct { prompts: u64 = 0, hits: u64 = 0, cached_rows: u64 = 0, windows: u64 = 0, rows: u64 = 0, rewinds: u64 = 0, launches: u64 = 0, history_rows: u64 = 0, warms: u64 = 0 }; /// A slot: its device state, prompt tail, ids (rows run, the last window's included until its keep) and taps. const Slot = struct { @@ -138,7 +138,7 @@ pub const Target = struct { } pub fn target(t: *Target) iface.Target { - return .{ .ptr = t, .vtable = &.{ .prefill = prefill, .window = window, .keep = keep, .taps = taps, .release = release, .resumed = resumedFn, .history = history } }; + return .{ .ptr = t, .vtable = &.{ .prefill = prefill, .window = window, .keep = keep, .taps = taps, .release = release, .resumed = resumedFn, .history = history, .warm = warm } }; } fn self(ptr: *anyopaque) *Target { @@ -351,12 +351,33 @@ pub const Target = struct { segs[i] = .{ .slot = &s.kv, .p0 = start, .r0 = r0, .n = n }; r0 += n; } - try forward.prepareSegs(&t.b, c, pieces[0..group.len], e.lookup); + var rows = try forward.stageSegs(&t.b, c, pieces[0..group.len], e.lookup); + defer rows.deinit(); try e.s.writeSpans(c, spans[0..group.len]); const x: ctx_.Ctx = .{ .c = c, .p = e.p, .s = e.s, .slot = segs[0].slot, .tables = e.tables, .p0 = segs[0].p0, .rows = r0, .segs = segs[0..group.len] }; const pool = mtl.objc.Pool.push(); defer pool.pop(); - try forward.run(&x, e.queue, e.model, &t.b); + try forward.runStaged(&x, e.queue, e.model, &t.b, &rows); + } + + /// Iface.Target.warm: starts the Engram row reads of rows a coming window may hold; reads only, never its bits. + fn warm(ptr: *anyopaque, asks: []const iface.Warm) void { + const t = self(ptr); + const l = readingLookup(t) orelse return; + const look = t.env.c.engram_max_ngram - 1; + for (asks) |w| { + if (w.slot >= t.slots.len or w.ids.len == 0 or w.ids.len > R) continue; + const s = &t.slots[w.slot]; + if (!s.live or w.start > s.hist.items.len) continue; // a start past the ids held has no history to hash + const at: usize = @intCast(w.start); + t.stats.warms += 1; + l.host.prefetch(l.a, l.source, w.ids, s.hist.items[at -| look..at], 0, 1); + } + } + + fn readingLookup(t: *const Target) ?forward.Lookup { + const l = t.env.lookup orelse return null; + return if (l.source == null) null else l; } /// Keep the window's first rows (a chain from row 0): later rows' ids go, the compressor's carry rewinds. diff --git a/zig/tests/dsv41_metal/serve_test.zig b/zig/tests/dsv41_metal/serve_test.zig index 8a9a0b9de56..095af4c7386 100644 --- a/zig/tests/dsv41_metal/serve_test.zig +++ b/zig/tests/dsv41_metal/serve_test.zig @@ -146,6 +146,8 @@ test "dsv41 metal serve: (a) concurrent == solo == serial, (b) drafted == draft: try testing.expectEqual([3]usize{ 0, 0, 0 }, bad); try testing.expect(drafted > 0 and m.t.stats.rewinds > 0); try testing.expectEqual(@as(u64, 0), plain_drafted); + // the lanes warmed Engram rows ahead on every round, and the serial reference (no warms) has the same replies + try testing.expect(m.t.stats.warms > 0); } test "dsv41 metal serve: (c) prompt-cache hits (the same prompt, a later turn) == fresh runs" {