From db48f2b4b817d529b675fc421fe70a7ce6cb38d7 Mon Sep 17 00:00:00 2001
From: ashhart <71890694+ashhart@users.noreply.github.com>
Date: Fri, 20 Nov 2026 10:07:42 +0000
Subject: [PATCH 01/32] sessions: roll back slot when restore cannot queue
---
zig/src/sessions/store.zig | 5 +++++
zig/src/sessions/store_failure_test.zig | 10 ++++++++++
2 files changed, 15 insertions(+)
diff --git a/zig/src/sessions/store.zig b/zig/src/sessions/store.zig
index b8dfdbe6417..576099c9447 100644
--- a/zig/src/sessions/store.zig
+++ b/zig/src/sessions/store.zig
@@ -202,7 +202,12 @@ pub const Store = struct {
const e = s.index.get(id);
if (!e.extra.file) return error.NotOnDisk;
if (slot.len != 0) return error.SlotNotEmpty;
+ const over = slot.over;
try slot.ensure(e.pos);
+ errdefer {
+ _ = slot.truncate(0) catch unreachable;
+ slot.over = over;
+ }
const j = try s.gpa.create(Job);
j.* = .{ .kind = .restore, .entry = id, .slot = slot.id };
errdefer j.deinit(s.gpa);
diff --git a/zig/src/sessions/store_failure_test.zig b/zig/src/sessions/store_failure_test.zig
index bf04853023f..67333441382 100644
--- a/zig/src/sessions/store_failure_test.zig
+++ b/zig/src/sessions/store_failure_test.zig
@@ -253,9 +253,19 @@ test "Ownership rollback: a restore or park the tier thread cannot queue leaves
try d.by_key.put(a, key, 0);
const slot = try pool.newSlot(8);
defer _ = slot.releaseAll() catch {};
+ slot.reserve(1);
+ try slot.ensure(ids.len);
+ _ = try slot.truncate(0);
+ try std.testing.expectEqual(@as(u32, 1), slot.over);
+ const reserved = pool.reserved;
var full = std.testing.FailingAllocator.init(a, .{ .fail_index = 0 });
s.runner.?.gpa = full.allocator(); // the tier queue's append fails while its thread runs
try std.testing.expectError(error.OutOfMemory, s.beginRestore(filed, slot));
+ try std.testing.expectEqual(@as(u32, 0), slot.len);
+ try std.testing.expectEqual(@as(u32, 1), slot.over);
+ try std.testing.expectEqual(@as(?u32, 1), slot.quota);
+ try std.testing.expectEqual(reserved, pool.reserved);
+ try slot.ensure(ids.len);
const restores = s.pending.items.len;
s.pending.clearRetainingCapacity(); // if the rollback regresses this holds the freed job: dropped unread, so deinit cannot wait on it
var held: Plain = .{};
From 188e5dec2ac11562beea308726f710a8222ba131 Mon Sep 17 00:00:00 2001
From: ashhart <71890694+ashhart@users.noreply.github.com>
Date: Fri, 20 Nov 2026 10:10:15 +0000
Subject: [PATCH 02/32] kimi: reject invalid full attention layer indices
---
zig/src/families/kimi_k3/config.zig | 5 ++++-
zig/src/families/kimi_k3/config_test.zig | 8 ++++++++
2 files changed, 12 insertions(+), 1 deletion(-)
diff --git a/zig/src/families/kimi_k3/config.zig b/zig/src/families/kimi_k3/config.zig
index 9137f2edd66..7c11e65858e 100644
--- a/zig/src/families/kimi_k3/config.zig
+++ b/zig/src/families/kimi_k3/config.zig
@@ -125,7 +125,10 @@ pub fn parse(gpa: std.mem.Allocator, json: []const u8) !Config {
c.conv = @intCast(o.get("short_conv_kernel_size").?.integer);
if (o.get("gate_lower_bound")) |v| c.lower_bound = @floatCast(v.float);
c.full_attn = std.StaticBitSet(128).empty;
- for (o.get("full_attn_layers").?.array.items) |v| c.full_attn.set(@intCast(v.integer - 1));
+ for (o.get("full_attn_layers").?.array.items) |v| {
+ if (v != .integer or v.integer < 1 or v.integer > c.layers) return error.BadConfig;
+ c.full_attn.set(@intCast(v.integer - 1));
+ }
}
if (c.layers > 128) return error.TooManyLayers;
return c;
diff --git a/zig/src/families/kimi_k3/config_test.zig b/zig/src/families/kimi_k3/config_test.zig
index 8f915f1e654..8ec7aaed8d3 100644
--- a/zig/src/families/kimi_k3/config_test.zig
+++ b/zig/src/families/kimi_k3/config_test.zig
@@ -18,6 +18,14 @@ test "K3 release config retains every previous default" {
try std.testing.expectEqual(@as(u32, 2048), k31.dsa.?.topk);
}
+test "K3 rejects full attention layer indices outside its configured depth" {
+ inline for (.{ "0", "94" }) |bad| {
+ const changed = try std.mem.replaceOwned(u8, std.testing.allocator, @embedFile("fixtures/k3-config.json"), "\"full_attn_layers\": [\n 4,", "\"full_attn_layers\": [\n " ++ bad ++ ",");
+ defer std.testing.allocator.free(changed);
+ try std.testing.expectError(error.BadConfig, config.parse(std.testing.allocator, changed));
+ }
+}
+
test "K3.1 refuses unsupported index geometry and cadence instead of ignoring them" {
const cases = .{
.{ "\"index_topk\": 2048", "\"index_topk\": 2047" },
From fb525dbe8da8c205c91e49b4ffbaa8b4e17337fc Mon Sep 17 00:00:00 2001
From: ashhart <71890694+ashhart@users.noreply.github.com>
Date: Fri, 20 Nov 2026 10:16:26 +0000
Subject: [PATCH 03/32] glm: stop prefill at prompt cache marks
---
zig/src/families/glm/prefill.zig | 51 +++++++++++++++++++++++++++++++-
1 file changed, 50 insertions(+), 1 deletion(-)
diff --git a/zig/src/families/glm/prefill.zig b/zig/src/families/glm/prefill.zig
index 9962814fcc1..1621792930e 100644
--- a/zig/src/families/glm/prefill.zig
+++ b/zig/src/families/glm/prefill.zig
@@ -4,7 +4,7 @@ const Stream = @import("lanes").Stream;
/// Keep decode latency bounded when a prompt shares the GPU; solo passes retain the engine's normal chunk size.
pub const decode_rows: u32 = 256;
-pub const State = struct { stream: *Stream, slot: u32, at: u32 = 0, next: usize = 0 };
+pub const State = struct { stream: *Stream, slot: u32, at: u32 = 0, next: usize = 0, reuse_next: usize = 0 };
/// `b` is the real backend or a fake engine at the same prepare/chunk/finish boundary. `_: u32` keeps its 2048 grid.
pub fn step(b: anytype, s: *Stream, _: u32) !bool {
@@ -18,7 +18,9 @@ pub fn step(b: anytype, s: *Stream, _: u32) !bool {
const prompt = s.prompt();
if (p.at < prompt.len) {
while (p.next < s.chunks.len and s.chunks[p.next] <= p.at) p.next += 1;
+ while (p.reuse_next < s.reuse.marks.len and s.reuse.marks[p.reuse_next] <= p.at) p.reuse_next += 1;
var end: u32 = @intCast(@min(if (p.next < s.chunks.len) s.chunks[p.next] else prompt.len, prompt.len));
+ if (p.reuse_next < s.reuse.marks.len) end = @min(end, s.reuse.marks[p.reuse_next]);
if (b.decoding()) end = @min(end, p.at + @min(decode_rows, @as(u32, @intCast(prompt.len)) - p.at));
const n = b.promptRows(p.at, end);
if (n == 0 or n > end - p.at) return error.ChunkOutOfStep;
@@ -33,3 +35,50 @@ pub fn step(b: anytype, s: *Stream, _: u32) !bool {
_ = b.filling.remove(s);
return true;
}
+
+test "glm prefill: cache marks bound otherwise uncut chunks" {
+ const Backend = struct {
+ gpa: std.mem.Allocator = std.testing.allocator,
+ filling: std.AutoHashMapUnmanaged(*Stream, State) = .empty,
+ history: std.ArrayList(u32) = .empty,
+
+ fn beginPrompt(_: *@This(), s: *Stream) !State {
+ return .{ .stream = s, .slot = 0 };
+ }
+ fn decoding(_: *const @This()) bool {
+ return false;
+ }
+ fn promptRows(_: *const @This(), at: u32, end: u32) u32 {
+ return end - at;
+ }
+ fn chunkPrompt(b: *@This(), s: *Stream, _: u32, at: u32, n: u32) !void {
+ try b.history.appendSlice(std.testing.allocator, s.prompt()[at .. at + n]);
+ }
+ fn finishPrompt(_: *@This(), _: *Stream) !void {}
+ fn abortPrompt(_: *@This(), _: *Stream) void {}
+ };
+ const Marks = struct {
+ at: [2]u32 = undefined,
+ n: usize = 0,
+ fn hit(p: *anyopaque, _: *Stream, at: u32) void {
+ const m: *@This() = @ptrCast(@alignCast(p));
+ m.at[m.n] = at;
+ m.n += 1;
+ }
+ };
+ var b: Backend = .{};
+ defer b.filling.deinit(std.testing.allocator);
+ defer b.history.deinit(std.testing.allocator);
+ const ids = [_]u32{ 3, 1, 4, 1, 5, 9, 2, 6, 5 };
+ var s = try Stream.init(std.testing.allocator, .{ .id = "marks", .prompt = &ids, .max_new = 1 });
+ defer s.deinit(std.testing.allocator);
+ var marks: Marks = .{};
+ s.reuse = .{ .marks = &.{ 3, 7 }, .hook = .{ .ptr = &marks, .at = Marks.hit } };
+ try std.testing.expect(!try step(&b, &s, 0));
+ try std.testing.expectEqual(@as(u32, 3), s.fill_at.load(.monotonic));
+ try std.testing.expect(!try step(&b, &s, 0));
+ try std.testing.expectEqual(@as(u32, 7), s.fill_at.load(.monotonic));
+ try std.testing.expect(try step(&b, &s, 0));
+ try std.testing.expectEqualSlices(u32, &.{ 3, 7 }, &marks.at);
+ try std.testing.expectEqualSlices(u32, &ids, b.history.items);
+}
From ed143198da36a709f632a1877c85c3ecf191356e Mon Sep 17 00:00:00 2001
From: ashhart <71890694+ashhart@users.noreply.github.com>
Date: Fri, 20 Nov 2026 10:24:08 +0000
Subject: [PATCH 04/32] hip: skip consumed marks on resumed prefill
---
zig/src/hip_serve/backend.zig | 9 +++++++++
1 file changed, 9 insertions(+)
diff --git a/zig/src/hip_serve/backend.zig b/zig/src/hip_serve/backend.zig
index 52d21d4955b..dc1c7d5f24a 100644
--- a/zig/src/hip_serve/backend.zig
+++ b/zig/src/hip_serve/backend.zig
@@ -22,6 +22,7 @@ pub const Fill = struct {
pub fn init(from: usize, marks: []const u32) Fill {
var f: Fill = .{ .at = from, .count = @min(marks.len, 16) };
@memcpy(f.stops[0..f.count], marks[0..f.count]);
+ while (f.next < f.count and f.stops[f.next] <= from) f.next += 1;
return f;
}
@@ -378,6 +379,14 @@ test "a prompt pass stops at its cuts, then the prompt's end" {
try std.testing.expectEqual(@as(usize, 1000), f.limit(1000));
}
+test "a resumed prompt pass skips cuts at and before its restored row" {
+ var f = Fill.init(64, &.{ 32, 64, 128 });
+ try std.testing.expectEqual(@as(usize, 128), f.limit(1000));
+ try std.testing.expect(!f.cut(64));
+ try std.testing.expect(f.cut(128));
+ try std.testing.expectEqual(@as(usize, 1000), f.limit(1000));
+}
+
test "drawn tokens are read back by handle while the ring holds them" {
var d: Drawn = .{};
try std.testing.expectEqual(@as(u64, 0), d.take(7));
From 98394106d8f4ba6bc337ae11bdc9902512ac8f5f Mon Sep 17 00:00:00 2001
From: ashhart <71890694+ashhart@users.noreply.github.com>
Date: Fri, 20 Nov 2026 10:34:12 +0000
Subject: [PATCH 05/32] glm dsa: publish restored prefill progress
---
zig/src/families/glm_dsa/backend.zig | 22 +++++++++++++++++++++-
1 file changed, 21 insertions(+), 1 deletion(-)
diff --git a/zig/src/families/glm_dsa/backend.zig b/zig/src/families/glm_dsa/backend.zig
index b853f8216f3..06d9982039c 100644
--- a/zig/src/families/glm_dsa/backend.zig
+++ b/zig/src/families/glm_dsa/backend.zig
@@ -85,6 +85,11 @@ pub const Backend = struct {
return null;
}
+ fn startProgress(s: *Stream, at: u32) void {
+ s.cached = at;
+ s.fill_at.store(at, .monotonic);
+ }
+
fn prefill(ptr: *anyopaque, s: *Stream) anyerror!void {
const b = self(ptr);
const e = b.e;
@@ -103,9 +108,9 @@ pub const Backend = struct {
if (k.at < prompt.len) {
try fl.restore(e, i, k.id);
at = k.at;
- s.cached = at;
} else s.reuse_failed = true;
}
+ startProgress(s, at);
var next: usize = 0;
var mark: usize = 0;
while (at < prompt.len) {
@@ -277,3 +282,18 @@ pub const Backend = struct {
return @as(f64, @floatFromInt(t0.durationTo(std.Io.Timestamp.now(io, .awake)).nanoseconds)) / 1e6;
}
};
+
+test "glm_dsa prefill: a restored row seeds landed progress" {
+ const ids: [2049]u32 = @splat(1);
+ var resumed = try Stream.init(std.testing.allocator, .{ .id = "resumed", .prompt = &ids, .max_new = 1 });
+ defer resumed.deinit(std.testing.allocator);
+ Backend.startProgress(&resumed, 2048);
+ try std.testing.expectEqual(@as(u32, 2048), resumed.cached);
+ try std.testing.expectEqual(@as(u32, 2048), resumed.fill_at.load(.monotonic));
+
+ var fresh = try Stream.init(std.testing.allocator, .{ .id = "fresh", .prompt = &ids, .max_new = 1 });
+ defer fresh.deinit(std.testing.allocator);
+ Backend.startProgress(&fresh, 0);
+ try std.testing.expectEqual(@as(u32, 0), fresh.cached);
+ try std.testing.expectEqual(@as(u32, 0), fresh.fill_at.load(.monotonic));
+}
From 57b2138fa3474cca91989ca2d55b83c3cc3801bc Mon Sep 17 00:00:00 2001
From: ashhart <71890694+ashhart@users.noreply.github.com>
Date: Fri, 20 Nov 2026 10:35:34 +0000
Subject: [PATCH 06/32] step5: yield between native prefill chunks
---
docs/recipes/step-5-preview.md | 7 +-
zig/build/step5_host.zig | 2 +-
zig/src/families/step5/backend.zig | 122 +++++++++++++++--------
zig/src/families/step5/prefill_steps.zig | 77 ++++++++++++++
zig/step5_family_tests.zig | 1 +
5 files changed, 165 insertions(+), 44 deletions(-)
create mode 100644 zig/src/families/step5/prefill_steps.zig
diff --git a/docs/recipes/step-5-preview.md b/docs/recipes/step-5-preview.md
index 9de47f1367c..7b1196ea2e4 100644
--- a/docs/recipes/step-5-preview.md
+++ b/docs/recipes/step-5-preview.md
@@ -31,9 +31,10 @@ release archives ship it; from source, `zig build grammar -Dxgrammar=DIR` with a
`STEP5_LOAD_LIMIT_GB` sets another limit. With MTP and vision, 15.8 GiB is left for caches on a 256 GB Mac: up to
227,025 tokens of context by default, or `--context` for less. The model supports 1M tokens; a Mac's caches reach
what the limit leaves. A 212k-token prompt ran with free memory never below 19%.
-- **Prompts** run in 2,048-row chunks on the tensor units: 917, 901, 872 and 835 tokens a second at 4k, 8k, 16k and
- 32k tokens (the server's prefill time, prompt cache off). A 129k-token prompt took about 200 s and a 212k-token one
- about 376 s on the build before TensorFold 1.0.12, whose 4k-32k prompts ran 2-3% slower.
+- **Prompts** run in 2,048-row chunks on the tensor units, one a lane visit so other streams' rounds run between
+ chunks: 917, 901, 872 and 835 tokens a second at 4k, 8k, 16k and 32k tokens (the server's prefill time, prompt
+ cache off). A 129k-token prompt took about 200 s and a 212k-token one about 376 s on the build before TensorFold
+ 1.0.12, whose 4k-32k prompts ran 2-3% slower.
- **MTP drafts** (`--mtp` checkpoints): three chained drafts a round, verified in one window. Replies are the same as
undrafted ones. Greedy replies of 200-400 tokens, timed with their prompt: 41.2 tokens a second on code (25.8
undrafted), 36.6 on prose (27.0), 48.8 on math (26.9).
diff --git a/zig/build/step5_host.zig b/zig/build/step5_host.zig
index cbc3b24634b..5025335e0d6 100644
--- a/zig/build/step5_host.zig
+++ b/zig/build/step5_host.zig
@@ -5,7 +5,7 @@ pub fn steps(b: *std.Build, metal: *std.Build.Module, engine: *std.Build.Module,
const host = b.createModule(.{ .root_source_file = b.path("zig/src/native/step5.zig"), .target = b.graph.host, .optimize = .Debug, .link_libc = true, .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "tensorfold", .module = engine }, .{ .name = "engine_api", .module = api } } });
const filter = b.option([]const u8, "step5-filter", "One Step-5 host regression");
const check = b.step("test-step5-host", "Step-5 geometry and owned prompt-cache callback fixtures without GPU work");
- const family = b.createModule(.{ .root_source_file = b.path("zig/step5_family_tests.zig"), .target = b.graph.host, .optimize = .Debug, .link_libc = true, .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "kernel_sources", .module = engine.import_table.get("kernel_sources").? } } });
+ const family = b.createModule(.{ .root_source_file = b.path("zig/step5_family_tests.zig"), .target = b.graph.host, .optimize = .Debug, .link_libc = true, .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "kernel_sources", .module = engine.import_table.get("kernel_sources").? }, .{ .name = "lanes", .module = lanes } } });
for ([_]*std.Build.Module{ family, host }) |module| {
const tests = b.addTest(.{ .root_module = module, .filters = &.{ "step5 host: imports", filter orelse "step5 host:" } });
const run = b.addRunArtifact(tests);
diff --git a/zig/src/families/step5/backend.zig b/zig/src/families/step5/backend.zig
index 408075b172c..c94a0198b0f 100644
--- a/zig/src/families/step5/backend.zig
+++ b/zig/src/families/step5/backend.zig
@@ -6,6 +6,7 @@ const st = @import("state.zig");
const fwd = @import("forward.zig");
const Model = @import("model.zig").Model;
const snapshot = @import("snapshot.zig");
+const steps = @import("prefill_steps.zig");
const draw = @import("../qwen3_5/backend.zig").draw;
const be = lanes.backend;
@@ -25,6 +26,7 @@ pub const Metal = struct {
scratch: st.Scratch, // decode rounds
prompt: st.Scratch, // prompt chunks
caches: std.AutoHashMapUnmanaged(*lanes.Stream, *st.Cache) = .empty,
+ fills: std.AutoHashMapUnmanaged(*lanes.Stream, Fill) = .empty,
follow: ?mtl.ResidencySet.Follow = null,
held: u64 = 0, // bytes the streams' caches hold
room: ?Room = null, // the prompt cache, which takes what the streams leave of the budget
@@ -46,6 +48,12 @@ pub const Metal = struct {
self.gpa.destroy(cache.*);
}
self.caches.deinit(self.gpa);
+ var fills = self.fills.valueIterator();
+ while (fills.next()) |f| {
+ self.gpa.free(f.spans);
+ if (f.rows) |r| r.deinit();
+ }
+ self.fills.deinit(self.gpa);
self.scratch.deinit();
self.prompt.deinit();
self.gpa.destroy(self);
@@ -80,7 +88,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, .first_row = firstRowFn, .held = heldFn } };
+ return .{ .ptr = self, .vtable = &.{ .prefill = prefillFn, .prefill_step = prefillStepFn, .cancel_prefill = cancelPrefillFn, .reports_fill = true, .first = firstFn, .first_masked = firstMaskedFn, .queue = queueFn, .read = readFn, .verify = verifyFn, .keep = keepFn, .draft = draftFn, .release = releaseFn, .first_row = firstRowFn, .held = heldFn } };
}
fn cast(ptr: *anyopaque) *Metal {
@@ -95,39 +103,41 @@ pub const Metal = struct {
return cache.logits.slice(u16, self.model.config.vocab);
}
- /// Run `ids` at the cache's end, MTP absorbing rows with a known next; a stream's pass keeps at its marks.
- fn feed(self: *Metal, cache: *st.Cache, ids: []const u32, images: []const fwd.Span, stream: ?*lanes.Stream) !void {
+ /// Run one prompt chunk at the cache's end, MTP absorbing rows with a known next.
+ fn runChunk(self: *Metal, cache: *st.Cache, ids: []const u32, at: usize, end: usize, images: []const fwd.Span) !void {
const c = &self.model.config;
- const base = cache.len;
- var at: usize = 0;
- while (at < ids.len) {
- var end = @min(ids.len, at + st.prompt_rows);
- if (stream) |sm| {
- if (sm.isCancelled()) return error.Cancelled;
- for (sm.chunks) |x| if (x > base + at and x < base + end) {
- end = x - base;
- };
- for (sm.reuse.marks) |x| if (x > base + at and x < base + end) {
- end = x - base;
- };
- }
- const s = if (end - at > st.window_rows) &self.prompt else &self.scratch;
- const n = end - at;
- try fwd.run(self.model, s, cache, ids[at..end], .{ .hidden = .{ .buf = s.hid }, .images = images });
- const start = cache.len;
- cache.len += n;
- const last: [*]const u8 = s.hid.contents() + (n - 1) * c.hidden * 4;
- @memcpy(cache.hidden.contents()[0 .. c.hidden * 4], last[0 .. c.hidden * 4]);
- const known = if (end < ids.len) n else n - 1; // rows whose next token is in ids
- if (c.mtp > 0 and known > 0) try fwd.mtp(self.model, s, cache, 0, .{ .buf = s.hid }, ids[at + 1 .. at + 1 + known], start);
- if (stream) |sm| lanes.prefill_widths.completed(self.gpa, sm, end - at);
- at = end;
- if (stream) |sm| if (std.mem.indexOfScalar(u32, sm.reuse.marks, @intCast(cache.len)) != null) if (sm.reuse.hook) |k| k.at(k.ptr, sm, @intCast(cache.len));
- }
+ const n = end - at;
+ const s = if (n > st.window_rows) &self.prompt else &self.scratch;
+ try fwd.run(self.model, s, cache, ids[at..end], .{ .hidden = .{ .buf = s.hid }, .images = images });
+ const start = cache.len;
+ cache.len += n;
+ const last: [*]const u8 = s.hid.contents() + (n - 1) * c.hidden * 4;
+ @memcpy(cache.hidden.contents()[0 .. c.hidden * 4], last[0 .. c.hidden * 4]);
+ const known = if (end < ids.len) n else n - 1;
+ if (c.mtp > 0 and known > 0) try fwd.mtp(self.model, s, cache, 0, .{ .buf = s.hid }, ids[at + 1 .. at + 1 + known], start);
}
+ const Fill = struct { pass: steps.Fill, spans: []fwd.Span = &.{}, rows: ?mtl.Buffer = null };
+
+ const Run = struct {
+ m: *Metal,
+ cache: *st.Cache,
+ spans: []const fwd.Span,
+
+ pub fn run(r: Run, stream: *lanes.Stream, at: usize, end: usize) !void {
+ try r.m.runChunk(r.cache, stream.prompt(), at, end, r.spans);
+ }
+
+ pub fn keep(_: Run, stream: *lanes.Stream, at: u32) void {
+ if (stream.reuse.hook) |k| k.at(k.ptr, stream, at);
+ }
+ };
+
fn prefillFn(ptr: *anyopaque, stream: *lanes.Stream) !void {
- const self = cast(ptr);
+ while (!try prefillStepFn(ptr, stream, 0)) {}
+ }
+
+ fn opening(self: *Metal, stream: *lanes.Stream) !*Fill {
const ids = stream.prompt();
if (ids.len == 0 or ids.len + stream.max_new > self.options.capacity or self.caches.contains(stream)) return error.InvalidStep5Prompt;
const capacity = ids.len + stream.max_new + 1;
@@ -138,29 +148,60 @@ pub const Metal = struct {
}
self.held += need;
errdefer self.held -= need;
- if (stream.reuse.saved) |saved| { // a state the stream cannot hold beside its caches: freed now, no restore
+ if (stream.reuse.saved) |saved| {
const snap: *snapshot.Snap = @ptrCast(@alignCast(saved));
if (self.held + snap.bytes > self.options.budget) snap.free();
}
- // kept states give way first
if (self.room) |r| r.fit(r.ctx, self.options.budget - self.held, stream.reuse.saved, ids);
const cache = try self.createCache(capacity);
errdefer self.gpa.destroy(cache);
errdefer cache.deinit();
- try self.caches.put(self.gpa, stream, cache); // a mark's save finds it there
+ try self.caches.put(self.gpa, stream, cache);
errdefer _ = self.caches.remove(stream);
stream.cached = 0;
- if (stream.reuse.saved) |saved| { // a kept state of this prompt's prefix: the pass starts there
+ if (stream.reuse.saved) |saved| {
const snap: *const snapshot.Snap = @ptrCast(@alignCast(saved));
if (snap.at < ids.len) {
if (snapshot.restore(self.gpa, self.model.queue, &self.model.config, snap, cache)) stream.cached = snap.at else |_| stream.reuse_failed = true;
} else stream.reuse_failed = true;
}
- var rows: ?mtl.Buffer = null;
- defer if (rows) |r| r.deinit();
- const spans = try self.encodeImages(stream.images, cache.len, &rows);
- defer self.gpa.free(spans);
- try self.feed(cache, ids[cache.len..], spans, stream);
+ var f: Fill = .{ .pass = .{ .at = cache.len } };
+ errdefer self.gpa.free(f.spans);
+ errdefer if (f.rows) |r| r.deinit();
+ f.spans = try self.encodeImages(stream.images, cache.len, &f.rows);
+ try self.fills.put(self.gpa, stream, f);
+ stream.fill_at.store(@intCast(cache.len), .monotonic);
+ return self.fills.getPtr(stream).?;
+ }
+
+ fn closing(self: *Metal, stream: *lanes.Stream) void {
+ const entry = self.fills.fetchRemove(stream) orelse return;
+ self.gpa.free(entry.value.spans);
+ if (entry.value.rows) |r| r.deinit();
+ }
+
+ fn drop(self: *Metal, stream: *lanes.Stream) void {
+ self.closing(stream);
+ if (self.caches.fetchRemove(stream)) |entry| {
+ self.held -= st.cacheBytes(&self.model.config, entry.value.capacity);
+ entry.value.deinit();
+ self.gpa.destroy(entry.value);
+ }
+ }
+
+ fn prefillStepFn(ptr: *anyopaque, stream: *lanes.Stream, _: u32) !bool {
+ const self = cast(ptr);
+ const f = self.fills.getPtr(stream) orelse try self.opening(stream);
+ errdefer self.drop(stream);
+ const r: Run = .{ .m = self, .cache = try self.cacheOf(stream), .spans = f.spans };
+ const done = try steps.step(r, stream, &f.pass, st.prompt_rows);
+ if (done) self.closing(stream);
+ return done;
+ }
+
+ fn cancelPrefillFn(ptr: *anyopaque, stream: *lanes.Stream) !void {
+ const self = cast(ptr);
+ if (self.fills.get(stream)) |f| stream.keepInterruptedPrefill(@intCast(f.pass.at));
}
/// The tower's rows for every image piece past `from`, into one buffer, as spans over their placeholders.
@@ -206,7 +247,7 @@ pub const Metal = struct {
defer cache.deinit();
var ids: [st.prompt_rows]u32 = undefined;
for (&ids, 0..) |*t, i| t.* = @intCast(1000 + i * 37 % 20000);
- try self.feed(&cache, &ids, &.{}, null);
+ try self.runChunk(&cache, &ids, 0, ids.len, &.{});
try fwd.run(self.model, &self.scratch, &cache, &.{ids[0]}, .{ .all = true, .hidden = .{ .buf = cache.hidden } });
if (self.model.vision) |v| {
const rows = try self.model.device.buffer(169 * @as(usize, c.hidden) * 2, mtl.ResourceOptions.private);
@@ -362,6 +403,7 @@ pub const Metal = struct {
fn releaseFn(ptr: *anyopaque, stream: *lanes.Stream) void {
const self = cast(ptr);
+ self.closing(stream);
if (self.caches.fetchRemove(stream)) |entry| {
self.held -= st.cacheBytes(&self.model.config, entry.value.capacity);
entry.value.deinit();
diff --git a/zig/src/families/step5/prefill_steps.zig b/zig/src/families/step5/prefill_steps.zig
new file mode 100644
index 00000000000..dd310e97aca
--- /dev/null
+++ b/zig/src/families/step5/prefill_steps.zig
@@ -0,0 +1,77 @@
+//! Step-5 Metal prompt chunks between lane rounds, preserving the whole pass's cuts and native width observations.
+const std = @import("std");
+const lanes = @import("lanes");
+
+pub const Fill = struct { at: usize };
+
+pub fn chunkEnd(len: usize, at: usize, rows: usize, chunks: []const u32, marks: []const u32) usize {
+ var end = @min(len, at + rows);
+ for ([_][]const u32{ chunks, marks }) |cuts| for (cuts) |x| if (x > at and x < end) {
+ end = x;
+ };
+ return end;
+}
+
+pub fn step(r: anytype, stream: *lanes.Stream, fill: *Fill, rows: usize) !bool {
+ if (stream.isCancelled()) return error.Cancelled;
+ const len = stream.prompt().len;
+ const end = chunkEnd(len, fill.at, rows, stream.chunks, stream.reuse.marks);
+ try r.run(stream, fill.at, end);
+ lanes.prefill_widths.completed(r.m.gpa, stream, end - fill.at);
+ stream.fill_at.store(@intCast(end), .monotonic);
+ fill.at = end;
+ if (std.mem.indexOfScalar(u32, stream.reuse.marks, @intCast(end)) != null) r.keep(stream, @intCast(end));
+ return end == len;
+}
+
+const Owner = struct { gpa: std.mem.Allocator };
+const Event = union(enum) { chunk: [2]usize, keep: u32 };
+
+const Rec = struct {
+ m: *const Owner,
+ log: *std.ArrayList(Event),
+
+ pub fn run(r: Rec, _: *lanes.Stream, at: usize, end: usize) !void {
+ try r.log.append(r.m.gpa, .{ .chunk = .{ at, end } });
+ }
+
+ pub fn keep(r: Rec, _: *lanes.Stream, at: u32) void {
+ r.log.append(r.m.gpa, .{ .keep = at }) catch @panic("out of memory");
+ }
+};
+
+fn checkPass(ids: []const u32, from: usize, want: []const Event, widths: []const u32) !void {
+ const gpa = std.testing.allocator;
+ const owner: Owner = .{ .gpa = gpa };
+ var stream = try lanes.Stream.init(gpa, .{ .id = "s", .prompt = ids, .max_new = 4, .chunks = &.{6}, .reuse = .{ .marks = &.{9} } });
+ defer stream.deinit(gpa);
+ stream.cached = @intCast(from);
+ var log: std.ArrayList(Event) = .empty;
+ defer log.deinit(gpa);
+ var fill: Fill = .{ .at = from };
+ while (fill.at < ids.len) _ = try step(Rec{ .m = &owner, .log = &log }, &stream, &fill, 4);
+ try std.testing.expectEqual(@as(usize, ids.len), fill.at);
+ try std.testing.expectEqual(@as(u32, @intCast(ids.len)), stream.fill_at.load(.monotonic));
+ try std.testing.expectEqual(want.len, log.items.len);
+ for (want, log.items) |w, got| try std.testing.expectEqual(w, got);
+ try std.testing.expectEqualSlices(u32, widths, stream.prefill_widths.items);
+}
+
+test "step5 host: stepped prefill keeps fresh and resumed cuts and native widths" {
+ var ids: [15]u32 = undefined;
+ for (&ids, 0..) |*id, i| id.* = @intCast(i + 1);
+ try checkPass(&ids, 0, &.{
+ .{ .chunk = .{ 0, 4 } },
+ .{ .chunk = .{ 4, 6 } },
+ .{ .chunk = .{ 6, 9 } },
+ .{ .keep = 9 },
+ .{ .chunk = .{ 9, 13 } },
+ .{ .chunk = .{ 13, 15 } },
+ }, &.{ 4, 2, 3, 4, 2 });
+ try checkPass(&ids, 6, &.{
+ .{ .chunk = .{ 6, 9 } },
+ .{ .keep = 9 },
+ .{ .chunk = .{ 9, 13 } },
+ .{ .chunk = .{ 13, 15 } },
+ }, &.{ 3, 4, 2 });
+}
diff --git a/zig/step5_family_tests.zig b/zig/step5_family_tests.zig
index dbe3120022a..9f482431e40 100644
--- a/zig/step5_family_tests.zig
+++ b/zig/step5_family_tests.zig
@@ -3,4 +3,5 @@ test "step5 host: imports" {
_ = @import("src/families/step5/config.zig");
_ = @import("src/families/step5/weights.zig");
_ = @import("src/families/step5/vision.zig");
+ _ = @import("src/families/step5/prefill_steps.zig");
}
From 46c5fc7d96b174a88d9437fd15594b09b2c90af1 Mon Sep 17 00:00:00 2001
From: ashhart <71890694+ashhart@users.noreply.github.com>
Date: Fri, 20 Nov 2026 10:37:22 +0000
Subject: [PATCH 07/32] kimi: retain prefill state on cancellation
---
zig/src/families/kimi_k3/backend.zig | 39 +++++++++++++++++++++++++++-
1 file changed, 38 insertions(+), 1 deletion(-)
diff --git a/zig/src/families/kimi_k3/backend.zig b/zig/src/families/kimi_k3/backend.zig
index 75c0393a049..bf231fc8246 100644
--- a/zig/src/families/kimi_k3/backend.zig
+++ b/zig/src/families/kimi_k3/backend.zig
@@ -79,7 +79,7 @@ pub const Metal = struct {
}
pub fn backend(m: *Metal) be.Backend {
- return .{ .ptr = m, .chunk_invariant = true, .vtable = &.{ .prefill = prefill, .prefill_step = step, .reports_fill = true, .first = first, .first_masked = firstMasked, .queue = queueOne, .read = read, .verify = verify, .keep = keep, .draft = draft, .held = held, .release = release } };
+ return .{ .ptr = m, .chunk_invariant = true, .vtable = &.{ .prefill = prefill, .prefill_step = step, .cancel_prefill = cancelPrefill, .reports_fill = true, .first = first, .first_masked = firstMasked, .queue = queueOne, .read = read, .verify = verify, .keep = keep, .draft = draft, .held = held, .release = release } };
}
fn self(ptr: *anyopaque) *Metal {
@@ -173,6 +173,11 @@ pub const Metal = struct {
if (s.reuse.hook) |hook| hook.at(hook.ptr, s, @intCast(end));
return end == s.prompt_len;
}
+ fn cancelPrefill(ptr: *anyopaque, s: *lanes.Stream) !void {
+ const m = self(ptr);
+ const slot = try m.find(s);
+ s.keepInterruptedPrefill(m.state.streams[slot].pos);
+ }
fn draw(m: *Metal, s: *lanes.Stream, logits_: []const u16, pos: u64, mask: []const u32) !u32 {
for (logits_, m.values, 0..) |bits, *out, i| {
@@ -323,3 +328,35 @@ test "Kimi full verification publishes its position before an optional partial k
windowPosition(&state, 0, record, 1);
try std.testing.expectEqual(@as(u32, 20), positions[0].pos);
}
+
+test "Kimi cancel between prefill steps keeps the landed prompt state" {
+ const Observer = struct {
+ marked: usize = 0,
+ interrupted: usize = 0,
+ at: u32 = 0,
+ fn mark(ptr: *anyopaque, _: *lanes.Stream, _: u32) void {
+ @as(*@This(), @ptrCast(@alignCast(ptr))).marked += 1;
+ }
+ fn interrupt(ptr: *anyopaque, _: *lanes.Stream, at: u32) void {
+ const o: *@This() = @ptrCast(@alignCast(ptr));
+ o.interrupted += 1;
+ o.at = at;
+ }
+ };
+ var observer: Observer = .{};
+ var stream = try lanes.Stream.init(std.testing.allocator, .{ .id = "cancel", .prompt = &.{ 1, 2, 3, 4, 5, 6, 7, 8 }, .max_new = 4, .drafts = false, .reuse = .{ .hook = .{ .ptr = &observer, .at = Observer.mark, .interrupted = Observer.interrupt } } });
+ defer stream.deinit(std.testing.allocator);
+ var positions = [_]@import("state.zig").Stream{.{ .pos = 4, .kept = 3 }};
+ var slots = [_]Slot{.{ .stream = &stream }};
+ var model: Metal = undefined;
+ model.slots = &slots;
+ model.state.streams = &positions;
+ const backend = model.backend();
+ const cancel = backend.vtable.cancel_prefill orelse return error.MissingKimiCancelHook;
+ try cancel(backend.ptr, &stream);
+ try std.testing.expectEqual(@as(usize, 0), observer.marked);
+ try std.testing.expectEqual(@as(usize, 1), observer.interrupted);
+ try std.testing.expectEqual(@as(u32, 4), observer.at);
+ try std.testing.expectEqual(@as(u32, 4), positions[0].pos);
+ try std.testing.expectEqual(@as(u32, 3), positions[0].kept);
+}
From 1c7ff8e2cff20b016444e363a20e619ab7cf2c6e Mon Sep 17 00:00:00 2001
From: ashhart <71890694+ashhart@users.noreply.github.com>
Date: Fri, 20 Nov 2026 10:38:54 +0000
Subject: [PATCH 08/32] replay: restore prepared seed for explicit null
---
tools/replay_request.py | 2 +-
tools/test_replay_request.py | 22 +++++++++++++++++++++-
2 files changed, 22 insertions(+), 2 deletions(-)
diff --git a/tools/replay_request.py b/tools/replay_request.py
index f8ce92e4bd3..fa7c8b66b87 100644
--- a/tools/replay_request.py
+++ b/tools/replay_request.py
@@ -132,7 +132,7 @@ def request_body(entry, replacement=None):
if redacted(body):
raise ReplayError('the request has redacted media; supply the original with --body FILE')
prepared = entry['prepared']
- if 'seed' not in body and prepared and prepared.get('seed') is not None:
+ if body.get('seed') is None and prepared and prepared.get('seed') is not None:
body['seed'] = prepared['seed']
return body
diff --git a/tools/test_replay_request.py b/tools/test_replay_request.py
index 3aedfa00fc5..ecbe1b72e93 100644
--- a/tools/test_replay_request.py
+++ b/tools/test_replay_request.py
@@ -27,10 +27,13 @@ def whole(content, reply_id='chatcmpl-1', created=1, tokens=TOKENS, seconds=0.5)
'tensorfold': {'token_sha256': tokens, 'seconds': seconds}}).encode()
-def streamed(pieces, reply_id='chatcmpl-1', keepalive=False):
+def streamed(pieces, reply_id='chatcmpl-1', keepalive=False, usage=False, cached=0):
frames = [{'id': reply_id, 'choices': [{'index': 0, 'delta': {'role': 'assistant'}, 'finish_reason': None}]}]
frames += [{'id': reply_id, 'choices': [{'index': 0, 'delta': {'content': p}, 'finish_reason': None}]} for p in pieces]
frames.append({'id': reply_id, 'choices': [{'index': 0, 'delta': {}, 'finish_reason': 'stop'}], 'tensorfold': {'token_sha256': TOKENS}})
+ if usage:
+ frames.append({'choices': [], 'usage': {'prompt_tokens': 8, 'completion_tokens': 2,
+ 'prompt_tokens_details': {'cached_tokens': cached}}})
out = b''.join(b'data: ' + json.dumps(f).encode() + b'\n\n' for f in frames)
return (b': keepalive\n\n' if keepalive else b'') + out + b'data: [DONE]\n\n'
@@ -75,6 +78,23 @@ def test_the_drawn_seed_is_sent_and_equal_output_passes_despite_new_ids_and_timi
r.replay(own, 'http://example.test', server.send)
self.assertEqual(server.calls[0][1]['seed'], 7) # the client's own seed is never replaced
+ def test_a_null_seed_replays_the_journaled_draw_and_keeps_cache_hits_out_of_stream_equality(self):
+ body = {'messages': [{'role': 'user', 'content': 'hi'}], 'temperature': 1, 'seed': None,
+ 'stream': True, 'stream_options': {'include_usage': True}}
+ entry = self.journal(streamed(['o', 'k'], usage=True), stream=True, body=body)
+ sent = []
+
+ def send(url, request):
+ sent.append(request)
+ pieces = ['ok'] if request.get('seed') == 42 else ['different']
+ return 200, streamed(pieces, reply_id='chatcmpl-2', usage=True, cached=8)
+
+ result, _ = r.replay(entry, 'http://example.test', send)
+ self.assertTrue(result['equal'])
+ self.assertEqual(sent[0]['seed'], 42)
+ self.assertEqual(sent[0]['stream_options'], {'include_usage': True})
+ self.assertIsNone(entry['start']['body']['seed'])
+
def test_different_text_or_tokens_are_a_reported_mismatch(self):
result, _ = r.replay(self.journal(), 'http://example.test', FakeServer(whole('oK')).send)
self.assertFalse(result['equal'])
From cf561298f533c7131cf5203f9f7c949c7cbf86ea Mon Sep 17 00:00:00 2001
From: ashhart <71890694+ashhart@users.noreply.github.com>
Date: Fri, 20 Nov 2026 10:46:23 +0000
Subject: [PATCH 09/32] deepseek: plan text TBO beside image replay
---
.../deepseek_v41/forward_prefill_k4.zig | 6 ++-
zig/src/families/deepseek_v41/pftbo_test.zig | 42 +++++++++++++++++++
2 files changed, 47 insertions(+), 1 deletion(-)
diff --git a/zig/src/families/deepseek_v41/forward_prefill_k4.zig b/zig/src/families/deepseek_v41/forward_prefill_k4.zig
index e6d1f65ad31..8425c4fa3d9 100644
--- a/zig/src/families/deepseek_v41/forward_prefill_k4.zig
+++ b/zig/src/families/deepseek_v41/forward_prefill_k4.zig
@@ -59,7 +59,11 @@ pub fn planWorkspace(f: *Forward, wp: *buffers.Plan, rows: u32, layers: []const
if (replay and f.opts.pf_tbo and rows >= 2 * block_prefill.tbo_min) {
const enc = try encoderLayers(f, layers);
const k4 = pf.state(f).k4;
- const op = if (k4) k4Options(image_opts.planOptions(f)) else image_opts.planOptions(f);
+ var op = if (k4) k4Options(image_opts.planOptions(f)) else image_opts.planOptions(f);
+ if (op.image_rows != 0) {
+ op.image_rows = 0;
+ op.image_keep = false;
+ }
const seg: u32 = if (k4) K4.rows else rows;
const top = @max(0, try lastStartWith(f, op, enc, seg, .encoder) - seg); // B at the last start a segment takes
for ([_]i64{ 0, top }) |start| {
diff --git a/zig/src/families/deepseek_v41/pftbo_test.zig b/zig/src/families/deepseek_v41/pftbo_test.zig
index 17fbde6fb69..ea9f6cb7be6 100644
--- a/zig/src/families/deepseek_v41/pftbo_test.zig
+++ b/zig/src/families/deepseek_v41/pftbo_test.zig
@@ -8,6 +8,7 @@ const branches = @import("branches.zig");
const check = @import("calls_check.zig");
const pk = @import("serve_knobs.zig");
const fp = @import("forward_prefill.zig");
+const ws = @import("forward_prefill_k4.zig");
const Config = @import("config.zig").Config;
const Fake = struct {
@@ -258,3 +259,44 @@ test "TF_DSV41_PF_TBO with TF_DSV41_PF_4K: 4,096-row micro-batches, each its 4K
try testing.expectEqual([2]usize{ 4096, 4096 }, fp.pairSplit(4096, 8192).?);
try testing.expectEqual([2]usize{ 3008, 3008 }, fp.pairSplit(4096, 6016).?);
}
+
+test "TF_DSV41_PF_TBO with image bias plans sequential replay images and its supported text pairs" {
+ var arena = std.heap.ArenaAllocator.init(testing.allocator);
+ defer arena.deinit();
+ const aa = arena.allocator();
+ const cfg: Config = .{};
+ const w = try widths(aa);
+ var layers: [25]u32 = undefined;
+ for (&layers, 0..) |*l, i| l.* = @intCast(i);
+ const enc = layers[0..21];
+ const base: block.Options = .{ .gm_v2 = .one, .branches = true, .pf_tbo = true, .limit = 1 << 16, .rope_rows = (1 << 16) + 4096, .index_budget = 64 << 20, .taps = true };
+ var f = @import("forward.zig").Forward.init(aa, &cfg, &w, base, undefined, undefined);
+ f.layers = &layers;
+ f.images = true;
+ f.image_bias = true;
+ var state: fp.State = .{ .mode = .replay, .k4 = true };
+ f.prefill_state = &state;
+ var planned: buffers.Plan = .{ .a = aa };
+ try ws.planWorkspace(&f, &planned, 2048, &layers);
+ const bytes = ws.planBytes(&planned);
+ try testing.expect(bytes > 0);
+ try testing.expectEqual(bytes, try fp.workspaceBytes(&f, 2048));
+ const text = fp.k4Options(base);
+ var image = text;
+ image.image_keep = true;
+ image.image_rows = 4096;
+ var image_pair = image;
+ image_pair.image_rows = 8192;
+ try testing.expectError(error.Unsupported, bp.emitTbo(aa, &cfg, &w, image_pair, enc, 4096, 4096, 32768));
+ var needed: buffers.Plan = .{ .a = aa };
+ try needed.add(try bp.ownCalls(aa, try bp.emitReplay(aa, &cfg, &w, image, enc, 4096, 32768, .encoder), fp.K4.tag));
+ try needed.add(try ws.wsPair(aa, try bp.emitTbo(aa, &cfg, &w, text, enc, 4096, 4096, 32768), true));
+ for (needed.sizes.keys(), needed.sizes.values()) |role, size| {
+ if (std.mem.indexOf(u8, role, fp.K4.tag) == null) continue;
+ const have = planned.sizes.get(role) orelse {
+ std.debug.print("image replay workspace misses {s} ({d} bytes)\n", .{ role, size });
+ return error.TestUnexpectedResult;
+ };
+ try testing.expect(have >= size);
+ }
+}
From e90bf30021975581fcdd3412282e3de36f301978 Mon Sep 17 00:00:00 2001
From: ashhart <71890694+ashhart@users.noreply.github.com>
Date: Fri, 20 Nov 2026 10:48:45 +0000
Subject: [PATCH 10/32] cache: isolate decoded-row extension namespaces
---
zig/src/core/lane_host_cache_queue_test.zig | 60 +++++++++++++++++++++
zig/src/core/prompt_cache_policy.zig | 13 +++--
2 files changed, 68 insertions(+), 5 deletions(-)
diff --git a/zig/src/core/lane_host_cache_queue_test.zig b/zig/src/core/lane_host_cache_queue_test.zig
index 5416887bcd6..2bb33da4eab 100644
--- a/zig/src/core/lane_host_cache_queue_test.zig
+++ b/zig/src/core/lane_host_cache_queue_test.zig
@@ -214,3 +214,63 @@ test "queued cache: progress a shared-cut request without history replaces an id
test "queued cache: growing states do not spend the same sixteen free bytes twice" {
for ([_]usize{ 2, 4, 8 }) |n| try followupsSized(n, false, false, .{ .min_prompt = 0 }, true);
}
+
+test "queued cache: decoded namespaces retain their own reusable prefix" {
+ var cfg = try lanes.Config.init(a, .{ .exact_width = 8, .gpu_tokens = true, .hidden_rows = true }, 8, 7);
+ defer cfg.deinit(a);
+ var target: lanes.fake.Fake = .{ .gpa = a, .prefill_chunks = 3 };
+ defer target.deinit();
+ var clock: lanes.fake.FixedClock = .{};
+ var core = lanes.Engine.init(a, &cfg, target.stepped(), clock.clock());
+ defer core.deinit();
+ var snapshots: Snapshots = .{ .target = &target };
+ var store = pc.Store.init(a, .{ .ptr = &snapshots, .vtable = &.{ .bytes = Snapshots.bytes, .save = Snapshots.save, .restore = Snapshots.restore, .drop = Snapshots.drop } }, .{ .min_prompt = 0 }, 300);
+ defer store.deinit();
+ var words: [20]u32 = undefined;
+ var idle: [20]u32 = undefined;
+ var cold_words: [20]u32 = undefined;
+ for (&words, &idle, &cold_words, 0..) |*word, *other, *cold_word, i| {
+ word.* = @intCast(1000 + i);
+ other.* = @intCast(2000 + i);
+ cold_word.* = @intCast(3000 + i);
+ }
+ const ordinary = [_][2]u32{.{ 1, 3 }};
+ const changed = [_][2]u32{.{ 5, 7 }};
+ const fresh_spans = [_][2]u32{.{ 13, 17 }};
+ snapshots.seed = &words;
+ try std.testing.expect(store.keepBorn(&words, 4, 4, null, &.{}, &ordinary));
+ snapshots.seed = &idle;
+ try std.testing.expect(store.keepBorn(&idle, 8, 8, null, &.{}, &.{}));
+ snapshots.seed = &words;
+ try std.testing.expect(store.keepBorn(&words, 8, 8, null, &.{}, &changed));
+ const touch = try store.lookup(a, &words, 4, &.{}, &.{}, &ordinary);
+ defer a.free(touch.marks);
+ try std.testing.expectEqual(@as(u32, 4), touch.entry.?.at);
+ store.resumed(touch.entry.?, &words, true);
+ var host = api.LaneHost.init(a, std.testing.io, &core, .{ .lanes = 1 });
+ host.cache = &store;
+ host.decoded_rows = true;
+ try host.start();
+ defer host.stop();
+ const engine = host.engine();
+ var cold: Reply = .{};
+ const other: api.Request = .{ .prompt = &cold_words, .max_tokens = 4, .history_len = 12 };
+ try engine.submit(1, &other, .{ .ctx = &cold, .event = Reply.event });
+ try cold.wait();
+ const retained = store.find(&words, &.{}, &ordinary);
+ try std.testing.expect(retained != null);
+ try std.testing.expectEqual(@as(u32, 4), retained.?.at);
+ var resumed: Reply = .{};
+ const hit: api.Request = .{ .prompt = &words, .max_tokens = 4, .history_len = 12, .decode_spans = &ordinary };
+ try engine.submit(2, &hit, .{ .ctx = &resumed, .event = Reply.event });
+ try resumed.wait();
+ try std.testing.expectEqual(@as(?u32, 4), resumed.cached);
+ try std.testing.expectEqual(@as(usize, 4), resumed.count);
+ var fresh: Reply = .{};
+ const cold_hit: api.Request = .{ .prompt = &words, .max_tokens = 4, .history_len = 12, .decode_spans = &fresh_spans };
+ try engine.submit(3, &cold_hit, .{ .ctx = &fresh, .event = Reply.event });
+ try fresh.wait();
+ try std.testing.expectEqual(@as(?u32, 0), fresh.cached);
+ try std.testing.expectEqual(@as(usize, 4), fresh.count);
+ try std.testing.expectEqualSlices(u32, &resumed.tokens, &fresh.tokens);
+}
diff --git a/zig/src/core/prompt_cache_policy.zig b/zig/src/core/prompt_cache_policy.zig
index fdb5996d894..40cf746a652 100644
--- a/zig/src/core/prompt_cache_policy.zig
+++ b/zig/src/core/prompt_cache_policy.zig
@@ -59,6 +59,11 @@ pub fn own(e: *const pc.Entry, skip: ?*pc.Entry, prompt: []const u32) bool {
return std.mem.eql(u32, prompt[0..e.tokens.len], e.tokens);
}
+fn extends(short: *const pc.Entry, long: *const pc.Entry) bool {
+ return long.tokens.len > short.tokens.len and std.mem.eql(u32, long.tokens[0..short.tokens.len], short.tokens) and
+ @import("cache_modes.zig").equal(short.decode_spans, long.decode_spans, short.at);
+}
+
/// Only live continuations make a prefix a branch point or a superseded state.
pub fn extended(s: *const pc.Store, e: *const pc.Entry) bool {
if (s.links_lost) return extendedScan(s, e);
@@ -72,15 +77,13 @@ pub fn continuedLater(s: *const pc.Store, e: *const pc.Entry) bool {
for (e.ext.items) |o| if (!o.expired and o.born > e.born) return true;
return false;
}
- for (s.entries.items) |o| if (!o.expired and o.born > e.born and o.tokens.len > e.tokens.len and
- std.mem.eql(u32, o.tokens[0..e.tokens.len], e.tokens)) return true;
+ for (s.entries.items) |o| if (!o.expired and o.born > e.born and extends(e, o)) return true;
return false;
}
/// `extended` over every entry, for a store whose links an allocation failure left incomplete.
pub fn extendedScan(s: *const pc.Store, e: *const pc.Entry) bool {
- for (s.entries.items) |o| if (!o.expired and o != e and (o.born > e.born or (o.born == e.born and !e.rewind)) and o.tokens.len > e.tokens.len and
- std.mem.eql(u32, o.tokens[0..e.tokens.len], e.tokens)) return true;
+ for (s.entries.items) |o| if (!o.expired and o != e and (o.born > e.born or (o.born == e.born and !e.rewind)) and extends(e, o)) return true;
return false;
}
@@ -89,7 +92,7 @@ pub fn link(s: *pc.Store, x: *pc.Entry) void {
for (s.entries.items) |o| {
if (o == x or o.tokens.len == x.tokens.len) continue;
const short, const long = if (o.tokens.len < x.tokens.len) .{ o, x } else .{ x, o };
- if (long.born < short.born or !std.mem.eql(u32, long.tokens[0..short.tokens.len], short.tokens)) continue;
+ if (long.born < short.born or !extends(short, long)) continue;
short.ext.append(s.gpa, long) catch {
s.links_lost = true;
};
From d5357ecfff096ca27baf608c34ef534e31d9d3a8 Mon Sep 17 00:00:00 2001
From: ashhart <71890694+ashhart@users.noreply.github.com>
Date: Fri, 20 Nov 2026 10:56:09 +0000
Subject: [PATCH 11/32] gemma4: retain cancelled CUDA prefill prefixes
---
zig/build/gemma4_shared_host.zig | 4 +
zig/gemma4_prefill_host.zig | 161 +++++++++++++++++++++++
zig/src/families/gemma4/cuda_backend.zig | 12 +-
3 files changed, 175 insertions(+), 2 deletions(-)
create mode 100644 zig/gemma4_prefill_host.zig
diff --git a/zig/build/gemma4_shared_host.zig b/zig/build/gemma4_shared_host.zig
index 1166c595874..6018fa6c648 100644
--- a/zig/build/gemma4_shared_host.zig
+++ b/zig/build/gemma4_shared_host.zig
@@ -6,4 +6,8 @@ pub fn host(b: *std.Build, cuda: *std.Build.Module, core: *std.Build.Module, lan
const run = b.addRunArtifact(b.addTest(.{ .root_module = root, .filters = &.{"Gemma shared:"} }));
b.step("test-gemma4-shared-host", "Gemma paged resumes, shared streams and MTP cache bindings without a GPU").dependOn(&run.step);
all.dependOn(&run.step);
+ const prefill_root = b.createModule(.{ .root_source_file = b.path("zig/gemma4_prefill_host.zig"), .target = b.graph.host, .link_libc = true, .imports = &.{ .{ .name = "cuda", .module = cuda }, .{ .name = "core", .module = core }, .{ .name = "engine_api", .module = api }, .{ .name = "lanes", .module = lanes }, .{ .name = "gemma4", .module = gemma } } });
+ const prefill_run = b.addRunArtifact(b.addTest(.{ .root_module = prefill_root, .filters = &.{"Gemma prefill:"} }));
+ b.step("test-gemma4-prefill-host", "Gemma 4 cancelled-prefill snapshots and exact resumed rows without a GPU").dependOn(&prefill_run.step);
+ all.dependOn(&prefill_run.step);
}
diff --git a/zig/gemma4_prefill_host.zig b/zig/gemma4_prefill_host.zig
new file mode 100644
index 00000000000..7a6bfc4eeed
--- /dev/null
+++ b/zig/gemma4_prefill_host.zig
@@ -0,0 +1,161 @@
+//! Real Gemma cancelled-prefill snapshots and restores with a deterministic row oracle, not checkpoint arithmetic.
+const std = @import("std");
+const g4 = @import("gemma4");
+const cuda = @import("cuda");
+const lanes = @import("lanes");
+const pc = @import("engine_api").prompt_cache;
+const fake = @import("gemma4_page_driver.zig");
+const a = std.testing.allocator;
+const t = std.testing;
+const cfg = g4.config;
+const fwd = g4.forward;
+const be = g4.backend;
+const geo: cfg.Geometry = .{ .name = "fixture", .hidden = 64, .layers = 6, .intermediate = 128, .query_heads = 2, .sliding_kv_heads = 1, .global_kv_heads = 1 };
+
+const Fixture = struct {
+ d: cuda.Driver,
+ m: fwd.Model,
+ g: be.Gemma,
+ k: g4.kernels.Kernels = undefined,
+
+ fn init(f: *Fixture) !void {
+ f.d = fake.driver();
+ const queue: cuda.Stream = .{ .d = &f.d, .handle = @ptrFromInt(1) };
+ f.m = .{ .gpa = a, .d = &f.d, .w = undefined, .geo = geo, .layers = 6, .context = 4096, .slots = 2, .kc = &.{}, .vc = &.{}, .inv_sliding = 0, .inv_global = 0, .s = undefined, .paged = false };
+ errdefer f.m.deinit();
+ f.m.kc = try a.alloc(u64, 6);
+ f.m.vc = try a.alloc(u64, 6);
+ try fwd.pages.build(&f.m, queue);
+ f.g = try be.Gemma.init(a, &f.d, &f.m, &f.k, queue);
+ }
+
+ fn deinit(f: *Fixture) void {
+ f.g.deinit();
+ f.m.deinit();
+ }
+
+ fn release(f: *Fixture, s: *lanes.Stream) void {
+ const b = f.g.backend();
+ b.vtable.release(b.ptr, s);
+ }
+};
+
+fn keep(ctx: *anyopaque, s: *lanes.Stream, at: u32) void {
+ const store: *pc.Store = @ptrCast(@alignCast(ctx));
+ _ = store.keep(s.prompt(), at, s, &.{}, &.{});
+}
+
+fn cancelled(_: *anyopaque) bool {
+ return true;
+}
+
+fn cancelNow(_: *anyopaque) bool {
+ return false;
+}
+
+fn stream(ids: []const u32, store: *pc.Store) !lanes.Stream {
+ return lanes.Stream.init(a, .{ .id = "fixture", .prompt = ids, .max_new = 16, .drafts = false, .reuse = .{ .hook = .{ .ptr = store, .at = keep, .interrupted = keep } }, .cancel_check = .{ .ptr = store, .check = cancelNow } });
+}
+
+fn prompt() ![]u32 {
+ const out = try a.alloc(u32, 2179);
+ for (out, 0..) |*x, i| x.* = @intCast(i % 97 + 3);
+ return out;
+}
+
+fn address(m: *const fwd.Model, cache: []const u64, layer: usize, slot: usize, position: usize) u64 {
+ const rb = m.geo.kvHeads(layer) * cfg.headDim(layer) * 2;
+ const row = slot * m.cacheLen(layer) + position % m.cacheLen(layer);
+ return cache[layer] + row * rb;
+}
+
+fn value(token: u32, position: usize, layer: usize, v: bool) u16 {
+ return @truncate(token *% 73 +% @as(u32, @truncate(position)) *% 17 +% @as(u32, @intCast(layer)) *% 101 +% @as(u32, @intFromBool(v)) *% 19);
+}
+
+fn advance(f: *Fixture, s: *lanes.Stream, l: anytype, end: usize) !void {
+ const start = l.fill.?;
+ for (start..end) |pos| for (0..f.m.layers) |i| for ([_][]u64{ f.m.kc, f.m.vc }, 0..) |cache, v| {
+ const row: [*]u16 = @ptrFromInt(address(&f.m, cache, i, l.slot, pos));
+ @memset(row[0 .. f.m.geo.kvHeads(i) * cfg.headDim(i)], value(s.prompt()[pos], pos, i, v == 1));
+ };
+ l.fill = if (end == s.prompt().len) null else end;
+ if (end == s.prompt().len) l.len = end;
+ s.fill_at.store(@intCast(end), .monotonic);
+ f.g.marked(s, end);
+}
+
+fn fill(f: *Fixture, s: *lanes.Stream) !u64 {
+ const l = try f.g.opening(s);
+ while (l.fill) |start| try advance(f, s, l, @min(s.prompt().len, (start / fwd.prompt_rows + 1) * fwd.prompt_rows));
+ return digest(&f.m, l.slot, s.prompt().len);
+}
+
+fn digest(m: *const fwd.Model, slot: usize, at: usize) u64 {
+ var hash = std.hash.Wyhash.init(0);
+ for (0..m.layers) |i| {
+ const first = if (cfg.global(i)) 0 else at - @min(at, cfg.window - 1);
+ for (first..at) |pos| for ([_][]u64{ m.kc, m.vc }) |cache| {
+ const row: [*]const u8 = @ptrFromInt(address(m, cache, i, slot, pos));
+ hash.update(row[0 .. m.geo.kvHeads(i) * cfg.headDim(i) * 2]);
+ };
+ }
+ return hash.final();
+}
+
+fn reply(hash: u64) [16]u32 {
+ var prng = std.Random.DefaultPrng.init(hash);
+ var out: [16]u32 = undefined;
+ for (&out) |*x| x.* = prng.random().uintLessThan(u32, cfg.vocab);
+ return out;
+}
+
+fn resumedAfterCancel(between_steps: bool) !struct { fresh: [16]u32, resumed: [16]u32, cached: u64, identity: bool } {
+ var f: Fixture = undefined;
+ try f.init();
+ defer f.deinit();
+ var store = pc.Store.init(a, .{ .ptr = &f.g, .vtable = &.{ .bytes = g4.native.snap_bytes, .save = g4.native.snap_save, .restore = g4.native.snap_restore, .drop = g4.native.snap_drop } }, .{ .lookahead = 0, .min_prompt = 0, .chunk = fwd.prompt_rows }, 1 << 30);
+ defer store.deinit();
+ const ids = try prompt();
+ defer a.free(ids);
+ var plain = try stream(ids, &store);
+ defer plain.deinit(a);
+ const fresh = reply(try fill(&f, &plain));
+ f.release(&plain);
+
+ var stopped = try stream(ids, &store);
+ defer stopped.deinit(a);
+ const l = try f.g.opening(&stopped);
+ try advance(&f, &stopped, l, fwd.prompt_rows);
+ const b = f.g.backend();
+ if (between_steps) {
+ if (b.vtable.cancel_prefill) |keep_prefix| try keep_prefix(b.ptr, &stopped);
+ f.release(&stopped);
+ } else {
+ stopped.cancel_check = .{ .ptr = &stopped, .check = cancelled };
+ try t.expectError(error.Cancelled, b.vtable.prefill_step.?(b.ptr, &stopped, 0));
+ }
+
+ const found = store.find(ids, &.{}, &.{});
+ var resumed = try stream(ids, &store);
+ defer resumed.deinit(a);
+ if (found) |entry| {
+ resumed.reuse.saved = entry.saved;
+ resumed.reuse.at = entry.at;
+ }
+ const rl = try f.g.opening(&resumed);
+ const identity = if (found) |entry| resumed.reuse.saved == entry.saved else false;
+ while (rl.fill) |start| try advance(&f, &resumed, rl, @min(ids.len, (start / fwd.prompt_rows + 1) * fwd.prompt_rows));
+ const got = reply(digest(&f.m, rl.slot, ids.len));
+ f.release(&resumed);
+ return .{ .fresh = fresh, .resumed = got, .cached = resumed.cached, .identity = identity };
+}
+
+test "Gemma prefill: cancelled chunks retain exact fresh replies and cache identity" {
+ for ([_]bool{ false, true }) |between_steps| {
+ const out = try resumedAfterCancel(between_steps);
+ try t.expectEqualSlices(u32, &out.fresh, &out.resumed);
+ try t.expectEqual(@as(u64, fwd.prompt_rows), out.cached);
+ try t.expect(out.identity);
+ }
+}
diff --git a/zig/src/families/gemma4/cuda_backend.zig b/zig/src/families/gemma4/cuda_backend.zig
index c2b87d38bc8..2f6225f28ac 100644
--- a/zig/src/families/gemma4/cuda_backend.zig
+++ b/zig/src/families/gemma4/cuda_backend.zig
@@ -126,7 +126,7 @@ pub const Gemma = struct {
return .{ .ptr = x, .vtable = &vtable };
}
- const vtable: be.Backend.VTable = .{ .prefill = prefill, .prefill_step = prefillStep, .first = first, .first_masked = firstMasked, .queue = queue, .read = read, .verify = verify, .keep = keep, .draft = draft, .release = release, .reports_fill = true, .prepare_features = prepareFeatures, .features = features, .prefill_features = prefillFeatures };
+ const vtable: be.Backend.VTable = .{ .prefill = prefill, .prefill_step = prefillStep, .cancel_prefill = cancelPrefill, .first = first, .first_masked = firstMasked, .queue = queue, .read = read, .verify = verify, .keep = keep, .draft = draft, .release = release, .reports_fill = true, .prepare_features = prepareFeatures, .features = features, .prefill_features = prefillFeatures };
/// The drafter's taps: those layers' outputs (before the next norm), kept by every forward from now on.
fn prepareFeatures(ptr: *anyopaque, taps: []const u32) anyerror!void {
@@ -343,7 +343,10 @@ pub const Gemma = struct {
fn chunk(x: *Gemma, s: *Stream, l: *Lane, streamed: bool, _: u32) !bool {
const p = s.prompt();
const at = l.fill.?;
- if (s.isCancelled()) return error.Cancelled;
+ if (s.isCancelled()) {
+ s.keepInterruptedPrefill(@intCast(at));
+ return error.Cancelled;
+ }
// solo passes (TF_GEMMA4_CHUNK_SOLO) only without a drafter's taps, at most `injects` images a pass
const solo = lanes.solo_chunk.passRows(&x.lanes, s, "fill", x.m.prompt_most, prompt_rows);
const rows = if (x.tapped or s.images.len > max_injects) prompt_rows else solo;
@@ -415,6 +418,11 @@ pub const Gemma = struct {
return done;
}
+ fn cancelPrefill(ptr: *anyopaque, s: *Stream) anyerror!void {
+ const l = self(ptr).lanes.getPtr(s) orelse return;
+ if (l.fill) |at| s.keepInterruptedPrefill(@intCast(at));
+ }
+
fn handle(x: *Gemma) usize {
const h = x.next;
x.next += 1;
From 6a9753cf823d99c22ce6dbb71bb7dd9e6eaa93e5 Mon Sep 17 00:00:00 2001
From: ashhart <71890694+ashhart@users.noreply.github.com>
Date: Fri, 20 Nov 2026 10:57:54 +0000
Subject: [PATCH 12/32] nemotron: retain cancelled HIP prefill prefixes
---
zig/build/hip.zig | 4 +-
zig/src/families/nemotron/hip/prompt_test.zig | 96 ++++++++++++++++++-
zig/src/hip_serve/backend.zig | 9 ++
3 files changed, 105 insertions(+), 4 deletions(-)
diff --git a/zig/build/hip.zig b/zig/build/hip.zig
index 3629da26fc3..d859f82c5f9 100644
--- a/zig/build/hip.zig
+++ b/zig/build/hip.zig
@@ -192,7 +192,9 @@ pub fn steps(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.buil
b.step("test-qwen35-hip-host", "Qwen HIP family CPU tests with inert kernels").dependOn(&family_host.step);
test_step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = host.flashnext })).step);
b.step("test-flashnext-proposal-hip-host", "Original Flash Next HIP IDs and head-row spans without device runtime").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = host.flashnext, .filters = &.{"Flash Next proposal:"} })).step);
- test_step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = host.nemotron })).step);
+ const nemotron_host = b.addRunArtifact(b.addTest(.{ .root_module = host.nemotron }));
+ test_step.dependOn(&nemotron_host.step);
+ b.step("test-nemotron-hip-host", "Nemotron HIP prompt adapters and cancelled-prefix snapshots without GPU execution").dependOn(&nemotron_host.step);
const qwen3_host = b.addRunArtifact(b.addTest(.{ .root_module = host.qwen3 }));
test_step.dependOn(&qwen3_host.step);
b.step("test-qwen3-hip-host", "Qwen3 dense config, checkpoint prefix and lm_head rows on the CPU").dependOn(&qwen3_host.step);
diff --git a/zig/src/families/nemotron/hip/prompt_test.zig b/zig/src/families/nemotron/hip/prompt_test.zig
index 2606e9b3cc3..1f1844ff76f 100644
--- a/zig/src/families/nemotron/hip/prompt_test.zig
+++ b/zig/src/families/nemotron/hip/prompt_test.zig
@@ -101,12 +101,18 @@ const Fake = struct {
e: *RecordedEngine,
streams: serve.backend.Streams(source.Lane),
tp: serve.protocol.Sender,
+ prefix: void = {},
lane: *source.Lane,
head: ?*NoHead = null,
sampler: Sampler,
drawer_state: Drawer = .{},
chunk_rows: usize,
start: usize,
+ cut: usize = 0,
+ state: u64 = 0,
+ saved_at: usize = 0,
+ saved_state: u64 = 0,
+ saved_valid: bool = false,
kept: usize = 0,
pub const cancelOf = source.Hip.cancelOf;
@@ -125,6 +131,7 @@ const Fake = struct {
r.layers += 1;
try forward.traceLayer(ctx.trace, layer, .{ .ptr = 1, .kind = .bf16 }, rows);
}
+ for (pos..pos + rows) |i| h.state = (h.state *% 16777619) ^ @as(u64, @intCast(i + 1));
return .{ .ptr = 1, .kind = .bf16 };
}
@@ -133,8 +140,16 @@ const Fake = struct {
}
pub fn begin(h: *Fake, s: *lanes.Stream) !*source.Lane {
- h.lane.fill = serve.backend.Fill.init(h.start, &.{@intCast(h.start + h.chunk_rows)});
- h.lane.s.len = h.start;
+ const from: usize = if (s.reuse.saved != null) s.reuse.at else h.start;
+ const cut = if (h.cut != 0) h.cut else from + h.chunk_rows;
+ h.lane.fill = serve.backend.Fill.init(from, &.{@intCast(cut)});
+ h.lane.s.len = from;
+ if (s.reuse.saved != null) {
+ try T.expect(h.saved_valid);
+ try T.expectEqual(h.saved_at, from);
+ h.state = h.saved_state;
+ } else h.state = 0;
+ s.cached = @intCast(from);
h.lane.id = try h.streams.idOf(s);
try h.streams.map.put(h.gpa, s, h.lane);
return h.lane;
@@ -144,8 +159,11 @@ const Fake = struct {
return @min(at + h.chunk_rows, limit);
}
- pub fn keepCut(h: *Fake, _: *source.Lane, _: []const u32, _: usize) !void {
+ pub fn keepCut(h: *Fake, _: *source.Lane, _: []const u32, at: usize) !void {
h.kept += 1;
+ h.saved_at = at;
+ h.saved_state = h.state;
+ h.saved_valid = true;
}
pub fn keepRows(_: *Fake, _: *source.Lane, _: usize) !void {}
@@ -238,6 +256,78 @@ test "Nemotron final prompt chunks cancel before progress logits or a first draw
};
}
+test "Nemotron cancellation between prompt cuts resumes with the exact fresh recurrent state" {
+ const rows = 64;
+ var tokens: [3 * rows]u32 = @splat(1);
+ var flag: Flag = .{};
+ var r: Record = .{ .flag = &flag, .cancel_inside = false };
+ Inert.runtime.api.hipCtxSetCurrent = current;
+ Inert.runtime.api.hipStreamSynchronize = synchronize;
+ var e: RecordedEngine = .{
+ .rec = &r,
+ .ctx = .{ .r = &Inert.runtime, .device = 0, .handle = null },
+ .stream = .{ .r = &Inert.runtime, .handle = @ptrCast(&r) },
+ .o = .{ .world = 1 },
+ };
+ e.m.dims.hidden = 1;
+ var lane: source.Lane = undefined;
+ lane.fill = null;
+ lane.first_row = null;
+ lane.pending = null;
+ lane.held_n = 0;
+ lane.resumed = false;
+ lane.hidden = .{ .r = &Inert.runtime, .ptr = @ptrFromInt(1), .len = 2 };
+ var h: Fake = .{
+ .gpa = T.allocator,
+ .e = &e,
+ .streams = serve.backend.Streams(source.Lane).init(T.allocator),
+ .tp = .{ .gpa = T.allocator },
+ .lane = &lane,
+ .sampler = .{ .rec = &r },
+ .chunk_rows = rows,
+ .start = 0,
+ .cut = 2 * rows,
+ };
+ defer h.streams.deinit();
+ const b = serve.backend.Backend(Fake).backend(&h);
+ const step = b.vtable.prefill_step.?;
+
+ var cancelled = try lanes.Stream.init(T.allocator, .{ .id = "cancelled", .prompt = &tokens, .max_new = 8 });
+ defer cancelled.deinit(T.allocator);
+ try T.expect(!try step(b.ptr, &cancelled, 0));
+ try T.expectEqual(rows, lane.fill.?.at);
+ try T.expect(!h.saved_valid);
+ if (b.vtable.cancel_prefill) |keep| try keep(b.ptr, &cancelled);
+ try T.expect(h.saved_valid);
+ try T.expectEqual(rows, h.saved_at);
+ try T.expectEqual(h.state, h.saved_state);
+ b.vtable.release(b.ptr, &cancelled);
+ h.state = 0;
+
+ var resumed = try lanes.Stream.init(T.allocator, .{
+ .id = "resumed",
+ .prompt = &tokens,
+ .max_new = 8,
+ .reuse = .{ .saved = @ptrCast(&h.saved_state), .at = rows },
+ });
+ defer resumed.deinit(T.allocator);
+ try T.expect(!try step(b.ptr, &resumed, 0));
+ try T.expectEqual(rows, resumed.cached);
+ try T.expect(try step(b.ptr, &resumed, 0));
+ const resumed_state = h.state;
+ b.vtable.release(b.ptr, &resumed);
+
+ h.saved_valid = false;
+ var fresh = try lanes.Stream.init(T.allocator, .{ .id = "fresh", .prompt = &tokens, .max_new = 8 });
+ defer fresh.deinit(T.allocator);
+ try T.expect(!try step(b.ptr, &fresh, 0));
+ try T.expect(!try step(b.ptr, &fresh, 0));
+ try T.expect(try step(b.ptr, &fresh, 0));
+ try T.expectEqual(tokens.len, lane.s.len);
+ try T.expectEqual(resumed_state, h.state);
+ b.vtable.release(b.ptr, &fresh);
+}
+
test "Nemotron layer traces keep non-cancel failures as BadShape" {
const Fail = struct {
fn layer(_: *anyopaque, _: usize, _: hip.ops.Tensor, _: usize) anyerror!void {
diff --git a/zig/src/hip_serve/backend.zig b/zig/src/hip_serve/backend.zig
index dc1c7d5f24a..41e81a13db4 100644
--- a/zig/src/hip_serve/backend.zig
+++ b/zig/src/hip_serve/backend.zig
@@ -198,6 +198,7 @@ pub fn Backend(comptime F: type) type {
const vtable: be.Backend.VTable = .{
.prefill = prefillFn,
.prefill_step = prefillStepFn,
+ .cancel_prefill = if (@hasField(F, "prefix")) cancelPrefillFn else null,
.first = firstFn,
.first_masked = firstMaskedFn,
.held = heldTokensFn,
@@ -225,6 +226,14 @@ pub fn Backend(comptime F: type) type {
while (!try prefillStepFn(ptr, s, 0)) {} // whole prompts: the 512-row cap would cut where this driver never does
}
+ fn cancelPrefillFn(ptr: *anyopaque, s: *lanes.Stream) anyerror!void {
+ const h = of(ptr);
+ const lane = try h.streams.get(s);
+ const f = lane.fill orelse return;
+ if (s.readout != null or f.at <= s.cached) return;
+ try h.keepCut(lane, s.prompt(), f.at);
+ }
+
/// One chunk of the prompt pass, ending on the next cut or the prompt's end; the last draws the first token.
fn prefillStepFn(ptr: *anyopaque, s: *lanes.Stream, _: u32) anyerror!bool {
const h = of(ptr);
From 8c76698fb4142d4990007bfb25248b3da582a630 Mon Sep 17 00:00:00 2001
From: ashhart <71890694+ashhart@users.noreply.github.com>
Date: Fri, 20 Nov 2026 11:00:10 +0000
Subject: [PATCH 13/32] llama: retain cancelled prompt chunks
---
build.llama-prefill.zig | 15 ++++++++++++
zig/src/families/llama/backend.zig | 38 +++++++++++++++++++++++++++++-
zig/src/families/llama/llama.zig | 1 +
zig/src/llama_prefill_host.zig | 3 +++
4 files changed, 56 insertions(+), 1 deletion(-)
create mode 100644 build.llama-prefill.zig
create mode 100644 zig/src/llama_prefill_host.zig
diff --git a/build.llama-prefill.zig b/build.llama-prefill.zig
new file mode 100644
index 00000000000..e027a1a00da
--- /dev/null
+++ b/build.llama-prefill.zig
@@ -0,0 +1,15 @@
+const std = @import("std");
+const metal = @import("zig/build/metal_targets.zig");
+
+pub fn build(b: *std.Build) void {
+ const ids_files = b.addWriteFiles();
+ _ = ids_files.addCopyFile(b.path("zig/src/families/nemotron/draft_ids.txt"), "draft_ids.txt");
+ const draft_ids = b.createModule(.{ .root_source_file = ids_files.add("draft_ids.zig", "pub const text = @embedFile(\"draft_ids.txt\");") });
+ const mods = metal.metalEngineModules(b, b.graph.host, .Debug, draft_ids);
+ const empty = b.addWriteFiles().add("llama-prefill-empty.metallib", "");
+ mods.sources.addImport("nemotron_packed_metallib", metal.embedded(b, empty, "nemotron_packed.metallib"));
+ const llama = b.createModule(.{ .root_source_file = b.path("zig/src/llama_prefill_host.zig"), .target = b.graph.host, .optimize = .Debug, .link_libc = true, .imports = &.{ .{ .name = "metal", .module = mods.metal }, .{ .name = "lanes", .module = mods.lanes }, .{ .name = "kernel_sources", .module = mods.sources } } });
+ const run = b.addRunArtifact(b.addTest(.{ .root_module = llama, .filters = &.{"llama prefill:"} }));
+ b.step("test", "Llama's cancelled-prefill checkpoint without GPU work").dependOn(&run.step);
+ @import("zig/build/profile.zig").walk(b);
+}
diff --git a/zig/src/families/llama/backend.zig b/zig/src/families/llama/backend.zig
index cb6d81a345e..4114b2dea84 100644
--- a/zig/src/families/llama/backend.zig
+++ b/zig/src/families/llama/backend.zig
@@ -179,7 +179,7 @@ pub const Metal = struct {
while (at < ids.len) {
var end = @min(ids.len, at + st.prompt_rows);
if (stream) |sm| {
- if (sm.isCancelled()) return error.Cancelled;
+ try checkCancelled(sm, cache.len);
for (sm.chunks) |x| if (x > base + at and x < base + end) {
end = x - base;
};
@@ -439,3 +439,39 @@ fn argmax(l: []const u16) usize {
};
return best;
}
+
+fn checkCancelled(s: *lanes.Stream, at: usize) error{Cancelled}!void {
+ if (!s.isCancelled()) return;
+ s.keepInterruptedPrefill(@intCast(at));
+ return error.Cancelled;
+}
+
+test "llama prefill: cancellation keeps a restored pass's last completed chunk" {
+ const Observer = struct {
+ cancelled: bool = false,
+ marked: usize = 0,
+ interrupted: ?u32 = null,
+ fn cancel(ptr: *anyopaque) bool {
+ return @as(*@This(), @ptrCast(@alignCast(ptr))).cancelled;
+ }
+ fn mark(ptr: *anyopaque, _: *lanes.Stream, _: u32) void {
+ @as(*@This(), @ptrCast(@alignCast(ptr))).marked += 1;
+ }
+ fn interrupt(ptr: *anyopaque, _: *lanes.Stream, at: u32) void {
+ @as(*@This(), @ptrCast(@alignCast(ptr))).interrupted = at;
+ }
+ };
+ var observer: Observer = .{};
+ const ids: [2 * st.prompt_rows + 17]u32 = @splat(3);
+ var stream = try lanes.Stream.init(std.testing.allocator, .{ .id = "cancel", .prompt = &ids, .max_new = 4, .drafts = false, .cancel_check = .{ .ptr = &observer, .check = Observer.cancel }, .reuse = .{ .hook = .{ .ptr = &observer, .at = Observer.mark, .interrupted = Observer.interrupt } } });
+ defer stream.deinit(std.testing.allocator);
+ stream.cached = 64;
+ const at = 64 + st.prompt_rows;
+ try checkCancelled(&stream, at);
+ try std.testing.expectEqual(@as(usize, 0), observer.marked);
+ try std.testing.expectEqual(@as(?u32, null), observer.interrupted);
+ observer.cancelled = true;
+ try std.testing.expectError(error.Cancelled, checkCancelled(&stream, at));
+ try std.testing.expectEqual(@as(usize, 0), observer.marked);
+ try std.testing.expectEqual(@as(?u32, @intCast(at)), observer.interrupted);
+}
diff --git a/zig/src/families/llama/llama.zig b/zig/src/families/llama/llama.zig
index b02b6f1127b..dbc078fefe0 100644
--- a/zig/src/families/llama/llama.zig
+++ b/zig/src/families/llama/llama.zig
@@ -20,6 +20,7 @@ test {
_ = state;
_ = budget;
_ = snapshot;
+ _ = backend;
_ = drafter;
_ = @import("drafter_test.zig");
_ = pricing;
diff --git a/zig/src/llama_prefill_host.zig b/zig/src/llama_prefill_host.zig
new file mode 100644
index 00000000000..6810e9648ed
--- /dev/null
+++ b/zig/src/llama_prefill_host.zig
@@ -0,0 +1,3 @@
+test {
+ _ = @import("families/llama/backend.zig");
+}
From d9f89b7b03882ce5a24bb54a6c4a349332d1db26 Mon Sep 17 00:00:00 2001
From: ashhart <71890694+ashhart@users.noreply.github.com>
Date: Fri, 20 Nov 2026 11:05:00 +0000
Subject: [PATCH 14/32] spark25: retain cancelled prompt chunks
---
zig/build/spark25.zig | 7 +
zig/spark25_prefill_host.zig | 206 +++++++++++++++++++++++++++
zig/src/families/spark25/backend.zig | 14 +-
3 files changed, 224 insertions(+), 3 deletions(-)
create mode 100644 zig/spark25_prefill_host.zig
diff --git a/zig/build/spark25.zig b/zig/build/spark25.zig
index ac977b30e1f..22d84600740 100644
--- a/zig/build/spark25.zig
+++ b/zig/build/spark25.zig
@@ -8,5 +8,12 @@ pub fn module(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.bui
pub fn host(b: *std.Build, m: *std.Build.Module, all: *std.Build.Step) void {
const run = b.addRunArtifact(b.addTest(.{ .root_module = m }));
b.step("test-spark25-host", "Spark2.5 config admission, RoPE tables, cache sizes, snapshot runs and refusals without a GPU").dependOn(&run.step);
+ const core = m.import_table.get("core").?;
+ const lanes = m.import_table.get("lanes").?;
+ const api = b.createModule(.{ .root_source_file = b.path("zig/src/core/engine_api.zig"), .target = b.graph.host, .link_libc = true, .imports = &.{.{ .name = "lanes", .module = lanes }} });
+ const prefill_root = b.createModule(.{ .root_source_file = b.path("zig/spark25_prefill_host.zig"), .target = b.graph.host, .link_libc = true, .imports = &.{ .{ .name = "cuda", .module = m.import_table.get("cuda").? }, .{ .name = "core", .module = core }, .{ .name = "engine_api", .module = api }, .{ .name = "lanes", .module = lanes }, .{ .name = "spark25", .module = m } } });
+ const prefill_run = b.addRunArtifact(b.addTest(.{ .root_module = prefill_root, .filters = &.{"Spark25 prefill:"} }));
+ b.step("test-spark25-prefill-host", "Spark2.5 cancelled-prefill snapshots and exact resumed rows without a GPU").dependOn(&prefill_run.step);
all.dependOn(&run.step);
+ all.dependOn(&prefill_run.step);
}
diff --git a/zig/spark25_prefill_host.zig b/zig/spark25_prefill_host.zig
new file mode 100644
index 00000000000..b168bdcb9a3
--- /dev/null
+++ b/zig/spark25_prefill_host.zig
@@ -0,0 +1,206 @@
+//! Real Spark2.5 cancelled-prefill snapshots and restores with deterministic cache rows, not checkpoint arithmetic.
+const std = @import("std");
+const spark = @import("spark25");
+const cuda = @import("cuda");
+const lanes = @import("lanes");
+const pc = @import("engine_api").prompt_cache;
+const fake = @import("gemma4_page_driver.zig");
+const a = std.testing.allocator;
+const t = std.testing;
+const cfg = spark.config;
+const fwd = spark.forward;
+const be = spark.backend;
+const geo: cfg.Geometry = .{ .hidden = 64, .layers = 4, .intermediate = 128, .query_heads = 1, .kv_heads = 1 };
+
+const Fixture = struct {
+ d: cuda.Driver,
+ m: fwd.Model,
+ g: be.Spark,
+ k: spark.kernels.Kernels = undefined,
+
+ fn init(f: *Fixture) !void {
+ f.d = fake.driver();
+ const queue: cuda.Stream = .{ .d = &f.d, .handle = @ptrFromInt(1) };
+ f.m = .{ .gpa = a, .d = &f.d, .w = undefined, .geo = geo, .layers = geo.layers, .context = 4096, .slots = 2, .kc = &.{}, .vc = &.{}, .inv_sliding = 0, .inv_full = 0, .s = undefined, .paged = false };
+ errdefer f.m.deinit();
+ f.m.kc = try a.alloc(u64, geo.layers);
+ f.m.vc = try a.alloc(u64, geo.layers);
+ for (0..geo.layers) |i| {
+ f.m.kc[i] = try f.cache(i);
+ f.m.vc[i] = try f.cache(i);
+ }
+ f.g = try be.Spark.init(a, &f.d, &f.m, &f.k, queue);
+ }
+
+ fn cache(f: *Fixture, layer: usize) !u64 {
+ const bytes = f.m.slots * f.m.cacheLen(layer) * f.m.geo.kvWidth() * 2;
+ var b = try cuda.DeviceBuffer.alloc(&f.d, bytes);
+ errdefer b.free();
+ try f.m.buffers.append(a, b);
+ return b.ptr;
+ }
+
+ fn deinit(f: *Fixture) void {
+ f.g.deinit();
+ f.m.deinit();
+ }
+
+ fn release(f: *Fixture, s: *lanes.Stream) void {
+ const b = f.g.backend();
+ b.vtable.release(b.ptr, s);
+ }
+};
+
+fn keep(ctx: *anyopaque, s: *lanes.Stream, at: u32) void {
+ const store: *pc.Store = @ptrCast(@alignCast(ctx));
+ _ = store.keep(s.prompt(), at, s, &.{}, &.{});
+}
+
+fn cancelled(_: *anyopaque) bool {
+ return true;
+}
+
+fn cancelNow(_: *anyopaque) bool {
+ return false;
+}
+
+fn stream(ids: []const u32, store: *pc.Store) !lanes.Stream {
+ return lanes.Stream.init(a, .{ .id = "fixture", .prompt = ids, .max_new = 16, .drafts = false, .reuse = .{ .hook = .{ .ptr = store, .at = keep, .interrupted = keep } }, .cancel_check = .{ .ptr = store, .check = cancelNow } });
+}
+
+fn prompt(scrub: bool) ![]u32 {
+ const out = try a.alloc(u32, 2179);
+ for (out, 0..) |*x, i| x.* = @intCast(if (scrub) i % 89 + 500 else i % 97 + 3);
+ return out;
+}
+
+fn address(m: *const fwd.Model, cache: []const u64, layer: usize, slot: usize, position: usize) u64 {
+ const rb = m.geo.kvWidth() * 2;
+ const row = slot * m.cacheLen(layer) + position % m.cacheLen(layer);
+ return cache[layer] + row * rb;
+}
+
+fn value(token: u32, position: usize, layer: usize, v: bool) u16 {
+ return @truncate(token *% 73 +% @as(u32, @truncate(position)) *% 17 +% @as(u32, @intCast(layer)) *% 101 +% @as(u32, @intFromBool(v)) *% 19);
+}
+
+fn marked(s: *lanes.Stream, end: usize) void {
+ if (s.reuse.hook) |hk| if (std.mem.indexOfScalar(u32, s.reuse.marks, @intCast(end)) != null) hk.at(hk.ptr, s, @intCast(end));
+}
+
+fn advance(f: *Fixture, s: *lanes.Stream, l: anytype, end: usize) !void {
+ const start = l.fill.?;
+ for (start..end) |pos| for (0..f.m.layers) |i| for ([_][]u64{ f.m.kc, f.m.vc }, 0..) |cache, v| {
+ const row: [*]u16 = @ptrFromInt(address(&f.m, cache, i, l.slot, pos));
+ @memset(row[0..f.m.geo.kvWidth()], value(s.prompt()[pos], pos, i, v == 1));
+ };
+ l.fill = if (end == s.prompt().len) null else end;
+ if (end == s.prompt().len) l.len = end;
+ s.fill_at.store(@intCast(end), .monotonic);
+ marked(s, end);
+}
+
+fn fill(f: *Fixture, s: *lanes.Stream) !u64 {
+ const l = try f.g.opening(s);
+ while (l.fill) |start| try advance(f, s, l, @min(s.prompt().len, (start / fwd.prompt_rows + 1) * fwd.prompt_rows));
+ return digest(&f.m, l.slot, s.prompt().len);
+}
+
+fn digest(m: *const fwd.Model, slot: usize, at: usize) u64 {
+ var hash = std.hash.Wyhash.init(0);
+ for (0..m.layers) |i| {
+ const first = if (cfg.full(i)) 0 else at - @min(at, cfg.window - 1);
+ for (first..at) |pos| for ([_][]u64{ m.kc, m.vc }) |cache| {
+ const row: [*]const u8 = @ptrFromInt(address(m, cache, i, slot, pos));
+ hash.update(row[0 .. m.geo.kvWidth() * 2]);
+ };
+ }
+ return hash.final();
+}
+
+fn reply(hash: u64) [16]u32 {
+ var prng = std.Random.DefaultPrng.init(hash);
+ var out: [16]u32 = undefined;
+ for (&out) |*x| x.* = prng.random().uintLessThan(u32, cfg.vocab);
+ return out;
+}
+
+const Outcome = struct {
+ fresh: [16]u32,
+ resumed: [16]u32,
+ stopped: u64,
+ restored: u64,
+ cached: u64,
+ identity: bool,
+ needed: u64,
+ entries: usize,
+ held: u64,
+ refused: u64,
+};
+
+fn resumedAfterCancel(between_steps: bool, shortage: u64) !Outcome {
+ var f: Fixture = undefined;
+ try f.init();
+ defer f.deinit();
+ const needed = spark.native.snap_bytes(&f.g, fwd.prompt_rows);
+ var store = pc.Store.init(a, .{ .ptr = &f.g, .vtable = &.{ .bytes = spark.native.snap_bytes, .save = spark.native.snap_save, .restore = spark.native.snap_restore, .drop = spark.native.snap_drop } }, .{ .lookahead = 0, .min_prompt = 0, .chunk = fwd.prompt_rows }, needed -| shortage);
+ defer store.deinit();
+ const ids = try prompt(false);
+ defer a.free(ids);
+ const scrub = try prompt(true);
+ defer a.free(scrub);
+ var plain = try stream(ids, &store);
+ defer plain.deinit(a);
+ const fresh = reply(try fill(&f, &plain));
+ f.release(&plain);
+
+ var stopped = try stream(ids, &store);
+ defer stopped.deinit(a);
+ const l = try f.g.opening(&stopped);
+ try advance(&f, &stopped, l, fwd.prompt_rows);
+ const stopped_state = digest(&f.m, l.slot, fwd.prompt_rows);
+ const b = f.g.backend();
+ if (between_steps) {
+ if (b.vtable.cancel_prefill) |keep_prefix| try keep_prefix(b.ptr, &stopped);
+ f.release(&stopped);
+ } else {
+ stopped.cancel_check = .{ .ptr = &stopped, .check = cancelled };
+ try t.expectError(error.Cancelled, b.vtable.prefill_step.?(b.ptr, &stopped, 0));
+ }
+
+ var other = try stream(scrub, &store);
+ defer other.deinit(a);
+ _ = try fill(&f, &other);
+ f.release(&other);
+ const found = store.find(ids, &.{}, &.{});
+ var resumed = try stream(ids, &store);
+ defer resumed.deinit(a);
+ if (found) |entry| {
+ resumed.reuse.saved = entry.saved;
+ resumed.reuse.at = entry.at;
+ }
+ const rl = try f.g.opening(&resumed);
+ const identity = if (found) |entry| resumed.reuse.saved == entry.saved else false;
+ const restored = digest(&f.m, rl.slot, rl.fill.?);
+ while (rl.fill) |start| try advance(&f, &resumed, rl, @min(ids.len, (start / fwd.prompt_rows + 1) * fwd.prompt_rows));
+ const got = reply(digest(&f.m, rl.slot, ids.len));
+ f.release(&resumed);
+ return .{ .fresh = fresh, .resumed = got, .stopped = stopped_state, .restored = restored, .cached = resumed.cached, .identity = identity, .needed = needed, .entries = store.entries.items.len, .held = store.held, .refused = store.counts.refused };
+}
+
+test "Spark25 prefill: cancelled chunks retain exact fresh replies within cache capacity" {
+ for ([_]bool{ false, true }) |between_steps| {
+ for ([_]u64{ 0, 1 }) |shortage| {
+ const out = try resumedAfterCancel(between_steps, shortage);
+ const fits = shortage == 0;
+ try t.expectEqualSlices(u32, &out.fresh, &out.resumed);
+ try t.expectEqual(if (fits) @as(u64, fwd.prompt_rows) else 0, out.cached);
+ try t.expectEqual(fits, out.identity);
+ try t.expectEqual(@as(usize, @intFromBool(fits)), out.entries);
+ try t.expectEqual(if (fits) out.needed else 0, out.held);
+ try t.expectEqual(@as(u64, @intFromBool(!fits)), out.refused);
+ if (fits) try t.expectEqual(out.stopped, out.restored);
+ try t.expect(fake.empty());
+ }
+ }
+}
diff --git a/zig/src/families/spark25/backend.zig b/zig/src/families/spark25/backend.zig
index 8e18e4816d3..d170bbd5336 100644
--- a/zig/src/families/spark25/backend.zig
+++ b/zig/src/families/spark25/backend.zig
@@ -129,7 +129,7 @@ pub const Spark = struct {
return .{ .ptr = x, .vtable = &vtable };
}
- const vtable: be.Backend.VTable = .{ .prefill = prefill, .prefill_step = prefillStep, .first = first, .queue = queue, .read = read, .verify = verify, .keep = keep, .draft = draft, .release = release, .reports_fill = true };
+ const vtable: be.Backend.VTable = .{ .prefill = prefill, .prefill_step = prefillStep, .cancel_prefill = cancelPrefill, .first = first, .queue = queue, .read = read, .verify = verify, .keep = keep, .draft = draft, .release = release, .reports_fill = true };
/// The round loop's facts: no draft head; host copies verified in windows up to 16 rows, streams sharing a forward.
pub fn facts(x: *const Spark) lanes.Model {
@@ -256,7 +256,7 @@ pub const Spark = struct {
}
/// A prompt pass begins: a slot, the stream's rule, a kept state restored; where its first chunk starts.
- fn opening(x: *Spark, s: *Stream) !*Lane {
+ pub fn opening(x: *Spark, s: *Stream) !*Lane {
const p = s.prompt();
if (p.len == 0) return error.EmptyPrompt;
if (s.images.len > 0) return error.SparkTextOnly;
@@ -332,7 +332,10 @@ pub const Spark = struct {
fn chunk(x: *Spark, s: *Stream, l: *Lane, _: u32) !bool {
const p = s.prompt();
const at = l.fill.?;
- if (s.isCancelled()) return error.Cancelled;
+ if (s.isCancelled()) {
+ s.keepInterruptedPrefill(@intCast(at));
+ return error.Cancelled;
+ }
var end = @min(p.len, (at / prompt_rows + 1) * prompt_rows);
const marks = if (x.prompts != null) l.marks else s.reuse.marks;
for (marks) |mk| if (mk > at and mk < end) {
@@ -371,6 +374,11 @@ pub const Spark = struct {
return x.chunk(s, l, 0);
}
+ fn cancelPrefill(ptr: *anyopaque, s: *Stream) anyerror!void {
+ const l = self(ptr).lanes.getPtr(s) orelse return;
+ if (l.fill) |at| s.keepInterruptedPrefill(@intCast(at));
+ }
+
fn handle(x: *Spark) usize {
const h = x.next;
x.next += 1;
From 2ba3a8bd6dbc6828eb8cfdbdb2bfa1efe780366d Mon Sep 17 00:00:00 2001
From: ashhart <71890694+ashhart@users.noreply.github.com>
Date: Fri, 20 Nov 2026 11:08:27 +0000
Subject: [PATCH 15/32] dory: retain cancelled prompt chunks
---
zig/build/dory.zig | 7 +
zig/dory_prefill_host.zig | 208 +++++++++++++++++++++++++
zig/src/families/dory/cuda_backend.zig | 15 +-
3 files changed, 227 insertions(+), 3 deletions(-)
create mode 100644 zig/dory_prefill_host.zig
diff --git a/zig/build/dory.zig b/zig/build/dory.zig
index 41b3884ac30..d5ef40ac148 100644
--- a/zig/build/dory.zig
+++ b/zig/build/dory.zig
@@ -12,5 +12,12 @@ pub fn host(b: *std.Build, m: *std.Build.Module, all: *std.Build.Step) void {
const loader = b.addRunArtifact(b.addTest(.{ .root_module = m, .filters = &.{"Dory loader:"} }));
b.step("test-dory-loader-host", "Dory load refusals and device ownership under host allocation failure").dependOn(&loader.step);
const upload = b.addRunArtifact(b.addTest(.{ .root_module = m, .filters = &.{"Dory queued upload:"} }));
+ const core = m.import_table.get("core").?;
+ const lanes = m.import_table.get("lanes").?;
+ const api = b.createModule(.{ .root_source_file = b.path("zig/src/core/engine_api.zig"), .target = b.graph.host, .link_libc = true, .imports = &.{.{ .name = "lanes", .module = lanes }} });
+ const prefill_root = b.createModule(.{ .root_source_file = b.path("zig/dory_prefill_host.zig"), .target = b.graph.host, .link_libc = true, .imports = &.{ .{ .name = "cuda", .module = m.import_table.get("cuda").? }, .{ .name = "core", .module = core }, .{ .name = "engine_api", .module = api }, .{ .name = "lanes", .module = lanes }, .{ .name = "dory", .module = m } } });
+ const prefill_run = b.addRunArtifact(b.addTest(.{ .root_module = prefill_root, .filters = &.{"Dory prefill:"} }));
+ b.step("test-dory-prefill-host", "Dory cancelled-prefill snapshots and exact resumed rows without a GPU").dependOn(&prefill_run.step);
+ all.dependOn(&prefill_run.step);
b.step("test-dory-upload-host", "Queued Dory inputs outlive caller mutation without GPU work").dependOn(&upload.step);
}
diff --git a/zig/dory_prefill_host.zig b/zig/dory_prefill_host.zig
new file mode 100644
index 00000000000..a233c0c5272
--- /dev/null
+++ b/zig/dory_prefill_host.zig
@@ -0,0 +1,208 @@
+//! Real Dory cancelled-prefill snapshots and restores with deterministic cache rows, not checkpoint arithmetic.
+const std = @import("std");
+const dory = @import("dory");
+const cuda = @import("cuda");
+const lanes = @import("lanes");
+const pc = @import("engine_api").prompt_cache;
+const fake = @import("gemma4_page_driver.zig");
+const a = std.testing.allocator;
+const t = std.testing;
+const fwd = dory.cuda_model;
+const be = dory.cuda_backend;
+
+const Fixture = struct {
+ d: cuda.Driver,
+ m: fwd.Model,
+ g: be.Dory,
+ k: fwd.Kernels = undefined,
+
+ fn init(f: *Fixture) !void {
+ f.d = fake.driver();
+ const queue: cuda.Stream = .{ .d = &f.d, .handle = @ptrFromInt(1) };
+ const text = try dory.config.pinnedText(a);
+ defer a.free(text);
+ var why: dory.config.Why = .{};
+ const c = try (try dory.config.parse(a, text, &why)).withLoops(1);
+ f.m = .{ .gpa = a, .d = &f.d, .w = undefined, .c = c, .sched = dory.schedule.build(c), .context = 4096, .ring = fwd.ringSize(fwd.prompt_rows, c.window), .slots = 2 };
+ errdefer f.m.deinit();
+ f.m.k = try a.alloc(u64, f.m.sched.caches);
+ f.m.v = try a.alloc(u64, f.m.sched.caches);
+ for (0..f.m.sched.caches) |i| {
+ f.m.k[i] = try f.cache(i);
+ f.m.v[i] = try f.cache(i);
+ }
+ f.g = try be.Dory.init(a, &f.d, &f.m, &f.k, queue);
+ }
+
+ fn cache(f: *Fixture, index: usize) !u64 {
+ const bytes = f.m.slots * f.m.cacheLen(index) * f.m.c.kvDim() * 2;
+ var b = try cuda.DeviceBuffer.alloc(&f.d, bytes);
+ errdefer b.free();
+ try f.m.buffers.append(a, b);
+ return b.ptr;
+ }
+
+ fn deinit(f: *Fixture) void {
+ f.g.deinit();
+ f.m.deinit();
+ }
+
+ fn release(f: *Fixture, s: *lanes.Stream) void {
+ const b = f.g.backend();
+ b.vtable.release(b.ptr, s);
+ }
+};
+
+fn keep(ctx: *anyopaque, s: *lanes.Stream, at: u32) void {
+ const store: *pc.Store = @ptrCast(@alignCast(ctx));
+ _ = store.keep(s.prompt(), at, s, &.{}, &.{});
+}
+
+fn cancelled(_: *anyopaque) bool {
+ return true;
+}
+
+fn cancelNow(_: *anyopaque) bool {
+ return false;
+}
+
+fn stream(ids: []const u32, store: *pc.Store) !lanes.Stream {
+ return lanes.Stream.init(a, .{ .id = "fixture", .prompt = ids, .max_new = 16, .drafts = false, .reuse = .{ .hook = .{ .ptr = store, .at = keep, .interrupted = keep } }, .cancel_check = .{ .ptr = store, .check = cancelNow } });
+}
+
+fn prompt(scrub: bool) ![]u32 {
+ const out = try a.alloc(u32, 2179);
+ for (out, 0..) |*x, i| x.* = @intCast(if (scrub) i % 89 + 500 else i % 97 + 3);
+ return out;
+}
+
+fn address(m: *const fwd.Model, cache: []const u64, index: usize, slot: usize, position: usize) u64 {
+ const rb = m.c.kvDim() * 2;
+ const row = slot * m.cacheLen(index) + position % m.cacheLen(index);
+ return cache[index] + row * rb;
+}
+
+fn value(token: u32, position: usize, index: usize, v: bool) u16 {
+ return @truncate(token *% 73 +% @as(u32, @truncate(position)) *% 17 +% @as(u32, @intCast(index)) *% 101 +% @as(u32, @intFromBool(v)) *% 19);
+}
+
+fn marked(s: *lanes.Stream, end: usize) void {
+ if (s.reuse.hook) |hk| if (std.mem.indexOfScalar(u32, s.reuse.marks, @intCast(end)) != null) hk.at(hk.ptr, s, @intCast(end));
+}
+
+fn advance(f: *Fixture, s: *lanes.Stream, l: anytype, end: usize) !void {
+ const start = l.fill.?;
+ for (start..end) |pos| for (0..f.m.sched.caches) |i| for ([_][]u64{ f.m.k, f.m.v }, 0..) |cache, v| {
+ const row: [*]u16 = @ptrFromInt(address(&f.m, cache, i, l.slot, pos));
+ @memset(row[0..f.m.c.kvDim()], value(s.prompt()[pos], pos, i, v == 1));
+ };
+ l.fill = if (end == s.prompt().len) null else end;
+ if (end == s.prompt().len) l.len = end;
+ s.fill_at.store(@intCast(end), .monotonic);
+ marked(s, end);
+}
+
+fn fill(f: *Fixture, s: *lanes.Stream) !u64 {
+ const l = try f.g.opening(s);
+ while (l.fill) |start| try advance(f, s, l, @min(s.prompt().len, (start / fwd.prompt_rows + 1) * fwd.prompt_rows));
+ return digest(&f.m, l.slot, s.prompt().len);
+}
+
+fn digest(m: *const fwd.Model, slot: usize, at: usize) u64 {
+ var hash = std.hash.Wyhash.init(0);
+ for (0..m.sched.caches) |i| {
+ const first = if (m.sched.cache_kind[i] == .full) 0 else at - @min(at, m.c.window - 1);
+ for (first..at) |pos| for ([_][]u64{ m.k, m.v }) |cache| {
+ const row: [*]const u8 = @ptrFromInt(address(m, cache, i, slot, pos));
+ hash.update(row[0 .. m.c.kvDim() * 2]);
+ };
+ }
+ return hash.final();
+}
+
+fn reply(hash: u64) [16]u32 {
+ var prng = std.Random.DefaultPrng.init(hash);
+ var out: [16]u32 = undefined;
+ for (&out) |*x| x.* = prng.random().uintLessThan(u32, 131072);
+ return out;
+}
+
+const Outcome = struct {
+ fresh: [16]u32,
+ resumed: [16]u32,
+ stopped: u64,
+ restored: u64,
+ cached: u64,
+ identity: bool,
+ needed: u64,
+ entries: usize,
+ held: u64,
+ refused: u64,
+};
+
+fn resumedAfterCancel(between_steps: bool, shortage: u64) !Outcome {
+ var f: Fixture = undefined;
+ try f.init();
+ defer f.deinit();
+ const needed = dory.native.snap_bytes(&f.g, fwd.prompt_rows);
+ var store = pc.Store.init(a, .{ .ptr = &f.g, .vtable = &.{ .bytes = dory.native.snap_bytes, .save = dory.native.snap_save, .restore = dory.native.snap_restore, .drop = dory.native.snap_drop } }, .{ .lookahead = 0, .min_prompt = 0, .chunk = fwd.prompt_rows }, needed -| shortage);
+ defer store.deinit();
+ const ids = try prompt(false);
+ defer a.free(ids);
+ const scrub = try prompt(true);
+ defer a.free(scrub);
+ var plain = try stream(ids, &store);
+ defer plain.deinit(a);
+ const fresh = reply(try fill(&f, &plain));
+ f.release(&plain);
+
+ var stopped = try stream(ids, &store);
+ defer stopped.deinit(a);
+ const l = try f.g.opening(&stopped);
+ try advance(&f, &stopped, l, fwd.prompt_rows);
+ const stopped_state = digest(&f.m, l.slot, fwd.prompt_rows);
+ const b = f.g.backend();
+ if (between_steps) {
+ if (b.vtable.cancel_prefill) |keep_prefix| try keep_prefix(b.ptr, &stopped);
+ f.release(&stopped);
+ } else {
+ stopped.cancel_check = .{ .ptr = &stopped, .check = cancelled };
+ try t.expectError(error.Cancelled, b.vtable.prefill_step.?(b.ptr, &stopped, 0));
+ }
+
+ var other = try stream(scrub, &store);
+ defer other.deinit(a);
+ _ = try fill(&f, &other);
+ f.release(&other);
+ const found = store.find(ids, &.{}, &.{});
+ var resumed = try stream(ids, &store);
+ defer resumed.deinit(a);
+ if (found) |entry| {
+ resumed.reuse.saved = entry.saved;
+ resumed.reuse.at = entry.at;
+ }
+ const rl = try f.g.opening(&resumed);
+ const identity = if (found) |entry| resumed.reuse.saved == entry.saved else false;
+ const restored = digest(&f.m, rl.slot, rl.fill.?);
+ while (rl.fill) |start| try advance(&f, &resumed, rl, @min(ids.len, (start / fwd.prompt_rows + 1) * fwd.prompt_rows));
+ const got = reply(digest(&f.m, rl.slot, ids.len));
+ f.release(&resumed);
+ return .{ .fresh = fresh, .resumed = got, .stopped = stopped_state, .restored = restored, .cached = resumed.cached, .identity = identity, .needed = needed, .entries = store.entries.items.len, .held = store.held, .refused = store.counts.refused };
+}
+
+test "Dory prefill: cancelled chunks retain exact fresh replies within cache capacity" {
+ for ([_]bool{ false, true }) |between_steps| {
+ for ([_]u64{ 0, 1 }) |shortage| {
+ const out = try resumedAfterCancel(between_steps, shortage);
+ const fits = shortage == 0;
+ try t.expectEqualSlices(u32, &out.fresh, &out.resumed);
+ try t.expectEqual(if (fits) @as(u64, fwd.prompt_rows) else 0, out.cached);
+ try t.expectEqual(fits, out.identity);
+ try t.expectEqual(@as(usize, @intFromBool(fits)), out.entries);
+ try t.expectEqual(if (fits) out.needed else 0, out.held);
+ try t.expectEqual(@as(u64, @intFromBool(!fits)), out.refused);
+ if (fits) try t.expectEqual(out.stopped, out.restored);
+ try t.expect(fake.empty());
+ }
+ }
+}
diff --git a/zig/src/families/dory/cuda_backend.zig b/zig/src/families/dory/cuda_backend.zig
index 6e84aaba8f6..9917e510a61 100644
--- a/zig/src/families/dory/cuda_backend.zig
+++ b/zig/src/families/dory/cuda_backend.zig
@@ -130,7 +130,7 @@ pub const Dory = struct {
return .{ .ptr = x, .vtable = &vtable };
}
- const vtable: be.Backend.VTable = .{ .prefill = prefill, .prefill_step = prefillStep, .first = first, .queue = queue, .read = read, .verify = verify, .keep = keep, .draft = draft, .release = release, .reports_fill = true };
+ const vtable: be.Backend.VTable = .{ .prefill = prefill, .prefill_step = prefillStep, .cancel_prefill = cancelPrefill, .first = first, .queue = queue, .read = read, .verify = verify, .keep = keep, .draft = draft, .release = release, .reports_fill = true };
/// The round loop's facts: no draft head; host copies verified in windows up to 16 rows, streams sharing a forward.
pub fn facts(x: *const Dory) lanes.Model {
@@ -262,7 +262,7 @@ pub const Dory = struct {
}
/// A prompt pass begins: a slot, the stream's rule, a kept state restored; where its first chunk starts.
- fn opening(x: *Dory, s: *Stream) !*Lane {
+ pub fn opening(x: *Dory, s: *Stream) !*Lane {
const p = s.prompt();
if (p.len == 0) return error.EmptyPrompt;
if (!fits(x.m.context, p.len, @as(usize, s.max_new))) return error.PastContext;
@@ -316,7 +316,10 @@ pub const Dory = struct {
fn chunk(x: *Dory, s: *Stream, l: *Lane, _: u32) !bool {
const p = s.prompt();
const at = l.fill.?;
- if (s.isCancelled()) return error.Cancelled;
+ if (s.isCancelled()) {
+ s.keepInterruptedPrefill(@intCast(at));
+ return error.Cancelled;
+ }
var end = @min(p.len, (at / prompt_rows + 1) * prompt_rows);
const marks = if (x.prompts != null) l.marks else s.reuse.marks;
for (marks) |mk| if (mk > at and mk < end) {
@@ -353,6 +356,12 @@ pub const Dory = struct {
errdefer x.dropLane(s);
return x.chunk(s, l, 0);
}
+ fn cancelPrefill(ptr: *anyopaque, s: *Stream) anyerror!void {
+ const x = self(ptr);
+ const l = x.lanes.getPtr(s) orelse return;
+ if (l.fill) |at| s.keepInterruptedPrefill(@intCast(at));
+ l.fill = null;
+ }
fn handle(x: *Dory) usize {
const h = x.next;
From f97706cb08f29a17b2024225a67bf4c8e67952e9 Mon Sep 17 00:00:00 2001
From: ashhart <71890694+ashhart@users.noreply.github.com>
Date: Fri, 20 Nov 2026 11:08:27 +0000
Subject: [PATCH 16/32] minimax m3: retain cancelled prompt chunks
---
zig/src/families/minimax_m3/cuda_lanes.zig | 59 ++++++++++++++++++++--
1 file changed, 55 insertions(+), 4 deletions(-)
diff --git a/zig/src/families/minimax_m3/cuda_lanes.zig b/zig/src/families/minimax_m3/cuda_lanes.zig
index eac65b4ffd1..0961eadfe41 100644
--- a/zig/src/families/minimax_m3/cuda_lanes.zig
+++ b/zig/src/families/minimax_m3/cuda_lanes.zig
@@ -197,8 +197,12 @@ pub const Lanes = struct {
var resume_from = from;
while (true) : (at += engine.prompt_rows) {
if (resume_from == null) mark(s, at);
- if (try self.x.chunk(s.prompt(), at, resume_from, .{ .ptr = s, .check = cancelled })) |first| {
- self.lanes.getPtr(s).?.first = self.take(first);
+ const first = self.x.chunk(s.prompt(), at, resume_from, .{ .ptr = s, .check = cancelled }) catch |err| {
+ if (err == error.Cancelled) s.keepInterruptedPrefill(@intCast(at));
+ return err;
+ };
+ if (first) |token| {
+ self.lanes.getPtr(s).?.first = self.take(token);
return;
}
resume_from = null;
@@ -215,8 +219,12 @@ pub const Lanes = struct {
const at = going orelse if (from) |r| r.at else 0;
errdefer l.fill = null;
if (from == null) mark(s, at);
- if (try self.x.chunk(s.prompt(), at, from, .{ .ptr = s, .check = cancelled })) |first| {
- l.first = self.take(first);
+ const first = self.x.chunk(s.prompt(), at, from, .{ .ptr = s, .check = cancelled }) catch |err| {
+ if (err == error.Cancelled) s.keepInterruptedPrefill(@intCast(at));
+ return err;
+ };
+ if (first) |token| {
+ l.first = self.take(token);
l.fill = null;
return true;
}
@@ -227,6 +235,7 @@ pub const Lanes = struct {
fn cancelPrefillFn(ptr: *anyopaque, s: *lanes.Stream) !void {
const self = of(ptr);
const l = self.lanes.getPtr(s) orelse return;
+ if (l.fill) |at| s.keepInterruptedPrefill(@intCast(at));
l.fill = null;
}
@@ -382,3 +391,45 @@ pub const Lanes = struct {
if (self.lanes.count() == 0) self.x.idle() catch |err| std.log.err("the other ranks' idle step: {s}", .{@errorName(err)});
}
};
+
+test "MiniMax CUDA prefill: cancellation keeps the landed chunk for a resumed pass" {
+ const Record = struct {
+ kept: engine.Kept = .{ .id = 7, .at = 0 },
+ calls: usize = 0,
+ fn interrupted(ptr: *anyopaque, _: *lanes.Stream, at: u32) void {
+ const r: *@This() = @ptrCast(@alignCast(ptr));
+ r.kept.at = at;
+ r.calls += 1;
+ }
+ };
+ const ids: [2 * engine.prompt_rows + 1]u32 = @splat(7);
+ var record: Record = .{};
+ var s = try lanes.Stream.init(std.testing.allocator, .{
+ .id = "cancelled",
+ .prompt = &ids,
+ .max_new = 1,
+ .reuse = .{ .hook = .{ .ptr = &record, .at = Record.interrupted, .interrupted = Record.interrupted } },
+ });
+ defer s.deinit(std.testing.allocator);
+ var e: engine.Engine = undefined;
+ e.snaps = .empty;
+ defer e.snaps.deinit(std.testing.allocator);
+ var back: Lanes = .{ .x = .{ .e = &e, .link = null } };
+ defer back.lanes.deinit(std.testing.allocator);
+ try back.lanes.put(std.testing.allocator, &s, .{ .slot = 0, .fill = engine.prompt_rows });
+ const b = back.backend();
+ try b.vtable.cancel_prefill.?(b.ptr, &s);
+ try std.testing.expectEqual(@as(usize, 1), record.calls);
+ try std.testing.expectEqual(@as(u32, engine.prompt_rows), record.kept.at);
+ try std.testing.expect(back.lanes.getPtr(&s).?.fill == null);
+ try e.snaps.put(std.testing.allocator, record.kept.id, .{ .buf = undefined, .at = record.kept.at, .drafted = .{ 0, 0 } });
+
+ var resumed = try lanes.Stream.init(std.testing.allocator, .{ .id = "resumed", .prompt = &ids, .max_new = 1, .reuse = .{ .saved = @ptrCast(&record.kept), .at = record.kept.at } });
+ defer resumed.deinit(std.testing.allocator);
+ const from = back.resumeFrom(&resumed, ids.len) orelse return error.TestUnexpectedResult;
+ try std.testing.expectEqual(@as(usize, engine.prompt_rows), from.at);
+ try std.testing.expectEqual(record.kept.id, from.id);
+ try std.testing.expectEqual(record.kept.at, resumed.cached);
+ try std.testing.expectEqual(record.kept.at, resumed.fill_at.load(.monotonic));
+ try std.testing.expect(!resumed.reuse_failed);
+}
From 3f4530551b1f1befeb4cf1e5668995a8f6dd214e Mon Sep 17 00:00:00 2001
From: ashhart <71890694+ashhart@users.noreply.github.com>
Date: Fri, 20 Nov 2026 11:10:13 +0000
Subject: [PATCH 17/32] nemotron parse: retain cancelled prompt prefixes
---
zig/build/hip.zig | 4 +-
zig/src/families/nemotron_parse/backend.zig | 5 ++-
zig/src/families/nemotron_parse/hip.zig | 4 ++
zig/src/families/nemotron_parse/prefill.zig | 42 ++++++++++++++++++++-
4 files changed, 51 insertions(+), 4 deletions(-)
diff --git a/zig/build/hip.zig b/zig/build/hip.zig
index d859f82c5f9..4c7cfe89cb4 100644
--- a/zig/build/hip.zig
+++ b/zig/build/hip.zig
@@ -199,7 +199,9 @@ pub fn steps(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.buil
test_step.dependOn(&qwen3_host.step);
b.step("test-qwen3-hip-host", "Qwen3 dense config, checkpoint prefix and lm_head rows on the CPU").dependOn(&qwen3_host.step);
test_step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = host.serve })).step);
- test_step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = host.parse })).step);
+ const parse_host = b.addRunArtifact(b.addTest(.{ .root_module = host.parse }));
+ test_step.dependOn(&parse_host.step);
+ b.step("test-nemotron-parse-prefill-host", "Parse cancelled-prefill prefix retention without GPU execution").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = host.parse, .filters = &.{"Parse cancelled prefill"} })).step);
const native_host_tests = b.addRunArtifact(b.addTest(.{ .root_module = host.native }));
test_step.dependOn(&native_host_tests.step);
b.step("test-native-hip-host", "Native HIP family offers and flags without a device").dependOn(&native_host_tests.step);
diff --git a/zig/src/families/nemotron_parse/backend.zig b/zig/src/families/nemotron_parse/backend.zig
index 0e534adeb41..a4e84150f68 100644
--- a/zig/src/families/nemotron_parse/backend.zig
+++ b/zig/src/families/nemotron_parse/backend.zig
@@ -69,7 +69,7 @@ pub const Backend = struct {
return .{ .ptr = h, .vtable = &vtable, .penalties = true, .chunk_invariant = true };
}
- const vtable: be.Backend.VTable = .{ .reports_fill = true, .prefill = fillAll, .prefill_step = fillStep, .first = first, .first_masked = firstMasked, .queue = queue, .read = read, .verify = verify, .keep = keep, .draft = draft, .tree = tree, .held = held, .release = release };
+ const vtable: be.Backend.VTable = .{ .reports_fill = true, .prefill = fillAll, .prefill_step = fillStep, .cancel_prefill = cancelPrefill, .first = first, .first_masked = firstMasked, .queue = queue, .read = read, .verify = verify, .keep = keep, .draft = draft, .tree = tree, .held = held, .release = release };
pub fn of(ptr: *anyopaque) *Backend {
const h: *Backend = @ptrCast(@alignCast(ptr));
@@ -84,6 +84,9 @@ pub const Backend = struct {
fn fillStep(ptr: *anyopaque, s: *lanes.Stream, max_rows: u32) anyerror!bool {
return prefill.step(of(ptr), s, max_rows);
}
+ fn cancelPrefill(ptr: *anyopaque, s: *lanes.Stream) anyerror!void {
+ return prefill.cancel(of(ptr), s);
+ }
fn first(ptr: *anyopaque, s: *lanes.Stream, position: u64) anyerror!u64 {
if (position != s.prompt_len) return error.PositionMismatch;
diff --git a/zig/src/families/nemotron_parse/hip.zig b/zig/src/families/nemotron_parse/hip.zig
index 75733da1514..07f79507b4f 100644
--- a/zig/src/families/nemotron_parse/hip.zig
+++ b/zig/src/families/nemotron_parse/hip.zig
@@ -114,3 +114,7 @@ test "Parse refuses missing image input, tensor parallelism and unsupported trai
other.context = 16385;
try std.testing.expect(refusal(other) != null);
}
+
+test {
+ _ = @import("prefill.zig");
+}
diff --git a/zig/src/families/nemotron_parse/prefill.zig b/zig/src/families/nemotron_parse/prefill.zig
index 59fd7b390e4..ffab70d14bf 100644
--- a/zig/src/families/nemotron_parse/prefill.zig
+++ b/zig/src/families/nemotron_parse/prefill.zig
@@ -10,7 +10,9 @@ const Tensor = hip.ops.Tensor;
fn cancelled(ptr: *anyopaque) bool {
const s: *lanes.Stream = @ptrCast(@alignCast(ptr));
- return s.isCancelled();
+ if (!s.isCancelled()) return false;
+ s.keepInterruptedPrefill(s.fill_at.load(.monotonic));
+ return true;
}
fn compute(h: *backend.Backend, s: *lanes.Stream) Compute {
@@ -54,7 +56,7 @@ fn begin(h: *backend.Backend, s: *lanes.Stream) !*backend.Lane {
}
pub fn step(h: *backend.Backend, s: *lanes.Stream, max_rows: u32) !bool {
- if (s.isCancelled()) return error.Cancelled;
+ if (cancelled(s)) return error.Cancelled;
const l = h.streams.map.get(s) orelse try begin(h, s);
const from = l.fill;
if (from == s.prompt_len) {
@@ -94,6 +96,11 @@ pub fn step(h: *backend.Backend, s: *lanes.Stream, max_rows: u32) !bool {
return to == s.prompt_len;
}
+pub fn cancel(h: *backend.Backend, s: *lanes.Stream) !void {
+ const l = h.streams.map.get(s) orelse return;
+ s.keepInterruptedPrefill(@intCast(l.fill));
+}
+
fn finish(h: *backend.Backend, s: *lanes.Stream, l: *backend.Lane, comp: Compute) !void {
const logits = try decoder.logits(comp, try l.state.hiddenAt(s.prompt_len - 1), 1);
var r = try h.request(h.a, s, l.image_rows, s.prompt_len, &.{}, s.prompt_len);
@@ -104,3 +111,34 @@ fn finish(h: *backend.Backend, s: *lanes.Stream, l: *backend.Lane, comp: Compute
try h.sampler.draw(comp.ops, h.e.stream, logits, &.{r}, &choice, false);
l.first = h.streams.drawn.take(choice[0]);
}
+
+test "Parse cancelled prefill retains the last completed prefix" {
+ const Record = struct {
+ calls: usize = 0,
+ at: u32 = 0,
+ fn interrupted(ptr: *anyopaque, _: *lanes.Stream, at: u32) void {
+ const r: *@This() = @ptrCast(@alignCast(ptr));
+ r.calls += 1;
+ r.at = at;
+ }
+ fn cancelledNow(_: *anyopaque) bool {
+ return true;
+ }
+ };
+ const ids: [513]u32 = @splat(1);
+ var saved: u8 = 0;
+ var record: Record = .{};
+ var s = try lanes.Stream.init(std.testing.allocator, .{ .id = "cancelled", .prompt = &ids, .max_new = 1, .reuse = .{ .saved = &saved, .at = 512, .hook = .{ .ptr = &record, .at = Record.interrupted, .interrupted = Record.interrupted } }, .cancel_check = .{ .ptr = &record, .check = Record.cancelledNow } });
+ defer s.deinit(std.testing.allocator);
+ var h: backend.Backend = undefined;
+ try std.testing.expectError(error.Cancelled, step(&h, &s, 512));
+ try std.testing.expectEqual(@as(usize, 1), record.calls);
+ try std.testing.expectEqual(@as(u32, 512), record.at);
+ h.streams = .init(std.testing.allocator);
+ defer h.streams.deinit();
+ var lane: backend.Lane = .{ .state = undefined, .prefix = undefined, .image_rows = 0, .fill = 256 };
+ try h.streams.map.put(std.testing.allocator, &s, &lane);
+ try cancel(&h, &s);
+ try std.testing.expectEqual(@as(usize, 2), record.calls);
+ try std.testing.expectEqual(@as(u32, 256), record.at);
+}
From 52ab88bc102df913b62c88e08f87411057830dd0 Mon Sep 17 00:00:00 2001
From: ashhart <71890694+ashhart@users.noreply.github.com>
Date: Fri, 20 Nov 2026 11:11:53 +0000
Subject: [PATCH 18/32] uocr: stop cancelled image and decoder prefill
---
zig/src/families/uocr/decoder.zig | 20 +++++++++++++++++++-
zig/src/families/uocr/serve.zig | 27 +++++++++++++++++++++++----
2 files changed, 42 insertions(+), 5 deletions(-)
diff --git a/zig/src/families/uocr/decoder.zig b/zig/src/families/uocr/decoder.zig
index cdd222c3cb6..7246b69fd6a 100644
--- a/zig/src/families/uocr/decoder.zig
+++ b/zig/src/families/uocr/decoder.zig
@@ -158,7 +158,8 @@ pub const Decoder = struct {
}
/// Prefill a prompt: `image_rows` (bf16 [image tokens, 1280]) at its image tokens, the token embeddings elsewhere.
- pub fn prefill(d: *Decoder, p: prompt_mod.Prompt, image_rows: []const u16) !void {
+ pub fn prefill(d: *Decoder, p: prompt_mod.Prompt, image_rows: []const u16, cancel: ?@import("lanes").stream.CancelCheck) !void {
+ if (cancel) |c| if (c.check(c.ptr)) return error.Cancelled;
const n = p.len();
if (n == 0 or n > d.cap) return error.UocrPromptTooLong;
var images: usize = 0;
@@ -173,6 +174,7 @@ pub const Decoder = struct {
var s0: usize = 0;
const embed: [*]const u16 = @ptrCast(@alignCast(d.w.embed.addr()));
while (s0 < n) {
+ if (cancel) |c| if (c.check(c.ptr)) return error.Cancelled;
const r = @min(d.rows, n - s0);
const x = d.scratch.host(u16, .x, r * H);
for (0..r) |i| {
@@ -190,6 +192,22 @@ pub const Decoder = struct {
if (tr) |t| t.copyOut(d.trace, d.trace_parts, n);
}
+ test "uocr: cancelled decoder prefill stops before device work" {
+ const Stop = struct {
+ fn yes(_: *anyopaque) bool {
+ return true;
+ }
+ };
+ var ids: [1]u32 = .{1};
+ var p: prompt_mod.Prompt = undefined;
+ p.ids = &ids;
+ var d: Decoder = undefined;
+ d.cap = 0;
+ var stopped = false;
+ const cancel: @import("lanes").stream.CancelCheck = .{ .ptr = &stopped, .check = Stop.yes };
+ try std.testing.expectError(error.Cancelled, d.prefill(p, &.{}, cancel));
+ }
+
/// One decode step for token `id` at the next position, with its coordinates from prompt.Step.
pub fn step(d: *Decoder, id: u32, c: prompt_mod.Coord) !void {
if (d.len >= d.cap) return error.UocrContextFull;
diff --git a/zig/src/families/uocr/serve.zig b/zig/src/families/uocr/serve.zig
index a8e25ca1674..3cd4fe2403d 100644
--- a/zig/src/families/uocr/serve.zig
+++ b/zig/src/families/uocr/serve.zig
@@ -101,7 +101,7 @@ pub const Model = struct {
pub const Prepared = struct { pixels: []f32, gh: u32, gw: u32, tokens: u32, hash: u64 };
/// Every image of the stream through the tower, laid out as its image tokens in prompt order.
- fn encodeImages(m: *Model, a: std.mem.Allocator, images: []const lanes.stream.Image) ![]u16 {
+ fn encodeImages(m: *Model, a: std.mem.Allocator, images: []const lanes.stream.Image, cancel: ?lanes.stream.CancelCheck) ![]u16 {
var total: usize = 0;
for (images) |img| total += img.tokens;
const rows = try a.alloc(u16, total * H);
@@ -111,6 +111,7 @@ pub const Model = struct {
const tile_px = 3 * cfg.tile_size * cfg.tile_size;
var at: usize = 0;
for (images) |img| {
+ if (cancel) |c| if (c.check(c.ptr)) return error.Cancelled;
const across: usize = img.gw;
const down: usize = img.gh;
const tiles: usize = if (across * down > 1) across * down else 0;
@@ -123,7 +124,10 @@ pub const Model = struct {
try m.encoder.encode(cfg.base_size, px[0..global_px], global, .{});
const tile_rows = try a.alloc(u16, tiles * t * t * H);
defer a.free(tile_rows);
- for (0..tiles) |i| try m.encoder.encode(cfg.tile_size, px[global_px + i * tile_px ..][0..tile_px], tile_rows[i * t * t * H ..][0 .. t * t * H], .{});
+ for (0..tiles) |i| {
+ if (cancel) |c| if (c.check(c.ptr)) return error.Cancelled;
+ try m.encoder.encode(cfg.tile_size, px[global_px + i * tile_px ..][0..tile_px], tile_rows[i * t * t * H ..][0 .. t * t * H], .{});
+ }
const out = rows[at * H ..][0 .. @as(usize, img.tokens) * H];
vision.layout(&m.weights, global, tile_rows, across, down, out);
at += img.tokens;
@@ -146,16 +150,17 @@ pub const Model = struct {
fn prefillFn(ptr: *anyopaque, stream: *lanes.Stream) !void {
const m = cast(ptr);
+ if (stream.isCancelled()) return error.Cancelled;
if (m.stream != null) return error.UocrBusy;
const ids = stream.prompt();
// the prompt's rows, then a row for every reply token fed back: all but the last, which ends the reply
if (ids.len == 0 or ids.len + @max(stream.max_new, 1) - 1 > m.decoder.cap) return error.UocrPromptTooLong;
var arena: std.heap.ArenaAllocator = .init(m.gpa);
defer arena.deinit();
- const rows = try m.encodeImages(arena.allocator(), stream.images);
+ const rows = try m.encodeImages(arena.allocator(), stream.images, stream.cancel_check);
var p = try prompt_mod.positions(m.gpa, try m.gpa.dupe(u32, ids));
errdefer p.deinit(m.gpa);
- try m.decoder.prefill(p, rows);
+ try m.decoder.prefill(p, rows, stream.cancel_check);
m.guard = generate.Guard.init(p);
m.step = prompt_mod.Step.init(p);
m.prompt = p;
@@ -223,3 +228,17 @@ test "uocr: a page's token bounds" {
try std.testing.expectEqual(@as(u32, 273), basePageTokens());
try std.testing.expect(maxPageTokens() > basePageTokens());
}
+
+test "uocr: cancelled prefill stops before the encoder" {
+ const Stop = struct {
+ fn yes(_: *anyopaque) bool {
+ return true;
+ }
+ };
+ var other: lanes.Stream = undefined;
+ var s: lanes.Stream = undefined;
+ s.cancel_check = .{ .ptr = &s, .check = Stop.yes };
+ var m: Model = undefined;
+ m.stream = &other;
+ try std.testing.expectError(error.Cancelled, Model.prefillFn(&m, &s));
+}
From 8ff758e0fbcf2e13eec40107541cda337974857f Mon Sep 17 00:00:00 2001
From: ashhart <71890694+ashhart@users.noreply.github.com>
Date: Fri, 20 Nov 2026 11:12:07 +0000
Subject: [PATCH 19/32] lfm3 xpu: clear stale carry on snapshot restore
---
zig/src/families/lfm3/resume_test.zig | 84 +++++++++++++++++++++++++
zig/src/families/lfm3/xpu_host_test.zig | 39 ++++++++++++
zig/src/families/lfm3/xpu_model.zig | 3 +
3 files changed, 126 insertions(+)
create mode 100644 zig/src/families/lfm3/resume_test.zig
create mode 100644 zig/src/families/lfm3/xpu_host_test.zig
diff --git a/zig/src/families/lfm3/resume_test.zig b/zig/src/families/lfm3/resume_test.zig
new file mode 100644
index 00000000000..3dd50a589fe
--- /dev/null
+++ b/zig/src/families/lfm3/resume_test.zig
@@ -0,0 +1,84 @@
+const std = @import("std");
+const xpu = @import("xpu");
+const cfg = @import("config.zig");
+const model = @import("xpu_model.zig");
+
+const conv_bytes = 6 * cfg.hidden * 2;
+const slot_bytes = cfg.kv_heads * cfg.head_dim * 2;
+
+fn fill(buf: xpu.rt.Buffer, seed: u8) void {
+ for (buf.ptr.?[0..buf.len], 0..) |*byte, i| byte.* = seed +% @as(u8, @truncate(i * 31 + 7));
+}
+
+fn expectFill(buf: xpu.rt.Buffer, bytes: usize, seed: u8) !void {
+ for (buf.ptr.?[0..bytes], 0..) |byte, i| try std.testing.expectEqual(seed +% @as(u8, @truncate(i * 31 + 7)), byte);
+}
+
+test "LFM3 snapshot resume restores logical state and retires the prior window carry" {
+ const a = std.testing.allocator;
+ var runtime: xpu.rt.Runtime = .{ .gpa = a };
+ var m: model.Model = undefined;
+ var layers: [3]@TypeOf(m.layers[0]) = undefined;
+ layers[0].mixer = .{ .conv = undefined };
+ layers[1].mixer = .{ .attn = undefined };
+ layers[1].mixer.attn.ring = 8;
+ layers[1].mixer.attn.window = 0;
+ layers[2].mixer = .{ .attn = undefined };
+ layers[2].mixer.attn.ring = 5;
+ layers[2].mixer.attn.window = cfg.sliding_window;
+ var q: model.Seq = .{ .pos = 3 };
+ m.gpa = a;
+ m.r = &runtime;
+ m.layers = &layers;
+ m.seq = &q;
+ m.pos = 3;
+
+ q.conv[0] = try runtime.alloc(conv_bytes);
+ defer q.conv[0].free();
+ q.ext[0] = try runtime.alloc((6 + model.window_rows) * cfg.hidden * 2);
+ defer q.ext[0].free();
+ q.kc[1] = try runtime.alloc(8 * slot_bytes);
+ defer q.kc[1].free();
+ q.vc[1] = try runtime.alloc(8 * slot_bytes);
+ defer q.vc[1].free();
+ q.kc[2] = try runtime.alloc(5 * slot_bytes);
+ defer q.kc[2].free();
+ q.vc[2] = try runtime.alloc(5 * slot_bytes);
+ defer q.vc[2].free();
+
+ fill(q.conv[0], 11);
+ fill(q.ext[0], 17);
+ fill(q.kc[1], 23);
+ fill(q.vc[1], 29);
+ fill(q.kc[2], 31);
+ fill(q.vc[2], 37);
+ const saved = try m.snapSave();
+ defer m.snapDrop(saved);
+
+ fill(q.conv[0], 101);
+ fill(q.kc[1], 103);
+ fill(q.vc[1], 107);
+ fill(q.kc[2], 109);
+ fill(q.vc[2], 113);
+ q.pos = 11;
+ q.win_start = 8;
+ q.win_rows = 3;
+ m.pos = 11;
+ try m.snapRestore(saved);
+
+ const fresh: model.Seq = .{ .pos = 3 };
+ try std.testing.expectEqual(fresh.pos, q.pos);
+ try std.testing.expectEqual(fresh.win_start, q.win_start);
+ try std.testing.expectEqual(fresh.win_rows, q.win_rows);
+ try std.testing.expectEqual(@as(u32, 3), m.pos);
+ try expectFill(q.conv[0], conv_bytes, 11);
+ try expectFill(q.kc[1], 3 * slot_bytes, 23);
+ try expectFill(q.vc[1], 3 * slot_bytes, 29);
+ try expectFill(q.kc[2], 5 * slot_bytes, 31);
+ try expectFill(q.vc[2], 5 * slot_bytes, 37);
+
+ try m.keepRows(2);
+ try std.testing.expectEqual(@as(u32, 3), m.pos);
+ try std.testing.expectEqual(@as(u32, 3), q.pos);
+ try expectFill(q.conv[0], conv_bytes, 11);
+}
diff --git a/zig/src/families/lfm3/xpu_host_test.zig b/zig/src/families/lfm3/xpu_host_test.zig
new file mode 100644
index 00000000000..40e1c2dbd30
--- /dev/null
+++ b/zig/src/families/lfm3/xpu_host_test.zig
@@ -0,0 +1,39 @@
+const std = @import("std");
+
+pub const rt = struct {
+ pub const Runtime = struct {
+ gpa: std.mem.Allocator,
+
+ pub fn alloc(self: *Runtime, bytes: usize) !Buffer {
+ const memory = try self.gpa.alloc(u8, bytes);
+ return .{ .rt = self, .ptr = memory.ptr, .len = memory.len };
+ }
+
+ pub fn copy(_: *Runtime, dest: Buffer, source: Buffer, bytes: usize) !void {
+ std.debug.assert(bytes <= dest.len and bytes <= source.len);
+ @memcpy(dest.ptr.?[0..bytes], source.ptr.?[0..bytes]);
+ }
+
+ pub fn sync(_: *Runtime) !void {}
+ };
+
+ pub const Buffer = struct {
+ rt: *Runtime,
+ ptr: ?[*]u8,
+ len: usize,
+
+ pub fn free(self: Buffer) void {
+ self.rt.gpa.free(self.ptr.?[0..self.len]);
+ }
+ };
+
+ pub const Kernel = struct {};
+};
+
+pub const loader = struct {
+ pub const Loader = struct {};
+};
+
+pub const kernels = struct {
+ pub const dpas = false;
+};
diff --git a/zig/src/families/lfm3/xpu_model.zig b/zig/src/families/lfm3/xpu_model.zig
index 39e7e8b8641..7e773e41508 100644
--- a/zig/src/families/lfm3/xpu_model.zig
+++ b/zig/src/families/lfm3/xpu_model.zig
@@ -372,6 +372,9 @@ pub const Model = struct {
/// The bound stream continues from a kept state.
pub fn snapRestore(m: *Model, sn: *const Snap) !void {
+ m.seq.pos = sn.at;
+ m.seq.win_start = 0;
+ m.seq.win_rows = 0;
m.pos = sn.at;
try m.snapCopy(sn, false);
}
From 28c5641095a9adb90d998cca446cc8768f3b99a8 Mon Sep 17 00:00:00 2001
From: ashhart <71890694+ashhart@users.noreply.github.com>
Date: Fri, 20 Nov 2026 11:13:08 +0000
Subject: [PATCH 20/32] glm: retain cancelled prefill prefixes
---
zig/src/families/glm/prefill.zig | 5 +++-
zig/src/families/glm/prefill_test.zig | 39 +++++++++++++++++++++++++++
2 files changed, 43 insertions(+), 1 deletion(-)
diff --git a/zig/src/families/glm/prefill.zig b/zig/src/families/glm/prefill.zig
index 1621792930e..89433a67b65 100644
--- a/zig/src/families/glm/prefill.zig
+++ b/zig/src/families/glm/prefill.zig
@@ -8,7 +8,10 @@ pub const State = struct { stream: *Stream, slot: u32, at: u32 = 0, next: usize
/// `b` is the real backend or a fake engine at the same prepare/chunk/finish boundary. `_: u32` keeps its 2048 grid.
pub fn step(b: anytype, s: *Stream, _: u32) !bool {
- errdefer b.abortPrompt(s);
+ errdefer {
+ if (s.isCancelled()) if (b.filling.get(s)) |p| s.keepInterruptedPrefill(p.at);
+ b.abortPrompt(s);
+ }
if (s.isCancelled()) return error.Cancelled;
if (!b.filling.contains(s)) {
const begun = try b.beginPrompt(s);
diff --git a/zig/src/families/glm/prefill_test.zig b/zig/src/families/glm/prefill_test.zig
index a4d807e964d..73eae3ba9ee 100644
--- a/zig/src/families/glm/prefill_test.zig
+++ b/zig/src/families/glm/prefill_test.zig
@@ -187,6 +187,45 @@ test "glm prefill: a failed chunk, cancellation or state allocation releases jus
try std.testing.expectEqual(@as(usize, 0), f.filling.count());
}
+test "glm prefill: cancellation keeps a completed prefix for exact resume" {
+ const Kept = struct {
+ rows: std.ArrayList(u32) = .empty,
+ at: u32 = 0,
+
+ fn interrupted(ctx: *anyopaque, s: *Stream, at: u32) void {
+ const k: *@This() = @ptrCast(@alignCast(ctx));
+ k.rows.clearRetainingCapacity();
+ k.rows.appendSlice(a, s.prompt()[0..at]) catch unreachable;
+ k.at = at;
+ }
+ };
+ var f: Fake = .{};
+ defer f.deinit();
+ var kept: Kept = .{};
+ defer kept.rows.deinit(a);
+ const ids = [_]u32{ 3, 1, 4, 1, 5, 9 };
+ var stopped = try Stream.init(a, .{ .id = "stopped", .prompt = &ids, .max_new = 4, .chunks = &.{2}, .reuse = .{ .hook = .{ .ptr = &kept, .at = Kept.interrupted, .interrupted = Kept.interrupted } } });
+ defer stopped.deinit(a);
+ try std.testing.expect(!try fill.step(&f, &stopped, 0));
+ const Cancel = struct {
+ fn yes(_: *anyopaque) bool {
+ return true;
+ }
+ };
+ var dummy: u8 = 0;
+ stopped.cancel_check = .{ .ptr = &dummy, .check = Cancel.yes };
+ try std.testing.expectError(error.Cancelled, fill.step(&f, &stopped, 0));
+ try std.testing.expectEqual(@as(u32, 2), kept.at);
+
+ var resumed = try Stream.init(a, .{ .id = "resumed", .prompt = &ids, .max_new = 4, .chunks = &.{2} });
+ defer resumed.deinit(a);
+ resumed.reuse.saved = &kept.rows;
+ resumed.reuse.at = kept.at;
+ while (!try fill.step(&f, &resumed, 0)) {}
+ try std.testing.expectEqual(@as(u32, 2), resumed.cached);
+ try std.testing.expectEqualSlices(u32, &ids, f.target.lanes.getPtr(&resumed).?.history.items);
+}
+
test "glm prefill: shared prompt input restores each owner's IDs and lookahead after settling decoder scratch" {
const Input = struct {
shared: [16]u32 = @splat(99),
From 1cd50d7527780c6fa9233e4cd49f63c51e2fd1e8 Mon Sep 17 00:00:00 2001
From: ashhart <71890694+ashhart@users.noreply.github.com>
Date: Fri, 20 Nov 2026 11:14:13 +0000
Subject: [PATCH 21/32] glm dsa: retain cancelled prefill prefixes
---
zig/build/glm_expiry.zig | 9 ++++
zig/src/families/glm_dsa/backend.zig | 75 ++++++++++++++++++++++------
zig/src/glm_dsa_prefill_tests.zig | 3 ++
3 files changed, 72 insertions(+), 15 deletions(-)
create mode 100644 zig/src/glm_dsa_prefill_tests.zig
diff --git a/zig/build/glm_expiry.zig b/zig/build/glm_expiry.zig
index 25e71ec4643..a4a53e5ec2d 100644
--- a/zig/build/glm_expiry.zig
+++ b/zig/build/glm_expiry.zig
@@ -52,6 +52,15 @@ pub fn steps(b: *std.Build, test_step: *std.Build.Step, lanes: *std.Build.Module
const schedule_run = b.addRunArtifact(schedule);
b.step("test-glm-scheduling-host", "Actual GLM prefill chunks and lane-host decode fairness using a fake engine").dependOn(&schedule_run.step);
b.step("test-glm-prefill-widths-host", "Actual GLM pass widths, restore cuts and shared lane stats without devices").dependOn(&schedule_run.step);
+ const dsa = b.addTest(.{ .filters = &.{"glm_dsa prefill:"}, .root_module = b.createModule(.{
+ .root_source_file = b.path("zig/src/glm_dsa_prefill_tests.zig"),
+ .target = b.graph.host,
+ .optimize = .debug,
+ .link_libc = true,
+ .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "lanes", .module = lanes } },
+ }) });
+ if (b.graph.host.result.os.tag == .macos) dsa.root_module.linkSystemLibrary("objc", .{});
+ b.step("test-glm-dsa-prefill-host", "GLM DSA prompt progress and cancelled-prefix retention without devices").dependOn(&b.addRunArtifact(dsa).step);
if (b.graph.host.result.os.tag == .macos) {
const comp_mod = hostMod(b, "zig/src/glm_restore_compile.zig", metal, lanes, fabric, sources, core);
const compile = b.addObject(.{ .name = "glm-restore-host", .root_module = comp_mod });
diff --git a/zig/src/families/glm_dsa/backend.zig b/zig/src/families/glm_dsa/backend.zig
index 06d9982039c..c2234f858b8 100644
--- a/zig/src/families/glm_dsa/backend.zig
+++ b/zig/src/families/glm_dsa/backend.zig
@@ -111,21 +111,12 @@ pub const Backend = struct {
} else s.reuse_failed = true;
}
startProgress(s, at);
- var next: usize = 0;
- var mark: usize = 0;
- while (at < prompt.len) {
- if (s.isCancelled()) return error.Cancelled;
- while (next < s.chunks.len and s.chunks[next] <= at) next += 1;
- while (mark < s.reuse.marks.len and s.reuse.marks[mark] <= at) mark += 1;
- var end: u32 = if (next < s.chunks.len) s.chunks[next] else @intCast(prompt.len);
- if (mark < s.reuse.marks.len) end = @min(end, s.reuse.marks[mark]); // a mark ends a chunk: its state is kept there
- const n = @min(end - at, gpu.prompt_rows);
- if (try fl.chunk(e, i, at, n, false)) |t| b.first[i] = t;
- lanes.prefill_widths.completed(b.gpa, s, n);
- 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);
- }
+ try drivePrompt(b, e, i, s, at, &b.first[i]);
+ }
+
+ fn chunkPrompt(b: *Backend, e: *eng.Engine, i: u32, at: u32, n: u32) !?u32 {
+ _ = b;
+ return fl.chunk(e, i, at, n, false);
}
/// The prompt cache's functions: a stream's state at a mark, kept on both Macs by id.
@@ -283,6 +274,60 @@ pub const Backend = struct {
}
};
+fn drivePrompt(b: anytype, e: anytype, i: u32, s: *Stream, initial: u32, first: *u32) !void {
+ var at = initial;
+ errdefer if (s.isCancelled()) s.keepInterruptedPrefill(at);
+ const prompt = s.prompt();
+ var next: usize = 0;
+ var mark: usize = 0;
+ while (at < prompt.len) {
+ if (s.isCancelled()) return error.Cancelled;
+ while (next < s.chunks.len and s.chunks[next] <= at) next += 1;
+ while (mark < s.reuse.marks.len and s.reuse.marks[mark] <= at) mark += 1;
+ var end: u32 = if (next < s.chunks.len) s.chunks[next] else @intCast(prompt.len);
+ if (mark < s.reuse.marks.len) end = @min(end, s.reuse.marks[mark]); // a mark ends a chunk: its state is kept there
+ const n = @min(end - at, gpu.prompt_rows);
+ if (try b.chunkPrompt(e, i, at, n)) |t| first.* = t;
+ lanes.prefill_widths.completed(b.gpa, s, n);
+ at += n;
+ s.fill_at.store(at, .monotonic); // the 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);
+ }
+}
+
+test "glm_dsa prefill: cancellation keeps a completed prefix for exact resume" {
+ _ = Backend.prefill;
+ const Fake = struct {
+ gpa: std.mem.Allocator = std.testing.allocator,
+ stopped: bool = false,
+
+ fn chunkPrompt(f: *@This(), _: void, _: u32, _: u32, _: u32) !?u32 {
+ f.stopped = true;
+ return null;
+ }
+ fn cancelled(ctx: *anyopaque) bool {
+ const f: *@This() = @ptrCast(@alignCast(ctx));
+ return f.stopped;
+ }
+ };
+ const Kept = struct {
+ at: u32 = 0,
+ fn interrupted(ctx: *anyopaque, _: *Stream, at: u32) void {
+ const k: *@This() = @ptrCast(@alignCast(ctx));
+ k.at = at;
+ }
+ };
+ var f: Fake = .{};
+ var kept: Kept = .{};
+ const ids = [_]u32{ 3, 1, 4, 1 };
+ var s = try Stream.init(std.testing.allocator, .{ .id = "stopped", .prompt = &ids, .max_new = 1, .chunks = &.{2}, .reuse = .{ .hook = .{ .ptr = &kept, .at = Kept.interrupted, .interrupted = Kept.interrupted } } });
+ defer s.deinit(std.testing.allocator);
+ s.cancel_check = .{ .ptr = &f, .check = Fake.cancelled };
+ var first: u32 = 0;
+ try std.testing.expectError(error.Cancelled, drivePrompt(&f, {}, 0, &s, 0, &first));
+ try std.testing.expectEqual(@as(u32, 2), kept.at);
+}
+
test "glm_dsa prefill: a restored row seeds landed progress" {
const ids: [2049]u32 = @splat(1);
var resumed = try Stream.init(std.testing.allocator, .{ .id = "resumed", .prompt = &ids, .max_new = 1 });
diff --git a/zig/src/glm_dsa_prefill_tests.zig b/zig/src/glm_dsa_prefill_tests.zig
new file mode 100644
index 00000000000..cb847f1497e
--- /dev/null
+++ b/zig/src/glm_dsa_prefill_tests.zig
@@ -0,0 +1,3 @@
+test {
+ _ = @import("families/glm_dsa/backend.zig");
+}
From 9328323b1b33427261db1d499639f3de060d1d14 Mon Sep 17 00:00:00 2001
From: ashhart <71890694+ashhart@users.noreply.github.com>
Date: Fri, 20 Nov 2026 11:14:54 +0000
Subject: [PATCH 22/32] muse spark: retain cancelled prefill prefixes
---
zig/src/families/muse_spark/native.zig | 28 ++++++++++++++++++++++++--
1 file changed, 26 insertions(+), 2 deletions(-)
diff --git a/zig/src/families/muse_spark/native.zig b/zig/src/families/muse_spark/native.zig
index 4be458df44a..526fd3c9f86 100644
--- a/zig/src/families/muse_spark/native.zig
+++ b/zig/src/families/muse_spark/native.zig
@@ -198,7 +198,7 @@ pub const Lanes = struct {
defer l.gpa.free(toks);
var at: usize = from;
while (at < ids.len) {
- if (s.isCancelled()) return error.Cancelled;
+ try cancelledPrefix(s, at);
if (l.pins != null and s.yields()) return error.Yielded; // a warm pass steps aside, keeping its marks
const n = kept.chunkRows(at, ids.len, pr.cap, marks);
for (0..n) |j| toks[j] = ids[at + j];
@@ -213,7 +213,7 @@ pub const Lanes = struct {
var rows: [fwd.DECODE_ROWS]fwd.Row = undefined;
var at: usize = from;
while (at < ids.len) {
- if (s.isCancelled()) return error.Cancelled;
+ try cancelledPrefix(s, at);
if (l.pins != null and s.yields()) return error.Yielded;
const n = kept.chunkRows(at, ids.len, fwd.DECODE_ROWS, marks);
for (0..n) |j| rows[j] = .{ .slot = slot, .pos = @intCast(at + j), .token = ids[at + j] };
@@ -225,6 +225,12 @@ pub const Lanes = struct {
}
}
+ fn cancelledPrefix(s: *lanes.Stream, at: usize) !void {
+ if (!s.isCancelled()) return;
+ s.keepInterruptedPrefill(@intCast(at));
+ return error.Cancelled;
+ }
+
fn bit(slot: u32) u32 {
return @as(u32, 1) << @intCast(slot);
}
@@ -559,3 +565,21 @@ test "Windows refuses Muse Spark's two ranks by name, before any TP session open
const why = explain(null, error.MuseSparkTpPlatform).?;
try std.testing.expect(std.mem.indexOf(u8, why, "runs on Linux only") != null);
}
+
+test "muse prefill: cancellation keeps a completed prefix for exact resume" {
+ const Kept = struct {
+ at: u32 = 0,
+ fn interrupted(ctx: *anyopaque, _: *lanes.Stream, at: u32) void {
+ const k: *@This() = @ptrCast(@alignCast(ctx));
+ k.at = at;
+ }
+ fn cancelled(_: *anyopaque) bool {
+ return true;
+ }
+ };
+ var snap: Kept = .{};
+ var s = try lanes.Stream.init(std.testing.allocator, .{ .id = "stopped", .prompt = &.{ 3, 1, 4, 1, 5, 9 }, .max_new = 1, .reuse = .{ .hook = .{ .ptr = &snap, .at = Kept.interrupted, .interrupted = Kept.interrupted } }, .cancel_check = .{ .ptr = &snap, .check = Kept.cancelled } });
+ defer s.deinit(std.testing.allocator);
+ try std.testing.expectError(error.Cancelled, Lanes.cancelledPrefix(&s, 2));
+ try std.testing.expectEqual(@as(u32, 2), snap.at);
+}
From 280e0a420772b107d5b2aac14d2f9b9782ece716 Mon Sep 17 00:00:00 2001
From: ashhart <71890694+ashhart@users.noreply.github.com>
Date: Fri, 20 Nov 2026 11:15:37 +0000
Subject: [PATCH 23/32] lfm2 moe: retain cancelled prefill state
---
zig/src/families/lfm2_moe/cuda_backend.zig | 26 +++++++++++++++++++++-
1 file changed, 25 insertions(+), 1 deletion(-)
diff --git a/zig/src/families/lfm2_moe/cuda_backend.zig b/zig/src/families/lfm2_moe/cuda_backend.zig
index 46ac4e2ef81..dfe2f3517d9 100644
--- a/zig/src/families/lfm2_moe/cuda_backend.zig
+++ b/zig/src/families/lfm2_moe/cuda_backend.zig
@@ -282,7 +282,7 @@ pub const Lfm = struct {
fn chunk(x: *Lfm, s: *Stream, l: *Lane) !bool {
const p = s.prompt();
const at = l.fill.?;
- if (s.isCancelled()) return error.Cancelled;
+ try cancelledPrefix(s, at);
const points = lanes.cutPoints(s); // cold and resumed passes cut at the same named starts
const c = cut(at, p.len, s.reuse.marks, points);
const done = c.end == p.len;
@@ -342,6 +342,30 @@ pub const Lfm = struct {
return c;
}
+ fn cancelledPrefix(s: *Stream, at: usize) !void {
+ if (!s.isCancelled()) return;
+ s.keepInterruptedPrefill(@intCast(at));
+ return error.Cancelled;
+ }
+
+ test "lfm2 moe prefill: cancellation keeps a completed prefix for exact resume" {
+ const Kept = struct {
+ at: u32 = 0,
+ fn interrupted(ctx: *anyopaque, _: *Stream, at: u32) void {
+ const k: *@This() = @ptrCast(@alignCast(ctx));
+ k.at = at;
+ }
+ fn cancelled(_: *anyopaque) bool {
+ return true;
+ }
+ };
+ var stored: Kept = .{};
+ var s = try Stream.init(std.testing.allocator, .{ .id = "stopped", .prompt = &.{ 3, 1, 4, 1, 5, 9 }, .max_new = 1, .reuse = .{ .hook = .{ .ptr = &stored, .at = Kept.interrupted, .interrupted = Kept.interrupted } }, .cancel_check = .{ .ptr = &stored, .check = Kept.cancelled } });
+ defer s.deinit(std.testing.allocator);
+ try std.testing.expectError(error.Cancelled, cancelledPrefix(&s, 2));
+ try std.testing.expectEqual(@as(u32, 2), stored.at);
+ }
+
fn prefill(ptr: *anyopaque, s: *Stream) anyerror!void {
const x = self(ptr);
const l = try x.opening(s);
From 8ec6db2849615fa468c606a470472081288456df Mon Sep 17 00:00:00 2001
From: ashhart <71890694+ashhart@users.noreply.github.com>
Date: Fri, 20 Nov 2026 11:18:12 +0000
Subject: [PATCH 24/32] dots mocr: retain cancelled prefill snapshots
---
zig/build/dots_mocr.zig | 5 ++-
zig/build/hip.zig | 2 +-
zig/src/families/dots_mocr/hip.zig | 1 +
zig/src/families/dots_mocr/hip_backend.zig | 42 ++++++++++++++++++++--
4 files changed, 45 insertions(+), 5 deletions(-)
diff --git a/zig/build/dots_mocr.zig b/zig/build/dots_mocr.zig
index 90765b85fa1..68be4934784 100644
--- a/zig/build/dots_mocr.zig
+++ b/zig/build/dots_mocr.zig
@@ -23,10 +23,13 @@ pub fn hostTests(b: *std.Build, test_step: *std.Build.Step) void {
}
}
-pub fn hipTests(b: *std.Build, hip: *std.Build.Module, test_step: *std.Build.Step) void {
+pub fn hipTests(b: *std.Build, hip: *std.Build.Module, backend: *std.Build.Module, test_step: *std.Build.Step) void {
const host = b.addRunArtifact(b.addTest(.{ .root_module = hip, .filters = &.{ "dots HIP columns:", "dots HIP vision:", "dots HIP text:" } }));
test_step.dependOn(&host.step);
b.step("test-dots-hip-host", "dots.mocr HIP column, vision and text operator admission without GPU execution").dependOn(&host.step);
+ const backend_host = b.addRunArtifact(b.addTest(.{ .root_module = backend, .filters = &.{"dots prefill"} }));
+ test_step.dependOn(&backend_host.step);
+ b.step("test-dots-hip-prefill-host", "dots.mocr interrupted prefill snapshots without GPU execution").dependOn(&backend_host.step);
const family = hipModule(b, hip);
const weights_host = b.addRunArtifact(b.addTest(.{ .root_module = family, .filters = &.{ "dots HIP weights:", "dots HIP graph:", "dots HIP plan:" } }));
b.step("test-dots-hip-weights-host", "HIP weight ownership, layout and budget refusal without GPU calls").dependOn(&weights_host.step);
diff --git a/zig/build/hip.zig b/zig/build/hip.zig
index 4c7cfe89cb4..457b2ab3d69 100644
--- a/zig/build/hip.zig
+++ b/zig/build/hip.zig
@@ -169,7 +169,7 @@ pub fn steps(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.buil
b.step("test-hip-family-offers-host", "HIP optional native family metadata without device execution").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = host.native, .filters = &.{"HIP optional family offers:"} })).step);
b.step("test-hip-native-options-host", "Shared HIP native open settings without device execution").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = host.serve, .filters = &.{"HIP native options:"} })).step);
@import("hip_followers.zig").steps(b, &.{ host.serve, host.flashnext, host.nemotron });
- @import("dots_mocr.zig").hipTests(b, host.hip, test_step);
+ @import("dots_mocr.zig").hipTests(b, host.hip, host.native.import_table.get("dots_mocr").?, test_step);
b.step("test-dots-native-host", "dots.mocr registry, reasoning, and unsupported flags without GPU execution").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = host.native, .filters = &.{ "dots refuses", "every registered family", "a HIP family declares replies without reasoning" } })).step);
@import("lighton_hip.zig").host(b, host.lighton, test_step);
const qwen_vision_host = b.addRunArtifact(b.addTest(.{ .root_module = host.family.import_table.get("qwen_hip_vision").? }));
diff --git a/zig/src/families/dots_mocr/hip.zig b/zig/src/families/dots_mocr/hip.zig
index ab18985e424..d0d8f934407 100644
--- a/zig/src/families/dots_mocr/hip.zig
+++ b/zig/src/families/dots_mocr/hip.zig
@@ -14,4 +14,5 @@ test {
_ = graph;
_ = text;
_ = plan;
+ _ = @import("hip_backend.zig");
}
diff --git a/zig/src/families/dots_mocr/hip_backend.zig b/zig/src/families/dots_mocr/hip_backend.zig
index f7a5308cde0..2dd7190939d 100644
--- a/zig/src/families/dots_mocr/hip_backend.zig
+++ b/zig/src/families/dots_mocr/hip_backend.zig
@@ -129,9 +129,17 @@ pub const Backend = struct {
return l.local[0..n];
}
+ fn cancelledPrefix(h: *Backend, s: *lanes.Stream, at: usize) !void {
+ if (!s.isCancelled()) return;
+ if (h.store.usable(@intCast(at), s.chunks)) s.keepInterruptedPrefill(@intCast(at));
+ return error.Cancelled;
+ }
+
fn step(h: *Backend, s: *lanes.Stream) !bool {
- if (s.isCancelled()) return error.Cancelled;
- const l = h.map.get(s) orelse try h.begin(s);
+ const existing = h.map.get(s);
+ if (existing == null and s.isCancelled()) return error.Cancelled;
+ const l = existing orelse try h.begin(s);
+ try cancelledPrefix(h, s, if (l.fill) |filled| filled.at else 0);
if (l.fill == null) return true;
const f = &l.fill.?;
const prompt = s.prompt();
@@ -156,7 +164,7 @@ pub const Backend = struct {
if (f.cut(to)) if (s.reuse.hook) |hook| hook.at(hook.ptr, s, @intCast(to));
}
if (f.at < prompt.len) return false;
- if (s.isCancelled()) return error.Cancelled;
+ try cancelledPrefix(h, s, f.at);
l.first = try h.firstDraw(s, l, &.{});
l.fill = null;
return true;
@@ -263,3 +271,31 @@ pub const Backend = struct {
if (h.map.fetchRemove(s)) |entry| h.drop(entry.value);
}
};
+
+test "dots prefill cancellation keeps a completed prefix for exact resume" {
+ const Kept = struct {
+ at: u32 = 0,
+ fn interrupted(ctx: *anyopaque, _: *lanes.Stream, at: u32) void {
+ const k: *@This() = @ptrCast(@alignCast(ctx));
+ k.at = at;
+ }
+ fn cancelled(_: *anyopaque) bool {
+ return true;
+ }
+ };
+ var kept: Kept = .{};
+ var s = try lanes.Stream.init(std.testing.allocator, .{
+ .id = "stopped",
+ .prompt = &.{ 3, 1, 4, 1, 5, 9 },
+ .max_new = 1,
+ .reuse = .{ .hook = .{ .ptr = &kept, .at = Kept.interrupted } },
+ .cancel_check = .{ .ptr = &kept, .check = Kept.cancelled },
+ });
+ defer s.deinit(std.testing.allocator);
+ var h: Backend = undefined;
+ h.store = api.prompt_cache.Store.init(std.testing.allocator, undefined, .{}, 0);
+ defer h.store.deinit();
+ try std.testing.expectEqual(@as(u32, 0), kept.at);
+ try std.testing.expectError(error.Cancelled, Backend.cancelledPrefix(&h, &s, 2));
+ try std.testing.expectEqual(@as(u32, 2), kept.at);
+}
From 98c21dfcb288f695a123b87fceeb29c10bf258de Mon Sep 17 00:00:00 2001
From: ashhart <71890694+ashhart@users.noreply.github.com>
Date: Fri, 20 Nov 2026 11:19:32 +0000
Subject: [PATCH 25/32] lfm2 moe: split cancellation regression fixture
---
zig/src/families/lfm2_moe/cuda_backend.zig | 20 +----------------
zig/src/families/lfm2_moe/cuda_family.zig | 2 +-
.../families/lfm2_moe/cuda_prefill_test.zig | 22 +++++++++++++++++++
3 files changed, 24 insertions(+), 20 deletions(-)
create mode 100644 zig/src/families/lfm2_moe/cuda_prefill_test.zig
diff --git a/zig/src/families/lfm2_moe/cuda_backend.zig b/zig/src/families/lfm2_moe/cuda_backend.zig
index dfe2f3517d9..70d4a857e13 100644
--- a/zig/src/families/lfm2_moe/cuda_backend.zig
+++ b/zig/src/families/lfm2_moe/cuda_backend.zig
@@ -342,30 +342,12 @@ pub const Lfm = struct {
return c;
}
- fn cancelledPrefix(s: *Stream, at: usize) !void {
+ pub fn cancelledPrefix(s: *Stream, at: usize) !void {
if (!s.isCancelled()) return;
s.keepInterruptedPrefill(@intCast(at));
return error.Cancelled;
}
- test "lfm2 moe prefill: cancellation keeps a completed prefix for exact resume" {
- const Kept = struct {
- at: u32 = 0,
- fn interrupted(ctx: *anyopaque, _: *Stream, at: u32) void {
- const k: *@This() = @ptrCast(@alignCast(ctx));
- k.at = at;
- }
- fn cancelled(_: *anyopaque) bool {
- return true;
- }
- };
- var stored: Kept = .{};
- var s = try Stream.init(std.testing.allocator, .{ .id = "stopped", .prompt = &.{ 3, 1, 4, 1, 5, 9 }, .max_new = 1, .reuse = .{ .hook = .{ .ptr = &stored, .at = Kept.interrupted, .interrupted = Kept.interrupted } }, .cancel_check = .{ .ptr = &stored, .check = Kept.cancelled } });
- defer s.deinit(std.testing.allocator);
- try std.testing.expectError(error.Cancelled, cancelledPrefix(&s, 2));
- try std.testing.expectEqual(@as(u32, 2), stored.at);
- }
-
fn prefill(ptr: *anyopaque, s: *Stream) anyerror!void {
const x = self(ptr);
const l = try x.opening(s);
diff --git a/zig/src/families/lfm2_moe/cuda_family.zig b/zig/src/families/lfm2_moe/cuda_family.zig
index 50263f9d8af..d7c1729c779 100644
--- a/zig/src/families/lfm2_moe/cuda_family.zig
+++ b/zig/src/families/lfm2_moe/cuda_family.zig
@@ -14,7 +14,7 @@ test {
_ = kernels;
_ = model;
_ = forward;
- _ = backend;
+ _ = @import("cuda_prefill_test.zig");
_ = native;
_ = snap;
}
diff --git a/zig/src/families/lfm2_moe/cuda_prefill_test.zig b/zig/src/families/lfm2_moe/cuda_prefill_test.zig
new file mode 100644
index 00000000000..1a2f40d6719
--- /dev/null
+++ b/zig/src/families/lfm2_moe/cuda_prefill_test.zig
@@ -0,0 +1,22 @@
+const std = @import("std");
+const lanes = @import("lanes");
+const backend = @import("cuda_backend.zig");
+const Stream = lanes.Stream;
+
+test "lfm2 moe prefill: cancellation keeps a completed prefix for exact resume" {
+ const Kept = struct {
+ at: u32 = 0,
+ fn interrupted(ctx: *anyopaque, _: *Stream, at: u32) void {
+ const k: *@This() = @ptrCast(@alignCast(ctx));
+ k.at = at;
+ }
+ fn cancelled(_: *anyopaque) bool {
+ return true;
+ }
+ };
+ var stored: Kept = .{};
+ var s = try Stream.init(std.testing.allocator, .{ .id = "stopped", .prompt = &.{ 3, 1, 4, 1, 5, 9 }, .max_new = 1, .reuse = .{ .hook = .{ .ptr = &stored, .at = Kept.interrupted } }, .cancel_check = .{ .ptr = &stored, .check = Kept.cancelled } });
+ defer s.deinit(std.testing.allocator);
+ try std.testing.expectError(error.Cancelled, backend.Lfm.cancelledPrefix(&s, 2));
+ try std.testing.expectEqual(@as(u32, 2), stored.at);
+}
From 9a30d176d1ef12ea0dc58a0dd48e3b9629684d55 Mon Sep 17 00:00:00 2001
From: ashhart <71890694+ashhart@users.noreply.github.com>
Date: Fri, 20 Nov 2026 11:21:57 +0000
Subject: [PATCH 26/32] minimax_m3: reserve draft state before cache admission
---
zig/build/qwen27_host.zig | 2 +-
zig/src/families/minimax_m3/budget.zig | 7 +++
zig/src/families/minimax_m3/dflash2.zig | 7 +++
zig/src/families/minimax_m3/dspark.zig | 7 +++
zig/src/native/minimax_m3.zig | 66 ++++++++++++++++---------
5 files changed, 65 insertions(+), 24 deletions(-)
diff --git a/zig/build/qwen27_host.zig b/zig/build/qwen27_host.zig
index 5d0b5be5def..c114cb3dbcd 100644
--- a/zig/build/qwen27_host.zig
+++ b/zig/build/qwen27_host.zig
@@ -112,7 +112,7 @@ pub fn compileHost(b: *std.Build, metal: *std.Build.Module, engine: *std.Build.M
floor_step.dependOn(&run.step);
}
const minimax = b.createModule(.{ .root_source_file = b.path("zig/src/native/minimax_m3.zig"), .target = b.graph.host, .link_libc = true, .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "tensorfold", .module = engine }, .{ .name = "engine_api", .module = api } } });
- b.step("test-minimax-info-host", "MiniMax logprob offers against its actual wrapped backend without devices").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = minimax, .filters = &.{"MiniMax capabilities:"} })).step);
+ b.step("test-minimax-info-host", "MiniMax logprob offers and draft reservation against its actual wrapped backend without devices").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = minimax, .filters = &.{ "MiniMax capabilities:", "minimax_m3 budget: drafting reserves shared taps and every stream" } })).step);
const boundary = b.addTest(.{ .root_module = b.createModule(.{ .root_source_file = b.path("zig/qwen27_bank_boundary_host.zig"), .target = b.graph.host, .optimize = .debug, .link_libc = true, .imports = &.{ .{ .name = "tensorfold", .module = engine }, .{ .name = "metal", .module = metal } } }), .filters = &.{"qwen27 bank boundary:"} });
b.step("test-qwen27-bank-boundary-host", "Runner pending-keep guards with no device or shader execution").dependOn(&b.addRunArtifact(boundary).step);
const facts = b.createModule(.{ .root_source_file = b.path("zig/src/native/draft_sources_metal_test.zig"), .target = b.graph.host, .link_libc = true, .imports = &.{ .{ .name = "metal", .module = metal }, .{ .name = "tensorfold", .module = engine }, .{ .name = "engine_api", .module = api }, .{ .name = "lanes", .module = lanes } } });
diff --git a/zig/src/families/minimax_m3/budget.zig b/zig/src/families/minimax_m3/budget.zig
index 5461cb68b86..1695304b7af 100644
--- a/zig/src/families/minimax_m3/budget.zig
+++ b/zig/src/families/minimax_m3/budget.zig
@@ -21,7 +21,14 @@ pub fn caches(ram: u64, working_set: u64, text: ?[]const u8, resident: u64) erro
}
return if (limit > resident + margin) limit - resident - margin else 0;
}
+/// Draft scratch and per-stream bytes; `base` already owns the checkpoint's draft weights.
+pub const Draft = struct { fixed: u64, stream: u64, tap_row: u64 };
+pub fn residentBytes(base: u64, streams: u64, draft: ?Draft) u64 {
+ const d = draft orelse return base;
+ const shared = @as(u64, st.batch_rows + st.prompt_rows) * d.tap_row;
+ return base + d.fixed + shared + streams * (d.stream + d.tap_row);
+}
/// The longest context one stream's caches fit in `bytes`, at most `most`.
pub fn longest(c: *const cfg.Config, bytes: u64, most: usize) usize {
if (st.cacheBytes(c, 1) > bytes) return 0;
diff --git a/zig/src/families/minimax_m3/dflash2.zig b/zig/src/families/minimax_m3/dflash2.zig
index 48e838af538..00245506892 100644
--- a/zig/src/families/minimax_m3/dflash2.zig
+++ b/zig/src/families/minimax_m3/dflash2.zig
@@ -229,6 +229,13 @@ pub const Drafter = struct {
return d;
}
+ /// Draft scratch only: its weights are part of the target checkpoint's resident bytes.
+ pub fn fixedBytes(d: *const Drafter) u64 {
+ var bytes: u64 = 0;
+ for (d.s) |x| bytes += x.length();
+ return bytes;
+ }
+
pub fn deinit(d: *Drafter) void {
d.settle() catch {}; // an absorb in flight writes the lanes freed below
d.setResident(null);
diff --git a/zig/src/families/minimax_m3/dspark.zig b/zig/src/families/minimax_m3/dspark.zig
index 2794a42cff2..0c7f3633874 100644
--- a/zig/src/families/minimax_m3/dspark.zig
+++ b/zig/src/families/minimax_m3/dspark.zig
@@ -222,6 +222,13 @@ pub const Drafter = struct {
return d;
}
+ /// Draft scratch only: its weights are part of the target checkpoint's resident bytes.
+ pub fn fixedBytes(d: *const Drafter) u64 {
+ var bytes: u64 = 0;
+ for (d.s) |x| bytes += x.length();
+ return bytes;
+ }
+
pub fn deinit(d: *Drafter) void {
d.settle() catch {}; // an absorb in flight writes the lanes freed below
d.setResident(null);
diff --git a/zig/src/native/minimax_m3.zig b/zig/src/native/minimax_m3.zig
index ce2e2f535fa..43787a32e27 100644
--- a/zig/src/native/minimax_m3.zig
+++ b/zig/src/native/minimax_m3.zig
@@ -70,7 +70,32 @@ pub fn open(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, o: api.Ope
const c = &model.config; // the decode window's and the prompt chunk's buffers
const tower: u64 = if (model.vision) |v| v.bytes() else 0;
const scratch: u64 = fl.state.scratchBytes(c, fl.state.batch_rows, c.context) + fl.state.scratchBytes(c, fl.state.prompt_rows, c.context) + tower;
- const budget = fl.budget.caches(ram, model.device.maxWorkingSet(), text, model.checkpoint.residentBytes() + scratch) catch {
+ const df2 = if (o.drafts and kind == .dflash2) fl.dflash2.Config.read(gpa, io, o.dir) catch |err| {
+ problem.* = try std.fmt.allocPrint(a, "the checkpoint's DFlash2 config cannot be read ({s})", .{@errorName(err)});
+ model.deinit();
+ return null;
+ } else null;
+ const dspark = if (o.drafts and df2 == null) fl.dspark.Config.read(gpa, io, o.dir) catch |err| {
+ problem.* = try std.fmt.allocPrint(a, "the checkpoint's DSpark config cannot be read ({s})", .{@errorName(err)});
+ model.deinit();
+ return null;
+ } else null;
+ const draft2 = if (df2) |dc| try fl.dflash2.Drafter.init(gpa, model, dc) else null;
+ errdefer if (draft2) |d| d.deinit();
+ const draft = if (dspark) |dc| try fl.dspark.Drafter.init(gpa, model, dc) else null;
+ errdefer if (draft) |d| d.deinit();
+ const reserved: ?fl.budget.Draft = if (draft2) |d| .{
+ .fixed = d.fixedBytes(),
+ .stream = d.laneBytes(),
+ .tap_row = @as(u64, df2.?.taps.len) * model.config.hidden * 2,
+ } else if (draft) |d| .{
+ .fixed = d.fixedBytes(),
+ .stream = d.laneBytes(),
+ .tap_row = @as(u64, dspark.?.taps.len) * model.config.hidden * 2,
+ } else null;
+ const budget = fl.budget.caches(ram, model.device.maxWorkingSet(), text, fl.budget.residentBytes(model.checkpoint.residentBytes() + scratch, @max(o.lanes, 1), reserved)) catch {
+ if (draft2) |d| d.deinit();
+ if (draft) |d| d.deinit();
model.deinit();
problem.* = "MINIMAX_LOAD_LIMIT_GB is not a load limit: give a number of GB above 0, or unset it for 75% of RAM";
return null;
@@ -79,6 +104,8 @@ pub fn open(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, o: api.Ope
const window: i64 = o.context orelse @intCast(fits);
if (window < 1 or window > fits) {
problem.* = try std.fmt.allocPrint(a, "--context {d}: this Mac's MiniMax-M3 caches fit {d} tokens under its load limit (75% of RAM, or MINIMAX_LOAD_LIMIT_GB)", .{ window, fits });
+ if (draft2) |d| d.deinit();
+ if (draft) |d| d.deinit();
model.deinit(); // after the message, so a failed allocation leaves the model to the errdefer
return null;
}
@@ -89,34 +116,19 @@ pub fn open(a: std.mem.Allocator, gpa: std.mem.Allocator, io: std.Io, o: api.Ope
h.io = io;
h.model = model;
h.resident = null;
- const df2 = if (o.drafts and kind == .dflash2) fl.dflash2.Config.read(gpa, io, o.dir) catch |err| {
- problem.* = try std.fmt.allocPrint(a, "the checkpoint's DFlash2 config cannot be read ({s})", .{@errorName(err)});
- model.deinit();
- return null;
- } else null;
- const dspark = if (o.drafts and df2 == null) fl.dspark.Config.read(gpa, io, o.dir) catch |err| {
- problem.* = try std.fmt.allocPrint(a, "the checkpoint's DSpark config cannot be read ({s})", .{@errorName(err)});
- model.deinit();
- return null;
- } else null;
+ h.draft = draft;
+ h.draft2 = draft2;
h.metal = try fl.backend.Metal.init(gpa, model, .{ .capacity = @intCast(window), .streams = @max(o.lanes, 1), .budget = budget, .drafts = dspark != null or df2 != null });
errdefer h.metal.deinit();
try h.metal.warm();
- h.draft = null;
- h.draft2 = null;
h.wrap = null;
- if (df2) |dc| {
- try h.metal.measure();
- h.draft2 = try fl.dflash2.Drafter.init(gpa, model, dc);
- h.wrap = try lanes.drafted.Drafted.init(gpa, h.metal.backend(), h.draft2.?.drafter());
- } else if (dspark) |dc| {
- try h.metal.measure(); // the depth rule prices drafts against the window forward's cost by rows
- h.draft = try fl.dspark.Drafter.init(gpa, model, dc);
- h.wrap = try lanes.drafted.Drafted.init(gpa, h.metal.backend(), h.draft.?.drafter());
+ if (h.draft2 != null or h.draft != null) try h.metal.measure(); // the depth rule prices drafts against the window forward's cost by rows
+ if (h.draft2) |d| {
+ h.wrap = try lanes.drafted.Drafted.init(gpa, h.metal.backend(), d.drafter());
+ } else if (h.draft) |d| {
+ h.wrap = try lanes.drafted.Drafted.init(gpa, h.metal.backend(), d.drafter());
}
errdefer if (h.wrap) |*w| w.deinit();
- errdefer if (h.draft) |d| d.deinit();
- errdefer if (h.draft2) |d| d.deinit();
const facts = if (h.wrap) |*w| w.facts(h.metal.facts()) else h.metal.facts();
h.config = try lanes.Config.init(gpa, facts, fl.state.window_rows, fl.state.window_rows - 1);
errdefer h.config.deinit(gpa);
@@ -256,3 +268,11 @@ test "MiniMax capabilities: logprobs match the actual plain or external-draft ba
try std.testing.expectEqual(plain.context_window, drafted.context_window);
try std.testing.expectEqual(plain.prefill_step, drafted.prefill_step);
}
+
+test "minimax_m3 budget: drafting reserves shared taps and every stream" {
+ const base: u64 = 4096;
+ const draft = fl.budget.Draft{ .fixed = 100, .stream = 200, .tap_row = 8 };
+ try std.testing.expectEqual(base, fl.budget.residentBytes(base, 2, null));
+ const shared = @as(u64, fl.state.batch_rows + fl.state.prompt_rows) * draft.tap_row;
+ try std.testing.expectEqual(base + draft.fixed + shared + 2 * (draft.stream + draft.tap_row), fl.budget.residentBytes(base, 2, draft));
+}
From 57998b8cf7bd4fbdcf2e962fd81811b1c75895f0 Mon Sep 17 00:00:00 2001
From: ashhart <71890694+ashhart@users.noreply.github.com>
Date: Fri, 20 Nov 2026 11:27:33 +0000
Subject: [PATCH 27/32] prompt cache: fix RAM rollback fault count
---
zig/src/core/prompt_cache_index_test.zig | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/zig/src/core/prompt_cache_index_test.zig b/zig/src/core/prompt_cache_index_test.zig
index 742d02966d7..e839c4041e2 100644
--- a/zig/src/core/prompt_cache_index_test.zig
+++ b/zig/src/core/prompt_cache_index_test.zig
@@ -257,8 +257,8 @@ test "snapshot index: RAM keep unwinds every allocation failure and failed famil
break;
}
}
- try std.testing.expect(succeeded); // spans, Entry, the one prompt copy, the save, then both publication reserves
- try std.testing.expectEqual(@as(usize, 7), failures);
+ try std.testing.expect(succeeded); // empty images allocate nothing: spans, Entry, prompt, save, then both publication reserves
+ try std.testing.expectEqual(@as(usize, 6), failures);
}
/// A conversation tree: each prompt a kept one's prefix and new tokens, so states share long prefixes and fork.
From 52f9ee5c8d465add8c49b13a140c6d6d6061aa41 Mon Sep 17 00:00:00 2001
From: ashhart <71890694+ashhart@users.noreply.github.com>
Date: Fri, 20 Nov 2026 11:58:15 +0000
Subject: [PATCH 28/32] docs: scope Gemma and XPU qualification evidence
---
docs/recipes/xpu-arc.md | 3 +--
docs/supported-models.md | 4 ++--
zig/src/families/gemma4/cuda_native.zig | 2 +-
3 files changed, 4 insertions(+), 5 deletions(-)
diff --git a/docs/recipes/xpu-arc.md b/docs/recipes/xpu-arc.md
index 08f6bf5fc20..b1c153c3ad3 100644
--- a/docs/recipes/xpu-arc.md
+++ b/docs/recipes/xpu-arc.md
@@ -1,7 +1,6 @@
# Intel Arc (XPU): Nemotron 3.5 Lightning
-Status: experimental. One checkpoint, one card class, one request at a time. Everything below was measured on the setup in
-[Tested setup](#tested-setup); nothing is claimed for other cards.
+Status: each checkpoint remains separately qualified and the broader backend is experimental. Nemotron runs on one Arc Pro B70 with one or more streams; the table below also records LFM3 on Iris Xe. Every measurement belongs to its named [tested setup](#tested-setup); nothing is claimed for other cards or unlisted checkpoints.
The Intel GPU backend runs OpenCL C kernels compiled to SPIR-V (`ocloc`) through Level Zero, on the same loader table as the
Qwen3.8-27B XPU runner (`zig/src/xpu/ze.zig`), and has no CUDA or Metal code in its path. The token-id CLI is a separate
diff --git a/docs/supported-models.md b/docs/supported-models.md
index 3e16288ce65..00fb716df48 100644
--- a/docs/supported-models.md
+++ b/docs/supported-models.md
@@ -45,8 +45,8 @@ Conversions are explicitly marked: their upstream weights need the linked conver
| LFM2.5-24B-A2B, MLX 4 / 6 / 8-bit | `tensorfold pull LiquidAI/LFM2.5-24B-A2B-MLX-4bit@667408d494bde191c2cb9dd4f4549827816b9275`
`tensorfold pull LiquidAI/LFM2.5-24B-A2B-MLX-6bit@1deec53eb49571e21cdcbf82fd5839248f07ed88`
`tensorfold pull LiquidAI/LFM2.5-24B-A2B-MLX-8bit@67ab417dd02d0c9545802a726df668620eae049d` | One Mac (M4 Pro checked), or one NVIDIA GPU with the 4-bit export (GB10 checked). | [Native recipe](recipes/lfm2.5-24b-a2b.md) ([CUDA](recipes/lfm2.5-24b-a2b.md#cuda)), [release history](../CHANGELOG.md). Weights: LFM Open License v1.0. |
| Qwen3.6-35B-A3B, MLX with MTP | `tensorfold pull TensorFold/Qwen3.6-35B-A3B-MLX-4bit-MTP@81169a9bc511a27c1b4eedb77a2cd98ced431847` | One GB10; 20.9 GB checkpoint. | [Qwen3.6](recipes/qwen3.6-moe.md). Native CUDA receipt here. Metal also registers this model type; the recipe's Metal commands describe Python 0.6.6. |
| Qwen3.6-35B-A3B, NVIDIA NVFP4 with MTP | `tensorfold pull nvidia/Qwen3.6-35B-A3B-NVFP4@1355db6a052410cfd62085d94b58866fd0f2c3c5` | One GB10; 20.3 GiB on the device, 20.9 GiB with the drafter. | [Native CUDA](recipes/qwen3.6-moe.md#nvidias-nvfp4-checkpoint-native-cuda). Serve with `--drafter` naming the same checkpoint for MTP drafts. |
-| Gemma 4 31B, MLX 4-bit | `tensorfold pull mlx-community/gemma-4-31B-it-4bit@696d436c404745a59f30e4939a658162b0a9e57f`
`tensorfold pull z-lab/gemma-4-31B-it-DFlash@eabd648301ce28583cc14757912e5e0f84e152e1` | One Mac (M5 Ultra checked), or one GB10 on CUDA. Pre-M5 Metal has a row path; its assistant and DFlash drafters require M5 tensor units. | [Native 31B on Metal](recipes/gemma-4-native.md), [CUDA commands](recipes/gemma-4-native.md#cuda), [CUDA qualification](../CHANGELOG.md#114). Name the drafter with `--drafter`; images with `--vision`. |
-| Gemma 4 12B, converted MLX 4-bit | `hf download google/gemma-4-12B-it --revision 707f0a3b8a3c7ad586ed01e27eafbad8a27dd0f7 --local-dir ~/models/gemma-4-12b-hf`
`hf download google/gemma-4-12B-it-assistant --revision 46d4c6f13f0ac0ad827b915669b8df9b81c64c51 --local-dir ~/models/gemma-4-12b-assistant` | One Mac (M5 Ultra checked); converted text weights 6.3 GB, image weights 100 MB, plus assistant/caches. MLX 4-bit also served on one GB10. Pre-M5 Metal has a row path; the MTP assistant requires M5 tensor units. | [Convert and serve](recipes/gemma-4-12b-native.md). Upstream download needs `hf`; conversion needs Python, mlx and mlx-lm. Serving is native; [CUDA qualification](../CHANGELOG.md#114) includes the MTP assistant. |
+| Gemma 4 31B, MLX 4-bit | `tensorfold pull mlx-community/gemma-4-31B-it-4bit@696d436c404745a59f30e4939a658162b0a9e57f`
`tensorfold pull z-lab/gemma-4-31B-it-DFlash@eabd648301ce28583cc14757912e5e0f84e152e1` | One Mac (M5 Ultra checked), or one GB10 on CUDA. Pre-M5 Metal has a row path; the 31B DFlash drafter requires M5 tensor units. | [Native 31B on Metal](recipes/gemma-4-native.md), [CUDA commands](recipes/gemma-4-native.md#cuda), [CUDA qualification](../CHANGELOG.md#114). Metal uses the named DFlash drafter with `--drafter`; CUDA also qualifies the Google MTP assistant. `--vision` has Metal served checks; CUDA image cells remain unlaunched. |
+| Gemma 4 12B, converted MLX 4-bit | `hf download google/gemma-4-12B-it --revision 707f0a3b8a3c7ad586ed01e27eafbad8a27dd0f7 --local-dir ~/models/gemma-4-12b-hf`
`hf download google/gemma-4-12B-it-assistant --revision 46d4c6f13f0ac0ad827b915669b8df9b81c64c51 --local-dir ~/models/gemma-4-12b-assistant` | One Mac (M5 Ultra checked); converted text weights 6.3 GB, image weights 100 MB, plus assistant/caches. MLX 4-bit also served on one GB10. Pre-M5 Metal has a row path; the MTP assistant requires M5 tensor units. | [Convert and serve](recipes/gemma-4-12b-native.md). Upstream download needs `hf`; conversion needs Python, mlx and mlx-lm. Serving is native; [CUDA qualification](../CHANGELOG.md#114) includes the MTP assistant. `--vision` has Metal served checks; CUDA image cells remain unlaunched. |
| Step-5-Preview, converted affine | `hf download stepfun-ai/Step-5-Preview --local-dir ~/models/step5-preview-fp8` | One 256 GB Mac; text 166.9 GiB, MTP adds 2.5 GiB and vision 3.7 GiB. | [Convert and serve](recipes/step-5-preview.md). The documented 256 GB setup serves converted affine weights; converting the upstream FP8 download needs Python and mlx. |
| MiniMax-M3.1-Flash, community affine 3/4-bit | `hf download BobClawblaw/MiniMax-M3.1-Flash-MLX-mix34 --revision 9524999057e0d277d26438606e033e2191fb465c --local-dir ~/models/MiniMax-M3.1-Flash-MLX-mix34`
`hf download BobClawblaw/MiniMax-M3.1-Flash-MLX-mix256k --revision 916e7ca1044f1c3e7566163096243c940327224d --local-dir ~/models/MiniMax-M3.1-Flash-MLX-mix256k` | One 256 GB M5 Ultra; 203.7 GiB (32,768-token window) or 189.2 GiB (147,456), plus caches. | [MiniMax-M3.1-Flash](recipes/minimax-m3.1-flash.md). Set `MINIMAX_LOAD_LIMIT_GB`; images with `--vision`. Community checkpoints: lossy conversions of MiniMax's NVFP4 release (KL 0.244 / 0.295). MiniMax Community License. |
| Recursive Flint 40B-A2.5B, MLX INT4 | `hf download RecursiveSI/flint-int4 --revision 3b93f9053b530488405ae9fca51d4900d6ce21f0 --local-dir ~/models/flint-int4` | One M5 Mac; M5 Ultra checked; 21.4 GiB resident plus caches. M1-M4 untested. | [Flint](recipes/flint.md). Text and tools; always reasons. Optional `incoai/Flint-DFlash2` through `--drafter` on M5, up to four streams. |
diff --git a/zig/src/families/gemma4/cuda_native.zig b/zig/src/families/gemma4/cuda_native.zig
index 9678ae00f75..b50504b99d7 100644
--- a/zig/src/families/gemma4/cuda_native.zig
+++ b/zig/src/families/gemma4/cuda_native.zig
@@ -1,4 +1,4 @@
-//! Gemma 4 (affine-4/64 text) behind the native CUDA registry; images, widths, drafters (steps 9-12) refused.
+//! Gemma 4 (affine-4/64 text), images and native assistant/DFlash paths behind the CUDA registry.
const std = @import("std");
const cuda = @import("cuda");
const lanes = @import("lanes");
From 8f3233dd1b1a4e2bc37ddc5bfdf9b5561803ab28 Mon Sep 17 00:00:00 2001
From: ashhart <71890694+ashhart@users.noreply.github.com>
Date: Fri, 20 Nov 2026 12:22:16 +0000
Subject: [PATCH 29/32] HIP: share Flash Next prefixes through LaneHost
---
zig/build/hip.zig | 1 +
zig/src/families/flashnext/hip/lanes.zig | 54 ++++++++++++-------
.../families/flashnext/hip/lanes_states.zig | 24 ++++-----
zig/src/families/flashnext/hip/native.zig | 3 ++
zig/src/native/hip.zig | 9 ++--
5 files changed, 54 insertions(+), 37 deletions(-)
diff --git a/zig/build/hip.zig b/zig/build/hip.zig
index 457b2ab3d69..65e62203486 100644
--- a/zig/build/hip.zig
+++ b/zig/build/hip.zig
@@ -192,6 +192,7 @@ pub fn steps(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.buil
b.step("test-qwen35-hip-host", "Qwen HIP family CPU tests with inert kernels").dependOn(&family_host.step);
test_step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = host.flashnext })).step);
b.step("test-flashnext-proposal-hip-host", "Original Flash Next HIP IDs and head-row spans without device runtime").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = host.flashnext, .filters = &.{"Flash Next proposal:"} })).step);
+ b.step("test-flashnext-prefix-hip-host", "Flash Next HIP prompt-store offer to LaneHost without GPU execution").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = host.flashnext, .filters = &.{"Flash Next HIP offers its real prompt store"} })).step);
const nemotron_host = b.addRunArtifact(b.addTest(.{ .root_module = host.nemotron }));
test_step.dependOn(&nemotron_host.step);
b.step("test-nemotron-hip-host", "Nemotron HIP prompt adapters and cancelled-prefix snapshots without GPU execution").dependOn(&nemotron_host.step);
diff --git a/zig/src/families/flashnext/hip/lanes.zig b/zig/src/families/flashnext/hip/lanes.zig
index d8fa79d9d18..13263867171 100644
--- a/zig/src/families/flashnext/hip/lanes.zig
+++ b/zig/src/families/flashnext/hip/lanes.zig
@@ -30,8 +30,6 @@ pub const Fill = struct {
stops: [16]u32 = undefined,
count: usize = 0,
next: usize = 0,
- from: usize = 0,
- kept0: u64 = 0,
};
/// A kept row inside a prompt chunk (forward.Mark): its position, the n-gram history there and its side buffer.
@@ -136,6 +134,11 @@ pub const Fx = struct {
);
}
+ /// The offered store LaneHost uses for cross-request waiting, lookup and reports.
+ pub fn promptCache(f: *Fx) ?*pc.Store {
+ return if (f.store) |*st| st else null;
+ }
+
/// How the kept states are copied: through the bounce buffer when there is one.
pub fn copy(f: *Fx) snapshot.Copy {
return .{ .d = &f.e.driver, .bounce = if (f.bounce) |b| b.bytes else &.{} };
@@ -259,23 +262,22 @@ pub const Fx = struct {
gop.value_ptr.* = lane;
if (f.link != null) try f.send(&.{ @backingInt(worker.Op.begin), lane.id, slot });
const fill = &lane.fill.?;
- if (f.store) |*st| {
- var arena: std.heap.ArenaAllocator = .init(f.gpa);
- defer arena.deinit();
- fill.kept0 = st.counts.kept;
- const plan = st.begin(
- arena.allocator(),
- prompt,
- s.history_len,
- s.shared_prefixes,
- &.{},
- lane,
- &.{},
- ) catch pc.Plan{};
- fill.at = plan.from;
- fill.from = plan.from;
- fill.count = @min(plan.marks.len, fill.stops.len);
- for (plan.marks[0..fill.count], 0..) |mk, i| fill.stops[i] = mk;
+ fill.count = @min(s.reuse.marks.len, fill.stops.len);
+ for (s.reuse.marks[0..fill.count], 0..) |mk, i| fill.stops[i] = mk;
+ if (s.reuse.saved) |saved| {
+ const kept: *snapshot.Saved = @ptrCast(@alignCast(saved));
+ if (kept.at != s.reuse.at or kept.at == 0 or kept.at >= prompt.len) {
+ s.reuse_failed = true;
+ } else {
+ states.restore(f, s, saved) catch |err| switch (err) {
+ error.RestoreRefused, error.SnapshotTooLong, error.UnknownSnapshot => {
+ s.reuse_failed = true;
+ s.reuse_error = err;
+ },
+ else => return err,
+ };
+ if (!s.reuse_failed) fill.at = kept.at;
+ }
}
s.cached = @intCast(fill.at);
return lane;
@@ -338,7 +340,7 @@ pub const Fx = struct {
fill.next = taken;
const live = fill.next < fill.count and to == fill.stops[fill.next];
if (live) fill.next += 1;
- f.keeps = .{ .lane = lane, .s = s, .marks = held, .n = n_marks, .live = if (live) to else null, .last = last, .from = fill.from, .kept0 = fill.kept0 };
+ f.keeps = .{ .lane = lane, .s = s, .marks = held, .n = n_marks, .live = if (live) to else null };
if (!last or f.link != null) states.settle(f); // the other ranks take each keep in step order
if (!last) return false;
try hip.raw.copy(lane.streams, 0, out.streams.ptr + (rows - 1) * row_bytes, row_bytes, e.stream.handle);
@@ -500,3 +502,15 @@ pub const Fx = struct {
f.free(kv.value);
}
};
+
+test "Flash Next HIP offers its real prompt store to LaneHost only when reuse is enabled" {
+ var f: Fx = .{ .gpa = std.testing.allocator, .e = undefined, .streams = 1, .ones = undefined, .draft_ids = &.{}, .drafts = 0 };
+ try std.testing.expect(f.promptCache() == null);
+ f.store = pc.Store.init(f.gpa, .{ .ptr = &f, .vtable = &.{ .bytes = states.bytes, .save = states.save, .restore = states.restore, .drop = states.drop } }, .{ .lookahead = 1, .planned = true, .grid = 64 }, 1 << 20);
+ defer if (f.store) |*st| st.deinit();
+ const offered = f.promptCache().?;
+ if (f.store) |*st| try std.testing.expectEqual(st, offered) else return error.ExpectedPromptStore;
+ var saved: u8 = 0;
+ try std.testing.expectError(error.NoStream, states.save(&f, null, 64));
+ try std.testing.expectError(error.NoStream, states.restore(&f, null, &saved));
+}
diff --git a/zig/src/families/flashnext/hip/lanes_states.zig b/zig/src/families/flashnext/hip/lanes_states.zig
index 296f390aa00..627852c1cf1 100644
--- a/zig/src/families/flashnext/hip/lanes_states.zig
+++ b/zig/src/families/flashnext/hip/lanes_states.zig
@@ -10,16 +10,13 @@ const pc = @import("engine_api").prompt_cache;
const Fx = lanes.Fx;
const Lane = lanes.Lane;
-/// A prompt chunk's kept rows not saved yet: its marks, the row at its end, and the prompt's report after the last.
+/// A prompt chunk's kept rows not saved yet: its marks and the row at its end.
pub const Keeps = struct {
lane: *Lane,
s: *Stream,
marks: [cache.max_window]lanes.Marked,
n: usize,
live: ?usize,
- last: bool,
- from: usize,
- kept0: u64,
};
/// The keeps a prompt chunk left (Fx.keeps) saved, before any step that writes a stream's caches or window.
@@ -27,15 +24,13 @@ pub fn settle(f: *Fx) void {
const k = f.keeps orelse return;
f.keeps = null;
if (f.lanes.get(k.s) != k.lane) return; // its stream gone without a release: nothing to save from
- const st = if (f.store) |*st| st else return;
- const prompt = k.s.prompt();
+ const hook = k.s.reuse.hook orelse return;
for (k.marks[0..k.n]) |mk| {
f.marked = mk;
- _ = st.keep(prompt, @intCast(mk.at), k.lane, &.{}, &.{});
+ hook.at(hook.ptr, k.s, @intCast(mk.at));
}
f.marked = null; // a kept row at the chunk's end saves the live caches
- if (k.live) |at| _ = st.keep(prompt, @intCast(at), k.lane, &.{}, &.{});
- if (k.last) st.report(prompt.len, @intCast(k.from), st.counts.kept - k.kept0);
+ if (k.live) |at| hook.at(hook.ptr, k.s, @intCast(at));
}
pub fn bytes(ptr: *anyopaque, at: u32) u64 {
@@ -51,13 +46,17 @@ pub fn bytes(ptr: *anyopaque, at: u32) u64 {
}
pub fn save(ptr: *anyopaque, owner: ?*anyopaque, at: u32) anyerror!pc.Saved {
+ const stream: *Stream = @ptrCast(@alignCast(owner orelse return error.NoStream));
const f = Fx.of(ptr);
- const lane: *Lane = @ptrCast(@alignCast(owner orelse return error.NoOwner));
+ const lane = f.lanes.get(stream) orelse return error.UnknownStream;
const head = if (lane.head) |*h| h else null;
const saved = if (f.marked) |mk| if (mk.at == at)
try snapshot.saveMarked(f.gpa, f.copy(), f.e.stream, &lane.caches, head, at, f.e.cfg.index_ratio, mk.side, mk.history)
else
- return error.SnapshotNotAtMark else try snapshot.save(f.gpa, f.copy(), f.e.stream, &lane.caches, head, at, f.e.cfg.index_ratio);
+ return error.SnapshotNotAtMark else if ((if (lane.fill) |fill| fill.at else stream.prompt_len) != at)
+ return error.NotAtMark
+ else
+ try snapshot.save(f.gpa, f.copy(), f.e.stream, &lane.caches, head, at, f.e.cfg.index_ratio);
saved.slot = f.next_slot;
f.next_slot += 1;
if (f.link != null) try f.send(&.{ @backingInt(worker.Op.snap), lane.id, saved.slot, at });
@@ -66,8 +65,9 @@ pub fn save(ptr: *anyopaque, owner: ?*anyopaque, at: u32) anyerror!pc.Saved {
/// Every rank resumes from the state, or every rank starts the prompt over; a group that cannot do either stops.
pub fn restore(ptr: *anyopaque, owner: ?*anyopaque, saved: pc.Saved) anyerror!void {
+ const stream: *Stream = @ptrCast(@alignCast(owner orelse return error.NoStream));
const f = Fx.of(ptr);
- const lane: *Lane = @ptrCast(@alignCast(owner orelse return error.NoOwner));
+ const lane = f.lanes.get(stream) orelse return error.UnknownStream;
const s: *snapshot.Saved = @ptrCast(@alignCast(saved));
// a follower that got the step waits for every rank's word on it: a rank 0 that cannot send stops too
if (f.link != null) f.send(&.{ @backingInt(worker.Op.restore), lane.id, s.slot }) catch |err| {
diff --git a/zig/src/families/flashnext/hip/native.zig b/zig/src/families/flashnext/hip/native.zig
index 895f23a2405..7a40ec1a424 100644
--- a/zig/src/families/flashnext/hip/native.zig
+++ b/zig/src/families/flashnext/hip/native.zig
@@ -10,6 +10,7 @@ const Engine = @import("engine.zig").Engine;
const cache = @import("cache.zig");
const lanes_mod = @import("lanes.zig");
const worker = @import("worker.zig");
+const serve = @import("hip_serve");
pub const model_type = "qwen4_exp";
/// Most MTP drafts `--mtp-drafts` may ask of the head.
@@ -34,6 +35,7 @@ pub const Loaded = struct {
deinit: *const fn (*anyopaque) void,
streams: usize,
startup: []const u8,
+ offer: serve.Offer = .{},
};
pub const Refused = error{Refused};
@@ -310,6 +312,7 @@ pub fn open(
.deinit = Owned.release,
.streams = streams,
.startup = own.startup,
+ .offer = .{ .cache = own.fx.promptCache() },
};
}
diff --git a/zig/src/native/hip.zig b/zig/src/native/hip.zig
index 47d58449a2f..a23c1a12e06 100644
--- a/zig/src/native/hip.zig
+++ b/zig/src/native/hip.zig
@@ -378,11 +378,10 @@ test "a HIP family declares replies without reasoning with `pub const reasoning
}));
}
-test "the text families carry no offer, so the host gives them the empty one; GLM-OCR, Qwen3, Qwen3.5, dots.mocr and Parse offer through their Loaded" {
- inline for (.{ flashnext.native, nemotron.native }) |F| {
- const Loaded = @typeInfo(@typeInfo(@TypeOf(F.open)).@"fn".return_type.?).error_union.payload;
- try std.testing.expect(!@hasField(Loaded, "offer"));
- }
+test "text-only Nemotron has no offer; Flash Next, GLM-OCR, Qwen3, Qwen3.5, dots.mocr and Parse offer through Loaded" {
+ const NemotronLoaded = @typeInfo(@typeInfo(@TypeOf(nemotron.native.open)).@"fn".return_type.?).error_union.payload;
+ try std.testing.expect(!@hasField(NemotronLoaded, "offer"));
+ try std.testing.expect(@FieldType(flashnext.native.Loaded, "offer") == serve.Offer);
try std.testing.expect(@FieldType(glm_ocr.native.Loaded, "offer") == serve.Offer);
inline for (.{ "vision", "cache", "cache_capacity" }) |old| try std.testing.expect(!@hasField(glm_ocr.native.Loaded, old));
try std.testing.expect(@FieldType(qwen3.native.Loaded, "offer") == serve.Offer);
From 91f2cee9e10cf8dd1c0cc603c7063cacee9ade1e Mon Sep 17 00:00:00 2001
From: ashhart <71890694+ashhart@users.noreply.github.com>
Date: Fri, 20 Nov 2026 12:33:58 +0000
Subject: [PATCH 30/32] CUDA: preserve planned proposal routing through
LaneHost
---
zig/build/cuda.zig | 1 +
zig/src/native/cuda.zig | 21 +++++++++++++++++-
zig/src/native/cuda_bound.zig | 40 +++++++++++++++++++++++++++++++++++
3 files changed, 61 insertions(+), 1 deletion(-)
diff --git a/zig/build/cuda.zig b/zig/build/cuda.zig
index 73fb128cd4d..c95636e7517 100644
--- a/zig/build/cuda.zig
+++ b/zig/build/cuda.zig
@@ -313,6 +313,7 @@ pub fn hostTests(b: *std.Build, draft_ids: *std.Build.Module, build_options: *st
const native = native_modules.engines;
b.step("test-cuda-cache-budget-host", "CUDA cache defaults after stream sizing without devices").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = native, .filters = &.{"CUDA cache default"} })).step);
b.step("test-draft-cuda-host", "CUDA draft source metadata without devices").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = native, .filters = &.{"draft sources:"} })).step);
+ b.step("test-cuda-proposal-host", "CUDA planned-proposal forwarding without devices").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = native, .filters = &.{ "CUDA host preserves the calibrated proposal service identity", "each forwarded entry calls the family's entry of the same name, once" } })).step);
@import("cuda_family_host.zig").registerCopyFamilies(b, native, step);
const copies = b.step("test-nemotron-copies-host", "Nemotron CUDA copy gates and plain equality without devices");
for ([_]std.builtin.OptimizeMode{ .debug, .fast }) |mode| {
diff --git a/zig/src/native/cuda.zig b/zig/src/native/cuda.zig
index ff5c296e854..85007990d9d 100644
--- a/zig/src/native/cuda.zig
+++ b/zig/src/native/cuda.zig
@@ -153,7 +153,15 @@ pub const Host = struct {
/// The family's backend, each call made with the context current on the calling thread.
fn backend(h: *Host) lanes.backend.Backend {
h.vtable = lane_backend.vtable(Host, h.inner.vtable.*);
- return .{ .ptr = h, .round_observer = h.inner.round_observer, .vtable = &h.vtable, .first_before_draft = h.inner.first_before_draft, .penalties = h.inner.penalties, .chunk_invariant = h.inner.chunk_invariant };
+ return .{
+ .proposal_head = h.inner.proposal_head,
+ .ptr = h,
+ .round_observer = h.inner.round_observer,
+ .vtable = &h.vtable,
+ .first_before_draft = h.inner.first_before_draft,
+ .penalties = h.inner.penalties,
+ .chunk_invariant = h.inner.chunk_invariant,
+ };
}
};
const refusals = @import("cuda_refusal.zig");
@@ -534,6 +542,17 @@ test "CUDA host preserves prefill_step, first-before-draft and chunk-invariance
try std.testing.expect(!h.backend().chunk_invariant);
}
+test "draft sources: CUDA host preserves the calibrated proposal service identity" {
+ var target: lanes.fake.Fake = .{ .gpa = std.testing.allocator };
+ defer target.deinit();
+ var service: lanes.proposal_head.Service = undefined;
+ var h: Host = undefined;
+ h.inner = target.backend();
+ h.inner.proposal_head = &service;
+ try std.testing.expectEqual(&service, h.backend().proposal_head.?);
+ try std.testing.expect(h.backend().vtable.proposal_draft == null); // legacy stays legacy until planned callbacks exist
+}
+
test "a cancel during a long prompt stops it, and the next request's reply is unchanged (#291)" {
try @import("cuda_prompt_cancel_test.zig").check(Host, Host.serve);
}
diff --git a/zig/src/native/cuda_bound.zig b/zig/src/native/cuda_bound.zig
index e258af87c97..6dd6a6bbffc 100644
--- a/zig/src/native/cuda_bound.zig
+++ b/zig/src/native/cuda_bound.zig
@@ -79,6 +79,24 @@ pub fn vtable(comptime H: type, v: be.Backend.VTable) be.Backend.VTable {
return x.inner.vtable.draft(x.inner.ptr, r);
}
}.f,
+ .draft_capacity = if (v.draft_capacity != null) struct {
+ fn f(p: *anyopaque, s: *lanes.Stream) u32 {
+ const x = H.bind(p);
+ return x.inner.vtable.draft_capacity.?(x.inner.ptr, s);
+ }
+ }.f else null,
+ .proposal_draft = if (v.proposal_draft != null) struct {
+ fn f(p: *anyopaque, r: []const be.DraftRequest) anyerror!void {
+ const x = H.bind(p);
+ return x.inner.vtable.proposal_draft.?(x.inner.ptr, r);
+ }
+ }.f else null,
+ .clear_proposals = if (v.clear_proposals != null) struct {
+ fn f(p: *anyopaque, s: *lanes.Stream) void {
+ const x = H.bind(p);
+ x.inner.vtable.clear_proposals.?(x.inner.ptr, s);
+ }
+ }.f else null,
.unspeculate = if (v.unspeculate != null) struct {
fn f(p: *anyopaque, s: *lanes.Stream) anyerror!void {
const x = H.bind(p);
@@ -245,6 +263,22 @@ test "each forwarded entry calls the family's entry of the same name, once" {
Rec.hit(p, "draft");
}
}.f,
+ .draft_capacity = struct {
+ fn f(p: *anyopaque, _: *S) u32 {
+ Rec.hit(p, "draft_capacity");
+ return 5;
+ }
+ }.f,
+ .proposal_draft = struct {
+ fn f(p: *anyopaque, _: []const be.DraftRequest) anyerror!void {
+ Rec.hit(p, "proposal_draft");
+ }
+ }.f,
+ .clear_proposals = struct {
+ fn f(p: *anyopaque, _: *S) void {
+ Rec.hit(p, "clear_proposals");
+ }
+ }.f,
.unspeculate = struct {
fn f(p: *anyopaque, _: *S) anyerror!void {
Rec.hit(p, "unspeculate");
@@ -348,6 +382,12 @@ test "each forwarded entry calls the family's entry of the same name, once" {
try rec.once("keep");
try w.draft(p, &.{});
try rec.once("draft");
+ try std.testing.expectEqual(@as(u32, 5), w.draft_capacity.?(p, &s));
+ try rec.once("draft_capacity");
+ try w.proposal_draft.?(p, &.{});
+ try rec.once("proposal_draft");
+ w.clear_proposals.?(p, &s);
+ try rec.once("clear_proposals");
try w.unspeculate.?(p, &s);
try rec.once("unspeculate");
_ = try w.probabilities.?(p, &s, &probs);
From 1f0e5cd56b0c2385f618a105091a244bfe911437 Mon Sep 17 00:00:00 2001
From: ashhart <71890694+ashhart@users.noreply.github.com>
Date: Sat, 21 Nov 2026 13:05:55 +0000
Subject: [PATCH 31/32] adapt: keep Gemma CUDA backend and CUDA host within 600
lines
Moves the greedy-pick test to its own file and restores the one-line backend literal. No runtime change.
---
zig/src/families/gemma4/cuda_backend.zig | 25 ++++----------------
zig/src/families/gemma4/cuda_greedy_test.zig | 23 ++++++++++++++++++
zig/src/native/cuda.zig | 10 +-------
3 files changed, 29 insertions(+), 29 deletions(-)
create mode 100644 zig/src/families/gemma4/cuda_greedy_test.zig
diff --git a/zig/src/families/gemma4/cuda_backend.zig b/zig/src/families/gemma4/cuda_backend.zig
index 2f6225f28ac..faceef9dcbf 100644
--- a/zig/src/families/gemma4/cuda_backend.zig
+++ b/zig/src/families/gemma4/cuda_backend.zig
@@ -558,7 +558,7 @@ pub const Gemma = struct {
};
/// tf_round_bf16_argmax's pick among `mask`'s allowed tokens: the first largest; a non-finite logit is an error.
-fn pickAllowed(row: []const u16, mask: []const u32) !u32 {
+pub fn pickAllowed(row: []const u16, mask: []const u32) !u32 {
var best: f32 = 0;
var id: ?u32 = null;
for (row, 0..) |bits, t| {
@@ -573,25 +573,6 @@ fn pickAllowed(row: []const u16, mask: []const u32) !u32 {
return id orelse error.InvalidGrammarMasks;
}
-test "a greedy pick under a grammar: the first largest allowed token, refusals by name" {
- const bf = struct {
- fn of(f: f32) u16 {
- return @intCast(@as(u32, @bitCast(f)) >> 16);
- }
- }.of;
- var row: [64]u16 = @splat(bf(0.5));
- row[3] = bf(9);
- row[40] = bf(2);
- row[41] = bf(2);
- var mask = [2]u32{ 0, (1 << 8) | (1 << 9) }; // tokens 40 and 41
- try std.testing.expectEqual(@as(u32, 40), try pickAllowed(&row, &mask));
- mask[0] = 1 << 3;
- try std.testing.expectEqual(@as(u32, 3), try pickAllowed(&row, &mask));
- try std.testing.expectError(error.InvalidGrammarMasks, pickAllowed(&row, &.{ 0, 0 }));
- row[10] = 0xFF80; // -inf, even where the grammar refuses it
- try std.testing.expectError(error.NonFiniteLogits, pickAllowed(&row, &mask));
-}
-
test "zero grant and shared head costs: Gemma CUDA assistant and DFlash keep tokens and costed copy grants" {
var m: fwd.Model = undefined;
m.slots = 16;
@@ -602,3 +583,7 @@ test "zero grant and shared head costs: Gemma CUDA assistant and DFlash keep tok
try lanes.shared_draft_check.check(b.facts(), true);
try @import("cuda_head_cost_test.zig").check(b.facts());
}
+
+test {
+ _ = @import("cuda_greedy_test.zig");
+}
diff --git a/zig/src/families/gemma4/cuda_greedy_test.zig b/zig/src/families/gemma4/cuda_greedy_test.zig
new file mode 100644
index 00000000000..2d0b8306eff
--- /dev/null
+++ b/zig/src/families/gemma4/cuda_greedy_test.zig
@@ -0,0 +1,23 @@
+//! Host checks for Gemma CUDA grammar-constrained greedy selection.
+const std = @import("std");
+const backend = @import("cuda_backend.zig");
+const pickAllowed = backend.pickAllowed;
+
+test "a greedy pick under a grammar: the first largest allowed token, refusals by name" {
+ const bf = struct {
+ fn of(f: f32) u16 {
+ return @intCast(@as(u32, @bitCast(f)) >> 16);
+ }
+ }.of;
+ var row: [64]u16 = @splat(bf(0.5));
+ row[3] = bf(9);
+ row[40] = bf(2);
+ row[41] = bf(2);
+ var mask = [2]u32{ 0, (1 << 8) | (1 << 9) }; // tokens 40 and 41
+ try std.testing.expectEqual(@as(u32, 40), try pickAllowed(&row, &mask));
+ mask[0] = 1 << 3;
+ try std.testing.expectEqual(@as(u32, 3), try pickAllowed(&row, &mask));
+ try std.testing.expectError(error.InvalidGrammarMasks, pickAllowed(&row, &.{ 0, 0 }));
+ row[10] = 0xFF80; // -inf, even where the grammar refuses it
+ try std.testing.expectError(error.NonFiniteLogits, pickAllowed(&row, &mask));
+}
diff --git a/zig/src/native/cuda.zig b/zig/src/native/cuda.zig
index 85007990d9d..f2ca2ade63e 100644
--- a/zig/src/native/cuda.zig
+++ b/zig/src/native/cuda.zig
@@ -153,15 +153,7 @@ pub const Host = struct {
/// The family's backend, each call made with the context current on the calling thread.
fn backend(h: *Host) lanes.backend.Backend {
h.vtable = lane_backend.vtable(Host, h.inner.vtable.*);
- return .{
- .proposal_head = h.inner.proposal_head,
- .ptr = h,
- .round_observer = h.inner.round_observer,
- .vtable = &h.vtable,
- .first_before_draft = h.inner.first_before_draft,
- .penalties = h.inner.penalties,
- .chunk_invariant = h.inner.chunk_invariant,
- };
+ return .{ .proposal_head = h.inner.proposal_head, .ptr = h, .round_observer = h.inner.round_observer, .vtable = &h.vtable, .first_before_draft = h.inner.first_before_draft, .penalties = h.inner.penalties, .chunk_invariant = h.inner.chunk_invariant };
}
};
const refusals = @import("cuda_refusal.zig");
From b209e87727d4011a959ea013b3437821578afbef Mon Sep 17 00:00:00 2001
From: ashhart <71890694+ashhart@users.noreply.github.com>
Date: Sat, 21 Nov 2026 17:53:16 +0000
Subject: [PATCH 32/32] adapt: keep LFM2-MoE CUDA backend and CUDA host within
600 lines
---
zig/src/families/lfm2_moe/cuda_backend.zig | 7 -------
zig/src/families/lfm2_moe/cuda_prefill_test.zig | 7 +++++++
zig/src/native/cuda.zig | 3 +--
3 files changed, 8 insertions(+), 9 deletions(-)
diff --git a/zig/src/families/lfm2_moe/cuda_backend.zig b/zig/src/families/lfm2_moe/cuda_backend.zig
index 70d4a857e13..4a9157d4fb4 100644
--- a/zig/src/families/lfm2_moe/cuda_backend.zig
+++ b/zig/src/families/lfm2_moe/cuda_backend.zig
@@ -494,13 +494,6 @@ pub const Lfm = struct {
}
};
-test "a request holds its prompt, its reply and one verify window in whole pages" {
- try std.testing.expectEqual(@as(usize, 1), pagesFor(1, 1));
- try std.testing.expectEqual(@as(usize, 1), pagesFor(400, 96));
- try std.testing.expectEqual(@as(usize, 2), pagesFor(400, 97));
- try std.testing.expectEqual(@as(usize, 65), pagesFor(32768, 0));
-}
-
test "a chunk taps marks and message starts, up to four, then ends at the next, the grid line or the prompt's end" {
const cases = [_]struct { at: usize, len: usize, marks: []const u32, chunks: []const u32, end: usize, taps: []const usize }{
.{ .at = 0, .len = 3000, .marks = &.{}, .chunks = &.{}, .end = prompt_rows, .taps = &.{} },
diff --git a/zig/src/families/lfm2_moe/cuda_prefill_test.zig b/zig/src/families/lfm2_moe/cuda_prefill_test.zig
index 1a2f40d6719..c0d8e985cf3 100644
--- a/zig/src/families/lfm2_moe/cuda_prefill_test.zig
+++ b/zig/src/families/lfm2_moe/cuda_prefill_test.zig
@@ -20,3 +20,10 @@ test "lfm2 moe prefill: cancellation keeps a completed prefix for exact resume"
try std.testing.expectError(error.Cancelled, backend.Lfm.cancelledPrefix(&s, 2));
try std.testing.expectEqual(@as(u32, 2), stored.at);
}
+
+test "a request holds its prompt, its reply and one verify window in whole pages" {
+ try std.testing.expectEqual(@as(usize, 1), backend.pagesFor(1, 1));
+ try std.testing.expectEqual(@as(usize, 1), backend.pagesFor(400, 96));
+ try std.testing.expectEqual(@as(usize, 2), backend.pagesFor(400, 97));
+ try std.testing.expectEqual(@as(usize, 65), backend.pagesFor(32768, 0));
+}
diff --git a/zig/src/native/cuda.zig b/zig/src/native/cuda.zig
index f2ca2ade63e..dbcd3d4c95a 100644
--- a/zig/src/native/cuda.zig
+++ b/zig/src/native/cuda.zig
@@ -541,8 +541,7 @@ test "draft sources: CUDA host preserves the calibrated proposal service identit
var h: Host = undefined;
h.inner = target.backend();
h.inner.proposal_head = &service;
- try std.testing.expectEqual(&service, h.backend().proposal_head.?);
- try std.testing.expect(h.backend().vtable.proposal_draft == null); // legacy stays legacy until planned callbacks exist
+ try std.testing.expect(h.backend().proposal_head.? == &service and h.backend().vtable.proposal_draft == null); // legacy stays legacy until planned callbacks exist
}
test "a cancel during a long prompt stops it, and the next request's reply is unchanged (#291)" {