Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
15 commits
Select commit Hold shift + click to select a range
9f0d4c7
XPU backend: Qwen3.8-27B on Intel Arc Pro B70 (Xe2) over Level Zero
Mirrdhyn Oct 14, 2026
25ef56c
XPU: drop the Triton SPIR-V; streams sized from the device's free mem…
Mirrdhyn Oct 14, 2026
ba9193f
Add the Intel GPU (Level Zero) runtime and Nemotron 3.5 Lightning on …
BHCC2025 Oct 8, 2026
f8da783
Arc recipe: decode figures of the earlier decode attention measured o…
BHCC2025 Oct 9, 2026
0fdb2be
Arc recipe: prompt attention before and after measured with the CLI o…
BHCC2025 Oct 9, 2026
eb9a960
Arc: remove the debug and path switches, one admission rule, one-line…
BHCC2025 Oct 10, 2026
c936acf
xpu: Nemotron on the XPU backend's Level Zero table (ze.zig), not a s…
BHCC2025 Oct 15, 2026
5dc655b
xpu nemotron: windows take the decode step's arithmetic, a one-row wi…
BHCC2025 Oct 15, 2026
cd41379
xpu nemotron: prompt rows take the decode step's arithmetic, so a pro…
BHCC2025 Oct 15, 2026
ebb49f1
Nemotron on Intel Arc in the XPU server, beside Qwen3.8-27B
BHCC2025 Oct 15, 2026
d8b996c
xpu server: Nemotron's MTP head and copy drafts through the lane core…
BHCC2025 Oct 14, 2026
8aa5fc3
xpu server: a one-row round is the decode step itself
BHCC2025 Oct 15, 2026
9ec1385
xpu server: concurrent requests share rounds, each stream on its own …
BHCC2025 Oct 14, 2026
5375580
xpu server: the prompt cache, a resumed turn equal to a fresh prompt
BHCC2025 Oct 15, 2026
9674eb6
Arc recipe: drafts, concurrent streams and the prompt cache through t…
BHCC2025 Oct 15, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
xpu server: the prompt cache, a resumed turn equal to a fresh prompt
With sequences (drafted windows) the Arc host keeps prompt states: the server plans 512-row prompt chunks, the prompt pass
cuts there and calls the cache at its marks, and a stream whose prompt starts with a kept state's tokens restores it and
prefills from there. A state is the sequence's Mamba states and its KV rows (and the head's) below the mark, copied on the
device (Runtime.copy). The cache's rules: planned (resume and keep at chunk starts only, as a prompt piece's rows choose its
kernels) and lookahead 1 (the head absorbs row at-1 with token at). Budget: --prompt-cache-gib, else 4 GiB within the device
memory left past 2 GiB (Sysman,
ze.Gpu.memory). tools/zig/xpu_resume_receipt.py runs a two-turn chat over a long document for the comparison.
  • Loading branch information
BHCC2025 committed Oct 15, 2026
commit 537558084b00e67f16ccf04dbe562dd92a3041b6
40 changes: 40 additions & 0 deletions tools/zig/xpu_resume_receipt.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
#!/usr/bin/env python3
"""Two turns over a long document (turn 2 resumes turn 1's prompt): token_sha and cached tokens of each, as JSON."""
# usage: xpu_resume_receipt.py BASE_URL MODEL DOC_FILE [--chars N] [--tokens N]; compare with --prompt-cache-gib 0
import argparse
import json
import urllib.request

SAMPLINGS = {"greedy": {"temperature": 0}, "seeded": {"temperature": 0.8, "top_p": 0.95, "seed": 11}}


def ask(base, model, messages, tokens, extra):
body = {"model": model, "messages": messages, "max_tokens": tokens, "chat_template_kwargs": {"enable_thinking": False}, **extra}
req = urllib.request.Request(base + "/v1/chat/completions", json.dumps(body).encode(), {"content-type": "application/json"})
with urllib.request.urlopen(req, timeout=1800) as r:
out = json.load(r)
details = out["usage"].get("prompt_tokens_details") or {}
return (out["choices"][0]["message"]["content"], out["tensorfold"]["token_sha"], out["usage"]["prompt_tokens"],
details.get("cached_tokens", 0), out["tensorfold"].get("prefill_seconds"))


