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 @@ -2,6 +2,10 @@

Each release's page on GitHub has its notes and measurements. See [the 1.0.0 release notes](RELEASE-NOTES-1.0.0.md) for the native binary's supported models and migration details.

## Unreleased

- Legacy DSML tool-call envelopes contain nested XML/JSON call syntax in whole and streamed replies. An unfinished envelope cannot promote its payload into a call; valid closed envelopes stream once and preserve adjacent calls.

## 1.0.7

- Living Weights learns each fact into about ten new neurons inside the model's own shards, on Macs and on a GB10. Every MoE layer's shared expert gets a pocket of 64 extra neurons; a fact takes one at each of about ten layers, fired at the first row of the reply (a fact about you) or at the subject's last token where a question names it (a fact about someone or something), with outputs fitted through the model so the answers come back, thinking on too, while near misses, free writing about the subject and other answers stay as they were. Nothing the model had is changed, no adapter is loaded, and any MLX loader reads the folder as a slightly wider model. A fact is kept only when held-out wordings bring it back and nothing else moved; otherwise it is taken out and leaves nothing behind. Documents are learned fact by fact: the model finds the facts, names the organisation on each, and keeps only those whose names, numbers and words the text holds (a list holding others is read again), then writes questions that name their subject (rewriting ones that ask for it), and leaves a question another fact answers to that fact. Three personal facts taught one after another each came back on both test questions on an M5 Ultra, an M3 Ultra and a GB10, with no leaks and no drift, live and after a plain restart; a six-fact handbook gave 3 to 6 of 6 answers across six runs, and long documents about one subject are still weak (6 of 16 from a 21-fact handbook). Without learned facts, replies and speed equal 1.0.6's on both backends; a folder with 21 facts decodes about 16% slower on a Mac. `--slide` refuses a folder taught by 1.0.3 to 1.0.6, whose lessons sit in the shared experts the pocket widens; such folders still serve without it. It builds on the CUDA learner and the take-out rule of #591, #599 and #632. Thanks to @ZackSample and @ThinkOffApp.
Expand Down
182 changes: 180 additions & 2 deletions zig/src/server/stream_preflight_test.zig
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,8 @@ const CallEngine = struct {
for (reply, &out) |byte, *id| id.* = byte;
break :blk out;
};
tokens: []const u32 = &ids,
batched: bool = false,

