radiance 1.0.0

This commit is contained in:
Deadcode committed 2026-10-04 12:02:41 +02:00
commit ae74a8aebf
616 files changed
+338692

No files matched your search

+695
View File
@@ -0,0 +1,695 @@
/* 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.
*
* 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.
*/
#pragma once
#include "iface.h"
#include "mem/kvtier.h"
#if !defined(RAD_SERVER_NO_ENGINE_BRIDGE) && \
__has_include("sched/scheduler.h") && __has_include("text/tokenizer.h")
#define RAD_SERVER_HAVE_ENGINE_BRIDGE 1
#include "sample/gbnf.h"
#include "sample/grammar.h"
#include "sample/sampler.h"
#include "sched/scheduler.h"
#include "rad_builder.h"
#include "text/chat.h"
#include "text/chatfmt.h"
#include "text/chatparse.h"
#include "text/tokenizer.h"
#include "mm/processor.h"
#include <nlohmann/json.hpp>
#include <algorithm>
#include <atomic>
#include <memory>
namespace rad {
namespace server {
/* ================================================================== scheduler */
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-host-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. */
explicit SchedulerBridge(Scheduler* s, const Sampler* sampler = nullptr,
const IdleTiers* tiers = nullptr)
: s_(s), sampler_(sampler), tiers_(tiers) {}
int admit(const SamplingParams& sp, std::string* why) const override {
if (!sampler_) return RAD_OK;
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;
}
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<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;
}
s_->add_all(ps.data(), n, rc.data());
for (size_t i = 0; i < n; ++i) {
if (rc[i] >= 0) continue;
RAD_WARN("server: scheduler refused request %llu: %s",
(unsigned long long)(*ids)[i], rad_strerror(rc[i]));
(*ids)[i] = 0;
}
}
void cancel(uint64_t id) override { s_->cancel(id); }
void reap(uint64_t id) override { s_->reap(id); }
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. */
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.to_disk = s.to_disk;
c.promoted = s.promoted;
c.host_freed = s.host_freed; c.host_drops = s.host_drops; c.failures = s.failures;
c.fetched = s.fetched; c.ck_fetched = s.ck_fetched;
c.host_bytes = s.host_bytes; c.disk_bytes = s.disk_bytes;
c.ck_to_host = s.ck_to_host; c.ck_to_disk = s.ck_to_disk; c.ck_promoted = s.ck_promoted;
c.ck_drops = s.ck_drops; c.ck_starved = s.ck_starved;
c.ck_bytes = tiers_->ckpt_bytes();
c.ck_host_slots = tiers_->ckpt_arena().capacity();
c.ck_disk_slots = tiers_->ckpt_disk_slots();
c.host_on = tiers_->host_on();
c.disk_on = tiers_->disk_on();
return c;
}
int sessions(std::vector<SessionStat>* out, SessionOccupancy* occ) const override {
out->clear();
if (!tiers_) return 0;
IdleTiers::Occupancy held;
const std::vector<IdleTiers::SessionInfo> v = tiers_->sessions(occ ? &held : nullptr);
if (occ) {
occ->host_bytes = held.host_bytes; occ->disk_bytes = held.disk_bytes;
occ->host_cap_bytes = held.host_cap_bytes; occ->disk_cap_bytes = held.disk_cap_bytes;
}
const uint64_t now = rad_mono_ns();
out->reserve(v.size());
for (const IdleTiers::SessionInfo& s : v) {
SessionStat o;
o.id = s.id;
o.model = s.model;
o.n_tokens = s.n_tokens;
o.bytes = s.bytes;
o.idle_s = now > s.last_used_ns ? (double)(now - s.last_used_ns) / 1e9 : 0.0;
o.age_s = now > s.first_seen_ns ? (double)(now - s.first_seen_ns) / 1e9 : 0.0;
o.on_device = s.on_device;
o.on_host = s.on_host;
o.on_disk = s.on_disk;
o.moving = s.moving;
o.snapshots = s.snapshots;
o.snap_device = s.snap_device;
o.snap_host = s.snap_host;
o.snap_disk = s.snap_disk;
o.snap_bytes = s.snap_bytes;
o.resume_tokens = s.resume_tokens;
out->push_back(std::move(o));
}
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. */
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());
out->clear();
out->reserve((size_t)n);
for (int i = 0; i < n; ++i) {
const Scheduler::ReqStat& r = raw[(size_t)i];
RequestStat o;
o.id = r.id;
switch ((ReqState)r.state) {
case ReqState::Waiting: o.state = "waiting"; break;
case ReqState::Preempted: o.state = "preempted"; break;
case ReqState::Running:
o.state = r.computed_tokens < r.prompt_tokens ? "prefill" : "decode";
break;
default: o.state = "done"; break;
}
o.prompt_tokens = r.prompt_tokens;
o.computed_tokens = r.computed_tokens;
o.cached_tokens = r.cached_tokens;
o.output_tokens = r.output_tokens;
o.max_tokens = r.max_tokens;
o.ctx_tokens = r.ctx_tokens;
o.kv_blocks = r.kv_blocks;
o.kv_tokens = r.kv_tokens;
o.n_draft = r.n_draft;
o.slot = r.slot;
o.age_s = r.age_s;
o.ttft_s = r.ttft_s;
o.decode_tps = r.decode_tps;
out->push_back(std::move(o));
}
return n;
}
/* 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;
}
/* 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.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.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.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.decode_rows_unspeculated = m.decode_rows_unspeculated;
o.step_ns = m.step_ns; o.step_ns_decode = m.step_ns_decode;
return o;
}
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. */
Scheduler* s_;
const Sampler* sampler_ = nullptr;
const IdleTiers* tiers_ = nullptr;
/* Ids start at 1: zero is the "no request" value the sink and the metrics use. */
std::atomic<uint64_t> next_{1};
};
/* ================================================================== text */
class DetokenizerBridge final : public IDetokenizer {
public:
DetokenizerBridge(std::shared_ptr<const Vocab> v, std::vector<std::string> stops,
const std::vector<std::string>& preserved)
: d_(std::move(v), std::move(stops), /*render_special=*/false, preserved) {}
std::string push(int32_t t) override { return d_.push(t); }
std::string flush() override { return d_.flush(); }
bool stopped() const override { return d_.stopped(); }
private:
Detokenizer d_;
};
class TokenizerBridge final : public ITokenizer {
public:
explicit TokenizerBridge(std::shared_ptr<const Vocab> v) : vocab_(std::move(v)) {
tok_.init(vocab_);
}
std::vector<int32_t> encode(const std::string& text, bool add_special,
bool parse_special) const override {
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. */
RAD_WARN("server: tokenise failed: %s", rad_strerror(st));
out.clear();
}
return out;
}
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. */
return utf8_sanitize(tok_.decode(ids, /*render_special=*/false));
}
int32_t eos() const override { return vocab_->eos(); }
int32_t bos() const override { return vocab_->bos(); }
VocabInfo vocab_info() const override {
VocabInfo i;
i.n_tokens = vocab_->n_tokens();
i.bos = vocab_->bos(); i.eos = vocab_->eos(); i.eot = vocab_->eot();
i.unk = vocab_->unk(); i.pad = vocab_->pad();
i.add_bos = vocab_->add_bos(); i.add_eos = vocab_->add_eos();
switch (vocab_->kind()) {
case RAD_TOK_BPE: i.kind = "bpe"; break;
case RAD_TOK_UNIGRAM: i.kind = "unigram"; break;
case RAD_TOK_WORDPIECE: i.kind = "wordpiece"; break;
case RAD_TOK_RWKV: i.kind = "rwkv"; break;
default: i.kind = "unknown"; break;
}
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. */
std::string piece(int32_t id) const override {
if (id < 0 || id >= vocab_->n_tokens()) return std::string();
return utf8_sanitize(vocab_->text(id));
}
std::unique_ptr<IDetokenizer> detokenizer(
const std::vector<std::string>& stops,
const std::vector<std::string>& preserved = {}) const override {
return std::unique_ptr<IDetokenizer>(new DetokenizerBridge(vocab_, stops, preserved));
}
private:
std::shared_ptr<const Vocab> vocab_;
Tokenizer tok_;
};
/* ================================================================== 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:
*
* * `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.
*
* * 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.
*/
class ReplyReaderBridge final : public IReplyReader {
public:
ReplyReaderBridge(std::unique_ptr<ReplyStream> s, const std::string* format_name)
: s_(std::move(s)), name_(format_name),
keep_(log_level() >= Log::Trace) {}
void feed(std::string_view text, std::vector<ReplyDelta>* out) override {
if (keep_) raw_.append(text);
s_->feed(text, out ? &ev_ : nullptr);
move_out(out);
}
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. */
if (!s_->strict() && !warned_) {
warned_ = true;
RAD_WARN("server: a reply left the '%s' reply format and was read by its recovery "
"rules; at trace level the reply is logged", name_->c_str());
if (keep_) RAD_TRACE("server: the reply was <<<%s>>>", raw_.c_str());
}
}
ParsedMessage message() const override {
const ReplyMessage& r = s_->message();
ParsedMessage m;
m.content = r.content;
m.reasoning = r.reasoning;
m.tool_calls.reserve(r.calls.size());
for (const ReplyCall& c : r.calls) m.tool_calls.push_back({ std::string(), c.name, c.arguments });
return m;
}
private:
void move_out(std::vector<ReplyDelta>* out) {
if (!out) return;
for (ReplyEvent& e : ev_) {
ReplyDelta d;
switch (e.kind) {
case ReplyEvent::Reasoning: d.kind = ReplyDelta::Reasoning; break;
case ReplyEvent::Content: d.kind = ReplyDelta::Content; break;
case ReplyEvent::CallBegin: d.kind = ReplyDelta::CallBegin; break;
case ReplyEvent::CallArgs: d.kind = ReplyDelta::CallArgs; break;
case ReplyEvent::CallEnd: d.kind = ReplyDelta::CallEnd; break;
}
d.call = e.call;
d.text = std::move(e.text);
out->push_back(std::move(d));
}
ev_.clear();
}
std::unique_ptr<ReplyStream> s_;
const std::string* name_;
std::vector<ReplyEvent> ev_;
bool keep_ = false, warned_ = false;
std::string raw_; /* the reply, kept only when trace logging is on */
};
class ReplyParserBridge final : public IReplyParser {
public:
explicit ReplyParserBridge(std::shared_ptr<const ReplyParser> p) : p_(std::move(p)) {}
std::unique_ptr<IReplyReader> open() const override {
return std::unique_ptr<IReplyReader>(new ReplyReaderBridge(p_->open(), &p_->format().name));
}
private:
std::shared_ptr<const ReplyParser> p_;
};
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.
*
* `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. */
int init(const Vocab& v, const RadChatFormat* declared = nullptr,
const std::string& plugin = std::string()) {
/* The spellings, resolved once. See ReplyOptions::terminators. */
terminators_.clear();
for (int32_t id : v.eog()) {
const std::string s = v.text(id);
if (!s.empty()) terminators_.push_back(s);
}
const int st = t_.load_from_vocab(v);
if (st < 0) return st;
ChatFormat f;
std::string why;
declared_ = declared != nullptr;
if (declared) {
if (chat_format_from_abi(declared, &f, &why) < 0 || chat_format_check(f, &why) < 0) {
RAD_ERR("chat: plugin '%s' declares a reply format the parser cannot run: %s",
plugin.c_str(), why.c_str());
return RAD_E_INVAL;
}
if (f.name.empty()) f.name = "plugin:" + plugin;
} else {
const std::string bos = v.bos() >= 0 ? v.text(v.bos()) : std::string();
const std::string eos = v.eos() >= 0 ? v.text(v.eos()) : std::string();
std::string refused;
if (chat_format_from_template(v.chat_template(), bos, eos, &f, &refused, &why) < 0) {
RAD_WARN("chat: this model's reply format cannot be described (%s). Replies are "
"returned as content with no reasoning split, and requests with tools "
"are refused.", why.c_str());
f = ChatFormat{};
f.name = "content";
tool_refusal_ = why;
} else if (!refused.empty()) {
tool_refusal_ = refused;
} else if (t_.caps().tools && !f.has_tools()) {
tool_refusal_ = "the template analysis found no tool-call format in it";
}
}
if (ReplyFormat::compile(f, &fmt_, &why) < 0) {
RAD_ERR("chat: the reply format '%s' cannot be run: %s", f.name.c_str(), why.c_str());
return RAD_E_INVAL;
}
RAD_INFO("chat: reply format %s", chat_format_describe(f).c_str());
if (t_.caps().tools && !tool_refusal_.empty())
RAD_WARN("chat: tool calls are refused for this model: %s", tool_refusal_.c_str());
return RAD_OK;
}
bool ready() const { return t_.ready() && fmt_ != nullptr; }
bool supports_tools() const override { return t_.caps().tools; }
bool supports_reasoning() const override { return t_.caps().preserve_reasoning; }
std::string tool_refusal() const override { return tool_refusal_; }
const std::string& source() const { return t_.source(); }
int apply(const json& messages, const json& tools, const ChatRenderOptions& opt,
ChatRender* out, std::string* why) const override {
ChatOptions o;
o.add_generation_prompt = opt.add_generation_prompt;
o.enable_thinking = opt.enable_thinking;
o.parallel_tool_calls = opt.parallel_tool_calls;
o.tool_choice = opt.tool_choice;
o.reasoning_format = opt.reasoning_format;
o.grammar = opt.grammar;
o.json_schema = opt.json_schema;
o.template_kwargs = opt.template_kwargs;
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. */
if (why)
*why = !p.error.empty()
? p.error
: st == RAD_E_UNSUPPORTED
? "the model's chat template refused this request"
: "the messages could not be rendered by this model's chat "
"template";
return st;
}
const ChatFormat& f = fmt_->format();
/* Calls are parsed only when the request offered tools to call. With none, or with
* `tool_choice: "none"` (which arrives here with the tools already cleared), call syntax
* in the reply is prose to this request. */
const bool calls = opt.tool_choice != "none" && tools.is_array() && !tools.empty();
const bool doc = !opt.json_schema.empty();
out->prompt = std::move(p.prompt);
out->additional_stops = std::move(p.additional_stops);
out->generation_prompt = p.generation_prompt;
out->preserved_tokens = declared_ ? chat_format_markers(f) : p.preserved_tokens;
out->grammar_triggers.clear();
if (calls || doc) {
/* The grammar, and the words that trigger it, come from the reply format: the same
* description the parser reads the reply back with. */
const nlohmann::ordered_json schema =
doc ? nlohmann::ordered_json::parse(opt.json_schema, nullptr, false)
: nlohmann::ordered_json();
ChatGrammarRequest gq;
gq.tools = calls ? &tools : nullptr;
gq.json_schema = doc && schema.is_object() ? &schema : nullptr;
gq.generation_prompt = p.generation_prompt;
gq.parallel_tool_calls = opt.parallel_tool_calls;
gq.extract_reasoning = opt.reasoning_format != "none";
ChatGrammar g;
std::string gerr;
if (chat_format_grammar(f, gq, &g, &gerr) < 0) {
if (why) *why = "the grammar for this request could not be built: " + gerr;
return RAD_E_INVAL;
}
out->grammar = std::move(g.text);
out->grammar_lazy = g.lazy;
for (const std::string& w : g.trigger_words)
out->grammar_triggers.push_back({ kTriggerWord, w });
} else {
out->grammar = std::move(p.grammar);
out->grammar_lazy = p.grammar_lazy;
for (const auto& t : p.grammar_triggers)
out->grammar_triggers.push_back({ t.type, t.value });
}
ReplyOptions ro;
ro.generation_prompt = p.generation_prompt;
ro.extract_reasoning = opt.reasoning_format != "none";
ro.tools = calls ? &tools : nullptr;
ro.parallel_tool_calls = opt.parallel_tool_calls;
ro.response_format = doc;
ro.terminators = terminators_;
std::shared_ptr<const ReplyParser> rp;
std::string perr;
const int ps = ReplyParser::create(fmt_, ro, &rp, &perr);
if (ps < 0) {
if (why) *why = perr;
return ps;
}
out->parser = std::make_shared<ReplyParserBridge>(std::move(rp));
return RAD_OK;
}
private:
/* A lazy grammar's trigger is a literal word; SamplingParams::GrammarTrigger numbers the
* kinds the way llama.cpp's common_grammar_trigger_type does. */
static constexpr int kTriggerWord = 1;
ChatTemplate t_;
std::vector<std::string> terminators_;
std::shared_ptr<const ReplyFormat> fmt_;
bool declared_ = false;
std::string tool_refusal_;
};
/* ================================================================== 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.
*/
class GrammarBridge final : public IGrammarCompiler {
public:
explicit GrammarBridge(const VocabView* v) : v_(v) {}
int from_json_schema(const json& schema, std::string& out, std::string& err) const override {
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. */
int compile(const std::string& gbnf, std::shared_ptr<const GbnfProgram>* out,
std::string& err) const override {
if (gbnf.empty()) return RAD_OK;
if (!v_) { err = "no vocabulary attached"; return RAD_E_STATE; }
return gbnf_compile(gbnf, "root", v_, out, &err);
}
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. */
class MultimodalBridge final : public IMultimodal {
public:
MultimodalBridge(const mm::Processor* p, uint32_t modalities) : p_(p), mod_(modalities) {}
bool accepts(MediaKind k) const override {
if (!p_ || !mm::decoder_available()) return false;
if (k == MediaKind::Image) return (mod_ & RAD_MM_IMAGE) != 0;
if (k == MediaKind::Video) return (mod_ & RAD_MM_VIDEO) != 0;
return false;
}
int prepare(MediaKind k, const std::vector<uint8_t>& bytes, std::shared_ptr<mm::Item>* out,
std::string* why) override {
if (!accepts(k)) { if (why) *why = "this kind of media is not served"; return RAD_E_UNSUPPORTED; }
return k == MediaKind::Image ? p_->image(bytes.data(), bytes.size(), out, why)
: p_->video(bytes.data(), bytes.size(), out, why);
}
private:
const mm::Processor* p_;
uint32_t mod_;
};
} /* namespace server */
} /* namespace rad */
#endif /* the engine components are present */
+347
View File
@@ -0,0 +1,347 @@
/* core/server/admin.cpp -- vLLM's non-generation endpoints.
*
* /version /ping /load /tokenize /detokenize /get_tokenizer_info /server_info /reset_prefix_cache.
*
* 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.
*
* WHAT IS DELIBERATELY NOT HERE. vLLM's surface also carries /pooling, /classify, /score and
* /rerank (an embedding or cross-encoder model, 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
* /v1/responses (a stateful conversation store, which is a component and not an endpoint). Each
* would be a lie in the shape of a 200, so each is absent and answers 404 rather than pretending.
*/
#include "server.h"
#include "rad_internal.h"
#include <nlohmann/json.hpp>
namespace rad {
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. */
json health_body(const std::string& model, bool stopping, int64_t in_flight, int64_t depth) {
json o;
o["status"] = stopping ? "stopping" : "ok";
o["model"] = model;
o["in_flight"] = in_flight;
o["queue_cap"] = depth;
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;
}
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;
}
bool get_bool_or(const json& b, const char* key, bool def) {
auto it = b.find(key);
return it != b.end() && it->is_boolean() ? it->get<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. */
HttpResponse Server::handle_version(const HttpRequest&) {
json o;
o["version"] = opt_.version;
o["engine"] = "radiance";
o["abi_version"] = (int)RAD_ABI_VERSION;
metrics_.observe_http(200);
return HttpResponse::json_body(200, json_dump(o));
}
/* ================================================================== /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". */
HttpResponse Server::handle_load(const HttpRequest&) {
json o;
o["server_load"] = in_flight_.load(std::memory_order_relaxed);
o["queue_cap"] = queue_depth_;
if (deps_.sched) {
const SchedMetrics m = deps_.sched->metrics();
o["running"] = m.running;
o["waiting"] = m.waiting;
}
metrics_.observe_http(200);
return HttpResponse::json_body(200, json_dump(o));
}
/* ================================================================== /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.
*
* `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. */
HttpResponse Server::handle_tokenize(const HttpRequest& req) {
if (!deps_.tok)
return error_response(err_not_implemented("the server has no tokenizer attached"));
json b;
ApiError err;
if (!parse_object(req.body, opt_.max_ctx, &b, &err)) return error_response(err);
const bool want_strs = get_bool_or(b, "return_token_strs", false);
std::vector<int32_t> toks;
auto msgs = b.find("messages");
auto prom = b.find("prompt");
if (msgs != b.end() && prom != b.end())
return error_response(err_bad("prompt", "send `prompt` or `messages`, not both"));
if (msgs != b.end()) {
if (!deps_.chat)
return error_response(err_not_implemented(
"tokenising `messages` requires a chat template; this model was not loaded with "
"one. Send `prompt` with the text you want tokenised"));
if (!msgs->is_array() || msgs->empty())
return error_response(err_bad("messages", "must be a non-empty array"));
ChatRenderOptions opt;
opt.add_generation_prompt = get_bool_or(b, "add_generation_prompt", true);
auto kw = b.find("chat_template_kwargs");
if (kw != b.end() && kw->is_object())
for (auto it = kw->begin(); it != kw->end(); ++it)
opt.template_kwargs[it.key()] = json_dump(it.value());
json tools = json::array();
auto t = b.find("tools");
if (t != b.end() && t->is_array()) tools = *t;
ChatRender render;
std::string why;
if (deps_.chat->apply(*msgs, tools, opt, &render, &why) < 0)
return error_response(err_bad("messages", why.empty()
? "the chat template could not render this request"
: why));
toks = deps_.tok->encode(render.prompt,
get_bool_or(b, "add_special_tokens", false),
/*parse_special=*/true);
} else {
if (prom == b.end() || !prom->is_string())
return error_response(err_bad("prompt", "must be a string, or send `messages`"));
toks = deps_.tok->encode(prom->get<std::string>(),
get_bool_or(b, "add_special_tokens", true),
/*parse_special=*/false);
}
json o;
o["count"] = (int64_t)toks.size();
o["max_model_len"] = opt_.max_ctx;
o["tokens"] = toks;
if (want_strs) {
json strs = json::array();
for (int32_t t : toks) strs.push_back(deps_.tok->piece(t));
o["token_strs"] = std::move(strs);
} else {
o["token_strs"] = nullptr;
}
metrics_.observe_http(200);
return HttpResponse::json_body(200, json_dump(o));
}
/* ================================================================== /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. */
HttpResponse Server::handle_detokenize(const HttpRequest& req) {
if (!deps_.tok)
return error_response(err_not_implemented("the server has no tokenizer attached"));
json b;
ApiError err;
if (!parse_object(req.body, opt_.max_ctx, &b, &err)) return error_response(err);
auto t = b.find("tokens");
if (t == b.end() || !t->is_array())
return error_response(err_bad("tokens", "must be an array of integers"));
std::vector<int32_t> toks;
toks.reserve(t->size());
for (const auto& v : *t) {
if (!v.is_number_integer())
return error_response(err_bad("tokens", "must be an array of integers"));
int32_t id = 0;
if (!token_id(v, &id))
return error_response(err_bad("tokens", "a token id must be in [0, 2147483647], "
"got " + v.dump()));
toks.push_back(id);
}
json o;
o["prompt"] = deps_.tok->decode(toks);
metrics_.observe_http(200);
return HttpResponse::json_body(200, json_dump(o));
}
/* ================================================================== /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. */
HttpResponse Server::handle_tokenizer_info(const HttpRequest&) {
if (!deps_.tok)
return error_response(err_not_implemented("the server has no tokenizer attached"));
const ITokenizer::VocabInfo v = deps_.tok->vocab_info();
json o;
o["tokenizer_class"] = v.kind;
o["vocab_size"] = v.n_tokens;
o["model_max_length"] = opt_.max_ctx;
o["bos_token_id"] = v.bos >= 0 ? json(v.bos) : json(nullptr);
o["eos_token_id"] = v.eos >= 0 ? json(v.eos) : json(nullptr);
o["eot_token_id"] = v.eot >= 0 ? json(v.eot) : json(nullptr);
o["unk_token_id"] = v.unk >= 0 ? json(v.unk) : json(nullptr);
o["pad_token_id"] = v.pad >= 0 ? json(v.pad) : json(nullptr);
o["add_bos_token"] = v.add_bos;
o["add_eos_token"] = v.add_eos;
o["chat_template"] = deps_.chat != nullptr;
o["supports_tools"] = deps_.chat && deps_.chat->supports_tools();
o["supports_reasoning"] = deps_.chat && deps_.chat->supports_reasoning();
metrics_.observe_http(200);
return HttpResponse::json_body(200, json_dump(o));
}
/* ================================================================== /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. */
HttpResponse Server::handle_server_info(const HttpRequest&) {
json srv;
srv["model"] = opt_.model_id;
srv["version"] = opt_.version;
srv["max_model_len"] = opt_.max_ctx;
srv["max_num_seqs"] = opt_.max_seqs;
srv["queue_cap"] = queue_depth_;
srv["default_max_tokens"] = opt_.default_max_tokens;
srv["max_n"] = opt_.max_n;
srv["uptime_s"] = unix_now() - started_at_;
srv["in_flight"] = in_flight_.load(std::memory_order_relaxed);
json caps;
caps["chat"] = deps_.chat != nullptr;
caps["tools"] = deps_.chat && deps_.chat->supports_tools();
caps["reasoning"] = deps_.chat && deps_.chat->supports_reasoning();
caps["grammar"] = deps_.grammar != nullptr;
caps["embedding"] = deps_.embed != nullptr;
caps["image"] = deps_.mm && deps_.mm->accepts(MediaKind::Image);
caps["video"] = deps_.mm && deps_.mm->accepts(MediaKind::Video);
caps["audio"] = deps_.mm && deps_.mm->accepts(MediaKind::Audio);
caps["logprobs"] = opt_.supports_logprobs;
json o;
o["server"] = std::move(srv);
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. */
if (!opt_.engine_info.empty()) {
json e = json::parse(opt_.engine_info, nullptr, false);
if (e.is_discarded() || !e.is_object())
RAD_WARN("server: engine_info is not a JSON object; /server_info omits it");
else
o["engine"] = std::move(e);
}
metrics_.observe_http(200);
return HttpResponse::json_body(200, json_dump(o));
}
/* ================================================================== /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. */
HttpResponse Server::handle_reset_prefix_cache(const HttpRequest&) {
if (!deps_.sched)
return error_response(err_not_implemented("the server has no engine attached"));
const int64_t n = deps_.sched->reset_prefix_cache();
if (n < 0)
return error_response(err_not_implemented(
"this engine has no prefix cache (started with --no-prefix-cache, or the model "
"declares no cacheable KV group)"));
json o;
o["entries_dropped"] = n;
metrics_.observe_http(200);
return HttpResponse::json_body(200, json_dump(o));
}
/* ================================================================== /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. */
HttpResponse Server::handle_health(const HttpRequest& req) { return handle_ping(req); }
HttpResponse Server::handle_ping(const HttpRequest&) {
const bool stopping = stopping_.load();
return HttpResponse::json_body(
stopping ? 503 : 200,
json_dump(health_body(opt_.model_id, stopping,
in_flight_.load(std::memory_order_relaxed), queue_depth_)));
}
} /* namespace server */
} /* namespace rad */
File diff suppressed because it is too large. Load diff
+475
View File
@@ -0,0 +1,475 @@
#include "http.h"
#include "rad_internal.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. */
#include "cpp-httplib/httplib.h"
#include <algorithm>
#include <atomic>
#include <cctype>
#include <chrono>
#include <condition_variable>
#include <list>
#include <mutex>
#include <system_error>
#include <thread>
#include <vector>
namespace rad {
namespace server {
bool CiLess::operator()(const std::string& a, const std::string& b) const {
return std::lexicographical_compare(
a.begin(), a.end(), b.begin(), b.end(),
[](unsigned char x, unsigned char y) { return std::tolower(x) < std::tolower(y); });
}
std::string HttpRequest::header(const std::string& k, const std::string& def) const {
auto it = headers.find(k);
return it == headers.end() ? def : it->second;
}
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;
auto q = query.find(k);
return q == query.end() ? def : q->second;
}
HttpResponse HttpResponse::json_body(int status, std::string body) {
HttpResponse r;
r.status = status;
r.body = std::move(body);
return r;
}
HttpResponse HttpResponse::text(int status, std::string body) {
HttpResponse r;
r.status = status;
r.content_type = "text/plain; charset=utf-8";
r.body = std::move(body);
return r;
}
/* ------------------------------------------------------------------ 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. */
std::string url_decode(const std::string& s, bool plus_is_space) {
std::string out;
out.reserve(s.size());
auto hex = [](char c) -> int {
if (c >= '0' && c <= '9') return c - '0';
if (c >= 'a' && c <= 'f') return c - 'a' + 10;
if (c >= 'A' && c <= 'F') return c - 'A' + 10;
return -1;
};
for (size_t i = 0; i < s.size(); ++i) {
if (s[i] == '%' && i + 2 < s.size()) {
int h = hex(s[i + 1]), l = hex(s[i + 2]);
if (h >= 0 && l >= 0) { out.push_back((char)(h * 16 + l)); i += 2; continue; }
}
out.push_back(plus_is_space && s[i] == '+' ? ' ' : s[i]);
}
return out;
}
void parse_target(const std::string& target, std::string* path,
std::map<std::string, std::string>* query) {
size_t q = target.find('?');
if (path) *path = url_decode(target.substr(0, q), /*plus_is_space=*/false);
if (!query || q == std::string::npos) return;
size_t i = q + 1;
while (i < target.size()) {
size_t amp = target.find('&', i);
if (amp == std::string::npos) amp = target.size();
std::string kv = target.substr(i, amp - i);
size_t eq = kv.find('=');
if (eq == std::string::npos) (*query)[url_decode(kv)] = "";
else (*query)[url_decode(kv.substr(0, eq))] = url_decode(kv.substr(eq + 1));
i = amp + 1;
}
}
/* ------------------------------------------------------------------ routing */
static std::vector<std::string> split_path(const std::string& p) {
std::vector<std::string> out;
size_t i = 0;
while (i < p.size()) {
while (i < p.size() && p[i] == '/') ++i;
size_t j = i;
while (j < p.size() && p[j] != '/') ++j;
if (j > i) out.push_back(p.substr(i, j - i));
i = j;
}
return out;
}
void Router::add(std::string method, std::string path, Handler h) {
routes_.push_back(Route{std::move(method), split_path(path), std::move(h)});
}
std::vector<std::string> Router::routes() const {
std::vector<std::string> out;
for (auto& r : routes_) {
std::string p;
for (auto& s : r.segs) { p += '/'; p += s; }
out.push_back(r.method + " " + (p.empty() ? "/" : p));
}
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. */
std::string esc;
for (char c : 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);
}
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;
for (const auto& r : routes_) {
if (r.segs.size() != segs.size()) continue;
std::map<std::string, std::string> caps;
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];
else if (r.segs[i] != segs[i]) { ok = false; break; }
}
if (!ok) continue;
path_matched = true;
if (r.method != req.method) continue;
req.params.insert(caps.begin(), caps.end());
return r.h(req);
}
if (path_matched)
return HttpResponse::json_body(
405, error_body("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));
}
HttpResponse Router::call(const std::string& method, const std::string& path,
const std::string& body) const {
HttpRequest r;
r.method = method;
parse_target(path, &r.path, &r.query);
r.body = body;
if (!body.empty()) r.headers["Content-Type"] = "application/json";
return dispatch(std::move(r));
}
/* ------------------------------------------------------------------ the worker pool */
/* A WORKER FOR EVERY CONNECTION, UP TO A BOUND, STARTED THE MOMENT THE 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
* 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. */
class ConnectionPool final : public httplib::TaskQueue {
public:
ConnectionPool(size_t keep, size_t most, size_t queued)
: keep_(keep), most_(std::max(most, keep)), queued_(queued) {
std::lock_guard<std::mutex> lk(m_);
for (size_t i = 0; i < keep_; ++i) start();
}
~ConnectionPool() override { shutdown(); }
bool enqueue(std::function<void()> fn) override {
{
std::lock_guard<std::mutex> lk(m_);
if (stop_) return false;
if (jobs_.size() >= free_) { /* no free worker is left for this job */
const bool started = threads_.size() < most_ && start();
if (!started && queued_ && jobs_.size() - free_ >= queued_) return false;
}
jobs_.push_back(std::move(fn));
}
cv_.notify_one();
return true;
}
/* Runs what is queued, then joins every worker. Idempotent: httplib calls it and then
* destroys the pool, which calls it again. */
void shutdown() override {
std::list<std::thread> live;
{
std::lock_guard<std::mutex> lk(m_);
stop_ = true;
live.swap(threads_);
}
cv_.notify_all();
for (auto& t : live) t.join();
std::lock_guard<std::mutex> lk(m_);
reap();
}
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. */
bool start() {
reap();
try {
threads_.emplace_back([this] { work(); });
} catch (const std::system_error& e) {
RAD_WARN("server: cannot start an HTTP worker (%s); the connection waits", e.what());
return false;
}
++free_;
return true;
}
/* With m_ held: join the workers that exited idle. They left m_ before exiting, so this
* waits only for their last instructions. */
void reap() {
for (auto& t : finished_) t.join();
finished_.clear();
}
void work() {
std::unique_lock<std::mutex> lk(m_);
for (;;) {
while (jobs_.empty() && !stop_) {
if (threads_.size() <= keep_) { cv_.wait(lk); continue; }
if (cv_.wait_for(lk, kIdleExit) == std::cv_status::timeout && jobs_.empty() &&
!stop_ && threads_.size() > keep_) {
/* Hand this thread's handle to finished_, for the next start() to join. */
for (auto it = threads_.begin(); it != threads_.end(); ++it) {
if (it->get_id() != std::this_thread::get_id()) continue;
finished_.push_back(std::move(*it));
threads_.erase(it);
break;
}
--free_;
return;
}
}
if (jobs_.empty()) { --free_; return; } /* stopping, and nothing is left to run */
std::function<void()> fn = std::move(jobs_.front());
jobs_.pop_front();
--free_;
lk.unlock();
fn();
lk.lock();
++free_;
}
}
const size_t keep_, most_, queued_;
std::mutex m_;
std::condition_variable cv_;
std::list<std::function<void()>> jobs_;
std::list<std::thread> threads_; /* every worker not yet exited */
std::vector<std::thread> finished_; /* exited idle, not yet joined */
size_t free_ = 0; /* workers not running a job */
bool stop_ = false;
};
/* ------------------------------------------------------------------ the httplib binding */
struct HttpTransport::Impl {
httplib::Server svr;
std::atomic<int> port{0};
};
HttpTransport::HttpTransport() : impl_(new Impl) {}
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. */
int HttpTransport::port() const {
return impl_ && impl_->svr.is_running() ? impl_->port.load() : 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);
}
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. */
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);
svr.set_payload_max_length(o.max_body_bytes);
int nt = o.n_threads > 0 ? o.n_threads : (int)std::thread::hardware_concurrency();
if (nt < 4) nt = 4;
const size_t most = (size_t)std::max<int64_t>(o.max_threads, nt);
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,
std::exception_ptr ep) {
std::string what = "unhandled exception in handler";
try { std::rethrow_exception(ep); }
catch (const std::exception& e) { what = e.what(); }
catch (...) {}
RAD_ERR("server: %s", what.c_str());
res.status = 500;
res.set_content(error_body("internal_server_error", what), "application/json");
});
const std::string api_key = o.api_key;
const bool cors = o.cors;
/* 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 {
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");
}
/* 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. */
const std::string& p = hreq.path;
if (!api_key.empty() && p != "/health" && p != "/ping" && p != "/" && p != "/dashboard") {
std::string got = hreq.get_header_value("Authorization");
const std::string want = "Bearer " + api_key;
if (got != want) {
hres.status = 401;
hres.set_content(error_body("authentication_error", "invalid api key"),
"application/json");
return false;
}
}
return true;
};
auto bridge = [&router](const httplib::Request& hreq, std::string body,
httplib::Response& hres) {
HttpRequest req;
req.method = hreq.method;
req.path = hreq.path;
req.body = std::move(body);
for (auto& h : hreq.headers) req.headers[h.first] = h.second;
for (auto& p : hreq.params) req.query[p.first] = p.second;
req.closed = [&hreq] { return hreq.is_connection_closed(); };
HttpResponse res = router.dispatch(std::move(req));
apply(res, hres);
if (!res.streaming()) {
hres.set_content(std::move(res.body), res.content_type);
if (res.on_close) res.on_close(true);
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. */
auto st = std::make_shared<HttpResponse>(std::move(res));
hres.set_chunked_content_provider(
st->content_type,
[st](size_t /*offset*/, httplib::DataSink& sink) -> bool {
std::string chunk;
bool more = st->next(chunk);
if (!chunk.empty()) {
if (!sink.write(chunk.data(), chunk.size())) return false; /* peer gone */
}
if (!more) sink.done();
return more;
},
[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 is not read at all -- no endpoint takes one, and httplib discards what a
* handler leaves unread -- so the handler sees an empty body and refuses it. */
svr.Post(path, [gate, bridge](const httplib::Request& q, httplib::Response& s,
const httplib::ContentReader& read) {
if (!gate(q, s)) return;
std::string body;
if (!q.is_multipart_form_data() &&
!read([&body](const char* p, size_t n) { body.append(p, n); return true; })) {
/* 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;
}
bridge(q, std::move(body), s);
});
}
svr.Options(".*", [cors](const httplib::Request&, httplib::Response& res) {
if (cors) {
res.set_header("Access-Control-Allow-Origin", "*");
res.set_header("Access-Control-Allow-Headers", "Content-Type, Authorization");
res.set_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
}
res.status = 204;
});
/* Bound once: asking for a named port and then for 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) {
RAD_ERR("server: cannot bind %s:%d", o.host.c_str(), o.port);
return RAD_E_IO;
}
impl_->port.store(port);
RAD_INFO("server: listening on http://%s:%d (%d threads, up to %zu)", o.host.c_str(), port,
nt, most);
return svr.listen_after_bind() ? RAD_OK : RAD_E_IO;
}
} /* namespace server */
} /* namespace rad */
+153
View File
@@ -0,0 +1,153 @@
/* 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.
*/
#pragma once
#include <cstdint>
#include <functional>
#include <map>
#include <memory>
#include <string>
#include <vector>
namespace rad {
namespace server {
/* Header names are case-insensitive per RFC 9110, and clients disagree about capitalisation of
* Authorization and Content-Type in particular. */
struct CiLess {
bool operator()(const std::string& a, const std::string& b) const;
};
struct HttpRequest {
std::string method = "GET";
std::string path; /* no query string */
std::string body;
std::map<std::string, std::string, CiLess> headers;
std::map<std::string, std::string> query;
std::map<std::string, std::string> params; /* from a ":name" route segment */
/* 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. */
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;
bool peer_gone() const { return closed && closed(); }
};
struct HttpResponse {
int status = 200;
std::string content_type = "application/json; charset=utf-8";
std::string body;
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. */
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. */
std::function<void(bool ok)> on_close;
bool streaming() const { return next != nullptr; }
void set_header(std::string k, std::string v) { headers.emplace_back(std::move(k), std::move(v)); }
static HttpResponse json_body(int status, std::string body);
static HttpResponse text(int status, std::string body);
};
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. */
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)); }
/* 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. */
HttpResponse dispatch(HttpRequest req) const;
/* Convenience for tests and for anything that speaks in whole request lines. */
HttpResponse call(const std::string& method, const std::string& path,
const std::string& body = "") const;
std::vector<std::string> routes() const;
private:
struct Route {
std::string method;
std::vector<std::string> segs; /* ":name" segments are wildcards */
Handler h;
};
std::vector<Route> routes_;
};
/* 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. */
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. */
struct TransportOptions {
std::string host = "0.0.0.0";
int port = 8000; /* 0 -> any free port; see HttpTransport::port */
int n_threads = 0; /* kept alive while idle. 0 -> hardware_concurrency,
* floor 4 */
int64_t max_threads = 0; /* what the pool may grow to. 0 -> n_threads */
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. */
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 */
size_t max_body_bytes = 512ull << 20; /* images arrive base64 inside the JSON body */
std::string api_key; /* "" disables the check */
bool cors = true;
};
class HttpTransport {
public:
HttpTransport();
~HttpTransport();
HttpTransport(const HttpTransport&) = delete;
HttpTransport& operator=(const HttpTransport&) = delete;
/* Blocks until stop(). Returns RAD_OK, or negative if the bind failed. */
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. */
int port() const;
private:
struct Impl;
std::unique_ptr<Impl> impl_;
};
} /* namespace server */
} /* namespace rad */
+518
View File
@@ -0,0 +1,518 @@
/* 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 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.
*/
#pragma once
#include "rad_core.h"
#include <nlohmann/json_fwd.hpp>
#include <map>
#include <memory>
#include <string>
#include <string_view>
#include <vector>
namespace rad {
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. */
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.
*/
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. */
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. */
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.
*
* 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. */
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;
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. */
int64_t prefix_evictions = 0;
int64_t prefix_ckpt_evictions = 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. */
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. */
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. */
int64_t draft_tokens = 0;
int64_t draft_accepted = 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. */
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] = {};
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. */
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. */
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 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. */
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.
*
* 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. */
struct SessionStat {
uint64_t id = 0;
std::string model; /* the container it was built against */
int64_t n_tokens = 0;
int64_t bytes = 0;
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, on_disk = 0; /* blocks */
/* LINEAR STATE, on a hybrid model, and counted apart from blocks because the two are not
* interchangeable. A session showing every block on disk and no snapshot anywhere 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. */
int64_t snapshots = 0;
int64_t snap_device = 0, snap_host = 0, snap_disk = 0;
int64_t snap_bytes = 0;
/* The prefix a return skips: the deepest snapshot's position (IdleTiers::SessionInfo). */
int64_t resume_tokens = 0;
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. */
struct SessionOccupancy {
int64_t host_bytes = 0, disk_bytes = 0;
int64_t host_cap_bytes = 0, disk_cap_bytes = 0;
};
struct RequestStat {
uint64_t id = 0;
std::string state; /* waiting | prefill | decode | preempted | done */
int64_t prompt_tokens = 0;
int64_t computed_tokens = 0;
int64_t cached_tokens = 0;
int64_t output_tokens = 0;
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. */
int64_t kv_tokens = 0;
int32_t n_draft = 0;
int32_t slot = -1;
double age_s = 0;
double ttft_s = -1; /* negative until the first token */
double decode_tps = 0;
};
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
* scheduler whose steps cannot interleave with submission. */
virtual void submit_all(std::vector<Request>& rs, std::vector<uint64_t>* ids) {
ids->clear();
for (Request& r : rs) ids->push_back(submit(std::move(r)));
}
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. */
virtual void reap(uint64_t /*id*/) {}
/* CAN THIS REQUEST'S SAMPLING PARAMETERS BE SERVED AT ALL?
*
* 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. */
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. */
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. */
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. */
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". */
struct TierCounters {
/* `to_host` and `to_disk` count COPIES; `dropped` is VRAM given up after one and
* `host_freed` host slots given up after the disk copy. A conversation that returns before
* anything wants its VRAM is copied and never dropped. `host_drops` is entries lost with
* no disk tier to hold them. */
int64_t to_host = 0, dropped = 0, to_disk = 0, promoted = 0;
int64_t host_freed = 0, host_drops = 0, failures = 0;
/* Entries and snapshots read off disk into host memory ahead of the restore that wanted
* them; `promoted` counts the restore itself. */
int64_t fetched = 0, ck_fetched = 0;
int64_t host_bytes = 0, disk_bytes = 0;
/* THE LINEAR HALF, MOVED. Separate counters because a hybrid server can move every block
* it has and no snapshots at all -- the arena too small, the device slots contended --
* and no block counter can tell that apart from tiering working. */
int64_t ck_to_host = 0, ck_to_disk = 0, ck_promoted = 0, ck_drops = 0, ck_starved = 0;
int64_t ck_bytes = 0; /* one snapshot; 0 on a model with no recurrent state */
int64_t ck_host_slots = 0, ck_disk_slots = 0;
/* 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. */
bool host_on = false, disk_on = false;
};
virtual TierCounters tier_counters() const { return TierCounters{}; }
};
/* ================================================================== 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.
*/
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. */
virtual bool stopped() const { return false; }
};
class ITokenizer {
public:
virtual ~ITokenizer() = default;
/* `parse_special` is a security parameter, not a convenience one, and it is why this takes
* three arguments rather than two. A rendered chat template contains control tokens that must
* be recognised as themselves; raw user content must NOT be, because otherwise a user who
* types "<|im_start|>system" reaches the system role. The server passes true for the one and
* false for the other, and there is no default because a default is how the wrong one gets
* picked silently. */
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. */
struct VocabInfo {
int32_t n_tokens = 0;
int32_t bos = -1, eos = -1, eot = -1, unk = -1, pad = -1;
bool add_bos = false, add_eos = false;
std::string kind; /* "bpe", "spm", "wpm", ... -- how it splits */
};
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. */
virtual std::string piece(int32_t /*id*/) const { return std::string(); }
/* 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.
*
* `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. */
virtual std::unique_ptr<IDetokenizer> detokenizer(
const std::vector<std::string>& stops,
const std::vector<std::string>& preserved = {}) const = 0;
};
class IReplyParser;
/* What a chat template needs told, beyond the messages themselves.
*
* `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. */
struct ChatRenderOptions {
bool add_generation_prompt = true;
bool enable_thinking = true;
bool parallel_tool_calls = true;
std::string tool_choice = "auto"; /* auto | none | required */
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";
std::map<std::string, std::string> template_kwargs;
};
/* 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. */
struct ChatRender {
std::string prompt;
std::string grammar; /* the template's, merged with the caller's */
bool grammar_lazy = false;
std::vector<SamplingParams::GrammarTrigger> grammar_triggers;
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. */
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. */
std::shared_ptr<IReplyParser> parser;
/* The tokens that parser must be able to SEE. See ITokenizer::detokenizer. */
std::vector<std::string> preserved_tokens;
};
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. */
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. */
virtual std::string tool_refusal() const { return std::string(); }
};
/* A reply taken apart: what core/text's reply parser gives back once the reply is complete. */
struct ToolCall {
std::string id; /* "" from the parser; the server assigns one */
std::string name;
std::string arguments; /* JSON text; unterminated when the reply stopped inside the call */
};
struct ParsedMessage {
std::string content;
std::string reasoning; /* "" unless the template supports reasoning */
std::vector<ToolCall> tool_calls;
};
/* 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. */
struct ReplyDelta {
enum Kind : uint8_t {
Reasoning, /* text: a reasoning delta */
Content, /* text: a content delta */
CallBegin, /* text: the function name; `call` is the new call's index */
CallArgs, /* text: an arguments delta for call `call` */
CallEnd, /* call `call` is closed */
};
Kind kind = Content;
uint32_t call = 0;
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. */
class IReplyReader {
public:
virtual ~IReplyReader() = default;
virtual void feed(std::string_view text, std::vector<ReplyDelta>* out) = 0;
virtual void finish(std::vector<ReplyDelta>* out) = 0;
/* The whole reply, once finish() has run. */
virtual ParsedMessage message() 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. */
class IReplyParser {
public:
virtual ~IReplyParser() = default;
virtual std::unique_ptr<IReplyReader> open() const = 0;
};
/* JSON-schema -> GBNF (spec §13). Errors are values: RAD_OK, or negative with `err` naming the
* part of the schema that could not be compiled. */
class IGrammarCompiler {
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. */
virtual int compile(const std::string& gbnf, std::shared_ptr<const GbnfProgram>* out,
std::string& err) const = 0;
};
/* ================================================================== optional backends */
/* /v1/embeddings. Absent, the endpoint is 501 naming that this model was not loaded with an
* embedding head -- not an empty 200. */
class IEmbedder {
public:
virtual ~IEmbedder() = default;
virtual int embed(const std::vector<int32_t>& tokens, std::vector<float>& out) = 0;
virtual int64_t dim() const = 0;
};
/* Multimodal preprocessing (spec §11). The server pulls the bytes out of a content part; the
* processor behind this decodes them, resizes and cuts them for the encoder, and says which
* tokens take the part's place in the prompt -- placeholder runs, the markers around them and,
* 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. */
#define RAD_MEDIA_MARKER "<__media__>"
class IMultimodal {
public:
virtual ~IMultimodal() = default;
virtual bool accepts(MediaKind k) const = 0;
/* Decode and process one part. `bytes` is the decoded file, not a URL: the server never
* fetches a remote URL on a request's behalf. On success `*out` carries the patches and the
* 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,
std::shared_ptr<mm::Item>* out, std::string* why) = 0;
};
} /* namespace server */
} /* namespace rad */
+178
View File
@@ -0,0 +1,178 @@
#include "json_partial.h"
namespace rad {
namespace server {
namespace {
struct Scanner {
std::string_view s;
size_t i = 0;
void ws() {
while (i < s.size() && (s[i] == ' ' || s[i] == '\t' || s[i] == '\n' || s[i] == '\r')) ++i;
}
bool eof() const { return i >= s.size(); }
char peek() const { return s[i]; }
bool lit(std::string_view w) {
if (s.size() - i < w.size()) return false;
if (s.compare(i, w.size(), w) != 0) return false;
i += w.size();
return true;
}
bool str() {
if (eof() || s[i] != '"') return false;
++i;
while (!eof()) {
char c = s[i];
if (c == '\\') {
if (i + 1 >= s.size()) return false;
char e = s[i + 1];
if (e == 'u') {
if (i + 5 >= s.size()) return false;
i += 6;
} else {
i += 2;
}
continue;
}
if (c == '"') { ++i; return true; }
++i;
}
return false; /* unterminated */
}
bool num() {
size_t start = i;
if (!eof() && s[i] == '-') ++i;
size_t d0 = i;
while (!eof() && s[i] >= '0' && s[i] <= '9') ++i;
if (i == d0) { i = start; return false; }
if (!eof() && s[i] == '.') {
++i;
size_t d1 = i;
while (!eof() && s[i] >= '0' && s[i] <= '9') ++i;
if (i == d1) { i = start; return false; }
}
if (!eof() && (s[i] == 'e' || s[i] == 'E')) {
++i;
if (!eof() && (s[i] == '+' || s[i] == '-')) ++i;
size_t d2 = i;
while (!eof() && s[i] >= '0' && s[i] <= '9') ++i;
if (i == d2) { i = start; return false; }
}
return true;
}
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. */
if (depth > 256) return false;
ws();
if (eof()) return false;
char c = peek();
if (c == '"') return str();
if (c == '{') return obj(depth + 1);
if (c == '[') return arr(depth + 1);
if (c == 't') return lit("true");
if (c == 'f') return lit("false");
if (c == 'n') return lit("null");
return num();
}
bool obj(int depth) {
++i; /* '{' */
ws();
if (eof()) return false;
if (peek() == '}') { ++i; return true; }
for (;;) {
ws();
if (!str()) return false;
ws();
if (eof() || peek() != ':') return false;
++i;
if (!value(depth)) return false;
ws();
if (eof()) return false;
if (peek() == ',') { ++i; continue; }
if (peek() == '}') { ++i; return true; }
return false;
}
}
bool arr(int depth) {
++i; /* '[' */
ws();
if (eof()) return false;
if (peek() == ']') { ++i; return true; }
for (;;) {
if (!value(depth)) return false;
ws();
if (eof()) return false;
if (peek() == ',') { ++i; continue; }
if (peek() == ']') { ++i; return true; }
return false;
}
}
};
} /* namespace */
bool json_complete(std::string_view s) {
Scanner sc{s};
if (!sc.value(0)) return false;
sc.ws();
return sc.eof();
}
size_t utf8_trunc(std::string_view s) {
size_t n = s.size();
if (n == 0) return 0;
/* Walk back over at most three continuation bytes to find the lead byte, then decide whether
* the sequence it starts is complete. */
size_t k = n;
size_t back = 0;
while (k > 0 && back < 4) {
unsigned char c = (unsigned char)s[k - 1];
if ((c & 0xC0) == 0x80) { --k; ++back; continue; }
size_t need = 1;
if ((c & 0x80) == 0x00) need = 1;
else if ((c & 0xE0) == 0xC0) need = 2;
else if ((c & 0xF0) == 0xE0) need = 3;
else if ((c & 0xF8) == 0xF0) need = 4;
else return n; /* not a lead byte: not our truncation to fix */
size_t have = n - (k - 1);
return have >= need ? n : k - 1;
}
return n;
}
size_t json_stable_prefix(std::string_view s) {
size_t n = utf8_trunc(s);
if (n == 0) return 0;
/* Back out of an unfinished escape. Count the run of backslashes immediately before the cut:
* an odd run means the last one is an opening escape whose payload has not arrived. */
size_t bs = 0;
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. */
for (size_t k = 0; k <= 4 && n >= k + 2; ++k) {
if (s[n - 1 - k] != 'u') continue;
if (s[n - 2 - k] != '\\') break;
size_t bs2 = 0, j = n - 2 - k;
while (j > 0 && s[j - 1] == '\\') { ++bs2; --j; }
if (bs2 % 2 == 1) break; /* the backslash was itself escaped */
if (k < 4) return n - 2 - k; /* fewer than four hex digits have arrived */
break;
}
return n;
}
} /* namespace server */
} /* namespace rad */
+40
View File
@@ -0,0 +1,40 @@
/* core/server/json_partial.h -- what may be sent, and what may be called a tool call.
*
* Two questions about text that is still arriving, and they are different questions:
*
* 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.
*
* This is a scanner, not a parser: it allocates nothing and builds no DOM.
*/
#pragma once
#include <cstddef>
#include <string_view>
namespace rad {
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. */
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. */
size_t json_stable_prefix(std::string_view s);
} /* namespace server */
} /* namespace rad */
+372
View File
@@ -0,0 +1,372 @@
#include "liveview.h"
#include "iface.h"
#include "rad_internal.h"
#include <chrono>
#include <cmath>
#include <cstring>
#include <sys/ioctl.h>
#include <unistd.h>
namespace rad {
namespace server {
static_assert((int)kLiveTiers == kTierCount,
"liveview.h restates rad::kTierCount; the tier enum grew and the snapshot did not");
void snapshot_from(const SchedMetrics& m, LiveSnapshot* out) {
out->waiting = m.waiting;
out->running = m.running;
out->preempted = m.preempted;
out->kv_util = m.kv_util;
out->prefix_hit_rate = m.prefix_hit_rate;
out->prefix_evictions = m.prefix_evictions;
out->prefill_tps = m.prefill_tps;
out->decode_tps = m.decode_tps;
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. */
out->step = m.steps;
}
/* ------------------------------------------------------------------ small formatting */
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. */
const char* tier_colour(uint8_t t) {
switch (t) {
case 0: return "\033[32m"; /* VRAM */
case 1: return "\033[33m"; /* host, pinned */
case 2: return "\033[35m"; /* host, pageable */
case 4: return "\033[36m"; /* the container's mapping */
default: return "\033[31m"; /* SSD */
}
}
char tier_glyph(uint8_t t) {
switch (t) {
case 0: return '#';
case 1: return '+';
case 2: return '-';
default: return '.';
}
}
std::string bar(double frac, int width, bool colour) {
if (frac < 0) frac = 0;
if (frac > 1) frac = 1;
int fill = (int)std::lround(frac * width);
std::string s;
if (colour) s += frac > 0.9 ? "\033[31m" : (frac > 0.7 ? "\033[33m" : "\033[32m");
s.append((size_t)fill, '=');
if (colour) s += "\033[0m";
s.append((size_t)(width - fill), ' ');
return s;
}
std::string gib(int64_t bytes) {
char b[48];
snprintf(b, sizeof b, "%.1fG", (double)bytes / (1024.0 * 1024.0 * 1024.0));
return b;
}
std::string f2(double v) {
char b[32];
snprintf(b, sizeof b, "%.2f", 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. */
std::string tps(double v) {
char b[32];
snprintf(b, sizeof b, v >= 99.95 ? "%.0f" : "%.1f", v);
return b;
}
/* ---- 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%.
*
* 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 digits of 0 <= a < 999.5; the thresholds are where the rounded value gains a digit. */
std::string sig3(double a) {
char b[32];
snprintf(b, sizeof b, "%.*f", a >= 99.95 ? 0 : a >= 9.995 ? 1 : 2, a);
return b;
}
/* 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. */
std::string ladder(double v, double base, const char* const* units, int n_units, bool exact,
const char* sep) {
if (!std::isfinite(v)) return "-";
const char* u = units[0];
std::string n;
if (v == 0.0) {
n = "0";
} else {
double a = std::fabs(v);
int i = 0;
while (a >= 999.5 && i < n_units - 1) { a /= base; ++i; }
u = units[i];
n = (i == 0 && exact) ? std::to_string(std::llround(a)) : sig3(a);
if (v < 0) n = "-" + n;
}
return *u ? n + sep + u : n;
}
const char* const kIec[] = { "B", "KiB", "MiB", "GiB", "TiB", "PiB" };
const char* const kPfx[] = { "", "k", "M", "G", "T", "P" };
std::string size_iec(int64_t bytes) { return ladder((double)bytes, 1024.0, kIec, 6, true, " "); }
/* Used and total of one quantity, the unit said once when it is the same unit. */
std::string size_of(int64_t used, int64_t total) {
std::string a = size_iec(used), b = size_iec(total);
const size_t ia = a.rfind(' '), ib = b.rfind(' ');
if (ia != std::string::npos && ib != std::string::npos && a.substr(ia) == b.substr(ib))
return a.substr(0, ia) + " / " + b;
return a + " / " + b;
}
/* A continuous quantity -- watts, degrees -- to three figures and an SI prefix. Not tokens a
* second: tps() prints those 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. */
std::string grouped(int64_t n) {
std::string d = std::to_string(n < 0 ? -n : n), o;
for (size_t i = 0; i < d.size(); ++i) {
if (i && d.size() > 4 && (d.size() - i) % 3 == 0) o += " ";
o += d[i];
}
return n < 0 ? "-" + o : o;
}
/* A share of one 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];
snprintf(b, sizeof b, "%.1f", 100.0 * f);
if (f > 0 && strcmp(b, "0.0") == 0) return "<0.1%";
if (f < 1 && strcmp(b, "100.0") == 0) return ">99.9%";
return std::string(b) + "%";
}
} /* namespace */
/* ------------------------------------------------------------------ construction */
LiveView::LiveView(Source src, int interval_ms, FILE* out)
: src_(std::move(src)), interval_ms_(interval_ms), out_(out ? out : stdout) {
tty_ = isatty(fileno(out_)) != 0;
if (tty_) {
struct winsize ws;
if (ioctl(fileno(out_), TIOCGWINSZ, &ws) == 0 && ws.ws_col > 20) cols_ = ws.ws_col;
}
}
LiveView::~LiveView() { stop(); }
void LiveView::start() {
if (running_.exchange(true)) return;
thread_ = std::thread([this] { loop(); });
}
void LiveView::stop() {
if (!running_.exchange(false)) return;
if (thread_.joinable()) thread_.join();
if (tty_) {
/* Leave the terminal as we found it: cursor visible, no leftover attributes. */
fputs("\033[?25h\033[0m\n", out_);
fflush(out_);
}
}
void LiveView::loop() {
if (tty_) fputs("\033[?25l", out_); /* hide the cursor; the redraw is what moves it */
LiveSnapshot s;
while (running_.load()) {
s = LiveSnapshot{};
if (src_) src_(s);
std::string frame = tty_ ? render_screen(s) : render_line(s);
fwrite(frame.data(), 1, frame.size(), out_);
fflush(out_);
std::this_thread::sleep_for(std::chrono::milliseconds(interval_ms_));
}
}
/* ------------------------------------------------------------------ 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.
*/
std::string LiveView::render_line(const LiveSnapshot& s) const {
std::string o = "live";
o += " step=" + std::to_string(s.step);
o += " run=" + std::to_string(s.running);
o += " wait=" + std::to_string(s.waiting);
if (s.preempted) o += " preempt=" + std::to_string(s.preempted);
o += " kv=" + f2(s.kv_util);
o += " prefix_hit=" + f2(s.prefix_hit_rate);
if (s.prefix_evictions) o += " prefix_evict=" + std::to_string(s.prefix_evictions);
o += " prefill_tps=" + tps(s.prefill_tps);
o += " decode_tps=" + tps(s.decode_tps);
if (s.draft_acceptance > 0.0) o += " draft_accept=" + f2(s.draft_acceptance);
for (const auto& c : s.cards) {
o += " gpu" + std::to_string(c.index) + "=";
o += f2(c.util);
o += "/vram:" + gib(c.vram_used) + "of" + gib(c.vram_total);
if (c.power_w > 0) { o += "/pw:" + f2(c.power_w); }
if (c.temp_c > 0) { o += "/t:" + f2(c.temp_c); }
}
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]);
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. */
if (s.experts.routed > 0)
o += " hit=" + f2(100.0 * (double)s.experts.routed_resident /
(double)s.experts.routed) + "%";
if (s.experts.promotions || s.experts.demotions) {
o += " promo=" + std::to_string(s.experts.promotions);
o += " demo=" + std::to_string(s.experts.demotions);
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. */
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);
o += " h2d=" + std::to_string(s.link.h2d_bytes);
o += " d2h=" + std::to_string(s.link.d2h_bytes);
if (s.link.stream_bytes) o += " stream=" + std::to_string(s.link.stream_bytes);
if (s.link.ssd_bytes) o += " ssd=" + std::to_string(s.link.ssd_bytes);
}
o += "\n";
return o;
}
/* ------------------------------------------------------------------ the terminal form */
std::string LiveView::render_screen(const LiveSnapshot& s) const {
const int W = cols_;
std::string o;
o.reserve(4096);
o += "\033[H\033[2J"; /* home, clear */
o += "\033[1mradiance\033[0m ";
o += s.model.empty() ? "-" : s.model;
o += " step " + grouped(s.step);
o += " requests " + grouped(s.total_requests) + "\n\n";
for (const auto& c : s.cards) {
char head[96];
snprintf(head, sizeof head, " gpu%d %-14.14s ", c.index, c.name.c_str());
o += head;
o += "util [" + bar(c.util, std::max(10, W / 4), true) + "] ";
o += share(c.util) + " ";
double vf = c.vram_total > 0 ? (double)c.vram_used / (double)c.vram_total : 0.0;
o += "vram [" + bar(vf, std::max(10, W / 6), true) + "] ";
o += size_of(c.vram_used, c.vram_total);
if (c.power_w > 0) o += " " + num_si(c.power_w) + " W";
if (c.temp_c > 0) o += " " + num_si(c.temp_c) + " \u00b0C";
o += "\n";
}
if (!s.cards.empty()) o += "\n";
o += " running " + std::to_string(s.running) +
" waiting " + std::to_string(s.waiting);
if (s.preempted) o += " preempted " + std::to_string(s.preempted);
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. */
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";
if (s.draft_acceptance > 0.0)
o += " draft accept " + share(s.draft_acceptance);
o += "\n";
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. */
char tl[192];
for (int t = 0; t < 4; ++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",
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());
o += tl;
}
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. */
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) {
char lb[16];
snprintf(lb, sizeof lb, " %3d ", l);
o += lb;
for (int e = 0; e < s.experts.n_experts; e += stride) {
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]);
}
o += tier_colour(worst);
o += tier_glyph(worst);
}
o += "\033[0m\n";
}
if (s.experts.promotions || s.experts.demotions) {
o += " moves +" + grouped(s.experts.promotions) +
" -" + grouped(s.experts.demotions) + "\n";
}
}
return o;
}
} /* namespace server */
} /* namespace rad */
+192
View File
@@ -0,0 +1,192 @@
/* 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.
*
* 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.
*
* 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.
*/
#pragma once
#include <atomic>
#include <cstdint>
#include <cstdio>
#include <functional>
#include <string>
#include <thread>
#include <vector>
namespace rad {
namespace server {
struct SchedMetrics;
struct CardStat {
int index = 0;
std::string name;
double util = 0.0; /* 0..1 */
int64_t vram_used = 0;
int64_t vram_total = 0;
double power_w = 0.0; /* 0 = not sampled */
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. */
enum { kLiveTiers = 5 };
/* THE EXPERT PLANE, and what the placement engine has been doing to 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.
*
* 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.
*/
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. */
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
* 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. */
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. */
int64_t promotions = 0, demotions = 0;
/* Is the churn PROGRESS or THRASH? Same move count, opposite meanings -- 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. */
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. */
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
* copied onto the card, and pooled units a buffer had no room for. */
int64_t stage_layers = 0, staged_units = 0, staged_bytes = 0, stage_overflow = 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. */
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.
*
* 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".
*
* `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.
*/
struct LinkStat {
bool present = false; /* false when nothing measured any of it */
int world = 1;
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. */
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. */
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. */
struct PassStat {
bool present = false;
int64_t played = 0, recorded = 0, audited = 0;
int64_t issued_unkeyed = 0, issued_refused = 0, issued_first = 0;
int64_t dispatched = 0, unordered = 0;
};
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. */
int64_t waiting = 0, running = 0, preempted = 0;
double kv_util = 0.0, prefix_hit_rate = 0.0;
int64_t prefix_evictions = 0;
double prefill_tps = 0.0, decode_tps = 0.0, draft_acceptance = 0.0;
int64_t total_requests = 0, preemptions = 0;
std::vector<CardStat> cards;
ExpertPlane experts;
LinkStat link;
PassStat passes;
};
void snapshot_from(const SchedMetrics& m, LiveSnapshot* out);
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. */
LiveView(Source src, int interval_ms = 250, FILE* out = nullptr);
~LiveView();
void start();
void stop();
/* Both renderers are public because they are the testable part: 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;
private:
void loop();
Source src_;
int interval_ms_;
FILE* out_;
bool tty_ = false;
int cols_ = 100;
std::atomic<bool> running_{false};
std::thread thread_;
};
} /* namespace server */
} /* namespace rad */
+409
View File
@@ -0,0 +1,409 @@
#include "metrics.h"
#include "iface.h"
#include <algorithm>
#include <cmath>
#include <cstdio>
namespace rad {
namespace server {
/* ------------------------------------------------------------------ primitives */
Histogram::Histogram(std::vector<double> bounds) : bounds_(std::move(bounds)) {
cnt_.reset(new std::atomic<uint64_t>[bounds_.size()]);
for (size_t i = 0; i < bounds_.size(); ++i) cnt_[i].store(0);
}
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);
double cur = sum_.load(std::memory_order_relaxed);
while (!sum_.compare_exchange_weak(cur, cur + v, std::memory_order_relaxed)) {}
}
std::vector<double> buckets_ttft() {
return {0.001, 0.005, 0.01, 0.02, 0.04, 0.06, 0.08, 0.1, 0.25, 0.5, 0.75,
1.0, 2.5, 5.0, 7.5, 10.0, 20.0, 40.0, 80.0, 160.0, 640.0, 2560.0};
}
std::vector<double> buckets_tpot() {
return {0.01, 0.025, 0.05, 0.075, 0.1, 0.15, 0.2, 0.3, 0.4, 0.5,
0.75, 1.0, 2.5, 5.0, 7.5, 10.0, 20.0, 40.0, 80.0};
}
std::vector<double> buckets_latency() {
return {0.3, 0.5, 0.8, 1.0, 1.5, 2.0, 2.5, 5.0, 10.0, 15.0, 20.0,
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. */
std::vector<double> buckets_1_2_5(int64_t max_value) {
std::vector<double> out;
if (max_value < 1) max_value = 1;
const int mant[3] = {1, 2, 5};
for (int exp = 0; exp < 12; ++exp) {
for (int m = 0; m < 3; ++m) {
double v = (double)mant[m] * std::pow(10.0, exp);
if (v > (double)max_value) return out;
out.push_back(v);
}
}
return out;
}
/* ------------------------------------------------------------------ registry */
static std::string esc_label(const std::string& s) {
std::string o;
for (char c : s) {
if (c == '\\' || c == '"') { o.push_back('\\'); o.push_back(c); }
else if (c == '\n') o += "\\n";
else o.push_back(c);
}
return o;
}
Metrics::Metrics(std::string model_name, int64_t max_model_len)
: model_(std::move(model_name)),
h_ttft_(buckets_ttft()),
h_tpot_(buckets_tpot()),
h_e2e_(buckets_latency()),
h_decode_(buckets_latency()),
h_prompt_tokens_(buckets_1_2_5(max_model_len > 0 ? max_model_len : 32768)),
h_generation_tokens_(buckets_1_2_5(max_model_len > 0 ? max_model_len : 32768)),
h_params_n_({1, 2, 5, 10, 20}),
h_params_max_tokens_(buckets_1_2_5(max_model_len > 0 ? max_model_len : 32768)) {
labels_ = "{model_name=\"" + esc_label(model_) + "\",engine=\"0\"}";
}
static const char* reason_str(SuccessReason r) {
switch (r) {
case SuccessReason::Stop: return "stop";
case SuccessReason::Length: return "length";
case SuccessReason::ToolCalls: return "tool_calls";
case SuccessReason::Abort: return "abort";
case SuccessReason::Error: return "error";
default: return "stop";
}
}
void Metrics::observe_request(int64_t n_prompt, int64_t n_generated,
double ttft_s, double tpot_s, double e2e_s, double decode_s,
int n_choices, int64_t max_tokens, SuccessReason r) {
c_prompt_tokens_.inc((double)n_prompt);
c_generation_tokens_.inc((double)n_generated);
c_success_[(size_t)r].inc();
h_prompt_tokens_.observe((double)n_prompt);
h_generation_tokens_.observe((double)n_generated);
h_params_n_.observe((double)n_choices);
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. */
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);
}
void Metrics::observe_rejected() { c_rejected_.inc(); }
void Metrics::observe_disconnect() { c_disconnect_.inc(); }
void Metrics::observe_overflow() { c_overflow_.inc(); }
void Metrics::observe_http(int status) {
if (status >= 500) c_http_5xx_.inc();
else if (status >= 400) c_http_4xx_.inc();
else c_http_2xx_.inc();
}
void Metrics::sample(const SchedMetrics& m) {
std::lock_guard<std::mutex> lk(sample_mu_);
g_running_.set((double)m.running);
g_waiting_.set((double)m.waiting);
g_preempted_.set((double)m.preempted);
g_kv_util_.set(m.kv_util);
g_prefix_hit_.set(m.prefix_hit_rate);
g_prefill_tps_.set(m.prefill_tps);
g_decode_tps_.set(m.decode_tps);
g_draft_accept_.set(m.draft_acceptance);
const int seen = std::max(0, std::min(m.draft_depth_seen, (int)MAX_DRAFT_POS));
for (int j = 0; j < seen; ++j) {
const int64_t r = m.draft_pos_reached[j];
g_draft_pos_reached_[j].set((double)r);
g_draft_pos_[j].set(r ? (double)m.draft_pos_accepted[j] / (double)r : 0.0);
}
/* Published after the gauges it bounds, so a concurrent render never lists a position whose
* gauge has not been written yet. */
draft_pos_seen_.store(seen, 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_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_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()));
g_linear_hit_.set(m.linear_hit_rate);
}
/* ------------------------------------------------------------------ exposition */
namespace {
/* Prometheus wants a bare decimal; %g would emit "1e+06" for a bucket bound, which parses, and
* "inf" for +Inf, which does not. 17 significant digits round-trips a double exactly. */
std::string num(double v) {
if (std::isinf(v)) return v > 0 ? "+Inf" : "-Inf";
if (v == (double)(long long)v && std::fabs(v) < 1e15) {
char b[32];
snprintf(b, sizeof b, "%lld", (long long)v);
return b;
}
char b[64];
snprintf(b, sizeof b, "%.17g", v);
return b;
}
struct Writer {
std::string out;
void help(const char* name, const char* doc, const char* type) {
out += "# HELP "; out += name; out += ' '; out += doc; out += '\n';
out += "# TYPE "; out += name; out += ' '; out += type; out += '\n';
}
void gauge(const char* name, const char* doc, const std::string& labels, double v) {
help(name, doc, "gauge");
out += name; out += labels; out += ' '; out += num(v); out += '\n';
}
void counter(const char* name, const char* doc, const std::string& labels, double v) {
/* The _total suffix is part of the exposed family name for a counter, which is what the
* Python client does and therefore what the dashboards match on. */
help(name, doc, "counter");
out += name; out += labels; out += ' '; out += num(v); out += '\n';
}
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) {
out += name; out += "_bucket";
out += labels.substr(0, labels.size() - 1); /* drop the closing brace */
out += ",le=\""; out += num(h.bounds()[i]); out += "\"} ";
out += num((double)h.bucket(i)); out += '\n';
}
out += name; out += "_bucket";
out += labels.substr(0, labels.size() - 1);
out += ",le=\"+Inf\"} ";
out += num((double)h.count()); 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';
}
};
} /* namespace */
std::string Metrics::render() const {
Writer w;
w.out.reserve(8192);
const std::string& L = labels_;
/* ---------------- vLLM-compatible: gauges ---------------- */
w.gauge("vllm:num_requests_running",
"Number of requests currently running on GPU.", L, g_running_.get());
w.gauge("vllm:num_requests_waiting",
"Number of requests waiting to be processed.", L, g_waiting_.get());
w.gauge("vllm:gpu_cache_usage_perc",
"GPU KV-cache usage. 1 means 100 percent usage.", L, g_kv_util_.get());
w.gauge("vllm:kv_cache_usage_perc",
"KV-cache usage. 1 means 100 percent usage.", L, g_kv_util_.get());
w.gauge("vllm:gpu_prefix_cache_hit_rate",
"GPU prefix cache block hit rate.", L, g_prefix_hit_.get());
/* ---------------- vLLM-compatible: counters ---------------- */
w.counter("vllm:prompt_tokens_total",
"Number of prefill tokens processed.", L, c_prompt_tokens_.get());
w.counter("vllm:generation_tokens_total",
"Number of generation tokens processed.", L, c_generation_tokens_.get());
w.counter("vllm:num_preemptions_total",
"Cumulative number of preemptions from the engine.", L, c_preemptions_.get());
w.help("vllm:request_success_total",
"Count of successfully processed requests.", "counter");
for (size_t i = 0; i < (size_t)SuccessReason::N_; ++i) {
w.out += "vllm:request_success_total";
w.out += L.substr(0, L.size() - 1);
w.out += ",finished_reason=\"";
w.out += reason_str((SuccessReason)i);
w.out += "\"} ";
w.out += num(c_success_[i].get());
w.out += '\n';
}
/* ---------------- vLLM-compatible: histograms ---------------- */
w.hist("vllm:time_to_first_token_seconds",
"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. */
w.hist("vllm:inter_token_latency_seconds",
"Histogram of inter-token latency in seconds.", L, h_tpot_);
w.hist("vllm:e2e_request_latency_seconds",
"Histogram of end to end request latency in seconds.", L, h_e2e_);
w.hist("vllm:request_decode_time_seconds",
"Histogram of time spent in the decode phase, in seconds.", L, h_decode_);
w.hist("vllm:request_prompt_tokens",
"Number of prefill tokens processed.", L, h_prompt_tokens_);
w.hist("vllm:request_generation_tokens",
"Number of generation tokens processed.", L, h_generation_tokens_);
w.hist("vllm:request_params_n",
"Histogram of the n request parameter.", L, h_params_n_);
w.hist("vllm:request_params_max_tokens",
"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. */
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",
"Decode throughput over the scheduler's recent window.", L, g_decode_tps_.get());
w.counter("radiance:engine_steps_total",
"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. */
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",
"Scheduler steps carrying both a prefill chunk and a decode row.",
L, c_steps_mixed_.get());
w.counter("radiance:engine_steps_decode_total",
"Scheduler steps carrying only decode rows.", L, c_steps_decode_.get());
w.counter("radiance:engine_steps_ahead_total",
"Steps whose forward pass was issued behind the step before, ahead of its commit.",
L, c_steps_ahead_.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. */
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. */
w.counter("radiance:prefill_tokens_total",
"Prompt tokens the engine has computed, exact.", L, c_prefill_tokens_.get());
w.counter("radiance:decode_tokens_total",
"Tokens the engine has generated, exact, counted when the step commits rather "
"than when the request finishes.", L, c_decode_tokens_.get());
w.counter("radiance:draft_tokens_total",
"Speculative tokens proposed.", L, c_draft_tokens_.get());
w.counter("radiance:draft_accepted_total",
"Speculative tokens accepted; the pair the acceptance ratio is computed from.",
L, c_draft_accepted_.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. */
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());
w.counter("radiance:attn_cached_tokens_total",
"Prompt tokens served from the paged attention prefix cache.", L, c_attn_cached_.get());
w.counter("radiance:linear_cached_tokens_total",
"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. */
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",
"Prefix-cache linear-state checkpoints evicted.", L, c_prefix_ckpt_evict_.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. */
const int seen = draft_pos_seen_.load(std::memory_order_acquire);
if (seen > 0) {
const std::string base = L.substr(0, L.size() - 1);
w.help("radiance:draft_position_acceptance_ratio",
"Conditional acceptance at each draft position, given every earlier one was taken.",
"gauge");
for (int j = 0; j < seen; ++j)
w.out += "radiance:draft_position_acceptance_ratio" + base + ",position=\"" +
std::to_string(j) + "\"} " + num(g_draft_pos_[j].get()) + '\n';
w.help("radiance:draft_position_reached_total",
"Verifies that evaluated each draft position.", "counter");
for (int j = 0; j < seen; ++j)
w.out += "radiance:draft_position_reached_total" + base + ",position=\"" +
std::to_string(j) + "\"} " + num(g_draft_pos_reached_[j].get()) + '\n';
}
w.gauge("radiance:num_requests_preempted",
"Requests currently preempted and awaiting recompute.", L, g_preempted_.get());
w.gauge("radiance:http_queue_depth",
"Requests admitted by the HTTP layer and not yet finished.", L, queue_depth_.get());
w.counter("radiance:http_admission_rejected_total",
"Requests refused with 429 because the admission queue was full.",
L, c_rejected_.get());
w.counter("radiance:client_disconnect_total",
"Streams cancelled because the client went away.", L, c_disconnect_.get());
w.counter("radiance:stream_overflow_total",
"Requests failed because the HTTP reader could not drain the sink.",
L, c_overflow_.get());
w.help("radiance:http_responses_total", "HTTP responses by status class.", "counter");
w.out += "radiance:http_responses_total" + L.substr(0, L.size() - 1) + ",class=\"2xx\"} "
+ num(c_http_2xx_.get()) + '\n';
w.out += "radiance:http_responses_total" + L.substr(0, L.size() - 1) + ",class=\"4xx\"} "
+ num(c_http_4xx_.get()) + '\n';
w.out += "radiance:http_responses_total" + L.substr(0, L.size() - 1) + ",class=\"5xx\"} "
+ num(c_http_5xx_.get()) + '\n';
return w.out;
}
} /* namespace server */
} /* namespace rad */
+158
View File
@@ -0,0 +1,158 @@
/* 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.
*
* 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.
*
* 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.
*/
#pragma once
#include <atomic>
#include <cstdint>
#include <memory>
#include <mutex>
#include <string>
#include <vector>
namespace rad {
namespace server {
struct SchedMetrics;
/* ------------------------------------------------------------------ primitives */
class Counter {
public:
void inc(double v = 1.0) {
double cur = v_.load(std::memory_order_relaxed);
while (!v_.compare_exchange_weak(cur, cur + v, std::memory_order_relaxed)) {}
}
double get() const { return v_.load(std::memory_order_relaxed); }
private:
std::atomic<double> v_{0.0};
};
class Gauge {
public:
void set(double v) { v_.store(v, std::memory_order_relaxed); }
double get() const { return v_.load(std::memory_order_relaxed); }
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. */
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); }
double sum() const { return sum_.load(std::memory_order_relaxed); }
private:
std::vector<double> bounds_;
std::unique_ptr<std::atomic<uint64_t>[]> cnt_;
std::atomic<uint64_t> n_{0};
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. */
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 */
std::vector<double> buckets_1_2_5(int64_t max_value); /* token-count histograms */
/* ------------------------------------------------------------------ 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. */
enum class SuccessReason { Stop = 0, Length, ToolCalls, Abort, Error, N_ };
class Metrics {
public:
Metrics(std::string model_name, int64_t max_model_len);
/* --- observed at the HTTP boundary, per finished request --- */
void observe_request(int64_t n_prompt, int64_t n_generated,
double ttft_s, double tpot_s, double e2e_s, double decode_s,
int n_choices, int64_t max_tokens, SuccessReason r);
void observe_rejected(); /* 429: the admission queue was full */
void observe_disconnect(); /* the client went away mid-stream */
void observe_overflow(); /* the sink ring filled: the HTTP side could not keep up */
void observe_http(int status);
void set_queue_depth(int64_t d) { queue_depth_.set((double)d); }
/* --- pulled from the scheduler at scrape time --- */
void sample(const SchedMetrics& m);
/* Prometheus text exposition format, version 0.0.4. */
std::string render() const;
private:
std::string model_;
std::string labels_; /* {model_name="...",engine="0"} */
Gauge g_running_, g_waiting_, g_kv_util_, g_prefix_hit_;
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. */
enum { MAX_DRAFT_POS = 64 };
Gauge g_draft_pos_[MAX_DRAFT_POS];
Gauge g_draft_pos_reached_[MAX_DRAFT_POS];
std::atomic<int> draft_pos_seen_{0};
/* 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. */
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. */
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. */
Counter c_steps_prefill_, c_steps_mixed_, c_steps_decode_, c_rows_unspec_, c_steps_ahead_;
/* 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_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. */
Counter c_prefill_tokens_, c_decode_tokens_, c_draft_tokens_, c_draft_accepted_;
Counter c_attn_cached_, c_linear_cached_, c_checkpoints_;
Counter c_prefix_evict_, c_prefix_ckpt_evict_;
Gauge g_linear_hit_;
Counter c_success_[(size_t)SuccessReason::N_];
Counter c_rejected_, c_disconnect_, c_overflow_;
Counter c_http_2xx_, c_http_4xx_, c_http_5xx_;
Histogram h_ttft_, h_tpot_, h_e2e_, h_decode_;
Histogram h_prompt_tokens_, h_generation_tokens_, h_params_n_, h_params_max_tokens_;
};
} /* namespace server */
} /* namespace rad */
+1807
View File
File diff suppressed because it is too large. Load diff
+265
View File
@@ -0,0 +1,265 @@
/* core/server/oai.h -- the OpenAI schema, in and out.
*
* Two rules shape everything here.
*
* 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 we do not support is a 400 that names it. Not a silent ignore. A client that sends
* `logit_bias` and gets a 200 has been told its bias was applied, and the resulting bug report
* ("the model ignores my bias") is unanswerable from the server side. The cost of strictness is
* that a client sending a field we have not heard of gets a 400 rather than a shrug; the
* allowlist below is where the genuinely inert OpenAI metadata fields (`user`, `store`, ...)
* are named, so that cost falls only on fields that actually mean something.
*/
#pragma once
#include "iface.h"
#include "rad_core.h"
#include "sink.h"
#include <cstdint>
#include <memory>
#include <string>
#include <vector>
namespace rad {
namespace server {
/* ================================================================== errors */
struct ApiError {
int status = 400;
std::string type = "invalid_request_error";
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 */
std::string dump() const; /* the OpenAI error envelope, as a JSON string */
};
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);
/* ================================================================== a parsed request */
enum class Endpoint { Chat, Completion, Embedding };
struct PromptInput {
std::vector<int32_t> tokens;
std::string text; /* the rendered prompt; needed for `echo` and for the logs */
/* The media parts, processed and placed; null for a text prompt (Request::media). */
std::shared_ptr<mm::PromptMedia> media;
};
struct OaiRequest {
Endpoint endpoint = Endpoint::Chat;
std::string model;
std::string id; /* "chatcmpl-..." / "cmpl-..." */
int64_t created = 0; /* unix seconds */
bool stream = false;
bool include_usage = false; /* stream_options.include_usage */
int n = 1;
SamplingParams sp;
int32_t max_tokens = 0;
std::vector<std::string> stop;
/* Generate past end-of-text, to max_tokens. See Request::ignore_eos. */
bool ignore_eos = false;
int priority = 0;
std::vector<PromptInput> prompts; /* /v1/completions accepts a batch; chat has exactly one */
bool echo = false;
int n_logprobs = 0; /* 0 = off */
bool want_logprobs = false;
bool tools_present = false;
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. */
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. */
std::vector<std::string> preserved_tokens;
/* /v1/embeddings */
bool base64_embeddings = false;
int n_choices() const { return (int)prompts.size() * n; }
};
/* What the server needs to know about itself to validate a request. */
struct OaiLimits {
std::string model_id = "radiance";
int64_t max_ctx = 0; /* 0 = unknown, no length check */
int64_t default_max_tokens = 512;
int max_n = 8;
bool allow_image = false;
bool allow_video = false;
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. */
std::string default_reasoning_effort;
/* WHAT A REQUEST THAT SENDS NO SAMPLER FIELDS IS SERVED WITH, field by field.
*
* The struct's own defaults are an untruncated sampler -- temperature 1, top_k off, top_p 1
* -- 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.
*
* 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. */
SamplingParams default_sampling;
};
struct OaiDeps {
ITokenizer* tok = nullptr;
IChatTemplate* chat = nullptr;
IGrammarCompiler* grammar = nullptr;
IMultimodal* mm = nullptr;
};
/* 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);
int parse_completion_request(const std::string& body, const OaiDeps& d, const OaiLimits& lim,
OaiRequest* out, ApiError* err);
/* Embeddings: fills `out->prompts` with one entry per input. */
int parse_embeddings_request(const std::string& body, const OaiDeps& d, const OaiLimits& lim,
OaiRequest* out, ApiError* err);
/* ================================================================== responses */
struct LogprobEntry {
int32_t token = 0;
std::string text;
float logprob = 0.0f;
};
struct ChoiceOut {
int index = 0;
std::string text; /* raw generated text */
ParsedMessage msg; /* chat: content / reasoning / tool_calls after parsing */
Finish finish = Finish::None;
std::vector<LogprobEntry> logprobs;
};
struct UsageOut {
int64_t prompt = 0;
int64_t completion = 0;
int64_t cached = 0;
};
std::string chat_completion_body(const OaiRequest& r, const std::vector<ChoiceOut>& choices,
const UsageOut& u);
std::string text_completion_body(const OaiRequest& r, const std::vector<ChoiceOut>& choices,
const UsageOut& u);
std::string embeddings_body(const OaiRequest& r, const std::vector<std::vector<float>>& vecs,
const UsageOut& u);
std::string models_body(const std::string& model_id, int64_t created);
/* 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. */
std::string text_usage_chunk(const OaiRequest& r, const UsageOut& u);
std::string chat_usage_chunk(const OaiRequest& r, const UsageOut& u);
/* ================================================================== 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.
*/
class ChatDeltaStream {
public:
ChatDeltaStream(const OaiRequest& r, int index, const IReplyParser* parser);
/* The `role: assistant` opener OpenAI clients expect before any content. */
std::string first_chunk();
/* Feed the text generated since the last push; returns zero or more SSE `data:` lines.
* `is_final` says the generation is over, which resolves whatever the reader was holding. */
std::string push(std::string_view appended, bool is_final);
/* The terminating chunk carrying finish_reason. The usage chunk is the stream's, not the
* choice's: chat_usage_chunk. */
std::string final_chunk(Finish f);
/* What the whole generation parsed to -- 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;
private:
std::string chunk(json delta, const char* finish_reason);
std::string emit(const std::vector<ReplyDelta>& ev);
std::unique_ptr<IReplyReader> reader_;
std::string id_, model_;
int64_t created_;
int index_;
bool finished_ = false;
ParsedMessage last_;
std::vector<ReplyDelta> ev_;
};
/* 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. */
extern const char* const SSE_DONE;
std::string sse_event(const std::string& json_text);
std::string sse_error(const ApiError& e);
/* ================================================================== small shared helpers */
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. */
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. */
json parse_json_bounded(const std::string& body, int64_t max_ctx, bool* over, bool* deep);
int64_t json_value_budget(int64_t max_ctx);
constexpr int kJsonMaxDepth = 1024;
std::string random_id(const char* prefix);
int64_t unix_now();
} /* namespace server */
} /* namespace rad */
+806
View File
@@ -0,0 +1,806 @@
#include "server.h"
#include "json_partial.h"
#include "rad_internal.h"
#include <nlohmann/json.hpp>
#include <algorithm>
#include <chrono>
#include <thread>
namespace rad {
namespace server {
/* ------------------------------------------------------------------ per-choice state */
struct Server::Generation {
std::shared_ptr<Sink> sink;
std::unique_ptr<IDetokenizer> detok;
std::unique_ptr<ChatDeltaStream> delta; /* chat streaming only */
uint64_t id = 0;
int index = 0;
int prompt_index = 0;
std::string text;
std::vector<LogprobEntry> logprobs;
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 */
size_t stop_cut = std::string::npos;
size_t emitted = 0; /* streaming: text already handed to the delta stream */
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;
};
/* ------------------------------------------------------------------ construction */
Server::Server(const Deps& d, const ServerOptions& o)
: deps_(d), opt_(o),
metrics_(o.model_id, o.max_ctx > 0 ? o.max_ctx : 32768) {
lim_.model_id = opt_.model_id;
lim_.max_ctx = opt_.max_ctx;
lim_.default_max_tokens = opt_.default_max_tokens;
lim_.max_n = opt_.max_n;
lim_.allow_image = opt_.allow_image;
lim_.allow_video = opt_.allow_video;
lim_.allow_audio = opt_.allow_audio;
lim_.supports_logprobs = opt_.supports_logprobs;
lim_.default_reasoning_effort = opt_.default_reasoning_effort;
lim_.default_sampling = opt_.default_sampling;
odeps_.tok = deps_.tok;
odeps_.chat = deps_.chat;
odeps_.grammar = deps_.grammar;
odeps_.mm = deps_.mm;
queue_depth_ = opt_.queue_depth > 0 ? opt_.queue_depth : opt_.max_seqs * 8;
started_at_ = unix_now();
register_routes();
}
Server::~Server() { stop(); }
/* Sinks the engine may still be writing into must not be freed. `Request::sink` is a raw pointer
* the scheduler holds for the life of the request, so the only safe moment to release one is
* after the scheduler has reported it terminal. At shutdown we wait a bounded time for that and,
* if it never comes, we leak the remainder on purpose and say so.
*
* A deliberate leak of a few KiB at process exit is the cheap failure. Freeing under a running
* step is the expensive one: it corrupts whatever the allocator hands out next, and it surfaces
* as garbage in an unrelated request several steps later, which is precisely the class of bug
* spec §17 exists to keep out of this engine. */
void Server::drain_graveyard(int timeout_ms) {
const int slice = 5;
for (int waited = 0; waited <= timeout_ms; waited += slice) {
sweep_abandoned();
{
std::lock_guard<std::mutex> lk(grave_m_);
if (grave_.empty()) return;
}
std::this_thread::sleep_for(std::chrono::milliseconds(slice));
}
std::lock_guard<std::mutex> lk(grave_m_);
if (grave_.empty()) return;
RAD_ERR("server: %zu cancelled requests are still held by the scheduler after %d ms. "
"Stop the scheduler before destroying the server. Leaking their sinks rather than "
"freeing memory a running step may still write to.",
grave_.size(), timeout_ms);
/* Hand the remainder to storage that outlives the process's teardown of this object. */
static std::vector<std::vector<std::shared_ptr<Sink>>>* leaked =
new std::vector<std::vector<std::shared_ptr<Sink>>>();
leaked->push_back(std::move(grave_));
grave_.clear();
}
/* WHAT IS SERVED. One table, and /server_info answers with it rather than with a copy -- a list
* kept beside this one is a list that goes stale on the next route added.
*
* Method spellings follow vLLM's, including the ones that look wrong: /tokenize and /detokenize
* are POST because their input is a body, /reset_prefix_cache is POST because it changes state,
* and /ping answers both GET and POST because different load balancers send different ones and
* neither is worth a 405 on a health probe. */
void Server::register_routes() {
router_.post("/v1/chat/completions", [this](const HttpRequest& q) { return handle_chat(q); });
router_.post("/v1/completions", [this](const HttpRequest& q) { return handle_completion(q); });
router_.post("/v1/embeddings", [this](const HttpRequest& q) { return handle_embeddings(q); });
router_.get ("/v1/models", [this](const HttpRequest& q) { return handle_models(q); });
router_.get ("/v1/models/:id", [this](const HttpRequest& q) { return handle_models(q); });
router_.get ("/metrics", [this](const HttpRequest& q) { return handle_metrics(q); });
router_.get ("/health", [this](const HttpRequest& q) { return handle_health(q); });
router_.get ("/ping", [this](const HttpRequest& q) { return handle_ping(q); });
router_.post("/ping", [this](const HttpRequest& q) { return handle_ping(q); });
router_.get ("/load", [this](const HttpRequest& q) { return handle_load(q); });
router_.get ("/version", [this](const HttpRequest& q) { return handle_version(q); });
router_.get ("/server_info", [this](const HttpRequest& q) { return handle_server_info(q); });
router_.post("/tokenize", [this](const HttpRequest& q) { return handle_tokenize(q); });
router_.post("/detokenize", [this](const HttpRequest& q) { return handle_detokenize(q); });
router_.get ("/get_tokenizer_info", [this](const HttpRequest& q) { return handle_tokenizer_info(q); });
router_.post("/reset_prefix_cache", [this](const HttpRequest& q) { return handle_reset_prefix_cache(q); });
/* The dashboard. `/` rather than only `/dashboard` because a person who has the host and port
* of a running engine types exactly that, and answering it with a 404 is answering the
* question "is this thing alive" with "no". */
router_.get ("/", [this](const HttpRequest& q) { return handle_dashboard(q); });
router_.get ("/dashboard", [this](const HttpRequest& q) { return handle_dashboard(q); });
router_.get ("/stats", [this](const HttpRequest& q) { return handle_stats(q); });
router_.get ("/graph", [this](const HttpRequest& q) { return handle_graph(q); });
router_.get ("/sessions", [this](const HttpRequest& q) { return handle_sessions(q); });
}
/* WORKERS FOR EVERYTHING ADMISSION CAN LET IN, AND A RESERVE BESIDE THEM.
*
* A generation holds its connection's worker for as long as it runs -- a stream writes from it, a
* blocking request waits on its sink in it -- so a pool no larger than the admission ceiling runs
* out of workers before admission refuses anyone. The 429 can then never happen, and every
* connection after that waits in the pool's queue behind generations that may run for minutes,
* /health included. So the pool may grow to the ceiling plus a reserve no admitted generation can
* occupy: that is what keeps a probe, the dashboard, a request about to be told 429 and a
* client's idle keep-alive connections answerable while every admitted request is running. The
* same number bounds the connections that may wait once even the reserve is busy. */
static const int64_t kSpareWorkers = 64;
int Server::run() {
TransportOptions t;
t.host = opt_.host;
t.port = opt_.port;
t.n_threads = opt_.n_threads;
t.max_threads = queue_depth_ + kSpareWorkers;
t.max_queued = kSpareWorkers;
t.api_key = opt_.api_key;
t.cors = opt_.cors;
return transport_.serve(router_, t);
}
void Server::stop() {
stopping_.store(true);
transport_.stop();
drain_graveyard(2000);
}
/* ------------------------------------------------------------------ admission */
bool Server::admit(int64_t n) {
int64_t cur = in_flight_.fetch_add(n, std::memory_order_acq_rel) + n;
if (cur > queue_depth_) {
in_flight_.fetch_sub(n, std::memory_order_acq_rel);
return false;
}
metrics_.set_queue_depth(cur);
return true;
}
void Server::release(int64_t n) {
int64_t cur = in_flight_.fetch_sub(n, std::memory_order_acq_rel) - n;
metrics_.set_queue_depth(cur);
}
void Server::sweep_abandoned() {
std::lock_guard<std::mutex> lk(grave_m_);
size_t before = grave_.size();
grave_.erase(std::remove_if(grave_.begin(), grave_.end(),
[this](const std::shared_ptr<Sink>& s) {
if (!s->done()) return false;
deps_.sched->reap(s->id);
return true;
}),
grave_.end());
if (grave_.size() > 256 && grave_.size() >= before)
RAD_WARN("server: %zu cancelled requests the scheduler has not reported terminal; "
"IScheduler::cancel must finish them, not just unschedule them",
grave_.size());
}
/* ------------------------------------------------------------------ errors */
HttpResponse Server::error_response(const ApiError& e) {
metrics_.observe_http(e.status);
HttpResponse r = HttpResponse::json_body(e.status, e.dump());
if (e.status == 429) r.set_header("Retry-After", std::to_string(opt_.retry_after_s));
return r;
}
/* ------------------------------------------------------------------ submission */
int Server::submit_all(const OaiRequest& r, std::vector<Generation>* gens, ApiError* err) {
const int n_choices = r.n_choices();
gens->reserve((size_t)n_choices);
/* THE SAMPLER GETS A SAY BEFORE ANYTHING IS QUEUED. A stage that did not resolve is not a
* declare failure -- it becomes one when a request asks for it. Refusing here makes that a
* 400 naming the parameter, instead of an admitted request that the step loop cancels three
* steps in with a dead stream at the client.
*
* Once, not per choice: `n` varies only the seed, and no check here reads it. */
{
std::string why;
if (deps_.sched->admit(r.sp, &why) < 0) {
*err = err_unsupported("sampling", why.empty()
? "these sampling parameters cannot be served" : why);
return RAD_E_INVAL;
}
}
int idx = 0;
std::vector<Request> rqs;
rqs.reserve(r.prompts.size() * (size_t)r.n);
const size_t first = gens->size();
for (size_t p = 0; p < r.prompts.size(); ++p) {
for (int k = 0; k < r.n; ++k, ++idx) {
Generation g;
g.index = idx;
g.prompt_index = (int)p;
g.sink = std::make_shared<Sink>();
g.sink->set_has_logprobs(opt_.supports_logprobs);
g.detok = deps_.tok->detokenizer(r.stop, r.preserved_tokens);
if (!g.detok) {
*err = err_not_implemented("the tokenizer did not supply an incremental decoder");
return RAD_E_UNSUPPORTED;
}
Request rq;
rq.prompt = r.prompts[p].tokens;
rq.sp = r.sp;
/* n identical seeds would give n identical completions, which is not what `n` means.
* Offsetting is enough: the sampler's stream is seeded, not chained. */
rq.sp.seed = r.sp.seed + (uint64_t)k;
rq.max_tokens = r.max_tokens;
rq.stop = r.stop;
rq.ignore_eos = r.ignore_eos;
rq.priority = r.priority;
rq.stream = r.stream;
rq.media = r.prompts[p].media;
rq.sink = g.sink.get();
rqs.push_back(std::move(rq));
gens->push_back(std::move(g));
}
}
std::vector<uint64_t> ids;
deps_.sched->submit_all(rqs, &ids);
for (size_t i = 0; i < ids.size(); ++i) {
Generation& g = (*gens)[first + i];
g.id = ids[i];
g.sink->id = g.id;
}
return RAD_OK;
}
void Server::cancel_all(std::vector<Generation>& gens, bool count_disconnect) {
for (auto& g : gens) {
if (g.sink->done()) continue;
g.sink->request_cancel();
deps_.sched->cancel(g.id);
}
if (count_disconnect) metrics_.observe_disconnect();
}
/* Every exit from a request goes through here exactly once. A generation the engine has finished
* is reaped -- that is the server telling the scheduler it may drop the Request, which it cannot
* know on its own because we are the ones holding the sink. One the engine has not finished moves
* to the graveyard, and is reaped by the sweep when it does. */
void Server::retire(std::vector<Generation>& gens) {
std::vector<std::shared_ptr<Sink>> pending;
for (auto& g : gens) {
if (g.retired) continue;
g.retired = true;
if (g.sink->done()) deps_.sched->reap(g.id);
else pending.push_back(g.sink);
}
if (pending.empty()) return;
std::lock_guard<std::mutex> lk(grave_m_);
for (auto& s : pending) grave_.push_back(std::move(s));
}
/* ------------------------------------------------------------------ draining */
bool Server::all_done(const std::vector<Generation>& gens) const {
for (const auto& g : gens) if (!g.closed) return false;
return true;
}
bool Server::pump(std::vector<Generation>& gens, const OaiRequest& r) {
bool progress = false;
SinkToken buf[128];
size_t maxstop = 0;
for (const auto& s : r.stop) maxstop = std::max(maxstop, s.size());
for (auto& g : gens) {
if (g.closed) continue;
size_t n;
while ((n = g.sink->read(buf, 128)) > 0) {
progress = true;
for (size_t i = 0; i < n; ++i) {
std::string piece = g.detok->push(buf[i].token);
if (!piece.empty()) g.text += piece;
if (r.want_logprobs)
g.logprobs.push_back(LogprobEntry{buf[i].token, piece, buf[i].logprob});
}
}
/* The decoder may have swallowed the stop string itself, in which case our own scan below
* can never find it -- it is searching text the stop string was already removed from. */
if (maxstop && !g.closed && g.stop_cut == std::string::npos && g.detok->stopped()) {
g.stop_cut = g.text.size();
g.finish = Finish::StopString;
g.closed = true;
progress = true;
g.sink->request_cancel();
deps_.sched->cancel(g.id);
continue;
}
/* Stop strings. The scheduler is given Request::stop and may stop first, but a stop
* string straddles token boundaries and only the detokenised text can be searched, so the
* authoritative cut is made here. Scanning restarts (maxstop-1) bytes behind the previous
* end so a match spanning two drains is still found. */
if (maxstop && g.stop_cut == std::string::npos && !g.text.empty()) {
size_t start = g.scanned >= maxstop ? g.scanned - maxstop + 1 : 0;
for (const auto& s : r.stop) {
if (s.empty()) continue;
size_t at = g.text.find(s, start);
if (at != std::string::npos && (g.stop_cut == std::string::npos || at < g.stop_cut))
g.stop_cut = at;
}
g.scanned = g.text.size();
if (g.stop_cut != std::string::npos) {
g.text.resize(g.stop_cut);
g.finish = Finish::StopString;
g.closed = true;
progress = true;
/* The client will never see another token of this choice, so the blocks it holds
* are dead weight the moment we decide that (spec §14). */
g.sink->request_cancel();
deps_.sched->cancel(g.id);
continue;
}
}
if (g.sink->done()) {
std::string tail = g.detok->flush();
if (!tail.empty()) { g.text += tail; progress = true; }
g.finish = g.sink->finish_reason();
if (g.sink->overflowed()) metrics_.observe_overflow();
g.closed = true;
progress = true;
}
}
return progress;
}
/* ------------------------------------------------------------------ metrics bookkeeping */
static SuccessReason to_reason(Finish f) {
switch (f) {
case Finish::Length: return SuccessReason::Length;
case Finish::ToolCalls: return SuccessReason::ToolCalls;
case Finish::Cancelled: return SuccessReason::Abort;
case Finish::Error: return SuccessReason::Error;
default: return SuccessReason::Stop;
}
}
void Server::record(const OaiRequest& r, const std::vector<Generation>& gens, Finish overall) {
int64_t n_prompt = 0;
for (const auto& p : r.prompts) n_prompt += (int64_t)p.tokens.size();
int64_t n_gen = 0;
double ttft = -1.0, tpot = -1.0, decode = -1.0, e2e = 0.0;
for (const auto& g : gens) {
int64_t produced = g.sink->n_produced();
n_gen += produced;
e2e = std::max(e2e, (double)g.sink->age_ns() * 1e-9);
int64_t tf = g.sink->t_first_token_ns(), tl = g.sink->t_last_token_ns();
if (tf >= 0) {
double t = (double)tf * 1e-9;
ttft = ttft < 0 ? t : std::min(ttft, t);
if (produced > 1 && tl > tf) {
double d = (double)(tl - tf) * 1e-9;
decode = decode < 0 ? d : std::max(decode, d);
double per = d / (double)(produced - 1);
tpot = tpot < 0 ? per : std::max(tpot, per);
}
}
}
metrics_.observe_request(n_prompt, n_gen, ttft, tpot, e2e, decode,
r.n, r.max_tokens, to_reason(overall));
}
/* ------------------------------------------------------------------ non-streaming */
HttpResponse Server::blocking_completion(const HttpRequest& req, OaiRequest& r) {
std::vector<Generation> gens;
ApiError err;
if (submit_all(r, &gens, &err) < 0) {
retire(gens);
release(r.n_choices());
return error_response(err);
}
for (;;) {
pump(gens, r);
if (all_done(gens)) break;
/* A client that hangs up before the answer is ready is a cancellation, not something to
* finish computing for nobody. */
if (req.peer_gone()) {
cancel_all(gens, true);
retire(gens);
release(r.n_choices());
metrics_.observe_http(499);
HttpResponse res = HttpResponse::text(499, "client closed request\n");
return res;
}
if (stopping_.load()) {
cancel_all(gens, false);
retire(gens);
release(r.n_choices());
return error_response(err_overloaded("the server is shutting down"));
}
/* Wait on whichever choice is still running. Bounded, so the peer check above runs. */
for (auto& g : gens) if (!g.closed) { g.sink->wait(); break; }
}
Finish overall = Finish::Stop;
UsageOut usage;
for (const auto& p : r.prompts) usage.prompt += (int64_t)p.tokens.size();
std::vector<ChoiceOut> choices;
choices.reserve(gens.size());
for (auto& g : gens) {
usage.completion += g.sink->n_produced();
if (g.prompt_index * r.n == g.index) usage.cached += g.sink->n_cached();
ChoiceOut c;
c.index = g.index;
c.finish = g.finish;
c.logprobs = std::move(g.logprobs);
if (r.endpoint == Endpoint::Chat) {
/* Parse whenever there is a parser, not only when tools were sent: the same parser
* separates the reasoning block from the answer, and a request with no tools still
* wants `reasoning_content` split out rather than glued to the front of the reply.
* It is the same reader the streaming path feeds a piece at a time, fed the whole
* reply at once, so the two agree by construction. With no tools in the request the
* parser reads no calls and the tool bookkeeping below finds none. */
if (r.reply_parser) {
std::unique_ptr<IReplyReader> rd = r.reply_parser->open();
rd->feed(g.text, nullptr);
rd->finish(nullptr);
c.msg = rd->message();
/* Only claim a tool call when the arguments actually parse (json_partial.h). */
bool complete = r.parse_tools && !c.msg.tool_calls.empty();
for (const auto& tc : c.msg.tool_calls)
if (tc.name.empty() || !json_complete(tc.arguments)) complete = false;
if (complete && (c.finish == Finish::Stop || c.finish == Finish::StopString))
c.finish = Finish::ToolCalls;
else if (!c.msg.tool_calls.empty() && !complete) {
/* A half-finished call is content, not a call. The client gets what the model
* actually produced instead of a tool invocation with truncated arguments. */
c.msg.tool_calls.clear();
c.msg.content = g.text;
}
} else {
c.msg.content = g.text;
}
for (auto& tc : c.msg.tool_calls) if (tc.id.empty()) tc.id = random_id("call_");
} else {
c.text = r.echo ? r.prompts[g.prompt_index].text + g.text : g.text;
}
if (c.finish == Finish::Error || c.finish == Finish::Cancelled) overall = c.finish;
choices.push_back(std::move(c));
}
/* An engine-side failure is not a 200 with an empty answer. */
for (auto& g : gens) {
if (g.finish == Finish::Error) {
int st = g.sink->status();
retire(gens);
release(r.n_choices());
record(r, gens, Finish::Error);
ApiError e;
e.status = 500;
e.type = "internal_server_error";
e.message = std::string("the engine failed this request: ") + rad_strerror(st);
return error_response(e);
}
}
record(r, gens, overall);
retire(gens);
release(r.n_choices());
std::string body = r.endpoint == Endpoint::Chat
? chat_completion_body(r, choices, usage)
: text_completion_body(r, choices, usage);
metrics_.observe_http(200);
return HttpResponse::json_body(200, std::move(body));
}
/* ------------------------------------------------------------------ streaming */
static std::string text_chunk(const OaiRequest& r, int index, const std::string& delta,
const char* finish_reason) {
nlohmann::ordered_json ch;
ch["text"] = delta;
ch["index"] = index;
ch["logprobs"] = nullptr;
if (finish_reason) ch["finish_reason"] = finish_reason; else ch["finish_reason"] = nullptr;
nlohmann::ordered_json o;
o["id"] = r.id;
o["object"] = "text_completion";
o["created"] = r.created;
o["model"] = r.model;
o["choices"] = nlohmann::ordered_json::array({ch});
return sse_event(o.dump());
}
HttpResponse Server::streaming_completion(const HttpRequest& req, OaiRequest& r) {
auto st = std::make_shared<StreamState>();
st->r = r;
st->peer_closed = req.closed;
ApiError err;
if (submit_all(st->r, &st->gens, &err) < 0) {
retire(st->gens);
release(r.n_choices());
return error_response(err);
}
if (st->r.endpoint == Endpoint::Chat)
for (auto& g : st->gens)
g.delta.reset(new ChatDeltaStream(st->r, g.index, st->r.reply_parser.get()));
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");
/* nginx buffers proxied responses by default, which turns a token stream into one large
* delivery at the end. This header is the documented opt-out and costs nothing elsewhere. */
res.set_header("X-Accel-Buffering", "no");
Server* self = this;
res.next = [self, st](std::string& out) -> bool {
out.clear();
if (st->done_sent) return false;
if (!st->opened) {
st->opened = true;
if (st->r.endpoint == Endpoint::Chat) {
for (auto& g : st->gens) out += g.delta->first_chunk();
} else if (st->r.echo) {
/* `echo`, ON THE STREAMING PATH. The buffered path applies it by prepending the
* prompt to the choice's text; this is the equivalent, and without it the same
* request would answer differently depending on `stream`.
*
* The prompt goes out as the first content chunk, before any token, which is what
* "echo" means and what a client reassembling the deltas needs: concatenating the
* stream gives the same string the buffered response returns.
* Empty prompts emit nothing rather than an empty chunk. */
for (auto& g : st->gens) {
const std::string& p = st->r.prompts[(size_t)g.prompt_index].text;
if (!p.empty()) out += text_chunk(st->r, g.index, p, nullptr);
}
}
return true;
}
if (st->peer_closed && st->peer_closed()) {
return false;
}
const bool progress = self->pump(st->gens, st->r);
size_t maxstop = 0;
for (const auto& s : st->r.stop) maxstop = std::max(maxstop, s.size());
for (auto& g : st->gens) {
/* Hold back the longest stop string minus one byte while the choice is still running:
* otherwise the first half of a stop sequence is already on the wire by the time we
* recognise it, and it cannot be taken back.
*
* ONLY WHILE IT IS RUNNING. Every hold-back rule here waits for bytes that may still
* arrive, and a closed choice has none coming, so its whole text is the answer. That
* includes a tail the escape rule would keep -- a trailing `\` or a partial `\uXXXX`
* is ordinary text in a completion, and holding it back at the end drops it. */
size_t safe = g.text.size();
if (!g.closed) {
if (maxstop > 1) safe = safe > maxstop - 1 ? safe - (maxstop - 1) : 0;
safe = json_stable_prefix(std::string_view(g.text.data(), safe));
if (safe <= g.emitted) continue;
}
if (st->r.endpoint == Endpoint::Chat) {
/* Only what is new: the reader keeps its own place in the reply, which is what
* makes a long reply cost its length rather than its length squared. */
out += g.delta->push(std::string_view(g.text).substr(g.emitted, safe - g.emitted),
g.closed);
} else if (safe > g.emitted) {
out += text_chunk(st->r, g.index, g.text.substr(g.emitted, safe - g.emitted),
nullptr);
}
g.emitted = safe;
}
if (self->all_done(st->gens)) {
UsageOut u;
for (const auto& p : st->r.prompts) u.prompt += (int64_t)p.tokens.size();
for (auto& g : st->gens) {
u.completion += g.sink->n_produced();
if (g.prompt_index * st->r.n == g.index) u.cached += g.sink->n_cached();
}
Finish overall = Finish::Stop;
for (auto& g : st->gens) {
if (st->r.endpoint == Endpoint::Chat) {
out += g.delta->final_chunk(g.finish);
Finish adj = g.delta->adjusted_finish(g.finish);
if (adj == Finish::Error || adj == Finish::Cancelled) overall = adj;
else if (adj == Finish::ToolCalls) overall = adj;
} else {
out += text_chunk(st->r, g.index, "", finish_reason_oai(g.finish));
if (g.finish == Finish::Error) overall = Finish::Error;
}
/* A failed generation cannot become a non-200 -- the headers left long ago -- so
* it travels as an error event before [DONE]. Silence would look like a normal
* end of stream and the client would use a truncated answer. */
if (g.finish == Finish::Error) {
ApiError e;
e.status = 500;
e.type = "internal_server_error";
e.message = std::string("the engine failed this request: ") +
rad_strerror(g.sink->status());
out += sse_error(e);
}
}
/* THE USAGE CHUNK. `stream_options.include_usage` is parsed and validated on both
* endpoints, so both have to honour it -- accepting a field and then ignoring it is
* the outcome oai.h's header forbids.
*
* After the per-generation final chunks and before [DONE], which is where OpenAI puts
* it, and once for the request rather than once per choice: `n` completions share one
* prompt and one total, so emitting it per generation would count the prompt n times
* and interleave usage between the choices' final chunks. */
if (st->r.include_usage)
out += st->r.endpoint == Endpoint::Chat ? chat_usage_chunk(st->r, u)
: text_usage_chunk(st->r, u);
out += SSE_DONE;
st->done_sent = true;
self->record(st->r, st->gens, overall);
self->retire(st->gens);
self->metrics_.observe_http(200);
if (!st->released) { st->released = true; self->release(st->r.n_choices()); }
return false;
}
if (!progress && out.empty()) {
/* Nothing to send: sleep on the first live sink rather than spinning. The bounded
* wait is what makes the peer-closed check above run a few times a second. */
for (auto& g : st->gens) if (!g.closed) { g.sink->wait(); break; }
}
return true;
};
res.on_close = [self, st](bool ok) {
if (!st->done_sent) {
/* Either the peer went away or the write failed. Both are cancellations, and the
* blocks have to go back now rather than when the generation would have ended. */
self->cancel_all(st->gens, true);
self->record(st->r, st->gens, Finish::Cancelled);
self->retire(st->gens);
RAD_DEBUG("server: stream %s abandoned by the client (write %s)",
st->r.id.c_str(), ok ? "ok" : "failed");
}
if (!st->released) { st->released = true; self->release(st->r.n_choices()); }
};
return res;
}
/* ------------------------------------------------------------------ endpoints */
HttpResponse Server::handle_chat(const HttpRequest& req) {
if (!deps_.sched || !deps_.tok)
return error_response(err_not_implemented("the server has no engine attached"));
OaiRequest r;
ApiError err;
if (parse_chat_request(req.body, odeps_, lim_, &r, &err) < 0) return error_response(err);
sweep_abandoned();
if (!admit(r.n_choices())) {
metrics_.observe_rejected();
return error_response(err_overloaded(
"the admission queue is full; retry after " + std::to_string(opt_.retry_after_s) +
"s. The server refuses rather than queueing without bound"));
}
return r.stream ? streaming_completion(req, r) : blocking_completion(req, r);
}
HttpResponse Server::handle_completion(const HttpRequest& req) {
if (!deps_.sched || !deps_.tok)
return error_response(err_not_implemented("the server has no engine attached"));
OaiRequest r;
ApiError err;
if (parse_completion_request(req.body, odeps_, lim_, &r, &err) < 0) return error_response(err);
sweep_abandoned();
if (!admit(r.n_choices())) {
metrics_.observe_rejected();
return error_response(err_overloaded(
"the admission queue is full; retry after " + std::to_string(opt_.retry_after_s) +
"s. The server refuses rather than queueing without bound"));
}
return r.stream ? streaming_completion(req, r) : blocking_completion(req, r);
}
HttpResponse Server::handle_embeddings(const HttpRequest& req) {
if (!deps_.tok)
return error_response(err_not_implemented("the server has no tokenizer attached"));
if (!deps_.embed)
return error_response(err_not_implemented(
"/v1/embeddings requires an embedding head; this model was not loaded with one"));
OaiRequest r;
ApiError err;
if (parse_embeddings_request(req.body, odeps_, lim_, &r, &err) < 0) return error_response(err);
std::vector<std::vector<float>> vecs;
UsageOut u;
vecs.reserve(r.prompts.size());
for (const auto& p : r.prompts) {
std::vector<float> v;
int s = deps_.embed->embed(p.tokens, v);
if (s < 0) {
ApiError e;
e.status = 500;
e.type = "internal_server_error";
e.message = std::string("the embedding pass failed: ") + rad_strerror(s);
return error_response(e);
}
u.prompt += (int64_t)p.tokens.size();
vecs.push_back(std::move(v));
}
metrics_.observe_http(200);
return HttpResponse::json_body(200, embeddings_body(r, vecs, u));
}
HttpResponse Server::handle_models(const HttpRequest& req) {
const std::string id = req.param("id");
if (!id.empty() && id != opt_.model_id) {
ApiError e;
e.status = 404;
e.type = "not_found_error";
e.param = "model";
e.message = "no such model: " + id;
return error_response(e);
}
metrics_.observe_http(200);
return HttpResponse::json_body(200, models_body(opt_.model_id, started_at_));
}
HttpResponse Server::handle_metrics(const HttpRequest&) {
if (deps_.sched) metrics_.sample(deps_.sched->metrics());
metrics_.set_queue_depth(in_flight_.load(std::memory_order_relaxed));
HttpResponse r;
r.status = 200;
/* The exposition format version is part of the content type; Prometheus uses it to decide how
* to parse, and omitting it makes some scrapers fall back to OpenMetrics and fail. */
r.content_type = "text/plain; version=0.0.4; charset=utf-8";
r.body = metrics_.render();
return r;
}
} /* namespace server */
} /* namespace rad */
+204
View File
@@ -0,0 +1,204 @@
/* 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.
*
* 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.
*
* 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.
*/
#pragma once
#include <functional>
#include "http.h"
#include "iface.h"
#include "liveview.h"
#include "metrics.h"
#include "oai.h"
#include "sink.h"
#include <atomic>
#include <memory>
#include <mutex>
#include <string>
#include <vector>
namespace rad {
namespace server {
struct Deps {
IScheduler* sched = nullptr; /* required */
ITokenizer* tok = nullptr; /* required */
IChatTemplate* chat = nullptr; /* absent -> /v1/chat/completions is 501 */
IGrammarCompiler* grammar = nullptr; /* absent -> response_format is 501 */
IEmbedder* embed = nullptr; /* absent -> /v1/embeddings is 501 */
IMultimodal* mm = nullptr; /* absent -> image and audio parts are 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. */
LiveView::Source live;
};
struct ServerOptions {
std::string model_id = "radiance";
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. */
int64_t queue_depth = 0;
int64_t max_seqs = 256;
int retry_after_s = 1;
int64_t max_ctx = 0;
int64_t default_max_tokens = 512;
int max_n = 8;
bool supports_logprobs = false;
/* The deployment default for `reasoning_effort`, empty for the template's own. See
* OaiLimits::default_reasoning_effort for why a server-side default is needed at all. */
std::string default_reasoning_effort;
/* What a request that sends no sampler fields is served with. See
* OaiLimits::default_sampling; only the sampler knobs are read from it. */
SamplingParams default_sampling;
bool allow_image = false;
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. */
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 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. */
std::function<std::string()> graph_json;
std::string api_key;
bool cors = true;
};
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
* running step may touch. */
~Server();
/* Every endpoint, registered. Tests drive this directly -- same handlers, no socket. */
const Router& router() const { return router_; }
int run(); /* binds, serves, blocks. RAD_OK or negative. */
void stop();
int port() const { return transport_.port(); } /* 0 until run() is accepting */
int64_t in_flight() const { return in_flight_.load(std::memory_order_relaxed); }
private:
struct Generation;
struct StreamState;
void register_routes();
HttpResponse handle_chat(const HttpRequest& req);
HttpResponse handle_completion(const HttpRequest& req);
HttpResponse handle_embeddings(const HttpRequest& req);
HttpResponse handle_models(const HttpRequest& req);
HttpResponse handle_metrics(const HttpRequest& req);
/* ------------------------------------------------------------------ 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. */
HttpResponse handle_health(const HttpRequest& req);
HttpResponse handle_ping(const HttpRequest& req);
HttpResponse handle_version(const HttpRequest& req);
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_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 error_response(const ApiError& e);
/* Admission. Returns false when the queue is full; the caller answers 429. */
bool admit(int64_t n);
void release(int64_t n);
void sweep_abandoned();
/* Wait, bounded, for the scheduler to finish everything it was told to cancel. */
void drain_graveyard(int timeout_ms);
/* 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);
void retire(std::vector<Generation>& gens);
/* Drain sinks into decoded text. Returns true if anything new arrived. */
bool pump(std::vector<Generation>& gens, const OaiRequest& r);
bool all_done(const std::vector<Generation>& gens) const;
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);
Deps deps_;
ServerOptions opt_;
OaiLimits lim_;
OaiDeps odeps_;
Router router_;
Metrics metrics_;
HttpTransport transport_;
std::atomic<int64_t> in_flight_{0};
int64_t queue_depth_ = 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. */
std::mutex grave_m_;
std::vector<std::shared_ptr<Sink>> grave_;
};
} /* namespace server */
} /* namespace rad */
+130
View File
@@ -0,0 +1,130 @@
#include "sink.h"
#include <chrono>
#include <thread>
namespace rad {
namespace server {
static int64_t now_ns() {
using namespace std::chrono;
return duration_cast<nanoseconds>(steady_clock::now().time_since_epoch()).count();
}
const char* finish_reason_oai(Finish f) {
switch (f) {
case Finish::Stop:
case Finish::StopString: return "stop";
case Finish::Length: return "length";
case Finish::ToolCalls: return "tool_calls";
case Finish::Cancelled: return "abort"; /* vLLM's spelling; dashboards key off it */
case Finish::Error: return "error";
case Finish::None: return "";
}
return "";
}
static size_t round_pow2(size_t n) {
size_t p = 1;
while (p < n) p <<= 1;
return p;
}
Sink::Sink(size_t capacity) {
size_t cap = round_pow2(capacity < 16 ? 16 : capacity);
ring_.resize(cap);
mask_ = cap - 1;
t_start_ns_ = now_ns();
}
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. */
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. */
if (spins > 256) std::this_thread::sleep_for(std::chrono::microseconds(20));
}
}
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. */
cv_.notify_one();
}
bool Sink::push(int32_t token, float logprob) {
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. */
overflow_.store(true, std::memory_order_release);
fail(RAD_E_FULL);
return false;
}
ring_[h & mask_] = SinkToken{token, logprob};
head_.store(h + 1, std::memory_order_release);
const int64_t t_now = now_ns() - t_start_ns_;
if (h == 0) t_first_.store(t_now, std::memory_order_release);
t_last_.store(t_now, std::memory_order_release);
notify();
return true;
}
void Sink::finish(Finish f) {
int expected = (int)Finish::None;
/* 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. */
quiesced_.store(true, std::memory_order_release);
}
}
void Sink::fail(int rad_status) {
status_.store(rad_status, std::memory_order_release);
finish(Finish::Error);
}
void Sink::set_prompt_stats(int32_t n_prompt, int32_t n_cached) {
n_prompt_.store(n_prompt, std::memory_order_release);
n_cached_.store(n_cached, std::memory_order_release);
}
size_t Sink::read(SinkToken* out, size_t max) {
const uint64_t t = tail_.load(std::memory_order_relaxed);
const uint64_t h = head_.load(std::memory_order_acquire);
size_t n = (size_t)(h - t);
if (n > max) n = max;
for (size_t i = 0; i < n; ++i) out[i] = ring_[(t + i) & mask_];
if (n) tail_.store(t + n, std::memory_order_release);
return n;
}
bool Sink::wait(int timeout_ms) {
auto ready = [&] {
return head_.load(std::memory_order_acquire) != tail_.load(std::memory_order_relaxed)
|| finish_.load(std::memory_order_acquire) != (int)Finish::None
|| cancel_.load(std::memory_order_acquire);
};
if (ready()) return true;
std::unique_lock<std::mutex> lk(m_);
cv_.wait_for(lk, std::chrono::milliseconds(timeout_ms), ready);
return ready();
}
void Sink::request_cancel() {
cancel_.store(true, std::memory_order_release);
notify();
}
} /* namespace server */
} /* namespace rad */
+173
View File
@@ -0,0 +1,173 @@
/* 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.
*
* 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.
*
* 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.
*/
#pragma once
#include "rad_core.h"
#include <atomic>
#include <condition_variable>
#include <cstdint>
#include <mutex>
#include <vector>
namespace rad {
namespace server {
/* How long the consumer sleeps before re-testing. Also the connection-liveness poll interval. */
static constexpr int RAD_SINK_POLL_MS = 25;
enum class Finish : int {
None = 0, /* still running */
Stop, /* EOS */
StopString, /* a stop string matched */
Length, /* max_tokens */
ToolCalls, /* the parser found a complete tool call and the model stopped */
Cancelled, /* client went away, or /cancel */
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. */
const char* finish_reason_oai(Finish f);
struct SinkToken {
int32_t token = 0;
float logprob = 0.0f; /* 0 when the sampler does not supply one; see Sink::has_logprobs */
};
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. */
explicit Sink(size_t capacity = 8192);
/* Waits for the producer to be finished touching this object before letting it go.
*
* 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. */
~Sink();
/* ------------------------------------------------------------------ producer: scheduler */
/* Returns false only on overflow, which also marks the request failed. */
bool push(int32_t token, float logprob = 0.0f);
/* Terminal. Idempotent -- the first call wins, so a cancel racing a natural stop does not
* produce two finish reasons. */
void finish(Finish f);
void fail(int rad_status);
/* 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. */
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);
/* ------------------------------------------------------------------ consumer: HTTP */
/* Copies up to `max` tokens out. Returns how many. Never blocks. */
size_t read(SinkToken* out, size_t max);
/* Sleeps until there is something to read, the request is terminal, or `timeout_ms` elapses.
* Returns true if there is now something to look at. */
bool wait(int timeout_ms = RAD_SINK_POLL_MS);
bool done() const { return finish_.load(std::memory_order_acquire) != (int)Finish::None; }
Finish finish_reason() const { return (Finish)finish_.load(std::memory_order_acquire); }
int status() const { return status_.load(std::memory_order_acquire); }
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. */
void request_cancel();
/* Timings, in steady-clock nanoseconds since the sink was constructed. -1 until observed. */
int64_t t_first_token_ns() const { return t_first_.load(std::memory_order_acquire); }
int64_t t_last_token_ns() const { return t_last_.load(std::memory_order_acquire); }
int64_t age_ns() const;
int64_t n_produced() const { return (int64_t)head_.load(std::memory_order_acquire); }
int32_t n_prompt() const { return n_prompt_.load(std::memory_order_acquire); }
int32_t n_cached() const { return n_cached_.load(std::memory_order_acquire); }
/* The engine sets this at wiring time if its sampler returns per-token probabilities. Without
* it the logprobs field of a response is null rather than zeros (spec: nothing unimplemented
* returns success). */
void set_has_logprobs(bool v) { has_logprobs_ = v; }
bool has_logprobs() const { return has_logprobs_; }
/* The engine's request id, so a dropped connection can reach IScheduler::cancel. */
uint64_t id = 0;
private:
void notify();
std::vector<SinkToken> ring_;
size_t mask_ = 0;
std::atomic<uint64_t> head_{0}; /* produced count; producer writes, both read */
std::atomic<uint64_t> tail_{0}; /* consumed count; consumer writes, both read */
std::atomic<int> finish_{(int)Finish::None};
std::atomic<int> status_{RAD_OK};
std::atomic<bool> overflow_{false};
std::atomic<bool> cancel_{false};
std::atomic<bool> quiesced_{false}; /* the producer will not touch this object again */
std::atomic<int64_t> t_first_{-1};
std::atomic<int64_t> t_last_{-1};
int64_t t_start_ns_ = 0;
std::atomic<int32_t> n_prompt_{0};
std::atomic<int32_t> n_cached_{0};
bool has_logprobs_ = false;
std::mutex m_;
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. */
inline bool sink_push(void* s, int32_t token, float logprob = 0.0f) {
return s ? static_cast<Sink*>(s)->push(token, logprob) : true;
}
inline void sink_finish(void* s, Finish f) {
if (s) static_cast<Sink*>(s)->finish(f);
}
inline void sink_fail(void* s, int rad_status) {
if (s) static_cast<Sink*>(s)->fail(rad_status);
}
inline bool sink_cancelled(const void* s) {
return s && static_cast<const Sink*>(s)->cancel_requested();
}
inline void sink_prompt_stats(void* s, int32_t n_prompt, int32_t n_cached) {
if (s) static_cast<Sink*>(s)->set_prompt_stats(n_prompt, n_cached);
}
} /* namespace server */
} /* namespace rad */