def main():
ap = argparse.ArgumentParser()
ap.add_argument("base")
ap.add_argument("model")
ap.add_argument("doc")
ap.add_argument("--chars", type=int, default=26000)
ap.add_argument("--tokens", type=int, default=96)
a = ap.parse_args()
doc = open(a.doc).read()[: a.chars]
for name, s in SAMPLINGS.items():
m1 = [{"role": "user", "content": f"Here is a document:\n\n{doc}\n\nIn two sentences, what is it about?"}]
r1 = ask(a.base, a.model, m1, a.tokens, s)
m2 = m1 + [{"role": "assistant", "content": r1[0]}, {"role": "user", "content": "List three numbers the document reports, with what each measures."}]
r2 = ask(a.base, a.model, m2, a.tokens, s)
print(json.dumps({"sampling": name, "turn1": {"sha": r1[1], "prompt": r1[2], "cached": r1[3], "prefill_s": r1[4]},
"turn2": {"sha": r2[1], "prompt": r2[2], "cached": r2[3], "prefill_s": r2[4]}}), flush=True)


if __name__ == "__main__":
main()
114 changes: 111 additions & 3 deletions zig/src/families/nemotron/xpu_engine.zig
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,12 @@ pub const Seq = struct {
win: [4]u32 = .{ 0, 1, 0, 0 }, // the window record: rows, inplace, pos0, head_rows
};

/// A sequence after `at` prompt tokens (the prompt cache's copy): Mamba states, KV rows [0, at), the head's too.
pub const Snap = struct { at: u32, cstate: []xpu.rt.Buffer, sstate: []xpu.rt.Buffer, kc: []xpu.rt.Buffer, vc: []xpu.rt.Buffer, hkc: ?xpu.rt.Buffer, hvc: ?xpu.rt.Buffer };

