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: Nemotron's MTP head and copy drafts through the lane core…
…, drafted == "draft": false

With the head loaded (mtp-4bit.safetensors present, drafts not turned off) the Arc lane host serves windows of up to
16 rows: verify runs the pending token and its drafts as one window, keep commits the path, and draft absorbs the kept
rows into the head and holds its chain. Every round is a window, so a reply with drafts off takes the same arithmetic
(the windows equal one-row windows, nem_rows). The prompt runs in 512-row windows and the head absorbs every row but
the last, 16 rows a step. Window costs (1 to 16 rows) and a head step are timed at load for the depth rule.
--no-drafts (or TENSORFOLD_XPU_MTP=0) leaves the head unloaded and keeps the one-row decode path.
tools/zig/xpu_draft_receipt.py checks drafted against "draft": false through the server.
  • Loading branch information
BHCC2025 committed Oct 15, 2026
commit d8b996c3d82449b5086acd089e2bfcecc7e63203
58 changes: 58 additions & 0 deletions tools/zig/xpu_draft_receipt.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
#!/usr/bin/env python3
"""Drafted == "draft": false through the server: token_sha per prompt and sampling, with tok/s and acceptance."""
# usage: xpu_draft_receipt.py BASE_URL MODEL [--tokens N] [--reps R]
import argparse
import json
import statistics
import urllib.request

PROMPTS = {
"code": "Write a Python function that parses an ISO 8601 date string and returns a datetime, with error handling and tests.",
"prose": "Describe a quiet harbour town at dawn in about two hundred words.",
"list": "List the planets of the solar system in order, one per line, with one fact about each.",
"copy": "Repeat the following paragraph exactly, twice: The quick brown fox jumps over the lazy dog while the "
"five boxing wizards jump quickly, and a wizard's job is to vex chumps quickly in fog.",
}
SAMPLINGS = {"greedy": {"temperature": 0}, "seeded": {"temperature": 0.8, "top_p": 0.95, "seed": 7}}


