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

+187 -185
View File
@@ -1,22 +1,20 @@
/* core/server/adapters.h -- bind the real components onto the server's interfaces.
*
* iface.h deliberately knows nothing about core/sched or core/text, so that the HTTP layer can be
* compiled and tested against fakes with no engine present. This file is where the two sides
* actually meet, and it is included by exactly one translation unit: whoever wires the engine
* (core/engine.cpp). Nothing in core/server/ includes it, so the server's own build stays
* independent of those components' headers.
* iface.h knows nothing about core/sched or core/text, so the HTTP layer can be built and tested
* against fakes. This file joins the two sides and is included only by the translation unit that
* wires the engine (core/engine.cpp); nothing in core/server/ includes it.
*
* rad::server::SchedulerBridge sched(&engine_scheduler);
* rad::server::TokenizerBridge tok(vocab);
* rad::server::Deps d; d.sched = &sched; d.tok = &tok; ...
*
* Every impedance mismatch between what the server wants and what those components provide is
* resolved here, in one place, with the reason written down -- rather than being smeared across
* either component as a special case for the other.
* Mismatches between what the server wants and what the components provide are resolved here
* rather than as special cases inside either side.
*/
#pragma once
#include "iface.h"
#include "mem/kvtier.h"
#include "sink.h"
#if !defined(RAD_SERVER_NO_ENGINE_BRIDGE) && \
__has_include("sched/scheduler.h") && __has_include("text/tokenizer.h")
@@ -37,6 +35,7 @@
#include <algorithm>
#include <atomic>
#include <iterator>
#include <memory>
namespace rad {
@@ -44,15 +43,111 @@ namespace server {
/* ================================================================== scheduler */
/* The scheduler's snapshot in the server's terms (SchedulerBridge::metrics). */
inline SchedMetrics bridge_metrics(const rad::SchedMetrics& m) {
SchedMetrics o;
o.waiting = m.queue_depth;
o.running = m.running;
o.preempted = m.preempted_waiting;
/* KV utilisation is the maximum over groups, not the mean: a hybrid model's attention
* and linear-state groups have different geometries (spec §7.2) and exhausting either
* one preempts.
*
* Token capacity is not a sum either. Paged groups share one token axis: each context
* token takes a slot in every paged group (e.g. Qwen4-Exp's `kv_attn` and `kv_qsa_bkey`),
* so summing overcounts by the number of paged groups. The token figures are the binding
* group's: the paged group nearest full, which decides the next preemption. A windowed group
* never binds: it recycles blocks below its window, so its fill bounds lookback, not how much
* context fits (a drafter's window sits full for the server's whole life). */
o.kv_util = 0.0;
int bind = -1;
for (int i = 0; i < m.n_kv_groups; ++i) {
if (m.kv[i].block_tokens <= 0) continue; /* a linear state has no token axis */
if (m.kv[i].window) continue;
if (bind < 0 || m.kv[i].utilisation > m.kv[bind].utilisation) bind = i;
}
for (int i = 0; i < m.n_kv_groups; ++i)
o.kv_util = std::max(o.kv_util, (double)m.kv[i].utilisation);
if (bind >= 0) {
const int64_t bt = m.kv[bind].block_tokens;
o.kv_tokens_total = m.kv[bind].blocks_total * bt;
o.kv_tokens_used = (m.kv[bind].blocks_total - m.kv[bind].blocks_free) * bt;
}
/* Bytes, unlike tokens, do sum: each group has its own extent of VRAM, so every group
* (recurrent ones included) is added. */
for (int i = 0; i < m.n_kv_groups; ++i) {
o.kv_bytes_total += m.kv[i].bytes_total;
o.kv_bytes_used += m.kv[i].bytes_used;
o.kv_bytes_carved += m.kv[i].bytes_carved;
if (m.kv[i].block_tokens <= 0 || m.kv[i].window) continue;
const int64_t t = m.kv[i].blocks_total * m.kv[i].block_tokens;
if (o.kv_tokens_max == 0 || t < o.kv_tokens_max) o.kv_tokens_max = t;
}
/* vLLM's gpu_prefix_cache_hit_rate means attention caching. The linear-checkpoint hit
* rate has a different granularity (spec §7.3) and is reported separately, not averaged
* in. */
o.prefix_hit_rate = m.attn_hit_rate;
o.prefix_evictions = m.prefix_evictions;
/* What only the cache holds (SchedMetrics::prefix_held_tokens), clamped to the pool's
* used figure: the two are counted at different moments in a step, and cached > used
* would show a negative live share. */
o.kv_tokens_cached = std::min(m.prefix_held_tokens, o.kv_tokens_used);
o.prefix_ckpt_evictions = m.prefix_ckpt_evictions;
o.prefix_ckpt_retired = m.prefix_ckpt_retired;
o.prefix_ckpt_lru = m.prefix_ckpt_lru;
o.prefix_ckpt_refused = m.prefix_ckpt_refused;
o.hit_cut_no_snapshot = m.hit_cut_no_snapshot;
o.hit_cut_window = m.hit_cut_window;
o.hit_cut_adopt = m.hit_cut_adopt;
o.hit_cut_tokens = m.hit_cut_tokens;
o.prefix_expired = m.prefix_expired;
o.prefix_ckpt_expired = m.prefix_ckpt_expired;
o.prefill_tps = m.prefill_tps;
o.decode_tps = m.decode_tps;
o.draft_acceptance = m.draft_acceptance;
o.prefill_tokens = m.prefill_tokens; o.decode_tokens = m.decode_tokens;
o.draft_tokens = m.draft_tokens; o.draft_accepted = m.draft_accepted;
o.draft_refills = m.draft_refills; o.draft_refill_tokens = m.draft_refill_tokens;
o.linear_hit_rate = m.linear_hit_rate;
o.attn_cached_tokens = m.attn_cached_tokens;
o.linear_cached_tokens = m.linear_cached_tokens;
o.checkpoints_written = m.checkpoints_written;
o.draft_depth_seen = m.draft_depth_seen;
if (o.draft_depth_seen > SchedMetrics::MAX_DRAFT_POS)
o.draft_depth_seen = SchedMetrics::MAX_DRAFT_POS;
for (int j = 0; j < o.draft_depth_seen; ++j) {
o.draft_pos_reached [j] = m.draft_pos_reached [j];
o.draft_pos_accepted[j] = m.draft_pos_accepted[j];
}
o.draft_adaptive = m.draft_adaptive;
o.draft_depth_adaptive = m.draft_depth_adaptive;
for (size_t d = 0;
d < std::size(m.draft_verify_depth) && d < std::size(o.draft_verify_depth); ++d)
o.draft_verify_depth[d] = m.draft_verify_depth[d];
o.preemptions = m.preemptions;
o.total_requests = m.admitted;
o.steps = m.steps;
o.steps_prefill = m.steps_prefill; o.steps_mixed = m.steps_mixed;
o.steps_decode = m.steps_decode;
o.steps_ahead = m.steps_ahead;
o.prefill_chunks_capped = m.prefill_chunks_capped;
o.steps_held = m.steps_held;
o.decode_rows_unspeculated = m.decode_rows_unspeculated;
o.step_ns = m.step_ns; o.step_ns_decode = m.step_ns_decode;
return o;
}
class SchedulerBridge final : public IScheduler {
public:
/* `sampler` is the rank-0 sampler, and it is optional only so that a caller with no engine
* behind it still compiles. Every rank declares the same chain against the same hierarchy, so
* whether a stage resolved is not a per-rank fact and asking one of them is asking all. */
/* `tiers` is rank 0's IdleTiers, and it is given whether or not a tier can move anything:
* the object holds the session table either way, and a server with no --prefix-cache-mib is
* one whose every stored session is in VRAM rather than one with no sessions. Null only when
* there is no engine behind this at all. */
/* `sampler` is the rank-0 sampler; optional only for callers with no engine. Every rank
* declares the same chain against the same hierarchy, so rank 0 answers for all.
* `tiers` is rank 0's IdleTiers, passed even when no tier can move anything: it holds the
* session table either way (without --prefix-cache-mib every session is in VRAM). Null only
* with no engine. */
explicit SchedulerBridge(Scheduler* s, const Sampler* sampler = nullptr,
const IdleTiers* tiers = nullptr)
: s_(s), sampler_(sampler), tiers_(tiers) {}
@@ -62,33 +157,29 @@ public:
return sampler_->check_request(sp, why);
}
/* Request ids are the server's to allocate: Scheduler::add refuses a duplicate id and does
* not mint one, which is the right split -- the id has to exist before submission so that a
* connection dropped during submission still has something to cancel. */
uint64_t submit(Request&& r) override {
auto p = std::make_unique<Request>(std::move(r));
p->id = next_.fetch_add(1, std::memory_order_relaxed);
const uint64_t id = p->id;
int st = s_->add(std::move(p));
if (st < 0) {
/* Failing here means the request never entered the queue, so nothing will ever finish
* its sink. Tell the sink itself, or the HTTP thread waits forever. */
RAD_WARN("server: scheduler refused request %llu: %s",
(unsigned long long)id, rad_strerror(st));
return 0;
}
return id;
std::vector<Request> one;
one.push_back(std::move(r));
std::vector<uint64_t> ids;
submit_all(one, &ids);
return ids[0];
}
/* The server allocates request ids (Scheduler::add refuses duplicates and mints none), so
* the id exists before submission and a connection dropped mid-submission can cancel it.
* A refused request gets id 0 and a failed sink: it never entered the queue, so nothing
* else would finish the sink, and the HTTP thread waiting on it would hang. */
void submit_all(std::vector<Request>& rs, std::vector<uint64_t>* ids) override {
const size_t n = rs.size();
std::vector<std::unique_ptr<Request>> ps(n);
std::vector<void*> sinks(n);
std::vector<int> rc(n, RAD_OK);
ids->assign(n, 0);
for (size_t i = 0; i < n; ++i) {
ps[i] = std::make_unique<Request>(std::move(rs[i]));
ps[i]->id = next_.fetch_add(1, std::memory_order_relaxed);
(*ids)[i] = ps[i]->id;
sinks[i] = ps[i]->sink;
}
s_->add_all(ps.data(), n, rc.data());
for (size_t i = 0; i < n; ++i) {
@@ -96,6 +187,9 @@ public:
RAD_WARN("server: scheduler refused request %llu: %s",
(unsigned long long)(*ids)[i], rad_strerror(rc[i]));
(*ids)[i] = 0;
/* A stopped engine has already failed the sink with its own reason. */
Sink* k = static_cast<Sink*>(sinks[i]);
if (k && !k->done()) k->fail(rc[i], "the scheduler refused the request");
}
}
@@ -104,15 +198,15 @@ public:
int64_t reset_prefix_cache() override { return s_->reset_prefix_cache(); }
/* THE STORED CONVERSATIONS. Idle time is computed here rather than carried, because the tiers
* keep a monotonic timestamp and a browser wants "how long ago" -- converting at the edge
* means one clock is authoritative and the other never has to be trusted. */
/* The stored conversations. The tiers keep monotonic timestamps; idle and age are converted
* to "seconds ago" here, so only the monotonic clock is authoritative. */
TierCounters tier_counters() const override {
TierCounters c;
if (!tiers_) return c;
const IdleTiers::Stats& s = tiers_->stats();
c.to_host = s.to_host; c.dropped = s.dropped; c.promoted = s.promoted;
c.host_drops = s.host_drops; c.failures = s.failures;
c.held_back = s.held_back;
c.host_bytes = s.host_bytes;
c.restores = s.restores; c.restore_ns = s.restore_ns;
c.flushes = s.flushes; c.flush_ns = s.flush_ns;
@@ -153,10 +247,8 @@ public:
return (int)out->size();
}
/* THE STATE NAME IS DERIVED, not stored: ReqState has no `Prefill`, because to the scheduler
* prefill is not a state -- it is a running request whose prompt is not yet all in the KV.
* That distinction is the single most useful thing this table shows, so it is made here
* rather than left for every reader to reconstruct from two integers. */
/* The state name is derived: ReqState has no `Prefill`, since to the scheduler prefill is a
* running request whose prompt is not yet all in the KV. The table reports it separately. */
int requests(std::vector<RequestStat>* out) const override {
std::vector<Scheduler::ReqStat> raw(256);
const int n = s_->observed_requests(raw.data(), (int)raw.size());
@@ -195,109 +287,11 @@ public:
/* Both read the copy the engine thread publishes (Scheduler::publish), never the
* scheduler's live state: every caller is an observer. */
SchedMetrics metrics() const override {
const rad::SchedMetrics m = s_->observed_metrics();
SchedMetrics o;
o.waiting = m.queue_depth;
o.running = m.running;
o.preempted = m.preempted_waiting;
/* One KV utilisation number, and it is the MAXIMUM over groups rather than the mean. A
* hybrid model has a full-attention group and a linear-state group with different
* geometries (spec §7.2), and exhausting either one preempts -- so the number a dashboard
* should be watching is the closest one to the wall, not the average of it with the one
* that has room.
*
* AND THE TOKEN CAPACITY IS NOT A SUM, for the same reason, which is easier to get wrong
* because the units look additive. PAGED GROUPS SHARE ONE TOKEN AXIS: on Qwen4-Exp
* `kv_attn` and `kv_qsa_bkey` are both 129216 blocks of 4 tokens, and one token of context
* takes a slot in BOTH of them (26.00 KiB + 3.25 KiB a block, 7.31 KiB a token together).
* Adding them would report 1,033,728 tokens of capacity for a pool that holds 516,864 --
* off by exactly the number of paged groups, an error that is invisible on a one-group
* model.
*
* So the figure is the BINDING group's: the one nearest the wall, which is the one that
* decides when the next sequence is preempted, and the same group `kv_util` reports. */
o.kv_util = 0.0;
int bind = -1;
for (int i = 0; i < m.n_kv_groups; ++i) {
if (m.kv[i].block_tokens <= 0) continue; /* a linear state has no token axis */
if (bind < 0 || m.kv[i].utilisation > m.kv[bind].utilisation) bind = i;
}
for (int i = 0; i < m.n_kv_groups; ++i)
o.kv_util = std::max(o.kv_util, (double)m.kv[i].utilisation);
if (bind >= 0) {
const int64_t bt = m.kv[bind].block_tokens;
o.kv_tokens_total = m.kv[bind].blocks_total * bt;
o.kv_tokens_used = (m.kv[bind].blocks_total - m.kv[bind].blocks_free) * bt;
}
/* AND THE WHOLE POOL IN BYTES, WHICH IS THE ONE FIGURE THAT IS A SUM. The paragraph above
* is about why tokens are not: the groups share a token axis. Bytes do not overlap -- each
* group was carved its own extent of the card -- so every group is added here, the
* recurrent ones included, and the answer is how much VRAM the KV cache is holding. */
for (int i = 0; i < m.n_kv_groups; ++i) {
o.kv_bytes_total += m.kv[i].bytes_total;
o.kv_bytes_used += m.kv[i].bytes_used;
o.kv_bytes_carved += m.kv[i].bytes_carved;
if (m.kv[i].block_tokens <= 0 || m.kv[i].window) continue;
const int64_t t = m.kv[i].blocks_total * m.kv[i].block_tokens;
if (o.kv_tokens_max == 0 || t < o.kv_tokens_max) o.kv_tokens_max = t;
}
/* vLLM's gpu_prefix_cache_hit_rate is a single number and attention caching is what it
* has always meant. The linear-checkpoint hit rate is a different measurement at a
* different granularity (spec §7.3) and averaging the two would hide exactly the effect
* the decoupling exists to expose, so it is not folded in here. */
o.prefix_hit_rate = m.attn_hit_rate;
o.prefix_evictions = m.prefix_evictions;
/* WHAT ONLY THE CACHE IS HOLDING -- see SchedMetrics::prefix_held_tokens. Clamped to what
* the pool reports held: they are counted at different moments in a step and a cached
* figure above the used one would draw a negative live share. */
o.kv_tokens_cached = std::min(m.prefix_held_tokens, o.kv_tokens_used);
o.prefix_ckpt_evictions = m.prefix_ckpt_evictions;
o.prefix_expired = m.prefix_expired;
o.prefix_ckpt_expired = m.prefix_ckpt_expired;
o.prefill_tps = m.prefill_tps;
o.decode_tps = m.decode_tps;
o.draft_acceptance = m.draft_acceptance;
o.prefill_tokens = m.prefill_tokens; o.decode_tokens = m.decode_tokens;
o.draft_tokens = m.draft_tokens; o.draft_accepted = m.draft_accepted;
o.draft_refills = m.draft_refills; o.draft_refill_tokens = m.draft_refill_tokens;
o.linear_hit_rate = m.linear_hit_rate;
o.attn_cached_tokens = m.attn_cached_tokens;
o.linear_cached_tokens = m.linear_cached_tokens;
o.checkpoints_written = m.checkpoints_written;
o.draft_depth_seen = m.draft_depth_seen;
if (o.draft_depth_seen > SchedMetrics::MAX_DRAFT_POS)
o.draft_depth_seen = SchedMetrics::MAX_DRAFT_POS;
for (int j = 0; j < o.draft_depth_seen; ++j) {
o.draft_pos_reached [j] = m.draft_pos_reached [j];
o.draft_pos_accepted[j] = m.draft_pos_accepted[j];
}
o.draft_adaptive = m.draft_adaptive;
o.draft_depth_adaptive = m.draft_depth_adaptive;
{
const int ka = (int)(sizeof m.draft_verify_depth / sizeof m.draft_verify_depth[0]);
const int kb = (int)(sizeof o.draft_verify_depth / sizeof o.draft_verify_depth[0]);
for (int d = 0; d < ka && d < kb; ++d) o.draft_verify_depth[d] = m.draft_verify_depth[d];
}
o.preemptions = m.preemptions;
o.total_requests = m.admitted;
o.steps = m.steps;
o.steps_prefill = m.steps_prefill; o.steps_mixed = m.steps_mixed;
o.steps_decode = m.steps_decode;
o.steps_ahead = m.steps_ahead;
o.prefill_chunks_capped = m.prefill_chunks_capped;
o.decode_rows_unspeculated = m.decode_rows_unspeculated;
o.step_ns = m.step_ns; o.step_ns_decode = m.step_ns_decode;
return o;
return bridge_metrics(s_->observed_metrics());
}
private:
/* DECLARED IN CONSTRUCTION ORDER. Members initialise in declaration order whatever the
* initialiser list says, so a list that disagrees with it draws a -Wreorder warning and
* becomes a use-before-initialisation the first time one of these is derived from another. */
/* Declared in the constructor's initialiser order (-Wreorder). */
Scheduler* s_;
const Sampler* sampler_ = nullptr;
const IdleTiers* tiers_ = nullptr;
@@ -332,9 +326,8 @@ public:
std::vector<int32_t> out;
int st = tok_.encode(text, out, add_special, parse_special);
if (st < 0) {
/* The caller checks for an empty result and answers 400. Returning a partial
* tokenisation would be worse than returning none: it is a prompt that is silently
* not the prompt that was sent. */
/* The caller answers 400 on an empty result. A partial tokenisation would silently
* serve a different prompt. */
RAD_WARN("server: tokenise failed: %s", rad_strerror(st));
out.clear();
}
@@ -342,9 +335,8 @@ public:
}
std::string decode(const std::vector<int32_t>& ids) const override {
/* Sanitised for the same reason Detokenizer::push is: a token array naming byte-fallback
* ids need not decode to well-formed UTF-8, and this text is echoed back inside a JSON
* string, where a malformed byte costs the client the whole response. */
/* Sanitised like Detokenizer::push: byte-fallback ids need not decode to valid UTF-8,
* and one malformed byte in a JSON string breaks the whole response. */
return utf8_sanitize(tok_.decode(ids, /*render_special=*/false));
}
int32_t eos() const override { return vocab_->eos(); }
@@ -366,9 +358,8 @@ public:
return i;
}
/* Vocab::text, sanitised: a byte-level BPE piece is a mapped codepoint sequence that is valid
* UTF-8, but a byte-fallback vocabulary's piece need not be, and this goes into a JSON string
* where one malformed byte costs the client the whole response. */
/* Vocab::text, sanitised: a byte-fallback vocabulary's piece need not be valid UTF-8 (a
* byte-level BPE piece always is), and this goes into a JSON string. */
std::string piece(int32_t id) const override {
if (id < 0 || id >= vocab_->n_tokens()) return std::string();
return utf8_sanitize(vocab_->text(id));
@@ -395,25 +386,19 @@ private:
/* ================================================================== chat
*
* THE ONE PLACE THE TWO CHAT INTERFACES MEET. core/text's ChatTemplate renders the prompt and the
* generation prompt; the model's reply format (chatfmt.h) says how the reply is spelled, and
* everything that depends on the spelling -- the grammar, its trigger words, the tokens the
* decoder must render, and the parser that reads the reply back -- is derived from that one
* description here. Two decisions worth stating:
* core/text's ChatTemplate renders the prompt and generation prompt. The model's reply format
* (chatfmt.h) says how the reply is spelled, and everything depending on the spelling (grammar,
* trigger words, tokens the decoder must render, the reply parser) is derived from it here.
*
* * `preserved_tokens` IS CARRIED, and the reason is not the one it has upstream. Upstream it
* stops a sampler that bans special tokens from banning the ones a tool-call format is made
* of; this sampler has no ban stage at all (core/sample/sampler.h), so there is nothing to
* preserve them FROM. It is carried because the DECODER suppresses control tokens, and a
* format can be built out of them -- MiniCPM5 writes `<function`, `<param` and their closers
* as control tokens, so a reply decoded the ordinary way reaches the parser as ` name="get
* _weather"> name="city">Berlin`, every tag gone, and comes back to the client as prose.
* These, and only these, are decoded as text. If a ban stage is ever added it wants this
* same field, for the original reason.
* * `preserved_tokens` lists control tokens the decoder must render as text. The decoder
* suppresses control tokens, and some formats are built from them: MiniCPM5 writes
* `<function`, `<param` and their closers as control tokens, so without this the parser
* sees no tags and the call reaches the client as prose. (Upstream the field protects them
* from a sampler ban stage; this sampler has none, core/sample/sampler.h.)
*
* * THE PARSER IS BUILT PER RENDER and handed over behind IReplyParser. A server-wide parser
* cannot be correct: which arguments are JSON depends on the schemas THIS request sent, and
* whether the reply starts inside a reasoning block depends on THIS generation prompt.
* * The parser is built per render, behind IReplyParser: which arguments are JSON depends on
* this request's tool schemas, and whether the reply starts inside a reasoning block on this
* generation prompt.
*/
class ReplyReaderBridge final : public IReplyReader {
public:
@@ -430,10 +415,9 @@ public:
void finish(std::vector<ReplyDelta>* out) override {
s_->finish(out ? &ev_ : nullptr);
move_out(out);
/* A reply that left the grammar still came back whole -- a call to a function that is
* not a tool, text inside a call, a call after a closing sentence -- but it is worth a
* line: it is either a model writing its format loosely or a format described wrongly,
* and nothing in the response says which. */
/* A reply outside the format (a call to an unknown function, text inside a call, a call
* after closing prose) is still returned whole, but logged once: either the model writes
* its format loosely or the format is described wrongly. */
if (!s_->strict() && !warned_) {
warned_ = true;
RAD_WARN("server: a reply left the '%s' reply format and was read by its recovery "
@@ -495,13 +479,11 @@ private:
class ChatTemplateBridge final : public IChatTemplate {
public:
/* Returns RAD_OK, or the status ChatTemplate::load_from_vocab gave. A server whose template
* did not compile must not be wired: the endpoint answering 501 is a better outcome than one
* answering 200 with ChatML-shaped nonsense.
/* Returns RAD_OK, or ChatTemplate::load_from_vocab's status. A server whose template did not
* compile must not wire it: a 501 beats a 200 with ChatML-shaped nonsense.
*
* `declared` is the architecture plugin's reply format (rad_arch_chat_format), or null to
* derive it from the template. A declaration the parser cannot run is refused here, at
* startup, rather than at the first request that needs it. */
* derive it from the template. A declaration the parser cannot run is refused at startup. */
int init(const Vocab& v, const RadChatFormat* declared = nullptr,
const std::string& plugin = std::string()) {
/* The spellings, resolved once. See ReplyOptions::terminators. */
@@ -587,9 +569,8 @@ public:
ChatPrompt p;
const int st = t_.apply(messages, tools, o, &p);
if (st < 0) {
/* THE TEMPLATE'S OWN SENTENCE WHERE THERE IS ONE. A jinja `raise_exception` names the
* field and the values it accepts; the generic line below names neither, and a caller
* reading a 400 has no other way to find out. */
/* Prefer the template's own message: a jinja `raise_exception` names the field and
* its accepted values, which the generic lines below do not. */
if (why)
*why = !p.error.empty()
? p.error
@@ -680,9 +661,8 @@ private:
/* ================================================================== grammar
*
* Compiles at ADMISSION, not at first token, so a schema that cannot be compiled is a 400 naming
* it rather than a request that starts and then dies on the step path -- and so the scheduler
* thread never compiles one.
* Compiles at admission, not at first token, so an uncompilable schema is a 400 rather than a
* request that fails on the step path, and the scheduler thread never compiles.
*/
class GrammarBridge final : public IGrammarCompiler {
public:
@@ -692,9 +672,8 @@ public:
return grammar_from_json_schema(schema.dump(), "root", &out, &err);
}
/* The whole compile -- parse, checks and mask plan -- on the admission thread. The program
* goes back to ride on the request; the sampler finds it by its text when the request starts,
* for as long as the request holds it. */
/* The whole compile (parse, checks, mask plan) runs on the admission thread. The program
* rides on the request; the sampler finds it by its text while the request holds it. */
int compile(const std::string& gbnf, std::shared_ptr<const GbnfProgram>* out,
std::string& err) const override {
if (gbnf.empty()) return RAD_OK;
@@ -706,10 +685,9 @@ private:
const VocabView* v_;
};
/* MEDIA, through the processor the container describes (core/mm). Present only when the program
* declared an encoder: `accepts` answers from what that encoder said it serves, so a request for
* video against an image-only tower is refused by the server with a reason rather than processed
* into patches nothing can encode. */
/* Media, through the container's processor (core/mm). Present only when the program declares an
* encoder; `accepts` follows the modalities that encoder serves, so e.g. video against an
* image-only tower is refused with a reason instead of processed into unencodable patches. */
class MultimodalBridge final : public IMultimodal {
public:
MultimodalBridge(const mm::Processor* p, uint32_t modalities) : p_(p), mod_(modalities) {}
@@ -732,6 +710,30 @@ public:
: p_->video(bytes.data(), bytes.size(), out, why);
}
int32_t audio_rate() const override {
return accepts(MediaKind::Audio) ? p_->audio_config().rate : 0;
}
int64_t audio_max_samples() const override {
return accepts(MediaKind::Audio) ? p_->audio_config().max_samples : 0;
}
int decode_audio(const std::vector<uint8_t>& bytes, int64_t max_samples,
std::vector<float>* out, std::string* why) override {
if (!accepts(MediaKind::Audio)) { if (why) *why = "audio is not served"; return RAD_E_UNSUPPORTED; }
/* One sample past the bound is decoded, so a longer file is refused rather than cut. */
RAD_TRY(mm::decode_audio(bytes.data(), bytes.size(), p_->audio_config().rate,
max_samples + 1, out, why));
if ((int64_t)out->size() > max_samples) {
if (why) *why = "the recording is longer than this server transcribes";
return RAD_E_INVAL;
}
return RAD_OK;
}
int prepare_audio(const std::vector<float>& samples, std::shared_ptr<mm::Item>* out,
std::string* why) override {
if (!accepts(MediaKind::Audio)) { if (why) *why = "audio is not served"; return RAD_E_UNSUPPORTED; }
return p_->audio_from(samples, out, why);
}
private:
const mm::Processor* p_;
uint32_t mod_;
+73 -133
View File
@@ -1,20 +1,15 @@
/* core/server/admin.cpp -- vLLM's and llama-server's non-generation endpoints.
*
* /version /ping /load /tokenize /detokenize /get_tokenizer_info /server_info /reset_prefix_cache
* /props.
* /props /diagnostics.
*
* Separate from server.cpp because none of it touches the step path: no admission, no Sink, no
* cancellation, nothing that outlives the handler. They are questions ABOUT the server, answered
* on the HTTP thread and finished before they return, and mixing them into the file that owns the
* streaming lifetime would make that file harder to read for no shared code at all.
* None of these touch the step path (no admission, no Sink, no cancellation); each is answered on
* the HTTP thread before it returns, so they are kept out of server.cpp.
*
* WHAT IS DELIBERATELY NOT HERE. vLLM's surface also carries /pooling, /classify, /score and
* /rerank (a classifier or cross-encoder head, which this engine does not load), /sleep, /wake_up
* and /is_sleeping (there is no sleep mode: weights are placed once, see spec §5), the LoRA
* adapter endpoints (no LoRA), /invocations (a SageMaker envelope around the others) and the
* Responses API's stored responses (retrieved or deleted by id: a conversation store, which is a
* component and not an endpoint); llama-server's carries /slots (its own slot state). Each would
* be a lie in the shape of a 200, so each is absent and answers 404 rather than pretending.
* Deliberately absent, answering 404: vLLM's /pooling, /classify, /score and /rerank (no
* classifier or cross-encoder head), /sleep, /wake_up and /is_sleeping (no sleep mode; weights
* are placed once, spec §5), the LoRA endpoints (no LoRA), /invocations (a SageMaker envelope),
* stored Responses-API responses (would need a conversation store), and llama-server's /slots.
*/
#include "server.h"
@@ -28,18 +23,12 @@ namespace server {
namespace {
/* The body every "how loaded is this server" answer shares. /health and /ping are the same
* question asked by a load balancer and by a human, and vLLM answers both, so both exist here and
* neither is a redirect to the other -- a probe that follows a redirect is a probe that reports
* the redirect's latency. */
/* `queue_cap` AND NOT `queue_depth`. The value is the CEILING -- `opt_.queue_depth` or
* max_seqs * 8 -- and it never changes while the server runs. Spelling it "queue_depth" would
* collide head-on with `radiance:http_queue_depth`, which is the OCCUPANCY ("admitted by the HTTP
* layer and not yet finished"): one name for two opposite quantities on the same server, so a
* dashboard graphing both plots a flat ceiling beside a number that moves and calls them the same
* thing. `queue_depth` therefore means occupancy everywhere it appears, and the occupancy is
* carried here too under its own names -- `in_flight` on /health and /server_info, `server_load`
* on /load. */
/* The body /health and /ping share. vLLM answers both, and neither redirects to the other, so a
* probe never measures a redirect.
*
* `queue_cap` is the admission ceiling (`opt_.queue_depth` or max_seqs * 8), fixed while the
* server runs. It is not called `queue_depth` because `radiance:http_queue_depth` is the occupancy;
* the occupancy appears here as `in_flight` (and as `server_load` on /load). */
json health_body(const std::string& model, bool stopping, int64_t in_flight, int64_t depth) {
json o;
o["status"] = stopping ? "stopping" : "ok";
@@ -49,35 +38,15 @@ json health_body(const std::string& model, bool stopping, int64_t in_flight, int
return o;
}
/* nlohmann parses "3" and "[1,2]" happily, and both are the wrong shape for every endpoint here.
* Checking is_object() at the door means each handler's field reads can be plain rather than each
* one re-deciding what a non-object body means. Bounded like the generation endpoints' bodies
* (parse_json_bounded): /detokenize takes a token array, which is the body that grows most. */
bool parse_object(const std::string& body, int64_t max_ctx, json* out, ApiError* err) {
*out = json::object();
if (body.empty()) return true; /* {} -- every field takes its default */
bool over = false, deep = false;
json j = parse_json_bounded(body, max_ctx, &over, &deep);
if (deep) {
*err = err_bad("body", "the request body nests more than " +
std::to_string(kJsonMaxDepth) + " levels deep");
return false;
/* Parses a body that must be a JSON object (an empty body is {}, so every field takes its
* default). Bounded like a generation body (parse_request_object), since /detokenize takes a
* token array of any length. */
bool parse_object(const std::string& body, const OaiLimits& lim, json* out, ApiError* err) {
if (body.empty()) {
*out = json::object();
return true;
}
if (over) {
*err = err_bad("body", "the request body holds more than " +
std::to_string(json_value_budget(max_ctx)) + " JSON values");
return false;
}
if (j.is_discarded()) {
*err = err_bad("body", "the request body is not valid JSON");
return false;
}
if (!j.is_object()) {
*err = err_bad("body", "the request body must be a JSON object");
return false;
}
*out = std::move(j);
return true;
return parse_request_object(body, lim, out, err) == RAD_OK;
}
bool get_bool_or(const json& b, const char* key, bool def) {
@@ -88,10 +57,8 @@ bool get_bool_or(const json& b, const char* key, bool def) {
} /* namespace */
/* ================================================================== /version */
/* vLLM answers {"version": "..."} and a client that checks compatibility reads exactly that key,
* so it keeps the name and the shape. The rest is what this engine is, and it is here rather than
* in /server_info because a client deciding whether to talk to us at all should not have to ask
* for the whole configuration to find out which ABI the kernels were built against. */
/* vLLM's {"version": "..."}, which compatibility checks read, plus the engine name and kernel ABI
* version so a client need not fetch the whole /server_info for them. */
HttpResponse Server::handle_version(const HttpRequest&) {
json o;
o["version"] = opt_.version;
@@ -102,10 +69,8 @@ HttpResponse Server::handle_version(const HttpRequest&) {
}
/* ================================================================== /load */
/* vLLM's key is `server_load` and it means requests admitted and not yet finished -- which is
* this server's `in_flight`, the same number admission control refuses on. `queue_cap` comes
* along because a load figure without its ceiling cannot answer the question a load balancer is
* actually asking, which is "how much room is left". */
/* vLLM's `server_load`: requests admitted and not yet finished, i.e. `in_flight`, which admission
* control refuses on. `queue_cap` is included so a load balancer can tell how much room is left. */
HttpResponse Server::handle_load(const HttpRequest&) {
json o;
o["server_load"] = in_flight_.load(std::memory_order_relaxed);
@@ -120,18 +85,13 @@ HttpResponse Server::handle_load(const HttpRequest&) {
}
/* ================================================================== /tokenize */
/* Two request shapes under one path, exactly as vLLM has it: `prompt` is the completion form and
* `messages` is the chat form, which renders the template first and tokenises what it produced.
/* vLLM's two request shapes: `prompt` (completion form) and `messages` (chat form, rendered
* through the template, then tokenised), plus llama-server's `content`.
*
* `add_special_tokens` DEFAULTS DIFFERENTLY BETWEEN THEM, and that is not an inconsistency to
* tidy away: a raw prompt wants BOS prepended because nothing else will, while a rendered chat
* template already contains whatever opening the model expects, and adding another is a prompt
* with two beginnings. vLLM's defaults are true and false respectively for that reason.
*
* PARSE_SPECIAL IS NOT THE CALLER'S CHOICE. The chat form tokenises a string this server rendered
* and its control tokens must be recognised as themselves; the completion form tokenises text the
* caller sent, where they must NOT be, or a caller who writes "<|im_start|>system" into `prompt`
* finds out what this endpoint's token ids do to a subsequent /v1/completions. */
* `add_special_tokens` defaults to true for `prompt` and false for `messages`, as in vLLM: a raw
* prompt needs BOS prepended, while a rendered template already contains the model's opening.
* `parse_special` is not the caller's choice: each form tokenises exactly as /v1/completions or
* /v1/chat/completions would, so the count matches what that endpoint sees. */
HttpResponse Server::handle_tokenize(const HttpRequest& req) {
if (!deps_.tok)
return error_response(err_not_implemented("the server has no tokenizer attached"),
@@ -139,7 +99,7 @@ HttpResponse Server::handle_tokenize(const HttpRequest& req) {
json b;
ApiError err;
if (!parse_object(req.body, opt_.max_ctx, &b, &err)) return error_response(err, req.peer);
if (!parse_object(req.body, lim_, &b, &err)) return error_response(err, req.peer);
const bool want_strs = get_bool_or(b, "return_token_strs", false);
std::vector<int32_t> toks;
@@ -151,11 +111,9 @@ HttpResponse Server::handle_tokenize(const HttpRequest& req) {
return error_response(err_bad("prompt", "send one of `prompt`, `messages` or `content`"),
req.peer);
/* THE THIRD SHAPE IS llama-server's: `content` -- a string, or strings and token ids mixed,
* as its /completion takes a prompt -- with its own two flags and its own defaults (no BOS,
* control tokens recognised), answered under its own key, `tokens`, as ids or with
* `with_pieces` as {id, piece} objects. A piece that is not whole UTF-8 is its bytes, as
* llama-server sends it. */
/* llama-server's shape: `content` is a string, or strings and token ids mixed (as its
* /completion prompt), with its own flags and defaults (no BOS, control tokens recognised).
* Answered as `tokens`: ids, or with `with_pieces` {id, piece} objects. */
if (cont != b.end()) {
const bool add_special = get_bool_or(b, "add_special", false);
const bool parse_special = get_bool_or(b, "parse_special", true);
@@ -256,8 +214,8 @@ HttpResponse Server::handle_tokenize(const HttpRequest& req) {
}
/* ================================================================== /detokenize */
/* vLLM's response key is `prompt` -- not `text` -- because the endpoint's purpose is to show what
* a token array would arrive as. The name is odd and it is the name clients read. */
/* vLLM's response key is `prompt`, not `text` (the text a token array would arrive as); clients
* read that name. */
HttpResponse Server::handle_detokenize(const HttpRequest& req) {
if (!deps_.tok)
return error_response(err_not_implemented("the server has no tokenizer attached"),
@@ -265,7 +223,7 @@ HttpResponse Server::handle_detokenize(const HttpRequest& req) {
json b;
ApiError err;
if (!parse_object(req.body, opt_.max_ctx, &b, &err)) return error_response(err, req.peer);
if (!parse_object(req.body, lim_, &b, &err)) return error_response(err, req.peer);
auto t = b.find("tokens");
if (t == b.end() || !t->is_array())
@@ -292,19 +250,17 @@ HttpResponse Server::handle_detokenize(const HttpRequest& req) {
}
/* ================================================================== /props */
/* llama-server's /props, for the clients built against it: a front-end that sizes its context
* from default_generation_settings.n_ctx, shows an image button when modalities.vision is set,
* and reads what a request that sends no sampler fields inherits. /server_info says all of it and
* more, but nothing written for llama-server knows to ask there.
/* llama-server's /props, for clients built against it: front-ends size their context from
* default_generation_settings.n_ctx, show an image button for modalities.vision, and read the
* default sampler settings. /server_info has all of it, but llama-server clients do not ask there.
*
* Only what this server can fill honestly, under llama-server's names: no GGUF metadata, no
* per-slot state. n_ctx is the context ONE request may use, which is what llama-server's per-slot
* n_ctx means to the clients reading it; left out when the server does not know its length. */
* per-slot state. n_ctx is the context one request may use (llama-server's per-slot n_ctx);
* omitted when the context length is unknown. */
HttpResponse Server::handle_props(const HttpRequest&) {
const SamplingParams& sp = opt_.default_sampling;
/* EVERY FIELD llama-server's `params` CARRIES, so a client that reads one does not find it
* missing. The samplers this server does not run are reported at their off values -- which
* is what it serves -- and `samplers` is its own order, temperature first. */
/* Every field llama-server's `params` carries, so no client finds one missing. Samplers this
* server does not run are reported at their off values, which is what it serves. */
const int64_t n_predict = opt_.default_max_tokens > 0 ? opt_.default_max_tokens : -1;
json params;
params["n_predict"] = n_predict;
@@ -329,9 +285,8 @@ HttpResponse Server::handle_props(const HttpRequest&) {
params["dry_base"] = sp.dry_base;
params["dry_allowed_length"] = sp.dry_allowed_length;
params["dry_penalty_last_n"] = sp.dry_penalty_last_n;
params["dry_sequence_breakers"] = sp.dry_seq_breakers.empty() && !opt_.default_dry_breakers_set
? std::vector<std::string>{ "\n", ":", "\"", "*" }
: sp.dry_seq_breakers;
params["dry_sequence_breakers"] = dry_breakers(sp.dry_seq_breakers,
opt_.default_dry_breakers_set);
params["mirostat"] = 0;
params["mirostat_tau"] = 5.0;
params["mirostat_eta"] = 0.1;
@@ -395,10 +350,9 @@ HttpResponse Server::handle_props(const HttpRequest&) {
}
/* ================================================================== /get_tokenizer_info */
/* vLLM returns the HuggingFace tokenizer config verbatim, which this engine does not have: a .rad
* container carries a normalised vocabulary and not the JSON it was built from. So this answers
* the questions that config is actually READ for -- how big is the vocabulary, which ids end a
* generation, is a chat template available -- and says nothing it would have to invent. */
/* vLLM returns the HuggingFace tokenizer config verbatim, which a .rad container does not carry
* (it holds a normalised vocabulary). This answers what that config is read for: vocabulary size,
* the special ids, and whether a chat template is available. */
HttpResponse Server::handle_tokenizer_info(const HttpRequest& req) {
if (!deps_.tok)
return error_response(err_not_implemented("the server has no tokenizer attached"),
@@ -429,8 +383,8 @@ json Server::capabilities() const {
caps["chat"] = deps_.chat != nullptr;
caps["tools"] = deps_.chat && deps_.chat->supports_tools();
caps["reasoning"] = deps_.chat && deps_.chat->supports_reasoning();
/* An image model reads pictures for its edits and nothing else, and writes no text a grammar
* could constrain -- whatever its conditioning network's processor would take. */
/* An image model reads pictures only for edits and writes no text a grammar could constrain,
* whatever its conditioning network's processor would take. */
const bool img = opt_.image_model;
caps["grammar"] = !img && deps_.grammar != nullptr;
caps["embedding"] = deps_.embed != nullptr;
@@ -440,8 +394,8 @@ json Server::capabilities() const {
caps["logprobs"] = opt_.supports_logprobs;
caps["image_generation"] = deps_.images != nullptr;
caps["image_edit"] = deps_.images != nullptr && deps_.images->info().max_refs > 0;
/* THE EFFORTS A CHAT REQUEST MAY SEND, as probed from the template at startup: null when it
* takes any word. "none" and "minimal" are this server's, and turn thinking off. */
/* The efforts a chat request may send, probed from the template at startup; null when it
* takes any word. "none" and "minimal" are this server's and turn thinking off. */
if (lim_.reasoning_efforts.empty()) {
caps["reasoning_efforts"] = nullptr;
} else {
@@ -453,14 +407,10 @@ json Server::capabilities() const {
}
/* ================================================================== /server_info */
/* vLLM returns the repr() of its config object, which is a Python string a client can only print.
* This returns the same information as JSON, in two halves: what the SERVER decided, which is
* this component's own state, and what the ENGINE decided, which arrives pre-rendered because the
* server knows nothing about devices, containers or placement (ServerOptions::engine_info).
*
* `endpoints` is the router's own table rather than a list kept beside it. A hand-written list is
* a list that goes stale the first time somebody adds a route, and this endpoint exists precisely
* so that a client does not have to guess what is served. */
/* vLLM returns the repr() of its config; this returns the information as JSON: the server's own
* state, plus the engine's, pre-rendered because the server knows nothing about devices,
* containers or placement (ServerOptions::engine_info). `endpoints` is the router's own table, so
* it cannot go stale. */
HttpResponse Server::handle_server_info(const HttpRequest&) {
json srv;
srv["model"] = opt_.model_id;
@@ -480,8 +430,7 @@ HttpResponse Server::handle_server_info(const HttpRequest&) {
json caps = capabilities();
/* 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. */
/* What a request that omits a field gets, under the request's own field names. */
const SamplingParams& sp = opt_.default_sampling;
json defs;
defs["temperature"] = sp.temp;
@@ -497,9 +446,8 @@ HttpResponse Server::handle_server_info(const HttpRequest&) {
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["dry_sequence_breakers"] = dry_breakers(sp.dry_seq_breakers,
opt_.default_dry_breakers_set);
defs["xtc_probability"] = sp.xtc_probability;
defs["xtc_threshold"] = sp.xtc_threshold;
defs["max_tokens"] = srv["default_max_tokens"];
@@ -524,10 +472,8 @@ HttpResponse Server::handle_server_info(const HttpRequest&) {
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
* this component is a pipe for it. A blob that is not an object is dropped with a warning
* instead of corrupting the response -- an unparseable /server_info is worse than one that is
* missing a section. */
/* Spliced in whole; the engine owns its contents. A blob that is not a JSON object is dropped
* with a warning rather than corrupting the response. */
if (!opt_.engine_info.empty()) {
json e = json::parse(opt_.engine_info, nullptr, false);
if (e.is_discarded() || !e.is_object())
@@ -540,13 +486,10 @@ HttpResponse Server::handle_server_info(const HttpRequest&) {
}
/* ================================================================== /diagnostics */
/* The startup report, read again for this request (ServerOptions::diagnostics_json). Behind the
* bearer key like /server_info: it names the machine's devices and boot parameters.
*
* AND WITHOUT A KEY, ONLY TO THIS MACHINE. /server_info without a key describes the model a
* client is already talking to; this describes the host -- its kernel, its boot parameters, its
* PCI layout, its memory limits -- which a server bound to 0.0.0.0 with no key would otherwise
* hand to anyone who can reach the port. A key is the operator's statement of who may ask. */
/* The startup report, regenerated per request (ServerOptions::diagnostics_json), behind the API
* key like /server_info. Without a key it is served to loopback clients only: it describes the
* host (kernel, boot parameters, PCI layout, memory limits), which a keyless server bound to
* 0.0.0.0 would otherwise hand to anyone who can reach the port. */
HttpResponse Server::handle_diagnostics(const HttpRequest& req) {
if (!opt_.diagnostics_json)
return error_response(err_not_implemented(
@@ -556,9 +499,8 @@ HttpResponse Server::handle_diagnostics(const HttpRequest& req) {
ApiError e;
e.status = 403;
e.type = "permission_error";
e.message = "/diagnostics describes this machine, and a server started without --api-key "
"answers it only to a client on the same machine (a loopback address); start "
"it with --api-key to read it from elsewhere";
e.message = "without --api-key, /diagnostics answers only loopback clients; start the "
"server with --api-key to read it from elsewhere";
return error_response(e, req.peer);
}
metrics_.observe_http(200);
@@ -566,9 +508,8 @@ HttpResponse Server::handle_diagnostics(const HttpRequest& req) {
}
/* ================================================================== /reset_prefix_cache */
/* 501 when there is no prefix cache to reset, and that is the point: vLLM answers 200 with an
* empty body whether or not anything happened, so a benchmark that thinks it started cold has no
* way to find out it did not. This says how many entries went. */
/* 501 when there is no prefix cache to reset (vLLM answers 200 regardless, so a benchmark cannot
* tell whether it started cold). Reports how many entries were dropped. */
HttpResponse Server::handle_reset_prefix_cache(const HttpRequest& req) {
if (!deps_.sched)
return error_response(err_not_implemented("the server has no engine attached"), req.peer);
@@ -586,9 +527,8 @@ HttpResponse Server::handle_reset_prefix_cache(const HttpRequest& req) {
}
/* ================================================================== /health, /ping */
/* NOT counted in the HTTP status metrics, and neither is /metrics. A load balancer probing every
* second would otherwise dominate `request_success_total` and make the 2xx/5xx ratio a statement
* about the probe rather than about the service. */
/* Not counted in the HTTP status metrics (nor is /metrics): a load balancer probing every second
* would dominate the 2xx/5xx ratio. */
HttpResponse Server::handle_health(const HttpRequest& req) { return handle_ping(req); }
HttpResponse Server::handle_ping(const HttpRequest&) {
+92 -120
View File
@@ -1,22 +1,16 @@
/* core/server/dashboard.cpp -- the web view of a running engine.
*
* Two routes: `/` serves a page, `/stats` serves the JSON it polls. Nothing else, and no
* framework: the page is a string literal in this file, so there is no asset directory to install,
* no build step that can go stale against the binary, and no network fetch at all. This engine is
* deployed on machines with no route to a CDN, and a dashboard that renders blank without one is
* a dashboard that does not exist.
* `/` serves the page and `/stats` the JSON it polls (plus `/sessions` and `/graph`). No
* framework: the page is a string literal in this file, so there is no asset directory, no build
* step that can go stale against the binary, and no network fetch; the engine runs on machines
* with no route to a CDN.
*
* WHY IT IS NOT JUST /metrics. Prometheus exposition is the right answer for an operator who has
* a Prometheus, and this server serves it. It is the wrong answer for the question
* being asked here -- "what is this process doing right now" -- because getting to that answer
* costs a scrape config, a time-series database and a Grafana dashboard somebody has to build.
* The engine already has a terminal view for exactly this (liveview.h, spec §16); this is the
* same snapshot in a browser, which is where it can be looked at from another machine.
* /metrics serves Prometheus, but answering "what is this process doing right now" from it needs a
* scrape config, a time-series database and a Grafana dashboard. This is the terminal view's
* snapshot (liveview.h, spec §16) in a browser, viewable from another machine.
*
* THE PER-POSITION DRAFT PANEL IS THE POINT. Everything else here is visible in some other tool.
* The conditional acceptance at each draft position is not: it is in SchedMetrics and in /metrics
* as a labelled gauge, and no ordinary reading of either shows that one late position collapsed
* while the pooled rate stayed plausible. As a bar chart it is the first thing seen.
* The per-position draft panel shows what no pooled metric does: one late draft position
* collapsing while the pooled acceptance rate stays plausible.
*/
#include "server.h"
@@ -30,22 +24,17 @@ namespace rad {
namespace server {
/* ================================================================== /stats */
/* One object, polled. It carries the scheduler's metrics, the per-position draft table and
* whatever the engine's snapshot function could see -- and it is deliberately NOT a stable
* public API: /metrics is that, with vLLM's names, and this is free to say whatever the page
* needs. A client automating against radiance should scrape /metrics.
/* One polled object: the scheduler's metrics, the per-position draft table and whatever the
* engine's snapshot function provides. Not a stable public API; automation should scrape /metrics.
*
* DERIVED RATES ARE THE PAGE'S JOB, not this handler's. Tokens a second and milliseconds a step
* are differences of counters over wall time, and the browser has both endpoints of the interval
* while this handler has neither -- computing them here would mean holding per-client state for
* something the client can subtract. */
* Derived rates are the page's job: they are counter differences over wall time, and only the
* browser holds both ends of its poll interval. Computing them here would need per-client state. */
/* ------------------------------------------------------------------ /sessions
*
* ITS OWN ROUTE, not a field in /stats. The dashboard polls /stats every second and a stored
* session changes on the scale of its idle thresholds -- tens of seconds at the fastest. Folding
* a table of conversations into the per-second poll would carry the same bytes a hundred times
* for each change in them, and the view that reads it is not even on screen most of the time. */
* A separate route, not a /stats field: /stats is polled every second, while a stored session
* changes on the scale of its idle thresholds (tens of seconds at the fastest), and the view that
* reads this is usually off screen. */
HttpResponse Server::handle_sessions(const HttpRequest&) {
json o;
std::vector<SessionStat> v;
@@ -67,9 +56,8 @@ HttpResponse Server::handle_sessions(const HttpRequest&) {
e["on_device"] = s.on_device;
e["on_host"] = s.on_host;
e["moving"] = s.moving;
/* THE RECURRENT HALF. On a hybrid model a session's attention blocks are only part of
* what it needs back; the rest is its linear-state snapshots, which are a different size
* of object in a different store, in host memory. */
/* On a hybrid model a session also needs its linear-state snapshots back: a different
* object size, kept in a separate store in host memory. */
e["snapshots"] = s.snapshots;
e["snap_bytes"] = s.snap_bytes;
e["resume_tokens"] = s.resume_tokens;
@@ -79,19 +67,15 @@ HttpResponse Server::handle_sessions(const HttpRequest&) {
bytes += s.bytes;
}
o["sessions"] = std::move(a);
/* SAID HERE SO A READER DOES NOT HAVE TO INFER IT. Two sessions sharing a system prompt share
* the blocks for it, so these per-session sizes overlap and adding them up over-counts -- on
* a server carrying long agent transcripts by more than an order of magnitude. The field
* names say so rather than pretending the sums are totals. */
/* Sessions sharing a prefix share its blocks, so these sums over-count (by more than an order
* of magnitude with long agent transcripts); the field names say so. */
o["blocks_sum_overlapping"] = { { "device", dev }, { "host", host } };
o["snapshots_sum_overlapping"] = snaps;
o["bytes_sum_overlapping"] = bytes;
const SchedMetrics sm = deps_.sched ? deps_.sched->metrics() : SchedMetrics{};
/* AND THE ONE FIGURE THAT IS NOT A SUM, because a view about what the conversations cost has
* to be able to say what the card is actually holding. The pool counts a block once however
* many sessions name it, which is the number an operator is asking for and the only one the
* per-session rows cannot be made to yield. One group's, the binding one -- see
* SchedMetrics::kv_tokens_used for why tokens across paged groups are not additive. */
/* What the card actually holds: the pool counts a block once however many sessions name it,
* which the per-session rows cannot yield. Tokens are the binding group's only; see
* SchedMetrics::kv_tokens_used for why paged groups are not additive. */
o["pool"] = { { "tokens_used", sm.kv_tokens_used },
{ "tokens_total", sm.kv_tokens_total },
{ "unshared_tokens", sm.kv_tokens_cached },
@@ -101,31 +85,36 @@ HttpResponse Server::handle_sessions(const HttpRequest&) {
deps_.sched ? deps_.sched->tier_counters() : IScheduler::TierCounters{};
o["moved"] = { { "to_host", c.to_host }, { "dropped", c.dropped },
{ "promoted", c.promoted }, { "host_drops", c.host_drops },
{ "held_back", c.held_back },
{ "failures", c.failures } };
/* THE SNAPSHOT STORE, on a hybrid model: what one snapshot costs and how many the store
* holds. `bytes_each` is 0 on a model with no recurrent state. */
/* Snapshot store on a hybrid model: bytes per snapshot and slot count. `bytes_each` is 0
* on a model with no recurrent state. */
o["snapshot_store"] = { { "bytes_each", c.ck_bytes }, { "slots", c.ck_slots } };
/* WHAT --prefix-cache-ttl TOOK, entries and snapshots, from whichever tier held them. */
/* Entries and snapshots removed by --prefix-cache-ttl, from whichever tier held them. */
o["expired"] = { { "entries", sm.prefix_expired }, { "snapshots", sm.prefix_ckpt_expired } };
/* THE STEP THREAD'S TIME ON THE TIERS: every request waits through it. */
/* Step-thread time spent on tier moves; every request waits through it. */
o["stall"] = { { "restores", c.restores }, { "restore_ms", (double)c.restore_ns / 1e6 },
{ "flushes", c.flushes }, { "flush_ms", (double)c.flush_ns / 1e6 } };
/* AND WHETHER ANY OF IT IS BEING READ. Moving a snapshot and restoring it proves the bytes
* travelled; this is the number that says a lookup then SERVED one. A hybrid server can move
* snapshots all day and still replay from token zero if the checkpoint the restore put back
* is not the one a hit can reach. */
/* Whether restored snapshots are served. A hybrid server can move snapshots and still replay
* from token zero if the restored checkpoint is not one a hit can reach. */
o["linear"] = { { "hit_rate", sm.linear_hit_rate },
{ "cached_tokens", sm.linear_cached_tokens },
{ "checkpoints_written", sm.checkpoints_written } };
/* WHETHER ANYTHING MOVES, which is not whether anything is STORED. A session is recorded
* whether or not it can be demoted, so a non-empty table says only that something is held;
* these say whether a tier exists that can move it. */
{ "checkpoints_written", sm.checkpoints_written },
{ "evictions", { { "retention", sm.prefix_ckpt_retired },
{ "store_full", sm.prefix_ckpt_lru } } },
{ "refused", sm.prefix_ckpt_refused },
{ "hit_cuts", { { "no_snapshot", sm.hit_cut_no_snapshot },
{ "windowed_group", sm.hit_cut_window },
{ "adopt_failed", sm.hit_cut_adopt } } },
{ "hit_cut_tokens", sm.hit_cut_tokens } };
/* Whether a tier exists to move sessions to. A session is recorded whether or not it can be
* demoted, so a non-empty table only says something is held. */
o["tiers"] = { { "host", c.host_on } };
/* WHAT IS OFF THE CARD, counted once -- see SessionOccupancy. */
/* Off-card bytes, counted once; see SessionOccupancy. */
o["occupancy"] = { { "host_bytes", occ.host_bytes },
{ "host_cap_bytes", occ.host_cap_bytes } };
/* THE ATTENTION HIT RATE, for a model with no recurrent state, where it is the whole answer
* to how much of the prompt the cache served. On a hybrid model `linear.hit_rate` is. */
/* The attention hit rate: the whole answer on a model with no recurrent state. On a hybrid
* model, read `linear.hit_rate`. */
o["prefix_hit_rate"] = sm.prefix_hit_rate;
o["enabled"] = c.host_on;
return HttpResponse::json_body(200, json_dump(o));
@@ -148,34 +137,36 @@ HttpResponse Server::handle_stats(const HttpRequest&) {
o["kv_util"] = m.kv_util;
o["kv_tokens_used"] = m.kv_tokens_used;
o["kv_tokens_total"] = m.kv_tokens_total;
/* AND THE PART OF `used` THAT NO RUNNING REQUEST IS READING. Held is held, so a finished
* turn's blocks are in the figure above for exactly as long as the cache keeps them --
* and on a server carrying conversations that is most of a full pool. Without the split
* a cache doing its job and a pool that never releases draw the same bar. */
/* The part of `used` no running request reads: cached blocks of finished turns. Without
* the split, a working cache and a pool that never releases look the same. */
o["kv_tokens_cached"] = m.kv_tokens_cached;
/* THE POOL IN BYTES BESIDE THE POOL IN TOKENS, because they answer different questions and
* only one of them is about the card. Tokens say how much context fits; bytes say how much
* VRAM is being held, which is what a reader comparing the cache against the weights and
* against the card's total is asking. The two are not a unit conversion of each other:
* tokens are the binding paged group's and bytes are every group's, recurrent included. */
/* The pool in bytes beside tokens: tokens say how much context fits, bytes how much VRAM
* is held. Not a unit conversion: tokens are the binding paged group's, bytes are every
* group's, recurrent included. */
o["kv_bytes_used"] = (double)m.kv_bytes_used;
o["kv_bytes_total"] = (double)m.kv_bytes_total;
o["kv_bytes_carved"] = (double)m.kv_bytes_carved;
o["kv_tokens_max"] = m.kv_tokens_max;
o["prefix_hit_rate"] = m.prefix_hit_rate;
/* The leading indicator beside the lagging one: past ~75% kv utilisation the cache
* begins dropping prefixes the next turn wants, and the hit rate only falls once
* that has happened. An agent turn that re-prefills from scratch costs orders of
* magnitude more than one that resumes from the cache. */
/* Leading indicator beside the lagging hit rate: past ~75% kv utilisation the cache
* starts dropping prefixes the next turn wants. */
o["prefix_evictions"] = (double)m.prefix_evictions;
/* THE LINEAR HALF, WHICH THE ATTENTION HIT RATE SAYS NOTHING ABOUT. On a hybrid model a
* prompt can be 100% attention-cached and still re-run every recurrent layer over its
* whole prefix, because the two hit at different granularities. Without these a
* deployment cannot tell whether linear checkpointing is working at all. Zero throughout
* on a model with no recurrent state. */
/* Linear-state caching, separate from the attention hit rate: a hybrid prompt can be
* fully attention-cached and still re-run every recurrent layer over its prefix, since
* the two hit at different granularities. Zero on a model with no recurrent state. */
o["linear_hit_rate"] = m.linear_hit_rate;
o["linear_cached_tokens"] = (double)m.linear_cached_tokens;
o["checkpoints_written"] = (double)m.checkpoints_written;
/* Why snapshots went and why hits reused nothing: on a hybrid model these say why a
* long prompt was prefilled again. `hit_cut_tokens` is the checkpoint shortfall,
* prompt tokens the attention cache held and admission computed again. */
o["ckpt_evictions"] = { { "retention", m.prefix_ckpt_retired },
{ "store_full", m.prefix_ckpt_lru } };
o["ckpt_refused"] = m.prefix_ckpt_refused;
o["hit_cuts"] = { { "no_snapshot", m.hit_cut_no_snapshot },
{ "windowed_group", m.hit_cut_window },
{ "adopt_failed", m.hit_cut_adopt } };
o["hit_cut_tokens"] = (double)m.hit_cut_tokens;
o["prefill_tps"] = m.prefill_tps;
o["decode_tps"] = m.decode_tps;
o["draft_accept"] = m.draft_acceptance;
@@ -186,18 +177,15 @@ HttpResponse Server::handle_stats(const HttpRequest&) {
o["steps_mixed"] = m.steps_mixed;
o["prefill_chunks_capped"] = m.prefill_chunks_capped;
o["steps_decode"] = m.steps_decode;
/* WHAT THE STEPS COST, so the page does not have to divide wall clock by a step count.
* That is the derivation this handler's header calls the page's job, and it is the one
* derivation the page cannot do: the browser's two endpoints bracket the engine's IDLE
* time as well as its work, and an agent client is idle between turns. See
* SchedMetrics::step_ns. */
o["steps_held"] = m.steps_held;
/* Time inside steps. The one rate the page cannot derive: wall clock between polls also
* covers idle time (see SchedMetrics::step_ns). */
o["step_ns"] = m.step_ns;
o["step_ns_decode"] = m.step_ns_decode;
o["rows_unspec"] = m.decode_rows_unspeculated;
/* THE CONDITIONAL RATE AT EACH POSITION, with the reach count beside it. Both are needed
* and neither alone means anything: a position with a rate of 0.0 and a reach of 3 is
* noise, and one with a rate of 0.0 and a reach of 40000 is a broken draft round. */
/* Conditional rate per position with its reach count: a rate of 0.0 over a reach of 3 is
* noise, over a reach of 40000 a broken draft round. */
json pos = json::array();
for (int j = 0; j < m.draft_depth_seen && j < SchedMetrics::MAX_DRAFT_POS; ++j) {
json p;
@@ -209,9 +197,8 @@ HttpResponse Server::handle_stats(const HttpRequest&) {
}
o["draft_positions"] = std::move(pos);
/* THE LIVE REQUEST TABLE. Counters and timestamps, not rates the page could not check:
* `decode_tps` is this request's own average since its first token, which is the number
* that stays meaningful when a request has been running for four minutes. */
/* Live request table: counters and timestamps. `decode_tps` is the request's own average
* since its first token. */
std::vector<RequestStat> rq;
deps_.sched->requests(&rq);
json reqs = json::array();
@@ -237,9 +224,8 @@ HttpResponse Server::handle_stats(const HttpRequest&) {
o["requests"] = std::move(reqs);
}
/* The engine's half. Absent when nothing supplied a snapshot function, in which case the page
* omits the panels rather than drawing zeroes -- an empty VRAM bar reads as "no memory used",
* which is a much worse answer than no bar. */
/* The engine's snapshot. Absent without a snapshot function, and the page then omits those
* panels rather than drawing zeroes (an empty VRAM bar would read as "no memory used"). */
if (deps_.live) {
LiveSnapshot s;
deps_.live(s);
@@ -259,11 +245,8 @@ HttpResponse Server::handle_stats(const HttpRequest&) {
}
o["cards"] = std::move(cards);
/* THE EXPERT PANEL'S DATA. The plane is the picture; everything beside it is what the
* picture cannot say -- how much of the model is resident in BYTES, whether the residency
* is spread across layers or piled into the first ones, and whether the move traffic is
* discovery or thrash. Counted in the engine (liveview.h), not here and not in the page:
* three tallies of one snapshot is three chances to disagree. */
/* Expert panel data (see ExpertPlane in liveview.h). Tallied once in the engine, not here
* or in the page, so all views agree. */
if (s.experts.n_layers > 0 && s.experts.n_experts > 0) {
json e;
e["n_layers"] = s.experts.n_layers;
@@ -273,8 +256,7 @@ HttpResponse Server::handle_stats(const HttpRequest&) {
e["bytes"] = s.experts.total_bytes;
e["movable"] = s.experts.movable;
e["heat"] = s.experts.heat_enabled;
/* One row per tier, named -- the page must not hold its own copy of the enum's order,
* which is the kind of duplication that survives a reordering and then lies. */
/* One named row per tier, so the page holds no copy of the enum's order. */
json tiers = json::array();
for (int t = 0; t < kTierCount; ++t) {
json r;
@@ -309,8 +291,7 @@ HttpResponse Server::handle_stats(const HttpRequest&) {
o["experts"] = std::move(e);
}
/* THE LINK. Cumulative byte counters and nothing derived: both ends of the poll interval
* are in the browser and neither is here, exactly as for step time above. */
/* Link traffic: cumulative byte counters only; the page derives rates. */
if (s.link.present) {
json l;
l["world"] = s.link.world;
@@ -340,21 +321,17 @@ HttpResponse Server::handle_stats(const HttpRequest&) {
}
}
/* No metrics_.observe_http here, and the same reasoning as /health: a page polling twice a
* second would make request_success_total a statement about the dashboard. */
/* Not counted in metrics_.observe_http, as for /health: a page polling twice a second would
* make the request counters describe the dashboard. */
return HttpResponse::json_body(200, json_dump(o));
}
/* ================================================================== /graph */
/* THE DECLARED COMPUTE GRAPH: every op, its bucket table, the kernel that resolved each band, the
* library it came from, the constraints it matched on and the chain it stands in for.
*
* `--debug-graph` prints all of this, but printing it is not the same as being able to look at it:
* the text dump answers the question on a terminal, at startup, on the machine the engine is on.
* This is the same walk (dump_graph_json shares every helper with the text one) served from the
* process that is actually running, which is where the question is usually asked. Static after
* declare, so it is rendered once and handed over. */
/* The declared compute graph: every op, its bucket table, the kernel that resolved each band, its
* library, the constraints it matched and the chain it stands in for. The same walk as
* `--debug-graph` (dump_graph_json shares its helpers), served from the running process. Static
* after declare, so it is rendered once. */
HttpResponse Server::handle_graph(const HttpRequest& req) {
if (!opt_.graph_json)
return error_response(err_not_implemented(
@@ -367,21 +344,16 @@ HttpResponse Server::handle_graph(const HttpRequest& req) {
}
/* ================================================================== the page */
/* One string. It is long, and every alternative is worse: a file on disk is a file that can be
* missing or stale against the binary, a generated header is a build step, and a framework is a
* network fetch. It parses no untrusted input -- every value it renders comes from /stats on the
* same origin and goes in through textContent or a numeric attribute, never innerHTML.
/* One string, so it cannot go missing or stale against the binary and needs no build step or
* network fetch. It parses no untrusted input: every value comes from same-origin /stats and goes
* in through textContent or a numeric attribute, never innerHTML.
*
* IT IS BUILT ONCE AND UPDATED IN PLACE. A dashboard that rebuilds its DOM twice a second lays
* the document out twice a second, drops the reader's text selection every time, and flickers --
* and it does that on the machine the engine is being watched from. Elements are created when
* their SHAPE changes (a different draft depth, a different card count) and after that only
* textContent and one style property are written.
* Built once and updated in place: elements are created only when a panel's shape changes (draft
* depth, card count); after that only textContent and one style property are written. Rebuilding
* the DOM every poll would relayout, flicker and drop the reader's text selection.
*
* The design rules are the terminal view's (spec §16) in a browser: a number nobody sampled is
* blank rather than zero, a section with no data is hidden rather than empty, and nothing moves
* that is not actually changing. Black, one weight, one accent -- the numbers are the content and
* everything else on the page is there to not compete with them. */
* Display rules: an unsampled number is blank, not zero; a section without data is hidden;
* nothing moves that is not changing. Black, one weight, one accent. */
static const char* const kPage = R"HTML(<!doctype html>
<html lang="en"><head>
<meta charset="utf-8">
@@ -2996,8 +2968,8 @@ HttpResponse Server::handle_dashboard(const HttpRequest&) {
r.status = 200;
r.content_type = "text/html; charset=utf-8";
r.body = kPage;
/* No caching: the page and the binary ship together, so a browser holding yesterday's copy
* against today's /stats is a shape mismatch with no symptom other than blank panels. */
/* No caching: the page must match the binary's /stats shape, and a stale copy shows only
* blank panels. */
r.set_header("Cache-Control", "no-store");
return r;
}
+348 -132
View File
@@ -1,8 +1,8 @@
#include "http.h"
#include "rad_internal.h"
#include "text/tokenizer.h"
/* httplib pulls in <thread>, <sys/socket.h> and a great deal else. It is included in exactly this
* translation unit so that nothing above the transport seam pays for it. */
/* httplib pulls in <thread>, <sys/socket.h> and much else; only this unit includes it. */
#include "cpp-httplib/httplib.h"
#include <arpa/inet.h>
@@ -33,6 +33,12 @@ std::string HttpRequest::header(const std::string& k, const std::string& def) co
return it == headers.end() ? def : it->second;
}
const FormPart* HttpRequest::part(const std::string& k) const {
for (const FormPart& p : form)
if (p.name == k) return &p;
return nullptr;
}
std::string HttpRequest::param(const std::string& k, const std::string& def) const {
auto it = params.find(k);
if (it != params.end()) return it->second;
@@ -77,11 +83,9 @@ HttpResponse HttpResponse::text(int status, std::string body) {
/* ------------------------------------------------------------------ target parsing */
/* `+` IS A SPACE IN A QUERY STRING AND A PLUS SIGN IN A PATH. The two halves of a target are
* decoded by different rules: the form encoding that gives `+` its second meaning applies to
* `application/x-www-form-urlencoded` data, which is what a query string is and what a path is
* not. Decoding a path the query's way renames a route -- /v1/models/gpt+4 becomes a request for
* "gpt 4", which resolves to nothing and reports the name it was not asked about. */
/* `+` is a space in a query string and a plus sign in a path: the form encoding
* (application/x-www-form-urlencoded) applies to a query only. Decoding a path the query's way
* would turn /v1/models/gpt+4 into a request for "gpt 4". */
std::string url_decode(const std::string& s, bool plus_is_space) {
std::string out;
out.reserve(s.size());
@@ -137,6 +141,22 @@ void Router::add(std::string method, std::string path, Handler h) {
routes_.push_back(Route{std::move(method), split_path(path), std::move(h)});
}
void Router::socket(std::string path, SocketHandler h) {
sockets_.emplace_back(std::move(path), std::move(h));
}
const SocketHandler* Router::socket_for(const std::string& path) const {
for (const auto& s : sockets_)
if (s.first == path) return &s.second;
return nullptr;
}
std::vector<std::string> Router::socket_routes() const {
std::vector<std::string> out;
for (const auto& s : sockets_) out.push_back(s.first);
return out;
}
std::vector<std::string> Router::routes() const {
std::vector<std::string> out;
for (auto& r : routes_) {
@@ -147,46 +167,87 @@ std::vector<std::string> Router::routes() const {
return out;
}
static std::string error_body(const char* type, const std::string& msg) {
/* Hand-rolled rather than routed through nlohmann, because this is the one error path that
* must work even if the JSON layer is what failed. */
bool anthropic_path(const std::string& path) {
return path == "/v1/messages" || path.rfind("/v1/messages/", 0) == 0;
}
const char* anthropic_error_type(int status) {
return status == 401 ? "authentication_error"
: status == 403 ? "permission_error"
: status == 404 ? "not_found_error"
: status == 413 ? "request_too_large"
: status == 429 ? "rate_limit_error"
: status >= 500 ? "api_error"
: "invalid_request_error";
}
/* A refusal the transport or the router writes itself. `type` is OpenAI's; on an Anthropic path
* the status picks Anthropic's instead. Hand-rolled, not nlohmann: this error path must work even
* if the JSON layer failed. The message can quote a request's decoded path, so bytes that are not
* UTF-8 become U+FFFD; a JSON body must be UTF-8 for a client to parse it. */
static std::string error_body(const std::string& path, int status, const char* type,
const std::string& msg) {
std::string esc;
for (char c : msg) {
for (char c : utf8_sanitize(msg)) {
if (c == '"' || c == '\\') { esc.push_back('\\'); esc.push_back(c); }
else if (c == '\n') esc += "\\n";
else if ((unsigned char)c < 0x20) esc += "?";
else esc.push_back(c);
}
if (anthropic_path(path))
return std::string("{\"type\":\"error\",\"error\":{\"type\":\"") +
anthropic_error_type(status) + "\",\"message\":\"" + esc + "\"}}";
return std::string("{\"error\":{\"message\":\"") + esc + "\",\"type\":\"" + type +
"\",\"param\":null,\"code\":null}}";
}
HttpResponse Router::dispatch(HttpRequest req) const {
auto segs = split_path(req.path);
bool path_matched = false;
const Router::Route* Router::match(const std::string& method, const std::vector<std::string>& segs,
std::map<std::string, std::string>* caps,
bool* path_matched) const {
*path_matched = false;
for (const auto& r : routes_) {
if (r.segs.size() != segs.size()) continue;
std::map<std::string, std::string> caps;
const bool rest = !r.segs.empty() && r.segs.back()[0] == '*';
if (rest ? segs.size() < r.segs.size() : segs.size() != r.segs.size()) continue;
const size_t fixed = rest ? r.segs.size() - 1 : r.segs.size();
std::map<std::string, std::string> c;
bool ok = true;
for (size_t i = 0; i < segs.size(); ++i) {
if (!r.segs[i].empty() && r.segs[i][0] == ':') caps[r.segs[i].substr(1)] = segs[i];
for (size_t i = 0; i < fixed; ++i) {
if (!r.segs[i].empty() && r.segs[i][0] == ':') c[r.segs[i].substr(1)] = segs[i];
else if (r.segs[i] != segs[i]) { ok = false; break; }
}
if (!ok) continue;
path_matched = true;
if (r.method != req.method) continue;
if (rest) {
std::string& v = c[r.segs.back().substr(1)];
for (size_t i = fixed; i < segs.size(); ++i) v += (i > fixed ? "/" : "") + segs[i];
}
*path_matched = true;
if (r.method != method) continue;
if (caps) *caps = std::move(c);
return &r;
}
return nullptr;
}
bool Router::allows(const std::string& method, const std::string& path) const {
bool path_matched = false;
return match(method, split_path(path), nullptr, &path_matched) != nullptr;
}
HttpResponse Router::dispatch(HttpRequest req) const {
bool path_matched = false;
std::map<std::string, std::string> caps;
if (const Route* r = match(req.method, split_path(req.path), &caps, &path_matched)) {
req.params.insert(caps.begin(), caps.end());
return r.h(req);
return r->h(req);
}
if (path_matched)
return HttpResponse::json_body(
405, error_body("invalid_request_error",
405, error_body(req.path, 405, "invalid_request_error",
req.method + " is not allowed on " + req.path));
return HttpResponse::json_body(
404, error_body("not_found_error", "no route for " + req.method + " " + req.path));
404, error_body(req.path, 404, "not_found_error",
"no route for " + req.method + " " + req.path));
}
HttpResponse Router::call(const std::string& method, const std::string& path,
@@ -201,18 +262,16 @@ HttpResponse Router::call(const std::string& method, const std::string& path,
/* ------------------------------------------------------------------ the worker pool */
/* A WORKER FOR EVERY CONNECTION, UP TO A BOUND, STARTED THE MOMENT THE CONNECTION HAS NONE.
/* A worker for every connection, up to a bound, started as soon as a connection has none.
*
* httplib's own ThreadPool starts an extra worker only when it counts no idle one, and a worker
* counts as idle from the moment it is woken until it has taken its job. Two connections arriving
* inside that window leave the second queued with no worker started for it -- and a generation
* holds its worker for minutes, so that connection waits for the next one to arrive or for a
* generation to end. This pool compares the queue with the number of workers free to take from
* httplib's ThreadPool counts a worker as idle from its wake-up until it takes its job, so two
* connections arriving in that window leave the second queued with no new worker, possibly for
* minutes behind a generation. This pool compares the queue with the workers free to take from
* it, so a connection waits only once the pool is at its bound.
*
* `keep` workers stay up; the rest exit after kIdleExit with nothing to do. Past `most` workers,
* `queued` connections may wait (0: any number) and further ones are refused, which httplib
* answers by closing the socket. */
* `keep` workers stay up; the rest exit after kIdleExit idle. Past `most` workers, `queued`
* connections may wait (0: any number) and further ones are refused, which httplib answers by
* closing the socket. */
class ConnectionPool final : public httplib::TaskQueue {
public:
ConnectionPool(size_t keep, size_t most, size_t queued)
@@ -236,8 +295,8 @@ public:
return true;
}
/* Runs what is queued, then joins every worker. Idempotent: httplib calls it and then
* destroys the pool, which calls it again. */
/* Runs what is queued, then joins every worker. Idempotent: httplib calls it, then the
* destructor calls it again. */
void shutdown() override {
std::list<std::thread> live;
{
@@ -254,7 +313,7 @@ public:
private:
static constexpr std::chrono::seconds kIdleExit{5};
/* With m_ held. False when the system will not give us a thread; the job then waits. */
/* With m_ held. False when no thread can be created; the job then waits. */
bool start() {
reap();
try {
@@ -267,8 +326,8 @@ private:
return true;
}
/* With m_ held: join the workers that exited idle. They left m_ before exiting, so this
* waits only for their last instructions. */
/* With m_ held: join the workers that exited idle. They released m_ before exiting, so the
* join is short. */
void reap() {
for (auto& t : finished_) t.join();
finished_.clear();
@@ -325,25 +384,95 @@ HttpTransport::~HttpTransport() { stop(); }
void HttpTransport::stop() { if (impl_) impl_->svr.stop(); }
/* Not before the accept loop is running: until then httplib's stop() has nothing to stop and
* does nothing, so a caller that took the port as "up" and then stopped would wait forever. */
/* 0 until the accept loop runs: before that httplib's stop() is a no-op, and a caller that
* stopped a server it believed up would wait forever. */
int HttpTransport::port() const {
return impl_ && impl_->svr.is_running() ? impl_->port.load() : 0;
}
/* Compares a credential with the key in time independent of where they differ, so a client
* cannot find the key a byte at a time by timing refusals. The length is not secret. */
static bool same_secret(const std::string& got, const std::string& key) {
if (got.size() != key.size()) return false;
unsigned char d = 0;
for (size_t i = 0; i < key.size(); ++i) d |= (unsigned char)(got[i] ^ key[i]);
return d == 0;
}
static void apply(const HttpResponse& r, httplib::Response& res) {
res.status = r.status;
for (auto& h : r.headers) res.set_header(h.first, h.second);
}
/* httplib's WebSocket as a WsConn. Sending from another thread is httplib's own practice -- its
* writes are under a mutex and its heartbeat pings from a thread of its own -- and so is closing
* from one: its heartbeat closes on a pong timeout while the route's thread is reading. */
class HttplibConn final : public WsConn {
public:
explicit HttplibConn(httplib::ws::WebSocket& ws) : ws_(ws) {}
bool read(std::string* msg, bool* binary) override {
const httplib::ws::ReadResult r = ws_.read(*msg);
if (r == httplib::ws::Fail) return false;
*binary = r == httplib::ws::Binary;
return true;
}
bool send(const std::string& text) override { return ws_.send(text); }
void close(int code, const std::string& reason) override {
ws_.close((httplib::ws::CloseStatus)code, reason);
}
private:
httplib::ws::WebSocket& ws_;
};
static std::string lower_ascii(std::string s) {
for (char& c : s) c = (char)std::tolower((unsigned char)c);
return s;
}
/* The API key a browser's socket carries. A browser cannot set a header on a WebSocket, so
* OpenAI's browser clients offer it as a subprotocol, `openai-insecure-api-key.<key>`, beside
* `realtime`; the subprotocol chosen is never that one. Compared in constant time, as the header
* key is. */
static bool offers_key(const std::string& protocols, const std::string& key) {
static const std::string kPrefix = "openai-insecure-api-key.";
size_t i = 0;
while (i <= protocols.size()) {
size_t j = protocols.find(',', i);
if (j == std::string::npos) j = protocols.size();
size_t a = i, b = j;
while (a < b && protocols[a] == ' ') ++a;
while (b > a && protocols[b - 1] == ' ') --b;
if (b - a >= kPrefix.size() && protocols.compare(a, kPrefix.size(), kPrefix) == 0 &&
same_secret(protocols.substr(a + kPrefix.size(), b - a - kPrefix.size()), key))
return true;
i = j + 1;
}
return false;
}
/* httplib's own test for a WebSocket upgrade (RFC 6455 §4.2.1), which it applies before the
* pre-routing handler and does not export. A request it rejects is routed as a plain GET, so the
* pre-routing handler must not leave such a request to httplib either. */
static bool is_socket_upgrade(const httplib::Request& q) {
if (q.method != "GET" || lower_ascii(q.get_header_value("Upgrade")) != "websocket") return false;
if (lower_ascii(q.get_header_value("Connection")).find("upgrade") == std::string::npos)
return false;
const std::string key = q.get_header_value("Sec-WebSocket-Key");
if (key.size() != 24 || key[22] != '=' || key[23] != '=') return false;
static const std::string b64 =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
for (size_t i = 0; i < 22; ++i)
if (b64.find(key[i]) == std::string::npos) return false;
return q.get_header_value("Sec-WebSocket-Version") == "13";
}
int HttpTransport::serve(const Router& router, const TransportOptions& o) {
auto& svr = impl_->svr;
/* A REQUEST LINE LONGER THAN httplib's LINE LIMIT (CPPHTTPLIB_MAX_LINE_LENGTH) GETS NO STATUS.
* Its line reader gives up before the request exists, and no handler, error handler or logger
* runs, so there is nothing here that could answer 414: the connection is closed unanswered.
* With the build's CPPHTTPLIB_REQUEST_URI_MAX_LENGTH equal to that limit, httplib's own 414
* cannot fire either, because a target that long never fits in a line that is read. */
/* A request line longer than CPPHTTPLIB_MAX_LINE_LENGTH is closed with no status: httplib's
* line reader gives up before any handler, error handler or logger runs. The build sets
* CPPHTTPLIB_REQUEST_URI_MAX_LENGTH to the same limit, so httplib's own 414 never fires. */
svr.set_read_timeout(o.read_timeout_s, 0);
svr.set_write_timeout(o.write_timeout_s, 0);
svr.set_keep_alive_timeout(o.keep_alive_timeout_s);
@@ -354,9 +483,9 @@ int HttpTransport::serve(const Router& router, const TransportOptions& o) {
const size_t queued = (size_t)std::max<int64_t>(o.max_queued, 0);
svr.new_task_queue = [nt, most, queued] { return new ConnectionPool((size_t)nt, most, queued); };
/* A handler must never throw across the transport: an exception here closes the connection
* with no body at all, which is the least diagnosable failure a client can get. */
svr.set_exception_handler([](const httplib::Request&, httplib::Response& res,
/* An exception escaping a handler would close the connection with no body; answer 500 with
* an error object instead. */
svr.set_exception_handler([](const httplib::Request& req, httplib::Response& res,
std::exception_ptr ep) {
std::string what = "unhandled exception in handler";
try { std::rethrow_exception(ep); }
@@ -364,40 +493,54 @@ int HttpTransport::serve(const Router& router, const TransportOptions& o) {
catch (...) {}
RAD_ERR("server: %s", what.c_str());
res.status = 500;
res.set_content(error_body("internal_server_error", what), "application/json");
res.set_content(error_body(req.path, 500, "internal_server_error", what),
"application/json");
});
const std::string api_key = o.api_key;
const bool cors = o.cors;
/* The headers a cross-origin client sends: the body type, either form of the API key, and the
* anthropic-version and anthropic-beta headers of Anthropic's clients, which nothing reads. */
static const char* const kCorsHeaders =
"Content-Type, Authorization, X-Api-Key, anthropic-version, anthropic-beta";
static const char* const kCorsMethods = "GET, POST, OPTIONS";
/* Whether a request carries the API key: `Authorization: Bearer` (OpenAI; the scheme is
* case-insensitive, RFC 9110) or `X-Api-Key` (Anthropic, also accepted by llama-server). */
auto key_ok = [api_key](const httplib::Request& hreq) -> bool {
const std::string auth = hreq.get_header_value("Authorization");
const size_t sp = auth.find(' ');
const size_t cred = sp == std::string::npos ? sp : auth.find_first_not_of(' ', sp);
const bool bearer = cred != std::string::npos && sp == 6 &&
std::equal(auth.begin(), auth.begin() + 6, "bearer",
[](char a, char b) {
return std::tolower((unsigned char)a) == b;
});
return (bearer && same_secret(auth.substr(cred), api_key)) ||
same_secret(hreq.get_header_value("X-Api-Key"), api_key);
};
/* What a request must pass before its body is read, so a refused one never has it buffered. */
auto gate = [api_key, cors](const httplib::Request& hreq, httplib::Response& hres) -> bool {
auto gate = [api_key, cors, key_ok](const httplib::Request& hreq,
httplib::Response& hres) -> bool {
if (cors) {
hres.set_header("Access-Control-Allow-Origin", "*");
hres.set_header("Access-Control-Allow-Headers", "Content-Type, Authorization");
hres.set_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
hres.set_header("Access-Control-Allow-Headers", kCorsHeaders);
hres.set_header("Access-Control-Allow-Methods", kCorsMethods);
}
/* THE PROBE PATHS ARE EXEMPT, AND THE DASHBOARD PAGE. A load balancer cannot carry a
* bearer token, so an authenticated /health is a server that reports itself down. The
* page is the one static document the server has: it holds no data, and a browser opening
* it cannot send a header, so it loads and then sends the key on every fetch of data it
* makes. Everything else is guarded. vLLM's middleware guards only paths under /v1,
* leaving /tokenize open, which hands an unauthenticated caller the vocabulary and the
* chat template. This does not. */
/* The probe paths and the dashboard page are exempt. A load balancer cannot send a
* bearer token, and a browser opening the page cannot send a header; the page holds no
* data and sends the key on every data fetch. Everything else is guarded, including
* /tokenize, which vLLM leaves open (it only guards /v1). */
const std::string& p = hreq.path;
if (!api_key.empty() && p != "/health" && p != "/v1/health" && p != "/ping" && p != "/" &&
p != "/dashboard") {
/* `Authorization: Bearer` is OpenAI's spelling and `X-Api-Key` Anthropic's, which
* llama-server takes as well; either one carrying the key is enough. */
const bool ok = hreq.get_header_value("Authorization") == "Bearer " + api_key ||
hreq.get_header_value("X-Api-Key") == api_key;
if (!ok) {
/* Said like every other refusal (Server::error_response), which this one never
* reaches: the gate answers before the router does. */
if (!key_ok(hreq)) {
/* Logged in Server::error_response's format; the gate answers before the router. */
RAD_INFO("req refused from %s:%d -> 401 authentication_error: invalid api key",
hreq.remote_addr.c_str(), hreq.remote_port);
hres.status = 401;
hres.set_content(error_body("authentication_error", "invalid api key"),
hres.set_content(error_body(p, 401, "authentication_error", "invalid api key"),
"application/json");
return false;
}
@@ -408,7 +551,8 @@ int HttpTransport::serve(const Router& router, const TransportOptions& o) {
auto bridge = [&router](const httplib::Request& hreq, std::string body,
httplib::Response& hres, std::vector<FormPart> form = {}) {
HttpRequest req;
req.method = hreq.method;
/* HEAD is GET without the body, which httplib leaves off the wire. */
req.method = hreq.method == "HEAD" ? "GET" : hreq.method;
req.path = hreq.path;
req.body = std::move(body);
req.form = std::move(form);
@@ -428,9 +572,9 @@ int HttpTransport::serve(const Router& router, const TransportOptions& o) {
return;
}
/* Streaming. The provider owns the handler's state via the shared_ptr, because httplib
* keeps it alive past this function; `releaser` is what tells us whether the peer went
* away, and it is the hook cancellation hangs off. */
/* Streaming. The shared_ptr keeps the handler's state alive, because httplib calls the
* provider after this function returns. The releaser reports whether the peer went away
* and is where cancellation hooks in. */
auto st = std::make_shared<HttpResponse>(std::move(res));
hres.set_chunked_content_provider(
st->content_type,
@@ -440,77 +584,148 @@ int HttpTransport::serve(const Router& router, const TransportOptions& o) {
if (!chunk.empty()) {
if (!sink.write(chunk.data(), chunk.size())) return false; /* peer gone */
}
/* The end is done() and true: false cancels the response, and httplib closes a
* connection the client would reuse for its next request. */
if (!more) sink.done();
return more;
return true;
},
[st](bool ok) { if (st->on_close) st->on_close(ok); });
};
for (const auto& sig : router.routes()) {
size_t sp = sig.find(' ');
std::string method = sig.substr(0, sp);
std::string path = sig.substr(sp + 1);
/* ":name" is httplib's own wildcard spelling too, so the pattern carries across. */
if (method == "GET") {
svr.Get(path, [gate, bridge](const httplib::Request& q, httplib::Response& s) {
if (gate(q, s)) bridge(q, q.body, s);
});
continue;
}
/* A POST BODY IS READ STRAIGHT INTO THE STRING THE HANDLER PARSES. Left to httplib it
* lands in its own Request first, which only hands it out const, so it would be copied
* into ours: a body at the size limit held twice before a byte of it is looked at. A
* multipart body (an image upload) is read as its parts, each straight into its own
* string, under the same size limit. */
svr.Post(path, [gate, bridge](const httplib::Request& q, httplib::Response& s,
const httplib::ContentReader& read) {
if (!gate(q, s)) return;
std::string body;
std::vector<FormPart> form;
const bool ok = q.is_multipart_form_data()
? read([&form](const httplib::FormData& f) {
form.push_back(FormPart{ f.name, f.filename, f.content_type, {} });
return true;
},
[&form](const char* p, size_t n) {
if (!form.empty()) form.back().data.append(p, n);
return true;
})
: read([&body](const char* p, size_t n) { body.append(p, n); return true; });
if (!ok) {
/* httplib has already set 413 for a body over the limit; anything else is a peer
* that stopped sending partway, which has to be answered as something. */
if (s.status < 0) {
s.status = 400;
s.set_content(error_body("invalid_request_error",
"the request body could not be read"),
"application/json");
}
return;
/* A body is read straight into the string the handler parses. httplib's own Request hands
* it out only const, so it would be copied and held twice. A multipart body (an image
* upload) is read part by part, each into its own string, under the same limit. */
auto read_and_bridge = [bridge](const httplib::Request& q, httplib::Response& s,
const httplib::ContentReader& read) {
std::string body;
std::vector<FormPart> form;
const bool ok = q.is_multipart_form_data()
? read([&form](const httplib::FormData& f) {
form.push_back(FormPart{ f.name, f.filename, f.content_type, {} });
return true;
},
[&form](const char* p, size_t n) {
if (!form.empty()) form.back().data.append(p, n);
return true;
})
: read([&body](const char* p, size_t n) { body.append(p, n); return true; });
if (!ok) {
/* httplib has already set 413 for a body over the limit; anything else is a peer
* that stopped sending partway. */
if (s.status < 0) {
s.status = 400;
s.set_content(error_body(q.path, 400, "invalid_request_error",
"the request body could not be read"),
"application/json");
}
bridge(q, std::move(body), s, std::move(form));
});
}
/* THE PREFLIGHT ALLOWS WHATEVER HEADERS IT IS ASKED ABOUT. A browser client sends more than
* the two this server reads -- the OpenAI SDK adds its x-stainless-* set -- and a preflight
* that does not list one fails the request before it is sent. A wildcard would not do: CORS
* never lets `*` stand for Authorization, so the requested list is echoed back. */
svr.Options(".*", [cors](const httplib::Request& req, httplib::Response& res) {
return;
}
bridge(q, std::move(body), s, std::move(form));
};
/* The preflight allows whatever headers it is asked about. Browser clients send more than
* the two this server reads (the OpenAI SDK adds x-stainless-*), and an unlisted one fails
* the request. `*` cannot stand for Authorization in CORS, so the requested list is echoed. */
auto preflight = [cors](const httplib::Request& req, httplib::Response& res) {
if (cors) {
const std::string asked = req.get_header_value("Access-Control-Request-Headers");
res.set_header("Access-Control-Allow-Origin", "*");
res.set_header("Access-Control-Allow-Headers",
asked.empty() ? "Content-Type, Authorization, X-Api-Key" : asked);
res.set_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
res.set_header("Access-Control-Allow-Headers", asked.empty() ? kCorsHeaders : asked);
res.set_header("Access-Control-Allow-Methods", kCorsMethods);
res.set_header("Access-Control-Max-Age", "86400");
}
res.status = 204;
});
};
/* A PATH NO ROUTE NAMES is answered by httplib before the router sees it, with no body. Every
* other refusal this server makes is an error object, and a client reading one finds an
* empty 404 unparseable; so an error with no body gets one here. A response that already
* carries a body -- the router's own 404 and 405, the gate's 401 -- is left as it is. */
/* Socket routes. An upgrade is gated before httplib answers 101 by the same key, carried the
* ways a socket client can carry it, and, with CORS off, by its Origin: a browser lets any
* page open a socket to any host, and CORS is what would otherwise keep another site's page
* out. True when the upgrade may proceed; false with the refusal in `s`. */
auto socket_gate = [api_key, cors, key_ok](const httplib::Request& q,
httplib::Response& s) -> bool {
auto refuse = [&](int status, const char* type, const std::string& why) {
RAD_INFO("req refused from %s:%d -> %d %s: %s", q.remote_addr.c_str(), q.remote_port,
status, type, why.c_str());
s.status = status;
s.set_content(error_body(q.path, status, type, why), "application/json");
return false;
};
if (!cors && q.has_header("Origin")) {
std::string origin = q.get_header_value("Origin");
const size_t at = origin.find("://");
if (at != std::string::npos) origin = origin.substr(at + 3);
if (lower_ascii(origin) != lower_ascii(q.get_header_value("Host")))
return refuse(403, "permission_error",
"a page on another origin may not open this socket (--no-cors)");
}
if (!api_key.empty() && !key_ok(q) &&
!offers_key(q.get_header_value("Sec-WebSocket-Protocol"), api_key))
return refuse(401, "authentication_error", "invalid api key");
return true;
};
for (const std::string& path : router.socket_routes()) {
const SocketHandler h = *router.socket_for(path);
svr.WebSocket(
path,
[h](const httplib::Request& hreq, httplib::ws::WebSocket& ws) {
HttpRequest req;
req.method = hreq.method;
req.path = hreq.path;
req.peer = hreq.remote_addr + ":" + std::to_string(hreq.remote_port);
for (auto& hd : hreq.headers) req.headers[hd.first] = hd.second;
for (auto& p : hreq.params) req.query[p.first] = p.second;
HttplibConn conn(ws);
try {
h(req, conn);
} catch (const std::exception& e) {
RAD_ERR("server: %s on %s", e.what(), req.path.c_str());
conn.close(1011, "internal error");
}
},
/* `realtime` when it is offered, as OpenAI's server answers; otherwise none. */
[](const std::vector<std::string>& offered) -> std::string {
for (const auto& p : offered)
if (p == "realtime") return p;
return std::string();
});
}
/* The router routes every request, not httplib: registered under its own method, a route
* would make httplib answer the same path under another method 404, where the router answers
* 405 (http.h). So a request is answered here, before httplib routes it, unless a route takes
* it with a body to read: httplib hands its body reader only to a route's handler, so those
* routes are registered below and left to it. A request no route takes is answered without
* its body being read. */
svr.set_pre_routing_handler([&router, gate, socket_gate, bridge,
preflight](const httplib::Request& q, httplib::Response& s) {
/* A WebSocket upgrade to a socket route is left to httplib, which then answers 101 and
* runs the route's socket handler. */
if (is_socket_upgrade(q) && router.socket_for(q.path))
return socket_gate(q, s) ? httplib::Server::HandlerResponse::Unhandled
: httplib::Server::HandlerResponse::Handled;
if (q.method == "OPTIONS") {
preflight(q, s);
return httplib::Server::HandlerResponse::Handled;
}
if (!gate(q, s)) return httplib::Server::HandlerResponse::Handled;
if (q.method != "GET" && q.method != "HEAD" && router.allows(q.method, q.path))
return httplib::Server::HandlerResponse::Unhandled;
bridge(q, std::string(), s);
return httplib::Server::HandlerResponse::Handled;
});
for (const auto& sig : router.routes()) {
const size_t sp = sig.find(' ');
const std::string method = sig.substr(0, sp), path = sig.substr(sp + 1);
if (method == "POST") svr.Post(path, read_and_bridge);
else if (method == "PUT") svr.Put(path, read_and_bridge);
else if (method == "PATCH") svr.Patch(path, read_and_bridge);
else if (method == "DELETE") svr.Delete(path, read_and_bridge);
}
/* What httplib answers itself (a malformed request, a body over the limit, a body sent to a
* path its route pattern does not spell) has no body. Give such errors an OpenAI error object
* like every other refusal; a response that already has a body (the router's 404 and 405,
* the gate's 401) is left as it is. */
svr.set_error_handler([cors](const httplib::Request& req, httplib::Response& res) {
if (!res.body.empty()) return httplib::Server::HandlerResponse::Unhandled;
if (cors) res.set_header("Access-Control-Allow-Origin", "*");
@@ -519,12 +734,13 @@ int HttpTransport::serve(const Router& router, const TransportOptions& o) {
: "invalid_request_error";
const std::string what = res.status == 404 ? "no route for " + req.method + " " + req.path
: httplib::status_message(res.status);
res.set_content(error_body(type.c_str(), what), "application/json");
res.set_content(error_body(req.path, res.status, type.c_str(), what),
"application/json");
return httplib::Server::HandlerResponse::Handled;
});
/* Bound once: asking for a named port and then for any port would leave the first socket
* bound and unused. */
/* Bind once: binding a named port and then any port would leave the first socket bound and
* unused. */
const int port = o.port == 0 ? svr.bind_to_any_port(o.host.c_str())
: svr.bind_to_port(o.host.c_str(), o.port) ? o.port : -1;
if (port <= 0) {
+73 -39
View File
@@ -1,10 +1,8 @@
/* core/server/http.h -- the transport seam.
*
* Everything above this line (routing, OpenAI translation, metrics) is written against these
* plain structs and never sees a socket. That is what lets tests/server_test.cpp drive the real
* handlers in-process: `Router::dispatch` is the same call the transport makes, minus the port.
* The alternative -- testing by binding a loopback socket -- tests cpp-httplib, which is already
* tested, and makes the suite depend on a free port.
* Routing, OpenAI translation and metrics are written against these plain structs and never see
* a socket, so tests/server_test.cpp drives the real handlers in-process: `Router::dispatch` is
* the same call the transport makes. Tests need no free port and do not re-test cpp-httplib.
*/
#pragma once
@@ -39,21 +37,20 @@ struct HttpRequest {
std::map<std::string, std::string> query;
std::map<std::string, std::string> params; /* from a ":name" route segment */
std::string peer; /* "addr:port"; empty in-process */
/* WHEN THE WHOLE BODY HAD ARRIVED, in steady-clock nanoseconds: where the server's own time
* for the request starts, before it is parsed, rendered or tokenised, so the time the body
* spent on the network is not in it. -1 for a request made in-process. */
/* Steady-clock nanoseconds at which the whole body had arrived. The server's own time for
* the request starts here, before parsing, so network time is excluded. -1 in-process. */
int64_t t_received_ns = -1;
/* True once the peer is gone. The transport supplies it; in-process it is absent and the
* waiting paths simply never see a drop. A dropped connection is a cancellation (spec §14),
* so every path that waits polls this. */
/* True once the peer is gone; absent in-process. A dropped connection is a cancellation
* (spec §14), so every path that waits polls this. */
std::function<bool()> closed;
std::string header(const std::string& k, const std::string& def = "") const;
std::string param(const std::string& k, const std::string& def = "") const;
/* The first form part named `k` (a field or a file), or null. */
const FormPart* part(const std::string& k) const;
bool peer_gone() const { return closed && closed(); }
/* True when the peer is this machine: 127.0.0.0/8, ::1, or either written as an IPv4-mapped
* IPv6 address -- and for a request made in-process, which has no peer. */
/* True for 127.0.0.0/8, ::1, an IPv4-mapped 127.x address, and an in-process request. */
bool peer_is_loopback() const;
};
@@ -64,12 +61,11 @@ struct HttpResponse {
std::vector<std::pair<std::string, std::string>> headers;
/* Streaming. When `next` is set, `body` is ignored and the transport pulls chunks until next()
* returns false. A chunk may legitimately be empty (nothing produced this poll), in which case
* nothing is written but the connection is checked. */
* returns false. An empty chunk writes nothing but still checks the connection. */
std::function<bool(std::string&)> next;
/* Runs exactly once when the connection ends, with `ok` false if the peer went away before the
* stream finished. This is where a dropped stream becomes a scheduler cancellation. */
/* Runs exactly once when the connection ends; `ok` is false if the peer left before the
* stream finished. A dropped stream becomes a scheduler cancellation here. */
std::function<void(bool ok)> on_close;
bool streaming() const { return next != nullptr; }
@@ -82,47 +78,88 @@ struct HttpResponse {
using Handler = std::function<HttpResponse(const HttpRequest&)>;
/* Exact-match routing plus a single ":name" wildcard segment, which is all the OpenAI surface
* needs (/v1/models/:id). No regex, no priority rules, nothing to reason about. */
/* One WebSocket connection, as a socket route sees it: messages in, messages out, and a close.
* The route runs for the connection's whole life on the transport's thread for it. It reads on
* that thread and may send and close from another, so it can answer while it listens. A test
* hands the route a connection of its own. */
class WsConn {
public:
virtual ~WsConn() = default;
/* Blocks for the next message: true with it in `*msg` and `*binary` saying which frame it came
* in, false once the connection is gone. */
virtual bool read(std::string* msg, bool* binary) = 0;
/* A text message. Safe from any thread; false once the connection is gone. */
virtual bool send(const std::string& text) = 0;
/* Ends the connection with a close code and reason (RFC 6455 §7.4); a read() blocked on it
* returns false once the peer has answered or gone. Safe from any thread. */
virtual void close(int code, const std::string& reason) = 0;
};
/* A socket route: the upgrade request, and the connection it became. */
using SocketHandler = std::function<void(const HttpRequest&, WsConn&)>;
/* Exact-match routing plus ":name" wildcard segments and a final "*name" that takes the rest of
* the path, which is all the OpenAI surface needs (a model id may hold a slash, so the model
* entry's route ends in "*id"). No regex and no priority rules. */
class Router {
public:
void add(std::string method, std::string path, Handler h);
void get(std::string path, Handler h) { add("GET", std::move(path), std::move(h)); }
void post(std::string path, Handler h) { add("POST", std::move(path), std::move(h)); }
/* A WebSocket route, exact path. An upgrade request to it becomes a connection the handler
* is given; a plain GET to the same path is whatever add() registered there, if anything. */
void socket(std::string path, SocketHandler h);
/* The handler for an upgrade to `path`, or null. */
const SocketHandler* socket_for(const std::string& path) const;
std::vector<std::string> socket_routes() const;
/* 404 with a body naming the path, 405 when the path exists under another method. By value,
* so the transport can move a request -- body included -- into the handler rather than copy
* a body that may be hundreds of megabytes. */
/* 404 with a body naming the path, 405 when the path exists under another method. Takes the
* request by value so the transport can move a body of up to hundreds of MB into the handler. */
HttpResponse dispatch(HttpRequest req) const;
/* Convenience for tests and for anything that speaks in whole request lines. */
/* Convenience for tests. */
HttpResponse call(const std::string& method, const std::string& path,
const std::string& body = "") const;
/* Whether a route takes `method` on `path`, as dispatch would match it. */
bool allows(const std::string& method, const std::string& path) const;
std::vector<std::string> routes() const;
private:
struct Route {
std::string method;
std::vector<std::string> segs; /* ":name" segments are wildcards */
std::vector<std::string> segs; /* ":name" is any one segment, a final "*name" the rest */
Handler h;
};
/* The route taking `method` on the path `segs`, with its captures; null when none.
* `*path_matched` says whether a route takes the path under any method. */
const Route* match(const std::string& method, const std::vector<std::string>& segs,
std::map<std::string, std::string>* caps, bool* path_matched) const;
std::vector<Route> routes_;
std::vector<std::pair<std::string, SocketHandler>> sockets_;
};
/* Anthropic's clients read Anthropic's error envelope, `{"type":"error","error":{"type",
* "message"}}`, so every refusal on one of its paths (/v1/messages and below) is written in it,
* the transport's own included; every other path gets OpenAI's. */
bool anthropic_path(const std::string& path);
/* Anthropic's error `type` for an HTTP status. */
const char* anthropic_error_type(int status);
/* Split "/v1/models/foo?x=1" into path and decoded query parameters. */
void parse_target(const std::string& target, std::string* path,
std::map<std::string, std::string>* query);
/* Percent-decode. `plus_is_space` is the form encoding, which applies to a query string and
* not to a path -- see the definition. */
/* Percent-decode. `plus_is_space` is the form encoding: true for a query string, false for a
* path. */
std::string url_decode(const std::string& s, bool plus_is_space = true);
/* ================================================================== the cpp-httplib binding */
/* ONE WORKER PER CONNECTION, for the connection's whole life: httplib reads a request, runs the
* handler and writes the response on the same thread, and a generation's handler runs until the
* generation ends. So the pool bounds are connection counts, and Server::run derives them from
* the admission ceiling rather than from the core count. */
/* One worker per connection for the connection's whole life: httplib reads, handles and writes
* on one thread, and a generation's handler runs until the generation ends. The pool bounds are
* therefore connection counts, which Server::run derives from the admission ceiling, not the
* core count. */
struct TransportOptions {
std::string host = "0.0.0.0";
int port = 8000; /* 0 -> any free port; see HttpTransport::port */
@@ -132,9 +169,8 @@ struct TransportOptions {
int64_t max_queued = 0; /* accepted connections that may wait for a worker once
* it has grown to max_threads; past that they are
* closed. 0 -> unbounded */
/* The longest the peer may go silent while its REQUEST is being read. It bounds nothing about
* generation, which is written, not read. A connection that sends part of a request and then
* goes quiet holds a worker until this runs out, so it is short. */
/* Longest silence allowed while the request is being read; generation is not bounded by it.
* A peer that stalls mid-request holds a worker until this expires, so it is short. */
int read_timeout_s = 30;
int write_timeout_s = 600;
int keep_alive_timeout_s = 5; /* an idle connection's hold on a worker between requests */
@@ -143,9 +179,8 @@ struct TransportOptions {
bool cors = true;
};
/* The workers the pool keeps while idle for TransportOptions::n_threads: that many, one a
* hardware thread for 0, and never fewer than 4. One definition, so the number the startup
* report states is the number the transport runs. */
/* Idle workers kept for TransportOptions::n_threads: that many, one per hardware thread for 0,
* never fewer than 4. Shared so the startup report states what the transport runs. */
int idle_workers(int n_threads);
class HttpTransport {
@@ -159,9 +194,8 @@ public:
int serve(const Router& r, const TransportOptions& o);
void stop();
/* The port serve() bound, which is the only way to learn it when it was asked for port 0.
* 0 until the server is accepting connections, so a non-zero answer also means stop() will
* take effect. */
/* The port serve() bound (the only way to learn it for port 0). 0 until the server accepts
* connections, so a non-zero answer also means stop() will take effect. */
int port() const;
private:
+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;
+73 -82
View File
@@ -1,24 +1,22 @@
/* images.cpp -- OpenAI's images API over an image generator (core/gen): /v1/images/generations
* and /v1/images/edits.
*
* WHAT A REQUEST BECOMES. The prompt goes into the model's own template (ImageGenInfo), with the
* fixed system turn the generator drops; a transparent background asks for one in the words the
* model was trained on. An edit's pictures are each resized to the model's reference area at their
* own aspect -- with PIL's premultiplied Lanczos, as diffusers resizes them -- and read twice: as
* RGBA pixels by the generator's encoder, and composited on white by the conditioning network's.
* With a mask, the first picture is repainted: the mask's transparent pixels are where it may
* change, the rest is put back exactly after decoding.
* Request: the prompt goes into the model's own template (ImageGenInfo), including the fixed
* system turn the generator drops; a transparent background is requested in the model's trained
* wording. Each edit picture is resized to the model's reference area at its own aspect (PIL's
* premultiplied Lanczos, as diffusers does) and read twice: as RGBA by the generator's encoder,
* and composited on white by the conditioning network's. With a mask, the first picture is
* repainted where the mask is transparent; the rest is restored exactly after decoding.
*
* WHAT IS EXTENDED, beside OpenAI's fields, by vLLM-Omni's names: `seed`, `negative_prompt` with
* `true_cfg_scale` (guidance), `num_inference_steps`, and `width` / `height` in place of `size`.
* A model with a fixed schedule (a distilled one) takes no step count but its own.
* Extensions, under vLLM-Omni's names: `seed`, `negative_prompt` with `true_cfg_scale`
* (guidance), `num_inference_steps`, and `width` / `height` instead of `size`. A fixed-schedule
* (distilled) model accepts only its own step count.
*
* WHAT IS REFUSED: `response_format: url` -- nothing here stores an image to serve later, so the
* picture comes back in the response (b64_json) or not at all.
* Refused: `response_format: url`, since no image is stored to serve later; only b64_json.
*
* STREAMING is OpenAI's: `image_generation.partial_image` (`image_edit.partial_image`) events
* for the `partial_images` previews -- the step's estimate of the finished latent, decoded -- and
* one `.completed` event an image.
* Streaming follows OpenAI: `image_generation.partial_image` (`image_edit.partial_image`) events
* for the `partial_images` previews (each step's decoded estimate of the final latent), and one
* `.completed` event per image.
*/
#include "server.h"
#include "oai.h"
@@ -28,6 +26,7 @@
#include "mm/media.h"
#include "mm/processor.h"
#include "rad_internal.h"
#include "rad_plugin.h"
#include <nlohmann/json.hpp>
@@ -46,9 +45,9 @@ namespace {
/* The largest picture a request may upload, before any resize. */
constexpr int64_t kMaxSourcePixels = (int64_t)1 << 26;
/* Below this alpha a pixel is transparent: where a mask lets the picture change, and what makes a
* picture one with transparency. A decoder's alpha is not exactly 255 on an opaque picture, so a
* picture this model made and is given back to edit stays opaque. */
/* Below this alpha a pixel counts as transparent, both in a mask and when deciding whether a
* picture has transparency. A threshold, not 255, because a decoder's alpha on an opaque picture is
* not exactly 255, so this model's own output stays opaque when edited. */
constexpr uint8_t kTransparentBelow = 128;
struct ImgReq {
@@ -91,7 +90,7 @@ json form_value(const std::string& key, const std::string& v) {
return json(v);
}
/* diffusers' calculate_dimensions: a target area at an aspect, each side rounded to 32. */
/* diffusers' calculate_dimensions: a target area at an aspect, each side rounded to `mult`. */
void dims_for(double area, double ratio, int32_t mult, int32_t* w, int32_t* h) {
const double wd = std::sqrt(area * ratio);
const double hd = wd / ratio;
@@ -107,15 +106,8 @@ std::string replace_all(std::string s, const std::string& what, const std::strin
return s;
}
uint16_t f32_bf16(float f) {
uint32_t u;
std::memcpy(&u, &f, 4);
u += 0x7FFFu + ((u >> 16) & 1u);
return (uint16_t)(u >> 16);
}
/* A picture as the generator's encoder reads it: each channel u -> 2 * (u / 255) - 1 in f32, then
* bf16 -- VaeImageProcessor's preprocess, cast to the VAE's dtype. */
* bf16 (VaeImageProcessor's preprocess, cast to the VAE's dtype). */
gen::Pixels to_pixels(const mm::FrameRGBA& f) {
gen::Pixels p;
p.w = f.w;
@@ -123,7 +115,7 @@ gen::Pixels to_pixels(const mm::FrameRGBA& f) {
p.ch = 4;
p.bf16.resize(f.rgba.size());
for (size_t i = 0; i < f.rgba.size(); ++i)
p.bf16[i] = f32_bf16(2.0f * ((float)f.rgba[i] / 255.0f) - 1.0f);
p.bf16[i] = rad_f32_to_bf16(2.0f * ((float)f.rgba[i] / 255.0f) - 1.0f);
return p;
}
@@ -168,15 +160,11 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
}
}
} else {
try {
body = json::parse(req.body);
} catch (const std::exception& e) {
return error_response(err_bad("", std::string("the body is not JSON: ") + e.what()),
req.peer);
}
if (!body.is_object()) return error_response(err_bad("", "the body is not a JSON object"), req.peer);
/* An edit's pictures as JSON: `images: [{image_url: "data:..."}]` and `mask: {image_url}`,
* the newer form of the API, or `image` as one data URL or a list of them. */
ApiError err;
if (parse_request_object(req.body, lim_, &body, &err) < 0)
return error_response(err, req.peer);
/* An edit's pictures as JSON: `images: [{image_url: "data:..."}]` and `mask: {image_url}`
* (the newer API form), or `image` as one data URL or a list. */
auto url_of = [](const json& v, std::string* u) {
if (v.is_string()) { *u = v.get<std::string>(); return true; }
if (v.is_object() && v.contains("image_url") && v["image_url"].is_string()) {
@@ -252,13 +240,13 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
return 1;
};
if (str("prompt", &r.prompt) < 0)
return error_response(err_bad("prompt", "a string"), req.peer);
return error_response(err_bad("prompt", "expected a string"), req.peer);
if (!body.contains("prompt"))
return error_response(err_bad("prompt", "the prompt is required"), req.peer);
if (r.prompt.empty()) r.prompt = " ";
std::string rf;
if (str("response_format", &rf) < 0 || (!rf.empty() && rf != "b64_json" && rf != "url"))
return error_response(err_bad("response_format", "b64_json"), req.peer);
return error_response(err_bad("response_format", "expected b64_json"), req.peer);
if (rf == "url") {
ApiError e = err_unsupported("response_format",
"url is not served: this server keeps no image to serve "
@@ -268,17 +256,18 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
}
int64_t v = 0;
if (num("n", 1, info.max_lanes, &v) < 0)
return error_response(err_bad("n", "1.." + std::to_string(info.max_lanes)), req.peer);
return error_response(
err_bad("n", "expected an integer in 1.." + std::to_string(info.max_lanes)), req.peer);
r.n = body.contains("n") && !body["n"].is_null() ? (int32_t)v : 1;
if (str("background", &r.background) < 0 ||
(r.background != "auto" && r.background != "transparent" && r.background != "opaque")) {
ApiError e = err_bad("background", "auto, transparent or opaque");
ApiError e = err_bad("background", "expected auto, transparent or opaque");
e.supported = { "auto", "transparent", "opaque" };
return error_response(e, req.peer);
}
if (str("output_format", &r.format) < 0 ||
(r.format != "png" && r.format != "jpeg" && r.format != "webp")) {
ApiError e = err_bad("output_format", "png, jpeg or webp");
ApiError e = err_bad("output_format", "expected png, jpeg or webp");
e.supported = { "png", "jpeg", "webp" };
return error_response(e, req.peer);
}
@@ -286,14 +275,16 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
return error_response(err_bad("background", "jpeg has no transparency; ask for png or "
"webp"), req.peer);
if (num("output_compression", 0, 100, &v) < 0)
return error_response(err_bad("output_compression", "0..100"), req.peer);
return error_response(err_bad("output_compression", "expected an integer in 0..100"),
req.peer);
if (body.contains("output_compression")) r.compression = (int32_t)v;
if (body.contains("stream") && !body["stream"].is_null()) {
if (!body["stream"].is_boolean()) return error_response(err_bad("stream", "a boolean"), req.peer);
if (!body["stream"].is_boolean())
return error_response(err_bad("stream", "expected a boolean"), req.peer);
r.stream = body["stream"].get<bool>();
}
if (num("partial_images", 0, 3, &v) < 0)
return error_response(err_bad("partial_images", "0..3"), req.peer);
return error_response(err_bad("partial_images", "expected an integer in 0..3"), req.peer);
if (body.contains("partial_images")) r.previews = (int32_t)v;
if (r.previews > 0 && !r.stream)
return error_response(err_bad("partial_images", "partial images are sent on a stream; "
@@ -301,14 +292,15 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
if (str("quality", &r.quality) < 0 ||
(r.quality != "auto" && r.quality != "low" && r.quality != "medium" &&
r.quality != "high" && r.quality != "standard" && r.quality != "hd")) {
ApiError e = err_bad("quality", "auto, low, medium, high (standard, hd)");
ApiError e = err_bad("quality", "expected auto, low, medium or high (or standard, hd)");
e.supported = { "auto", "low", "medium", "high", "standard", "hd" };
return error_response(e, req.peer);
}
/* The step count: the request's, or what its quality asks for, or the model's. */
int64_t steps = 0;
if (num("num_inference_steps", 1, 200, &steps) < 0)
return error_response(err_bad("num_inference_steps", "1..200"), req.peer);
return error_response(err_bad("num_inference_steps", "expected an integer in 1..200"),
req.peer);
if (info.fixed_schedule) {
if (steps != 0 && steps != info.fixed_steps)
return error_response(err_unsupported("num_inference_steps",
@@ -322,23 +314,25 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
else if (r.quality == "medium") steps = std::max<int64_t>(1, info.default_steps * 3 / 4);
}
r.steps = (int32_t)steps;
/* -1 asks for a random seed, as llama-server and the chat endpoints read it. */
if (body.contains("seed") && !body["seed"].is_null()) {
if (!body["seed"].is_number_integer())
return error_response(err_bad("seed", "an integer"), req.peer);
return error_response(err_bad("seed", "expected an integer"), req.peer);
r.seed = (uint64_t)body["seed"].get<int64_t>();
r.seed_given = true;
r.seed_given = body["seed"].is_number_unsigned() || body["seed"].get<int64_t>() != -1;
}
if (str("negative_prompt", &r.negative) < 0)
return error_response(err_bad("negative_prompt", "a string"), req.peer);
return error_response(err_bad("negative_prompt", "expected a string"), req.peer);
if (body.contains("true_cfg_scale") && !body["true_cfg_scale"].is_null()) {
if (!body["true_cfg_scale"].is_number())
return error_response(err_bad("true_cfg_scale", "a number"), req.peer);
return error_response(err_bad("true_cfg_scale", "expected a number"), req.peer);
r.cfg = body["true_cfg_scale"].get<double>();
if (!(r.cfg >= 1.0 && r.cfg <= 30.0))
return error_response(err_bad("true_cfg_scale", "1..30"), req.peer);
return error_response(err_bad("true_cfg_scale", "expected a number in 1..30"),
req.peer);
}
/* Guidance needs both halves, as the reference pipeline does: a scale above one and a
* negative prompt (an empty one is " "). */
/* Guidance needs a scale above one and a negative prompt (empty becomes " "), as in the
* reference pipeline. */
r.has_neg = r.cfg > 1.0 && body.contains("negative_prompt");
if (r.has_neg && r.negative.empty()) r.negative = " ";
if (r.cfg > 1.0 && !r.has_neg)
@@ -374,9 +368,8 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
} else if (!files.empty() || have_mask) {
return error_response(err_bad("image", "pictures go to /v1/images/edits"), req.peer);
}
/* `auto` is decided by what was sent: an edit of a picture with transparency keeps it, and
* anything else is opaque -- a picture made without asking for transparency carries only the
* decoder's noise in its alpha. */
/* `auto`: an edit of a picture with transparency keeps it; anything else is opaque, since an
* image generated without transparency has only decoder noise in its alpha. */
if (r.background == "auto") {
bool alpha = false;
if (r.format != "jpeg")
@@ -386,14 +379,17 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
r.background = alpha ? "transparent" : "opaque";
}
/* ---- the size: `width`/`height`, or `size` "WxH", or auto -- the native size, at the last
* picture's aspect for an edit. Sides are rounded down to the model's multiple. */
/* ---- the size: `width`/`height`, `size` "WxH", or auto (the native area, at the last
* picture's aspect for an edit). Sides are rounded down to the model's multiple. */
const int32_t mult = (int32_t)info.size_multiple;
std::string size = "auto";
if (str("size", &size) < 0) return error_response(err_bad("size", "\"WxH\" or \"auto\""), req.peer);
if (str("size", &size) < 0)
return error_response(err_bad("size", "expected \"WxH\" or \"auto\""), req.peer);
int64_t bw = 0, bh = 0;
if (num("width", 1, 16384, &bw) < 0 || num("height", 1, 16384, &bh) < 0)
return error_response(err_bad("width", "1..16384"), req.peer);
if (num("width", 1, 16384, &bw) < 0)
return error_response(err_bad("width", "expected an integer in 1..16384"), req.peer);
if (num("height", 1, 16384, &bh) < 0)
return error_response(err_bad("height", "expected an integer in 1..16384"), req.peer);
if ((bw > 0) != (bh > 0))
return error_response(err_bad(bw ? "height" : "width", "width and height go together"),
req.peer);
@@ -404,7 +400,7 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
int a = 0, b = 0;
char x = 0;
if (std::sscanf(size.c_str(), "%d%c%d", &a, &x, &b) != 3 || x != 'x' || a <= 0 || b <= 0)
return error_response(err_bad("size", "\"WxH\" or \"auto\""), req.peer);
return error_response(err_bad("size", "expected \"WxH\" or \"auto\""), req.peer);
r.w = a;
r.h = b;
} else if (edit) {
@@ -427,8 +423,8 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
std::to_string(info.max_tokens * ls * ls) +
" pixels)"), req.peer);
if (!r.seed_given) {
/* 53 bits: the seed goes back in the response to be sent again, and a JavaScript client
* reads a JSON number as a double -- a 64-bit seed would come back as another picture. */
/* 53 bits: the seed is returned for reuse, and JavaScript reads JSON numbers as doubles,
* so a wider seed would not round-trip. */
std::random_device rd;
r.seed = (((uint64_t)rd() << 32) ^ rd()) & (((uint64_t)1 << 53) - 1);
}
@@ -461,8 +457,8 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
req.peer);
items.push_back(std::move(it));
}
/* Repainting: the first picture at the size being made, and per latent token the share of
* its 16 x 16 pixels the mask leaves transparent -- those are repainted, the rest kept. */
/* Repainting: the first picture at the output size, and per latent token the fraction of
* its ls x ls pixels the mask leaves transparent. Those are repainted, the rest kept. */
std::vector<uint8_t> keep_px, src_px;
if (r.has_mask) {
mm::FrameRGBA src, msk;
@@ -498,8 +494,8 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
tmpl = replace_all(tmpl, "{images}", imgs);
}
const std::string rendered = replace_all(tmpl, "{prompt}", text);
/* Tokenised piece by piece around the markers, each marker replaced by its picture's
* token run -- the chat path's tokenize_with_media, with pictures already processed. */
/* Tokenised around the markers, each marker replaced by its picture's token run: the
* chat path's tokenize_with_media, with the pictures already processed. */
auto pm = std::make_shared<mm::PromptMedia>();
size_t pos = 0, mi = 0;
for (;;) {
@@ -522,12 +518,12 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
pm->layout();
out->media = std::move(pm);
}
/* The fixed turn the generator does not see, which must be where the prompt starts. */
/* The fixed turn the generator drops; the prompt must start with it. */
const auto drop = deps_.tok->encode(info.drop_prefix, false, true);
if (drop.size() > out->tokens.size() ||
!std::equal(drop.begin(), drop.end(), out->tokens.begin())) {
*err = err_bad("prompt", "the prompt does not start with the model's fixed turn");
err->status = 500;
/* The model's own templates disagree; nothing the request did. */
*err = err_internal("the prompt does not start with the model's fixed turn");
return RAD_E_STATE;
}
out->n_drop = (int32_t)drop.size();
@@ -547,12 +543,7 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
}
/* ---- admitted and queued */
sweep_abandoned();
if (!admit(1)) {
metrics_.observe_rejected();
return error_response(err_overloaded("the admission queue is full; retry after " +
std::to_string(opt_.retry_after_s) + "s"), req.peer);
}
if (auto no = admit(1, req.peer)) return *no;
std::shared_ptr<gen::Ticket> ticket = g->ticket;
{
std::string why;
@@ -632,9 +623,9 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
}
release(1);
if (ticket->status() < 0 || (int32_t)done.size() != r.n) {
/* RAD_E_INVAL is the driver's refusal at admission -- a request this deployment can
* never serve, such as a conditioning longer than the cache -- and the client's to
* change; anything else failed while it ran. */
/* RAD_E_INVAL is the driver's admission refusal (a request this deployment can never
* serve, e.g. conditioning longer than the cache), so a 400; anything else failed
* while running. */
ApiError e;
const bool client = ticket->status() == RAD_E_INVAL;
e.status = client ? 400 : 500;
@@ -669,7 +660,7 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
return HttpResponse::json_body(200, json_dump(out));
}
/* ---- streamed: partial images as the previews arrive, a completed event an image */
/* ---- streamed: partial images as previews arrive, one completed event per image */
HttpResponse res;
res.status = 200;
res.content_type = "text/event-stream";
+6 -7
View File
@@ -67,8 +67,8 @@ struct Scanner {
}
bool value(int depth) {
/* A hard depth cap, because the input is model output and a runaway "[[[[[..." would
* otherwise recurse until the stack ends. 256 is far past any real tool schema. */
/* Depth cap: the input is model output, and a runaway "[[[[..." would otherwise recurse
* until the stack overflows. 256 is far past any real tool schema. */
if (depth > 256) return false;
ws();
if (eof()) return false;
@@ -159,9 +159,8 @@ size_t json_stable_prefix(std::string_view s) {
while (bs < n && s[n - 1 - bs] == '\\') ++bs;
if (bs % 2 == 1) return n - 1;
/* Back out of an unfinished "\uXXXX". `k` is how many characters have arrived after the 'u',
* so the escape is complete at k == 4 and short before it. Only six bytes ever need looking
* at, which is why this is a loop and not a parser. */
/* Back out of an unfinished "\uXXXX". `k` counts the characters after the 'u'; the escape is
* complete at k == 4. At most six bytes are examined. */
for (size_t k = 0; k <= 4 && n >= k + 2; ++k) {
if (s[n - 1 - k] != 'u') continue;
if (s[n - 2 - k] != '\\') break;
@@ -185,8 +184,8 @@ bool json_quote_append(std::string& out, std::string_view s) {
while (p < e) {
const unsigned char c = *p;
if (c >= 0x80) {
/* Length, and the range the SECOND byte is restricted to, which is what rejects
* overlong forms, surrogates and anything past U+10FFFF without decoding. */
/* Sequence length and the allowed range of the second byte, which rejects overlong
* forms, surrogates and code points past U+10FFFF without decoding. */
size_t len;
unsigned char lo = 0x80, hi = 0xBF;
if (c >= 0xC2 && c <= 0xDF) len = 2;
+22 -29
View File
@@ -1,21 +1,15 @@
/* core/server/json_partial.h -- what may be sent, and what may be called a tool call.
/* core/server/json_partial.h -- scanning JSON text that is still arriving.
*
* Two questions about text that is still arriving, and they are different questions:
* json_complete Is this a tool call? A call is reported as `finish_reason:
* "tool_calls"` only if its arguments parse whole; a malformed call is
* returned as ordinary content, so a tool is never called with truncated
* arguments.
* json_stable_prefix How much may be streamed now? A fragment is JSON-encoded into the SSE
* payload, so it must end on a UTF-8 boundary; a split code point corrupts
* this delta and the next.
* json_quote_append Writes a string literal exactly as nlohmann does, for delta chunks.
*
* 1. "Is this a tool call?" -- answered by `json_complete`. Nothing is ever reported to a
* client as `finish_reason: "tool_calls"` unless the arguments parse whole. A malformed call
* is returned as ordinary content, because a client that gets a truncated arguments object
* and is told it is a tool call will call the tool with the wrong arguments.
*
* 2. "How much of it can I put on the wire right now?" -- answered by `json_stable_prefix`.
* A streamed fragment is itself JSON-encoded into the SSE payload, so it must end on a UTF-8
* boundary: cutting a multi-byte code point in half turns one delta into mojibake and the
* next into a decode error.
*
* And one way to write it: `json_quote_append`, a string literal exactly as nlohmann writes one,
* for the chunks that carry a delta.
*
* This is a scanner, not a parser: it allocates nothing and builds no DOM.
* A scanner, not a parser: it allocates nothing and builds no DOM.
*/
#pragma once
@@ -29,25 +23,24 @@ namespace server {
/* Does `s` parse as exactly one complete JSON value, with only whitespace after it? */
bool json_complete(std::string_view s);
/* Largest n <= s.size() such that s[0,n) ends on a UTF-8 code point boundary. Bytes that are not
* valid UTF-8 at all are left alone -- this backs out of a truncation, it does not validate. */
/* Largest n <= s.size() such that s[0,n) ends on a UTF-8 code point boundary. Invalid UTF-8 is
* left alone: this backs out of a truncation, it does not validate. */
size_t utf8_trunc(std::string_view s);
/* Largest prefix of `s` that is safe to emit as one streaming fragment: a UTF-8 boundary, and not
* in the middle of a "\uXXXX" escape or on a lone trailing backslash. The escape rule buys
* nothing for a client that only concatenates, and costs four bytes of latency; it is here
* because a client that pretty-prints each delta is a client that would otherwise print a broken
* escape, and the class of bug that produces is unbisectable from the server side. */
/* Largest prefix of `s` that is safe to emit as one streaming fragment: on a UTF-8 boundary, not
* inside a "\uXXXX" escape and not on a lone trailing backslash. The escape rule costs up to four
* bytes of latency; it keeps a client that renders each delta separately from seeing a broken
* escape. */
size_t json_stable_prefix(std::string_view s);
/* Append `s` to `out` as a JSON string literal, quotes included, byte for byte as nlohmann's
* dump() writes one: `\b \t \n \f \r \" \\` as two characters, every other control character
* as `\u00xx` in lowercase hex, and everything else -- DEL and non-ASCII included -- as itself.
* Returns false, with `out` as it was, when `s` is not well-formed UTF-8 (overlong forms,
* surrogates and code points past U+10FFFF included), which nlohmann refuses rather than writes.
* dump() writes one: `\b \t \n \f \r \" \\` as two characters, other control characters as
* `\u00xx` in lowercase hex, everything else (DEL and non-ASCII included) as itself. Returns
* false with `out` unchanged when `s` is not well-formed UTF-8 (including overlong forms,
* surrogates and code points past U+10FFFF), which nlohmann refuses.
*
* A streamed chunk is written with this around a fixed frame instead of through a DOM: building
* and dumping a tree per token cost more than every other part of the token's host work. */
* Streamed chunks use this around a fixed frame: building and dumping a DOM per token cost more
* than the rest of the token's host work. */
bool json_quote_append(std::string& out, std::string_view s);
} /* namespace server */
+48 -51
View File
@@ -26,9 +26,8 @@ void snapshot_from(const SchedMetrics& m, LiveSnapshot* out) {
out->draft_acceptance = m.draft_acceptance;
out->total_requests = m.total_requests;
out->preemptions = m.preemptions;
/* The step counter is the one field a stalled loop moves and everything else does not:
* throughput decays toward zero on its own, but a step count frozen between two draws says
* the loop itself stopped. It comes from the same metrics as the rest. */
/* Throughput decays toward zero on its own; a step count frozen between two draws is what
* shows the loop itself stopped. */
out->step = m.steps;
}
@@ -36,9 +35,8 @@ void snapshot_from(const SchedMetrics& m, LiveSnapshot* out) {
namespace {
/* Tier -> colour. The order matches rad::Tier: VRAM, HostPinned, HostPageable, SSD, Mapped. Green is
* resident and fast, red is on a disk; the gradient is the point, so a glance at the plane says
* how much of the model is where without reading a number. */
/* Tier -> colour, in rad::Tier order: VRAM, HostPinned, HostPageable, SSD, Mapped. Green is
* resident, red is on disk, so the plane shows at a glance where the model lives. */
const char* tier_colour(uint8_t t) {
switch (t) {
case 0: return "\033[32m"; /* VRAM */
@@ -48,6 +46,13 @@ const char* tier_colour(uint8_t t) {
default: return "\033[31m"; /* SSD */
}
}
/* Tier names, in rad::Tier order. */
const char* const kTierNames[kLiveTiers] = {"vram", "pinned", "host", "ssd", "mapped"};
/* How slow a tier is to read, in rad::Tier order, for a column's worst tier: SSD is the slowest,
* so it outranks the mapping though it comes first in the enum. */
const uint8_t kTierRank[kLiveTiers] = {0, 1, 2, 4, 3};
char tier_glyph(uint8_t t) {
switch (t) {
case 0: return '#';
@@ -81,8 +86,8 @@ std::string f2(double v) {
return b;
}
/* Tokens a second, never scaled by a prefix: rates are read against each other digit by digit,
* and 6.12k beside 5.98k hides the difference 6116 beside 5979 shows. */
/* Tokens per second, never SI-scaled: rates are compared digit by digit, and 6.12k beside 5.98k
* hides what 6116 beside 5979 shows. */
std::string tps(double v) {
char b[32];
snprintf(b, sizeof b, v >= 99.95 ? "%.0f" : "%.1f", v);
@@ -91,14 +96,13 @@ std::string tps(double v) {
/* ---- the terminal form's figures.
*
* THE WEB PAGE'S RULES (dashboard.cpp), so the two views of one snapshot print one figure. Three
* significant figures and at most two decimals, ROUNDED BEFORE THE UNIT IS CHOSEN -- choosing the
* unit first prints 1023.7 MiB as "1024 MiB". Sizes in binary units, because the card and every
* --*-mib flag count in them. Counters exact and grouped in threes by a narrow space past four
* digits, as SI writes them. A share never rounds onto 0% or 100%.
* Same rules as the web page (dashboard.cpp), so both views print the same figure. Three
* significant figures and at most two decimals, rounded before the unit is chosen (otherwise
* 1023.7 MiB prints as "1024 MiB"). Sizes in binary units, as the card and every --*-mib flag
* count. Counters exact, grouped in threes by a narrow space past four digits, as SI writes them.
* A share never rounds onto 0% or 100%.
*
* The piped form above keeps its own formatting: it is parsed as well as read, and its keys and
* value shapes are what a log consumer already matches. */
* The piped form keeps its own formatting, since log consumers parse its keys and value shapes. */
/* The digits of 0 <= a < 999.5; the thresholds are where the rounded value gains a digit. */
std::string sig3(double a) {
@@ -108,7 +112,7 @@ std::string sig3(double a) {
}
/* A value on a unit ladder: steps up while the value would round to four digits. `exact` prints
* the first rung as a whole number -- "5.00 B" is a precision that does not exist. */
* the first rung as a whole number (no "5.00 B"). */
std::string ladder(double v, double base, const char* const* units, int n_units, bool exact,
const char* sep) {
if (!std::isfinite(v)) return "-";
@@ -141,8 +145,8 @@ std::string size_of(int64_t used, int64_t total) {
return a + " / " + b;
}
/* A continuous quantity -- watts, degrees -- to three figures and an SI prefix. Not tokens a
* second: tps() prints those whole. */
/* A continuous quantity (watts, degrees) to three figures and an SI prefix. Not for tokens per
* second, which tps() prints whole. */
std::string num_si(double v) { return ladder(v, 1000.0, kPfx, 6, false, ""); }
/* A counter, exact, grouped in threes by U+202F past four digits. */
@@ -155,7 +159,8 @@ std::string grouped(int64_t n) {
return n < 0 ? "-" + o : o;
}
/* A share of one to one decimal. Only exactly 0 reads 0 and only exactly 1 reads 100. */
/* A fraction as a percentage to one decimal. Only exactly 0 reads 0 and only exactly 1 reads
* 100. */
std::string share(double f) {
if (!std::isfinite(f)) return "-";
char b[32];
@@ -210,8 +215,8 @@ void LiveView::loop() {
/* ------------------------------------------------------------------ the piped form
*
* One ordinary line per interval, key=value, no escape sequences, no cursor movement. This is
* what a log file or a `| tee` gets, and it is greppable and diffable by construction.
* One line per interval, key=value, no escape sequences or cursor movement, so a log file or a
* `| tee` stays greppable and diffable.
*/
std::string LiveView::render_line(const LiveSnapshot& s) const {
std::string o = "live";
@@ -235,20 +240,17 @@ std::string LiveView::render_line(const LiveSnapshot& s) const {
}
if (s.experts.n_units > 0) {
/* THE SNAPSHOT'S OWN TALLY, not a second walk of the plane. Walking it would count CELLS,
* which is not the same as counting UNITS: the plane is a rectangle and a model need not
* fill it -- a draft head carrying fewer experts than the trunk leaves empty cells, and
* those cells would be charged to whatever tier their row was initialised at. The engine
* counts the units it actually placed (liveview.h) and both renderers read that. */
o += " experts vram=" + std::to_string(s.experts.units[0]);
o += " pinned=" + std::to_string(s.experts.units[1]);
o += " host=" + std::to_string(s.experts.units[2]);
o += " ssd=" + std::to_string(s.experts.units[3]);
/* The snapshot's own unit tally, not a walk of the plane. The plane is a rectangle a
* model need not fill (a draft head with fewer experts than the trunk leaves empty
* cells), so counting cells would charge empty ones to some tier. */
o += " experts";
for (int t = 0; t < kLiveTiers; ++t)
o += std::string(" ") + kTierNames[t] + "=" + std::to_string(s.experts.units[t]);
o += " resident=" + f2(s.experts.n_units
? 100.0 * (double)s.experts.units[0] / (double)s.experts.n_units
: 0.0) + "%";
/* THE HIT RATE, which residency does not imply: a plan holding most of the units still
* misses on most tokens if the hot ones are the ones outside. */
/* Hit rate, which residency does not imply: a plan holding most units still misses on
* most tokens if the hot ones are outside. */
if (s.experts.routed > 0)
o += " hit=" + f2(100.0 * (double)s.experts.routed_resident /
(double)s.experts.routed) + "%";
@@ -258,10 +260,8 @@ std::string LiveView::render_line(const LiveSnapshot& s) const {
o += " readmit=" + std::to_string(s.experts.readmits);
}
}
/* THE LINK, and the THREE things sharing it: the collective, the mover, and the MoE GEMM
* reading an expert that was not resident. Cumulative, so a `| tee` of this line is a time
* series a reader can difference -- which is the only form that says which of them is
* filling the bus. */
/* Link traffic by consumer (collective, mover, MoE GEMM streaming), cumulative so a `| tee`
* of these lines can be differenced into rates. */
if (s.link.present &&
(s.link.ar_bytes || s.link.h2d_bytes || s.link.d2h_bytes || s.link.stream_bytes)) {
o += " link ar=" + std::to_string(s.link.ar_bytes);
@@ -308,10 +308,8 @@ std::string LiveView::render_screen(const LiveSnapshot& s) const {
o += "\n";
o += " kv [" + bar(s.kv_util, std::max(10, W / 4), true) + "] " +
share(s.kv_util) + " prefix hit " + share(s.prefix_hit_rate);
/* THE NUMBER THAT PREDICTS THE CLIFF, beside the one that reports it afterwards. Past
* ~75% kv the cache starts dropping prefixes the next turn wants and an agent's turn goes
* from seconds to minutes; the hit rate only falls once that has already happened. Shown
* only when non-zero -- a cache that has never evicted has nothing to say. */
/* Evictions predict a prefix-cache collapse that the hit rate reports only afterwards: past
* ~75% kv the cache drops prefixes the next turn wants. Shown only when non-zero. */
if (s.prefix_evictions) o += " evicted " + grouped(s.prefix_evictions);
o += "\n";
o += " prefill " + tps(s.prefill_tps) + " tok/s decode " + tps(s.decode_tps) + " tok/s";
@@ -322,16 +320,14 @@ std::string LiveView::render_screen(const LiveSnapshot& s) const {
if (s.experts.n_layers > 0 && s.experts.n_experts > 0) {
o += "\n experts by tier " + grouped(s.experts.n_units) + " units " +
size_iec(s.experts.total_bytes) + "\n ";
/* RESIDENCY, ABSOLUTE AND PROPORTIONAL, so it can be read off the legend rather than by
* counting glyphs in the plane. Units and their share, plus the bytes -- a tier's unit
* count and its byte share are not the same ratio, because the tiers hold different
* weight classes. */
/* Residency per tier in the legend: units, their share, and bytes. Unit share and byte
* share differ because the tiers hold different weight classes. */
char tl[192];
for (int t = 0; t < 4; ++t) {
for (int t = 0; t < kLiveTiers; ++t) {
if (!s.experts.units[t]) continue;
snprintf(tl, sizeof tl, "%s%c %-6s\033[0m %s %s %s ",
tier_colour((uint8_t)t), tier_glyph((uint8_t)t),
t == 0 ? "vram" : t == 1 ? "pinned" : t == 2 ? "host" : "ssd",
kTierNames[t],
grouped(s.experts.units[t]).c_str(),
share((double)s.experts.units[t] / (double)s.experts.n_units).c_str(),
size_iec(s.experts.bytes[t]).c_str());
@@ -339,10 +335,9 @@ std::string LiveView::render_screen(const LiveSnapshot& s) const {
}
o += "\n";
/* The plane is usually wider than the terminal (128 experts x 48 layers is normal), so it
* is downsampled by taking the worst tier in each column group. Worst, not average: the
* question the plane answers is "what is going to be slow", and one SSD expert in a group
* of four is what makes that group slow. */
/* The plane is usually wider than the terminal (128 experts x 48 layers is typical), so
* each column group shows its worst tier, not the average: one SSD expert makes the
* group slow. */
const int avail = W - 8;
const int stride = std::max(1, (s.experts.n_experts + avail - 1) / std::max(1, avail));
for (int l = 0; l < s.experts.n_layers; ++l) {
@@ -353,7 +348,9 @@ std::string LiveView::render_screen(const LiveSnapshot& s) const {
uint8_t worst = 0;
for (int k = 0; k < stride && e + k < s.experts.n_experts; ++k) {
size_t idx = (size_t)l * s.experts.n_experts + e + k;
if (idx < s.experts.tier.size()) worst = std::max(worst, s.experts.tier[idx]);
if (idx >= s.experts.tier.size()) continue;
const uint8_t t = s.experts.tier[idx];
if (t < kLiveTiers && kTierRank[t] > kTierRank[worst]) worst = t;
}
o += tier_colour(worst);
o += tier_glyph(worst);
+51 -63
View File
@@ -1,16 +1,14 @@
/* core/server/liveview.h -- the live view (spec §16).
*
* Per-card utilisation and VRAM, throughput, draft acceptance, and the expert plane coloured by
* tier. It is a terminal view and nothing else: no web page, no port, no JSON.
* tier. A terminal view only: no web page, no port, no JSON.
*
* The rule that shapes the implementation is the last sentence of §16 -- piped or redirected it
* prints ordinary lines instead. So there are two renderers, chosen once by isatty(), and the
* non-interactive one emits no escape sequence at all. A log file full of cursor-home sequences
* is a log file you cannot grep, and the failure is silent: it looks fine on the terminal where
* it was written.
* Piped or redirected, it prints ordinary lines instead (spec §16). There are two renderers,
* chosen once by isatty(), and the non-interactive one emits no escape sequences, so a log file
* stays greppable.
*
* The view owns no data. A snapshot function supplied by the engine fills a LiveSnapshot; this
* component only draws it, which keeps the server free of any device dependency.
* The view owns no data: an engine-supplied snapshot function fills a LiveSnapshot and this only
* draws it, which keeps the server free of any device dependency.
*/
#pragma once
@@ -37,55 +35,50 @@ struct CardStat {
double temp_c = 0.0; /* 0 = not sampled */
};
/* rad::kTierCount, restated. This header deliberately does not include the program description --
* a tier arrives here as a byte -- so the size is written out and liveview.cpp static_asserts the
* two against each other. A fifth tier that fits in four slots is an out-of-bounds write that
* costs nothing until it costs everything. */
/* rad::kTierCount, restated so this header need not include the program description (a tier
* arrives here as a byte). liveview.cpp static_asserts that the two agree, since the per-tier
* arrays below are indexed by tier. */
enum { kLiveTiers = 5 };
/* THE EXPERT PLANE, and what the placement engine has been doing to it.
/* The expert plane and the placement engine's activity on it.
*
* The plane itself -- one cell per (layer, expert), valued by rad::Tier -- is the picture. The
* counters beside it are the things the picture cannot say. Residency per tier says how much of
* the model is actually in VRAM; the per-layer counts say whether that residency is SPREAD, since
* a fill that walks the model in order can starve the last layers and the draft head while the
* global count still looks healthy; and the move counters say whether the traffic on the link is
* the engine discovering a working set or re-admitting what it just evicted.
* The plane is one cell per (layer, expert), valued by rad::Tier. The counters say what the
* picture cannot: residency per tier (how much of the model is in VRAM), per-layer counts
* (whether residency is spread, since an in-order fill can starve the last layers and the draft
* head while the global count looks healthy), and moves (whether link traffic is the engine
* finding a working set or re-admitting what it just evicted).
*
* Counted ONCE, here, rather than by each renderer: the terminal view and the web page are two
* drawings of the same snapshot and two independent tallies are two chances to disagree.
* Counted once, here, so the terminal view and the web page draw the same tallies.
*/
struct ExpertPlane {
int n_layers = 0;
int n_experts = 0;
std::vector<uint8_t> tier; /* row-major, size n_layers * n_experts */
/* Residency, by rad::Tier. Sized by kTierCount and not by 4: folding an unknown tier into the
* SSD bucket would report a weight as on disk when it is not. `bytes` is this rank's shard,
* which is the number that has to add up against the VRAM bar beside it. */
/* Residency by rad::Tier, sized by the tier count so an unknown tier is never folded into the
* SSD bucket. `bytes` is this rank's shard, which is what must add up against the VRAM bar. */
int64_t units[kLiveTiers] = {0};
int64_t bytes[kLiveTiers] = {0};
int64_t n_units = 0; /* expert units in the plan; NOT n_layers * n_experts, which
int64_t n_units = 0; /* expert units in the plan; not n_layers * n_experts, which
* counts cells a ragged model never had */
int64_t total_bytes = 0;
int64_t movable = 0; /* how many of them the heat engine is allowed to relocate */
/* Per layer, so a starved layer is visible as a number and not only as a dark band. */
/* Per layer, so a starved layer shows as a number, not only as a dark band. */
std::vector<int32_t> layer_units;
std::vector<int32_t> layer_resident;
/* What the mover did. Cumulative since start: a rate over a poll interval is the reader's
* subtraction, and a counter is the only form that survives being read twice. */
/* Mover activity, cumulative since start; readers take rates by subtracting two polls. */
int64_t promotions = 0, demotions = 0;
/* Is the churn PROGRESS or THRASH? Same move count, opposite meanings -- see HeatStats. */
/* Separate progress from thrash at the same move count; see HeatStats. */
int64_t distinct_promoted = 0, readmits = 0;
/* Why a dispatch moved nothing. `refused` is the guard declining, which is the healthy steady
* state; the starved counts are the mover having nowhere to put the bytes. */
/* Why a dispatch moved nothing. `refused` is the guard declining (the healthy steady state);
* the starved counts mean the mover had nowhere to put the bytes. */
int64_t dispatches = 0, refused = 0, no_candidate = 0;
/* DID THE ROUTER FIND THE EXPERT IN VRAM. `routed` is expert selections seen by the heat
* engine and `routed_resident` the subset that was already there; the difference is what the
* MoE GEMM had to stream across the link, which LinkStat::stream_bytes prices. A residency
* percentage says how much of the model is close; this says how much of the WORK is. */
/* Whether the router found the expert in VRAM. `routed` counts expert selections seen by the
* heat engine, `routed_resident` the subset already resident; the difference was streamed
* across the link (priced by LinkStat::stream_bytes). This measures how much of the work, not
* of the model, is resident. */
int64_t routed = 0, routed_resident = 0;
int64_t no_record = 0, starved_slab = 0, starved_pool = 0, quarantined = 0;
/* The prefill stager's copies (Mover::stage_units), rank 0: layers staged, units and bytes
@@ -93,26 +86,23 @@ struct ExpertPlane {
* the units. */
int64_t stage_layers = 0, staged_units = 0, staged_bytes = 0, stage_overflow = 0;
int64_t stage_copies = 0;
/* HOW MUCH OF THE SLAB IS BORROWED. `flex_bytes` is what the slab holds in VRAM the KV cache
* lent it; `flex_capacity` is how much the cache is lending right now. The pair is what says
* whether the boundary between the two pools is moving, and whether what was lent is being
* used -- a gap between them is lent VRAM holding nothing. */
/* Slab VRAM borrowed from the KV cache: `flex_bytes` is what the slab holds in lent VRAM,
* `flex_capacity` what the cache lends right now. A gap between them is lent VRAM holding
* nothing. */
int64_t flex_bytes = 0, flex_capacity = 0;
bool heat_enabled = false; /* false = the plan is static and none of the above will move */
};
/* WHAT IS ON THE INTERCONNECT, and in what proportion.
/* Interconnect traffic by consumer.
*
* Three things share it and they are never discussed together: the tensor-parallel all-reduce,
* which is a property of the model's width and the batch; the expert mover's promotions and
* demotions, which are a property of the placement policy; and the MoE GEMM streaming an expert
* the router asked for and placement had not put in VRAM, which is what the policy is spending
* the moves to avoid. All three are cumulative byte counts from the same wall clock, so a reader
* who subtracts two polls gets rates that can be compared -- which is the whole question "is the
* link busy because the model is wide, or because placement is thrashing".
* Three things share the link: the tensor-parallel all-reduce (set by model width and batch), the
* expert mover's promotions and demotions (set by placement policy), and the MoE GEMM streaming a
* routed expert that is not in VRAM (what the moves try to avoid). All are cumulative byte counts
* on one clock, so rates from two polls compare directly: is the link busy because the model is
* wide or because placement is thrashing?
*
* `ar_bytes` is the message payload summed over issues; Ctx::ar_bytes documents exactly what that
* is and is not. `h2d`/`d2h` are the mover's own measured copy sizes.
* `ar_bytes` is the message payload summed over issues (see Ctx::ar_bytes). `h2d`/`d2h` are the
* mover's measured copy sizes.
*/
struct LinkStat {
bool present = false; /* false when nothing measured any of it */
@@ -120,19 +110,18 @@ struct LinkStat {
int64_t ar_calls = 0, ar_bytes = 0;
int64_t h2d_bytes = 0, d2h_bytes = 0;
int64_t ssd_reads = 0, ssd_bytes = 0;
/* The MoE GEMM reading a routed expert that was not resident. Not a move and not a
* collective: the third consumer of the link, and the one a promotion is spent to remove. */
/* The MoE GEMM reading a routed expert that was not resident: the traffic promotions aim to
* remove. */
int64_t stream_bytes = 0;
int64_t prefetched = 0, prefetch_bytes = 0;
/* The prefill stager's copies of the next layer's pooled experts (core/place/stager.h). Part
* of `h2d_bytes`, like `prefetch_bytes`: the mover counts every copy it makes there, and a
* reader that wants the promotions alone takes both out. */
/* The prefill stager's copies of the next layer's pooled experts (core/place/stager.h).
* Included in `h2d_bytes`, like `prefetch_bytes`; subtract both for promotions alone. */
int64_t staged_bytes = 0;
};
/* HOW THE RANKS RAN THEIR PASSES, summed over ranks: Ctx::PassCounts says what each is. A played
* pass costs the host a packet copy; every other kind walks the architecture's issue path, so the
* share that is not `played` is where a step's host time goes. */
/* How the ranks ran their passes, summed over ranks (see Ctx::PassCounts). A played pass costs
* the host a packet copy; every other kind walks the architecture's issue path, so the non-played
* share is where a step's host time goes. */
struct PassStat {
bool present = false;
int64_t played = 0, recorded = 0, audited = 0;
@@ -143,8 +132,8 @@ struct PassStat {
struct LiveSnapshot {
int64_t step = 0;
std::string model;
/* Duplicated rather than referenced so that a snapshot is a value the drawing thread can hold
* without racing the scheduler that produced it. */
/* Copied, not referenced, so the drawing thread can hold a snapshot without racing the
* scheduler. */
int64_t waiting = 0, running = 0, preempted = 0;
double kv_util = 0.0, prefix_hit_rate = 0.0;
int64_t prefix_evictions = 0;
@@ -163,8 +152,8 @@ class LiveView {
public:
using Source = std::function<void(LiveSnapshot&)>;
/* `out` defaults to stdout. `interval_ms` is the redraw period; 250 ms is fast enough to see
* a stall and slow enough that the view costs nothing measurable. */
/* `out` defaults to stdout. `interval_ms` is the redraw period; 250 ms shows a stall and
* costs nothing measurable. */
LiveView(Source src, int interval_ms = 250, FILE* out = nullptr);
~LiveView();
@@ -172,8 +161,7 @@ public:
void stop();
/* Both renderers are public because they are the testable part: a snapshot in, a string out,
* no terminal involved. */
/* Public for tests: a snapshot in, a string out, no terminal involved. */
std::string render_screen(const LiveSnapshot& s) const;
std::string render_line(const LiveSnapshot& s) const;
+111 -79
View File
@@ -17,11 +17,16 @@ Histogram::Histogram(std::vector<double> bounds) : bounds_(std::move(bounds)) {
void Histogram::observe(double v) {
if (!std::isfinite(v)) return; /* a NaN latency is a bug upstream, not a data point */
/* Cumulative: every bucket whose bound is >= v counts this observation. Linear because the
* bucket lists are twenty-odd entries and a binary search plus a fixup loop is not faster. */
for (size_t i = 0; i < bounds_.size(); ++i)
if (v <= bounds_[i]) cnt_[i].fetch_add(1, std::memory_order_relaxed);
n_.fetch_add(1, std::memory_order_relaxed);
/* Cumulative: every bucket whose bound is >= v counts this observation. A linear scan, since
* the lists are twenty-odd entries.
*
* The count first, then the buckets widest first, each with release. A scrape reads the
* buckets narrowest first and the count last, with acquire, so an observation it sees in one
* bucket it also sees in every wider one and in the count: the buckets it renders never
* decrease and never exceed the count. */
n_.fetch_add(1, std::memory_order_release);
for (size_t i = bounds_.size(); i-- > 0 && v <= bounds_[i];)
cnt_[i].fetch_add(1, std::memory_order_release);
double cur = sum_.load(std::memory_order_relaxed);
while (!sum_.compare_exchange_weak(cur, cur + v, std::memory_order_relaxed)) {}
}
@@ -41,8 +46,8 @@ std::vector<double> buckets_latency() {
30.0, 40.0, 50.0, 60.0, 120.0, 240.0, 480.0, 960.0, 1920.0, 7680.0};
}
/* vLLM's build_1_2_5_buckets: mantissas 1, 2, 5 at every decade, stopping at the first value past
* max_value. A 32K-context model therefore gets 1..20000 and no more. */
/* vLLM's build_1_2_5_buckets: mantissas 1, 2, 5 at every decade, up to max_value (a 32K-context
* model gets 1..20000). */
std::vector<double> buckets_1_2_5(int64_t max_value) {
std::vector<double> out;
if (max_value < 1) max_value = 1;
@@ -106,9 +111,8 @@ void Metrics::observe_request(int64_t n_prompt, int64_t n_generated,
if (max_tokens > 0) h_params_max_tokens_.observe((double)max_tokens);
if (ttft_s >= 0.0) h_ttft_.observe(ttft_s);
/* TPOT is undefined for a one-token generation -- there is no inter-token interval to
* measure. Recording a zero there would drag every quantile down, so it is simply not an
* observation. */
/* TPOT is undefined for a one-token generation; recording a zero would drag every quantile
* down. */
if (tpot_s >= 0.0 && n_generated > 1) h_tpot_.observe(tpot_s);
if (e2e_s >= 0.0) h_e2e_.observe(e2e_s);
if (decode_s >= 0.0 && n_generated > 1) h_decode_.observe(decode_s);
@@ -157,37 +161,38 @@ void Metrics::sample(const SchedMetrics& m) {
draft_vdepth_top_.store(top, std::memory_order_release);
draft_adapt_on_.store(true, std::memory_order_release);
}
c_preemptions_.inc(std::max(0.0, (double)m.preemptions - c_preemptions_.get()));
c_steps_.inc(std::max(0.0, (double)m.steps - c_steps_.get()));
c_steps_prefill_.inc(std::max(0.0, (double)m.steps_prefill - c_steps_prefill_.get()));
c_steps_mixed_.inc(std::max(0.0, (double)m.steps_mixed - c_steps_mixed_.get()));
c_steps_decode_.inc(std::max(0.0, (double)m.steps_decode - c_steps_decode_.get()));
c_steps_ahead_.inc(std::max(0.0, (double)m.steps_ahead - c_steps_ahead_.get()));
c_prefill_capped_.inc(std::max(0.0, (double)m.prefill_chunks_capped - c_prefill_capped_.get()));
c_rows_unspec_.inc(std::max(0.0,
(double)m.decode_rows_unspeculated - c_rows_unspec_.get()));
c_step_secs_.inc(std::max(0.0, (double)m.step_ns * 1e-9 - c_step_secs_.get()));
c_step_secs_decode_.inc(std::max(0.0,
(double)m.step_ns_decode * 1e-9 - c_step_secs_decode_.get()));
c_prefill_tokens_.inc(std::max(0.0, (double)m.prefill_tokens - c_prefill_tokens_.get()));
c_decode_tokens_.inc(std::max(0.0, (double)m.decode_tokens - c_decode_tokens_.get()));
c_draft_tokens_.inc(std::max(0.0, (double)m.draft_tokens - c_draft_tokens_.get()));
c_draft_accepted_.inc(std::max(0.0, (double)m.draft_accepted - c_draft_accepted_.get()));
c_draft_refills_.inc(std::max(0.0, (double)m.draft_refills - c_draft_refills_.get()));
c_draft_refill_tokens_.inc(
std::max(0.0, (double)m.draft_refill_tokens - c_draft_refill_tokens_.get()));
c_attn_cached_.inc(std::max(0.0, (double)m.attn_cached_tokens - c_attn_cached_.get()));
c_linear_cached_.inc(std::max(0.0, (double)m.linear_cached_tokens - c_linear_cached_.get()));
c_checkpoints_.inc(std::max(0.0, (double)m.checkpoints_written - c_checkpoints_.get()));
/* The cache's own cumulative counts, so the delta is taken the same way the others are.
* A prefix cache that is evicting under steady load is one that cannot hold the working
* set, and the next turn of every session it drops re-prefills from scratch. */
c_prefix_evict_.inc(std::max(0.0, (double)m.prefix_evictions - c_prefix_evict_.get()));
c_prefix_ckpt_evict_.inc(std::max(0.0,
(double)m.prefix_ckpt_evictions - c_prefix_ckpt_evict_.get()));
c_prefix_expired_.inc(std::max(0.0, (double)m.prefix_expired - c_prefix_expired_.get()));
c_prefix_ckpt_expired_.inc(std::max(0.0,
(double)m.prefix_ckpt_expired - c_prefix_ckpt_expired_.get()));
c_preemptions_.advance_to(m.preemptions);
c_steps_.advance_to(m.steps);
c_steps_prefill_.advance_to(m.steps_prefill);
c_steps_mixed_.advance_to(m.steps_mixed);
c_steps_decode_.advance_to(m.steps_decode);
c_steps_ahead_.advance_to(m.steps_ahead);
c_prefill_capped_.advance_to(m.prefill_chunks_capped);
c_steps_held_.advance_to(m.steps_held);
c_rows_unspec_.advance_to(m.decode_rows_unspeculated);
c_step_secs_.advance_to((double)m.step_ns * 1e-9);
c_step_secs_decode_.advance_to((double)m.step_ns_decode * 1e-9);
c_prefill_tokens_.advance_to(m.prefill_tokens);
c_decode_tokens_.advance_to(m.decode_tokens);
c_draft_tokens_.advance_to(m.draft_tokens);
c_draft_accepted_.advance_to(m.draft_accepted);
c_draft_refills_.advance_to(m.draft_refills);
c_draft_refill_tokens_.advance_to(m.draft_refill_tokens);
c_attn_cached_.advance_to(m.attn_cached_tokens);
c_linear_cached_.advance_to(m.linear_cached_tokens);
c_checkpoints_.advance_to(m.checkpoints_written);
/* The cache's own cumulative counts, turned into deltas like the others. */
c_prefix_evict_.advance_to(m.prefix_evictions);
c_prefix_ckpt_evict_.advance_to(m.prefix_ckpt_evictions);
c_prefix_expired_.advance_to(m.prefix_expired);
c_prefix_ckpt_expired_.advance_to(m.prefix_ckpt_expired);
c_ckpt_retired_.advance_to(m.prefix_ckpt_retired);
c_ckpt_lru_.advance_to(m.prefix_ckpt_lru);
c_ckpt_refused_.advance_to(m.prefix_ckpt_refused);
c_cut_no_snapshot_.advance_to(m.hit_cut_no_snapshot);
c_cut_window_.advance_to(m.hit_cut_window);
c_cut_adopt_.advance_to(m.hit_cut_adopt);
c_cut_tokens_.advance_to(m.hit_cut_tokens);
g_linear_hit_.set(m.linear_hit_rate);
}
@@ -226,6 +231,8 @@ struct Writer {
help(name, doc, "counter");
out += name; out += labels; out += ' '; out += num(v); out += '\n';
}
/* The buckets in ascending order, then the count once for both +Inf and _count, the order
* Histogram::observe makes consistent. */
void hist(const char* name, const char* doc, const std::string& labels, const Histogram& h) {
help(name, doc, "histogram");
for (size_t i = 0; i < h.bounds().size(); ++i) {
@@ -234,13 +241,14 @@ struct Writer {
out += ",le=\""; out += num(h.bounds()[i]); out += "\"} ";
out += num((double)h.bucket(i)); out += '\n';
}
const double n = (double)h.count();
out += name; out += "_bucket";
out += labels.substr(0, labels.size() - 1);
out += ",le=\"+Inf\"} ";
out += num((double)h.count()); out += '\n';
out += num(n); out += '\n';
out += name; out += "_sum"; out += labels; out += ' '; out += num(h.sum()); out += '\n';
out += name; out += "_count"; out += labels; out += ' ';
out += num((double)h.count()); out += '\n';
out += num(n); out += '\n';
}
};
@@ -294,8 +302,7 @@ std::string Metrics::render() const {
"Histogram of time to first token in seconds.", L, h_ttft_);
w.hist("vllm:time_per_output_token_seconds",
"Histogram of time per output token in seconds.", L, h_tpot_);
/* The name current vLLM uses for the same measurement. Same data, both spellings, so a
* dashboard written against either version works unchanged. */
/* Current vLLM's name for the same measurement; both spellings are emitted. */
w.hist("vllm:inter_token_latency_seconds",
"Histogram of inter-token latency in seconds.", L, h_tpot_);
w.hist("vllm:e2e_request_latency_seconds",
@@ -312,8 +319,7 @@ std::string Metrics::render() const {
"Histogram of the max_tokens request parameter.", L, h_params_max_tokens_);
/* ---------------- radiance-specific ----------------
* Under our own prefix, never under vllm:. A dashboard that finds an unfamiliar vllm: name is
* a dashboard that has been lied to about which engine it is looking at. */
* Under our own prefix, never under vllm:. */
w.gauge("radiance:prefill_tokens_per_second",
"Prefill throughput over the scheduler's recent window.", L, g_prefill_tps_.get());
w.gauge("radiance:decode_tokens_per_second",
@@ -322,10 +328,10 @@ std::string Metrics::render() const {
"Scheduler steps executed. One forward pass of the model, plus whatever draft "
"rounds followed it; with speculation a step emits more than one token.",
L, c_steps_.get());
/* STEPS BY SHAPE, and how much of the decode ran unspeculated.
* `radiance:decode_rows_unspeculated_total` counts rows that took no draft for ANY reason --
* depth 0, a request that may not speculate, a drafter with nothing to propose. Its rate
* against engine_steps_total says how much of the decode speculation is not reaching. */
/* Steps by shape, and how much of the decode ran unspeculated.
* `radiance:decode_rows_unspeculated_total` counts rows that took no draft for any reason
* (depth 0, a request that may not speculate, a drafter with nothing to propose); its rate
* against engine_steps_total shows how much of the decode speculation misses. */
w.counter("radiance:engine_steps_prefill_total",
"Scheduler steps carrying only prefill chunks.", L, c_steps_prefill_.get());
w.counter("radiance:engine_steps_mixed_total",
@@ -340,24 +346,24 @@ std::string Metrics::render() const {
"Prefill chunks held back so decode rows and waiting requests got into the step "
"(--busy-prefill-chunk).",
L, c_prefill_capped_.get());
w.counter("radiance:engine_steps_held_total",
"Decode-only steps run after a prefill chunk while other sequences decode "
"(--prefill-interleave).", L, c_steps_held_.get());
w.counter("radiance:decode_rows_unspeculated_total",
"Decode rows that took no draft, for any reason.",
L, c_rows_unspec_.get());
/* THE STEP TIME, AS A COUNTER AND NOT A RATE. Divide by engine_steps_decode_total for the
* milliseconds a decode step costs. Wall clock over a step count answers that only for a
* window that was saturated and carried no prefill, and says nothing when it was not. */
/* Step time as a counter. Divided by engine_steps_decode_total it gives the cost of a decode
* step; wall clock over a step count does so only for a saturated window with no prefill. */
w.counter("radiance:engine_step_seconds_total",
"Seconds spent inside a scheduler step, all shapes.", L, c_step_secs_.get());
w.counter("radiance:engine_step_seconds_decode_total",
"Seconds spent inside a scheduler step carrying only decode rows.",
L, c_step_secs_decode_.get());
/* THE EXACT TOTALS, beside the rate gauges above rather than instead of them. A gauge is what
* a dashboard wants; a counter is what a comparison wants, because two runs that settled into
* different mixes of prefill and decode have incomparable rates and perfectly comparable
* totals. These are the only counters that answer it: vllm:generation_tokens_total is charged
* when a request FINISHES, and is therefore identically zero over a window in which nothing
* finishes. */
/* Exact totals beside the rate gauges. Two runs with different prefill/decode mixes have
* incomparable rates but comparable totals. vllm:generation_tokens_total is charged when a
* request finishes, so it reads zero over a window in which nothing finishes; these are
* charged per step. */
w.counter("radiance:prefill_tokens_total",
"Prompt tokens the engine has computed, exact.", L, c_prefill_tokens_.get());
w.counter("radiance:decode_tokens_total",
@@ -375,11 +381,9 @@ std::string Metrics::render() const {
"Cached prompt tokens those hits gave back to be recomputed.",
L, c_draft_refill_tokens_.get());
/* PREFIX CACHING, DECOUPLED (spec §7.3). vllm:gpu_prefix_cache_hit_rate 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 them would hide the
* effect the decoupling exists to expose. Without these a deployment cannot tell whether
* linear checkpointing is working at all. */
/* Decoupled prefix caching (spec §7.3). vllm:gpu_prefix_cache_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 rather than averaged in. */
w.gauge("radiance:linear_prefix_cache_hit_rate",
"Fraction of prompt tokens served from a linear-state checkpoint (spec 7.3).",
L, g_linear_hit_.get());
@@ -389,10 +393,9 @@ std::string Metrics::render() const {
"Prompt tokens served from a linear-state checkpoint.", L, c_linear_cached_.get());
w.counter("radiance:linear_checkpoints_written_total",
"Linear-state checkpoints written.", L, c_checkpoints_.get());
/* THE LEADING INDICATOR FOR A PREFIX-CACHE COLLAPSE. `gpu_prefix_cache_hit_rate` falls
* only after a reusable prefix is already gone; this rises as it is dropped. Above ~75%
* pool utilisation the cache starts evicting prefixes that the next turn wants, and an
* agent's turn-2 latency goes from seconds to minutes. */
/* Leading indicator of prefix-cache collapse: the hit rate falls only after a reusable prefix
* is gone, while evictions rise as it is dropped. Above ~75% pool utilisation the cache
* starts evicting prefixes the next turn wants. */
w.counter("radiance:prefix_cache_evictions_total",
"Prefix-cache entries evicted (attention blocks).", L, c_prefix_evict_.get());
w.counter("radiance:prefix_cache_ckpt_evictions_total",
@@ -403,14 +406,44 @@ std::string Metrics::render() const {
w.counter("radiance:prefix_cache_ckpt_expired_total",
"Prefix-cache linear-state checkpoints taken out by --prefix-cache-ttl.", L,
c_prefix_ckpt_expired_.get());
/* Why snapshots went, and why hits were cut: a hybrid server that re-prefills long prompts
* shows it here before the linear hit rate says so. */
{
const std::string base = L.substr(0, L.size() - 1);
auto labelled = [&](const char* name, const char* label, const char* value, double v) {
w.out += name; w.out += base; w.out += ','; w.out += label; w.out += "=\"";
w.out += value; w.out += "\"} "; w.out += num(v); w.out += '\n';
};
w.help("radiance:prefix_cache_ckpt_evictions_by_reason_total",
"Linear-state checkpoints evicted, by reason: released by --checkpoint-policy, or "
"the least recently used of a store retention left full.", "counter");
labelled("radiance:prefix_cache_ckpt_evictions_by_reason_total", "reason", "retention",
c_ckpt_retired_.get());
labelled("radiance:prefix_cache_ckpt_evictions_by_reason_total", "reason", "store_full",
c_ckpt_lru_.get());
w.counter("radiance:prefix_cache_ckpt_refused_total",
"Checkpoints not written because every snapshot slot was in use by a restore "
"in the same step.", L, c_ckpt_refused_.get());
w.help("radiance:prefix_hit_cuts_total",
"Admissions whose prefix hit reused nothing, by reason: no snapshot at or below "
"the hit, a windowed group no window snapshot covers, or blocks that could not be "
"adopted.", "counter");
labelled("radiance:prefix_hit_cuts_total", "reason", "no_snapshot",
c_cut_no_snapshot_.get());
labelled("radiance:prefix_hit_cuts_total", "reason", "windowed_group", c_cut_window_.get());
labelled("radiance:prefix_hit_cuts_total", "reason", "adopt_failed", c_cut_adopt_.get());
w.counter("radiance:prefix_hit_cut_tokens_total",
"Prompt tokens the attention cache held and admission computed again, because "
"the hit resumed at a snapshot below it or reused nothing.", L,
c_cut_tokens_.get());
}
w.gauge("radiance:draft_acceptance_ratio",
"Fraction of speculative draft tokens accepted (spec 10).", L, g_draft_accept_.get());
/* CONDITIONAL, per draft position: of the verifies that reached position j -- every earlier
* one accepted -- the fraction that took j as well. The pooled ratio above cannot tell a
* drafter that decays from one whose later rounds are broken; these can, and the companion
* `_reached_total` says how much evidence each position carries. `_accepted_total` gives the
* same ratio over any window: at a fixed depth the next position's reach would do, but an
* adaptive window can end at j with j taken. */
"Fraction of speculative draft tokens accepted.", L, g_draft_accept_.get());
/* Conditional acceptance per draft position: of the verifies that reached position j (every
* earlier one accepted), the fraction that took j too. Unlike the pooled ratio, this tells a
* drafter that decays from one whose later rounds are broken. `_reached_total` is the evidence
* per position; `_accepted_total` gives the ratio over any window (an adaptive window can end
* at j with j taken, so the next position's reach is not enough). */
const int seen = draft_pos_seen_.load(std::memory_order_acquire);
if (seen > 0) {
const std::string base = L.substr(0, L.size() - 1);
@@ -431,9 +464,8 @@ std::string Metrics::render() const {
w.out += "radiance:draft_position_accepted_total" + base + ",position=\"" +
std::to_string(j) + "\"} " + num(g_draft_pos_accepted_[j].get()) + '\n';
}
/* THE ADAPTIVE DRAFT WINDOW, only while --draft-window adaptive is in force: where the policy stands --
* at one sequence, that sequence's window -- and where it has been, as verifies by the
* number of drafts they carried. */
/* Adaptive draft window, only under --draft-window adaptive: the current mean window (at one
* sequence, that sequence's window) and its history as verifies by drafts carried. */
if (draft_adapt_on_.load(std::memory_order_acquire)) {
w.gauge("radiance:draft_depth_adaptive",
"Mean draft window the adaptive policy gives the running sequences.",
+37 -44
View File
@@ -1,24 +1,20 @@
/* core/server/metrics.h -- Prometheus /metrics, with vLLM's metric names.
*
* The names are not ours to choose. There is a published Grafana dashboard for vLLM and a great
* deal of alerting built on `vllm:time_to_first_token_seconds_bucket` and friends, and the point
* of matching them is that swapping vLLM for radiance behind an existing deployment changes
* nothing on the observability side. So: the vLLM names, the vLLM bucket boundaries, and the
* vLLM label set (`model_name`, `engine`), copied exactly. Where vLLM renamed something we emit
* both spellings -- `vllm:gpu_cache_usage_perc` is what every dashboard in the wild queries and
* `vllm:kv_cache_usage_perc` is what current vLLM emits, and two gauges cost nothing.
* Names, bucket boundaries and the label set (`model_name`, `engine`) are copied exactly from vLLM,
* so existing vLLM dashboards and alerts work unchanged against radiance. Where vLLM renamed a
* metric both spellings are emitted (`vllm:gpu_cache_usage_perc`, which dashboards query, and
* `vllm:kv_cache_usage_perc`, which current vLLM emits).
*
* Anything vLLM does not have goes under `radiance:`. Inventing a new `vllm:` name would be worse
* than useless: it would look to a dashboard like a metric it knows and is not.
* Anything vLLM lacks goes under `radiance:`; a new `vllm:` name would pass for a metric a
* dashboard knows.
*
* What is deliberately NOT emitted is as important. `vllm:iteration_tokens_total` and
* `vllm:request_queue_time_seconds` are properties of the scheduler's step loop, not of the HTTP
* boundary, and the server cannot observe them. Emitting a plausible-looking approximation of a
* latency breakdown is how a dashboard ends up lying, so they are absent until the scheduler
* reports them, and their absence is documented rather than papered over.
* Not emitted: `vllm:iteration_tokens_total` and `vllm:request_queue_time_seconds`. They belong to
* the scheduler's step loop, which the HTTP boundary cannot observe, and an approximation would
* mislead. They stay absent until the scheduler reports them.
*/
#pragma once
#include <algorithm>
#include <atomic>
#include <cstdint>
#include <memory>
@@ -39,6 +35,8 @@ public:
double cur = v_.load(std::memory_order_relaxed);
while (!v_.compare_exchange_weak(cur, cur + v, std::memory_order_relaxed)) {}
}
/* Raises the count to `total`, a cumulative value kept elsewhere; never lowers it. */
void advance_to(double total) { inc(std::max(0.0, total - get())); }
double get() const { return v_.load(std::memory_order_relaxed); }
private:
std::atomic<double> v_{0.0};
@@ -52,17 +50,18 @@ private:
std::atomic<double> v_{0.0};
};
/* Cumulative buckets, the Prometheus convention: bucket i counts observations <= bounds[i], and
* the implicit +Inf bucket is `count`. Atomics rather than a lock because /metrics is scraped
* from one thread while every HTTP thread observes into it. */
/* Cumulative buckets, the Prometheus convention: bucket i counts observations <= bounds[i] and
* the implicit +Inf bucket is `count`. Atomic, since every HTTP thread observes while /metrics
* is scraped. */
class Histogram {
public:
explicit Histogram(std::vector<double> bounds);
void observe(double v);
const std::vector<double>& bounds() const { return bounds_; }
uint64_t bucket(size_t i) const { return cnt_[i].load(std::memory_order_relaxed); }
uint64_t count() const { return n_.load(std::memory_order_relaxed); }
/* Read the buckets in ascending order, then the count, for a consistent picture (observe). */
uint64_t bucket(size_t i) const { return cnt_[i].load(std::memory_order_acquire); }
uint64_t count() const { return n_.load(std::memory_order_acquire); }
double sum() const { return sum_.load(std::memory_order_relaxed); }
private:
@@ -72,8 +71,8 @@ private:
std::atomic<double> sum_{0.0};
};
/* vLLM's bucket layouts, verbatim. Changing one of these silently invalidates every histogram
* quantile a dashboard computes across a version boundary, so they are constants, not options. */
/* vLLM's bucket layouts, verbatim. Changing one breaks every histogram quantile a dashboard
* computes across versions, so they are constants, not options. */
std::vector<double> buckets_ttft(); /* vllm:time_to_first_token_seconds */
std::vector<double> buckets_tpot(); /* vllm:time_per_output_token_seconds */
std::vector<double> buckets_latency(); /* every vllm:request_*_seconds */
@@ -81,8 +80,8 @@ std::vector<double> buckets_1_2_5(int64_t max_value); /* token-count histogram
/* ------------------------------------------------------------------ the registry */
/* The finish reasons `vllm:request_success_total` is broken down by. Fixed, because a label whose
* cardinality depends on user input is a Prometheus outage waiting to happen. */
/* The finish reasons `vllm:request_success_total` is broken down by. A fixed set, because label
* cardinality must never depend on user input. */
enum class SuccessReason { Stop = 0, Length, ToolCalls, Abort, Error, N_ };
class Metrics {
@@ -115,48 +114,42 @@ private:
Gauge g_kv_max_tokens_, g_kv_max_bytes_;
Gauge g_prefill_tps_, g_decode_tps_, g_draft_accept_, g_preempted_;
Gauge queue_depth_;
/* The per-position draft hazard, kept as plain gauges because that is what it is: a
* conditional acceptance rate at each draft position, which is the only number that separates
* a drafter that decays from one whose later rounds are broken. See core/sched/draft.h. */
/* Per-position conditional draft acceptance (see render() and core/sched/draft.h). */
enum { MAX_DRAFT_POS = 64 };
Gauge g_draft_pos_[MAX_DRAFT_POS];
Gauge g_draft_pos_reached_[MAX_DRAFT_POS];
Gauge g_draft_pos_accepted_[MAX_DRAFT_POS];
std::atomic<int> draft_pos_seen_{0};
/* THE ADAPTIVE DRAFT WINDOW (--draft-window adaptive): the mean window of the running sequences,
* and the verifies by the window they carried, index = drafts. Rendered only while the policy
* is on, so a deployment without it exposes exactly what it always did. */
/* Adaptive draft window (--draft-window adaptive): the running sequences' mean window, and
* verifies by the window they carried (index = drafts). Rendered only while the policy is on. */
Gauge g_draft_depth_adapt_;
Gauge g_draft_vdepth_[MAX_DRAFT_POS + 1];
std::atomic<bool> draft_adapt_on_{false};
std::atomic<int> draft_vdepth_top_{0}; /* the deepest window with a verify counted */
/* sample() turns the scheduler's cumulative totals into counter increments by reading each
* counter and adding the difference. Two scrapes doing that at once both read the old value
* and both add the whole difference, so they are serialised. */
/* sample() turns the scheduler's cumulative totals into counter increments (read, add the
* difference). Concurrent scrapes would both add the same difference, so they are serialised. */
std::mutex sample_mu_;
Counter c_prompt_tokens_, c_generation_tokens_, c_preemptions_;
/* ENGINE STEPS. Tokens a second cannot answer "how long is a step", and with speculation the
* two stop being the same question: a step emits 1 + however many drafts survived. Exposed as
* a counter so two scrapes and a clock give the step time directly. */
/* Engine steps. With speculation a step emits 1 + the accepted drafts, so tokens/s does not
* give step time; two scrapes of this counter and a clock do. */
Counter c_steps_;
/* STEPS BY SHAPE, and the decode rows a mixed step cost speculation. Exposed as counters so
* two scrapes give the rate over a window rather than a number dominated by startup. */
/* Steps by shape, and decode rows that ran unspeculated. Counters, so two scrapes give the
* rate over a window rather than an average dominated by startup. */
Counter c_steps_prefill_, c_steps_mixed_, c_steps_decode_, c_rows_unspec_, c_steps_ahead_;
Counter c_prefill_capped_;
/* SECONDS SPENT INSIDE A STEP, and the decode half of it. A step time is not wall clock over
* a step count -- SchedMetrics::step_ns says why -- and without these every scraper has to
* assume a saturated window and no prefill in it. */
Counter c_prefill_capped_, c_steps_held_;
/* Seconds inside a step, all shapes and decode-only. Wall clock over a step count is not a
* step time (see SchedMetrics::step_ns). */
Counter c_step_secs_, c_step_secs_decode_;
/* THE EXACT TOTALS BEHIND THE RATE GAUGES. A gauge answers "how fast right now"; a counter
* answers "how much between these two scrapes", and only the second survives a comparison
* between two runs that settled into different mixes. */
/* Exact totals behind the rate gauges; see render(). */
Counter c_prefill_tokens_, c_decode_tokens_, c_draft_tokens_, c_draft_accepted_;
Counter c_draft_refills_, c_draft_refill_tokens_;
Counter c_attn_cached_, c_linear_cached_, c_checkpoints_;
Counter c_prefix_evict_, c_prefix_ckpt_evict_;
Counter c_prefix_expired_, c_prefix_ckpt_expired_;
Counter c_ckpt_retired_, c_ckpt_lru_, c_ckpt_refused_;
Counter c_cut_no_snapshot_, c_cut_window_, c_cut_adopt_, c_cut_tokens_;
Gauge g_linear_hit_;
Counter c_success_[(size_t)SuccessReason::N_];
Counter c_rejected_, c_disconnect_, c_overflow_;
+1017 -759
View File
File diff suppressed because it is too large. Load diff
+211 -214
View File
@@ -1,19 +1,13 @@
/* core/server/oai.h -- the OpenAI schema, in and out.
*
* Two rules shape everything here.
* Errors are values. Nothing here throws; every entry point returns RAD_OK or a negative status
* and fills an ApiError carrying its HTTP status, `param` and a message naming the problem. An
* exception crossing the transport would close the connection with no body.
*
* Errors are values. Nothing in this file throws; every entry point returns RAD_OK or a negative
* status and fills an ApiError that already knows its HTTP status, its `param`, and a message
* that names what was wrong. The HTTP layer turns that into a status code and a body. An
* exception crossing the transport is a connection closed with no body, which is the least
* diagnosable thing a client can be handed.
*
* A parameter that would change the answer and is not served is a 400 that names it, not a
* silent ignore: a client that sends a `logit_bias` and gets a 200 has been told its bias was
* applied, and the bug report that follows ("the model ignores my bias") is unanswerable from the
* server side. Such a field is accepted at its "off" value, which is what llama.cpp-built clients
* send on every request. A field this server has never heard of is ignored, as llama.cpp and vLLM
* ignore it (oai.cpp, key vetting).
* A parameter that would change the answer and is not served is a 400 naming it, never a silent
* ignore, so a client is not told its `logit_bias` was applied when it was not. Such a field is
* accepted at its "off" value, which llama.cpp-built clients send on every request. An unknown
* field is ignored, as llama.cpp and vLLM do (oai.cpp, key vetting).
*/
#pragma once
#include "iface.h"
@@ -37,12 +31,11 @@ struct ApiError {
std::string message;
std::string param; /* "" when the error is not about one field */
std::string code; /* "" when there is nothing more specific to say */
/* The values `param` takes, when the error is a value outside a known set: `supported` in the
* envelope, so a client can retry with one rather than parse the sentence. */
/* The legal values of `param` when the error is a value outside a known set; sent as
* `supported` so a client can retry with one. */
std::vector<std::string> supported;
/* A prompt the context cannot hold: its length and the context's, under llama-server's names,
* so a client that compacts its history on overflow reads the numbers rather than the
* sentence. -1 leaves them out. */
/* For a prompt the context cannot hold: its length and the context's, under llama-server's
* names, for clients that compact their history on overflow. -1 leaves them out. */
int64_t n_prompt_tokens = -1;
int64_t n_ctx = -1;
@@ -52,22 +45,25 @@ struct ApiError {
ApiError err_bad(const std::string& param, const std::string& why);
ApiError err_unsupported(const std::string& param, const std::string& why);
ApiError err_not_implemented(const std::string& what);
/* SERIALISE OUT OF LINE. nlohmann's dump() inlines a shared_ptr release that GCC 16 speculatively
* devirtualises onto std::mutex and then reports as an out-of-bounds destroy -- a false positive
* in a vendored header, which appears or not depending on how deeply the CALLING function
* inlined. That makes "is this file warning-clean" a property of how short its handlers are,
* which is not something anybody can act on. One definition, in one translation unit. */
std::string json_dump(const json& j);
ApiError err_overloaded(const std::string& why);
ApiError err_internal(const std::string& why);
/* DRY's sequence breakers when a request names none: the deployment's when it set any (`set`, even
* to an empty list), otherwise llama.cpp's four (newline, colon, quote, asterisk). */
std::vector<std::string> dry_breakers(const std::vector<std::string>& deployment, bool set);
/* Out of line on purpose: inlined, nlohmann's dump() trips a GCC 16 false-positive warning
* (a speculatively devirtualised shared_ptr release reported as an out-of-bounds destroy) that
* comes and goes with how deeply the caller inlines. */
std::string json_dump(const json& j);
/* ================================================================== a parsed request */
enum class Endpoint { Chat, Completion, Embedding };
/* WHICH API A CHAT REQUEST CAME IN THROUGH, and so which shape its answer goes out in. Every shape
* is parsed into the same chat request (Anthropic's is translated first, anthropic_to_chat) and
* served by the same path; only the bytes on the wire differ. */
/* The API a chat request came in through, which decides the shape of its answer. Every shape is
* parsed into the same chat request (Anthropic's is translated first, anthropic_to_chat) and
* served by the same path; only the wire bytes differ. */
enum class ApiShape { OpenAI, Anthropic, Responses, LlamaNative };
struct PromptInput {
@@ -90,31 +86,33 @@ struct OaiRequest {
* `prompt_progress` chunks while the prompt is read. */
bool timings_per_token = false;
bool return_progress = false;
/* The conversation as the client names it (OpenRouter's `session_id`), "" when it names none:
* a label on /sessions, nothing else. */
/* The client's conversation name (OpenRouter's `session_id`), "" if none; only a label on
* /sessions. */
std::string session_label;
/* The build, as OpenAI's `system_fingerprint` and llama.cpp's own: what produced the reply. */
/* The build, as OpenAI's and llama.cpp's `system_fingerprint`. */
std::string system_fingerprint;
int n = 1;
SamplingParams sp;
int32_t max_tokens = 0;
std::vector<std::string> stop;
/* Of `stop`, how many the client sent; the rest are the chat format's own end-of-turn
* markers. A reply cut on one of the first is Anthropic's `stop_sequence`, on the rest its
* `end_turn`. */
/* How many of `stop` the client sent; the rest are the chat format's end-of-turn markers.
* A cut on a client stop is Anthropic's `stop_sequence`, on the rest its `end_turn`. */
size_t n_client_stops = 0;
/* The assistant text a continued conversation ends in (assistant prefill), "" otherwise. The
* OpenAI shape answers the whole message, as llama-server does; Anthropic's answers what
* OpenAI shape answers the whole message, as llama-server does; Anthropic's answers only what
* follows it, as Anthropic's API does. */
std::string continued;
/* The Responses API's request fields its response object echoes (instructions, tools,
/* Anthropic's `context_management` was sent: the answer reports `applied_edits: []`, as the
* conversation is served as sent. */
bool context_management = false;
/* The Responses API request fields its response object echoes (instructions, tools,
* tool_choice, text, reasoning, ...), as a JSON object; "" for the other shapes. */
std::string echo_json;
/* llama-server's native /completion: the generated token ids beside the text. */
bool return_tokens = false;
/* The reasoning block's closer when the reply starts inside the block, else "": the stop
* strings above then apply only after it (IDetokenizer::defer_stops_until). */
* strings then apply only after it (IDetokenizer::defer_stops_until). */
std::string stops_after;
/* Generate past end-of-text, to max_tokens. See Request::ignore_eos. */
bool ignore_eos = false;
@@ -130,29 +128,28 @@ struct OaiRequest {
/* OpenAI's deprecated functions API: the request sent `functions`, so the reply carries its
* call as `function_call` (one at most) and ends in finish_reason "function_call". */
bool legacy_functions = false;
/* FOR THE REQUEST LOG, counted while the parse walks the body anyway: the messages and tools
* a chat request carried, and the last user message's opening (one line, bounded) that the
* debug level prints so a log line can be matched to what was typed. Completion requests
* leave them at zero and empty. */
/* For the request log, counted during the parse: the messages and tools a chat request
* carried, and a bounded one-line opening of the last user message for the debug level.
* Zero and empty for completion requests. */
int n_messages = 0;
int n_tools = 0;
std::string last_user;
std::string peer; /* the handler sets it from the transport; "" in-process */
int64_t t_received_ns = -1; /* HttpRequest::t_received_ns, for timings' ttft and total */
bool parse_tools = false;
/* The reply parser this request's render produced. Per request and not per server: it is the
* model's format bound to the tools THIS call sent, so two concurrent requests against the
* same model can legitimately need different parsers. */
/* The reply parser this request's render produced. Per request, not per server: it binds the
* model's format to the tools this call sent, so concurrent requests may need different
* parsers. */
std::shared_ptr<IReplyParser> reply_parser;
/* The control tokens this request's reply must be decoded AS TEXT, so `tool_parser` can see
* the structure it is looking for. See ITokenizer::detokenizer. */
/* Control tokens this reply must be decoded as text, so `tool_parser` can see its structure.
* See ITokenizer::detokenizer. */
std::vector<std::string> preserved_tokens;
/* /v1/embeddings */
bool base64_embeddings = false;
/* OpenAI's `dimensions`: the vector's first `dimensions` components, renormalised -- a
* Matryoshka-trained model's shorter embedding. 0 is the model's own width. */
/* OpenAI's `dimensions`: the vector's first `dimensions` components, renormalised (a
* Matryoshka-trained model's shorter embedding). 0 is the model's own width. */
int64_t dimensions = 0;
/* /v1/embeddings: a soft-token budget for the request's images, 0 the server's. */
int32_t image_tokens = 0;
@@ -165,13 +162,10 @@ struct OaiLimits {
std::string model_id = "radiance";
std::string version; /* the build, for `system_fingerprint` */
int64_t max_ctx = 0; /* 0 = unknown, no length check */
/* What a request that names no max_tokens may generate. 0 is "whatever the context leaves",
* resolved against the prompt in clamp_max_tokens, 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. */
/* What a request that names no max_tokens may generate. 0, the default as in vLLM, is
* "whatever the context leaves", resolved against the prompt and max_ctx in
* clamp_max_tokens. A small fixed default ends a reasoning model's answer inside its
* reasoning with finish_reason "length", which chat clients do not show. */
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;
@@ -184,67 +178,58 @@ struct OaiLimits {
bool allow_audio = false;
bool supports_logprobs = false;
/* THE DEPLOYMENT'S DEFAULT REASONING EFFORT, empty for "whatever the template's own default
* is". It exists because the template's default is not always a servable one: Qwen3.8's is
* `xhigh`, which on a short task reliably spends the whole token budget inside <think> and
* returns a turn with EMPTY content and finish_reason "length" -- an agent turn that carries
* no answer and no tool call. The per-request field is the right control and most OpenAI
* clients never send it, so without this an operator serving such a client cannot reach the
* dial at all. Seeded only when the request says nothing, so a caller always wins. */
/* The deployment's default reasoning effort; empty uses the template's own default. Needed
* because a template's default is not always servable: Qwen3.8's is `xhigh`, which on a
* short task can spend the whole budget inside <think> and return empty content with
* finish_reason "length". Most OpenAI clients never send the field. Applied only when the
* request says nothing, so a caller always wins. */
std::string default_reasoning_effort;
/* THE WORDS THE CHAT TEMPLATE TAKES AS `reasoning_effort`, found at startup by rendering each
* word this server knows of (Server::probe_reasoning_efforts). Empty when the template takes
* any word -- it does not read the variable, or reads it without refusing one -- and when
* nothing was probed. A request whose effort the template refuses is answered with this set
* rather than with the template's traceback (template_refusal). */
/* The words the chat template accepts as `reasoning_effort`, found at startup by rendering
* each known word (Server::probe_reasoning_efforts). Empty when the template takes any word
* or nothing was probed. A refused effort is answered with this set instead of the
* template's traceback (template_refusal). */
std::vector<std::string> reasoning_efforts;
/* --reasoning-effort-map: an effort a request sends, replaced by the deployment's word before
* the template sees it. For a client that always sends a word of OpenAI's ladder ("high")
* to a model whose template has its own ("xhigh"). */
/* --reasoning-effort-map: a request's effort word replaced by the deployment's before the
* template sees it, e.g. OpenAI's "high" to a template's "xhigh". */
std::map<std::string, std::string> reasoning_effort_map;
/* A STARTUP PROBE, NOT A REQUEST: what the template refuses is the answer being asked for, so
* its refusal is not logged (ChatRenderOptions::quiet). */
/* A startup probe, not a request: the template's refusal is the expected answer and is not
* logged (ChatRenderOptions::quiet). */
bool probe = false;
/* 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. */
/* The deployment's default `thinking_token_budget`, -1 for none. Agent frameworks size
* max_tokens per turn and send no budget, and a reasoning block that spends all of max_tokens
* leaves no answer. 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 sampler 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
* -- which is the right thing to fall back to and the wrong thing to serve a checkpoint
* with: a model tuned against a truncated tail, sampled without one, will occasionally draw
* a token from far down its distribution. End-of-turn is one of those tokens, and drawing it
* early ends an agent's turn with prose and no tool call, which reads as the server dropping
* the request. The deployment resolves this from what the checkpoint itself states and hands
* the result over here.
* The struct's own defaults truncate only to the sampler's 1024 candidates (temperature 1,
* top_k 0, top_p 1). A model tuned against a tighter cut occasionally draws from far down its
* distribution without one, and an early end-of-turn ends an agent's turn with no tool call.
* The deployment resolves these from what the checkpoint states.
*
* Only the sampler knobs are read: the grammar fields are per request and are filled in
* after this is copied. A request that names a field always wins, exactly as with
* default_reasoning_effort. */
* Only the sampler knobs are read; grammar fields are per request and filled in after this is
* copied. A field the request names always wins. */
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. */
/* SamplingParams cannot tell a stated empty breaker list from an unstated one: 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. */
/* The deployment's chat template variables, key -> JSON text, applied under the request's own
* chat_template_kwargs so the request wins per key. 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. */
/* What a request says about thinking, in any of its three spellings: `effort` when it names a
* non-empty reasoning effort (top-level or in chat_template_kwargs), `thinking` when it says
* anything at all (an effort, or enable_thinking in either place). */
struct RequestThinking {
bool thinking = false;
bool effort = false;
@@ -254,27 +239,25 @@ 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. */
* The chat endpoint and /tokenize both render through this, so both count the same prompt. */
void apply_template_defaults(const json& b, const OaiLimits& lim, ChatRenderOptions* opt);
/* --reasoning-effort-map, on the effort chat_template_kwargs put in the render options: a mapped
* word replaces it, and a word mapped to "none" or "minimal" turns thinking off instead. The chat
* endpoint maps the top-level `reasoning_effort` itself, before it reads "none" and "minimal";
* this is the kwargs spelling, for it and for /tokenize. */
/* --reasoning-effort-map, applied to the effort chat_template_kwargs put in `opt`: a mapped word
* replaces it, and one mapped to "none" or "minimal" turns thinking off instead. The chat endpoint
* maps the top-level `reasoning_effort` itself; this handles the kwargs spelling for it and for
* /tokenize. */
void map_reasoning_effort(const OaiLimits& lim, ChatRenderOptions* opt);
/* THE 400 FOR A TEMPLATE THAT REFUSED A RENDER. An effort outside the template's known set
* (OaiLimits::reasoning_efforts) is named as `reasoning_effort` with the set in `supported`, the
* way OpenAI answers an unsupported value; anything else is `messages` with the template's own
* sentence. */
/* The 400 for a template that refused a render. An effort outside OaiLimits::reasoning_efforts is
* reported against `reasoning_effort` with the set in `supported`, as OpenAI reports an
* unsupported value; anything else against `messages` with the template's own sentence. */
ApiError template_refusal(const ChatRenderOptions& opt, const OaiLimits& lim, int rs,
const std::string& why);
/* 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. */
/* True when `v` is legal for the sampler field a request spells `field`; otherwise `why` states
* the legal set as a 400 would. The same table checks requests and the command-line flag that
* sets the field's default, so an accepted default is always servable. A field with no bounds
* takes any value. */
bool sampler_value_ok(const char* field, double v, std::string* why);
struct OaiDeps {
@@ -285,17 +268,25 @@ struct OaiDeps {
IEmbedder* embed = nullptr;
};
/* The request-key policy (oai.cpp, key vetting) as lists, so a test can cover every key. */
struct KeyPolicy {
std::vector<std::string> common, chat, completion, embedding; /* accepted per endpoint */
std::vector<std::string> inert, inert_prefixes;
std::vector<std::string> guarded; /* refused unless at their neutral value */
};
KeyPolicy request_key_policy();
/* Parse. `body` is the raw request body; a malformed body is a 400 that says where. */
int parse_chat_request(const std::string& body, const OaiDeps& d, const OaiLimits& lim,
OaiRequest* out, ApiError* err);
/* `native` is llama-server's /completion: its `return_tokens`, and a prompt array of strings and
* token ids mixed as ONE prompt, as llama-server reads it. */
/* `native` is llama-server's /completion: `return_tokens`, and a prompt array of strings and
* token ids mixed as one prompt, as llama-server reads it. */
int parse_completion_request(const std::string& body, const OaiDeps& d, const OaiLimits& lim,
OaiRequest* out, ApiError* err, bool native = false);
/* A media part's bytes out of a data: URL; any other URL is refused, never fetched. */
int decode_media_url(const std::string& url, const std::string& field,
std::vector<uint8_t>* out, ApiError* err);
/* A prompt holding RAD_MEDIA_MARKER once a media part, tokenised with each marker replaced by its
/* Tokenise a prompt holding one RAD_MEDIA_MARKER per media part, replacing each marker with its
* part's processed token run; `media` is consumed in order. */
int tokenize_with_media(const std::string& rendered, const OaiDeps& d,
std::vector<std::pair<MediaKind, std::vector<uint8_t>>>& media,
@@ -306,11 +297,10 @@ int parse_embeddings_request(const std::string& body, const OaiDeps& d, const Oa
/* ================================================================== responses */
/* One emitted token's logprobs as the wire carries them. `bytes` is the token's own bytes and
* `text` is their longest well-formed UTF-8 prefix -- a byte-level token can hold half a
* character, and a JSON string cannot -- llama-server's spelling. `end` is where the token's
* decoded text ends in the choice's text, which is what decides whether it went out before a stop
* string cut the reply. */
/* One emitted token's logprobs as the wire carries them. `bytes` is the token's bytes and `text`
* their longest well-formed UTF-8 prefix (a byte-level token can hold half a character, which a
* JSON string cannot), as llama-server spells it. `end` is where the token's text ends in the
* choice's text, which decides whether it went out before a stop string cut the reply. */
struct LogprobAlt {
int32_t token = 0;
std::string text, bytes;
@@ -324,11 +314,11 @@ struct LogprobEntry {
size_t end = 0;
};
/* The entries as a JSON array's elements, comma-joined, in OpenAI's chat shape with llama-server's
* `id` beside each token -- which is also llama-server's native `completion_probabilities`. */
/* The entries as comma-joined JSON array elements, in OpenAI's chat shape with llama-server's
* `id` beside each token; also llama-server's native `completion_probabilities`. */
std::string logprobs_content(const LogprobEntry* e, size_t n);
/* OpenAI's legacy /v1/completions `logprobs` object for the entries, `offset` the text offset of
* the first, with llama-server's `content` array beside the legacy arrays. */
/* OpenAI's legacy /v1/completions `logprobs` object, `offset` the text offset of the first entry,
* with llama-server's `content` array beside the legacy arrays. */
std::string logprobs_legacy(const LogprobEntry* e, size_t n, size_t offset);
struct ChoiceOut {
@@ -344,35 +334,31 @@ 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
/* Of `completion`, the tokens inside the reasoning block, markers included (OpenAI's
* completion_tokens_details.reasoning_tokens). -1 when the block cannot be counted; 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.
/* One request's timing, in llama.cpp's `timings` shape (read by proxies and dashboards built for
* llama-server, e.g. llama-swap). /metrics holds the same quantities summed over all requests.
*
* 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
* prompt_n prompt tokens computed, excluding prefix-cache hits; cache_n is those
* prompt_ms from the request's first scheduled step to its first token: the prefill,
* without the admission wait
* 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
* ttft_ms from the moment the server had the whole request body to the first token: the
* parse, the chat template, tokenisation, the wait for admission and the prefill.
* The time the body took to arrive is not in it, so a client far from the server
* reads the server's own share of what it measured
* were proposed, as in llama.cpp
* ttft_ms from having the whole request body to the first token: parse, chat template,
* tokenisation, admission wait and prefill. Body transfer time is excluded, so
* a remote client sees the server's own share
* total_ms from the same moment to the last token
*
* 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
* Rates are prompt_n / prompt_ms and (predicted_n - 1) / predicted_ms, since the first token
* belongs to the prompt phase; the latter matches /metrics' time per output token. A rate with a
* zero count or time is null. Over several choices the counts are summed and each time spans 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 */
@@ -392,23 +378,19 @@ std::string text_completion_body(const OaiRequest& r, const std::vector<ChoiceOu
const UsageOut& u, const TimingsOut& t = TimingsOut());
std::string embeddings_body(const OaiRequest& r, const std::vector<std::vector<float>>& vecs,
const UsageOut& u);
/* ONE MODEL ENTRY: what /v1/models lists and /v1/models/:id returns on its own. */
/* One model entry: what /v1/models lists and /v1/models/:id returns. */
struct ModelCard {
std::string id;
int64_t created = 0;
/* The context the server was started with (--max-model-len, else the container's trained
* length), the field vLLM's model card carries. Clients size their own context from it -- an
* agent that compresses its history at the window's edge, a UI that shows how much is left --
* and without it they guess from the model's name, which is wrong whenever the deployment sets
* its own length. 0 leaves the field out rather than reporting a length the server does not
* know. */
/* The served context (--max-model-len, else the container's trained length), vLLM's model
* card field. Clients size their own context from it (history compression, UI meters);
* without it they guess from the model name. 0 leaves the field out. */
int64_t max_model_len = 0;
/* What the server loaded (ServerOptions::model_path), vLLM's `root`. Empty leaves it out. */
std::string root;
/* What the model can be asked for -- tools, reasoning, images -- as /server_info reports it.
* There is no field for it in OpenAI's model object, so without this a client learns it by
* sending a request and reading the refusal; the entry it already fetches can say so up
* front. A JSON object as text, spliced in as it is; empty leaves it out. */
/* What the model can be asked for (tools, reasoning, images), as /server_info reports it.
* OpenAI's model object has no such field. A JSON object as text, spliced in verbatim; empty
* leaves it out. */
std::string capabilities;
};
/* The list, for GET /v1/models. */
@@ -417,10 +399,9 @@ std::string models_body(const ModelCard& m);
* list of one, and its SDK reads `id` off the top level. */
std::string model_body(const ModelCard& m);
/* The usage chunk of each endpoint's stream: an SSE event whose choices array is empty and whose
* 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. */
/* The usage chunk of each endpoint's stream: an SSE event with an empty choices array and only
* `usage`. Sent when stream_options.include_usage is set, once per stream after every choice's
* final chunk, since `n` choices share one prompt and one total. */
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,
@@ -428,55 +409,58 @@ std::string chat_usage_chunk(const OaiRequest& r, const UsageOut& u,
/* The `timings` object, for a stream's final chunks. */
json timings_json(const TimingsOut& t);
/* Whether a parsed reply's calls are all calls a client can run: none left open, each named,
* each one's arguments one JSON value (json_partial.h). A reply is answered `tool_calls` by this
* alone, streamed or not. */
/* Whether every call in a parsed reply is runnable: none left open, each named, each one's
* arguments a single JSON value (json_partial.h). This alone decides finish_reason
* `tool_calls`, streamed or not. */
bool calls_complete(const ParsedMessage& m);
/* ================================================================== streaming
*
* One of these per choice. It feeds the generated text to the choice's reply reader as it grows
* and forwards each increment the reader completes as an SSE chunk. The reader never revises
* what it has delivered, so nothing here diffs, holds back or reconciles: a delta is the next
* piece of the answer, and the chunks a client concatenates are the answer the buffered path
* returns.
* One per choice. Feeds the generated text to the choice's reply reader as it grows and writes
* each increment the reader completes as an SSE chunk. The reader never revises what it has
* delivered, so nothing here diffs or holds back: the concatenated deltas equal the buffered
* answer.
*
* THE WIRE SHAPE IS THE SUBCLASS'S. Reading the reply -- the reader, the message it adds up to,
* the finish it implies -- is the same for every API this server speaks, so it lives here once;
* what one increment looks like on the wire is OpenAI's chunk (ChatDeltaStream) or Anthropic's
* event (AnthropicStream).
* Reading the reply is shared by every API; the subclass owns the wire shape of an increment:
* OpenAI's chunk (ChatDeltaStream), Anthropic's event (AnthropicStream) or the Responses API's
* (ResponsesStream).
*/
class ReplyStream {
public:
ReplyStream(const OaiRequest& r, int index, const IReplyParser* parser);
virtual ~ReplyStream() = default;
/* What opens the stream: OpenAI's `role: assistant` chunk, Anthropic's message_start. */
/* What the stream sends when it opens, before the request has run: the Responses API's
* response.created and response.in_progress, which report the response object's state as
* OpenAI's do. The chat and Anthropic streams send nothing here. */
virtual std::string first_chunk() = 0;
/* What the stream sends once the reply's first token exists, ahead of any of its text, which
* a reader or a stop string may still hold back: OpenAI's opening chunk, Anthropic's
* message_start. A client that times its first event then times the first token. */
virtual std::string started() { return std::string(); }
/* Feed the text generated since the last push; returns the bytes for what it completed.
* `is_final` says the generation is over, which resolves whatever the reader was holding. */
std::string push(std::string_view appended, bool is_final);
/* What closes the choice: the finish reason, and this choice's `timings` when they are valid
/* What closes the choice: the finish reason, and this choice's `timings` when valid
* (llama.cpp sends them on the final chunk). `u` is the request's usage, for the shapes that
* close a message with it. */
virtual std::string final_chunk(Finish f, const TimingsOut& t, const UsageOut& u) = 0;
/* What closes a choice the engine failed, in place of final_chunk: the shape's own failure,
* so a client reading to the terminal event never takes a truncated reply as complete.
* OpenAI's chunks have none, so theirs is the final chunk with finish_reason "error" and the
* error object after it. */
/* Closes a choice the engine failed, in place of final_chunk, with the shape's own failure so
* a client never takes a truncated reply as complete. OpenAI's chunks have no failure event,
* so the default is the final chunk with finish_reason "error" followed by the error object. */
virtual std::string error_chunk(const ApiError& e, const TimingsOut& t, const UsageOut& u);
/* What the whole generation parsed to -- the non-streaming shape. Complete once push has
* been called with is_final. */
/* The whole generation parsed (the non-streaming shape). Complete once push has been called
* with is_final. */
const ParsedMessage& parsed() const { return last_; }
Finish adjusted_finish(Finish f) const;
/* llama.cpp's `timings_per_token`, for the shapes that carry timings. */
virtual void set_timings(const TimingsOut&) {}
/* Logprobs entries (logprobs_content's elements) for the next chunk this stream writes, for
* the shapes that carry them; the others drop them. */
/* Logprobs entries (logprobs_content's elements) for the next chunk written, for the shapes
* that carry them; the others drop them. */
virtual void add_logprobs(const std::string&) {}
protected:
@@ -496,20 +480,21 @@ protected:
std::vector<ReplyDelta> ev_;
};
/* ANTHROPIC'S MESSAGES API, translated into the chat request it means (`*chat`, a /v1/chat/completions
* body) so that every refusal and default is the chat endpoint's. `*label` is the conversation's
* label if the request carries one (metadata.user_id). Claude Code's per-request billing stamp in
* the system prompt is held constant, as llama-server holds it, or no turn of a conversation could
* reuse the one before it. */
/* Anthropic's Messages API, translated into the equivalent /v1/chat/completions body (`*chat`),
* so every refusal and default is the chat endpoint's. `*label` is the conversation label if the
* request carries one (metadata.user_id); `*context_management` is set when the request sent
* one (OaiRequest::context_management). Claude Code's per-request billing stamp in the system
* prompt is held constant, as llama-server does, so consecutive turns can reuse the prefix
* cache. */
int anthropic_to_chat(const std::string& body, const OaiLimits& lim, std::string* chat,
std::string* label, ApiError* err);
std::string* label, ApiError* err, bool* context_management = nullptr);
/* The non-streaming answer, and an error, in Anthropic's shapes. */
std::string anthropic_message_body(const OaiRequest& r, const ChoiceOut& c, const UsageOut& u);
std::string anthropic_error_body(const ApiError& e);
/* OPENAI'S RESPONSES API, translated into the chat request it means, as Anthropic's is. `*echo` is
* the request's fields the response object repeats back. previous_response_id needs responses
* stored server-side and is refused; tool types other than function have no chat equivalent and
* are left out, as llama-server leaves them out. */
/* OpenAI's Responses API, translated into the equivalent chat request like Anthropic's. `*echo`
* holds the request fields the response object repeats. previous_response_id needs server-side
* storage and is refused; non-function tool types have no chat equivalent and are dropped, as
* llama-server does. */
int responses_to_chat(const std::string& body, const OaiLimits& lim, std::string* chat,
std::string* echo, ApiError* err);
std::string responses_body(const OaiRequest& r, const ChoiceOut& c, const UsageOut& u);
@@ -517,19 +502,24 @@ std::string responses_body(const OaiRequest& r, const ChoiceOut& c, const UsageO
/* Anthropic's stop_reason for a finish and the stop string that caused it. */
const char* anthropic_stop_reason(const OaiRequest& r, Finish f, const std::string& stop_word);
/* OpenAI's chat.completion.chunk. */
/* OpenAI's chat.completion.chunk. The opening chunk (`role: assistant`, empty content) goes out
* with the choice's first token (started), not when the stream opens, as vLLM and llama-server
* send it: a client that times its first data chunk (llama-benchy's ttfr) then times the first
* token, not the start of the prefill. It precedes every other chunk of the choice, also when
* the reply has no text. */
class ChatDeltaStream final : public ReplyStream {
public:
ChatDeltaStream(const OaiRequest& r, int index, const IReplyParser* parser)
: ReplyStream(r, index, parser), legacy_(r.legacy_functions) {}
std::string first_chunk() override;
std::string started() override;
std::string final_chunk(Finish f, const TimingsOut& t, const UsageOut& u) override;
/* llama.cpp's `timings_per_token`: the timings the next pushes' chunks carry, beside
* `choices` as the final chunk carries them. Invalid timings carry nothing. */
/* llama.cpp's `timings_per_token`: the timings the next chunks carry beside `choices`, as the
* final chunk does. Invalid timings carry nothing. */
void set_timings(const TimingsOut& t) override;
/* OpenAI's `logprobs.content` on the next chunk out: entries wait for one, because a push may
* complete no delta (a tool call's opening, a held-back byte) and the tokens still count. */
/* OpenAI's `logprobs.content` on the next chunk out. Entries wait for a chunk because a
* push may complete no delta (a tool call's opening, a held-back byte). */
void add_logprobs(const std::string& elems) override;
private:
@@ -537,23 +527,27 @@ private:
std::string chunk(json delta, const char* finish_reason, const TimingsOut* t = nullptr);
std::string lp_; /* pending logprobs entries, comma-joined */
/* A delta's chunk is written, not built: the frame around the delta object is the same in
* every one, so it is serialised once, and the delta between is written with
* json_quote_append. The bytes are the ones chunk() writes for the same delta. */
/* Delta chunks are written, not built: the frame around the delta object is serialised once
* and the delta written with json_quote_append. The bytes match what chunk() writes. */
void delta_open(std::string& out);
void delta_close(std::string& out);
/* The opening chunk, once, ahead of the first one written. */
void open_role(std::string& out);
bool role_sent_ = false;
std::string head_; /* `data: {...,"choices":[{"index":N,"delta":`, built on first use */
std::string timings_; /* `"timings":{...}` for every delta chunk, or "" */
bool legacy_; /* OaiRequest::legacy_functions */
};
/* ANTHROPIC'S EVENTS: message_start, then a content block a kind -- thinking, text, each tool_use
* -- opened, filled by deltas and stopped, then message_delta with the stop reason and the usage,
* and message_stop. The prefill a continued conversation ends in is not repeated (`continued`). */
/* Anthropic's events: message_start once the first token exists (started); each content block
* (thinking, text, each tool_use) opened, filled by deltas and stopped; then message_delta with
* the stop reason and usage, and message_stop. message_start precedes every other event, an
* error included. The prefill of a continued conversation is not repeated (`continued`). */
class AnthropicStream final : public ReplyStream {
public:
AnthropicStream(const OaiRequest& r, int index, const IReplyParser* parser);
std::string first_chunk() override;
std::string started() override;
std::string final_chunk(Finish f, const TimingsOut& t, const UsageOut& u) override;
/* Anthropic's `error` event, which ends the stream with no message_stop. */
std::string error_chunk(const ApiError& e, const TimingsOut& t, const UsageOut& u) override;
@@ -565,21 +559,25 @@ private:
std::string emit(const std::vector<ReplyDelta>& ev) override;
void open(std::string& out, Block b, const ToolCall* tc);
void close(std::string& out);
void text_delta(std::string& out, const std::string& text);
void release_held(std::string& out);
static void event(std::string& out, const char* type, const json& data);
const OaiRequest* r_;
int64_t n_input_ = 0;
std::string skip_; /* the prefill still to be passed over */
std::string held_; /* content matching the start of `skip_` so far, not yet sent */
std::string stop_word_;
Block block_ = Block::None;
int n_blocks_ = 0; /* blocks opened so far: the next one's index */
bool started_ = false; /* message_start sent */
};
/* THE RESPONSES API'S EVENTS: response.created and .in_progress; an output item a kind --
* reasoning, the message, each function call -- added, its content part added, filled by deltas,
* and done; then response.completed (or .incomplete at the token limit) with the whole response.
* Every event carries its output_index, content_index and sequence_number, which the OpenAI SDK's
* stream accumulator places deltas by. */
/* The Responses API's events: response.created and .in_progress; per output item (reasoning, the
* message, each function call) item added, content part added, deltas, done; then
* response.completed (or .incomplete at the token limit) with the whole response. Every event
* carries output_index, content_index and sequence_number, by which the OpenAI SDK's stream
* accumulator places deltas. */
class ResponsesStream final : public ReplyStream {
public:
ResponsesStream(const OaiRequest& r, int index, const IReplyParser* parser);
@@ -600,14 +598,14 @@ private:
Item item_ = Item::None;
std::string item_id_, text_; /* the open item's id and its text so far */
size_t call_ = 0; /* the open call's index into last_.tool_calls */
std::vector<std::string> items_; /* every closed item, serialised, in output order */
std::vector<json> items_; /* every closed item, in output order */
int64_t seq_ = 0;
UsageOut usage_;
const char* incomplete_ = nullptr;
};
/* The SSE terminator. Written once at the end of every stream, including a failed one, because a
* client blocked on the reader has no other way to learn the stream is over. */
/* The SSE terminator. Written once at the end of every stream, failed ones included, since a
* blocked client reader has no other way to learn the stream is over. */
extern const char* const SSE_DONE;
std::string sse_event(const std::string& json_text);
@@ -617,18 +615,17 @@ std::string sse_error(const ApiError& e);
std::string base64_encode(const void* data, size_t len);
bool base64_decode(const std::string& in, std::vector<uint8_t>* out);
/* A token id as a request spells it: an integer in [0, INT32_MAX]. False for anything else, and
* the caller refuses the request -- narrowing instead would make 2^32 + 5 an alias of token 5. */
/* A token id as a request spells it: an integer in [0, INT32_MAX]. False otherwise, and the
* caller refuses the request; narrowing would make 2^32 + 5 an alias of token 5. */
bool token_id(const json& v, int32_t* out);
/* Parse a request body into a tree of at most json_value_budget(max_ctx) values, nested at most
* kJsonMaxDepth deep. A syntax error comes back discarded, as json::parse's would; a body with
* more values than the budget sets `*over`, and one nested deeper than the bound sets `*deep`,
* and either comes back holding only what fitted, which the caller refuses. See the definition
* for why the tree is bounded rather than the body alone. */
* kJsonMaxDepth deep. A syntax error returns discarded, as json::parse does. Exceeding the value
* budget sets `*over`, exceeding the depth sets `*deep`, and either returns a partial tree the
* caller refuses. See the definition for why the tree, not just the body, is bounded. */
json parse_json_bounded(const std::string& body, int64_t max_ctx, bool* over, bool* deep);
/* The body of a generation endpoint: parse_json_bounded, and a 400 saying which bound it broke or
* that it is not one JSON object. */
/* The body of a generation endpoint: parse_json_bounded, and a 400 naming the broken bound or
* saying it is not one JSON object. */
int parse_request_object(const std::string& body, const OaiLimits& lim, json* b,
ApiError* err);
int64_t json_value_budget(int64_t max_ctx);
+978
View File
@@ -0,0 +1,978 @@
/* realtime.cpp -- OpenAI's realtime transcription session, over a WebSocket at /v1/realtime.
*
* The upload route (speech.cpp) transcribes a recording once it has ended. This one is sent the
* audio as it is captured and answers with the words as they settle, as OpenAI's live
* transcription does: deltas while the audio arrives, and a completed transcript for each turn
* once it is committed.
*
* Protocol: OpenAI's realtime one in its transcription form. The client sends `session.update`
* (session.type "transcription", or the beta's `transcription_session.update`) and
* `input_audio_buffer.append` / `.commit` / `.clear`. The server sends `session.created` /
* `.updated`, `input_audio_buffer.committed` / `.cleared` / `.speech_started` /
* `.speech_stopped`, `conversation.item.input_audio_transcription.delta` / `.completed` /
* `.failed`, and `error`. Audio is 16-bit little-endian mono PCM, base64 in an append or the same
* bytes as a binary frame, at the session's rate (24 kHz unless it names another), resampled to
* the model's.
*
* Settling: the encoder takes a clip whole, so a turn in progress is heard again from its start
* each time enough new audio has come in, one short pass whose prompt is the turn so far. Each
* pass is held to what the earlier ones settled (the settled reply tokens follow the prompt as the
* start of the reply, so the pass decodes only what comes after them) and settles all of its reply
* but the last few tokens, which the end of the audio can still change: a word cut off mid-sound,
* or the full stop the model puts after what it has heard so far. Settled text is sent as a delta
* and never taken back; the rest is sent as `radiance.input_audio_transcription.tentative`, which
* each pass replaces. OpenAI's protocol has no such event, and a client that does not know it
* ignores it.
*
* A turn ends at the client's commit, or at a pause with server_vad turn detection, and is then
* heard once more, whole, for its completed transcript. A turn that reaches the length of one
* encoder pass is committed at its quietest point in the last five seconds, and the rest goes on
* as the next turn.
*
* The model's side comes from its plugin (RadAudioFormat) through the helpers the upload route
* uses; this file knows OpenAI's side.
*
* Threads: the connection's thread reads messages and queues them. The session's thread does
* everything else (the audio, the passes, every event sent), so the session's state has one owner
* and its events go out in the order they happen.
*/
#include "server.h"
#include "server_priv.h"
#include "mm/processor.h"
#include "mm/resample.h"
#include "rad_internal.h"
#include <nlohmann/json.hpp>
#include <algorithm>
#include <chrono>
#include <cmath>
#include <condition_variable>
#include <ctime>
#include <deque>
#include <mutex>
#include <thread>
namespace rad {
namespace server {
namespace {
using ojson = nlohmann::ordered_json;
using Clock = std::chrono::steady_clock;
/* A pass once this much audio has come in since the turn's last one began. */
constexpr double kStepSeconds = 0.5;
/* No pass hears less than this. */
constexpr double kFirstPassSeconds = 0.5;
/* Nothing settles before the turn has this much audio: the first words of a turn heard on their
* own are where the model guesses most. */
constexpr double kSettleAfterSeconds = 1.0;
/* The most one pass may decode. Thirty seconds of the fastest speech is a few hundred tokens. */
constexpr int32_t kMaxTokensPerPass = 512;
/* The client messages a session may have queued and not yet taken in. */
constexpr size_t kMaxQueuedBytes = 16u << 20;
/* Committed turns not yet transcribed: past either bound the session has fallen behind its
* audio for good, and is closed with an error rather than left to grow. */
constexpr double kMaxBehindSeconds = 120.0;
constexpr size_t kMaxBehindTurns = 64;
/* A client commit needs at least this much audio, as OpenAI's does. */
constexpr int64_t kMinCommitMs = 100;
/* Pause detection: a frame, the speech that starts a turn, and the level nothing under counts as
* speech however quiet the room. */
constexpr int32_t kFrameMs = 20;
constexpr int kStartFrames = 3;
constexpr double kSpeechFloorDb = -55.0;
/* The reply tokens left unsettled, by OpenAI's `delay`: how far behind the speech the settled
* text may run. A settled word is never taken back, even when the rest of the sentence would have
* changed it, so the default leaves a few words open: on LibriSpeech, four tokens settled
* "The English forwarded" once as "The English voted", and six did not. The tentative text shows
* the open words meanwhile. */
int unsettled_for(const std::string& delay) {
if (delay == "minimal") return 3;
if (delay == "low") return 4;
if (delay == "high") return 8;
if (delay == "xhigh") return 10;
return 6; /* medium */
}
bool starts_with(const std::string& s, const std::string& p) {
return s.size() >= p.size() && s.compare(0, p.size(), p) == 0;
}
std::string rtrim(std::string s) {
while (!s.empty() && std::isspace((unsigned char)s.back())) s.pop_back();
return s;
}
/* A string member, or `def` when it is absent or not a string. */
std::string str_of(const ojson& o, const char* k, const std::string& def) {
return o.contains(k) && o[k].is_string() ? o[k].get<std::string>() : def;
}
ojson event(const char* type) {
ojson o;
o["type"] = type;
o["event_id"] = random_id("event_");
return o;
}
} /* namespace */
/* One turn: its audio at the model's rate, and what of its transcript has gone out. */
struct RtTurn {
std::string id;
std::vector<float> audio;
int64_t start_ms = 0; /* on the session's clock */
bool committed = false;
bool dropped = false; /* cleared before it was committed */
Clock::time_point committed_at;
std::vector<int32_t> settled; /* reply tokens every later pass is held to */
std::string sent; /* transcript text sent as deltas */
std::string tentative; /* the tentative text last sent */
size_t heard = 0; /* audio.size() when its last pass began */
int64_t n_prompt = 0, n_gen = 0;
int passes = 0;
};
struct Server::RealtimeSession {
std::string id;
std::string peer;
/* The connection's thread to the session's: messages, and whether the peer is gone. */
std::mutex m;
std::condition_variable cv;
std::deque<std::pair<std::string, bool>> inbox; /* (message, binary) */
size_t inbox_bytes = 0;
bool peer_gone = false;
bool overflow = false;
/* Everything below is the session thread's alone. */
std::string model;
bool beta = false; /* answers in the beta's event names */
int32_t rate = 24000; /* the client's audio */
std::string language_code; /* as the client named it, "" for none */
std::string language; /* the model's name for it, "" to detect */
std::string prompt;
std::vector<std::string> keywords;
std::string delay;
int unsettled = 6;
bool vad = false;
double threshold = 0.5;
int prefix_ms = 300;
int silence_ms = 500;
int32_t model_rate = 16000;
std::unique_ptr<mm::Resampler> rs;
int64_t clock = 0; /* samples at the model's rate heard so far */
std::vector<float> frame; /* pause detection's frame in progress */
std::vector<float> recent; /* the audio before speech, for the turn's lead-in */
double floor_db = NAN;
bool speaking = false;
int run = 0, quiet = 0;
std::shared_ptr<RtTurn> open; /* the turn the audio goes into */
std::deque<std::shared_ptr<RtTurn>> turns; /* committed, not yet completed */
std::string last_item;
struct Pass {
std::shared_ptr<RtTurn> turn;
bool final = false;
size_t heard = 0;
OaiRequest r;
std::vector<Generation> gens;
bool running = false;
} pass;
int64_t n_turns = 0;
int64_t ms(int64_t samples) const { return samples * 1000 / model_rate; }
std::string context() const {
std::string c = prompt;
if (!keywords.empty()) {
if (!c.empty()) c += "\n";
for (size_t i = 0; i < keywords.size(); ++i) c += (i ? ", " : "") + keywords[i];
}
return c;
}
};
/* ------------------------------------------------------------------ the connection's thread */
void Server::handle_realtime(const HttpRequest& req, WsConn& ws) {
auto refuse = [&](const char* type, const char* code, const std::string& why, int close_code) {
ojson o = event("error");
ojson e;
e["type"] = type;
e["code"] = code;
e["message"] = why;
e["param"] = nullptr;
e["event_id"] = nullptr;
o["error"] = std::move(e);
ws.send(json_dump(o));
RAD_INFO("realtime refused from %s: %s", req.peer.c_str(), why.c_str());
ws.close(close_code, code);
};
if (stopping_.load()) return refuse("server_error", "shutting_down",
"the server is shutting down", 1001);
if (!deps_.sched || !deps_.tok || !deps_.speech || !deps_.speech->transcribes() || !deps_.mm ||
!deps_.mm->accepts(MediaKind::Audio) || deps_.mm->audio_rate() <= 0)
return refuse("invalid_request_error", "model_not_supported",
"this model does not transcribe: its architecture plugin states no "
"transcription format (rad_arch_audio_format), or it was started without "
"its audio encoder", 1008);
/* A session holds a connection's thread and one of its own for its whole life, and runs one
* pass at a time: more sessions than the engine has sequences would only queue. */
const int64_t cap = std::max<int64_t>(1, opt_.max_seqs);
if (realtime_sessions_.fetch_add(1) >= cap) {
realtime_sessions_.fetch_sub(1);
return refuse("server_error", "session_limit",
fmt("this server holds %lld realtime sessions at once; try again later",
(long long)cap), 1013);
}
struct Count {
std::atomic<int64_t>& n;
~Count() { n.fetch_sub(1); }
} count{ realtime_sessions_ };
/* One admission place for the session's whole life, which its passes run in, so a session
* counts against the queue (and the HTTP workers sized from it) like any request. */
if (admit(1, req.peer))
return refuse("server_error", "rate_limit_exceeded",
"the admission queue is full; try again later", 1013);
struct Place {
Server& srv;
~Place() { srv.release(1); }
} place{ *this };
RealtimeSession s;
s.id = random_id("sess_");
s.peer = req.peer;
s.model = opt_.model_id;
s.model_rate = deps_.mm->audio_rate();
std::thread worker([this, &s, &ws] { realtime_run(s, ws); });
/* The session's thread ends once the peer is gone, however this one leaves. */
struct Join {
RealtimeSession& s;
std::thread& t;
~Join() {
{
std::lock_guard<std::mutex> lk(s.m);
s.peer_gone = true;
}
s.cv.notify_one();
if (t.joinable()) t.join();
}
} join{ s, worker };
std::string msg;
bool binary = false;
while (ws.read(&msg, &binary)) {
std::lock_guard<std::mutex> lk(s.m);
if (s.inbox_bytes + msg.size() > kMaxQueuedBytes) {
s.overflow = true;
s.cv.notify_one();
break;
}
s.inbox_bytes += msg.size();
s.inbox.emplace_back(std::move(msg), binary);
s.cv.notify_one();
}
}
/* ------------------------------------------------------------------ the session's thread */
void Server::realtime_run(RealtimeSession& s, WsConn& ws) {
bool server_closed = true;
try {
server_closed = realtime_loop(s, ws);
} catch (const std::exception& e) {
RAD_ERR("realtime %s failed: %s", s.id.c_str(), e.what());
ojson o = event("error");
ojson err;
err["type"] = "server_error";
err["code"] = "internal_error";
err["message"] = std::string("the session failed: ") + e.what();
err["param"] = nullptr;
err["event_id"] = nullptr;
o["error"] = std::move(err);
ws.send(json_dump(o));
ws.close(1011, "internal error");
}
if (s.pass.running) {
cancel_all(s.pass.gens, !server_closed);
record(s.pass.r, s.pass.gens, Finish::Cancelled, /*quiet=*/true);
retire(s.pass.gens);
s.pass.running = false;
}
RAD_INFO("realtime %s closed: %lld turns, %.1fs of audio", s.id.c_str(),
(long long)s.n_turns, (double)s.clock / s.model_rate);
}
bool Server::realtime_loop(RealtimeSession& s, WsConn& ws) {
const SpeechFormat& f = *deps_.speech;
const int64_t max_clip = deps_.mm->audio_max_samples();
const int64_t frame_n = (int64_t)s.model_rate * kFrameMs / 1000;
/* Where a turn that reaches the length of a pass is cut: its last five seconds, or half of it
* if that is less. Nothing in this stretch settles, so whatever has gone out as a delta was
* heard before the cut, wherever in the stretch the cut lands. */
const int64_t cut_zone =
max_clip > 0 ? std::min<int64_t>(max_clip / 2, 5 * (int64_t)s.model_rate) : 0;
s.rs.reset(new mm::Resampler(s.rate, s.model_rate));
auto send = [&](const ojson& o) { ws.send(json_dump(o)); };
auto error = [&](const char* type, const std::string& code, const std::string& why,
const std::string& param, const ojson& client_event) {
ojson o = event("error");
ojson e;
e["type"] = type;
e["code"] = code;
e["message"] = why;
e["param"] = param.empty() ? ojson(nullptr) : ojson(param);
e["event_id"] = client_event.is_string() ? client_event : ojson(nullptr);
o["error"] = std::move(e);
send(o);
};
/* ---- the session as the client sees it */
auto session_json = [&]() {
ojson tr;
tr["model"] = s.model;
tr["language"] = s.language_code.empty() ? ojson(nullptr) : ojson(s.language_code);
tr["prompt"] = s.prompt;
ojson td = nullptr;
if (s.vad) {
td = ojson::object();
td["type"] = "server_vad";
td["threshold"] = s.threshold;
td["prefix_padding_ms"] = s.prefix_ms;
td["silence_duration_ms"] = s.silence_ms;
}
ojson o;
if (s.beta) {
o["id"] = s.id;
o["object"] = "realtime.transcription_session";
o["input_audio_format"] = "pcm16";
o["input_audio_transcription"] = std::move(tr);
o["turn_detection"] = std::move(td);
o["input_audio_noise_reduction"] = nullptr;
return o;
}
if (!s.keywords.empty()) tr["keywords"] = s.keywords;
if (!s.delay.empty()) tr["delay"] = s.delay;
ojson fmt_o;
fmt_o["type"] = "audio/pcm";
fmt_o["rate"] = s.rate;
ojson in;
in["format"] = std::move(fmt_o);
in["transcription"] = std::move(tr);
in["turn_detection"] = std::move(td);
in["noise_reduction"] = nullptr;
o["type"] = "transcription";
o["object"] = "realtime.transcription_session";
o["id"] = s.id;
o["audio"]["input"] = std::move(in);
return o;
};
/* ---- turns */
auto new_turn = [&](int64_t start_ms) {
auto t = std::make_shared<RtTurn>();
t->id = random_id("item_");
t->start_ms = start_ms;
return t;
};
auto commit_open = [&]() {
std::shared_ptr<RtTurn> t = std::move(s.open);
s.open.reset();
t->committed = true;
t->committed_at = Clock::now();
ojson o = event("input_audio_buffer.committed");
o["previous_item_id"] = s.last_item.empty() ? ojson(nullptr) : ojson(s.last_item);
o["item_id"] = t->id;
send(o);
s.last_item = t->id;
s.turns.push_back(std::move(t));
++s.n_turns;
};
/* A turn as long as one pass takes is committed at its quietest point in the last five
* seconds of that pass; what follows that point goes on as the next turn. */
auto bound_open = [&]() {
while (s.open && max_clip > 0 && (int64_t)s.open->audio.size() >= max_clip) {
std::vector<float>& a = s.open->audio;
const int64_t cut = speech_quiet_point(a, max_clip - cut_zone, max_clip, s.model_rate);
std::vector<float> rest(a.begin() + cut, a.end());
a.resize((size_t)cut);
const int64_t start = s.open->start_ms + s.ms(cut);
commit_open();
s.open = new_turn(start);
s.open->audio = std::move(rest);
if (s.vad) {
ojson o = event("input_audio_buffer.speech_started");
o["audio_start_ms"] = start;
o["item_id"] = s.open->id;
send(o);
}
}
};
/* ---- pause detection: a frame's level against the room's, tracked as its quietest */
auto vad_frame = [&](const float* x, int64_t n) {
double e = 0.0;
for (int64_t i = 0; i < n; ++i) e += (double)x[i] * x[i];
const double db = 10.0 * std::log10(e / (double)n + 1e-12);
if (std::isnan(s.floor_db) || db < s.floor_db) s.floor_db = db;
else s.floor_db += s.speaking ? 0.002 : 0.02; /* 0.1 dB/s in speech, 1 dB/s out of it */
const double margin = 6.0 + 18.0 * s.threshold;
const bool voiced = db > std::max(s.floor_db + margin, kSpeechFloorDb);
s.clock += n;
if (!s.speaking) {
s.recent.insert(s.recent.end(), x, x + n);
s.run = voiced ? s.run + 1 : 0;
const size_t lead = (size_t)((int64_t)s.model_rate * s.prefix_ms / 1000 +
kStartFrames * n);
if (s.run >= kStartFrames) {
const size_t take = std::min(lead, s.recent.size());
s.open = new_turn(s.ms(s.clock) - s.ms((int64_t)take));
s.open->audio.assign(s.recent.end() - (std::ptrdiff_t)take, s.recent.end());
s.recent.clear();
s.speaking = true;
s.quiet = 0;
ojson o = event("input_audio_buffer.speech_started");
o["audio_start_ms"] = s.open->start_ms;
o["item_id"] = s.open->id;
send(o);
} else if (s.recent.size() > lead + (size_t)s.model_rate) {
s.recent.erase(s.recent.begin(), s.recent.end() - (std::ptrdiff_t)lead);
}
return;
}
s.open->audio.insert(s.open->audio.end(), x, x + n);
s.quiet = voiced ? 0 : s.quiet + 1;
if ((int64_t)s.quiet * kFrameMs >= s.silence_ms) {
s.speaking = false;
s.run = 0;
ojson o = event("input_audio_buffer.speech_stopped");
o["audio_end_ms"] = s.ms(s.clock);
o["item_id"] = s.open->id;
send(o);
commit_open();
return;
}
bound_open();
};
/* Audio at the model's rate, into the open turn or through pause detection. */
auto take = [&](const std::vector<float>& x) {
if (x.empty()) return;
if (!s.vad) {
if (!s.open) s.open = new_turn(s.ms(s.clock));
s.open->audio.insert(s.open->audio.end(), x.begin(), x.end());
s.clock += (int64_t)x.size();
bound_open();
return;
}
size_t i = 0;
while (i < x.size()) {
const size_t k = std::min(x.size() - i, (size_t)frame_n - s.frame.size());
s.frame.insert(s.frame.end(), x.begin() + (std::ptrdiff_t)i,
x.begin() + (std::ptrdiff_t)(i + k));
i += k;
if ((int64_t)s.frame.size() == frame_n) {
vad_frame(s.frame.data(), frame_n);
s.frame.clear();
}
}
};
auto append_pcm = [&](const uint8_t* p, size_t n, const ojson& eid) {
if (n % 2) {
error("invalid_request_error", "invalid_value",
"the audio is 16-bit PCM, two bytes a sample; this chunk has an odd length",
"audio", eid);
return;
}
std::vector<float> in(n / 2), out;
for (size_t i = 0; i < n / 2; ++i)
in[i] = (float)(int16_t)(uint16_t)(p[2 * i] | (p[2 * i + 1] << 8)) / 32768.0f;
s.rs->push(in.data(), in.size(), &out);
take(out);
};
/* The pause detector's half-heard frame, into the open turn when there is one. */
auto flush_frame = [&]() {
if (s.speaking && s.open) s.open->audio.insert(s.open->audio.end(), s.frame.begin(),
s.frame.end());
s.clock += (int64_t)s.frame.size();
s.frame.clear();
};
/* ---- session.update: checked whole, then applied whole */
auto update = [&](const ojson& j, bool beta) {
const ojson eid = j.contains("event_id") ? j["event_id"] : ojson(nullptr);
const char* ack = beta ? "transcription_session.updated" : "session.updated";
if (!j.contains("session") || !j["session"].is_object())
return error("invalid_request_error", "missing_required_parameter",
"the update carries no session object", "session", eid);
const ojson& se = j["session"];
int32_t rate = s.rate;
std::string code = s.language_code, name = s.language, prompt = s.prompt, delay = s.delay;
std::vector<std::string> keywords = s.keywords;
bool vad = s.vad;
double threshold = s.threshold;
int prefix = s.prefix_ms, silence = s.silence_ms;
std::string model = s.model;
auto bad = [&](const std::string& param, const std::string& why) {
error("invalid_request_error", "invalid_value", why, param, eid);
};
const ojson* tr = nullptr;
const ojson* td = nullptr;
bool has_td = false;
if (!beta) {
if (se.contains("type") && se["type"] != "transcription")
return bad("session.type", "this server's realtime sessions transcribe: "
"session.type is \"transcription\"");
if (se.contains("audio") && se["audio"].is_object() && se["audio"].contains("input") &&
se["audio"]["input"].is_object()) {
const ojson& in = se["audio"]["input"];
if (in.contains("format") && in["format"].is_object()) {
const ojson& fo = in["format"];
if (str_of(fo, "type", "audio/pcm") != "audio/pcm")
return bad("session.audio.input.format.type",
"the audio is \"audio/pcm\": 16-bit little-endian mono");
if (fo.contains("rate")) {
if (!fo["rate"].is_number_integer() ||
!mm::Resampler::takes(fo["rate"].get<int32_t>()))
return bad("session.audio.input.format.rate",
"the rate is one of " + mm::Resampler::rates() + " Hz");
rate = fo["rate"].get<int32_t>();
}
}
if (in.contains("transcription") && in["transcription"].is_object())
tr = &in["transcription"];
if (in.contains("turn_detection")) { td = &in["turn_detection"]; has_td = true; }
}
} else {
if (se.contains("input_audio_format") && se["input_audio_format"] != "pcm16")
return bad("session.input_audio_format",
"the audio is \"pcm16\": 16-bit little-endian mono at 24 kHz");
if (se.contains("input_audio_format")) rate = 24000;
if (se.contains("input_audio_transcription") &&
se["input_audio_transcription"].is_object())
tr = &se["input_audio_transcription"];
if (se.contains("turn_detection")) { td = &se["turn_detection"]; has_td = true; }
}
if (tr) {
const ojson& t = *tr;
model = str_of(t, "model", model);
std::string want = str_of(t, "language", "");
bool detect = t.contains("language") && t["language"].is_null();
/* The live models' `languages`: one is a forced language; several, detection. */
if (t.contains("languages") && t["languages"].is_array()) {
if (t["languages"].size() == 1 && t["languages"][0].is_string())
want = t["languages"][0].get<std::string>();
else
detect = true;
}
if (detect && want.empty()) {
code.clear();
name.clear();
}
if (!want.empty()) {
const std::string n = f.language_name(want);
if (n.empty()) {
std::string known;
for (const auto& l : f.languages)
known += (known.empty() ? "" : ", ") + l.first;
return bad("session.audio.input.transcription.language",
"this model names no language '" + want + "'; it knows " + known);
}
code = want;
name = n;
}
prompt = str_of(t, "prompt", prompt);
if (t.contains("keywords") && t["keywords"].is_array()) {
keywords.clear();
for (const auto& k : t["keywords"])
if (k.is_string()) keywords.push_back(k.get<std::string>());
}
if (t.contains("delay") && t["delay"].is_string()) {
delay = str_of(t, "delay", "");
if (delay != "minimal" && delay != "low" && delay != "medium" && delay != "high" &&
delay != "xhigh")
return bad("session.audio.input.transcription.delay",
"delay is minimal, low, medium, high or xhigh");
}
}
if (has_td) {
const ojson& t = *td;
if (t.is_null()) {
vad = false;
} else if (t.is_object()) {
const std::string type = str_of(t, "type", "server_vad");
if (type != "server_vad")
return bad("turn_detection.type",
"turn detection is server_vad, or null for turns the client "
"commits; not '" + type + "'");
vad = true;
if (t.contains("threshold") && t["threshold"].is_number()) {
threshold = t["threshold"].get<double>();
if (!(threshold >= 0.0 && threshold <= 1.0))
return bad("turn_detection.threshold", "threshold is between 0 and 1");
}
if (t.contains("prefix_padding_ms") && t["prefix_padding_ms"].is_number_integer())
prefix = std::clamp(t["prefix_padding_ms"].get<int>(), 0, 2000);
if (t.contains("silence_duration_ms") &&
t["silence_duration_ms"].is_number_integer())
silence = std::clamp(t["silence_duration_ms"].get<int>(), 100, 5000);
} else {
return bad("turn_detection", "turn detection is an object or null");
}
}
/* Applied. Audio already in at the old rate comes out before the new rate's. */
if (rate != s.rate) {
std::vector<float> tail;
s.rs->flush(&tail);
take(tail);
s.rate = rate;
s.rs.reset(new mm::Resampler(s.rate, s.model_rate));
}
if (vad != s.vad) {
if (s.vad) flush_frame(); /* off: the open turn waits for a commit */
s.speaking = vad && s.open && !s.open->audio.empty();
s.run = s.quiet = 0;
s.recent.clear();
s.vad = vad;
}
s.beta = beta;
s.model = model;
s.language_code = code;
s.language = name;
s.prompt = prompt;
s.keywords = keywords;
s.delay = delay;
s.unsettled = unsettled_for(delay);
s.threshold = threshold;
s.prefix_ms = prefix;
s.silence_ms = silence;
ojson o = event(ack);
o["session"] = session_json();
send(o);
};
auto handle = [&](const std::string& msg, bool binary) {
if (binary) return append_pcm((const uint8_t*)msg.data(), msg.size(), nullptr);
const ojson j = ojson::parse(msg, nullptr, /*allow_exceptions=*/false);
if (j.is_discarded() || !j.is_object() || !j.contains("type") || !j["type"].is_string())
return error("invalid_request_error", "invalid_json",
"a client event is a JSON object with a string `type`", "", nullptr);
const std::string type = j["type"].get<std::string>();
const ojson eid = j.contains("event_id") ? j["event_id"] : ojson(nullptr);
if (type == "input_audio_buffer.append") {
std::vector<uint8_t> pcm;
if (!j.contains("audio") || !j["audio"].is_string() ||
!base64_decode(j["audio"].get<std::string>(), &pcm))
return error("invalid_request_error", "invalid_value",
"`audio` is base64 of 16-bit little-endian PCM", "audio", eid);
return append_pcm(pcm.data(), pcm.size(), eid);
}
if (type == "input_audio_buffer.commit") {
/* The turn ends here: what the resampler still holds back belongs to it. */
std::vector<float> tail;
s.rs->flush(&tail);
take(tail);
if (s.vad) flush_frame();
if (!s.open || s.ms((int64_t)s.open->audio.size()) < kMinCommitMs)
return error("invalid_request_error", "input_audio_buffer_commit_empty",
fmt("the buffer holds less than %lld ms of audio",
(long long)kMinCommitMs), "", eid);
commit_open();
s.speaking = false;
s.run = s.quiet = 0;
return;
}
if (type == "input_audio_buffer.clear") {
if (s.open) s.open->dropped = true;
s.open.reset();
s.frame.clear();
s.recent.clear();
s.speaking = false;
s.run = s.quiet = 0;
send(event("input_audio_buffer.cleared"));
return;
}
if (type == "session.update") return update(j, false);
if (type == "transcription_session.update") return update(j, true);
error("invalid_request_error", "unknown_event",
"this session takes session.update, input_audio_buffer.append, "
"input_audio_buffer.commit and input_audio_buffer.clear; not '" + type + "'",
"type", eid);
};
/* ---- passes */
auto detok = [&](const std::vector<int32_t>& ids, bool flush) {
std::unique_ptr<IDetokenizer> d = deps_.tok->detokenizer({});
std::string t;
for (int32_t id : ids) t += d->push(id);
if (flush) t += d->flush();
return t;
};
auto usage = [](const RtTurn& t) {
ojson u;
u["type"] = "tokens";
u["input_tokens"] = t.n_prompt;
u["output_tokens"] = t.n_gen;
u["total_tokens"] = t.n_prompt + t.n_gen;
return u;
};
auto delta = [&](RtTurn& t, const std::string& d) {
if (d.empty()) return;
ojson o = event("conversation.item.input_audio_transcription.delta");
o["item_id"] = t.id;
o["content_index"] = 0;
o["delta"] = d;
send(o);
t.sent += d;
};
auto failed = [&](RtTurn& t, const std::string& why) {
ojson o = event("conversation.item.input_audio_transcription.failed");
o["item_id"] = t.id;
o["content_index"] = 0;
ojson e;
e["type"] = "server_error";
e["code"] = nullptr;
e["message"] = why;
e["param"] = nullptr;
o["error"] = std::move(e);
send(o);
RAD_WARN("realtime %s %s failed: %s", s.id.c_str(), t.id.c_str(), why.c_str());
};
auto drop_front = [&](const std::shared_ptr<RtTurn>& t) {
if (!s.turns.empty() && s.turns.front() == t) s.turns.pop_front();
};
/* What to hear next: the oldest committed turn whole, else the open turn once enough new
* audio has come in. */
auto next_work = [&](bool* final) -> std::shared_ptr<RtTurn> {
if (s.pass.running) return nullptr;
if (!s.turns.empty()) { *final = true; return s.turns.front(); }
if (!s.open) return nullptr;
const size_t n = s.open->audio.size();
if ((double)n < kFirstPassSeconds * s.model_rate ||
(double)n < (double)s.open->heard + kStepSeconds * s.model_rate)
return nullptr;
*final = false;
return s.open;
};
auto start_pass = [&](const std::shared_ptr<RtTurn>& t, bool final) {
const size_t n = t->audio.size();
std::shared_ptr<mm::Item> item;
std::string why;
PromptInput p;
const int st = deps_.mm->prepare_audio(t->audio, &item, &why);
if (st < 0 || !item ||
speech_prompt(f, *deps_.tok, s.context(),
s.language.empty() ? std::string() : speech_language_text(f, s.language),
item, &p) < 0) {
t->heard = n;
if (final) {
failed(*t, st < 0 ? "the audio could not be used: " + why
: "the model's transcription template has no {audio} slot");
drop_front(t);
}
return;
}
p.tokens.insert(p.tokens.end(), t->settled.begin(), t->settled.end());
OaiRequest& r = s.pass.r;
r = OaiRequest{};
r.endpoint = Endpoint::Completion;
r.shape = ApiShape::OpenAI;
r.model = opt_.model_id;
r.id = random_id("rt-");
r.created = (int64_t)std::time(nullptr);
r.peer = s.peer;
r.n = 1;
r.sp = SamplingParams{};
r.sp.temp = 0.0f;
r.sp.top_k = 1;
r.return_tokens = true;
r.max_tokens = kMaxTokensPerPass;
if (lim_.max_ctx > 0) {
if ((int64_t)p.tokens.size() >= lim_.max_ctx) {
t->heard = n;
if (final) {
failed(*t, "the turn's prompt is longer than the context");
drop_front(t);
}
return;
}
r.max_tokens = (int32_t)std::min<int64_t>(r.max_tokens,
lim_.max_ctx - (int64_t)p.tokens.size());
}
r.prompts.assign(1, std::move(p));
s.pass.gens.clear();
ApiError err;
if (submit_all(r, &s.pass.gens, &err) < 0) {
retire(s.pass.gens);
t->heard = n;
if (final) {
failed(*t, err.message);
drop_front(t);
}
return;
}
s.pass.turn = t;
s.pass.final = final;
s.pass.heard = n;
s.pass.running = true;
t->heard = n;
++t->passes;
};
auto finish_pass = [&]() {
Generation& g = s.pass.gens[0];
std::shared_ptr<RtTurn> t = s.pass.turn;
const Finish fin = g.finish;
const std::string why = fin == Finish::Error ? engine_failure(*g.sink) : std::string();
t->n_prompt += (int64_t)s.pass.r.prompts[0].tokens.size();
t->n_gen += g.sink->n_produced();
std::vector<int32_t> ids = t->settled;
ids.insert(ids.end(), g.tokens.begin(), g.tokens.end());
/* The end of the turn, which the decoder renders as nothing, is no part of the reply. */
while (!ids.empty() && deps_.tok->reply_bytes(ids.back()).empty()) ids.pop_back();
record(s.pass.r, s.pass.gens, fin, /*quiet=*/true);
retire(s.pass.gens);
s.pass.running = false;
s.pass.turn.reset();
if (t->dropped) return;
const bool forced = !s.language.empty();
if (fin == Finish::Error) {
if (s.pass.final) {
failed(*t, why);
drop_front(t);
}
return;
}
if (s.pass.final) {
const std::string text = detok(ids, /*flush=*/true);
const size_t at = speech_transcript_start(f, text, forced, /*closed=*/true);
const std::string transcript = rtrim(text.substr(std::min(at, text.size())));
if (starts_with(transcript, t->sent)) delta(*t, transcript.substr(t->sent.size()));
ojson o = event("conversation.item.input_audio_transcription.completed");
o["item_id"] = t->id;
o["content_index"] = 0;
o["transcript"] = transcript;
o["usage"] = usage(*t);
send(o);
RAD_INFO("realtime %s %s: %.1fs of audio, %d passes, prompt=%lld gen=%lld, final "
"%.2fs after the commit", s.id.c_str(), t->id.c_str(),
(double)t->audio.size() / s.model_rate, t->passes, (long long)t->n_prompt,
(long long)t->n_gen,
std::chrono::duration<double>(Clock::now() - t->committed_at).count());
drop_front(t);
return;
}
/* An interim pass: settle all but the last few tokens -- none in the turn's first second,
* none once the turn is where it may be cut (cut_zone), and none of a reply that ran to its
* bound, which is a model looping. */
if ((double)s.pass.heard >= kSettleAfterSeconds * s.model_rate && fin != Finish::Length &&
(max_clip <= 0 || (int64_t)s.pass.heard <= max_clip - cut_zone) &&
ids.size() > (size_t)s.unsettled)
t->settled.assign(ids.begin(),
ids.begin() + (std::ptrdiff_t)std::max(t->settled.size(),
ids.size() - s.unsettled));
const std::string settled_text = detok(t->settled, /*flush=*/false);
const size_t a = speech_transcript_start(f, settled_text, forced, /*closed=*/false);
const std::string settled = a == std::string::npos ? std::string()
: rtrim(settled_text.substr(a));
if (settled.size() > t->sent.size() && starts_with(settled, t->sent))
delta(*t, settled.substr(t->sent.size()));
const std::string all_text = detok(ids, /*flush=*/false);
const size_t b = speech_transcript_start(f, all_text, forced, /*closed=*/false);
const std::string all = b == std::string::npos ? std::string()
: rtrim(all_text.substr(b));
const std::string tentative = starts_with(all, t->sent) ? all.substr(t->sent.size())
: std::string();
if (tentative != t->tentative) {
ojson o = event("radiance.input_audio_transcription.tentative");
o["item_id"] = t->id;
o["content_index"] = 0;
o["text"] = tentative;
send(o);
t->tentative = tentative;
}
};
/* ---- the loop */
RAD_INFO("realtime %s open from %s", s.id.c_str(), s.peer.c_str());
{
ojson o = event("session.created");
o["session"] = session_json();
send(o);
}
for (;;) {
std::deque<std::pair<std::string, bool>> got;
bool gone = false, overflow = false;
{
std::unique_lock<std::mutex> lk(s.m);
bool final = false;
if (s.inbox.empty() && !s.peer_gone && !s.overflow && !s.pass.running &&
!next_work(&final))
s.cv.wait_for(lk, std::chrono::milliseconds(100));
got.swap(s.inbox);
s.inbox_bytes = 0;
gone = s.peer_gone;
overflow = s.overflow;
}
if (overflow) {
/* The reader stopped at the message that overflowed; what it queued before is
* dropped with the session. */
error("invalid_request_error", "buffer_overflow",
fmt("the session fell more than %zu MiB of messages behind",
kMaxQueuedBytes >> 20), "", nullptr);
ws.close(1008, "buffer overflow");
return true;
}
for (const auto& m : got) handle(m.first, m.second);
if (gone) return false;
{
double behind = 0.0;
for (const auto& t : s.turns) behind += (double)t->audio.size() / s.model_rate;
if (s.turns.size() > kMaxBehindTurns || behind > kMaxBehindSeconds) {
error("invalid_request_error", "buffer_overflow",
fmt("the session is %zu committed turns (%.0f s of audio) behind its "
"transcription; the most is %zu turns or %.0f s",
s.turns.size(), behind, kMaxBehindTurns, kMaxBehindSeconds),
"", nullptr);
ws.close(1008, "buffer overflow");
return true;
}
}
if (stopping_.load()) {
error("server_error", "shutting_down", "the server is shutting down", "", nullptr);
ws.close(1001, "closing");
return true;
}
if (s.pass.running) {
pump(s.pass.gens, s.pass.r);
if (all_done(s.pass.gens)) {
finish_pass();
continue;
}
bool idle;
{
std::lock_guard<std::mutex> lk(s.m);
idle = s.inbox.empty() && !s.peer_gone;
}
if (idle) s.pass.gens[0].sink->wait(10);
continue;
}
sweep_abandoned();
bool final = false;
if (std::shared_ptr<RtTurn> t = next_work(&final)) start_pass(t, final);
}
}
} /* namespace server */
} /* namespace rad */
+318 -487
View File
File diff suppressed because it is too large. Load diff
+119 -110
View File
@@ -1,19 +1,16 @@
/* core/server/server.h -- the OpenAI-compatible server (spec §14).
*
* Threading, in the spec's terms (§1): HTTP threads feed a request queue, one scheduler thread
* produces one step. This object owns the HTTP thread pool and the admission queue; it does not
* own the step loop and never calls into it. Output comes back per request through a Sink the
* scheduler pushes into (sink.h), which `Request::sink` points at.
* Threading (spec §1): HTTP threads feed a request queue and one scheduler thread runs the steps.
* This object owns the HTTP thread pool and the admission queue, never the step loop. Output
* returns per request through a Sink (sink.h) that `Request::sink` points at.
*
* Backpressure is admission control, not buffering. A full queue is a 429 with Retry-After. The
* alternative -- accepting everything and letting the waiting list grow -- turns a load spike
* into an out-of-memory kill twenty minutes later, at which point every in-flight request dies
* rather than the marginal ones being refused up front.
* Backpressure is admission control, not buffering: a full queue answers 429 with Retry-After.
* Accepting everything would turn a load spike into a later out-of-memory kill of every in-flight
* request instead of refusing the marginal ones.
*
* Cancellation is not an edge case. An agent client that abandons a long generation is the normal
* case, so a dropped connection is detected on the streaming path (a failed write, or a closed
* socket seen while waiting) and turned into IScheduler::cancel, which frees the request's KV
* blocks immediately rather than at completion.
* Cancellation is the normal case for agent clients. A dropped connection, seen on the streaming
* path as a failed write or a closed socket, becomes IScheduler::cancel, which frees the request's
* KV blocks immediately.
*/
#pragma once
#include <functional>
@@ -27,6 +24,7 @@
#include <atomic>
#include <memory>
#include <mutex>
#include <optional>
#include <string>
#include <vector>
@@ -41,41 +39,36 @@ struct Deps {
IEmbedder* embed = nullptr; /* absent -> /v1/embeddings is 501 */
IMultimodal* mm = nullptr; /* absent -> image and audio parts are 501 */
IImageGen* images = nullptr; /* absent -> the images endpoints are 501 */
const SpeechFormat* speech = nullptr; /* absent -> /v1/audio/transcriptions is 501 */
/* WHAT ONLY THE ENGINE CAN SEE: per-card VRAM, the expert plane. The server holds interfaces
* and no device handle, so this dependency is a function rather than an object -- there is
* nothing to name it after. Absent, the dashboard shows the scheduler's half and omits the
* cards rather than drawing zeroes.
*
* The SAME function the live view is built with (liveview.h), so the terminal view and the
* web page cannot drift into disagreeing about what the engine is doing. */
/* Engine-side state the server cannot see (per-card VRAM, the expert plane), as a snapshot
* function since the server holds no device handle. The same function feeds the live view
* (liveview.h), so the terminal and the web page agree. Absent, the dashboard shows only the
* scheduler's metrics and omits the cards. */
LiveView::Source live;
};
struct ServerOptions {
std::string model_id = "radiance";
/* AN EMBEDDING MODEL (rad_declare_pooled) GENERATES NOTHING: /v1/chat/completions and
* /v1/completions answer 501 naming /v1/embeddings, rather than queueing a request the engine
* would finish after one step with no text. */
/* An embedding model (rad_declare_pooled) generates nothing: /v1/chat/completions and
* /v1/completions answer 501 naming /v1/embeddings. */
bool embedding_model = false;
/* AN IMAGE GENERATOR (rad_declare_generator) GENERATES NO TEXT either: the text endpoints
* answer 501 naming /v1/images/generations and /v1/images/edits. */
/* An image generator (rad_declare_generator) generates no text: the text endpoints answer
* 501 naming /v1/images/generations and /v1/images/edits. */
bool image_model = false;
/* WHICH DECISION PROTOCOL THE MODEL WAS TRAINED ON, from the container's `decision.type`:
* "d1" serves /v1/systemone (systemone.h); empty answers it 501. Never inferred from a name. */
/* The decision protocol from the container's `decision.type`: "d1" serves /v1/systemone
* (systemone.h); empty answers it 501. Never inferred from a name. */
std::string decision_type;
/* What --model named, reported as the model entry's `root` the way vLLM reports the path it
* loaded: a served name chosen for clients says nothing about which file is behind it. Empty
* leaves the field out. */
/* What --model named, reported as the model entry's `root` as vLLM reports its loaded path
* (the served name says nothing about the file behind it). Empty omits the field. */
std::string model_path;
std::string host = "0.0.0.0";
int port = 8000;
int n_threads = 0;
/* How many requests may be admitted and unfinished at once. Beyond this the answer is 429.
* Defaults to 8x max_seqs: enough that the scheduler always has a full batch to choose from
* and a queue to prefill out of, and small enough that the memory held by waiting requests is
* bounded by a number the operator picked. */
/* Requests that may be admitted and unfinished at once; beyond it, 429. Defaults to 8 x
* max_seqs: enough for a full batch plus a prefill queue, while bounding the memory waiting
* requests hold. */
int64_t queue_depth = 0;
int64_t max_seqs = 256;
int retry_after_s = 1;
@@ -88,14 +81,14 @@ struct ServerOptions {
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. */
/* Deployment default for `reasoning_effort`; empty for the template's own. See
* OaiLimits::default_reasoning_effort. */
std::string default_reasoning_effort;
/* The deployment default for `thinking_token_budget`, -1 for none. See
/* 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. */
/* Sampling for a request that sends no sampler fields; only the sampler knobs are read. See
* OaiLimits::default_sampling. */
SamplingParams default_sampling;
bool default_dry_breakers_set = false;
/* The deployment's chat template variables and reply format. See OaiLimits. */
@@ -107,33 +100,24 @@ struct ServerOptions {
bool allow_video = false;
bool allow_audio = false;
/* WHAT /server_info AND /version REPORT ABOUT THE ENGINE BEHIND THIS SERVER.
*
* `engine_info` is a JSON OBJECT as text, spliced in verbatim under "engine". The server
* cannot derive any of it -- it deliberately knows nothing about the device layer, the
* container or the placement plan -- and a struct with a field per fact would be a struct
* this component has to grow every time the engine learns something new about itself. */
/* What /server_info and /version report about the engine. `engine_info` is a JSON object as
* text, spliced in verbatim under "engine": the server knows nothing of the device layer,
* container or placement plan, and an opaque blob need not grow with every new engine fact. */
std::string version = RAD_VERSION;
std::string engine_info;
/* The declared compute graph, as JSON, for the Model view. A PROVIDER, called per request,
* rather than a string rendered once after declare.
/* The declared compute graph as JSON, for the Model view. A provider called per request, not
* a string rendered once: the dump includes `OpInfo::issued`, which a pre-first-step snapshot
* would report as false for every op, hiding dead declarations.
*
* The declaration itself does not change while the server runs, but the dump also carries what
* the run phase has DONE with it -- `OpInfo::issued` -- and a snapshot taken before the first
* step reports every op in the model as never issued, permanently, which makes /graph useless
* for finding a dead declaration.
*
* Regenerating reads the Program from the HTTP thread while the step path writes that one
* field. It is a monotonic false -> true bool, so the worst case is a graph fetched mid-step
* showing an op as unissued one step before it flips. Registry::select is asked with
* record = false and mutates nothing else. */
* Regenerating reads the Program on the HTTP thread while the step path writes that field. It
* is a monotonic false -> true bool, so at worst a mid-step fetch shows an op unissued one step
* early. Registry::select is called with record = false and mutates nothing else. */
std::function<std::string()> graph_json;
/* THE STARTUP REPORT READ AGAIN, as JSON (core/diag/diag.h): the options in force, the machine
* as it is now (the provider may reuse a reading for a second), and what on it costs speed.
* Without a key it is answered to loopback clients only (Server::handle_diagnostics). A
* provider like the graph's, because a card's link speed and clock only say anything under
* load -- a request made during a long prefill is how a link parked below its maximum is told
* from one at rest. */
/* The startup report as JSON (core/diag/diag.h): options in force, the machine as it is now
* (the provider may reuse a reading for a second), and what on it costs speed. Without an API
* key, loopback clients only (Server::handle_diagnostics). A provider because link speed and
* clock only mean something under load: queried during a long prefill, it tells a link parked
* below its maximum from one at rest. */
std::function<std::string()> diagnostics_json;
std::string api_key;
@@ -149,37 +133,34 @@ struct ServerOptions {
class Server {
public:
Server(const Deps& d, const ServerOptions& o);
/* Lifetime rule, and it is load-bearing: stop the scheduler before destroying the Server.
* `Request::sink` is a raw pointer into storage this object owns, and a request the scheduler
* has not finished is a request still writing into it. The destructor waits a bounded time
* for anything it cancelled and then deliberately leaks the rest rather than free memory a
/* Stop the scheduler before destroying the Server: `Request::sink` is a raw pointer into
* storage this object owns, and an unfinished request still writes into it. The destructor
* waits a bounded time for cancelled requests, then leaks the rest rather than free memory a
* running step may touch. */
~Server();
/* Every endpoint, registered. Tests drive this directly -- same handlers, no socket. */
/* Every endpoint. Tests drive this directly: same handlers, no socket. */
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. */
/* Renders the deployment's template defaults once at startup, since a default the template
* refuses would 400 every request relying on it. A one-message chat is parsed as a request
* would be: with no defaults, then with --chat-template-kwargs, then also --reasoning-effort.
* A failure at the first stage is not about the defaults and is not reported. `kwargs_why` /
* `effort_why` stay empty or hold the template's refusal at that stage. */
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. */
/* Checks the deployment's thinking_token_budget with a one-message chat, as a request would
* send it. Empty when the model's reasoning block can take one; otherwise the 400 message a
* request naming the budget would get. */
std::string check_thinking_budget() const;
/* THE EFFORTS THE CHAT TEMPLATE TAKES, found by parsing a one-message chat with each word this
* server knows of (low, medium, high, xhigh, max) the way a request would send it, with no
* deployment defaults. A template that takes a word nobody uses takes any word, and the answer
* is empty. Kept for the refusal of a word outside the set and for /server_info; called once,
* before run(). */
/* The reasoning efforts the chat template takes, found by parsing a one-message chat with each
* known word (low, medium, high, xhigh, max), with no deployment defaults. If the template
* also takes a nonsense word it takes any word, and the result is empty. Used to refuse words
* outside the set and for /server_info; called once, before run(). */
std::vector<std::string> probe_reasoning_efforts();
/* --reasoning-effort-map's targets, each rendered as a request's effort would be. Empty when
* the template takes every one; otherwise the first refusal, naming the target. */
/* Renders each --reasoning-effort-map target as a request's effort. Empty when the template
* takes all of them; otherwise the first refusal, naming the target. */
std::string check_reasoning_effort_map() const;
void stop();
int port() const { return transport_.port(); } /* 0 until run() is accepting */
@@ -190,6 +171,8 @@ public:
private:
struct Generation;
struct TranscriptionJob; /* speech.cpp */
struct RealtimeSession; /* realtime.cpp */
struct StreamState;
static UsageOut usage_of(const OaiRequest& r, const std::vector<Generation>& gens);
@@ -198,62 +181,77 @@ private:
void register_routes();
/* ------------------------------------------------------------------ server.cpp */
HttpResponse handle_chat(const HttpRequest& req);
HttpResponse handle_completion(const HttpRequest& req);
HttpResponse handle_messages(const HttpRequest& req);
HttpResponse handle_responses(const HttpRequest& req);
HttpResponse handle_native_completion(const HttpRequest& req);
HttpResponse handle_infill(const HttpRequest& req);
HttpResponse handle_embeddings(const HttpRequest& req);
/* ------------------------------------------------------------------ images.cpp */
HttpResponse handle_images(const HttpRequest& req, bool edit);
HttpResponse handle_systemone(const HttpRequest& req);
HttpResponse handle_apply_template(const HttpRequest& req);
using ToChat = int (*)(const std::string& body, const OaiLimits& lim, std::string* chat,
std::string* extra, ApiError* err);
HttpResponse count_tokens(const HttpRequest& req, ToChat to_chat, ApiShape shape,
const char* object);
/* OpenAI's /v1/audio/transcriptions, from the model's own RadAudioFormat (speech.cpp). */
HttpResponse handle_transcription(const HttpRequest& req);
/* OpenAI's realtime transcription session over a WebSocket at /v1/realtime: audio streamed
* in, the transcript streamed out while it is spoken (realtime.cpp). */
void handle_realtime(const HttpRequest& req, WsConn& ws);
/* The session's thread: realtime_loop, an exception turned into an error event and a close,
* and the pass in flight cancelled however the loop ends. The loop returns true when the
* server ended the session, false when the peer left. */
void realtime_run(RealtimeSession& s, WsConn& ws);
bool realtime_loop(RealtimeSession& s, WsConn& ws);
HttpResponse handle_models(const HttpRequest& req);
HttpResponse handle_metrics(const HttpRequest& req);
std::optional<HttpResponse> refuse_text(const std::string& peer,
ApiShape shape = ApiShape::OpenAI);
/* A parsed generation request, in any API's shape: admitted, run, answered in `r.shape`. */
HttpResponse serve(const HttpRequest& req, OaiRequest& r);
json native_result(const OaiRequest& r, const Generation& g, const std::string& content);
/* ------------------------------------------------------------------ images.cpp */
HttpResponse handle_images(const HttpRequest& req, bool edit);
/* ------------------------------------------------------------------ admin.cpp
* vLLM's non-generation surface. Separate because none of it touches the scheduler's step
* path, the admission queue or a Sink: these are questions about the server, answered on the
* HTTP thread and finished before they return. */
* vLLM's non-generation surface, answered on the HTTP thread without the step path, the
* admission queue or a Sink. */
HttpResponse handle_health(const HttpRequest& req);
HttpResponse handle_ping(const HttpRequest& req);
HttpResponse handle_version(const HttpRequest& req);
HttpResponse handle_props(const HttpRequest& req);
HttpResponse handle_apply_template(const HttpRequest& req);
HttpResponse handle_input_tokens(const HttpRequest& req);
HttpResponse handle_messages(const HttpRequest& req);
HttpResponse handle_count_tokens(const HttpRequest& req);
HttpResponse handle_responses(const HttpRequest& req);
HttpResponse handle_responses_tokens(const HttpRequest& req);
/* A request another API's shape was translated into: admitted and served like a chat one,
* answered in `r.shape`. */
HttpResponse serve_translated(const HttpRequest& req, OaiRequest& r);
HttpResponse handle_native_completion(const HttpRequest& req);
HttpResponse handle_infill(const HttpRequest& req);
json native_result(const OaiRequest& r, const Generation& g, const std::string& content);
HttpResponse handle_load(const HttpRequest& req);
HttpResponse handle_tokenize(const HttpRequest& req);
HttpResponse handle_detokenize(const HttpRequest& req);
HttpResponse handle_tokenizer_info(const HttpRequest& req);
HttpResponse handle_server_info(const HttpRequest& req);
HttpResponse handle_diagnostics(const HttpRequest& req);
/* What this deployment can do -- chat, tools, reasoning, grammar, media, logprobs, the
* reasoning efforts it takes -- as /server_info's `capabilities` and the model entry both
* report it, built in one place so the two cannot disagree. */
/* What this deployment can do (chat, tools, reasoning, grammar, media, logprobs, reasoning
* efforts), shared by /server_info's `capabilities` and the model entry so they agree. */
json capabilities() const;
HttpResponse handle_sessions(const HttpRequest& req);
HttpResponse handle_reset_prefix_cache(const HttpRequest& req);
/* ------------------------------------------------------------------ dashboard.cpp */
HttpResponse handle_dashboard(const HttpRequest& req);
HttpResponse handle_stats(const HttpRequest& req);
HttpResponse handle_graph(const HttpRequest& req);
HttpResponse handle_sessions(const HttpRequest& req);
HttpResponse error_response(const ApiError& e, const std::string& peer,
ApiShape shape = ApiShape::OpenAI);
/* THE REQUEST LOG. One line when a request is admitted and one from record() when it ends,
* at the info level, so `docker logs` answers "who asked what, how long, how did it end"
* without the engine's own levels. The debug level adds the last user message's opening. */
/* Request log: one info line at admission and one from record() at the end (who asked what,
* how long, how it ended). The debug level adds the opening of the last user message. */
void log_admitted(const OaiRequest& r) const;
/* Admission. Returns false when the queue is full; the caller answers 429. */
bool admit(int64_t n);
/* Admission: reserves `n` places in the queue, or returns the 429 to answer when it is full.
* More places than the queue has can never be admitted, so that is a 400 under `field` (the
* request field that multiplied them) naming the bound, not a 429 retried forever. Sweeps the
* graveyard first. */
std::optional<HttpResponse> admit(int64_t n, const std::string& peer,
ApiShape shape = ApiShape::OpenAI, const char* field = "n");
void release(int64_t n);
void sweep_abandoned();
/* Wait, bounded, for the scheduler to finish everything it was told to cancel. */
@@ -262,6 +260,13 @@ private:
/* Turn a parsed request into `n_choices` submitted engine requests. */
int submit_all(const OaiRequest& r, std::vector<Generation>* gens, ApiError* err);
void cancel_all(std::vector<Generation>& gens, bool count_disconnect);
/* While `gens` run: once the client has left (499) or the server is stopping, every
* generation is cancelled and retired, `n` queue places are released, and the answer is
* returned. Nothing otherwise. A generation request (`r`) is recorded as an abort, as a
* dropped stream is. */
std::optional<HttpResponse> abandoned(const HttpRequest& req, std::vector<Generation>& gens,
int64_t n, ApiShape shape = ApiShape::OpenAI,
const OaiRequest* r = nullptr);
void retire(std::vector<Generation>& gens);
/* Drain sinks into decoded text. Returns true if anything new arrived. */
@@ -271,7 +276,10 @@ private:
HttpResponse blocking_completion(const HttpRequest& req, OaiRequest& r);
HttpResponse streaming_completion(const HttpRequest& req, OaiRequest& r);
void record(const OaiRequest& r, const std::vector<Generation>& gens, Finish overall);
/* `quiet` says the request's line at the debug level: one of the many small passes a
* realtime session makes, which its own lines account for. */
void record(const OaiRequest& r, const std::vector<Generation>& gens, Finish overall,
bool quiet = false);
Deps deps_;
ServerOptions opt_;
@@ -283,12 +291,13 @@ private:
std::atomic<int64_t> in_flight_{0};
int64_t queue_depth_ = 0;
std::atomic<int64_t> realtime_sessions_{0};
std::atomic<bool> stopping_{false};
int64_t started_at_ = 0;
/* Sinks whose HTTP side is gone but whose engine side may still be mid-step. Held until the
* scheduler reports the request terminal, because Request::sink is a raw pointer and freeing
* it under a running step is a use-after-free in the one place it is unbisectable. */
* it under a running step is a use-after-free. */
std::mutex grave_m_;
std::vector<std::shared_ptr<Sink>> grave_;
};
+88
View File
@@ -0,0 +1,88 @@
/* server_priv.h -- the Server's per-request state, shared by the units that serve requests
* (server.cpp, speech.cpp, realtime.cpp). Not part of the server's interface: nothing outside
* core/server includes it. */
#pragma once
#include "server.h"
#include "rad_internal.h"
#include <functional>
#include <memory>
#include <string>
#include <vector>
namespace rad {
namespace mm { struct Item; }
namespace server {
/* ------------------------------------------------------------------ per-choice state */
struct Server::Generation {
std::shared_ptr<Sink> sink;
std::unique_ptr<IDetokenizer> detok;
std::unique_ptr<ReplyStream> delta; /* chat streaming only, in the request's API shape */
uint64_t id = 0;
int index = 0;
int prompt_index = 0;
std::string text;
std::vector<LogprobEntry> logprobs;
size_t lp_sent = 0; /* streaming: how many of `logprobs` a chunk already carried */
/* Tracks every delivered token against the reasoning block, for
* completion_tokens_details.reasoning_tokens. */
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 */
/* OaiRequest::stops_after: where in `text` the reasoning block's closer ends (npos until it
* has been generated) and how far the search for it has reached. */
size_t stops_floor = std::string::npos;
size_t closer_scanned = 0;
size_t stop_cut = std::string::npos;
std::string stop_word; /* the stop string at stop_cut, "" when the decoder cut it */
size_t emitted = 0; /* streaming: text already handed to the delta stream */
std::vector<int32_t> tokens; /* llama-server's native shape: the ids generated */
size_t tokens_sent = 0; /* ...and how many of them a stream chunk carried */
int32_t progress_sent = -1; /* streaming: the prompt_progress last sent, -1 for none */
bool retired = false; /* reap() has been said for this id, at most once */
};
struct Server::StreamState {
OaiRequest r;
std::vector<Generation> gens;
std::function<bool()> peer_closed;
bool opened = false;
bool done_sent = false;
bool released = false;
};
/* The failure message for the client: the failing component's sentence and the status. A failed
* request always carries a negative status (RAD_E_STATE if none was set), so this never reads
* "ok". */
inline 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));
}
/* ------------------------------------------------------------------ speech (speech.cpp)
* The model's transcription format, used by the upload route and the realtime one alike. */
/* The plugin's template with its three slots filled (`context` as plain text, the clip's
* placeholder run, and `language_text`, from speech_language_text or ""), as tokens with the clip
* placed. RAD_E_INVAL when the template has no {audio} slot. */
int speech_prompt(const SpeechFormat& f, ITokenizer& tok, const std::string& context,
const std::string& language_text, const std::shared_ptr<mm::Item>& item,
PromptInput* out);
/* What a forced language puts in the {language} slot: the plugin's language_prompt naming it. */
std::string speech_language_text(const SpeechFormat& f, const std::string& name);
/* Where the transcript starts in a reply so far: past the transcript's opener, once it has been
* generated, and past the whitespace after it. npos while a reply that is not `closed` has not
* named it yet; a closed reply that never named it is all transcript. */
size_t speech_transcript_start(const SpeechFormat& f, const std::string& text, bool forced,
bool closed);
/* The centre of the quietest 100 ms of x[lo, hi): where a recording too long for one pass is cut,
* between words when there is a pause to cut in. */
int64_t speech_quiet_point(const std::vector<float>& x, int64_t lo, int64_t hi, int32_t rate);
} /* namespace server */
} /* namespace rad */
+9 -12
View File
@@ -39,12 +39,11 @@ Sink::Sink(size_t capacity) {
}
Sink::~Sink() {
/* Only a sink the producer actually terminated can have a notify in flight; one that was
* never handed to the scheduler quiesces trivially. */
/* Only a sink the producer terminated can have a notify in flight. */
if (finish_.load(std::memory_order_acquire) == (int)Finish::None) return;
for (int spins = 0; !quiesced_.load(std::memory_order_acquire); ++spins) {
/* The window is a handful of instructions wide, so a short spin covers it; the sleep is
* there so a descheduled producer cannot burn a core. */
/* The window is a few instructions wide, so a short spin covers it; the sleep keeps a
* descheduled producer from burning a core. */
if (spins > 256) std::this_thread::sleep_for(std::chrono::microseconds(20));
}
}
@@ -52,9 +51,8 @@ Sink::~Sink() {
int64_t Sink::age_ns() const { return now_ns() - t_start_ns_; }
void Sink::notify() {
/* Deliberately not holding m_. See the header: this can lose a wake-up, and the consumer's
* bounded wait is what pays for that. Taking the lock here would put the scheduler thread
* behind whatever an HTTP thread happens to be doing. */
/* Deliberately without m_ (see sink.h): a lost wake-up is covered by the consumer's bounded
* wait, and the scheduler thread never waits on an HTTP thread. */
cv_.notify_one();
}
@@ -68,7 +66,7 @@ bool Sink::push(int32_t token, const TokenLogprobs* lp) {
const uint64_t h = head_.load(std::memory_order_relaxed);
const uint64_t t = tail_.load(std::memory_order_acquire);
if (h - t > mask_) {
/* The consumer is not draining. Failing loudly beats a stream with a hole in it. */
/* The consumer is not draining; fail rather than leave a hole in the stream. */
overflow_.store(true, std::memory_order_release);
fail(RAD_E_FULL);
return false;
@@ -96,9 +94,8 @@ void Sink::finish(Finish f) {
/* First terminal state wins: a cancel racing an EOS must not be reported twice. */
if (finish_.compare_exchange_strong(expected, (int)f, std::memory_order_acq_rel)) {
notify();
/* The last write the producer ever makes to this object, and the one the destructor
* waits on. It has to come after the notify, not before it: the point is to publish that
* the condition variable is no longer being touched. */
/* The producer's last write to this object, which the destructor waits on. It must
* follow the notify: it publishes that the condition variable is no longer in use. */
quiesced_.store(true, std::memory_order_release);
}
}
@@ -126,7 +123,7 @@ void Sink::mark_admitted() {
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. */
/* One producer, so a load and a store suffice. */
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,
+44 -56
View File
@@ -1,22 +1,18 @@
/* core/server/sink.h -- the per-request channel from the scheduler thread to the HTTP thread.
*
* `Request::sink` is the void* hook for this (rad_core.h). Exactly one scheduler thread writes it
* and exactly one HTTP thread reads it, so it is a single-producer single-consumer ring and needs
* no lock on the data path: a relaxed load of the head, a store into a slot, a release store of
* the head. The producer never allocates and never blocks, which is the requirement -- a step
* that can be delayed by a slow HTTP client is a step that has coupled every request in the batch
* to the worst one.
* `Request::sink` is the void* hook for this (rad_core.h). One scheduler thread writes and one
* HTTP thread reads, so it is a lock-free single-producer single-consumer ring: relaxed load of
* the head, store into a slot, release store of the head. The producer never allocates or
* blocks, so a slow HTTP client cannot delay a step for the whole batch.
*
* The wake-up is the one place a mutex appears, and only on the consumer's side of it. The
* producer calls notify_one() without holding the lock, which can lose a wake-up in the window
* between the consumer testing the predicate and sleeping; the consumer therefore waits with a
* bounded timeout (RAD_SINK_POLL_MS) rather than indefinitely. The cost is named: a lost wake-up
* adds at most that many milliseconds to one token's latency. The benefit is that the scheduler
* thread never takes a lock an HTTP thread might be holding, and the same timeout doubles as the
* interval at which the streaming path polls whether the client is still there.
* Only the consumer takes the mutex. The producer calls notify_one() without it, which can lose
* a wake-up between the consumer's predicate test and its sleep, so the consumer waits at most
* RAD_SINK_POLL_MS. A lost wake-up costs at most that much latency on one token; in exchange the
* scheduler never waits on a lock an HTTP thread holds. The same timeout is the streaming path's
* client-liveness poll interval.
*
* Tokens, not text: detokenisation is stateful and per-request (spec §12) and belongs on the HTTP
* thread. Pushing an int32 keeps the producer's write to eight bytes and no allocation.
* thread, and the producer's write stays a fixed-size SinkToken.
*/
#pragma once
#include "rad_core.h"
@@ -43,8 +39,8 @@ enum class Finish : int {
Error, /* the engine failed the request; `status` says why */
};
/* The OpenAI `finish_reason` string. Cancelled has no OpenAI spelling; vLLM reports "abort" and
* dashboards key off that, so we match vLLM rather than inventing one. */
/* The OpenAI `finish_reason` string. Cancelled has no OpenAI spelling; it is "abort" as in vLLM,
* which dashboards key off. */
const char* finish_reason_oai(Finish f);
struct SinkToken {
@@ -61,21 +57,17 @@ struct SinkAlt {
class Sink {
public:
/* `capacity` is rounded up to a power of two. 8192 tokens is ~64 KiB and is far more than any
* HTTP consumer can fall behind by without being dead: at 100 tok/s that is 80 seconds of
* slack. Overflow is not silently dropped -- it fails the request, because a stream missing
* tokens in the middle is worse than a stream that stops and says so. */
/* `capacity` is rounded up to a power of two. 8192 tokens is 80 s of slack at 100 tok/s, far
* more than a live consumer falls behind. Overflow fails the request rather than dropping
* tokens from the middle of the stream. */
explicit Sink(size_t capacity = 8192);
/* Waits for the producer to be finished touching this object before letting it go.
/* Waits until the producer has stopped touching this object.
*
* Observing `done()` is not enough. The producer publishes the terminal state and only then
* wakes the consumer, so between those two instructions the consumer can already be inside
* this destructor -- and destroying a condition_variable while another thread is inside
* notify_one() on it is a use-after-free in pthread_cond_signal. The producer therefore sets
* a quiesced flag as its genuinely last act, and this waits for that flag rather than for the
* state. The window is a handful of instructions wide, so only a data-race detector reports
* it. */
* Observing `done()` is not enough: the producer publishes the terminal state and only then
* calls notify_one(), and destroying the condition_variable in between is a use-after-free in
* pthread_cond_signal. The producer's last act is to set a quiesced flag, which this waits
* for. The window is a few instructions wide. */
~Sink();
/* ------------------------------------------------------------------ producer: scheduler */
@@ -84,30 +76,28 @@ public:
* logprobs when the request asked for them (enable_logprobs), and null otherwise. */
bool push(int32_t token, const TokenLogprobs* lp = nullptr);
/* Terminal. Idempotent -- the first call wins, so a cancel racing a natural stop does not
/* Terminal and idempotent: the first call wins, so a cancel racing a natural stop does not
* produce two finish reasons. */
void finish(Finish f);
/* `why` says what failed, in a sentence a client can read; a string that outlives the sink
* (a literal), or null. */
/* `why` is a client-readable sentence 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. */
/* The scheduler polls this to learn the client hung up, then frees the blocks (spec §14).
* IScheduler::cancel() also tells it; this is the cheap path with no lookup. */
bool cancel_requested() const { return cancel_.load(std::memory_order_acquire); }
/* 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. */
/* Marks the first step the scheduler gives this request, where its prompt phase starts, so
* queue time is not counted as prefill. A preempted request keeps its 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. */
/* One verify step: `n` draft tokens proposed, `accepted` taken. Summed per request for
* /metrics' draft counters. */
void add_drafts(int32_t n, int32_t accepted);
/* HOW MUCH OF THE PROMPT IS IN THE CACHE: at admission (what the prefix cache supplied) and
* after every prefill step, of `total`, of which `cached` came from the prefix cache. What
* llama-server streams as `prompt_progress` when a request asks for it; wakes the consumer. */
/* Prompt tokens processed of `total`, `cached` of them from the prefix cache. Set at
* admission and after every prefill step; streamed as llama-server's `prompt_progress` when
* a request asks for it. Wakes the consumer. */
void set_prompt_progress(int32_t processed, int32_t total, int32_t cached);
int32_t progress_processed() const { return prog_done_.load(std::memory_order_acquire); }
int32_t progress_total() const { return prog_total_.load(std::memory_order_acquire); }
@@ -115,9 +105,8 @@ public:
/* ------------------------------------------------------------------ consumer: HTTP */
/* Copies up to `max` tokens out. Returns how many. Never blocks. With `alts`, each token's
* alternatives too: token i's n_alt of them at alts[i * alt_width()], which needs room for
* max * alt_width(). */
/* Copies up to `max` tokens out and returns how many; never blocks. With `alts`, token i's
* n_alt alternatives go to alts[i * alt_width()], which needs room for max * alt_width(). */
size_t read(SinkToken* out, size_t max, SinkAlt* alts = nullptr);
/* Sleeps until there is something to read, the request is terminal, or `timeout_ms` elapses.
@@ -130,8 +119,8 @@ public:
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 --
* the server calls IScheduler::cancel(id) as well; this only stops the producer sooner. */
/* Called by the HTTP thread when the peer disappears. Frees nothing: the server also calls
* IScheduler::cancel(id); this only stops the producer sooner. */
void request_cancel();
/* Timings, in steady-clock nanoseconds since the sink was constructed. -1 until observed. */
@@ -139,7 +128,7 @@ public:
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'
/* The steady clock at construction, which the times above count from; puts two sinks'
* times on one axis. */
int64_t t_start_ns() const { return t_start_ns_; }
@@ -150,19 +139,18 @@ public:
int32_t n_prompt() const { return n_prompt_.load(std::memory_order_acquire); }
int32_t n_cached() const { return n_cached_.load(std::memory_order_acquire); }
/* THE ALTERNATIVES' RING, sized for `n` a token, beside the token ring: allocated only for a
* request that asks for them, because at RAD_MAX_LOGPROBS it is twenty times the token ring.
* Called by the consumer before the request is handed to the scheduler. */
/* Allocates the alternatives ring, `n` per token, beside the token ring. Only requests that
* ask for logprobs get one: at RAD_MAX_LOGPROBS it is twenty times the token ring. The
* consumer calls this before handing the request to the scheduler. */
void enable_logprobs(int n);
int alt_width() const { return alt_w_; }
/* The engine's request id, so a dropped connection can reach IScheduler::cancel. */
uint64_t id = 0;
/* AN EMBEDDING REQUEST'S ANSWER: the pooled vector, written once by the engine before the
* step's commit finishes the request, and read by the consumer only after done(). finish()
* publishes with a release store and done() reads with an acquire load, so the vector is
* visible to anyone who has seen the request finish. Empty for every generating request. */
/* An embedding request's pooled vector; empty for generating requests. Written once by the
* engine before the request finishes and read only after done(): finish()'s release store
* and done()'s acquire load publish it. */
void set_embedding(const float* v, int64_t n) { embd_.assign(v, v + n); }
const std::vector<float>& embedding() const { return embd_; }
@@ -203,8 +191,8 @@ private:
std::condition_variable cv_;
};
/* The scheduler's call sites, so core/sched needs one include and no casts of its own. A null
* sink is legal and means nobody is listening -- an offline or benchmark request. */
/* The scheduler's call sites, so core/sched needs no casts. A null sink means nobody is
* listening (an offline or benchmark request). */
inline bool sink_push(void* s, int32_t token, const TokenLogprobs* lp = nullptr) {
return s ? static_cast<Sink*>(s)->push(token, lp) : true;
}
+589
View File
@@ -0,0 +1,589 @@
/* speech.cpp -- OpenAI's POST /v1/audio/transcriptions, over the model's own speech format.
*
* What this route knows about the model is what its plugin states: the turn a transcription is
* asked in, how a language is forced and named, and where the transcript starts in the reply
* (rad_arch_audio_format, copied into SpeechFormat at startup). This file knows OpenAI's side: the
* form, the response shapes and the stream's events.
*
* Request: multipart/form-data, as OpenAI's is: `file` (required), `model`, `language` (a code or
* a name the model knows), `prompt` (context for the recognition: a name, a domain),
* `response_format` (json, text or verbose_json), `stream`, and `temperature`, which must be 0
* because the decode is greedy, as the reference model's is. Word timestamps are refused rather
* than answered with nothing.
*
* A recording longer than one encoder pass is cut into clips, each ending at the quietest 100 ms of
* the last five seconds before the pass would be full, so a cut lands in a pause where there is
* one. Each clip is one prompt; the clips run a wave at a time and their transcripts are joined
* with a space.
*
* Prompt: the plugin's template with its three slots filled: the request's `prompt` as plain text
* (tokenised with no special tokens parsed, so a caller cannot write the model's control tokens
* into it), the clip's placeholder run, and the forced-language text or nothing.
*/
#include "server.h"
#include "server_priv.h"
#include "mm/processor.h"
#include "rad_internal.h"
#include <nlohmann/json.hpp>
#include <algorithm>
#include <cctype>
#include <cmath>
#include <cstdlib>
#include <ctime>
namespace rad {
namespace server {
std::string SpeechFormat::language_name(const std::string& lang) const {
auto lower = [](std::string s) {
for (char& c : s) c = (char)std::tolower((unsigned char)c);
return s;
};
const std::string l = lower(lang);
for (const auto& p : languages)
if (lower(p.first) == l || lower(p.second) == l) return p.second;
return std::string();
}
namespace {
/* The most a clip's transcript may run to. Thirty seconds of the fastest speech is a few hundred
* tokens; the bound is there for a model that loops, not for one that talks. */
constexpr int32_t kMaxTokensPerClip = 512;
/* The longest recording one request transcribes. */
constexpr int64_t kMaxSeconds = 3600;
/* Clips submitted together. */
constexpr size_t kWave = 8;
std::string trim(const std::string& s) {
size_t a = 0, b = s.size();
while (a < b && std::isspace((unsigned char)s[a])) ++a;
while (b > a && std::isspace((unsigned char)s[b - 1])) --b;
return s.substr(a, b - a);
}
/* Where a long recording is cut: [start, end) clips of at most `max_n` samples, each ending at the
* quietest point in the last five seconds (or half a clip, if that is shorter) before the clip
* would be full. */
std::vector<std::pair<int64_t, int64_t>> cut_clips(const std::vector<float>& x, int64_t max_n,
int32_t rate) {
std::vector<std::pair<int64_t, int64_t>> out;
const int64_t n = (int64_t)x.size();
const int64_t search = std::min<int64_t>(max_n / 2, (int64_t)rate * 5);
int64_t start = 0;
while (n - start > max_n) {
const int64_t hi = start + max_n;
const int64_t best = speech_quiet_point(x, hi - search, hi, rate);
out.emplace_back(start, best);
start = best;
}
out.emplace_back(start, n);
return out;
}
/* What one clip's reply says: the transcript, and the language when the model named it. A reply
* the language was forced in is the transcript alone. */
struct Heard {
std::string language;
std::string text;
};
Heard read_reply(const SpeechFormat& f, const std::string& reply, const std::string& forced) {
if (!forced.empty() || f.transcript_open.empty()) return { forced, trim(reply) };
const size_t at = reply.find(f.transcript_open);
if (at == std::string::npos) return { std::string(), trim(reply) };
Heard h;
h.text = trim(reply.substr(at + f.transcript_open.size()));
const std::string head = reply.substr(0, at);
const size_t lead = f.language_lead.empty() ? std::string::npos : head.rfind(f.language_lead);
const std::string said = trim(lead == std::string::npos ? head
: head.substr(lead + f.language_lead.size()));
/* A name the model does not list (its own "None" for a clip with no speech) is no
* language. */
h.language = f.language_name(said);
return h;
}
std::string lower(std::string s) {
for (char& c : s) c = (char)std::tolower((unsigned char)c);
return s;
}
} /* namespace */
/* ------------------------------------------------------------------ shared with realtime.cpp */
int speech_prompt(const SpeechFormat& f, ITokenizer& tok, const std::string& context,
const std::string& language_text, const std::shared_ptr<mm::Item>& item,
PromptInput* out) {
auto pm = std::make_shared<mm::PromptMedia>();
const std::string& t = f.transcribe_prompt;
auto add = [&](const std::string& text, bool special) {
if (text.empty()) return;
const std::vector<int32_t> ids = tok.encode(text, /*add_special=*/false, special);
out->tokens.insert(out->tokens.end(), ids.begin(), ids.end());
out->text += text;
};
size_t pos = 0;
bool placed = false;
while (pos < t.size()) {
size_t at = t.find('{', pos);
if (at == std::string::npos) at = t.size();
add(t.substr(pos, at - pos), true);
if (at == t.size()) break;
if (!t.compare(at, 9, "{context}")) {
add(context, false);
pos = at + 9;
} else if (!t.compare(at, 10, "{language}")) {
add(language_text, true);
pos = at + 10;
} else if (!t.compare(at, 7, "{audio}")) {
mm::Placed pl;
pl.item = item;
pl.tok = (int32_t)out->tokens.size();
out->tokens.insert(out->tokens.end(), item->expand.begin(), item->expand.end());
out->text += RAD_MEDIA_MARKER;
pm->items.push_back(std::move(pl));
placed = true;
pos = at + 7;
} else {
add("{", true);
pos = at + 1;
}
}
if (!placed) return RAD_E_INVAL;
pm->layout();
out->media = std::move(pm);
return RAD_OK;
}
std::string speech_language_text(const SpeechFormat& f, const std::string& name) {
std::string t = f.language_prompt;
const size_t at = t.find("{language}");
if (at != std::string::npos) t.replace(at, 10, name);
return t;
}
size_t speech_transcript_start(const SpeechFormat& f, const std::string& text, bool forced,
bool closed) {
size_t s = 0;
if (!forced && !f.transcript_open.empty()) {
const size_t at = text.find(f.transcript_open);
if (at == std::string::npos) return closed ? 0 : std::string::npos;
s = at + f.transcript_open.size();
}
while (s < text.size() && std::isspace((unsigned char)text[s])) ++s;
return s;
}
int64_t speech_quiet_point(const std::vector<float>& x, int64_t lo, int64_t hi, int32_t rate) {
const int64_t win = std::max<int64_t>(2, rate / 10);
lo = std::max<int64_t>(lo, 0);
int64_t best = hi;
double best_e = INFINITY;
for (int64_t a = lo; a + win <= hi; a += win / 2) {
double e = 0.0;
for (int64_t i = a; i < a + win; ++i) e += (double)x[(size_t)i] * x[(size_t)i];
if (e < best_e) { best_e = e; best = a + win / 2; }
}
return best;
}
/* One transcription request: the recording, where it is cut, and what each clip heard. Clips
* are prepared a wave at a time, so a long recording holds its samples and one wave's features,
* not every clip's at once. The request holds `places` admission places from its first wave to
* its last, so a later wave is never refused once the first has run. Shared between the handler
* and, for a stream, the transport's callbacks. */
struct Server::TranscriptionJob {
OaiRequest base; /* everything but the prompts and max_tokens */
std::vector<float> samples; /* the whole recording at the model's rate */
std::vector<std::pair<int64_t, int64_t>> cuts; /* each clip's [start, end) in samples */
int32_t rate = 0;
std::string context; /* the request's `prompt`, plain text */
std::string language_text;
std::string forced; /* the forced language's name, "" for none */
std::vector<std::string> replies; /* each clip's whole reply, once its wave is done */
std::vector<Heard> heard;
int64_t n_prompt = 0, n_gen = 0;
size_t next = 0; /* the first clip not yet submitted */
int64_t places = 0; /* admission places held, 0 once released */
/* The wave in flight. */
OaiRequest r;
std::vector<Generation> gens;
bool running = false;
/* Streaming: how much of the stream's text has gone out, and the clip it is reading. */
size_t stream_clip = 0;
size_t stream_off = 0;
bool stream_started = false;
bool done_sent = false;
std::string streamed;
};
HttpResponse Server::handle_transcription(const HttpRequest& req) {
if (!deps_.sched || !deps_.tok)
return error_response(err_not_implemented("the server has no engine attached"), req.peer);
if (!deps_.speech || !deps_.speech->transcribes() || !deps_.mm ||
!deps_.mm->accepts(MediaKind::Audio) || deps_.mm->audio_rate() <= 0)
return error_response(err_not_implemented(
"this model does not transcribe: its architecture plugin states "
"no transcription format (rad_arch_audio_format), or it was "
"started without its audio encoder"),
req.peer);
const SpeechFormat& f = *deps_.speech;
/* ---- the form */
if (req.form.empty())
return error_response(err_bad("file", "expected multipart/form-data with a `file` part, "
"as OpenAI's transcription API takes"),
req.peer);
auto field = [&](const char* k) {
const FormPart* p = req.part(k);
return p ? trim(p->data) : std::string();
};
const FormPart* file = req.part("file");
if (!file || file->data.empty())
return error_response(err_bad("file", "the audio file is missing or empty"), req.peer);
const std::string fmt = field("response_format").empty() ? "json" : field("response_format");
if (fmt != "json" && fmt != "text" && fmt != "verbose_json")
return error_response(err_unsupported("response_format",
"json, text or verbose_json; not '" + fmt + "'"),
req.peer);
const std::string stream_s = lower(field("stream"));
const bool stream = stream_s == "true" || stream_s == "1";
if (!stream_s.empty() && !stream && stream_s != "false" && stream_s != "0")
return error_response(err_bad("stream", "expected true or false"), req.peer);
if (const std::string t = field("temperature"); !t.empty()) {
char* end = nullptr;
const double v = std::strtod(t.c_str(), &end);
if (end == t.c_str() || *end != '\0' || !std::isfinite(v))
return error_response(err_bad("temperature", "expected a number, not '" + t + "'"),
req.peer);
if (v != 0.0)
return error_response(err_unsupported("temperature",
"this route decodes greedily, as the model's "
"reference does; send 0 or leave it out"),
req.peer);
}
for (const FormPart& p : req.form)
if ((p.name == "timestamp_granularities[]" || p.name == "timestamp_granularities") &&
trim(p.data) == "word")
return error_response(err_unsupported("timestamp_granularities",
"word timestamps are not produced; verbose_json "
"carries one segment a clip"),
req.peer);
std::string forced;
if (!field("language").empty()) {
forced = f.language_name(field("language"));
if (forced.empty()) {
std::string known;
for (const auto& l : f.languages) known += (known.empty() ? "" : ", ") + l.first;
return error_response(err_bad("language", "this model names no language '" +
field("language") + "'; it knows " +
known),
req.peer);
}
}
/* ---- the recording, and where it is cut into clips one encoder pass each */
auto job = std::make_shared<TranscriptionJob>();
job->rate = deps_.mm->audio_rate();
const int32_t rate = job->rate;
const int64_t max_clip = deps_.mm->audio_max_samples();
{
std::string why;
const std::vector<uint8_t> bytes(file->data.begin(), file->data.end());
const int s = deps_.mm->decode_audio(bytes, kMaxSeconds * rate, &job->samples, &why);
if (s < 0) return error_response(err_bad("file", "the audio could not be used: " + why),
req.peer);
}
if (job->samples.empty())
return error_response(err_bad("file", "the recording holds no audio"), req.peer);
job->cuts = cut_clips(job->samples, max_clip > 0 ? max_clip : (int64_t)job->samples.size(),
rate);
job->context = field("prompt");
job->forced = forced;
job->language_text = forced.empty() ? std::string() : speech_language_text(f, forced);
job->replies.assign(job->cuts.size(), std::string());
job->heard.assign(job->cuts.size(), Heard{});
OaiRequest& b = job->base;
b.endpoint = Endpoint::Completion;
b.shape = ApiShape::OpenAI;
b.model = opt_.model_id;
b.id = random_id("tr-");
b.created = (int64_t)std::time(nullptr);
b.peer = req.peer;
b.n = 1;
b.sp = SamplingParams{};
b.sp.temp = 0.0f;
b.sp.top_k = 1;
/* A wave is at most kWave clips and never more than the admission queue holds. */
const size_t wave = (size_t)std::max<int64_t>(
1, std::min<int64_t>({ (int64_t)kWave, (int64_t)job->cuts.size(), queue_depth_ }));
if (auto no = admit((int64_t)wave, req.peer)) return *no;
job->places = (int64_t)wave;
sweep_abandoned();
Server* self = this;
const SpeechFormat* fp = &f;
auto release_job = [self, job]() {
if (job->places > 0) { self->release(job->places); job->places = 0; }
};
/* Prepare and submit the next wave; false with `*err` set when it could not be. */
auto start_wave = [self, job, fp, wave](ApiError* err) -> bool {
const size_t n = std::min(wave, job->cuts.size() - job->next);
job->r = job->base;
job->r.prompts.clear();
int64_t longest = 0;
for (size_t i = job->next; i < job->next + n; ++i) {
const std::vector<float> clip(job->samples.begin() + job->cuts[i].first,
job->samples.begin() + job->cuts[i].second);
std::shared_ptr<mm::Item> item;
std::string why;
if (self->deps_.mm->prepare_audio(clip, &item, &why) < 0 || !item) {
*err = err_bad("file", "the audio could not be used: " + why);
return false;
}
PromptInput p;
if (speech_prompt(*fp, *self->deps_.tok, job->context, job->language_text, item,
&p) < 0) {
*err = err_not_implemented("the model's transcription template has no {audio} "
"slot");
return false;
}
longest = std::max<int64_t>(longest, (int64_t)p.tokens.size());
job->n_prompt += (int64_t)p.tokens.size();
job->r.prompts.push_back(std::move(p));
}
job->r.max_tokens = kMaxTokensPerClip;
if (self->lim_.max_ctx > 0) {
if (longest >= self->lim_.max_ctx) {
*err = err_bad("file", "a clip's prompt (" + std::to_string(longest) +
" tokens) is longer than the context");
return false;
}
job->r.max_tokens = (int32_t)std::min<int64_t>(job->r.max_tokens,
self->lim_.max_ctx - longest);
}
if (job->next == 0) self->log_admitted(job->r);
job->gens.clear();
if (self->submit_all(job->r, &job->gens, err) < 0) {
self->retire(job->gens);
return false;
}
job->running = true;
return true;
};
/* A wave that has finished: its replies kept, its sequences retired. Error when one failed. */
auto finish_wave = [self, job, fp](std::string* failure) -> bool {
Finish overall = Finish::Stop;
for (const auto& g : job->gens) {
const size_t k = job->next + (size_t)g.prompt_index;
job->replies[k] = g.text;
job->heard[k] = read_reply(*fp, g.text, job->forced);
job->n_gen += g.sink->n_produced();
if (g.finish == Finish::Error) {
overall = Finish::Error;
if (failure) *failure = engine_failure(*g.sink);
}
}
self->record(job->r, job->gens, overall);
self->retire(job->gens);
job->next += job->r.prompts.size();
job->running = false;
return overall != Finish::Error;
};
auto joined = [job]() {
std::string t;
for (const Heard& h : job->heard) {
if (h.text.empty()) continue;
if (!t.empty()) t += ' ';
t += h.text;
}
return t;
};
auto usage = [job]() {
nlohmann::ordered_json u;
u["type"] = "tokens";
u["input_tokens"] = job->n_prompt;
u["output_tokens"] = job->n_gen;
u["total_tokens"] = job->n_prompt + job->n_gen;
return u;
};
auto internal = [](const std::string& why) {
ApiError e;
e.status = 500;
e.type = "internal_server_error";
e.message = why;
return e;
};
if (!stream) {
while (job->next < job->cuts.size()) {
ApiError err;
if (!start_wave(&err)) {
release_job();
return error_response(err, req.peer);
}
for (;;) {
pump(job->gens, job->r);
if (all_done(job->gens)) break;
if (req.peer_gone() || stopping_.load()) {
cancel_all(job->gens, req.peer_gone());
record(job->r, job->gens, Finish::Cancelled);
retire(job->gens);
release_job();
if (req.peer_gone()) {
metrics_.observe_http(499);
return HttpResponse::text(499, "client closed request\n");
}
return error_response(err_overloaded("the server is shutting down"), req.peer);
}
for (auto& g : job->gens) if (!g.closed) { g.sink->wait(); break; }
}
std::string failure;
if (!finish_wave(&failure)) {
release_job();
return error_response(internal(failure), req.peer);
}
}
release_job();
const std::string text = joined();
metrics_.observe_http(200);
if (fmt == "text") return HttpResponse::text(200, text + "\n");
nlohmann::ordered_json o;
if (fmt == "verbose_json") {
std::string lang = forced;
for (const Heard& h : job->heard)
if (lang.empty() && !h.language.empty()) lang = h.language;
o["task"] = "transcribe";
o["language"] = lower(lang);
o["duration"] = (double)job->samples.size() / rate;
o["text"] = text;
nlohmann::ordered_json segs = nlohmann::ordered_json::array();
for (size_t i = 0; i < job->heard.size(); ++i) {
nlohmann::ordered_json s;
s["id"] = (int64_t)i;
s["start"] = (double)job->cuts[i].first / rate;
s["end"] = (double)job->cuts[i].second / rate;
s["text"] = job->heard[i].text;
segs.push_back(std::move(s));
}
o["segments"] = std::move(segs);
} else {
o["text"] = text;
}
o["usage"] = usage();
return HttpResponse::json_body(200, json_dump(o));
}
/* ---- the stream: transcript.text.delta events as each clip's transcript settles, in clip
* order, then transcript.text.done with the whole text. */
{
ApiError err;
if (!start_wave(&err)) {
release_job();
return error_response(err, req.peer);
}
}
HttpResponse res;
res.status = 200;
res.content_type = "text/event-stream; charset=utf-8";
res.set_header("Cache-Control", "no-cache");
res.set_header("Connection", "keep-alive");
res.set_header("X-Accel-Buffering", "no");
auto peer_closed = req.closed;
res.next = [self, job, peer_closed, fp, start_wave, finish_wave, joined, usage, internal,
release_job](std::string& out) -> bool {
out.clear();
if (job->done_sent) return false;
if (peer_closed && peer_closed()) return false;
auto delta = [&](const std::string& d) {
if (d.empty()) return;
nlohmann::ordered_json o;
o["type"] = "transcript.text.delta";
o["delta"] = d;
out += sse_event(json_dump(o));
job->streamed += d;
};
const bool progress = job->running && self->pump(job->gens, job->r);
/* Whatever of the clip being read has settled; the clips after it wait their turn. */
while (job->stream_clip < job->cuts.size()) {
const size_t k = job->stream_clip;
const bool in_wave = k >= job->next && k < job->next + job->gens.size() && job->running;
const Generation* g = in_wave ? &job->gens[k - job->next] : nullptr;
const bool closed = g ? g->closed : k < job->next;
const std::string& text = g ? g->text : job->replies[k];
const size_t s = speech_transcript_start(*fp, text, !job->forced.empty(), closed);
if (s != std::string::npos) {
std::string end = closed ? trim(text.substr(std::min(s, text.size())))
: text.substr(s);
if (closed && end.size() < job->stream_off) end.clear();
if (end.size() > job->stream_off) {
std::string d = end.substr(job->stream_off);
if (!job->stream_started && !job->streamed.empty() && job->stream_off == 0)
d = " " + d;
if (job->stream_off == 0 && !d.empty()) job->stream_started = true;
job->stream_off = end.size();
delta(d);
}
}
if (!closed) break;
++job->stream_clip;
job->stream_off = 0;
job->stream_started = false;
}
if (job->running && self->all_done(job->gens)) {
std::string failure;
if (!finish_wave(&failure)) {
out += sse_error(internal(failure));
job->done_sent = true;
release_job();
return true;
}
if (job->next < job->cuts.size()) {
ApiError err;
if (!start_wave(&err)) {
out += sse_error(err);
job->done_sent = true;
release_job();
return true;
}
}
return true;
}
if (!job->running && job->stream_clip >= job->cuts.size()) {
release_job();
nlohmann::ordered_json o;
o["type"] = "transcript.text.done";
o["text"] = joined();
o["usage"] = usage();
out += sse_event(json_dump(o));
job->done_sent = true;
self->metrics_.observe_http(200);
return true;
}
if (!progress && out.empty() && job->running)
for (auto& g : job->gens) if (!g.closed) { g.sink->wait(); break; }
return true;
};
res.on_close = [self, job, release_job](bool) {
if (job->running) {
self->cancel_all(job->gens, true);
self->record(job->r, job->gens, Finish::Cancelled);
self->retire(job->gens);
job->running = false;
}
release_job();
};
return res;
}
} /* namespace server */
} /* namespace rad */
+16 -23
View File
@@ -1,19 +1,18 @@
/* systemone.cpp -- d1's prompt and readout (systemone.h).
*
* EVERY STRING BELOW IS d1's OWN, from prompt.py in the model's repository: the user turn, the
* state block, the three question blocks, the option codes and their fallback codebook, the
* yes/no spellings. The model was trained on exactly these, so a reworded instruction or a
* different code for an option is a different (and worse-calibrated) question.
* Every prompt string below is d1's own, from prompt.py in the model's repository: the user turn,
* the state block, the three question blocks, the option codes and their fallback codebook, and the
* yes/no spellings. The model was trained on exactly these; a reworded instruction or a different
* option code is a different, worse-calibrated question.
*
* THAT TEXT IS LIQUID AI'S, under the LFM Open License v1.0 (core/server/LICENSE.lfm, and NOTICE):
* this file is a C++ rewrite of prompt.py's and api.py's logic, modified from them, with their
* That text is Liquid AI's, under the LFM Open License v1.0 (core/server/LICENSE.lfm, and NOTICE).
* This file is a C++ rewrite of prompt.py's and api.py's logic, modified from them, with their
* strings kept as they are.
*
* AND SO IS THE TOKENISATION SPLIT. d1 tokenises a single question's prompt as one text, and a
* request with several as the shared head (the state and the pictures) followed by each question's
* tail, tokenised separately -- its runner reads the head once and branches. The two are not the
* same ids where BPE would merge across the join, so each case is tokenised the way the model's
* own runner does.
* The tokenisation split also follows d1's runner: a single question's prompt is tokenised as one
* text; with several, the shared head (state and pictures) and each question's tail are tokenised
* separately, and the runner reads the head once and branches. BPE can merge across the join, so
* the two give different ids.
*/
#include "systemone.h"
@@ -253,7 +252,7 @@ int parse_decision_request(const std::string& body, const OaiDeps& d, const OaiL
return RAD_E_INVAL;
}
/* THE PICTURES, decoded here and processed when the head is tokenised. */
/* Pictures are decoded here and processed when the head is tokenised. */
std::vector<std::pair<MediaKind, std::vector<uint8_t>>> media;
if (b.contains("images")) {
const json& im = b["images"];
@@ -302,8 +301,8 @@ int parse_decision_request(const std::string& body, const OaiDeps& d, const OaiL
suffixes.push_back(std::move(suffix));
}
/* runner.py, VISION_MAX_PIXELS: d1 bounds every picture at 1024 x 1024 pixels' area before
* its processor, so a larger one is a different input unless it is bounded here too. */
/* runner.py, VISION_MAX_PIXELS: d1 caps every picture at 1024 x 1024 pixels' area before its
* processor, so the same cap applies here. */
MediaOpts opts;
opts.max_pixels = 1024 * 1024;
auto tokenize = [&](const std::string& text, std::vector<int32_t>* ids) -> int {
@@ -330,7 +329,7 @@ int parse_decision_request(const std::string& body, const OaiDeps& d, const OaiL
out->input_tokens += (int64_t)tail.size();
}
}
/* One position stays free: the request samples a token, which nobody reads. */
/* One position stays free for the token the request samples and discards. */
for (const DecisionQuestion& q : out->questions)
if (lim.max_ctx > 0 && (int64_t)q.tokens.size() >= lim.max_ctx) {
ApiError e = err_bad("questions." + q.name,
@@ -347,10 +346,7 @@ int parse_decision_request(const std::string& body, const OaiDeps& d, const OaiL
int decision_answer(const DecisionQuestion& q, const std::vector<float>& logits, json* out,
ApiError* err) {
if (logits.size() != q.candidates.size() || q.groups.size() != q.labels.size()) {
*err = ApiError{};
err->status = 500;
err->type = "internal_server_error";
err->message = "the engine returned no scores for question " + q.name;
*err = err_internal("the engine returned no scores for question " + q.name);
return RAD_E_STATE;
}
std::vector<double> p;
@@ -358,10 +354,7 @@ int decision_answer(const DecisionQuestion& q, const std::vector<float>& logits,
double best = -std::numeric_limits<double>::infinity();
for (size_t i : g) best = std::max(best, (double)logits[i]);
if (!std::isfinite(best)) {
*err = ApiError{};
err->status = 500;
err->type = "internal_server_error";
err->message = "question " + q.name + " scored a non-finite logit";
*err = err_internal("question " + q.name + " scored a non-finite logit");
return RAD_E_STATE;
}
p.push_back(best);
+13 -13
View File
@@ -1,13 +1,13 @@
/* systemone.h -- POST /v1/systemone: LiquidAI d1's decisions, a distribution read off one position.
*
* d1 is a decision model. It is given a state (text, any JSON value, pictures, or a mix) and named
* questions, and each answer is a softmax over a handful of tokens at the position right after the
* assistant header: `yes` / `no` for a noul, one code a option for a choice, a digit a level for a
* score. Nothing is generated. The API and the prompt are the model's own (its prompt.py and api.py
* on the Hub); this file is that adapter, and the engine knows nothing of it beyond
* Request::token_scores -- "read these ids' raw logits at the prompt's last position".
* questions; each answer is a softmax over a few tokens at the position right after the assistant
* header: `yes` / `no` for a noul, one code per option for a choice, one digit per level for a
* score. Nothing is generated. The API and prompt are the model's own (prompt.py and api.py on the
* Hub). The engine sees only Request::token_scores: read these ids' raw logits at the prompt's last
* position.
*
* A container serves it only when it says it is d1 (`decision.type` = `d1`, set at convert with
* Served only when the container declares d1 (`decision.type` = `d1`, set at convert with
* `--set decision.type=d1`); the HF config does not declare it.
*/
#pragma once
@@ -23,12 +23,12 @@ namespace server {
struct DecisionQuestion {
std::string name, type; /* type: noul | choice | score */
/* One entry an answer, in the response's order: "true"/"false", the option names, the
* levels "0".."n-1". */
/* One entry per answer, in response order: "true"/"false", the option names, or the levels
* "0".."n-1". */
std::vector<std::string> labels;
std::vector<std::string> legend; /* score: each level's description */
/* The ids read at the answer slot, and for each answer the indices into them of the
* spellings it scores as: an answer's score is its best spelling's. */
/* The ids read at the answer slot, and per answer the indices of its spellings among them;
* an answer scores as its best spelling. */
std::vector<int32_t> candidates;
std::vector<std::vector<size_t>> groups;
std::vector<int32_t> tokens; /* the whole prompt */
@@ -41,7 +41,7 @@ struct DecisionRequest {
/* How many leading tokens every question's prompt shares: the state, tokenised once. 0 for
* a single question, which d1 tokenises as one text. */
int32_t trunk = 0;
/* What the model reads, as d1 counts it: the shared head once and each question's own tail. */
/* Input tokens as d1 counts them: the shared head once plus each question's tail. */
int64_t input_tokens = 0;
};
@@ -50,8 +50,8 @@ struct DecisionRequest {
int parse_decision_request(const std::string& body, const OaiDeps& d, const OaiLimits& lim,
const std::string& model_id, DecisionRequest* out, ApiError* err);
/* One answer from its candidates' raw logits: each answer scores its best spelling, a softmax over
* the answers is the distribution. Non-finite logits are an error, not a distribution. */
/* One question's answer from its candidates' raw logits: each answer scores its best spelling and
* a softmax over the answers is the distribution. A non-finite logit is an error. */
int decision_answer(const DecisionQuestion& q, const std::vector<float>& logits, json* out,
ApiError* err);