pub const Engine = struct {
pub const Sequence = Seq;
pub const Snapshot = Snap;
gpa: std.mem.Allocator,
ctx: *const xpu.Context,
stream: xpu.Stream,
Expand Down Expand Up @@ -265,13 +269,19 @@ pub const Engine = struct {

/// The prompt in windows of `rows`, in place; the head absorbs all rows but the last (last_h, for draftFirst).
pub fn prefillHead(e: *Engine, prompt: []const u32, rows: u32) !void {
try e.prefillSpan(prompt, 0, prompt.len, rows);
}

/// Prompt tokens [from, to) at m.pos == from, in windows of `rows`; the head absorbs as prefillHead does.
pub fn prefillSpan(e: *Engine, prompt: []const u32, from: usize, to: usize, rows: u32) !void {
const mt = &e.head.?;
if (e.m.pos != from) return error.PositionMismatch;
e.w.ms = e.big_ms; // prompt windows (in place) take the shared scratch; the sequence's own is for verify windows
defer e.w.ms = e.cur.ms;
var t: usize = 0;
while (t < prompt.len) {
var t: usize = from;
while (t < to) {
try nw.stopCheck(&e.r);
const n = @min(rows, prompt.len - t);
const n = @min(rows, to - t);
const last = t + n == prompt.len;
try e.w.forward(&e.m, prompt[t .. t + n], true, if (last) 1 else 0);
const absorb = if (last) n - 1 else n;
Expand All @@ -286,6 +296,104 @@ pub const Engine = struct {
}
}

/// Device bytes a snapshot after `at` prompt tokens takes.
pub fn snapBytes(e: *const Engine, at: u32) u64 {
const c = e.cfg;
const conv = (c.conv_kernel - 1) * c.convDim() * 2;
const ssm = @as(u64, c.mamba_num_heads) * c.mamba_head_dim * c.ssm_state_size * 4;
const row = @as(u64, c.num_key_value_heads) * c.head_dim * 2;
const kvs = e.own.kc.len + @as(u64, @intFromBool(e.head != null));
return e.own.cstate.len * (conv + ssm) + 2 * kvs * at * row;
}

/// The bound sequence after `at` prompt tokens (no window pending) copied into new storage.
pub fn snapSave(e: *Engine, at: u32) !*Snap {
if (e.m.pos != at) return error.SnapshotOutOfStep;
const c = e.cfg;
const conv = (c.conv_kernel - 1) * c.convDim() * 2;
const ssm = @as(usize, c.mamba_num_heads) * c.mamba_head_dim * c.ssm_state_size * 4;
const kvb = @as(usize, at) * c.num_key_value_heads * c.head_dim * 2;
const s = try e.gpa.create(Snap);
const nm = e.own.cstate.len;
const na = e.own.kc.len;
s.* = .{ .at = at, .cstate = try e.gpa.alloc(xpu.rt.Buffer, nm), .sstate = try e.gpa.alloc(xpu.rt.Buffer, nm), .kc = try e.gpa.alloc(xpu.rt.Buffer, na), .vc = try e.gpa.alloc(xpu.rt.Buffer, na), .hkc = null, .hvc = null };
var mi: usize = 0;
var ai: usize = 0;
for (e.m.layers) |ly| switch (ly.mixer) {
.mamba => |mw| {
s.cstate[mi] = try e.r.alloc(conv);
s.sstate[mi] = try e.r.alloc(ssm);
try e.r.copy(s.cstate[mi], mw.cstate, conv);
try e.r.copy(s.sstate[mi], mw.sstate, ssm);
mi += 1;
},
.attention => |aw| {
s.kc[ai] = try e.r.alloc(@max(kvb, 4));
s.vc[ai] = try e.r.alloc(@max(kvb, 4));
if (kvb > 0) try e.r.copy(s.kc[ai], aw.kc, kvb);
if (kvb > 0) try e.r.copy(s.vc[ai], aw.vc, kvb);
ai += 1;
},
else => {},
};
if (e.head) |h| {
s.hkc = try e.r.alloc(@max(kvb, 4));
s.hvc = try e.r.alloc(@max(kvb, 4));
if (kvb > 0) try e.r.copy(s.hkc.?, h.attn.kc, kvb);
if (kvb > 0) try e.r.copy(s.hvc.?, h.attn.vc, kvb);
}
try e.r.sync();
return s;
}

/// The bound sequence becomes the snapshot's: states and KV rows [0, at) copied in, m.pos = at.
pub fn snapRestore(e: *Engine, s: *const Snap) !void {
const c = e.cfg;
const conv = (c.conv_kernel - 1) * c.convDim() * 2;
const ssm = @as(usize, c.mamba_num_heads) * c.mamba_head_dim * c.ssm_state_size * 4;
const kvb = @as(usize, s.at) * c.num_key_value_heads * c.head_dim * 2;
var mi: usize = 0;
var ai: usize = 0;
for (e.m.layers) |ly| switch (ly.mixer) {
.mamba => |mw| {
try e.r.copy(mw.cstate, s.cstate[mi], conv);
try e.r.copy(mw.sstate, s.sstate[mi], ssm);
mi += 1;
},
.attention => |aw| {
if (kvb > 0) try e.r.copy(aw.kc, s.kc[ai], kvb);
if (kvb > 0) try e.r.copy(aw.vc, s.vc[ai], kvb);
ai += 1;
},
else => {},
};
if (e.head) |h| if (kvb > 0) {
try e.r.copy(h.attn.kc, s.hkc.?, kvb);
try e.r.copy(h.attn.vc, s.hvc.?, kvb);
};
try e.r.sync();
e.m.pos = s.at;
}

pub fn snapDrop(e: *Engine, s: *Snap) void {
e.r.sync() catch {};
for (s.cstate, s.sstate) |*a, *b| {
a.free();
b.free();
}
for (s.kc, s.vc) |*a, *b| {
a.free();
b.free();
}
if (s.hkc) |*b| b.free();
if (s.hvc) |*b| b.free();
e.gpa.free(s.cstate);
e.gpa.free(s.sstate);
e.gpa.free(s.kc);
e.gpa.free(s.vc);
e.gpa.destroy(s);
}

/// One window of ids at m.pos, not committed; every row gets logits (rowTokens / rowLogits).
pub fn verifyRows(e: *Engine, ids: []const u32) !void {
try nw.stopCheck(&e.r);
Expand Down
64 changes: 62 additions & 2 deletions zig/src/native/xpu_lane.zig
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
//! The Intel GPU engines as a lane backend: one sequence, host sampling; with an MTP head, drafted windows (16 rows).
const std = @import("std");
const lanes = @import("lanes");
const api = @import("engine_api");

const be = lanes.backend;

Expand Down Expand Up @@ -213,8 +214,7 @@ pub fn Xpu(comptime S: type) type {
} };
if (own) self.own_free = false;
e.bind(gop.value_ptr.seq);
try e.reset();
try e.prefillHead(ids, S.promptRows(e));
try self.prefillPlanned(s, ids);
if (s.isCancelled()) return error.Cancelled;
var first: [1]u32 = undefined;
try self.drawRows(1, s.sampling, &.{ids.len}, &first);
Expand All @@ -239,6 +239,66 @@ pub fn Xpu(comptime S: type) type {
_ = self.take(try self.step(ids[ids.len - 1], s.sampling, ids.len));
}

/// A bound sequence's prompt pass: from a kept state if the cache has one, planned chunks, the cache's marks.
fn prefillPlanned(self: *Self, s: *lanes.Stream, ids: []const u32) !void {
if (comptime !has_head) unreachable;
const e = self.e;
const rows = S.promptRows(e);
s.cached = 0;
var at: u32 = 0;
if (s.reuse.saved) |saved| {
const snap: *S.Engine.Snapshot = @ptrCast(@alignCast(saved));
if (snap.at < ids.len) {
try e.snapRestore(snap);
at = snap.at;
s.cached = at;
} else s.reuse_failed = true;
}
if (at == 0) try e.reset();
var next: usize = 0;
while (at < ids.len) {
if (s.isCancelled()) return error.Cancelled;
if (self.stopped()) return error.ShuttingDown;
while (next < s.chunks.len and s.chunks[next] <= at) next += 1;
const end: u32 = if (next < s.chunks.len) s.chunks[next] else @intCast(ids.len);
const n = @min(end - at, rows);
try e.prefillSpan(ids, at, at + n, rows);
at += n;
if (std.mem.indexOfScalar(u32, s.reuse.marks, at) != null) if (s.reuse.hook) |k| k.at(k.ptr, s, at);
}
}

// -- the prompt cache's Snapshots: a stream's sequence at a prompt chunk end ---------------------------------

pub fn snapshots(self: *Self) api.prompt_cache.Snapshots {
return .{ .ptr = self, .vtable = &.{ .bytes = snapBytes, .save = snapSave, .restore = snapRestore, .drop = snapDrop } };
}

fn snapBytes(ptr: *anyopaque, at: u32) u64 {
if (comptime !has_head) return 0;
return of(ptr).e.snapBytes(at);
}

fn snapSave(ptr: *anyopaque, owner: ?*anyopaque, at: u32) anyerror!*anyopaque {
if (comptime !has_head) return error.NoSnapshots;
const self = of(ptr);
const l = try self.bound(@ptrCast(@alignCast(owner orelse return error.NoStream)));
if (l.pending != null) return error.SnapshotOutOfStep;
return try self.e.snapSave(at);
}

fn snapRestore(ptr: *anyopaque, owner: ?*anyopaque, saved: *anyopaque) anyerror!void {
if (comptime !has_head) return error.NoSnapshots;
const self = of(ptr);
_ = try self.bound(@ptrCast(@alignCast(owner orelse return error.NoStream)));
try self.e.snapRestore(@ptrCast(@alignCast(saved)));
}

fn snapDrop(ptr: *anyopaque, saved: *anyopaque) void {
if (comptime !has_head) return;
of(ptr).e.snapDrop(@ptrCast(@alignCast(saved)));
}

fn firstFn(ptr: *anyopaque, s: *lanes.Stream, position: u64) anyerror!u64 {
const self = of(ptr);
if (position != s.prompt_len) return error.PositionMismatch;
Expand Down
20 changes: 19 additions & 1 deletion zig/src/native/xpu_nem.zig
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,12 @@ fn readMemory(_: ?*anyopaque, reset_peak: bool) ?api.Memory {
return m;
}

/// Device memory left: Sysman's free bytes (ze.Gpu.memory), at most the card's size less what this engine allocated.
fn freeMemory(ctx: *xpu.Context) u64 {
const mem = ctx.gpu.memory() catch return 0;
return @min(mem.free, mem.size -| xpu.rt.alloc_now);
}

/// One loaded model behind the lane host: the device, the engine, the lane backend and the round loop.
fn Host(comptime S: type) type {
return struct {
Expand All @@ -67,10 +73,12 @@ fn Host(comptime S: type) type {
core: lanes.Engine,
host: api.LaneHost,
startup: []u8 = &.{},
cache: ?api.prompt_cache.Store = null,

fn close(p: *anyopaque) void {
const h: *Self = @ptrCast(@alignCast(p));
h.host.stop();
if (h.cache) |*store| store.deinit();
h.core.deinit();
h.cfg.deinit(h.gpa);
h.backend.deinit();
Expand Down Expand Up @@ -139,7 +147,17 @@ fn openFamily(comptime S: type, a: Allocator, gpa: Allocator, io: std.Io, o: api
h.core = lanes.Engine.init(gpa, &h.cfg, h.backend.backend(), h.clock.clock());
const note = try S.note(a, h.engine);
h.startup = try std.fmt.allocPrint(gpa, "Intel GPU engine: {s}, {d:.2} GB on the device, context {d}{s}; {d} stream(s) a round on the lane core, sampling on the host", .{ h.ctx.name(), @as(f64, @floatFromInt(xpu.rt.alloc_now)) / 1e9, window, note, h.backend.streams });
h.host = api.LaneHost.init(gpa, io, &h.core, .{ .name = S.name, .lanes = h.backend.streams, .context_window = @intCast(window), .context_fitted = true, .startup = h.startup });
const drafted = facts.exact_width > 1;
h.host = api.LaneHost.init(gpa, io, &h.core, .{ .name = S.name, .lanes = h.backend.streams, .context_window = @intCast(window), .context_fitted = true, .startup = h.startup, .prefill_step = if (drafted) S.promptRows(h.engine) else 0 });
// kept prompt states (with sequences): --prompt-cache-gib, else 4 GiB, inside the device memory left past 2 GiB
const want: u64 = @intFromFloat((o.prompt_cache_gib orelse 4) * (1 << 30));
const free = freeMemory(&h.ctx);
const budget: u64 = if (free > 2 << 30) @min(want, free - (2 << 30)) else 0;
h.cache = null;
if (drafted and budget > 0) {
h.cache = api.prompt_cache.Store.init(gpa, h.backend.snapshots(), .{ .lookahead = 1, .planned = true }, budget);
h.host.cache = &h.cache.?;
}
h.host.memory = .{ .read = readMemory };
h.host.explain = .{ .text = lane.explain };
try h.host.start();
Expand Down
5 changes: 5 additions & 0 deletions zig/src/xpu/rt.zig
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,11 @@ pub const Runtime = struct {
try self.drv.check(self.drv.api.zeCommandListAppendMemoryCopy(self.list, dst.ptr, src.ptr, dst.len, null, 0, null), "download");
}

/// Device to device: the first `bytes` of src into dst, queued in order with the kernels.
pub fn copy(self: *Runtime, dst: Buffer, src: Buffer, bytes: usize) Error!void {
try self.drv.check(self.drv.api.zeCommandListAppendMemoryCopy(self.list, dst.ptr, src.ptr, bytes, null, 0, null), "copy");
}

pub fn sync(self: *Runtime) Error!void {
try self.drv.check(self.drv.api.zeCommandListHostSynchronize(self.list, std.math.maxInt(u64)), "sync");
}
Expand Down