diff --git a/CMakeLists.txt b/CMakeLists.txt index 730e4dee..e7bfd464 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2,7 +2,7 @@ cmake_minimum_required(VERSION 3.21) # VERSION is what /version reports and what a client checks compatibility against. It is NOT the # ABI version -- that lives in abi/rad_abi.h and is read out of the header below, because # a plugin contract and a server release do not move together. -project(radiance VERSION 1.0.3 LANGUAGES C CXX) +project(radiance VERSION 1.0.4 LANGUAGES C CXX) set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD_REQUIRED ON) diff --git a/core/config.cpp b/core/config.cpp index d4c7cf64..38d02612 100644 --- a/core/config.cpp +++ b/core/config.cpp @@ -6,9 +6,19 @@ * (spec ยง6). */ #include "rad_core.h" +#include "sample/host_ref.h" +#include "server/oai.h" +#include + +#include +#include +#include +#include #include #include +#include +#include namespace rad { @@ -104,6 +114,58 @@ static const Flag g_flags[] = { " set is the template's: Qwen3.8 takes xhigh|medium|low and defaults\n" " to xhigh, which on a short task can spend the whole token budget\n" " inside and answer nothing. \"none\" turns thinking off" }, + { "--typical-p", "F", "default typical_p, (0, 1]. This flag and the eleven below set the default\n" + " for requests that do not name the field; a request that names it wins" }, + { "--presence-penalty", "F", "default presence_penalty, [-2, 2]" }, + { "--frequency-penalty", "F", "default frequency_penalty, [-2, 2]" }, + { "--repetition-penalty", "F", "default repetition_penalty, > 0" }, + { "--repeat-last-n", "N", "default repeat_last_n, the tokens those penalties look back over; -1 is all" }, + { "--dry-multiplier", "F", "default dry_multiplier; 0 is DRY off" }, + { "--dry-base", "F", "default dry_base, >= 1" }, + { "--dry-allowed-length", "N", "default dry_allowed_length" }, + { "--dry-penalty-last-n", "N", "default dry_penalty_last_n; -1 is the whole context" }, + { "--dry-sequence-breakers", "JSON", "default dry_sequence_breakers, a JSON array of at most 16 strings" }, + { "--xtc-probability", "F", "default xtc_probability, [0, 1]" }, + { "--xtc-threshold", "F", "default xtc_threshold, [0, 1]" }, + { "--default-max-tokens", "N", "max_tokens for requests that do not set one (default 512). `auto` is\n" + " whatever the context leaves after the prompt" }, + { "--max-tokens-cap", "N", "the most any request may generate. A larger max_tokens is cut to it rather\n" + " than refused, and the reply ends with finish_reason \"length\". 0 is none\n" + " (default)" }, + { "--max-n", "N", "the largest `n` a request may ask for (default: the larger of 8 and\n" + " --max-num-seqs)" }, + { "--max-queued-requests", "N", "requests admitted and unfinished at once, past which the answer is 429\n" + " (default 8 x --max-num-seqs)" }, + { "--max-stop-strings", "N", "stop strings one request may send (default 64)" }, + { "--max-stop-bytes", "N", "bytes in one stop string (default 4096)" }, + { "--chat-template-kwargs", "JSON", "variables handed to the chat template on every chat request: a JSON object,\n" + " or @FILE to read one. Repeatable, a later key replacing an earlier one.\n" + " A key the request's own chat_template_kwargs names is the request's, and a\n" + " request that says anything about thinking replaces enable_thinking and\n" + " reasoning_effort here" }, + { "--reasoning-format", "MODE", "auto (default): a reasoning block comes back as reasoning_content.\n" + " none: it stays inline in content" }, + + { "--http-threads", "N", "HTTP workers kept while idle (default: one per core, at least 4)" }, + { "--read-timeout", "S", "seconds a client may go silent while sending a request (default 30)" }, + { "--write-timeout", "S", "seconds one write to a client may block (default 600)" }, + { "--keep-alive-timeout", "S", "seconds an idle connection is held open between requests (default 5)" }, + { "--max-body-mib", "N", "the largest request body; images and video arrive base64 inside it\n" + " (default 512)" }, + { "--retry-after", "S", "the Retry-After a 429 carries, in seconds (default 1)" }, + { "--no-cors", nullptr, "send no CORS headers, so a page on another origin cannot read the API" }, + + { "--image-min-pixels", "N", "an image is resized to at least N pixels (default: the container's)" }, + { "--image-max-pixels", "N", "and to at most N; one encoder pass (--mm-max-patches) still bounds it" }, + { "--video-min-pixels", "N", "a video's sampled frames together resize to at least N pixels" }, + { "--video-max-pixels", "N", "and to at most N" }, + { "--video-fps", "F", "frames sampled per second of video" }, + { "--video-min-frames", "N", "the fewest frames sampled from a video" }, + { "--video-max-frames", "N", "the most frames sampled from a video" }, + { "--video-max-frame-tokens", "N", "the most prompt tokens one video frame may become; 0 is no cap" }, + { "--max-source-pixels", "N", "the largest image or video frame the decoder accepts, before any resize\n" + " (default 67108864). The media flags above default to what the container\n" + " states, and do nothing for a model that takes no media" }, { "--kld-record", "DIR", "instead of serving, run --kld-corpus through prefill and write this\n" " model's log-probabilities at every scored position to DIR: the\n" @@ -154,6 +216,104 @@ static std::vector split_commas(const std::string& s) { return out; } +/* A NUMBER IS THE WHOLE ARGUMENT OR IT IS REFUSED. atof reads "high" as 0, and for --temp that is + * greedy decoding: a typo that changes every reply and says nothing. */ +static bool parse_num(const char* flag, const char* v, double* out) { + char* end = nullptr; + errno = 0; + const double d = std::strtod(v, &end); + if (!*v || !end || *end || errno == ERANGE || !std::isfinite(d)) { + RAD_ERR("%s takes a number, not '%s'", flag, v); + return false; + } + *out = d; + return true; +} + +static bool parse_int(const char* flag, const char* v, int64_t lo, int64_t hi, int64_t* out) { + char* end = nullptr; + errno = 0; + const long long n = std::strtoll(v, &end, 10); + if (!*v || !end || *end || errno == ERANGE) { + RAD_ERR("%s takes a whole number, not '%s'", flag, v); + return false; + } + if (n < lo || n > hi) { + if (lo > INT32_MIN && (hi == INT32_MAX || hi == INT64_MAX)) + RAD_ERR("%s must be >= %lld, not %lld", flag, (long long)lo, n); + else + RAD_ERR("%s must be in [%lld, %lld], not %lld", flag, (long long)lo, (long long)hi, n); + return false; + } + *out = n; + return true; +} + +/* A SAMPLER DEFAULT IS CHECKED AGAINST THE RANGE A REQUEST'S OWN VALUE IS (server::sampler_value_ok), + * here rather than at the first request. A default outside it would be a 400 on every request + * that omits the field -- a server that starts, reports healthy, and answers nothing. */ +static bool sampler_num(const char* flag, const char* field, const char* v, double* out) { + if (!parse_num(flag, v, out)) return false; + std::string why; + if (!server::sampler_value_ok(field, *out, &why)) { + RAD_ERR("%s %s: %s %s", flag, v, field, why.c_str()); + return false; + } + return true; +} +static bool sampler_int(const char* flag, const char* field, const char* v, int* out) { + int64_t n = 0; + double d = 0; + if (!parse_int(flag, v, INT32_MIN, INT32_MAX, &n) || !sampler_num(flag, field, v, &d)) + return false; + *out = (int)n; + return true; +} + +/* THE NAMES THE RENDERER SETS ITSELF. The template context is built from these and the variables + * are written over them (common_chat_template_direct_apply_impl), so a variable by one of these + * names would replace the conversation, the tools or the special tokens of every request. */ +static const char* const kTemplateOwnNames[] = { + "messages", "tools", "bos_token", "eos_token", "add_generation_prompt", +}; + +/* --chat-template-kwargs: a JSON object, or @FILE holding one, merged key by key into `out`. */ +static bool parse_template_kwargs(const char* v, std::map* out) { + std::string text = v; + std::string src = "--chat-template-kwargs"; + if (!text.empty() && text[0] == '@') { + std::ifstream f(text.substr(1), std::ios::binary); + if (!f) { + RAD_ERR("--chat-template-kwargs %s: cannot read %s", v, text.c_str() + 1); + return false; + } + std::ostringstream ss; + ss << f.rdbuf(); + src += " " + text.substr(1); + text = ss.str(); + } + const nlohmann::json j = nlohmann::json::parse(text, nullptr, false); + if (j.is_discarded() || !j.is_object()) { + RAD_ERR("%s takes a JSON object, such as '{\"enable_thinking\": false}'", src.c_str()); + return false; + } + for (auto it = j.begin(); it != j.end(); ++it) { + for (const char* own : kTemplateOwnNames) + if (it.key() == own) { + RAD_ERR("%s: '%s' is set by the server for every request and cannot be a template " + "variable", src.c_str(), own); + return false; + } + if (it.key() == "enable_thinking" && !it.value().is_boolean()) { + RAD_ERR("%s: enable_thinking takes true or false", src.c_str()); + return false; + } + /* dump(): the template context takes JSON, so a string arrives still quoted. */ + (*out)[it.key()] = it.value().dump(); + } + return true; +} + /* Returns 0 on success, 1 for --help (caller exits 0), negative on a bad argument. An unknown * flag is an error naming it, not a warning: a typo in a budget flag is the difference between * the plan you asked for and one the planner invented. */ @@ -293,30 +453,152 @@ int config_parse(int argc, char** argv, Config* c) { c->generation_config = v; } else if (S("--override-chat-template")) { if (!(v = need(i))) return RAD_E_INVAL; c->override_chat_template = v; } - /* A NEGATIVE VALUE IS REFUSED HERE, not left to the range checks below: the fields use - * a negative number to mean "not set", so `--temp -0.5` would otherwise be read as no - * flag at all and the container's default served in its place. */ - else if (S("--temp")) { if (!(v = need(i))) return RAD_E_INVAL; - c->sample_temp = (float)atof(v); - if (!(c->sample_temp >= 0.0f)) { - RAD_ERR("--temp must be in [0, 2], not '%s'", v); - return RAD_E_INVAL; } } + /* A NEGATIVE VALUE IS REFUSED BY THE RANGE: these four fields use a negative number to + * mean "not set", so `--temp -0.5` taken as given would be read as no flag at all and + * the container's default served in its place. */ + else if (S("--temp") || S("--top-p") || S("--min-p")) { + if (!(v = need(i))) return RAD_E_INVAL; + const char* field = S("--temp") ? "temperature" : S("--top-p") ? "top_p" : "min_p"; + double d = 0; + if (!sampler_num(a.c_str(), field, v, &d)) return RAD_E_INVAL; + (S("--temp") ? c->sample_temp : S("--top-p") ? c->sample_top_p : c->sample_min_p) = (float)d; + } else if (S("--top-k")) { if (!(v = need(i))) return RAD_E_INVAL; - c->sample_top_k = atoi(v); - if (c->sample_top_k < 0) { - RAD_ERR("--top-k must be >= 0 (0 disables " - "it), not '%s'", v); - return RAD_E_INVAL; } } - else if (S("--top-p")) { if (!(v = need(i))) return RAD_E_INVAL; - c->sample_top_p = (float)atof(v); - if (!(c->sample_top_p >= 0.0f)) { - RAD_ERR("--top-p must be in (0, 1], not '%s'", v); - return RAD_E_INVAL; } } - else if (S("--min-p")) { if (!(v = need(i))) return RAD_E_INVAL; - c->sample_min_p = (float)atof(v); - if (!(c->sample_min_p >= 0.0f)) { - RAD_ERR("--min-p must be in [0, 1], not '%s'", v); - return RAD_E_INVAL; } } + if (!sampler_int("--top-k", "top_k", v, &c->sample_top_k)) + return RAD_E_INVAL; } + else if (S("--typical-p") || S("--presence-penalty") || S("--frequency-penalty") || + S("--repetition-penalty") || S("--dry-multiplier") || S("--dry-base") || + S("--xtc-probability") || S("--xtc-threshold")) { + if (!(v = need(i))) return RAD_E_INVAL; + struct F { const char* flag; const char* field; std::optional Config::* m; }; + static const F kF[] = { + { "--typical-p", "typical_p", &Config::sample_typical_p }, + { "--presence-penalty", "presence_penalty", &Config::sample_pres_penalty }, + { "--frequency-penalty", "frequency_penalty", &Config::sample_freq_penalty }, + { "--repetition-penalty", "repetition_penalty", &Config::sample_rep_penalty }, + { "--dry-multiplier", "dry_multiplier", &Config::sample_dry_multiplier }, + { "--dry-base", "dry_base", &Config::sample_dry_base }, + { "--xtc-probability", "xtc_probability", &Config::sample_xtc_probability }, + { "--xtc-threshold", "xtc_threshold", &Config::sample_xtc_threshold }, + }; + for (const F& f : kF) { + if (!S(f.flag)) continue; + double d = 0; + if (!sampler_num(f.flag, f.field, v, &d)) return RAD_E_INVAL; + c->*f.m = (float)d; + } + } + else if (S("--repeat-last-n") || S("--dry-allowed-length") || S("--dry-penalty-last-n")) { + if (!(v = need(i))) return RAD_E_INVAL; + const char* field = S("--repeat-last-n") ? "repeat_last_n" + : S("--dry-allowed-length") ? "dry_allowed_length" + : "dry_penalty_last_n"; + int n = 0; + if (!sampler_int(a.c_str(), field, v, &n)) return RAD_E_INVAL; + (S("--repeat-last-n") ? c->sample_penalty_last_n + : S("--dry-allowed-length") ? c->sample_dry_allowed_length + : c->sample_dry_penalty_last_n) = n; + } + else if (S("--dry-sequence-breakers")) { + if (!(v = need(i))) return RAD_E_INVAL; + const nlohmann::json j = nlohmann::json::parse(v, nullptr, false); + bool strings = j.is_array(); + if (strings) for (const auto& e : j) strings = strings && e.is_string(); + if (!strings) { + RAD_ERR("--dry-sequence-breakers takes a JSON array of strings, such as " + "'[\"\\n\", \":\"]', not '%s'", v); + return RAD_E_INVAL; + } + /* The sampler refuses a DRY request with more (sample/host_ref.h), and every request + * leaving the field to this default would be that request. */ + if (j.size() > kDryMaxBreakers) { + RAD_ERR("--dry-sequence-breakers holds %zu strings; the sampler takes at most %zu", + j.size(), kDryMaxBreakers); + return RAD_E_INVAL; + } + c->sample_dry_seq_breakers = j.get>(); + } + else if (S("--default-max-tokens")) { + if (!(v = need(i))) return RAD_E_INVAL; + if (!std::strcmp(v, "auto")) c->default_max_tokens = 0; + else if (!parse_int(a.c_str(), v, 1, INT32_MAX, &c->default_max_tokens)) { + RAD_ERR("--default-max-tokens takes a token count >= 1, or auto"); + return RAD_E_INVAL; + } + } + else if (S("--max-tokens-cap")) { if (!(v = need(i)) || + !parse_int(a.c_str(), v, 0, INT32_MAX, &c->max_tokens_cap)) + return RAD_E_INVAL; } + else if (S("--max-n")) { if (!(v = need(i)) || + !parse_int(a.c_str(), v, 1, INT32_MAX, &c->max_n)) + return RAD_E_INVAL; } + else if (S("--max-queued-requests")) { if (!(v = need(i)) || + !parse_int(a.c_str(), v, 1, INT32_MAX, &c->max_queued_requests)) + return RAD_E_INVAL; } + else if (S("--max-stop-strings")) { if (!(v = need(i)) || + !parse_int(a.c_str(), v, 1, INT32_MAX, &c->max_stop_strings)) + return RAD_E_INVAL; } + else if (S("--max-stop-bytes")) { if (!(v = need(i)) || + !parse_int(a.c_str(), v, 1, INT32_MAX, &c->max_stop_bytes)) + return RAD_E_INVAL; } + else if (S("--chat-template-kwargs")) { if (!(v = need(i)) || + !parse_template_kwargs(v, &c->chat_template_kwargs)) + return RAD_E_INVAL; } + else if (S("--reasoning-format")) { + if (!(v = need(i))) return RAD_E_INVAL; + /* Two values, because the reply reader makes one distinction: whether a reasoning + * block is lifted out of the content or left in it. */ + if (std::strcmp(v, "auto") && std::strcmp(v, "none")) { + RAD_ERR("--reasoning-format takes auto or none, not '%s'", v); + return RAD_E_INVAL; + } + c->reasoning_format = v; + } + else if (S("--http-threads") || S("--read-timeout") || S("--write-timeout") || + S("--keep-alive-timeout") || S("--retry-after")) { + if (!(v = need(i))) return RAD_E_INVAL; + /* The transport keeps at least four workers whatever it is told (server/http.cpp); + * fewer would be a number this flag accepted and the server did not serve. */ + const int64_t lo = S("--http-threads") ? 4 : S("--retry-after") ? 0 : 1; + int64_t n = 0; + if (!parse_int(a.c_str(), v, lo, INT32_MAX, &n)) return RAD_E_INVAL; + (S("--http-threads") ? c->http_threads + : S("--read-timeout") ? c->http_read_timeout_s + : S("--write-timeout") ? c->http_write_timeout_s + : S("--retry-after") ? c->retry_after_s + : c->http_keep_alive_timeout_s) = (int)n; + } + else if (S("--max-body-mib")) { if (!(v = need(i)) || + !parse_int(a.c_str(), v, 1, (int64_t)1 << 20, &c->http_max_body_mib)) + return RAD_E_INVAL; } + else if (S("--no-cors")) c->cors = false; + else if (S("--image-min-pixels") || S("--image-max-pixels") || S("--video-min-pixels") || + S("--video-max-pixels") || S("--max-source-pixels")) { + if (!(v = need(i))) return RAD_E_INVAL; + int64_t n = 0; + if (!parse_int(a.c_str(), v, 1, INT64_MAX, &n)) return RAD_E_INVAL; + (S("--image-min-pixels") ? c->image_min_pixels + : S("--image-max-pixels") ? c->image_max_pixels + : S("--video-min-pixels") ? c->video_min_pixels + : S("--video-max-pixels") ? c->video_max_pixels + : c->max_source_pixels) = n; + } + else if (S("--video-fps")) { + if (!(v = need(i))) return RAD_E_INVAL; + double d = 0; + if (!parse_num(a.c_str(), v, &d)) return RAD_E_INVAL; + if (!(d > 0.0)) { RAD_ERR("--video-fps must be > 0, not '%s'", v); return RAD_E_INVAL; } + c->video_fps = d; + } + else if (S("--video-min-frames") || S("--video-max-frames") || S("--video-max-frame-tokens")) { + if (!(v = need(i))) return RAD_E_INVAL; + int64_t n = 0; + if (!parse_int(a.c_str(), v, S("--video-max-frame-tokens") ? 0 : 1, INT32_MAX, &n)) + return RAD_E_INVAL; + (S("--video-min-frames") ? c->video_min_frames + : S("--video-max-frames") ? c->video_max_frames + : c->video_max_frame_tokens) = (int32_t)n; + } else if (S("--kld-record")) { if (!(v = need(i))) return RAD_E_INVAL; c->kld_record = v; } else if (S("--kld-ref")) { if (!(v = need(i))) return RAD_E_INVAL; c->kld_ref = v; } else if (S("--kld-corpus")) { if (!(v = need(i))) return RAD_E_INVAL; c->kld_corpus = v; } @@ -386,15 +668,42 @@ int config_parse(int argc, char** argv, Config* c) { return RAD_E_INVAL; } - /* THE SAME RANGES THE REQUEST PARSER ENFORCES, and refused here rather than at the first - * request. A default outside them would otherwise be a 400 on every request that omits the - * field -- a server that starts, reports healthy, and answers nothing. */ - if (c->sample_temp >= 0.0f && c->sample_temp > 2.0f) { - RAD_ERR("--temp must be in [0, 2]"); return RAD_E_INVAL; } - if (c->sample_top_p >= 0.0f && !(c->sample_top_p > 0.0f && c->sample_top_p <= 1.0f)) { - RAD_ERR("--top-p must be in (0, 1]"); return RAD_E_INVAL; } - if (c->sample_min_p >= 0.0f && c->sample_min_p > 1.0f) { - RAD_ERR("--min-p must be in [0, 1]"); return RAD_E_INVAL; } + /* TWO FLAGS THAT WOULD SAY THE SAME THING. --reasoning-effort is a template variable with one + * extra meaning ("none" is enable_thinking false), so naming either key in + * --chat-template-kwargs as well leaves two defaults for one setting and no order to read. */ + if (!c->reasoning_effort.empty() && + (c->chat_template_kwargs.count("reasoning_effort") || + c->chat_template_kwargs.count("enable_thinking"))) { + RAD_ERR("--reasoning-effort and a reasoning_effort or enable_thinking key in " + "--chat-template-kwargs both set the default for thinking; give one"); + return RAD_E_INVAL; + } + if (c->default_max_tokens > 0 && c->max_tokens_cap > 0 && + c->default_max_tokens > c->max_tokens_cap) { + RAD_ERR("--default-max-tokens %lld is above --max-tokens-cap %lld, so no request could be " + "served at the default", (long long)c->default_max_tokens, + (long long)c->max_tokens_cap); + return RAD_E_INVAL; + } + /* A request is admitted only if all its choices fit the queue, so an `n` past it would be a + * 429 however long the caller waited. Checked only when one of the two was stated: the + * defaults (8, or --max-num-seqs; and 8 x --max-num-seqs) always fit. */ + if (c->max_n > 0 || c->max_queued_requests > 0) { + const int64_t n = c->max_n > 0 ? c->max_n : std::max(8, c->max_seqs); + const int64_t q = c->max_queued_requests > 0 ? c->max_queued_requests : c->max_seqs * 8; + if (n > q) { + RAD_ERR("--max-n %lld is above the %lld requests the queue admits " + "(--max-queued-requests), so a request asking for it could never be admitted", + (long long)n, (long long)q); + return RAD_E_INVAL; + } + } + if (c->image_min_pixels && c->image_max_pixels && *c->image_min_pixels > *c->image_max_pixels) { + RAD_ERR("--image-min-pixels is above --image-max-pixels"); return RAD_E_INVAL; } + if (c->video_min_pixels && c->video_max_pixels && *c->video_min_pixels > *c->video_max_pixels) { + RAD_ERR("--video-min-pixels is above --video-max-pixels"); return RAD_E_INVAL; } + if (c->video_min_frames && c->video_max_frames && *c->video_min_frames > *c->video_max_frames) { + RAD_ERR("--video-min-frames is above --video-max-frames"); return RAD_E_INVAL; } return RAD_OK; } diff --git a/core/engine.cpp b/core/engine.cpp index adbc63a1..6ccb7a99 100644 --- a/core/engine.cpp +++ b/core/engine.cpp @@ -1742,6 +1742,22 @@ SamplingParams resolve_sampling_defaults(const RadModelMeta& meta, bool containe if (cfg.sample_min_p >= 0.0f) { sp.min_p = cfg.sample_min_p; over += " --min-p"; } if (cfg.sample_top_k >= 0) { sp.top_k = cfg.sample_top_k; over += " --top-k"; } + /* THE REST OF THE SAMPLER HAS NO FILE SOURCE: a generation_config.json is read for the four + * fields above and no others, so these are SamplingParams' own values unless a flag sets + * them, and request_overrides() logs the ones that did. */ + if (cfg.sample_typical_p) sp.typical_p = *cfg.sample_typical_p; + if (cfg.sample_rep_penalty) sp.rep_penalty = *cfg.sample_rep_penalty; + if (cfg.sample_pres_penalty) sp.pres_penalty = *cfg.sample_pres_penalty; + if (cfg.sample_freq_penalty) sp.freq_penalty = *cfg.sample_freq_penalty; + if (cfg.sample_penalty_last_n) sp.penalty_last_n = *cfg.sample_penalty_last_n; + if (cfg.sample_dry_multiplier) sp.dry_multiplier = *cfg.sample_dry_multiplier; + if (cfg.sample_dry_base) sp.dry_base = *cfg.sample_dry_base; + if (cfg.sample_dry_allowed_length) sp.dry_allowed_length = *cfg.sample_dry_allowed_length; + if (cfg.sample_dry_penalty_last_n) sp.dry_penalty_last_n = *cfg.sample_dry_penalty_last_n; + if (cfg.sample_dry_seq_breakers) sp.dry_seq_breakers = *cfg.sample_dry_seq_breakers; + if (cfg.sample_xtc_probability) sp.xtc_probability = *cfg.sample_xtc_probability; + if (cfg.sample_xtc_threshold) sp.xtc_threshold = *cfg.sample_xtc_threshold; + const std::string from = src.empty() ? (over.empty() ? "nothing stated it" : "the command line") : src; RAD_INFO("sampling defaults for requests that send none: %s (from %s%s%s)", @@ -1755,6 +1771,45 @@ SamplingParams resolve_sampling_defaults(const RadModelMeta& meta, bool containe "container as %s.", gen_sidecar_path(cfg.model).c_str()); return sp; } + +/* "presence_penalty 1.5, max_tokens auto, ..." -- every request default and bound the command line + * moved, under the request's spelling of the field, or "" when it moved none. The four fields + * resolve_sampling_defaults describes are not repeated. */ +std::string request_overrides(const Config& c) { + std::string out; + auto add = [&out](const std::string& s) { out += (out.empty() ? "" : ", ") + s; }; + char b[64]; + auto f = [&](const char* k, const std::optional& v) { + if (v) { snprintf(b, sizeof b, "%s %g", k, (double)*v); add(b); } + }; + auto i = [&](const char* k, const std::optional& v) { + if (v) add(std::string(k) + " " + std::to_string(*v)); + }; + f("typical_p", c.sample_typical_p); + f("presence_penalty", c.sample_pres_penalty); + f("frequency_penalty", c.sample_freq_penalty); + f("repetition_penalty", c.sample_rep_penalty); + i("repeat_last_n", c.sample_penalty_last_n); + f("dry_multiplier", c.sample_dry_multiplier); + f("dry_base", c.sample_dry_base); + i("dry_allowed_length", c.sample_dry_allowed_length); + i("dry_penalty_last_n", c.sample_dry_penalty_last_n); + if (c.sample_dry_seq_breakers) + add("dry_sequence_breakers " + std::to_string(c.sample_dry_seq_breakers->size()) + + " strings"); + f("xtc_probability", c.sample_xtc_probability); + f("xtc_threshold", c.sample_xtc_threshold); + if (c.default_max_tokens == 0) add("max_tokens auto"); + else if (c.default_max_tokens > 0) add("max_tokens " + std::to_string(c.default_max_tokens)); + if (c.max_tokens_cap > 0) add("max_tokens capped at " + std::to_string(c.max_tokens_cap)); + if (c.max_n > 0) add("n up to " + std::to_string(c.max_n)); + if (c.max_stop_strings != 64 || c.max_stop_bytes != 4096) + add("stop up to " + std::to_string(c.max_stop_strings) + " strings of " + + std::to_string(c.max_stop_bytes) + " bytes"); + for (const auto& [k, v] : c.chat_template_kwargs) add("template " + k + "=" + v); + if (c.reasoning_format != "auto") add("reasoning_format " + c.reasoning_format); + return out; +} } /* namespace */ int Engine::run_server() { /* The rank-0 sampler comes along so admission can refuse a request whose sampling stage this @@ -1967,10 +2022,37 @@ int Engine::run_server() { o.max_seqs = cfg_.max_seqs; /* `n` fans one request out over the batch, so a server that runs more sequences a step takes * more choices a request; the floor keeps a small batch from refusing what it would queue. */ - o.max_n = (int)std::max(o.max_n, cfg_.max_seqs); + o.max_n = cfg_.max_n > 0 ? (int)cfg_.max_n : (int)std::max(o.max_n, cfg_.max_seqs); o.max_ctx = cfg_.max_ctx ? cfg_.max_ctx : meta_.n_ctx_train; o.default_reasoning_effort = cfg_.reasoning_effort; o.default_sampling = resolve_sampling_defaults(meta_, file_ != nullptr, cfg_); + o.default_dry_breakers_set = cfg_.sample_dry_seq_breakers.has_value(); + /* -1 leaves ServerOptions' own default. `auto` (0) is resolved per request against the + * context, so it needs one to resolve against. */ + if (cfg_.default_max_tokens >= 0) o.default_max_tokens = cfg_.default_max_tokens; + if (o.default_max_tokens == 0 && o.max_ctx <= 0) { + RAD_ERR("--default-max-tokens auto is what the context leaves, and this model states no " + "context; pass --max-model-len"); + return RAD_E_INVAL; + } + o.max_tokens_cap = cfg_.max_tokens_cap; + o.queue_depth = cfg_.max_queued_requests; /* 0: the server's 8 x max_seqs */ + o.max_stops = cfg_.max_stop_strings; + o.max_stop_bytes = cfg_.max_stop_bytes; + o.default_template_kwargs = cfg_.chat_template_kwargs; + o.reasoning_format = cfg_.reasoning_format; + o.n_threads = cfg_.http_threads; + o.read_timeout_s = cfg_.http_read_timeout_s; + o.write_timeout_s = cfg_.http_write_timeout_s; + o.keep_alive_timeout_s = cfg_.http_keep_alive_timeout_s; + o.max_body_bytes = (size_t)cfg_.http_max_body_mib << 20; + o.retry_after_s = cfg_.retry_after_s; + o.cors = cfg_.cors; + { + const std::string moved = request_overrides(cfg_); + if (!moved.empty()) RAD_INFO("request defaults and bounds from the command line: %s", + moved.c_str()); + } o.engine_info = engine_info(); /* Per request, not once: the dump carries OpInfo::issued, which only becomes true once the * run phase has run. See ServerOptions::graph_json. */ @@ -1991,6 +2073,30 @@ int Engine::run_server() { return RAD_E_INVAL; } vc.max_patches = encd.max_patches; + /* THE COMMAND LINE OVER THE CONTAINER, field by field, and the result checked as a whole: + * a minimum stated alone can land above the maximum the container states. */ + if (cfg_.image_min_pixels) vc.image_min_pixels = *cfg_.image_min_pixels; + if (cfg_.image_max_pixels) vc.image_max_pixels = *cfg_.image_max_pixels; + if (cfg_.video_min_pixels) vc.video_min_pixels = *cfg_.video_min_pixels; + if (cfg_.video_max_pixels) vc.video_max_pixels = *cfg_.video_max_pixels; + if (cfg_.video_fps) vc.fps = *cfg_.video_fps; + if (cfg_.video_min_frames) vc.min_frames = *cfg_.video_min_frames; + if (cfg_.video_max_frames) vc.max_frames = *cfg_.video_max_frames; + if (cfg_.video_max_frame_tokens) vc.max_frame_rows = *cfg_.video_max_frame_tokens; + if (cfg_.max_source_pixels) vc.max_source_pixels = *cfg_.max_source_pixels; + if (cfg_.media_flags_set() && vc.check(&why) < 0) { + RAD_ERR("media: the media flags and what the container states disagree: %s", + why.c_str()); + return RAD_E_INVAL; + } + /* The processor lowers the image band to one encoder pass; an operator who asked for + * more is told, rather than finding the cap in the startup line below. */ + const int64_t pass_px = encd.max_patches * vc.patch * vc.patch; + if (cfg_.image_max_pixels && *cfg_.image_max_pixels > pass_px) + RAD_WARN("media: --image-max-pixels %lld is above what one encoder pass takes (%lld " + "pixels at --mm-max-patches %lld); images are resized to at most that", + (long long)*cfg_.image_max_pixels, (long long)pass_px, + (long long)encd.max_patches); if (vc.patch_dim() != encd.patch_dim || (int64_t)vc.merge * vc.merge != encd.merge) { RAD_ERR("the container's processor cuts %lld-element patches merged %lld to a row; the " "'%s' encoder takes %lld-element patches merged %lld", (long long)vc.patch_dim(), @@ -2019,7 +2125,30 @@ int Engine::run_server() { (long long)mm_proc->config().video_max_pixels); } + if (encd.modalities == 0 && cfg_.media_flags_set()) + RAD_WARN("media: the media flags do nothing here -- this model %s", + cfg_.mm_max_patches == 0 ? "is served text only (--mm-max-patches 0)" + : "takes no images or video"); + server::Server srv(d, o); + + /* A TEMPLATE DEFAULT THE TEMPLATE REFUSES is a 400 on every chat request that leaves it to + * the default, found by the first caller rather than the operator. --chat-template-kwargs + * stops startup; --reasoning-effort only warns, because a deployment whose clients all send + * their own effort serves correctly with one the template would refuse. */ + if (d.chat && (!cfg_.chat_template_kwargs.empty() || !cfg_.reasoning_effort.empty())) { + std::string kw_why, eff_why; + srv.check_template_defaults(&kw_why, &eff_why); + if (!kw_why.empty()) { + RAD_ERR("--chat-template-kwargs: the chat template refuses a request carrying them: %s", + kw_why.c_str()); + return RAD_E_INVAL; + } + if (!eff_why.empty()) + RAD_WARN("--reasoning-effort %s: the chat template refuses it, so every chat request " + "that sends no reasoning effort of its own will be answered 400: %s", + cfg_.reasoning_effort.c_str(), eff_why.c_str()); + } RAD_INFO("serving on http://%s:%d (/v1/completions%s)%s", o.host.c_str(), o.port, d.chat ? "; /v1/chat/completions with tools and reasoning" : "; chat is 501", o.api_key.empty() ? "" : " -- a bearer key is required"); diff --git a/core/mm/processor.cpp b/core/mm/processor.cpp index fab26f8d..07d4ac35 100644 --- a/core/mm/processor.cpp +++ b/core/mm/processor.cpp @@ -59,10 +59,9 @@ int VisionConfig::from_meta(const RadModelMeta& m, std::string* why) { max_frame_rows = (int32_t)rad_meta_geti(&m, "video_preprocessor.max_video_tokens", 768); read_triple(m, "preprocessor.image_mean", mean); read_triple(m, "preprocessor.image_std", stdv); - if (image_min_pixels <= 0 || image_max_pixels < image_min_pixels || video_min_pixels <= 0 || - video_max_pixels < video_min_pixels || !(fps > 0.0) || min_frames < 1 || - max_frames < min_frames) { - if (why) *why = "the container's preprocessor configuration is inconsistent"; + std::string bad; + if (check(&bad) < 0) { + if (why) *why = "the container's preprocessor configuration is inconsistent: " + bad; return RAD_E_INVAL; } for (int c = 0; c < 3; ++c) @@ -73,6 +72,27 @@ int VisionConfig::from_meta(const RadModelMeta& m, std::string* why) { return RAD_OK; } +int VisionConfig::check(std::string* why) const { + auto no = [why](const std::string& w) { + if (why) *why = w; + return RAD_E_INVAL; + }; + if (image_min_pixels <= 0) return no("image_min_pixels must be positive"); + if (image_max_pixels < image_min_pixels) + return no("image_max_pixels " + std::to_string(image_max_pixels) + " is below image_min_pixels " + + std::to_string(image_min_pixels)); + if (video_min_pixels <= 0) return no("video_min_pixels must be positive"); + if (video_max_pixels < video_min_pixels) + return no("video_max_pixels " + std::to_string(video_max_pixels) + " is below video_min_pixels " + + std::to_string(video_min_pixels)); + if (!(fps > 0.0)) return no("fps must be positive"); + if (min_frames < 1) return no("min_frames must be at least 1"); + if (max_frames < min_frames) + return no("max_frames " + std::to_string(max_frames) + " is below min_frames " + + std::to_string(min_frames)); + return RAD_OK; +} + /* ================================================================== sizes and sampling */ /* Python's round(), which is round-half-to-even on the double -- the reference computes these in diff --git a/core/mm/processor.h b/core/mm/processor.h index a03d7e19..c46f5af9 100644 --- a/core/mm/processor.h +++ b/core/mm/processor.h @@ -62,6 +62,11 @@ struct VisionConfig { /* A whole video's patch budget, across all its passes. */ int64_t max_video_patches = 0; + /* The pixel bands are non-empty and the frame counts and rate positive. RAD_OK, or + * RAD_E_INVAL with the first one that is not in `why`. from_meta runs it on what the + * container states, and the engine again after the command line has replaced some of it. */ + int check(std::string* why) const; + int64_t patch_dim() const { return 3LL * temporal * patch * patch; } int32_t factor() const { return patch * merge; } diff --git a/core/rad_core.h b/core/rad_core.h index 512052f4..541a350b 100644 --- a/core/rad_core.h +++ b/core/rad_core.h @@ -9,7 +9,9 @@ #include "rad_internal.h" #include +#include #include +#include #include #include #include @@ -673,6 +675,66 @@ struct Config { int sample_top_k = -1; float sample_top_p = -1.0f; float sample_min_p = -1.0f; + /* THE REST OF THE SAMPLER, each one the default for a request that does not name the field. + * Optional rather than negative-for-unset: a presence penalty of -1 and a DRY multiplier of + * -1 are settings a request can send, so no value of the field itself can mean "not set". + * Unset, a request that sends nothing gets SamplingParams' own value, exactly as before the + * flags existed. */ + std::optional sample_typical_p, sample_rep_penalty, sample_pres_penalty, + sample_freq_penalty, sample_dry_multiplier, sample_dry_base, + sample_xtc_probability, sample_xtc_threshold; + std::optional sample_penalty_last_n, sample_dry_allowed_length, + sample_dry_penalty_last_n; + std::optional> sample_dry_seq_breakers; + + /* --default-max-tokens: what a request that names no max_tokens may generate. -1 is unset + * (the server's 512), 0 is `auto` (whatever the context leaves after the prompt). */ + int64_t default_max_tokens = -1; + /* --max-tokens-cap: the most any request may generate. A larger max_tokens is clamped to it, + * the way the context clamps one, and the reply ends with finish_reason "length". 0 is none. */ + int64_t max_tokens_cap = 0; + /* --max-n: the largest `n` a request may ask for. 0 is the larger of 8 and --max-num-seqs. */ + int64_t max_n = 0; + /* --max-queued-requests: requests admitted and unfinished at once, beyond which the answer is + * 429. 0 is 8 x --max-num-seqs. */ + int64_t max_queued_requests = 0; + /* --max-stop-strings / --max-stop-bytes: how many stop strings a request may send, and how + * long each may be. Every stop string is searched for in every stretch of generated text, so + * these bound what one request can make that scan cost. */ + int64_t max_stop_strings = 64; + int64_t max_stop_bytes = 4096; + + /* --chat-template-kwargs: variables handed to the chat template for every chat request, as + * key -> JSON text (a string arrives still quoted, as the template context wants it). A key + * the request's own chat_template_kwargs names is the request's. */ + std::map chat_template_kwargs; + /* --reasoning-format auto|none: `auto` returns a reasoning block as reasoning_content, `none` + * leaves it inline in content for a client that reads it there. */ + std::string reasoning_format = "auto"; + + /* ---------------- THE HTTP TRANSPORT ---------------- + * The values the transport has always used, settable. See TransportOptions (server/http.h). */ + int http_threads = 0; /* 0: one per core, at least 4 */ + int http_read_timeout_s = 30; + int http_write_timeout_s = 600; + int http_keep_alive_timeout_s = 5; + int64_t http_max_body_mib = 512; + int retry_after_s = 1; + bool cors = true; + + /* ---------------- MEDIA PREPROCESSING ---------------- + * Each one replaces what the container's preprocessor configuration states (mm::VisionConfig). + * Unset, the container's value is served. */ + std::optional image_min_pixels, image_max_pixels, video_min_pixels, video_max_pixels; + std::optional video_fps; + std::optional video_min_frames, video_max_frames, video_max_frame_tokens; + std::optional max_source_pixels; + bool media_flags_set() const { + return image_min_pixels || image_max_pixels || video_min_pixels || video_max_pixels || + video_fps || video_min_frames || video_max_frames || video_max_frame_tokens || + max_source_pixels; + } + /* An operator-supplied generation_config.json, overriding the search described above. */ std::string generation_config; /* --override-chat-template: a Jinja file whose text replaces the chat template the container diff --git a/core/server/admin.cpp b/core/server/admin.cpp index a9f40eff..67677b75 100644 --- a/core/server/admin.cpp +++ b/core/server/admin.cpp @@ -155,6 +155,7 @@ HttpResponse Server::handle_tokenize(const HttpRequest& req) { ChatRenderOptions opt; opt.add_generation_prompt = get_bool_or(b, "add_generation_prompt", true); + apply_template_defaults(b, lim_, &opt); auto kw = b.find("chat_template_kwargs"); if (kw != b.end() && kw->is_object()) for (auto it = kw->begin(); it != kw->end(); ++it) @@ -273,8 +274,13 @@ HttpResponse Server::handle_server_info(const HttpRequest&) { srv["max_model_len"] = opt_.max_ctx; srv["max_num_seqs"] = opt_.max_seqs; srv["queue_cap"] = queue_depth_; - srv["default_max_tokens"] = opt_.default_max_tokens; + /* null is `--default-max-tokens auto`: what the context leaves after the prompt. */ + srv["default_max_tokens"] = opt_.default_max_tokens > 0 ? json(opt_.default_max_tokens) + : json(nullptr); + srv["max_tokens_cap"] = opt_.max_tokens_cap > 0 ? json(opt_.max_tokens_cap) : json(nullptr); srv["max_n"] = opt_.max_n; + srv["max_stop_strings"] = opt_.max_stops; + srv["max_stop_bytes"] = opt_.max_stop_bytes; srv["uptime_s"] = unix_now() - started_at_; srv["in_flight"] = in_flight_.load(std::memory_order_relaxed); @@ -289,9 +295,43 @@ HttpResponse Server::handle_server_info(const HttpRequest&) { caps["audio"] = deps_.mm && deps_.mm->accepts(MediaKind::Audio); caps["logprobs"] = opt_.supports_logprobs; + /* WHAT A REQUEST THAT LEAVES A FIELD OUT GETS, under the request's own spelling of each + * field, so a client can read off exactly what leaving one out means on this deployment. */ + const SamplingParams& sp = opt_.default_sampling; + json defs; + defs["temperature"] = sp.temp; + defs["top_k"] = sp.top_k; + defs["top_p"] = sp.top_p; + defs["min_p"] = sp.min_p; + defs["typical_p"] = sp.typical_p; + defs["presence_penalty"] = sp.pres_penalty; + defs["frequency_penalty"] = sp.freq_penalty; + defs["repetition_penalty"] = sp.rep_penalty; + defs["repeat_last_n"] = sp.penalty_last_n; + defs["dry_multiplier"] = sp.dry_multiplier; + defs["dry_base"] = sp.dry_base; + defs["dry_allowed_length"] = sp.dry_allowed_length; + defs["dry_penalty_last_n"] = sp.dry_penalty_last_n; + defs["dry_sequence_breakers"] = opt_.default_dry_breakers_set + ? json(sp.dry_seq_breakers) + : json(std::vector{ "\n", ":", "\"", "*" }); + defs["xtc_probability"] = sp.xtc_probability; + defs["xtc_threshold"] = sp.xtc_threshold; + defs["max_tokens"] = srv["default_max_tokens"]; + defs["reasoning_effort"] = opt_.default_reasoning_effort.empty() + ? json(nullptr) : json(opt_.default_reasoning_effort); + json kw = json::object(); + for (const auto& [k, v] : opt_.default_template_kwargs) { + json parsed = json::parse(v, nullptr, false); + kw[k] = parsed.is_discarded() ? json(v) : std::move(parsed); + } + defs["chat_template_kwargs"] = std::move(kw); + defs["reasoning_format"] = opt_.reasoning_format; + json o; - o["server"] = std::move(srv); - o["capabilities"] = std::move(caps); + o["server"] = std::move(srv); + o["request_defaults"] = std::move(defs); + o["capabilities"] = std::move(caps); o["endpoints"] = router_.routes(); /* Spliced rather than re-parsed field by field: the engine owns what it says about itself and diff --git a/core/server/oai.cpp b/core/server/oai.cpp index 7fc1d885..2d99034d 100644 --- a/core/server/oai.cpp +++ b/core/server/oai.cpp @@ -9,6 +9,7 @@ #include #include #include +#include #include namespace rad { @@ -201,7 +202,7 @@ const char* kAcceptedCommon[] = { const char* kAcceptedChat[] = { "messages", "tools", "tool_choice", "response_format", "top_logprobs", "parallel_tool_calls", "add_generation_prompt", "max_completion_tokens", - "chat_template_kwargs", "reasoning_effort", "enable_thinking", + "chat_template_kwargs", "reasoning_effort", "enable_thinking", "preserve_thinking", }; const char* kAcceptedCompletion[] = { "prompt", "echo" }; @@ -311,15 +312,6 @@ bool get_str(const json& b, const char* k, std::string* out, ApiError* err) { return true; } -bool range(double v, double lo, double hi, const char* k, ApiError* err) { - if (v < lo || v > hi) { - char b[160]; - snprintf(b, sizeof b, "must be in [%g, %g], got %g", lo, hi, v); - *err = err_bad(k, b); - return false; - } - return true; -} /* The body of every generation endpoint: one JSON object, parsed into a bounded tree. */ int parse_request_object(const std::string& body, const OaiLimits& lim, json* b, ApiError* err) { @@ -349,10 +341,68 @@ int parse_request_object(const std::string& body, const OaiLimits& lim, json* b, /* ================================================================== sampling params */ +namespace { + +/* One row per bounded sampler field. `lo_open` excludes the lower bound; `hi` of infinity is no + * upper bound. `why` is the refusal when the range alone does not say it well, and null for a + * closed interval, whose refusal names the interval and the value. */ +struct SamplerRange { + const char* field; + double lo, hi; + bool lo_open; + const char* why; +}; + +constexpr double kInf = std::numeric_limits::infinity(); + +const SamplerRange kSamplerRanges[] = { + { "temperature", 0.0, 2.0, false, nullptr }, + { "top_p", 0.0, 1.0, true, "must be in (0, 1]" }, + { "top_k", 0.0, kInf, false, "must be >= 0 (0 disables it)" }, + { "min_p", 0.0, 1.0, false, nullptr }, + { "typical_p", 0.0, 1.0, true, "must be in (0, 1]" }, + { "presence_penalty", -2.0, 2.0, false, nullptr }, + { "frequency_penalty", -2.0, 2.0, false, nullptr }, + { "repetition_penalty", 0.0, kInf, true, "must be > 0" }, + { "repeat_last_n", -1.0, kInf, false, "must be >= -1" }, + { "xtc_probability", 0.0, 1.0, false, nullptr }, + { "xtc_threshold", 0.0, 1.0, false, nullptr }, + { "dry_base", 1.0, kInf, false, "must be >= 1" }, + { "dry_penalty_last_n", -1.0, kInf, false, "must be >= -1" }, +}; + +} /* namespace */ + +/* Written as "inside the range" and negated, so a NaN -- which a flag can parse and JSON cannot + * carry -- fails every row rather than passing them all. */ +bool sampler_value_ok(const char* field, double v, std::string* why) { + for (const SamplerRange& r : kSamplerRanges) { + if (std::strcmp(r.field, field)) continue; + const bool in = (r.lo_open ? v > r.lo : v >= r.lo) && v <= r.hi; + if (in) return true; + if (why) { + if (r.why) *why = r.why; + else { + char b[160]; + snprintf(b, sizeof b, "must be in [%g, %g], got %g", r.lo, r.hi, v); + *why = b; + } + } + return false; + } + return true; +} + static int parse_sampling(const json& b, const OaiLimits& lim, OaiRequest* r, ApiError* err) { double d; int64_t i64; bool bl; + auto ok = [err](const char* k, double v) { + std::string why; + if (sampler_value_ok(k, v, &why)) return true; + *err = err_bad(k, why); + return false; + }; /* THE DEPLOYMENT'S DEFAULTS ARE THE SEED, and every field below reads its current value * before looking for one in the body -- so a field the request names overrides, and a field @@ -363,57 +413,57 @@ static int parse_sampling(const json& b, const OaiLimits& lim, OaiRequest* r, Ap d = r->sp.temp; if (!get_num(b, "temperature", &d, err)) return RAD_E_INVAL; - if (!range(d, 0.0, 2.0, "temperature", err)) return RAD_E_INVAL; + if (!ok("temperature", d)) return RAD_E_INVAL; r->sp.temp = (float)d; d = r->sp.top_p; if (!get_num(b, "top_p", &d, err)) return RAD_E_INVAL; - if (d <= 0.0 || d > 1.0) { *err = err_bad("top_p", "must be in (0, 1]"); return RAD_E_INVAL; } + if (!ok("top_p", d)) return RAD_E_INVAL; r->sp.top_p = (float)d; i64 = r->sp.top_k; if (!get_int(b, "top_k", &i64, err)) return RAD_E_INVAL; - if (i64 < 0) { *err = err_bad("top_k", "must be >= 0 (0 disables it)"); return RAD_E_INVAL; } + if (!ok("top_k", (double)i64)) return RAD_E_INVAL; r->sp.top_k = (int)i64; d = r->sp.min_p; if (!get_num(b, "min_p", &d, err)) return RAD_E_INVAL; - if (!range(d, 0.0, 1.0, "min_p", err)) return RAD_E_INVAL; + if (!ok("min_p", d)) return RAD_E_INVAL; r->sp.min_p = (float)d; d = r->sp.typical_p; if (!get_num(b, "typical_p", &d, err)) return RAD_E_INVAL; - if (d <= 0.0 || d > 1.0) { *err = err_bad("typical_p", "must be in (0, 1]"); return RAD_E_INVAL; } + if (!ok("typical_p", d)) return RAD_E_INVAL; r->sp.typical_p = (float)d; d = r->sp.pres_penalty; if (!get_num(b, "presence_penalty", &d, err)) return RAD_E_INVAL; - if (!range(d, -2.0, 2.0, "presence_penalty", err)) return RAD_E_INVAL; + if (!ok("presence_penalty", d)) return RAD_E_INVAL; r->sp.pres_penalty = (float)d; d = r->sp.freq_penalty; if (!get_num(b, "frequency_penalty", &d, err)) return RAD_E_INVAL; - if (!range(d, -2.0, 2.0, "frequency_penalty", err)) return RAD_E_INVAL; + if (!ok("frequency_penalty", d)) return RAD_E_INVAL; r->sp.freq_penalty = (float)d; d = r->sp.rep_penalty; if (!get_num(b, "repetition_penalty", &d, err)) return RAD_E_INVAL; - if (d <= 0.0) { *err = err_bad("repetition_penalty", "must be > 0"); return RAD_E_INVAL; } + if (!ok("repetition_penalty", d)) return RAD_E_INVAL; r->sp.rep_penalty = (float)d; i64 = r->sp.penalty_last_n; if (!get_int(b, "repeat_last_n", &i64, err)) return RAD_E_INVAL; - if (i64 < -1) { *err = err_bad("repeat_last_n", "must be >= -1"); return RAD_E_INVAL; } + if (!ok("repeat_last_n", (double)i64)) return RAD_E_INVAL; r->sp.penalty_last_n = (int)i64; d = r->sp.xtc_probability; if (!get_num(b, "xtc_probability", &d, err)) return RAD_E_INVAL; - if (!range(d, 0.0, 1.0, "xtc_probability", err)) return RAD_E_INVAL; + if (!ok("xtc_probability", d)) return RAD_E_INVAL; r->sp.xtc_probability = (float)d; d = r->sp.xtc_threshold; if (!get_num(b, "xtc_threshold", &d, err)) return RAD_E_INVAL; - if (!range(d, 0.0, 1.0, "xtc_threshold", err)) return RAD_E_INVAL; + if (!ok("xtc_threshold", d)) return RAD_E_INVAL; r->sp.xtc_threshold = (float)d; d = r->sp.dry_multiplier; @@ -421,14 +471,14 @@ static int parse_sampling(const json& b, const OaiLimits& lim, OaiRequest* r, Ap r->sp.dry_multiplier = (float)d; d = r->sp.dry_base; if (!get_num(b, "dry_base", &d, err)) return RAD_E_INVAL; - if (d < 1.0) { *err = err_bad("dry_base", "must be >= 1"); return RAD_E_INVAL; } + if (!ok("dry_base", d)) return RAD_E_INVAL; r->sp.dry_base = (float)d; i64 = r->sp.dry_allowed_length; if (!get_int(b, "dry_allowed_length", &i64, err)) return RAD_E_INVAL; r->sp.dry_allowed_length = (int)i64; i64 = r->sp.dry_penalty_last_n; if (!get_int(b, "dry_penalty_last_n", &i64, err)) return RAD_E_INVAL; - if (i64 < -1) { *err = err_bad("dry_penalty_last_n", "must be >= -1"); return RAD_E_INVAL; } + if (!ok("dry_penalty_last_n", (double)i64)) return RAD_E_INVAL; r->sp.dry_penalty_last_n = (int)i64; /* ABSENT MEANS llama.cpp's FOUR, not none. A client that turns DRY on and names no breakers @@ -437,7 +487,8 @@ static int parse_sampling(const json& b, const OaiLimits& lim, OaiRequest* r, Ap * with DRY off: the sampler resolves breakers only for a request that runs DRY. */ auto dsb = b.find("dry_sequence_breakers"); if (dsb == b.end() || dsb->is_null()) { - if (r->sp.dry_seq_breakers.empty()) r->sp.dry_seq_breakers = { "\n", ":", "\"", "*" }; + if (r->sp.dry_seq_breakers.empty() && !lim.default_dry_breakers_set) + r->sp.dry_seq_breakers = { "\n", ":", "\"", "*" }; } else { r->sp.dry_seq_breakers.clear(); if (!dsb->is_array()) { @@ -500,14 +551,15 @@ static int parse_sampling(const json& b, const OaiLimits& lim, OaiRequest* r, Ap * text a choice produces -- by the decoder and again by the server's own scan -- so what one * request costs per token is its number of stop strings times the longest of them. OpenAI * allows four. The bounds here are far past anything a client sends and exist so that no - * request can buy that scan without limit. */ - constexpr size_t kMaxStops = 64, kMaxStopBytes = 4096; + * request can buy that scan without limit. The deployment may move them (--max-stop-strings, + * --max-stop-bytes). */ + const size_t max_stops = (size_t)lim.max_stops, max_stop_bytes = (size_t)lim.max_stop_bytes; auto st = b.find("stop"); if (st != b.end() && !st->is_null()) { if (st->is_string()) r->stop.push_back(st->get()); else if (st->is_array()) { - if (st->size() > kMaxStops) { - *err = err_bad("stop", "at most " + std::to_string(kMaxStops) + + if (st->size() > max_stops) { + *err = err_bad("stop", "at most " + std::to_string(max_stops) + " stop strings are accepted, got " + std::to_string(st->size())); return RAD_E_INVAL; @@ -524,9 +576,9 @@ static int parse_sampling(const json& b, const OaiLimits& lim, OaiRequest* r, Ap return RAD_E_INVAL; } for (const auto& s : r->stop) { - if (s.size() > kMaxStopBytes) { + if (s.size() > max_stop_bytes) { *err = err_bad("stop", "a stop string may be at most " + - std::to_string(kMaxStopBytes) + " bytes, got one of " + + std::to_string(max_stop_bytes) + " bytes, got one of " + std::to_string(s.size())); return RAD_E_INVAL; } @@ -563,15 +615,54 @@ static int parse_sampling(const json& b, const OaiLimits& lim, OaiRequest* r, Ap * caller who sends the kwarg and nothing else has it silently overwritten with the default true, * and sees the model think anyway -- a 200 that did not honour the request, which is the one * outcome this file's header forbids. Lifting the kwarg into the field is what makes it real. + * + * THE DEPLOYMENT'S DEFAULTS GO IN FIRST AND THE REQUEST OVERWRITES THEM, key by key -- except that + * thinking is one setting with three spellings, and a default in one spelling must not survive a + * request that used another. A request that says anything about thinking (either enable_thinking, + * or a reasoning effort) drops the deployment's enable_thinking; one that names an effort drops + * the deployment's effort too. Otherwise `--chat-template-kwargs '{"enable_thinking":false}'` + * would turn off thinking for a caller who sent `reasoning_effort: "high"`, and + * `--reasoning-effort none` would do the same to one who sent `enable_thinking: true`. */ +RequestThinking request_thinking(const json& b) { + auto kw = b.find("chat_template_kwargs"); + const bool obj = kw != b.end() && kw->is_object(); + auto top = b.find("enable_thinking"); + /* An empty reasoning_effort string reads as unset, so it names no effort either. */ + auto re = b.find("reasoning_effort"); + RequestThinking t; + t.effort = (obj && kw->contains("reasoning_effort")) || + (re != b.end() && re->is_string() && !re->get().empty()); + t.thinking = t.effort || (top != b.end() && !top->is_null()) || + (obj && kw->contains("enable_thinking")); + return t; +} + +void apply_template_defaults(const json& b, const OaiLimits& lim, ChatRenderOptions* opt) { + const RequestThinking says = request_thinking(b); + for (const auto& [k, v] : lim.default_template_kwargs) { + if (k == "enable_thinking") { + if (says.thinking) continue; + opt->enable_thinking = v == "true"; + } + if (k == "reasoning_effort" && says.effort) continue; + opt->template_kwargs[k] = v; + } + opt->reasoning_format = lim.reasoning_format; +} + static int parse_thinking(const json& b, const OaiLimits& lim, ChatRenderOptions* opt, ApiError* err) { auto kw = b.find("chat_template_kwargs"); - if (kw != b.end() && !kw->is_null()) { - if (!kw->is_object()) { - *err = err_bad("chat_template_kwargs", "expected an object"); - return RAD_E_INVAL; - } + const bool has_kw = kw != b.end() && !kw->is_null(); + if (has_kw && !kw->is_object()) { + *err = err_bad("chat_template_kwargs", "expected an object"); + return RAD_E_INVAL; + } + const RequestThinking says = request_thinking(b); + apply_template_defaults(b, lim, opt); + + if (has_kw) { for (auto it = kw->begin(); it != kw->end(); ++it) { /* dump(), not get(): the template context wants JSON, so a string value has * to arrive still quoted. See ChatRenderOptions. */ @@ -590,6 +681,21 @@ static int parse_thinking(const json& b, const OaiLimits& lim, ChatRenderOptions if (!get_bool(b, "enable_thinking", &think, err)) return RAD_E_INVAL; opt->enable_thinking = think; + /* `preserve_thinking` AT THE TOP LEVEL is the template variable of that name, the same + * shorthand `enable_thinking` is: llama.cpp maps the field into the template, and clients + * written against it (oh-my-pi, for every Qwen model) send it there as well as in + * chat_template_kwargs. The Qwen3.6 and later templates read it to keep earlier assistant + * turns' reasoning in the prompt; a template that does not read it ignores it, as it ignores + * any variable it does not name. Like enable_thinking, the top-level spelling wins. */ + auto pt = b.find("preserve_thinking"); + if (pt != b.end() && !pt->is_null()) { + if (!pt->is_boolean()) { + *err = err_bad("preserve_thinking", "expected a boolean"); + return RAD_E_INVAL; + } + opt->template_kwargs["preserve_thinking"] = pt->dump(); + } + /* REASONING EFFORT IS THE TEMPLATE'S VOCABULARY, NOT OURS, so there is no allow-list here. * One would be wrong in both directions: OpenAI's ladder is none/minimal/low/medium/high, * while a model's template may accept a different set -- Qwen3.8's takes xhigh/medium/low and @@ -607,8 +713,14 @@ static int parse_thinking(const json& b, const OaiLimits& lim, ChatRenderOptions std::string effort; if (!get_str(b, "reasoning_effort", &effort, err)) return RAD_E_INVAL; /* The deployment's default, where the request did not say. Last, so every explicit spelling - * above it wins; emplace, so a chat_template_kwargs entry that already set the key stands. */ - if (effort.empty()) effort = lim.default_reasoning_effort; + * above it wins; emplace, so a chat_template_kwargs entry that already set the key stands. + * "none" and "minimal" are an enable_thinking default, so any word about thinking drops them; + * a level is an effort default, dropped by an effort. */ + if (effort.empty()) { + const std::string& def = lim.default_reasoning_effort; + const bool off = def == "none" || def == "minimal"; + if (off ? !says.thinking : !says.effort) effort = def; + } if (!effort.empty()) { if (effort == "none" || effort == "minimal") opt->enable_thinking = false; else opt->template_kwargs.emplace("reasoning_effort", json(effort).dump()); @@ -1005,8 +1117,16 @@ static int tokenize_with_media(const std::string& rendered, const OaiDeps& d, * anyway. What the caller gets back still says so: the completion ends with finish_reason * "length" and `usage` reports the tokens it actually produced. */ +/* THE DEPLOYMENT'S CAP IS A THIRD BOUND OF THE SAME KIND, clamped for the same reason: a request + * asking for more than the operator allows is still a request worth serving up to the cap. And a + * max_tokens of 0 is the `--default-max-tokens auto` default, which is "what the context leaves" -- + * resolved here, against this prompt, so that the scheduler always sees a finite bound. */ static int clamp_max_tokens(size_t n_prompt, const OaiLimits& lim, const char* field, OaiRequest* out, ApiError* err) { + if (lim.max_tokens_cap > 0 && + (out->max_tokens <= 0 || (int64_t)out->max_tokens > lim.max_tokens_cap)) + out->max_tokens = (int32_t)lim.max_tokens_cap; + if (lim.max_ctx <= 0) return RAD_OK; /* no bound declared, nothing to clamp against */ const int64_t room = lim.max_ctx - (int64_t)n_prompt; @@ -1021,7 +1141,9 @@ static int clamp_max_tokens(size_t n_prompt, const OaiLimits& lim, const char* f return RAD_E_INVAL; } - if ((int64_t)out->max_tokens > room) { + if (out->max_tokens <= 0) { + out->max_tokens = (int32_t)std::min(room, INT32_MAX); + } else if ((int64_t)out->max_tokens > room) { /* Debug rather than Warn: on a long-context deployment whose clients send a constant * max_tokens this fires on every request that is working correctly, and a line printed * per request is how a server's log stops being read at all. */ diff --git a/core/server/oai.h b/core/server/oai.h index 2cf70071..a9893655 100644 --- a/core/server/oai.h +++ b/core/server/oai.h @@ -21,6 +21,7 @@ #include "sink.h" #include +#include #include #include #include @@ -107,8 +108,15 @@ struct OaiRequest { struct OaiLimits { std::string model_id = "radiance"; int64_t max_ctx = 0; /* 0 = unknown, no length check */ + /* What a request that names no max_tokens may generate. 0 is "whatever the context leaves", + * resolved against the prompt in clamp_max_tokens. */ int64_t default_max_tokens = 512; + /* The most any request may generate; a larger max_tokens is clamped, not refused. 0 = none. */ + int64_t max_tokens_cap = 0; int max_n = 8; + /* How many stop strings a request may send, and how long each may be. */ + int64_t max_stops = 64; + int64_t max_stop_bytes = 4096; bool allow_image = false; bool allow_video = false; bool allow_audio = false; @@ -137,8 +145,40 @@ struct OaiLimits { * after this is copied. A request that names a field always wins, exactly as with * default_reasoning_effort. */ SamplingParams default_sampling; + /* SamplingParams cannot tell an empty breaker list that was stated from one that was not, and + * the two mean different things: unstated is llama-server's four, stated-empty is none. */ + bool default_dry_breakers_set = false; + + /* THE DEPLOYMENT'S CHAT TEMPLATE VARIABLES, key -> JSON text, applied under the request's own + * chat_template_kwargs so a key the request names is the request's. The thinking keys follow + * parse_thinking's rule: a request that says anything about thinking replaces them whole. */ + std::map default_template_kwargs; + /* "auto" returns reasoning as reasoning_content; "none" leaves it inline in content. */ + std::string reasoning_format = "auto"; }; +/* WHAT A REQUEST SAYS ABOUT THINKING, in any of its three spellings: `effort` when it names a + * reasoning effort (top-level or in chat_template_kwargs, non-empty), `thinking` when it says + * anything at all -- an effort, or enable_thinking in either place. */ +struct RequestThinking { + bool thinking = false; + bool effort = false; +}; +RequestThinking request_thinking(const json& b); + +/* The deployment's template variables and reply format, onto `opt`, before the request's own + * chat_template_kwargs are written over them. A request that says anything about thinking keeps + * the deployment's enable_thinking out; one that names an effort keeps its reasoning_effort out. + * The chat endpoint and /tokenize both render through this, so a prompt counted by one is the + * prompt served by the other. */ +void apply_template_defaults(const json& b, const OaiLimits& lim, ChatRenderOptions* opt); + +/* True when `v` is a legal value of the sampler field a request spells `field`; otherwise `why` + * says what the legal set is, in the words a 400 carries. The same table checks a request and the + * command-line flag that sets the field's default, so a default the command line accepts is one + * every request omitting the field can be served with. A field with no bounds takes any value. */ +bool sampler_value_ok(const char* field, double v, std::string* why); + struct OaiDeps { ITokenizer* tok = nullptr; IChatTemplate* chat = nullptr; diff --git a/core/server/server.cpp b/core/server/server.cpp index 8468093a..6bd5bf3f 100644 --- a/core/server/server.cpp +++ b/core/server/server.cpp @@ -47,13 +47,19 @@ Server::Server(const Deps& d, const ServerOptions& o) lim_.model_id = opt_.model_id; lim_.max_ctx = opt_.max_ctx; lim_.default_max_tokens = opt_.default_max_tokens; + lim_.max_tokens_cap = opt_.max_tokens_cap; lim_.max_n = opt_.max_n; + lim_.max_stops = opt_.max_stops; + lim_.max_stop_bytes = opt_.max_stop_bytes; lim_.allow_image = opt_.allow_image; lim_.allow_video = opt_.allow_video; lim_.allow_audio = opt_.allow_audio; lim_.supports_logprobs = opt_.supports_logprobs; lim_.default_reasoning_effort = opt_.default_reasoning_effort; lim_.default_sampling = opt_.default_sampling; + lim_.default_dry_breakers_set = opt_.default_dry_breakers_set; + lim_.default_template_kwargs = opt_.default_template_kwargs; + lim_.reasoning_format = opt_.reasoning_format; odeps_.tok = deps_.tok; odeps_.chat = deps_.chat; @@ -158,9 +164,35 @@ int Server::run() { t.max_queued = kSpareWorkers; t.api_key = opt_.api_key; t.cors = opt_.cors; + t.read_timeout_s = opt_.read_timeout_s; + t.write_timeout_s = opt_.write_timeout_s; + t.keep_alive_timeout_s = opt_.keep_alive_timeout_s; + t.max_body_bytes = opt_.max_body_bytes; return transport_.serve(router_, t); } +void Server::check_template_defaults(std::string* kwargs_why, std::string* effort_why) const { + kwargs_why->clear(); + effort_why->clear(); + if (!deps_.chat) return; + const std::string body = R"({"messages":[{"role":"user","content":"Hello"}],"max_tokens":1})"; + auto render = [&](const OaiLimits& l, std::string* why) { + OaiRequest r; + ApiError e; + if (parse_chat_request(body, odeps_, l, &r, &e) >= 0) return true; + if (why) *why = e.message; + return false; + }; + OaiLimits l = lim_; + l.default_template_kwargs.clear(); + l.default_reasoning_effort.clear(); + if (!render(l, nullptr)) return; + l.default_template_kwargs = lim_.default_template_kwargs; + if (!l.default_template_kwargs.empty() && !render(l, kwargs_why)) return; + l.default_reasoning_effort = lim_.default_reasoning_effort; + if (!l.default_reasoning_effort.empty()) render(l, effort_why); +} + void Server::stop() { stopping_.store(true); transport_.stop(); diff --git a/core/server/server.h b/core/server/server.h index 03e45c32..fded2f99 100644 --- a/core/server/server.h +++ b/core/server/server.h @@ -66,8 +66,11 @@ struct ServerOptions { int retry_after_s = 1; int64_t max_ctx = 0; - int64_t default_max_tokens = 512; + int64_t default_max_tokens = 512; /* 0: what the context leaves (OaiLimits) */ + int64_t max_tokens_cap = 0; /* 0: none */ int max_n = 8; + int64_t max_stops = 64; + int64_t max_stop_bytes = 4096; bool supports_logprobs = false; /* The deployment default for `reasoning_effort`, empty for the template's own. See @@ -76,6 +79,10 @@ struct ServerOptions { /* What a request that sends no sampler fields is served with. See * OaiLimits::default_sampling; only the sampler knobs are read from it. */ SamplingParams default_sampling; + bool default_dry_breakers_set = false; + /* The deployment's chat template variables and reply format. See OaiLimits. */ + std::map default_template_kwargs; + std::string reasoning_format = "auto"; bool allow_image = false; bool allow_video = false; bool allow_audio = false; @@ -104,6 +111,12 @@ struct ServerOptions { std::string api_key; bool cors = true; + + /* The transport's timeouts and body bound. See TransportOptions. */ + int read_timeout_s = 30; + int write_timeout_s = 600; + int keep_alive_timeout_s = 5; + size_t max_body_bytes = 512ull << 20; }; class Server { @@ -120,6 +133,14 @@ public: const Router& router() const { return router_; } int run(); /* binds, serves, blocks. RAD_OK or negative. */ + + /* THE DEPLOYMENT'S TEMPLATE DEFAULTS, RENDERED ONCE BEFORE A CALLER DEPENDS ON THEM. A value + * the chat template refuses is a 400 on every request that leaves it to the default, so a + * one-message chat is parsed exactly as a request would be: first with no template defaults, + * then with the --chat-template-kwargs ones, then with the --reasoning-effort one as well. + * A render that fails at the first step says nothing about the defaults and is not reported. + * `kwargs_why` / `effort_why` are left empty, or hold the template's refusal at that step. */ + void check_template_defaults(std::string* kwargs_why, std::string* effort_why) const; void stop(); int port() const { return transport_.port(); } /* 0 until run() is accepting */ diff --git a/core/text/chatfmt.cpp b/core/text/chatfmt.cpp index 2f7f69bb..837e30f3 100644 --- a/core/text/chatfmt.cpp +++ b/core/text/chatfmt.cpp @@ -640,11 +640,11 @@ int chat_format_grammar(const ChatFormat& f, const ChatGrammarRequest& req, Chat std::vector req_arms, opt_arms; for (const auto& [pname, pschema] : properties.items()) { - /* An optional argument no value satisfies -- `false`, or `{"not": {}}`, an - * Arktype or TypeBox `never` -- is one no call writes, so it gets no arm; a - * model that writes it anyway reaches the undeclared arm below. The template - * path does the same (vendor/patches/0012); required, it goes through the - * schema and is refused there by name. */ + /* An optional argument no value satisfies -- `false`, or the `not` of a schema + * every value satisfies, an Arktype or TypeBox `never` -- is one no call + * writes, so it gets no arm; a model that writes it anyway reaches the + * undeclared arm below. The template path does the same (vendor/patches/0012, + * 0014); required, it goes through the schema and is refused there by name. */ if (!required.count(pname) && info.unsatisfiable(pschema)) continue; G value; if (f.other_value != ChatValue::Json || info.resolves_to_string(pschema)) { diff --git a/docs/GUIDE.md b/docs/GUIDE.md index 75ddb5bb..ab35924c 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -710,30 +710,85 @@ blocks alone leaves the session re-running every linear layer over its whole tra every hit-rate counter reports as a hit. `/sessions` shows what is stored, where, and whether the linear half is being served. -### 4.9 What a request that sets no sampler fields gets +### 4.9 What a request that leaves a field out gets -Resolution order, first one that exists wins: +Every default below applies only to a request that does not name the field. A request that names +it wins. Without any of these flags, the server behaves exactly as it always has. + +**Temperature, top-k, top-p, min-p.** First one that exists wins: 1. `--temp` / `--top-k` / `--top-p` / `--min-p` on the command line 2. `--generation-config PATH` โ€” a `generation_config.json` -3. the container's own `generation.*` metadata -4. `.generation.json` beside the container +3. `.generation.json` beside the container +4. the container's own `generation.*` metadata 5. the built-in defaults ```sh radiance --model m.rad --temp 0.7 --top-p 0.8 --top-k 20 ``` +**The rest of the sampler** has a flag per field, spelled like the request field: +`--presence-penalty`, `--frequency-penalty`, `--repetition-penalty`, `--repeat-last-n`, +`--typical-p`, `--dry-multiplier`, `--dry-base`, `--dry-allowed-length`, `--dry-penalty-last-n`, +`--dry-sequence-breakers` (a JSON array), `--xtc-probability`, `--xtc-threshold`. They are checked +against the same ranges a request is, at startup: + +```sh +radiance --model m.rad --presence-penalty 1.5 --repetition-penalty 1.05 +``` + +**How much a request may generate.** + +- `--default-max-tokens N` sets `max_tokens` for a request that sends none. The default is 512. + `auto` means whatever the context leaves after the prompt. +- `--max-tokens-cap N` is the most any request may generate. A larger `max_tokens` is cut to it + rather than refused, and the reply ends with `finish_reason: "length"`, the same as the context + bound (ยง5.8). + +```sh +radiance --model m.rad --default-max-tokens auto --max-tokens-cap 32768 +``` + +**Chat template variables.** `--chat-template-kwargs` hands variables to the chat template on +every chat request, the way a request's own `chat_template_kwargs` does: + +```sh +radiance --model m.rad --chat-template-kwargs '{"enable_thinking": false}' +radiance --model m.rad --chat-template-kwargs @template-vars.json +``` + +- It takes a JSON object, or `@FILE` to read one. Give it more than once and a later key replaces + an earlier one. +- A key the request's own `chat_template_kwargs` names is the request's. +- Thinking is one setting with three spellings. A request that says anything about thinking + (`enable_thinking`, at the top level or in `chat_template_kwargs`, or `reasoning_effort`) + replaces the server's `enable_thinking`. One that names a `reasoning_effort` replaces the + server's effort too. +- `messages`, `tools`, `bos_token`, `eos_token` and `add_generation_prompt` are refused: the + server sets those itself. +- At startup a one-message chat is rendered with the variables. A value the template refuses + stops startup with the template's own message, instead of failing every request. +- `/tokenize` renders `messages` with the same variables, so the count it gives is the prompt + chat serves. + **`--reasoning-effort` is worth knowing about.** It is the default for chat requests that do not set one, and the value goes to the model's chat template verbatim โ€” so the legal set is the template's. Qwen3.8 takes `xhigh|medium|low` and **defaults to `xhigh`**, which on a short task can spend the entire token budget inside `` and return a turn with empty content and -`finish_reason: "length"`. `"none"` turns thinking off. +`finish_reason: "length"`. `"none"` turns thinking off. It cannot be combined with a +`reasoning_effort` or `enable_thinking` key in `--chat-template-kwargs`. A value the template +refuses is a warning at startup: requests that send their own effort still work. ```sh radiance --model m.rad --reasoning-effort medium ``` +**`--reasoning-format none`** leaves a reasoning block inline in `content` instead of returning it +as `reasoning_content`, for a client that reads it there. + +`/server_info` lists every effective default under `request_defaults` (ยง6.2), and startup prints +one line naming each one the command line moved. + ### 4.10 Every flag `radiance --help` prints this table. Grouped here by what you are doing: @@ -809,10 +864,48 @@ radiance --model m.rad --reasoning-effort medium | `--api-key KEY` | โ€” | require `Authorization: Bearer KEY` on every request but `/health`, `/ping` and the dashboard page (ยง6.6) | | `--served-model-name NAME` | container's name | the model id `/v1/models` lists, the metrics carry and a response names when its request named none. A request may name any model; the one loaded serves it | | `--mm-max-patches N` | auto | patches one vision-encoder pass carries, and so the largest image (a patch is 16x16 pixels). `auto` is 16384 when the container carries a vision tower; 0 serves text only and keeps the tower off the card | -| `--generation-config PATH` | โ€” | sampler defaults from a `generation_config.json` | | `--override-chat-template PATH` | container's | a Jinja chat template file served in place of the one the container carries. The reply format (reasoning markers, tool calls) is derived from it too, unless the architecture plugin declares one. An unreadable or empty file stops startup | +| `--max-queued-requests N` | 8 ร— `--max-num-seqs` | requests admitted and unfinished at once; past it, 429 | +| `--http-threads N` | one per core, at least 4 | HTTP workers kept while idle | +| `--read-timeout S` | 30 | seconds a client may go silent while sending a request | +| `--write-timeout S` | 600 | seconds one write to a client may block | +| `--keep-alive-timeout S` | 5 | seconds an idle connection is held open between requests | +| `--max-body-mib N` | 512 | the largest request body; images and video arrive base64 inside it | +| `--retry-after S` | 1 | the `Retry-After` a 429 carries | +| `--no-cors` | CORS on | send no CORS headers (ยง6.6) | + +**Request defaults and bounds** โ€” what a request that leaves a field out gets (ยง4.9). A request +that names the field wins. + +| flag | default | | +|---|---|---| +| `--generation-config PATH` | โ€” | sampler defaults from a `generation_config.json` | | `--temp F`, `--top-k N`, `--top-p F`, `--min-p F` | from container | sampler defaults | +| `--presence-penalty F`, `--frequency-penalty F` | 0 | [-2, 2] | +| `--repetition-penalty F`, `--repeat-last-n N` | 1, 64 | > 0; โ‰ฅ -1 (-1 is all) | +| `--typical-p F` | 1 | (0, 1] | +| `--dry-multiplier F`, `--dry-base F`, `--dry-allowed-length N`, `--dry-penalty-last-n N` | 0, 1.75, 2, -1 | DRY; a multiplier of 0 is off | +| `--dry-sequence-breakers JSON` | `["\n", ":", "\"", "*"]` | a JSON array of at most 16 strings | +| `--xtc-probability F`, `--xtc-threshold F` | 0, 0.1 | [0, 1] | +| `--default-max-tokens N` | 512 | `max_tokens` for a request that sends none; `auto` is what the context leaves | +| `--max-tokens-cap N` | none | the most any request may generate; a larger `max_tokens` is cut to it, not refused | +| `--max-n N` | the larger of 8 and `--max-num-seqs` | the largest `n` a request may ask for | +| `--max-stop-strings N`, `--max-stop-bytes N` | 64, 4096 | how many stop strings a request may send, and how long each may be | +| `--chat-template-kwargs JSON` | โ€” | variables for the chat template on every chat request; a JSON object or `@FILE`, repeatable | | `--reasoning-effort S` | template's own | default `reasoning_effort` for chat | +| `--reasoning-format MODE` | auto | `auto` returns reasoning as `reasoning_content`; `none` leaves it inline in `content` | + +**Media** โ€” each replaces what the container's preprocessor configuration states. They do nothing +for a model that takes no images or video. + +| flag | default | | +|---|---|---| +| `--image-min-pixels N`, `--image-max-pixels N` | container's | the band an image is resized into; one encoder pass (`--mm-max-patches`) still bounds the top | +| `--video-min-pixels N`, `--video-max-pixels N` | container's | the same for a video's sampled frames together | +| `--video-fps F` | container's, else 2 | frames sampled per second of video | +| `--video-min-frames N`, `--video-max-frames N` | container's, else 4 and 768 | the fewest and most frames sampled from a video | +| `--video-max-frame-tokens N` | container's, else 768 | the most prompt tokens one frame may become; 0 is no cap | +| `--max-source-pixels N` | 67108864 | the largest image or frame the decoder accepts, before any resize | **Quality measurement** โ€” instead of serving; see [TOOLS.md](TOOLS.md#the-kl-mode) @@ -999,7 +1092,7 @@ curl -s http://localhost:8000/detokenize -H 'Content-Type: application/json' \ |---|---| | `model` | accepted and not enforced โ€” one server serves one model | | `messages` / `prompt` / `input` | chat / completion / embedding | -| `max_tokens`, `max_completion_tokens` | default 512. Clamped to what the context leaves rather than refused โ€” see ยง5.8 | +| `max_tokens`, `max_completion_tokens` | default 512 (`--default-max-tokens`). Clamped to what the context leaves, and to `--max-tokens-cap`, rather than refused โ€” see ยง5.8 | | `temperature` | [0, 2] | | `top_p` | (0, 1] | | `top_k` | โ‰ฅ 0, 0 disables | @@ -1009,15 +1102,16 @@ curl -s http://localhost:8000/detokenize -H 'Content-Type: application/json' \ | `xtc_probability`, `xtc_threshold` | | | `dry_multiplier`, `dry_base`, `dry_allowed_length`, `dry_penalty_last_n`, `dry_sequence_breakers` | | | `seed` | absent means "pick one" โ€” **not** seed 0 | -| `n` | 1 to the larger of 8 and `--max-num-seqs`. Fan-out over the same prompt; the prefix cache makes it nearly free after the first | +| `n` | 1 to `--max-n`, by default the larger of 8 and `--max-num-seqs`. Fan-out over the same prompt; the prefix cache makes it nearly free after the first | | `priority` | | -| `stop` | a string or an array | +| `stop` | a string or an array; at most 64 strings of 4096 bytes (`--max-stop-strings`, `--max-stop-bytes`) | | `ignore_eos` | generate to `max_tokens` whatever the model emits | | `stream`, `stream_options.include_usage` | | | `logprobs`, `top_logprobs` | **not implemented** โ€” refused, not returned as nulls. `/server_info` reports `logprobs: false` | | `tools`, `tool_choice`, `parallel_tool_calls` | chat only | | `add_generation_prompt`, `chat_template_kwargs` | chat only | | `reasoning_effort`, `enable_thinking` | chat only | +| `preserve_thinking` | chat only. The chat template variable of that name, as llama.cpp maps it; Qwen3.6 and later keep earlier turns' reasoning in the prompt with it | | `response_format` | chat only. Mutually exclusive with `grammar` | | `grammar` | a GBNF grammar directly. On chat it passes through the chat template and a template that drops it makes the request a refusal โ€” see ยง5.5 | | `echo` | `/v1/completions` only | @@ -1138,6 +1232,11 @@ model, on how many cards, with how much KV, drafting how deeply, over which wire the startup log too โ€” but a startup log is on a machine, in a file, from a process that may have been restarted since. +Its `request_defaults` object says what a request that leaves a field out is served with: every +sampler field, `max_tokens`, `reasoning_effort`, `chat_template_kwargs` and `reasoning_format`, +under the request's own spelling of each. `server.default_max_tokens` is `null` for `auto`, and +`server.max_tokens_cap` is `null` when there is none. + ### 6.3 Metrics `GET /metrics` is Prometheus text. Two families: @@ -1200,7 +1299,8 @@ radiance --model m.rad -vv # same as trace ### 6.6 Security -**There is no TLS, and without `--api-key` there is no authentication.** CORS is on. +**There is no TLS, and without `--api-key` there is no authentication.** CORS is on, so a page on +any origin can call the API from a browser; `--no-cors` turns it off. ```sh radiance --model m.rad --api-key "$KEY" diff --git a/tests/chatparse_test.cpp b/tests/chatparse_test.cpp index 3f27b0e3..3d4d8923 100644 --- a/tests/chatparse_test.cpp +++ b/tests/chatparse_test.cpp @@ -916,6 +916,37 @@ TEST(an_argument_no_value_satisfies_has_no_arm_in_either_grammar) { CHECK_EQ(g.text, b->prompt().grammar); } +/* OH-MY-PI 18.6.0's TOOLS AS AN UNMODIFIED CLIENT SENDS THEM (tests/data/chat), descriptions aside. + * Its `task` tool spells the optional `model` as the `not` of a union of all six JSON types rather + * than `{"not": {}}`, which is `never` all the same; the declared format must give it no arm and + * agree with the derived format about the whole tool set, as it does about every other. */ +TEST(oh_my_pis_tools_build_the_same_grammar_in_either_format) { + std::ifstream f(std::string(RAD_CHAT_FIXTURES) + "/oh-my-pi-18.6.0-tools.json"); + std::ostringstream ss; + ss << f.rdbuf(); + const json tools = json::parse(ss.str()); + REQUIRE(tools.is_array() && tools.size() == 11); + + RadChatFormat c = qwen_abi(); + ChatFormat declared; + std::string why; + CHECK_OK(chat_format_from_abi(&c, &declared, &why)); + ChatGrammarRequest gq; + gq.tools = &tools; + ChatGrammar g; + CHECK_OK(chat_format_grammar(declared, gq, &g, &why)); + if (!why.empty()) fprintf(stderr, " %s\n", why.c_str()); + CHECK(!g.text.empty()); + CHECK(g.text.find("task-arg-model") == std::string::npos); + CHECK(g.text.find("task-arg-tasks") != std::string::npos); + + Bench* b = bench(models()[0], ChatRequest{}, tools); + if (!b) return; + gq.generation_prompt = b->prompt().generation_prompt; + CHECK_OK(chat_format_grammar(declared, gq, &g, &why)); + CHECK_EQ(g.text, b->prompt().grammar); +} + /* THE STRUCT GROWS AT ITS END. A plugin built against a header with fewer fields reports a smaller * struct_size, and the fields past it read as zero; one built against a larger header has its * extra fields ignored. Nothing is read past what the plugin said it has. */ diff --git a/tests/config_test.cpp b/tests/config_test.cpp index c188b412..788d53cf 100644 --- a/tests/config_test.cpp +++ b/tests/config_test.cpp @@ -23,6 +23,7 @@ #include #include #include +#include #include using namespace rad; @@ -52,6 +53,13 @@ int parse(std::initializer_list v, Config* c) { return config_parse((int)argv.size(), argv.data(), c); } +/* The same into a Config of its own, for a case whose answer depends on flags not carrying over + * from an earlier parse. */ +int parse_fresh(std::initializer_list v) { + Config c; + return parse(v, &c); +} + /* The level `-v` moves and every other test in this binary reads. */ struct LogGuard { Log saved = log_level(); @@ -383,6 +391,243 @@ TEST(the_sampler_defaults_are_range_checked_at_startup) { CHECK(d.sample_min_p < 0.0f); } +/* A NUMBER IS THE WHOLE ARGUMENT. atof read "high" as 0, which for --temp is greedy decoding. */ +TEST(a_sampler_default_that_is_not_a_number_is_refused) { + Config c; + CHECK_EQ(parse({ "--temp", "high" }, &c), RAD_E_INVAL); + CHECK_EQ(parse({ "--temp", "0.7x" }, &c), RAD_E_INVAL); + CHECK_EQ(parse({ "--temp", "" }, &c), RAD_E_INVAL); + CHECK_EQ(parse({ "--top-k", "20.5" }, &c), RAD_E_INVAL); + CHECK_EQ(parse({ "--top-p", "inf" }, &c), RAD_E_INVAL); + CHECK_EQ(parse({ "--presence-penalty", "nan" }, &c), RAD_E_INVAL); +} + +/* ================================================================== request defaults and bounds + * + * NONE OF THEM MOVES ANYTHING UNTIL IT IS GIVEN. Each field's unset value is the one the server + * used before the flag existed (or a marker the engine reads as "leave it"), so a command line + * that names none of them serves exactly what it served before. */ +TEST(the_request_defaults_and_bounds_are_unset_until_given) { + Config d; + CHECK_EQ(parse({}, &d), RAD_OK); + CHECK(!d.sample_typical_p && !d.sample_rep_penalty && !d.sample_pres_penalty && + !d.sample_freq_penalty && !d.sample_dry_multiplier && !d.sample_dry_base && + !d.sample_xtc_probability && !d.sample_xtc_threshold); + CHECK(!d.sample_penalty_last_n && !d.sample_dry_allowed_length && + !d.sample_dry_penalty_last_n && !d.sample_dry_seq_breakers); + CHECK_EQ(d.default_max_tokens, -1ll); + CHECK_EQ(d.max_tokens_cap, 0ll); + CHECK_EQ(d.max_n, 0ll); + CHECK_EQ(d.max_queued_requests, 0ll); + CHECK_EQ(d.max_stop_strings, 64ll); + CHECK_EQ(d.max_stop_bytes, 4096ll); + CHECK(d.chat_template_kwargs.empty()); + CHECK_EQ(d.reasoning_format, std::string("auto")); + /* The transport's own values (server/http.h TransportOptions). */ + CHECK_EQ(d.http_threads, 0); + CHECK_EQ(d.http_read_timeout_s, 30); + CHECK_EQ(d.http_write_timeout_s, 600); + CHECK_EQ(d.http_keep_alive_timeout_s, 5); + CHECK_EQ(d.http_max_body_mib, 512ll); + CHECK_EQ(d.retry_after_s, 1); + CHECK(d.cors); + CHECK(!d.media_flags_set()); +} + +TEST(the_request_defaults_reach_their_fields) { + Config c; + CHECK_EQ(parse({ "--typical-p", "0.9", "--presence-penalty", "1.5", + "--frequency-penalty", "-0.5", "--repetition-penalty", "1.05", + "--repeat-last-n", "-1", "--dry-multiplier", "0.8", "--dry-base", "1.75", + "--dry-allowed-length", "3", "--dry-penalty-last-n", "256", + "--dry-sequence-breakers", R"(["\n", ":"])", + "--xtc-probability", "0.5", "--xtc-threshold", "0.1", + "--default-max-tokens", "4096", "--max-tokens-cap", "8192", + "--max-n", "4", "--max-queued-requests", "64", + "--max-stop-strings", "8", "--max-stop-bytes", "256", + "--reasoning-format", "none" }, &c), RAD_OK); + CHECK_NEAR(*c.sample_typical_p, 0.9f, 1e-6); + CHECK_NEAR(*c.sample_pres_penalty, 1.5f, 1e-6); + CHECK_NEAR(*c.sample_freq_penalty, -0.5f, 1e-6); + CHECK_NEAR(*c.sample_rep_penalty, 1.05f, 1e-6); + CHECK_EQ(*c.sample_penalty_last_n, -1); + CHECK_NEAR(*c.sample_dry_multiplier, 0.8f, 1e-6); + CHECK_NEAR(*c.sample_dry_base, 1.75f, 1e-6); + CHECK_EQ(*c.sample_dry_allowed_length, 3); + CHECK_EQ(*c.sample_dry_penalty_last_n, 256); + CHECK(*c.sample_dry_seq_breakers == std::vector({ "\n", ":" })); + CHECK_NEAR(*c.sample_xtc_probability, 0.5f, 1e-6); + CHECK_NEAR(*c.sample_xtc_threshold, 0.1f, 1e-6); + CHECK_EQ(c.default_max_tokens, 4096ll); + CHECK_EQ(c.max_tokens_cap, 8192ll); + CHECK_EQ(c.max_n, 4ll); + CHECK_EQ(c.max_queued_requests, 64ll); + CHECK_EQ(c.max_stop_strings, 8ll); + CHECK_EQ(c.max_stop_bytes, 256ll); + CHECK_EQ(c.reasoning_format, std::string("none")); + + /* `auto` is 0, which the server resolves per request to what the context leaves. */ + Config a; + CHECK_EQ(parse({ "--default-max-tokens", "auto" }, &a), RAD_OK); + CHECK_EQ(a.default_max_tokens, 0ll); + + /* An empty breaker list is a stated value -- DRY with no breakers -- and stays one. */ + Config e; + CHECK_EQ(parse({ "--dry-sequence-breakers", "[]" }, &e), RAD_OK); + CHECK(e.sample_dry_seq_breakers && e.sample_dry_seq_breakers->empty()); + + /* A negative penalty is a value a request can send, so the flag can state it. */ + Config n; + CHECK_EQ(parse({ "--presence-penalty", "-2" }, &n), RAD_OK); + CHECK_NEAR(*n.sample_pres_penalty, -2.0f, 1e-6); +} + +/* THE RANGES A REQUEST IS HELD TO, at startup: a default outside them would be a 400 on every + * request that leaves the field to it. */ +TEST(the_request_defaults_are_range_checked_like_a_request) { + Config c; + CHECK_EQ(parse({ "--typical-p", "0" }, &c), RAD_E_INVAL); + CHECK_EQ(parse({ "--typical-p", "1.5" }, &c), RAD_E_INVAL); + CHECK_EQ(parse({ "--presence-penalty", "2.5" }, &c), RAD_E_INVAL); + CHECK_EQ(parse({ "--frequency-penalty", "-3" }, &c), RAD_E_INVAL); + CHECK_EQ(parse({ "--repetition-penalty", "0" }, &c), RAD_E_INVAL); + CHECK_EQ(parse({ "--repeat-last-n", "-2" }, &c), RAD_E_INVAL); + CHECK_EQ(parse({ "--dry-base", "0.5" }, &c), RAD_E_INVAL); + CHECK_EQ(parse({ "--dry-penalty-last-n", "-2" }, &c), RAD_E_INVAL); + CHECK_EQ(parse({ "--xtc-probability", "1.5" }, &c), RAD_E_INVAL); + CHECK_EQ(parse({ "--xtc-threshold", "-0.1" }, &c), RAD_E_INVAL); + CHECK_EQ(parse({ "--dry-allowed-length", "3.5" }, &c), RAD_E_INVAL); + CHECK_EQ(parse({ "--dry-sequence-breakers", R"("\n")" }, &c), RAD_E_INVAL); + CHECK_EQ(parse({ "--dry-sequence-breakers", "[1]" }, &c), RAD_E_INVAL); + /* The sampler takes at most 16 (sample/host_ref.h); every DRY request would be refused. */ + CHECK_EQ(parse({ "--dry-sequence-breakers", + R"(["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q"])" }, + &c), RAD_E_INVAL); + + CHECK_EQ(parse({ "--default-max-tokens", "0" }, &c), RAD_E_INVAL); /* auto is the word */ + CHECK_EQ(parse({ "--default-max-tokens", "-1" }, &c), RAD_E_INVAL); + CHECK_EQ(parse({ "--default-max-tokens", "AUTO" }, &c), RAD_E_INVAL); + CHECK_EQ(parse({ "--default-max-tokens", "4294967296" }, &c), RAD_E_INVAL); + CHECK_EQ(parse({ "--max-tokens-cap", "-1" }, &c), RAD_E_INVAL); + CHECK_EQ(parse({ "--max-n", "0" }, &c), RAD_E_INVAL); + CHECK_EQ(parse({ "--max-queued-requests", "0" }, &c), RAD_E_INVAL); + CHECK_EQ(parse({ "--max-stop-strings", "0" }, &c), RAD_E_INVAL); + CHECK_EQ(parse({ "--max-stop-bytes", "0" }, &c), RAD_E_INVAL); + CHECK_EQ(parse({ "--reasoning-format", "deepseek" }, &c), RAD_E_INVAL); + CHECK_EQ(parse({ "--reasoning-format", "" }, &c), RAD_E_INVAL); +} + +/* BOUNDS THAT CONTRADICT EACH OTHER. A default above the cap is a default no request is served + * at; an `n` above the queue is a request that is 429 however long its caller waits. */ +TEST(request_bounds_that_contradict_each_other_are_refused) { + CHECK_EQ(parse_fresh({ "--default-max-tokens", "4096", "--max-tokens-cap", "1024" }), RAD_E_INVAL); + CHECK_EQ(parse_fresh({ "--default-max-tokens", "1024", "--max-tokens-cap", "1024" }), RAD_OK); + CHECK_EQ(parse_fresh({ "--default-max-tokens", "auto", "--max-tokens-cap", "1024" }), RAD_OK); + + CHECK_EQ(parse_fresh({ "--max-n", "65", "--max-queued-requests", "64" }), RAD_E_INVAL); + CHECK_EQ(parse_fresh({ "--max-n", "64", "--max-queued-requests", "64" }), RAD_OK); + /* The queue's default is 8 x --max-num-seqs, and the check reads it. */ + CHECK_EQ(parse_fresh({ "--max-num-seqs", "2", "--max-n", "17" }), RAD_E_INVAL); + CHECK_EQ(parse_fresh({ "--max-num-seqs", "2", "--max-n", "16" }), RAD_OK); + /* And a stated queue smaller than the default n (8, or --max-num-seqs). */ + CHECK_EQ(parse_fresh({ "--max-queued-requests", "4" }), RAD_E_INVAL); +} + +TEST(the_template_variables_merge_key_by_key_and_later_wins) { + Config c; + CHECK_EQ(parse({ "--chat-template-kwargs", R"({"enable_thinking": false, "custom": "a"})", + "--chat-template-kwargs", R"({"custom": "b", "n": 3})" }, &c), RAD_OK); + CHECK_EQ(c.chat_template_kwargs.size(), 3u); + CHECK_EQ(c.chat_template_kwargs["enable_thinking"], std::string("false")); + CHECK_EQ(c.chat_template_kwargs["custom"], std::string("\"b\"")); /* JSON text, quoted */ + CHECK_EQ(c.chat_template_kwargs["n"], std::string("3")); + + /* @FILE reads the object from a file. */ + char path[] = "/tmp/rad_kwargs_XXXXXX"; + const int fd = mkstemp(path); + REQUIRE(fd >= 0); + const std::string body = R"({"date_string": "01 Jan 2026"})"; + CHECK_EQ((size_t)write(fd, body.data(), body.size()), body.size()); + close(fd); + Config f; + const std::string at = std::string("@") + path; + CHECK_EQ(parse({ "--chat-template-kwargs", at.c_str() }, &f), RAD_OK); + CHECK_EQ(f.chat_template_kwargs["date_string"], std::string("\"01 Jan 2026\"")); + unlink(path); + CHECK_EQ(parse({ "--chat-template-kwargs", at.c_str() }, &f), RAD_E_INVAL); /* gone */ +} + +TEST(a_template_variable_the_server_owns_or_cannot_read_is_refused) { + CHECK_EQ(parse_fresh({ "--chat-template-kwargs", "[1]" }), RAD_E_INVAL); + CHECK_EQ(parse_fresh({ "--chat-template-kwargs", "{nope" }), RAD_E_INVAL); + CHECK_EQ(parse_fresh({ "--chat-template-kwargs", R"("enable_thinking")" }), RAD_E_INVAL); + CHECK_EQ(parse_fresh({ "--chat-template-kwargs", R"({"enable_thinking": "no"})" }), RAD_E_INVAL); + /* The renderer writes these over the context; one here would replace every conversation. */ + for (const char* k : { "messages", "tools", "bos_token", "eos_token", "add_generation_prompt" }) { + const std::string j = std::string("{\"") + k + "\": 1}"; + CHECK_EQ(parse_fresh({ "--chat-template-kwargs", j.c_str() }), RAD_E_INVAL); + } + /* Two defaults for thinking, in two flags, with no order between them. */ + CHECK_EQ(parse_fresh({ "--reasoning-effort", "low", + "--chat-template-kwargs", R"({"reasoning_effort": "high"})" }), RAD_E_INVAL); + CHECK_EQ(parse_fresh({ "--chat-template-kwargs", R"({"enable_thinking": true})", + "--reasoning-effort", "none" }), RAD_E_INVAL); + CHECK_EQ(parse_fresh({ "--reasoning-effort", "low", + "--chat-template-kwargs", R"({"custom": 1})" }), RAD_OK); +} + +TEST(the_transport_flags_reach_their_fields_and_hold_their_floors) { + Config c; + CHECK_EQ(parse({ "--http-threads", "16", "--read-timeout", "10", "--write-timeout", "120", + "--keep-alive-timeout", "30", "--max-body-mib", "64", "--retry-after", "5", + "--no-cors" }, &c), RAD_OK); + CHECK_EQ(c.http_threads, 16); + CHECK_EQ(c.http_read_timeout_s, 10); + CHECK_EQ(c.http_write_timeout_s, 120); + CHECK_EQ(c.http_keep_alive_timeout_s, 30); + CHECK_EQ(c.http_max_body_mib, 64ll); + CHECK_EQ(c.retry_after_s, 5); + CHECK(!c.cors); + + /* The transport keeps four workers whatever it is told, so fewer is refused, not ignored. */ + CHECK_EQ(parse({ "--http-threads", "2" }, &c), RAD_E_INVAL); + CHECK_EQ(parse({ "--read-timeout", "0" }, &c), RAD_E_INVAL); + CHECK_EQ(parse({ "--write-timeout", "-1" }, &c), RAD_E_INVAL); + CHECK_EQ(parse({ "--keep-alive-timeout", "x" }, &c), RAD_E_INVAL); + CHECK_EQ(parse({ "--max-body-mib", "0" }, &c), RAD_E_INVAL); + CHECK_EQ(parse({ "--retry-after", "-1" }, &c), RAD_E_INVAL); + CHECK_EQ(parse({ "--retry-after", "0" }, &c), RAD_OK); +} + +TEST(the_media_flags_reach_their_fields_and_refuse_an_empty_band) { + Config c; + CHECK_EQ(parse({ "--image-min-pixels", "3136", "--image-max-pixels", "1003520", + "--video-min-pixels", "4096", "--video-max-pixels", "8388608", + "--video-fps", "1.5", "--video-min-frames", "2", "--video-max-frames", "64", + "--video-max-frame-tokens", "0", "--max-source-pixels", "16777216" }, &c), + RAD_OK); + CHECK(c.media_flags_set()); + CHECK_EQ(*c.image_min_pixels, 3136ll); + CHECK_EQ(*c.image_max_pixels, 1003520ll); + CHECK_EQ(*c.video_min_pixels, 4096ll); + CHECK_EQ(*c.video_max_pixels, 8388608ll); + CHECK_NEAR(*c.video_fps, 1.5, 1e-9); + CHECK_EQ(*c.video_min_frames, 2); + CHECK_EQ(*c.video_max_frames, 64); + CHECK_EQ(*c.video_max_frame_tokens, 0); /* 0 is "no per-frame cap" */ + CHECK_EQ(*c.max_source_pixels, 16777216ll); + + CHECK_EQ(parse({ "--image-min-pixels", "2000", "--image-max-pixels", "1000" }, &c), RAD_E_INVAL); + CHECK_EQ(parse({ "--video-min-pixels", "2000", "--video-max-pixels", "1000" }, &c), RAD_E_INVAL); + CHECK_EQ(parse({ "--video-min-frames", "8", "--video-max-frames", "4" }, &c), RAD_E_INVAL); + CHECK_EQ(parse({ "--image-max-pixels", "0" }, &c), RAD_E_INVAL); + CHECK_EQ(parse({ "--video-fps", "0" }, &c), RAD_E_INVAL); + CHECK_EQ(parse({ "--video-fps", "-1" }, &c), RAD_E_INVAL); + CHECK_EQ(parse({ "--video-min-frames", "0" }, &c), RAD_E_INVAL); + CHECK_EQ(parse({ "--video-max-frame-tokens", "-1" }, &c), RAD_E_INVAL); + CHECK_EQ(parse({ "--max-source-pixels", "0" }, &c), RAD_E_INVAL); +} + /* REFUSED, NOT QUIETLY IGNORED. Accepting it and then serving the container's own drafter -- or * none -- hands the caller a server that is not the one they asked for, with nothing in the * output to say so. A caller coming from vLLM will reach for this flag. */ @@ -537,6 +782,12 @@ TEST(usage_names_every_flag_it_documents) { CHECK(text.find("--tp-wire") != std::string::npos); CHECK(text.find("--kld-record") != std::string::npos); CHECK(text.find("--kld-ref") != std::string::npos); + for (const char* f : { "--default-max-tokens", "--max-tokens-cap", "--presence-penalty", + "--dry-sequence-breakers", "--chat-template-kwargs", + "--reasoning-format", "--max-n", "--max-queued-requests", + "--max-stop-strings", "--http-threads", "--max-body-mib", "--no-cors", + "--image-max-pixels", "--video-fps", "--max-source-pixels" }) + CHECK(text.find(f) != std::string::npos); CHECK(text.size() > 1000); } diff --git a/tests/data/chat/oh-my-pi-18.6.0-tools.json b/tests/data/chat/oh-my-pi-18.6.0-tools.json new file mode 100644 index 00000000..b6525a50 --- /dev/null +++ b/tests/data/chat/oh-my-pi-18.6.0-tools.json @@ -0,0 +1,484 @@ +[ + { + "type": "function", + "function": { + "name": "read", + "description": "read", + "parameters": { + "type": "object", + "properties": { + "i": { + "type": "string" + }, + "path": { + "type": "string" + } + }, + "required": [ + "path", + "i" + ], + "additionalProperties": false + } + } + }, + { + "type": "function", + "function": { + "name": "bash", + "description": "bash", + "parameters": { + "type": "object", + "properties": { + "i": { + "type": "string" + }, + "command": { + "type": "string" + }, + "timeout": { + "type": "number" + }, + "cwd": { + "type": "string" + }, + "pty": { + "type": "boolean" + }, + "async": { + "type": "boolean" + }, + "name": { + "type": "string", + "maxLength": 48 + }, + "ready": { + "type": "object", + "properties": { + "log": { + "type": "string" + }, + "port": { + "type": "number" + }, + "host": { + "type": "string" + }, + "timeout": { + "type": "number" + } + }, + "additionalProperties": false + } + }, + "required": [ + "command", + "i" + ], + "additionalProperties": false + } + } + }, + { + "type": "function", + "function": { + "name": "edit", + "description": "edit", + "parameters": { + "type": "object", + "properties": { + "i": { + "type": "string" + }, + "input": { + "type": "string" + } + }, + "required": [ + "input", + "i" + ], + "additionalProperties": false + } + } + }, + { + "type": "function", + "function": { + "name": "eval", + "description": "eval", + "parameters": { + "type": "object", + "properties": { + "language": { + "enum": [ + "py", + "js" + ], + "type": "string" + }, + "code": { + "type": "string" + }, + "title": { + "type": "string" + }, + "timeout": { + "type": "number" + }, + "reset": { + "type": "boolean" + } + }, + "required": [ + "language", + "code" + ], + "additionalProperties": false + } + } + }, + { + "type": "function", + "function": { + "name": "glob", + "description": "glob", + "parameters": { + "type": "object", + "properties": { + "i": { + "type": "string" + }, + "path": { + "type": "string" + }, + "hidden": { + "type": "boolean" + }, + "gitignore": { + "type": "boolean" + }, + "limit": { + "type": "number" + } + }, + "additionalProperties": false, + "required": [ + "i" + ] + } + } + }, + { + "type": "function", + "function": { + "name": "grep", + "description": "grep", + "parameters": { + "type": "object", + "properties": { + "i": { + "type": "string" + }, + "pattern": { + "type": "string" + }, + "path": { + "type": "string" + }, + "case": { + "type": "boolean" + }, + "gitignore": { + "type": "boolean" + }, + "skip": { + "type": [ + "number", + "null" + ] + } + }, + "required": [ + "pattern", + "i" + ], + "additionalProperties": false + } + } + }, + { + "type": "function", + "function": { + "name": "task", + "description": "task", + "parameters": { + "type": "object", + "properties": { + "i": { + "type": "string" + }, + "context": { + "type": "string" + }, + "tasks": { + "type": "array", + "items": { + "type": "object", + "properties": { + "task": { + "type": "string" + }, + "solutionSpace": { + "type": "string" + }, + "name": { + "type": "string" + }, + "agent": { + "type": "string", + "default": "task" + }, + "model": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "array", + "items": { + "type": "string" + } + } + ] + }, + "outputSchema": { + "anyOf": [ + { + "type": "object" + }, + { + "type": "boolean" + }, + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "schemaMode": { + "enum": [ + "permissive", + "strict" + ], + "type": "string" + }, + "tools": { + "type": "array", + "items": { + "type": "string" + } + } + }, + "required": [ + "task", + "solutionSpace" + ], + "additionalProperties": false + } + }, + "model": { + "not": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "number" + }, + { + "type": "boolean" + }, + { + "type": "object" + }, + { + "type": "array" + }, + { + "type": "null" + } + ] + } + } + }, + "required": [ + "context", + "tasks", + "i" + ], + "additionalProperties": false + } + } + }, + { + "type": "function", + "function": { + "name": "wait", + "description": "wait", + "parameters": { + "type": "object", + "properties": { + "i": { + "type": "string" + } + }, + "additionalProperties": false + } + } + }, + { + "type": "function", + "function": { + "name": "todo", + "description": "todo", + "parameters": { + "type": "object", + "properties": { + "i": { + "type": "string" + }, + "op": { + "enum": [ + "init", + "start", + "done", + "rm", + "drop", + "block", + "unblock", + "append", + "view" + ], + "type": "string" + }, + "list": { + "type": "array", + "items": { + "type": "object", + "properties": { + "phase": { + "type": "string" + }, + "items": { + "type": "array", + "items": { + "type": "string" + }, + "minItems": 1 + } + }, + "required": [ + "phase", + "items" + ], + "additionalProperties": false + } + }, + "task": { + "type": "string" + }, + "phase": { + "type": "string" + }, + "items": { + "type": "array", + "items": { + "type": "string" + } + }, + "reason": { + "type": "string" + } + }, + "required": [ + "op", + "i" + ], + "additionalProperties": false + } + } + }, + { + "type": "function", + "function": { + "name": "web_search", + "description": "web_search", + "parameters": { + "type": "object", + "properties": { + "i": { + "type": "string" + }, + "query": { + "type": "string" + }, + "recency": { + "enum": [ + "day", + "week", + "month", + "year" + ], + "type": "string" + }, + "limit": { + "type": "number" + }, + "max_tokens": { + "type": "number" + }, + "temperature": { + "type": "number" + }, + "num_search_results": { + "type": "number" + } + }, + "required": [ + "query", + "i" + ], + "additionalProperties": false + } + } + }, + { + "type": "function", + "function": { + "name": "write", + "description": "write", + "parameters": { + "type": "object", + "properties": { + "i": { + "type": "string" + }, + "path": { + "type": "string" + }, + "content": { + "type": "string" + } + }, + "required": [ + "path", + "i" + ], + "additionalProperties": false + } + } + } +] diff --git a/tests/gbnf_test.cpp b/tests/gbnf_test.cpp index 5e38226e..16474401 100644 --- a/tests/gbnf_test.cpp +++ b/tests/gbnf_test.cpp @@ -850,6 +850,88 @@ TEST(gbnf_a_property_no_value_satisfies_is_a_key_never_written) { CHECK(built >= 3); } +/* THE `not` OF A SCHEMA EVERY VALUE SATISFIES is `never` too, whatever spelling the universal + * schema takes. oh-my-pi 18.6.0 sends its `task` tool's optional `model` as the `not` of a union + * of all six JSON types, not as `{"not": {}}`; refused, it failed the tool-call grammar of every + * request carrying the tool under every template that constrains arguments. A `not` of anything + * narrower is a real complement and stays refused. */ +TEST(gbnf_a_not_of_every_json_type_is_never_too) { + auto bv = bpe_like(29, 1500); + auto whole = [&](const std::string& gbnf, const std::string& text) { + std::unique_ptr g; + std::string err; + if (GbnfGrammar::create(gbnf, "root", &bv->v, false, {}, {}, &g, &err) < 0) return false; + return g->accept_str(text) >= 0 && g->complete(); + }; + auto optional_model = [](const std::string& never) { + return std::string(R"({"type":"object","properties":{"context":{"type":"string"},"model":)") + + never + R"(},"required":["context"]})"; + }; + + for (const char* never : { + R"({"not":{"anyOf":[{"type":"string"},{"type":"number"},{"type":"boolean"},)" + R"({"type":"object"},{"type":"array"},{"type":"null"}]}})", + R"({"not":{"type":["string","number","boolean","object","array","null"]}})", + R"({"not":{"anyOf":[{"type":["string","number"]},{"type":["boolean","object"]},)" + R"({"type":"array","description":"a list"},{"type":"null"}]}})", + R"({"not":{"anyOf":[{"type":"string","minLength":1},{}]}})", + R"({"not":true})", + R"({"not":{"description":"anything"}})" }) { + std::string gbnf, err; + CHECK_OK(grammar_from_json_schema(optional_model(never), "root", &gbnf, &err)); + CHECK(whole(gbnf, "{\"context\": \"x\"}")); + CHECK(!whole(gbnf, "{\"context\": \"x\", \"model\": \"y\"}")); + CHECK(!whole(gbnf, "{\"context\": \"x\", \"model\": null}")); + } + + for (const char* complement : { + /* no null among the six */ + R"({"not":{"anyOf":[{"type":"string"},{"type":"number"},{"type":"boolean"},)" + R"({"type":"object"},{"type":"array"}]}})", + /* integer is not number */ + R"({"not":{"type":["string","integer","boolean","object","array","null"]}})", + /* an alternative that constrains more than its type is not all of that type */ + R"({"not":{"anyOf":[{"type":"string","minLength":1},{"type":"number"},)" + R"({"type":"boolean"},{"type":"object"},{"type":"array"},{"type":"null"}]}})", + /* a keyword beside the type narrows it */ + R"({"not":{"type":["string","number","boolean","object","array","null"],"minimum":0}})", + R"({"not":{"type":"string"}})" }) { + std::string gbnf, err; + CHECK(grammar_from_json_schema(optional_model(complement), "root", &gbnf, &err) < 0); + CHECK(err.find("not") != std::string::npos); + } +} + +/* OH-MY-PI 18.6.0's TOOLS AS IT SENDS THEM, captured from an unmodified client and kept whole but + * for their descriptions (tests/data/chat/oh-my-pi-18.6.0-tools.json). Every served template must + * render them and every grammar it writes must compile, which is what admission does with it. */ +TEST(gbnf_oh_my_pi_tools_build_and_compile_under_every_template) { + auto bv = bpe_like(31, 3000); + const ojson tools = ojson::parse(slurp(fixture("../chat/oh-my-pi-18.6.0-tools.json"))); + REQUIRE(tools.is_array() && tools.size() == 11); + const ojson messages = ojson::array({ ojson{ { "role", "user" }, { "content", "hi" } } }); + int built = 0; + for (const TemplateCase& tc : kTemplates) { + ChatTemplate ct; + REQUIRE(ct.load(slurp(fixture(tc.file)), tc.bos, tc.eos) >= 0); + for (int par = 0; par < 2; ++par) { + ChatOptions opt; + opt.tool_choice = "auto"; + opt.parallel_tool_calls = par != 0; + opt.template_kwargs["preserve_thinking"] = "true"; + ChatPrompt cp; + CHECK(ct.apply(messages, tools, opt, &cp) >= 0); + if (cp.grammar.empty()) continue; + ++built; + std::unique_ptr g; + std::string err; + CHECK(GbnfGrammar::create(cp.grammar, "root", &bv->v, false, {}, {}, &g, &err) >= 0); + if (!err.empty()) fprintf(stderr, " %s: %s\n", tc.file, err.c_str()); + } + } + CHECK(built >= 2); +} + /* The grammars a chat template writes for its own tool-call syntax, from the three templates the * engine serves: walked, and replayed over four agent calls wherever the syntax is the one the * calls are written in. */ diff --git a/tests/mm_test.cpp b/tests/mm_test.cpp index 32bc7337..3d277cd1 100644 --- a/tests/mm_test.cpp +++ b/tests/mm_test.cpp @@ -303,4 +303,33 @@ TEST(every_admitted_video_format_decodes) { } } +/* THE BANDS ARE CHECKED AS A WHOLE, because the command line can replace one end of a band and + * leave the other to the container: a minimum stated alone can land above the container's maximum. */ +TEST(a_media_configuration_with_an_empty_band_names_it) { + mm::VisionConfig c; + c.image_min_pixels = 65536; + c.image_max_pixels = 16777216; + c.video_min_pixels = 4096; + c.video_max_pixels = 25165824; + std::string why; + CHECK_EQ(c.check(&why), RAD_OK); + + mm::VisionConfig b = c; + b.image_min_pixels = 32 << 20; + CHECK_EQ(b.check(&why), RAD_E_INVAL); + CHECK(why.find("image_max_pixels") != std::string::npos); + b = c; + b.video_max_pixels = 1000; + CHECK_EQ(b.check(&why), RAD_E_INVAL); + CHECK(why.find("video_max_pixels") != std::string::npos); + b = c; + b.fps = 0.0; + CHECK_EQ(b.check(&why), RAD_E_INVAL); + b = c; + b.min_frames = 10; + b.max_frames = 5; + CHECK_EQ(b.check(&why), RAD_E_INVAL); + CHECK(why.find("max_frames") != std::string::npos); +} + RAD_TEST_MAIN() diff --git a/tests/server_test.cpp b/tests/server_test.cpp index 80338169..d35d4efb 100644 --- a/tests/server_test.cpp +++ b/tests/server_test.cpp @@ -29,6 +29,7 @@ #include #include #include +#include #include #include #include @@ -89,9 +90,15 @@ struct FakeChatTemplate : IChatTemplate { mutable int last_n_tools = 0; int apply(const json& messages, const json& tools, const ChatRenderOptions& opt, - ChatRender* out, std::string*) const override { + ChatRender* out, std::string* why) const override { last_opt = opt; last_n_tools = (int)tools.size(); + /* A template that raise_exception's on one variable, as Qwen3.8's does on an effort it + * does not know. */ + if (!refuse_kwarg.empty() && opt.template_kwargs.count(refuse_kwarg)) { + if (why) *why = "the template does not take " + refuse_kwarg; + return RAD_E_UNSUPPORTED; + } std::string s; if (!tools.empty()) s += "[tools:" + std::to_string(tools.size()) + "]"; if (!opt.enable_thinking) s += "[nothink]"; @@ -125,6 +132,7 @@ struct FakeChatTemplate : IChatTemplate { bool with_parser = false; std::string refusal; + std::string refuse_kwarg; /* Reads "TOOL::" -- everything after the second colon is the arguments, * however incomplete, and it arrives a piece at a time. That is exactly the shape the @@ -945,6 +953,349 @@ TEST(the_ways_of_turning_thinking_off_all_reach_the_template) { CHECK(f.tmpl.last_opt.enable_thinking); } +/* ================================================================== deployment defaults + * + * Every default the command line can move, seen from a request: it reaches a request that leaves + * the field out, and loses to one that names it. */ + +static OaiRequest chat_with(Fixture& f, const OaiLimits& lim, const std::string& extra) { + OaiRequest r; + ApiError e; + const std::string body = + R"({"messages":[{"role":"user","content":"hi"}])" + (extra.empty() ? "" : "," + extra) + "}"; + CHECK_OK(parse_chat_request(body, f.odeps(), lim, &r, &e)); + return r; +} + +TEST(the_rest_of_the_sampler_is_seeded_from_the_deployment_too) { + Fixture f; + OaiLimits lim = f.limits(); + lim.default_sampling.pres_penalty = 1.5f; + lim.default_sampling.rep_penalty = 1.05f; + lim.default_sampling.penalty_last_n = 256; + lim.default_sampling.typical_p = 0.9f; + lim.default_sampling.dry_multiplier = 0.8f; + lim.default_sampling.xtc_probability = 0.5f; + + OaiRequest r = chat_with(f, lim, ""); + CHECK_NEAR(r.sp.pres_penalty, 1.5f, 1e-6); + CHECK_NEAR(r.sp.rep_penalty, 1.05f, 1e-6); + CHECK_EQ(r.sp.penalty_last_n, 256); + CHECK_NEAR(r.sp.typical_p, 0.9f, 1e-6); + CHECK_NEAR(r.sp.dry_multiplier, 0.8f, 1e-6); + CHECK_NEAR(r.sp.xtc_probability, 0.5f, 1e-6); + + OaiRequest r2 = chat_with(f, lim, R"("presence_penalty":0,"repeat_last_n":64)"); + CHECK_NEAR(r2.sp.pres_penalty, 0.0f, 1e-6); + CHECK_EQ(r2.sp.penalty_last_n, 64); + CHECK_NEAR(r2.sp.rep_penalty, 1.05f, 1e-6); + + /* A STATED EMPTY BREAKER LIST STAYS EMPTY, which SamplingParams alone cannot say: unstated is + * llama-server's four. A request's own list still wins. */ + lim.default_sampling.dry_seq_breakers.clear(); + lim.default_dry_breakers_set = true; + CHECK(chat_with(f, lim, "").sp.dry_seq_breakers.empty()); + CHECK(chat_with(f, lim, R"("dry_sequence_breakers":["x"])").sp.dry_seq_breakers == + std::vector({ "x" })); + lim.default_sampling.dry_seq_breakers = { "\n" }; + CHECK(chat_with(f, lim, "").sp.dry_seq_breakers == std::vector({ "\n" })); +} + +/* A sampler field's range is ONE table for the request and the flag; this holds the request half + * of it to the exact sentences it has always carried. */ +TEST(the_shared_sampler_ranges_refuse_in_the_words_a_request_always_got) { + struct Case { const char* body; const char* param; const char* msg; }; + const Case cases[] = { + { R"("temperature":2.5)", "temperature", "must be in [0, 2], got 2.5" }, + { R"("top_p":0)", "top_p", "must be in (0, 1]" }, + { R"("top_k":-1)", "top_k", "must be >= 0 (0 disables it)" }, + { R"("min_p":1.5)", "min_p", "must be in [0, 1], got 1.5" }, + { R"("typical_p":0)", "typical_p", "must be in (0, 1]" }, + { R"("presence_penalty":3)", "presence_penalty", "must be in [-2, 2], got 3" }, + { R"("frequency_penalty":-3)", "frequency_penalty", "must be in [-2, 2], got -3" }, + { R"("repetition_penalty":0)", "repetition_penalty", "must be > 0" }, + { R"("repeat_last_n":-2)", "repeat_last_n", "must be >= -1" }, + { R"("xtc_probability":2)", "xtc_probability", "must be in [0, 1], got 2" }, + { R"("xtc_threshold":-1)", "xtc_threshold", "must be in [0, 1], got -1" }, + { R"("dry_base":0.5)", "dry_base", "must be >= 1" }, + { R"("dry_penalty_last_n":-2)", "dry_penalty_last_n", "must be >= -1" }, + }; + Fixture f; + for (const Case& c : cases) { + OaiRequest r; + ApiError e; + const std::string body = + std::string(R"({"messages":[{"role":"user","content":"hi"}],)") + c.body + "}"; + CHECK_EQ(parse_chat_request(body, f.odeps(), f.limits(), &r, &e), RAD_E_INVAL); + CHECK_EQ(e.param, std::string(c.param)); + CHECK_EQ(e.message, std::string(c.param) + ": " + c.msg); + } + /* The other half: the same function, as config.cpp calls it. */ + std::string why; + CHECK(sampler_value_ok("presence_penalty", -2.0, &why)); + CHECK(!sampler_value_ok("presence_penalty", std::nan(""), &why)); + CHECK(!sampler_value_ok("temperature", std::nan(""), &why)); + CHECK(sampler_value_ok("dry_multiplier", -5.0, &why)); /* unbounded, as a request is */ +} + +/* `--default-max-tokens auto` IS WHAT THE CONTEXT LEAVES, and `--max-tokens-cap` CLAMPS like the + * context does: a request asking for more is served up to the cap, not refused. */ +TEST(the_max_tokens_default_and_cap_bound_a_request_like_the_context) { + Fixture f; + OaiLimits lim = f.limits(); + lim.max_ctx = 64; + lim.default_max_tokens = 0; + + OaiRequest r = chat_with(f, lim, ""); + CHECK_EQ((int64_t)r.prompts[0].tokens.size() + r.max_tokens, lim.max_ctx); + CHECK_EQ(chat_with(f, lim, R"("max_tokens":5)").max_tokens, 5); + + lim.max_tokens_cap = 10; + CHECK_EQ(chat_with(f, lim, "").max_tokens, 10); /* auto, then the cap */ + CHECK_EQ(chat_with(f, lim, R"("max_tokens":9999)").max_tokens, 10); + CHECK_EQ(chat_with(f, lim, R"("max_tokens":5)").max_tokens, 5); + + /* The cap holds where no context is declared, and on /v1/completions. */ + lim.max_ctx = 0; + lim.default_max_tokens = 512; + CHECK_EQ(chat_with(f, lim, "").max_tokens, 10); + OaiRequest c; + ApiError e; + CHECK_OK(parse_completion_request(R"({"prompt":"ab","max_tokens":100})", f.odeps(), lim, &c, &e)); + CHECK_EQ(c.max_tokens, 10); + + /* Unset, nothing moves: the fixture's default with no cap and no context. */ + CHECK_EQ(chat_with(f, f.limits(), "").max_tokens, 32); + CHECK_EQ(chat_with(f, f.limits(), R"("max_tokens":100000)").max_tokens, 100000); +} + +TEST(the_stop_bounds_are_the_deployments) { + Fixture f; + OaiLimits lim = f.limits(); + lim.max_stops = 2; + lim.max_stop_bytes = 3; + OaiRequest r; + ApiError e; + CHECK_OK(parse_chat_request(R"({"messages":[{"role":"user","content":"hi"}],"stop":["a","bcd"]})", + f.odeps(), lim, &r, &e)); + CHECK_EQ(parse_chat_request(R"({"messages":[{"role":"user","content":"hi"}],"stop":["a","b","c"]})", + f.odeps(), lim, &r, &e), RAD_E_INVAL); + CHECK(has(e.message, "at most 2 stop strings")); + CHECK_EQ(parse_chat_request(R"({"messages":[{"role":"user","content":"hi"}],"stop":"abcd"})", + f.odeps(), lim, &r, &e), RAD_E_INVAL); + CHECK(has(e.message, "at most 3 bytes")); +} + +/* THE DEPLOYMENT'S TEMPLATE VARIABLES go under the request's, key by key. */ +TEST(the_deployments_template_variables_reach_the_template_under_the_requests) { + Fixture f; + OaiLimits lim = f.limits(); + lim.default_template_kwargs = { { "custom", "\"a\"" }, { "depth", "2" } }; + + chat_with(f, lim, ""); + CHECK_EQ(f.tmpl.last_opt.template_kwargs.at("custom"), std::string("\"a\"")); + CHECK_EQ(f.tmpl.last_opt.template_kwargs.at("depth"), std::string("2")); + + chat_with(f, lim, R"("chat_template_kwargs":{"custom":"b"})"); + CHECK_EQ(f.tmpl.last_opt.template_kwargs.at("custom"), std::string("\"b\"")); + CHECK_EQ(f.tmpl.last_opt.template_kwargs.at("depth"), std::string("2")); + + lim.reasoning_format = "none"; + chat_with(f, lim, ""); + CHECK_EQ(f.tmpl.last_opt.reasoning_format, std::string("none")); + chat_with(f, f.limits(), ""); + CHECK_EQ(f.tmpl.last_opt.reasoning_format, std::string("auto")); + CHECK(f.tmpl.last_opt.template_kwargs.empty()); + + /* /tokenize renders with the same variables, so the prompt it counts is the prompt chat + * serves -- and with none set it renders exactly as before. */ + FakeScheduler sched; + FakeTokenizer tok; + FakeChatTemplate tmpl; + Deps d; + d.sched = &sched; + d.tok = &tok; + d.chat = &tmpl; + const std::string body = R"({"messages":[{"role":"user","content":"hi"}]})"; + { + ServerOptions o; + o.default_template_kwargs = { { "enable_thinking", "false" }, { "custom", "\"a\"" } }; + Server srv(d, o); + CHECK_EQ(srv.router().call("POST", "/tokenize", body).status, 200); + CHECK(!tmpl.last_opt.enable_thinking); + CHECK_EQ(tmpl.last_opt.template_kwargs.at("custom"), std::string("\"a\"")); + CHECK_EQ(srv.router().call("POST", "/tokenize", + R"({"messages":[{"role":"user","content":"hi"}], + "chat_template_kwargs":{"enable_thinking":true}})").status, 200); + CHECK_EQ(tmpl.last_opt.template_kwargs.at("enable_thinking"), std::string("true")); + } + { + ServerOptions o; + Server srv(d, o); + CHECK_EQ(srv.router().call("POST", "/tokenize", body).status, 200); + CHECK(tmpl.last_opt.enable_thinking); + CHECK(tmpl.last_opt.template_kwargs.empty()); + } +} + +/* THINKING IS ONE SETTING WITH THREE SPELLINGS, and a deployment default in one spelling must not + * outlive a request that used another. */ +TEST(a_request_that_says_anything_about_thinking_replaces_the_deployments_default) { + Fixture f; + OaiLimits off = f.limits(); + off.default_template_kwargs = { { "enable_thinking", "false" } }; + + chat_with(f, off, ""); + CHECK(!f.tmpl.last_opt.enable_thinking); + CHECK_EQ(f.tmpl.last_opt.template_kwargs.at("enable_thinking"), std::string("false")); + + for (const char* extra : { R"("enable_thinking":true)", + R"("chat_template_kwargs":{"enable_thinking":true})", + R"("reasoning_effort":"high")", + R"("chat_template_kwargs":{"reasoning_effort":"high"})" }) { + chat_with(f, off, extra); + CHECK(f.tmpl.last_opt.enable_thinking); + } + chat_with(f, off, R"("reasoning_effort":"high")"); + CHECK_EQ(f.tmpl.last_opt.template_kwargs.at("reasoning_effort"), std::string("\"high\"")); + CHECK(!f.tmpl.last_opt.template_kwargs.count("enable_thinking")); + /* An empty effort is no effort, and leaves the default standing. */ + chat_with(f, off, R"("reasoning_effort":"")"); + CHECK(!f.tmpl.last_opt.enable_thinking); + + /* --reasoning-effort none is the same default in its other spelling. */ + OaiLimits none = f.limits(); + none.default_reasoning_effort = "none"; + chat_with(f, none, ""); + CHECK(!f.tmpl.last_opt.enable_thinking); + chat_with(f, none, R"("enable_thinking":true)"); + CHECK(f.tmpl.last_opt.enable_thinking); + chat_with(f, none, R"("reasoning_effort":"low")"); + CHECK(f.tmpl.last_opt.enable_thinking); + + /* A LEVEL is an effort default: a request that only turns thinking on keeps it, as before, + * and one that names its own effort replaces it. */ + OaiLimits low = f.limits(); + low.default_reasoning_effort = "low"; + chat_with(f, low, R"("enable_thinking":true)"); + CHECK_EQ(f.tmpl.last_opt.template_kwargs.at("reasoning_effort"), std::string("\"low\"")); + chat_with(f, low, R"("reasoning_effort":"xhigh")"); + CHECK_EQ(f.tmpl.last_opt.template_kwargs.at("reasoning_effort"), std::string("\"xhigh\"")); + chat_with(f, low, R"("chat_template_kwargs":{"reasoning_effort":"xhigh"})"); + CHECK_EQ(f.tmpl.last_opt.template_kwargs.at("reasoning_effort"), std::string("\"xhigh\"")); + + OaiLimits kw_low = f.limits(); + kw_low.default_template_kwargs = { { "reasoning_effort", "\"low\"" } }; + chat_with(f, kw_low, R"("enable_thinking":true)"); + CHECK_EQ(f.tmpl.last_opt.template_kwargs.at("reasoning_effort"), std::string("\"low\"")); + chat_with(f, kw_low, R"("reasoning_effort":"xhigh")"); + CHECK_EQ(f.tmpl.last_opt.template_kwargs.at("reasoning_effort"), std::string("\"xhigh\"")); +} + +/* A TEMPLATE DEFAULT THE TEMPLATE REFUSES is found at startup, and attributed to the flag that + * set it. A render that fails without any default blames nothing. */ +TEST(a_template_default_the_template_refuses_is_found_before_a_caller_sends_one) { + auto run = [](const std::map& kw, const std::string& effort, + const std::string& refuse, std::string* kw_why, std::string* eff_why) { + FakeScheduler sched; + FakeTokenizer tok; + FakeChatTemplate tmpl; + tmpl.refuse_kwarg = refuse; + Deps d; + d.sched = &sched; + d.tok = &tok; + d.chat = &tmpl; + ServerOptions o; + o.default_template_kwargs = kw; + o.default_reasoning_effort = effort; + Server srv(d, o); + srv.check_template_defaults(kw_why, eff_why); + }; + std::string kw_why, eff_why; + run({ { "bad", "1" } }, "", "bad", &kw_why, &eff_why); + CHECK(has(kw_why, "does not take bad")); + CHECK(eff_why.empty()); + + run({ { "fine", "1" } }, "high", "reasoning_effort", &kw_why, &eff_why); + CHECK(kw_why.empty()); + CHECK(has(eff_why, "does not take reasoning_effort")); + + run({ { "fine", "1" } }, "high", "", &kw_why, &eff_why); + CHECK(kw_why.empty() && eff_why.empty()); + /* "none" is enable_thinking false, never a template variable, so nothing to refuse. */ + run({}, "none", "reasoning_effort", &kw_why, &eff_why); + CHECK(kw_why.empty() && eff_why.empty()); +} + +TEST(server_info_reports_what_a_request_that_leaves_a_field_out_gets) { + FakeScheduler sched; + FakeTokenizer tok; + FakeChatTemplate tmpl; + Deps d; + d.sched = &sched; + d.tok = &tok; + d.chat = &tmpl; + { + ServerOptions o; + Server srv(d, o); + const json j = json::parse(srv.router().call("GET", "/server_info").body); + CHECK_EQ(j["server"]["default_max_tokens"].get(), 512); + CHECK(j["server"]["max_tokens_cap"].is_null()); + CHECK_EQ(j["server"]["max_stop_strings"].get(), 64); + const json& r = j["request_defaults"]; + CHECK_NEAR(r["temperature"].get(), 1.0, 1e-9); + CHECK_NEAR(r["repetition_penalty"].get(), 1.0, 1e-9); + CHECK_EQ(r["dry_sequence_breakers"].size(), 4u); + CHECK(r["reasoning_effort"].is_null()); + CHECK(r["chat_template_kwargs"].is_object() && r["chat_template_kwargs"].empty()); + CHECK_EQ(r["reasoning_format"].get(), std::string("auto")); + } + { + ServerOptions o; + o.default_max_tokens = 0; + o.max_tokens_cap = 4096; + o.default_sampling.pres_penalty = 1.5f; + o.default_template_kwargs = { { "enable_thinking", "false" }, { "tag", "\"x\"" } }; + Server srv(d, o); + const json j = json::parse(srv.router().call("GET", "/server_info").body); + CHECK(j["server"]["default_max_tokens"].is_null()); /* auto */ + CHECK_EQ(j["server"]["max_tokens_cap"].get(), 4096); + const json& r = j["request_defaults"]; + CHECK_NEAR(r["presence_penalty"].get(), 1.5, 1e-6); + CHECK_EQ(r["chat_template_kwargs"]["enable_thinking"].get(), false); + CHECK_EQ(r["chat_template_kwargs"]["tag"].get(), std::string("x")); + } +} + +/* `preserve_thinking` AT THE TOP LEVEL IS THE TEMPLATE VARIABLE, as `enable_thinking` is. oh-my-pi + * sends it there and in chat_template_kwargs on every request to a Qwen model, and refusing it as + * an unknown field failed all of them. */ +TEST(preserve_thinking_at_the_top_level_reaches_the_template) { + Fixture f; + OaiLimits lim = f.limits(); + chat_with(f, lim, R"("preserve_thinking":true)"); + CHECK_EQ(f.tmpl.last_opt.template_kwargs.at("preserve_thinking"), std::string("true")); + CHECK(f.tmpl.last_opt.enable_thinking); /* a history knob, not a thinking one */ + + /* oh-my-pi's exact pair, and the top-level spelling winning a disagreement. */ + chat_with(f, lim, R"("preserve_thinking":true,"chat_template_kwargs":{"preserve_thinking":true})"); + CHECK_EQ(f.tmpl.last_opt.template_kwargs.at("preserve_thinking"), std::string("true")); + chat_with(f, lim, R"("preserve_thinking":false,"chat_template_kwargs":{"preserve_thinking":true})"); + CHECK_EQ(f.tmpl.last_opt.template_kwargs.at("preserve_thinking"), std::string("false")); + + chat_with(f, lim, ""); + CHECK(!f.tmpl.last_opt.template_kwargs.count("preserve_thinking")); + + OaiRequest r; + ApiError e; + CHECK_EQ(parse_chat_request(R"({"messages":[{"role":"user","content":"hi"}],"preserve_thinking":"yes"})", + f.odeps(), lim, &r, &e), RAD_E_INVAL); + CHECK_EQ(e.param, std::string("preserve_thinking")); + /* A chat field, not a completion one: /v1/completions has no template to hand it to. */ + CHECK_EQ(parse_completion_request(R"({"prompt":"ab","preserve_thinking":true})", f.odeps(), lim, + &r, &e), RAD_E_INVAL); +} + /* parallel_tool_calls reaches the template, because it is the one tool-choice knob the generated * grammar actually honours -- it narrows the repetition rule rather than being advice. */ TEST(parallel_tool_calls_false_reaches_the_template) { @@ -1852,7 +2203,8 @@ struct LiveServer { std::vector fds; /* Generations never finish on their own; each one holds its worker until its peer leaves. */ - LiveServer(int n_threads, int64_t max_seqs) { + LiveServer(int n_threads, int64_t max_seqs, + const std::function& tweak = nullptr) { sched.reply = "abcdefgh"; sched.hang = true; Deps d; @@ -1864,6 +2216,7 @@ struct LiveServer { o.n_threads = n_threads; o.max_seqs = max_seqs; o.default_max_tokens = 32; + if (tweak) tweak(o); srv.reset(new Server(d, o)); serving = std::thread([this] { srv->run(); }); for (int i = 0; i < 500 && srv->port() == 0; ++i) @@ -1912,4 +2265,86 @@ TEST(a_probe_and_a_429_are_answered_while_every_admitted_request_holds_a_worker) CHECK(has(status_line(probe), " 200 ")); } +/* The response head on `fd`: everything up to the blank line, or what arrived before the read + * timeout. */ +static std::string response_head(int fd) { + std::string got; + char buf[512]; + while (got.find("\r\n\r\n") == std::string::npos) { + const ssize_t n = ::recv(fd, buf, sizeof buf, 0); + if (n <= 0) break; + got.append(buf, (size_t)n); + } + return got.substr(0, got.find("\r\n\r\n")); +} + +/* THE TRANSPORT SETTINGS REACH THE LISTENER. CORS headers are on unless turned off, and a body + * past --max-body-mib is refused before it is read. */ +TEST(the_transport_settings_reach_the_listener) { + const std::string probe = "GET /health HTTP/1.1\r\nHost: t\r\nConnection: close\r\n\r\n"; + { + LiveServer s(4, 1); + REQUIRE(s.srv->port() > 0); + const int fd = s.open(probe); + REQUIRE(fd >= 0); + CHECK(has(response_head(fd), "Access-Control-Allow-Origin: *")); + } + { + LiveServer s(4, 1, [](ServerOptions& o) { + o.cors = false; + o.max_body_bytes = 64; + }); + REQUIRE(s.srv->port() > 0); + const int fd = s.open(probe); + REQUIRE(fd >= 0); + const std::string head = response_head(fd); + CHECK(has(head, " 200 ")); + CHECK(!has(head, "Access-Control-Allow-Origin")); + + const std::string big = std::string(R"({"prompt":")") + std::string(100, 'x') + "\"}"; + const int b = s.open("POST /v1/completions HTTP/1.1\r\nHost: t\r\nConnection: close\r\n" + "Content-Type: application/json\r\nContent-Length: " + + std::to_string(big.size()) + "\r\n\r\n" + big); + REQUIRE(b >= 0); + CHECK(has(status_line(b), " 413 ")); + } +} + +/* The Retry-After a 429 carries is the deployment's. */ +TEST(a_429_carries_the_deployments_retry_after) { + FakeScheduler sched; + FakeTokenizer tok; + sched.reply = "abcdefgh"; + sched.hang = true; + Deps d; + d.sched = &sched; + d.tok = &tok; + ServerOptions o; + o.max_seqs = 1; + o.queue_depth = 1; + o.retry_after_s = 7; + o.default_max_tokens = 32; + auto srv = std::make_unique(d, o); + std::atomic never{false}; + std::vector live; + std::string retry; + for (int i = 0; i < 2; ++i) { + HttpRequest q; + q.method = "POST"; + q.path = "/v1/completions"; + q.body = R"({"prompt":"hi","stream":true})"; + q.closed = [&never] { return never.load(); }; + HttpResponse r = srv->router().dispatch(q); + if (r.status == 429) { + for (auto& h : r.headers) if (h.first == "Retry-After") retry = h.second; + } else { + live.push_back(std::move(r)); + } + } + CHECK_EQ(retry, std::string("7")); + for (auto& r : live) if (r.on_close) r.on_close(false); + sched.join_all(); + srv.reset(); +} + RAD_TEST_MAIN() diff --git a/vendor/UPSTREAM b/vendor/UPSTREAM index a9b032c4..0bdad5bc 100644 --- a/vendor/UPSTREAM +++ b/vendor/UPSTREAM @@ -99,6 +99,7 @@ vendor/llama/common/regex-partial.{h,cpp} <- llama.cpp common/* patches/0011-chat-add_bos-must-come-from-the-inputs.patch patches/0012-json-schema-a-schema-no-value-satisfies.patch patches/0013-json-schema-a-count-past-int-is-no-bound.patch + patches/0014-json-schema-a-not-of-every-type-is-never.patch On 0003: a `pattern` in a `response_format` reaches _visit_pattern() as client data, and three of its paths do not survive that. `front()`/`back()` run on an empty string; `seq.back()` runs @@ -444,3 +445,18 @@ PATCH SERIES long. A count that is negative or not a number is refused by name. A float count is truncated, where maxItems used to ignore one. The other half of the same report -- any count past 2000 refused -- was the GBNF parser's, and is fixed in core/sample/gbnf.cpp. + + patches/0014-json-schema-a-not-of-every-type-is-never.patch + + 0012 recognised `never` only as `{"not": {}}`. oh-my-pi 18.6.0 sends its `task` tool's + optional `model` as the `not` of a union of all six JSON types -- `{"not": {"anyOf": + [{"type": "string"}, {"type": "number"}, {"type": "boolean"}, {"type": "object"}, + {"type": "array"}, {"type": "null"}]}}` -- so under every template that constrains tool + arguments the request still failed with "Unsupported schema keyword \"not\"". A `not` is now + `never` whenever what it negates accepts every value: `{}` or `true`, a type list naming all + six types, or a union of bare types that between them name all six (an alternative that is + itself universal settles it). Annotations may sit beside; any other keyword narrows the + schema, an alternative that constrains more than its type is not counted, and `integer` does + not stand for `number`, so a `not` is only read as `never` when it is. Every other `not` is + refused as 0004 refuses it. The comment of 0012 above is_unsatisfiable, which 0013 had left + above _schema_count, is back beside the function it describes. diff --git a/vendor/llama/common/json-schema-to-grammar.cpp b/vendor/llama/common/json-schema-to-grammar.cpp index 0bf2b72f..12e2756e 100644 --- a/vendor/llama/common/json-schema-to-grammar.cpp +++ b/vendor/llama/common/json-schema-to-grammar.cpp @@ -900,10 +900,6 @@ public: visit_refs(schema); } - // RADIANCE: the schema no value satisfies. JSON Schema spells it `false`, and `{"not": {}}` -- - // which is how TypeBox's Type.Never and Arktype's "never" are exported, the latter as an - // optional property no call may set. A `not` of the empty schema makes its whole schema - // unsatisfiable whatever sits beside it, so the sibling keywords do not matter. // RADIANCE: a count -- minLength, maxLength, minItems, maxItems -- as the int build_repetition // takes, or `dflt` where the schema has none. get() casts, so a bound past INT_MAX wrapped: // Number.MAX_SAFE_INTEGER, a common way to write "no limit", came out as -1 and the grammar did @@ -924,11 +920,74 @@ public: return d >= (double) std::numeric_limits::max() ? std::numeric_limits::max() : (int) d; } + // RADIANCE: the schema every value satisfies, whose `not` is therefore the schema none does. + // `{}` and `true` are it, and so is a type list, or a union of bare types, that between them + // name all six JSON types -- the way Arktype exports the complement of `never` for an optional + // property: {"not": {"anyOf": [{"type": "string"}, {"type": "number"}, {"type": "boolean"}, + // {"type": "object"}, {"type": "array"}, {"type": "null"}]}}. Annotations may sit beside; any + // other keyword narrows the schema, and its `not` is a real complement, refused below. A union + // alternative that constrains more than its type is not counted, so a union is only ever read + // as universal when it is. + static bool is_universal(const json & s) { + if (s.is_boolean()) return s.get(); + if (!s.is_object()) return false; + static const std::unordered_set annotations = { + "description", "title", "default", "examples", "$comment", "deprecated", "readOnly", + "writeOnly", + }; + // Whether every key of `o` is an annotation or `allowed`. + auto only = [&](const json & o, const char * allowed) { + for (auto it = o.begin(); it != o.end(); ++it) { + if (annotations.count(it.key()) == 0 && (allowed == nullptr || it.key() != allowed)) { + return false; + } + } + return true; + }; + // The types a bare `type` names, into `out`; false for anything that is not one. + auto types_of = [](const json & t, std::unordered_set & out) { + if (t.is_string()) { + out.insert(t.get()); + return true; + } + if (!t.is_array()) return false; + for (const auto & e : t) { + if (!e.is_string()) return false; + out.insert(e.get()); + } + return true; + }; + auto covers = [](const std::unordered_set & ts) { + for (const char * t : { "string", "number", "boolean", "object", "array", "null" }) { + if (ts.count(t) == 0) return false; + } + return true; + }; + if (only(s, nullptr)) return true; + std::unordered_set ts; + if (s.contains("type") && only(s, "type")) { + return types_of(s["type"], ts) && covers(ts); + } + if (s.contains("anyOf") && only(s, "anyOf") && s["anyOf"].is_array()) { + for (const auto & a : s["anyOf"]) { + if (is_universal(a)) return true; + if (a.is_object() && a.contains("type") && only(a, "type")) { + types_of(a["type"], ts); + } + } + return covers(ts); + } + return false; + } + + // RADIANCE: the schema no value satisfies. JSON Schema spells it `false`, and TypeBox's + // Type.Never and Arktype's "never" export it as a `not` of the universal schema above, the + // latter for an optional property no call may set. Such a `not` makes its whole schema + // unsatisfiable whatever sits beside it, so the sibling keywords do not matter. static bool is_unsatisfiable(const json & schema) { if (schema.is_boolean()) return !schema.get(); if (!schema.is_object() || !schema.contains("not")) return false; - const json & n = schema["not"]; - return (n.is_object() && n.empty()) || (n.is_boolean() && n.get()); + return is_universal(schema["not"]); } static std::string _generate_constant_rule(const json & value) { diff --git a/vendor/llama/common/json-schema-to-grammar.h b/vendor/llama/common/json-schema-to-grammar.h index 86c78f3a..8223dd40 100644 --- a/vendor/llama/common/json-schema-to-grammar.h +++ b/vendor/llama/common/json-schema-to-grammar.h @@ -26,7 +26,8 @@ class common_schema_info { void resolve_refs(nlohmann::ordered_json & schema); bool resolves_to_string(const nlohmann::ordered_json & schema); - // RADIANCE: whether no value satisfies the schema -- `false`, or `{"not": {}}`. + // RADIANCE: whether no value satisfies the schema -- `false`, or a `not` of a schema every + // value satisfies (`{}`, or types naming all six JSON types). bool unsatisfiable(const nlohmann::ordered_json & schema) const; }; diff --git a/vendor/patches/0014-json-schema-a-not-of-every-type-is-never.patch b/vendor/patches/0014-json-schema-a-not-of-every-type-is-never.patch new file mode 100644 index 00000000..aefc9283 --- /dev/null +++ b/vendor/patches/0014-json-schema-a-not-of-every-type-is-never.patch @@ -0,0 +1,106 @@ +diff --git a/common/json-schema-to-grammar.cpp b/common/json-schema-to-grammar.cpp +index 0bf2b72..12e2756 100644 +--- a/common/json-schema-to-grammar.cpp ++++ b/common/json-schema-to-grammar.cpp +@@ -900,10 +900,6 @@ public: + visit_refs(schema); + } + +- // RADIANCE: the schema no value satisfies. JSON Schema spells it `false`, and `{"not": {}}` -- +- // which is how TypeBox's Type.Never and Arktype's "never" are exported, the latter as an +- // optional property no call may set. A `not` of the empty schema makes its whole schema +- // unsatisfiable whatever sits beside it, so the sibling keywords do not matter. + // RADIANCE: a count -- minLength, maxLength, minItems, maxItems -- as the int build_repetition + // takes, or `dflt` where the schema has none. get() casts, so a bound past INT_MAX wrapped: + // Number.MAX_SAFE_INTEGER, a common way to write "no limit", came out as -1 and the grammar did +@@ -924,11 +920,74 @@ public: + return d >= (double) std::numeric_limits::max() ? std::numeric_limits::max() : (int) d; + } + ++ // RADIANCE: the schema every value satisfies, whose `not` is therefore the schema none does. ++ // `{}` and `true` are it, and so is a type list, or a union of bare types, that between them ++ // name all six JSON types -- the way Arktype exports the complement of `never` for an optional ++ // property: {"not": {"anyOf": [{"type": "string"}, {"type": "number"}, {"type": "boolean"}, ++ // {"type": "object"}, {"type": "array"}, {"type": "null"}]}}. Annotations may sit beside; any ++ // other keyword narrows the schema, and its `not` is a real complement, refused below. A union ++ // alternative that constrains more than its type is not counted, so a union is only ever read ++ // as universal when it is. ++ static bool is_universal(const json & s) { ++ if (s.is_boolean()) return s.get(); ++ if (!s.is_object()) return false; ++ static const std::unordered_set annotations = { ++ "description", "title", "default", "examples", "$comment", "deprecated", "readOnly", ++ "writeOnly", ++ }; ++ // Whether every key of `o` is an annotation or `allowed`. ++ auto only = [&](const json & o, const char * allowed) { ++ for (auto it = o.begin(); it != o.end(); ++it) { ++ if (annotations.count(it.key()) == 0 && (allowed == nullptr || it.key() != allowed)) { ++ return false; ++ } ++ } ++ return true; ++ }; ++ // The types a bare `type` names, into `out`; false for anything that is not one. ++ auto types_of = [](const json & t, std::unordered_set & out) { ++ if (t.is_string()) { ++ out.insert(t.get()); ++ return true; ++ } ++ if (!t.is_array()) return false; ++ for (const auto & e : t) { ++ if (!e.is_string()) return false; ++ out.insert(e.get()); ++ } ++ return true; ++ }; ++ auto covers = [](const std::unordered_set & ts) { ++ for (const char * t : { "string", "number", "boolean", "object", "array", "null" }) { ++ if (ts.count(t) == 0) return false; ++ } ++ return true; ++ }; ++ if (only(s, nullptr)) return true; ++ std::unordered_set ts; ++ if (s.contains("type") && only(s, "type")) { ++ return types_of(s["type"], ts) && covers(ts); ++ } ++ if (s.contains("anyOf") && only(s, "anyOf") && s["anyOf"].is_array()) { ++ for (const auto & a : s["anyOf"]) { ++ if (is_universal(a)) return true; ++ if (a.is_object() && a.contains("type") && only(a, "type")) { ++ types_of(a["type"], ts); ++ } ++ } ++ return covers(ts); ++ } ++ return false; ++ } ++ ++ // RADIANCE: the schema no value satisfies. JSON Schema spells it `false`, and TypeBox's ++ // Type.Never and Arktype's "never" export it as a `not` of the universal schema above, the ++ // latter for an optional property no call may set. Such a `not` makes its whole schema ++ // unsatisfiable whatever sits beside it, so the sibling keywords do not matter. + static bool is_unsatisfiable(const json & schema) { + if (schema.is_boolean()) return !schema.get(); + if (!schema.is_object() || !schema.contains("not")) return false; +- const json & n = schema["not"]; +- return (n.is_object() && n.empty()) || (n.is_boolean() && n.get()); ++ return is_universal(schema["not"]); + } + + static std::string _generate_constant_rule(const json & value) { +diff --git a/common/json-schema-to-grammar.h b/common/json-schema-to-grammar.h +index 86c78f3..8223dd4 100644 +--- a/common/json-schema-to-grammar.h ++++ b/common/json-schema-to-grammar.h +@@ -26,7 +26,8 @@ class common_schema_info { + + void resolve_refs(nlohmann::ordered_json & schema); + bool resolves_to_string(const nlohmann::ordered_json & schema); +- // RADIANCE: whether no value satisfies the schema -- `false`, or `{"not": {}}`. ++ // RADIANCE: whether no value satisfies the schema -- `false`, or a `not` of a schema every ++ // value satisfies (`{}`, or types naming all six JSON types). + bool unsatisfiable(const nlohmann::ordered_json & schema) const; + }; +