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

- Server: every chat request records where each message starts in the rendered prompt, at exact token boundaries; nothing uses the starts yet, so replies are unchanged (#3679, step 0 of #3617).

- Server: `--cors-origin ORIGIN` (repeatable, exact origins only, no wildcard or credentials mode) lets a browser page on that origin call the API: its preflights are answered and its replies and streams name it, while keys are still required. `/v1/apply-template` returns the prompt text a chat request's `messages` render to, special tokens included, without running the model (#3166, fixes #3111).



- GLM-5.3-Flash on CUDA: `TF_GLM_EXPERT_FORM=classic` or `factored` names the expert form and skips the load's race between the two, so launches and builds compare at one form; a load that times nothing still takes the named form, and unset keeps the race (#3151). Thanks to @Bizuayeu.
- Security: on macOS and Windows, a library named without a folder is never loaded from the directory the server was started in; on macOS, name its folder in DYLD_FALLBACK_LIBRARY_PATH if it was only found there (#3100).

Expand Down
2 changes: 2 additions & 0 deletions zig/src/core/engine_api.zig
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,8 @@ pub const Request = struct {
user_end: u32 = 0,
/// Prompt chunk starts after 0 (Python PrefillPlan); empty selects the engine's plan.
chunks: []const u32 = &.{},
/// Where each message the chat template renders begins, sorted, past 0; empty for raw prompts (never a cut).
message_starts: []const u32 = &.{},
/// Decoded intervals [start,end), sorted, nonempty and strictly separated; an empty list uses prompt arithmetic.
decode_spans: []const [2]u32 = &.{},
/// Most reply tokens inside a think block before the engine writes ``think_close`` (0: no limit).
Expand Down
1 change: 1 addition & 0 deletions zig/src/core/lane_stream.zig
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ pub fn open(h: *LaneHost, job: *Job) bool {
.loop_guard = r.loop_guard,
.loop_stop = r.loop_stop,
.chunks = r.chunks,
.message_starts = r.message_starts,
.history_len = r.history_len,
.shared_prefixes = r.shared_prefixes,
.reuse = reuse,
Expand Down
3 changes: 3 additions & 0 deletions zig/src/core/lanes/stream.zig
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,7 @@ pub const Spec = struct {
loop_guard: bool = false,
loop_stop: bool = false, // with loop_guard: finish where it fires instead of forcing the close
chunks: []const u32 = &.{}, // where prefill chunks start after 0 (Python's PrefillPlan); empty: the backend's step
message_starts: []const u32 = &.{}, // where each templated message begins (api.Request.message_starts); not a cut
history_len: u32 = 0, // prompt prefix lengths a backend may keep for a later turn: the rendered history,
shared_prefixes: []const u32 = &.{}, // then shared system blocks
reuse: Reuse = .{},
Expand Down Expand Up @@ -175,6 +176,7 @@ pub const Stream = struct {
loop_period: ?u32 = null,
long_loop: long_loop.Index = .{}, // the reasoning's runs, for passages repeated verbatim (long_loop.zig)
chunks: []const u32,
message_starts: []const u32,
history_len: u32,
shared_prefixes: []const u32,
logprobs: ?u8 = null,
Expand Down Expand Up @@ -272,6 +274,7 @@ pub const Stream = struct {
.loop_guard = spec.loop_guard,
.loop_stop = spec.loop_stop,
.chunks = spec.chunks,
.message_starts = spec.message_starts,
.history_len = spec.history_len,
.shared_prefixes = spec.shared_prefixes,
.reuse = spec.reuse,
Expand Down
38 changes: 34 additions & 4 deletions zig/src/core/template/eval.zig
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ pub const Ctx = struct {
steps: u64 = 0,
/// The stack where the render began; frames differ too much in size for a count of levels to bound it.
base: usize = 0,
/// Where each request message's own output began (template.zig `renderMarked`); null: not recorded.
marks: ?*Marks = null,

/// One more statement list or loop-filter test: a step of the render, taken only while the stack has room.
fn enter(c: *Ctx) Error!void {
Expand All @@ -46,6 +48,8 @@ pub const Ctx = struct {
}
};

pub const Marks = @import("marks.zig").Marks;

const acc_min = 4096;

fn accumulator(s: v.Str) ?*v.Buffer {
Expand All @@ -57,6 +61,12 @@ fn accumulator(s: v.Str) ?*v.Buffer {
}

fn join(c: *Ctx, l: v.Str, r: v.Str) Error!v.Str {
const s = try joinText(c, l, r);
if (c.marks) |m| try m.joined(l, r, s);
return s;
}

fn joinText(c: *Ctx, l: v.Str, r: v.Str) Error!v.Str {
const a = c.rt.a;
const owned = accumulator(l);
if (l.s.len < acc_min and owned == null) {
Expand Down Expand Up @@ -131,14 +141,18 @@ fn exec(c: *Ctx, act: *Activation, body: []const ast.Stmt) Error!Flow {
for (body) |st| switch (st) {
.output => |pieces| for (pieces) |pc| switch (pc) {
.text => |t| try c.out.literal(c.rt.a, t),
.expr => |e| try c.out.append(c.rt.a, try v.asStr(&c.rt, try eval(c, act, e))),
.expr => |e| try emit(c, try v.asStr(&c.rt, try eval(c, act, e))),
},
.for_ => |f| try execFor(c, act, f),
.if_ => |n| {
const flow = try execIf(c, act, n);
if (flow != .normal) return flow;
},
.assign => |as| try assign(c, act, as.target, try eval(c, act, as.value)),
.assign => |as| {
const x = try eval(c, act, as.value);
if (c.marks) |m| m.bind(c.out, x);
try assign(c, act, as.target, x);
},
.block_set => |b| {
const inner = try enter(c, act, b.frame);
var text = Value{ .str = try capture(c, inner, b.body) };
Expand All @@ -150,19 +164,26 @@ fn exec(c: *Ctx, act: *Activation, body: []const ast.Stmt) Error!Flow {
mv.* = .{ .node = m, .closure = act, .name = m.name.id };
(try slotOf(c, act, m.name.frame, m.name.slot)).* = .{ .macro = mv };
},
.scoped => |sc| try c.out.append(c.rt.a, try capture(c, try enter(c, act, sc.frame), sc.body)),
.scoped => |sc| try emit(c, try capture(c, try enter(c, act, sc.frame), sc.body)),
.break_ => return .brk,
.continue_ => return .cont,
};
return .normal;
}

fn emit(c: *Ctx, s: v.Str) Error!void {
const base = c.out.text.items.len;
try c.out.append(c.rt.a, s);
if (c.marks) |m| try m.carry(c.out, s, base);
}

fn capture(c: *Ctx, act: *Activation, body: []const ast.Stmt) Error!v.Str {
const saved = c.out;
var buf: v.Buffer = .{};
c.out = &buf;
defer c.out = saved;
_ = try exec(c, act, body);
if (c.marks) |m| try m.close(&buf, buf.str());
return buf.str();
}

Expand Down Expand Up @@ -192,7 +213,12 @@ fn execFor(c: *Ctx, act: *Activation, f: *const ast.For) Error!void {
const body = try enter(c, act, f.body_frame);
if (f.uses_loop) body.slots[f.loop_name.slot] = .{ .loop = loop };
try assign(c, body, f.target, item);
switch (try exec(c, body, f.body)) {
const at = c.out.text.items.len;
var saved: Marks.Saved = undefined;
if (c.marks) |m| saved = m.begin(c.out);
const flow = try exec(c, body, f.body);
if (c.marks) |m| try m.end(saved, c.out, at, item);
switch (flow) {
.brk => break,
.cont => continue,
.normal => completed = true,
Expand Down Expand Up @@ -240,6 +266,10 @@ pub fn call(c: *Ctx, callee: Value, pos: []const Value, kw: []const Kw) Error!Va

/// Jinja2's Macro.__call__: positions first, keywords only for the rest, then defaults in the macro's frame.
fn callMacro(c: *Ctx, m: *const v.Macro, pos: []const Value, kw: []const Kw) Error!Value {
if (c.marks) |mk| {
for (pos) |x| mk.bind(c.out, x);
for (kw) |k| mk.bind(c.out, k.value); // keyword arguments bind as positional ones do
}
const node: *const ast.Macro = @ptrCast(@alignCast(m.node));
const params = node.params;
if (pos.len > params.len) return c.rt.fail("macro '{s}' takes not more than {d} argument(s)", .{ m.name, params.len });
Expand Down
91 changes: 91 additions & 0 deletions zig/src/core/template/marks.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
//! Where each request message's own output starts in a render (template.zig `renderMarked`), or nothing when unsure.
const std = @import("std");
const v = @import("value.zig");
const Allocator = std.mem.Allocator;

const Mark = struct { at: usize, k: u32 };
const Key = struct { ptr: usize, len: usize };

/// A loop iteration over a message, or one that binds it first, marks that message where its output begins.
pub const Marks = struct {
a: Allocator,
index: std.AutoHashMapUnmanaged(*const v.Dict, u32) = .empty,
starts: []?usize,
root: *const v.Buffer,
bound: ?u32 = null, // the message the current iteration set to a name or passed to a macro first
level: ?*const v.Buffer = null, // where the current iteration writes; a bind made inside a capture is not its own
open: std.AutoHashMapUnmanaged(*const v.Buffer, std.ArrayList(Mark)) = .empty, // marks in captures being written
held: std.AutoHashMapUnmanaged(Key, []const Mark) = .empty, // marks of finished captures, by the exact string

pub const Saved = struct { bound: ?u32, level: ?*const v.Buffer };

pub fn init(a: Allocator, items: []const v.Value, root: *const v.Buffer) Allocator.Error!Marks {
var m: Marks = .{ .a = a, .starts = &.{}, .root = root };
for (items) |item| if (item == .dict) try m.index.put(a, item.dict, m.index.count());
m.starts = try a.alloc(?usize, m.index.count());
@memset(m.starts, null);
return m;
}

fn of(m: *const Marks, item: v.Value) ?u32 {
return if (item == .dict) m.index.get(item.dict) else null;
}

pub fn bind(m: *Marks, out: *const v.Buffer, x: v.Value) void {
if (m.bound == null and out == m.level) m.bound = m.of(x);
}

/// An iteration starts writing to `out`.
pub fn begin(m: *Marks, out: *const v.Buffer) Saved {
const saved: Saved = .{ .bound = m.bound, .level = m.level };
m.bound = null;
m.level = out;
return saved;
}

/// The iteration over `item` that began at byte `at` of `out` ended; one that wrote nothing marks nothing.
pub fn end(m: *Marks, saved: Saved, out: *const v.Buffer, at: usize, item: v.Value) Allocator.Error!void {
const k = if (out.text.items.len > at) (m.of(item) orelse m.bound) else null;
m.bound = saved.bound;
m.level = saved.level;
if (k) |x| try m.mark(out, at, x);
}

fn mark(m: *Marks, out: *const v.Buffer, at: usize, k: u32) Allocator.Error!void {
if (out == m.root) {
if (m.starts[k] == null or at < m.starts[k].?) m.starts[k] = at;
return;
}
const slot = try m.open.getOrPut(m.a, out);
if (!slot.found_existing) slot.value_ptr.* = .empty;
try slot.value_ptr.append(m.a, .{ .at = at, .k = k });
}

/// A capture into `buf` finished as `s`: its marks travel with that exact string, and with nothing else.
pub fn close(m: *Marks, buf: *const v.Buffer, s: v.Str) Allocator.Error!void {
const kv = m.open.fetchRemove(buf) orelse return;
try m.held.put(m.a, keyOf(s), kv.value.items);
}

/// `s` was written to `out` at `base`; a string changed after its capture carries no marks (fail closed).
pub fn carry(m: *Marks, out: *const v.Buffer, s: v.Str, base: usize) Allocator.Error!void {
if (m.held.count() == 0) return;
for (m.held.get(keyOf(s)) orelse return) |x| try m.mark(out, base + x.at, x.k);
}

/// `l` and `r` joined into `s` (`~` or `+`): both sides' marks travel with it.
pub fn joined(m: *Marks, l: v.Str, r: v.Str, s: v.Str) Allocator.Error!void {
if (m.held.count() == 0) return;
const left = m.held.get(keyOf(l)) orelse &.{};
const right = m.held.get(keyOf(r)) orelse &.{};
if (left.len + right.len == 0) return;
const both = try m.a.alloc(Mark, left.len + right.len);
@memcpy(both[0..left.len], left);
for (right, both[left.len..]) |x, *y| y.* = .{ .at = l.s.len + x.at, .k = x.k };
try m.held.put(m.a, keyOf(s), both);
}

fn keyOf(s: v.Str) Key {
return .{ .ptr = @intFromPtr(s.s.ptr), .len = s.s.len };
}
};
24 changes: 22 additions & 2 deletions zig/src/core/template/template.zig
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,15 @@ pub fn renderProvenance(gpa: Allocator, t: *const Compiled, messages: std.json.V

/// Checkpoint-owned globals are template data; request context overrides them and retains its provenance.
pub fn renderProvenanceGlobals(gpa: Allocator, t: *const Compiled, messages: std.json.Value, tools: std.json.Value, context: std.json.Value, template_globals: std.json.Value, add_generation_prompt: bool, diag: ?*Diag) Error!Str {
return renderWith(gpa, t, messages, tools, context, template_globals, add_generation_prompt, diag, null);
}

/// `renderProvenanceGlobals`, and with `starts` the byte where each message's own output starts (sorted, caller-owned).
pub fn renderMarked(gpa: Allocator, t: *const Compiled, messages: std.json.Value, tools: std.json.Value, context: std.json.Value, template_globals: std.json.Value, add_generation_prompt: bool, diag: ?*Diag, starts: ?*[]usize) Error!Str {
return renderWith(gpa, t, messages, tools, context, template_globals, add_generation_prompt, diag, starts);
}

fn renderWith(gpa: Allocator, t: *const Compiled, messages: std.json.Value, tools: std.json.Value, context: std.json.Value, template_globals: std.json.Value, add_generation_prompt: bool, diag: ?*Diag, starts: ?*[]usize) Error!Str {
// not on `gpa`: an arena there, such as a server request's, would keep the freed scratch until it is reset
var capped: Capped = .{ .child = t.arena.child_allocator, .left = t.limits.bytes };
var arena = std.heap.ArenaAllocator.init(capped.allocator());
Expand All @@ -198,18 +207,21 @@ pub fn renderProvenanceGlobals(gpa: Allocator, t: *const Compiled, messages: std
var out: v.Buffer = .{};
var vars: v.Map = .empty;
var c = eval.Ctx{ .rt = .{ .a = a }, .vars = &vars, .out = &out, .limits = t.limits };
run(&c, &vars, t, messages, tools, context, template_globals, add_generation_prompt) catch |err| {
var marked: std.ArrayList(usize) = .empty;
run(&c, &vars, t, messages, tools, context, template_globals, add_generation_prompt, if (starts != null) &marked else null) catch |err| {
if (err == error.OutOfMemory and capped.spent) return report(gpa, diag, "the chat template needs more than {d} MiB to render this request", .{t.limits.bytes >> 20});
if (err == error.OutOfMemory) return error.OutOfMemory;
if (diag) |d| d.raised = c.rt.raised;
return report(gpa, diag, "{s}", .{c.rt.msg});
};
const text = try gpa.dupe(u8, out.text.items);
errdefer gpa.free(text);
if (starts) |s| s.* = try gpa.dupe(usize, marked.items);
errdefer if (starts) |s| gpa.free(s.*);
return .{ .s = text, .spans = try gpa.dupe(Span, out.spans.items) };
}

fn run(c: *eval.Ctx, vars: *v.Map, t: *const Compiled, messages: std.json.Value, tools: std.json.Value, context: std.json.Value, template_globals: std.json.Value, add_generation_prompt: bool) v.Error!void {
fn run(c: *eval.Ctx, vars: *v.Map, t: *const Compiled, messages: std.json.Value, tools: std.json.Value, context: std.json.Value, template_globals: std.json.Value, add_generation_prompt: bool, marked: ?*std.ArrayList(usize)) v.Error!void {
const a = c.rt.a;
if (template_globals == .object) {
var it = template_globals.object.iterator();
Expand All @@ -227,7 +239,15 @@ fn run(c: *eval.Ctx, vars: *v.Map, t: *const Compiled, messages: std.json.Value,
try vars.put(a, key, try pyjson.fromJson(&c.rt, e.value_ptr.*));
}
}
var marks: eval.Marks = undefined;
if (marked != null) {
marks = try eval.Marks.init(a, try access.iterate(&c.rt, vars.get("messages").?), c.out);
c.marks = &marks;
}
try eval.root(c, t.tree);
const out = marked orelse return;
for (marks.starts) |at| if (at) |x| try out.append(a, x);
std.mem.sort(usize, out.items, {}, std.sort.asc(usize));
}

/// One-shot compile and render, the call the engine's chat prompts make.
Expand Down
1 change: 1 addition & 0 deletions zig/src/server/chat.zig
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,7 @@ pub fn prepare(srv: *Server, cx: *Cx, input: Input, gone: anytype) Failure!Prepa
.rewind_len = @intCast(rendered.rewind_len),
.user_end = @intCast(rendered.user_end),
.shared_prefixes = shared.items,
.message_starts = rendered.message_starts,
// a cut before the conversation's own text: fresh sessions resume their whole harness
.chunks = try srv.chunks.request(a, rendered.ids, system_len),
// from the tokens alone, for every request: cached states are keyed by tokens
Expand Down
2 changes: 1 addition & 1 deletion zig/src/server/hf_text.zig
Original file line number Diff line number Diff line change
Expand Up @@ -437,7 +437,7 @@ pub const HfText = struct {
if (t.clear_thinking) |clear| try context.put(a, "clear_thinking", .{ .bool = options.clear_thinking orelse clear });
var diag: template.Diag = .{};
const tools: std.json.Value = if (options.tools) |tl| try toStd(a, tl) else .null;
const out = template.renderProvenanceGlobals(a, compiled, try toStd(a, messages), tools, .{ .object = context }, .{ .object = globals }, options.add_generation_prompt, &diag) catch |e| {
const out = template.renderMarked(a, compiled, try toStd(a, messages), tools, .{ .object = context }, .{ .object = globals }, options.add_generation_prompt, &diag, options.message_starts) catch |e| {
if (e == error.OutOfMemory) return error.OutOfMemory;
problem.* = diag.msg;
return error.Template;
Expand Down
Loading
Loading