radiance 1.5.0

- Gemma 4 31B (PRs #74, #75, #81, #86; sfjes, keptn42): sliding and global attention with their
  own kernels, the assistant head as a drafter that reads the trunk's cache, the vision tower, a
  fused w4a8 decode step, bf16 and compressed-tensors int4 checkpoints, and window snapshots so a
  prefix hit on a sliding-window model resumes instead of prefilling again.
  deploy/compose/gemma4-31b-w4a8.yaml serves keptn42's container on two cards
- ParoQuant (PRs #65, #66, #67; malic): Qwen3.8-27B checkpoints with learned Givens rotations,
  as int4, int5 and MXFP4, imported without re-quantising, the prefill's rotations on the matrix
  cores. deploy/compose/qwen3.8-27b-paro.yaml serves them on one card. A ParoQuant container made
  with the PR builds is refused: convert it again with --reuse <old container>
- Gemma 4 26B-A4B with z-lab's DFlash drafter (PR #88; Perire): arch/gemma4 serves Google's bf16
  checkpoint with the routed experts in block fp8 or bf16 (data/recipes/gemma4-26b-a4b-df*.recipe),
  and libr4d gains its windowed paged attention, the fused sandwich-norm joins, expert_scale and
  the sharded draft head's pair_argmax. A prefill chunk runs as two slices with its all-reduces
  beside the compute, bit-exact with the whole step. The 31B's global layers take the windowed
  attention too: an 11.5K-token prefill on two R9700s in 3.1 s instead of 4.9
- a startup that logs nothing for two minutes says where it waits (#89): the system call (a KFD
  request by name), the library that made it, and its stack, which addr2line resolves against the
  binary
- the prefix cache is kept in VRAM and host memory only (#70): the disk tier wrote every block and
  snapshot a prompt produced, and its copies never outlived the process. --prefix-cache-host-mib
  is renamed --prefix-cache-mib; --prefix-cache-dir and --prefix-cache-disk-mib are removed, and
  startup refuses all three with what replaced them. The compose files no longer mount /data, and
  .env no longer needs RADIANCE_STATE
- --prefix-cache-ttl S (default 3600, 0 never): a conversation no request has used for that long
  leaves the cache, whichever tier holds it; radiance:prefix_cache_expired_total counts them. A
  full host tier now drops its least recently used conversations
- --vision-tower-placement vram|ram (#84): ram keeps an encoder tower in pinned host memory and
  gives its VRAM to the KV cache, read over the link once an image
- timings carry ttft_ms and total_ms (#85): the server's own time from the request body's arrival
  to the first and the last token, queueing and tokenisation included
- a KV-cache recall that found a moved expert with nowhere to go stopped halfway and leaked the
  slots it had already freed: after it every recall failed, the cache stayed short until a
  restart, and requests failed with HTTP 500. A recall now waits for the slots it is owed and
  always finishes
- a tool result or tool-call arguments that are not JSON are no longer refused as nesting past
  1024 levels for their unmatched brackets (#90): only text that parses as JSON is held to the
  bound, since nothing else is parsed into a tree
- the host-pool refusal names the limit that applies to pinned memory (RAM less 1/64 and
  1.5 GiB), not ttm.pages_limit
- --embedding-placement auto, removed in 1.3.0, is refused with what replaced it
- for out-of-tree kernel libraries: gemm_nt_q gains two operands (pb1, pb2, the part bounds), and
  the loader requires identical op schemas, so a library built against 1.4.0 must be rebuilt. For
  architecture plugins, rad_op_declared(b, op) asks whether an op is in the loaded vocabulary
  without declaring it
This commit is contained in:
Deadcode committed 2026-10-13 19:35:16 +02:00
commit b93b531f63
127 files changed
+9609 -4796

No files matched your search

+9 -15
View File
@@ -50,7 +50,7 @@ public:
* 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
* the object holds the session table either way, and a server with no --prefix-cache-mib is
* one whose every stored session is in VRAM rather than one with no sessions. Null only when
* there is no engine behind this at all. */
explicit SchedulerBridge(Scheduler* s, const Sampler* sampler = nullptr,
@@ -111,19 +111,14 @@ public:
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_disk = s.ck_to_disk; c.ck_drops = s.ck_drops;
c.to_host = s.to_host; c.dropped = s.dropped; c.promoted = s.promoted;
c.host_drops = s.host_drops; c.failures = s.failures;
c.host_bytes = s.host_bytes;
c.restores = s.restores; c.restore_ns = s.restore_ns;
c.flushes = s.flushes; c.flush_ns = s.flush_ns;
c.ck_bytes = tiers_->ckpt_bytes();
c.ck_host_slots = tiers_->ckpt_slots();
c.ck_disk_slots = tiers_->ckpt_disk_slots();
c.ck_slots = tiers_->ckpt_slots();
c.host_on = tiers_->host_on();
c.disk_on = tiers_->disk_on();
return c;
}
@@ -133,8 +128,8 @@ public:
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;
occ->host_bytes = held.host_bytes;
occ->host_cap_bytes = held.host_cap_bytes;
}
const uint64_t now = rad_mono_ns();
out->reserve(v.size());
@@ -149,11 +144,8 @@ public:
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_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));
@@ -263,6 +255,8 @@ public:
* figure above the used one would draw a negative live share. */
o.kv_tokens_cached = std::min(m.prefix_held_tokens, o.kv_tokens_used);
o.prefix_ckpt_evictions = m.prefix_ckpt_evictions;
o.prefix_expired = m.prefix_expired;
o.prefix_ckpt_expired = m.prefix_ckpt_expired;
o.prefill_tps = m.prefill_tps;
o.decode_tps = m.decode_tps;
+26 -39
View File
@@ -52,8 +52,8 @@ HttpResponse Server::handle_sessions(const HttpRequest&) {
SessionOccupancy occ;
if (deps_.sched) deps_.sched->sessions(&v, &occ);
int64_t dev = 0, host = 0, disk = 0, bytes = 0;
int64_t shost = 0, sdisk = 0;
int64_t dev = 0, host = 0, bytes = 0;
int64_t snaps = 0;
json a = json::array();
for (const SessionStat& s : v) {
json e;
@@ -66,20 +66,16 @@ HttpResponse Server::handle_sessions(const HttpRequest&) {
e["age_s"] = s.age_s;
e["on_device"] = s.on_device;
e["on_host"] = s.on_host;
e["on_disk"] = s.on_disk;
e["moving"] = s.moving;
/* THE RECURRENT HALF. On a hybrid model a session's attention blocks are only part of
* what it needs back; the rest is its linear-state snapshots, which are a different size
* of object in a different store. Counted where the BYTES are: in the store in host
* memory, or on disk alone. */
* of object in a different store, in host memory. */
e["snapshots"] = s.snapshots;
e["snap_host"] = s.snap_host;
e["snap_disk"] = s.snap_disk;
e["snap_bytes"] = s.snap_bytes;
e["resume_tokens"] = s.resume_tokens;
a.push_back(std::move(e));
dev += s.on_device; host += s.on_host; disk += s.on_disk;
shost += s.snap_host; sdisk += s.snap_disk;
dev += s.on_device; host += s.on_host;
snaps += s.snapshots;
bytes += s.bytes;
}
o["sessions"] = std::move(a);
@@ -87,8 +83,8 @@ HttpResponse Server::handle_sessions(const HttpRequest&) {
* the blocks for it, so these per-session sizes overlap and adding them up over-counts -- on
* a server carrying long agent transcripts by more than an order of magnitude. The field
* names say so rather than pretending the sums are totals. */
o["blocks_sum_overlapping"] = { { "device", dev }, { "host", host }, { "disk", disk } };
o["snapshots"] = { { "host", shost }, { "disk", sdisk } };
o["blocks_sum_overlapping"] = { { "device", dev }, { "host", host } };
o["snapshots_sum_overlapping"] = snaps;
o["bytes_sum_overlapping"] = bytes;
const SchedMetrics sm = deps_.sched ? deps_.sched->metrics() : SchedMetrics{};
/* AND THE ONE FIGURE THAT IS NOT A SUM, because a view about what the conversations cost has
@@ -103,17 +99,14 @@ HttpResponse Server::handle_sessions(const HttpRequest&) {
{ "bytes_total", sm.kv_bytes_total } };
const IScheduler::TierCounters c =
deps_.sched ? deps_.sched->tier_counters() : IScheduler::TierCounters{};
o["moved"] = { { "to_host", c.to_host }, { "dropped", c.dropped }, { "to_disk", c.to_disk },
{ "promoted", c.promoted }, { "host_freed", c.host_freed },
{ "host_drops", c.host_drops }, { "failures", c.failures },
{ "fetched", c.fetched } };
/* THE SNAPSHOT COUNTERS ARE NOT OPTIONAL ON A HYBRID MODEL, because a server that moves every
* block it has and no snapshots at all looks identical in the block counters to one where
* tiering works -- and the difference is a full linear replay on every restored session. */
o["snapshots_moved"] = { { "to_disk", c.ck_to_disk }, { "fetched", c.ck_fetched },
{ "drops", c.ck_drops }, { "bytes_each", c.ck_bytes },
{ "host_slots", c.ck_host_slots },
{ "disk_slots", c.ck_disk_slots } };
o["moved"] = { { "to_host", c.to_host }, { "dropped", c.dropped },
{ "promoted", c.promoted }, { "host_drops", c.host_drops },
{ "failures", c.failures } };
/* THE SNAPSHOT STORE, on a hybrid model: what one snapshot costs and how many the store
* holds. `bytes_each` is 0 on a model with no recurrent state. */
o["snapshot_store"] = { { "bytes_each", c.ck_bytes }, { "slots", c.ck_slots } };
/* WHAT --prefix-cache-ttl TOOK, entries and snapshots, from whichever tier held them. */
o["expired"] = { { "entries", sm.prefix_expired }, { "snapshots", sm.prefix_ckpt_expired } };
/* THE STEP THREAD'S TIME ON THE TIERS: every request waits through it. */
o["stall"] = { { "restores", c.restores }, { "restore_ms", (double)c.restore_ns / 1e6 },
{ "flushes", c.flushes }, { "flush_ms", (double)c.flush_ns / 1e6 } };
@@ -127,15 +120,14 @@ HttpResponse Server::handle_sessions(const HttpRequest&) {
/* WHETHER ANYTHING MOVES, which is not whether anything is STORED. A session is recorded
* whether or not it can be demoted, so a non-empty table says only that something is held;
* these say whether a tier exists that can move it. */
o["tiers"] = { { "host", c.host_on }, { "disk", c.disk_on } };
o["tiers"] = { { "host", c.host_on } };
/* WHAT IS OFF THE CARD, counted once -- see SessionOccupancy. */
o["occupancy"] = { { "host_bytes", occ.host_bytes }, { "disk_bytes", occ.disk_bytes },
{ "host_cap_bytes", occ.host_cap_bytes },
{ "disk_cap_bytes", occ.disk_cap_bytes } };
o["occupancy"] = { { "host_bytes", occ.host_bytes },
{ "host_cap_bytes", occ.host_cap_bytes } };
/* THE ATTENTION HIT RATE, for a model with no recurrent state, where it is the whole answer
* to how much of the prompt the cache served. On a hybrid model `linear.hit_rate` is. */
o["prefix_hit_rate"] = sm.prefix_hit_rate;
o["enabled"] = c.host_on || c.disk_on;
o["enabled"] = c.host_on;
return HttpResponse::json_body(200, json_dump(o));
}
@@ -695,7 +687,6 @@ th + th, td + td { padding-left:14px; }
.tbar > i { display:block; height:100%; }
.t-dev { background:#4ade80; } .tn-dev { color:#7fe0a3; }
.t-host { background:#60a5fa; } .tn-host { color:#8dbcfb; }
.t-disk { background:#a78bfa; } .tn-disk { color:#c4b5fd; }
/* The group that starts over is folded by default: it is a count first and rows second. */
details.sgrp > summary { list-style:none; cursor:pointer; }
details.sgrp > summary::-webkit-details-marker { display:none; }
@@ -1185,9 +1176,6 @@ nav button.on { color:var(--fg); background:var(--track); }
<div class="cell" id="s-hostcell"><div class="n" id="s-host">–<u></u></div>
<span class="cap">moved to host ram</span>
<span class="det" id="s-hostdet"></span></div>
<div class="cell" id="s-diskcell"><div class="n" id="s-disk">–<u></u></div>
<span class="cap">moved to disk</span>
<span class="det" id="s-diskdet"></span></div>
</div>
<section class="panel">
@@ -2838,7 +2826,7 @@ $("tab-model").addEventListener("click", () => show("model"));
* snapshot reuses nothing however many of its blocks are kept. On a model with no recurrent state
* the blocks are the whole answer and every stored token is reused. */
const reuseOf = (r, hybrid) => hybrid ? Math.min(r.resume_tokens || 0, r.tokens) : r.tokens;
const TIERS = [["dev", "on_device", "vram"], ["host", "on_host", "host"], ["disk", "on_disk", "disk"]];
const TIERS = [["dev", "on_device", "vram"], ["host", "on_host", "host"]];
function sessCols(tr, manyModels) {
tr.textContent = "";
@@ -2874,7 +2862,7 @@ function sessRow(r, hybrid, manyModels) {
read as three equal parts. The per-tier counts are blocks, and a block is the same number of
tokens in every tier, so the proportion is the proportion of its tokens. */
const wh = tr.appendChild(el("td", "l")), bar = wh.appendChild(el("span", "tbar"));
const held = r.on_device + r.on_host + r.on_disk, parts = [];
const held = r.on_device + r.on_host, parts = [];
for (const [k, f, name] of TIERS) {
if (!(r[f] > 0)) continue;
bar.appendChild(el("i", "t-" + k)).style.width = (100 * r[f] / held).toFixed(1) + "%";
@@ -2897,7 +2885,7 @@ async function loadSessions() {
return;
}
const rows = (s.sessions || []).slice().sort((x, y) => x.idle_s - y.idle_s);
const mv = s.snapshots_moved || {}, ln = s.linear || {};
const mv = s.snapshot_store || {}, ln = s.linear || {};
const pool = s.pool || {}, occ = s.occupancy || {};
/* The model has recurrent state if its snapshots have a size. */
const hybrid = mv.bytes_each > 0;
@@ -2913,13 +2901,12 @@ async function loadSessions() {
$("s-live").firstChild.nodeValue = cnt(live.length);
$("s-liveof").textContent = "of " + cnt(rows.length);
$("s-livedet").textContent = cold.length ? cnt(cold.length) + " start over" : "";
/* VRAM IN TOKENS, THE OTHER TIERS IN BYTES. The pool's token count is the context the card can
serve without a copy; the tiers off the card are sized by --prefix-cache-host-mib and
--prefix-cache-disk-mib and are read against them. A tier that is off has no cell. */
/* VRAM IN TOKENS, HOST MEMORY IN BYTES. The pool's token count is the context the card can
serve without a copy; the host tier is sized by --prefix-cache-mib and read against it. A
tier that is off has no cell. */
$("s-vram").firstChild.nodeValue = cnt3(pool.tokens_used || 0);
$("s-vramdet").textContent = pool.tokens_total ? "of " + cnt3(pool.tokens_total) + " tok" : "";
for (const [id, used, cap] of [["s-host", occ.host_bytes, occ.host_cap_bytes],
["s-disk", occ.disk_bytes, occ.disk_cap_bytes]]) {
for (const [id, used, cap] of [["s-host", occ.host_bytes, occ.host_cap_bytes]]) {
$(id + "cell").hidden = !(cap > 0);
const x = hbs(used || 0);
$(id).firstChild.nodeValue = x.n;
+2
View File
@@ -412,6 +412,8 @@ int HttpTransport::serve(const Router& router, const TransportOptions& o) {
req.path = hreq.path;
req.body = std::move(body);
req.peer = hreq.remote_addr + ":" + std::to_string(hreq.remote_port);
req.t_received_ns = std::chrono::duration_cast<std::chrono::nanoseconds>(
std::chrono::steady_clock::now().time_since_epoch()).count();
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(); };
+4
View File
@@ -32,6 +32,10 @@ struct HttpRequest {
std::map<std::string, std::string> query;
std::map<std::string, std::string> params; /* from a ":name" route segment */
std::string peer; /* "addr:port"; empty in-process */
/* WHEN THE WHOLE BODY HAD ARRIVED, in steady-clock nanoseconds: where the server's own time
* for the request starts, before it is parsed, rendered or tokenised, so the time the body
* spent on the network is not in it. -1 for a request made in-process. */
int64_t t_received_ns = -1;
/* True once the peer is gone. The transport supplies it; in-process it is absent and the
* waiting paths simply never see a drop. A dropped connection is a cancellation (spec §14),
+15 -21
View File
@@ -79,6 +79,8 @@ struct SchedMetrics {
* between an alert and a post-mortem. */
int64_t prefix_evictions = 0;
int64_t prefix_ckpt_evictions = 0;
/* What --prefix-cache-ttl took, cumulative. Not evictions: nothing wanted the memory. */
int64_t prefix_expired = 0, prefix_ckpt_expired = 0;
/* PREFIX CACHING, DECOUPLED (spec §7.3). `prefix_hit_rate` above is the ATTENTION one, because
* that is what vLLM's single number has always meant. The linear side hits at a different
* granularity -- whole checkpoints, not blocks -- and averaging the two would hide exactly the
@@ -166,13 +168,12 @@ struct SessionStat {
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 */
int64_t on_device = 0, on_host = 0; /* blocks */
/* LINEAR STATE, on a hybrid model, and counted apart from blocks because the two are not
* interchangeable. A session showing every block on disk and no snapshot anywhere will come
* interchangeable. A session showing every block in host memory and no snapshot will come
* back and re-run every recurrent layer over its whole transcript -- which the hit rate will
* report as a hit. Zero everywhere on a model that has no recurrent state. */
int64_t snapshots = 0;
int64_t snap_host = 0, snap_disk = 0; /* in the store; only on disk */
int64_t snap_bytes = 0;
/* The prefix a return skips: the deepest snapshot's position (IdleTiers::SessionInfo). */
int64_t resume_tokens = 0;
@@ -182,8 +183,8 @@ struct SessionStat {
/* 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;
int64_t host_bytes = 0;
int64_t host_cap_bytes = 0;
};
struct RequestStat {
@@ -268,27 +269,20 @@ public:
* 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, and no block counter can tell that apart from tiering
* working. `ck_drops` is snapshots whose only copy was lost. */
int64_t ck_to_disk = 0, ck_drops = 0;
/* `to_host` counts COPIES; `dropped` is VRAM given up after one. A conversation that
* returns before anything wants its VRAM is copied and never dropped. `host_drops` is
* entries a full host tier gave up; `promoted` counts restores. */
int64_t to_host = 0, dropped = 0, promoted = 0;
int64_t host_drops = 0, failures = 0;
int64_t host_bytes = 0;
/* THE SNAPSHOT STORE, which lives in host memory and moves nothing. */
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; /* the store's; the disk store's */
int64_t ck_slots = 0;
int64_t restores = 0, restore_ns = 0, flushes = 0, flush_ns = 0; /* IdleTiers::Stats */
/* WHETHER ANYTHING CAN MOVE AT ALL, which no counter above can answer: a tier that is on
* and has had nothing to do reads the same as one that was never given a size, and the
* two call for opposite responses from whoever is looking. */
bool host_on = false, disk_on = false;
bool host_on = false;
};
virtual TierCounters tier_counters() const { return TierCounters{}; }
};
+9
View File
@@ -185,6 +185,9 @@ void Metrics::sample(const SchedMetrics& m) {
c_prefix_evict_.inc(std::max(0.0, (double)m.prefix_evictions - c_prefix_evict_.get()));
c_prefix_ckpt_evict_.inc(std::max(0.0,
(double)m.prefix_ckpt_evictions - c_prefix_ckpt_evict_.get()));
c_prefix_expired_.inc(std::max(0.0, (double)m.prefix_expired - c_prefix_expired_.get()));
c_prefix_ckpt_expired_.inc(std::max(0.0,
(double)m.prefix_ckpt_expired - c_prefix_ckpt_expired_.get()));
g_linear_hit_.set(m.linear_hit_rate);
}
@@ -394,6 +397,12 @@ std::string Metrics::render() const {
"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.counter("radiance:prefix_cache_expired_total",
"Prefix-cache entries no request used for --prefix-cache-ttl, taken out.", L,
c_prefix_expired_.get());
w.counter("radiance:prefix_cache_ckpt_expired_total",
"Prefix-cache linear-state checkpoints taken out by --prefix-cache-ttl.", L,
c_prefix_ckpt_expired_.get());
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
+1
View File
@@ -156,6 +156,7 @@ private:
Counter c_draft_refills_, c_draft_refill_tokens_;
Counter c_attn_cached_, c_linear_cached_, c_checkpoints_;
Counter c_prefix_evict_, c_prefix_ckpt_evict_;
Counter c_prefix_expired_, c_prefix_ckpt_expired_;
Gauge g_linear_hit_;
Counter c_success_[(size_t)SuccessReason::N_];
Counter c_rejected_, c_disconnect_, c_overflow_;
+54 -7
View File
@@ -245,7 +245,11 @@ const char* kAcceptedChat[] = {
"functions", "function_call",
};
const char* kAcceptedCompletion[] = { "prompt", "echo" };
/* `preserved_tokens` is llama-server's: control tokens a raw completion's text keeps. On chat the
* reply format decides them (the guarded entry below); a raw completion has no format, and a
* client that renders its own template and parses its own reply -- a tool-call sidecar -- has no
* other way to see a format built of control tokens. */
const char* kAcceptedCompletion[] = { "prompt", "echo", "preserved_tokens" };
const char* kAcceptedEmbedding[] = { "model", "input", "messages", "encoding_format",
"dimensions", "image_tokens", "prompt_name" };
@@ -1233,6 +1237,15 @@ static int json_text_depth(const std::string& s) {
return most;
}
/* A STRING THAT PARSES INTO A TREE DEEPER THAN THE BOUND. Only valid JSON becomes a tree: text
* that is not JSON never becomes one (a tool result that does not parse is rendered as the
* string it is), so its brackets are not nesting, however they count. The count
* runs first and the validation (json::accept, which builds nothing and does not recurse) only
* when it is over. */
static bool json_text_too_deep(const std::string& s) {
return json_text_depth(s) > kJsonMaxDepth && json::accept(s);
}
/* STRINGS THE CHAT TEMPLATE PARSES AS JSON are bounded like the body is (parse_json_bounded). An
* assistant message's tool-call arguments and a tool message's content arrive as strings, one
* level deep in the request, and the template layer parses them into trees and serialises those
@@ -1248,7 +1261,7 @@ static int check_template_json(const json& msg, const std::string& role, ApiErro
if (fn == tc.end() || !fn->is_object()) continue;
auto args = fn->find("arguments");
if (args != fn->end() && args->is_string() &&
json_text_depth(args->get_ref<const std::string&>()) > kJsonMaxDepth) {
json_text_too_deep(args->get_ref<const std::string&>())) {
*err = err_bad("messages[].tool_calls[].function.arguments",
"nests more than " + std::to_string(kJsonMaxDepth) +
" levels deep");
@@ -1260,7 +1273,7 @@ static int check_template_json(const json& msg, const std::string& role, ApiErro
if (role == "tool") {
auto c = msg.find("content");
if (c != msg.end() && c->is_string() &&
json_text_depth(c->get_ref<const std::string&>()) > kJsonMaxDepth) {
json_text_too_deep(c->get_ref<const std::string&>())) {
*err = err_bad("messages[].content", "a tool result nests more than " +
std::to_string(kJsonMaxDepth) +
" levels deep");
@@ -1613,9 +1626,18 @@ static int parse_thinking_budget(const json& b, const OaiDeps& d, const OaiLimit
if (!render.think_open.empty()) o = d.tok->encode(render.think_open, false, true);
n_close = c.size();
n_open = o.size();
if (c.size() == 1 && (render.think_starts_open || o.size() == 1)) {
/* AN OPENER THAT IS ONE CONTROL TOKEN AND THEN TEXT -- Gemma 4's `<|channel>thought` --
* is found by that first token: it is what a reply opening its own block writes first,
* and no text can be. The text after it counts as reasoning, as the markers do. An opener
* with a second control token in it (a channel and a message marker) is not read this
* way, since its first token may open something other than the reasoning. */
bool open_first = o.size() > 1 && d.tok->reply_bytes(o[0]).empty() &&
!d.tok->token_bytes(o[0]).empty();
for (size_t i = 1; open_first && i < o.size(); ++i)
if (d.tok->reply_bytes(o[i]).empty()) open_first = false;
if (c.size() == 1 && (render.think_starts_open || o.size() == 1 || open_first)) {
span.close = c[0];
span.open = o.size() == 1 ? o[0] : -1;
span.open = (o.size() == 1 || open_first) ? o[0] : -1;
span.starts_open = render.think_starts_open;
}
}
@@ -1654,8 +1676,8 @@ static int parse_thinking_budget(const json& b, const OaiDeps& d, const OaiLimit
"as one token";
else
why = "this reply has to open its own reasoning block, and the opener `" +
render.think_open + "` is " + std::to_string(n_open) + " tokens, so the block "
"cannot be found by token";
render.think_open + "` is " + std::to_string(n_open) + " tokens and does not "
"start with a lone control token, so the block cannot be found by token";
*err = err_unsupported(named, why);
return RAD_E_UNSUPPORTED;
}
@@ -2135,6 +2157,29 @@ int parse_completion_request(const std::string& body, const OaiDeps& d, const Oa
if (!get_bool(b, "echo", &out->echo, err)) return RAD_E_INVAL;
/* The control tokens this completion's text keeps (llama-server's field): each string is
* tokenised by the decoder and every control token in it is rendered rather than dropped.
* Bounded as the stop strings are, since the decoder looks each one up per token. */
{
auto pt = b.find("preserved_tokens");
if (pt != b.end() && !pt->is_null()) {
if (!pt->is_array() || pt->size() > (size_t)lim.max_stops) {
*err = err_bad("preserved_tokens", "expected an array of at most " +
std::to_string(lim.max_stops) + " strings");
return RAD_E_INVAL;
}
for (const auto& s : *pt) {
if (!s.is_string() || s.get<std::string>().size() > (size_t)lim.max_stop_bytes) {
*err = err_bad("preserved_tokens", "expected strings of at most " +
std::to_string(lim.max_stop_bytes) +
" bytes");
return RAD_E_INVAL;
}
out->preserved_tokens.push_back(s.get<std::string>());
}
}
}
RAD_TRY(parse_logprobs(b, lim, Endpoint::Completion, out, err));
/* `echo` with logprobs asks for the PROMPT's logprobs too, which are not computed: a prompt
* position's distribution never leaves the card. */
@@ -2569,6 +2614,8 @@ json timings_json(const TimingsOut& t) {
o["predicted_ms"] = t.predicted_ms;
o["predicted_per_token_ms"] = per(t.decode_n, t.predicted_ms);
o["predicted_per_second"] = rate(t.decode_n, t.predicted_ms);
o["ttft_ms"] = t.ttft_ms >= 0.0 ? json(t.ttft_ms) : json(nullptr);
o["total_ms"] = t.total_ms >= 0.0 ? json(t.total_ms) : json(nullptr);
if (t.draft_n > 0) {
o["draft_n"] = t.draft_n;
o["draft_n_accepted"] = t.draft_n_accepted;
+7
View File
@@ -138,6 +138,7 @@ struct OaiRequest {
int n_tools = 0;
std::string last_user;
std::string peer; /* the handler sets it from the transport; "" in-process */
int64_t t_received_ns = -1; /* HttpRequest::t_received_ns, for timings' ttft and total */
bool parse_tools = false;
/* The reply parser this request's render produced. Per request and not per server: it is the
* model's format bound to the tools THIS call sent, so two concurrent requests against the
@@ -362,6 +363,11 @@ struct UsageOut {
* draft_n, draft_n_accepted
* speculative tokens proposed for this request and accepted; present when any
* were proposed, as llama.cpp does
* ttft_ms from the moment the server had the whole request body to the first token: the
* parse, the chat template, tokenisation, the wait for admission and the prefill.
* The time the body took to arrive is not in it, so a client far from the server
* reads the server's own share of what it measured
* total_ms from the same moment to the last token
*
* The rates divide the tokens by the time that produced them: prompt_n by prompt_ms, and the
* predicted_n - 1 tokens after the first by predicted_ms, since the first token is the prompt
@@ -376,6 +382,7 @@ struct TimingsOut {
int64_t decode_n = 0; /* of predicted_n, the tokens after each choice's first */
double predicted_ms = 0.0;
int64_t draft_n = 0, draft_n_accepted = 0;
double ttft_ms = -1.0, total_ms = -1.0; /* < 0: the body's arrival is not known */
};
/* `timings` is added at the top level when it is valid. */
+17 -10
View File
@@ -635,8 +635,9 @@ UsageOut Server::usage_of(const OaiRequest& r, const std::vector<Generation>& ge
/* WHERE THE REQUEST'S TIME WENT, from its sinks: one for a choice's final chunk, all of them for
* the request. Every time is moved onto one clock first -- each sink counts from its own
* construction. See TimingsOut for what each field means. */
TimingsOut Server::timings_of(const Sink* const* sinks, size_t n) {
* construction, and `received_ns` (the body's arrival, -1 when unknown) is on that clock already.
* See TimingsOut for what each field means. */
TimingsOut Server::timings_of(const Sink* const* sinks, size_t n, int64_t received_ns) {
TimingsOut t;
int64_t admit = INT64_MAX, first_lo = INT64_MAX, first_hi = INT64_MIN, last = INT64_MIN;
bool admitted = true;
@@ -662,14 +663,18 @@ TimingsOut Server::timings_of(const Sink* const* sinks, size_t n) {
if (!t.valid) return t;
if (admitted) t.prompt_ms = (double)(first_hi - admit) * 1e-6;
t.predicted_ms = (double)(last - first_lo) * 1e-6;
if (received_ns >= 0) {
t.ttft_ms = (double)(first_lo - received_ns) * 1e-6;
t.total_ms = (double)(last - received_ns) * 1e-6;
}
return t;
}
TimingsOut Server::timings_of(const std::vector<Generation>& gens) {
TimingsOut Server::timings_of(const std::vector<Generation>& gens, int64_t received_ns) {
std::vector<const Sink*> v;
v.reserve(gens.size());
for (const auto& g : gens) v.push_back(g.sink.get());
return timings_of(v.data(), v.size());
return timings_of(v.data(), v.size(), received_ns);
}
/* ------------------------------------------------------------------ metrics bookkeeping */
@@ -722,7 +727,7 @@ void Server::record(const OaiRequest& r, const std::vector<Generation>& gens, Fi
/* THE OTHER HALF OF THE REQUEST LOG. The same figures /metrics aggregates, for this one
* request: how it ended, what the prefix cache spared, the reasoning share when the parser
* knows it, time to first token, the decode rate after it, and the whole. */
const TimingsOut t = timings_of(gens);
const TimingsOut t = timings_of(gens, r.t_received_ns);
const UsageOut u = usage_of(r, gens);
const double rate = (decode > 0.0 && n_gen > 1) ? (double)(n_gen - 1) / decode : -1.0;
char reason[32] = "";
@@ -740,6 +745,7 @@ void Server::record(const OaiRequest& r, const std::vector<Generation>& gens, Fi
/* ------------------------------------------------------------------ non-streaming */
HttpResponse Server::blocking_completion(const HttpRequest& req, OaiRequest& r) {
r.t_received_ns = req.t_received_ns;
std::vector<Generation> gens;
ApiError err;
if (submit_all(r, &gens, &err) < 0) {
@@ -846,7 +852,7 @@ HttpResponse Server::blocking_completion(const HttpRequest& req, OaiRequest& r)
retire(gens);
release(r.n_choices());
const TimingsOut timings = timings_of(gens);
const TimingsOut timings = timings_of(gens, r.t_received_ns);
if (r.shape == ApiShape::LlamaNative) {
/* llama-server answers one result, and an array of them for several prompts. */
json res = json::array();
@@ -918,7 +924,7 @@ static const char* native_stop_type(Finish f) {
* in the chunks before it. */
json Server::native_result(const OaiRequest& r, const Generation& g, const std::string& content) {
const Sink* one = g.sink.get();
const TimingsOut t = timings_of(&one, 1);
const TimingsOut t = timings_of(&one, 1, r.t_received_ns);
const int64_t n_prompt = (int64_t)r.prompts[(size_t)g.prompt_index].tokens.size();
nlohmann::ordered_json o;
o["index"] = g.index;
@@ -1014,6 +1020,7 @@ static std::string progress_chunk(const OaiRequest& r, int index, const Sink& s)
}
HttpResponse Server::streaming_completion(const HttpRequest& req, OaiRequest& r) {
r.t_received_ns = req.t_received_ns;
auto st = std::make_shared<StreamState>();
st->r = r;
st->peer_closed = req.closed;
@@ -1121,7 +1128,7 @@ HttpResponse Server::streaming_completion(const HttpRequest& req, OaiRequest& r)
TimingsOut now;
if (st->r.timings_per_token) {
const Sink* one = g.sink.get();
now = timings_of(&one, 1);
now = timings_of(&one, 1, st->r.t_received_ns);
if (g.delta) g.delta->set_timings(now);
}
if (st->r.endpoint == Endpoint::Chat) {
@@ -1172,7 +1179,7 @@ HttpResponse Server::streaming_completion(const HttpRequest& req, OaiRequest& r)
/* EACH CHOICE'S OWN TIMINGS ON ITS FINAL CHUNK, so a client that asked for no
* usage chunk still has them, as llama.cpp sends them. */
const Sink* one = g.sink.get();
const TimingsOut gt = timings_of(&one, 1);
const TimingsOut gt = timings_of(&one, 1, st->r.t_received_ns);
/* A failed generation cannot become a non-200 -- the headers left long ago -- so
* it travels as an error event in the stream. Silence would look like a normal
* end of stream and the client would use a truncated answer. */
@@ -1212,7 +1219,7 @@ HttpResponse Server::streaming_completion(const HttpRequest& req, OaiRequest& r)
* 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) {
const TimingsOut t = timings_of(st->gens);
const TimingsOut t = timings_of(st->gens, st->r.t_received_ns);
out += st->r.endpoint == Endpoint::Chat ? chat_usage_chunk(st->r, u, t)
: text_usage_chunk(st->r, u, t);
}
+2 -2
View File
@@ -189,8 +189,8 @@ private:
struct StreamState;
static UsageOut usage_of(const OaiRequest& r, const std::vector<Generation>& gens);
static TimingsOut timings_of(const Sink* const* sinks, size_t n);
static TimingsOut timings_of(const std::vector<Generation>& gens);
static TimingsOut timings_of(const Sink* const* sinks, size_t n, int64_t received_ns);
static TimingsOut timings_of(const std::vector<Generation>& gens, int64_t received_ns);
void register_routes();