Compare commits

...
7 Commits
Author SHA1 Message Date
Deadcode 966bda899a radiance 1.0.7
- Chat responses report usage.completion_tokens_details.reasoning_tokens: how much of
  completion_tokens was the reasoning block. A reply that ran out of max_tokens inside <think>
  now reads as that, instead of as a model that answered nothing.
- thinking_token_budget (vLLM's name; thinking_budget is read as the same field) caps the
  reasoning. At that many tokens the block is closed and the model answers from what it has
  reasoned so far. It holds under speculative decoding and at any temperature.
  --thinking-token-budget sets the default for clients that send none.
- Every completion response carries a `timings` object in llama.cpp's shape: prompt and generated
  token counts, times and rates, and the speculative tokens drafted and accepted for that request.
  It is on the buffered response, on each streamed choice's final chunk and on the usage chunk,
  so a proxy such as llama-swap can read per-request speed. /metrics stays the aggregate.
- Peer-to-peer access between the cards is checked at launch. The all-reduce kernels need it; on
  a machine where the cards cannot reach each other's memory, startup stops and names device.p2p
  instead of the first all-reduce faulting or hanging. A kernel library can require it with a
  constraint on the new "device." keys, which match the machine and not the op's parameters.
- A pool allocation the driver refuses says why, with the card's free VRAM at that moment and,
  for the host pool, the pinned memory taken against the amdgpu limit (ttm.pages_limit). Every
  rank pins its own --host-pool-mib, so --tp 2 pins it twice.
2026-10-04 21:23:07 +02:00
Deadcode 6df26315b9 radiance 1.0.6
- A text prompt to /v1/completions reads the model's control tokens as tokens, as vLLM and
  llama.cpp do. A client that renders its own chat template can send "<|im_start|>user ..." and
  the model sees the turn markers; they used to reach it as plain text. /tokenize and
  /v1/embeddings read a text prompt the same way, and a prompt that already opens with BOS gets
  no second one.
- The VRAM budget counts the engine's own hardware queues, which the driver backs with about
  33 MiB of VRAM each, and the KV tiers' copy staging. Both used to come out of
  --gpu-headroom-mib: Qwen3.8-Flash-Next ran with 9 MiB free under load against the 96 MiB it
  asked to keep, the room a kernel's first launch allocates from. The startup receipt has a
  "hardware queues" line.
- Running the whole model on the CPU (RADIANCE_HOST_DOMAIN=1 with no GPU visible) no longer
  repeats words or answers differently at temperature 0. A decode step could read its input
  token before the copy that delivers it had landed.
- The README says to clone the repository before installing.
2026-10-04 20:07:08 +02:00
Deadcode 6c11671bdd radiance 1.0.5
- Answers no longer stop partway through. A request without max_tokens got 512 tokens, and a
  reasoning model can think for thousands before it answers, so the reply ended inside the
  reasoning with finish_reason "length", which chat clients do not show. It now gets whatever
  the context leaves after the prompt, as in vLLM. --default-max-tokens N sets a number, and
  --max-tokens-cap bounds every request.
- Qwen3.8-Flash-Next in Docker without --security-opt seccomp=unconfined is refused at startup,
  in about a second, with a message naming that option. It used to load the whole model and then
  fail every request as "unsupported", and a restart policy reloaded it over and over. The
  n-gram table is read through io_uring, which Docker's default seccomp profile refuses.
- A request the engine fails says what failed, in the 500 or the stream's error event. It read
  "the engine failed this request: ok".
- Flash-Next no longer crashes at startup about one start in seven (a race between the
  parallel declares that size the activation arena).
- rad-convert no longer needs io_uring, so it converts in a sandbox that forbids it.
2026-10-04 18:44:29 +02:00
Deadcode 09fb41735b 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.
2026-10-04 17:52:35 +02:00
StillDeadcode d008fdb32b Update README.md 2026-10-04 17:51:42 +02:00
StillDeadcode 01b816f8a0 Update README.md 2026-10-04 17:51:12 +02:00
Deadcode f48786483d radiance 1.0.3
- A tool whose schema bounds a string or an array past 2000 (maxLength, minLength, maxItems,
  minItems) no longer fails every request carrying it (issue #5). The bound is held exactly, up to
  about 200,000; past that the request is refused with a 400 naming the tool's property and the
  count. A bound past 2^31, such as Number.MAX_SAFE_INTEGER, is no bound.
- Compiling a grammar with a long bounded repetition is linear in the bound instead of quadratic:
  maxLength 32000 compiles in 0.7 s instead of 2.1 s.
2026-10-04 16:30:28 +02:00
84 changed files with 5113 additions and 416 deletions

No files matched your search

+1 -1
View File
@@ -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.2 LANGUAGES C CXX)
project(radiance VERSION 1.0.7 LANGUAGES C CXX)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
+11 -6
View File
@@ -9,6 +9,8 @@ below are for **two 32 GB cards** (Radeon AI PRO R9700). The engine itself start
family; another card needs a kernel library for it. A machine with no GPU builds the host backend,
which runs the full test suite but does not serve these models at any useful speed.
If you wish to support the developement of the radiance engine you can do so [here](https://patreon.com/StillDeadCode?utm_medium=unknown&utm_source=join_link&utm_campaign=creatorshare_creator&utm_content=copyLink)
## Models
| model | container | get it | compose file |
@@ -34,11 +36,13 @@ curl -LC - -O https://huggingface.co/StillDeadcode/minicpm5-2b-fp8/resolve/main/
The host needs Docker and an `amdgpu` driver that supports ROCm 7.2; it does not need ROCm. The
image is [`stilldeadcode/radiance`](https://hub.docker.com/r/stilldeadcode/radiance), with its
kernels built for `gfx1201`. Pull it, then start a model from its compose file:
kernels built for `gfx1201`. Pull it, clone this repository for its compose files, then start a
model from one of them:
```sh
docker pull stilldeadcode/radiance
cp -r deploy/compose ~/radiance-compose && cd ~/radiance-compose
git clone https://codeberg.org/StillDeadcode/radiance.git
cp -r radiance/deploy/compose ~/radiance-compose && cd ~/radiance-compose
cp .env.example .env # set RADIANCE_MODELS, RADIANCE_STATE, RADIANCE_API_KEY, the GIDs
docker compose -f minicpm5-2b.yaml up -d # or any file from the table
docker compose -f minicpm5-2b.yaml logs -f
@@ -49,15 +53,16 @@ Every model uses both cards and the same port, so run one at a time. Running wit
the reason for each `docker run` option, is in [`docs/DOCKER.md`](docs/DOCKER.md).
To build the image yourself, for example for other cards, run `docker/build.sh -t 'gfx1200;gfx1201'`
(it needs `docker buildx` and tests the build as it goes). Then set `RADIANCE_IMAGE=radiance:latest`
in `.env`.
in the clone (it needs `docker buildx` and tests the build as it goes). Then set
`RADIANCE_IMAGE=radiance:latest` in `.env`.
## Build from source
You need Linux, a C++20 compiler, CMake 3.21+ and Ninja. For the device kernels you also need ROCm
7.2 (`hipcc`; set `ROCM_PATH` if it is not `/opt/rocm`).
You need Linux, git, a C++20 compiler, CMake 3.21+ and Ninja. For the device kernels you also need
ROCm 7.2 (`hipcc`; set `ROCM_PATH` if it is not `/opt/rocm`). Clone the repository and build in it:
```sh
git clone https://codeberg.org/StillDeadcode/radiance.git && cd radiance
./build.sh # configure, build for the cards present, run the tests
./build.sh --no-hip # host backend only
cmake -S . -B build -G Ninja -DRAD_GPU_TARGETS='gfx1201' # build for cards this machine lacks
+13
View File
@@ -303,6 +303,19 @@ typedef struct RadConstraint {
const char* sval; /* IN: space-separated set of admissible strings */
} RadConstraint;
/* A CONSTRAINT ON THE MACHINE rather than on the geometry. A key that starts "device." is matched
* against what the engine measured about the ranks' devices at launch, not against the op's
* parameters: a capability such as reaching another card's memory belongs to the machine, and
* carrying it as a parameter would have every architecture plugin declare it on every op and
* every schema grow a field for it. Such a key is in no geometry, so it changes no tuning key
* and no selection fold. Where nothing measured it -- a tool selecting without an engine -- it is
* absent, and a constraint on an absent key does not hold.
*
* device.p2p 1 when every rank's device can read and write every other rank's memory
* directly; 0 when some pair cannot. One rank has no peer to reach, and is 1. */
#define RAD_DEVICE_FACT_PREFIX "device."
#define RAD_FACT_P2P "device.p2p"
#define RAD_C(k, o, v) { (k), (o), (long long)(v), 0 }
#define RAD_CEQ(k, v) { (k), RAD_C_EQ, (long long)(v), 0 }
#define RAD_CLE(k, v) { (k), RAD_C_LE, (long long)(v), 0 }
+9
View File
@@ -165,6 +165,14 @@ public:
* laid over the real ones. */
void set_reference(const Program* ref) { ref_ = ref; }
/* WITHOUT INSTANCES: finish() selects every kernel and initialises none. For a caller that
* launches nothing -- rad-convert plans a container's stored form, which is the kernels'
* layouts and not their setup. A kernel's init is about the process it runs in (a ring, a
* peer's buffers) and the conversion is often not that process: libavx's n-gram gather
* refuses a process that may not make an io_uring ring, and a sandbox that forbids one still
* has to be able to convert the model. */
void set_instances(bool on) { instances_ = on; }
Program& program() { return prog_; }
const Program& program() const { return prog_; }
@@ -195,6 +203,7 @@ private:
Registry& reg_;
Program prog_;
const Program* ref_ = nullptr;
bool instances_ = true;
std::vector<std::string> errors_;
int status_ = RAD_OK;
+1 -1
View File
@@ -1498,7 +1498,7 @@ int Builder::finish() {
w.source.c_str(), rad_dtype_name(w.decl.dtype));
}
finish_instances();
if (instances_) finish_instances();
finish_weight_uses();
finish_layouts();
finish_kv_groups();
+2 -1
View File
@@ -319,7 +319,7 @@ std::vector<std::string> CheckpointSources::refused() const {
int rad_tools_declare(const LoadedPlugins& lp, const RadModelMeta& meta, const RadBuildCtx& ctx,
Program* out, const std::function<int(RadBuilder*, int64_t)>& also,
const Program* ref, const WeightSourceFn& sources) {
const Program* ref, const WeightSourceFn& sources, bool instances) {
if (!out) return RAD_E_INVAL;
Registry& r = rad_tools_registry();
@@ -334,6 +334,7 @@ int rad_tools_declare(const LoadedPlugins& lp, const RadModelMeta& meta, const R
Builder b(r, meta, ctx);
if (ref) b.set_reference(ref);
if (sources) b.set_sources(sources);
b.set_instances(instances);
int s = ap->arch_declare(&b, &meta, &ctx);
if (s < 0) {
+4 -1
View File
@@ -88,10 +88,13 @@ const RadChatFormat* rad_tools_chat_format(const LoadedPlugins& plugins, const R
* or initialised. The Program that comes back is for its buffers and nothing else. */
/* `sources` answers rad_weight_encoding (Builder::set_sources): a container's entries, a
* checkpoint's tensors, or a recipe. Empty, every weight is read as plain in its declared dtype. */
/* `instances` false selects every kernel and initialises none (Builder::set_instances): for a
* caller that launches nothing, such as rad-convert planning a container's stored form. */
int rad_tools_declare(const LoadedPlugins& plugins, const RadModelMeta& meta,
const RadBuildCtx& ctx, Program* out,
const std::function<int(RadBuilder*, int64_t logits_width)>& also = {},
const Program* ref = nullptr, const WeightSourceFn& sources = {});
const Program* ref = nullptr, const WeightSourceFn& sources = {},
bool instances = true);
/* A container's entries as the source of every declaration's encoding. `f` must outlive the
* declare. */
+349 -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,62 @@ 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" },
{ "--thinking-token-budget", "N", "default `thinking_token_budget` for chat requests that do not set one: at\n"
" N reasoning tokens the reasoning block is closed and the answer follows,\n"
" so a client's max_tokens is not spent on reasoning alone. Unset is no\n"
" limit. Needs a reasoning block that ends in one token, as </think> is" },
{ "--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: N, or `auto` (default),\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 +220,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. */
@@ -289,34 +453,160 @@ int config_parse(int argc, char** argv, Config* c) {
}
else if (S("--reasoning-effort")) { if (!(v = need(i))) return RAD_E_INVAL;
c->reasoning_effort = v; }
else if (S("--thinking-token-budget")) { if (!(v = need(i)) ||
!parse_int(a.c_str(), v, 0, INT32_MAX,
&c->thinking_token_budget))
return RAD_E_INVAL; }
else if (S("--generation-config")) { if (!(v = need(i))) return RAD_E_INVAL;
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 +676,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;
}
+8
View File
@@ -223,6 +223,11 @@ struct DeviceBackend {
* as device memory is shared with every process on the machine. Null on a backend with no such
* devices, which answers 0. */
int (*integrated)(int device);
/* ---- 1 when `self` can read and write `peer`'s memory directly, 0 when it cannot, < 0 when
* the backend cannot say. Asked, not enabled: rad_dev_enable_peer is the call that maps the
* memory. Null on a backend whose devices share one address space, which answers 1. */
int (*peer_access)(int self, int peer);
};
@@ -241,6 +246,9 @@ void tape_destroy(RadTape t);
int tape_record(RadTape t, int i, int* kind, uint32_t* queue);
int tape_set_overlap(RadTape t, int i, bool on);
/* The current backend's DeviceBackend::peer_access. */
int dev_peer_access(int self, int peer);
/* The current backend's DeviceBackend::vram_used. */
int dev_vram_used(int device, int64_t* out);
+4
View File
@@ -430,6 +430,10 @@ int tape_set_overlap(RadTape t, int i, bool on) {
return dev()->tape_set_overlap ? dev()->tape_set_overlap(t, i, on ? 1 : 0) : RAD_E_UNSUPPORTED;
}
bool dev_integrated(int device) { return dev()->integrated && dev()->integrated(device) > 0; }
int dev_peer_access(int self, int peer) {
if (self == peer) return 1;
return dev()->peer_access ? dev()->peer_access(self, peer) : 1;
}
size_t dev_code_mark() { return dev()->code_mark ? dev()->code_mark() : 0; }
int dev_code_runs(size_t from, size_t to, int device, std::string* why) {
if (!dev()->code_runs || from >= to) return 1;
+7
View File
@@ -251,6 +251,12 @@ int d_props(int device, RadDeviceProps* out) {
return RAD_OK;
}
int d_peer_access(int self, int peer) {
int can = 0;
HIP_TRY(hipDeviceCanAccessPeer(&can, self, peer));
return can ? 1 : 0;
}
int d_enable_peer(int self, int peer) {
if (self == peer) return RAD_OK;
int can = 0;
@@ -370,6 +376,7 @@ const DeviceBackend g_hip = {
/* Plugin device code: the AQL backend's, which owns the fat-binary registrations. */
nullptr, nullptr,
d_integrated,
d_peer_access,
};
} /* namespace */
+146 -2
View File
@@ -383,7 +383,7 @@ void Engine::phase_mark(int p) {
int Engine::fail_loop(int st) {
stopping_.store(true, std::memory_order_release);
if (barrier_) barrier_->abort();
sched_.shutdown("the engine stopped on an error and is not serving");
sched_.shutdown("the engine stopped on an error and is not serving", st < 0 ? st : RAD_E_STATE);
loop_status_.store(st < 0 ? st : RAD_E_STATE, std::memory_order_release);
return st;
}
@@ -1525,6 +1525,10 @@ int Engine::serve() {
for (auto& rk : ranks_)
rio.push_back({ rk->device, rk->ctx.stream(), &rk->program });
RAD_TRY(sched_.init(ranks_[0]->program, cfg_, kv_iface_.get(), pc_iface_.get(), rio, &geo_));
/* The step staging the budget kept room for exists now, so a checkpoint slot backed from here
* on leaves the headroom and only what is still to be built on first use. */
set_checkpoint_floors(std::max<int64_t>(cfg_.gpu_headroom_mib, 0) * (1ll << 20) +
late_lazy_bytes_);
for (auto& r : ranks_) r->sampler.attach_vocab(vocab_view_.get());
@@ -1742,6 +1746,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 +1775,47 @@ 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);
if (c.thinking_token_budget >= 0)
add("thinking_token_budget " + std::to_string(c.thinking_token_budget));
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 +2028,39 @@ 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_thinking_budget = cfg_.thinking_token_budget;
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, which is `auto` (0). That 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("a request that names no max_tokens gets what the context leaves after its prompt "
"(--default-max-tokens auto), and this model states no context; pass "
"--max-model-len, or --default-max-tokens N");
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 +2081,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 +2133,37 @@ 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());
}
/* A BUDGET THE MODEL CANNOT HOLD STOPS STARTUP, as --chat-template-kwargs does: the default
* would apply to no request at all, and the operator who set it would not find out. */
if (const std::string why = srv.check_thinking_budget(); !why.empty()) {
RAD_ERR("--thinking-token-budget %lld: %s", (long long)cfg_.thinking_token_budget,
why.c_str());
return RAD_E_INVAL;
}
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");
+9
View File
@@ -310,6 +310,15 @@ private:
* one part of the KV pool still backed on demand. Measured once at the end of bringup; it is
* not something the API promises. */
bool release_frees_card_ = true;
/* WHAT THE VRAM BUDGET KEPT FOR ALLOCATIONS MADE AFTER start(), on top of --gpu-headroom-mib:
* the step batch's staging, which serve() allocates, and what is built on first use, if
* ever -- the KV tiers' copy staging and the second compute lane's queue. The checkpoint
* slots backed at the end of bringup leave both free, and the bringup's closing reading is
* checked against both. */
int64_t late_step_bytes_ = 0;
int64_t late_lazy_bytes_ = 0;
/* Every rank's checkpoint floor: a slot is backed only while the card keeps `keep` free. */
void set_checkpoint_floors(int64_t keep);
int run_server();
/* THE KL MODE (core/kld.h), in place of run_server: the corpus's documents submitted as
* scoring requests, and every step's scored rows copied to the host and handed to `kld_`.
+187 -47
View File
@@ -188,6 +188,58 @@ static int usable_devices(std::vector<int>* out, std::string* inventory, std::st
return out->empty() ? RAD_E_DEVICE : RAD_OK;
}
/* WHY A POOL'S MEMORY WAS REFUSED, from what the machine holds now. The refusal carries the
* driver's own answer; these are the facts that explain most of them.
*
* A card refusing its weights pool after its budget was measured had that memory taken in
* between, and another process on the card is the usual taker -- the budget is measured once,
* before any rank allocates. A host pool is PINNED memory, and the amdgpu driver caps what the
* whole system may pin (ttm.pages_limit, half of RAM unless raised); every rank pins its own
* --host-pool-mib, so a second rank asks for the same amount again. */
static void report_pool_refusal(int rank, int device, const Pools& pools, const Config& cfg) {
bool card = false, host = false;
for (const Shortfall& f : pools.shortfalls()) (f.pool == "host_pool" ? host : card) = true;
if (card) {
RadDeviceProps p{};
if (rad_dev_props(device, &p) == RAD_OK)
RAD_ERR("card %d has %s of %s free now. Its budget was measured before any rank "
"allocated, so memory gone since then is another process's; rocm-smi "
"--showpids names it", device, humanb(p.vram_free).c_str(),
humanb(p.vram_bytes).c_str());
}
if (host) {
int64_t pinned = 0, mapped = 0;
rad_dev_alloc_totals(RAD_MEM_HOST_PINNED, &pinned, nullptr);
rad_dev_alloc_totals(RAD_MEM_HOST_MAPPED, &mapped, nullptr);
int64_t cap = -1, avail = -1;
{
std::ifstream f("/sys/module/ttm/parameters/pages_limit");
long long pages = 0;
if (f >> pages && pages > 0) cap = (int64_t)pages * (int64_t)sysconf(_SC_PAGESIZE);
}
{
std::ifstream f("/proc/meminfo");
std::string line;
while (std::getline(f, line)) {
long long kb = 0;
if (std::sscanf(line.c_str(), "MemAvailable: %lld kB", &kb) == 1) {
avail = (int64_t)kb * 1024;
break;
}
}
}
RAD_ERR("host: --host-pool-mib %lld is pinned once per rank, so %d rank(s) pin %s; this "
"process had taken %s of pinned host memory before rank %d's pool. The amdgpu "
"driver caps pinned memory system-wide at %s (ttm.pages_limit, half of RAM unless "
"raised), and %s of RAM is available. Lower --host-pool-mib, or raise the cap",
(long long)cfg.host_pool_mib, cfg.tp,
humanb((int64_t)cfg.tp * cfg.host_pool_mib * 1024 * 1024).c_str(),
humanb(pinned + mapped).c_str(), rank,
cap > 0 ? humanb(cap).c_str() : "an unreadable limit",
avail >= 0 ? humanb(avail).c_str() : "an unknown amount");
}
}
/* ================================================================== 2. metadata */
/* The model's metadata ONLY -- architecture id, dimensions, quantisation, vocab. Not the weights:
* which weights exist is the architecture plugin's answer, not the container's, and reading them
@@ -652,12 +704,27 @@ int Engine::plan() {
{
std::vector<VramFacts> facts;
facts.reserve(ranks_.size());
late_step_bytes_ = late_lazy_bytes_ = 0;
const int64_t ctx = cfg_.max_ctx ? cfg_.max_ctx : meta_.n_ctx_train;
for (auto& r : ranks_) {
RAD_TRY(rad_dev_set(r->device));
VramFacts f{};
/* ONE HARDWARE QUEUE'S VRAM, MEASURED BY MAKING TWO. The engine's compute stream,
* its mover's and a second compute lane are all made after this reading, and the
* driver backs each queue with VRAM the ring alone does not account for. The second
* queue is the unit, so a runtime that sets itself up on its first queue charges that
* once and to `already held`, which is read after both are gone. */
{
RadStream q[2] = { nullptr, nullptr };
RadDeviceProps a{}, b{};
if (rad_stream_create(&q[0], 0) >= 0 && rad_dev_props(r->device, &a) >= 0 &&
rad_stream_create(&q[1], 0) >= 0 && rad_dev_props(r->device, &b) >= 0)
f.queue_bytes = std::max<int64_t>(a.vram_free - b.vram_free, 0);
for (RadStream s : q) if (s) rad_stream_destroy(s);
}
f.n_queues = 2 + (r->program.scratch_regions > 1 ? 1 : 0);
RadDeviceProps props{};
rad_dev_props(r->device, &props);
VramFacts f{};
f.capacity = props.vram_bytes;
f.free = props.vram_free;
/* AN EIGHTH OF THE HOST'S MEMORY STAYS THE HOST'S on integrated graphics. The card's
@@ -702,6 +769,26 @@ int Engine::plan() {
}
f.staging = BatchBuilder::device_bytes(r->program, cfg_, kg);
if (f.staging < 0) return RAD_E_INVAL;
late_step_bytes_ = std::max(late_step_bytes_, f.staging);
int64_t lazy = r->program.scratch_regions > 1 ? f.queue_bytes : 0;
/* AND THE KV TIERS' COPY STAGING, which TierExec::device_init builds on the first
* copy out. Which groups the prefix cache indexes is settled after this split, so
* every paged group is counted: the entry it sizes can only be smaller. */
if (cfg_.prefix_cache_host_mib > 0 || cfg_.prefix_cache_disk_mib > 0) {
int64_t entry = 0, bs = 0;
int ng = 0;
for (size_t g = 0; g < r->program.kv_groups.size(); ++g) {
const KVGroupPlan* p = probe.plan((int32_t)g);
if (!p || !p->paged() || p->bytes_per_block <= 0) continue;
entry += p->bytes_per_block;
bs = bs > 0 ? std::min<int64_t>(bs, p->block_size) : p->block_size;
++ng;
}
const int64_t tier = TierExec::device_bytes(entry, ng, TierExec::sizes(entry, ctx, bs));
f.staging += tier;
lazy += tier;
}
late_lazy_bytes_ = std::max(late_lazy_bytes_, lazy);
facts.push_back(f);
}
VramBudget vb;
@@ -735,7 +822,10 @@ int Engine::plan() {
* much rather than shrinking anything. */
int s = r->pools.configure(cfg_, props.vram_bytes);
RAD_INFO("pools:\n%s", r->pools.fit_report().c_str());
if (s < 0) return s;
if (s < 0) {
report_pool_refusal(r->index, r->device, r->pools, cfg_);
return s;
}
/* Under tensor parallel the placement unit is a SHARD of a weight, so each rank plans
* against its own card's budget (spec §5.3). */
@@ -2150,20 +2240,19 @@ int Engine::configure_kv() {
* and 0.02 ms a step of the VRAM it costs. The batch is one gather per (group,
* layer) however many entries are in it, so the launches are the same either
* way -- this buys the copies, which are what there are thousands of. */
const int max_batch = (int)std::min<int64_t>(
4096, std::max<int64_t>(64, (16ll << 20) / entry_bytes));
/* A COPY OUT IS FOUR STAGING BATCHES, about 64 MiB a rank. It shares the transfer
* stream with the expert mover, so what it queues is what a promotion issued
* behind it waits for -- a few milliseconds of link at this size -- and the next
* copy goes out on the tick after this one lands, so a long conversation still
* leaves at the rate the link carries it.
*
* A RESTORE IS A WHOLE CHAIN, as long as the longest context this server takes. */
const int64_t max_copy = 4ll * max_batch;
const int64_t bs = std::max<int64_t>(1, ranks_[0]->prefix.block_size());
const int64_t max_chain =
(std::max<int64_t>(1, cfg_.max_ctx > 0 ? cfg_.max_ctx : meta_.n_ctx_train)
+ bs - 1) / bs + 1;
* A RESTORE IS A WHOLE CHAIN, as long as the longest context this server takes.
* TierExec::sizes holds the arithmetic, which the VRAM budget reserves from. */
const TierExec::Sizes tz = TierExec::sizes(
entry_bytes, cfg_.max_ctx > 0 ? cfg_.max_ctx : meta_.n_ctx_train,
ranks_[0]->prefix.block_size());
const int max_batch = tz.max_batch;
const int64_t max_copy = tz.max_copy, max_chain = tz.max_chain;
bool all = true;
for (auto& r : ranks_) {
/* ON THAT RANK'S DEVICE. rad_dev_alloc takes the CURRENT device, and the
@@ -2345,6 +2434,18 @@ static void bind_kv_pools(const Program& p, const KVManager& kv, std::vector<KVP
}
/* ================================================================== start */
void Engine::set_checkpoint_floors(int64_t keep) {
for (auto& r : ranks_) {
const int dev = r->device;
r->kv.set_checkpoint_floor([dev](int64_t* free_now) -> int {
RadDeviceProps p{};
RAD_TRY(rad_dev_props(dev, &p));
*free_now = p.vram_free;
return RAD_OK;
}, keep);
}
}
int Engine::start() {
std::vector<int> devs;
std::string inventory;
@@ -2378,6 +2479,40 @@ int Engine::start() {
ranks_.push_back(std::move(r));
}
/* PEER ACCESS, MEASURED BEFORE ANYTHING IS SELECTED. A kernel that reads or writes another
* card's memory says so with a constraint on device.p2p (rad_types.h), and the selector reads
* it from here: on a machine where some pair of the ranks' cards cannot reach each other such a
* kernel is not selected, and declare names the constraint instead of the all-reduce faulting
* or hanging on its first message. Every ordered pair, because access is granted one way at a
* time. */
{
long long p2p = 1;
std::string blocked;
for (int i = 0; i < cfg_.tp; ++i)
for (int j = 0; j < cfg_.tp; ++j) {
if (i == j) continue;
const int a = dev_peer_access(devs[i], devs[j]);
if (a < 0) {
RAD_ERR("device: could not ask whether card %d can reach card %d's memory: %s",
devs[i], devs[j], rad_dev_last_error());
return a;
}
if (a == 0) {
p2p = 0;
blocked += fmt("%s%d->%d", blocked.empty() ? "" : ", ", devs[i], devs[j]);
}
}
rad_tools_registry().set_device_fact(RAD_FACT_P2P, p2p);
if (cfg_.tp > 1) {
if (p2p) RAD_INFO("device: the %d cards reach each other's memory directly (peer to "
"peer)", cfg_.tp);
else RAD_WARN("device: no peer-to-peer access between cards %s. A kernel that needs "
"it (device.p2p == 1) is not selected; if nothing else implements its "
"op, startup stops below naming it. IOMMU settings and the PCIe "
"topology decide this, not radiance", blocked.c_str());
}
}
RAD_TRY(declare());
/* --debug-graph stops here on purpose: everything it prints is known between declare and
@@ -2650,18 +2785,14 @@ int Engine::start() {
* HEADROOM. Rank 0's free list hands the ids out and every rank writes its shard of a snapshot
* into the same slot of its own pool; backing a slot on one card and meeting a refusal on the
* other at the snapshot copy would stop the engine mid-serve. See
* KVManager::set_checkpoint_floor for why the floor is the headroom. */
* KVManager::set_checkpoint_floor for why the floor is the headroom.
*
* AND NOT INTO WHAT THE BUDGET KEPT FOR LATER either: the step staging serve() allocates, and
* what is built on first use. serve() lowers the floor once the staging exists. */
const int64_t headroom = std::max<int64_t>(cfg_.gpu_headroom_mib, 0) * (1ll << 20);
const int64_t keep_now = headroom + late_step_bytes_ + late_lazy_bytes_;
if (!ranks_.empty()) {
const int64_t keep = std::max<int64_t>(cfg_.gpu_headroom_mib, 0) * (1ll << 20);
for (auto& r : ranks_) {
const int dev = r->device;
r->kv.set_checkpoint_floor([dev](int64_t* free_now) -> int {
RadDeviceProps p{};
RAD_TRY(rad_dev_props(dev, &p));
*free_now = p.vram_free;
return RAD_OK;
}, keep);
}
set_checkpoint_floors(keep_now);
std::vector<KVManager*> peers;
for (size_t i = 1; i < ranks_.size(); ++i) peers.push_back(&ranks_[i]->kv);
ranks_[0]->kv.set_checkpoint_peers(std::move(peers));
@@ -2679,21 +2810,22 @@ int Engine::start() {
RAD_TRY(lead.back_free_checkpoints(&gone));
if (gone > 0) {
const int64_t stride = lead.checkpoint_stride();
const int64_t keep = std::max<int64_t>(cfg_.gpu_headroom_mib, 0) * (1ll << 20);
int64_t short_by = 0;
for (auto& r : ranks_) {
RadDeviceProps p{};
if (rad_dev_props(r->device, &p) < 0) continue;
short_by = std::max(short_by, gone * stride - (p.vram_free - keep));
short_by = std::max(short_by, gone * stride - (p.vram_free - keep_now));
}
RAD_WARN("checkpoint slots: %lld of %lld backed (%s each), %lld withdrawn -- one more "
"would take a card under the %s --gpu-headroom-mib, the room a kernel's first "
"launch allocates from. The prefix cache holds %lld linear-state snapshots on "
"the card and its retention policy decides which. The budget counted all "
"%lld; the card is %s short of them, which is allocations made after the "
"budget was resolved.",
"would take a card under the %s it has to keep free: the %s "
"--gpu-headroom-mib, the room a kernel's first launch allocates from, and %s "
"the budget kept for the step staging and for what is built on first use. "
"The prefix cache holds %lld linear-state snapshots on the card and its "
"retention policy decides which. The budget counted all %lld; the card is %s "
"short of them, which is allocations made after the budget was resolved.",
(long long)(asked - gone), (long long)asked, humanb(stride).c_str(),
(long long)gone, humanb(keep).c_str(), (long long)(asked - gone),
(long long)gone, humanb(keep_now).c_str(), humanb(headroom).c_str(),
humanb(late_step_bytes_ + late_lazy_bytes_).c_str(), (long long)(asked - gone),
(long long)asked, humanb(short_by).c_str());
}
}
@@ -2703,20 +2835,29 @@ int Engine::start() {
RadDeviceProps props{};
if (rad_dev_props(r->device, &props) < 0 || props.vram_bytes <= 0) continue;
/* AGAINST THE HEADROOM AND WHAT THE BUDGET KEPT FOR LATER, because both are still free
* here: the step staging is allocated by serve(), and the KV tiers' staging and a second
* compute lane are built on first use. A card at exactly the headroom now would be under
* it once those exist. */
const int64_t MiB = 1024 * 1024;
const int64_t want = std::max<int64_t>(cfg_.gpu_headroom_mib, 0) * MiB;
const int64_t late = late_step_bytes_ + late_lazy_bytes_;
const int64_t want = headroom + late;
const int64_t got = props.vram_free;
const std::string asked =
late > 0 ? fmt("%s (the %s --gpu-headroom-mib and %s kept for the step staging and "
"for what is built on first use)", humanb(want).c_str(),
humanb(headroom).c_str(), humanb(late).c_str())
: fmt("%s --gpu-headroom-mib", humanb(want).c_str());
if (got < want) {
/* WHAT THIS SHORTFALL THREATENS is whatever allocates after startup: a kernel's code
* object, loaded on its FIRST launch, and a spilling kernel's scratch, sized on its
* first launch by the whole grid. Neither is knowable when the budget is resolved, and
* running out for either is a fault inside the HIP runtime rather than an error. */
RAD_WARN("card %d settled at %s free against the %s --gpu-headroom-mib asked to keep. "
"The difference is allocations made after the budget was resolved, and it is "
"the room a kernel's first launch allocates from. Raise --gpu-headroom-mib by "
"at least %s so the budget is resolved against the right number.",
r->device, humanb(got).c_str(), humanb(want).c_str(),
humanb(want - got).c_str());
RAD_WARN("card %d settled at %s free against %s. The difference is allocations "
"made after the budget was resolved, and it comes out of the room a kernel's "
"first launch allocates from. Raise --gpu-headroom-mib by at least %s so the "
"budget is resolved against the right number.",
r->device, humanb(got).c_str(), asked.c_str(), humanb(want - got).c_str());
}
else if (got > want + 256 * MiB) {
/* AND "TOO MUCH" IS ONLY A FAULT WHERE SOMEBODY STATED THE BUDGET. Where the resolver
@@ -2726,20 +2867,19 @@ int Engine::start() {
* Warning here would contradict that receipt and send the reader looking for a flag
* to set. */
if (cfg_.vram_budget_derived)
RAD_INFO("card %d settled at %s free against the %s --gpu-headroom-mib asked to "
"keep. The split accounted for it: neither pool could address another "
"byte, which is the `unusable` line of the VRAM budget above.",
r->device, humanb(got).c_str(), humanb(want).c_str());
RAD_INFO("card %d settled at %s free against %s. The split accounted for it: "
"neither pool could address another byte, which is the `unusable` line of "
"the VRAM budget above.",
r->device, humanb(got).c_str(), asked.c_str());
else
RAD_WARN("card %d settled at %s free against the %s --gpu-headroom-mib asked to "
"keep, so %s is unused. On a model that does not fit in VRAM every unused "
"GiB is weight that has to be moved instead of read, and that is decode "
"step time.",
r->device, humanb(got).c_str(), humanb(want).c_str(),
RAD_WARN("card %d settled at %s free against %s, so %s is unused. On a model that "
"does not fit in VRAM every unused GiB is weight that has to be moved "
"instead of read, and that is decode step time.",
r->device, humanb(got).c_str(), asked.c_str(),
humanb(got - want).c_str());
} else
RAD_INFO("card %d settled at %s free, against the %s --gpu-headroom-mib asked to keep",
r->device, humanb(got).c_str(), humanb(want).c_str());
RAD_INFO("card %d settled at %s free, against %s",
r->device, humanb(got).c_str(), asked.c_str());
}
return RAD_OK;
}
+11 -3
View File
@@ -43,6 +43,9 @@ MemAllocator& rad_malloc_allocator() { static MallocAllocator a; return a; }
/* ------------------------------------------------------------------ Shortfall */
std::string Shortfall::str() const {
if (!refused.empty())
return fmt("%s: %s of %s refused: %s", pool.c_str(), what.c_str(),
humanb(wanted).c_str(), refused.c_str());
return fmt("%s: %s wanted %s, %s available -- short by %s",
pool.c_str(), what.c_str(), humanb(wanted).c_str(),
humanb(available).c_str(), humanb(missing()).c_str());
@@ -81,8 +84,11 @@ int Pool::init(std::string_view nm, int64_t bytes, int kind, MemAllocator* a, bo
base_ = a->alloc(bytes_, kind);
if (!base_) {
/* Refuse; do not retry smaller. An engine that quietly re-optimises the split is an
* engine whose benchmarks do not reproduce (spec §6). */
shortfalls_.push_back({name_, "backing allocation", bytes_, 0});
* engine whose benchmarks do not reproduce (spec §6). The allocator's reason goes with
* it: the device layer says what the driver answered. */
const char* why = a == &rad_device_allocator() ? rad_dev_last_error() : nullptr;
shortfalls_.push_back({name_, "backing allocation", bytes_, 0,
why && *why ? why : "the allocator returned nothing"});
bytes_ = 0;
return RAD_E_NOMEM;
}
@@ -131,7 +137,9 @@ int Pool::init_elastic(std::string_view nm, int64_t bytes, int kind, MemAllocato
/* Refuse; do not retry smaller. An address range is not memory -- a reservation that
* fails on a 64-bit card is a bug and not a budget, and quietly halving it would hide the
* bug behind a pool that cannot grow to what the operator asked for. */
shortfalls_.push_back({ name_, "address reservation", bytes_, 0 });
const char* why = rad_dev_last_error();
shortfalls_.push_back({ name_, "address reservation", bytes_, 0,
*why ? why : "the device layer gave no reason" });
bytes_ = 0;
return rc;
}
+4
View File
@@ -54,6 +54,10 @@ struct Shortfall {
std::string what; /* what was being reserved when it ran out */
int64_t wanted = 0;
int64_t available = 0;
/* A backing allocation the allocator refused: there is no "available" to report, only the
* allocator's own sentence for why, which is what tells an out-of-memory card from a pinned-
* memory limit from a driver that would not map the range. */
std::string refused;
int64_t missing() const { return wanted - available; }
std::string str() const;
};
+15 -4
View File
@@ -49,6 +49,11 @@ int vram_budget_resolve(Config& cfg, const std::vector<VramFacts>& per_rank, Vra
freeb = std::min(freeb, f.free);
b.arena = std::max(b.arena, f.arena);
b.staging = std::max(b.staging, f.staging);
if ((int64_t)f.n_queues * f.queue_bytes > b.queues) {
b.queues = (int64_t)f.n_queues * f.queue_bytes;
b.n_queues = f.n_queues;
b.queue_bytes = f.queue_bytes;
}
b.kv_ceiling = std::max(b.kv_ceiling, f.kv_ceiling);
b.kv_fixed = std::max(b.kv_fixed, f.kv_fixed);
b.statics = std::max(b.statics, f.statics);
@@ -83,7 +88,7 @@ int vram_budget_resolve(Config& cfg, const std::vector<VramFacts>& per_rank, Vra
b.derived_kv = want_kv;
/* What is left after the terms nobody gets to spend. */
int64_t fixed = b.already_held + b.headroom + b.arena + b.staging;
int64_t fixed = b.already_held + b.headroom + b.arena + b.staging + b.queues;
if (!want_w) fixed += cfg.vram_weights_mib * kMiB; /* a stated pool is fixed too */
if (!want_kv) fixed += cfg.vram_kv_mib * kMiB;
b.claimable = b.capacity - fixed;
@@ -95,7 +100,8 @@ int vram_budget_resolve(Config& cfg, const std::vector<VramFacts>& per_rank, Vra
" already held %10s (driver context, code objects, anything else on the card)\n"
" --gpu-headroom-mib %10s\n"
" activation arena %10s (buffer plan + kernel scratch)\n"
" step staging %10s (block tables + media staging)\n"
" step staging %10s (block tables, media and KV tier staging)\n"
" hardware queues %10s (%d at %s each, measured)\n"
"%s%s"
" ------------------------------\n"
" SHORT BY %10s\n"
@@ -103,6 +109,7 @@ int vram_budget_resolve(Config& cfg, const std::vector<VramFacts>& per_rank, Vra
"or free the card.\n",
humanb(b.capacity).c_str(), humanb(b.already_held).c_str(),
humanb(b.headroom).c_str(), humanb(b.arena).c_str(), humanb(b.staging).c_str(),
humanb(b.queues).c_str(), b.n_queues, humanb(b.queue_bytes).c_str(),
want_w ? "" : fmt(" --vram-weights-mib %10s (stated)\n",
humanb(cfg.vram_weights_mib * kMiB).c_str()).c_str(),
want_kv ? "" : fmt(" --vram-kv-mib %10s (stated)\n",
@@ -252,14 +259,17 @@ int vram_budget_resolve(Config& cfg, const std::vector<VramFacts>& per_rank, Vra
* line is not padding: to_mib truncates, and what it drops is real VRAM that ends up beside
* the headroom. */
const int64_t granted = cfg.vram_weights_mib * kMiB + cfg.vram_kv_mib * kMiB;
const int64_t unclaimed = b.capacity - b.already_held - b.arena - b.staging - b.stage - granted;
const int64_t unclaimed = b.capacity - b.already_held - b.arena - b.staging - b.queues - b.stage -
granted;
const double ela = b.elastic > 0 ? (double)b.elastic : 1.0;
b.report = fmt(
"VRAM budget, per card:\n"
" card total %10s\n"
" already held %10s measured: driver context, code objects, anything else resident\n"
" activation arena %10s computed from the buffer plan\n"
" step staging %10s the step batch's block tables and media staging\n"
" step staging %10s the step batch's block tables and media staging, and the\n"
" KV tiers' copy staging\n"
" hardware queues %10s %d a card at %s each, measured: the engine's streams\n"
" %-18s %10s %s\n"
" ------------------------------\n"
" claimable %10s\n"
@@ -277,6 +287,7 @@ int vram_budget_resolve(Config& cfg, const std::vector<VramFacts>& per_rank, Vra
" could not place\n",
humanb(b.capacity).c_str(), humanb(b.already_held).c_str(), humanb(b.arena).c_str(),
humanb(b.staging).c_str(),
humanb(b.queues).c_str(), b.n_queues, humanb(b.queue_bytes).c_str(),
shared ? "left to the host" : "--gpu-headroom-mib", humanb(b.headroom).c_str(),
shared ? "integrated graphics: this memory is the host's; --vram-kv-mib states a pool "
"outright"
+12 -1
View File
@@ -60,7 +60,15 @@ struct VramFacts {
int64_t capacity = 0; /* RadDeviceProps::vram_bytes -- totalGlobalMem */
int64_t free = 0; /* RadDeviceProps::vram_free, measured now */
int64_t arena = 0; /* arena_plan_bytes() for this rank's program, total incl. scratch */
int64_t staging = 0; /* BatchBuilder::device_bytes(): the step slab and the media staging */
int64_t staging = 0; /* BatchBuilder::device_bytes(): the step slab and the media staging,
* and TierExec::device_bytes() when a KV tier is configured */
/* THE HARDWARE QUEUES this rank creates after `free` was read -- its compute stream, the expert
* mover's, and the second compute lane where the program declares one -- at `queue_bytes`
* each. MEASURED, by making one: a queue's kernel-argument ring is the engine's, and the
* driver backs every queue with VRAM of its own beside it (33 MiB a queue on an R9700, eight
* times the ring). */
int n_queues = 0;
int64_t queue_bytes = 0;
int64_t kv_ceiling = 0; /* KVManager::ceiling(max_ctx) for this rank's declared groups */
int64_t kv_fixed = 0; /* KVManager::fixed_bytes(): the part of the ceiling that is state */
/* weight_footprint() for this rank, which under tensor parallel is already this card's even
@@ -78,6 +86,9 @@ struct VramFacts {
* operator stated the budgets -- the placement report and the pool report both want the totals. */
struct VramBudget {
int64_t capacity = 0, already_held = 0, headroom = 0, arena = 0, staging = 0;
int64_t queues = 0; /* n_queues * queue_bytes, from the rank that needs most */
int n_queues = 0;
int64_t queue_bytes = 0;
int64_t claimable = 0; /* after the fixed terms above */
int64_t statics = 0; /* off the top, before the ratio sees anything */
int64_t elastic = 0; /* claimable - statics: what the ratio divides */
+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; }
+7
View File
@@ -181,6 +181,12 @@ public:
* loads anything, once it has chosen its cards. */
void set_code_device(int device) { code_device_ = device; }
/* WHAT THE ENGINE MEASURED ABOUT THE RANKS' DEVICES, for the constraints on "device." keys
* (rad_types.h). Set before the first selection, by whoever chose the devices; a registry
* nobody told anything has no facts, and a kernel constrained on one is not selected. */
void set_device_fact(std::string_view key, long long v) { device_facts_.set_i(key, v); }
const Geometry& device_facts() const { return device_facts_; }
void close(); /* fini instances, close hooks, dlclose, forget everything */
const std::vector<Plugin>& plugins() const { return plugins_; }
@@ -327,6 +333,7 @@ private:
};
int code_device_ = 0;
Geometry device_facts_;
TuneCache tune_;
int stage_(const std::string& path, Staged* out);
+13 -3
View File
@@ -23,14 +23,24 @@ namespace {
/* True when every constraint holds. Otherwise `why` names the FIRST one that did not and what it
* wanted: "no kernel" on its own is not an answer anyone can act on, and the first failure is the
* one a reader can fix -- listing all four of a row's unmet constraints buries it. */
bool row_matches(const KernelRow& r, const Geometry& g, const std::vector<std::string>& skip,
std::string* why) {
bool row_matches(const KernelRow& r, const Geometry& g, const Geometry& facts,
const std::vector<std::string>& skip, std::string* why) {
static const size_t kFact = std::strlen(RAD_DEVICE_FACT_PREFIX);
for (int i = 0; i < r.info->n_constraints; ++i) {
const RadConstraint& c = r.info->constraints[i];
/* A constraint on a RAD_DERIVED parameter the caller did not name is not a predicate on
* the question -- it IS the answer, read back afterwards. Matching on it would make the
* kernel unreachable by the only query anyone can ask (rad_abi.h, spec §7.2). */
if (c.key && std::find(skip.begin(), skip.end(), c.key) != skip.end()) continue;
/* A "device." key is a fact about the machine, read from what the engine measured. */
if (c.key && std::strncmp(c.key, RAD_DEVICE_FACT_PREFIX, kFact) == 0) {
if (constraint_holds(c, facts)) continue;
if (why)
*why = facts.has(c.key)
? constraint_why(c, facts) + " -- this machine, measured at launch"
: std::string(c.key) + " is not known: nothing measured this machine";
return false;
}
if (!constraint_holds(c, g)) {
if (why) *why = constraint_why(c, g);
return false;
@@ -111,7 +121,7 @@ const KernelRow* Registry::select(std::string_view op, const Geometry& g, int do
}
std::string whynot;
bool ok = row_matches(*r, g, derived_keys, &whynot);
bool ok = row_matches(*r, g, device_facts_, derived_keys, &whynot);
if (ok && accept && *accept) {
whynot = (*accept)(*r, g);
ok = whynot.empty();
+23
View File
@@ -159,6 +159,11 @@ static const RadConstraint kCNorm4096[] = {
static const RadConstraint kCTie[] = {
RAD_CGE("M", 1),
};
/* A kernel that reaches another card's memory: a constraint on the machine, not the geometry. */
static const RadConstraint kCPeer[] = {
RAD_CGE("M", 1),
RAD_CEQ(RAD_FACT_P2P, 1),
};
/* Constraint ORDER is the order the miss message reports in: the first unmet one is what a reader
* is told, so the cheapest and most identifying predicate goes first. */
static const RadConstraint kCAttn[] = {
@@ -197,6 +202,10 @@ static const RadOpSchema kSchemas[] = {
"a derived key its kernel does not pin" },
{ "t_skinny", kPGemm, NELEM(kPGemm), kOpdGemm, NELEM(kOpdGemm), "a range with a hole in it" },
{ "t_eq", kPTie, NELEM(kPTie), kOpdNorm, NELEM(kOpdNorm), "an EQ band boundary" },
{ "t_peer", kPTie, NELEM(kPTie), kOpdNorm, NELEM(kOpdNorm),
"a peer kernel with a fallback beneath it" },
{ "t_peer_only", kPTie, NELEM(kPTie), kOpdNorm, NELEM(kOpdNorm),
"a peer kernel and nothing else" },
};
static const RadKernelInfo kKernels[] = {
@@ -236,6 +245,20 @@ static const RadKernelInfo kKernels[] = {
.computes = "nothing; a registry row", .shape = "any", .dtypes = "any",
.domain = RAD_DOMAIN_HOST, .priority = 10, .launch = t_launch },
/* Peer access is the machine's: the direct row needs it, the staged one does not. */
{ .name = "t_peer_direct", .op = "t_peer", .family = "ar",
.computes = "nothing; a registry row", .shape = "M >= 1, cards reach each other",
.dtypes = "any", .domain = RAD_DOMAIN_DEVICE, .priority = 20,
.constraints = kCPeer, .n_constraints = NELEM(kCPeer), .launch = t_launch },
{ .name = "t_peer_staged", .op = "t_peer", .family = "ar",
.computes = "nothing; a registry row", .shape = "M >= 1", .dtypes = "any",
.domain = RAD_DOMAIN_DEVICE, .priority = 10,
.constraints = kCTie, .n_constraints = NELEM(kCTie), .launch = t_launch },
{ .name = "t_peer_only_direct", .op = "t_peer_only", .family = "ar",
.computes = "nothing; a registry row", .shape = "M >= 1, cards reach each other",
.dtypes = "any", .domain = RAD_DOMAIN_DEVICE, .priority = 10,
.constraints = kCPeer, .n_constraints = NELEM(kCPeer), .launch = t_launch },
/* Same op, same priority, same constraints. Ties break on declaration order, so t_tie_first
* wins -- and if it ever does not, the tie rule has silently changed. */
{ .name = "t_tie_first", .op = "t_tie", .family = "norm",
+116
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>
@@ -371,6 +373,50 @@ public:
enum class ReqState { Waiting, Running, Preempted, Finished, Failed, Cancelled };
/* A CHAT REPLY'S REASONING BLOCK, AS TOKENS. The reply parser reads the block in text
* (core/text/chatparse.h); this is the same block named by token id, so the engine can count it
* and close it without detokenising. It exists only where both markers the reply needs are
* single tokens -- `<think>` and `</think>` are, on every model this engine serves -- and
* `close < 0` says it does not: such a reply's reasoning is still split out as text, but it is
* not counted and no budget can be held on it.
*
* The block is read where the parser reads it: at the start of the reply. It is open from the
* first token when the generation prompt opened it (`starts_open`), or opens on `open` as the
* reply's first token, and the first `close` ends it. A reply that starts any other way has no
* block. */
struct ReasoningSpan {
int32_t open = -1; /* the token a reply opens its own block with; -1 for none */
int32_t close = -1; /* the token that ends the block; -1: no countable block */
bool starts_open = false; /* the generation prompt left the reply inside the block */
bool known() const { return close >= 0; }
};
/* A reply's position relative to its ReasoningSpan, advanced one emitted token at a time. The
* server counts with it and the sampler enforces a budget with it, and both must agree on where
* the block ends, so there is one definition. */
struct ReasoningCount {
enum State : uint8_t { Lead, Think, Done };
State st = Lead;
int64_t tokens = 0; /* reasoning tokens: the markers the reply wrote, and the body */
int64_t body = 0; /* the tokens between the markers, which a budget limits */
void start(const ReasoningSpan& s) {
st = !s.known() ? Done : s.starts_open ? Think : Lead;
tokens = body = 0;
}
void push(const ReasoningSpan& s, int32_t tok) {
if (st == Lead) {
if (s.open >= 0 && tok == s.open) { st = Think; ++tokens; }
else st = Done;
} else if (st == Think) {
++tokens;
if (tok == s.close) st = Done;
else ++body;
}
}
bool inside() const { return st == Think; }
};
struct SamplingParams {
float temp = 1.0f;
int top_k = 0; /* 0 = off */
@@ -392,6 +438,13 @@ struct SamplingParams {
std::string grammar; /* GBNF, or "" */
std::vector<std::string> dry_seq_breakers;
/* THE REPLY'S REASONING BLOCK, and how many tokens its body may run to. -1 is no limit. At
* the limit the sampler masks every position still inside the block to `reasoning.close`, so
* the block ends there and the answer follows -- vLLM's `thinking_token_budget`. A budget
* needs a known span; the server refuses one it cannot hold. */
ReasoningSpan reasoning;
int32_t thinking_budget = -1;
/* A LAZY GRAMMAR CONSTRAINS NOTHING UNTIL A TRIGGER FIRES, and that is the only shape in
* which a tool-calling chat template can be enforced: the reply is free prose until the
* model starts writing a call, and grammar-shaped from there. Without this a request that
@@ -649,6 +702,8 @@ struct Config {
/* The chat endpoint's default `reasoning_effort`, empty for the template's own default.
* Passed through verbatim: the legal set belongs to the template, not to us. */
std::string reasoning_effort;
/* --thinking-token-budget: the chat endpoint's default `thinking_token_budget`, -1 for none. */
int64_t thinking_token_budget = -1;
int port = 8000;
/* --api-key: the bearer key every request but the probes and the dashboard page must carry.
* Empty serves without one. */
@@ -673,6 +728,67 @@ 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,
* which is the server's default, `auto`; 0 is `auto` stated (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
+28 -19
View File
@@ -100,40 +100,46 @@ class Geometry {
public:
Geometry() = default;
/* The cached RadParam view holds char* into THIS object's own strings. An implicit copy would
* carry those pointers into the copy along with dirty_ = false, so the copy would hand a
* kernel pointers that dangle the moment the source dies -- and every Resolved holds a
* Geometry while every Band holds two, so this type is copied constantly. A copy therefore
* takes the storage and NOT the view, and rebuilds on first use.
/* THE RadParam VIEW IS KEPT CURRENT BY EVERY WRITE, never built on first read. It holds char*
* into this object's own strings, and a view rebuilt lazily from a const reader is a write
* that two readers can make at once: the sizing declares of one rank all read the real
* program's geometries side by side (Engine::probe_arena_levels), and one clearing the view
* while another filled it is the heap corruption that crashed startup. So params() writes
* nothing, and a Geometry nobody is writing can be read from any number of threads.
*
* The move is the same rule for a different reason: a moved-from vector's buffer may be
* stolen, so the view's pointers stop meaning anything even though nothing was destroyed. */
* A copy takes the storage and builds its own view, because the source's points into the
* source. A move takes the view along with the storage: the vectors hand over their arrays,
* so every string stays where it was and every pointer stays good. The moved-from object is
* emptied, view included, so it is a valid empty geometry rather than one whose view names
* strings it no longer owns. */
Geometry(const Geometry& o)
: keys_(o.keys_), svals_(o.svals_), ivals_(o.ivals_), dvals_(o.dvals_), kinds_(o.kinds_) {}
: keys_(o.keys_), svals_(o.svals_), ivals_(o.ivals_), dvals_(o.dvals_), kinds_(o.kinds_) {
rebuild();
}
Geometry& operator=(const Geometry& o) {
if (this != &o) {
keys_ = o.keys_; svals_ = o.svals_; ivals_ = o.ivals_; dvals_ = o.dvals_;
kinds_ = o.kinds_;
view_.clear(); dirty_ = true;
rebuild();
}
return *this;
}
Geometry(Geometry&& o) noexcept
: keys_(std::move(o.keys_)), svals_(std::move(o.svals_)),
ivals_(std::move(o.ivals_)), dvals_(std::move(o.dvals_)),
kinds_(std::move(o.kinds_)) {
o.view_.clear(); o.dirty_ = true;
view_(std::move(o.view_)), ivals_(std::move(o.ivals_)),
dvals_(std::move(o.dvals_)), kinds_(std::move(o.kinds_)) {
o.clear();
}
Geometry& operator=(Geometry&& o) noexcept {
if (this != &o) {
keys_ = std::move(o.keys_); svals_ = std::move(o.svals_);
view_ = std::move(o.view_);
ivals_ = std::move(o.ivals_); dvals_ = std::move(o.dvals_);
kinds_ = std::move(o.kinds_);
view_.clear(); dirty_ = true;
o.view_.clear(); o.dirty_ = true;
o.clear();
}
return *this;
}
@@ -149,17 +155,20 @@ public:
const char* get_s(std::string_view k) const;
bool has(std::string_view k) const;
/* A view suitable for RadArgs.p. Valid while this object lives. */
const RadParam* params() const;
int n_params() const;
/* A view suitable for RadArgs.p. Valid while this object lives and is not written. */
const RadParam* params() const { return view_.data(); }
int n_params() const { return (int)view_.size(); }
std::string str() const; /* "M=64 N=8192 K=5120 dtype=w4a8", for diagnostics */
private:
std::vector<std::string> keys_, svals_;
std::vector<RadParam> view_;
mutable bool dirty_ = true;
void rebuild() const;
void rebuild();
void clear() noexcept {
keys_.clear(); svals_.clear(); view_.clear(); ivals_.clear(); dvals_.clear();
kinds_.clear();
}
std::vector<long long> ivals_;
std::vector<double> dvals_;
std::vector<int> kinds_;
+22
View File
@@ -86,6 +86,28 @@ int TierExec::configure(Registry* reg, KVManager* kv, IdleTiers* tiers, SSDTier*
return RAD_OK;
}
TierExec::Sizes TierExec::sizes(int64_t entry_bytes, int64_t max_ctx, int64_t block_size) {
Sizes s;
if (entry_bytes <= 0) return s;
/* 16 MiB of staging a rank, as entries, between 64 and 4096 of them: the reasons are at the
* call in bringup. A copy out is four batches, and a restore is a whole chain, as long as the
* longest context the server takes. */
s.max_batch = (int)std::min<int64_t>(4096, std::max<int64_t>(64, (16ll << 20) / entry_bytes));
s.max_copy = 4ll * s.max_batch;
const int64_t bs = std::max<int64_t>(1, block_size);
s.max_chain = (std::max<int64_t>(1, max_ctx) + bs - 1) / bs + 1;
return s;
}
/* What device_init() allocates, each allocation rounded to the pool granule the card hands VRAM
* out in. */
int64_t TierExec::device_bytes(int64_t entry_bytes, int n_groups, const Sizes& s) {
if (entry_bytes <= 0 || n_groups <= 0 || s.max_batch <= 0) return 0;
const int64_t idx_n = (int64_t)n_groups * (s.max_copy + (int64_t)kRing * s.max_chain);
return align_up((int64_t)s.max_batch * entry_bytes, (int64_t)RAD_ALIGN_POOL) +
align_up(idx_n * (int64_t)sizeof(int32_t), (int64_t)RAD_ALIGN_POOL);
}
void TierExec::close() {
/* Nothing may still be reading the buffers about to be freed. */
if (stream_) (void)rad_stream_sync(stream_);
+8
View File
@@ -76,6 +76,14 @@ public:
bool enabled() const { return enabled_; }
std::string report() const { return report_; }
/* THE SIZES A CONFIGURE IS GIVEN, from one entry's bytes on this rank, the longest context and
* the block size, and the VRAM device_init() then takes for them. The VRAM budget reserves
* device_bytes() before any of this exists and bringup configures with sizes(), so the two
* cannot drift apart. */
struct Sizes { int max_batch = 0; int64_t max_copy = 0, max_chain = 0; };
static Sizes sizes(int64_t entry_bytes, int64_t max_ctx, int64_t block_size);
static int64_t device_bytes(int64_t entry_bytes, int n_groups, const Sizes& s);
/* DECIDING AND DOING ARE SEPARATE, and under tensor parallelism that is the point. The policy
* is one object describing CONVERSATIONS, which are not sharded; the transfer is per rank,
* because each rank holds its own shard of every block. So the leader plans, every rank runs
+4
View File
@@ -2,12 +2,16 @@
#include "wtab.h"
#include "device/device.h"
#include "rad_internal.h"
namespace rad {
int wtab_patch(const WtabPatch& p, RadStream s) {
if (p.n == 0) return RAD_OK;
/* After the stream's queued work, for the reason step_advance gives: a host stream is a queue
* with a worker, and a write made ahead of it changes a table that work issued earlier reads. */
if (device_is_host()) {
RAD_TRY(rad_stream_sync(s));
for (uint32_t i = 0; i < p.n; ++i) *p.dst[i] = p.val[i];
return RAD_OK;
}
+2 -2
View File
@@ -24,8 +24,8 @@ struct WtabPatch {
void* val[kWtabPatch] = {};
};
/* Enqueue `p` on `s`. Under the host backend, whose streams run their work as it is issued and
* whose device memory is host memory, the writes happen here. */
/* Enqueue `p` on `s`. Under the host backend, whose device memory is host memory, the writes
* happen here once `s` has run everything issued before them. */
int wtab_patch(const WtabPatch& p, RadStream s);
} /* namespace rad */
+80 -61
View File
@@ -30,11 +30,6 @@ using gbnf::match_token;
using gbnf::kMaxCompileBytes;
using gbnf::kMaxNesting;
/* A repetition `S{m,n}` expands into rules, and the expansion multiplies. Past this many the
* grammar is a denial of service against the machine that compiled it, so refuse rather than
* allocate. Upstream calls it MAX_REPETITION_THRESHOLD and picks the same number. */
static constexpr uint64_t MAX_REPETITION_THRESHOLD = 2000;
namespace gbnf {
void throw_set_limit() {
@@ -254,6 +249,19 @@ static const char* parse_int(const char* src) {
return pos;
}
/* The repetition count written in [src, end), which parse_int has checked is digits. A count past
* 2^64 - 2 is refused here; any smaller one is the compile budget's to judge, by what it expands
* to (handle_repetitions). UINT64_MAX itself is reserved for "no maximum". */
static uint64_t parse_count(const char* src, const char* end) {
uint64_t v = 0;
for (const char* p = src; p < end; ++p)
if (__builtin_mul_overflow(v, 10u, &v) ||
__builtin_add_overflow(v, (uint64_t)(*p - '0'), &v) || v == UINT64_MAX)
throw std::runtime_error("repetition count " + std::string(src, (size_t)(end - src)) +
" is past what any grammar can expand to");
return v;
}
static std::pair<uint32_t, const char*> parse_char(const char* src) {
if (*src == '\\') {
switch (src[1]) {
@@ -311,12 +319,14 @@ static std::pair<uint32_t, const char*> parse_token(const VocabView* vocab, cons
/* What a symbol costs beyond its name: the map node that holds it and the rule slot it owns. */
static constexpr uint64_t kSymbolOverhead = 64 + sizeof(GbnfRule);
/* Saturating: `bytes` may be a count from the grammar text times a size, and a sum that wrapped
* would pass. budget_used_ never exceeds the budget, so the comparison cannot overflow. */
void GbnfParser::charge(uint64_t bytes) {
budget_used_ += bytes;
if (budget_used_ > kMaxCompileBytes)
if (bytes > kMaxCompileBytes - budget_used_)
throw std::runtime_error("the grammar expands past " +
std::to_string(kMaxCompileBytes >> 20) + " MiB when compiled; "
"reduce its repetition counts or the size of what they repeat");
budget_used_ += bytes;
}
uint32_t GbnfParser::get_symbol_id(const char* src, size_t len) {
@@ -358,14 +368,21 @@ const char* GbnfParser::parse_sequence(const char* src, const std::string& rule_
GbnfRule& rule, bool is_nested) {
size_t last_sym_start = rule.size();
const char* pos = src;
uint64_t n_prev_rules = 1;
/* S{m,n} is rewritten into rules rather than counted at match time, which is what keeps the
* state machine a pushdown automaton with no counters in it:
* S{m,n} -> S S ... (m times) S'(n-m), S'(x) ::= S S'(x-1) |
* S{m,} -> S S ... (m times) S', S' ::= S S' |
* S* -> S{0,} S+ -> S{1,} S? -> S{0,1}
* The cost is that the rule count multiplies, which is why the threshold above exists. */
*
* WHAT BOUNDS THE EXPANSION IS ITS SIZE, charged to the compile budget before any of it is
* made, and not a count of repetitions. Upstream refuses any count past 2000, and a JSON
* schema's `maxLength: 8000` -- an ordinary bound on a tool's free-text argument -- failed
* every request carrying the tool. The expansion is linear in the count: each optional link
* is a rule of a few elements and a generated name, and nothing after the parse is worse than
* linear in the rules (find_left_recursion, and the mask plan, which gives every link past
* the longest token one class). So `[^"]{0,8000}` costs about a megabyte and compiles to the
* plan `[^"]{0,1999}` does, and a count the budget cannot hold is refused naming its rule. */
auto handle_repetitions = [&](uint64_t min_times, uint64_t max_times) {
const bool no_max = max_times == UINT64_MAX;
if (last_sym_start == rule.size())
@@ -379,54 +396,59 @@ const char* GbnfParser::parse_sequence(const char* src, const std::string& rule_
const GbnfRule prev_rule(rule.begin() + (std::ptrdiff_t)last_sym_start, rule.end());
uint64_t total_rules = 1;
if (!no_max && max_times > 0) total_rules = max_times;
else if (min_times > 0) total_rules = min_times;
/* A refusal names the repetition: the count is what a client wrote. */
try {
/* The copies about to be made: the operand once per required count beyond the
* first, and once more in each optional rule with its reference, ALT and END. The
* counts are the grammar's own, up to 2^64 - 2, so the arithmetic saturates where it
* would wrap: a count past the budget is refused here, before the loops below start.
* Each generated rule's name and slot are charged again as it is made
* (generate_symbol_id). */
{
const uint64_t w = prev_rule.size();
const uint64_t n_rest = no_max ? 1 : max_times - min_times;
uint64_t req = 0, opt = 0, copies = 0, bytes = 0;
const bool wraps =
__builtin_mul_overflow(min_times > 1 ? min_times - 1 : 0, w, &req) ||
__builtin_mul_overflow(n_rest, w + 3, &opt) ||
__builtin_add_overflow(req, opt, &copies) ||
__builtin_mul_overflow(copies, (uint64_t)sizeof(GbnfElement), &bytes);
charge(wraps ? UINT64_MAX : bytes);
}
if (n_prev_rules * total_rules >= MAX_REPETITION_THRESHOLD)
throw std::runtime_error("repeated rules multiplied past the sane limit; reduce the "
"number of repetitions or the rule's complexity");
if (min_times == 0) {
rule.resize(last_sym_start);
} else {
for (uint64_t i = 1; i < min_times; i++)
rule.insert(rule.end(), prev_rule.begin(), prev_rule.end());
}
/* The copies about to be made: the operand once per required count beyond the first, and
* once more in each optional rule with its reference, ALT and END. Both counts are below
* MAX_REPETITION_THRESHOLD here, so the product cannot overflow. */
{
const uint64_t w = prev_rule.size();
const uint64_t n_rest = no_max ? 1 : max_times - min_times;
const uint64_t copies = (min_times > 1 ? (min_times - 1) * w : 0) + n_rest * (w + 3);
charge(copies * sizeof(GbnfElement));
uint32_t last_rec_rule_id = 0;
const uint64_t n_opt = no_max ? 1 : max_times - min_times;
GbnfRule rec_rule(prev_rule);
for (uint64_t i = 0; i < n_opt; i++) {
rec_rule.resize(prev_rule.size());
const uint32_t rec_rule_id = generate_symbol_id(rule_name);
if (i > 0 || no_max)
rec_rule.push_back({ GRE_RULE_REF, no_max ? rec_rule_id : last_rec_rule_id });
rec_rule.push_back({ GRE_ALT, 0 });
rec_rule.push_back({ GRE_END, 0 });
add_rule(rec_rule_id, rec_rule);
last_rec_rule_id = rec_rule_id;
}
if (n_opt > 0) rule.push_back({ GRE_RULE_REF, last_rec_rule_id });
} catch (const std::runtime_error& ex) {
throw std::runtime_error("the repetition {" + std::to_string(min_times) + "," +
(no_max ? std::string() : std::to_string(max_times)) + "}: " +
ex.what());
}
if (min_times == 0) {
rule.resize(last_sym_start);
} else {
for (uint64_t i = 1; i < min_times; i++)
rule.insert(rule.end(), prev_rule.begin(), prev_rule.end());
}
uint32_t last_rec_rule_id = 0;
const uint64_t n_opt = no_max ? 1 : max_times - min_times;
GbnfRule rec_rule(prev_rule);
for (uint64_t i = 0; i < n_opt; i++) {
rec_rule.resize(prev_rule.size());
const uint32_t rec_rule_id = generate_symbol_id(rule_name);
if (i > 0 || no_max)
rec_rule.push_back({ GRE_RULE_REF, no_max ? rec_rule_id : last_rec_rule_id });
rec_rule.push_back({ GRE_ALT, 0 });
rec_rule.push_back({ GRE_END, 0 });
add_rule(rec_rule_id, rec_rule);
last_rec_rule_id = rec_rule_id;
}
if (n_opt > 0) rule.push_back({ GRE_RULE_REF, last_rec_rule_id });
n_prev_rules *= total_rules;
};
while (*pos) {
if (*pos == '"') { /* literal string */
pos++;
last_sym_start = rule.size();
n_prev_rules = 1;
while (*pos != '"') {
if (!*pos) throw std::runtime_error("unexpected end of input");
auto cp = parse_char(pos);
@@ -439,7 +461,6 @@ const char* GbnfParser::parse_sequence(const char* src, const std::string& rule_
GreType start_type = GRE_CHAR;
if (*pos == '^') { pos++; start_type = GRE_CHAR_NOT; }
last_sym_start = rule.size();
n_prev_rules = 1;
while (*pos != ']') {
if (!*pos) throw std::runtime_error("unexpected end of input");
auto cp = parse_char(pos);
@@ -459,7 +480,6 @@ const char* GbnfParser::parse_sequence(const char* src, const std::string& rule_
if (*pos == '!') { type = GRE_TOKEN_NOT; pos++; }
auto tp = parse_token(vocab_, pos);
last_sym_start = rule.size();
n_prev_rules = 1;
rule.push_back({ type, tp.first });
pos = parse_space(tp.second, is_nested);
} else if (is_word_char(*pos)) { /* rule reference */
@@ -467,25 +487,21 @@ const char* GbnfParser::parse_sequence(const char* src, const std::string& rule_
const uint32_t ref = get_symbol_id(pos, (size_t)(name_end - pos));
pos = parse_space(name_end, is_nested);
last_sym_start = rule.size();
n_prev_rules = 1;
rule.push_back({ GRE_RULE_REF, ref });
} else if (*pos == '(') { /* grouping */
if (++depth_ > kMaxNesting)
throw std::runtime_error("parentheses nest more than " +
std::to_string(kMaxNesting) + " deep");
pos = parse_space(pos + 1, true);
const uint32_t n_before = (uint32_t)symbol_ids_.size();
const uint32_t sub_rule_id = generate_symbol_id(rule_name);
pos = parse_alternates(pos, rule_name, sub_rule_id, true);
--depth_;
n_prev_rules = std::max(1u, (uint32_t)symbol_ids_.size() - n_before);
last_sym_start = rule.size();
rule.push_back({ GRE_RULE_REF, sub_rule_id });
if (*pos != ')') throw std::runtime_error(std::string("expecting ')' at ") + pos);
pos = parse_space(pos + 1, is_nested);
} else if (*pos == '.') { /* any char */
last_sym_start = rule.size();
n_prev_rules = 1;
rule.push_back({ GRE_CHAR_ANY, 0 });
pos = parse_space(pos + 1, is_nested);
} else if (*pos == '*') {
@@ -502,7 +518,7 @@ const char* GbnfParser::parse_sequence(const char* src, const std::string& rule_
if (!is_digit_char(*pos))
throw std::runtime_error(std::string("expecting an int at ") + pos);
const char* int_end = parse_int(pos);
const uint64_t min_times = std::stoull(std::string(pos, (size_t)(int_end - pos)));
const uint64_t min_times = parse_count(pos, int_end);
pos = parse_space(int_end, is_nested);
uint64_t max_times = UINT64_MAX;
@@ -513,7 +529,7 @@ const char* GbnfParser::parse_sequence(const char* src, const std::string& rule_
pos = parse_space(pos + 1, is_nested);
if (is_digit_char(*pos)) {
const char* e = parse_int(pos);
max_times = std::stoull(std::string(pos, (size_t)(e - pos)));
max_times = parse_count(pos, e);
pos = parse_space(e, is_nested);
}
if (*pos != '}') throw std::runtime_error(std::string("expecting '}' at ") + pos);
@@ -521,10 +537,6 @@ const char* GbnfParser::parse_sequence(const char* src, const std::string& rule_
} else {
throw std::runtime_error(std::string("expecting ',' at ") + pos);
}
const bool has_max = max_times != UINT64_MAX;
if (min_times > MAX_REPETITION_THRESHOLD ||
(has_max && max_times > MAX_REPETITION_THRESHOLD))
throw std::runtime_error("number of repetitions exceeds the sane limit");
handle_repetitions(min_times, max_times);
} else {
break;
@@ -544,7 +556,14 @@ const char* GbnfParser::parse_rule(const char* src) {
throw std::runtime_error(std::string("expecting ::= at ") + pos);
pos = parse_space(pos + 3, true);
pos = parse_alternates(pos, name, rule_id, false);
/* An error inside a rule names the rule. A grammar written from a JSON schema or a tool list
* names its rules after the tool and the property, so this is what tells a client which part
* of its request the grammar could not hold. */
try {
pos = parse_alternates(pos, name, rule_id, false);
} catch (const std::runtime_error& ex) {
throw std::runtime_error("rule '" + name + "': " + ex.what());
}
if (*pos == '\r') pos += pos[1] == '\n' ? 2 : 1;
else if (*pos == '\n') pos++;
+41 -8
View File
@@ -928,7 +928,7 @@ struct Grammar {
std::vector<std::vector<uint32_t>> tops; /* class -> its terminal elements, reachable */
std::vector<std::vector<uint32_t>> below; /* rule -> entries that can sit below it */
std::vector<char> below_done;
std::vector<uint32_t> stamp; /* rule -> the below_of search that last saw it */
std::vector<uint32_t> stamp; /* rule -> the below search that last saw it */
uint32_t stamp_now = 0;
explicit Grammar(const GbnfRuleSet& r, uint32_t rt) : R(r), root(rt) {}
@@ -1376,16 +1376,49 @@ static const std::vector<uint32_t>& below_of(Grammar& G, uint32_t r, OpWork& wor
return out;
}
/* The entries that can sit directly below any of `pos`, as (class, element), sorted. */
/* The entries that can sit directly below any of `pos`, as (class, element), sorted.
*
* ONE WALK FROM ALL OF `pos`'s RULES, not one below_of per rule. The links of a repetition chain
* hand over to each other by tail reference, so the walk up from one link climbs every link above
* it; and every link past the longest token is one class, so one key's positions are all n links
* of `x{0,n}`. Walked a rule at a time that is n^2/2 steps -- `maxLength: 32000` took two seconds
* to compile, and 48000 was refused for the work. Walked from every rule at once, each rule is
* visited once. A rule whose own set is already known contributes it and is not climbed past. A
* key of one rule, the common case, keeps the memo. */
static void preds_of(Grammar& G, const MaskPlan& P, const std::vector<uint32_t>& pos,
std::vector<std::pair<uint32_t, uint32_t>>* out, OpWork& work) {
out->clear();
uint32_t last_rule = kNone;
for (uint32_t p : pos) {
const uint32_t r = G.erule[p];
if (r == last_rule) continue;
last_rule = r;
for (uint32_t u : below_of(G, r, work)) out->push_back({ P.cls[u], u });
const uint32_t first = pos.empty() ? kNone : G.erule[pos[0]];
bool one_rule = true;
for (uint32_t p : pos)
if (G.erule[p] != first) { one_rule = false; break; }
if (one_rule) {
if (first != kNone)
for (uint32_t u : below_of(G, first, work)) out->push_back({ P.cls[u], u });
} else {
const uint32_t mark = ++G.stamp_now;
std::vector<uint32_t> todo;
for (uint32_t p : pos) {
const uint32_t r = G.erule[p];
if (G.stamp[r] != mark) { G.stamp[r] = mark; todo.push_back(r); }
}
work.add(pos.size());
while (!todo.empty()) {
const uint32_t b = todo.back();
todo.pop_back();
if (G.below_done[b]) {
for (uint32_t u : G.below[b]) out->push_back({ P.cls[u], u });
work.add(G.below[b].size() + 1);
continue;
}
for (uint32_t q : G.refs_to[b]) {
const uint32_t u = q + 1;
if (!is_end_of_sequence(&G.R.elems[u])) out->push_back({ P.cls[u], u });
}
for (uint32_t t : G.rev_tail[b])
if (G.stamp[t] != mark) { G.stamp[t] = mark; todo.push_back(t); }
work.add(G.refs_to[b].size() + G.rev_tail[b].size() + 1);
}
}
std::sort(out->begin(), out->end());
out->erase(std::unique(out->begin(), out->end()), out->end());
+46 -1
View File
@@ -382,7 +382,8 @@ int Sampler::check_request(const SamplingParams& sp, std::string* why) const {
if (!missing) missing = need(sp.typical_p < 1.0f, op_typical_, "sample_typical");
if (!missing) missing = need(sp.xtc_probability > 0.0f, op_xtc_, "sample_xtc");
if (!missing) missing = need(dry_on(sp), op_dry_, "sample_dry");
if (!missing) missing = need(!sp.grammar.empty(), op_mask_, "sample_mask");
if (!missing) missing = need(!sp.grammar.empty() || sp.thinking_budget >= 0, op_mask_,
"sample_mask");
if (!missing) missing = need(penalties_on(sp), op_penalties_, "sample_penalties");
if (missing) {
if (why) *why = std::string("no kernel resolved for '") + missing + "'";
@@ -456,6 +457,7 @@ int Sampler::begin_request(uint64_t req_id, const SamplingParams& sp, std::strin
}
}
st.think.start(sp.reasoning);
seqs_[req_id] = std::move(st);
return RAD_OK;
}
@@ -591,8 +593,25 @@ int Sampler::build_step(const std::vector<Request*>& reqs) {
if (walk) gr->push_state();
bool dead = false;
/* THE REASONING BUDGET, walked over the window as the grammar is. Position k is inside the
* block or not according to the committed reply and drafts 0..k-1, which is the only
* history under which its token is ever emitted; a draft that ends the block early is
* accepted or rejected like any other. */
const bool budget = st && sp.thinking_budget >= 0 && sp.reasoning.known();
ReasoningCount think;
if (budget) {
if (st->think_seen > (size_t)n_out) {
st->think.start(sp.reasoning);
st->think_seen = 0;
}
for (; st->think_seen < (size_t)n_out; ++st->think_seen)
st->think.push(sp.reasoning, r->output[st->think_seen]);
think = st->think;
}
for (int k = 0; k < n_pos; ++k) {
if (walk && k > 0 && !dead && gr->accept_token(r->draft[k - 1]) < 0) dead = true;
if (budget && k > 0) think.push(sp.reasoning, r->draft[k - 1]);
const int64_t row = n_seq_++;
DeviceSampleParams& p = params_stage_[row];
@@ -744,6 +763,9 @@ int Sampler::build_step(const std::vector<Request*>& reqs) {
}
}
}
if (budget && think.inside() && think.body >= sp.thinking_budget)
force_close(p, row, sp.reasoning.close);
}
/* Back to where the sequence actually is. The tokens it really accepted are applied by
@@ -767,6 +789,29 @@ int Sampler::build_step(const std::vector<Request*>& reqs) {
return RAD_OK;
}
void Sampler::force_close(DeviceSampleParams& p, int64_t row, int32_t close) {
uint32_t* dst = mask_stage_ + row * mask_words_;
const int64_t at = (int64_t)close - cfg_.vocab_off;
const bool local = at >= 0 && at < cfg_.n_vocab_local;
if (p.flags & RAD_SP_MASK) {
/* The grammar's mask for this row. Under a split vocabulary the whole one is still in
* mask_full_, and the close may be another rank's column. */
const bool admitted =
vocab_parallel()
? close < (int64_t)mask_full_.size() * 32 &&
(mask_full_[(size_t)(close >> 5)] >> (uint32_t)(close & 31)) & 1u
: local && (dst[at >> 5] >> (uint32_t)(at & 31)) & 1u;
if (!admitted) return;
}
/* ONE ADMISSIBLE TOKEN, on whichever rank holds its column. The others mask the whole row
* out, which the candidate merge reads as no candidate from them (the grammar's own masks do
* the same when the admissible set lives on one shard). */
std::memset(dst, 0, (size_t)mask_words_ * 4);
if (local) dst[at >> 5] |= 1u << (uint32_t)(at & 31);
p.mask_row = (int32_t)row;
p.flags |= RAD_SP_MASK;
}
int Sampler::build_greedy(int64_t n) {
if (!declared_) return RAD_E_STATE;
if (n < 0) return RAD_E_INVAL;
+11
View File
@@ -218,8 +218,19 @@ private:
struct SeqState {
std::unique_ptr<GrammarBackend> grammar;
DryBreakers dry;
/* Where the reply stands against its reasoning block, over `output[0, think_seen)`.
* Advanced by build_step over what each commit appended, so a step costs the tokens it
* added and not the reply's length. Read only when the request carries a budget. */
ReasoningCount think;
size_t think_seen = 0;
};
/* Mask staged row `row` to the reasoning block's close token: the budget is spent and the
* sampled position is still inside the block. A grammar already masking the row keeps the
* last word -- the close is forced only where the grammar admits it, and a row whose grammar
* forbids it is left to the grammar and forced at a later position. */
void force_close(DeviceSampleParams& p, int64_t row, int32_t close);
SamplerConfig cfg_{};
const VocabView* vocab_ = nullptr;
bool declared_ = false;
+6 -2
View File
@@ -7,9 +7,13 @@ namespace rad {
int step_advance(const AdvanceArgs& a, RadStream s) {
if (a.n_seq <= 0) return RAD_OK;
/* THE HOST BACKEND RUNS A STREAM'S WORK AS IT IS ISSUED, and its device memory is host memory,
* so the rows run here, now, in the order the stream would have run them. */
/* THE HOST BACKEND'S STREAMS ARE QUEUES, each run by its own worker thread (device/host.cpp),
* and its device memory is host memory. So the rows run here once the stream has finished
* everything issued before this call, which is where the kernel would run in stream order.
* Without the wait they can read a sampled token or a staged row whose copy is still queued,
* and the next step then continues from the token before it. */
if (device_is_host()) {
RAD_TRY(rad_stream_sync(s));
for (int i = 0; i < a.n_seq; ++i) adv_row(a, i);
return RAD_OK;
}
+3 -2
View File
@@ -19,8 +19,9 @@
* chunk, a history row for positions the host already knows -- with rows whose positions come from
* the card; `rows[0][i]` says which, and the advance leaves a host row exactly as it was uploaded.
*
* The same code runs on the host backend, where device memory is host memory and a stream runs
* its work as it is issued (advance_impl.h is shared by both builds).
* The same code runs on the host backend, where device memory is host memory: the rows run on the
* issuing thread once the stream has drained, which is their place in stream order
* (advance_impl.h is shared by both builds).
*/
#pragma once
#include <cstdint>
+16 -8
View File
@@ -98,6 +98,7 @@ int Scheduler::init(Program& prog, const Config& cfg, IKVManager* kv, IPrefixCac
ctx_limit_ = builder_.max_ctx();
n_deferred_ = 0;
closed_ = false;
closed_status_ = RAD_E_STATE;
/* Everything the step path touches is reserved here. A vector that grows during a step is an
* allocator call on the path this whole component exists to keep clear. */
@@ -152,7 +153,7 @@ int Scheduler::add_locked(std::unique_ptr<Request> r) {
* listening to -- and the refusal says why. */
if (closed_) {
RAD_WARN("request %llu refused: %s", (unsigned long long)r->id, closed_reason_);
server::sink_fail(r->sink, RAD_E_STATE);
server::sink_fail(r->sink, closed_status_, closed_reason_);
return RAD_E_STATE;
}
@@ -256,7 +257,8 @@ int Scheduler::set_draft(uint64_t id, const int32_t* tokens, int n) {
*
* Appending to `Request::output` is not enough on its own: without a push the engine generates
* correctly, step after step, while the HTTP thread waits in `Sink::wait()` until the client times
* out. `sink_push`, `sink_finish` and `sink_prompt_stats` are called from here and nowhere else.
* out. Every sink_* call -- push, finish, prompt stats, admission and drafts -- is made from this
* file and nowhere else.
*
* A push returns false ONLY on overflow, and an overflowing sink has already failed the request --
* a stream missing tokens in the middle is worse than one that stops and says so -- so the return
@@ -312,7 +314,7 @@ void Scheduler::trim_prefix_cache() {
}
void Scheduler::close_request(SchedReq& s, ReqState st, const char* reason, bool defer_free,
bool publish) {
bool publish, int status, const char* why) {
/* PUBLISH BEFORE FREEING. This is the only moment the sequence's whole prefix is both
* computed and still owned, and it is what makes the cache a cache rather than a permanently
* empty lookup: insert() takes its own KV references, so the blocks survive the free below.
@@ -359,7 +361,8 @@ void Scheduler::close_request(SchedReq& s, ReqState st, const char* reason, bool
/* Terminal, and idempotent on the sink's side: the first call wins, so a cancel racing a
* natural stop does not produce two finish reasons. This is the last thing the producer does
* to the sink, and the HTTP thread is waiting on exactly it. */
server::sink_finish(s.req->sink, finish_of(st, s.req->finish_reason));
if (st == ReqState::Failed && status < 0) server::sink_fail(s.req->sink, status, why);
else server::sink_finish(s.req->sink, finish_of(st, s.req->finish_reason));
}
int Scheduler::cancel(uint64_t id) {
@@ -467,10 +470,11 @@ void Scheduler::release_deferred() {
sweep_deferred();
}
void Scheduler::shutdown(const char* reason) {
void Scheduler::shutdown(const char* reason, int status) {
std::lock_guard<std::mutex> lk(mu_);
closed_ = true;
closed_reason_ = reason ? reason : "the engine has stopped";
closed_status_ = status < 0 ? status : RAD_E_STATE;
/* Copied first: close_request erases from both queues. */
std::vector<int32_t> live(running_);
live.insert(live.end(), waiting_.begin(), waiting_.end());
@@ -478,7 +482,7 @@ void Scheduler::shutdown(const char* reason) {
SchedReq& s = *reqs_[(size_t)slot];
if (!s.req) continue;
close_request(s, ReqState::Failed, closed_reason_, /*defer_free=*/false,
/*publish=*/false);
/*publish=*/false, closed_status_, closed_reason_);
++m_.failed;
completed_.push_back(s.req->id);
}
@@ -823,6 +827,7 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget) {
if (s.card < 0) { s.card = free_cards_.back(); free_cards_.pop_back(); }
r.state = ReqState::Running;
s.running = true;
server::sink_admitted(r.sink);
s.sched_tokens = (int32_t)want;
s.pending_ckpt = ckpt;
++m_.admitted;
@@ -944,7 +949,8 @@ const RadBatch* Scheduler::step() {
kv_->can_ever_fit(r.n_computed + want)
? " and nothing lower-priority is left to preempt"
: " at any occupancy");
close_request(s, ReqState::Failed, "kv_exhausted");
close_request(s, ReqState::Failed, "kv_exhausted", false, true, RAD_E_FULL,
"the KV pool cannot hold it");
++m_.failed;
completed_.push_back(r.id);
failed = true;
@@ -1035,7 +1041,8 @@ const RadBatch* Scheduler::step() {
RAD_WARN("request %llu failed: %lld tokens leave no room in a %lld-token context",
(unsigned long long)s.req->id, (long long)s.seq_len(),
(long long)ctx_limit_);
close_request(s, ReqState::Failed, "context_length_exceeded");
close_request(s, ReqState::Failed, "context_length_exceeded", false, true,
RAD_E_FULL, "it leaves no room in the context");
++m_.failed;
completed_.push_back(s.req->id);
continue;
@@ -1483,6 +1490,7 @@ int Scheduler::commit(const StepResult& res) {
draft_.observe(e.n_spec, a);
m_.draft_tokens += e.n_spec;
m_.draft_accepted += a;
server::sink_drafts(r.sink, e.n_spec, a);
}
}
s.n_draft = 0;
+10 -4
View File
@@ -238,8 +238,9 @@ public:
/* THE ENGINE HAS STOPPED AND WILL RUN NO MORE STEPS. Every request still queued or running is
* failed with `reason` so its connection is answered rather than left waiting on a step that
* will never come, and any request submitted afterwards is refused the same way. */
void shutdown(const char* reason);
* will never come, and any request submitted afterwards is refused the same way. `status` is
* what stopped it, and what each of those requests reports. */
void shutdown(const char* reason, int status = RAD_E_STATE);
/* The waiting queue in SERVICE order, by request id -- what the live view shows and what a
* test asserts a preempted request re-entered at the front of. Returns how many were written. */
@@ -522,6 +523,7 @@ private:
/* Set by shutdown(); add() refuses from then on. */
bool closed_ = false;
const char* closed_reason_ = "";
int closed_status_ = RAD_E_STATE;
/* THE LONGEST SEQUENCE THIS DEPLOYMENT CAN ADDRESS, prompt and output together. The batch
* builder sizes its block tables for it and the rotary tables are this long, so no position
@@ -631,9 +633,13 @@ private:
/* lifecycle */
/* `publish` is false only when the engine is shutting down: a sequence the device may have
* left half-computed is not worth indexing, and nothing will ever hit it. */
* left half-computed is not worth indexing, and nothing will ever hit it.
*
* A FAILED REQUEST SAYS WHAT FAILED: its sink is failed with `status` and `why`, which the
* server puts in the error the client gets. RAD_OK leaves a sink that has failed already (an
* overflow) as it is. */
void close_request(SchedReq& s, ReqState st, const char* reason, bool defer_free = false,
bool publish = true);
bool publish = true, int status = RAD_OK, const char* why = nullptr);
/* What reap() does once nothing points at the slot any more: give the blocks back, forget the
* id, destroy the Request and return the slot. Called by reap() directly, or by the sweep in
* commit() for a request whose reap arrived while something still pointed at it. */
+4
View File
@@ -618,6 +618,10 @@ public:
if (why) *why = perr;
return ps;
}
const ReasoningMarkers rm = rp->reasoning();
out->think_open = rm.open;
out->think_close = rm.close;
out->think_starts_open = rm.starts_open;
out->parser = std::make_shared<ReplyParserBridge>(std::move(rp));
return RAD_OK;
}
+47 -4
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)
@@ -176,9 +177,10 @@ HttpResponse Server::handle_tokenize(const HttpRequest& req) {
} else {
if (prom == b.end() || !prom->is_string())
return error_response(err_bad("prompt", "must be a string, or send `messages`"));
/* Encoded as /v1/completions encodes it, so the count is the count that endpoint sees. */
toks = deps_.tok->encode(prom->get<std::string>(),
get_bool_or(b, "add_special_tokens", true),
/*parse_special=*/false);
/*parse_special=*/true);
}
json o;
@@ -273,8 +275,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 +296,45 @@ 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);
defs["thinking_token_budget"] = opt_.default_thinking_budget < 0
? json(nullptr) : json(opt_.default_thinking_budget);
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
+13 -6
View File
@@ -299,12 +299,12 @@ class ITokenizer {
public:
virtual ~ITokenizer() = default;
/* `parse_special` is a security parameter, not a convenience one, and it is why this takes
* three arguments rather than two. A rendered chat template contains control tokens that must
* be recognised as themselves; raw user content must NOT be, because otherwise a user who
* types "<|im_start|>system" reaches the system role. The server passes true for the one and
* false for the other, and there is no default because a default is how the wrong one gets
* picked silently. */
/* `parse_special` decides whether a control token spelled out in the text is that token or
* its characters, and there is no default because a default is how the wrong one gets picked
* silently. Text the server is sent as a whole prompt is parsed: a rendered chat template
* carries the control tokens that frame its turns, and a raw /v1/completions prompt is the
* client's own rendering of the same, as vLLM and llama.cpp read it. Text that must reach the
* model as characters is encoded with false. */
virtual std::vector<int32_t> encode(const std::string& text, bool add_special,
bool parse_special) const = 0;
virtual std::string decode(const std::vector<int32_t>& toks) const = 0;
@@ -391,6 +391,13 @@ struct ChatRender {
/* The tokens that parser must be able to SEE. See ITokenizer::detokenizer. */
std::vector<std::string> preserved_tokens;
/* THE REASONING BLOCK THIS RENDER LEAVES THE REPLY FACING, as the parser reads it: the
* markers with their optional whitespace trimmed, and whether the reply starts inside the
* block. Empty `think_close` is a model with no reasoning block. The server turns these into
* token ids (ReasoningSpan) to count the block and to hold a budget on it. */
std::string think_open, think_close;
bool think_starts_open = false;
};
class IChatTemplate {
+288 -51
View File
@@ -9,6 +9,7 @@
#include <cmath>
#include <cstring>
#include <ctime>
#include <limits>
#include <random>
namespace rad {
@@ -201,7 +202,8 @@ 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",
"thinking_token_budget", "thinking_budget",
};
const char* kAcceptedCompletion[] = { "prompt", "echo" };
@@ -311,15 +313,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 +342,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 +414,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 +472,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 +488,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 +552,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 +577,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 +616,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 +682,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 +714,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 +1118,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 +1142,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. */
@@ -1035,6 +1158,74 @@ static int clamp_max_tokens(size_t n_prompt, const OaiLimits& lim, const char* f
/* ================================================================== chat */
/* THE REASONING BLOCK BY TOKEN ID, and the budget on it.
*
* The render names the block's markers as text; the engine counts and closes it by token, so
* the markers are encoded here, once per request. A marker that is not one token leaves the span
* unknown: the reply's reasoning is still split out, but it is not counted and cannot be closed
* by forcing a token. The opener matters only to a reply that must open its own block.
*
* `thinking_token_budget` is vLLM's name for the field and `thinking_budget` Qwen's API's; both
* are read, as max_tokens and max_completion_tokens are. A budget the span cannot hold is a 400
* naming why -- accepting it and generating unbounded reasoning is the outcome this file's
* header forbids. The deployment's default applies only where it can be held: a reply whose
* block cannot be counted gets none, as it would on a model with no reasoning block at all. */
static int parse_thinking_budget(const json& b, const OaiDeps& d, const OaiLimits& lim,
const ChatRender& render, SamplingParams* sp, ApiError* err) {
ReasoningSpan span;
size_t n_close = 0, n_open = 0;
if (!render.think_close.empty() && d.tok) {
const std::vector<int32_t> c = d.tok->encode(render.think_close, false, true);
std::vector<int32_t> o;
if (!render.think_open.empty()) o = d.tok->encode(render.think_open, false, true);
n_close = c.size();
n_open = o.size();
if (c.size() == 1 && (render.think_starts_open || o.size() == 1)) {
span.close = c[0];
span.open = o.size() == 1 ? o[0] : -1;
span.starts_open = render.think_starts_open;
}
}
sp->reasoning = span;
int64_t budget = -1;
const char* named = nullptr;
for (const char* k : { "thinking_token_budget", "thinking_budget" }) {
auto it = b.find(k);
if (it == b.end() || it->is_null()) continue;
int64_t v = 0;
if (!get_int(b, k, &v, err)) return RAD_E_INVAL;
if (v < 0) { *err = err_bad(k, "must be >= 0"); return RAD_E_INVAL; }
if (named && v != budget) {
*err = err_bad(k, std::string("disagrees with ") + named + ", which is the same field");
return RAD_E_INVAL;
}
budget = v;
named = k;
}
if (!named) {
if (span.known()) sp->thinking_budget = (int32_t)lim.default_thinking_budget;
return RAD_OK;
}
if (!span.known()) {
std::string why;
if (render.think_close.empty())
why = "this model's chat template has no reasoning block to hold a budget on";
else if (n_close != 1)
why = "this model's reasoning block ends in `" + render.think_close + "`, which is " +
std::to_string(n_close) + " tokens, and a budget is held by forcing that end "
"as one token";
else
why = "this reply has to open its own reasoning block, and the opener `" +
render.think_open + "` is " + std::to_string(n_open) + " tokens, so the block "
"cannot be found by token";
*err = err_unsupported(named, why);
return RAD_E_UNSUPPORTED;
}
sp->thinking_budget = (int32_t)budget;
return RAD_OK;
}
int parse_chat_request(const std::string& body, const OaiDeps& d, const OaiLimits& lim,
OaiRequest* out, ApiError* err) {
json b;
@@ -1225,6 +1416,7 @@ int parse_chat_request(const std::string& body, const OaiDeps& d, const OaiLimit
out->reply_parser = render.parser;
out->preserved_tokens = render.preserved_tokens;
out->parse_tools = out->tools_present && render.parser != nullptr;
RAD_TRY(parse_thinking_budget(b, d, lim, render, &out->sp, err));
/* The format's own end-of-turn markers join the caller's stop strings rather than living in a
* second list: both end the generation and both report `finish_reason: "stop"` (sink.cpp), so
@@ -1322,10 +1514,15 @@ int parse_completion_request(const std::string& body, const OaiDeps& d, const Oa
return RAD_E_INVAL;
}
/* A raw prompt is the client's whole input: no template wraps it and no role is the server's
* to protect, so its control tokens are parsed, as vLLM and llama.cpp parse them. A client
* that renders its own chat template sends "<|im_start|>" meaning the token; read as text it
* reaches the model as six pieces of punctuation. Token ids could name any control token
* already. */
auto push_text = [&](const std::string& s) {
PromptInput p;
p.text = s;
p.tokens = d.tok->encode(s, true, /*parse_special=*/false);
p.tokens = d.tok->encode(s, true, /*parse_special=*/true);
out->prompts.push_back(std::move(p));
};
auto push_ids = [&](const json& arr, ApiError* e) -> bool {
@@ -1443,10 +1640,12 @@ int parse_embeddings_request(const std::string& body, const OaiDeps& d, const Oa
return true;
};
/* Parsed like a /v1/completions prompt, and for the same reason: the input is the client's
* own text with no template around it. */
if (it->is_string()) {
PromptInput p;
p.text = it->get<std::string>();
p.tokens = d.tok->encode(p.text, true, /*parse_special=*/false);
p.tokens = d.tok->encode(p.text, true, /*parse_special=*/true);
out->prompts.push_back(std::move(p));
} else if (it->is_array()) {
if (it->empty()) { *err = err_bad("input", "must not be empty"); return RAD_E_INVAL; }
@@ -1455,7 +1654,7 @@ int parse_embeddings_request(const std::string& body, const OaiDeps& d, const Oa
if (!s.is_string()) { *err = err_bad("input", "expected all strings"); return RAD_E_INVAL; }
PromptInput p;
p.text = s.get<std::string>();
p.tokens = d.tok->encode(p.text, true, /*parse_special=*/false);
p.tokens = d.tok->encode(p.text, true, /*parse_special=*/true);
out->prompts.push_back(std::move(p));
}
} else if (it->front().is_number_integer()) {
@@ -1510,6 +1709,39 @@ static json usage_json(const UsageOut& u) {
o["completion_tokens"] = u.completion;
o["total_tokens"] = u.prompt + u.completion;
o["prompt_tokens_details"] = d;
/* HOW MUCH OF completion_tokens THE CLIENT NEVER SEES AS CONTENT. Without it a reply cut at
* max_tokens inside its reasoning reads as a model that answered nothing; with it the client
* can tell the budget went to reasoning. */
if (u.reasoning >= 0) {
json c;
c["reasoning_tokens"] = u.reasoning;
o["completion_tokens_details"] = c;
}
return o;
}
json timings_json(const TimingsOut& t) {
auto per = [](int64_t n, double ms) -> json {
return n > 0 && ms > 0.0 ? json(ms / (double)n) : json(nullptr);
};
auto rate = [](int64_t n, double ms) -> json {
return n > 0 && ms > 0.0 ? json((double)n * 1000.0 / ms) : json(nullptr);
};
const json pms = t.prompt_ms >= 0.0 ? json(t.prompt_ms) : json(nullptr);
json o;
o["cache_n"] = t.cache_n;
o["prompt_n"] = t.prompt_n;
o["prompt_ms"] = pms;
o["prompt_per_token_ms"] = per(t.prompt_n, t.prompt_ms);
o["prompt_per_second"] = rate(t.prompt_n, t.prompt_ms);
o["predicted_n"] = t.predicted_n;
o["predicted_ms"] = t.predicted_ms;
o["predicted_per_token_ms"] = per(t.decode_n, t.predicted_ms);
o["predicted_per_second"] = rate(t.decode_n, t.predicted_ms);
if (t.draft_n > 0) {
o["draft_n"] = t.draft_n;
o["draft_n_accepted"] = t.draft_n_accepted;
}
return o;
}
@@ -1521,7 +1753,8 @@ static json usage_json(const UsageOut& u) {
*
* One contract for both, OpenAI's: an empty choices array, sent after the last content chunk
* and before [DONE]. Only the `object` differs, because it is a different endpoint's stream. */
static std::string usage_chunk(const OaiRequest& r, const UsageOut& u, const char* object) {
static std::string usage_chunk(const OaiRequest& r, const UsageOut& u, const TimingsOut& t,
const char* object) {
json o;
o["id"] = r.id;
o["object"] = object;
@@ -1529,15 +1762,16 @@ static std::string usage_chunk(const OaiRequest& r, const UsageOut& u, const cha
o["model"] = r.model;
o["choices"] = json::array();
o["usage"] = usage_json(u);
if (t.valid) o["timings"] = timings_json(t);
return sse_event(o.dump());
}
std::string text_usage_chunk(const OaiRequest& r, const UsageOut& u) {
return usage_chunk(r, u, "text_completion");
std::string text_usage_chunk(const OaiRequest& r, const UsageOut& u, const TimingsOut& t) {
return usage_chunk(r, u, t, "text_completion");
}
std::string chat_usage_chunk(const OaiRequest& r, const UsageOut& u) {
return usage_chunk(r, u, "chat.completion.chunk");
std::string chat_usage_chunk(const OaiRequest& r, const UsageOut& u, const TimingsOut& t) {
return usage_chunk(r, u, t, "chat.completion.chunk");
}
static json chat_logprobs_json(const std::vector<LogprobEntry>& lp) {
@@ -1558,7 +1792,7 @@ static json chat_logprobs_json(const std::vector<LogprobEntry>& lp) {
}
std::string chat_completion_body(const OaiRequest& r, const std::vector<ChoiceOut>& choices,
const UsageOut& u) {
const UsageOut& u, const TimingsOut& t) {
json arr = json::array();
for (const auto& c : choices) {
json m;
@@ -1583,11 +1817,12 @@ std::string chat_completion_body(const OaiRequest& r, const std::vector<ChoiceOu
o["model"] = r.model;
o["choices"] = std::move(arr);
o["usage"] = usage_json(u);
if (t.valid) o["timings"] = timings_json(t);
return o.dump();
}
std::string text_completion_body(const OaiRequest& r, const std::vector<ChoiceOut>& choices,
const UsageOut& u) {
const UsageOut& u, const TimingsOut& t) {
json arr = json::array();
for (const auto& c : choices) {
json ch;
@@ -1621,6 +1856,7 @@ std::string text_completion_body(const OaiRequest& r, const std::vector<ChoiceOu
o["model"] = r.model;
o["choices"] = std::move(arr);
o["usage"] = usage_json(u);
if (t.valid) o["timings"] = timings_json(t);
return o.dump();
}
@@ -1679,7 +1915,7 @@ ChatDeltaStream::ChatDeltaStream(const OaiRequest& r, int index, const IReplyPar
: reader_(parser ? parser->open() : nullptr), id_(r.id), model_(r.model),
created_(r.created), index_(index) {}
std::string ChatDeltaStream::chunk(json delta, const char* finish_reason) {
std::string ChatDeltaStream::chunk(json delta, const char* finish_reason, const TimingsOut* t) {
json ch;
ch["index"] = index_;
ch["delta"] = std::move(delta);
@@ -1691,6 +1927,7 @@ std::string ChatDeltaStream::chunk(json delta, const char* finish_reason) {
o["created"] = created_;
o["model"] = model_;
o["choices"] = json::array({ch});
if (t && t->valid) o["timings"] = timings_json(*t);
return sse_event(o.dump());
}
@@ -1795,11 +2032,11 @@ Finish ChatDeltaStream::adjusted_finish(Finish f) const {
return Finish::ToolCalls;
}
std::string ChatDeltaStream::final_chunk(Finish f) {
std::string ChatDeltaStream::final_chunk(Finish f, const TimingsOut& t) {
/* The generation is over, so whatever the reader was holding is resolved now. A caller that
* already said so gets nothing twice. */
std::string out = push(std::string_view(), true);
out += chunk(json::object(), finish_reason_oai(adjusted_finish(f)));
out += chunk(json::object(), finish_reason_oai(adjusted_finish(f)), &t);
return out;
}
+100 -9
View File
@@ -21,6 +21,7 @@
#include "sink.h"
#include <cstdint>
#include <map>
#include <memory>
#include <string>
#include <vector>
@@ -107,8 +108,20 @@ struct OaiRequest {
struct OaiLimits {
std::string model_id = "radiance";
int64_t max_ctx = 0; /* 0 = unknown, no length check */
int64_t default_max_tokens = 512;
/* What a request that names no max_tokens may generate. 0 is "whatever the context leaves",
* resolved against the prompt in clamp_max_tokens, which needs max_ctx to resolve against.
*
* 0 BY DEFAULT, as vLLM's is: many clients send no max_tokens, and a reasoning model spends
* the first thousands of tokens of an answer thinking. A fixed default of 512 ended those
* answers inside the reasoning, with finish_reason "length" that a chat client does not show,
* so they read as a model that stops at random. */
int64_t default_max_tokens = 0;
/* 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;
@@ -123,6 +136,13 @@ struct OaiLimits {
* dial at all. Seeded only when the request says nothing, so a caller always wins. */
std::string default_reasoning_effort;
/* THE DEPLOYMENT'S DEFAULT `thinking_token_budget`, -1 for none. For the same reason the
* effort default exists: an agent framework sizes max_tokens per turn and sends no budget, and
* a reasoning block that spends the whole of max_tokens returns a turn with no answer in it.
* Applied only to a request that names no budget, and only where the reply's reasoning block
* can be counted. */
int64_t default_thinking_budget = -1;
/* WHAT A REQUEST THAT SENDS NO SAMPLER FIELDS IS SERVED WITH, field by field.
*
* The struct's own defaults are an untruncated sampler -- temperature 1, top_k off, top_p 1
@@ -137,8 +157,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;
@@ -175,12 +227,46 @@ struct UsageOut {
int64_t prompt = 0;
int64_t completion = 0;
int64_t cached = 0;
/* Of `completion`, the tokens inside the reply's reasoning block, its markers included: OpenAI's
* completion_tokens_details.reasoning_tokens. -1 when the block cannot be counted, and the
* breakdown is then left out. */
int64_t reasoning = -1;
};
/* WHERE ONE REQUEST'S TIME WENT, in llama.cpp's `timings` shape, which proxies and dashboards
* built against llama-server already read (llama-swap's activity view is one). /metrics holds the
* same quantities summed over every request, and two overlapping requests cannot be told apart
* there; this is the per-request half.
*
* prompt_n prompt tokens computed, the prefix cache's excluded; cache_n is those
* prompt_ms from the first step the scheduler gave the request to its first token -- the
* prefill, without the time it waited for admission
* predicted_n tokens generated: usage.completion_tokens
* predicted_ms from the first token to the last
* draft_n, draft_n_accepted
* speculative tokens proposed for this request and accepted; present when any
* were proposed, as llama.cpp does
*
* The rates divide the tokens by the time that produced them: prompt_n by prompt_ms, and the
* predicted_n - 1 tokens after the first by predicted_ms, since the first token is the prompt
* phase's product -- the same figure as /metrics' time per output token. A rate whose count or
* time is zero is null. Over several choices the counts are summed and each time runs from the
* earliest choice's start to the latest choice's end. */
struct TimingsOut {
bool valid = false; /* some choice produced a token; nothing is reported otherwise */
int64_t prompt_n = 0, cache_n = 0;
double prompt_ms = -1.0; /* < 0: the engine did not report the admission */
int64_t predicted_n = 0;
int64_t decode_n = 0; /* of predicted_n, the tokens after each choice's first */
double predicted_ms = 0.0;
int64_t draft_n = 0, draft_n_accepted = 0;
};
/* `timings` is added at the top level when it is valid. */
std::string chat_completion_body(const OaiRequest& r, const std::vector<ChoiceOut>& choices,
const UsageOut& u);
const UsageOut& u, const TimingsOut& t = TimingsOut());
std::string text_completion_body(const OaiRequest& r, const std::vector<ChoiceOut>& choices,
const UsageOut& u);
const UsageOut& u, const TimingsOut& t = TimingsOut());
std::string embeddings_body(const OaiRequest& r, const std::vector<std::vector<float>>& vecs,
const UsageOut& u);
std::string models_body(const std::string& model_id, int64_t created);
@@ -189,8 +275,12 @@ std::string models_body(const std::string& model_id, int64_t created);
* only payload is `usage`. Emitted when the request asked for stream_options.include_usage, ONCE
* per stream and after every choice's final chunk -- `n` choices share one prompt and one total,
* so a chunk per choice would count the prompt n times and interleave with the choices. */
std::string text_usage_chunk(const OaiRequest& r, const UsageOut& u);
std::string chat_usage_chunk(const OaiRequest& r, const UsageOut& u);
std::string text_usage_chunk(const OaiRequest& r, const UsageOut& u,
const TimingsOut& t = TimingsOut());
std::string chat_usage_chunk(const OaiRequest& r, const UsageOut& u,
const TimingsOut& t = TimingsOut());
/* The `timings` object, for a stream's final chunks. */
json timings_json(const TimingsOut& t);
/* ================================================================== streaming
*
@@ -211,9 +301,10 @@ public:
* `is_final` says the generation is over, which resolves whatever the reader was holding. */
std::string push(std::string_view appended, bool is_final);
/* The terminating chunk carrying finish_reason. The usage chunk is the stream's, not the
* choice's: chat_usage_chunk. */
std::string final_chunk(Finish f);
/* The terminating chunk carrying finish_reason, and this choice's `timings` when they are
* valid -- on the final chunk whether or not the request asked for a usage chunk, as
* llama.cpp sends them. The usage chunk is the stream's, not the choice's: chat_usage_chunk. */
std::string final_chunk(Finish f, const TimingsOut& t = TimingsOut());
/* What the whole generation parsed to -- the non-streaming shape. Complete once push has
* been called with is_final. */
@@ -221,7 +312,7 @@ public:
Finish adjusted_finish(Finish f) const;
private:
std::string chunk(json delta, const char* finish_reason);
std::string chunk(json delta, const char* finish_reason, const TimingsOut* t = nullptr);
std::string emit(const std::vector<ReplyDelta>& ev);
std::unique_ptr<IReplyReader> reader_;
+136 -22
View File
@@ -22,6 +22,9 @@ struct Server::Generation {
int prompt_index = 0;
std::string text;
std::vector<LogprobEntry> logprobs;
/* The reply against its reasoning block, every token the sink delivers: what
* completion_tokens_details.reasoning_tokens reports. */
ReasoningCount think;
Finish finish = Finish::None;
bool closed = false; /* the server has decided this choice is over */
size_t scanned = 0; /* how far the stop-string scan has reached */
@@ -47,13 +50,20 @@ 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_thinking_budget = opt_.default_thinking_budget;
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 +168,45 @@ 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);
}
std::string Server::check_thinking_budget() const {
if (!deps_.chat || lim_.default_thinking_budget < 0) return std::string();
const std::string body = R"({"messages":[{"role":"user","content":"Hello"}],"max_tokens":1,)"
R"("thinking_token_budget":)" +
std::to_string(lim_.default_thinking_budget) + "}";
OaiRequest r;
ApiError e;
return parse_chat_request(body, odeps_, lim_, &r, &e) < 0 ? e.message : std::string();
}
void Server::stop() {
stopping_.store(true);
transport_.stop();
@@ -241,6 +287,7 @@ int Server::submit_all(const OaiRequest& r, std::vector<Generation>* gens, ApiEr
g.prompt_index = (int)p;
g.sink = std::make_shared<Sink>();
g.sink->set_has_logprobs(opt_.supports_logprobs);
g.think.start(r.sp.reasoning);
g.detok = deps_.tok->detokenizer(r.stop, r.preserved_tokens);
if (!g.detok) {
*err = err_not_implemented("the tokenizer did not supply an incremental decoder");
@@ -321,6 +368,7 @@ bool Server::pump(std::vector<Generation>& gens, const OaiRequest& r) {
while ((n = g.sink->read(buf, 128)) > 0) {
progress = true;
for (size_t i = 0; i < n; ++i) {
g.think.push(r.sp.reasoning, buf[i].token);
std::string piece = g.detok->push(buf[i].token);
if (!piece.empty()) g.text += piece;
if (r.want_logprobs)
@@ -378,8 +426,75 @@ bool Server::pump(std::vector<Generation>& gens, const OaiRequest& r) {
return progress;
}
/* ------------------------------------------------------------------ usage */
/* THE REQUEST'S TOKENS, ONCE FOR BOTH PATHS. `n` choices share a prompt, so the prompt and its
* cached part are counted once per prompt. Reasoning is reported only where the reply's block can
* be counted by token (ReasoningSpan); a model without one reports no breakdown rather than a
* zero that would claim there was no reasoning. */
UsageOut Server::usage_of(const OaiRequest& r, const std::vector<Generation>& gens) {
UsageOut u;
for (const auto& p : r.prompts) u.prompt += (int64_t)p.tokens.size();
if (r.sp.reasoning.known()) u.reasoning = 0;
for (const auto& g : gens) {
u.completion += g.sink->n_produced();
if (g.prompt_index * r.n == g.index) u.cached += g.sink->n_cached();
if (u.reasoning >= 0) u.reasoning += g.think.tokens;
}
return u;
}
/* WHERE THE REQUEST'S TIME WENT, from its sinks: one for a choice's final chunk, all of them for
* the request. Every time is moved onto one clock first -- each sink counts from its own
* construction. See TimingsOut for what each field means. */
TimingsOut Server::timings_of(const Sink* const* sinks, size_t n) {
TimingsOut t;
int64_t admit = INT64_MAX, first_lo = INT64_MAX, first_hi = INT64_MIN, last = INT64_MIN;
bool admitted = true;
for (size_t i = 0; i < n; ++i) {
const Sink& s = *sinks[i];
const int64_t produced = s.n_produced();
t.predicted_n += produced;
t.draft_n += s.n_drafted();
t.draft_n_accepted += s.n_draft_accepted();
const int64_t tf = s.t_first_token_ns();
if (tf < 0) continue;
t.valid = true;
t.cache_n += s.n_cached();
t.prompt_n += s.n_prompt() - s.n_cached();
if (produced > 1) t.decode_n += produced - 1;
const int64_t t0 = s.t_start_ns(), ta = s.t_admitted_ns();
if (ta < 0) admitted = false;
else admit = std::min(admit, t0 + ta);
first_lo = std::min(first_lo, t0 + tf);
first_hi = std::max(first_hi, t0 + tf);
last = std::max(last, t0 + s.t_last_token_ns());
}
if (!t.valid) return t;
if (admitted) t.prompt_ms = (double)(first_hi - admit) * 1e-6;
t.predicted_ms = (double)(last - first_lo) * 1e-6;
return t;
}
TimingsOut Server::timings_of(const std::vector<Generation>& gens) {
std::vector<const Sink*> v;
v.reserve(gens.size());
for (const auto& g : gens) v.push_back(g.sink.get());
return timings_of(v.data(), v.size());
}
/* ------------------------------------------------------------------ metrics bookkeeping */
/* WHAT FAILED, for the client: the sentence the failing component gave, and the status. A failed
* request always carries a status -- an engine that stopped carries the one that stopped it -- so
* this never reads "ok". */
static std::string engine_failure(const Sink& s) {
const int st = s.status() < 0 ? s.status() : RAD_E_STATE;
const char* why = s.why();
return why ? fmt("the engine failed this request: %s (%s)", why, rad_strerror(st))
: fmt("the engine failed this request: %s", rad_strerror(st));
}
static SuccessReason to_reason(Finish f) {
switch (f) {
case Finish::Length: return SuccessReason::Length;
@@ -452,14 +567,11 @@ HttpResponse Server::blocking_completion(const HttpRequest& req, OaiRequest& r)
}
Finish overall = Finish::Stop;
UsageOut usage;
for (const auto& p : r.prompts) usage.prompt += (int64_t)p.tokens.size();
const UsageOut usage = usage_of(r, gens);
std::vector<ChoiceOut> choices;
choices.reserve(gens.size());
for (auto& g : gens) {
usage.completion += g.sink->n_produced();
if (g.prompt_index * r.n == g.index) usage.cached += g.sink->n_cached();
ChoiceOut c;
c.index = g.index;
@@ -504,14 +616,14 @@ HttpResponse Server::blocking_completion(const HttpRequest& req, OaiRequest& r)
/* An engine-side failure is not a 200 with an empty answer. */
for (auto& g : gens) {
if (g.finish == Finish::Error) {
int st = g.sink->status();
const std::string why = engine_failure(*g.sink);
retire(gens);
release(r.n_choices());
record(r, gens, Finish::Error);
ApiError e;
e.status = 500;
e.type = "internal_server_error";
e.message = std::string("the engine failed this request: ") + rad_strerror(st);
e.message = why;
return error_response(e);
}
}
@@ -520,9 +632,10 @@ HttpResponse Server::blocking_completion(const HttpRequest& req, OaiRequest& r)
retire(gens);
release(r.n_choices());
const TimingsOut timings = timings_of(gens);
std::string body = r.endpoint == Endpoint::Chat
? chat_completion_body(r, choices, usage)
: text_completion_body(r, choices, usage);
? chat_completion_body(r, choices, usage, timings)
: text_completion_body(r, choices, usage, timings);
metrics_.observe_http(200);
return HttpResponse::json_body(200, std::move(body));
}
@@ -530,7 +643,7 @@ HttpResponse Server::blocking_completion(const HttpRequest& req, OaiRequest& r)
/* ------------------------------------------------------------------ streaming */
static std::string text_chunk(const OaiRequest& r, int index, const std::string& delta,
const char* finish_reason) {
const char* finish_reason, const TimingsOut* t = nullptr) {
nlohmann::ordered_json ch;
ch["text"] = delta;
ch["index"] = index;
@@ -542,6 +655,7 @@ static std::string text_chunk(const OaiRequest& r, int index, const std::string&
o["created"] = r.created;
o["model"] = r.model;
o["choices"] = nlohmann::ordered_json::array({ch});
if (t && t->valid) o["timings"] = timings_json(*t);
return sse_event(o.dump());
}
@@ -633,21 +747,20 @@ HttpResponse Server::streaming_completion(const HttpRequest& req, OaiRequest& r)
}
if (self->all_done(st->gens)) {
UsageOut u;
for (const auto& p : st->r.prompts) u.prompt += (int64_t)p.tokens.size();
for (auto& g : st->gens) {
u.completion += g.sink->n_produced();
if (g.prompt_index * st->r.n == g.index) u.cached += g.sink->n_cached();
}
const UsageOut u = usage_of(st->r, st->gens);
Finish overall = Finish::Stop;
for (auto& g : st->gens) {
/* EACH CHOICE'S OWN TIMINGS ON ITS FINAL CHUNK, so a client that asked for no
* usage chunk still has them, as llama.cpp sends them. */
const Sink* one = g.sink.get();
const TimingsOut gt = timings_of(&one, 1);
if (st->r.endpoint == Endpoint::Chat) {
out += g.delta->final_chunk(g.finish);
out += g.delta->final_chunk(g.finish, gt);
Finish adj = g.delta->adjusted_finish(g.finish);
if (adj == Finish::Error || adj == Finish::Cancelled) overall = adj;
else if (adj == Finish::ToolCalls) overall = adj;
} else {
out += text_chunk(st->r, g.index, "", finish_reason_oai(g.finish));
out += text_chunk(st->r, g.index, "", finish_reason_oai(g.finish), &gt);
if (g.finish == Finish::Error) overall = Finish::Error;
}
/* A failed generation cannot become a non-200 -- the headers left long ago -- so
@@ -657,8 +770,7 @@ HttpResponse Server::streaming_completion(const HttpRequest& req, OaiRequest& r)
ApiError e;
e.status = 500;
e.type = "internal_server_error";
e.message = std::string("the engine failed this request: ") +
rad_strerror(g.sink->status());
e.message = engine_failure(*g.sink);
out += sse_error(e);
}
}
@@ -670,9 +782,11 @@ HttpResponse Server::streaming_completion(const HttpRequest& req, OaiRequest& r)
* it, and once for the request rather than once per choice: `n` completions share one
* prompt and one total, so emitting it per generation would count the prompt n times
* and interleave usage between the choices' final chunks. */
if (st->r.include_usage)
out += st->r.endpoint == Endpoint::Chat ? chat_usage_chunk(st->r, u)
: text_usage_chunk(st->r, u);
if (st->r.include_usage) {
const TimingsOut t = timings_of(st->gens);
out += st->r.endpoint == Endpoint::Chat ? chat_usage_chunk(st->r, u, t)
: text_usage_chunk(st->r, u, t);
}
out += SSE_DONE;
st->done_sent = true;
+33 -1
View File
@@ -66,16 +66,26 @@ struct ServerOptions {
int retry_after_s = 1;
int64_t max_ctx = 0;
int64_t default_max_tokens = 512;
int64_t default_max_tokens = 0; /* 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
* OaiLimits::default_reasoning_effort for why a server-side default is needed at all. */
std::string default_reasoning_effort;
/* The deployment default for `thinking_token_budget`, -1 for none. See
* OaiLimits::default_thinking_budget. */
int64_t default_thinking_budget = -1;
/* 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 +114,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 +136,18 @@ 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;
/* THE DEPLOYMENT'S thinking_token_budget, asked for by a one-message chat the way a request
* would ask for it. Empty when this model's reasoning block can hold one; otherwise the 400 a
* request naming the budget would get, which says why. */
std::string check_thinking_budget() const;
void stop();
int port() const { return transport_.port(); } /* 0 until run() is accepting */
@@ -129,6 +157,10 @@ private:
struct Generation;
struct StreamState;
static UsageOut usage_of(const OaiRequest& r, const std::vector<Generation>& gens);
static TimingsOut timings_of(const Sink* const* sinks, size_t n);
static TimingsOut timings_of(const std::vector<Generation>& gens);
void register_routes();
HttpResponse handle_chat(const HttpRequest& req);
+14 -1
View File
@@ -89,8 +89,9 @@ void Sink::finish(Finish f) {
}
}
void Sink::fail(int rad_status) {
void Sink::fail(int rad_status, const char* why) {
status_.store(rad_status, std::memory_order_release);
why_.store(why, std::memory_order_release);
finish(Finish::Error);
}
@@ -99,6 +100,18 @@ void Sink::set_prompt_stats(int32_t n_prompt, int32_t n_cached) {
n_cached_.store(n_cached, std::memory_order_release);
}
void Sink::mark_admitted() {
if (t_admit_.load(std::memory_order_relaxed) < 0)
t_admit_.store(now_ns() - t_start_ns_, std::memory_order_release);
}
/* One producer, so a load and a store is the whole of the update. */
void Sink::add_drafts(int32_t n, int32_t accepted) {
n_draft_.store(n_draft_.load(std::memory_order_relaxed) + n, std::memory_order_release);
n_draft_acc_.store(n_draft_acc_.load(std::memory_order_relaxed) + accepted,
std::memory_order_release);
}
size_t Sink::read(SinkToken* out, size_t max) {
const uint64_t t = tail_.load(std::memory_order_relaxed);
const uint64_t h = head_.load(std::memory_order_acquire);
+31 -3
View File
@@ -79,7 +79,9 @@ public:
/* Terminal. Idempotent -- the first call wins, so a cancel racing a natural stop does not
* produce two finish reasons. */
void finish(Finish f);
void fail(int rad_status);
/* `why` says what failed, in a sentence a client can read; a string that outlives the sink
* (a literal), or null. */
void fail(int rad_status, const char* why = nullptr);
/* The scheduler polls this to learn that the client hung up, and frees the blocks (spec §14).
* It is also told by IScheduler::cancel(); this is the cheap path that needs no lookup. */
@@ -88,6 +90,14 @@ public:
/* Admission accounting, set once by the scheduler when the prompt is placed. */
void set_prompt_stats(int32_t n_prompt, int32_t n_cached);
/* THE FIRST TIME THE SCHEDULER GIVES THIS REQUEST A STEP: where its prompt phase starts, so
* the time it waited in the queue is not counted as prefill. A preempted request admitted
* again keeps the first mark. */
void mark_admitted();
/* A verify step's speculation for this request: `n` tokens proposed, `accepted` of them
* taken. Summed over the request, the per-request half of /metrics' draft counters. */
void add_drafts(int32_t n, int32_t accepted);
/* ------------------------------------------------------------------ consumer: HTTP */
/* Copies up to `max` tokens out. Returns how many. Never blocks. */
@@ -100,6 +110,7 @@ public:
bool done() const { return finish_.load(std::memory_order_acquire) != (int)Finish::None; }
Finish finish_reason() const { return (Finish)finish_.load(std::memory_order_acquire); }
int status() const { return status_.load(std::memory_order_acquire); }
const char* why() const { return why_.load(std::memory_order_acquire); }
bool overflowed() const { return overflow_.load(std::memory_order_acquire); }
/* The HTTP thread calls this when the peer disappears. It does NOT free anything itself --
@@ -109,7 +120,14 @@ public:
/* Timings, in steady-clock nanoseconds since the sink was constructed. -1 until observed. */
int64_t t_first_token_ns() const { return t_first_.load(std::memory_order_acquire); }
int64_t t_last_token_ns() const { return t_last_.load(std::memory_order_acquire); }
int64_t t_admitted_ns() const { return t_admit_.load(std::memory_order_acquire); }
int64_t age_ns() const;
/* The steady clock at construction, which the times above count from: what puts two sinks'
* times on one axis. */
int64_t t_start_ns() const { return t_start_ns_; }
int64_t n_drafted() const { return n_draft_.load(std::memory_order_acquire); }
int64_t n_draft_accepted() const { return n_draft_acc_.load(std::memory_order_acquire); }
int64_t n_produced() const { return (int64_t)head_.load(std::memory_order_acquire); }
int32_t n_prompt() const { return n_prompt_.load(std::memory_order_acquire); }
@@ -135,12 +153,16 @@ private:
std::atomic<int> finish_{(int)Finish::None};
std::atomic<int> status_{RAD_OK};
std::atomic<const char*> why_{nullptr};
std::atomic<bool> overflow_{false};
std::atomic<bool> cancel_{false};
std::atomic<bool> quiesced_{false}; /* the producer will not touch this object again */
std::atomic<int64_t> t_first_{-1};
std::atomic<int64_t> t_last_{-1};
std::atomic<int64_t> t_admit_{-1};
std::atomic<int64_t> n_draft_{0};
std::atomic<int64_t> n_draft_acc_{0};
int64_t t_start_ns_ = 0;
std::atomic<int32_t> n_prompt_{0};
@@ -159,8 +181,8 @@ inline bool sink_push(void* s, int32_t token, float logprob = 0.0f) {
inline void sink_finish(void* s, Finish f) {
if (s) static_cast<Sink*>(s)->finish(f);
}
inline void sink_fail(void* s, int rad_status) {
if (s) static_cast<Sink*>(s)->fail(rad_status);
inline void sink_fail(void* s, int rad_status, const char* why = nullptr) {
if (s) static_cast<Sink*>(s)->fail(rad_status, why);
}
inline bool sink_cancelled(const void* s) {
return s && static_cast<const Sink*>(s)->cancel_requested();
@@ -168,6 +190,12 @@ inline bool sink_cancelled(const void* s) {
inline void sink_prompt_stats(void* s, int32_t n_prompt, int32_t n_cached) {
if (s) static_cast<Sink*>(s)->set_prompt_stats(n_prompt, n_cached);
}
inline void sink_admitted(void* s) {
if (s) static_cast<Sink*>(s)->mark_admitted();
}
inline void sink_drafts(void* s, int32_t n, int32_t accepted) {
if (s) static_cast<Sink*>(s)->add_drafts(n, accepted);
}
} /* namespace server */
} /* namespace rad */
+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)) {
+15
View File
@@ -704,6 +704,21 @@ size_t ReplyParser::hold_bound() const {
3 * 3;
}
ReasoningMarkers ReplyParser::reasoning() const {
const ReplyFormat::Impl& F = impl_->fmt->impl();
ReasoningMarkers m;
if (!F.f.has_reasoning()) return m;
m.open = F.open_core;
m.close = F.close_core;
/* `tail` starts at the opener when the prompt holds one, and a prompt that also closed the
* block -- thinking turned off -- leaves the reply after it. With no opener at all the stream
* starts in the block (after_lead). */
const std::string& t = impl_->tail;
m.starts_open = F.open_core.empty() ||
(!t.empty() && t.find(F.close_core, F.open_core.size()) == std::string::npos);
return m;
}
/* Read the tools the way the grammar generator reads them, so a name or a type means the same
* thing to the parser as to the grammar that constrained the reply. */
static int bind_tools(const ReplyFormat::Impl& F, const ojson& tools, ReplyParser::Impl* P,
+11
View File
@@ -118,6 +118,14 @@ struct ReplyOptions {
class ReplyStream;
/* The reasoning block as one request's reply meets it: its markers with the optional whitespace
* around them trimmed, and whether the reply starts inside it -- the generation prompt opened it,
* or the format has no opener. Empty `close` is a format with no reasoning block. */
struct ReasoningMarkers {
std::string open, close;
bool starts_open = false;
};
/* A format compiled once: its automata and its delimiters. Shared by every request. */
class ReplyFormat {
public:
@@ -150,6 +158,9 @@ public:
* prefix in each place one can be pending at once, a value's undecided head, and an
* unfinished UTF-8 sequence on each output. A constant of the format, not of the reply. */
size_t hold_bound() const;
/* Read from the generation prompt exactly as a stream's first bytes are, so a reply this
* says starts in the block is one the stream reads as reasoning from its first byte. */
ReasoningMarkers reasoning() const;
struct Impl;
const Impl& impl() const { return *impl_; }
+13 -2
View File
@@ -1312,8 +1312,6 @@ int Tokenizer::encode(std::string_view text, std::vector<int32_t>& out,
if (!v_ || !v_->ready()) return RAD_E_STATE;
const TokEncoder& e = *v_->enc_;
if (add_special && v_->add_bos() && v_->bos() >= 0) out.push_back(v_->bos());
/* Special-token partitioning. The text is cut into (raw, token, raw, token, ...) around any
* declared special token that appears literally, before any other step touches it, because a
* special token is not something the pre-tokeniser is allowed to split.
@@ -1324,6 +1322,19 @@ int Tokenizer::encode(std::string_view text, std::vector<int32_t>& out,
std::vector<SpecialFrag> frags;
e.specials.split(text, parse_special, frags);
/* A text that already opens with BOS gets no second one. A client that renders its own chat
* template writes the template's BOS into the prompt, and a doubled BOS is a sequence the
* model never saw in training. */
if (add_special && v_->add_bos() && v_->bos() >= 0) {
int32_t first = -1;
for (const SpecialFrag& f : frags) {
if (f.id < 0 && f.len == 0) continue;
first = f.id;
break;
}
if (first != v_->bos()) out.push_back(v_->bos());
}
EncodeScratch sc;
WordCache words;
for (const SpecialFrag& f : frags) {
+13 -15
View File
@@ -156,35 +156,35 @@ std::vector<std::string_view> split_ws(std::string_view s) {
* touches this at declare, not per step. A hash map here would be slower and less predictable. */
void Geometry::set_i(std::string_view k, long long v) {
for (size_t i = 0; i < keys_.size(); ++i)
if (keys_[i] == k) { kinds_[i] = RAD_P_INT; ivals_[i] = v; dirty_ = true; return; }
if (keys_[i] == k) { kinds_[i] = RAD_P_INT; ivals_[i] = v; rebuild(); return; }
keys_.emplace_back(k);
svals_.emplace_back();
ivals_.push_back(v);
dvals_.push_back(0.0);
kinds_.push_back(RAD_P_INT);
dirty_ = true;
rebuild();
}
void Geometry::set_f(std::string_view k, double v) {
for (size_t i = 0; i < keys_.size(); ++i)
if (keys_[i] == k) { kinds_[i] = RAD_P_F64; dvals_[i] = v; dirty_ = true; return; }
if (keys_[i] == k) { kinds_[i] = RAD_P_F64; dvals_[i] = v; rebuild(); return; }
keys_.emplace_back(k);
svals_.emplace_back();
ivals_.push_back(0);
dvals_.push_back(v);
kinds_.push_back(RAD_P_F64);
dirty_ = true;
rebuild();
}
void Geometry::set_s(std::string_view k, std::string_view v) {
for (size_t i = 0; i < keys_.size(); ++i)
if (keys_[i] == k) { kinds_[i] = RAD_P_STR; svals_[i] = std::string(v); dirty_ = true; return; }
if (keys_[i] == k) { kinds_[i] = RAD_P_STR; svals_[i] = std::string(v); rebuild(); return; }
keys_.emplace_back(k);
svals_.emplace_back(v);
ivals_.push_back(0);
dvals_.push_back(0.0);
kinds_.push_back(RAD_P_STR);
dirty_ = true;
rebuild();
}
bool Geometry::get_i(std::string_view k, long long* out) const {
@@ -210,10 +210,12 @@ bool Geometry::has(std::string_view k) const {
return false;
}
void Geometry::rebuild() const {
auto* self = const_cast<Geometry*>(this);
self->view_.clear();
self->view_.reserve(keys_.size());
/* Every key and every string value may have moved: an append can reallocate keys_ and svals_, and
* a short string lives inside its element. So the whole view is redone, which is the same handful
* of entries the setter's scan already walked. */
void Geometry::rebuild() {
view_.clear();
view_.reserve(keys_.size());
for (size_t i = 0; i < keys_.size(); ++i) {
RadParam p{};
p.key = keys_[i].c_str();
@@ -221,14 +223,10 @@ void Geometry::rebuild() const {
p.ival = ivals_[i];
p.dval = dvals_[i];
p.sval = kinds_[i] == RAD_P_STR ? svals_[i].c_str() : nullptr;
self->view_.push_back(p);
view_.push_back(p);
}
dirty_ = false;
}
const RadParam* Geometry::params() const { if (dirty_) rebuild(); return view_.data(); }
int Geometry::n_params() const { if (dirty_) rebuild(); return (int)view_.size(); }
std::string Geometry::str() const {
std::string s;
for (size_t i = 0; i < keys_.size(); ++i) {
+207 -11
View File
@@ -513,6 +513,12 @@ quite keep its headroom is safe rather than fatal — but it is costing you the
`--gpu-headroom-mib` past the number startup names, so the budget resolver sees it and the expert
plane is sized against it instead of trimmed afterwards.
What the engine itself allocates after the card is read is charged before the split, so it never
comes out of the headroom: the step staging, the KV tiers' copy staging, and its hardware queues.
A queue costs more than its ring — the driver backs each one with VRAM of its own, 33 MiB on an
R9700 — so startup measures one and the receipt's `hardware queues` line shows how many a card
holds at that price.
### 4.4 Long context
```sh
@@ -673,6 +679,14 @@ write, with the MoE gather in front of it, on either wire: the rotated forms of
worth +5.6–6.3% of prefill at a 2048-token chunk (20K prompt 5556 → 5908 tok/s; a 23K extension at
81K depth 4998 → 5278) and −1.3% of the eight-stream decode step; one-stream decode stays exact.
**The cards must reach each other's memory directly** (peer to peer, P2P). The all-reduce
kernels push into the other card's memory. At launch radiance asks the driver, for every pair of
the cards it will use, whether that works, and logs the answer. When some pair cannot, those
kernels are not selected, and startup stops naming `device.p2p` instead of the first all-reduce
faulting or hanging. Whether P2P works is decided by the platform: the IOMMU setting, the PCIe
topology, and whether the cards sit behind a switch that allows peer traffic. The startup line
names the pairs that failed.
### 4.8 Finished conversations: copied to host, VRAM given up on demand
By default a finished conversation's KV blocks stay in VRAM, held by the prefix cache, until the
@@ -710,30 +724,95 @@ 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. `<model>.generation.json` beside the container
3. `<model>.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, `auto`,
is whatever the context leaves after the prompt, as in vLLM. Many clients send no `max_tokens`,
and a reasoning model can think for thousands of tokens before it answers: a small default ends
those answers inside the reasoning, with a `finish_reason: "length"` that chat clients do not
show.
- `--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 `<think>` 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
```
**`--thinking-token-budget N`** caps the reasoning instead of its depth. At N tokens inside the
reasoning block the block is closed, by masking the next position to its end token
(`</think>`), and the answer follows. This makes a client's `max_tokens` buy an answer, where
otherwise the reasoning could use all of it. It is the default for chat requests that send no
`thinking_token_budget` of their own (§5.2). It needs a reasoning block that ends in a single
token, as Qwen's and MiniCPM's do. On a model whose block does not, startup stops and says why.
**`--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 +888,49 @@ 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` | `auto` | `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 |
| `--thinking-token-budget N` | none | default `thinking_token_budget` for chat: the reasoning block is closed at N tokens |
| `--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)
@@ -862,6 +980,11 @@ Method spellings follow vLLM's, including the ones that look odd: `/tokenize` is
input is a body, and `/ping` answers both GET and POST because different load balancers send
different ones.
A text prompt to `/v1/completions`, `/v1/embeddings` or `/tokenize` reads the model's control
tokens as tokens, as vLLM and llama.cpp do: a client that renders its own chat template can send
`<|im_start|>user\n…` and the model sees the turn markers. The BOS the model declares is prepended
unless the prompt already opens with it.
### 5.2 Chat
```sh
@@ -888,6 +1011,27 @@ so — use `/v1/completions` instead.
Reasoning text comes back in `choices[].message.reasoning_content`, separate from `content`.
**Reasoning counts against `max_tokens`**, as in OpenAI's API, vLLM and llama.cpp: every
generated token does. A reply that runs out inside its reasoning comes back with empty
`content` and `finish_reason: "length"`. `usage.completion_tokens_details.reasoning_tokens` says
how many of `completion_tokens` were reasoning, the block's end token included, so a client can
tell that case from a model that answered nothing.
**Capping the reasoning.** `thinking_token_budget` (vLLM's name; `thinking_budget`, Qwen's, is
read as the same field) is how many tokens the reasoning may run to. At that count the block is
closed and the model answers from what it has reasoned so far:
```json
{"max_tokens": 4096, "thinking_token_budget": 2048}
```
The count starts after the opening `<think>`. A reasoning block that ends sooner is not
affected. The close is forced by the sampler, so it holds under speculative decoding and at any
temperature. A `grammar` or `response_format` that does not allow the close at some position
keeps that position, and the close comes at the next position that allows it. The budget and
`reasoning_tokens` need the block's end to be one token. A model whose end is not one token
reports no `completion_tokens_details` and refuses a budget with a 400 that says why.
### 5.3 Streaming
```sh
@@ -933,6 +1077,13 @@ accepts no value — `false`, or `{"not": {}}`, which is how TypeBox and Arktype
an argument no call writes. Any other `not` is refused with a 400 naming it: the grammar cannot
express a complement, and dropping the constraint silently would serve a call the tool forbids.
Length bounds are held exactly: `maxLength`, `minLength`, `maxItems` and `minItems` up to about
200,000, which costs the first request carrying the tool under a second to compile on a
quarter-million-token vocabulary and nothing per token after that. A bound past 2^31 (as
`Number.MAX_SAFE_INTEGER` is) is no bound, since no context holds that much. One in between is
refused with a 400 naming the property's rule and the count. The same holds for `response_format`
schemas and `{m,n}` in a GBNF grammar.
### 5.5 Constrained output
```sh
@@ -992,7 +1143,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: what the context leaves after the prompt (`--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 |
@@ -1002,15 +1153,17 @@ 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 |
| `thinking_token_budget`, `thinking_budget` | chat only. ≥ 0: the reasoning tokens after which the block is closed — see §5.2. Default `--thinking-token-budget`, else none |
| `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 |
@@ -1084,6 +1237,42 @@ precisely without running the model.
---
### 5.9 What a response says about its own speed
Every chat and completion response carries a top-level `timings` object for the request. It uses
llama.cpp's field names, so a proxy or dashboard built against llama-server (llama-swap's activity
view, for one) reads it unchanged:
```json
"timings": {
"cache_n": 1024, "prompt_n": 71, "prompt_ms": 284.0,
"prompt_per_token_ms": 4.0, "prompt_per_second": 250.0,
"predicted_n": 64, "predicted_ms": 711.0,
"predicted_per_token_ms": 11.29, "predicted_per_second": 88.6,
"draft_n": 78, "draft_n_accepted": 37
}
```
| field | meaning |
|---|---|
| `prompt_n` | prompt tokens this request computed. Tokens the prefix cache supplied are not in it |
| `cache_n` | prompt tokens the prefix cache supplied. `prompt_n + cache_n` is the prompt |
| `prompt_ms` | from the first step the scheduler gave the request to its first token: the prefill. The time it waited for admission is not in it |
| `prompt_per_second`, `prompt_per_token_ms` | `prompt_n` over `prompt_ms`. A prompt the cache mostly supplied computes few tokens, so this is the speed of the prefill that actually ran, not the prompt length over the time to first token |
| `predicted_n` | tokens generated, the same as `usage.completion_tokens` |
| `predicted_ms` | from the first generated token to the last |
| `predicted_per_second`, `predicted_per_token_ms` | the `predicted_n − 1` tokens after the first, over `predicted_ms`. The first token is the prefill's product. It is the same figure as `/metrics`' time per output token, and with speculative decoding it counts every token a step accepts |
| `draft_n`, `draft_n_accepted` | speculative tokens proposed for this request and how many were accepted. Present when any were proposed, as llama.cpp does |
Milliseconds are wall-clock milliseconds, and the rates are tokens per second. A rate whose count
or time is zero is `null`. A request with several choices (`n`, or a batch of prompts) sums the
counts, and each time runs from the earliest choice's start to the latest choice's end.
When streaming, each choice's final chunk (the one with `finish_reason`) carries its own
`timings`, whether or not the request asked for `stream_options.include_usage`. The usage chunk,
when asked for, carries the request's. `/metrics` stays the aggregate surface (§6.3). It sums
the same quantities over every request, so it cannot say which request they belong to.
## 6. Operate it
### 6.1 The dashboard
@@ -1131,6 +1320,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:
@@ -1193,7 +1387,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"
@@ -1235,10 +1430,11 @@ released until it does.
| The server dies with no log line, on a request it had been serving fine | A kernel whose code object had never been loaded could not be: the card has no room left. HIP faults inside the launch rather than returning an error, so there is nothing to print | A card that never met `--gpu-headroom-mib` — see §4.3. Raise the headroom past the shortfall startup names. `coredumpctl info` names the kernel; `AMD_LOG_LEVEL=1` prints `HSA_STATUS_ERROR_OUT_OF_RESOURCES` just above the fault |
| KV in VRAM stays high with one session and nothing moves | The idle tiers are **off** — they are sized, and with no size nothing is copied | Pass `--prefix-cache-host-mib N` |
| `out of memory` / `the carve reserved N of address space and the card would not back it` | Something else is holding VRAM | Check with `rocm-smi`; stop the other process. The budget is stated before allocation, so the log says what it asked for |
| `pool allocation refused` with `backing allocation of … refused` on the second card, after the first card's pools succeeded | The VRAM budget is measured before any rank allocates. A card that refuses its weights pool lost that memory to another process in between (the line below the refusal says how much is free now). A refused `host_pool` is pinned memory: **every rank pins its own `--host-pool-mib`**, so `--tp 2` pins it twice, and the amdgpu driver caps pinned memory system-wide at `ttm.pages_limit`, half of RAM by default | Stop the other process (`rocm-smi --showpids`). For the host pool, keep `--tp` × `--host-pool-mib` under the cap the refusal names, or raise it with the kernel parameter `ttm.pages_limit` |
| `--draft-model is not implemented` | This engine loads its drafter from the container | `rad-convert --draft-model DIR` at conversion time |
| `context_length_exceeded` on a request | The **prompt alone** does not fit the context. `max_tokens` is clamped rather than refused, so this fires only when there is no room left to generate at all | Shorten the prompt by the number of tokens the message names, or raise `--max-model-len` if the model allows it |
| `unknown option '--foo'` and the engine exits | Deliberate. A typo in a budget flag is the difference between the plan you asked for and one the planner invented | Check `radiance --help` |
| Empty `content` and `finish_reason: "length"` on short chat turns | The template's default `reasoning_effort` spent the budget inside `<think>` | `--reasoning-effort medium`, or `"reasoning_effort": "none"` per request |
| Empty `content` and `finish_reason: "length"` on short chat turns | The reasoning spent all of `max_tokens` inside `<think>`; `usage.completion_tokens_details.reasoning_tokens` equals `completion_tokens`. Qwen3.8's default `reasoning_effort` is `xhigh` | `--reasoning-effort medium`, or `"reasoning_effort": "none"` per request; or cap the reasoning with `thinking_token_budget` / `--thinking-token-budget` below `max_tokens` |
| `401` with `invalid api key` | The server was started with `--api-key` | Send `Authorization: Bearer KEY` (§6.6) |
First three things to run when a server will not start:
+10
View File
@@ -97,6 +97,16 @@ Two consequences worth internalising:
- **A band you claim and cannot serve is invisible to a single-sequence bench.** It only shows at
concurrency, where M is larger. Run the whole ladder, not just C=1.
**A constraint can be on the machine instead of the geometry.** A key that starts with `device.`
is matched against what the engine measured about the ranks' cards at launch, not against the
op's parameters. `RAD_CEQ(RAD_FACT_P2P, 1)` (`device.p2p`) is how a kernel says it reads or writes
another card's memory. On a machine where some pair of the ranks' cards cannot reach each other,
such a kernel is not selected. The next row that does not need it takes the op. With no such row,
startup stops and the selection table names the fact (`device.p2p == 1, have 0 -- this machine,
measured at launch`). Every collective in libr4d carries it. A machine fact is in no geometry, so
it changes no tuning key. A tool that selects without an engine has measured nothing, and such a
kernel is not selected there either.
`priority` breaks ties **within your plugin**, highest first, a tie going to declaration order.
Between plugins there is no contest: **the hierarchy is absolute.** The first plugin in `--kernels`
order with any matching kernel supplies it, and a later plugin never outbids it however
+1 -1
View File
@@ -452,7 +452,7 @@ rad-tokcheck [options] <tokenizer.json> <corpus-file>...
--hf-dir DIR compare against HuggingFace ids in DIR/<corpus basename>.ids
(little-endian int32, encode(text, add_special_tokens=False))
--no-ref skip the reference encoder, which is slow
--user encode with parse_special off, as the server does for user content
--user encode with parse_special off: a control token's spelling is text
--turns N turns in the multi-turn measurement (default 40, 0 skips it)
--repeat N timing repeats, best taken (default 3)
--context N ids shown either side of a difference (default 6)
+8
View File
@@ -802,6 +802,8 @@ static bool schema_same(const RadOpSchema& a, const RadOpSchema& b, std::string*
/* embed_lookup_q over a file-backed table, two ranks and the reader racing (avx_check_rows.cpp). */
bool row_gather_case(const Lib& avx, const std::string& dir, int64_t calls, bool verbose,
bool bf16);
/* embed_lookup_q's init, where io_uring is refused and here (avx_check_rows.cpp). */
bool ngram_init_case(const Lib& avx);
int main(int argc, char** argv) {
std::string ref_path = "libref.so", avx_path = "libavx.so", only_op;
@@ -885,6 +887,12 @@ int main(int argc, char** argv) {
}
int rc = missing ? 1 : 0;
/* Before anything runs a gather: the case forks, and a child is cleanest taken from a process
* that has started none of the gather's threads. */
if (only_op.empty() || only_op == "embed_lookup_q") {
std::printf("\n");
if (!ngram_init_case(avx)) rc = 1;
}
const int lo = only_level >= 0 ? only_level : 0;
const int hi = only_level >= 0 ? only_level : AVX_N_LEVELS - 1;
std::vector<std::string> declined_ops;
+91
View File
@@ -28,13 +28,104 @@
#include <cstring>
#include <thread>
#include <cstddef>
#include <fcntl.h>
#include <linux/filter.h>
#include <linux/io_uring.h>
#include <linux/seccomp.h>
#include <sys/mman.h>
#include <sys/prctl.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/wait.h>
#include <unistd.h>
/* EMBED_LOOKUP_Q'S INIT REFUSES A PROCESS THAT MAY NOT MAKE AN io_uring RING, and says why: Docker's
* default seccomp profile answers EPERM to io_uring_setup, and a server started that way used to
* load the whole model and then fail every request as "unsupported". A child process installs the
* same refusal as a seccomp filter and asks the kernel's init, which must refuse a gather into
* bf16 -- the one that reads through the ring -- name the Docker option on stderr, and accept a
* gather into f32, which reads the table as memory. Then this process asks: it must accept where a
* ring can be made and refuse where it cannot, as in a build sandbox. */
bool ngram_init_case(const Lib& avx) {
const char* what = "embed_lookup_q's init";
const RadKernelInfo* r = avx.row("embed_lookup_q");
if (!r || !r->init) {
std::printf(" %s: the row has no init\n", what);
return false;
}
RadParam bf16[2]{}, f32[2]{};
bf16[0].key = f32[0].key = "n_embd";
bf16[0].kind = f32[0].kind = RAD_P_INT;
bf16[0].ival = f32[0].ival = 160;
bf16[1].key = f32[1].key = "dtype";
bf16[1].kind = f32[1].kind = RAD_P_STR;
bf16[1].sval = "bf16";
f32[1].sval = "f32";
int out[2];
if (::pipe(out) != 0) {
std::printf(" %s: pipe: %s\n", what, std::strerror(errno));
return false;
}
std::fflush(nullptr);
const pid_t pid = ::fork();
if (pid == 0) {
::dup2(out[1], 2);
::close(out[0]);
sock_filter f[] = {
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, offsetof(seccomp_data, nr)),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_io_uring_setup, 0, 1),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ERRNO | (EPERM & SECCOMP_RET_DATA)),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
};
sock_fprog prog{ (unsigned short)(sizeof f / sizeof f[0]), f };
if (::prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) != 0 ||
::prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &prog) != 0)
::_exit(3);
void* inst = nullptr;
const int a = r->init(bf16, 2, 0, 1, &inst);
const int b = r->init(f32, 2, 0, 1, &inst);
std::fflush(nullptr);
::_exit(a == RAD_E_UNSUPPORTED && b == RAD_OK ? 0 : 1);
}
::close(out[1]);
std::string said;
char buf[512];
for (ssize_t k; (k = ::read(out[0], buf, sizeof buf)) > 0;) said.append(buf, (size_t)k);
::close(out[0]);
int ws = 0;
if (pid < 0 || ::waitpid(pid, &ws, 0) != pid || !WIFEXITED(ws)) {
std::printf(" %s: the child did not run to the end\n", what);
return false;
}
bool ok = true;
if (WEXITSTATUS(ws) == 3) {
std::printf(" %s, where io_uring is refused: SKIPPED -- no seccomp filter can be installed "
"here\n", what);
} else if (WEXITSTATUS(ws) != 0 ||
said.find("--security-opt seccomp=unconfined") == std::string::npos) {
std::printf(" %s, where io_uring is refused: FAIL -- %s; it said: %s\n", what,
WEXITSTATUS(ws) ? "the statuses were wrong" : "the reason was not named",
said.c_str());
ok = false;
} else {
std::printf(" %s, where io_uring is refused: refused, naming the Docker option\n", what);
}
io_uring_params p{};
const long ring = syscall(__NR_io_uring_setup, 1, &p);
const bool here = ring >= 0;
if (here) ::close((int)ring);
void* inst = nullptr;
const int st = r->init(bf16, 2, 0, 1, &inst);
const bool right = here ? st == RAD_OK : st == RAD_E_UNSUPPORTED;
std::printf(" %s, in this process (io_uring %s): %s\n", what, here ? "available" : "refused",
right ? (here ? "accepted" : "refused") : "FAIL");
return ok && right;
}
bool row_gather_case(const Lib& avx, const std::string& dir, int64_t calls, bool verbose,
bool bf16) {
const RadKernelInfo* r = avx.row("embed_lookup_q");
+76 -8
View File
@@ -439,6 +439,7 @@ struct ReadRing {
io_uring_cqe *cqes = nullptr;
void *sq_ring = nullptr, *cq_ring = nullptr;
size_t sq_sz = 0, cq_sz = 0, sqe_sz = 0;
int err = 0; /* the errno that stopped init(), for ring_refusal() */
/* One thread submits and reaps (SINGLE_ISSUER), and completions are run when it asks for them
* rather than by interrupting it (DEFER_TASKRUN): the ring is thread-local and the thread only
@@ -448,7 +449,7 @@ struct ReadRing {
std::memset(&p, 0, sizeof p);
p.flags = IORING_SETUP_SINGLE_ISSUER | IORING_SETUP_DEFER_TASKRUN;
const long r = syscall(__NR_io_uring_setup, kEntries, &p);
if (r < 0) return false;
if (r < 0) { err = errno; return false; }
fd = (int)r;
entries = p.sq_entries;
sq_sz = p.sq_off.array + (size_t)p.sq_entries * sizeof(unsigned);
@@ -459,16 +460,16 @@ struct ReadRing {
}
sq_ring = mmap(nullptr, sq_sz, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_POPULATE,
fd, IORING_OFF_SQ_RING);
if (sq_ring == MAP_FAILED) { sq_ring = nullptr; shut(); return false; }
if (sq_ring == MAP_FAILED) { err = errno; sq_ring = nullptr; shut(); return false; }
cq_ring = (p.features & IORING_FEAT_SINGLE_MMAP)
? sq_ring
: mmap(nullptr, cq_sz, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_POPULATE,
fd, IORING_OFF_CQ_RING);
if (cq_ring == MAP_FAILED) { cq_ring = nullptr; shut(); return false; }
if (cq_ring == MAP_FAILED) { err = errno; cq_ring = nullptr; shut(); return false; }
sqe_sz = (size_t)p.sq_entries * sizeof(io_uring_sqe);
sqes = (io_uring_sqe*)mmap(nullptr, sqe_sz, PROT_READ | PROT_WRITE,
MAP_SHARED | MAP_POPULATE, fd, IORING_OFF_SQES);
if (sqes == MAP_FAILED) { sqes = nullptr; shut(); return false; }
if (sqes == MAP_FAILED) { err = errno; sqes = nullptr; shut(); return false; }
sq_tail = (unsigned*)((char*)sq_ring + p.sq_off.tail);
sq_mask = (unsigned*)((char*)sq_ring + p.sq_off.ring_mask);
sq_array = (unsigned*)((char*)sq_ring + p.sq_off.array);
@@ -532,17 +533,51 @@ struct ReadRing {
/* Thread-local: each rank thread issues its own step, so each gets its own ring and the two never
* contend. Built on that thread's first gather over a file and torn down when the thread exits. */
inline ReadRing* read_ring() {
/* This thread's ring, made on its first gather. Null if it could not be made, with the errno in
* `*why`. */
inline ReadRing* read_ring(int* why) {
static thread_local bool tried = false;
static thread_local int err = 0;
static thread_local std::unique_ptr<ReadRing> r;
if (!tried) {
tried = true;
std::unique_ptr<ReadRing> p(new ReadRing());
if (p->init()) r = std::move(p);
else err = p->err ? p->err : EIO;
}
if (!r && why) *why = err;
return r.get();
}
/* WHY THIS PROCESS CANNOT MAKE A RING, said in terms of what to change. Docker's default seccomp
* profile is by far the commonest: it answers EPERM to io_uring_setup, and so does the
* kernel.io_uring_disabled sysctl. A kernel too old for SINGLE_ISSUER and DEFER_TASKRUN answers
* EINVAL. */
std::string ring_refusal(int e) {
std::string s = "libavx: the n-gram table is read through io_uring, and this process cannot "
"make a ring (" + std::string(std::strerror(e)) + "). ";
if (e == EPERM || e == EACCES)
s += "Docker's default seccomp profile refuses io_uring: run the container with "
"--security-opt seccomp=unconfined (docs/DOCKER.md). Outside a container, the "
"kernel.io_uring_disabled sysctl refuses it the same way.";
else if (e == ENOSYS)
s += "This kernel is built without io_uring.";
else if (e == EINVAL)
s += "The ring needs IORING_SETUP_SINGLE_ISSUER and IORING_SETUP_DEFER_TASKRUN, which "
"Linux 6.1 added.";
return s;
}
/* Whether this process can make the ring every gathering thread makes: 0, or the errno that
* stopped it. Asked once, by making one and closing it. */
int ring_errno() {
static const int e = [] {
ReadRing r;
return r.init() ? 0 : (r.err ? r.err : EIO);
}();
return e;
}
/* Read `reads` through the ring, a batch at a time: a row with a slot is copied into the cache and
* published READY; a row without one is decoded straight into its output row. On a failed read,
* every claim not yet published is given up (its word back to EMPTY) so no other thread waits on
@@ -711,7 +746,7 @@ struct AheadReader {
void run() {
Gather& g = gather_state();
ReadRing* rr = read_ring();
ReadRing* rr = read_ring(nullptr);
const uint64_t me = owner_tag();
for (;;) {
AheadJob j;
@@ -861,9 +896,15 @@ int avx::row_gather(const RowGather& q, RowDecode decode) {
if (!tfile) return ferr;
#if defined(__linux__)
if (tfile->fd >= 0) {
ReadRing* rr = read_ring();
int why = 0;
ReadRing* rr = read_ring(&why);
if (!rr) {
static std::once_flag said;
std::call_once(said, [why] { std::fprintf(stderr, "%s\n", ring_refusal(why).c_str()); });
return RAD_E_UNSUPPORTED;
}
RowCache* rc = row_cache(tfile, q.row_bytes);
if (!rr || !rc) return RAD_E_UNSUPPORTED;
if (!rc) return RAD_E_NOMEM;
const long long ws = q.world_size > 1 ? q.world_size : 1;
const long long first = q.rank > 0 && q.rank < ws ? q.M * q.rank / ws : 0;
const int rs = gather_rows(*tfile, *rc, *rr, q, first, decode, lut);
@@ -943,3 +984,30 @@ extern "C" int avx_layout_ngram(const RadParam* p, int n_p, int operand, const R
if (pl[0].rank != 2 || pl[0].shape[0] != r || pl[0].shape[1] != c) return RAD_E_SHAPE;
return RAD_E_UNSUPPORTED;
}
/* ============================== THE INSTANCE: CAN THIS PROCESS READ THE TABLE ==============================
*
* Every miss of the gather into bf16 is an io_uring read, and a process that may not make a ring
* fails every step that gathers: the first request fails, after the whole model has loaded, and
* the engine stops. So the instance asks at declare, before a byte is loaded, and refuses with
* the reason. A gather into any other dtype takes the general path, which reads the table as
* memory and makes no ring. rad-convert declares without instances -- it launches nothing -- so a
* sandbox that forbids io_uring still converts the model. */
extern "C" int avx_init_ngram(const RadParam* p, int n_p, int rank, int world_size, void** out) {
(void)rank;
(void)world_size;
if (out) *out = nullptr;
#if defined(__linux__)
const char* dt = rad_param_gets(p, n_p, "dtype", nullptr);
if (!dt || std::strcmp(dt, "bf16") != 0) return RAD_OK;
if (const int e = ring_errno()) {
static std::once_flag said;
std::call_once(said, [e] { std::fprintf(stderr, "%s\n", ring_refusal(e).c_str()); });
return RAD_E_UNSUPPORTED;
}
#else
(void)p;
(void)n_p;
#endif
return RAD_OK;
}
+5 -3
View File
@@ -725,14 +725,16 @@ SIMPLE("avx_all_gather", "all_gather", "ar", "gather every rank's shard; world_s
SIMPLE("avx_embed_lookup", "embed_lookup", "vocab", "embedding gather", DT_FLOAT, L(embed_lookup)),
/* THE ONE ROW WITH A LAYOUT HOOK, and it only checks: the table is read as it is stored, and the
* hook refuses a table encoded any other way (avx_ngram.cpp). An E4M3 table into bf16 goes through
* the row cache; every other dtype pair takes the general gather. */
* the row cache; every other dtype pair takes the general gather. Its init refuses a process that
* may not make the io_uring ring the cache's misses are read through, at declare and not at the
* first request. */
{ "avx_embed_lookup_q", "embed_lookup_q", "vocab",
"embedding gather, one scale for the table: an E4M3 table into bf16 through a shared row cache "
"and direct reads of the container, a later call's rows read ahead",
SHAPE_ANY, DT_ANY, RAD_DOMAIN_HOST, 0,
nullptr, 0, nullptr, 0, nullptr,
/* init, fini, LAUNCH, scratch, layout, relayout, opd_shape, unrelayout */
nullptr, nullptr, L(embed_lookup_q), nullptr, avx_layout_ngram, nullptr, nullptr, nullptr,
/* INIT, fini, LAUNCH, scratch, layout, relayout, opd_shape, unrelayout */
avx_init_ngram, nullptr, L(embed_lookup_q), nullptr, avx_layout_ngram, nullptr, nullptr, nullptr,
nullptr, nullptr },
SIMPLE("avx_logits_gemm", "logits_gemm", "vocab", "the lm_head projection", DT_FLOAT,
L(logits_gemm)),
+4
View File
@@ -52,4 +52,8 @@ int row_gather(const RowGather& g, RowDecode decode);
extern "C" int avx_layout_ngram(const RadParam*, int, int, const RadEncoding*, const int*,
const RadTensor*, int, RadLayout*);
/* Whether this process can read the table's rows: refused, with the reason on stderr, where it may
* not make an io_uring ring (avx_ngram.cpp). */
extern "C" int avx_init_ngram(const RadParam*, int, int, int, void**);
#endif /* RAD_AVX_ROWS_H */
+17
View File
@@ -62,6 +62,11 @@
#define C_DIV(k, v) { (k), RAD_C_DIV, (long long)(v), nullptr }
#define C_IN(k, s) { (k), RAD_C_IN, 0, (s) }
/* EVERY KERNEL THAT TOUCHES A PEER'S MEMORY: the collectives push into the other ranks' scratch and
* raise their flags directly, so a machine whose cards cannot reach each other must not select
* them. The engine measures this at launch (rad_types.h, device.p2p). */
#define C_P2P C_EQ(RAD_FACT_P2P, 1)
/* libr4d's R4D_AR_TWOSHOT_WIDE_MAX_ELEMS, restated because this file must not include r4d.h.
* r4d_ar_entry.hip static_asserts the two against each other. */
#define R4D_AR_TWOSHOT_WIDE_MAX_ELEMS 20971520
@@ -2297,32 +2302,40 @@ static const RadConstraint cGdnGatedRmsNorm[] = {
* accepts either, so a constraint that took only one would refuse the sampler by a synonym. */
static const RadConstraint cArGather2[] = {
C_EQ("world_size", 2), C_IN("dtype", "bf16 fp16 f16 fp32 f32"),
C_P2P,
};
static const RadConstraint cArExact[] = {
C_EQ("world_size", 2), C_EQ("exact", 1), C_IN("dtype", "bf16 fp16 fp32"),
C_P2P,
};
static const RadConstraint cArExact4[] = {
C_EQ("world_size", 4), C_EQ("exact", 1), C_IN("dtype", "bf16 fp16 fp32"),
C_P2P,
};
static const RadConstraint cArExact8[] = {
C_EQ("world_size", 8), C_EQ("exact", 1), C_IN("dtype", "bf16 fp16 fp32"),
C_P2P,
};
static const RadConstraint cArTsExact4[] = {
C_EQ("world_size", 4), C_EQ("exact", 1), C_EQ("hops", 2),
C_IN("dtype", "bf16 fp16 fp32"),
C_DIV("numel", 64), C_LE("numel", R4D_AR_TWOSHOT_WIDE_MAX_ELEMS),
C_P2P,
};
static const RadConstraint cArTsExact8[] = {
C_EQ("world_size", 8), C_EQ("exact", 1), C_EQ("hops", 2),
C_IN("dtype", "bf16 fp16 fp32"),
C_DIV("numel", 64), C_LE("numel", R4D_AR_TWOSHOT_WIDE_MAX_ELEMS),
C_P2P,
};
static const RadConstraint cArWht6[] = {
C_EQ("world_size", 2), C_EQ("exact", 0), C_IN("dtype", "bf16 fp16"), C_DIV("numel", 64),
C_P2P,
};
static const RadConstraint cArTi8Ts4[] = {
C_EQ("world_size", 4), C_EQ("exact", 0), C_IN("dtype", "bf16 fp16"), C_DIV("numel", 128),
C_P2P,
};
/* ---- GEMM ------------------------------------------------------------------------------------
@@ -2595,17 +2608,20 @@ static const RadConstraint cRmsNormQuantFp8[] = {
static const RadConstraint cArRmsNormQuantFp8[] = {
C_DIV("n", 8), C_EQ("group", R4D_FP8_BLOCK), C_IN("dtype", "bf16"),
C_EQ("world_size", 2),
C_P2P,
};
/* hc_write's own bounds plus the all-reduce's: `n DIV 8` because `y` is pushed as 16B words, and
* world_size 2 because the handshake is one peer flag per block. */
static const RadConstraint cArHcWrite[] = {
C_GE("M", 1), C_DIV("n", 8), C_GE("hc", 2), C_LE("hc", 8), C_IN("dtype", "bf16"),
C_EQ("world_size", 2),
C_P2P,
};
/* ar_hc_write's bounds and the gather's: top_k up to the 64 slots a row's table holds in LDS. */
static const RadConstraint cArGatherHcWrite[] = {
C_GE("M", 1), C_DIV("n", 8), C_GE("hc", 2), C_LE("hc", 8), C_IN("dtype", "bf16"),
C_EQ("world_size", 2), C_GE("top_k", 1), C_LE("top_k", 64),
C_P2P,
};
static const RadConstraint cGatedQuantFp8[] = {
C_DIV("n", 4), C_EQ("group", R4D_FP8_BLOCK), C_IN("dtype", "bf16"),
@@ -2658,6 +2674,7 @@ static const RadConstraint cRmsNormHadQuantI8[] = {
static const RadConstraint cArLnHadQuantI8[] = {
C_DIV("n", 16), C_DIV("n", 128), C_LE("n", 16256), C_LE("group", 512), C_IN("dtype", "bf16"),
C_EQ("world_size", 2),
C_P2P,
};
static const RadConstraint cQkNormRopeGate[] = {
C_IN("q_dtype", "bf16"), C_LE("head_dim", 256), C_DIV("head_dim", 32),
+4 -1
View File
@@ -337,8 +337,11 @@ static void cross_check(const Plugin& pl) {
continue;
}
/* THE CHECK THAT EARNS ITS KEEP. A constraint on a key the op does not declare can never
* be satisfied, so the row is unreachable and nothing says so. */
* be satisfied, so the row is unreachable and nothing says so. A "device." key is not a
* parameter at all: it is matched against the machine (rad_types.h). */
static const size_t kFact = std::strlen(RAD_DEVICE_FACT_PREFIX);
for (int c = 0; c < r->n_constraints; ++c) {
if (!std::strncmp(r->constraints[c].key, RAD_DEVICE_FACT_PREFIX, kFact)) continue;
bool found = false;
for (int j = 0; j < sc->n_params; ++j)
if (!std::strcmp(sc->params[j].key, r->constraints[c].key)) { found = true; break; }
+82 -6
View File
@@ -849,6 +849,42 @@ static RadChatFormat qwen_abi() {
return c;
}
/* WHERE THE REPLY STARTS AGAINST ITS REASONING BLOCK, read from the generation prompt as the stream
* reads it: opened by the prompt, opened and closed again (thinking off), or not opened at all --
* and the markers trimmed of the whitespace that is optional to match. The engine counts and closes
* the block by these, so a reply this calls open has to be one the stream reads as reasoning. */
TEST(the_parser_says_whether_a_reply_starts_inside_its_reasoning_block) {
RadChatFormat c = qwen_abi();
ChatFormat f;
std::string why;
CHECK_OK(chat_format_from_abi(&c, &f, &why));
std::shared_ptr<const ReplyFormat> rf;
CHECK_OK(ReplyFormat::compile(f, &rf, &why));
struct Case { const char* prompt; bool open; };
for (const Case& k : { Case{ "<|im_start|>assistant\n<think>\n", true },
Case{ "<|im_start|>assistant\n<think>\n\n</think>\n\n", false },
Case{ "<|im_start|>assistant\n", false } }) {
ReplyOptions ro;
ro.generation_prompt = k.prompt;
std::shared_ptr<const ReplyParser> rp;
CHECK_OK(ReplyParser::create(rf, ro, &rp, &why));
const ReasoningMarkers m = rp->reasoning();
CHECK_EQ(m.open, std::string("<think>"));
CHECK_EQ(m.close, std::string("</think>"));
CHECK_EQ(m.starts_open, k.open);
const ReplyMessage r = reply_parse(*rp, "x</think>\n\ny");
CHECK_EQ(r.reasoning.empty(), !k.open);
}
ChatFormat none;
CHECK_OK(chat_format_from_template("", "", "", &none, &why, &why));
CHECK_OK(ReplyFormat::compile(none, &rf, &why));
std::shared_ptr<const ReplyParser> rp;
CHECK_OK(ReplyParser::create(rf, ReplyOptions{}, &rp, &why));
CHECK(rp->reasoning().close.empty());
CHECK(!rp->reasoning().starts_open);
}
/* A plugin that declares its model's format gets exactly what the template analysis derives for
* the same model: the same parser behaviour and the same grammar. */
TEST(a_declared_format_reads_and_constrains_like_the_derived_one) {
@@ -916,6 +952,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. */
@@ -1197,7 +1264,7 @@ static double seconds_to(const std::function<void()>& f, int reps = 3) {
}
static double stream_bytes(const ReplyParser& p, const std::string& text, size_t piece,
std::vector<double>* per_call = nullptr) {
std::vector<double>* per_call = nullptr, int reps = 3) {
return seconds_to([&] {
std::unique_ptr<ReplyStream> s = p.open();
std::vector<ReplyEvent> ev;
@@ -1209,7 +1276,7 @@ static double stream_bytes(const ReplyParser& p, const std::string& text, size_t
ev.clear();
}
s->finish(&ev);
}, per_call ? 1 : 3);
}, per_call ? 1 : reps);
}
TEST(a_long_reply_streamed_byte_by_byte_costs_a_constant_factor_of_parsing_it_once) {
@@ -1233,16 +1300,25 @@ TEST(a_long_reply_streamed_byte_by_byte_costs_a_constant_factor_of_parsing_it_on
}
}
TEST(twice_the_reply_costs_twice_the_time) {
/* FOUR TIMES THE REPLY COSTS FOUR TIMES THE TIME, and a quadratic path sixteen: the bound of 8 sits
* a factor of two from each. The two sizes are timed in turns, best of five each, so a burst of load
* from whatever else the machine runs lands on both: timed one size after the other, best of three,
* a 2x step read x3.9 beside three other test binaries and a server, against the 4 a quadratic
* path gives. */
TEST(four_times_the_reply_costs_four_times_the_time) {
for (const Model& m : models()) {
Bench* b = bench(m, ChatRequest{});
if (!b) continue;
const std::string a = long_reply(m, 200 * 1024), c = long_reply(m, 400 * 1024);
const double ta = stream_bytes(b->parser(), a, 1), tc = stream_bytes(b->parser(), c, 1);
const std::string a = long_reply(m, 100 * 1024), c = long_reply(m, 400 * 1024);
double ta = 1e30, tc = 1e30;
for (int rep = 0; rep < 5; ++rep) {
ta = std::min(ta, stream_bytes(b->parser(), a, 1, nullptr, 1));
tc = std::min(tc, stream_bytes(b->parser(), c, 1, nullptr, 1));
}
const double ratio = tc / ta;
fprintf(stderr, " %s: %zu -> %zu bytes byte by byte: %.3f -> %.3f ms (x%.2f)\n",
m.name.c_str(), a.size(), c.size(), ta * 1e3, tc * 1e3, ratio);
CHECK(ratio < 3.0);
CHECK(ratio < 8.0);
}
}
+268
View File
@@ -23,6 +23,7 @@
#include <cstdio>
#include <string>
#include <unistd.h>
#include <cstring>
#include <vector>
using namespace rad;
@@ -52,6 +53,13 @@ int parse(std::initializer_list<const char*> 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<const char*> 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();
@@ -212,6 +220,23 @@ TEST(the_paths_and_names_reach_their_fields) {
CHECK_EQ(c.override_chat_template, std::string("/t.jinja"));
}
/* The reasoning budget is a count or nothing: unset is -1, which no request default can mean. */
TEST(thinking_token_budget_takes_a_count_and_defaults_to_none) {
Config c;
CHECK_EQ(parse({}, &c), RAD_OK);
CHECK_EQ(c.thinking_token_budget, (int64_t)-1);
Config d;
CHECK_EQ(parse({ "--thinking-token-budget", "2048" }, &d), RAD_OK);
CHECK_EQ(d.thinking_token_budget, (int64_t)2048);
Config e;
CHECK_EQ(parse({ "--thinking-token-budget", "0" }, &e), RAD_OK);
CHECK_EQ(e.thinking_token_budget, (int64_t)0);
Config f;
CHECK(parse({ "--thinking-token-budget", "-1" }, &f) < 0);
Config g;
CHECK(parse({ "--thinking-token-budget", "lots" }, &g) < 0);
}
TEST(the_boolean_flags_are_off_until_they_are_given) {
Config d;
CHECK_EQ(parse({}, &d), RAD_OK);
@@ -383,6 +408,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<std::string>({ "\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 +799,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);
}
+484
View File
@@ -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
}
}
}
]
+63
View File
@@ -12,6 +12,7 @@
#include "rad_internal.h"
#include "device/device.h"
#include "device/directio.h"
#include "sched/advance.h"
#include <cstdio>
#include <cstdlib>
@@ -471,6 +472,68 @@ TEST(waiting_on_an_unrecorded_event_is_a_no_op) {
CHECK_OK(rad_stream_sync(st.s));
}
/* AN ADVANCE RUNS AT ITS PLACE IN STREAM ORDER. The sampled token it accepts is the last thing a
* step copies into place, and the advance is issued behind that copy without a host wait. The
* host backend's streams are queues with a worker thread each, so an advance run on the issuing
* thread without draining the stream read the token before the copy landed, and the next step
* continued from the previous token: CPU-only decode repeated words and differed at temperature
* 0. A long chain of copies goes ahead of the token's here, so an advance that jumps the queue
* reads the poison. */
TEST(an_advance_reads_the_token_a_copy_issued_before_it_delivers) {
const int64_t big = 4 << 20;
const int chain = 16;
RadStream s = nullptr;
REQUIRE(rad_stream_create(&s, 0) >= 0);
auto* blob_src = (uint8_t*)rad_dev_alloc(big, RAD_MEM_HOST_PINNED);
auto* blob_dst = (uint8_t*)rad_dev_alloc(big, RAD_MEM_DEVICE);
auto* slab = (char*)rad_dev_alloc(4096, RAD_MEM_DEVICE);
auto* src = (int32_t*)rad_dev_alloc(64, RAD_MEM_DEVICE);
auto* st = (rad::StepSlot*)rad_dev_alloc((int64_t)sizeof(rad::StepSlot), RAD_MEM_DEVICE);
auto* stage = (int32_t*)rad_dev_alloc(4096, RAD_MEM_HOST_PINNED);
REQUIRE(blob_src && blob_dst && slab && src && st && stage);
std::memset(blob_src, 0x5A, (size_t)big);
/* One device row that sampled row 0 with no drafts, at context 10, slot 0. */
rad::AdvanceArgs a;
a.mode = rad::ADV_ACCEPT;
a.n_seq = 1;
a.slab = slab;
a.row_off = 0; a.row_pitch = 1;
a.tok_off = 16; a.pos_off = 24; a.ctx_off = 32; a.acc_off = 40; a.out_off = 48;
a.sid_off = 56; a.cu_off = 64; a.q_off = 72; a.grp_off = 80;
a.st = st;
a.src = src;
const int32_t layout[20] = { 1, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0 };
std::memcpy(stage, layout, sizeof(layout));
for (int round = 0; round < 3; ++round) {
stage[64] = 7; /* the poison: what src holds before the copy */
stage[65] = 4242 + round; /* the token the copy delivers */
REQUIRE(rad_memcpy_async(slab, stage, sizeof(layout), s) >= 0);
REQUIRE(rad_memcpy_async(src, stage + 64, 4, s) >= 0);
REQUIRE(rad_memset_async(st, 0, (int64_t)sizeof(rad::StepSlot), s) >= 0);
REQUIRE(rad_stream_sync(s) >= 0);
for (int i = 0; i < chain; ++i) REQUIRE(rad_memcpy_async(blob_dst, blob_src, big, s) >= 0);
REQUIRE(rad_memcpy_async(src, stage + 65, 4, s) >= 0);
CHECK_OK(rad::step_advance(a, s));
rad::StepSlot got{};
REQUIRE(rad_memcpy_async(stage + 128, st, (int64_t)sizeof(rad::StepSlot), s) >= 0);
REQUIRE(rad_stream_sync(s) >= 0);
std::memcpy(&got, stage + 128, sizeof(rad::StepSlot));
CHECK_EQ(got.tok[0], 4242 + round);
CHECK_EQ(got.ctx, 11);
CHECK_EQ(got.n_acc, 1);
}
rad_dev_free(stage, RAD_MEM_HOST_PINNED);
rad_dev_free(st, RAD_MEM_DEVICE);
rad_dev_free(src, RAD_MEM_DEVICE);
rad_dev_free(slab, RAD_MEM_DEVICE);
rad_dev_free(blob_dst, RAD_MEM_DEVICE);
rad_dev_free(blob_src, RAD_MEM_HOST_PINNED);
rad_stream_destroy(s);
}
TEST(the_null_stream_is_refused) {
/* HIP's stream 0 serialises against every other blocking stream in the process, which is the
* opposite of what a transfer is for here. Refusing it on both backends means a caller cannot
+236
View File
@@ -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<GbnfGrammar> 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<GbnfGrammar> 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. */
@@ -1063,6 +1145,160 @@ TEST(gbnf_a_repetition_longer_than_any_token_costs_what_the_token_does) {
CHECK_EQ(t.mismatches, 0);
}
/* A LENGTH BOUND PAST 2000 IS HELD, EXACTLY. Upstream refused any repetition count past 2000, so
* a tool whose string argument declared `maxLength: 8000` failed every request carrying it. The
* expansion is bounded by what it costs to compile, not by the count: the bound is the string's
* length to the character, the plan is the one a count under 2000 compiles to, and only a count
* the compile budget cannot hold is refused -- naming the rule it is in. */
TEST(gbnf_a_length_bound_past_two_thousand_is_held_exactly) {
auto bv = bpe_like(59, 1500);
auto whole = [&](const std::string& gbnf, const std::string& text) {
std::unique_ptr<GbnfGrammar> 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 from_schema = [](const std::string& schema) {
std::string gbnf, err;
CHECK_OK(grammar_from_json_schema(schema, "root", &gbnf, &err));
return gbnf;
};
auto quoted = [](size_t n) { return "\"" + std::string(n, 'a') + "\""; };
for (int n : { 2001, 8000, 65536 }) {
const std::string g =
from_schema("{\"type\":\"string\",\"maxLength\":" + std::to_string(n) + "}");
CHECK(whole(g, quoted(0)));
CHECK(whole(g, quoted((size_t)n)));
CHECK(!whole(g, quoted((size_t)n + 1)));
}
{
const std::string g = from_schema(R"({"type":"string","minLength":3000,"maxLength":8000})");
CHECK(!whole(g, quoted(2999)));
CHECK(whole(g, quoted(3000)));
CHECK(whole(g, quoted(8000)));
CHECK(!whole(g, quoted(8001)));
}
{
const std::string g =
from_schema(R"({"type":"array","items":{"type":"integer"},"maxItems":5000})");
auto ones = [](int k) {
std::string s = "[";
for (int i = 0; i < k; ++i) s += i ? ",1" : "1";
return s + "]";
};
CHECK(whole(g, ones(5000)));
CHECK(!whole(g, ones(5001)));
}
/* The plan does not grow with the bound: past the longest token, no token tells the counts
* apart. */
std::vector<GbnfProgramInfo> info;
for (int n : { 1999, 8000, 65536 }) {
std::shared_ptr<const GbnfProgram> p;
std::string err;
REQUIRE(gbnf_compile(from_schema("{\"type\":\"string\",\"maxLength\":" +
std::to_string(n) + "}"),
"root", &bv->v, &p, &err) >= 0);
info.push_back(gbnf_program_info(*p));
}
CHECK_EQ(info[0].keys, info[1].keys);
CHECK_EQ(info[1].keys, info[2].keys);
CHECK_EQ(info[0].dense_masks, info[2].dense_masks);
/* The tool from the report, four 8000-character fields, through every served template's
* tool-call grammar and compiled: the request it is in is served. */
const char* tools = R"([{"type":"function","function":{"name":"clarify",
"description":"Ask the user to choose.","parameters":{"type":"object","properties":{
"question":{"type":"string","maxLength":8000},
"choices":{"type":"array","maxItems":4,"items":{"type":"string","maxLength":8000}}},
"required":["question","choices"]}}}])";
const ojson messages = ojson::array({ ojson{ { "role", "user" }, { "content", "hi" } } });
int compiled = 0, carried = 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) {
for (const char* choice : { "auto", "required" }) {
ChatOptions opt;
opt.tool_choice = choice;
opt.parallel_tool_calls = par != 0;
ChatPrompt cp;
CHECK(ct.apply(messages, ojson::parse(tools), opt, &cp) >= 0);
if (cp.grammar.empty()) continue;
std::shared_ptr<const GbnfProgram> p;
std::string err;
const auto t0 = std::chrono::steady_clock::now();
CHECK(gbnf_compile(cp.grammar, "root", &bv->v, &p, &err) >= 0);
if (!err.empty()) std::fprintf(stderr, " %s: %s\n", tc.file, err.c_str());
const double ms = ms_since(t0);
CHECK(ms < 2000.0);
++compiled;
if (cp.grammar.find("8000}") != std::string::npos) {
++carried;
std::fprintf(stderr, " %s, %s, parallel %s: the bound is in the grammar\n",
tc.file, choice, par ? "on" : "off");
}
}
}
}
CHECK(compiled >= 6);
CHECK(carried >= 1);
/* A group under a repetition is a reference to the group's rule, not a copy of it, so its
* cost is the two counts added, not multiplied; upstream refused it as multiplied. */
{
std::shared_ptr<const GbnfProgram> p;
std::string err;
CHECK(gbnf_compile("root ::= ([a-z]{3000}){3000} \";\"\n", "root", &bv->v, &p, &err) >= 0);
}
/* A schema's bound past INT_MAX -- Number.MAX_SAFE_INTEGER is a common "no limit" -- is no
* bound, which no context the engine serves can tell from the bound; it used to wrap to -1 and
* fail to parse. A negative or non-numeric bound is refused by the converter, naming it. */
for (const char* big : { "9007199254740991", "1e300", "2147483648" }) {
const std::string g =
from_schema(std::string("{\"type\":\"string\",\"maxLength\":") + big + "}");
CHECK(whole(g, quoted(3000)));
const std::string a = from_schema(std::string("{\"type\":\"array\",\"maxItems\":") + big +
",\"items\":{\"type\":\"integer\"}}");
CHECK(whole(a, "[1,2,3]"));
}
for (const char* bad : { R"({"type":"string","maxLength":-5})",
R"({"type":"string","minLength":"3"})",
R"({"type":"array","items":{},"maxItems":-1})" }) {
std::string gbnf, err;
CHECK(grammar_from_json_schema(bad, "root", &gbnf, &err) < 0);
CHECK(err.find("must be a non-negative number") != std::string::npos);
}
/* A bound the compile budget cannot hold is refused naming the property's rule and the
* count, which is what a client needs to find it in its tool list. */
{
std::shared_ptr<const GbnfProgram> p;
std::string err;
CHECK(gbnf_compile(from_schema(R"({"type":"object","properties":{"content":)"
R"({"type":"string","maxLength":1000000}}})"),
"root", &bv->v, &p, &err) < 0);
CHECK(err.find("rule 'content'") != std::string::npos);
CHECK(err.find("{0,1000000}") != std::string::npos);
}
/* What the budget cannot hold is refused, by rule, and a count past 2^64 - 2 is refused as
* one; none of them wraps into a small expansion that compiles. A repetition of a repetition
* copies the expanded run, so `{3000}{3000}` is nine million elements. */
for (const char* g : { "root ::= \"a\" item\nitem ::= [a-z]{0,100000000}\n",
"root ::= \"a\" item\nitem ::= [a-z]{0,18446744073709551614}\n",
"root ::= \"a\" item\nitem ::= [a-z]{18446744073709551614}\n",
"root ::= \"a\" item\nitem ::= [a-z]{0,99999999999999999999999}\n",
"root ::= \"a\" item\nitem ::= [a-z]{3000}{3000}\n" }) {
std::shared_ptr<const GbnfProgram> p;
std::string err;
CHECK(gbnf_compile(g, "root", &bv->v, &p, &err) < 0);
CHECK(err.find("rule 'item'") != std::string::npos);
}
}
/* EVERY TOOL'S COPY OF THE SAME CLAUSE IS ONE CLAUSE TO THE PLAN. A tool-calling template writes
* the same undeclared-parameter clause, the same free-text value and the same closing tags once
* per tool, as rules of their own; the plan hash-conses rules by body, so its size -- and the
+64
View File
@@ -170,6 +170,25 @@ TEST(pool_reservation_never_falls_through) {
CHECK_EQ(p.kv().used(), 512ll << 10);
}
/* A BACKING ALLOCATION THE ALLOCATOR REFUSES IS REPORTED AS A REFUSAL, with the allocator's reason
* where it has one -- not as "0 B available", which reads as a measurement of the card and sends
* the reader looking for memory that was never measured. */
TEST(a_refused_backing_allocation_says_it_was_refused_and_why) {
struct Refuses final : MemAllocator {
void* alloc(int64_t, int) override { return nullptr; }
void free(void*, int) override {}
const char* name() const override { return "refuses"; }
} none;
Config c = small_config();
Pools p;
CHECK_EQ(p.configure(c, 0, &none, &none), RAD_E_NOMEM);
const std::string& r = p.fit_report();
CHECK(r.find("backing allocation of") != std::string::npos);
CHECK(r.find("refused: the allocator returned nothing") != std::string::npos);
CHECK(r.find("0 B available") == std::string::npos);
CHECK(!p.configured());
}
/* ================================================================== the derived budget */
TEST(derived_budget_takes_the_statics_off_the_top_then_divides_the_rest) {
@@ -307,6 +326,51 @@ TEST(a_dense_model_has_no_expert_share_to_lose) {
CHECK(c.vram_weights_mib * MiB - f.statics < MiB);
}
/* THE ENGINE'S HARDWARE QUEUES ARE A FIXED TERM. Each one costs the card VRAM the driver backs it
* with, and the streams are made after the card is read, so a split that left them out spent
* them out of the headroom: 67 MiB a card on a two-card Flash-Next server, leaving 9 MiB free
* under load against 96. The rank that needs most sets the term, as every fold here does. */
TEST(the_engine_s_queues_come_off_the_card_before_the_split) {
Config c = small_config();
c.vram_weights_mib = 0;
c.vram_kv_mib = 0;
c.gpu_headroom_mib = 96;
c.expert_cache_ratio = 0.75;
VramFacts f{};
f.capacity = 32LL << 30;
f.free = f.capacity - (512LL << 20);
f.arena = 144LL << 20;
f.staging = 98LL << 20;
f.statics = 2LL << 30;
f.experts = 200LL << 30;
f.kv_ceiling = 100LL << 30;
VramBudget b0;
CHECK_OK(vram_budget_resolve(c, { f }, &b0));
/* A fresh config: the resolver writes its answer back into the one it is given. */
Config c2 = small_config();
c2.vram_weights_mib = 0;
c2.vram_kv_mib = 0;
c2.gpu_headroom_mib = 96;
c2.expert_cache_ratio = 0.75;
VramFacts g = f, h = f;
g.n_queues = 2; g.queue_bytes = 33LL << 20;
h.n_queues = 3; h.queue_bytes = 33LL << 20; /* a rank with a second compute lane */
VramBudget b;
CHECK_OK(vram_budget_resolve(c2, { g, h }, &b));
CHECK_EQ(b.queues, 99LL << 20);
CHECK_EQ(b.n_queues, 3);
CHECK_EQ(b.claimable, b0.claimable - (99LL << 20));
CHECK(b.report.find("hardware queues") != std::string::npos);
/* What is left after the pools is still the headroom, with the queues and the staging paid. */
const int64_t MiB = 1024 * 1024;
const int64_t unclaimed = f.capacity - (512LL << 20) - f.arena - f.staging - b.queues
- c2.vram_weights_mib * MiB - c2.vram_kv_mib * MiB;
CHECK(unclaimed >= 96 * MiB);
CHECK(unclaimed < 98 * MiB);
}
TEST(a_stated_budget_still_wins_and_the_other_side_still_derives) {
Config c = small_config();
c.vram_weights_mib = 20000; /* stated */
+29
View File
@@ -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()
+32 -6
View File
@@ -119,10 +119,17 @@ say "4. the installed rad-kbench replays the fixture from the out-of-tree home:
# 5. The device library's machine code, against the tree's, object by object. A code object also
# carries its compilation unit's ID, which clang hashes from the command line and the output path,
# so two builds of one source never agree byte for byte; their instructions (.text) and kernel
# descriptors (.rodata) do, unless the flags that reach the device compiler differ.
# descriptors do, unless the flags that reach the device compiler differ.
#
# THE DESCRIPTORS ARE COMPARED BY NAME, NOT AS .rodata's BYTES. The compiler lays them out in an
# order that changes from one run of the same command to the next -- ROCm 7's clang does it to the
# eight instances of the template in r4d_gdn_chunk_scan_k128_v128_c64_bf16.hip -- and each holds
# its kernel's entry as an offset from itself, so the section's bytes differ while every kernel and
# every descriptor is the same. Each descriptor is read by its symbol, its entry resolved to the
# address in .text it names, and the rest of .rodata is compared with the descriptors blanked.
if [ -n "$HIPC" ]; then
L=$(dirname "$HIPC")
for t in llvm-objcopy clang-offload-bundler; do
for t in llvm-objcopy llvm-readelf clang-offload-bundler; do
[ -x "$L/$t" ] || fail "no $t beside $HIPC"
done
td="$B/libr4d/CMakeFiles/libr4d.dir"
@@ -131,15 +138,34 @@ if [ -n "$HIPC" ]; then
fatbin() { # fatbin OBJ -- its fat binary into $W/co/fb; false for a source with no kernels
"$L/llvm-objcopy" --dump-section .hip_fatbin="$W/co/fb" "$1" /dev/null 2>/dev/null
}
code() { # code OBJ TARGET -- checksums of that target's instructions and kernel descriptors
descriptors() { # descriptors CO RODATA -- each descriptor by name; blanks it in RODATA
set -- "$1" "$2" $("$L/llvm-readelf" -SW "$1" |
awk '{ for (i = 1; i < NF; ++i) if ($i == ".rodata") print $(i + 2), $(i + 3) }')
[ $# -eq 4 ] || return 0
base=$((0x$3)); foff=$((0x$4))
"$L/llvm-readelf" -sW "$1" | awk '$4 == "OBJECT" && $8 ~ /\.kd$/ { print $2, $3, $8 }' |
sort -u -k3 |
while read -r val size name; do
a=$((0x$val)); o=$((foff + a - base))
e=$(od -An -t d8 -j $((o + 16)) -N 8 "$1" | tr -d ' ')
printf '%s %s entry=%x %s %s\n' "$name" "$size" $((a + e)) \
"$(od -An -v -t x1 -j "$o" -N 16 "$1" | tr -d ' \n')" \
"$(od -An -v -t x1 -j $((o + 24)) -N $((size - 24)) "$1" | tr -d ' \n')"
dd if=/dev/zero of="$2" bs=1 seek=$((a - base)) count="$size" conv=notrunc 2>/dev/null
done
}
code() { # code OBJ TARGET -- checksums of that target's instructions, its descriptors by
# name, and the rest of its read-only data
fatbin "$1"
"$L/clang-offload-bundler" --type=o --input="$W/co/fb" --unbundle --targets="$2" \
--output="$W/co/co"
for sec in .text .rodata; do
"$L/llvm-objcopy" --dump-section "$sec=$W/co/sec" "$W/co/co" /dev/null 2>/dev/null ||
: > "$W/co/sec"
cksum < "$W/co/sec"
"$L/llvm-objcopy" --dump-section "$sec=$W/co/$sec" "$W/co/co" /dev/null 2>/dev/null ||
: > "$W/co/$sec"
done
cksum < "$W/co/.text"
descriptors "$W/co/co" "$W/co/.rodata" | cksum
cksum < "$W/co/.rodata"
}
[ "$(ls "$td"/*.hip.o | wc -l)" = "$(ls "$od"/*.hip.o | wc -l)" ] ||
fail "libr4d compiles a different set of HIP sources out of tree"
+30 -3
View File
@@ -118,8 +118,8 @@ TEST(loading_reads_identity_and_calls_open) {
if (!base) return;
CHECK_EQ((int)base->kind, RAD_PLUGIN_KERNEL);
CHECK_EQ(base->version, "0.1");
CHECK_EQ(base->n_kernels, 13);
CHECK_EQ(base->n_schemas, 7);
CHECK_EQ(base->n_kernels, 16);
CHECK_EQ(base->n_schemas, 9);
/* The optional open hook runs once, after load and before any selection. */
auto open_calls = reinterpret_cast<int (*)(void)>(dlsym(base->handle, "radtest_open_calls"));
@@ -285,7 +285,7 @@ TEST(every_row_s_op_has_a_schema) {
CHECK_OK(load(r));
CHECK_OK(r.check_complete());
const auto ops = r.op_names();
CHECK_EQ(ops.size(), (size_t)7);
CHECK_EQ(ops.size(), (size_t)9);
CHECK_EQ(ops[0], "t_attn");
}
@@ -790,4 +790,31 @@ TEST(the_selection_table_folds_repeats_and_names_the_refusal) {
CHECK_EQ(r.n_selections(), (size_t)0);
}
/* A "device." CONSTRAINT IS READ FROM THE MACHINE, not from the query: the engine measures peer
* access at launch and the selector holds a kernel that needs it to that. Unmeasured, the kernel
* is not selected and the refusal says nothing measured it; measured absent, the next row in the
* plugin takes the op, and an op with no such row is refused naming the fact. The query never
* carries the key, so no geometry -- and no tuning key -- changes. */
TEST(a_device_fact_constraint_is_matched_against_the_machine) {
Registry r;
CHECK_OK(load(r));
Geometry g;
g.set_i("M", 4);
g.set_i("n", 64);
CHECK_EQ(picked(r.select("t_peer", g, RAD_DOMAIN_DEVICE)), "t_peer_staged");
CHECK(has(refusal(r, "t_peer_only", g), "device.p2p is not known"));
r.set_device_fact(RAD_FACT_P2P, 1);
CHECK_EQ(picked(r.select("t_peer", g, RAD_DOMAIN_DEVICE)), "t_peer_direct");
CHECK_EQ(picked(r.select("t_peer_only", g, RAD_DOMAIN_DEVICE)), "t_peer_only_direct");
CHECK(!g.has(RAD_FACT_P2P));
r.set_device_fact(RAD_FACT_P2P, 0);
CHECK_EQ(picked(r.select("t_peer", g, RAD_DOMAIN_DEVICE)), "t_peer_staged");
const std::string why = refusal(r, "t_peer_only", g);
CHECK(has(why, "device.p2p == 1, have 0"));
CHECK(has(why, "measured at launch"));
}
RAD_TEST_MAIN()
+44
View File
@@ -20,6 +20,7 @@
#include "runtime/ctx.h"
#include "runtime/rank_barrier.h"
#include "runtime/residency.h"
#include "runtime/wtab.h"
#include <chrono>
#include <cstdlib>
@@ -1261,4 +1262,47 @@ TEST(arena_plan_bytes_returns_the_total_with_or_without_its_out_parameters) {
CHECK_EQ(a, total);
}
/* A WEIGHT-TABLE PATCH LANDS AT ITS PLACE IN STREAM ORDER: work issued before it reads the old
* entry, work issued after it the new one. On the host backend the patch is a host write, and
* made without draining the stream it reached the table before a queued reader issued ahead of
* it. A chain of copies holds that reader back long enough for a write that jumps the queue to
* show. */
TEST(a_weight_table_patch_lands_in_stream_order) {
const int64_t big = 4 << 20;
const int chain = 16;
RadStream s = nullptr;
REQUIRE(rad_stream_create(&s, 0) >= 0);
auto* blob_src = (uint8_t*)rad_dev_alloc(big, RAD_MEM_HOST_PINNED);
auto* blob_dst = (uint8_t*)rad_dev_alloc(big, RAD_MEM_DEVICE);
auto* tab = (void**)rad_dev_alloc(64, RAD_MEM_DEVICE);
auto* stage = (void**)rad_dev_alloc(64, RAD_MEM_HOST_PINNED);
REQUIRE(blob_src && blob_dst && tab && stage);
std::memset(blob_src, 0x5A, (size_t)big);
for (int round = 0; round < 3; ++round) {
void* const before = (void*)(uintptr_t)(0x1000 + round);
void* const after = (void*)(uintptr_t)(0x2000 + round);
stage[0] = before;
stage[1] = stage[2] = nullptr;
REQUIRE(rad_memcpy_async(tab, stage, sizeof(void*), s) >= 0);
REQUIRE(rad_stream_sync(s) >= 0);
for (int i = 0; i < chain; ++i) REQUIRE(rad_memcpy_async(blob_dst, blob_src, big, s) >= 0);
REQUIRE(rad_memcpy_async(stage + 1, tab, sizeof(void*), s) >= 0);
rad::WtabPatch p;
p.n = 1;
p.dst[0] = tab;
p.val[0] = after;
CHECK_OK(rad::wtab_patch(p, s));
REQUIRE(rad_memcpy_async(stage + 2, tab, sizeof(void*), s) >= 0);
REQUIRE(rad_stream_sync(s) >= 0);
CHECK(stage[1] == before);
CHECK(stage[2] == after);
}
rad_dev_free(stage, RAD_MEM_HOST_PINNED);
rad_dev_free(tab, RAD_MEM_DEVICE);
rad_dev_free(blob_dst, RAD_MEM_DEVICE);
rad_dev_free(blob_src, RAD_MEM_HOST_PINNED);
rad_stream_destroy(s);
}
RAD_TEST_MAIN()
+125
View File
@@ -1855,4 +1855,129 @@ TEST(admission_resolves_grammar_triggers_and_refuses_a_regular_expression) {
CHECK_EQ(ch.s.check_request(sp, &why), RAD_E_UNSUPPORTED);
}
/* A THINKING BUDGET CLOSES THE REASONING BLOCK WHERE THE BODY REACHES IT, and it is walked over the
* speculative window as a grammar is: position k counts the committed reply and drafts 0..k-1, so
* a window that crosses the budget is forced from the first position past it, and a draft that
* closes the block itself frees every position behind it. Token 1 wins every row's logits, so a
* row that comes back 5 was forced. */
TEST(a_thinking_budget_forces_the_close_from_the_position_that_spends_it) {
HostChain ch(8, 1, 2);
NEED_CHAIN(ch)
SamplingParams sp = greedy_params();
sp.reasoning.close = 5;
sp.reasoning.starts_open = true;
sp.thinking_budget = 2;
std::vector<float> lg(3 * 8, 0.0f);
for (int r = 0; r < 3; ++r) lg[(size_t)r * 8 + 1] = 5.0f;
std::vector<int32_t> tok;
Request a = make_req(1, { 3 }, sp);
a.output = { 1 };
int32_t da[2] = { 2, 2 };
a.n_draft = 2;
a.draft = da;
CHECK_OK(ch.step({ &a }, lg, &tok));
CHECK_EQ(tok[0], 1); /* one body token: within the budget */
CHECK_EQ(tok[1], 5); /* behind a draft that makes it two */
CHECK_EQ(tok[2], 5);
Request b = make_req(2, { 3 }, sp);
b.output = { 1 };
int32_t db[2] = { 5, 2 };
b.n_draft = 2;
b.draft = db;
CHECK_OK(ch.step({ &b }, lg, &tok));
CHECK_EQ(tok[0], 1);
CHECK_EQ(tok[1], 1); /* the draft closed the block: nothing left to force */
CHECK_EQ(tok[2], 1);
}
/* THE COMMITTED REPLY IS COUNTED ACROSS STEPS, and only from where the block opens: a reply that
* opens its own block counts from its opener, and one that starts any other way has no block to
* budget. Sampled, not greedy, so the mask is what decides and not an argmax that happens to
* agree. */
TEST(a_thinking_budget_counts_the_reply_across_steps_and_only_inside_the_block) {
HostChain ch(8, 2, 0);
NEED_CHAIN(ch)
SamplingParams sp;
sp.temp = 1.0f;
sp.reasoning.open = 4;
sp.reasoning.close = 5;
sp.thinking_budget = 1;
std::vector<float> lg(2 * 8, 0.0f);
lg[1] = 40.0f;
lg[8 + 1] = 40.0f;
std::vector<int32_t> tok;
Request opens = make_req(1, { 3 }, sp);
Request plain = make_req(2, { 3 }, sp);
opens.output = { 4 }; /* the opener: the block starts, nothing in it yet */
plain.output = { 2 }; /* no opener first: there is no block */
CHECK_OK(ch.step({ &opens, &plain }, lg, &tok));
CHECK_EQ(tok[0], 1);
CHECK_EQ(tok[1], 1);
opens.output.push_back(1); /* one body token: the budget is spent */
plain.output.push_back(1);
CHECK_OK(ch.step({ &opens, &plain }, lg, &tok));
CHECK_EQ(tok[0], 5);
CHECK_EQ(tok[1], 1);
opens.output.push_back(5); /* closed: the answer is free again */
CHECK_OK(ch.step({ &opens, &plain }, lg, &tok));
CHECK_EQ(tok[0], 1);
}
/* A GRAMMAR KEEPS THE LAST WORD. The close is forced only where the grammar admits it; where it
* does not, the row is the grammar's, and the budget waits for a position the grammar allows. */
TEST(a_thinking_budget_forces_the_close_only_where_the_grammar_admits_it) {
SimpleVocab v({ "a", "b", "c", "</t>" });
HostChain ch(4, 1, 0, &v);
NEED_CHAIN(ch)
SamplingParams sp = greedy_params();
sp.reasoning.close = 3;
sp.reasoning.starts_open = true;
sp.thinking_budget = 0;
std::vector<float> lg = { 9.0f, 0.0f, 0.0f, 0.0f };
std::vector<int32_t> tok;
sp.grammar = "root ::= (\"a\" | \"</t>\")+";
Request admits = make_req(1, { 1 }, sp);
CHECK_OK(ch.step({ &admits }, lg, &tok));
CHECK_EQ(tok[0], 3);
sp.grammar = "root ::= \"a\"+";
Request forbids = make_req(2, { 1 }, sp);
CHECK_OK(ch.step({ &forbids }, lg, &tok));
CHECK_EQ(tok[0], 0);
}
/* The count a budget is held against and the count usage reports are one definition. */
TEST(reasoning_count_follows_the_parser_s_reading_of_the_block) {
ReasoningSpan s;
s.open = 4;
s.close = 5;
ReasoningCount c;
c.start(s);
for (int32_t t : { 4, 1, 1, 5, 1, 4, 1 }) c.push(s, t);
CHECK_EQ(c.tokens, (int64_t)4); /* the opener, two body tokens, the close */
CHECK_EQ(c.body, (int64_t)2);
CHECK(!c.inside());
s.starts_open = true;
c.start(s);
for (int32_t t : { 1, 1, 1 }) c.push(s, t);
CHECK(c.inside());
CHECK_EQ(c.tokens, (int64_t)3);
s.starts_open = false;
c.start(s);
for (int32_t t : { 1, 4, 1 }) c.push(s, t);
CHECK_EQ(c.tokens, (int64_t)0); /* a block opened mid-reply is not one */
c.start(ReasoningSpan{});
c.push(ReasoningSpan{}, 1);
CHECK_EQ(c.tokens, (int64_t)0);
}
RAD_TEST_MAIN()
+82
View File
@@ -10,6 +10,7 @@
#include "sched/scheduler.h"
#include "sched/derive.h"
#include "server/sink.h"
#include <algorithm>
#include <cstdlib>
@@ -546,6 +547,19 @@ struct Fixture {
return id;
}
/* The same, with the server's sink attached, for what a request tells its client. */
uint64_t submit_to(server::Sink* sink, int n_prompt, int max_tokens) {
auto r = std::make_unique<Request>();
r->id = next_id++;
r->max_tokens = max_tokens;
r->sink = sink;
r->prompt.resize((size_t)n_prompt);
for (int i = 0; i < n_prompt; ++i) r->prompt[(size_t)i] = 1000 + i;
uint64_t id = r->id;
if (sch.add(std::move(r)) < 0) return 0;
return id;
}
/* Commit a step in which every sequence produced one token and none ended. */
void commit_plain(int32_t token = 7) {
const StepPlan& p = sch.plan();
@@ -2039,4 +2053,72 @@ TEST(shutdown_fails_what_is_queued_and_refuses_what_follows) {
CHECK(f.sch.step() == nullptr);
}
/* AND EACH OF THOSE REQUESTS SAYS WHAT STOPPED IT. The sink carries the status and the sentence
* the server puts in the 500: without them a client read "the engine failed this request: ok"
* after a step failed as unsupported. */
TEST(shutdown_fails_each_sink_with_the_status_that_stopped_the_engine) {
server::Sink running, waiting, late;
Fixture f;
f.build(/*blocks=*/20, /*states=*/64);
CHECK_OK(f.start());
CHECK(f.submit_to(&running, 160, 64) != 0);
CHECK(f.sch.step() != nullptr);
CHECK(f.submit_to(&waiting, 160, 64) != 0);
f.sch.shutdown("the engine stopped", RAD_E_UNSUPPORTED);
CHECK(f.submit_to(&late, 8, 8) == 0);
for (server::Sink* s : { &running, &waiting, &late }) {
CHECK(s->done());
CHECK_EQ((int)s->finish_reason(), (int)server::Finish::Error);
CHECK_EQ(s->status(), (int)RAD_E_UNSUPPORTED);
CHECK_EQ(std::string(s->why() ? s->why() : ""), std::string("the engine stopped"));
}
}
/* A REQUEST'S OWN SPECULATION AND ITS ADMISSION REACH ITS SINK, which is what lets a response say
* how many tokens were drafted for it and when its prefill started: the aggregate counters cannot
* be split between requests that overlap. The count is the drafts each verify step proposed for
* this request and the ones it accepted -- the same numbers /metrics sums. */
TEST(a_sink_carries_its_requests_admission_and_draft_counts) {
server::Sink sink;
Fixture f;
f.build(/*blocks=*/4096, /*states=*/64);
f.cfg.n_spec = 4;
CHECK_OK(f.start());
const uint64_t id = f.submit_to(&sink, 40, 60);
CHECK(id != 0);
CHECK(sink.t_admitted_ns() < 0);
int64_t drafted = 0, accepted = 0;
uint32_t rng = 99;
for (int step = 0; step < 40 && !sink.done(); ++step) {
int32_t draft[4] = { 31, 32, 33, 34 };
(void)f.sch.set_draft(id, draft, 4);
const RadBatch* b = f.sch.step();
if (!b) break;
CHECK(sink.t_admitted_ns() >= 0);
const StepPlan& p = f.sch.plan();
Scheduler::StepResult r;
static int32_t acc[64], tok[64];
static uint8_t eos[64];
for (size_t k = 0; k < p.e.size(); ++k) {
rng = rng * 1664525u + 1013904223u;
acc[k] = p.e[k].n_spec > 0 ? (int32_t)((rng >> 16) % (uint32_t)(p.e[k].n_spec + 1)) : 0;
tok[k] = 5;
eos[k] = 0;
if (!p.e[k].is_prefill && p.e[k].n_spec > 0) {
drafted += p.e[k].n_spec;
accepted += acc[k];
}
}
r.n_seq = (int)p.e.size();
r.n_accepted = acc; r.token = tok; r.eos = eos;
CHECK_OK(f.sch.commit(r));
}
CHECK(drafted > 0);
CHECK_EQ(sink.n_drafted(), drafted);
CHECK_EQ(sink.n_draft_accepted(), accepted);
}
RAD_TEST_MAIN()
+773 -7
View File
@@ -29,6 +29,7 @@
#include <atomic>
#include <chrono>
#include <cstring>
#include <functional>
#include <map>
#include <memory>
#include <mutex>
@@ -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]";
@@ -117,6 +124,9 @@ struct FakeChatTemplate : IChatTemplate {
/* The parser is built per render and reads calls only for a request that sent tools --
* the contract the real bridge keeps (IReplyParser). */
if (with_parser) out->parser = std::make_shared<FakeReplyParser>(!tools.empty());
out->think_open = think_open;
out->think_close = think_close;
out->think_starts_open = think_starts_open;
return RAD_OK;
}
bool supports_tools() const override { return tools_ok; }
@@ -125,6 +135,10 @@ struct FakeChatTemplate : IChatTemplate {
bool with_parser = false;
std::string refusal;
std::string refuse_kwarg;
/* The reasoning block a render reports. FakeTokenizer makes a one-byte marker one token. */
std::string think_open, think_close;
bool think_starts_open = false;
/* Reads "TOOL:<name>:<json...>" -- everything after the second colon is the arguments,
* however incomplete, and it arrives a piece at a time. That is exactly the shape the
@@ -218,10 +232,18 @@ struct FakeMultimodal : IMultimodal {
struct FakeScheduler : IScheduler {
std::string reply = "hello";
bool hang = false;
/* Nonzero: after the reply, the request is failed with this status and reason, as the engine
* fails every request it holds when a step fails. */
int fail_status = 0;
const char* fail_why = nullptr;
/* Nonzero: every token after the first is a verify step that proposed this many drafts and
* accepted one, as a speculating engine reports them. */
int32_t drafts = 0;
SchedMetrics m;
std::mutex mu;
std::vector<uint64_t> submitted;
SamplingParams last_sp; /* what the last submitted request was to sample with */
std::vector<uint64_t> cancelled;
std::vector<std::thread> workers;
std::atomic<uint64_t> next_id{1};
@@ -238,19 +260,25 @@ struct FakeScheduler : IScheduler {
{
std::lock_guard<std::mutex> lk(mu);
submitted.push_back(id);
last_sp = r.sp;
}
void* sink = r.sink;
int32_t cap = r.max_tokens;
std::string text = reply;
bool h = hang;
const int fst = fail_status;
const char* fwhy = fail_why;
const int32_t nd = drafts;
/* Under the lock: over a real socket, submits arrive from several HTTP workers at once. */
std::lock_guard<std::mutex> lk(mu);
workers.emplace_back([sink, cap, text, h] {
workers.emplace_back([sink, cap, text, h, fst, fwhy, nd] {
sink_admitted(sink);
sink_prompt_stats(sink, 8, 4);
int32_t n = 0;
for (char c : text) {
if (n >= cap) break;
if (sink_cancelled(sink)) { sink_finish(sink, Finish::Cancelled); return; }
if (n > 0 && nd > 0) sink_drafts(sink, nd, 1);
if (!sink_push(sink, (int32_t)(unsigned char)c)) return;
++n;
if (h && n >= 3) break;
@@ -263,6 +291,7 @@ struct FakeScheduler : IScheduler {
sink_finish(sink, Finish::Length);
return;
}
if (fst) { sink_fail(sink, fst, fwhy); return; }
sink_finish(sink, n >= cap ? Finish::Length : Finish::Stop);
});
return id;
@@ -945,6 +974,360 @@ 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<std::string>({ "x" }));
lim.default_sampling.dry_seq_breakers = { "\n" };
CHECK(chat_with(f, lim, "").sp.dry_seq_breakers == std::vector<std::string>({ "\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);
/* AND `auto` IS THE DEFAULT: limits built with nothing said about max_tokens give a request
* that names none what the context leaves. 512 ended a reasoning model's answers inside its
* reasoning, with a finish_reason "length" a chat client does not show. */
{
OaiLimits d;
d.model_id = lim.model_id;
d.max_ctx = 64;
OaiRequest a = chat_with(f, d, "");
CHECK_EQ((int64_t)a.prompts[0].tokens.size() + a.max_tokens, d.max_ctx);
}
/* 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<std::string, std::string>& 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(j["server"]["default_max_tokens"].is_null()); /* auto */
CHECK(j["server"]["max_tokens_cap"].is_null());
CHECK_EQ(j["server"]["max_stop_strings"].get<int64_t>(), 64);
const json& r = j["request_defaults"];
CHECK_NEAR(r["temperature"].get<double>(), 1.0, 1e-9);
CHECK_NEAR(r["repetition_penalty"].get<double>(), 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>(), 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<int64_t>(), 4096);
const json& r = j["request_defaults"];
CHECK_NEAR(r["presence_penalty"].get<double>(), 1.5, 1e-6);
CHECK_EQ(r["chat_template_kwargs"]["enable_thinking"].get<bool>(), false);
CHECK_EQ(r["chat_template_kwargs"]["tag"].get<std::string>(), 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) {
@@ -1091,6 +1474,43 @@ TEST(streaming_completions_use_the_text_completion_chunk_shape) {
CHECK_EQ(text, std::string("pq"));
}
/* A REQUEST THE ENGINE FAILED SAYS WHAT FAILED, in the 500 and in a stream's error event: the
* reason and the status the engine stopped on. It read "the engine failed this request: ok" when
* a step failed, because nothing carried the status to the request. */
TEST(a_request_the_engine_failed_says_what_failed) {
Fixture f;
f.sched.reply = "he";
f.sched.fail_status = RAD_E_UNSUPPORTED;
f.sched.fail_why = "the engine stopped on an error and is not serving";
const std::string want = "the engine failed this request: the engine stopped on an error and "
"is not serving (unsupported)";
HttpResponse r = f.post("/v1/chat/completions",
R"({"messages":[{"role":"user","content":"hi"}]})");
CHECK_EQ(r.status, 500);
CHECK_EQ(json::parse(r.body)["error"]["message"].get<std::string>(), want);
HttpResponse s = f.post("/v1/completions", R"({"prompt":"hi","stream":true})");
CHECK_EQ(s.status, 200);
int bad = 0, errors = 0;
for (const std::string& p : sse_payloads(drain(s), &bad)) {
if (p == "[DONE]") continue;
json j = json::parse(p);
if (!j.contains("error")) continue;
++errors;
CHECK_EQ(j["error"]["message"].get<std::string>(), want);
}
CHECK_EQ(bad, 0);
CHECK_EQ(errors, 1);
/* With no reason given, the status alone -- and never "ok". */
f.sched.fail_why = nullptr;
HttpResponse t = f.post("/v1/chat/completions",
R"({"messages":[{"role":"user","content":"hi"}]})");
CHECK_EQ(json::parse(t.body)["error"]["message"].get<std::string>(),
std::string("the engine failed this request: unsupported"));
}
TEST(a_streamed_tool_call_is_named_before_its_arguments_flow) {
Fixture f;
f.sched.reply = "TOOL:lookup:{\"q\":\"x\"}";
@@ -1241,6 +1661,254 @@ TEST(n_streamed_choices_share_one_usage_chunk_after_every_final_chunk) {
}
}
/* ================================================================== reasoning */
/* HOW MUCH OF completion_tokens WAS REASONING, on both paths: the reply below opens inside the
* block (the render says so), and `|` -- one token to FakeTokenizer -- closes it after three body
* tokens, so four of the seven tokens are reasoning, the close included. A model whose block
* cannot be counted reports no breakdown rather than a zero. */
TEST(usage_reports_the_reasoning_tokens_inside_completion_tokens) {
{
Fixture f;
f.tmpl.think_close = "|";
f.tmpl.think_starts_open = true;
f.sched.reply = "abc|xyz";
HttpResponse r = f.post("/v1/chat/completions",
R"({"messages":[{"role":"user","content":"hi"}]})");
CHECK_EQ(r.status, 200);
const json j = json::parse(r.body);
CHECK_EQ(j["usage"]["completion_tokens"].get<int>(), 7);
CHECK_EQ(j["usage"]["completion_tokens_details"]["reasoning_tokens"].get<int>(), 4);
HttpResponse st = f.post("/v1/chat/completions",
R"({"messages":[{"role":"user","content":"hi"}],"stream":true,
"stream_options":{"include_usage":true}})");
int bad = 0;
auto p = sse_payloads(drain(st), &bad);
CHECK_EQ(bad, 0);
REQUIRE(p.size() >= 2);
const json u = json::parse(p[p.size() - 2]);
CHECK_EQ(u["usage"]["completion_tokens_details"]["reasoning_tokens"].get<int>(), 4);
}
{
Fixture f;
f.tmpl.think_close = "</t>"; /* four tokens: not a countable block */
f.tmpl.think_starts_open = true;
HttpResponse r = f.post("/v1/chat/completions",
R"({"messages":[{"role":"user","content":"hi"}]})");
CHECK_EQ(r.status, 200);
CHECK(!json::parse(r.body)["usage"].contains("completion_tokens_details"));
}
}
/* THE BUDGET REACHES THE ENGINE in either spelling, with the block it is held on; one the block
* cannot hold, a negative one, and two spellings that disagree are 400s naming the field. */
TEST(a_thinking_budget_reaches_the_engine_or_is_refused_by_name) {
Fixture f;
f.tmpl.think_open = "{";
f.tmpl.think_close = "|";
f.tmpl.think_starts_open = true;
for (const char* k : { "thinking_token_budget", "thinking_budget" }) {
HttpResponse r = f.post("/v1/chat/completions",
std::string(R"({"messages":[{"role":"user","content":"hi"}],")") +
k + R"(":7})");
CHECK_EQ(r.status, 200);
f.sched.join_all();
std::lock_guard<std::mutex> lk(f.sched.mu);
CHECK_EQ(f.sched.last_sp.thinking_budget, 7);
CHECK_EQ(f.sched.last_sp.reasoning.close, (int32_t)'|');
CHECK_EQ(f.sched.last_sp.reasoning.open, (int32_t)'{');
CHECK(f.sched.last_sp.reasoning.starts_open);
}
struct Case { const char* extra; const char* param; };
for (const Case& c : { Case{ R"("thinking_token_budget":-1)", "thinking_token_budget" },
Case{ R"("thinking_token_budget":3,"thinking_budget":4)",
"thinking_budget" },
Case{ R"("thinking_budget":"3")", "thinking_budget" } }) {
HttpResponse r = f.post("/v1/chat/completions",
std::string(R"({"messages":[{"role":"user","content":"hi"}],)") +
c.extra + "}");
CHECK_EQ(r.status, 400);
CHECK_EQ(json::parse(r.body)["error"]["param"].get<std::string>(), std::string(c.param));
}
Fixture multi;
multi.tmpl.think_close = "</t>";
multi.tmpl.think_starts_open = true;
HttpResponse r = multi.post("/v1/chat/completions",
R"({"messages":[{"role":"user","content":"hi"}],
"thinking_token_budget":5})");
CHECK_EQ(r.status, 400);
CHECK(json::parse(r.body)["error"]["message"].get<std::string>().find("4 tokens") !=
std::string::npos);
Fixture none;
HttpResponse n = none.post("/v1/chat/completions",
R"({"messages":[{"role":"user","content":"hi"}],
"thinking_token_budget":5})");
CHECK_EQ(n.status, 400);
CHECK(json::parse(n.body)["error"]["message"].get<std::string>().find("no reasoning block") !=
std::string::npos);
}
/* THE DEPLOYMENT'S BUDGET applies to a request that names none, loses to one that does, and is
* not applied where the block cannot be counted -- it could not be held there. The startup check
* says why a model cannot take it at all. */
TEST(the_deployment_s_thinking_budget_is_a_default_a_request_can_override) {
Fixture f;
f.tmpl.think_close = "|";
f.tmpl.think_starts_open = true;
OaiLimits lim = f.limits();
lim.default_thinking_budget = 64;
CHECK_EQ(chat_with(f, lim, "").sp.thinking_budget, 64);
CHECK_EQ(chat_with(f, lim, R"("thinking_token_budget":3)").sp.thinking_budget, 3);
CHECK_EQ(chat_with(f, f.limits(), "").sp.thinking_budget, -1);
f.tmpl.think_close.clear();
CHECK_EQ(chat_with(f, lim, "").sp.thinking_budget, -1);
Fixture g;
ServerOptions o;
o.model_id = "test-model";
o.default_max_tokens = 32;
o.default_thinking_budget = 64;
Deps d;
d.sched = &g.sched;
d.tok = &g.tok;
d.chat = &g.tmpl;
d.grammar = &g.gram;
Server s(d, o);
CHECK(s.check_thinking_budget().find("no reasoning block") != std::string::npos);
g.tmpl.think_close = "|";
g.tmpl.think_starts_open = true;
CHECK(s.check_thinking_budget().empty());
}
/* ================================================================== timings */
/* WHERE THE REQUEST'S TIME WENT, in llama.cpp's shape, on every path a client can take: the
* buffered body, each streamed choice's final chunk whether or not a usage chunk was asked for,
* and the usage chunk when it was. The fake places 8 prompt tokens with 4 from the cache, and
* every token after the first is a verify step that proposed 3 drafts and took 1. */
TEST(a_response_carries_its_requests_timings_and_draft_counts) {
auto check = [](const json& t, int64_t predicted, bool drafts) {
CHECK_EQ(t["prompt_n"].get<int64_t>(), (int64_t)4);
CHECK_EQ(t["cache_n"].get<int64_t>(), (int64_t)4);
CHECK_EQ(t["predicted_n"].get<int64_t>(), predicted);
CHECK(t["prompt_ms"].is_number());
CHECK(t["predicted_ms"].is_number());
CHECK(t["prompt_ms"].get<double>() >= 0.0);
for (const char* k : { "prompt_per_token_ms", "prompt_per_second",
"predicted_per_token_ms", "predicted_per_second" })
CHECK(t[k].is_number() || t[k].is_null());
CHECK_EQ(t.contains("draft_n"), drafts);
if (drafts) {
CHECK_EQ(t["draft_n"].get<int64_t>(), (predicted - 1) * 3);
CHECK_EQ(t["draft_n_accepted"].get<int64_t>(), predicted - 1);
}
};
{
Fixture f;
f.sched.drafts = 3;
HttpResponse r = f.post("/v1/chat/completions",
R"({"messages":[{"role":"user","content":"hi"}]})");
CHECK_EQ(r.status, 200);
const json j = json::parse(r.body);
REQUIRE(j.contains("timings"));
check(j["timings"], 5, true);
CHECK_EQ(j["timings"]["predicted_n"].get<int64_t>(),
j["usage"]["completion_tokens"].get<int64_t>());
}
{
Fixture f;
HttpResponse r = f.post("/v1/completions", R"({"prompt":"hi","max_tokens":8})");
CHECK_EQ(r.status, 200);
const json j = json::parse(r.body);
REQUIRE(j.contains("timings"));
check(j["timings"], 5, false);
}
const char* paths[] = { "/v1/chat/completions", "/v1/completions" };
const char* bodies[] = { R"({"messages":[{"role":"user","content":"hi"}],"stream":true)",
R"({"prompt":"hi","stream":true)" };
for (int k = 0; k < 2; ++k)
for (bool usage : { false, true }) {
Fixture f;
f.sched.drafts = 3;
HttpResponse r = f.post(paths[k], std::string(bodies[k]) +
(usage ? R"(,"stream_options":{"include_usage":true}})"
: "}"));
CHECK_EQ(r.status, 200);
int bad = 0;
auto p = sse_payloads(drain(r), &bad);
CHECK_EQ(bad, 0);
int finals = 0, with_timings = 0;
for (size_t i = 0; i + 1 < p.size(); ++i) {
const json j = json::parse(p[i]);
if (j.contains("usage")) {
REQUIRE(j.contains("timings"));
check(j["timings"], 5, true);
++with_timings;
continue;
}
if (j["choices"][0]["finish_reason"].is_null()) {
CHECK(!j.contains("timings"));
continue;
}
++finals;
REQUIRE(j.contains("timings"));
check(j["timings"], 5, true);
++with_timings;
}
CHECK_EQ(finals, 1);
CHECK_EQ(with_timings, usage ? 2 : 1);
}
}
/* The rates are the tokens over the time that produced them, the first token being the prompt
* phase's; a rate whose count or time is zero is null, and so is a prompt time the engine never
* reported. */
TEST(timings_rates_divide_the_tokens_by_the_time_that_produced_them) {
TimingsOut t;
t.valid = true;
t.prompt_n = 100;
t.prompt_ms = 50.0;
t.predicted_n = 10;
t.decode_n = 9;
t.predicted_ms = 90.0;
json j = timings_json(t);
CHECK_NEAR(j["prompt_per_second"].get<double>(), 2000.0, 1e-9);
CHECK_NEAR(j["prompt_per_token_ms"].get<double>(), 0.5, 1e-12);
CHECK_NEAR(j["predicted_per_second"].get<double>(), 100.0, 1e-9);
CHECK_NEAR(j["predicted_per_token_ms"].get<double>(), 10.0, 1e-12);
CHECK(!j.contains("draft_n"));
t.decode_n = 0;
t.predicted_ms = 0.0;
t.prompt_ms = -1.0;
j = timings_json(t);
CHECK(j["predicted_per_second"].is_null());
CHECK(j["predicted_per_token_ms"].is_null());
CHECK(j["prompt_ms"].is_null());
CHECK(j["prompt_per_second"].is_null());
}
/* The sink keeps the first admission across a preemption and sums the drafts it is told of. */
TEST(a_sink_keeps_its_first_admission_and_sums_its_drafts) {
Sink s;
CHECK(s.t_admitted_ns() < 0);
s.mark_admitted();
const int64_t a = s.t_admitted_ns();
CHECK(a >= 0);
std::this_thread::sleep_for(std::chrono::milliseconds(2));
s.mark_admitted();
CHECK_EQ(s.t_admitted_ns(), a);
s.add_drafts(4, 2);
s.add_drafts(3, 3);
CHECK_EQ(s.n_drafted(), (int64_t)7);
CHECK_EQ(s.n_draft_accepted(), (int64_t)5);
}
/* ================================================================== cancellation */
TEST(a_dropped_stream_cancels_at_the_scheduler) {
@@ -1751,14 +2419,28 @@ TEST(tokenize_takes_a_prompt_or_messages_and_never_both) {
CHECK_EQ(f.post("/tokenize", "[1,2]").status, 400);
}
TEST(tokenize_never_lets_the_caller_choose_parse_special) {
TEST(a_raw_prompt_parses_control_tokens_on_every_endpoint_that_takes_one) {
/* A client that renders its own chat template sends "<|im_start|>" meaning the token, as vLLM
* and llama.cpp read it. /tokenize must count what /v1/completions will see. */
Fixture f;
/* A control token in `prompt` is raw text, or an /v1/completions built from these ids reaches
* the system role. The chat form is the opposite and must parse them. */
f.tok.last_parse_special = false;
CHECK_EQ(f.post("/v1/completions", R"({"prompt":"<|im_start|>user","max_tokens":4})").status, 200);
CHECK(f.tok.last_parse_special);
f.tok.last_parse_special = false;
CHECK_EQ(f.post("/v1/completions", R"({"prompt":["a","b"],"max_tokens":4})").status, 200);
CHECK(f.tok.last_parse_special);
f.tok.last_parse_special = false;
f.post("/tokenize", R"({"prompt":"<|im_start|>"})");
CHECK(!f.tok.last_parse_special);
CHECK(f.tok.last_parse_special);
f.tok.last_parse_special = false;
f.post("/tokenize", R"({"messages":[{"role":"user","content":"hi"}]})");
CHECK(f.tok.last_parse_special);
for (const char* body : {R"({"input":"<|im_start|>"})", R"({"input":["a","b"]})"}) {
OaiRequest r; ApiError e;
f.tok.last_parse_special = false;
CHECK_OK(parse_embeddings_request(body, f.odeps(), f.limits(), &r, &e));
CHECK(f.tok.last_parse_special);
}
}
TEST(detokenize_answers_under_the_key_vllm_uses) {
@@ -1852,7 +2534,8 @@ struct LiveServer {
std::vector<int> 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<void(ServerOptions&)>& tweak = nullptr) {
sched.reply = "abcdefgh";
sched.hang = true;
Deps d;
@@ -1864,6 +2547,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 +2596,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<Server>(d, o);
std::atomic<bool> never{false};
std::vector<HttpResponse> 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()
+33 -16
View File
@@ -7,8 +7,8 @@
* - throughput on prose-and-code text, against an absolute floor and against the reference
* encoder (tools/tokref) on the same text -- the ratio holds on a loaded machine where an
* absolute number would not;
* - LINEAR SCALING: twice the text takes about twice the time, on ordinary text and on the
* inputs a pre-tokeniser is quadratic on when it goes wrong (one enormous word, one
* - LINEAR SCALING: four times the text takes about four times the time, on ordinary text and
* on the inputs a pre-tokeniser is quadratic on when it goes wrong (one enormous word, one
* enormous run of whitespace, digits, alternating classes);
* - the segment cache: the last turn of a long conversation costs a fraction of encoding it.
*
@@ -82,6 +82,18 @@ double encode_seconds(const Tokenizer& t, const std::string& text, int runs = 5)
return best_of(runs, [&] { ids.clear(); t.encode(text, ids, false, true); });
}
/* TWO TEXTS TIMED IN TURNS, best of five each, so a burst of load from whatever else the machine
* runs lands on both: timed one after the other, a parallel ctest beside a server read a linear
* input as x3.6 for twice the text, past the bound a quadratic one is held to. */
void encode_both(const Tokenizer& t, const std::string& small, const std::string& big,
double* ts, double* tb) {
*ts = *tb = 1e30;
for (int i = 0; i < 5; ++i) {
*ts = std::min(*ts, encode_seconds(t, small, 1));
*tb = std::min(*tb, encode_seconds(t, big, 1));
}
}
} /* namespace */
TEST(throughput_has_a_floor_and_beats_the_reference) {
@@ -100,20 +112,23 @@ TEST(throughput_has_a_floor_and_beats_the_reference) {
CHECK(r / s > 4.0);
}
/* TWICE THE TEXT, ABOUT TWICE THE TIME. The texts differ, so a cache that remembered one would
* not help the other; the ratio is allowed well past 2 because the larger one also walks more of
* memory. */
/* FOUR TIMES THE TEXT, ABOUT FOUR TIMES THE TIME. The texts differ, so a cache that remembered one
* would not help the other; the ratio is allowed well past 4 because the larger one also walks
* more of memory. A quarter and a whole megabyte: the cost of a byte steps up by about half
* between one and two megabytes on the machine these were measured on, where the working set
* leaves the core's cache, and a step across that reads as growth the encoder does not have. */
TEST(encoding_time_is_linear_in_the_text) {
auto v = vocab();
REQUIRE(v != nullptr);
Tokenizer t;
t.init(v);
t.set_segment_cache(false);
const std::string one = document(3, 1 << 20), two = document(4, 2 << 20);
const double a = encode_seconds(t, one), b = encode_seconds(t, two);
std::fprintf(stderr, " 1 MB %.2f ms, 2 MB %.2f ms, ratio %.2f\n", a * 1e3, b * 1e3, b / a);
CHECK(b / a > 1.3);
CHECK(b / a < 2.8);
const std::string one = document(3, 256 << 10), four = document(4, 1 << 20);
double a, b;
encode_both(t, one, four, &a, &b);
std::fprintf(stderr, " 256 KB %.2f ms, 1 MB %.2f ms, ratio %.2f\n", a * 1e3, b * 1e3, b / a);
CHECK(b / a > 2.6);
CHECK(b / a < 6.0);
}
/* THE INPUTS A SPLITTER GOES QUADRATIC ON. A backtracking `\s+(?!\S)` rescans a whitespace run
@@ -133,14 +148,16 @@ TEST(pathological_inputs_stay_linear) {
{ "alternating", [](size_t n) { std::string s; while (s.size() < n) s += "a1!"; return s; } },
{ "apostrophes", [](size_t n) { std::string s; while (s.size() < n) s += "''s"; return s; } },
};
/* A megabyte and two, best of five: at a few hundred kilobytes one of these runs in a couple of
* milliseconds, which one preemption under a parallel ctest turns into a false quadratic. */
/* 125 and 500 KB: linear is 4, quadratic 16, and the bound of 8 sits a factor of two from
* each. Both stay below the size where a byte's cost steps up (see above); a run of whitespace
* costs a little more a byte as it grows, about x4.8 here, and that is not what this holds. */
for (const auto& in : inputs) {
const std::string one = in.make(1000000), two = in.make(2000000);
const double a = encode_seconds(t, one, 5), b = encode_seconds(t, two, 5);
std::fprintf(stderr, " %-17s 1 MB %7.2f ms, 2 MB %7.2f ms, ratio %.2f\n", in.name,
const std::string one = in.make(125000), four = in.make(500000);
double a, b;
encode_both(t, one, four, &a, &b);
std::fprintf(stderr, " %-17s 125 KB %7.2f ms, 500 KB %7.2f ms, ratio %.2f\n", in.name,
a * 1e3, b * 1e3, b / a);
CHECK(b / a < 3.0);
CHECK(b / a < 8.0);
}
}
+26
View File
@@ -515,6 +515,32 @@ TEST(the_encoder_matches_the_reference_on_trained_vocabularies) {
}
}
/* A TEXT THAT OPENS WITH BOS GETS NO SECOND ONE. A client rendering its own chat template writes
* the BOS into the prompt; one the text spells anywhere else, or a second one at the start, is
* the client's and stays. */
TEST(a_text_that_opens_with_bos_gets_no_second_one) {
VocabBuild vb;
REQUIRE(parse_tokenizer_json_buf(k_tiny, "test.json", vb) >= 0);
vb.bos = 12;
vb.add_bos = true;
auto v = load(std::move(vb));
REQUIRE(v != nullptr);
Tokenizer t;
CHECK_OK(t.init(v));
auto enc = [&](const char* s, bool add_special, bool parse_special) {
std::vector<int32_t> ids;
t.encode(s, ids, add_special, parse_special);
return ids;
};
CHECK(enc("ab", true, true) == (std::vector<int32_t>{ 12, 4 }));
CHECK(enc("<|end|>ab", true, true) == (std::vector<int32_t>{ 12, 4 }));
CHECK(enc("<|end|><|end|>ab", true, true) == (std::vector<int32_t>{ 12, 12, 4 }));
CHECK(enc("ab<|end|>", true, true) == (std::vector<int32_t>{ 12, 4, 12 }));
CHECK(enc("<|end|>ab", false, true) == (std::vector<int32_t>{ 12, 4 }));
/* Not parsed, the spelling is not the token, so the BOS is still owed. */
CHECK(enc("<|end|>x", true, false) == (std::vector<int32_t>{ 12, 11 }));
}
/* SPECIAL TOKENS ARE CLAIMED LONGEST FIRST, not leftmost: "bcde" wins over "ab" in "abcde" even
* though "ab" starts earlier, and "<|im_start|>" is never cut by its prefix "<|im". */
TEST(special_tokens_are_claimed_by_priority) {
+54 -6
View File
@@ -14,7 +14,10 @@
#include "rad_internal.h"
#include <atomic>
#include <string>
#include <thread>
#include <vector>
using namespace rad;
@@ -162,8 +165,8 @@ TEST(the_param_view_is_rebuilt_after_a_mutation) {
CHECK_EQ(g.n_params(), 1);
CHECK_EQ(g.params()[0].ival, 8ll);
/* The view is cached, so the question is whether the cache is invalidated. A stale view hands
* a kernel the geometry it was resolved against rather than the one it is being run on. */
/* The view is built by the writes, so the question is whether every write rebuilds it. A stale
* view hands a kernel the geometry it was resolved against rather than the one it is run on. */
g.set_i("M", 9);
CHECK_EQ(g.params()[0].ival, 9ll);
g.set_i("N", 4096);
@@ -186,15 +189,15 @@ TEST(the_param_view_is_rebuilt_after_a_mutation) {
CHECK_EQ(seen, 1);
}
/* THE COPY MUST OWN ITS OWN STRINGS, and the header says why at length: the cached view holds
* char* into the object's own storage, so a copy that took the view along with the storage would
/* THE COPY MUST OWN ITS OWN STRINGS, and the header says why at length: the view holds char*
* into the object's own storage, so a copy that took the view along with the storage would
* hand a kernel pointers into the source -- which dies first about as often as not, since every
* Resolved holds a Geometry and every Band holds two. */
TEST(a_copied_geometry_points_into_itself_and_not_at_the_source) {
Geometry a;
a.set_s("dtype", "w4a8");
a.set_i("M", 64);
const char* a_key = a.params()[0].key; /* force the source to build its view */
const char* a_key = a.params()[0].key;
Geometry b = a;
CHECK_EQ(b.n_params(), 2);
@@ -202,6 +205,7 @@ TEST(a_copied_geometry_points_into_itself_and_not_at_the_source) {
CHECK(b.params()[0].key != a_key); /* a different object's storage */
CHECK(b.params()[0].sval != a.params()[0].sval);
CHECK_EQ(std::string(b.params()[0].sval), std::string("w4a8"));
CHECK(b.params()[0].sval == b.get_s("dtype")); /* and into the copy's own string */
/* And the two are independent afterwards, in both directions. */
a.set_i("M", 1);
@@ -225,11 +229,12 @@ TEST(a_moved_geometry_does_not_leave_the_view_pointing_at_a_stolen_buffer) {
Geometry a;
a.set_s("dtype", "fp8");
a.set_i("K", 5120);
(void)a.params(); /* build the view, then move out from under it */
Geometry b = std::move(a);
CHECK_EQ(b.n_params(), 2);
CHECK_EQ(std::string(b.params()[0].sval), std::string("fp8"));
CHECK(b.params()[0].sval == b.get_s("dtype")); /* the view went with the strings it names */
CHECK_EQ(std::string(b.params()[0].key), std::string("dtype"));
/* The moved-from object is empty rather than holding a view of a buffer it no longer owns. */
CHECK_EQ(a.n_params(), 0);
@@ -241,6 +246,49 @@ TEST(a_moved_geometry_does_not_leave_the_view_pointing_at_a_stolen_buffer) {
CHECK_EQ(b.n_params(), 0);
}
/* READING A GEOMETRY WRITES NOTHING, so one that nobody is writing can be read from any number of
* threads. The sizing declares of one rank run side by side and every one of them reads the real
* program's op geometries (Engine::probe_arena_levels); a view built lazily on first read was a
* write each of them made, and two threads clearing and filling one vector corrupted the heap at
* startup. Each round reads a fresh geometry -- a moved one, as every OpInfo's is -- from eight
* threads released together, and every reader must see the whole view and the same one. */
TEST(a_geometry_read_from_many_threads_at_once_is_not_written) {
constexpr int kThreads = 8, kRounds = 400;
int bad = 0;
for (int round = 0; round < kRounds && bad == 0; ++round) {
Geometry src;
src.set_s("dtype", "fp8_e4m3_with_a_name_past_the_short_string_buffer");
for (int k = 0; k < 12; ++k) src.set_i(fmt("key_%d", k), k * 1000 + round);
const Geometry g = std::move(src);
std::atomic<int> ready{0};
std::atomic<bool> go{false};
std::vector<const RadParam*> seen(kThreads, nullptr);
std::vector<int> ok(kThreads, 0);
std::vector<std::thread> th;
for (int t = 0; t < kThreads; ++t)
th.emplace_back([&, t] {
ready.fetch_add(1);
while (!go.load()) {}
const RadParam* p = g.params();
const int n = g.n_params();
bool good = n == 13 && std::string(p[0].key) == "dtype" && p[0].sval &&
std::string(p[0].sval).rfind("fp8_e4m3", 0) == 0;
for (int k = 0; good && k < 12; ++k)
good = p[k + 1].kind == RAD_P_INT && p[k + 1].ival == k * 1000 + round &&
std::string(p[k + 1].key) == fmt("key_%d", k);
seen[t] = p;
ok[t] = good;
});
while (ready.load() < kThreads) {}
go.store(true);
for (auto& x : th) x.join();
for (int t = 0; t < kThreads; ++t)
if (!ok[t] || seen[t] != seen[0]) ++bad;
}
CHECK_EQ(bad, 0);
}
TEST(geometry_str_prints_every_kind_in_declaration_order) {
Geometry g;
g.set_i("M", 64);
+2 -1
View File
@@ -566,7 +566,8 @@ int main(int argc, char** argv) {
for (size_t k = 0; k < widths.size(); ++k) {
Program trial;
ctx.kv_dtype = widths[k];
if (rad_tools_declare(plugins, meta.m, ctx, &trial, {}, nullptr, provide) < 0) {
if (rad_tools_declare(plugins, meta.m, ctx, &trial, {}, nullptr, provide,
/*instances=*/false) < 0) {
if (planning_errors())
RAD_ERR("the weights above could not be planned, and declare saw each of them as "
"the plain dtype it was declared at -- fix those first");
+1 -1
View File
@@ -39,7 +39,7 @@ void usage() {
" --hf-dir DIR compare against HuggingFace ids in DIR/<corpus basename>.ids\n"
" (little-endian int32, encode(text, add_special_tokens=False))\n"
" --no-ref skip the reference encoder, which is slow\n"
" --user encode with parse_special off, as the server does for user content\n"
" --user encode with parse_special off: a control token's spelling is text\n"
" --turns N turns in the multi-turn measurement (default 40, 0 skips it)\n"
" --repeat N timing repeats, best taken (default 3)\n"
" --context N ids shown either side of a difference (default 6)\n"
+31 -3
View File
@@ -98,6 +98,8 @@ vendor/llama/common/regex-partial.{h,cpp} <- llama.cpp common/*
patches/0009-chat-a-cdata-section-is-punctuation-not-content.patch
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
@@ -429,6 +431,32 @@ PATCH SERIES
`string="true|false"` format), which give every argument an arm of its own and so never see
the object, give an optional one of that kind no arm; a model that writes it reaches the
undeclared-argument arm of 0010 where the format has one. core/text/chatfmt.cpp, the
declared-format grammar, does the same outside this tree. Where a value is required (a required property, the root, an array's items, a union
with no alternative left) it is still refused, by name. Every other `not` is refused as 0004
refuses it.
declared-format grammar, does the same outside this tree. Where a value is required (a
required property, the root, an array's items, a union with no alternative left) it is still
refused, by name. Every other `not` is refused as 0004 refuses it.
patches/0013-json-schema-a-count-past-int-is-no-bound.patch
minLength, maxLength, minItems and maxItems were read with get<int>(), which casts: a bound
past INT_MAX wrapped, and Number.MAX_SAFE_INTEGER -- a common way for a schema generator to
write "no limit" -- came out as -1 and the grammar failed to parse, failing the request with
it. A count at or past INT_MAX is now INT_MAX, which build_repetition already reads as no
maximum. That is exact for anything served here: no context holds a string or an array that
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.
+88 -10
View File
@@ -900,15 +900,94 @@ 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
// RADIANCE: a count -- minLength, maxLength, minItems, maxItems -- as the int build_repetition
// takes, or `dflt` where the schema has none. get<int>() 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
// not parse. A count at or past INT_MAX is INT_MAX, which build_repetition reads as no maximum;
// no context the engine serves holds a string or an array that long, so the bound changes
// nothing a generation can write. A count that is not a non-negative number is refused.
int _schema_count(const json & schema, const char * key, int dflt, const std::string & name) {
if (!schema.contains(key)) {
return dflt;
}
const json & v = schema[key];
const double d = v.is_number() ? v.get<double>() : -1.0;
if (!(d >= 0)) {
_errors.push_back(std::string(key) + " of \"" + (name.empty() ? std::string("root") : name) +
"\" must be a non-negative number");
return dflt;
}
return d >= (double) std::numeric_limits<int>::max() ? std::numeric_limits<int>::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<bool>();
if (!s.is_object()) return false;
static const std::unordered_set<std::string> 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<std::string> & out) {
if (t.is_string()) {
out.insert(t.get<std::string>());
return true;
}
if (!t.is_array()) return false;
for (const auto & e : t) {
if (!e.is_string()) return false;
out.insert(e.get<std::string>());
}
return true;
};
auto covers = [](const std::unordered_set<std::string> & 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<std::string> 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<bool>();
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<bool>());
return is_universal(schema["not"]);
}
static std::string _generate_constant_rule(const json & value) {
@@ -1059,9 +1138,8 @@ public:
return _add_rule(rule_name, rule);
}
std::string item_rule_name = visit(items, name + (name.empty() ? "" : "-") + "item");
int min_items = schema.contains("minItems") ? schema["minItems"].get<int>() : 0;
json max_items_json = schema.contains("maxItems") ? schema["maxItems"] : json();
int max_items = max_items_json.is_number_integer() ? max_items_json.get<int>() : std::numeric_limits<int>::max();
int min_items = _schema_count(schema, "minItems", 0, name);
int max_items = _schema_count(schema, "maxItems", std::numeric_limits<int>::max(), name);
return _add_rule(rule_name, "\"[\" space " + build_repetition(item_rule_name, min_items, max_items, "\",\" space") + " \"]\" space");
}
@@ -1077,8 +1155,8 @@ public:
}
if (schema_type == "string" && (schema.contains("minLength") || schema.contains("maxLength"))) {
std::string char_rule = _add_primitive("char", PRIMITIVE_RULES.at("char"));
int min_len = schema.contains("minLength") ? schema["minLength"].get<int>() : 0;
int max_len = schema.contains("maxLength") ? schema["maxLength"].get<int>() : std::numeric_limits<int>::max();
int min_len = _schema_count(schema, "minLength", 0, name);
int max_len = _schema_count(schema, "maxLength", std::numeric_limits<int>::max(), name);
return _add_rule(rule_name, "\"\\\"\" " + build_repetition(char_rule, min_len, max_len) + " \"\\\"\" space");
}
if (schema_type == "integer" && (schema.contains("minimum") || schema.contains("exclusiveMinimum") || schema.contains("maximum") || schema.contains("exclusiveMaximum"))) {
+2 -1
View File
@@ -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;
};
@@ -0,0 +1,54 @@
diff --git a/common/json-schema-to-grammar.cpp b/common/json-schema-to-grammar.cpp
index 95640fb..0bf2b72 100644
--- a/common/json-schema-to-grammar.cpp
+++ b/common/json-schema-to-grammar.cpp
@@ -904,6 +904,26 @@ public:
// 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<int>() 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
+ // not parse. A count at or past INT_MAX is INT_MAX, which build_repetition reads as no maximum;
+ // no context the engine serves holds a string or an array that long, so the bound changes
+ // nothing a generation can write. A count that is not a non-negative number is refused.
+ int _schema_count(const json & schema, const char * key, int dflt, const std::string & name) {
+ if (!schema.contains(key)) {
+ return dflt;
+ }
+ const json & v = schema[key];
+ const double d = v.is_number() ? v.get<double>() : -1.0;
+ if (!(d >= 0)) {
+ _errors.push_back(std::string(key) + " of \"" + (name.empty() ? std::string("root") : name) +
+ "\" must be a non-negative number");
+ return dflt;
+ }
+ return d >= (double) std::numeric_limits<int>::max() ? std::numeric_limits<int>::max() : (int) d;
+ }
+
static bool is_unsatisfiable(const json & schema) {
if (schema.is_boolean()) return !schema.get<bool>();
if (!schema.is_object() || !schema.contains("not")) return false;
@@ -1059,9 +1079,8 @@ public:
return _add_rule(rule_name, rule);
}
std::string item_rule_name = visit(items, name + (name.empty() ? "" : "-") + "item");
- int min_items = schema.contains("minItems") ? schema["minItems"].get<int>() : 0;
- json max_items_json = schema.contains("maxItems") ? schema["maxItems"] : json();
- int max_items = max_items_json.is_number_integer() ? max_items_json.get<int>() : std::numeric_limits<int>::max();
+ int min_items = _schema_count(schema, "minItems", 0, name);
+ int max_items = _schema_count(schema, "maxItems", std::numeric_limits<int>::max(), name);
return _add_rule(rule_name, "\"[\" space " + build_repetition(item_rule_name, min_items, max_items, "\",\" space") + " \"]\" space");
}
@@ -1077,8 +1096,8 @@ public:
}
if (schema_type == "string" && (schema.contains("minLength") || schema.contains("maxLength"))) {
std::string char_rule = _add_primitive("char", PRIMITIVE_RULES.at("char"));
- int min_len = schema.contains("minLength") ? schema["minLength"].get<int>() : 0;
- int max_len = schema.contains("maxLength") ? schema["maxLength"].get<int>() : std::numeric_limits<int>::max();
+ int min_len = _schema_count(schema, "minLength", 0, name);
+ int max_len = _schema_count(schema, "maxLength", std::numeric_limits<int>::max(), name);
return _add_rule(rule_name, "\"\\\"\" " + build_repetition(char_rule, min_len, max_len) + " \"\\\"\" space");
}
if (schema_type == "integer" && (schema.contains("minimum") || schema.contains("exclusiveMinimum") || schema.contains("maximum") || schema.contains("exclusiveMaximum"))) {
@@ -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<int>() 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<int>::max() ? std::numeric_limits<int>::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<bool>();
+ if (!s.is_object()) return false;
+ static const std::unordered_set<std::string> 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<std::string> & out) {
+ if (t.is_string()) {
+ out.insert(t.get<std::string>());
+ return true;
+ }
+ if (!t.is_array()) return false;
+ for (const auto & e : t) {
+ if (!e.is_string()) return false;
+ out.insert(e.get<std::string>());
+ }
+ return true;
+ };
+ auto covers = [](const std::unordered_set<std::string> & 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<std::string> 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<bool>();
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<bool>());
+ 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;
};