diff --git a/zig/src/core/engine_api.zig b/zig/src/core/engine_api.zig index 903dc4d40bd..0f4aeef5b92 100644 --- a/zig/src/core/engine_api.zig +++ b/zig/src/core/engine_api.zig @@ -230,7 +230,7 @@ pub const Open = struct { /// An opened engine; ``close`` stops its thread and frees its backend. pub const Opened = struct { engine: Engine, close: *const fn (ctx: *anyopaque) void, ctx: *anyopaque }; -pub const Memory = struct { active: u64 = 0, cache: u64 = 0, peak: u64 = 0, pinned: u64 = 0 }; +pub const Memory = struct { active: u64 = 0, cache: u64 = 0, peak: u64 = 0, pinned: u64 = 0, limit: ?u64 = null }; /// A backend's words for its own refusals (a request it cannot serve); null: the error's name. pub const Explain = struct { @@ -257,6 +257,13 @@ pub const Status = struct { streams: usize = 0, /// Generated tokens held by live streams, excluding their prompts. generation_tokens: u64 = 0, + /// Filling prompts' total tokens and those still to prefill (null: no prompt is going in). + fill_prompt_tokens: ?u32 = null, + fill_tokens_left: ?u32 = null, + /// A prompt pass is running whose backend reports no `fill_at`: the totals stay null rather than guessed. + fill_unknown: bool = false, + /// Changes whenever the filling set does: a reader pairs its drain samples with one fill. + fill_run: u64 = 0, }; pub const SubmitError = error{ Closed, Busy, InvalidSpans }; @@ -418,9 +425,10 @@ pub const keepalive = @import("keepalive.zig"); test { _ = @import("lane_host.zig"); _ = @import("lane_host_test.zig"); + _ = @import("lane_host_fill_test.zig"); + _ = @import("lane_host_status_test.zig"); _ = @import("lane_host_reuse_test.zig"); _ = @import("lane_host_warm_test.zig"); - _ = @import("lane_host_fill_test.zig"); _ = @import("prompt_cache.zig"); _ = @import("prompt_radix.zig"); _ = @import("prompt_imprint.zig"); diff --git a/zig/src/core/lane_host.zig b/zig/src/core/lane_host.zig index 4394fdac059..d6b599f13cb 100644 --- a/zig/src/core/lane_host.zig +++ b/zig/src/core/lane_host.zig @@ -66,6 +66,8 @@ pub const LaneHost = struct { prefill_sent: bool = false, // a lone driver's prefilled event went out fill_began: bool = false, // its first prompt chunk ran began: i96 = 0, + /// The engine thread says the prompt pass is going: status readers may count this job's fill atomics. + fill_on: std.atomic.Value(bool) = .init(false), prefilled: ?i96 = null, entry: ?*pc.Entry = null, // the kept state the backend restores, until its prompt pass reports marks: []const u32 = &.{}, // where the pass keeps states (gpa-owned) @@ -219,10 +221,11 @@ pub const LaneHost = struct { } } - /// Sends a stream's new tokens; true once it has finished (its job freed). + /// Sends a stream's new tokens; true once it has finished and left the lists a status read walks. pub fn deliver(h: *LaneHost, job: *Job) bool { h.send(job); if (!job.stream.finished) return false; + h.remove(job); const reason: Reason = switch (job.stream.reason) { .length => .length, .cancelled => .cancelled, @@ -264,15 +267,17 @@ pub const LaneHost = struct { for (dropped.items) |job| h.finish(job, .cancelled, ""); dropped.deinit(h.gpa); for (ids) |id| { + var found: ?*Job = null; + h.lock(); // the status reader walks `admitted` under this lock: the removal joins the walk's critical section for (h.admitted.items, 0..) |job, i| if (job.id == id) { fill.unfill(h, job); if (!job.stream.finished) h.core.discard(&job.stream); - h.lock(); _ = h.admitted.orderedRemove(i); - h.unlock(); - h.finish(job, .cancelled, ""); + found = job; break; }; + h.unlock(); + if (found) |job| h.finish(job, .cancelled, ""); } h.gpa.free(ids); } @@ -349,6 +354,7 @@ pub const LaneHost = struct { return h.drop(job, "out of memory"); }; job.started = true; + job.fill_on.store(true, .release); // status readers count the fill from here until the pass reports const began = std.Io.Clock.awake.now(h.io).toNanoseconds(); job.began = began; if (r.max_tokens == 0 and h.info_.warm_turns) return h.warmPass(job, began); @@ -363,7 +369,7 @@ pub const LaneHost = struct { else => h.drop(job, h.words(e)), }; h.prefilled(job, began); - if (h.deliver(job)) h.remove(job); + _ = h.deliver(job); return true; } @@ -388,7 +394,7 @@ pub const LaneHost = struct { if (!done) return; _ = h.filling.orderedRemove(at); h.prefilled(job, job.began); - if (h.deliver(job)) h.remove(job); + _ = h.deliver(job); } /// A reply's grammar from the server's compiler (Info.structures engines get requests that carry one). @@ -399,6 +405,7 @@ pub const LaneHost = struct { pub fn prefilled(h: *LaneHost, job: *Job, began: i96) void { const done = std.Io.Clock.awake.now(h.io).toNanoseconds(); + job.fill_on.store(false, .release); // the pass reported: status readers stop counting this fill h.lock(); if (done > began) h.prefill_rate = @as(f64, @floatFromInt(job.request.prompt.len - job.stream.cached)) / (@as(f64, @floatFromInt(done - began)) / 1e9); h.prefill_at = done; @@ -445,14 +452,6 @@ pub const LaneHost = struct { /// No memory for another lane yet: the job waits at the queue's head, and admission holds until a job ends. fn requeue(h: *LaneHost, job: *Job) bool { - if (job.stream.grammar) |g| g.deinit(h.gpa); // the next admission compiles its own - job.stream.deinit(h.gpa); - job.proposer.deinit(); - job.started = false; - job.fill_began = false; - job.entry = null; // looked up again at its next admission - h.gpa.free(job.marks); - job.marks = &.{}; h.lock(); for (h.admitted.items, 0..) |j, i| if (j == job) { _ = h.admitted.orderedRemove(i); @@ -468,6 +467,15 @@ pub const LaneHost = struct { h.finish(job, .failed, if (others > 0) "out of memory" else alone_words); return true; } + job.fill_on.store(false, .release); // off the lists before the teardown a status reader could have walked into + if (job.stream.grammar) |g| g.deinit(h.gpa); // the next admission compiles its own + job.stream.deinit(h.gpa); + job.proposer.deinit(); + job.started = false; + job.fill_began = false; + job.entry = null; // looked up again at its next admission + h.gpa.free(job.marks); + job.marks = &.{}; h.memory_lanes = others; return false; } @@ -532,11 +540,8 @@ pub const LaneHost = struct { var i: usize = 0; while (i < h.admitted.items.len) { const job = h.admitted.items[i]; - if (h.deliver(job)) { - h.lock(); - _ = h.admitted.orderedRemove(i); - h.unlock(); - } else i += 1; + if (h.deliver(job)) continue; // it left the list: the next job slid into slot i + i += 1; } lone.reclaim(h); } diff --git a/zig/src/core/lane_host_fill_test.zig b/zig/src/core/lane_host_fill_test.zig index 76c8446be25..d9515068c7e 100644 --- a/zig/src/core/lane_host_fill_test.zig +++ b/zig/src/core/lane_host_fill_test.zig @@ -7,6 +7,7 @@ const Reason = api.Reason; const Id = api.Id; const Event = api.Event; const Request = api.Request; +const Engine = api.Engine; test "a lane host fills the shortest waiting prompt first, so a short request waits on no long one" { const gpa = std.testing.allocator; @@ -121,3 +122,48 @@ test "a foreground prompt arriving while a background one fills takes the next c } try std.testing.expectEqualSlices(Id, &.{ 2, 1 }, &order.prefilled); } + +test "status reads a filling prompt's tokens while its pass runs, and none once it ends" { + const gpa = std.testing.allocator; + var cfg = try lanes.Config.init(gpa, .{ .exact_width = 8, .gpu_tokens = true, .hidden_rows = true }, 8, 7); + defer cfg.deinit(gpa); + var target: lanes.fake.Fake = .{ .gpa = gpa, .prefill_chunks = 4 }; + defer target.deinit(); + var clock: lanes.fake.FixedClock = .{}; + var core = lanes.Engine.init(gpa, &cfg, target.stepped(), clock.clock()); + defer core.deinit(); + var host = LaneHost.init(gpa, std.testing.io, &core, .{ .lanes = 1 }); + try host.start(); + defer host.stop(); + const Seen = struct { + engine: Engine = undefined, + lefts: std.ArrayList(u32) = .empty, + done: std.atomic.Value(bool) = .init(false), + + fn hook(ctx: *anyopaque, _: *lanes.Stream, _: usize) void { + const seen: *@This() = @ptrCast(@alignCast(ctx)); + var status: api.Status = .{}; + seen.engine.status(&status, &.{}); // the pass runs without the host's lock: this can read + if (status.fill_tokens_left) |left| seen.lefts.append(gpa, left) catch {}; + } + fn event(ctx: *anyopaque, _: Id, e: *const Event) void { + const seen: *@This() = @ptrCast(@alignCast(ctx)); + if (e.* == .finished) seen.done.store(true, .release); + } + }; + var seen: Seen = .{}; + seen.engine = host.engine(); + target.prefill_hook = Seen.hook; + target.prefill_hook_ctx = &seen; + const prompt = [_]u32{ 3, 1, 4, 1, 5, 9, 2, 6 }; + const request: Request = .{ .prompt = &prompt, .max_tokens = 4 }; + try seen.engine.submit(1, &request, .{ .ctx = &seen, .event = Seen.event }); + while (!seen.done.load(.acquire)) std.Io.sleep(std.testing.io, .fromMilliseconds(1), .awake) catch {}; + defer seen.lefts.deinit(gpa); + try std.testing.expect(seen.lefts.items.len >= 2); // each chunk of the pass sampled the status + for (seen.lefts.items) |left| try std.testing.expect(left > 0 and left <= prompt.len); + try std.testing.expect(seen.lefts.items[0] > seen.lefts.items[seen.lefts.items.len - 1]); // it counted down + var status: api.Status = .{}; + seen.engine.status(&status, &.{}); + try std.testing.expect(status.fill_prompt_tokens == null and status.fill_tokens_left == null); // the pass is over +} diff --git a/zig/src/core/lane_host_lone.zig b/zig/src/core/lane_host_lone.zig index 8eaf4feda39..e7cf1f17cfc 100644 --- a/zig/src/core/lane_host_lone.zig +++ b/zig/src/core/lane_host_lone.zig @@ -72,6 +72,6 @@ pub fn run(h: *LaneHost, job: *Job, began: i96, resumed: bool) bool { h.send(job); return true; } - if (h.deliver(job)) h.remove(job); + _ = h.deliver(job); // a finished job leaves the lists inside deliver, before finish frees it return true; } diff --git a/zig/src/core/lane_host_status.zig b/zig/src/core/lane_host_status.zig index a92bf19a0c2..d36b5c6f66e 100644 --- a/zig/src/core/lane_host_status.zig +++ b/zig/src/core/lane_host_status.zig @@ -28,6 +28,35 @@ pub fn read(ctx: *anyopaque, out: *api.Status, stream_tokens: []u32) void { .streams = n, .generation_tokens = h.live_generated, }; + fillTotals(h, out); +} + +/// A job whose prompt pass has not reported yet is filling; the engine thread publishes that with `fill_on`. +fn fillTotals(h: *LaneHost, out: *api.Status) void { + var total: u64 = 0; + var left: u64 = 0; + var filling = false; + var run: u64 = 0; + const reported = h.core.backend.vtable.reports_fill; // a backend that never stores `fill_at` has no honest totals + for (h.admitted.items) |job| { + if (!job.fill_on.load(.acquire)) continue; + filling = true; + var fields: [16]u8 = undefined; // id and seq hashed apart: XOR of the raw values collides (2^0 == 3^1) + std.mem.writeInt(u64, fields[0..8], job.id, .little); + std.mem.writeInt(u64, fields[8..16], job.seq, .little); + run = (run *% 0x9E3779B97F4A7C15) ^ std.hash.Wyhash.hash(0, &fields); + if (!reported) continue; // no counter for it: its prompt stays out of the totals rather than guessed + const prompt = job.request.prompt.len; + total += prompt; + left += prompt -| job.stream.fill_at.load(.monotonic); + } + if (!filling) return; + if (reported) { + out.fill_prompt_tokens = @intCast(total); + out.fill_tokens_left = @intCast(left); + } else out.fill_unknown = true; + run &= (1 << 53) - 1; // JSON numbers stay exact to 2^53: a wider marker loses bits in the page's JavaScript + out.fill_run = if (run == 0) 1 else run; } /// `n` tokens delivered now; marks older than the window drop. diff --git a/zig/src/core/lane_host_status_test.zig b/zig/src/core/lane_host_status_test.zig new file mode 100644 index 00000000000..8981b7878bc --- /dev/null +++ b/zig/src/core/lane_host_status_test.zig @@ -0,0 +1,397 @@ +//! Status reads stay lifetime-safe: a finishing job has left the host's lists before its event fires. +const std = @import("std"); +const lanes = @import("lanes"); +const api = @import("engine_api.zig"); +const LaneHost = @import("lane_host.zig").LaneHost; +const Reason = api.Reason; +const Id = api.Id; +const Event = api.Event; +const Request = api.Request; +const Engine = api.Engine; + +const short_prompt = [_]u32{ 3, 1, 4, 1, 5, 9, 2, 6 }; + +// The finished event fires inside `finish`, before the host frees the job: this is the racing poll. +test "status at a request's finished event no longer counts the job that just ended" { + const gpa = std.testing.allocator; + var cfg = try lanes.Config.init(gpa, .{ .exact_width = 8, .gpu_tokens = true, .hidden_rows = true }, 8, 7); + defer cfg.deinit(gpa); + var target: lanes.fake.Fake = .{ .gpa = gpa, .prefill_chunks = 2 }; + defer target.deinit(); + var clock: lanes.fake.FixedClock = .{}; + var core = lanes.Engine.init(gpa, &cfg, target.stepped(), clock.clock()); + defer core.deinit(); + var host = LaneHost.init(gpa, std.testing.io, &core, .{ .lanes = 2 }); + try host.start(); + defer host.stop(); + const Watch = struct { + engine: Engine = undefined, + mutex: std.Io.Mutex = .init, + done: ?Reason = null, + running_at_finish: usize = 0, + fill_at_finish: bool = false, + + fn event(ctx: *anyopaque, _: Id, e: *const Event) void { + const w: *@This() = @ptrCast(@alignCast(ctx)); + w.mutex.lockUncancelable(std.testing.io); + defer w.mutex.unlock(std.testing.io); + switch (e.*) { + .finished => |f| { + var status: api.Status = .{}; + w.engine.status(&status, &.{}); // the poll that raced with this completion + w.running_at_finish = status.running; + w.fill_at_finish = status.fill_tokens_left != null; + w.done = f.reason; + }, + else => {}, + } + } + fn wait(w: *@This()) Reason { + while (true) { + w.mutex.lockUncancelable(std.testing.io); + const d = w.done; + w.mutex.unlock(std.testing.io); + if (d) |r| return r; + std.Io.sleep(std.testing.io, .fromMilliseconds(1), .awake) catch {}; + } + } + }; + var watch: Watch = .{}; + watch.engine = host.engine(); + const request: Request = .{ .prompt = &short_prompt, .max_tokens = 4 }; + try watch.engine.submit(1, &request, .{ .ctx = &watch, .event = Watch.event }); + try std.testing.expectEqual(Reason.length, watch.wait()); + try std.testing.expectEqual(@as(usize, 0), watch.running_at_finish); // it left `admitted` before the event + try std.testing.expect(!watch.fill_at_finish); // and its fill progress with it + var status: api.Status = .{}; + watch.engine.status(&status, &.{}); + try std.testing.expectEqual(@as(u32, 0), status.running); // the host is idle: nothing is listed +} + +// A second request runs while the first completes: the poll at its finished event counts the survivor. +test "status at one request's finished event still counts the other request running" { + const gpa = std.testing.allocator; + var cfg = try lanes.Config.init(gpa, .{ .exact_width = 8, .gpu_tokens = true, .hidden_rows = true }, 8, 7); + defer cfg.deinit(gpa); + var target: lanes.fake.Fake = .{ .gpa = gpa, .prefill_chunks = 2 }; + defer target.deinit(); + var clock: lanes.fake.FixedClock = .{}; + var core = lanes.Engine.init(gpa, &cfg, target.stepped(), clock.clock()); + defer core.deinit(); + var host = LaneHost.init(gpa, std.testing.io, &core, .{ .lanes = 2 }); + try host.start(); + defer host.stop(); + const Watch = struct { + engine: Engine = undefined, + mutex: std.Io.Mutex = .init, + done: ?Reason = null, + running_at_finish: usize = 0, + fill_at_finish: bool = false, + + fn event(ctx: *anyopaque, _: Id, e: *const Event) void { + const w: *@This() = @ptrCast(@alignCast(ctx)); + w.mutex.lockUncancelable(std.testing.io); + defer w.mutex.unlock(std.testing.io); + switch (e.*) { + .finished => |f| { + var status: api.Status = .{}; + w.engine.status(&status, &.{}); + w.running_at_finish = status.running; + w.fill_at_finish = status.fill_tokens_left != null; + w.done = f.reason; + }, + else => {}, + } + } + fn wait(w: *@This()) Reason { + while (true) { + w.mutex.lockUncancelable(std.testing.io); + const d = w.done; + w.mutex.unlock(std.testing.io); + if (d) |r| return r; + std.Io.sleep(std.testing.io, .fromMilliseconds(1), .awake) catch {}; + } + } + }; + var first: Watch = .{}; + first.engine = host.engine(); + var second: Watch = .{}; + second.engine = host.engine(); + const quick: Request = .{ .prompt = &short_prompt, .max_tokens = 1 }; + const long: Request = .{ .prompt = &short_prompt, .max_tokens = 100000 }; + try second.engine.submit(1, &long, .{ .ctx = &second, .event = Watch.event }); + try first.engine.submit(2, &quick, .{ .ctx = &first, .event = Watch.event }); + try std.testing.expectEqual(Reason.length, first.wait()); + try std.testing.expectEqual(@as(usize, 1), first.running_at_finish); // only the long one + try std.testing.expect(!first.fill_at_finish); // the long one decodes: it fills nothing + var status: api.Status = .{}; + second.engine.status(&status, &.{}); + try std.testing.expectEqual(@as(u32, 1), status.running); + second.engine.cancel(1); + try std.testing.expectEqual(Reason.cancelled, second.wait()); +} + +test "status polls through a cancellation, a failed admission and a requeue stay sane" { + const gpa = std.testing.allocator; + var cfg = try lanes.Config.init(gpa, .{ .exact_width = 8, .gpu_tokens = true, .hidden_rows = true }, 8, 7); + defer cfg.deinit(gpa); + var target: lanes.fake.Fake = .{ .gpa = gpa, .memory_lanes = 1 }; + defer target.deinit(); + var clock: lanes.fake.FixedClock = .{}; + var core = lanes.Engine.init(gpa, &cfg, target.backend(), clock.clock()); + defer core.deinit(); + var host = LaneHost.init(gpa, std.testing.io, &core, .{ .lanes = 2 }); + try host.start(); + defer host.stop(); + const e = host.engine(); + const Poller = struct { + engine: Engine, + stop: std.atomic.Value(bool) = .init(false), + failed: std.atomic.Value(bool) = .init(false), + + fn poll(ctx: *anyopaque) void { + const p: *@This() = @ptrCast(@alignCast(ctx)); + while (!p.stop.load(.acquire)) { + var status: api.Status = .{}; + p.engine.status(&status, &.{}); + if (status.running > 2) p.failed.store(true, .release); // only two lanes exist + std.Io.sleep(std.testing.io, .fromMilliseconds(1), .awake) catch {}; + } + } + }; + var poller: Poller = .{ .engine = e }; + const thread = try std.Thread.spawn(.{}, Poller.poll, .{&poller}); + defer { + poller.stop.store(true, .release); + thread.join(); + } + const running: Request = .{ .prompt = &short_prompt, .max_tokens = 100000 }; + const small: Request = .{ .prompt = &short_prompt, .max_tokens = 4 }; + var a = try gpa.create(Box); + defer gpa.destroy(a); + a.* = .{}; + try e.submit(1, &running, .{ .ctx = a, .event = Box.event }); + var b = try gpa.create(Box); + defer gpa.destroy(b); + b.* = .{}; + try e.submit(2, &small, .{ .ctx = b, .event = Box.event }); // no memory for a second lane: it waits + std.Io.sleep(std.testing.io, .fromMilliseconds(20), .awake) catch {}; + e.cancel(1); + try std.testing.expectEqual(Reason.cancelled, a.wait()); + try std.testing.expectEqual(Reason.length, b.wait()); // admitted once the lane freed, then ran to its end + try std.testing.expect(!poller.failed.load(.acquire)); + var status: api.Status = .{}; + e.status(&status, &.{}); + try std.testing.expectEqual(@as(u32, 0), status.running); + try std.testing.expect(status.fill_prompt_tokens == null and status.fill_tokens_left == null); +} + +// The fill marker pins one fill: stable while a prompt's pass runs, and a later poll races it with no host lock. +test "fill_run is stable within one prompt's fill and changes for the next" { + const gpa = std.testing.allocator; + var cfg = try lanes.Config.init(gpa, .{ .exact_width = 8, .gpu_tokens = true, .hidden_rows = true }, 8, 7); + defer cfg.deinit(gpa); + var target: lanes.fake.Fake = .{ .gpa = gpa, .prefill_chunks = 3 }; + defer target.deinit(); + var clock: lanes.fake.FixedClock = .{}; + var core = lanes.Engine.init(gpa, &cfg, target.stepped(), clock.clock()); + defer core.deinit(); + var host = LaneHost.init(gpa, std.testing.io, &core, .{ .lanes = 1 }); + try host.start(); + defer host.stop(); + const Seen = struct { + engine: Engine = undefined, + first: ?u64 = null, + runs: std.ArrayList(u64) = .empty, + later: std.atomic.Value(bool) = .init(false), + later_runs: std.ArrayList(u64) = .empty, + done: std.atomic.Value(bool) = .init(false), + + fn hook(ctx: *anyopaque, _: *lanes.Stream, _: usize) void { + const seen: *@This() = @ptrCast(@alignCast(ctx)); + var status: api.Status = .{}; + seen.engine.status(&status, &.{}); // the pass holds no host lock here: the poll races it + if (status.fill_prompt_tokens == null) return; + if (seen.later.load(.acquire)) { + seen.later_runs.append(gpa, status.fill_run) catch {}; + } else { + if (seen.first == null) seen.first = status.fill_run; + seen.runs.append(gpa, status.fill_run) catch {}; + } + } + fn event(ctx: *anyopaque, _: Id, e: *const Event) void { + const seen: *@This() = @ptrCast(@alignCast(ctx)); + if (e.* == .finished) seen.done.store(true, .release); + } + }; + var seen: Seen = .{}; + seen.engine = host.engine(); + target.prefill_hook = Seen.hook; + target.prefill_hook_ctx = &seen; + const prompt = [_]u32{ 3, 1, 4, 1, 5, 9, 2, 6 }; + const request: Request = .{ .prompt = &prompt, .max_tokens = 4 }; + try seen.engine.submit(1, &request, .{ .ctx = &seen, .event = Seen.event }); + while (!seen.done.load(.acquire)) std.Io.sleep(std.testing.io, .fromMilliseconds(1), .awake) catch {}; + defer seen.runs.deinit(gpa); + try std.testing.expect(seen.runs.items.len >= 2); // the pass sampled the marker at least twice + for (seen.runs.items) |run| try std.testing.expectEqual(seen.first.?, run); // one fill, one marker + const second: Request = .{ .prompt = &prompt, .max_tokens = 4 }; + var gone: Box = .{}; + seen.later.store(true, .release); // the hook's next samples belong to the second fill + try seen.engine.submit(2, &second, .{ .ctx = &gone, .event = Box.event }); + try std.testing.expectEqual(Reason.length, gone.wait()); + defer seen.later_runs.deinit(gpa); + try std.testing.expect(seen.later_runs.items.len >= 1); // the next fill was sampled as well + try std.testing.expect(seen.later_runs.items[0] != seen.first.?); // its marker really does differ + for (seen.later_runs.items) |run| try std.testing.expectEqual(seen.later_runs.items[0], run); + var status: api.Status = .{}; + seen.engine.status(&status, &.{}); // idle again + try std.testing.expect(status.fill_run == 0); +} + +const Box = struct { + mutex: std.Io.Mutex = .init, + done: ?Reason = null, + message: []const u8 = "", + tokens: usize = 0, + fn event(ctx: *anyopaque, _: Id, e: *const Event) void { + const b: *@This() = @ptrCast(@alignCast(ctx)); + b.mutex.lockUncancelable(std.testing.io); + defer b.mutex.unlock(std.testing.io); + switch (e.*) { + .tokens => |t| b.tokens += t.len, + .finished => |f| { + b.done = f.reason; + b.message = f.message; + }, + else => {}, + } + } + fn wait(b: *@This()) Reason { + while (true) { + b.mutex.lockUncancelable(std.testing.io); + const d = b.done; + b.mutex.unlock(std.testing.io); + if (d) |r| return r; + std.Io.sleep(std.testing.io, .fromMilliseconds(1), .awake) catch {}; + } + } +}; + +// The reviewer's colliding pair: ids 2 and 3 at admissions 0 and 1 XOR alike, so the old marker read alike. +test "fill_run separates two equal-length fills whose id and sequence XOR alike" { + const gpa = std.testing.allocator; + var cfg = try lanes.Config.init(gpa, .{ .exact_width = 8, .gpu_tokens = true, .hidden_rows = true }, 8, 7); + defer cfg.deinit(gpa); + var target: lanes.fake.Fake = .{ .gpa = gpa, .prefill_chunks = 3 }; + defer target.deinit(); + var clock: lanes.fake.FixedClock = .{}; + var core = lanes.Engine.init(gpa, &cfg, target.stepped(), clock.clock()); + defer core.deinit(); + var host = LaneHost.init(gpa, std.testing.io, &core, .{ .lanes = 1 }); + try host.start(); + defer host.stop(); + const Seen = struct { + engine: Engine = undefined, + second: std.atomic.Value(bool) = .init(false), + first_runs: std.ArrayList(u64) = .empty, + second_runs: std.ArrayList(u64) = .empty, + + fn hook(ctx: *anyopaque, _: *lanes.Stream, _: usize) void { + const seen: *@This() = @ptrCast(@alignCast(ctx)); + var status: api.Status = .{}; + seen.engine.status(&status, &.{}); // the pass holds no host lock here: the poll races it + if (status.fill_prompt_tokens == null) return; + if (seen.second.load(.acquire)) { + seen.second_runs.append(gpa, status.fill_run) catch {}; + } else seen.first_runs.append(gpa, status.fill_run) catch {}; + } + }; + var seen: Seen = .{}; + seen.engine = host.engine(); + target.prefill_hook = Seen.hook; + target.prefill_hook_ctx = &seen; + const prompt = [_]u32{ 3, 1, 4, 1, 5, 9, 2, 6 }; // both prompts the same length: only id and sequence differ + const first: Request = .{ .prompt = &prompt, .max_tokens = 4 }; + var gone_a: Box = .{}; + try seen.engine.submit(2, &first, .{ .ctx = &gone_a, .event = Box.event }); // id 2, admission 0 + try std.testing.expectEqual(Reason.length, gone_a.wait()); + seen.second.store(true, .release); + const second: Request = .{ .prompt = &prompt, .max_tokens = 4 }; + var gone_b: Box = .{}; + try seen.engine.submit(3, &second, .{ .ctx = &gone_b, .event = Box.event }); // id 3, admission 1 + try std.testing.expectEqual(Reason.length, gone_b.wait()); + defer { + seen.first_runs.deinit(gpa); + seen.second_runs.deinit(gpa); + } + try std.testing.expect(seen.first_runs.items.len >= 1); + try std.testing.expect(seen.second_runs.items.len >= 1); // the second fill was sampled too + for (seen.second_runs.items) |run| try std.testing.expect(run != seen.first_runs.items[0]); // not the old collision + var status: api.Status = .{}; + seen.engine.status(&status, &.{}); // idle again + try std.testing.expect(status.fill_run == 0); +} + +// A cancelled filling request replaced by a queued one: the new fill carries its own marker, then idle. +test "fill_run changes when a cancelled fill is replaced by the queued request" { + const gpa = std.testing.allocator; + var cfg = try lanes.Config.init(gpa, .{ .exact_width = 8, .gpu_tokens = true, .hidden_rows = true }, 8, 7); + defer cfg.deinit(gpa); + var target: lanes.fake.Fake = .{ .gpa = gpa, .prefill_chunks = 4, .memory_lanes = 1 }; + defer target.deinit(); + var clock: lanes.fake.FixedClock = .{}; + var core = lanes.Engine.init(gpa, &cfg, target.stepped(), clock.clock()); + defer core.deinit(); + var host = LaneHost.init(gpa, std.testing.io, &core, .{ .lanes = 2 }); + try host.start(); + defer host.stop(); + const Seen = struct { + engine: Engine = undefined, + a_runs: std.ArrayList(u64) = .empty, + b_runs: std.ArrayList(u64) = .empty, + + // B's prompt alone is 12 tokens: a sample with that total belongs to the replacement, not to A. + fn hook(ctx: *anyopaque, _: *lanes.Stream, _: usize) void { + const seen: *@This() = @ptrCast(@alignCast(ctx)); + var status: api.Status = .{}; + seen.engine.status(&status, &.{}); + const total = status.fill_prompt_tokens orelse return; + if (total == 12) seen.b_runs.append(gpa, status.fill_run) catch {} else seen.a_runs.append(gpa, status.fill_run) catch {}; + } + }; + var seen: Seen = .{}; + seen.engine = host.engine(); + target.prefill_hook = Seen.hook; + target.prefill_hook_ctx = &seen; + const long_prompt = [_]u32{ 3, 1, 4, 1, 5, 9, 2, 6 }; + const longer_prompt = [_]u32{ 3, 1, 4, 1, 5, 9, 2, 6, 2, 5, 3, 8 }; + const first: Request = .{ .prompt = &long_prompt, .max_tokens = 100000 }; + var a: Box = .{}; + try seen.engine.submit(1, &first, .{ .ctx = &a, .event = Box.event }); + while (seen.a_runs.items.len == 0) std.Io.sleep(std.testing.io, .fromMilliseconds(1), .awake) catch {}; // A is filling + seen.engine.cancel(1); // a poll may never see idle: B takes the lane straight after + try std.testing.expectEqual(Reason.cancelled, a.wait()); + const queued: Request = .{ .prompt = &longer_prompt, .max_tokens = 100000 }; + var b = try gpa.create(Box); + defer gpa.destroy(b); + b.* = .{}; + try seen.engine.submit(2, &queued, .{ .ctx = b, .event = Box.event }); // admitted once the lane freed + var waited: usize = 0; + while (seen.b_runs.items.len == 0 and waited < 2000) { // B is filling: the hook samples its totals + std.Io.sleep(std.testing.io, .fromMilliseconds(1), .awake) catch {}; + waited += 1; + } + seen.engine.cancel(2); + try std.testing.expectEqual(Reason.cancelled, b.wait()); + defer { + seen.a_runs.deinit(gpa); + seen.b_runs.deinit(gpa); + } + try std.testing.expect(seen.b_runs.items.len >= 1); // the replacement fill was sampled + for (seen.b_runs.items) |run| try std.testing.expect(run != seen.a_runs.items[0]); // a new marker without an idle poll + var status: api.Status = .{}; + seen.engine.status(&status, &.{}); // both gone: idle, no fill counters at all + try std.testing.expect(status.fill_prompt_tokens == null and status.fill_tokens_left == null); + try std.testing.expect(status.fill_run == 0); +} diff --git a/zig/src/core/lanes/backend.zig b/zig/src/core/lanes/backend.zig index fe26d3f0039..8378c449003 100644 --- a/zig/src/core/lanes/backend.zig +++ b/zig/src/core/lanes/backend.zig @@ -100,6 +100,8 @@ pub const Backend = struct { held: ?*const fn (ptr: *anyopaque, s: *Stream, out: []u32) anyerror!void = null, /// `prefill` fills `Stream.prompt_rows` for a stream with `prompt_logprobs` (it then starts from 0). prompt_rows: bool = false, + /// The backend stores `Stream.fill_at` as its pass runs: the status reader may count its fill totals. + reports_fill: bool = false, /// The stream left the rounds: free its caches and held drafts. release: *const fn (ptr: *anyopaque, s: *Stream) void, }; diff --git a/zig/src/core/lanes/fake.zig b/zig/src/core/lanes/fake.zig index 9434736c46e..7827f286aca 100644 --- a/zig/src/core/lanes/fake.zig +++ b/zig/src/core/lanes/fake.zig @@ -76,12 +76,12 @@ pub const Fake = struct { } pub fn backend(x: *Fake) be.Backend { - return .{ .ptr = x, .vtable = &.{ .prefill = prefill, .first = first, .first_masked = firstMasked, .queue = queue, .read = read, .verify = verify, .keep = keep, .draft = draft, .features = features, .release = release, .first_row = firstRow, .alternatives = alternatives, .held = heldDrafts } }; + return .{ .ptr = x, .vtable = &.{ .prefill = prefill, .first = first, .first_masked = firstMasked, .queue = queue, .read = read, .verify = verify, .keep = keep, .draft = draft, .features = features, .release = release, .first_row = firstRow, .alternatives = alternatives, .held = heldDrafts, .reports_fill = true } }; } /// The same target filling its prompt a chunk a call (`prefill_chunks`), as a backend with `prefill_step`. pub fn stepped(x: *Fake) be.Backend { - return .{ .ptr = x, .vtable = &.{ .prefill = prefill, .prefill_step = prefillStep, .first = first, .queue = queue, .read = read, .verify = verify, .keep = keep, .draft = draft, .features = features, .release = release, .first_row = firstRow } }; + return .{ .ptr = x, .vtable = &.{ .prefill = prefill, .prefill_step = prefillStep, .first = first, .queue = queue, .read = read, .verify = verify, .keep = keep, .draft = draft, .features = features, .release = release, .first_row = firstRow, .reports_fill = true } }; } fn self(ptr: *anyopaque) *Fake { @@ -133,6 +133,7 @@ pub const Fake = struct { const chunks = if (x.prefill_chunks == 0) 1 else x.prefill_chunks; for (0..chunks) |chunk| { x.prefill_count += 1; + s.fill_at.store(@intCast(s.prompt_len * (chunk + 1) / chunks), .monotonic); if (x.prefill_hook) |hook| hook(x.prefill_hook_ctx.?, s, chunk); if (s.isCancelled()) return error.Cancelled; if (s.yields()) return error.Yielded; @@ -152,6 +153,7 @@ pub const Fake = struct { if (x.prefill_hook) |hook| hook(x.prefill_hook_ctx.?, s, l.filled); if (s.isCancelled()) return error.Cancelled; l.filled += 1; + s.fill_at.store(@intCast(s.prompt_len * l.filled / @max(1, x.prefill_chunks)), .monotonic); if (l.filled < @max(1, x.prefill_chunks)) return false; l.filling = false; try x.fillPrompt(l, s); diff --git a/zig/src/core/lanes/stream.zig b/zig/src/core/lanes/stream.zig index f028d10cc4f..cb17860fa84 100644 --- a/zig/src/core/lanes/stream.zig +++ b/zig/src/core/lanes/stream.zig @@ -156,6 +156,7 @@ pub const Stream = struct { decide: ?u32 = null, untaught: bool = false, cached: u32 = 0, // prompt tokens the backend restored from `reuse` (its prompt pass started there) + fill_at: std.atomic.Value(u32) = .init(0), // prompt tokens the pass has prefilled; the engine thread writes reuse_failed: bool = false, // the backend's restore of `reuse` failed: it prefilled from 0 context: std.ArrayList(u32) = .empty, pending: ?u32 = null, diff --git a/zig/src/families/glm/backend.zig b/zig/src/families/glm/backend.zig index 85b6f8c78e7..ec31cccfdb7 100644 --- a/zig/src/families/glm/backend.zig +++ b/zig/src/families/glm/backend.zig @@ -38,7 +38,7 @@ pub const Backend = struct { } pub fn backend(b: *Backend) be.Backend { - return .{ .ptr = b, .vtable = &.{ .prefill = prefill, .first = first, .queue = queue, .read = read, .verify = verify, .keep = keep, .draft = draft, .release = release } }; + return .{ .ptr = b, .vtable = &.{ .prefill = prefill, .first = first, .queue = queue, .read = read, .verify = verify, .keep = keep, .draft = draft, .release = release, .reports_fill = true } }; } /// Windows of up to 16 rows (drafted == plain at every width), the MTP head's chains, every stream in one forward. @@ -113,6 +113,7 @@ pub const Backend = struct { } else s.reuse_failed = true; } var next: usize = 0; // the planned chunk starts: a resumed pass cuts where a fresh one does + s.fill_at.store(at, .monotonic); // a restored prefix is done the moment it is restored while (at < prompt.len) { if (s.isCancelled()) return error.Cancelled; // the core releases the slot while (next < s.chunks.len and s.chunks[next] <= at) next += 1; @@ -120,8 +121,9 @@ pub const Backend = struct { const n = b.sl.chunkRows(at, end); try b.copyOut(i, at); try mirror.send(e, .chunk, &.{ i, at, n }); - try b.sl.chunk(i, at, n); + try b.sl.chunk(i, at, n); // the chunk's compute completes here: `at` is landed progress at += n; + s.fill_at.store(at, .monotonic); // the dashboard's prefill progress reads this between chunks if (std.mem.indexOfScalar(u32, s.reuse.marks, at) != null) if (s.reuse.hook) |k| k.at(k.ptr, s, at); } } diff --git a/zig/src/families/glm_dsa/backend.zig b/zig/src/families/glm_dsa/backend.zig index cdfe4969ff3..1bda04b6f6c 100644 --- a/zig/src/families/glm_dsa/backend.zig +++ b/zig/src/families/glm_dsa/backend.zig @@ -41,7 +41,7 @@ pub const Backend = struct { } pub fn backend(b: *Backend) be.Backend { - return .{ .ptr = b, .vtable = &.{ .prefill = prefill, .first = firstFn, .queue = queue, .read = read, .verify = verify, .keep = keep, .draft = draft, .release = release } }; + return .{ .ptr = b, .vtable = &.{ .prefill = prefill, .first = firstFn, .queue = queue, .read = read, .verify = verify, .keep = keep, .draft = draft, .release = release, .reports_fill = true } }; } /// Windows of up to 16 rows (each row's bits whatever shares its forward), MTP chains, streams in one forward. @@ -117,6 +117,7 @@ pub const Backend = struct { const n = @min(end - at, gpu.prompt_rows); if (try fl.chunk(e, i, at, n, false)) |t| b.first[i] = t; at += n; + s.fill_at.store(at, .monotonic); // fl.chunk waits on rank 0: `at` is landed progress if (std.mem.indexOfScalar(u32, s.reuse.marks, at) != null) if (s.reuse.hook) |k| k.at(k.ptr, s, at); } } diff --git a/zig/src/families/nemotron/backend.zig b/zig/src/families/nemotron/backend.zig index f52e5a4a6cd..476b8439b24 100644 --- a/zig/src/families/nemotron/backend.zig +++ b/zig/src/families/nemotron/backend.zig @@ -121,19 +121,7 @@ pub const Metal = struct { } pub fn backend(self: *Metal) be.Backend { - return .{ .ptr = self, .vtable = &.{ - .prefill = prefillFn, - .first = firstFn, - .first_masked = grammar.firstMasked, - .queue = queueFn, - .read = readFn, - .verify = verifyFn, - .keep = keepFn, - .draft = draftFn, - .release = releaseFn, - .alternatives = alternativesFn, - .held = grammar.held, - } }; + return .{ .ptr = self, .vtable = &.{ .prefill = prefillFn, .first = firstFn, .first_masked = grammar.firstMasked, .queue = queueFn, .read = readFn, .verify = verifyFn, .keep = keepFn, .draft = draftFn, .release = releaseFn, .alternatives = alternativesFn, .held = grammar.held, .reports_fill = true } }; } /// The facts the round loop reads at setup (Python's NemotronH attributes), with this engine's own timings. @@ -312,6 +300,7 @@ pub const Metal = struct { s.cached = @intCast(at); s.reuse_failed = at == 0; } + s.fill_at.store(@intCast(at), .monotonic); // a restored prefix is done the moment it is restored // a command buffer a chunk, each committed before the one ahead of it is waited on, so the GPU keeps a chunk queued var k: usize = 0; while (at < ids.len) { @@ -324,6 +313,7 @@ pub const Metal = struct { try self.submit(.prefill, self.next, Chunks{ .n = ids.len, .c = c, .at = at, .rows = rows }); while (self.flights.items.len > 1) try self.land(); at += rows; + s.fill_at.store(@intCast(at - rows), .monotonic); // landed tokens only: the newest chunk is still queued on the GPU if (s.reuse.hook) |hk| if (std.mem.indexOfScalar(u32, s.reuse.marks, @intCast(at)) != null) hk.at(hk.ptr, s, @intCast(at)); } if (self.trace and c.decide != lesson_route.none) try self.traceLessons(c); diff --git a/zig/src/families/qwen3_5/backend.zig b/zig/src/families/qwen3_5/backend.zig index 55fc09eecb8..8fd6c179e00 100644 --- a/zig/src/families/qwen3_5/backend.zig +++ b/zig/src/families/qwen3_5/backend.zig @@ -50,7 +50,7 @@ pub const Metal = struct { } pub fn backend(self: *Metal) be.Backend { - return .{ .ptr = self, .vtable = &.{ .prefill = prefillFn, .first = firstFn, .first_masked = firstMaskedFn, .queue = queueFn, .read = readFn, .verify = verifyFn, .keep = keepFn, .draft = draftFn, .release = releaseFn } }; + return .{ .ptr = self, .vtable = &.{ .prefill = prefillFn, .first = firstFn, .first_masked = firstMaskedFn, .queue = queueFn, .read = readFn, .verify = verifyFn, .keep = keepFn, .draft = draftFn, .release = releaseFn, .reports_fill = true } }; } fn cast(ptr: *anyopaque) *Metal { @@ -79,6 +79,7 @@ pub const Metal = struct { }; try fwd.run(self.model, &self.scratch, &.{.{ .cache = cache, .rows = end - at }}, ids[at..end], false, .last); at = end; + stream.fill_at.store(@intCast(at), .monotonic); // fwd.run waits: `at` is landed progress } try self.caches.put(self.gpa, stream, cache); } diff --git a/zig/src/native/cache_fit.zig b/zig/src/native/cache_fit.zig index 1c23bc5a5a4..36e8a332162 100644 --- a/zig/src/native/cache_fit.zig +++ b/zig/src/native/cache_fit.zig @@ -44,6 +44,22 @@ pub fn footprint() ?u64 { return info[9]; } +/// The Mac hosts' session peak: the footprint's high-water mark since the last `reset_peak`. +var host_peak: std.atomic.Value(u64) = .init(0); + +/// The mark after a reading: a reset restarts it at the footprint now, else it climbs to the reading's most. +fn peakAfter(mark: *std.atomic.Value(u64), reading: u64, reset_peak: bool) u64 { + if (reset_peak) mark.store(reading, .monotonic) else _ = mark.fetchMax(reading, .monotonic); + return mark.load(.monotonic); +} + +/// A Mac host's memory counts from the process footprint; a zero limit means the family has none configured. +pub fn hostMemory(limit_bytes: u64, reset_peak: bool) ?api.Memory { + const active = footprint() orelse return null; + const peak = peakAfter(&host_peak, active, reset_peak); + return .{ .active = active, .cache = 0, .peak = peak, .pinned = 0, .limit = if (limit_bytes > 0) limit_bytes else null }; +} + /// The cache plan: `gib` if it fits (or `over`), else what 70% of RAM leaves up to 16 GiB (no reading: `spare` for it). pub fn budget(gib: ?f64, over: bool, spare: u64, a: std.mem.Allocator, why: *[]const u8, rank: []const u8) !api.PromptCachePlan { return budgetBeside(gib, over, spare, 0, a, why, rank); @@ -130,7 +146,38 @@ test "a load fits only while it and the margin stay inside 70% of RAM" { test "the OS readings: RAM and this process's footprint" { if (builtin.os.tag != .macos) return error.SkipZigTest; - const r = ram() orelse return error.NoRam; - const p = footprint() orelse return error.NoFootprint; + const r = ram() orelse return error.SkipZigTest; + const p = footprint() orelse return error.SkipZigTest; try std.testing.expect(r >= 8 * GiB and p > 0 and p < r); } + +test "a host's memory counts keep the footprint, its measured peak and the limit apart" { + if (builtin.os.tag != .macos) return error.SkipZigTest; + const limit = 235 * GiB; + const m = hostMemory(limit, false) orelse return error.SkipZigTest; + try std.testing.expect(m.active > 0); // this test process's own footprint + try std.testing.expect(m.peak >= m.active); // the high-water mark covers now + try std.testing.expectEqual(limit, m.limit.?); + try std.testing.expectEqual(@as(u64, 0), m.cache); + try std.testing.expectEqual(@as(u64, 0), m.pinned); + const after_reset = hostMemory(limit, true).?; // a reset starts a new peak at the footprint now + try std.testing.expectEqual(after_reset.active, after_reset.peak); // the reset's own reading, not an older mark + const again = hostMemory(limit, false).?; + try std.testing.expect(again.peak >= again.active); // the mark covers the footprint now +} + +test "the high-water mark rises, holds, resets and the next read climbs from the reset" { + var mark: std.atomic.Value(u64) = .init(0); + try std.testing.expectEqual(@as(u64, 100), peakAfter(&mark, 100, false)); // the first read is the mark + try std.testing.expectEqual(@as(u64, 100), peakAfter(&mark, 60, false)); // a lower reading leaves the mark + try std.testing.expectEqual(@as(u64, 120), peakAfter(&mark, 120, false)); // a higher one raises it + try std.testing.expectEqual(@as(u64, 40), peakAfter(&mark, 40, true)); // a reset starts the mark at the reading + try std.testing.expectEqual(@as(u64, 50), peakAfter(&mark, 50, false)); // the next read reports 50, not 120 + try std.testing.expectEqual(@as(u64, 50), peakAfter(&mark, 45, false)); // and it holds against lower readings + try std.testing.expectEqual(@as(u64, 70), peakAfter(&mark, 70, false)); // then climbs again +} + +test "a host without a footprint reading reports no memory rather than zeros" { + if (builtin.os.tag == .macos) return error.SkipZigTest; // on macOS the reading always works + try std.testing.expect(hostMemory(1 << 30, false) == null); +} diff --git a/zig/src/native/cuda_bound.zig b/zig/src/native/cuda_bound.zig index 40977dfa508..2fd155bcebd 100644 --- a/zig/src/native/cuda_bound.zig +++ b/zig/src/native/cuda_bound.zig @@ -109,6 +109,7 @@ pub fn vtable(comptime H: type, v: be.Backend.VTable) be.Backend.VTable { } }.f else null, .prompt_rows = v.prompt_rows, + .reports_fill = v.reports_fill, // the family's fill-progress reporting reaches the CUDA wrapper .release = struct { fn f(p: *anyopaque, s: *lanes.Stream) void { const x = H.bind(p); diff --git a/zig/src/native/flashnext_host.zig b/zig/src/native/flashnext_host.zig index cdba9b907b4..4ce6e09a357 100644 --- a/zig/src/native/flashnext_host.zig +++ b/zig/src/native/flashnext_host.zig @@ -44,6 +44,7 @@ pub const Host = struct { prefill_at: i96 = 0, live_prompt: u64 = 0, // the running reply's prompt tokens, for status (which never reads the job: finish frees it) live_generated: u64 = 0, + prefilling: bool = false, // the engine thread's prompt pass is running (status reads it under this lock) cache: ?pc.Store = null, // kept prompt states (engine thread only); null: no reuse (rank 1, a zero budget) prompt: []const u32 = &.{}, // the request in the engine (speed-up mode names kept states by its tokens) saved: std.ArrayList(u32) = .empty, // this request's marks the cache kept (speed-up: rank 1 drops the others) @@ -158,11 +159,12 @@ pub const Host = struct { .preemptions = 0, .streams = n, .generation_tokens = generation_tokens, + .fill_unknown = h.prefilling, // this backend reports no fill counters: the page says so, not idle }; } - fn memoryFn(_: *anyopaque, _: bool) ?api.Memory { - return null; + fn memoryFn(_: *anyopaque, reset_peak: bool) ?api.Memory { + return cache_fit.hostMemory(0, reset_peak); // the process footprint; no configured load limit } fn emit(job: *Job, event: api.Event) void { @@ -210,11 +212,13 @@ pub const Host = struct { h.running = job; h.live_prompt = job.request.prompt.len; h.live_generated = 0; + h.prefilling = true; // its prompt pass starts: status shows an unknown-progress fill until it reports h.cancels.clearRetainingCapacity(); // a cancel for an id no longer queued or running h.unlock(); h.serve(job); h.lock(); h.running = null; + h.prefilling = false; h.live_generated = 0; const idle = h.queued.items.len == 0; h.unlock(); @@ -245,6 +249,7 @@ pub const Host = struct { h.lock(); if (done > c.job.began) h.prefill_rate = @as(f64, @floatFromInt(c.job.request.prompt.len - c.job.cached)) / (@as(f64, @floatFromInt(done - c.job.began)) / 1e9); h.prefill_at = done; + h.prefilling = false; // the pass reported: status stops showing an unknown-progress fill c.job.prefilled = done; h.unlock(); c.job.prefill_sent = true; diff --git a/zig/src/native/glm_dsa_host.zig b/zig/src/native/glm_dsa_host.zig index 2a6d28d3317..26091a12659 100644 --- a/zig/src/native/glm_dsa_host.zig +++ b/zig/src/native/glm_dsa_host.zig @@ -6,6 +6,7 @@ const tf = @import("tensorfold"); const lanes = tf.lanes; const g = tf.glm_dsa; const Allocator = std.mem.Allocator; +const cache_fit = @import("cache_fit.zig"); pub const Host = struct { gpa: Allocator, @@ -15,6 +16,7 @@ pub const Host = struct { wall: lanes.backend.WallClock, core: lanes.Engine, host: api.LaneHost, + limit: u64 = 0, // the configured load limit, for the memory counts cache: ?api.prompt_cache.Store = null, // rank 0's kept prompt states (rank 1 holds the same ids) warm: mtl.keepalive.Target, follower: ?std.Thread = null, @@ -24,6 +26,12 @@ pub const Host = struct { } }; +/// The host's memory counts: `cache_fit.hostMemory` under this engine's configured load limit. +fn readMemory(ctx: ?*anyopaque, reset_peak: bool) ?api.Memory { + const h: *Host = @ptrCast(@alignCast(ctx.?)); + return cache_fit.hostMemory(h.limit, reset_peak); +} + fn words(_: ?*anyopaque, err: anyerror) ?[]const u8 { return switch (err) { error.GreedyOnly => "the native GLM-5.3 engine decodes greedily only: send temperature 0", @@ -46,6 +54,7 @@ pub fn open(gpa: Allocator, io: std.Io, dir: []const u8, window: u32, speed_up: h.gpa = gpa; h.e = e; h.follower = null; + h.limit = limit; h.back = try g.backend.Backend.init(gpa, e); errdefer h.back.deinit(); if (e.rank() == 0) try h.back.time(io); @@ -55,6 +64,7 @@ pub fn open(gpa: Allocator, io: std.Io, dir: []const u8, window: u32, speed_up: h.core = lanes.Engine.init(gpa, &h.cfg, h.back.backend(), h.wall.clock()); errdefer h.core.deinit(); h.host = api.LaneHost.init(gpa, io, &h.core, .{ .name = "glm-dsa-zig", .lanes = streams, .context_window = window, .prefill_step = g.gpu.prompt_rows, .greedy_only = true }); + h.host.memory = .{ .ctx = h, .read = readMemory }; h.host.explain = .{ .text = words }; h.cache = null; const used = e.device.allocated(); diff --git a/zig/src/native/glm_host.zig b/zig/src/native/glm_host.zig index dab379dbf33..a3392fbd4fc 100644 --- a/zig/src/native/glm_host.zig +++ b/zig/src/native/glm_host.zig @@ -6,6 +6,7 @@ const tf = @import("tensorfold"); const lanes = tf.lanes; const glm = tf.glm; const ge = glm.engine; +const cache_fit = @import("cache_fit.zig"); const Allocator = std.mem.Allocator; /// The warm-up reply's draft depth: every rank of a pair pays a process's first-round costs at the same step. @@ -65,6 +66,12 @@ fn cacheBudget(eng: *const ge.Engine, gib: ?f64) u64 { return if (limit > used) @min(want, limit - used) else 0; } +/// The host's memory counts: `cache_fit.hostMemory` with this engine's configured load limit. +fn readMemory(ctx: ?*anyopaque, reset_peak: bool) ?api.Memory { + const h: *Host = @ptrCast(@alignCast(ctx.?)); + return cache_fit.hostMemory(h.eng.limit.bytes, reset_peak); +} + /// Learned states under `root` by checkpoint, split, chip, OS build, kernel sources and a probe's prompt-pass bits. fn learnedStates(gpa: Allocator, eng: *const ge.Engine, sl: *glm.slots.Slots, root: []const u8, cap: u64) !api.prompt_imprint.Imprint { var h = std.hash.Wyhash.init(0x62); @@ -105,6 +112,7 @@ pub fn open(gpa: Allocator, io: std.Io, dir: []const u8, window: u32, speed_up: errdefer h.core.deinit(); const serves = @min(window, glm.pool.capacity(&h.slots) -| (glm.state.max_rows + 1)); // prompt + reply a stream's caches hold beside its last window (a pool keeps whole blocks) h.host = api.LaneHost.init(gpa, io, &h.core, .{ .name = "glm-zig", .lanes = n, .context_window = serves, .prefill_step = eng.chunk_rows, .greedy_only = true, .admit = if (h.slots.pool != null) .{ .ctx = &h.back, .fits = glm.backend.Backend.fits } else null }); + h.host.memory = .{ .ctx = h, .read = readMemory }; h.cache = null; const budget = cacheBudget(eng, cache_gib); if (!eng.followsPeer() and budget > 0) { diff --git a/zig/src/native/metal.zig b/zig/src/native/metal.zig index 39fe5314084..82829285983 100644 --- a/zig/src/native/metal.zig +++ b/zig/src/native/metal.zig @@ -58,6 +58,11 @@ fn modelContext(a: Allocator, io: std.Io, dir: []const u8) i64 { return if (limit == .integer and limit.integer > 0) limit.integer else 0; } +/// The host's memory counts: `cache_fit.hostMemory` from the process footprint (no configured load limit). +fn readMemory(_: ?*anyopaque, reset_peak: bool) ?api.Memory { + return cache_fit.hostMemory(0, reset_peak); +} + /// One loaded model behind the lane host: everything the engine thread reads lives here. const Host = struct { gpa: Allocator, @@ -162,6 +167,7 @@ pub fn open(a: Allocator, gpa: Allocator, io: std.Io, o: api.Open, problem: *[]c h.core = lanes.Engine.init(gpa, &h.cfg, h.metal.backend(), h.clock.clock()); errdefer h.core.deinit(); h.host = api.LaneHost.init(gpa, io, &h.core, .{ .lanes = o.lanes, .context_window = @intCast(@max(window, 0)), .prefill_step = step, .structures = true }); + h.host.memory = .{ .ctx = h, .read = readMemory }; h.round = .{ .depth = 8 }; h.cache = null; var why: []const u8 = ""; diff --git a/zig/src/native/qwen27_lanes.zig b/zig/src/native/qwen27_lanes.zig index e09a508a8cc..7f4d0cb8887 100644 --- a/zig/src/native/qwen27_lanes.zig +++ b/zig/src/native/qwen27_lanes.zig @@ -117,7 +117,7 @@ pub const Metal = struct { const refill = slots.refill; pub fn backend(b: *Metal) be.Backend { - return .{ .ptr = b, .vtable = &.{ .prefill = prefillFn, .first = firstFn, .queue = queueFn, .read = readFn, .verify = verifyFn, .keep = keepFn, .draft = draftFn, .probabilities = probabilitiesFn, .tree = treeFn, .release = releaseFn } }; + return .{ .ptr = b, .vtable = &.{ .prefill = prefillFn, .first = firstFn, .queue = queueFn, .read = readFn, .verify = verifyFn, .keep = keepFn, .draft = draftFn, .probabilities = probabilitiesFn, .tree = treeFn, .release = releaseFn, .reports_fill = true } }; } /// What the round loop reads at setup: slot 0's stream drafts trees; every stream verifies copies. diff --git a/zig/src/native/qwen27_served.zig b/zig/src/native/qwen27_served.zig index 09da59e53f4..ad186f79e78 100644 --- a/zig/src/native/qwen27_served.zig +++ b/zig/src/native/qwen27_served.zig @@ -80,6 +80,11 @@ fn keepEnd(store: *pc.Store, gpa: Allocator, s: *lanes.Stream, stands: u32) void _ = store.keepBorn(tokens, prompt, stands, s, s.chunks, spans); } +/// The host's memory counts: `cache_fit.hostMemory` from the process footprint (no configured load limit). +fn readMemory(_: ?*anyopaque, reset_peak: bool) ?api.Memory { + return cache_fit.hostMemory(0, reset_peak); +} + /// The words for a request the engine refuses. fn words(_: ?*anyopaque, err: anyerror) ?[]const u8 { return switch (err) { @@ -285,6 +290,7 @@ pub fn attach(gpa: Allocator, io: std.Io, model: *q.model.Model, drafter: ?*q.df h.core = lanes.Engine.init(gpa, &h.cfg, h.back.backend(), h.clock.clock()); errdefer h.core.deinit(); h.host = api.LaneHost.init(gpa, io, &h.core, .{ .name = "qwen27", .lanes = slots, .context_window = capacity, .prefill_step = 128 }); + h.host.memory = .{ .ctx = h, .read = readMemory }; h.host.explain = .{ .text = words }; h.host.decoded_rows = true; // a reply's rows prefill with the bits decoding gave them, with the cache on or off // a lone greedy request takes the serial loop on tensor units, where it is faster (TF_QWEN27_LANES overrides) diff --git a/zig/src/native/qwen27_slots.zig b/zig/src/native/qwen27_slots.zig index 7cdd191d8cc..d3f882624ec 100644 --- a/zig/src/native/qwen27_slots.zig +++ b/zig/src/native/qwen27_slots.zig @@ -65,6 +65,7 @@ pub fn prefill(b: *Metal, s: *lanes.Stream, slot: u32) !void { if (b.ringOf(slot)) |g| try ringChunk(b, g, part.len); } at = end; + s.fill_at.store(@intCast(at), .monotonic); // a prompt chunk waits: `at` is landed progress if (std.mem.indexOfScalar(u32, s.reuse.marks, @intCast(at)) != null) if (s.reuse.hook) |k| k.at(k.ptr, s, @intCast(at)); } } diff --git a/zig/src/native/qwen35.zig b/zig/src/native/qwen35.zig index c1dab90e198..49e3060deb8 100644 --- a/zig/src/native/qwen35.zig +++ b/zig/src/native/qwen35.zig @@ -5,6 +5,12 @@ const api = @import("engine_api"); const tf = @import("tensorfold"); const q = tf.qwen35; const lanes = tf.lanes; +const cache_fit = @import("cache_fit.zig"); + +/// The host's memory counts: `cache_fit.hostMemory` from the process footprint (no configured load limit). +fn readMemory(_: ?*anyopaque, reset_peak: bool) ?api.Memory { + return cache_fit.hostMemory(0, reset_peak); +} const Host = struct { gpa: std.mem.Allocator, @@ -54,6 +60,7 @@ pub fn open(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, o: api.Ope h.core = lanes.Engine.init(gpa, &h.config, h.metal.backend(), h.clock.clock()); errdefer h.core.deinit(); h.host = api.LaneHost.init(gpa, io, &h.core, .{ .lanes = o.lanes, .context_window = @intCast(window), .prefill_step = chunk, .structures = true }); + h.host.memory = .{ .ctx = h, .read = readMemory }; h.warm = .{ .queue = h.metal.model.queue }; h.host.keepalive_target = .{ .ctx = &h.warm, .tick = mtl.keepalive.Target.tick }; try h.host.start(); diff --git a/zig/src/server/dashboard.html b/zig/src/server/dashboard.html index e56e25b0a0c..f6ca9264ced 100644 --- a/zig/src/server/dashboard.html +++ b/zig/src/server/dashboard.html @@ -58,6 +58,8 @@