def ask(base, model, prompt, tokens, extra):
body = {"model": model, "messages": [{"role": "user", "content": prompt}], "max_tokens": tokens,
"ignore_eos": True, "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=900) as r:
out = json.load(r)
rt = dict(out["tensorfold"])
rt["speculative"] = out.get("speculative") or {}
return rt


def main():
ap = argparse.ArgumentParser()
ap.add_argument("base")
ap.add_argument("model")
ap.add_argument("--tokens", type=int, default=256)
ap.add_argument("--reps", type=int, default=3)
a = ap.parse_args()
bad = 0
for sname, s in SAMPLINGS.items():
for pname, p in PROMPTS.items():
plain = [ask(a.base, a.model, p, a.tokens, {**s, "draft": False}) for _ in range(a.reps)]
drafted = [ask(a.base, a.model, p, a.tokens, s) for _ in range(a.reps)]
shas = {x["token_sha"] for x in plain + drafted}
same = len(shas) == 1
bad += not same
tp = statistics.median(x["tokens_per_second"] for x in plain)
td = statistics.median(x["tokens_per_second"] for x in drafted)
sp = drafted[-1]["speculative"]
acc = sp.get("acceptance_rate", 0)
tpr = sp.get("tokens_per_round", 0)
print(f"{sname:6s} {pname:5s} {'SAME' if same else 'DIFF'} sha {sorted(shas)[0][:12]}"
f"{'' if same else ' vs ' + ','.join(x[:12] for x in sorted(shas)[1:])} "
f"plain {tp:6.1f} tok/s drafted {td:6.1f} tok/s ({td / tp:.2f}x) acceptance {acc:.2f} tokens/round {tpr:.2f}",
flush=True)
print("DRAFT IDENTITY:", "PASS" if bad == 0 else f"FAIL ({bad})")


if __name__ == "__main__":
main()
123 changes: 123 additions & 0 deletions zig/src/families/nemotron/xpu_engine.zig
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ const xpu = @import("xpu");
const cfgm = @import("xpu_config.zig");
const model = @import("xpu_model.zig");
const nw = @import("xpu_win.zig");
const mtp = @import("xpu_mtp.zig");

const ld = xpu.loader;

Expand All @@ -14,8 +15,21 @@ pub const Options = struct {
progress: bool = false,
/// Rows of the prompt windows when more than 16 (`--prefill`): the prompt kernels.
window_rows: u32 = 0,
/// Load the MTP head (mtp-4bit.safetensors) for drafted rounds.
mtp: bool = false,
};

fn nowNs() u64 {
var ts: std.c.timespec = undefined;
_ = std.c.clock_gettime(.MONOTONIC, &ts);
return @as(u64, @intCast(ts.sec)) * 1_000_000_000 + @as(u64, @intCast(ts.nsec));
}

fn median(v: []f64) f64 {
std.mem.sort(f64, v, {}, std.sort.asc(f64));
return v[v.len / 2];
}

pub const Engine = struct {
gpa: std.mem.Allocator,
ctx: *const xpu.Context,
Expand All @@ -27,6 +41,9 @@ pub const Engine = struct {
w: nw.Win,
max_len: usize,
load_seconds: f64,
/// The MTP head and the prompt's last normed row (its first draft reads it), when loaded.
head: ?mtp.Mtp = null,
last_h: ?xpu.rt.Buffer = null,

pub fn init(gpa: std.mem.Allocator, io: std.Io, ctx: *const xpu.Context, dir: []const u8, o: Options) !*Engine {
const t0 = std.Io.Clock.awake.now(io);
Expand All @@ -46,6 +63,12 @@ pub const Engine = struct {
e.m.bf16_logits = true;
if (o.window_rows > 16) nw.default_rows = o.window_rows;
e.w = try nw.Win.init(gpa, &e.m);
e.head = null;
e.last_h = null;
if (o.mtp) {
e.head = try mtp.Mtp.load(gpa, &e.m, &e.loader, dir);
e.last_h = try e.r.alloc(e.cfg.hidden_size * 2);
}
e.max_len = o.context;
e.load_seconds = xpu.decode.seconds(io, t0);
return e;
Expand Down Expand Up @@ -92,6 +115,106 @@ pub const Engine = struct {
try e.m.fetchLogits(out);
}

// -- drafted rounds (the MTP head loaded): every round is a window, the head absorbs the kept rows --------------

/// 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 {
const mt = &e.head.?;
var t: usize = 0;
while (t < prompt.len) {
try nw.stopCheck(&e.r);
const n = @min(rows, prompt.len - 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;
var j: usize = 0;
while (j < absorb) : (j += nw.max_rows) {
const k = @min(nw.max_rows, absorb - j);
try e.w.normRowsAt(&e.m, @intCast(j), @intCast(k), mt.hn);
_ = try mt.step(&e.w, &e.m, prompt[t + j + 1 ..][0..k], mt.hn, @intCast(t + j), false);
}
if (last) try e.w.normRowsAt(&e.m, @intCast(n - 1), 1, e.last_h.?);
t += n;
}
}

/// 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);
try e.w.forward(&e.m, ids, false, @intCast(ids.len));
}

/// Greedy token of each row of the last window (syncs).
pub fn rowTokens(e: *Engine, out: []i32) !void {
try e.w.rowArgmax(&e.m, out);
}

/// fp32 logits [rows][vocab] of the last window (syncs).
pub fn rowLogits(e: *Engine, out: []f32) !void {
try e.w.fetchRowLogits(&e.m, out);
}

/// Keep the first c rows of the last window.
pub fn keepRows(e: *Engine, c: u32) !void {
try e.w.commit(&e.m, c);
}

/// The head absorbs the kept rows of the last window (follow: the token after each) from `start`, then drafts.
pub fn draftKept(e: *Engine, follow: []const u32, start: u32, depth: u32, out: []u32) !usize {
const mt = &e.head.?;
try e.w.normRows(&e.m, @intCast(follow.len), mt.hn);
const d = try mt.step(&e.w, &e.m, follow, mt.hn, start, depth > 0);
return e.chain(d, depth, out);
}

/// The head absorbs the prompt's last row with the first token, then drafts.
pub fn draftFirst(e: *Engine, first: u32, depth: u32, out: []u32) !usize {
const mt = &e.head.?;
const d = try mt.step(&e.w, &e.m, &.{first}, e.last_h.?, @intCast(e.m.pos - 1), depth > 0);
return e.chain(d, depth, out);
}

/// Drafts after the head's first: each from the head's last output row, at m.pos and on.
fn chain(e: *Engine, first: ?u32, depth: u32, out: []u32) !usize {
if (depth == 0) return 0;
const n = @min(depth, out.len);
out[0] = first.?;
var pos: u32 = @intCast(e.m.pos);
for (1..n) |i| {
out[i] = (try e.head.?.step(&e.w, &e.m, out[i - 1 .. i], e.head.?.fo, pos, true)).?;
pos += 1;
}
return n;
}

/// Times windows of 1 .. ms.len rows and one head step (ms, median of 5) on a scratch prompt; resets after.
pub fn timeRounds(e: *Engine, ms: []f64) !f64 {
var ids: [64]u32 = undefined;
for (&ids, 0..) |*x, i| x.* = 1000 + @as(u32, @intCast(i)) * 37;
try e.reset();
try e.prefillHead(&ids, 64);
var g: [nw.max_rows]i32 = undefined;
var runs: [5]f64 = undefined;
for (ms, 1..) |*out, width| {
for (&runs) |*r| {
const t0 = nowNs();
try e.verifyRows(ids[0..width]);
try e.rowTokens(g[0..width]);
r.* = @as(f64, @floatFromInt(nowNs() - t0)) / 1e6;
}
out.* = median(&runs);
}
var d: [1]u32 = undefined;
_ = try e.draftFirst(ids[0], 1, &d);
for (&runs) |*r| {
const t0 = nowNs();
_ = try e.head.?.step(&e.w, &e.m, &d, e.head.?.fo, @intCast(e.m.pos), true);
r.* = @as(f64, @floatFromInt(nowNs() - t0)) / 1e6;
}
try e.reset();
return median(&runs);
}

/// The prompt head in windows of `rows` tokens (above 16: the prompt kernels), in place; last token fed as decode.
pub fn prefillWindows(e: *Engine, head: []const u32, rows: u32) !void {
var t: usize = 0;
Expand Down
8 changes: 7 additions & 1 deletion zig/src/families/nemotron/xpu_win.zig
Original file line number Diff line number Diff line change
Expand Up @@ -331,7 +331,13 @@ pub const Win = struct {

/// norm_f of the first n rows of residual stream x after the last window (hidden rows for MTP) into out [n][h].
pub fn normRows(w: *Win, m: *model.Model, n: u32, out: Buf) !void {
try run(&m.k.rms, .{ n, 1, 1 }, .{ w.x, m.norm_f, out, m.cfg.hidden_size, m.cfg.layer_norm_epsilon });
try w.normRowsAt(m, 0, n, out);
}

/// norm_f of rows row0 .. row0+n of the last window's residual stream into out [n][h] (prompt rows for MTP).
pub fn normRowsAt(w: *Win, m: *model.Model, row0: u32, n: u32, out: Buf) !void {
const off = @as(usize, row0) * m.cfg.hidden_size * 2;
try run(&m.k.rms, .{ n, 1, 1 }, .{ at(w.x, off), m.norm_f, out, m.cfg.hidden_size, m.cfg.layer_norm_epsilon });
}

pub const Ep = enum(u32) { bf16, f32, relu2 };
Expand Down
Loading