radiance 1.7.0

- every model serves without a GPU: libavx covers every op, so `--kernels libavx` alone serves
  every shipped container
- Qwen3-ASR (zivius): speech to text on /v1/audio/transcriptions and live over /v1/realtime
- /v1/messages works with Claude Code as it ships (gearwave00001)
- a long agent conversation keeps its cached history when the client rewrites its last turn
  (manueloverride)
- a stream's first event goes out with the first token, so llama-benchy measures prefill right
- opt-in --prefill-interleave (Smellyyyy, baKon) and --prefill-span (keptn42)
- four-rank TP releases the link early; four-rank selftests and docs/TP4.md (goodman-b)
- NVFP4 and FP8 compressed-tensors imports (devmilan); tools/rad-export for finetunes and LoRA
  adapters (baKon)
- many fixes, among them lost tokens on stop strings under concurrency, keep-alive, MiniCPM5 tool
  arguments and the CPU's vision and audio encoders
- plugin ABI 17 and changed op schemas: out-of-tree plugins must be rebuilt
This commit is contained in:
Deadcode committed 2026-10-16 18:25:18 +02:00
1 parent b068190326
commit 1e968f6e1d
739 files changed
+128447 -84632

No files matched your search

+218 -244
View File
@@ -1,15 +1,12 @@
/* core/server/iface.h -- everything the server needs from components it does not own.
*
* The server is written against pure-virtual interfaces rather than against core/sched and
* core/text directly, for two reasons worth stating. The first is that the HTTP layer then carries
* no header dependency on those components and can be compiled without them. The second is that a
* test can drive every endpoint against a fake scheduler in-process, which is the only way to
* check cancellation and the streaming wire format without binding a port and loading a model.
* The server is written against pure-virtual interfaces rather than core/sched and core/text, so
* the HTTP layer has no header dependency on them, and tests can drive every endpoint against a
* fake scheduler in-process (cancellation and the streaming wire format, with no port or model).
*
* The cost is one virtual call per operation. That is paid on the admission path and on the HTTP
* thread, never inside rad_arch_step and never per token on the step path, so it is free where it
* would matter. The concrete types (rad::Scheduler, rad::Tokenizer, ...) are bound to these by
* the adapters in adapters.h: one line each at the wiring site.
* The cost is one virtual call per operation, on the admission path and the HTTP thread, never
* inside rad_arch_step or per token on the step path. adapters.h binds the concrete types
* (rad::Scheduler, rad::Tokenizer, ...) to these.
*/
#pragma once
#include "rad_core.h"
@@ -27,141 +24,118 @@ namespace gen { struct Request; }
namespace mm { struct Frame; struct Item; }
namespace server {
/* ordered_json, not json, and the reason is not cosmetic: a tool's parameter schema is rendered
* into the prompt in the order the caller wrote it, and property order in a JSON schema changes
* what the model emits. An unordered map would silently re-sort every caller's tool definitions. */
/* ordered_json, not json: a tool's parameter schema is rendered into the prompt in the caller's
* order, and property order in a schema changes what the model emits. */
using json = nlohmann::ordered_json;
/* ================================================================== the scheduler
*
* ASSUMED of core/sched. `submit` takes the request by value and returns the id it assigned;
* `cancel` is idempotent and must free the request's KV blocks immediately rather than at the
* next completion (spec §14), because an agent client abandoning a long generation is the normal
* case, not an edge case.
* Contract with core/sched: `submit` takes the request by value and returns its assigned id;
* `cancel` is idempotent and frees the request's KV blocks immediately, not at the next
* completion (spec §14), since abandoned generations are routine for agent clients.
*/
struct SchedMetrics {
int64_t waiting = 0;
int64_t running = 0;
int64_t preempted = 0;
double kv_util = 0.0; /* 0..1 of the paged KV pool */
/* The paged pools in TOKENS. A percentage answers "how close to preemption"; tokens answer
* "how much context fits", and an operator sizing a deployment is asking the second. */
/* The paged pools in tokens: how much context fits, which kv_util does not say. */
int64_t kv_tokens_used = 0;
int64_t kv_tokens_total = 0;
/* AND HOW MUCH OF `used` NO RUNNING REQUEST IS READING, which is the difference between a
* cache doing its job and a leak. A finished turn's blocks stay held so the next turn can
* reuse them, so on a server carrying conversations this is most of the pool -- and with one
* number for the whole of it there is no way to tell that from a pool that never releases.
* It is the cache's UNSHARED holding: a block a running request is also reading belongs to
* that request in this split, because evicting it would free nothing. */
/* The part of `used` no running request reads: the prefix cache's unshared holding of
* finished turns. It separates a working cache from a pool that never releases. A block a
* running request also reads counts as that request's, since evicting it frees nothing. */
int64_t kv_tokens_cached = 0;
/* AND THE PAGED AND STATEFUL POOLS TOGETHER, IN BYTES: how much of the card the KV cache is
* holding, which is the question an operator watching VRAM is actually asking and the one
* neither figure above can answer. Tokens cannot be summed across groups -- two paged groups
* share one token axis and a recurrent group has none -- so the totals above are one group's,
* the binding one. Bytes are disjoint allocations and add up, so these are every group.
/* Paged and stateful pools together, in bytes: how much VRAM the KV cache holds. Tokens do
* not sum across groups (paged groups share one token axis, a recurrent group has none), so
* the token figures above are the binding group's; bytes are disjoint and cover every group.
*
* USED IS WHAT IS HELD, not what a live request is reading. A finished turn's blocks stay held
* by the prefix cache so the next turn can reuse them, and they are occupying VRAM for exactly
* as long; they stop counting when they reach the free list, which is where an eviction, a
* cancellation and an idle-tier demotion all put them. */
* Used means held, including prefix-cache blocks of finished turns; a block stops counting
* when it reaches the free list (eviction, cancellation or idle-tier demotion). */
int64_t kv_bytes_used = 0;
int64_t kv_bytes_total = 0;
/* What the pool was carved to address, which an elastic pool may not be holding. */
int64_t kv_bytes_carved = 0;
/* THE MOST CONTEXT THE CACHE CAN HOLD: every block of its carve, the ones lent to the expert
* slab taken back. `kv_bytes_carved` is the same figure in bytes. The paged groups share one
* token axis, so it is the smallest of theirs; a windowed group is left out, because its carve
* bounds how far back a sequence keeps context rather than how much fits. */
/* The most context the cache can hold: every block of its carve, including those lent to the
* expert slab (`kv_bytes_carved` in bytes). The smallest over the paged groups, which share
* one token axis; windowed groups are excluded, since their carve bounds lookback, not fit. */
int64_t kv_tokens_max = 0;
double prefix_hit_rate = 0.0; /* 0..1 */
/* Cumulative prefix-cache evictions. `prefix_hit_rate` falls only AFTER a prefix that
* would have been reused is gone; this rises as it happens, which is the difference
* between an alert and a post-mortem. */
/* Cumulative prefix-cache evictions. They rise as reusable prefixes are dropped, while
* `prefix_hit_rate` falls only afterwards. */
int64_t prefix_evictions = 0;
int64_t prefix_ckpt_evictions = 0;
/* What --prefix-cache-ttl took, cumulative. Not evictions: nothing wanted the memory. */
/* Snapshot evictions by reason (the retention policy; the least recently used of a store
* retention left full) and reservations that went without a snapshot. */
int64_t prefix_ckpt_retired = 0, prefix_ckpt_lru = 0, prefix_ckpt_refused = 0;
/* Admissions whose prefix hit was cut to nothing, by reason, and the checkpoint shortfall:
* attention-cached prompt tokens computed again (rad::SchedMetrics::hit_cut_tokens). */
int64_t hit_cut_no_snapshot = 0, hit_cut_window = 0, hit_cut_adopt = 0;
int64_t hit_cut_tokens = 0;
/* Removed by --prefix-cache-ttl, cumulative. Not evictions: nothing wanted the memory. */
int64_t prefix_expired = 0, prefix_ckpt_expired = 0;
/* PREFIX CACHING, DECOUPLED (spec §7.3). `prefix_hit_rate` above is the ATTENTION one, because
* that is what vLLM's single number has always meant. The linear side hits at a different
* granularity -- whole checkpoints, not blocks -- and averaging the two would hide exactly the
* effect the decoupling exists to expose. So both are carried, and the token counts beside
* them, and the checkpoints actually written. Without all of it a deployment cannot tell
* whether linear checkpointing is working at all. */
/* Decoupled prefix caching (spec §7.3). `prefix_hit_rate` is the attention hit rate, as in
* vLLM. The linear side hits at a different granularity (whole checkpoints, not blocks), so
* it is reported separately, with token counts and checkpoints written. */
double linear_hit_rate = 0.0;
int64_t attn_cached_tokens = 0;
int64_t linear_cached_tokens = 0;
int64_t checkpoints_written = 0;
double prefill_tps = 0.0;
double decode_tps = 0.0;
/* AND THE EXACT COUNTS BEHIND THEM. The two rates above are EWMAs, which is the right thing
* for a dashboard and the wrong thing for anything that has to compare two runs: a gauge
* describes whatever mix the engine happened to be in when it was read. These cumulative
* totals are the comparable form, and the only one: `vllm:generation_tokens_total` is charged
* when a request FINISHES and is therefore identically zero over any steady-state window. */
/* Exact cumulative counts behind the EWMA rates above, for comparing runs.
* `vllm:generation_tokens_total` is charged when a request finishes, so it cannot serve. */
int64_t prefill_tokens = 0;
int64_t decode_tokens = 0;
double draft_acceptance = 0.0; /* 0..1, spec §10 */
/* The exact pair the ratio is computed from, for the same reason. */
/* The exact pair the ratio is computed from. */
int64_t draft_tokens = 0;
int64_t draft_accepted = 0;
/* Prefix hits ended early for a windowed block drafter, and the tokens they gave back. */
int64_t draft_refills = 0;
int64_t draft_refill_tokens = 0;
/* THE PER-POSITION DRAFT HAZARD. `draft_acceptance` above is pooled over the whole window and
* cannot distinguish a drafter that decays with depth from one whose later rounds are broken:
* both read as one small number. These carry the conditional rate at each position -- of the
* verifies that reached j because every earlier position was accepted, the fraction that took
* j as well -- and the reach counts that say how much evidence each one has. */
/* Per-position draft acceptance. The pooled `draft_acceptance` cannot tell a drafter that
* decays with depth from one whose later rounds are broken. Per position j: verifies that
* reached j (every earlier position accepted) and how many of those took j. */
static const int MAX_DRAFT_POS = 64;
int draft_depth_seen = 0;
int64_t draft_pos_reached [MAX_DRAFT_POS] = {};
int64_t draft_pos_accepted[MAX_DRAFT_POS] = {};
/* THE ADAPTIVE DRAFT WINDOW (--draft-window adaptive), all zero while it is off: the mean window
* of the running sequences, and the verifies by the window they carried (index = drafts). */
/* Adaptive draft window (--draft-window adaptive), zero while off: the running sequences'
* mean window, and verifies by the window they carried (index = drafts). */
bool draft_adaptive = false;
double draft_depth_adaptive = 0.0;
int64_t draft_verify_depth[MAX_DRAFT_POS + 1] = {};
int64_t preemptions = 0;
int64_t total_requests = 0;
/* ENGINE STEPS. One forward pass of the model plus whatever draft rounds followed it, which
* with speculation is more than one token -- so tokens a second cannot answer "how long is a
* step" and the two questions have to be asked separately. */
/* Engine steps: one forward pass plus any draft rounds after it. With speculation a step
* emits more than one token, so step time cannot be derived from tokens per second. */
int64_t steps = 0;
/* STEPS BY SHAPE. A step carrying a prefill chunk cannot roll back a rejected draft, so
* nothing in it speculates, decode rows included. These say how often the load produces that
* shape and how many decode rows paid for it. */
/* Steps by shape. A mixed step carries a prefill chunk and decode rows, and its decode rows
* take drafts like a decode step's (Scheduler::step). */
int64_t steps_prefill = 0;
int64_t steps_mixed = 0;
int64_t steps_decode = 0;
int64_t steps_ahead = 0; /* issued behind the step before, ahead of its commit */
int64_t prefill_chunks_capped = 0; /* held back for other work in the step (--busy-prefill-chunk) */
int64_t steps_held = 0; /* decode-only steps --prefill-interleave inserted */
int64_t decode_rows_unspeculated = 0;
/* WHAT THE STEPS COST: cumulative nanoseconds spent inside a step, and the decode half of it
* separately. A step time is not wall clock over a step count -- the engine idles between an
* agent's turns and a prefill chunk costs an order of magnitude more than a decode step, and
* a gauge that divides charges both to the decode step. `step_ns_decode / steps_decode` is
* what a decode step cost, whatever the load was doing around it. */
/* Cumulative nanoseconds inside steps, all shapes and decode-only. Wall clock over a step
* count is not a step time: the engine idles between turns, and a prefill chunk costs an
* order of magnitude more than a decode step. `step_ns_decode / steps_decode` is the cost of
* a decode step regardless of load. */
int64_t step_ns = 0;
int64_t step_ns_decode = 0;
};
/* WHAT ONE REQUEST IS DOING RIGHT NOW. The aggregate metrics answer "is the engine busy"; they
* cannot answer "which of these eight is stuck", and a request sitting in Waiting because its
* prompt will never fit is invisible in every one of them. */
/* ONE STORED CONVERSATION. Not a request: a request is in flight and is gone when it answers,
* while this is what the engine is still HOLDING on a session's behalf between turns -- which is
* the thing that decides whether the next turn costs a copy or a re-prefill.
/* One stored conversation: what the engine still holds for a session between turns, which
* decides whether the next turn costs a copy or a re-prefill.
*
* THE SIZES OVERLAP AND THE TOTAL IS NOT A SUM. Sessions that share a system prompt share the
* blocks for it, which is the entire point of a prefix cache; a view that hid that would make a
* server look like it was storing several times what it holds. Anything rendering these says so.
*
* A SESSION IS ROUTINELY SPLIT ACROSS TIERS, because a maintenance pass is bounded and moves a
* long conversation over several of them. So "where is it" is three counts and not a label. */
* Sizes overlap: sessions sharing a system prompt share its blocks, so a total is not a sum, and
* anything rendering these must say so. A session is routinely split across tiers (a maintenance
* pass is bounded), so its location is block counts, not a label. */
struct SessionStat {
uint64_t id = 0;
std::string model; /* the container it was built against */
@@ -171,10 +145,9 @@ struct SessionStat {
double idle_s = 0; /* since its last turn */
double age_s = 0; /* since it was first seen */
int64_t on_device = 0, on_host = 0; /* blocks */
/* LINEAR STATE, on a hybrid model, and counted apart from blocks because the two are not
* interchangeable. A session showing every block in host memory and no snapshot will come
* back and re-run every recurrent layer over its whole transcript -- which the hit rate will
* report as a hit. Zero everywhere on a model that has no recurrent state. */
/* Linear-state snapshots on a hybrid model, counted apart from blocks: a session with its
* blocks kept but no snapshot re-runs every recurrent layer over its transcript, though the
* hit rate reports a hit. Zero on a model with no recurrent state. */
int64_t snapshots = 0;
int64_t snap_bytes = 0;
/* The prefix a return skips: the deepest snapshot's position (IdleTiers::SessionInfo). */
@@ -182,13 +155,15 @@ struct SessionStat {
bool moving = false; /* a transfer is outstanding */
};
/* WHAT THE STORED CONVERSATIONS OCCUPY OFF THE CARD, blocks and snapshots each counted once --
* the one total the per-session rows cannot be summed into. Caps are 0 for a tier that is off. */
/* What stored conversations occupy off the card, blocks and snapshots each counted once (the
* per-session rows cannot be summed into this). Caps are 0 for a tier that is off. */
struct SessionOccupancy {
int64_t host_bytes = 0;
int64_t host_cap_bytes = 0;
};
/* One in-flight request, for the live request table: shows which request is stuck, e.g. one
* waiting on a prompt that will never fit, which no aggregate metric reveals. */
struct RequestStat {
uint64_t id = 0;
std::string state; /* waiting | prefill | decode | preempted | done */
@@ -199,8 +174,7 @@ struct RequestStat {
int64_t max_tokens = 0;
int64_t ctx_tokens = 0;
int64_t kv_blocks = 0; /* summed over the paged groups: they are disjoint allocations */
/* The context it is holding, on the token axis the paged groups share -- NOT their sum. See
* the note at the definition: the two figures are in different units on purpose. */
/* Context held, on the token axis the paged groups share (not their sum). */
int64_t kv_tokens = 0;
int32_t n_draft = 0;
int32_t slot = -1;
@@ -213,10 +187,9 @@ class IScheduler {
public:
virtual ~IScheduler() = default;
virtual uint64_t submit(Request&& r) = 0;
/* THE SEQUENCES OF ONE API REQUEST, all admitted before a step can see any of them: a prompt
* array or `n` > 1 submitted one call at a time can have a step begin between two calls, so
* the batch they decode in -- and its tie-level rounding -- would depend on thread timing.
* ids[i] is what submit() would have returned for rs[i]. This default is that loop, for a
/* Admits all sequences of one API request before a step can see any of them; submitted one
* at a time, a step could start between calls and the batch (and its tie-level rounding)
* would depend on thread timing. ids[i] is submit()'s id for rs[i]. The default loop suits a
* scheduler whose steps cannot interleave with submission. */
virtual void submit_all(std::vector<Request>& rs, std::vector<uint64_t>* ids) {
ids->clear();
@@ -225,65 +198,53 @@ public:
virtual void cancel(uint64_t id) = 0;
virtual SchedMetrics metrics() const = 0;
/* "I am finished with this request's sink; you may drop the Request." core/sched keeps a
* terminal request alive precisely because the HTTP thread still holds its sink, so somebody
* has to say when that stops being true, and the HTTP thread is the only one who knows.
* Called at most once per submitted id, after the response has been written. Default no-op,
* for a scheduler that frees at completion. */
/* The HTTP thread is done with this request's sink; the scheduler may drop the Request it
* keeps alive after termination. Called at most once per id, after the response is written.
* Default no-op, for a scheduler that frees at completion. */
virtual void reap(uint64_t /*id*/) {}
/* CAN THIS REQUEST'S SAMPLING PARAMETERS BE SERVED AT ALL?
/* Whether this request's sampling parameters can be served at all. An unresolved sampler op
* is not a declare failure (a deployment that never sends `typical_p` needs no typical
* kernel; core/sample/sampler.h), only a request that asks for it is refused. The step loop
* treats an unresolved stage as unreachable and relies on this check.
*
* A sampler op that does not resolve is deliberately not a declare failure -- a deployment
* that never sends `typical_p` does not need a typical kernel (core/sample/sampler.h). It
* becomes a failure when a request asks for it, and Sampler::check_request exists to say so
* by name. This is what the step loop relies on when it treats an unresolved stage as
* unreachable: without the check here, such a request is admitted, runs, and is cancelled
* mid-step with the reason in the log and a dead stream at the client.
*
* Asked once per submission, on the HTTP thread, before the first Request is built. Returns
* RAD_OK, or a negative status with `why` set. The default admits everything so a test's fake
* scheduler needs no change; the real answer comes from SchedulerBridge. */
* Called once per submission on the HTTP thread, before any Request is built. RAD_OK, or a
* negative status with `why` set. The default admits everything (test fakes); the real
* answer comes from SchedulerBridge. */
virtual int admit(const SamplingParams& /*sp*/, std::string* /*why*/) const { return RAD_OK; }
/* DROP EVERY PREFIX-CACHE ENTRY, returning how many were dropped -- or a negative status when
* this build has no prefix cache, which is a 501 rather than a lie about having cleared one.
*
* vLLM has this endpoint and it exists for the same reason: the second run of a benchmark is
* not measuring what the first one measured, and an operator who cannot say "start cold"
* cannot compare two numbers. Releasing the cache's references is safe against a running step
* -- a block a live sequence holds stays allocated -- but it still takes the scheduler's lock,
* because the alternative is an HTTP thread walking the map a step is inserting into. */
/* Drops every prefix-cache entry and returns how many, or a negative status (501) when there
* is no prefix cache. Lets a benchmark start cold, as vLLM's endpoint does. Releasing the
* cache's references is safe against a running step (blocks a live sequence holds stay
* allocated), but it takes the scheduler's lock because a step may be inserting into the map. */
virtual int64_t reset_prefix_cache() { return RAD_E_UNSUPPORTED; }
/* The live request table. Fills `out` and returns how many, oldest first; the default answers
* "this scheduler does not keep one", which is an empty table and not a wrong one. */
/* The live request table, oldest first; returns the count. Default: none kept. */
virtual int requests(std::vector<RequestStat>* /*out*/) const { return 0; }
/* The stored conversations: what the engine is still holding between turns, and where. The
* default answers "this build has no idle tiers", which is an empty table and not a wrong
* one -- with the tiers off, everything the cache holds is in VRAM by definition. */
/* The stored conversations and where they are held. Default: no idle tiers, so an empty
* table (everything the cache holds is in VRAM). */
virtual int sessions(std::vector<SessionStat>* /*out*/, SessionOccupancy* /*occ*/) const {
return 0;
}
/* WHAT THE TIERS HAVE ACTUALLY DONE. Without it the session table looks the same whether the
* tiers are working, switched off, or trying and failing every pass -- three very different
* situations that all render as "everything is in VRAM". */
/* What the idle tiers have done. Without it the session table looks the same whether the
* tiers work, are off, or fail every pass. */
struct TierCounters {
/* `to_host` counts COPIES; `dropped` is VRAM given up after one. A conversation that
* returns before anything wants its VRAM is copied and never dropped. `host_drops` is
* entries a full host tier gave up; `promoted` counts restores. */
/* `to_host` counts copies; `dropped` is VRAM given up after one (a conversation that
* returns before its VRAM is wanted is copied but never dropped). `host_drops` is entries
* a full host tier gave up; `promoted` counts restores. */
int64_t to_host = 0, dropped = 0, promoted = 0;
int64_t host_drops = 0, failures = 0;
/* Copies a full host tier did not take, every host entry being worth as much; their
* entries stay in VRAM only (IdleTiers::Stats::held_back). */
int64_t held_back = 0;
int64_t host_bytes = 0;
/* THE SNAPSHOT STORE, which lives in host memory and moves nothing. */
/* The snapshot store, in host memory; it moves nothing. */
int64_t ck_bytes = 0; /* one snapshot; 0 on a model with no recurrent state */
int64_t ck_slots = 0;
int64_t restores = 0, restore_ns = 0, flushes = 0, flush_ns = 0; /* IdleTiers::Stats */
/* WHETHER ANYTHING CAN MOVE AT ALL, which no counter above can answer: a tier that is on
* and has had nothing to do reads the same as one that was never given a size, and the
* two call for opposite responses from whoever is looking. */
/* Whether a host tier exists; an idle tier and an unconfigured one have equal counters. */
bool host_on = false;
};
virtual TierCounters tier_counters() const { return TierCounters{}; }
@@ -291,19 +252,18 @@ public:
/* ================================================================== text frontend
*
* ASSUMED of core/text. Detokenisation is incremental and streaming-safe (spec §12): byte-level
* BPE emits partial UTF-8 sequences, so `push` returns "" until the bytes resolve into a
* character, and `flush` drains whatever is left at the end of a generation.
* Contract with core/text. Detokenisation is incremental and streaming-safe (spec §12): byte-level
* BPE emits partial UTF-8, so `push` returns "" until the bytes form a character, and `flush`
* drains the rest at the end of a generation.
*/
class IDetokenizer {
public:
virtual ~IDetokenizer() = default;
virtual std::string push(int32_t token) = 0;
virtual std::string flush() = 0;
/* True once the decoder itself swallowed a stop string. core/text's Detokenizer can be built
* with the request's stop strings and then never emits one; without this the server would
* search text that can no longer contain what it is searching for, and the generation would
* run to max_tokens. Default false, for a decoder that leaves stop handling to us. */
/* True once the decoder itself swallowed a stop string. core/text's Detokenizer, built with
* the stop strings, never emits one, so the server cannot find it in the text and relies on
* this. Default false, for a decoder that leaves stop handling to the server. */
virtual bool stopped() const { return false; }
/* The stop string that stopped it, "" when none has. */
virtual std::string stop_hit() const { return std::string(); }
@@ -317,24 +277,18 @@ public:
virtual ~ITokenizer() = default;
/* `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. */
* its characters; it has no default so every caller chooses. Whole prompts are parsed (a
* rendered chat template, or a raw /v1/completions prompt, 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;
virtual int32_t eos() const = 0;
virtual int32_t bos() const = 0;
/* WHAT THIS VOCABULARY IS, for /tokenize and /get_tokenizer_info. Off every hot path: asked
* once per request to those two endpoints and never during generation.
*
* A struct rather than eight accessors because the set will grow, and a client that reads
* this to decide how to build a prompt would otherwise be reading it across eight virtual
* calls that can disagree about which vocabulary they describe. The default is "I do not
* know", which is what a fake tokenizer in a test honestly is. */
/* Vocabulary facts for /tokenize and /get_tokenizer_info; never called during generation.
* One struct, so the fields describe one vocabulary consistently. The default is "unknown"
* (test fakes). */
struct VocabInfo {
int32_t n_tokens = 0;
int32_t bos = -1, eos = -1, eot = -1, unk = -1, pad = -1;
@@ -343,32 +297,26 @@ public:
};
virtual VocabInfo vocab_info() const { return VocabInfo{}; }
/* The raw piece an id stands for, NOT its decoded text: /tokenize's `return_token_strs` shows
* what the tokeniser actually chose, and decoding each id one at a time would render a
* byte-fallback token as a replacement character and lose exactly the detail the caller
* turned the flag on to see. "" when the id is out of range. */
/* The raw piece an id stands for, not its decoded text: /tokenize's `return_token_strs` shows
* what the tokeniser chose, and decoding one id at a time would turn a byte-fallback token
* into a replacement character. "" when the id is out of range. */
virtual std::string piece(int32_t /*id*/) const { return std::string(); }
/* THE BYTES ONE ID DECODES TO, unsanitised, control tokens rendered: llama-server's
* `with_pieces`. Not necessarily whole UTF-8 -- a byte-fallback or a split multi-byte
* character is a fragment -- so the caller checks before putting it in a JSON string. */
/* The bytes one id decodes to, unsanitised, control tokens rendered (llama-server's
* `with_pieces`). Not necessarily whole UTF-8, so the caller checks before putting it in a
* JSON string. */
virtual std::string token_bytes(int32_t /*id*/) const { return std::string(); }
/* The bytes one id adds to a REPLY: token_bytes with control tokens rendered as nothing, as
* the decoder renders them -- what a logprobs entry spells the token as, so the entries'
* texts add up to the reply, as llama-server's do. */
/* The bytes one id adds to a reply: token_bytes with control tokens rendered as nothing, as
* the decoder does. Used for logprobs entries, so their texts add up to the reply, as
* llama-server's do. */
virtual std::string reply_bytes(int32_t id) const { return token_bytes(id); }
/* One incremental decoder per in-flight generation. It is made by the tokenizer rather than
* default-constructed by the caller, because it needs the vocabulary to decode anything.
* `stops` is passed down because core/text's Detokenizer can suppress a stop string that
* straddles a token boundary, which is strictly better than the server finding it after the
* fact -- and IDetokenizer::stopped() is how it tells us it did.
/* One incremental decoder per in-flight generation. `stops` lets core/text's Detokenizer
* suppress a stop string that straddles a token boundary; IDetokenizer::stopped() reports it.
*
* `preserved` is the control tokens this generation must decode as TEXT. A tool-calling
* format can be built out of control tokens -- MiniCPM5 writes `<function`, `<param` and
* their closers that way -- and a decoder that suppresses them the way control tokens are
* normally suppressed hands the reply parser the argument values with the structure gone.
* The chat render says which ones; empty everywhere else. */
* `preserved` lists control tokens to decode as text. Some tool-call formats are built from
* control tokens (MiniCPM5's `<function`, `<param` and closers); suppressing them would hand
* the reply parser argument values without their structure. Set by the chat render. */
virtual std::unique_ptr<IDetokenizer> detokenizer(
const std::vector<std::string>& stops,
const std::vector<std::string>& preserved = {}) const = 0;
@@ -376,12 +324,11 @@ public:
class IReplyParser;
/* What a chat template needs told, beyond the messages themselves.
/* What a chat template needs beyond the messages.
*
* `template_kwargs` VALUES ARE JSON TEXT, not display text: `"false"`, `"\"high\""`, `"3"`. That
* is the shape the request carries them in and the shape the template context wants them in, and
* converting in between would mean this layer deciding that the string "false" is a boolean --
* which is exactly the guess that makes `enable_thinking: "false"` silently enable thinking. */
* `template_kwargs` values are JSON text, not display text: `"false"`, `"\"high\""`, `"3"`, as
* the request carries them and the template context wants them. Converting would mean guessing
* that the string "false" is a boolean, which makes `enable_thinking: "false"` enable thinking. */
struct ChatRenderOptions {
bool add_generation_prompt = true;
bool enable_thinking = true;
@@ -391,20 +338,17 @@ struct ChatRenderOptions {
std::string grammar; /* the caller's GBNF, or "" */
std::string json_schema; /* a response_format schema, as JSON text, or "" */
std::string reasoning_format = "auto";
/* ASSISTANT PREFILL: continue the conversation's last (assistant) message rather than open a
* new turn. "" off, else llama.cpp's "auto", "content" or "reasoning_content". */
/* Assistant prefill: continue the last (assistant) message rather than open a new turn. ""
* off, else llama.cpp's "auto", "content" or "reasoning_content". */
std::string continue_final;
std::map<std::string, std::string> template_kwargs;
/* A render whose refusal is an answer and not an error -- the startup probes of what the
* template takes -- so the template's refusal is not logged. */
/* Startup probes, where a refusal is an answer, not an error: do not log it. */
bool quiet = false;
};
/* What it gives back. A STRING IS NOT ENOUGH, and that is the whole reason this struct exists: a
* tool-calling template emits a prompt AND the grammar that makes the model's call parseable AND
* the triggers that keep that grammar off the prose AND the stop strings the format ends on. A
* seam that returns only the prompt drops the other three silently, which is a chat endpoint that
* accepts `tools` and then produces calls no client can read. */
/* A render's result. A tool-calling template produces more than a prompt: the grammar that keeps
* the model's call parseable, the triggers that keep it off the prose, and the format's stop
* strings. Dropping them yields tool calls no client can read. */
struct ChatRender {
std::string prompt;
@@ -414,21 +358,21 @@ struct ChatRender {
std::vector<std::string> additional_stops;
/* The assistant prefix already inside `prompt`. The grammar describes the whole turn, so it
* has to be advanced over this before it constrains the first generated token. */
* is advanced over this before constraining the first generated token. */
std::string generation_prompt;
/* The reply parser this render implies: the model's reply format bound to THESE tools and
* THIS generation prompt, so it cannot be a server-wide singleton. It reads calls only when
* the request sent tools. Null when nothing needs parsing. */
/* The reply parser for this render: the model's reply format bound to these tools and this
* generation prompt, hence per request. It reads calls only when the request sent tools.
* Null when nothing needs parsing. */
std::shared_ptr<IReplyParser> parser;
/* The tokens that parser must be able to SEE. See ITokenizer::detokenizer. */
/* Control tokens the parser must see as text. 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. */
/* The reasoning block the reply faces, as the parser reads it: markers with optional
* whitespace trimmed, and whether the reply starts inside the block. Empty `think_close`
* means no reasoning block. The server maps these to token ids (ReasoningSpan) to count the
* block and enforce a budget. */
std::string think_open, think_close;
bool think_starts_open = false;
};
@@ -437,24 +381,22 @@ class IChatTemplate {
public:
virtual ~IChatTemplate() = default;
/* Render. Returns RAD_OK, or a negative status with `why` naming what the template refused --
* which becomes the 400's message, so it has to read like something a caller can act on. */
/* Render. RAD_OK, or a negative status with `why` naming what the template refused; `why`
* becomes the 400's message, so it must be actionable for the caller. */
virtual int apply(const json& messages, const json& tools, const ChatRenderOptions& opt,
ChatRender* out, std::string* why) const = 0;
virtual bool supports_tools() const = 0;
virtual bool supports_reasoning() const = 0;
/* WHY THIS MODEL'S TOOL CALLS CANNOT BE READ, or "" when they can. A template may declare tool
* support in a format the reply parser does not describe; such a model still chats, and a
* request that sends tools is refused with this sentence rather than answered with calls
* nobody can read back. */
/* Why this model's tool calls cannot be read, or "" when they can. A template may support
* tools in a format the reply parser does not know; the model still chats, and a request that
* sends tools is refused with this sentence. */
virtual std::string tool_refusal() const { return std::string(); }
/* THE TEMPLATE'S SOURCE TEXT and what the capability probe found in it, for /props: what
* llama-server reports as `chat_template` and `chat_template_caps`, so a client built against
* it can render a prompt the way this server will. "" when unknown; the caps are a JSON
* object as text, "{}" when unknown. */
/* The template's source and its probed capabilities, for /props (llama-server's
* `chat_template` and `chat_template_caps`), so clients can render prompts as this server
* does. "" and "{}" (a JSON object as text) when unknown. */
virtual std::string source() const { return std::string(); }
virtual std::string caps() const { return "{}"; }
};
@@ -474,9 +416,9 @@ struct ParsedMessage {
bool open_call = false;
};
/* One increment of a reply that is being read as it is generated. What has been delivered is
* never revised: the concatenated increments of each kind ARE the finished values, which is what
* lets the streaming endpoint forward each one as it comes. */
/* One increment of a reply read as it is generated. Delivered increments are never revised: the
* concatenated increments of each kind are the finished values, so streaming forwards each as it
* comes. */
struct ReplyDelta {
enum Kind : uint8_t {
Reasoning, /* text: a reasoning delta */
@@ -490,9 +432,9 @@ struct ReplyDelta {
std::string text;
};
/* One choice's reply, read once, in order, as it is generated. feed() appends generated text
* and finish() says there is no more; each appends the increments it completes. The cost is
* linear in the reply however it is cut up -- the text is never read from the top again. */
/* One choice's reply, read once, in order, as it is generated. feed() appends generated text and
* finish() ends it; each appends the increments it completes. Linear in the reply however it is
* split; the text is never re-read from the top. */
class IReplyReader {
public:
virtual ~IReplyReader() = default;
@@ -500,14 +442,14 @@ public:
virtual void finish(std::vector<ReplyDelta>* out) = 0;
/* The whole reply, once finish() has run. */
virtual ParsedMessage message() const = 0;
/* Once finish() has run: the content with an open last call (ParsedMessage::open_call) read
* as the text it was written as -- the content before the call, then the call's own bytes
* from `reply`, the whole text fed. The content alone when no call is open. */
/* After finish(): the content with an open last call (ParsedMessage::open_call) restored as
* text, i.e. the content before the call plus the call's own bytes from `reply` (the whole
* text fed). The content alone when no call is open. */
virtual std::string content_with_open_call(std::string_view reply) const = 0;
};
/* A request's reply format. Each choice opens its own reader, and a request that sent no tools
* gets a parser that reads no calls: call syntax in its reply is text to that request. */
/* A request's reply format. Each choice opens its own reader. A request that sent no tools gets
* a parser that reads no calls, so call syntax in its reply is plain text. */
class IReplyParser {
public:
virtual ~IReplyParser() = default;
@@ -521,26 +463,25 @@ public:
virtual ~IGrammarCompiler() = default;
virtual int from_json_schema(const json& schema, std::string& out, std::string& err) const = 0;
/* Compile this GBNF, here, on the admitting thread, and hand back the program for the request
* to carry (SamplingParams::grammar_program). Compiling is where a grammar is found not to
* run -- left recursion, a construct the mask engine cannot serve, a bound it outgrows -- and
* where its mask plan is built, which is host work in the tens to hundreds of milliseconds.
* The alternative is doing both on the scheduler thread, where the only thing left to do about
* a failure is kill the request three tokens into its answer, and every other request's step
* waits for the build. A grammar that cannot be compiled is a 400 that names why. */
/* Compiles this GBNF on the admitting thread into the program the request carries
* (SamplingParams::grammar_program). Compiling finds grammars that cannot run (left
* recursion, constructs the mask engine cannot serve, bounds it outgrows) and builds the mask
* plan, tens to hundreds of milliseconds of host work. On the scheduler thread a failure
* could only kill the request mid-answer and the build would stall every step. Failure is a
* 400 naming why. */
virtual int compile(const std::string& gbnf, std::shared_ptr<const GbnfProgram>* out,
std::string& err) const = 0;
};
/* ================================================================== optional backends */
/* /v1/embeddings: WHAT THE LOADED MODEL EMBEDS, present only when it is an embedding model
* (rad_declare_pooled). Absent, the endpoint is 501 naming that -- not an empty 200.
/* /v1/embeddings, present only for an embedding model (rad_declare_pooled); absent, the endpoint
* is 501.
*
* The vectors themselves come through the scheduler like any other request: the server submits
* one Request a input with Request::embed set, and each finishes at its one step with its pooled
* vector in its sink (Sink::embedding). So batching, admission, media encoding and cancellation
* are the scheduler's, exactly as they are for a completion. */
* Vectors come through the scheduler: the server submits one Request per input with
* Request::embed set, and each finishes after one step with its pooled vector in its sink
* (Sink::embedding). Batching, admission, media encoding and cancellation work as for a
* completion. */
class IEmbedder {
public:
virtual ~IEmbedder() = default;
@@ -548,8 +489,8 @@ public:
virtual int64_t dim() const = 0;
/* The longest input one step carries: an input is never split, so a longer one is refused. */
virtual int64_t max_input() const = 0;
/* THE MODEL'S NAMED PROMPTS (sentence-transformers' `prompts`): the text a `prompt_name` puts
* in front of an input -- "query" -> "task: search result | query: ". False when the model
/* The model's named prompts (sentence-transformers' `prompts`): the text a `prompt_name`
* prepends to an input, e.g. "query" -> "task: search result | query: ". False when the model
* states no prompt of that name. */
virtual bool prompt(const std::string& name, std::string* text) const {
(void)name; (void)text;
@@ -557,8 +498,7 @@ public:
}
/* The prompt an input takes when the request names none, "" for none. */
virtual std::string default_prompt() const { return std::string(); }
/* The template a `messages` input renders through -- the model's chat template -- or null
* when it has none. */
/* The chat template a `messages` input renders through, or null. */
virtual IChatTemplate* message_template() const { return nullptr; }
};
@@ -568,13 +508,12 @@ public:
* for a video, the timestamps between its frames. */
enum class MediaKind { Image, Video, Audio };
/* The placeholder a chat template renders where a media part sat. Both the template and the
* server have to agree on the spelling or the prompt silently loses its images, so it is declared
* once, here, rather than twice. llama.cpp's mtmd uses the same string, which is not an accident:
* the templates are the same templates. */
/* The placeholder a chat template renders where a media part sat. Template and server must agree
* on it, so it is declared once, here. It is llama.cpp mtmd's string, since the templates are
* shared. */
#define RAD_MEDIA_MARKER "<__media__>"
/* WHAT A REQUEST ASKED OF ITS MEDIA, beside the bytes. Zero is the server's default. */
/* Per-request media options beside the bytes. Zero is the server's default. */
struct MediaOpts {
/* Soft tokens (encoder output rows) an image may become, for a processor that sizes images
* by a token budget (Gemma 4's: 70, 140, 280, 560 or 1120). */
@@ -593,13 +532,48 @@ public:
* token run that replaces the marker; on failure `why` says what is wrong with the media. */
virtual int prepare(MediaKind k, const std::vector<uint8_t>& bytes, const MediaOpts& opts,
std::shared_ptr<mm::Item>* out, std::string* why) = 0;
/* Audio in two halves, for a route that cuts a long recording into clips itself
* (/v1/audio/transcriptions): the file decoded to mono samples at audio_rate(), at most
* `max_samples` of them (RAD_E_INVAL past that, never a silent cut), and a clip of at most
* audio_max_samples() processed as prepare() would. Zero rate: no audio is served. */
virtual int32_t audio_rate() const { return 0; }
virtual int64_t audio_max_samples() const { return 0; }
virtual int decode_audio(const std::vector<uint8_t>& bytes, int64_t max_samples,
std::vector<float>* out, std::string* why) {
(void)bytes; (void)max_samples; (void)out;
if (why) *why = "this server decodes no audio";
return RAD_E_UNSUPPORTED;
}
virtual int prepare_audio(const std::vector<float>& samples, std::shared_ptr<mm::Item>* out,
std::string* why) {
(void)samples; (void)out;
if (why) *why = "this server serves no audio";
return RAD_E_UNSUPPORTED;
}
};
/* How the model takes audio, as the architecture plugin states it (RadAudioFormat,
* abi/rad_builder.h), copied out at startup. It is all the speech routes know of the model. */
struct SpeechFormat {
std::string transcribe_prompt; /* {context}, {audio}, {language} */
std::string language_prompt; /* {language} */
std::string transcript_open;
std::string language_lead;
/* (ISO 639-1 code, the model's name for it) */
std::vector<std::pair<std::string, std::string>> languages;
bool transcribes() const { return !transcribe_prompt.empty(); }
/* The model's name for `lang`, which may be a code or a name in any case; "" when the model
* names no such language. */
std::string language_name(const std::string& lang) const;
};
/* THE IMAGE GENERATOR (core/gen), for a model that makes pictures rather than text: what the
* model declared about its prompts and sizes, and the queue a request goes into. The server turns
* an OpenAI images request into a gen::Request -- the prompt rendered and tokenised, the reference
* pictures resized for both of the model's readers -- and reads the pictures back off its ticket. */
/* The image generator (core/gen), for a model that makes pictures: its declared prompt templates
* and sizes, and its request queue. The server turns an OpenAI images request into a gen::Request
* (prompt rendered and tokenised, reference pictures resized for both of the model's readers) and
* reads the pictures back off its ticket. */
struct ImageGenInfo {
std::string name, tmpl_text, tmpl_edit, tmpl_image, tmpl_image_sep, drop_prefix,
tmpl_transparent;