fn engine(e: *@This()) api.Engine {
return .{ .ctx = e, .vtable = &.{ .info = info, .submit = submit, .cancel = HiEngine.cancel, .status = HiEngine.status, .memory = HiEngine.memory } };
Expand All @@ -98,9 +100,19 @@ const CallEngine = struct {
return .{ .context_window = 4096 };
}

fn submit(_: *anyopaque, id: api.Id, _: *const api.Request, sink: api.Sink) api.SubmitError!void {
fn submit(ctx: *anyopaque, id: api.Id, _: *const api.Request, sink: api.Sink) api.SubmitError!void {
const e: *CallEngine = @ptrCast(@alignCast(ctx));
sink.event(sink.ctx, id, &.{ .prefilled = 0 });
for (0..ids.len) |i| sink.event(sink.ctx, id, &.{ .tokens = ids[i..][0..1] });
if (e.batched) {
sink.event(sink.ctx, id, &.{ .tokens = e.tokens });
} else {
var at: usize = 0;
while (at < e.tokens.len) {
const n = std.unicode.utf8ByteSequenceLength(@intCast(e.tokens[at])) catch 1;
sink.event(sink.ctx, id, &.{ .tokens = e.tokens[at..][0..n] });
at += n;
}
}
sink.event(sink.ctx, id, &.{ .finished = .{ .reason = .stop } });
}
};
Expand All @@ -118,6 +130,16 @@ const Seen = struct {
text: [64]u8 = undefined, // the streamed delta content, or the whole reply's message content
text_len: usize = 0,
calls: usize = 0, // the tool calls the stream started, or the whole reply's tool calls
arguments: [2048]u8 = undefined,
arguments_len: usize = 0,

fn keepArguments(c: *Seen, call: json.Value) void {
const f = call.get("function") orelse return;
const args = f.strField("arguments") orelse return;
const n = @min(args.len, c.arguments.len - c.arguments_len);
@memcpy(c.arguments[c.arguments_len..][0..n], args[0..n]);
c.arguments_len += n;
}

fn content(c: *const Seen) []const u8 {
return c.text[0..c.text_len];
Expand Down Expand Up @@ -153,6 +175,7 @@ const Seen = struct {
if (d.get("content")) |t| c.keep(t);
if (d.get("tool_calls")) |t| if (t == .array) for (t.array) |call| {
if (call.get("id") != null) c.calls += 1;
c.keepArguments(call);
};
};
if (c.events != 1) return;
Expand All @@ -172,6 +195,7 @@ const Seen = struct {
if (m.get("content")) |t| c.keep(t);
if (m.get("tool_calls")) |t| if (t == .array) {
c.calls += t.array.len;
for (t.array) |call| c.keepArguments(call);
};
};
const code = (payload.get("error") orelse return).get("code") orelse return;
Expand Down Expand Up @@ -343,3 +367,157 @@ test "a greedy-only engine's refusal names --temperature 0 when the server's own
try std.testing.expect(try srv.resolveSampling(&cx, (try json.parse(a, "{\"temperature\":0}")).ok, 0, &.{}) == null);
}
}

const dsml_prefix = "<|DSML|tool_calls><|DSML|invoke name=\"lookup\">" ++
"<|DSML|parameter name=\"q\" string=\"true\">";
const dsml_suffix = "</|DSML|parameter></|DSML|invoke></|DSML|tool_calls>";
const dsml_body = "{\"model\":\"test-model\",\"max_tokens\":2000,\"messages\":[{\"role\":\"user\",\"content\":\"x\"}]," ++
"\"tools\":[{\"type\":\"function\",\"function\":{\"name\":\"lookup\",\"parameters\":{\"type\":\"object\"}}}]";

test "DSML literal calls and adjacent XML calls agree in whole and streamed consumer replies" {
const literals = [_][]const u8{
"<tool_call><function=lookup></function></tool_call>",
"<tool_call><function=lookup></function>",
};
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena.deinit();
const a = arena.allocator();
const adjacent = "<tool_call><function=lookup><parameter=n>7</parameter></function></tool_call>";
for (literals) |literal| for ([_]bool{ false, true }) |with_adjacent| {
const raw = try std.mem.concat(a, u8, &.{ dsml_prefix, literal, dsml_suffix, if (with_adjacent) adjacent else "" });
const tokens = try TestText.encode(undefined, a, raw, false);
for ([_]bool{ false, true }) |single| {
const expected = try std.mem.concat(a, u8, &.{
"{\"q\":", try json.quote(a, literal, .{}), "}", if (with_adjacent and !single) "{\"n\":\"7\"}" else "",
});
const body = try std.mem.concat(a, u8, &.{ dsml_body, if (single) ",\"parallel_tool_calls\":false" else "" });
for ([_]bool{ false, true }) |batched| {
var backend: CallEngine = .{ .tokens = tokens, .batched = batched };
const whole = try sendWith(backend.engine(), .chat, try std.mem.concat(a, u8, &.{ body, ",\"stream\":false}" }), .{});
const streamed = try sendWith(backend.engine(), .chat, try std.mem.concat(a, u8, &.{ body, ",\"stream\":true}" }), .{});
try std.testing.expectEqual(@as(?u16, 200), whole.status);
try std.testing.expect(streamed.opened and streamed.status == null);
try std.testing.expectEqual(@as(usize, if (with_adjacent and !single) 2 else 1), whole.calls);
try std.testing.expectEqual(whole.calls, streamed.calls);
try std.testing.expectEqualStrings(expected, whole.arguments[0..whole.arguments_len]);
try std.testing.expectEqualStrings(expected, streamed.arguments[0..streamed.arguments_len]);
try std.testing.expectEqualStrings("", whole.content());
try std.testing.expectEqualStrings("", streamed.content());
try std.testing.expectEqual(@as(i64, 0), streamed.preparing);
}
}
};
}

test "unfinished and malformed DSML never emit their complete nested call in consumer replies" {
const prefix = dsml_prefix ++ "<tool_call><function=lookup></function></tool_call>";
const replies = [_][]const u8{
prefix,
prefix ++ "</|DSML|parameter></|DSML|tool_calls>",
};
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena.deinit();
const a = arena.allocator();
for (replies) |raw| {
const tokens = try TestText.encode(undefined, a, raw, false);
for ([_]bool{ false, true }) |batched| {
var backend: CallEngine = .{ .tokens = tokens, .batched = batched };
const whole = try sendWith(backend.engine(), .chat, dsml_body ++ ",\"stream\":false}", .{});
const streamed = try sendWith(backend.engine(), .chat, dsml_body ++ ",\"stream\":true}", .{});
try std.testing.expectEqual(@as(?u16, 200), whole.status);
try std.testing.expect(streamed.opened and streamed.status == null);
try std.testing.expectEqual(@as(usize, 0), whole.calls);
try std.testing.expectEqual(@as(usize, 0), streamed.calls);
try std.testing.expectEqual(@as(usize, 0), streamed.arguments_len);
try std.testing.expectEqual(@as(i64, 0), streamed.preparing);
}
}
}

test "DSML and adjacent existing non-XML envelopes preserve whole and SSE calls without duplicates" {
const outer = dsml_prefix ++ "outer" ++ dsml_suffix;
const cases = [_][2][]const u8{
.{ "<tool_call>{\"name\":\"lookup\",\"arguments\":{\"q\":\"adjacent-json\"}}</tool_call>", "{\"q\":\"adjacent-json\"}" },
.{ "<tool_call>lookup<arg_key>q</arg_key><arg_value>adjacent-glm</arg_value></tool_call>", "{\"q\":\"adjacent-glm\"}" },
.{ "<|tool_call>call:lookup{q:<|\"|>adjacent-gemma<|\"|>}<tool_call|>", "{\"q\":\"adjacent-gemma\"}" },
.{ "<tools:tool_call>{\"name\":\"lookup\",\"arguments\":{\"q\":\"adjacent-namespaced\"}}</tools:tool_call>", "{\"q\":\"adjacent-namespaced\"}" },
};
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena.deinit();
const a = arena.allocator();
for (cases) |case| for ([_]bool{ false, true }) |outer_first| {
const raw = try std.mem.concat(a, u8, if (outer_first) &.{ outer, case[0] } else &.{ case[0], outer });
const expected = try std.mem.concat(a, u8, if (outer_first)
&.{ "{\"q\":\"outer\"}", case[1] }
else
&.{ case[1], "{\"q\":\"outer\"}" });
const tokens = try TestText.encode(undefined, a, raw, false);
for ([_]bool{ false, true }) |batched| {
var backend: CallEngine = .{ .tokens = tokens, .batched = batched };
const whole = try sendWith(backend.engine(), .chat, dsml_body ++ ",\"stream\":false}", .{});
const streamed = try sendWith(backend.engine(), .chat, dsml_body ++ ",\"stream\":true}", .{});
try std.testing.expectEqual(@as(?u16, 200), whole.status);
try std.testing.expect(streamed.opened and streamed.status == null);
try std.testing.expectEqual(@as(usize, 2), whole.calls);
try std.testing.expectEqual(@as(usize, 2), streamed.calls);
try std.testing.expectEqualStrings(expected, whole.arguments[0..whole.arguments_len]);
try std.testing.expectEqualStrings(expected, streamed.arguments[0..streamed.arguments_len]);
try std.testing.expectEqual(@as(i64, 0), streamed.preparing);
}
};
}

test "a supported bare JSON call containing a literal DSML opener agrees in whole and SSE replies" {
const call = "{\"name\":\"lookup\",\"arguments\":{\"q\":\"<|DSML|tool_calls>\"}}";
const replies = [_][]const u8{ call, "[" ++ call ++ "]", "```json\n" ++ call ++ "\n```" };
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena.deinit();
const a = arena.allocator();
for (replies) |raw| {
const tokens = try TestText.encode(undefined, a, raw, false);
for ([_]bool{ false, true }) |batched| {
var backend: CallEngine = .{ .tokens = tokens, .batched = batched };
const whole = try sendWith(backend.engine(), .chat, dsml_body ++ ",\"stream\":false}", .{});
const streamed = try sendWith(backend.engine(), .chat, dsml_body ++ ",\"stream\":true}", .{});
try std.testing.expectEqual(@as(?u16, 200), whole.status);
try std.testing.expect(streamed.opened and streamed.status == null);
try std.testing.expectEqual(@as(usize, 1), whole.calls);
try std.testing.expectEqual(@as(usize, 1), streamed.calls);
const expected = "{\"q\":\"<|DSML|tool_calls>\"}";
try std.testing.expectEqualStrings(expected, whole.arguments[0..whole.arguments_len]);
try std.testing.expectEqualStrings(expected, streamed.arguments[0..streamed.arguments_len]);
try std.testing.expectEqual(@as(i64, 0), streamed.preparing);
}
}
}

test "closed rejected calls and literal less-than prose preserve later consumer calls" {
const outer = dsml_prefix ++ "outer" ++ dsml_suffix;
const adjacent = "<tool_call><function=lookup><parameter=q>adjacent</parameter></function></tool_call>";
const cases = [_][2][]const u8{
.{ outer ++ "<tool_call>{\"name\":\"other\",\"arguments\":{}}</tool_call>" ++ adjacent, "{\"q\":\"outer\"}{\"q\":\"adjacent\"}" },
.{ outer ++ "<tool_call><function=other></function></tool_call>" ++ adjacent, "{\"q\":\"outer\"}{\"q\":\"adjacent\"}" },
.{ outer ++ "<tool_call></tool_call>" ++ adjacent, "{\"q\":\"outer\"}{\"q\":\"adjacent\"}" },
.{ outer ++ "<tool_call><not_a_function></not_a_function></tool_call>" ++ adjacent, "{\"q\":\"outer\"}{\"q\":\"adjacent\"}" },
.{ adjacent ++ "1 < 2 " ++ adjacent, "{\"q\":\"adjacent\"}{\"q\":\"adjacent\"}" },
.{ "1 < 2 " ++ outer ++ adjacent, "{\"q\":\"outer\"}{\"q\":\"adjacent\"}" },
};
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena.deinit();
const a = arena.allocator();
for (cases) |case| {
const tokens = try TestText.encode(undefined, a, case[0], false);
for ([_]bool{ false, true }) |batched| {
var backend: CallEngine = .{ .tokens = tokens, .batched = batched };
const whole = try sendWith(backend.engine(), .chat, dsml_body ++ ",\"stream\":false}", .{});
const streamed = try sendWith(backend.engine(), .chat, dsml_body ++ ",\"stream\":true}", .{});
try std.testing.expectEqual(@as(?u16, 200), whole.status);
try std.testing.expect(streamed.opened and streamed.status == null);
try std.testing.expectEqual(@as(usize, 2), whole.calls);
try std.testing.expectEqual(@as(usize, 2), streamed.calls);
try std.testing.expectEqualStrings(case[1], whole.arguments[0..whole.arguments_len]);
try std.testing.expectEqualStrings(case[1], streamed.arguments[0..streamed.arguments_len]);
try std.testing.expectEqual(@as(i64, 0), streamed.preparing);
}
}
}
27 changes: 19 additions & 8 deletions zig/src/server/tool_parse.zig
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ pub const wrapCalls = tool_streaming.wrapCalls;

const Error = error{ Invalid, OutOfMemory };
const Call = struct { name: []const u8, arguments: Value };
const Envelope = struct { start: usize, end: usize, payload: []const u8 };
const Envelope = struct { start: usize, end: usize, payload: []const u8, complete: bool = true };

pub const Parsed = struct { content: []const u8, calls: ?[]Value };

Expand Down Expand Up @@ -53,6 +53,10 @@ fn envelopes(a: Allocator, text: []const u8) Allocator.Error![]Envelope {
var found: std.ArrayList(Envelope) = .empty;
var pos: usize = 0;
while (findCI(text, "<tool_call>", pos)) |s| {
if (find(text, dsml_open, pos)) |outer| if (outer < s) {
pos = (find(text, dsml_close, outer + dsml_open.len) orelse break) + dsml_close.len;
continue;
};
const e = findCI(text, "</tool_call>", s + 11) orelse break;
try found.append(a, .{ .start = s, .end = e + 12, .payload = strip(text[s + 11 .. e]) });
pos = e + 12;
Expand All @@ -78,9 +82,10 @@ fn envelopes(a: Allocator, text: []const u8) Allocator.Error![]Envelope {
}
pos = 0;
while (find(text, dsml_open, pos)) |s| {
const e = find(text, dsml_close, s + dsml_open.len) orelse break;
try found.append(a, .{ .start = s, .end = e + dsml_close.len, .payload = text[s .. e + dsml_close.len] });
pos = e + dsml_close.len;
const e = find(text, dsml_close, s + dsml_open.len);
const end = if (e) |at| at + dsml_close.len else text.len;
try found.append(a, .{ .start = s, .end = end, .payload = text[s..end], .complete = e != null });
pos = end;
}
std.mem.sort(Envelope, found.items, {}, struct {
fn less(_: void, x: Envelope, y: Envelope) bool {
Expand All @@ -102,18 +107,20 @@ pub fn parse(a: Allocator, text: []const u8, tools: []const Value, max_calls: ?u
const name = try tool_specs.toolName(a, tool);
try known.put(a, try std.ascii.allocLowerString(a, name), name);
}
if (try bareCalls(a, text, &known, max_calls)) |calls| return .{ .content = "", .calls = calls };
const schemas = try tool_params.schemas(a, tools);
const envs = try envelopes(a, text);
if (envs.len == 0) {
if (try bareCalls(a, text, &known, max_calls)) |calls| return .{ .content = "", .calls = calls };
return .{ .content = text, .calls = null };
}
if (envs.len == 0) return .{ .content = text, .calls = null };
var calls: std.ArrayList(Value) = .empty;
var residue: std.ArrayList(u8) = .empty;
var cursor: usize = 0;
for (envs) |env| {
try residue.appendSlice(a, text[cursor..env.start]);
cursor = env.end;
if (!env.complete) {
try residue.appendSlice(a, text[env.start..env.end]);
continue;
}
if (max_calls) |m| if (calls.items.len >= m) continue;
const parsed: ?[]Call = blk: {
if (std.mem.startsWith(u8, env.payload, dsml_open)) {
Expand Down Expand Up @@ -155,6 +162,10 @@ pub fn closeCall(a: Allocator, text: []const u8, tools: []const Value) Allocator
var pos: usize = 0;
// the opener ``envelopes`` leaves without a closer, so the one appended pairs with it
const start = while (findCI(text, "<tool_call>", pos)) |s| {
if (find(text, dsml_open, pos)) |outer| if (outer < s) {
pos = (find(text, dsml_close, outer + dsml_open.len) orelse return "") + dsml_close.len;
continue;
};
pos = (findCI(text, "</tool_call>", s + 11) orelse break s) + 12;
} else return "";
const block = text[start + 11 ..];
Expand Down
Loading
Loading