Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,12 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel

## Unreleased

- DeepSeek-V4.1 on CUDA (`dsv41-cuda`, a source build): structured output runs on the lane core's token grammars with drafts on: `response_format`, the `guided_*` fields, `tool_choice: "required"` or a named function, and strict tools under `tool_choice: "auto"`; a grammar's stop token ends the reply with `finish_reason` `stop` even with `ignore_eos` (#3026, closes #1664, from #1665). Thanks to @nuk3s.

- Server: with `--execution-witness`, native Qwen3.5-2B on CUDA (one rank, MLX affine 4-bit, text only) attests its path: once the server is ready it reads every checkpoint shard, after stamping the files before the load, and binds them with the kernel images, GPU, driver, family facts and resolved profile values; other engines still read `unsupported` (#2956, refs #2741). Thanks to @kotevcode.



- Server: every image takes a fixed share of the visual-token budget, `--vision-image-tokens / --vision-max-images` (1,024 tokens at the defaults), whatever the request's image count, so a turn that adds an image no longer re-sizes earlier ones and the prompt cache can resume from the first image; a lone image gets that share, not the whole budget, and a budget that leaves no share is refused by name, naming the image and both flags (#2717, fixes #2510). Thanks to @devopsfortunato.

- OCR: GLM-OCR on native HIP serves `POST /v1/ocr`, returning normalized page Markdown with pipe or spanned-HTML tables and `$`/`$$` math, `blocks: []` because it has no geometry, and named refusals for header/footer extraction (#2572). Thanks to @laudney.
Expand Down
6 changes: 5 additions & 1 deletion docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -543,7 +543,9 @@ On CUDA, stop strings are checked after every token on the generated text, reaso
completes the match. The GLM engine, and Flash Next and Nemotron on two ranks, decode on after a match to an end
token or the reply limit; the server returns the reply only up to the match. Where a CUDA engine honors
`ignore_eos`, end tokens inside the reply are decoded into its text, as on MLX, and `finish_reason` is `length`
unless a stop string or a tool call ended the reply.
unless a stop string, a tool call or a grammar ended the reply. A grammar's stop token is an end token, and with
`ignore_eos` it still ends the reply with `finish_reason` `stop` and stays out of the text. End tokens in the
reasoning, before the grammar starts, stay in it.

### Exact incremental token IDs

Expand Down Expand Up @@ -838,6 +840,8 @@ The server does not silently turn a required call into `auto`. Installing the gr
backend mask hook. A missing library or grammar compilation error is also refused before generation with its reason.

The native GLM CUDA backend also supports token grammars, gathering vocabulary rows before rank 0 masks and draws.
DeepSeek-V4.1 on CUDA (`dsv41-cuda`, a source build) supports them too: rank 0 sends each pick's grammar rows to the
other ranks, and every rank masks its own vocabulary columns before the pick.

A native grammar request waits at most 2,000 ms for its compile. This holds for every format, including JSON objects
and schemas, regexes, choices, EBNF and the structural tags of tool calls. Past that the request gets HTTP 400 naming
Expand Down
7 changes: 6 additions & 1 deletion zig/src/families/deepseek_v41/batch_target.zig
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,18 @@ const rowtab = @import("rowtab.zig");
const iface = @import("draft/iface.zig");
const samp = @import("sampling_gpu.zig");
const batch = @import("batch.zig");
const gg = @import("grammar_gpu.zig");
const Batch = batch.Batch;

/// Target.window: the segments as one round (several forwards past the cap); each row's greedy or keyed choice.
pub fn targetWindow(b: *Batch, segments: []const iface.Segment, choices: [][]u32, sampler: ?*samp.GpuSampler) !void {
pub fn targetWindow(b: *Batch, segments: []const iface.Segment, choices: [][]u32, sampler: ?*samp.GpuSampler, grammar: ?*gg.Masks) !void {
if (segments.len == 0 or segments.len > 16) return error.Slots;
var mix: [16]rowtab.Seg = undefined;
var masked: [gg.max_rows]gg.Row = undefined;
for (segments, mix[0..segments.len]) |sg, *m| {
if (sg.parents != null) return error.TreeWindow;
// structured output: each segment's bits checked before the first forward goes out
if ((try gg.segmentRows(&masked, &.{sg})).len > 0 and grammar == null) return error.StructuresUnsupported;
if (samp.sampled(sg.sampling) and sampler == null) return error.Sampling;
if (sg.slot >= b.ss.n) return error.Slots;
// a pending window must end where the segment starts (a chain never kept keeps every row)
Expand All @@ -28,6 +32,7 @@ pub fn targetWindow(b: *Batch, segments: []const iface.Segment, choices: [][]u32
@memcpy(ids[n..][0..sg.tokens.len], sg.tokens);
n += sg.tokens.len;
}
if (grammar) |g| try g.stage(try gg.segmentRows(&masked, segments[rg[0]..rg[1]]));
try b.window(mix[rg[0]..rg[1]], ids[0..n], j > 0);
var greedy_rows = false;
for (segments[rg[0]..rg[1]]) |sg| greedy_rows = greedy_rows or !samp.sampled(sg.sampling);
Expand Down
7 changes: 7 additions & 0 deletions zig/src/families/deepseek_v41/cuda_model.zig
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ const sg = @import("sessions_gpu.zig");
const slots_mod = @import("slots.zig");
const batch = @import("batch.zig");
const samp = @import("sampling_gpu.zig");
const gg = @import("grammar_gpu.zig");
const dspark_rows = @import("dspark_rows.zig");
const dspark_slots = @import("dspark_slots.zig");
const l2pf_mod = @import("l2pf.zig");
Expand Down Expand Up @@ -116,6 +117,8 @@ pub const Model = struct {
slot_pass: ?*dspark_slots.SlotPass = null,
/// the keyed sampler, every rank with TF_DSV41_SAMPLING=1 (requests with T > 0; followers run its gathers)
sampler: ?*samp.GpuSampler = null,
/// structured output's masks, every rank (rank 0 stages each pick's grammar rows; followers mask what it sends)
grammar: ?*gg.Masks = null,
/// TF_DSV41_L2PF (l2pf.zig): the filled prefetch tables and the runner's side stream
l2pf: ?*l2pf_mod.L2pf = null,

Expand Down Expand Up @@ -156,6 +159,7 @@ pub const Model = struct {
m.rows = null;
m.slot_pass = null;
m.sampler = null;
m.grammar = null;
m.dev_arena = null;
m.supervisor = null;
m.arena = std.heap.ArenaAllocator.init(gpa);
Expand Down Expand Up @@ -434,6 +438,8 @@ pub const Model = struct {
// TF_DSV41_SAMPLING=1: keyed sampling (T > 0) on every rank; off: such requests are refused (error.Sampling)
m.sampler = if ((try samp.enabled())) try samp.GpuSampler.init(gpa, &m.f) else null;
m.gt.sampler = m.sampler;
m.grammar = try gg.Masks.init(gpa, &m.f);
m.gt.grammar = m.grammar;
try m.driver.synchronize();
tr.step("end", cuda.usage(false));
tr.trim();
Expand Down Expand Up @@ -512,6 +518,7 @@ pub const Model = struct {
if (m.slot_set) |ss| ss.deinit();
if (m.pass) |p| p.deinit();
if (m.sampler) |x| x.deinit();
if (m.grammar) |x| x.deinit();
if (m.sessions) |x| x.deinitAfterDrain();
if (m.f.kv) |k| k.deinitAfterDrain();
m.f.deinitAfterDrain();
Expand Down
3 changes: 2 additions & 1 deletion zig/src/families/deepseek_v41/device_host_test.zig
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,15 @@ test {
_ = @import("serve_cli.zig");
if (@import("builtin").os.tag == .linux) inline for (.{ @import("cuda_model.zig").Model, @import("serve_engine.zig").Served, @import("serve_cli.zig") }) |m| std.testing.refAllDecls(m);
_ = @import("slot_transactions_test.zig");
inline for (.{ @import("target.zig").GpuTarget, @import("batch.zig").Batch, @import("sampling_gpu.zig").GpuSampler, @import("sampling_dev.zig").Gpu, @import("dspark_gpu.zig").GpuPass, @import("dspark_slots.zig").SlotPass, @import("dspark_dev.zig").Dev, @import("sched_host.zig"), @import("phases_timed.zig"), @import("profile.zig"), @import("aot_needs.zig") }) |m| std.testing.refAllDecls(m);
inline for (.{ @import("target.zig").GpuTarget, @import("batch.zig").Batch, @import("sampling_gpu.zig").GpuSampler, @import("grammar_gpu.zig").Masks, @import("sampling_dev.zig").Gpu, @import("dspark_gpu.zig").GpuPass, @import("dspark_slots.zig").SlotPass, @import("dspark_dev.zig").Dev, @import("sched_host.zig"), @import("phases_timed.zig"), @import("profile.zig"), @import("aot_needs.zig") }) |m| std.testing.refAllDecls(m);
_ = @import("rows_test.zig");
_ = @import("slot_drafts_test.zig");
_ = @import("slot_drafts_chain_test.zig");
_ = @import("multi_test.zig");
_ = @import("branches_test.zig");
_ = @import("aot_needs_test.zig");
_ = @import("kx_early_test.zig");
_ = @import("grammar_gpu_test.zig");
}

test {
Expand Down
2 changes: 2 additions & 0 deletions zig/src/families/deepseek_v41/draft/draft.zig
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,8 @@ test {
_ = @import("branches_test.zig");
_ = @import("drive_test.zig");
_ = @import("lanes_test.zig");
_ = @import("lanes_grammar_test.zig");
_ = @import("lanes_first_test.zig");
_ = @import("golden_test.zig");
_ = spec;
_ = @import("spec_test.zig");
Expand Down
14 changes: 14 additions & 0 deletions zig/src/families/deepseek_v41/draft/iface.zig
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ pub const Segment = struct {
parents: ?[]const i32, // each row's parent row (row 0: -1); null: a chain
draws: []const u64,
sampling: ?lanes.Sampling,
masks: []const u32 = &.{}, // structured output: each row's allowed bits (rows x words, lanes/grammar.zig); empty: none
};

/// A slot's last rows' taps (bf16 [rows, 3 x hidden] at `address`); `map`: tree window row -> taps row (branches.zig).
Expand Down Expand Up @@ -48,6 +49,8 @@ pub const Target = struct {
warm: ?*const fn (ptr: *anyopaque, asks: []const Warm) void = null,
/// Before `prefill`: the slot's prompt images (their rows replace placeholder ids); borrowed until it returns.
images: ?*const fn (ptr: *anyopaque, slot: u32, images: []const lanes.stream.Image) anyerror!void = null,
/// Before prompt completion: the first token's allowed bits; empty means no grammar.
first_mask: ?*const fn (ptr: *anyopaque, slot: u32, bits: []const u32) void = null,
/// After `prefill`: the prompt rows the slot took from kept state (its first row computed is this one).
resumed: ?*const fn (ptr: *anyopaque, slot: u32) u64 = null,
/// Committed rows' taps for positions [start, start + rows), in order; null: not kept. null fn: none kept.
Expand Down Expand Up @@ -89,6 +92,17 @@ pub const Target = struct {
if (t.vtable.admit) |f| f(t.ptr, slot, max_new);
}

/// Whether the target draws rows among their grammar's tokens (`first_mask`, Segment.masks).
pub fn masks(t: Target) bool {
return t.vtable.first_mask != null;
}

/// The slot's next first token's bits; error.StructuresUnsupported when the target takes no masks.
pub fn firstMask(t: Target, slot: u32, bits: []const u32) !void {
const f = t.vtable.first_mask orelse return if (bits.len > 0) error.StructuresUnsupported else {};
f(t.ptr, slot, bits);
}

pub fn pieces(t: Target) bool {
return t.vtable.begin != null and t.vtable.piece != null and t.vtable.finish != null;
}
Expand Down
5 changes: 1 addition & 4 deletions zig/src/families/deepseek_v41/draft/lane_owner.zig
Original file line number Diff line number Diff line change
Expand Up @@ -42,10 +42,7 @@ pub fn init(gpa: std.mem.Allocator, target: iface.Target, pass: iface.Pass, pric
return x;
}
pub fn deinit(x: *ln.Lanes) void {
for (x.by_slot) |st| if (st) |owner| {
owner.shown.deinit(x.gpa);
x.gpa.destroy(owner);
};
for (x.by_slot) |st| if (st) |owner| x.drop(owner);
x.streams.deinit(x.gpa);
x.free.deinit(x.gpa);
x.drawn.deinit(x.gpa);
Expand Down
24 changes: 22 additions & 2 deletions zig/src/families/deepseek_v41/draft/lanes.zig
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ const calib = @import("calib.zig");
const costs_mod = @import("costs.zig");
const Policy = @import("policy.zig").Policy;
const spec_mod = @import("spec.zig");
const first_mask = @import("lanes_first.zig");

pub const max_block = 16;

Expand All @@ -34,6 +35,7 @@ pub const St = struct {
len: u64 = 0, // rows the target holds (provisional after a window until keep)
base: u64 = 0, // the last window's start
first: u32 = 0, // the prompt's choice (for `first`)
first_bits: std.ArrayList(u32) = .empty, // the grammar bits the pass drew `first` under (lanes_first.zig)
held: [max_block]u32 = undefined, // the last pass's drafts (the main chain)
conf: [max_block]f64 = undefined,
n: u32 = 0, // drafts held (0: none this round)
Expand Down Expand Up @@ -80,6 +82,7 @@ pub const Lanes = struct {

pub fn drop(x: *Lanes, st: *St) void {
st.shown.deinit(x.gpa);
st.first_bits.deinit(x.gpa);
x.gpa.destroy(st);
}

Expand All @@ -89,7 +92,7 @@ pub const Lanes = struct {
return .{ .ptr = x, .vtable = if (pieces) &vtable_pieces else &vtable };
}

const vtable: be.Backend.VTable = .{ .prefill = prefill, .first = first, .queue = queue, .read = read, .verify = verify, .keep = keep, .draft = draft, .probabilities = probabilities, .tree = heldTree, .release = release };
const vtable: be.Backend.VTable = .{ .prefill = prefill, .first = first, .queue = queue, .read = read, .verify = verify, .keep = keep, .draft = draft, .probabilities = probabilities, .tree = heldTree, .held = heldChain, .release = release, .first_masked = firstMasked };
/// a target that runs prompts in pieces (iface.Target begin / piece / finish): the round planner may use them
const vtable_pieces: be.Backend.VTable = blk: {
var v = vtable;
Expand Down Expand Up @@ -185,6 +188,7 @@ pub const Lanes = struct {
const ids = s.prompt();
x.target.admit(slot, s.max_new);
if (s.images.len > 0) try x.target.setImages(slot, s.images);
try x.target.firstMask(slot, try first_mask.take(x, st, s));
st.first = try x.target.prefill(slot, ids, s.sampling, ids.len);
s.cached = @intCast(x.target.resumedRows(slot));
st.len = ids.len;
Expand Down Expand Up @@ -261,6 +265,7 @@ pub const Lanes = struct {
const st = try x.get(s);
try x.settle();
const ids = s.prompt();
try x.target.firstMask(st.slot, try first_mask.take(x, st, s));
return x.finished(st, ids, try x.target.finish(st.slot, ids, s.sampling, ids.len));
}

Expand All @@ -270,6 +275,7 @@ pub const Lanes = struct {
const st = try x.get(s);
try x.settle();
const ids = s.prompt();
try x.target.firstMask(st.slot, try first_mask.take(x, st, s));
if (try x.target.tail(st.slot, ids, s.sampling, ids.len)) |first_| {
try x.finished(st, ids, first_);
return false;
Expand Down Expand Up @@ -297,6 +303,12 @@ pub const Lanes = struct {
return x.drawn.items.len - 1;
}

/// Backend.first_masked: `first`, the pass's pick under these same bits; no forward, KV row or draft runs.
fn firstMasked(ptr: *anyopaque, s: *Stream, position: u64, mask: []const u32) anyerror!u64 {
try first_mask.check(try self(ptr).get(s), mask);
return first(ptr, s, position);
}

fn queue(ptr: *anyopaque, s: *Stream, feed: be.Feed, position: u64) anyerror!u64 {
const x = self(ptr);
const st = try x.get(s);
Expand Down Expand Up @@ -334,7 +346,8 @@ pub const Lanes = struct {
@memcpy(tokens[1 .. 1 + w.held], st.held[0..w.held]);
@memcpy(tokens[1 + w.held ..], w.tokens);
const parents = w.parents; // each row's parent row (row 0: -1)
g.* = .{ .slot = st.slot, .start = st.len, .tokens = tokens, .parents = parents, .draws = w.positions, .sampling = w.stream.sampling };
if (w.masks.len > 0 and !x.target.masks()) return error.StructuresUnsupported;
g.* = .{ .slot = st.slot, .start = st.len, .tokens = tokens, .parents = parents, .draws = w.positions, .sampling = w.stream.sampling, .masks = w.masks };
c.* = o.sampled;
@memcpy(o.drafts, tokens[1..]);
}
Expand Down Expand Up @@ -556,6 +569,13 @@ pub const Lanes = struct {
return .{ .count = total, .tokens = tokens, .parents = parents };
}

/// Backend.held: the held chain's drafts as host tokens, the ones `verify` puts in a window's held rows.
fn heldChain(ptr: *anyopaque, s: *Stream, out: []u32) anyerror!void {
const st = try self(ptr).get(s);
if (out.len > st.n) return error.HeldMismatch;
@memcpy(out, st.held[0..out.len]);
}

/// Each held draft's chance of landing from the raw confidences (the engine's own allocation, without the policy).
fn probabilities(ptr: *anyopaque, s: *Stream, out: []f64) anyerror!bool {
const x = self(ptr);
Expand Down
21 changes: 21 additions & 0 deletions zig/src/families/deepseek_v41/draft/lanes_first.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
//! A grammar stream's first token: the prompt pass draws it among the bits that Backend.first_masked is then given.
const std = @import("std");
const lanes = @import("lanes");
const Stream = lanes.Stream;
const ln = @import("lanes.zig");

/// Before `prefill`, `finish` or `join`: the grammar's first-token bits, kept in `st` for the target (empty: none).
pub fn take(x: *ln.Lanes, st: *ln.St, s: *Stream) ![]const u32 {
st.first_bits.clearRetainingCapacity();
const g = s.grammar orelse return &.{};
// Constraint.next: the same bits Engine.drawFirst asks for after the pass; the grammar takes no token in between
const bits = (try g.next(x.scratch.allocator())) orelse return &.{};
try st.first_bits.appendSlice(x.gpa, bits);
return st.first_bits.items;
}

/// Backend.first_masked's guarantee: `mask` is the bits the pass drew the pick under, and the pick is among them.
pub fn check(st: *const ln.St, mask: []const u32) !void {
if (!std.mem.eql(u32, mask, st.first_bits.items)) return error.FirstMaskChanged;
if (!lanes.grammar.allows(mask, st.first)) return error.FirstNotMasked;
}
Loading
Loading