radiance 1.0.4

- oh-my-pi works unmodified on every Qwen model. Its requests carry a top-level
  preserve_thinking, which was refused as an unknown field; it now reaches the chat template the
  way enable_thinking does. Its task tool's `model` parameter is the `not` of every JSON type,
  which the 1.0.1 fix did not cover: any `not` that excludes every value is now an argument no
  call writes, under every chat template and Flash-Next's declared format.
- Command-line defaults and bounds for what a request leaves out. A flag left unset changes
  nothing; /server_info reports the values under request_defaults.
  - Sampling: --typical-p, --presence-penalty, --frequency-penalty, --repetition-penalty,
    --repeat-last-n, --dry-multiplier, --dry-base, --dry-allowed-length, --dry-penalty-last-n,
    --dry-sequence-breakers, --xtc-probability, --xtc-threshold.
  - Requests: --default-max-tokens N|auto, --max-tokens-cap, --max-n, --max-queued-requests,
    --max-stop-strings, --max-stop-bytes.
  - Chat template: --chat-template-kwargs JSON|@FILE sets template variables a request's own
    chat_template_kwargs override; --reasoning-format auto|none.
  - HTTP: --http-threads, --read-timeout, --write-timeout, --keep-alive-timeout, --max-body-mib,
    --retry-after, --no-cors.
  - Media: --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.
- Under --reasoning-effort none or minimal, a request that sets enable_thinking true now thinks
  instead of having the deployment default override it.
- --temp, --top-p, --min-p and --top-k refuse a value that is not a number instead of reading
  it as 0.
This commit is contained in:
Deadcode committed 2026-10-04 17:52:35 +02:00
1 parent d008fdb32b
commit 09fb41735b
23 files changed
+2478 -104

No files matched your search

+341 -32
View File
@@ -6,9 +6,19 @@
* (spec §6).
*/
#include "rad_core.h"
#include "sample/host_ref.h"
#include "server/oai.h"
#include <nlohmann/json.hpp>
#include <algorithm>
#include <cerrno>
#include <climits>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <sstream>
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 <think> 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<std::string> 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<std::string, std::string>* 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<float> 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<std::vector<std::string>>();
}
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<int64_t>(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;
}
+130 -1
View File
@@ -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<float>& v) {
if (v) { snprintf(b, sizeof b, "%s %g", k, (double)*v); add(b); }
};
auto i = [&](const char* k, const std::optional<int>& 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<int64_t>(o.max_n, cfg_.max_seqs);
o.max_n = cfg_.max_n > 0 ? (int)cfg_.max_n : (int)std::max<int64_t>(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");
+24 -4
View File
@@ -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
+5
View File
@@ -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; }
+62
View File
@@ -9,7 +9,9 @@
#include "rad_internal.h"
#include <atomic>
#include <map>
#include <memory>
#include <optional>
#include <string>
#include <unordered_map>
#include <vector>
@@ -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<float> 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<int> sample_penalty_last_n, sample_dry_allowed_length,
sample_dry_penalty_last_n;
std::optional<std::vector<std::string>> 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<std::string, std::string> 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<int64_t> image_min_pixels, image_max_pixels, video_min_pixels, video_max_pixels;
std::optional<double> video_fps;
std::optional<int32_t> video_min_frames, video_max_frames, video_max_frame_tokens;
std::optional<int64_t> 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
+43 -3
View File
@@ -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<std::string>{ "\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
+160 -38
View File
@@ -9,6 +9,7 @@
#include <cmath>
#include <cstring>
#include <ctime>
#include <limits>
#include <random>
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<double>::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<std::string>());
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<std::string>().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<string>(): 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<int64_t>(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. */
+40
View File
@@ -21,6 +21,7 @@
#include "sink.h"
#include <cstdint>
#include <map>
#include <memory>
#include <string>
#include <vector>
@@ -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<std::string, std::string> 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;
+32
View File
@@ -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();
+22 -1
View File
@@ -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<std::string, std::string> 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 */
+5 -5
View File
@@ -640,11 +640,11 @@ int chat_format_grammar(const ChatFormat& f, const ChatGrammarRequest& req, Chat
std::vector<G> 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)) {