From 539b1e14ed2e084b96b7f92ac2e15dc1830aa743 Mon Sep 17 00:00:00 2001 From: BobClawblaw <288991054+BobClawblaw@users.noreply.github.com> Date: Mon, 9 Nov 2026 02:40:48 +0000 Subject: [PATCH 1/5] Serve a model card's instruct sampling to thinking-off chats under --instruct-sampling Qwen 3.5, 3.6, Qwen3.8-27B and Qwen3.8-Flash-Next cards give two sampling sets: a thinking set, which generation_config.json carries and the server already serves, and an instruct set for non-thinking replies (temperature 0.7, top_p 0.8, top_k 20, presence_penalty 1.5) that nothing served. `--instruct-sampling card` serves that set to chat requests with thinking off that sample; `name=value,...` sets or changes temperature, top_p, top_k, min_p, presence_penalty and frequency_penalty over it (over the defaults for a family without a card set), and `none` serves one set. Without the flag nothing changes. The set, pairs included, sits between generation_config.json and the serve flags, so --temperature and the others still decide for both modes and a server started greedy stays greedy; a request's own fields win over it. Greedy decoding never takes it: a request's temperature 0, --temperature 0, or a checkpoint whose generation_config.json has do_sample false decodes greedily with no penalty; raw prompt completions and the server's own requests (compaction summaries, Living Weights' wordings and checks) never take it. A pair outside the range a request may send refuses the argument at startup, naming the field. On an engine that applies no penalties the card's presence_penalty is left out with a startup line, pairs naming a non-zero penalty are refused at startup, and `card` refuses a model type with no card set. The serving line prints the set after the sampling defaults. --- README.md | 1 + docs/api.md | 25 +++ zig/src/server/chat.zig | 7 +- zig/src/server/cli.zig | 4 +- zig/src/server/compact.zig | 4 +- zig/src/server/done_times_test.zig | 31 ++- zig/src/server/family_sampling.zig | 236 ++++++++++++++++++++++- zig/src/server/main.zig | 23 ++- zig/src/server/penalty_request_test.zig | 41 ++++ zig/src/server/serve.zig | 14 +- zig/src/server/server.zig | 21 +- zig/src/server/slide_ask.zig | 10 +- zig/src/server/stream_preflight_test.zig | 4 +- 13 files changed, 397 insertions(+), 24 deletions(-) diff --git a/README.md b/README.md index 0c8c12bb29b..7cbe75f9080 100644 --- a/README.md +++ b/README.md @@ -312,6 +312,7 @@ The binary's `capabilities --json` response lists its supported flags and platfo | `--temperature T` | Sampling temperature; zero requests greedy decoding. | | `--prompt-seed` | Use native prompt-derived keys instead of the fresh OS fallback; request and configured default seeds still win. | | `--top-p P`, `--top-k K`, `--min-p P` | Sampling defaults. | +| `--instruct-sampling SET` | Sampling defaults for sampled chat requests with thinking off: `card` (the Qwen 3.5, 3.6 and 3.8 cards' temperature 0.7, top_p 0.8, top_k 20, presence_penalty 1.5), `name=value` pairs over it, or `none`; the serve flags still win. Greedy requests, raw completions and the server's own requests never take them. | | `--thinking`, `--no-thinking` | Choose whether the chat template opens a reasoning block. | | `--reasoning-effort LEVEL` | Default template effort: `minimal`, `low`, `medium`, `high`, `xhigh` or `max`. | | `--thinking-budget N` | Limit reasoning tokens where the engine supports closing the reasoning block. | diff --git a/docs/api.md b/docs/api.md index 8ed0b7f7115..676ff0c2db3 100644 --- a/docs/api.md +++ b/docs/api.md @@ -401,6 +401,31 @@ request fields: a `--min-p` outside 0 through 1 refuses every chat request, a ne `--temperature` and `--top-p` must be finite numbers. An engine that decodes greedily only refuses sampled requests while the server samples by default, and its refusal suggests serving with `--temperature 0`. +`--instruct-sampling` gives chat requests with thinking off their own sampling defaults. Exactly these requests change +under it: a chat request (not a raw completion) whose reasoning block is off (the request's `enable_thinking: false`, +or `--no-thinking` with nothing in the request turning it on), that samples (its temperature, or the default it ends +up with, is above 0), takes the set's value for each sampling field it leaves unset; a field the request sends wins, +as over the ordinary defaults. Requests with thinking on, greedy requests (a request's `temperature: 0`, a server's +`--temperature 0`, or a checkpoint whose `generation_config.json` has `do_sample: false`), raw prompt completions and +the server's own requests (compaction summaries, Living Weights' lesson wordings and checks) are unchanged. `card` +serves the family's model-card instruct set: Qwen 3.5, Qwen 3.6, Qwen3.8-27B and Qwen3.8-Flash-Next give temperature +0.7, top_p 0.8, top_k 20 and presence_penalty 1.5, while their thinking set stays in `generation_config.json`. +`name=value,...` sets or changes `temperature`, `top_p`, `top_k`, `min_p`, `presence_penalty` and `frequency_penalty` +over that set, or over the server's defaults for a family without one; `none` serves one set. The set, pairs +included, sits between `generation_config.json` and the flags, so `--temperature`, `--top-p`, `--top-k` and `--min-p` +still decide for both modes: a server started with `--temperature 0` stays greedy whatever the pairs say. Without the +flag the server has one default set for every request, as before. A pair outside the range a request may send +(temperature below 0, top_p outside 0 through 1, a negative top_k, min_p outside 0 through 1, a penalty outside -2 +through 2) refuses the argument at startup, naming the field. `card` refuses a model type whose family gives no card +set; it cannot tell checkpoints apart within a type, so leave the flag off (or give pairs from the card) for a +checkpoint whose card gives no non-thinking set, such as Ornith-1.5-122B served as `qwen3_5_moe`. On an engine that +applies no penalties the card's presence_penalty is left out with a startup line saying so, and pairs naming a +non-zero penalty are refused at startup. The serving line prints the set after the sampling defaults +(`thinking off: ...`). With a DFlash2 drafter, presence_penalty 1.5 lowers draft acceptance: on Qwen3.8-27B drafted +thinking-off replies at the card set decode about 19% slower than with the penalty at 0, while the thinking set and +undrafted decoding are unaffected (#2645); `--instruct-sampling presence_penalty=0` keeps the card's temperature, +top_p and top_k without the penalty. + `--name-priority ID=background` gives one served id (`--name` or an `--alias`) a default priority: a request that asks for it and sends no `priority` of its own is treated as `priority: "background"`. The request's own `priority` field always wins over the default. This lets one server answer to several ids at their usual priority while a diff --git a/zig/src/server/chat.zig b/zig/src/server/chat.zig index 74ac27fbcbe..c64f523b47a 100644 --- a/zig/src/server/chat.zig +++ b/zig/src/server/chat.zig @@ -26,6 +26,8 @@ pub const Prompt = union(enum) { text: []const u8, ids: []const u32 }; pub const Input = struct { /// The client itself asked for thinking off (no server, template or route default counts): it must be honored. explicit_off: bool = false, + /// The server's own request (a compaction summary, a lesson's wordings): it never takes --instruct-sampling's set. + own: bool = false, messages: Value = .{ .array = &.{} }, tools: []const Value = &.{}, prompt: ?Prompt = null, @@ -145,6 +147,7 @@ pub fn prepare(srv: *Server, cx: *Cx, input: Input, gone: anytype) Failure!Prepa errdefer srv.release(preparing, null); if (gone.check()) return error.Cancelled; const thinking = input.prompt == null and (flag(f, "enable_thinking") orelse srv.config.enable_thinking); + const instruct = input.prompt == null and !thinking and !input.own; // a client's chat with thinking off may take --instruct-sampling's set const reasoning = thinking and srv.info.capability(.reasoning) and (srv.text.vtable.format != .kimi or input.prompt == null); // the prompt renders `thinking`; the reply reads `reasoning` const effort = srv.effortFor(if (f.get("reasoning_effort")) |e| (if (e == .string) e.string else null) else null); cx.clear_thinking = flag(f, "clear_thinking"); @@ -165,14 +168,14 @@ pub fn prepare(srv: *Server, cx: *Cx, input: Input, gone: anytype) Failure!Prepa if (system_len > 0) for ([_]i64{ @as(i64, @intCast(system_len)) - 2048, @as(i64, @intCast(system_len)) - 512, @intCast(system_len) }) |cut| { if (cut >= 512) try shared.append(a, @intCast(cut)); }; - const sampling = try srv.resolveSampling(cx, f, input.temperature, rendered.ids); + const sampling = try srv.resolveSampling(cx, f, input.temperature, rendered.ids, instruct); const draft_field = f.get("draft"); const drafts = srv.config.use_drafts and !(draft_field != null and draft_field.? == .bool and !draft_field.?.bool); var request: api.Request = .{ .prompt = rendered.ids, .max_tokens = @intCast(@min(limit, std.math.maxInt(u32))), .sampling = sampling, - .penalties = try srv.resolvePenalties(cx, f), + .penalties = try srv.resolvePenalties(cx, f, instruct), .eos = if (stops_opt.ignore_eos) &.{} else srv.eos, .drafts = drafts, .background = background, diff --git a/zig/src/server/cli.zig b/zig/src/server/cli.zig index e7168848f16..24d36ca4402 100644 --- a/zig/src/server/cli.zig +++ b/zig/src/server/cli.zig @@ -73,6 +73,7 @@ pub const flags = [_]Flag{ .{ .name = "--top-p", .native = true }, .{ .name = "--top-k", .native = true }, .{ .name = "--min-p", .native = true }, + .{ .name = "--instruct-sampling", .native = true }, .{ .name = "--thinking", .kind = .store_true, .native = true }, .{ .name = "--no-thinking", .kind = .store_true, .native = true }, .{ .name = "--reasoning-effort", .choices = @import("fields.zig").efforts[1..], .native = true }, @@ -211,6 +212,7 @@ pub const Args = struct { top_p: ?f64 = null, top_k: ?i64 = null, min_p: ?f64 = null, + instruct_sampling: ?[]const u8 = null, // none, card or name=value pairs: thinking-off sampled chats' set thinking: bool = true, reasoning_effort: ?[]const u8 = null, thinking_budget: i64 = 0, @@ -464,7 +466,7 @@ fn apply(a: Allocator, out: *Args, name: []const u8, value: ?[]const u8, u: *Usa } else if (is(name, "--decode-share")) { out.decode_share = try float(u, a, name, v); if (!(out.decode_share.? >= 0 and out.decode_share.? < 1)) return fail(u, a, "argument --decode-share: expected a share from 0 to under 1: '{s}'", .{v}); - } else if (is(name, "--prompt-seed")) out.prompt_seed = true else if (is(name, "--max-tokens")) out.max_tokens = try int(u, a, name, v) else if (is(name, "--temperature")) out.temperature = try float(u, a, name, v) else if (is(name, "--top-p")) out.top_p = try float(u, a, name, v) else if (is(name, "--top-k")) out.top_k = try int(u, a, name, v) else if (is(name, "--min-p")) out.min_p = try float(u, a, name, v) else if (is(name, "--thinking")) out.thinking = true else if (is(name, "--no-thinking")) out.thinking = false else if (is(name, "--reasoning-effort")) out.reasoning_effort = v else if (is(name, "--thinking-budget")) out.thinking_budget = try int(u, a, name, v) else if (is(name, "--thinking-reserve")) out.thinking_reserve = try int(u, a, name, v) else if (is(name, "--loop-guard")) out.loop_guard = true else if (is(name, "--loop-guard-stop")) out.loop_guard_stop = true else if (is(name, "--drafter")) out.drafter = v else if (is(name, "--drafter-bits")) out.drafter_bits = @intCast(try int(u, a, name, v)) else if (is(name, "--record")) out.record = v else if (is(name, "--kv-cache")) out.kv_cache = v else if (is(name, "--prompt-precision")) out.prompt_precision = v else if (is(name, "--no-drafts")) out.no_drafts = true else if (is(name, "--keep-warm")) out.keep_warm = try int(u, a, name, v) else if (is(name, "--idle-unload")) out.idle_unload = try int(u, a, name, v) else if (is(name, "--compact-at")) { + } else if (is(name, "--prompt-seed")) out.prompt_seed = true else if (is(name, "--max-tokens")) out.max_tokens = try int(u, a, name, v) else if (is(name, "--temperature")) out.temperature = try float(u, a, name, v) else if (is(name, "--top-p")) out.top_p = try float(u, a, name, v) else if (is(name, "--top-k")) out.top_k = try int(u, a, name, v) else if (is(name, "--min-p")) out.min_p = try float(u, a, name, v) else if (is(name, "--instruct-sampling")) out.instruct_sampling = if (try @import("family_sampling.zig").pairsProblem(a, v)) |why| return fail(u, a, "argument {s}: {s}: '{s}'", .{ name, why, v }) else v else if (is(name, "--thinking")) out.thinking = true else if (is(name, "--no-thinking")) out.thinking = false else if (is(name, "--reasoning-effort")) out.reasoning_effort = v else if (is(name, "--thinking-budget")) out.thinking_budget = try int(u, a, name, v) else if (is(name, "--thinking-reserve")) out.thinking_reserve = try int(u, a, name, v) else if (is(name, "--loop-guard")) out.loop_guard = true else if (is(name, "--loop-guard-stop")) out.loop_guard_stop = true else if (is(name, "--drafter")) out.drafter = v else if (is(name, "--drafter-bits")) out.drafter_bits = @intCast(try int(u, a, name, v)) else if (is(name, "--record")) out.record = v else if (is(name, "--kv-cache")) out.kv_cache = v else if (is(name, "--prompt-precision")) out.prompt_precision = v else if (is(name, "--no-drafts")) out.no_drafts = true else if (is(name, "--keep-warm")) out.keep_warm = try int(u, a, name, v) else if (is(name, "--idle-unload")) out.idle_unload = try int(u, a, name, v) else if (is(name, "--compact-at")) { if (std.mem.eql(u8, v, "auto")) out.compact_auto = true else { const f = try float(u, a, name, v); if (!(f > 0 and f <= 1)) return fail(u, a, "argument --compact-at: expected auto or a fraction in (0, 1]: '{s}'", .{v}); diff --git a/zig/src/server/compact.zig b/zig/src/server/compact.zig index faaa9f35787..6461cfc0caa 100644 --- a/zig/src/server/compact.zig +++ b/zig/src/server/compact.zig @@ -258,11 +258,11 @@ fn oneNote(srv: *Server, cx: *Cx, gone: anytype, task: []const u8, prev: []const const fields = try json.newObject(a); try fields.put(a, "enable_thinking", .{ .bool = false }); try fields.put(a, "temperature", .{ .float = 0 }); - var prepared = chat.prepare(srv, cx, .{ .messages = .{ .array = list.items }, .fields = .{ .object = fields }, .max_tokens = 1024, .temperature = 0 }, gone) catch |e| blk: { + var prepared = chat.prepare(srv, cx, .{ .own = true, .messages = .{ .array = list.items }, .fields = .{ .object = fields }, .max_tokens = 1024, .temperature = 0 }, gone) catch |e| blk: { if (!(e == error.Refused and cx.kind == .context_length)) return e; cx.kind = .request; cx.message = ""; - const fitted = chat.prepare(srv, cx, .{ .messages = .{ .array = list.items }, .fields = .{ .object = fields }, .max_tokens = 1, .temperature = 0 }, gone) catch |e2| { + const fitted = chat.prepare(srv, cx, .{ .own = true, .messages = .{ .array = list.items }, .fields = .{ .object = fields }, .max_tokens = 1, .temperature = 0 }, gone) catch |e2| { if (e2 == error.Refused and cx.kind == .context_length) { cx.kind = .request; cx.message = ""; diff --git a/zig/src/server/done_times_test.zig b/zig/src/server/done_times_test.zig index 0e0de229cd2..c7108b0e9bf 100644 --- a/zig/src/server/done_times_test.zig +++ b/zig/src/server/done_times_test.zig @@ -113,6 +113,7 @@ const Script = struct { tokens: []const u32 = &.{ 'h', 'i' }, seed: ?u64 = null, prompt: []const u32 = &.{}, + top_p: f64 = 0, fn engine(s: *Script) api.Engine { return .{ .ctx = s, .vtable = &.{ .info = info, .submit = submit, .cancel = cancel, .status = status, .memory = memory } }; } @@ -123,6 +124,7 @@ const Script = struct { const s: *Script = @ptrCast(@alignCast(ctx)); s.seed = if (req.sampling) |v| v.seed else null; s.prompt = req.prompt; + s.top_p = if (req.sampling) |v| v.top_p else 0; Clock.ns = s.first; sink.event(sink.ctx, id, &.{ .prefilled = s.cached }); sink.event(sink.ctx, id, &.{ .tokens = s.tokens }); @@ -166,6 +168,31 @@ test "slide ask: wordings are seeded from the lesson, and --prompt-seed still wi try std.testing.expectEqual(api.seedFor(script.prompt, srv.config.seed_salt), script.seed.?); } +test "slide ask: the server's own wordings and lessons never take --instruct-sampling's set" { + const gpa = std.testing.allocator; + var capture: Capture = .{}; + capture.start(); + defer capture.deinit(); + Clock.ns = 10_000_000_000; + var script: Script = .{ .first = 10_000_000_000 }; + var tt: helpers = .{}; + const srv = try server.Server.init(gpa, Clock.io(), script.engine(), text(&tt), .{ .served_name = "test", .model_ids = &.{"test"}, .enable_thinking = false, .tool_id_key = fixedIds() }, null); + defer srv.deinit(); + var arena = std.heap.ArenaAllocator.init(gpa); + defer arena.deinit(); + const a = arena.allocator(); + srv.config.instruct_sampling = (try json.parse(a, "{\"temperature\":0.7,\"top_p\":0.8,\"top_k\":20}")).ok; + var cx: Cx = .{ .a = a }; + // a client's sampled chat with thinking off takes the set's top_p + const client = try chat.prepare(srv, &cx, .{ .id = "client", .messages = (try json.parse(a, "[{\"role\":\"user\",\"content\":\"hi\"}]")).ok, .max_tokens = 2, .fields = (try json.parse(a, "{\"temperature\":0.9}")).ok }, Gone{}); + try std.testing.expectApproxEqAbs(@as(f64, 0.8), client.request.sampling.?.top_p, 1e-6); + srv.release(client.preparing, client.request); + // a lesson's sampled wordings, asked the same way by the server itself, do not: top_p stays 1 + _ = try slide_ask.askBaseAt(srv, &cx, "a system", "one user", 8, 0.9, Gone{}); + try std.testing.expect(script.seed != null); // it sampled + try std.testing.expectApproxEqAbs(@as(f64, 1.0), script.top_p, 1e-6); +} + fn scripted(cached: u32, left: bool) !void { var capture: Capture = .{}; capture.start(); @@ -210,7 +237,7 @@ test "done times: cached tokens above the prompt are clamped in the reply, log a fn seedSample(srv: *server.Server, a: std.mem.Allocator, body: []const u8) !?api.Sampling { var cx: Cx = .{ .a = a }; - return srv.resolveSampling(&cx, (try json.parse(a, body)).ok, 0, &.{ 1, 2, 3 }); + return srv.resolveSampling(&cx, (try json.parse(a, body)).ok, 0, &.{ 1, 2, 3 }, false); } fn seedControls(mode: enum { fresh, keyed, explicit, defaults, default_fresh, failed, log_drawn, log_given }) !void { @@ -248,7 +275,7 @@ fn seedControls(mode: enum { fresh, keyed, explicit, defaults, default_fresh, fa Clock.no_entropy = true; try std.testing.expectEqual(@as(?api.Sampling, null), try seedSample(srv, a, "{\"temperature\":0}")); var cx: Cx = .{ .a = a }; - try std.testing.expectError(error.Refused, srv.resolveSampling(&cx, (try json.parse(a, "{\"temperature\":0.7}")).ok, 0, &.{1})); + try std.testing.expectError(error.Refused, srv.resolveSampling(&cx, (try json.parse(a, "{\"temperature\":0.7}")).ok, 0, &.{1}, false)); try std.testing.expectEqual(@import("errors.zig").Kind.server, cx.kind); try std.testing.expectEqual(@as(usize, 1), Clock.draws); } else if (mode == .log_drawn or mode == .log_given) { diff --git a/zig/src/server/family_sampling.zig b/zig/src/server/family_sampling.zig index e7ab8158961..91ee96ae425 100644 --- a/zig/src/server/family_sampling.zig +++ b/zig/src/server/family_sampling.zig @@ -1,4 +1,4 @@ -//! Served sampling: the family's defaults, then generation_config.json, then the serve flags. +//! Served sampling: family defaults, generation_config.json, the flags; and --instruct-sampling's thinking-off set. const std = @import("std"); const json = @import("json"); @@ -10,6 +10,9 @@ pub const Flags = struct { min_p: ?f64 = null, }; +/// The request fields --instruct-sampling may name. +pub const instruct_fields = [_][]const u8{ "temperature", "top_p", "top_k", "min_p", "presence_penalty", "frequency_penalty" }; + /// DeepSeek-V4.x: temperature 1.0, top_p 1.0, no top_k (the V4 and V4.1 model cards' recommended sampling). pub fn put(a: std.mem.Allocator, out: *json.Object, model_type: []const u8) !void { if (!std.mem.eql(u8, model_type, "deepseek_v41") and !std.mem.eql(u8, model_type, "deepseek_v4")) return; @@ -17,9 +20,128 @@ pub fn put(a: std.mem.Allocator, out: *json.Object, model_type: []const u8) !voi try out.put(a, "top_p", .{ .float = 1.0 }); } +/// Qwen 3.5, 3.6, Qwen3.8-27B and Flash-Next cards: a thinking set (generation_config.json) and an instruct set. +pub fn hasInstruct(model_type: []const u8) bool { + for ([_][]const u8{ "qwen3_5", "qwen3_5_text", "qwen3_5_moe", "qwen3_5_moe_text", "qwen4_exp", "qwen4_exp_text" }) |t| { + if (std.mem.eql(u8, model_type, t)) return true; + } + return false; +} + +/// The Qwen cards' instruct set: temperature 0.7, top_p 0.8, top_k 20, presence_penalty 1.5 where penalties apply. +pub fn putInstruct(a: std.mem.Allocator, out: *json.Object, model_type: []const u8, penalties: bool) !bool { + if (!hasInstruct(model_type)) return false; + try out.put(a, "temperature", .{ .float = 0.7 }); + try out.put(a, "top_p", .{ .float = 0.8 }); + try out.put(a, "top_k", try json.intValue(a, 20)); + if (penalties) try out.put(a, "presence_penalty", .{ .float = 1.5 }); + return true; +} + /// The three layers over each other (``do_sample`` false is greedy); null when none sets a value. pub fn resolve(a: std.mem.Allocator, model_type: []const u8, generation_config: ?[]const u8, flags: Flags) !?json.Value { const out = try json.newObject(a); + try base(a, out, model_type, generation_config); + try applyFlags(a, out, flags); + return if (out.count() > 0) json.Value{ .object = out } else null; +} + +/// True when generation_config.json says ``do_sample: false``: the checkpoint decodes greedily. +pub fn greedyConfig(a: std.mem.Allocator, generation_config: ?[]const u8) !bool { + const bytes = generation_config orelse return false; + const parsed = try json.parse(a, bytes); + if (parsed != .ok) return false; + const d = parsed.ok.get("do_sample") orelse return false; + return d == .bool and !d.bool; +} + +/// --instruct-sampling's set: the layers, the card set (``card``, or under pairs), then the flags; ``none``: null. +pub fn resolveInstruct(a: std.mem.Allocator, model_type: []const u8, generation_config: ?[]const u8, flags: Flags, penalties: bool, text: []const u8) !?json.Value { + const word = std.mem.trim(u8, text, " "); + if (std.mem.eql(u8, word, "none")) return null; + const card = std.mem.eql(u8, word, "card"); + if (card and !hasInstruct(model_type)) return error.NoInstructSet; + const out = try json.newObject(a); + try base(a, out, model_type, generation_config); + _ = try putInstruct(a, out, model_type, penalties); + if (!card) if (try readPairs(a, out, word)) |_| return error.InvalidInstructSampling; + try applyFlags(a, out, flags); + return json.Value{ .object = out }; +} + +/// What the server does with ``--instruct-sampling`` at startup (`startup`). +pub const Startup = struct { + /// The set thinking-off sampled chats start from; null: none is served. + set: ?json.Value = null, + /// A startup line about what is not served, else null. + note: ?[]const u8 = null, + /// Why the server refuses to start, else null. + problem: ?[]const u8 = null, +}; + +/// ``--instruct-sampling text`` at startup: the set and a note, or the problem that refuses the start. +pub fn startup(a: std.mem.Allocator, model_type: []const u8, generation_config: ?[]const u8, flags: Flags, penalties: bool, text: []const u8) !Startup { + if (try greedyConfig(a, generation_config)) + return .{ .note = "--instruct-sampling is not served: generation_config.json has do_sample false, so replies decode greedily" }; + const set = resolveInstruct(a, model_type, generation_config, flags, penalties, text) catch |e| switch (e) { + error.NoInstructSet => return .{ .problem = try std.fmt.allocPrint(a, "--instruct-sampling card: model type {s} has no instruct set in its family defaults; give name=value pairs", .{model_type}) }, + error.InvalidInstructSampling => return .{ .problem = try std.fmt.allocPrint(a, "argument --instruct-sampling: {s}: '{s}'", .{ (try pairsProblem(a, text)).?, text }) }, + else => |x| return x, + } orelse return .{}; + if (penalties) return .{ .set = set }; + for ([_][]const u8{ "presence_penalty", "frequency_penalty" }) |k| if (set.get(k)) |v| if ((v.float64() orelse 0) != 0) + return .{ .problem = try std.fmt.allocPrint(a, "--instruct-sampling names {s} {d}, but this engine applies no penalties: name 0 or leave it out", .{ k, v.float64().? }) }; + const note: ?[]const u8 = if (hasInstruct(model_type) and std.mem.indexOf(u8, text, "presence_penalty") == null) + "presence_penalty 1.5 from the model card's instruct set is not served: this engine applies no penalties" + else + null; + return .{ .set = set, .note = note }; +} + +/// ``--instruct-sampling``'s text checked: null when it reads, else what is wrong with it, for the argument's refusal. +pub fn pairsProblem(a: std.mem.Allocator, text: []const u8) error{OutOfMemory}!?[]const u8 { + const word = std.mem.trim(u8, text, " "); + if (std.mem.eql(u8, word, "none") or std.mem.eql(u8, word, "card")) return null; + const out = try json.newObject(a); + return readPairs(a, out, word); +} + +const pairs_form = "expected none, card, or comma-separated name=value pairs naming temperature, top_p, top_k, min_p, presence_penalty or frequency_penalty"; + +/// Comma-separated ``name=value`` instruct pairs into ``out``, each in a request's range: null, or the problem. +pub fn readPairs(a: std.mem.Allocator, out: *json.Object, text: []const u8) error{OutOfMemory}!?[]const u8 { + var any = false; + var it = std.mem.splitScalar(u8, text, ','); + while (it.next()) |raw| { + const pair = std.mem.trim(u8, raw, " "); + if (pair.len == 0) continue; + const eq = std.mem.indexOfScalar(u8, pair, '=') orelse return pairs_form; + const name = std.mem.trim(u8, pair[0..eq], " "); + const value = std.mem.trim(u8, pair[eq + 1 ..], " "); + const known = for (instruct_fields) |f| { + if (std.mem.eql(u8, f, name)) break true; + } else false; + if (!known) return pairs_form; + if (std.mem.eql(u8, name, "top_k")) { + const k = std.fmt.parseInt(i64, value, 10) catch return "top_k must be an integer"; + if (k < 0) return "top_k must be 0 (off) or more"; + try out.put(a, name, try json.intValue(a, k)); + } else { + const x = std.fmt.parseFloat(f64, value) catch return try std.fmt.allocPrint(a, "{s} must be a finite number", .{name}); + if (!std.math.isFinite(x)) return try std.fmt.allocPrint(a, "{s} must be a finite number", .{name}); + if (std.mem.eql(u8, name, "temperature") and x < 0) return "temperature must be 0 (greedy) or more"; + if (std.mem.eql(u8, name, "top_p") and !(x > 0 and x <= 1)) return "top_p must be above 0 and at most 1"; + if (std.mem.eql(u8, name, "min_p") and !(x >= 0 and x <= 1)) return "min_p must be between 0 and 1"; + if (std.mem.endsWith(u8, name, "_penalty") and !(x >= -2 and x <= 2)) return try std.fmt.allocPrint(a, "{s} must be between -2 and 2", .{name}); + try out.put(a, name, .{ .float = x }); + } + any = true; + } + return if (any) null else pairs_form; +} + +/// Family defaults, then generation_config.json's sampling (``do_sample`` false: temperature 0). +fn base(a: std.mem.Allocator, out: *json.Object, model_type: []const u8, generation_config: ?[]const u8) !void { try put(a, out, model_type); if (generation_config) |bytes| if ((try json.parse(a, bytes)) == .ok) { const cfg = (try json.parse(a, bytes)).ok; @@ -28,11 +150,14 @@ pub fn resolve(a: std.mem.Allocator, model_type: []const u8, generation_config: if (!d.bool) try out.put(a, "temperature", .{ .float = 0 }) else if (out.get("temperature") == null) try out.put(a, "temperature", .{ .float = 1 }); }; }; +} + +/// The serve flags over everything below them. +fn applyFlags(a: std.mem.Allocator, out: *json.Object, flags: Flags) !void { if (flags.temperature) |t| try out.put(a, "temperature", .{ .float = t }); if (flags.top_p) |t| try out.put(a, "top_p", .{ .float = t }); if (flags.top_k) |t| try out.put(a, "top_k", try json.intValue(a, t)); if (flags.min_p) |t| try out.put(a, "min_p", .{ .float = t }); - return if (out.count() > 0) json.Value{ .object = out } else null; } test "DeepSeek-V4.x serves its cards' sampling defaults; other families keep none" { @@ -62,3 +187,110 @@ test "family sampling defaults sit under generation_config.json and the serve fl const greedy = try resolve(a, "deepseek_v41", "{\"do_sample\": false}", .{}); try std.testing.expectEqual(@as(f64, 0), greedy.?.get("temperature").?.float); } + +test "--instruct-sampling card serves the Qwen cards' instruct set under the flags; pairs edit it; none serves none" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const cfg = "{\"do_sample\": true, \"temperature\": 1.0, \"top_k\": 20, \"top_p\": 0.95}"; + for ([_][]const u8{ "qwen3_5", "qwen3_5_text", "qwen3_5_moe", "qwen3_5_moe_text", "qwen4_exp", "qwen4_exp_text" }) |kind| { + const thinking = (try resolve(a, kind, cfg, .{})).?; + try std.testing.expectEqual(@as(f64, 1.0), thinking.get("temperature").?.float); + try std.testing.expect(thinking.get("presence_penalty") == null); + const out = (try resolveInstruct(a, kind, cfg, .{}, true, "card")).?; + try std.testing.expectEqual(@as(f64, 0.7), out.get("temperature").?.float); + try std.testing.expectEqual(@as(f64, 0.8), out.get("top_p").?.float); + try std.testing.expectEqual(@as(?i64, 20), out.get("top_k").?.int64()); + try std.testing.expectEqual(@as(f64, 1.5), out.get("presence_penalty").?.float); + try std.testing.expect(out.get("frequency_penalty") == null); + } + // an engine without penalties gets the card set without presence_penalty + const plain = (try resolveInstruct(a, "qwen3_5", cfg, .{}, false, " card ")).?; + try std.testing.expectEqual(@as(f64, 0.7), plain.get("temperature").?.float); + try std.testing.expect(plain.get("presence_penalty") == null); + // the serve flags apply over the card set + const flagged = (try resolveInstruct(a, "qwen3_5", cfg, .{ .temperature = 0, .top_k = 40 }, true, "card")).?; + try std.testing.expectEqual(@as(f64, 0), flagged.get("temperature").?.float); + try std.testing.expectEqual(@as(?i64, 40), flagged.get("top_k").?.int64()); + try std.testing.expectEqual(@as(f64, 1.5), flagged.get("presence_penalty").?.float); + // pairs edit the card set and sit below the flags, so a server started greedy stays greedy + const pairs = (try resolveInstruct(a, "qwen3_5", cfg, .{}, true, "temperature=0.6, presence_penalty=0,top_k=10")).?; + try std.testing.expectEqual(@as(f64, 0.6), pairs.get("temperature").?.float); + try std.testing.expectEqual(@as(f64, 0), pairs.get("presence_penalty").?.float); + try std.testing.expectEqual(@as(?i64, 10), pairs.get("top_k").?.int64()); + try std.testing.expectEqual(@as(f64, 0.8), pairs.get("top_p").?.float); + const under = (try resolveInstruct(a, "qwen3_5", cfg, .{ .temperature = 0, .top_k = 40 }, true, "temperature=0.6,top_k=10")).?; + try std.testing.expectEqual(@as(f64, 0), under.get("temperature").?.float); + try std.testing.expectEqual(@as(?i64, 40), under.get("top_k").?.int64()); + // none serves no set; a family without a card set refuses card but takes pairs over its defaults + try std.testing.expect((try resolveInstruct(a, "qwen3_5", cfg, .{}, true, "none")) == null); + try std.testing.expectError(error.NoInstructSet, resolveInstruct(a, "deepseek_v41", null, .{}, true, "card")); + try std.testing.expectError(error.NoInstructSet, resolveInstruct(a, "glm5_next", cfg, .{}, true, "card")); + const given = (try resolveInstruct(a, "glm5_next", cfg, .{}, true, "presence_penalty=1")).?; + try std.testing.expectEqual(@as(f64, 1.0), given.get("temperature").?.float); + try std.testing.expectEqual(@as(f64, 1.0), given.get("presence_penalty").?.float); + // a checkpoint that decodes greedily + try std.testing.expect(try greedyConfig(a, "{\"do_sample\": false}")); + try std.testing.expect(!try greedyConfig(a, cfg)); + try std.testing.expect(!try greedyConfig(a, null)); + // malformed text and out-of-range values are refused by name + for ([_][]const u8{ "", " ", "temperature", "temperature=x", "foo=1", "top_k=1.5", "temperature=inf", "=0.5", "cards" }) |bad| { + try std.testing.expectError(error.InvalidInstructSampling, resolveInstruct(a, "qwen3_5", cfg, .{}, true, bad)); + try std.testing.expect((try pairsProblem(a, bad)) != null); + } + const ranges = [_][2][]const u8{ + .{ "temperature=-1", "temperature must be 0 (greedy) or more" }, + .{ "top_p=0", "top_p must be above 0 and at most 1" }, + .{ "top_p=1.5", "top_p must be above 0 and at most 1" }, + .{ "top_k=-1", "top_k must be 0 (off) or more" }, + .{ "min_p=2", "min_p must be between 0 and 1" }, + .{ "presence_penalty=3", "presence_penalty must be between -2 and 2" }, + .{ "frequency_penalty=-2.5", "frequency_penalty must be between -2 and 2" }, + .{ "temperature=0.7,top_p=nan", "top_p must be a finite number" }, + .{ "foo=1", pairs_form }, + }; + for (ranges) |r| { + try std.testing.expectEqualStrings(r[1], (try pairsProblem(a, r[0])).?); + try std.testing.expectError(error.InvalidInstructSampling, resolveInstruct(a, "qwen3_5", cfg, .{}, true, r[0])); + } + for ([_][]const u8{ "none", "card", "top_k=0", "temperature=0", "top_p=1", "temperature=0.7,top_p=0.8,top_k=20,min_p=0,presence_penalty=1.5,frequency_penalty=0", "presence_penalty=-2,frequency_penalty=2" }) |good| { + try std.testing.expect((try pairsProblem(a, good)) == null); + } +} + +test "--instruct-sampling at startup: the set and its notes, or the problem that refuses the start" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const cfg = "{\"do_sample\": true, \"temperature\": 1.0, \"top_k\": 20, \"top_p\": 0.95}"; + // card on an engine with penalties: the whole set, nothing to note + const served = try startup(a, "qwen3_5", cfg, .{}, true, "card"); + try std.testing.expectEqual(@as(f64, 1.5), served.set.?.get("presence_penalty").?.float); + try std.testing.expect(served.note == null and served.problem == null); + // a checkpoint whose generation_config.json has do_sample false leaves the flag unserved, with a line + const greedy = try startup(a, "qwen3_5", "{\"do_sample\": false}", .{}, true, "card"); + try std.testing.expect(greedy.set == null and greedy.problem == null); + try std.testing.expect(std.mem.indexOf(u8, greedy.note.?, "do_sample false") != null); + // card on an engine without penalties: the set without presence_penalty, with a line + const plain = try startup(a, "qwen3_5", cfg, .{}, false, "card"); + try std.testing.expectEqual(@as(f64, 0.7), plain.set.?.get("temperature").?.float); + try std.testing.expect(plain.set.?.get("presence_penalty") == null); + try std.testing.expect(std.mem.indexOf(u8, plain.note.?, "presence_penalty 1.5") != null); + try std.testing.expect(plain.problem == null); + // pairs that name the penalty 0 on that engine: no line + const zeroed = try startup(a, "qwen3_5", cfg, .{}, false, "presence_penalty=0"); + try std.testing.expect(zeroed.set != null and zeroed.note == null and zeroed.problem == null); + // pairs naming a non-zero penalty on that engine refuse the start, naming the pair + const refused = try startup(a, "qwen3_5", cfg, .{}, false, "temperature=0.6,frequency_penalty=0.5"); + try std.testing.expect(refused.set == null); + try std.testing.expectEqualStrings("--instruct-sampling names frequency_penalty 0.5, but this engine applies no penalties: name 0 or leave it out", refused.problem.?); + // card on a model type without a card set + const none = try startup(a, "glm5_next", cfg, .{}, true, "card"); + try std.testing.expect(std.mem.indexOf(u8, none.problem.?, "glm5_next has no instruct set") != null); + // none serves nothing, quietly + const off = try startup(a, "qwen3_5", cfg, .{}, true, "none"); + try std.testing.expect(off.set == null and off.note == null and off.problem == null); + // an out-of-range pair that reached startup is refused as the argument is + const range = try startup(a, "qwen3_5", cfg, .{}, true, "min_p=2"); + try std.testing.expectEqualStrings("argument --instruct-sampling: min_p must be between 0 and 1: 'min_p=2'", range.problem.?); +} diff --git a/zig/src/server/main.zig b/zig/src/server/main.zig index 8d31b627fdf..e1801632457 100644 --- a/zig/src/server/main.zig +++ b/zig/src/server/main.zig @@ -169,6 +169,8 @@ pub fn main(init: std.process.Init) !u8 { return if (problem.len > 0) fail(problem) else e; }; if (record) |r| if (!up.engine.engine.attachRecall(r)) return fail(not_lanes); + const instruct = try instructSampling(a, io, dir, args, model_type, up.engine.engine.info().capability(.penalties), &problem); + if (problem.len > 0) return fail(problem); return serve.run(gpa, io, args, .{ .engine = up.engine.engine, .stop = .{ .ctx = &closer, .close = Closer.close, .halt = Closer.halt }, @@ -179,6 +181,7 @@ pub fn main(init: std.process.Init) !u8 { .model_type = model_type, .reopen = .{ .ctx = &closer, .open = Reopen.open, .close_held = Reopen.closeHeld, .halt_held = Closer.halt, .replace = Reopen.replace }, .sampling = try sampling(a, io, dir, args, model_type), + .instruct = instruct, .environ = init.environ_map, .started = started, .identity = engines.identity(a, args), @@ -233,9 +236,25 @@ fn modelType(a: std.mem.Allocator, io: std.Io, dir: []const u8, problem: *[]cons /// The family's defaults, generation_config.json's sampling, then the serve flags (family_sampling.resolve). fn sampling(a: std.mem.Allocator, io: std.Io, dir: []const u8, args: cli.Args, model_type: []const u8) !?json.Value { + return @import("family_sampling.zig").resolve(a, model_type, try generationConfig(a, io, dir), samplingFlags(args)); +} + +/// --instruct-sampling's set for sampled chats with thinking off (family_sampling.startup), or ``problem``. +fn instructSampling(a: std.mem.Allocator, io: std.Io, dir: []const u8, args: cli.Args, model_type: []const u8, penalties: bool, problem: *[]const u8) !?json.Value { + const text = args.instruct_sampling orelse return null; + const got = try @import("family_sampling.zig").startup(a, model_type, try generationConfig(a, io, dir), samplingFlags(args), penalties, text); + if (got.note) |n| log.line("{s}", .{n}); + if (got.problem) |p| problem.* = p; + return got.set; +} + +fn generationConfig(a: std.mem.Allocator, io: std.Io, dir: []const u8) !?[]const u8 { const path = try std.fs.path.join(a, &.{ dir, "generation_config.json" }); - const bytes = std.Io.Dir.cwd().readFileAlloc(io, path, a, .limited(1 << 20)) catch null; - return @import("family_sampling.zig").resolve(a, model_type, bytes, .{ .temperature = args.temperature, .top_p = args.top_p, .top_k = args.top_k, .min_p = args.min_p }); + return std.Io.Dir.cwd().readFileAlloc(io, path, a, .limited(1 << 20)) catch null; +} + +fn samplingFlags(args: cli.Args) @import("family_sampling.zig").Flags { + return .{ .temperature = args.temperature, .top_p = args.top_p, .top_k = args.top_k, .min_p = args.min_p }; } const Closer = @import("idle_unload_closer.zig").Closer; diff --git a/zig/src/server/penalty_request_test.zig b/zig/src/server/penalty_request_test.zig index 357224d2c56..116f3a3057b 100644 --- a/zig/src/server/penalty_request_test.zig +++ b/zig/src/server/penalty_request_test.zig @@ -106,6 +106,47 @@ test "penalty request: presence_penalty zero, absent and null keep the same repl try check(false, "{\"presence_penalty\":1,\"frequency_penalty\":-1}", ",\"presence_penalty\":0,\"frequency_penalty\":0", 200, .{}); } +test "sampling defaults: a sampled chat with thinking off takes the instruct set; thinking on and greedy keep the defaults" { + const t = std.testing; + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var f = try fixture.Fixture.init(t.allocator, t.io, null); + defer f.deinit(); + var problem: []const u8 = ""; + const text = try HfText.load(t.allocator, t.io, f.path, null, a, &problem); + defer text.deinit(); + var script: Script = .{ .supported = true }; + const srv = try Server.init(t.allocator, t.io, script.engine(), text.text(), .{ + .served_name = "m", + .model_ids = &.{"m"}, + .use_drafts = false, + .default_sampling = (try json.parse(a, "{\"temperature\":1.0,\"top_p\":0.95,\"top_k\":20}")).ok, + .instruct_sampling = (try json.parse(a, "{\"temperature\":0.7,\"top_p\":0.8,\"top_k\":20,\"presence_penalty\":1.5}")).ok, + }, null); + defer srv.deinit(); + const none = (try json.parse(a, "{\"model\":\"m\",\"seed\":1}")).ok; + const own = (try json.parse(a, "{\"model\":\"m\",\"seed\":1,\"temperature\":0.2,\"presence_penalty\":0}")).ok; + const greedy = (try json.parse(a, "{\"model\":\"m\",\"temperature\":0}")).ok; + var cx: @import("errors.zig").Cx = .{ .a = a }; + const on = (try srv.resolveSampling(&cx, none, 0, &.{}, false)).?; + try t.expectApproxEqAbs(@as(f64, 1.0), @as(f64, on.temperature), 1e-6); + try t.expectApproxEqAbs(@as(f64, 0.95), @as(f64, on.top_p), 1e-6); + try t.expectEqualDeep(api.Penalties{}, try srv.resolvePenalties(&cx, none, false)); + const off = (try srv.resolveSampling(&cx, none, 0, &.{}, true)).?; + try t.expectApproxEqAbs(@as(f64, 0.7), @as(f64, off.temperature), 1e-6); + try t.expectApproxEqAbs(@as(f64, 0.8), @as(f64, off.top_p), 1e-6); + try t.expectEqual(@as(u32, 20), off.top_k); + try t.expectEqualDeep(api.Penalties{ .presence = 1.5 }, try srv.resolvePenalties(&cx, none, true)); + const chosen = (try srv.resolveSampling(&cx, own, 0, &.{}, true)).?; + try t.expectApproxEqAbs(@as(f64, 0.2), @as(f64, chosen.temperature), 1e-6); + try t.expectApproxEqAbs(@as(f64, 0.8), @as(f64, chosen.top_p), 1e-6); + try t.expectEqualDeep(api.Penalties{}, try srv.resolvePenalties(&cx, own, true)); + // a greedy request never takes the set: no penalty from it + try t.expect((try srv.resolveSampling(&cx, greedy, 0, &.{}, true)) == null); + try t.expectEqualDeep(api.Penalties{}, try srv.resolvePenalties(&cx, greedy, true)); +} + test "penalty request: supported request values override defaults unchanged" { try check(true, "{\"presence_penalty\":1,\"frequency_penalty\":-1}", "", 200, .{ .presence = 1, .frequency = -1 }); try check(true, "{\"presence_penalty\":1}", ",\"presence_penalty\":-2,\"frequency_penalty\":2", 200, .{ .presence = -2, .frequency = 2 }); diff --git a/zig/src/server/serve.zig b/zig/src/server/serve.zig index 69c0454f4c0..3ceda496e52 100644 --- a/zig/src/server/serve.zig +++ b/zig/src/server/serve.zig @@ -90,6 +90,8 @@ pub const Setup = struct { reopen: ?idle_unload.Reopen = null, /// Sampling defaults from generation_config.json and the flags, as a JSON object; null: greedy. sampling: ?json.Value = null, + /// --instruct-sampling's set for sampled chats with thinking off (family_sampling.resolveInstruct); null: none. + instruct: ?json.Value = null, environ: ?*const std.process.Environ.Map = null, started: i96 = 0, /// The release, backend and GPU the open /health names. @@ -197,6 +199,7 @@ pub fn run(gpa: Allocator, io: std.Io, args: cli.Args, s: Setup) u8 { .idle_unload_s = args.idle_unload, .admission = args.admission, .default_sampling = s.sampling, + .instruct_sampling = s.instruct, .use_drafts = !args.no_drafts, .vision_urls = args.vision_urls, .vision_pdf = args.vision_pdf, @@ -263,13 +266,14 @@ pub fn run(gpa: Allocator, io: std.Io, args: cli.Args, s: Setup) u8 { "profile: stable; registered overrides: unavailable (out of memory)"; log.line("{s}", .{profile_line}); const sampling = shownSampling(a, s.sampling); + const instruct = shownInstruct(a, s.instruct); const drafts = @import("draft_line.zig").shown(args.no_drafts, srv.info); const context = if (window > 0) std.fmt.bufPrint(&window_text, "{d}", .{window}) catch "?" else "unlimited"; // the TCP line keeps its exact form: the benchmark server reads the port from it (benchmark_server_test.zig) if (lis.unix_path) |path| { - log.line("serving {s} on Unix socket {s}, /v1 (sampling: {s}; drafts: {f}; context: {s}; loaded in {d:.1}s)", .{ s.served, path, sampling, drafts, context, loaded }); + log.line("serving {s} on Unix socket {s}, /v1 (sampling: {s}{s}; drafts: {f}; context: {s}; loaded in {d:.1}s)", .{ s.served, path, sampling, instruct, drafts, context, loaded }); } else { - log.line("serving {s} at http://{s}:{d}/v1 (sampling: {s}; drafts: {f}; context: {s}; loaded in {d:.1}s)", .{ s.served, args.host, port, sampling, drafts, context, loaded }); + log.line("serving {s} at http://{s}:{d}/v1 (sampling: {s}{s}; drafts: {f}; context: {s}; loaded in {d:.1}s)", .{ s.served, args.host, port, sampling, instruct, drafts, context, loaded }); } const reserved = args.thinking_reserve > 0 and srv.info.capability(.answer_limit); if (args.thinking_reserve > 0 and !srv.info.capability(.answer_limit)) log.line("--thinking-reserve is not applied: this engine cannot limit the answer apart from the reasoning", .{}); @@ -367,6 +371,12 @@ fn resolve(io: std.Io, host: []const u8, port: u16) ?std.Io.net.IpAddress { return std.Io.net.IpAddress.resolve(io, host, port) catch null; } +/// The serving line's thinking-off defaults when they differ from the sampling defaults: ``; thinking off: ...``. +fn shownInstruct(a: Allocator, instruct: ?json.Value) []const u8 { + const v = instruct orelse return ""; + return std.fmt.allocPrint(a, "; thinking off: {s}", .{shownSampling(a, v)}) catch ""; +} + /// The serving line's sampling: greedy, or each default as ``name value``. fn shownSampling(a: Allocator, sampling: ?json.Value) []const u8 { const v = sampling orelse return "greedy"; diff --git a/zig/src/server/server.zig b/zig/src/server/server.zig index c0b97638fe9..ce3cc37add0 100644 --- a/zig/src/server/server.zig +++ b/zig/src/server/server.zig @@ -66,6 +66,8 @@ pub const Config = struct { dashboard: bool = false, /// Sampling when a request names none (generation_config.json and the serve flags), or null for greedy. default_sampling: ?Value = null, + /// --instruct-sampling's set, for a sampled chat request with thinking off (family_sampling.resolveInstruct). + instruct_sampling: ?Value = null, use_drafts: bool = true, /// --vision-urls: image parts may name public HTTPS URLs, fetched before admission (media_fetch.zig). vision_urls: bool = false, @@ -273,11 +275,22 @@ pub const Server = struct { return fields.coerceEffort(e, srv.effort_levels); } + /// The defaults a request starts from: --instruct-sampling's set for a thinking-off chat that samples under it. + pub fn samplingDefaults(srv: *const Server, instruct: bool, f: Value) ?Value { + const defaults = srv.config.default_sampling; + if (instruct) if (srv.config.instruct_sampling) |set| { + const t = number(f.get("temperature")) orelse number(set.get("temperature")) orelse + (if (defaults) |d| number(d.get("temperature")) else null) orelse 0; + if (t > 0) return set; + }; + return defaults; + } + /// Request seeds override configured keys; otherwise use prompt keying or fresh entropy. - pub fn resolveSampling(srv: *Server, cx: *Cx, f: Value, temperature: f64, prompt_ids: []const u32) errors.Refused!?api.Sampling { + pub fn resolveSampling(srv: *Server, cx: *Cx, f: Value, temperature: f64, prompt_ids: []const u32, instruct: bool) errors.Refused!?api.Sampling { _ = temperature; // the request's own temperature field decides, as in the Python server const options = try json.newObject(cx.a); - const defaults = if (srv.config.default_sampling) |d| try fields.parseNumbers(cx, d) else null; + const defaults = if (srv.samplingDefaults(instruct, f)) |d| try fields.parseNumbers(cx, d) else null; if (defaults) |d| try merge(options, cx, d); const supplied = try fields.parseNumbers(cx, f); try merge(options, cx, supplied); @@ -305,9 +318,9 @@ pub const Server = struct { } /// The request's penalties over configured defaults; unsupported non-default values are refused by name. - pub fn resolvePenalties(srv: *Server, cx: *Cx, f: Value) errors.Refused!api.Penalties { + pub fn resolvePenalties(srv: *Server, cx: *Cx, f: Value, instruct: bool) errors.Refused!api.Penalties { const options = try json.newObject(cx.a); - if (srv.config.default_sampling) |d| try merge(options, cx, try fields.parseNumbers(cx, d)); + if (srv.samplingDefaults(instruct, f)) |d| try merge(options, cx, try fields.parseNumbers(cx, d)); try merge(options, cx, try fields.parseNumbers(cx, f)); const presence = number(options.get("presence_penalty")) orelse 0; const frequency = number(options.get("frequency_penalty")) orelse 0; diff --git a/zig/src/server/slide_ask.zig b/zig/src/server/slide_ask.zig index fbd17396391..519a4f9cd57 100644 --- a/zig/src/server/slide_ask.zig +++ b/zig/src/server/slide_ask.zig @@ -65,7 +65,7 @@ pub fn ask(srv: *Server, cx: *Cx, system: ?[]const u8, user: []const u8, max_tok const fields = try json.newObject(a); try fields.put(a, "enable_thinking", .{ .bool = false }); try fields.put(a, "temperature", .{ .float = 0 }); - const prepared = try chat.prepare(srv, cx, .{ .messages = .{ .array = list.items }, .fields = .{ .object = fields }, .max_tokens = max_tokens, .temperature = 0 }, gone); + const prepared = try chat.prepare(srv, cx, .{ .own = true, .messages = .{ .array = list.items }, .fields = .{ .object = fields }, .max_tokens = max_tokens, .temperature = 0 }, gone); return chat.generate(srv, cx, prepared, null, gone); } @@ -81,7 +81,7 @@ pub fn askIn(srv: *Server, cx: *Cx, before: []const [2][]const u8, user: []const const fields = try json.newObject(a); try fields.put(a, "enable_thinking", .{ .bool = false }); try fields.put(a, "temperature", .{ .float = 0 }); - var prepared = try chat.prepare(srv, cx, .{ .messages = .{ .array = list.items }, .fields = .{ .object = fields }, .max_tokens = max_tokens, .temperature = 0 }, gone); + var prepared = try chat.prepare(srv, cx, .{ .own = true, .messages = .{ .array = list.items }, .fields = .{ .object = fields }, .max_tokens = max_tokens, .temperature = 0 }, gone); if (shipped) { prepared.request.decide = null; prepared.request.untaught = true; @@ -116,7 +116,7 @@ pub fn askBaseAt(srv: *Server, cx: *Cx, system: ?[]const u8, user: []const u8, m try fields.put(a, "temperature", .{ .float = temperature }); // Extra wordings repeat: seeded from the lesson's text, unless --prompt-seed's own seed is on. if (!srv.config.prompt_seed) try fields.put(a, "seed", try json.intValue(a, lessonSeed(system, user))); - var prepared = try chat.prepare(srv, cx, .{ .messages = .{ .array = list.items }, .fields = .{ .object = fields }, .max_tokens = max_tokens, .temperature = temperature }, gone); + var prepared = try chat.prepare(srv, cx, .{ .own = true, .messages = .{ .array = list.items }, .fields = .{ .object = fields }, .max_tokens = max_tokens, .temperature = temperature }, gone); prepared.request.decide = null; prepared.request.untaught = true; return chat.generate(srv, cx, prepared, null, gone); @@ -139,7 +139,7 @@ fn thinkingFrom(srv: *Server, cx: *Cx, user: []const u8, shipped: bool, gone: an try fields.put(a, "enable_thinking", .{ .bool = true }); try fields.put(a, "temperature", .{ .float = 0 }); try fields.put(a, "thinking_budget", try json.intValue(a, think_budget)); - var prepared = try chat.prepare(srv, cx, .{ .messages = .{ .array = asked }, .fields = .{ .object = fields }, .max_tokens = think_reply, .temperature = 0 }, gone); + var prepared = try chat.prepare(srv, cx, .{ .own = true, .messages = .{ .array = asked }, .fields = .{ .object = fields }, .max_tokens = think_reply, .temperature = 0 }, gone); if (shipped) { prepared.request.decide = null; prepared.request.untaught = true; @@ -152,7 +152,7 @@ pub fn continueIds(srv: *Server, cx: *Cx, ids: []const u32, max_tokens: i64, gon const a = cx.a; const fields = try json.newObject(a); try fields.put(a, "temperature", .{ .float = 0 }); - const prepared = try chat.prepare(srv, cx, .{ .prompt = .{ .ids = ids }, .fields = .{ .object = fields }, .max_tokens = max_tokens, .temperature = 0 }, gone); + const prepared = try chat.prepare(srv, cx, .{ .own = true, .prompt = .{ .ids = ids }, .fields = .{ .object = fields }, .max_tokens = max_tokens, .temperature = 0 }, gone); return chat.generate(srv, cx, prepared, null, gone); } diff --git a/zig/src/server/stream_preflight_test.zig b/zig/src/server/stream_preflight_test.zig index a8587e41d39..473ce5f6cf4 100644 --- a/zig/src/server/stream_preflight_test.zig +++ b/zig/src/server/stream_preflight_test.zig @@ -412,9 +412,9 @@ test "a greedy-only engine's refusal names --temperature 0 when the server's own var srv = try server.Server.init(std.testing.allocator, std.testing.io, backend.engine(), text.text(), config, null); defer srv.deinit(); var cx: errors.Cx = .{ .a = a }; - try std.testing.expectError(error.Refused, srv.resolveSampling(&cx, (try json.parse(a, "{\"temperature\":0.7}")).ok, 0, &.{})); + try std.testing.expectError(error.Refused, srv.resolveSampling(&cx, (try json.parse(a, "{\"temperature\":0.7}")).ok, 0, &.{}, false)); try std.testing.expectEqual(case[1], std.mem.indexOf(u8, cx.message, "--temperature 0") != null); - try std.testing.expect(try srv.resolveSampling(&cx, (try json.parse(a, "{\"temperature\":0}")).ok, 0, &.{}) == null); + try std.testing.expect(try srv.resolveSampling(&cx, (try json.parse(a, "{\"temperature\":0}")).ok, 0, &.{}, false) == null); } } From 521a188df3a30ba9eef274dc728cc483f4d9a6c7 Mon Sep 17 00:00:00 2001 From: BobClawblaw <288991054+BobClawblaw@users.noreply.github.com> Date: Mon, 9 Nov 2026 02:42:04 +0000 Subject: [PATCH 2/5] benchmark: send presence_penalty and frequency_penalty 0 with every request The protocol names every draw setting; with the instruct sampling defaults a thinking-off request that leaves presence_penalty out would otherwise be penalized by the served default, and the receipt would not describe the draws it holds. --- zig/src/server/benchmark_stream.zig | 3 +++ zig/src/server/benchmark_stream_test.zig | 8 ++++---- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/zig/src/server/benchmark_stream.zig b/zig/src/server/benchmark_stream.zig index 8d26717008e..a5766a5db84 100644 --- a/zig/src/server/benchmark_stream.zig +++ b/zig/src/server/benchmark_stream.zig @@ -59,6 +59,9 @@ fn bodyMode(a: Allocator, served: []const u8, f: suite.Fixture, tokens: u32, t: const so = try json.newObject(a); try so.put(a, "include_usage", .{ .bool = true }); try o.put(a, "stream_options", .{ .object = so }); + // the protocol names every draw setting: a served default (the instruct set's presence_penalty 1.5) shapes none + try o.put(a, "presence_penalty", .{ .float = 0 }); + try o.put(a, "frequency_penalty", .{ .float = 0 }); if (t > 0) { try o.put(a, "top_k", try json.intValue(a, 20)); try o.put(a, "top_p", .{ .float = 0.95 }); diff --git a/zig/src/server/benchmark_stream_test.zig b/zig/src/server/benchmark_stream_test.zig index 54e7bfa25fa..f7a589d586e 100644 --- a/zig/src/server/benchmark_stream_test.zig +++ b/zig/src/server/benchmark_stream_test.zig @@ -6,8 +6,8 @@ const stop = @import("benchmark_stop.zig"); const fake = @import("benchmark_fake.zig"); const Write = fake.Write; -const golden_chat = "{\"model\": \".tensorfold-benchmark\", \"max_tokens\": 256, \"temperature\": 1.0, \"seed\": 1234, \"stream\": true, \"stream_options\": {\"include_usage\": true}, \"top_k\": 20, \"top_p\": 0.95, \"draft\": false, \"messages\": [{\"role\": \"user\", \"content\": \"Explain how matrix multiplication uses a GPU in plain English, then give a small numerical example.\"}], \"chat_template_kwargs\": {\"enable_thinking\": false}}"; -const golden_code = "{\"model\": \".tensorfold-benchmark\", \"max_tokens\": 256, \"temperature\": 0.0, \"seed\": 1238, \"stream\": true, \"stream_options\": {\"include_usage\": true}, \"prompt\": \"Write a short Python function that computes the Fibonacci sequence and explain it.\"}"; +const golden_chat = "{\"model\": \".tensorfold-benchmark\", \"max_tokens\": 256, \"temperature\": 1.0, \"seed\": 1234, \"stream\": true, \"stream_options\": {\"include_usage\": true}, \"presence_penalty\": 0.0, \"frequency_penalty\": 0.0, \"top_k\": 20, \"top_p\": 0.95, \"draft\": false, \"messages\": [{\"role\": \"user\", \"content\": \"Explain how matrix multiplication uses a GPU in plain English, then give a small numerical example.\"}], \"chat_template_kwargs\": {\"enable_thinking\": false}}"; +const golden_code = "{\"model\": \".tensorfold-benchmark\", \"max_tokens\": 256, \"temperature\": 0.0, \"seed\": 1238, \"stream\": true, \"stream_options\": {\"include_usage\": true}, \"presence_penalty\": 0.0, \"frequency_penalty\": 0.0, \"prompt\": \"Write a short Python function that computes the Fibonacci sequence and explain it.\"}"; fn opts(tokens: u32, serial: bool, timeout_s: f64) stream.Opts { return .{ .tokens = tokens, .reps = 1, .temperatures = &.{ 1.0, 0.0 }, .serial = serial, .timeout_s = timeout_s }; @@ -38,8 +38,8 @@ test "request bodies equal the golden bytes, routes and headers, and a chat repl var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); const a = arena.allocator(); - try std.testing.expectEqualStrings("d85d948f99e8c87c578e103e3e4e584e5d10fc53144a7585cfadd5f8c493fd5b", &sha(golden_chat)); - try std.testing.expectEqualStrings("fb516b455e574eba1c065ba914a8b7707d3839331156cb4defdcd766c97f4318", &sha(golden_code)); + try std.testing.expectEqualStrings("1f13ffe30999c85cb4ecc0bfc89ec9f262ebb2cc262935d1c1200d259bc7d74a", &sha(golden_chat)); + try std.testing.expectEqualStrings("a7528481b784a481f7a6c8365b87becec36c73294f4a02ef95bc1c5f591c75a6", &sha(golden_code)); const f = try fake.Fake.start(std.testing.allocator, &.{ .{ .method = "POST", .path = "/v1/chat/completions", .replies = &.{try fake.reply(a, true, 256, 12)} }, .{ .method = "POST", .path = "/v1/completions", .replies = &.{try fake.reply(a, false, 256, 12)} }, From d170f6d7038ebc5f175694291a26b167c6baf72f Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Mon, 9 Nov 2026 16:04:34 +0000 Subject: [PATCH 3/5] server: the --recall flags parse in cli_recall.zig, so cli.zig stays under 600 lines with --instruct-sampling --- zig/src/server/cli.zig | 16 +--------------- zig/src/server/cli_recall.zig | 19 +++++++++++++++++++ 2 files changed, 20 insertions(+), 15 deletions(-) create mode 100644 zig/src/server/cli_recall.zig diff --git a/zig/src/server/cli.zig b/zig/src/server/cli.zig index 24d36ca4402..8a1fa837b8d 100644 --- a/zig/src/server/cli.zig +++ b/zig/src/server/cli.zig @@ -412,7 +412,7 @@ fn apply(a: Allocator, out: *Args, name: []const u8, value: ?[]const u8, u: *Usa return repeated.origins.append(a, v); } if (try cudaFlag(a, out, name, v, u) or try gpuFlag(a, out, name, v, u)) return; - if (try recallFlag(a, out, name, v, u)) return; + if (try @import("cli_recall.zig").flag(a, out, name, v, u)) return; if (out.cfg.set(name, v) catch return fail(u, a, "--cfg-gamma must be 0 (off) or 1 (unguided) through 5", .{})) return; if (@import("cli_fsr.zig").apply(out, name, v) catch |err| return fail(u, a, "argument {s}: {s}", .{ name, @errorName(err) })) return; if (is(name, "--voices")) { @@ -503,20 +503,6 @@ fn apply(a: Allocator, out: *Args, name: []const u8, value: ?[]const u8, u: *Usa } /// --recall and the flags that imply it; false for any other flag. -fn recallFlag(a: Allocator, out: *Args, name: []const u8, v: []const u8, u: *Usage) error{ Usage, OutOfMemory }!bool { - if (std.mem.eql(u8, name, "--recall-dir")) { - out.recall_dir = v; - } else if (std.mem.eql(u8, name, "--recall-gib")) { - out.recall_gib = try gib(u, a, name, v); - const least = "argument --recall-gib: at least 1/128 GiB (two 4 MiB chunks): '{s}'"; - if (out.recall_gib < 1.0 / 128.0) return fail(u, a, least, .{v}); - } else if (std.mem.eql(u8, name, "--recall-read-only")) { - out.recall_read_only = true; - } else if (!std.mem.eql(u8, name, "--recall")) return false; - out.recall = true; - return true; -} - /// ``--parallel``: "auto" is up to 8 requests at once; a number caps it. pub fn parallel(text: []const u8) ?u32 { const t = std.mem.trim(u8, text, " "); diff --git a/zig/src/server/cli_recall.zig b/zig/src/server/cli_recall.zig new file mode 100644 index 00000000000..8766bde5be5 --- /dev/null +++ b/zig/src/server/cli_recall.zig @@ -0,0 +1,19 @@ +//! The --recall, --recall-dir, --recall-gib and --recall-read-only flags. +const std = @import("std"); +const Allocator = std.mem.Allocator; +const cli = @import("cli.zig"); + +/// Sets a --recall flag's field; false when `name` is none of them. +pub fn flag(a: Allocator, out: *cli.Args, name: []const u8, v: []const u8, u: *cli.Usage) error{ Usage, OutOfMemory }!bool { + if (std.mem.eql(u8, name, "--recall-dir")) { + out.recall_dir = v; + } else if (std.mem.eql(u8, name, "--recall-gib")) { + out.recall_gib = try cli.gib(u, a, name, v); + const least = "argument --recall-gib: at least 1/128 GiB (two 4 MiB chunks): '{s}'"; + if (out.recall_gib < 1.0 / 128.0) return cli.fail(u, a, least, .{v}); + } else if (std.mem.eql(u8, name, "--recall-read-only")) { + out.recall_read_only = true; + } else if (!std.mem.eql(u8, name, "--recall")) return false; + out.recall = true; + return true; +} From d14f8662b79ee74e4a6013664c85fd6bc575fa28 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Mon, 9 Nov 2026 16:16:11 +0000 Subject: [PATCH 4/5] server: --recall's doc comment moves with its parser --- zig/src/server/cli.zig | 1 - zig/src/server/cli_recall.zig | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/zig/src/server/cli.zig b/zig/src/server/cli.zig index 8a1fa837b8d..ceadd0d689d 100644 --- a/zig/src/server/cli.zig +++ b/zig/src/server/cli.zig @@ -502,7 +502,6 @@ fn apply(a: Allocator, out: *Args, name: []const u8, value: ?[]const u8, u: *Usa } else if (is(name, "--register-redraw-st")) out.redraw.register.st = try float(u, a, name, v) else if (is(name, "--register-redraw-high")) out.redraw.register.high = try float(u, a, name, v) else if (is(name, "--register-high-hz")) out.redraw.register.high_hz = try float(u, a, name, v); } -/// --recall and the flags that imply it; false for any other flag. /// ``--parallel``: "auto" is up to 8 requests at once; a number caps it. pub fn parallel(text: []const u8) ?u32 { const t = std.mem.trim(u8, text, " "); diff --git a/zig/src/server/cli_recall.zig b/zig/src/server/cli_recall.zig index 8766bde5be5..ed062e072ae 100644 --- a/zig/src/server/cli_recall.zig +++ b/zig/src/server/cli_recall.zig @@ -3,7 +3,7 @@ const std = @import("std"); const Allocator = std.mem.Allocator; const cli = @import("cli.zig"); -/// Sets a --recall flag's field; false when `name` is none of them. +/// --recall and the flags that imply it; false for any other flag. pub fn flag(a: Allocator, out: *cli.Args, name: []const u8, v: []const u8, u: *cli.Usage) error{ Usage, OutOfMemory }!bool { if (std.mem.eql(u8, name, "--recall-dir")) { out.recall_dir = v; From bced2a186d70684a084e96bc95f32e686aa552f0 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Mon, 9 Nov 2026 22:34:46 +0000 Subject: [PATCH 5/5] changelog: #2626 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index c3b02eeeeb8..c2212657c65 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased +- `--instruct-sampling card` (or `field=value` pairs) serves the model card's instruct sampling to chat requests with thinking off that leave those fields unset; request fields, then the serve flags, then the pairs decide, and the server's own requests never take it (#2626). Thanks to @BobClawblaw. + - XPU: Qwen3.8-27B's DFlash2 drafts go through the core Drafter and Drafted, and each stream's draft tree is keyed with its own request (a sampled shared round read another's) (#2672, #2460 item 5). Thanks to @jschmied, and to @Mirrdhyn for the Arc Pro B70 runs. - `POST /v1/images/generations` serves an engine's image capability: one picture a request as a base64 PNG, with `n` above 1, sizes past 1536 a side or 1,572,864 pixels, `response_format` `url`, unknown fields and a `negative_prompt` that is null or not valid UTF-8 refused by name; a text model's routes are unchanged (#2253, part of #1573). Thanks to @devopsfortunato.