radiance 1.3.0

- #47: llama-server's request fields, routes and sampler order, and /props (with baKon's model
  entry: max_model_len, root and capabilities on /v1/models, and /v1/models/:id)
- new APIs: Anthropic's Messages API (/v1/messages), OpenAI's Responses API (/v1/responses),
  llama-server's /completion and /infill, logprobs (OpenAI's logprobs and top_logprobs, up to
  20; llama-server's n_probs), OpenAI's legacy `functions`, and X-Api-Key beside the bearer key
- #4: --model takes a Hugging Face repo id (owner/name), fetched before startup into
  ~/.cache/radiance/hf or --download-dir and checked for changes at every start (redxherring)
- #46: --tp 3 --tp-wire wht6 serves -- a three-rank two-shot all-reduce with uneven shards and
  the tiered-int8 wire over it (baKon); scripts/cardclock.py names what holds each card's clock
  under load (baKon)
- CPU-only serving works again; --kernels names the kernel libraries to load; a model the
  loaded libraries cannot fully serve refuses at startup instead of failing its first request;
  --vram-kv-mib and --vram-weights-mib are gone (the split is automatic)
- --embedding-placement ram is the default, and `auto` is gone
- #40: Swift 1.5 recipes; rad-convert reads which shard holds a tensor from the index
- #53: the pinned host pool gets huge pages where shmem THP is off; #57: a crash on video with
  an odd frame width is fixed
This commit is contained in:
Deadcode committed 2026-10-08 18:22:08 +02:00
1 parent 6a2ee986d6
commit 89cee7ce41
107 files changed
+6849 -1091

No files matched your search

+28 -12
View File
@@ -10,6 +10,7 @@
* and have fusion be a selection rather than a compiler pass (spec §2.3).
*/
#include "rad_build.h"
#include "../device/device.h"
#include <algorithm>
#include <climits>
@@ -45,6 +46,26 @@ std::string Program::Miss::line() const {
why.c_str());
}
std::vector<const Program::Miss*> Program::device_holes(bool host_backend) const {
/* By INSTANCE, because bands are: two declarations of one op can differ in geometry and in
* whether they carry a weight, and only the instance that missed decides whether the planner
* can move it to the host. */
std::set<std::pair<int32_t, std::string>> no_host;
for (const Miss& m : misses)
if (m.domain == RAD_DOMAIN_HOST) no_host.emplace(m.index, m.span);
std::vector<const Miss*> out;
for (const Miss& m : misses) {
if (m.domain == RAD_DOMAIN_HOST) continue;
const bool host_kernel = no_host.count(std::make_pair(m.index, m.span)) == 0;
/* An instance with no weight has nothing the planner places, so nothing moves it. */
const bool weightless = m.index > 0 && (size_t)m.index < ops.size() &&
ops[(size_t)m.index].weights.empty();
if (host_kernel && (host_backend || !weightless)) continue;
out.push_back(&m);
}
return out;
}
const char* bld_access_name(int a) {
switch (a) {
case RAD_ACCESS_PER_TOKEN: return "per-token";
@@ -565,7 +586,7 @@ void Builder::resolve_bands(OpInfo& oi) {
* reports the list whole (spec §3.1). */
prog_.misses.push_back({ oi.op, display_geometry(oi, b).str(), b.span,
b.miss[d].empty() ? "no kernel matched" : b.miss[d],
d });
d, oi.index });
continue;
}
@@ -616,7 +637,7 @@ void Builder::finish_instances() {
r.geom.str().c_str(), rad_strerror(s));
b.miss[d] = fmt("init() refused the instance: %s", rad_strerror(s));
prog_.misses.push_back({ oi.op, display_geometry(oi, b).str(), b.span,
b.miss[d], d });
b.miss[d], d, oi.index });
r = Resolved{};
}
}
@@ -1621,16 +1642,11 @@ int Builder::finish() {
* SPLIT BY DOMAIN, because the two counts mean different things and one total means
* neither. Every caller of this that is not the engine -- rad-check, rad-tune, rad-convert
* -- reads this line and nothing else, so it has to say which kind it found. */
/* A device miss whose op resolved on the HOST for the same band is not a hole -- the
* planner runs it there (engine_bringup.cpp's miss_report says the same thing at more
* length). Counting it as a device miss makes a deliberately host-only op open every run
* with a warning that names a hole there is not. */
std::set<std::pair<std::string, std::string>> no_host;
for (const Program::Miss& m : prog_.misses)
if (m.domain == RAD_DOMAIN_HOST) no_host.emplace(m.op, m.span);
size_t dev = 0;
for (const Program::Miss& m : prog_.misses)
if (m.domain != RAD_DOMAIN_HOST && no_host.count(std::make_pair(m.op, m.span))) ++dev;
/* A device miss a host kernel stands in for is not a hole -- the planner runs it there
* (Program::device_holes has the rule, engine_bringup.cpp's miss_report the longer
* account). Counting it as a device miss makes a deliberately host-only op open every
* run with a warning that names a hole there is not. */
const size_t dev = prog_.device_holes(device_is_host()).size();
/* A host-only miss set is not a warning at all -- see the report in engine_bringup.cpp --
* so it does not get warned about here either. The device count is the one that means
* something to a tool reading this line and nothing else. */
+46 -19
View File
@@ -39,10 +39,13 @@ static const std::string g_draft_window_help =
draft_window_name(kDraftWindowDefault);
static const Flag g_flags[] = {
{ "--model", "PATH|REPO", "the .rad container, a checkpoint served as it stands, or an HF repo id (owner/name) fetched to the cache" },
{ "--model", "PATH", "the .rad container, a checkpoint served as it stands, or a\n"
"Hugging Face repo id (owner/name), fetched before startup" },
{ "--download-dir", "DIR", "where a repo id is fetched to; default\n"
"$XDG_CACHE_HOME/radiance/hf, else ~/.cache/radiance/hf" },
{ "--radiance-home", "DIRS", "where kernels/, architectures/ and quantizers/ live; several\n"
"homes separated by ':' are searched in order, the first winning" },
{ "--kernels", "LIST", "kernel plugin hierarchy, comma-separated, first wins" },
{ "--kernels", "LIST", "the kernel libraries to use, comma-separated, first wins; unnamed ones are not loaded. Default: every library found" },
{ "--tp", "N", "tensor-parallel ranks" },
{ "--tp-wire", "MODE", "cross-rank all-reduce payload: exact (default) or wht6, a\n"
@@ -59,15 +62,12 @@ static const Flag g_flags[] = {
"keys, no reconvert (docs/YARN.md); none: off" },
{ "--gpu-headroom-mib", "N", "VRAM left unclaimed on every card (default 96)" },
{ "--vram-weights-mib", "N", "the resident weight slab; 0 derives it from the card" },
{ "--vram-kv-mib", "N", "the paged KV pool; 0 derives it from the card" },
{ "--kv-cache-dtype", "T", "bf16 | fp8 -- fp8 halves what a token of context costs" },
{ "--host-pool-mib", "N", "pinned host tier" },
{ "--embedding-placement", "WHERE", "auto (default) | vram | ram: where the token embedding lives. ram\n"
" keeps it in the pinned host pool, read over the link in place;\n"
" auto keeps it on the card unless the KV cache could then not\n"
" hold one --max-model-len sequence. disk is refused: the lookup\n"
" writes the card's activations, which no host read can reach" },
{ "--embedding-placement", "WHERE", "ram (default) | vram: where the token embedding lives. ram\n"
" pins it in host memory beside --host-pool-mib, read over the\n"
" link in place; by default a model whose output head reads the\n"
" table, or a host without the memory, keeps it on the card" },
{ "--ngram-placement", "WHERE", "auto (default) | vram | ram | disk: where an n-gram\n"
" embedding table lives (Qwen3.8-Flash-Next: 47.7 GiB).\n"
" vram puts all of it on every card; ram copies it into\n"
@@ -226,10 +226,19 @@ static const Flag g_flags[] = {
void config_usage(const char* argv0) {
fprintf(stderr, "usage: %s --model FILE [options]\n\n", argv0);
/* A help text's continuation lines start under its first line, whatever indentation the
* string itself carries. */
for (const Flag& f : g_flags) {
char left[64];
snprintf(left, sizeof left, "%s%s%s", f.name, f.arg ? " " : "", f.arg ? f.arg : "");
fprintf(stderr, " %-32s %s\n", left, f.help);
std::string help;
for (const char* p = f.help; *p; ++p) {
help += *p;
if (*p != '\n') continue;
help.append(35, ' ');
while (p[1] == ' ') ++p;
}
fprintf(stderr, " %-32s %s\n", left, help.c_str());
}
fprintf(stderr,
"\nEvery pool is budgeted explicitly. The trade between KV blocks and resident weights\n"
@@ -376,6 +385,7 @@ int config_parse(int argc, char** argv, Config* c) {
else if (S("-v")) log_set_level(Log::Debug);
else if (S("-vv")) log_set_level(Log::Trace);
else if (S("--model")) { if (!(v = need(i))) return RAD_E_INVAL; c->model = v; }
else if (S("--download-dir")) { if (!(v = need(i))) return RAD_E_INVAL; c->download_dir = v; }
else if (S("--radiance-home")) { if (!(v = need(i))) return RAD_E_INVAL; c->radiance_home = v; }
else if (S("--kernels")) { if (!(v = need(i))) return RAD_E_INVAL; c->kernel_hierarchy = split_commas(v); }
else if (S("--tp")) { if (!(v = need(i))) return RAD_E_INVAL; c->tp = atoi(v); }
@@ -408,8 +418,16 @@ int config_parse(int argc, char** argv, Config* c) {
}
c->rope_scaling = v;
}
else if (S("--vram-weights-mib")) { if (!(v = need(i))) return RAD_E_INVAL; c->vram_weights_mib = atoll(v); }
else if (S("--vram-kv-mib")) { if (!(v = need(i))) return RAD_E_INVAL; c->vram_kv_mib = atoll(v); }
/* THE TWO POOLS ARE THE BUDGET RESOLVER'S, always (core/mem/vram_budget.h). A launch
* line that tries to size them is told which flags move the split, rather than "unknown
* option". */
else if (S("--vram-weights-mib") || S("--vram-kv-mib")) {
RAD_ERR("%s was removed: the card is split between the weights and the cache from what "
"the model needs. --gpu-headroom-mib takes card space away, --max-model-len and "
"--max-num-seqs bound the cache, and --host-pool-mib decides which experts stay "
"on the card", a.c_str());
return RAD_E_INVAL;
}
/* --gpu-headroom takes the short name too: it is the flag an operator reaches for and
* "-mib" is the unit, which every other size flag in this list also spells out. Both
* parse to the same field. */
@@ -428,11 +446,20 @@ int config_parse(int argc, char** argv, Config* c) {
const bool emb = S("--embedding-placement");
if (!(v = need(i))) return RAD_E_INVAL;
TablePlacement p;
if (!parse_table_placement(v, &p)) {
/* The embedding has two tiers: its lookup writes activations the card reads, which a
* host kernel reading the container cannot reach, so there is no disk -- and with
* ram the default wherever it can be honoured, nothing left for auto to choose. */
if (emb && (!parse_table_placement(v, &p) ||
(p != TablePlacement::Ram && p != TablePlacement::Vram))) {
RAD_ERR("--embedding-placement takes ram or vram, not '%s'", v);
return RAD_E_INVAL;
}
if (!emb && !parse_table_placement(v, &p)) {
RAD_ERR("%s takes auto, vram, ram or disk, not '%s'", a.c_str(), v);
return RAD_E_INVAL;
}
(emb ? c->embedding_placement : c->ngram_placement) = p;
if (emb) c->embedding_placement_given = true;
}
else if (S("--weights-disk-tier")) { c->weights_disk_tier = true; }
else if (S("--prefix-cache-host-mib")) { if (!(v = need(i))) return RAD_E_INVAL; c->prefix_cache_host_mib = atoll(v); }
@@ -735,12 +762,12 @@ int config_parse(int argc, char** argv, Config* c) {
* rank the one that IS installed behind the reference implementation, which matches every op
* and would answer for all of them.
*
* An empty hierarchy is not "no order". The loader orders what it finds: everything named by
* --kernels or RADIANCE_KERNELS first, then every other plugin, then the reference library
* last by construction because it matches anything (core/plugin/loader.cpp). So dropping a
* kernel library into $RADIANCE_HOME/kernels is enough to be used, on any card, with no
* configuration -- and naming one ahead of another is what settles a tie between two that
* both serve an op. */
* An empty hierarchy is not "no order". The loader loads everything it finds and orders it,
* the reference library last by construction because it matches anything
* (core/plugin/loader.cpp). So dropping a kernel library into $RADIANCE_HOME/kernels is
* enough to be used, on any card, with no configuration. A list names the libraries to use:
* only those load, in its order, so naming one ahead of another settles a tie between two that
* both serve an op and leaving one out keeps it out. */
if (c->model.empty()) {
RAD_ERR("--model is required");
return RAD_E_INVAL;
+35 -6
View File
@@ -57,6 +57,7 @@
#include <cstring>
#include <memory>
#include <deque>
#include <fstream>
#include <map>
#include <mutex>
#include <new>
@@ -2085,10 +2086,17 @@ int a_vmem_decommit(void* addr, int64_t bytes) {
* process takes is the runtime's HSA_AMD_SYSTEM_INFO_SVM_SUPPORTED, the same capability the thunk
* decides by, and the log says it once.
*
* What hipHostMalloc does besides the pin is kept, so the pages are the same pages: shared
* anonymous memory, huge pages advised from 2 MiB up, a preferred NUMA node that is the one
* nearest the current card (ROCr allocates from that node's pool), fine-grained coherence (the
* pool locked to), and access from every card.
* What hipHostMalloc does besides the pin is kept: huge pages advised from 2 MiB up, a preferred
* NUMA node that is the one nearest the current card (ROCr allocates from that node's pool),
* fine-grained coherence (the pool locked to), and access from every card. The memory is PRIVATE
* anonymous memory and not hipHostMalloc's shared kind, because the advice is only as good as the
* policy behind it: shared anonymous memory is shmem, whose huge pages follow
* transparent_hugepage/shmem_enabled, `never` on stock Ubuntu, so the pool got 4 KiB pages there
* whatever it advised. Private memory follows transparent_hugepage/enabled, `madvise` on the same
* hosts. Where an IOMMU translates the cards' reads (Intel VT-d, which these pieces exist for) each
* page is a translation of its own, and a pool streamed from at 4 KiB measured 10-21% slower
* prefill on such a host. MADV_DONTFORK keeps the range out of any child: a private range
* a card has pinned is copied whole into a forked child, where it is of no use.
*
* kPinPiece is a power of two well under the failing size. The cost is one buffer object per piece
* per card: a few dozen for the largest pools. */
@@ -2133,6 +2141,21 @@ void prefer_numa_node(void* p, int64_t len, int node) {
std::strerror(errno));
}
/* TRANSPARENT HUGE PAGES TURNED OFF leave every pinned range at 4 KiB pages whatever it advises:
* said once, because on a host whose IOMMU translates the cards' reads that is a slower stream
* from the host pool and nothing else on the log points at it. */
void warn_if_no_huge_pages() {
static std::atomic<bool> said{false};
if (said.exchange(true)) return;
std::ifstream f("/sys/kernel/mm/transparent_hugepage/enabled");
std::string mode;
if (!std::getline(f, mode) || mode.find("[never]") == std::string::npos) return;
RAD_WARN("device: transparent huge pages are off (/sys/kernel/mm/transparent_hugepage/enabled "
"is never), so pinned host memory gets 4 KiB pages; where an IOMMU translates the "
"cards' reads, streaming from the host pool is slower. 'madvise' gives the pinned "
"ranges huge pages and nothing else.");
}
const char* hsa_why(hsa_status_t st) {
const char* m = nullptr;
return hsa_status_string(st, &m) == HSA_STATUS_SUCCESS && m ? m : "unknown HSA status";
@@ -2193,7 +2216,7 @@ void* pin_pieces(int64_t bytes) {
/* One alignment over, trimmed at both ends, so the range starts on a 2 MiB boundary: a pool's
* fixed-stride slots inherit its base alignment, and a huge page needs it. */
void* m = ::mmap(nullptr, (size_t)(len + align), PROT_READ | PROT_WRITE,
MAP_SHARED | MAP_ANONYMOUS, -1, 0);
MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (m == MAP_FAILED) {
device_set_error("rad_dev_alloc(%s): mmap: %s", humanb(bytes).c_str(), std::strerror(errno));
return nullptr;
@@ -2205,7 +2228,11 @@ void* pin_pieces(int64_t bytes) {
char* const p = (char*)at;
prefer_numa_node(p, len, current_card_numa_node());
if (len >= ((int64_t)2 << 20)) ::madvise(p, (size_t)len, MADV_HUGEPAGE);
if (len >= ((int64_t)2 << 20)) {
::madvise(p, (size_t)len, MADV_HUGEPAGE);
warn_if_no_huge_pages();
}
(void)::madvise(p, (size_t)len, MADV_DONTFORK);
const int pieces = (int)((len + kPinPiece - 1) / kPinPiece);
int done = 0;
@@ -2343,6 +2370,8 @@ DeviceBackend g_aql;
} // namespace
size_t aql_code_registered(void) { return a_code_mark(); }
const DeviceBackend* aql_backend_if_present(void) {
static const DeviceBackend* b = []() -> const DeviceBackend* {
const DeviceBackend* hip = hip_backend_if_present();
+4
View File
@@ -376,6 +376,10 @@ const DeviceBackend* hip_backend_if_present(void);
const DeviceBackend* aql_backend_if_present(void);
/* Bytes copied to or from pageable host memory so far: every such copy is a host wait. */
int64_t aql_pageable_bytes(void);
/* The fat binaries registered so far, counted whichever backend runs: the registration hooks are
* this build's own exported symbols and see every dlopen'ed kernel plugin's device code, card or
* no card. The host backend's code_mark in a HIP build. */
size_t aql_code_registered(void);
#endif
/* ------------------------------------------------------------------ the error slot */
+14 -1
View File
@@ -87,6 +87,15 @@ static void warn_cwsr_off() {
"amdgpu.cwsr_enable=1 (module option, then rebuild the initramfs and reboot)");
}
#if defined(RAD_HAVE_HIP) && RAD_HAVE_HIP
/* THE HOST BACKEND IN A BUILD THAT HAS HIP STILL COUNTS THE GPU CODE PLUGINS BRING. The
* registration hooks are this build's own exported symbols and see every dlopen'ed kernel
* library's fat binaries, card or no card, so the plugin loader can bracket each dlopen and know
* which library brought device code. An engine serving here leaves that library's device rows out
* of selection (Registry::set_no_device_code); a tool that only selects keeps them. */
static DeviceBackend g_host_beside_hip;
#endif
static const DeviceBackend* select_backend() {
#if defined(RAD_HAVE_HIP) && RAD_HAVE_HIP
if (const DeviceBackend* b = aql_backend_if_present()) {
@@ -96,8 +105,12 @@ static const DeviceBackend* select_backend() {
return b;
}
RAD_INFO("device: built with HIP but no device is visible -- using the host backend");
#endif
g_host_beside_hip = *host_backend();
g_host_beside_hip.code_mark = aql_code_registered;
const DeviceBackend* b = &g_host_beside_hip;
#else
const DeviceBackend* b = host_backend();
#endif
RAD_INFO("device: host backend, %d device(s) [%s]", b->count(), device_inventory(b).c_str());
return b;
}
+28
View File
@@ -867,6 +867,10 @@ int Engine::step_loop() {
res.n_accepted = so.accepted.data();
res.token = so.token.data();
res.eos = so.eos.data();
if (!so.lp.empty()) {
res.lp = so.lp.data();
res.first_row = so.first_row.data();
}
st = sched_.commit(res);
if (t_on) phase_mark(PH_COMMIT);
if (st < 0) { RAD_ERR("commit: %s", rad_strerror(st)); return fail_loop(st); }
@@ -1000,6 +1004,20 @@ int Engine::collect_pooled(const RadBatch* b, StepOut& so) {
return RAD_OK;
}
/* One sampled row's logprobs into the step's table, which is sized on the first row that asks.
* A ROW WHOSE LOGPROBS CANNOT BE COMPUTED FAILS ITS REQUEST, NOT THE STEP: its numbers are not
* finite (RAD_E_INVAL), so its entry is left at token -1 (TokenLogprobs), which the scheduler
* answers by failing that request with the reason, and every other sequence in the batch goes on.
* A row outside the step, or one that was never staged for logprobs, is the engine's own fault. */
int Engine::row_logprobs(StepOut& so, int32_t row, int32_t token) {
if (so.lp.empty()) so.lp.resize((size_t)so.n_rows);
if (row < 0 || row >= so.n_rows) return RAD_E_STATE;
TokenLogprobs& lp = so.lp[(size_t)row];
const int s = ranks_[0]->sampler.logprobs_for(row, token, &lp);
if (s == RAD_E_INVAL) { lp = TokenLogprobs{}; return RAD_OK; }
return s;
}
/* Wait for the sampled ids and turn them into the three per-sequence arrays the scheduler wants.
* This is the ONE host synchronisation on the step path: the host needs the tokens to commit them
* and to stream them. Everything else in a step is enqueued and never waited on (spec §5.4). */
@@ -1008,6 +1026,7 @@ int Engine::collect_step(const RadBatch* b, StepOut& so) {
so.token.assign(plan.e.size(), 0);
so.accepted.assign(plan.e.size(), 0);
so.eos.assign(plan.e.size(), 0);
so.lp.clear();
if (so.n_rows <= 0) return RAD_OK;
so.rows.resize((size_t)so.n_rows);
@@ -1097,6 +1116,11 @@ int Engine::collect_step(const RadBatch* b, StepOut& so) {
so.accepted[i] = acc;
so.token[i] = out[acc];
so.eos[i] = vocab_ && vocab_->is_eog(so.token[i]) ? 1 : 0;
/* Each emitted token's logprobs from its own row: an accepted draft is the token the
* target drew at its position, so its row is the distribution it came from. */
if (e.req && e.req->sp.n_probs >= 0)
for (int32_t j = 0; j <= acc; ++j)
RAD_TRY(row_logprobs(so, so.first_row[i] + j, out[j]));
/* EVERY token that leaves, in order: the grammar's state has to advance over the
* accepted drafts too, or the next step's mask is built n_accepted tokens behind.
* Bounded by the truncated `acc`, so it sees exactly the tokens the client does. */
@@ -1122,6 +1146,8 @@ int Engine::collect_step(const RadBatch* b, StepOut& so) {
}
so.token[i] = so.rows[(size_t)so.first_row[i]];
so.eos[i] = vocab_ && vocab_->is_eog(so.token[i]) ? 1 : 0;
if (e.req && e.req->sp.n_probs >= 0)
RAD_TRY(row_logprobs(so, so.first_row[i], so.token[i]));
/* The grammar must see the token it just emitted, or the next step's mask is built from a
* state one token behind the sequence. EVERY rank, not just rank 0: each rank builds the
* mask for its own vocabulary shard from its own automaton, so a rank whose grammar did
@@ -2270,6 +2296,8 @@ int Engine::run_server() {
o.default_thinking_budget = cfg_.thinking_token_budget;
o.default_sampling = resolve_sampling_defaults(meta_, file_ != nullptr, cfg_);
o.default_dry_breakers_set = cfg_.sample_dry_seq_breakers.has_value();
/* An embedding model samples nothing, so it has no logprobs to give. */
o.supports_logprobs = !embedding_ && ranks_[0]->sampler.has_logprobs();
/* -1 leaves ServerOptions' own default, which is `auto` (0). That is resolved per request
* against the context, so it needs one to resolve against. */
if (cfg_.default_max_tokens >= 0) o.default_max_tokens = cfg_.default_max_tokens;
+5 -2
View File
@@ -134,8 +134,7 @@ private:
/* --embedding-placement and --ngram-placement, resolved into Config before the card is split
* (engine_bringup.cpp says how auto chooses). */
int resolve_table_placement(const std::vector<VramFacts>& facts,
const std::vector<int64_t>& emb_bytes,
const std::vector<int64_t>& floor_emb_ram, int64_t kv_floor,
const std::vector<int64_t>& emb_bytes, int64_t kv_floor,
int64_t ngram_bytes, bool ngram_device, bool ngram_host);
/* --ngram-placement ram: the copy of the container's [src, src + n), file offset `foff`, made
* once and shared by every rank -- locked for the host gather, or pinned for a device kernel
@@ -167,6 +166,9 @@ private:
std::vector<int32_t> token; /* [n_seq] */
std::vector<int32_t> accepted; /* [n_seq] */
std::vector<uint8_t> eos; /* [n_seq] */
/* [n_rows] each sampled row's logprobs, for the rows of requests that asked for them;
* empty on a step with none. */
std::vector<TokenLogprobs> lp;
};
/* The text frontend, loaded out of the container. `vocab_view_` is what the sampler's
@@ -238,6 +240,7 @@ private:
* wait left until after them. */
int collect_issue(const RadBatch* b, StepOut& so);
int collect_step(const RadBatch* b, StepOut& so);
int row_logprobs(StepOut& so, int32_t row, int32_t token);
/* WHERE THE STEP ENDS ON THE CARD: after its last draft pass and the copies the host reads,
* and before the step issued ahead of it. collect_step waits for this and not for the
* stream, so the card runs the next step while the host commits this one. */
+135 -117
View File
@@ -52,15 +52,17 @@ namespace rad {
/* ================================================================== the miss report */
/* WHAT DID NOT RESOLVE, in the three shapes the three answers want.
*
* A DEVICE miss WITH NO HOST KERNEL EITHER is a hole. The band exists, a request can land in it,
* and the step that does fails at ISSUE rather than here -- declare completes either way -- so
* every one gets a line of its own carrying the geometry and the constraint that refused it.
* A DEVICE miss NO HOST KERNEL STANDS IN FOR is a hole (Program::device_holes has the rule). The
* band exists and a request can land in it, so the engine refuses to start on one rather than
* serve until the first step that does -- and every one gets a line of its own carrying the
* geometry and the constraint that refused it.
*
* A DEVICE miss whose op DID resolve on the host is not a hole at all. The planner puts that op's
* A DEVICE miss a host kernel stands in for is not a hole at all. The planner puts that op's
* arithmetic on the host and its weights in the container's mapping, which is how `embed_lookup_q`
* serves a table too large to copy into VRAM when no device kernel for it is loaded. Reporting
* that as fatal produces an error nobody believes, and an error nobody believes is how a real one
* goes unread.
* goes unread. An op with no weights has nothing to place, so on a card its host kernel does not
* stand in: paged attention reads a cache in VRAM, and only a device kernel can.
*
* A HOST miss removes ONE placement option for ONE op, and for a kernel library written for a GPU
* it is the ordinary case rather than news: most ops have no host implementation and never will.
@@ -70,7 +72,7 @@ namespace rad {
* with thousands of lines of `E` that are all host misses, and a real device hole is invisible
* among them. */
struct MissReport {
std::vector<std::string> device; /* one line each; fatal at issue */
std::vector<std::string> device; /* one line each; the engine does not start */
std::string host; /* one line, or empty */
/* Device bands whose op DOES have a host kernel. Not a hole: the planner runs such an op on
* the host and pins its weights there (Tier::Mapped), which is the whole of how a table too
@@ -78,29 +80,43 @@ struct MissReport {
* operator has to learn to ignore -- and an error nobody believes is how a real one goes
* unread. */
std::string host_only;
/* A hole is an all-reduce instance declared on the lossy wire (`exact` 0, which the model
* plugin derives from --tp-wire, rad_builder.h). The libraries may serve that world size on
* the exact wire, so the refusal names the flag that asks for it. */
bool lossy_wire = false;
bool operator==(const MissReport& o) const {
return device == o.device && host == o.host && host_only == o.host_only;
return device == o.device && host == o.host && host_only == o.host_only &&
lossy_wire == o.lossy_wire;
}
};
static MissReport miss_report(const Program& p) {
static MissReport miss_report(const Program& p, bool host_backend) {
MissReport r;
std::vector<std::string> host_ops; /* in first-seen order */
std::map<std::string, std::string> host_spans; /* op -> "M <= 64, M in (64, 512]" */
/* (op, band) pairs the HOST could not serve either. A device miss that is in this set is a
* hole; one that is not has a host kernel standing behind it. */
std::set<std::pair<std::string, std::string>> no_host;
const std::vector<const Program::Miss*> holes = p.device_holes(host_backend);
std::set<std::pair<int32_t, std::string>> no_host; /* (instance, band) with no host kernel */
for (const Program::Miss& m : p.misses)
if (m.domain == RAD_DOMAIN_HOST) no_host.emplace(m.op, m.span);
if (m.domain == RAD_DOMAIN_HOST) no_host.emplace(m.index, m.span);
for (const Program::Miss* m : holes) {
long long exact = 1;
if (m->index > 0 && (size_t)m->index < p.ops.size() &&
p.ops[(size_t)m->index].base.get_i("exact", &exact) && exact == 0)
r.lossy_wire = true;
r.device.push_back(m->line());
if (!no_host.count(std::make_pair(m->index, m->span)))
r.device.back() += " (its host kernel cannot stand in: the op has no weights for "
"the planner to place on the host)";
}
std::vector<std::string> host_only_ops;
for (const Program::Miss& m : p.misses) {
if (m.domain != RAD_DOMAIN_HOST) {
if (no_host.count(std::make_pair(m.op, m.span))) r.device.push_back(m.line());
else if (std::find(host_only_ops.begin(), host_only_ops.end(), m.op) ==
host_only_ops.end()) host_only_ops.push_back(m.op);
if (std::find(holes.begin(), holes.end(), &m) == holes.end() &&
std::find(host_only_ops.begin(), host_only_ops.end(), m.op) ==
host_only_ops.end()) host_only_ops.push_back(m.op);
continue;
}
auto it = host_spans.find(m.op);
@@ -234,20 +250,27 @@ static void report_pool_refusal(int rank, int device, const Pools& pools, const
}
/* A refusal with room under both is not a capacity one, and advice to shrink the pool
* would send the reader after the wrong cause: the device's reason above is the answer. */
const int64_t want = (int64_t)cfg.tp * cfg.host_pool_mib * 1024 * 1024 + pinned + mapped;
const int64_t pool = (cfg.host_pool_mib + cfg.embedding_host_mib) * 1024 * 1024;
const int64_t want = (int64_t)cfg.tp * pool + pinned + mapped;
const bool fits = cap > 0 && avail >= 0 && want <= cap && want <= avail;
RAD_ERR("host: --host-pool-mib %lld is pinned once per rank, so %d rank(s) pin %s; this "
RAD_ERR("host: --host-pool-mib %lld%s is pinned once per rank, so %d rank(s) pin %s; this "
"process had taken %s of pinned host memory before rank %d's pool. The amdgpu "
"driver caps pinned memory system-wide at %s (ttm.pages_limit, half of RAM unless "
"raised), and %s of RAM is available. %s",
(long long)cfg.host_pool_mib, cfg.tp,
humanb((int64_t)cfg.tp * cfg.host_pool_mib * 1024 * 1024).c_str(),
(long long)cfg.host_pool_mib,
cfg.embedding_host_mib
? fmt(" and the token embedding's %lld MiB", (long long)cfg.embedding_host_mib).c_str()
: "",
cfg.tp, humanb((int64_t)cfg.tp * pool).c_str(),
humanb(pinned + mapped).c_str(), rank,
cap > 0 ? humanb(cap).c_str() : "an unreadable limit",
avail >= 0 ? humanb(avail).c_str() : "an unknown amount",
fits ? "The pools fit under both, so the refusal is not one of size; the reason "
"the device gave is above"
: "Lower --host-pool-mib, or raise the cap");
: cfg.embedding_host_mib
? "Lower --host-pool-mib, keep the embedding on the card with "
"--embedding-placement vram, or raise the cap"
: "Lower --host-pool-mib, or raise the cap");
}
}
@@ -417,7 +440,8 @@ int Engine::copy_table(const uint8_t* src, int64_t n, int64_t foff, bool card, v
bool Engine::ngram_gather_to_host() {
for (auto& r : ranks_) {
WeightFootprint f;
weight_footprint(r->program, &f, TablePlacement::Vram, TablePlacement::Disk);
weight_footprint(r->program, &f, TablePlacement::Vram, TablePlacement::Disk,
device_is_host(), file_ != nullptr);
if (!f.ngram_host) return false;
}
for (auto& r : ranks_)
@@ -432,78 +456,79 @@ bool Engine::ngram_gather_to_host() {
/* WHERE THE TWO LOOKUP TABLES GO (--embedding-placement, --ngram-placement), decided once for every
* rank before the card is split, and written into Config for the planner and the load phase.
*
* THE EMBEDDING: Auto keeps it on the card -- where every other weight a step reads lives --
* unless that leaves the split unable to hold the fixed weights, or leaves a derived KV pool
* unable to hold one --max-model-len sequence (`kv_floor`); then the pinned host pool takes it if
* --host-pool-mib can, the card's lookup reading it over the link in place. Disk is refused: the
* THE EMBEDDING: Ram, the default, pins it in host memory of its own beside --host-pool-mib
* (Config::embedding_host_mib), the card's lookup reading its M rows a step over the link in
* place, so its VRAM goes to the KV cache and the experts. Where it cannot -- a model whose output
* head is tied to the table reads it whole every step, and a host without the memory has nowhere
* to pin it -- the default keeps it on the card and says why, and a named `ram` stops the server.
* Vram keeps it on the card with every other weight a step reads. There is no third tier: the
* lookup writes the activations a card reads, which a host kernel reading the container cannot
* reach -- an architecture declares a buffer's domain, and the token embedding's is the device.
*
* THE N-GRAM TABLE: Vram where a device kernel gathers it and the card holds it; Ram as a copy,
* pinned for that kernel to read over the link or locked for the host gather; Disk in the
* container, read by the host gather. Each tier is refused where no kernel reads it there. Auto
* takes the first that holds the table, in that order: the card's test is the embedding's, and
* RAM's is lockable_room's -- the memory and every cgroup after the pools still to be allocated,
* and the memlock limit for a locked copy. */
* takes the first that holds the table, in that order: the card's test is the fixed weights and a
* KV pool for one --max-model-len sequence (`kv_floor`) beside it, and RAM's is lockable_room's --
* the memory and every cgroup after the pools still to be allocated, and the memlock limit for a
* locked copy. */
int Engine::resolve_table_placement(const std::vector<VramFacts>& facts,
const std::vector<int64_t>& emb_bytes,
const std::vector<int64_t>& floor_emb_ram, int64_t kv_floor,
const std::vector<int64_t>& emb_bytes, int64_t kv_floor,
int64_t ngram_bytes, bool ngram_device, bool ngram_host) {
const int64_t MiB = (int64_t)1 << 20;
int64_t emb_max = 0;
for (int64_t b : emb_bytes) emb_max = std::max(emb_max, b);
TablePlacement emb = cfg_.embedding_placement;
const bool emb_asked = cfg_.embedding_placement_given;
std::string emb_why;
if (emb == TablePlacement::Disk) {
RAD_ERR("--embedding-placement disk: the token embedding's lookup writes activations the "
"card reads, and a host kernel reading the container cannot write them -- the "
"architecture declares that buffer on the device. Use vram, ram or auto.");
return RAD_E_INVAL;
}
/* THE HOST MEMORY THE TABLE WOULD PIN, every rank its own shard, after the pools and the prefix
* cache's host tier still to be allocated: lockable_room's test, without the memlock limit,
* which a pin the cards read is not charged to. */
const int64_t emb_pin = (int64_t)cfg_.tp * align_up(emb_max, (int64_t)MiB);
const int64_t pools_still = (int64_t)cfg_.tp * cfg_.host_pool_mib * MiB +
cfg_.prefix_cache_host_mib * MiB;
std::string emb_room_why;
auto emb_room = [&]() { return lockable_room(emb_pin, pools_still, false, &emb_room_why); };
if (emb_max == 0) {
if (emb == TablePlacement::Ram) {
if (emb == TablePlacement::Ram && emb_asked) {
RAD_ERR("--embedding-placement ram: this model has no token embedding table that only "
"embed_lookup reads. An output head tied to the table reads it too, and would "
"stream it over the link every step.");
return RAD_E_INVAL;
}
emb = TablePlacement::Vram;
emb_why = "no table only embed_lookup reads";
} else if (emb == TablePlacement::Auto) {
VramBudget tb;
const int st = vram_budget_trial(cfg_, facts, &tb);
const bool holds = st == RAD_OK && (!tb.derived_kv || tb.kv >= kv_floor);
const bool host = cfg_.host_pool_mib * MiB >= emb_max;
if (holds) {
emb_why = "no table only embed_lookup reads (an output head tied to it reads it too, "
"whole, every step)";
} else if (emb == TablePlacement::Ram) {
if (!emb_room()) {
if (emb_asked) {
RAD_ERR("--embedding-placement ram: the token embedding (%s a rank, pinned on "
"every rank) cannot be held in host memory: %s. Use vram.",
humanb(emb_max).c_str(), emb_room_why.c_str());
return RAD_E_NOMEM;
}
emb = TablePlacement::Vram;
emb_why = "the card holds it beside the other weights and a KV pool for one "
"--max-model-len sequence";
} else if (host) {
emb = TablePlacement::Ram;
emb_why = st != RAD_OK
? "the card cannot hold the other weights with it, and the pinned host pool can"
: fmt("with it on the card the KV pool is %s, short of the %s one --max-model-len "
"sequence needs, and the pinned host pool can hold it",
humanb(tb.kv).c_str(), humanb(kv_floor).c_str());
emb_why = "the host cannot pin it: " + emb_room_why;
} else {
emb = TablePlacement::Vram;
emb_why = fmt("the card is short of room for it, and --host-pool-mib %lld cannot hold "
"%s either", (long long)cfg_.host_pool_mib, humanb(emb_max).c_str());
emb_why = emb_asked ? "as asked"
: "pinned in host memory and read over the link in place, so its "
"VRAM goes to the KV cache and the experts";
}
} else {
emb_why = "as asked";
}
cfg_.embedding_resolved = emb;
cfg_.embedding_host_mib = emb == TablePlacement::Ram ? align_up(emb_max, MiB) / MiB : 0;
TablePlacement ng = cfg_.ngram_placement;
std::string ng_why;
/* THE FASTEST TIER WITH THE ROOM, the card first: the table on the card, every rank holding
* all of it (a lookup is not sharded), with the fixed weights and a KV pool for one
* --max-model-len sequence beside it, as the embedding's test is; then a copy in RAM -- pinned
* --max-model-len sequence beside it; then a copy in RAM -- pinned
* for a device kernel to read over the link, or locked for the host gather; then the
* container, which only the host gather reads. Each is open only where a kernel reads it. */
const int64_t still = (int64_t)cfg_.tp * cfg_.host_pool_mib * MiB +
const int64_t still = (int64_t)cfg_.tp * (cfg_.host_pool_mib + cfg_.embedding_host_mib) * MiB +
cfg_.prefix_cache_host_mib * MiB;
const int64_t need = align_up(ngram_bytes, (int64_t)2 << 20);
const char* copy = ngram_device ? "a pinned copy the card reads" : "a locked copy";
@@ -513,10 +538,7 @@ int Engine::resolve_table_placement(const std::vector<VramFacts>& facts,
for (size_t i = 0; i < with.size(); ++i) {
VramFacts& f = with[i];
f.statics += ngram_bytes;
if (emb == TablePlacement::Ram) {
f.statics -= emb_max;
f.expert_floor = floor_emb_ram[i];
}
if (emb == TablePlacement::Ram) f.statics -= emb_bytes[i];
fixed = std::max(fixed, f.statics);
}
/* `fixed` and not the trial's own statics: the split clamps those to what the card can give
@@ -528,7 +550,7 @@ int Engine::resolve_table_placement(const std::vector<VramFacts>& facts,
* only the card, and a table that took their room would leave them nowhere. */
const bool starved = st == RAD_OK && tb.lends && tb.expert_ceiling > 0 &&
tb.experts < tb.expert_floor;
if (st == RAD_OK && !over && !starved && (!tb.derived_kv || tb.kv >= kv_floor))
if (st == RAD_OK && !over && !starved && tb.kv >= kv_floor)
return true;
if (st != RAD_OK)
*why = "the card cannot hold the other weights with it";
@@ -608,8 +630,7 @@ int Engine::resolve_table_placement(const std::vector<VramFacts>& facts,
if (emb_max > 0)
RAD_INFO("placement: token embedding (%s a rank) %s%s: %s", humanb(emb_max).c_str(),
table_placement_name(emb),
cfg_.embedding_placement == TablePlacement::Auto ? " (auto)" : "", emb_why.c_str());
table_placement_name(emb), emb_asked ? "" : " (default)", emb_why.c_str());
if (ngram_bytes > 0)
RAD_INFO("placement: n-gram table (%s) %s%s: %s", humanb(ngram_bytes).c_str(),
table_placement_name(ng),
@@ -956,9 +977,9 @@ int Engine::declare() {
const int64_t exact_rows = (cfg_.tp_wire_min_kb * 1024 + row_bytes - 1) / row_bytes - 1;
RAD_WARN("tp wire: LOSSY (--tp-wire wht6) at %lld KiB a message and above. A cross-rank "
"all-reduce of that size carries a quantised payload instead of bf16 (libr4d's "
"is Walsh-Hadamard-rotated 6-bit at two ranks and tiered int8 at three and four), so this "
"process does not compute the same function the exact wire does. Steps of at "
"most %lld rows are exact: single-sequence decode, and a "
"is Walsh-Hadamard-rotated 6-bit at two ranks and tiered int8 at three and "
"four), so this process does not compute the same function the exact wire does. "
"Steps of at most %lld rows are exact: single-sequence decode, and a "
"decode step until sequences x (1 + speculative depth) passes that; prefill and "
"a busy decode step are lossy. --tp-wire-min-kb moves the floor.",
(long long)cfg_.tp_wire_min_kb, (long long)exact_rows);
@@ -976,7 +997,7 @@ int Engine::declare() {
* rank whose report differs is itself worth seeing, and gets its own. */
{
std::vector<MissReport> rep;
for (auto& r : ranks_) rep.push_back(miss_report(r->program));
for (auto& r : ranks_) rep.push_back(miss_report(r->program, device_is_host()));
bool same = true;
for (size_t i = 1; i < rep.size(); ++i) if (!(rep[i] == rep[0])) same = false;
@@ -992,6 +1013,23 @@ int Engine::declare() {
if (!rep[i].host_only.empty()) RAD_INFO("%s", rep[i].host_only.c_str());
if (!rep[i].host.empty()) RAD_INFO("%s", rep[i].host.c_str());
}
/* A HOLE IS A REFUSAL HERE, not an error the first request finds. Every band is one a
* request can land in -- the bands are cut from the limits this run was started with --
* and the step that lands in one fails at issue and takes the engine down with it. A
* kernel library that serves the op (--kernels), or a model whose geometry the installed
* one covers, is the remedy; serving until then is not. --debug-graph serves nothing, so
* it goes on to print the graph the holes are in, and its exit status says they are there
* (Engine::dump). */
for (const MissReport& m : rep)
if (!m.device.empty() && !cfg_.debug_graph) {
if (m.lossy_wire)
RAD_ERR("the band(s) above include the lossy wire --tp-wire wht6 asks for, "
"which the loaded kernel libraries do not implement at --tp %d; "
"--tp-wire exact asks for the exact one", cfg_.tp);
RAD_ERR("not starting: the kernel libraries loaded have no kernel for the device "
"band(s) above, and this model needs them");
return RAD_E_UNSUPPORTED;
}
}
/* A CHECKPOINT WEIGHT THAT IS NOT SERVED AS IT STANDS was declared as plain and nothing can
* load it: every one is named, with the remedy, whatever declare made of the rest. */
@@ -1198,11 +1236,10 @@ int Engine::plan() {
* already this card's even share of the static weights: declare ran once per rank
* with every dimension divided. */
WeightFootprint wf;
weight_footprint(r->program, &wf, TablePlacement::Vram, TablePlacement::Disk);
weight_footprint(r->program, &wf, TablePlacement::Vram, TablePlacement::Disk,
device_is_host(), file_ != nullptr);
f.statics = wf.statics;
f.experts = wf.experts;
/* The expert floor waits for the tables' placement: the embedding may take its share
* of the host pool first. */
wfs.push_back(wf);
/* THE CACHE LENDS where units move and the pool can give its blocks back in place. */
f.lends = VMem::supported() && !cfg_.deterministic &&
@@ -1213,8 +1250,8 @@ int Engine::plan() {
ngram_host = ngram_host || wf.ngram_host;
/* ONE --max-model-len SEQUENCE'S CACHE: the same groups planned for a single
* sequence, which is the least a KV pool can hold and still serve every request the
* API accepts (configure_kv warns below it). --embedding-placement auto keeps the
* table off the card only to stay above it. */
* API accepts (configure_kv warns below it). --ngram-placement auto puts the table
* on the card only where the pool stays above it. */
{
Config one = cfg_;
one.max_seqs = 1;
@@ -1270,28 +1307,22 @@ int Engine::plan() {
late_lazy_bytes_ = std::max(late_lazy_bytes_, lazy);
facts.push_back(f);
}
/* THE PINNED HOST POOL IS THE EXPERTS' OTHER HOME, less what Planner::plan takes out of it
* before any expert: the embedding when it is placed there, and the file tier's staging.
* Both floors are known before the tables are placed, so placing them can ask whether the
* experts would still have a tier. */
std::vector<int64_t> floor_emb_ram(facts.size(), 0);
/* THE PINNED HOST POOL IS THE EXPERTS' OTHER HOME, less the file tier's staging, which
* Planner::plan takes out of it before any expert. The embedding placed in host memory
* brings its own room (Config::embedding_host_mib), so it leaves this floor as it is. */
for (size_t i = 0; i < facts.size(); ++i) {
int64_t room = cfg_.host_pool_mib * ((int64_t)1 << 20);
if (cfg_.weights_disk_tier)
room -= file_stage_reserve(wfs[i].layer_unit_max, wfs[i].routed);
facts[i].expert_floor = expert_vram_floor(wfs[i], std::max<int64_t>(room, 0));
floor_emb_ram[i] = expert_vram_floor(wfs[i], std::max<int64_t>(room - emb_bytes[i], 0));
}
RAD_TRY(resolve_table_placement(facts, emb_bytes, floor_emb_ram, kv_floor, ngram_bytes,
ngram_device, ngram_host));
RAD_TRY(resolve_table_placement(facts, emb_bytes, kv_floor, ngram_bytes, ngram_device,
ngram_host));
/* The n-gram table was counted off the card; on it, it is every rank's whole table. */
if (cfg_.ngram_resolved == TablePlacement::Vram)
for (VramFacts& f : facts) f.statics += ngram_bytes;
if (cfg_.embedding_resolved == TablePlacement::Ram)
for (size_t i = 0; i < facts.size(); ++i) {
facts[i].statics -= emb_bytes[i];
facts[i].expert_floor = floor_emb_ram[i];
}
for (size_t i = 0; i < facts.size(); ++i) facts[i].statics -= emb_bytes[i];
VramBudget vb;
RAD_TRY(vram_budget_resolve(cfg_, facts, &vb));
if (!vb.report.empty()) RAD_INFO("%s", vb.report.c_str());
@@ -1317,8 +1348,7 @@ int Engine::plan() {
* pool, up to every one of its weights resident. The token count, the carve, the loan and
* the dearest ranks' pools are what they were.
*
* Only a DERIVED split under expert_tiered is re-split. An operator who stated either pool
* has decided what every card gets. And under `auto` a rank whose grown pool covers all of
* Only a split under expert_tiered is re-split: under `auto` a rank whose grown pool covers all of
* its weights would choose all_vram while its peers spill -- one strategy per world is the
* contract that keeps their movers alike, so `auto` keeps the common split. A cache that
* does not lend (--deterministic, or a device without virtual memory management) is
@@ -1341,8 +1371,6 @@ int Engine::plan() {
int64_t T = -1;
if (cheaper.empty()) {
/* Every rank's cache costs the same per token: there is nothing to re-split. */
} else if (!vb.derived_kv || !vb.derived_weights) {
kept = "a stated --vram-kv-mib or --vram-weights-mib is applied to every card";
} else if (cfg_.placement != "expert_tiered") {
kept = fmt("--placement %s keeps one split for every card; only expert_tiered re-splits",
cfg_.placement.c_str());
@@ -1442,6 +1470,7 @@ int Engine::plan() {
in.n_profile = (int64_t)file_->header().prof_count;
}
in.container = file_ != nullptr;
in.host_backend = device_is_host();
Planner planner(in);
s = planner.plan(&r->plan);
if (cfg_.debug_placement || s < 0)
@@ -2329,7 +2358,7 @@ int Engine::load_weights() {
* past the end of the weights pool is a write to device memory the process does not own,
* and on this driver that does not fault -- the copy is accepted, never completes, and
* the host thread spins inside the runtime with the copy engine idle and no I/O. It looks
* exactly like a hang, and it moves with --vram-weights-mib because a bigger pool is a
* exactly like a hang, and it moves with the weights pool's size because a bigger pool is a
* later overrun. Cheap enough to check on every copy, and checked before any of them
* start rather than as each one is issued. */
const uint8_t* wp_lo = (const uint8_t*)r->pools.weights().base();
@@ -3217,6 +3246,7 @@ int Engine::start() {
/* The cards are chosen, so a kernel library's device code is checked against the ones the
* ranks will run on and not against whichever device the backend happens to list first. */
rad_tools_registry().set_code_device(devs[0]);
rad_tools_registry().set_no_device_code(device_is_host());
RAD_TRY(load_plugins());
ranks_.clear();
@@ -3570,34 +3600,27 @@ int Engine::start() {
r->device, humanb(got).c_str(), asked.c_str(), humanb(want - got).c_str(),
humanb(room).c_str());
} else if (got > want + 256 * MiB) {
/* AND "TOO MUCH" IS ONLY A FAULT WHERE SOMEBODY STATED THE BUDGET. Where the resolver
* made the split, what is left is left because neither pool could address another
* byte -- a small dense model already at the largest context its cache can hold
* leaves most of the card -- and vram_budget.cpp printed it on the `unusable` line.
* Warning here would contradict that receipt and send the reader looking for a flag
* to set. A rank plan() re-split for the common token count also leaves what its
* weights could not use, and the `kv: rank N ...` line said how much. */
/* "TOO MUCH" IS NOT A FAULT: the resolver made the split, and what is left is left
* because neither pool could address another byte -- a small dense model already at
* the largest context its cache can hold leaves most of the card -- and vram_budget.cpp
* printed it on the `unusable` line. A rank plan() re-split for the common token count
* also leaves what its weights could not use, and the `kv: rank N ...` line said how
* much. */
const int64_t unclaimed_mib =
(cfg_.vram_weights_mib + cfg_.vram_kv_mib) -
(rank_cfg_[ri].vram_weights_mib + rank_cfg_[ri].vram_kv_mib);
if (cfg_.vram_budget_derived && unclaimed_mib > 0)
if (unclaimed_mib > 0)
RAD_INFO("card %d settled at %s free against %s. The split accounted for it: %lld "
"MiB are what rank %d's weights could not use of what its KV pool did not "
"need, on the `kv: rank %d ...` line above, and the rest is the `unusable` "
"line of the VRAM budget.",
r->device, humanb(got).c_str(), asked.c_str(), (long long)unclaimed_mib,
r->index, r->index);
else if (cfg_.vram_budget_derived)
else
RAD_INFO("card %d settled at %s free against %s. The split accounted for it: "
"neither pool could address another byte, which is the `unusable` line of "
"the VRAM budget above.",
r->device, humanb(got).c_str(), asked.c_str());
else
RAD_WARN("card %d settled at %s free against %s, so %s is unused. On a model that "
"does not fit in VRAM every unused GiB is weight that has to be moved "
"instead of read, and that is decode step time.",
r->device, humanb(got).c_str(), asked.c_str(),
humanb(got - want).c_str());
} else
RAD_INFO("card %d settled at %s free, against %s",
r->device, humanb(got).c_str(), asked.c_str());
@@ -3614,17 +3637,12 @@ int Engine::dump() {
Program& p = ranks_[0]->program;
fputs(dump_graph_str(p, nullptr).c_str(), stdout);
if (cfg_.debug_selection) fputs(rad_tools_registry().selection_table().c_str(), stdout);
/* A HOST miss is not a failure -- see miss_report(). The exit code answers "is there a
* hole a request can fall into", and a host miss is not one. NOR IS A DEVICE MISS WHOSE OP
* HAS A HOST KERNEL: the planner places that op on the host and pins its weights in the
* container's mapping, which is how a table too large to copy into VRAM is served at all. A
* hole is a band NEITHER domain resolved. */
std::set<std::pair<std::string, std::string>> no_host;
for (const Program::Miss& m : p.misses)
if (m.domain == RAD_DOMAIN_HOST) no_host.emplace(m.op, m.span);
for (const Program::Miss& m : p.misses)
if (m.domain != RAD_DOMAIN_HOST && no_host.count(std::make_pair(m.op, m.span)))
return RAD_E_NOKERNEL;
/* The exit code answers "is there a hole a request can fall into", by the rule declare()
* refuses to serve on (Program::device_holes, miss_report()): a device band no kernel
* resolved, unless a host kernel stands in for an op whose weights the planner can place on
* the host. A host miss is not one. */
for (auto& r : ranks_)
if (!r->program.device_holes(device_is_host()).empty()) return RAD_E_NOKERNEL;
return RAD_OK;
}
+6 -5
View File
@@ -114,9 +114,10 @@ static void dump_row(int step, const char* phase, const char* name, uint32_t dty
* WHY THAT IS ENOUGH FOR A KL DIVERGENCE, with no log-sum-exp anywhere. Renormalised over a
* fixed candidate set S, p~_i = exp(l_i) / sum_{j in S} exp(l_j) -- the partition function
* over the WHOLE vocabulary cancels, in both engines independently. So a top-K KLD against
* another engine's top-K logprobs needs only these logits. An OpenAI `logprobs` FIELD would
* need the normaliser, and `supports_logprobs` is false; this is a probe, and it says so by
* being an environment variable at -vv rather than a response field. */
* another engine's top-K logprobs needs only these logits. The OpenAI `logprobs` field carries
* the normaliser (sample_logprobs) and only the RAW distribution's top 20; this reads the
* plane the pick drew from, which is a probe, and it says so by being an environment variable
* at -vv rather than a response field. */
static const int head = [] {
const char* s = std::getenv("RADIANCE_DUMP_HEAD");
const long v = (s && *s) ? std::strtol(s, nullptr, 10) : 0;
@@ -156,8 +157,8 @@ static void dump_row(int step, const char* phase, const char* name, uint32_t dty
* writing different code -- so the question a LOSSY LEVER asks ("how much worse, if at all")
* needs an instrument of its own.
*
* WHY THIS SHAPE AND NOT A PERPLEXITY. The server returns no logprobs (`supports_logprobs` is
* never set, so it refuses them) and a served prefill produces logits only at the rows
* WHY THIS SHAPE AND NOT A PERPLEXITY. The server's logprobs are the generated positions'
* only -- never the prompt's -- and a served prefill produces logits only at the rows
* `out_ids` names; the teacher-forced scoring pass is the KL mode's (core/kld.h), which runs in
* place of the server. What a serving engine offers: send N distinct prompts at max_tokens = 1,
* and every build under comparison sees IDENTICAL inputs at one row each. The top of that row,
+40 -18
View File
@@ -264,18 +264,23 @@ int meta_from_config_json(const std::string& dir, MetaOwn* out) {
* be a linear position divide for llama3, longrope or YaRN. */
m.rope_scale = 1.0f;
/* The quantisation descriptor, which with the architecture selects the plugin (spec §2.4).
* "fp8" plus its format, so qwen35_fp8 and qwen35_bf16 are told apart by the checkpoint
* rather than by a flag. */
if (const char* qm = gs("quantization_config.quant_method")) {
out->quant = qm;
if (const char* fm = gs("quantization_config.fmt")) { out->quant += "_"; out->quant += fm; }
}
out->quant = quant_descriptor(*out);
out->finish();
return RAD_OK;
}
/* The quantisation descriptor, which with the architecture selects the plugin (spec §2.4).
* "fp8" plus its format, so qwen35_fp8 and qwen35_bf16 are told apart by the checkpoint
* rather than by a flag. */
std::string quant_descriptor(const MetaOwn& m) {
std::string q;
if (const char* qm = m.get("quantization_config.quant_method")) {
q = qm;
if (const char* fm = m.get("quantization_config.fmt")) { q += "_"; q += fm; }
}
return q;
}
int meta_from_gguf(GgufFile& g, MetaOwn* out) {
if (!g.get_str("general.architecture", &out->arch)) {
RAD_ERR("the GGUF has no general.architecture, so no architecture plugin can be chosen");
@@ -414,10 +419,24 @@ int Checkpoint::open_gguf(const std::string& path) {
return meta_from_gguf(gguf_, &meta_);
}
int Checkpoint::add_shard(const std::string& p, const std::string& prefix) {
int Checkpoint::add_shard(const std::string& p, const std::string& prefix,
const std::unordered_map<std::string, std::string>* owner) {
shards_.push_back(std::make_unique<SafeTensorsFile>());
RAD_TRY(shards_.back()->open(p));
const std::string file = p.substr(p.find_last_of('/') + 1);
for (const auto& t : shards_.back()->tensors()) {
/* THE INDEX SAYS WHICH SHARD A TENSOR IS READ FROM. A directory that merges two
* checkpoints -- a finetune's changed tensors in its own shards beside links to the base
* model's -- holds some names in two shards, and only the index tells the copies apart. */
if (owner) {
auto it = owner->find(t.name);
if (it != owner->end() && it->second != file) continue;
}
if (index_.count(prefix + t.name)) {
RAD_ERR("%s: '%s' is also in %s, and no index entry says which copy to read", p.c_str(),
t.name.c_str(), shards_[index_shard_[prefix + t.name]]->path().c_str());
return RAD_E_FORMAT;
}
if (t.dtype == RAD_DT_INVALID) {
RAD_ERR("%s: '%s' has dtype %s, which has no RAD equivalent", p.c_str(),
t.name.c_str(), t.dtype_str.c_str());
@@ -429,6 +448,7 @@ int Checkpoint::add_shard(const std::string& p, const std::string& prefix) {
s.shape = t.shape; /* safetensors is already row-major */
s.data = t.data;
s.bytes = (int64_t)t.bytes;
index_shard_.emplace(s.name, shards_.size() - 1);
index_.emplace(s.name, tensors_.size());
tensors_.push_back(std::move(s));
}
@@ -437,13 +457,13 @@ int Checkpoint::add_shard(const std::string& p, const std::string& prefix) {
namespace {
/* Every shard an index names, once each and in name order, or the one model.safetensors. */
/* Every shard an index names, once each and in name order, or the one model.safetensors; `map`
* is the index's weight_map, empty without one. */
int shard_list(const std::string& dir, const std::string& index, bool index_given,
std::vector<std::string>* out) {
std::unordered_map<std::string, std::string> map;
const int s = st_load_index(index, &map);
std::vector<std::string>* out, std::unordered_map<std::string, std::string>* map) {
const int s = st_load_index(index, map);
if (s == RAD_OK) {
for (auto& [t, f] : map)
for (auto& [t, f] : *map)
if (std::find(out->begin(), out->end(), f) == out->end()) out->push_back(f);
std::sort(out->begin(), out->end());
for (auto& f : *out) f = dir + "/" + f;
@@ -460,6 +480,7 @@ int Checkpoint::open_safetensors(const std::string& path) {
kind_ = SafeT;
/* One shard, an index, or the directory holding either: one namespace whichever it is. */
std::vector<std::string> shards;
std::unordered_map<std::string, std::string> owner;
const bool is_index = path.size() > 10 && path.compare(path.size() - 10, 10, "index.json") == 0;
const bool is_file = path.size() > 12 &&
path.compare(path.size() - 12, 12, ".safetensors") == 0;
@@ -467,9 +488,9 @@ int Checkpoint::open_safetensors(const std::string& path) {
shards.push_back(path);
} else {
RAD_TRY(shard_list(dir_, is_index ? path : dir_ + "/model.safetensors.index.json",
is_index, &shards));
is_index, &shards, &owner));
}
for (const auto& sh : shards) RAD_TRY(add_shard(sh));
for (const auto& sh : shards) RAD_TRY(add_shard(sh, "", owner.empty() ? nullptr : &owner));
RAD_TRY(meta_from_config_json(dir_, &meta_));
RAD_TRY(meta_merge_generation_config(dir_, &meta_));
@@ -669,8 +690,9 @@ int Checkpoint::add_draft(const std::string& dir, const std::string& prefix) {
? prefix
: prefix.substr(0, prefix.size() - 1), &meta_));
std::vector<std::string> shards;
RAD_TRY(shard_list(dir, dir + "/model.safetensors.index.json", false, &shards));
for (const auto& sh : shards) RAD_TRY(add_shard(sh, prefix));
std::unordered_map<std::string, std::string> owner;
RAD_TRY(shard_list(dir, dir + "/model.safetensors.index.json", false, &shards, &owner));
for (const auto& sh : shards) RAD_TRY(add_shard(sh, prefix, owner.empty() ? nullptr : &owner));
meta_.finish();
return RAD_OK;
}
+7 -1
View File
@@ -84,6 +84,8 @@ struct MetaOwn {
};
int meta_from_config_json(const std::string& dir, MetaOwn* out);
/* quantization_config's quant_method and fmt as the plugin descriptor ("fp8_e4m3"), "" without. */
std::string quant_descriptor(const MetaOwn& m);
int meta_merge_config_json(const std::string& dir, const std::string& prefix, MetaOwn* out);
int meta_merge_generation_config(const std::string& dir, MetaOwn* out);
int meta_merge_preprocessor_configs(const std::string& dir, MetaOwn* out);
@@ -142,7 +144,10 @@ public:
std::string* why);
private:
int add_shard(const std::string& p, const std::string& prefix = "");
/* `owner`, when the checkpoint has an index, is its weight_map: a tensor the index places in
* another shard is not read from this one. */
int add_shard(const std::string& p, const std::string& prefix = "",
const std::unordered_map<std::string, std::string>* owner = nullptr);
int open_safetensors(const std::string& path);
int open_gguf(const std::string& path);
void detect_import();
@@ -154,6 +159,7 @@ private:
std::vector<std::unique_ptr<SafeTensorsFile>> shards_;
std::vector<SrcTensor> tensors_;
std::unordered_map<std::string, size_t> index_;
std::unordered_map<std::string, size_t> index_shard_; /* name -> shards_ position */
std::deque<SrcTensor> sliced_; /* views; a deque never moves what it holds */
int64_t fp8_br_ = 128, fp8_bc_ = 128;
Import import_ = Import::None;
+142 -55
View File
@@ -1,79 +1,166 @@
/* hf_model.cpp -- resolve a --model that is an HF repo id into a local cache dir.
/* hf_model.cpp -- resolve a --model that is a Hugging Face repo id (hf_model.h).
*
* The entry point (main.cpp) stays thin: it calls rad::resolve_hf_model() once, between
* config_parse and Engine construction, and the rest of bring-up sees a plain directory.
* The fetching itself is scripts/hfget.sh (curl + jq, no Python), run as a child process.
*/
#include "engine.h"
* The entry point (main.cpp) calls resolve_hf_model() once, between config_parse and the Engine,
* and the rest of bring-up sees a plain file or directory. The fetching is scripts/hfget.sh (curl
* and jq, no Python), run as a child process; it is installed to libexec/radiance/ and the build
* copies it to the same place under the build tree, so it is found beside the binary either way.
*
* WHERE IT GOES. Not under $RADIANCE_HOME: that is a ':'-separated search path for plugins, and
* its default is the install's share/ directory, which a user cannot write. A model is a cache --
* the XDG cache directory by default, --download-dir (vLLM's name) to put it on another disk.
*
* A HUB THAT CANNOT BE REACHED DOES NOT STOP A RESTART. hfget.sh exits 3 when it changed nothing
* on disk (the listing failed, or an update does not fit), and the copy a complete fetch left --
* marked by the manifest it writes only on success -- is then served with a warning. Any other
* failure may have left a file half-transferred, so it is not served. */
#include "hf_model.h"
#include "rad_internal.h"
#include <cerrno>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <filesystem>
#include <string>
#include <unistd.h>
#include <sys/wait.h>
#include <unistd.h>
#include <vector>
namespace rad {
/* "owner/name" that is not a local path: exactly one slash, no shell-fodder, not a known file. */
static bool is_hf_repo_id(const std::string& s) {
if (std::filesystem::exists(s)) return false; /* a real existing local path always wins */
if (s.empty() || s.front() == '/') return false;
if (s.find_first_of("\\:*?\"<>|") != std::string::npos) return false;
size_t slash = s.find('/');
if (slash == std::string::npos || s.find('/', slash + 1) != std::string::npos) return false;
std::string owner = s.substr(0, slash);
std::string name = s.substr(slash + 1);
if (owner.empty() || name.empty()) return false;
if (owner == ".." || name == "..") return false;
static const std::string kFileSuffixes[] = {".rad", ".safetensors", ".gguf", "index.json"};
for (const auto& suf : kFileSuffixes)
if (name.size() >= suf.size() && name.compare(name.size() - suf.size(), suf.size(), suf) == 0)
return false;
namespace fs = std::filesystem;
namespace {
bool repo_part(const std::string& p) {
if (p.empty() || p.front() == '.' || p.front() == '-') return false;
for (char ch : p) {
const bool ok = (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') ||
(ch >= '0' && ch <= '9') || ch == '.' || ch == '_' || ch == '-';
if (!ok) return false;
}
return true;
}
/* hfget.sh: $RADIANCE_HFGET, then <exe_dir>/../scripts/, then ./scripts/. */
static std::string find_hfget() {
if (const char* e = std::getenv("RADIANCE_HFGET"))
if (*e && std::filesystem::exists(e)) return e;
char buf[4096];
ssize_t n = readlink("/proc/self/exe", buf, sizeof buf - 1);
if (n > 0) {
buf[n] = '\0';
std::string p = (std::filesystem::path(buf).parent_path() / ".." / "scripts" / "hfget.sh").string();
if (std::filesystem::exists(p)) return p;
}
if (std::filesystem::exists("./scripts/hfget.sh")) return "./scripts/hfget.sh";
return "";
bool ends_with(const std::string& s, const char* suf) {
const size_t n = std::strlen(suf);
return s.size() >= n && s.compare(s.size() - n, n, suf) == 0;
}
/* If cfg.model is an HF repo id, fetch it into $RADIANCE_HOME/hf/ via hfget.sh and rewrite the path. */
bool resolve_hf_model(Config& cfg) {
if (!is_hf_repo_id(cfg.model)) return true;
std::string script = find_hfget();
if (script.empty()) {
RAD_ERR("hfget.sh not found -- set RADIANCE_HFGET to its path");
return false;
/* <exe>/../libexec/radiance/hfget.sh, which is where the install puts it and where the build
* copies it. */
std::string hfget_path() {
char buf[4096];
const ssize_t n = readlink("/proc/self/exe", buf, sizeof buf - 1);
if (n <= 0) return std::string();
buf[n] = '\0';
const fs::path p = fs::path(buf).parent_path() / ".." / "libexec" / "radiance" / "hfget.sh";
std::error_code ec;
return fs::is_regular_file(p, ec) ? p.lexically_normal().string() : std::string();
}
/* The script's exit status, or -1 when it could not be run. */
int run_hfget(const std::string& script, const std::string& repo, const std::string& dest) {
const pid_t pid = fork();
if (pid < 0) {
RAD_ERR("hfget: fork: %s", std::strerror(errno));
return -1;
}
std::string dest = cfg.radiance_home + "/hf/" + cfg.model;
std::filesystem::create_directories(dest);
fprintf(stderr, "radiance: downloading %s -> %s\n", cfg.model.c_str(), dest.c_str());
pid_t pid = fork();
if (pid < 0) { perror("fork"); return false; }
if (pid == 0) {
const char* argv[] = { script.c_str(), cfg.model.c_str(), dest.c_str(), nullptr };
execvp(script.c_str(), const_cast<char* const*>(argv));
perror("execvp hfget.sh");
const char* argv[] = { "sh", script.c_str(), repo.c_str(), dest.c_str(), nullptr };
execv("/bin/sh", const_cast<char* const*>(argv));
std::fprintf(stderr, "hfget: /bin/sh: %s\n", std::strerror(errno));
_exit(127);
}
int status = 0;
waitpid(pid, &status, 0);
if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
RAD_ERR("hfget.sh failed for %s (status %d) -- see output above", cfg.model.c_str(), status);
while (waitpid(pid, &status, 0) < 0)
if (errno != EINTR) return -1;
return WIFEXITED(status) ? WEXITSTATUS(status) : -1;
}
} /* namespace */
bool hf_repo_id(const std::string& s) {
std::error_code ec;
if (s.empty() || fs::exists(s, ec)) return false;
const size_t slash = s.find('/');
if (slash == std::string::npos || s.find('/', slash + 1) != std::string::npos) return false;
const std::string owner = s.substr(0, slash), name = s.substr(slash + 1);
if (!repo_part(owner) || !repo_part(name)) return false;
for (const char* suf : { ".rad", ".safetensors", ".gguf", ".json" })
if (ends_with(name, suf)) return false;
return true;
}
std::string hf_default_download_dir() {
if (const char* x = std::getenv("XDG_CACHE_HOME"); x && *x)
return std::string(x) + "/radiance/hf";
if (const char* h = std::getenv("HOME"); h && *h)
return std::string(h) + "/.cache/radiance/hf";
return std::string();
}
std::string hf_served_path(const std::string& dir, std::string* why) {
std::vector<std::string> rad;
std::error_code ec;
for (const fs::directory_entry& e : fs::directory_iterator(dir, ec)) {
std::error_code fe;
if (e.is_regular_file(fe) && ends_with(e.path().filename().string(), ".rad"))
rad.push_back(e.path().filename().string());
}
if (ec) {
*why = dir + ": " + ec.message();
return std::string();
}
if (rad.empty()) return dir;
if (rad.size() == 1) return dir + "/" + rad[0];
std::string names;
for (size_t i = 0; i < rad.size(); ++i) names += (i ? ", " : "") + rad[i];
*why = dir + " holds " + std::to_string(rad.size()) + " containers (" + names +
"); pass the one to serve as --model " + dir + "/<file>";
return std::string();
}
bool resolve_hf_model(Config& c) {
if (!hf_repo_id(c.model)) return true;
const std::string repo = c.model;
const std::string root = c.download_dir.empty() ? hf_default_download_dir() : c.download_dir;
if (root.empty()) {
RAD_ERR("--model %s: no download directory -- neither XDG_CACHE_HOME nor HOME is set; "
"name one with --download-dir", repo.c_str());
return false;
}
cfg.model = dest; /* rewrite to the cached local dir; downstream reads it as a checkpoint dir */
const std::string dest = root + "/" + repo;
std::error_code ec;
const bool cached = fs::is_regular_file(dest + "/.hfget-manifest", ec);
const std::string script = hfget_path();
if (script.empty()) {
RAD_ERR("--model %s: not a path here, and hfget.sh, which fetches a Hugging Face repo, is "
"not installed beside this binary (libexec/radiance/)", repo.c_str());
return false;
}
RAD_INFO("model: %s is not a path here; fetching it as a Hugging Face repo into %s",
repo.c_str(), dest.c_str());
const int rc = run_hfget(script, repo, dest);
if (rc != 0) {
if (rc == 3 && cached) {
RAD_WARN("model: %s could not be checked for changes (hfget.sh, above); serving the "
"copy fetched before", repo.c_str());
} else {
RAD_ERR("--model %s: not a path here, and fetching it as a Hugging Face repo failed "
"(hfget.sh exit %d, above)", repo.c_str(), rc);
return false;
}
}
std::string why;
const std::string path = hf_served_path(dest, &why);
if (path.empty()) {
RAD_ERR("--model %s: %s", repo.c_str(), why.c_str());
return false;
}
c.model = path;
RAD_INFO("model: serving %s", c.model.c_str());
return true;
}
+33
View File
@@ -0,0 +1,33 @@
/* hf_model.h -- a --model that names a Hugging Face repo instead of a local path.
*
* `radiance --model StillDeadcode/minicpm5-2b-fp8` fetches the repo with scripts/hfget.sh into
* the download directory and serves what it fetched: the one container at the repo's top level,
* or the directory as a checkpoint when it holds none. Every start re-checks the hub, so a
* changed file is fetched again before bring-up; a start that cannot reach the hub serves the
* copy a complete earlier fetch left. */
#pragma once
#include "rad_core.h"
#include <string>
namespace rad {
/* Is `s` a repo id ("owner/name") rather than a path? A path that exists always wins. A repo id is
* exactly two non-empty parts of [A-Za-z0-9._-], neither starting with '.' or '-', and a name that
* does not end like a model file (.rad, .safetensors, .gguf, .json): a missing local file should
* be reported as missing, not looked up on the hub. */
bool hf_repo_id(const std::string& s);
/* $XDG_CACHE_HOME/radiance/hf, else $HOME/.cache/radiance/hf; empty if neither is set. */
std::string hf_default_download_dir();
/* What to serve from a fetched repo directory: its one top-level .rad, or the directory itself (a
* checkpoint) when it holds none. Several containers are ambiguous: empty, and *why names them. */
std::string hf_served_path(const std::string& dir, std::string* why);
/* If c.model is a repo id, fetch it and point c.model at what to serve. False after an error has
* been logged. */
bool resolve_hf_model(Config& c);
} /* namespace rad */
+2 -1
View File
@@ -2,6 +2,7 @@
* a command line into that sequence and a status into an exit code.
*/
#include "engine.h"
#include "hf_model.h"
int main(int argc, char** argv) {
rad::Config cfg;
@@ -9,7 +10,7 @@ int main(int argc, char** argv) {
if (s == 1) { rad::config_usage(argv[0]); return 0; }
if (s < 0) { rad::config_usage(argv[0]); return 2; }
if (!rad::resolve_hf_model(cfg)) return 2; /* --model given as an HF repo id: fetch + rewrite */
if (!rad::resolve_hf_model(cfg)) return 1; /* a repo id: fetched, and --model points at it */
rad::Engine engine(std::move(cfg));
+7 -7
View File
@@ -424,8 +424,7 @@ int64_t KVManager::zero_blocks(const KVGroupPlan& p, int64_t tokens) const {
}
int KVManager::carve_into(Pool& kv_pool) {
/* The pool is whatever the operator stated or the resolver derived; nothing here re-decides
* it. What this does decide is how the groups share it, which is arithmetic, not policy. */
/* The pool is what the resolver derived; nothing here re-decides it. What this does decide is how the groups share it, which is arithmetic, not policy. */
const int64_t budget_bytes = kv_pool.avail();
const int64_t fixed = fixed_;
pool_base_ = kv_pool.base();
@@ -434,10 +433,11 @@ int KVManager::carve_into(Pool& kv_pool) {
if (fixed >= budget_bytes) {
RAD_ERR("vram_kv does not fit its fixed costs:\n"
" linear/conv state %10s (%lld sequences)\n"
" --vram-kv-mib %10s\n"
" vram_kv %10s\n"
" SHORT BY %10s\n"
"Lower --max-seqs or raise --vram-kv-mib. The engine will not shrink one of them "
"for you (spec §6).",
"Lower --max-num-seqs, or give the cache more of the card: a smaller "
"--gpu-headroom-mib or a larger --host-pool-mib. The engine will not shrink one of "
"them for you (spec §6).",
humanb(fixed).c_str(), (long long)max_seqs_, humanb(budget_bytes).c_str(),
humanb(fixed - budget_bytes + 1).c_str());
return RAD_E_NOMEM;
@@ -459,8 +459,8 @@ int KVManager::carve_into(Pool& kv_pool) {
}
if (p.n_blocks <= 0) {
RAD_ERR("KV group '%s': a %s KV pool leaves 0 blocks (%s a page) after the fixed "
"linear/conv costs of %s. Raise --vram-kv-mib or --host-pool-mib, or lower "
"--max-seqs.",
"linear/conv costs of %s. Raise --host-pool-mib or lower --gpu-headroom-mib, or "
"lower --max-num-seqs.",
p.name.c_str(), humanb(budget_bytes).c_str(),
humanb(p.bytes_per_block).c_str(), humanb(fixed).c_str());
return RAD_E_NOMEM;
+3 -3
View File
@@ -156,8 +156,8 @@ public:
* exhaust at the same total token count, and any other split strands memory in whichever
* group outlasts the others.
*
* The byte budget comes from the operator and is not derived here: it is whatever `kv_pool`
* still has (which is --vram-kv-mib). The linear-state snapshots take none of it -- they live
* The byte budget is the budget resolver's and is not re-derived here: it is whatever
* `kv_pool` still has (vram_kv). The linear-state snapshots take none of it -- they live
* in pinned host memory (set_checkpoint_store) -- so the pool is the live cache and nothing
* else (spec §6, §7.3). */
int configure(const std::vector<KVGroupInfo>& groups, const Config& cfg, Pool& kv_pool);
@@ -165,7 +165,7 @@ public:
/* configure(), split at the seam the budget resolver needs. plan_groups() sizes every group
* from the declaration and the run configuration -- no pool, no bytes -- and ceiling() then
* says what a FULL cache for `ctx` tokens on max_seqs sequences would cost. Pools are
* allocated before carve() runs, so a derived --vram-kv-mib has to be decided from these two
* allocated before carve() runs, so the KV pool has to be decided from these two
* and nothing else (core/mem/vram_budget.cpp). carve() spends the pool it is given. */
int plan_groups(const std::vector<KVGroupInfo>& groups, const Config& cfg);
int64_t ceiling(int64_t ctx) const;
+12 -2
View File
@@ -988,7 +988,7 @@ static bool chain_extends(const std::vector<BlockHash>& shorter,
}
void IdleTiers::note_session(uint64_t id, const std::vector<BlockHash>& chain, int64_t n_tokens,
uint64_t now_ns) {
uint64_t now_ns, const std::string& label) {
if (chain.empty()) return;
std::lock_guard lk(mu_);
@@ -1008,6 +1008,9 @@ void IdleTiers::note_session(uint64_t id, const std::vector<BlockHash>& chain, i
* to say which of them republished. So the most recent of them is touched and no row is
* added, which is the one answer that is wrong about nothing. */
uint64_t first_seen = 0;
/* A conversation's label outlives the turn that sent it: a later turn without one keeps the
* name an earlier one gave. */
std::string kept_label = label;
bool absorbed = false;
std::vector<uint64_t>& at_root = roots_[chain[0]];
for (size_t i = 0; i < at_root.size();) {
@@ -1016,6 +1019,7 @@ void IdleTiers::note_session(uint64_t id, const std::vector<BlockHash>& chain, i
if (!chain_extends(it->second.chain, chain)) { ++i; continue; }
if (first_seen == 0 || it->second.first_seen_ns < first_seen)
first_seen = it->second.first_seen_ns;
if (kept_label.empty()) kept_label = it->second.label;
sessions_.erase(it);
at_root.erase(at_root.begin() + (long)i);
absorbed = true;
@@ -1028,7 +1032,11 @@ void IdleTiers::note_session(uint64_t id, const std::vector<BlockHash>& chain, i
if (it == sessions_.end() || !chain_extends(chain, it->second.chain)) continue;
if (!newest || it->second.last_used_ns > newest->last_used_ns) newest = &it->second;
}
if (newest) { newest->last_used_ns = now_ns; return; }
if (newest) {
newest->last_used_ns = now_ns;
if (!label.empty()) newest->label = label;
return;
}
}
Session& s = sessions_[id];
@@ -1036,6 +1044,7 @@ void IdleTiers::note_session(uint64_t id, const std::vector<BlockHash>& chain, i
s.n_tokens = n_tokens;
s.first_seen_ns = first_seen ? first_seen : now_ns;
s.chain = chain;
s.label = std::move(kept_label);
at_root.push_back(id);
}
@@ -1079,6 +1088,7 @@ std::vector<IdleTiers::SessionInfo> IdleTiers::sessions(Occupancy* occ) const {
si.model = model_;
si.n_tokens = kv.second.n_tokens;
si.first_seen_ns = kv.second.first_seen_ns;
si.label = kv.second.label;
si.last_used_ns = kv.second.last_used_ns;
si.bytes = (int64_t)kv.second.chain.size() * cfg_.entry_bytes;
out.push_back(std::move(si));
+3 -1
View File
@@ -383,6 +383,7 @@ public:
struct SessionInfo {
uint64_t id = 0;
std::string model;
std::string label; /* the client's own name for the conversation, or "" */
int64_t n_tokens = 0;
int64_t bytes = 0;
uint64_t first_seen_ns = 0;
@@ -426,7 +427,7 @@ public:
* is a row per turn -- a table nobody can read, holding a copy of every prefix of the
* transcript for as long as the newest. */
void note_session(uint64_t id, const std::vector<BlockHash>& chain, int64_t n_tokens,
uint64_t now_ns);
uint64_t now_ns, const std::string& label = std::string());
void set_model(const std::string& m) { model_ = m; }
/* Newest activity first. Recomputes each session's tier histogram from the records, so it is
* a view and never a second copy of the truth. The walk takes the lock in slices and lets
@@ -545,6 +546,7 @@ private:
uint64_t first_seen_ns = 0;
uint64_t last_used_ns = 0;
std::vector<BlockHash> chain;
std::string label;
};
/* Erase one row and its root index entry together. */
+11 -37
View File
@@ -199,22 +199,20 @@ int Pools::configure(const Config& cfg, int64_t vram_capacity,
const int64_t MiB = 1024 * 1024;
const int64_t w = cfg.vram_weights_mib * MiB;
const int64_t kv = cfg.vram_kv_mib * MiB;
const int64_t hp = cfg.host_pool_mib * MiB;
const int64_t hp = (cfg.host_pool_mib + cfg.embedding_host_mib) * MiB;
/* THE BUDGETS ARE RESOLVED BEFORE THIS RUNS AND THIS DOES NOT RE-DECIDE THEM. Either the
* operator stated them or core/mem/vram_budget.cpp derived them from the card, the measured
* driver residency and the computed arena -- and either way they arrive here as two numbers
* with a report behind them. Either way this component refuses rather than shrinking
* anything: an engine that quietly re-optimises a split is an engine whose
* benchmarks do not reproduce (spec §6). A zero here means the resolver was never called,
* which is a wiring bug and gets named as one. */
/* THE BUDGETS ARE RESOLVED BEFORE THIS RUNS AND THIS DOES NOT RE-DECIDE THEM.
* core/mem/vram_budget.cpp derived them from the card, the measured driver residency and the
* computed arena, and they arrive here as two numbers with a report behind them. This
* component refuses rather than shrinking anything: an engine that quietly re-optimises a
* split is an engine whose benchmarks do not reproduce (spec §6). A zero here means the
* resolver was never called, which is a wiring bug and gets named as one. */
std::string missing;
if (cfg.vram_weights_mib <= 0) missing += " vram_weights resolved to 0 MiB\n";
if (cfg.vram_kv_mib <= 0) missing += " vram_kv resolved to 0 MiB\n";
if (!missing.empty()) {
fit_report_ = "VRAM pool budgets are empty -- state --vram-weights-mib / --vram-kv-mib, or "
"let the card be split from --gpu-headroom-mib and --host-pool-mib:\n"
+ missing;
fit_report_ = "VRAM pool budgets are empty: the budget resolver (core/mem/vram_budget.cpp) "
"did not run before the pools were configured:\n" + missing;
RAD_ERR("%s", fit_report_.c_str());
return RAD_E_INVAL;
}
@@ -230,8 +228,8 @@ int Pools::configure(const Config& cfg, int64_t vram_capacity,
" total %10s\n"
" card total %10s\n"
" OVER BY %10s\n"
"Lower --vram-weights-mib / --vram-kv-mib, or state neither and let the card be split "
"from --gpu-headroom-mib and --host-pool-mib (spec §6).\n",
"The resolved split is larger than the card, which the resolver does not produce: a "
"wiring bug (spec §6).\n",
humanb(w).c_str(), humanb(kv).c_str(),
humanb(want).c_str(), humanb(vram_capacity).c_str(),
humanb(want - vram_capacity).c_str());
@@ -239,30 +237,6 @@ int Pools::configure(const Config& cfg, int64_t vram_capacity,
return RAD_E_NOMEM;
}
/* THE SLACK IS NAMED, because nothing else will name it -- and after the resolver ran there
* should be almost none. `vram_capacity` is totalGlobalMem: it is not the free VRAM and it is
* not the sum of the budgets. What is left over here is the driver's residency, the activation
* arena, --gpu-headroom-mib, and whatever MiB rounding could not place; vram_budget.cpp's
* report breaks that down term by term. A budget a couple of GiB under the card is that much
* of the expert plane streaming from host memory instead, which costs real prefill throughput
* on a model whose experts do not fit.
*
* THIS IS FOR A STATED BUDGET AND ONLY FOR ONE. A size threshold cannot tell the two apart: a
* small dense model whose cache is already at the largest context it can address leaves many
* GiB that NOTHING can spend, and warning there would tell the operator to leave unset the
* very flags they already left unset. Where the resolver made the split it has already printed
* every term including the unusable one, and there is nothing to add. */
if (vram_capacity > 0 && !cfg.vram_budget_derived) {
const int64_t slack = vram_capacity - want;
if (slack >= 1024 * MiB)
RAD_WARN("VRAM budgets total %s of the card's %s, so %s is neither budgeted nor "
"accounted. The driver's context, the activation arena and "
"--gpu-headroom-mib come out of it; anything past those is throughput on the "
"floor. Leave --vram-weights-mib / --vram-kv-mib unset to have the card split "
"automatically.",
humanb(want).c_str(), humanb(vram_capacity).c_str(), humanb(slack).c_str());
}
int st = RAD_OK;
int s;
/* Order matters only for the diagnostic: allocate the two big ones first so a failure names
+2 -2
View File
@@ -342,7 +342,7 @@ int PrefixCache::insert(uint64_t session,
const std::vector<int32_t>& tokens,
const std::vector<MMContentKey>& mm,
const std::vector<std::vector<int32_t>>& blocks,
int64_t n_tokens) {
int64_t n_tokens, const std::string& label) {
if (!enabled_) return RAD_OK;
if (blocks.size() != groups_.size()) return RAD_E_INVAL;
if (n_tokens > (int64_t)tokens.size()) return RAD_E_INVAL;
@@ -427,7 +427,7 @@ int PrefixCache::insert(uint64_t session,
if (it == map_.end()) continue;
tiers_->note_used(hs[(size_t)b], it->second.blocks, now);
}
tiers_->note_session(session, hs, n_tokens, now);
tiers_->note_session(session, hs, n_tokens, now, label);
}
/* A CONVERSATION'S SNAPSHOTS BELONG TO ITS LATEST TURN. The index keys a session by REQUEST
+2 -1
View File
@@ -206,7 +206,8 @@ public:
const std::vector<int32_t>& tokens,
const std::vector<MMContentKey>& mm,
const std::vector<std::vector<int32_t>>& blocks,
int64_t n_tokens);
int64_t n_tokens,
const std::string& label = std::string());
/* Drop the least recently used entries, releasing their KV references. Returns how many were
* dropped. Blocks a live sequence still holds stay allocated -- releasing the cache's
+45 -68
View File
@@ -82,11 +82,21 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
const bool shared = host_reserve > b.headroom;
if (shared) b.headroom = host_reserve;
/* A host backend has no VRAM to speak of and reports none; there is nothing here to resolve
* and inventing a capacity would be exactly the inference §6 forbids. */
/* A DEVICE THAT REPORTS NO CAPACITY HAS NOTHING TO SPLIT, and inventing a capacity would be
* exactly the inference §6 forbids. What each pool needs is still known: the weights pool
* holds what the planner would copy out of the container -- the statics and experts
* weight_footprint counts -- and the cache is its ceiling, every sequence at the full context.
* (The host backend reports half the machine's memory and is split like a card.) */
if (b.capacity <= 0) {
b.weights = cfg.vram_weights_mib * kMiB;
b.kv = cfg.vram_kv_mib * kMiB;
b.weights = std::max<int64_t>(b.statics + b.expert_ceiling, kMiB);
b.kv = std::max<int64_t>(b.kv_ceiling, kMiB);
cfg.vram_weights_mib = to_mib_up(b.weights);
cfg.vram_kv_mib = to_mib_up(b.kv);
if (log)
b.report = fmt("the device reports no capacity: weights pool %s (what the planner "
"copies out of the container), cache %s (every sequence at the full "
"context)", humanb(cfg.vram_weights_mib * kMiB).c_str(),
humanb(cfg.vram_kv_mib * kMiB).c_str());
if (out) *out = b;
return RAD_OK;
}
@@ -98,17 +108,10 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
* plugin's init has run and its code object is resident. */
b.already_held = std::max<int64_t>(b.capacity - freeb, 0);
const bool want_w = cfg.vram_weights_mib <= 0;
const bool want_kv = cfg.vram_kv_mib <= 0;
b.derived_weights = want_w;
b.derived_kv = want_kv;
/* What is left after the terms nobody gets to spend. */
b.drift = (want_w || want_kv) ? kDriverDrift : 0;
int64_t fixed = b.already_held + b.drift + b.headroom + b.arena + b.staging + b.queues;
if (!want_w) fixed += cfg.vram_weights_mib * kMiB; /* a stated pool is fixed too */
if (!want_kv) fixed += cfg.vram_kv_mib * kMiB;
b.claimable = b.capacity - fixed;
b.drift = kDriverDrift;
b.claimable = b.capacity - (b.already_held + b.drift + b.headroom + b.arena + b.staging +
b.queues);
if (b.claimable < 0) {
b.report = fmt(
@@ -120,7 +123,6 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
" activation arena %10s (buffer plan + kernel scratch)\n"
" step staging %10s (block tables, media and KV tier staging)\n"
" hardware queues %10s (%d at %s each, measured)\n"
"%s%s"
" ------------------------------\n"
" SHORT BY %10s\n"
"Lower --gpu-headroom-mib, lower --max-num-batched-tokens (the arena scales with it), "
@@ -128,42 +130,31 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
humanb(b.capacity).c_str(), humanb(b.already_held).c_str(), humanb(b.drift).c_str(),
humanb(b.headroom).c_str(), humanb(b.arena).c_str(), humanb(b.staging).c_str(),
humanb(b.queues).c_str(), b.n_queues, humanb(b.queue_bytes).c_str(),
want_w ? "" : fmt(" --vram-weights-mib %10s (stated)\n",
humanb(cfg.vram_weights_mib * kMiB).c_str()).c_str(),
want_kv ? "" : fmt(" --vram-kv-mib %10s (stated)\n",
humanb(cfg.vram_kv_mib * kMiB).c_str()).c_str(),
humanb(-b.claimable).c_str());
if (log) RAD_ERR("%s", b.report.c_str());
if (out) *out = b;
return RAD_E_NOMEM;
}
b.weights = want_w ? 0 : cfg.vram_weights_mib * kMiB;
b.kv = want_kv ? 0 : cfg.vram_kv_mib * kMiB;
/* ---- the static weights come off the top ------------------------------------------------
*
* They are a floor and not a share. Only a DERIVED weight budget pays them here: an operator
* who stated --vram-weights-mib has already decided what the weights get, and second-guessing
* that is the re-optimisation §6 forbids. */
if (want_w) {
b.statics = std::min(b.statics, b.claimable);
if (b.statics >= b.claimable && b.claimable > 0) {
/* Not fatal: the planner will demote what does not fit and the model still serves,
* badly. Name it, because "why is this model 8x slower than it should be" has no other
* answer at startup. */
if (log) RAD_WARN("the static (non-expert) weights alone want %s of the %s this card has to "
"give. Every expert will stream from host memory and the KV cache has "
"nothing left -- this model wants more VRAM, fewer ranks of it, or a smaller "
"--max-num-batched-tokens.",
humanb(b.statics).c_str(), humanb(b.claimable).c_str());
}
* They are a floor and not a share. */
b.statics = std::min(b.statics, b.claimable);
if (b.statics >= b.claimable && b.claimable > 0) {
/* Not fatal: the planner will demote what does not fit and the model still serves,
* badly. Name it, because "why is this model 8x slower than it should be" has no other
* answer at startup. */
if (log) RAD_WARN("the static (non-expert) weights alone want %s of the %s this card has to "
"give. Every expert will stream from host memory and the KV cache has "
"nothing left -- this model wants more VRAM, fewer ranks of it, or a smaller "
"--max-num-batched-tokens.",
humanb(b.statics).c_str(), humanb(b.claimable).c_str());
}
b.elastic = want_w ? b.claimable - b.statics : b.claimable;
b.elastic = b.claimable - b.statics;
if (b.elastic < 0) b.elastic = 0;
/* ---- and only what is left is divided --------------------------------------------------- */
if (want_w && want_kv) {
{
/* An unset cache ceiling (plan_groups failed) bounds nothing; zero experts is a ceiling of
* zero, which weight_footprint always measures. */
const int64_t kv_cap = b.kv_ceiling > 0 ? b.kv_ceiling : b.elastic;
@@ -198,20 +189,12 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
b.kv = kv;
b.weights = b.statics + exp;
b.unusable = std::max<int64_t>(b.elastic - kv - exp, 0);
} else if (want_kv) {
b.kv = b.kv_ceiling > 0 ? std::min(b.claimable, b.kv_ceiling) : b.claimable;
b.unusable = b.claimable - b.kv;
} else if (want_w) {
/* The KV pool was stated, so `claimable` is already net of it; the weights take the rest,
* still capped at what the model has to put there. */
int64_t exp = b.elastic;
if (exp > b.expert_ceiling) {
b.unusable = exp - b.expert_ceiling;
exp = b.expert_ceiling;
}
b.experts = exp;
b.weights = b.statics + exp;
}
/* A POOL NOTHING IS PLACED IN STILL HAS TO EXIST. Where every weight is read where the
* container's mapping has it -- every op on the host, on the host backend -- the statics and
* experts are zero, and the pools refuse a zero budget as a resolver that never ran. A MiB,
* out of the headroom as the rounding's is. */
b.weights = std::max<int64_t>(b.weights, kMiB);
/* ---- THE PREFILL STAGING REGION, out of the expert share ---------------------------------
*
@@ -227,12 +210,12 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
* The share is the budget's -- what the slab alone leaves off -- which is the most a step can
* see: the loans the KV cache and the smaller arena levels make only ever add residency. A
* layer whose pooled part is larger than a buffer stages what fits and streams the rest. */
if (want_w && layer_max > 0 && b.expert_ceiling > b.experts && cfg.placement != "all_vram" &&
if (layer_max > 0 && b.expert_ceiling > b.experts && cfg.placement != "all_vram" &&
cfg.placement != "layer_offload") {
const double f = (double)(b.expert_ceiling - b.experts) / (double)b.expert_ceiling;
const int64_t one = ((int64_t)std::ceil(f * (double)layer_max) + RAD_ALIGN_UNIT - 1) /
RAD_ALIGN_UNIT * RAD_ALIGN_UNIT;
if (b.lends && want_kv) {
if (b.lends) {
/* A LENDING CACHE PAYS FOR IT: the experts are at their floor and a byte less would
* leave one with no tier, while the region is lent to the slab whenever the steps are
* small -- the same memory the cache would have lent. */
@@ -263,7 +246,7 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
* because it is a real limit rather than a ratio, is that ONE max-length sequence fits: a
* context no single request can complete is a configuration error however much slack the pool
* has (core/engine_bringup.cpp, configure_kv). */
if (log && b.derived_kv && b.kv_ceiling > 0 && cfg.max_ctx > 0)
if (log && b.kv_ceiling > 0 && cfg.max_ctx > 0)
RAD_INFO("kv: the pool backs %.0f%% of the worst case (%lld sequences all at %lld tokens), "
"%.1f full-length sessions. That is concurrency at length before the scheduler "
"preempts, not a bound on any one request. WITH PREFIX CACHING a finished "
@@ -276,13 +259,11 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
(long long)cfg.max_seqs, (long long)cfg.max_ctx,
(double)cfg.max_seqs * paged_share(b));
/* Rounding the floor up claims up to a MiB the split did not hand out. Take it back from the
* cache where the cache is ours to size -- a paged pool a MiB smaller addresses a handful
* fewer tokens and nothing else -- so the headroom stays whole. Where the KV budget was
* STATED it is not ours to shave and the MiB comes out of the headroom instead. */
cfg.vram_budget_derived = want_w || want_kv;
* cache -- a paged pool a MiB smaller addresses a handful fewer tokens and nothing else -- so
* the headroom stays whole. */
cfg.vram_weights_mib = to_mib_up(b.weights);
const int64_t w_over = cfg.vram_weights_mib * kMiB - b.weights;
cfg.vram_kv_mib = want_kv ? to_mib(std::max<int64_t>(b.kv - w_over, 0)) : to_mib(b.kv);
cfg.vram_kv_mib = to_mib(std::max<int64_t>(b.kv - w_over, 0));
/* THE RECEIPT. Every term, in the order it was spent, so that a split anybody disagrees with
* can be argued about against numbers instead of re-derived from sysfs by hand. The unclaimed
@@ -320,13 +301,11 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
humanb(b.arena).c_str(), humanb(b.staging).c_str(),
humanb(b.queues).c_str(), b.n_queues, humanb(b.queue_bytes).c_str(),
shared ? "left to the host" : "--gpu-headroom-mib", humanb(b.headroom).c_str(),
shared ? "integrated graphics: this memory is the host's; --vram-kv-mib states a pool "
"outright"
shared ? "integrated graphics: this memory is the host's"
: "left unclaimed on purpose",
humanb(b.claimable).c_str(),
humanb(b.statics).c_str(),
b.derived_weights ? "off the top: every rank's own shard, and not a share of anything"
: "(not charged here -- --vram-weights-mib was stated)",
"off the top: every rank's own shard, and not a share of anything",
humanb(b.elastic).c_str(),
b.lends ? "the experts keep what the host pool cannot hold; the cache takes the rest\n"
" and lends what no live request holds to the "
@@ -375,10 +354,8 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
"slab while steps are small\n", humanb(b.stage).c_str(),
b.lends ? "cache" : "experts").c_str()
: "",
humanb(cfg.vram_weights_mib * kMiB).c_str(),
b.derived_weights ? "static + experts" : "stated by --vram-weights-mib",
humanb(cfg.vram_kv_mib * kMiB).c_str(),
b.derived_kv ? "the cache's share" : "stated by --vram-kv-mib",
humanb(cfg.vram_weights_mib * kMiB).c_str(), "static + experts",
humanb(cfg.vram_kv_mib * kMiB).c_str(), "the cache's share",
humanb(unclaimed).c_str());
if (out) *out = b;
+14 -7
View File
@@ -3,7 +3,7 @@
* ============================== WHY THIS IS NOT THE §6 VIOLATION IT LOOKS LIKE ==============================
*
* Spec §6 says the engine does not derive its budgets, and core/mem/pools.cpp still refuses to
* re-optimise a split the operator stated. The reason given there is exact and worth repeating:
* re-optimise the split it is handed. The reason given there is exact and worth repeating:
* a budget derived from the FREE VRAM at startup is a benchmark that moves when somebody opens a
* window on the machine's desktop.
*
@@ -46,10 +46,17 @@
* (KVManager::ceiling), and an expert plane that fits entirely in VRAM has no use for more; when
* both fit, both are whole.
*
* A stated --vram-weights-mib or --vram-kv-mib still wins outright and turns the whole of this
* off for that pool. The point is that the DEFAULT is a full card rather than a guess: VRAM left
* THERE IS NO FLAG THAT STATES A POOL. The split is a full card rather than a guess: VRAM left
* unbudgeted is VRAM no pool can use, and on a model whose experts do not fit, every unbudgeted
* GiB costs measurable decode time.
* GiB costs measurable decode time. What an operator moves is the inputs -- --gpu-headroom-mib
* takes card space away, --max-model-len and --max-num-seqs bound the cache, --host-pool-mib
* decides which experts must stay on the card -- and the arithmetic follows from them.
*
* A HOST BACKEND HAS NO CARD, and half the machine's memory stands in for one (host_vram_bytes),
* split as a card's is. Its weights pool is host memory and holds what a host kernel cannot read
* where the container stores it (mapped_unit in core/place/planner.h). A device that reports no
* capacity at all is sized at what each pool needs: the weights the planner copies, and the cache
* at its ceiling.
*/
#pragma once
#include "../rad_core.h"
@@ -97,8 +104,9 @@ struct VramFacts {
int64_t host_reserve = 0;
};
/* The resolved split, in bytes, beside every term it came from. Always filled, including when the
* operator stated the budgets -- the placement report and the pool report both want the totals. */
/* The resolved split, in bytes, beside every term it came from. Always filled, including for a
* device that reports no capacity -- the placement report and the pool report both want the
* totals. */
struct VramBudget {
int64_t capacity = 0, already_held = 0, headroom = 0, arena = 0, staging = 0;
int64_t drift = 0; /* kDriverDrift: what already_held moves by after it is read */
@@ -120,7 +128,6 @@ struct VramBudget {
* any. */
int64_t stage = 0;
int64_t weights = 0; /* statics + experts: what vram_weights is set to */
bool derived_weights = false, derived_kv = false;
std::string report; /* the block the engine prints at startup */
};
+27 -5
View File
@@ -179,13 +179,35 @@ int to_rgb(const AVFrame* f, SwsContext** sws, Frame* out, std::string* why) {
src == AV_PIX_FMT_YUVJ444P || src == AV_PIX_FMT_YUVJ440P;
sws_setColorspaceDetails(*sws, coef, src_full, sws_getCoefficients(SWS_CS_DEFAULT), 1, 0,
1 << 16, 1 << 16);
/* THE SCALER WRITES INTO A FRAME FFMPEG ALLOCATED, and the rows are copied out. Its SIMD paths
* store whole vectors, so a row ends wherever the last vector does: a 4:2:0 or 4:2:2 picture
* 1788 wide converted with these flags writes 12 bytes past 1788 x 3, and into a buffer of
* exactly width x height x 3 those land on the next heap chunk's header -- the process aborts
* at a later allocation ("malloc(): corrupted top size"). av_frame_get_buffer pads every line
* and the end as the scaler expects. */
AVFrame* rgb = av_frame_alloc();
if (!rgb) { *why = "out of memory"; return RAD_E_NOMEM; }
rgb->format = AV_PIX_FMT_RGB24;
rgb->width = f->width;
rgb->height = f->height;
if (av_frame_get_buffer(rgb, 0) < 0) {
av_frame_free(&rgb);
*why = "out of memory";
return RAD_E_NOMEM;
}
const int e = sws_scale(*sws, f->data, f->linesize, 0, f->height, rgb->data, rgb->linesize);
if (e != f->height) {
av_frame_free(&rgb);
*why = "colour conversion failed";
return RAD_E_INVAL;
}
out->w = f->width;
out->h = f->height;
out->rgb.resize((size_t)f->width * (size_t)f->height * 3);
uint8_t* dst[4] = { out->rgb.data(), nullptr, nullptr, nullptr };
int dst_ls[4] = { f->width * 3, 0, 0, 0 };
const int e = sws_scale(*sws, f->data, f->linesize, 0, f->height, dst, dst_ls);
if (e != f->height) { *why = "colour conversion failed"; return RAD_E_INVAL; }
const size_t row = (size_t)f->width * 3;
out->rgb.resize(row * (size_t)f->height);
for (int y = 0; y < f->height; ++y)
std::memcpy(out->rgb.data() + (size_t)y * row, rgb->data[0] + (ptrdiff_t)y * rgb->linesize[0], row);
av_frame_free(&rgb);
return RAD_OK;
}
+4 -4
View File
@@ -114,8 +114,8 @@ Mover::~Mover() {
}
/* One place the mover asks for memory. Everything device-side and everything pinned comes out of
* the budgets the operator stated (spec §6); the fallback exists so the placement test can run
* without standing a whole Pools up, and it announces itself. */
* the resolved budgets (spec §6); the fallback exists so the placement test can run without
* standing a whole Pools up, and it announces itself. */
void* Mover::reserve(const char* what, int64_t bytes, int kind) {
if (bytes <= 0) return nullptr;
if (budget_) {
@@ -134,7 +134,7 @@ int Mover::init(const Program& prog, const Plan& plan, const MoverConfig& cfg, P
stats_ = MoverStats{};
if (!budget_)
RAD_WARN("mover: no Pools handed over; allocating its slab and host pool directly. That "
"double-spends --vram-weights-mib against whatever else already reserved it, so "
"double-spends the weights pool against whatever else already reserved it, so "
"it is a test path and not a deployment.");
unit_.assign(plan.units.size(), UnitState{});
@@ -180,7 +180,7 @@ int Mover::init(const Program& prog, const Plan& plan, const MoverConfig& cfg, P
* resident count is untouched by turning the engine on. Under a static plan the plan
* asked for none and the slab is exactly the resident set. */
/* THE PLAN'S NUMBER, not a config cap. The planner reserved these out of
* --vram-weights-mib and the report told the operator how many; allocating a different
* the weights pool and the report told the operator how many; allocating a different
* count here would mean the mover works against one number while the operator was charged
* for another, and the direction that is wrong in is an overrun. */
const int64_t shadow = plan.dynamic ? sc.n_shadow : 0;
+4 -4
View File
@@ -336,7 +336,7 @@ private:
/* ------------------------------------------------------------------ configuration */
struct MoverConfig {
/* Shadow slots and the staging ring are NOT here. They are budgeted by the planner out of
* --vram-weights-mib and reported in the plan (SlabClass::n_shadow, n_stage), and a second
* the weights pool and reported in the plan (SlabClass::n_shadow, n_stage), and a second
* knob for the same quantity is a second number for the mover and the operator to disagree
* about -- with an overrun as the direction that disagreement goes wrong in.
*
@@ -419,7 +419,7 @@ public:
* diagnosis.
*
* `budget` IS THE PRODUCTION PATH AND SHOULD ALWAYS BE PASSED. Pools already allocated
* --vram-weights-mib as one block; a mover that called rad_dev_alloc beside it would spend
* the weights pool as one block; a mover that called rad_dev_alloc beside it would spend
* that budget TWICE and the overrun would surface as an out-of-memory from an unrelated
* launch much later. Reserving from Pools::weights() is also what makes it structurally
* impossible for a promotion to reach a KV block -- there is no path from the weights pool to
@@ -598,7 +598,7 @@ public:
* grouped GEMM is handed every expert's pointer at issue -- so before a routed layer's first
* expert op, every one of its file-tier units is read into a VRAM buffer and published there,
* and after the layer it is published as null again (unstage_units does that half). The
* buffers are the two the plan charged out of --vram-weights-mib (Plan::file_stage_vram).
* buffers are the two the plan charged out of the weights pool (Plan::file_stage_vram).
*
* stage_file_units read every unit of `units` that is on the file tier into `dst`, packed at
* RAD_ALIGN_UNIT in the order given, through the pinned read windows: the
@@ -655,7 +655,7 @@ private:
};
/* One weight class's memory. The slab is two kinds of slot rather than one: the BUDGETED slots
* come out of --vram-weights-mib like every other weight allocation and sit at a fixed stride
* come out of the weights pool like every other weight allocation and sit at a fixed stride
* from one base, and the FLEX slots past them are addresses inside another pool's memory --
* the KV cache's carve, the activation arena's top -- lent while that pool is not using them.
* They cannot be one range because the flex slots are scattered over every layer's stripe of
+24 -15
View File
@@ -80,7 +80,7 @@ int strategy_parse(const char* s, Strategy* out) {
Budgets Budgets::from(const Config& c) {
Budgets b;
b.vram_weights = c.vram_weights_mib * 1024 * 1024;
b.host_pool = c.host_pool_mib * 1024 * 1024;
b.host_pool = (c.host_pool_mib + c.embedding_host_mib) * 1024 * 1024;
b.ssd = c.weights_disk_tier;
return b;
}
@@ -123,7 +123,7 @@ int plan_check_weights_pool(const Plan& p, int64_t pool_bytes) {
}
void weight_footprint(const Program& prog, WeightFootprint* out, TablePlacement embedding,
TablePlacement ngram) {
TablePlacement ngram, bool host_backend, bool container) {
if (!out) return;
*out = WeightFootprint{};
@@ -146,7 +146,7 @@ void weight_footprint(const Program& prog, WeightFootprint* out, TablePlacement
/* build_units: a model-level weight is its own unit, everything else groups by the declared
* (layer, expert). Ordered, for the same reason build_units is. */
struct U { int32_t layer = -1, expert = -1; int64_t bytes = 0; bool mapped = false;
bool emb = false, ngram = false, host = true; };
bool emb = false, ngram = false, host = true, direct = true; };
std::map<std::pair<int32_t, int32_t>, size_t> by_group;
std::vector<U> units;
@@ -175,6 +175,7 @@ void weight_footprint(const Program& prog, WeightFootprint* out, TablePlacement
mu.bytes = align_up(mu.bytes, a) + weight_bytes(wi);
/* pin_mapped: THE WHOLE UNIT GOES, not the one weight. */
if (w < device_ok.size() && !device_ok[w]) mu.mapped = true;
if (!weight_file_direct(wi, prog.ctx.world_size)) mu.direct = false;
if (w < host_ok.size() && !host_ok[w]) mu.host = false;
/* The placement flags' tables: model-level, so the unit is this one weight. */
if (layer < 0) {
@@ -186,6 +187,7 @@ void weight_footprint(const Program& prog, WeightFootprint* out, TablePlacement
/* And one align_up a unit, because that is how Mover::init spends the slab: `us.static_off =
* align_up(static_need, RAD_ALIGN_UNIT)` before every unit it places. A budget that summed raw
* bytes would be short by one alignment per unit, which on a 512-expert MoE is real. */
for (U& mu : units) mu.mapped = mapped_unit(mu.mapped, container && mu.direct, host_backend);
std::map<int32_t, int64_t> layer_experts;
std::set<int64_t> expert_strides;
bool ngram_host = true;
@@ -284,8 +286,8 @@ void Planner::resolve_sites(const Program& prog) {
* consulted, because it is not a budget question -- and so is an n-gram table --ngram-placement put
* in RAM or on disk, whatever kernels could read it on a card. The other three off-device tiers are
* what the planner falls back to when VRAM runs out; this one is where the weight has to be
* whatever the budgets say, and charging a pool for bytes that are never copied would make the
* operator size a pool against a number that does not exist.
* whatever the budgets say, and charging a pool for bytes that are never copied would size that
* pool against a number that does not exist.
*
* THE WHOLE UNIT GOES, not the one weight. A unit is the movement granularity and a half-mapped one
* has no meaning -- and it costs nothing here, because `device_ok_` is cleared for EVERY weight
@@ -295,9 +297,15 @@ void Planner::resolve_sites(const Program& prog) {
void Planner::pin_mapped(const Program& prog, Plan* p) {
const TablePlacement ng = in_.config->ngram_resolved;
for (MoveUnit& mu : p->units) {
bool host_only = false;
for (rad_weight w : mu.weights)
bool host_only = false, direct = in_.container;
for (rad_weight w : mu.weights) {
if (w < device_ok_.size() && !device_ok_[w]) host_only = true;
if (w < prog.weights.size() &&
!weight_file_direct(prog.weights[w], prog.ctx.world_size)) direct = false;
}
/* On the host backend a unit stored in another form than its host kernel reads is placed
* like any other weight, in the pool its kernel can read too (mapped_unit). */
host_only = mapped_unit(host_only, direct, in_.host_backend);
/* --ngram-placement keeps an n-gram table OFF THE CARD unless it says vram, whether or not
* a device kernel could read it there: ram and disk are where the operator put it, and the
* strategies below would otherwise spend the card on 48 GB of rows read sixteen a token. */
@@ -619,8 +627,8 @@ int Planner::assign_all_vram(Plan* p) {
used += mu.slot_bytes;
}
if (p->vram_budget > 0 && used > p->vram_budget) {
p->notes.push_back(fmt("all_vram needs %s of weights against a --vram-weights-mib "
"budget of %s: %s short",
p->notes.push_back(fmt("all_vram needs %s of weights against a weights pool "
"of %s: %s short",
humanb(used).c_str(), humanb(p->vram_budget).c_str(),
humanb(used - p->vram_budget).c_str()));
return RAD_E_NOMEM;
@@ -768,9 +776,9 @@ int Planner::assign_expert_tiered(Plan* p) {
rank_units(p, &order);
/* RESERVE THE SPARE SLOTS OUT OF THE BUDGET. The slab has to hold the residents AND the
* shadow slots a promotion writes into, and they all come out of --vram-weights-mib -- so a
* shadow slots a promotion writes into, and they all come out of the weights pool -- so a
* fill that spends the whole budget on residents leaves the mover with nowhere to move into
* and, worse, makes the mover's allocation overrun the pool the operator sized.
* and, worse, makes the mover's allocation overrun the weights pool.
*
* Two passes, and the second is enough: the reserve depends only on the first pass's slot
* counts, and the first pass over-counts (it had more room), so the reserve it produces is an
@@ -900,7 +908,7 @@ int Planner::assign_expert_tiered(Plan* p) {
k = fill(uncapped, --cap);
if (fixed + k.used + k.spare + k.file > p->vram_budget) {
p->notes.push_back(fmt("the file tier's two layer buffers need %s, beside %s of "
"fixed weights, against a --vram-weights-mib budget of %s",
"fixed weights, against a weights pool of %s",
humanb(k.file).c_str(), humanb(fixed).c_str(),
humanb(p->vram_budget).c_str()));
return RAD_E_NOMEM;
@@ -1119,8 +1127,8 @@ int Planner::pin_embedding(const Program& prog, const Config& cfg, Plan* p) cons
mu.host_forced = true;
mu.reason = "--embedding-placement ram; read over the link in place";
RAD_INFO("placement: '%s' (%s) in the pinned host pool, read in place "
"(--embedding-placement %s)", name.c_str(), humanb(mu.bytes).c_str(),
cfg.embedding_placement == TablePlacement::Auto ? "auto" : "ram");
"(--embedding-placement ram%s)", name.c_str(), humanb(mu.bytes).c_str(),
cfg.embedding_placement_given ? "" : ", the default");
}
/* Engine::plan resolves Ram only where weight_footprint found a table with this same test,
* so an empty pass is a plan built from a different program than the budget was: a wiring
@@ -1243,7 +1251,8 @@ int Planner::assign(Plan* p) {
/* Every pool is budgeted explicitly (spec §6). An offload strategy with no number to
* spill against would have to infer one from free VRAM, and an engine that quietly
* re-optimises its own split is an engine whose benchmarks do not reproduce. */
RAD_ERR("placement: %s needs --vram-weights-mib; there is nothing to spill against",
RAD_ERR("placement: %s needs a weights budget and none was resolved; there is nothing to "
"spill against",
strategy_name(s));
return RAD_E_INVAL;
}
+23 -6
View File
@@ -111,7 +111,7 @@ struct MoveUnit {
/* WHAT THE UNIT ACTUALLY COSTS A POOL, which is its class's slot stride and not `bytes`. The
* planner budgets against this and the mover allocates this, so the two cannot drift -- and
* the direction they would drift in is an overrun of the pool the operator sized. `bytes` is
* the direction they would drift in is an overrun of the weights pool. `bytes` is
* still what the report attributes to the weights, because padding is not a weight. */
int64_t slot_bytes = 0;
@@ -179,7 +179,7 @@ struct SlabClass {
/* SHADOW SLOTS: slab slots that are allocated but hold no unit, so a promotion writes into one
* and only then publishes and never DMAs over a slot a kernel might still be reading (mover.h).
*
* THEY COME OUT OF --vram-weights-mib, like everything else in the slab. Taking them from
* THEY COME OUT OF THE WEIGHTS POOL, like everything else in the slab. Taking them from
* whatever VRAM is left over after the slabs is not an option: spec §6 budgets every pool
* explicitly and --gpu-headroom-mib is memory the engine promises NOT to touch. So dynamic
* placement costs a few resident units, and the plan report prints exactly how many.
@@ -260,7 +260,7 @@ public:
* routed layer starts (place/stager.h, FileStager). `file_layer_max` is the most one layer's
* file-tier units take in a buffer, each at its own size rounded to RAD_ALIGN_UNIT, which is
* how the stager packs them; `file_stage_vram` is the two buffers, taken out of
* --vram-weights-mib before any expert is made resident. Both 0 when nothing routed is on the
* the weights pool before any expert is made resident. Both 0 when nothing routed is on the
* file tier. */
int64_t file_layer_max = 0;
int64_t file_stage_vram = 0;
@@ -310,8 +310,23 @@ struct PlannerInput {
* served directly is neither grouped by movement unit nor aligned for O_DIRECT, so with this
* false no unit is file-direct and both tiers are closed (spec §4.3). */
bool container = true;
/* No card is visible and the device backend is the host's own memory (device_is_host()), so a
* host kernel can read the weights pool as well as the container's mapping. See
* mapped_unit(). */
bool host_backend = false;
};
/* DOES A UNIT STAY IN THE CONTAINER'S MAPPING because only a host kernel can read it? On a card,
* always: a host kernel cannot read VRAM, and the mapping is the one host address its bytes
* already have. On the host backend the weights pool is host memory too, and a unit whose stored
* form is not the container's (a widening or a relayout its host kernel asked for at load, or a
* checkpoint served directly) has no place in the mapping that looks the way its kernel reads it,
* so there it takes a converted copy in the weights pool like any other weight. One rule, for the
* planner and the budget alike. */
inline bool mapped_unit(bool host_only, bool direct, bool host_backend) {
return host_only && (direct || !host_backend);
}
class Planner {
public:
explicit Planner(const PlannerInput& in) : in_(in) {}
@@ -399,10 +414,12 @@ struct WeightFootprint {
};
/* `embedding` is what the token embedding's placement resolved to; only Ram moves it out of the
* statics. `ngram` is the n-gram table's; only Vram puts it among them, and only where a device
* kernel reads it. Stated by every caller, so the budget and the planner cannot count it
* differently. */
* kernel reads it. `host_backend` and `container` are PlannerInput's: whether a host kernel can
* read the weights pool, and whether the weights lie in a container at all (a checkpoint served
* directly has no mapping a unit could stay in). Stated by every caller, so the budget and the
* planner cannot count it differently. */
void weight_footprint(const Program& prog, WeightFootprint* out, TablePlacement embedding,
TablePlacement ngram);
TablePlacement ngram, bool host_backend, bool container);
/* THE PINNED STAGING THE FILE TIER TAKES OUT OF --host-pool-mib before any unit is placed in it:
* RAD_PLACE_FILE_STAGE_SLOTS of the widest per-layer unit, and the read windows when a routed
+61 -16
View File
@@ -360,12 +360,16 @@ int Registry::commit_(Staged& s, int order) {
* libraries for several cards would serve none of them but the first in the hierarchy.
* What the library carries is read out of the fat binaries its dlopen registered, which is
* what the launch itself will consult (core/device/aql_code.cpp), not out of
* build_target, which is prose. Its host rows run anywhere and stay. */
* build_target, which is prose. Its host rows run anywhere and stay. On the host backend
* an engine that serves says no GPU code runs at all (set_no_device_code). */
int n_device = 0;
for (const auto& r : staged_rows) n_device += r.first->domain == RAD_DOMAIN_DEVICE;
std::string why;
if (no_device_code_)
why = "no card is visible, so this process runs on the host backend and no GPU code "
"object runs here";
if (n_device > 0 && s.code_to > s.code_from &&
rad::dev_code_runs(s.code_from, s.code_to, code_device_, &why) == 0) {
(no_device_code_ || rad::dev_code_runs(s.code_from, s.code_to, code_device_, &why) == 0)) {
std::vector<std::pair<const RadKernelInfo*, int>> keep;
for (const auto& r : staged_rows)
if (r.first->domain != RAD_DOMAIN_DEVICE) keep.push_back(r);
@@ -480,8 +484,8 @@ int Registry::commit_(Staged& s, int order) {
if (rad_dev_count() > code_device_ && rad_dev_props(code_device_, &dp) == RAD_OK &&
dp.arch[0] && !target_covers(p.build_target, dp.arch))
RAD_WARN("kernel plugin '%s' declares it was built for %s and this machine reports %s. "
"Its kernels will fail to launch; build it for %s, or put a library that "
"serves this device ahead of it with --kernels.",
"Its kernels will fail to launch; build it for %s, or leave it out with "
"--kernels.",
p.name.c_str(), p.build_target.c_str(), dp.arch, dp.arch);
}
@@ -576,33 +580,74 @@ int Registry::load_dirs(const std::vector<std::string>& dirs,
staged.push_back(s);
}
/* The hierarchy is configured, not discovered. A plugin the operator named takes that
* position; a plugin present on disk but absent from the list loads after everything named,
* so dropping an .so into the directory adds it with no configuration and naming it ahead of
* another is what substitutes it.
/* An entry names a library by its declared name or by its file, written as the operator sees
* it on disk: `libr4d`, `r4d`, `libr4d.so` and a path to it are one library. */
auto names = [](const std::string& h, const Staged& s) {
return h == s.name || h == s.file || stem_of(h) == s.file;
};
std::string found; /* every kernel library on the search path, for a list that names none */
for (const Staged& s : staged)
if (s.info && s.info->kind == RAD_PLUGIN_KERNEL)
found += (found.empty() ? "" : ", ") + s.name;
/* A HIERARCHY NAMES THE KERNEL LIBRARIES THAT SERVE, AND ONLY THOSE LOAD. Ordering alone
* cannot keep a library out: selection runs per domain, so a library named first that has no
* device row for an op leaves that op to whichever unnamed library does -- a GPU library on a
* machine whose card it was not built for, say -- and an operator who listed what to use gets
* something else. A kernel library on the search path that the list leaves out is closed again
* before it registers anything, and said once. Architecture and quantiser plugins are not
* kernel libraries and no list ranks them. */
if (!hierarchy.empty()) {
std::vector<Staged> kept;
std::string left_out;
for (Staged& s : staged) {
const bool kernel = s.info && s.info->kind == RAD_PLUGIN_KERNEL;
const bool named = std::find_if(hierarchy.begin(), hierarchy.end(),
[&](const std::string& h) {
return names(h, s);
}) != hierarchy.end();
if (!kernel || named) {
kept.push_back(s);
continue;
}
left_out += (left_out.empty() ? "" : ", ") + s.name;
unstage_(s);
}
staged.swap(kept);
if (!left_out.empty())
RAD_INFO("kernel libraries on the search path that --kernels (or RADIANCE_KERNELS) "
"does not name, and so not loaded: %s", left_out.c_str());
}
/* The hierarchy is configured, not discovered: a library the operator named takes that
* position. With no list every kernel library on the search path loads, so dropping an .so
* into the directory adds it with no configuration.
*
* A REFERENCE LIBRARY IS PINNED BELOW EVERY OTHER UNNAMED PLUGIN. It declares a kernel for
* every op it knows, so a plugin ranked behind it is unreachable -- an unnamed kernel library
* for this machine's card would load, never be selected for anything, and leave the whole
* model resolving to the naive implementation. Pinning it is what makes an unconfigured
* drop-in work. Naming it in the hierarchy overrides this, which is how it is put in front of
* a library to compare against. Which library is one is its own declaration
* drop-in work. Naming it in the hierarchy places it where it is named, which is how it is put
* in front of a library to compare against. Which library is one is its own declaration
* (RadPluginReferenceFn), not its name. */
const size_t kUnnamed = (size_t)INT_MAX - 1;
std::vector<size_t> rank(staged.size());
for (size_t i = 0; i < staged.size(); ++i)
rank[i] = staged[i].reference ? (size_t)INT_MAX : kUnnamed;
for (size_t h = 0; h < hierarchy.size(); ++h) {
bool found = false;
bool hit = false;
for (size_t i = 0; i < staged.size(); ++i) {
if (staged[i].name == hierarchy[h] || staged[i].file == hierarchy[h]) {
if (names(hierarchy[h], staged[i])) {
rank[i] = h;
found = true;
hit = true;
}
}
if (!found)
RAD_WARN("kernel hierarchy names '%s', which is not in %s -- ignored",
hierarchy[h].c_str(), dir.c_str());
/* The list is what loads, so an entry that matches nothing is a library that is not
* there to select -- and a list none of whose entries match loads no kernel library. */
if (!hit)
RAD_WARN("--kernels (or RADIANCE_KERNELS) names '%s', which is no kernel library in "
"%s, so nothing loads in its place; the kernel libraries there are: %s",
hierarchy[h].c_str(), dir.c_str(), found.empty() ? "none" : found.c_str());
}
std::vector<size_t> idx(staged.size());
for (size_t i = 0; i < idx.size(); ++i) idx[i] = i;
+14 -4
View File
@@ -150,10 +150,12 @@ public:
/* ---------------------------------------------------------- loading (§2, §18) */
/* Scan a directory of .so files and load them in HIERARCHY ORDER. The hierarchy is configured,
* not discovered: `hierarchy` is an ordered list of plugin names (RadPluginInfo::name, or the
* file's stem, whichever the operator wrote), so substituting a kernel is dropping an .so in a
* directory and naming it ahead of the default. A plugin present on disk but absent from the
* list loads at the END, after everything named, in filename order so the result is
* reproducible.
* file as the operator wrote it -- `libr4d`, `r4d`, `libr4d.so`), so substituting a kernel is
* dropping an .so in a directory and naming it ahead of the default. A non-empty list is
* EXCLUSIVE: a kernel library it does not name is closed before it registers anything, and an
* entry that matches nothing is warned about by name. An empty list loads every kernel library
* found, in filename order so the result is reproducible, with a reference library last.
* Architecture and quantiser plugins are not ranked and always load.
*
* Always completes: every plugin that can be loaded is, every refusal is recorded in
* load_errors(), and the FIRST negative status is returned. Reporting the whole list beats
@@ -181,6 +183,13 @@ public:
* loads anything, once it has chosen its cards. */
void set_code_device(int device) { code_device_ = device; }
/* THE ENGINE ABOUT TO SERVE ON THE HOST BACKEND SAYS SO: no card is visible, and no GPU code
* object runs in this process at all. A kernel library that brought device code then has its
* device rows left out of selection at load, its host rows staying, so every op takes its host
* kernel. Only the engine says this. A tool that selects without serving -- rad-convert's
* recipe check, rad-kbench's tables, a test of a library's constraints -- sees every row, as
* it would on the machine the model is served on. */
void set_no_device_code(bool v) { no_device_code_ = v; }
/* WHAT THE ENGINE MEASURED ABOUT THE RANKS' DEVICES, for the constraints on "device." keys
* (rad_types.h). Set before the first selection, by whoever chose the devices; a registry
* nobody told anything has no facts, and a kernel constrained on one is not selected. */
@@ -333,6 +342,7 @@ private:
};
int code_device_ = 0;
bool no_device_code_ = false;
Geometry device_facts_;
TuneCache tune_;
+61 -17
View File
@@ -122,11 +122,12 @@ enum class Tier { VRAM = 0, HostPinned = 1, HostPageable = 2, SSD = 3, Mapped =
* it, and why the operator gets to choose.
*
* Vram resident on the card, a weight like any other.
* Ram in host memory the card or a host kernel reads in place: the embedding in the pinned
* host pool, read over the link; an n-gram table as a locked copy made at load.
* Disk read from the container on demand.
* Auto the fastest of the three that has room once every other weight is placed; Engine::plan
* decides it and writes the answer into Config, so every rank plans from one choice. */
* Ram in host memory the card or a host kernel reads in place: the embedding pinned beside
* the host pool, read over the link; an n-gram table as a copy made at load.
* Disk read from the container on demand; the n-gram table's only.
* Auto the fastest of the three that has room once every other weight is placed; the n-gram
* table's only. Engine::plan decides it and writes the answer into Config, so every rank
* plans from one choice. The embedding takes Ram or Vram. */
enum class TablePlacement { Auto = 0, Vram = 1, Ram = 2, Disk = 3 };
const char* table_placement_name(TablePlacement p);
/* --draft-window: how many drafts a step verifies for each sequence (core/sched/draft.h).
@@ -405,9 +406,18 @@ public:
std::string span; /* the band, as Band::span */
std::string why;
int domain = 0; /* RAD_DOMAIN_DEVICE | RAD_DOMAIN_HOST */
int32_t index = 0; /* the instance that missed (OpInfo::index): bands are its own */
std::string line() const; /* "op geometry [domain] -> why", the full-detail rendering */
};
std::vector<Miss> misses;
/* THE DEVICE MISSES A REQUEST CAN FALL INTO, in `misses` order: the device bands no kernel
* serves and no host kernel stands in for. A host kernel for the same band stands in on the
* host backend, where every op without a device row runs on the host (Ctx::bind_ops); on a
* card it stands in only for an op that has weights, because the planner moves an op to the
* host by placing its weights there and has nothing to place for an op without them --
* attention over a cache that lives in VRAM is the case that matters. One rule for the engine
* that refuses to start on a hole and for the tools that count them. */
std::vector<const Miss*> device_holes(bool host_backend) const;
/* Every (kernel, shape) pair rad-tune would need to benchmark (spec §15). */
/* `info` is the kernel's own row, so rad-tune can read its RadTunable axes and expand the
@@ -482,6 +492,24 @@ struct ReasoningCount {
bool inside() const { return st == Think; }
};
/* THE MOST ALTERNATIVES ONE TOKEN'S LOGPROBS MAY CARRY: OpenAI's bound on top_logprobs. A request
* above it is refused. The sampler declares `sample_logprobs` one wider (Sampler::kLpK), for the
* width of the row the split-vocabulary gather moves; the extra pair is never reported. */
static constexpr int RAD_MAX_LOGPROBS = 20;
/* One emitted token's log-probability under the model's RAW distribution -- the logits before any
* penalty, temperature, mask or cut -- and its `n_top` most likely alternatives in descending
* order, ties to the lower id. What OpenAI's `logprobs` and llama-server's `n_probs` report.
* `token` -1 is a token whose logprobs could not be computed (a row with no finite logit): the
* scheduler fails its request rather than report a number for it. */
struct TokenLogprobs {
int32_t token = -1;
float logprob = 0.0f;
int32_t n_top = 0;
int32_t top_id[RAD_MAX_LOGPROBS] = {};
float top_lp[RAD_MAX_LOGPROBS] = {};
};
struct SamplingParams {
float temp = 1.0f;
int top_k = 0; /* 0 = off */
@@ -498,6 +526,14 @@ struct SamplingParams {
int dry_penalty_last_n = -1;
float xtc_probability = 0.0f;
float xtc_threshold = 0.1f;
/* TEMPERATURE AFTER THE CUTS rather than before them: top-p, min-p, typical and XTC read the
* distribution at temperature 1 and the pick draws at `temp`. llama.cpp's default order; the
* default here is vLLM's, temperature first. A request names the order with `samplers`. */
bool temp_last = false;
/* LOGPROBS: -1 is none; 0..RAD_MAX_LOGPROBS returns every emitted token's logprob and that
* many alternatives. Speculation is unaffected: every verified position is a row of its own,
* and an accepted draft is the token the target drew there. */
int n_probs = -1;
uint64_t seed = 0;
bool greedy() const { return top_k == 1 || temp <= 0.0f; }
std::string grammar; /* GBNF, or "" */
@@ -610,6 +646,11 @@ struct Request {
* embedding program (rad_declare_pooled) serves these, and it serves nothing else. */
bool embed = false;
/* THE CONVERSATION AS THE CLIENT NAMES IT (OpenRouter's `session_id`), "" when it names
* none: carried to the session the prefix cache records for it, as a label on /sessions and
* the dashboard. It changes nothing about how the request is served. */
std::string session_label;
std::string finish_reason;
void* sink = nullptr; /* the server's per-request stream sink */
};
@@ -620,7 +661,8 @@ struct Request {
enum { RAD_P2P_AUTO = 0, RAD_P2P_ON = 1, RAD_P2P_OFF = 2 };
struct Config {
std::string model; /* path to the .rad */
std::string model; /* path to the .rad, or a Hugging Face repo id (hf_model.h) */
std::string download_dir; /* where a repo id is fetched to; empty = the XDG cache */
std::string radiance_home;
std::vector<std::string> kernel_hierarchy; /* ordered; first wins */
@@ -661,8 +703,8 @@ struct Config {
* YaRN off; empty serves what the checkpoint says. Engine::apply_rope_scaling. */
std::string rope_scaling;
/* THE OPERATOR STATES A BUDGET OR THE ENGINE DERIVES ONE FROM THE CARD, AND EITHER WAY IT IS
* STATED IN FULL BEFORE ANYTHING IS ALLOCATED.
/* THE ENGINE DERIVES THE BUDGET FROM THE CARD, AND IT IS STATED IN FULL BEFORE ANYTHING IS
* ALLOCATED.
*
* Spec §6 forbids a derived budget because a budget derived from the FREE VRAM at startup is
* a benchmark that moves when a desktop opens a window. What it does not forbid is arithmetic
@@ -676,7 +718,7 @@ struct Config {
* still one number per card, and the same number on every card whose cache costs as much per
* token as the dearest rank's.
*
* Zero means "derive"; a stated --vram-weights-mib / --vram-kv-mib still wins outright. */
* NO FLAG SETS THEM: zero until the resolver has run. */
int64_t vram_weights_mib = 0;
int64_t vram_kv_mib = 0;
int64_t gpu_headroom_mib = 96; /* --gpu-headroom, left unclaimed on every card */
@@ -689,11 +731,6 @@ struct Config {
* a third name for the second one, and a flag whose values are not all distinct is a flag
* whose log line cannot be read back. */
std::string kv_cache_dtype = "bf16";
/* SET BY THE RESOLVER, NOT BY A FLAG. vram_budget_resolve writes the two budgets above into
* this config, which erases the only evidence of whether they were stated or derived -- and
* Pools needs that to know whether unspent VRAM is a mis-stated budget worth warning about or
* a split it made itself and already printed a receipt for. */
bool vram_budget_derived = false;
int64_t host_pool_mib = 0;
/* THE FILE TIER FOR WEIGHTS: what fits neither the VRAM slab nor the pinned host pool is read
* from the container itself, with O_DIRECT, ahead of the ops that read it -- a scheduled unit by
@@ -705,11 +742,19 @@ struct Config {
std::string placement = "auto"; /* all_vram | layer_offload | expert_tiered | auto */
/* --embedding-placement and --ngram-placement, as asked (TablePlacement says what each tier
* is), and what Engine::plan resolved them to before any rank planned: never Auto. */
TablePlacement embedding_placement = TablePlacement::Auto;
* is), and what Engine::plan resolved them to before any rank planned: never Auto. The
* embedding's default is Ram; `embedding_placement_given` says whether the operator named it,
* because a named tier that cannot be honoured stops the server where the default gives way
* to the card with the reason. */
TablePlacement embedding_placement = TablePlacement::Ram;
bool embedding_placement_given = false;
TablePlacement ngram_placement = TablePlacement::Auto;
TablePlacement embedding_resolved = TablePlacement::Vram;
TablePlacement ngram_resolved = TablePlacement::Disk;
/* SET BY THE RESOLVER: the pinned host room the token embedding takes when it resolves to Ram,
* a rank, ON TOP OF host_pool_mib -- so the table never takes the experts' share of the pool,
* and a dense model that has no pool still has a place for it. */
int64_t embedding_host_mib = 0;
bool deterministic = false;
int64_t checkpoint_interval = 2048; /* linear-state checkpoints (spec §7.3) */
/* HOW MANY LINEAR-STATE SNAPSHOTS THE SERVER MAY HOLD AT ONCE -- a CAP and not a charge.
@@ -921,5 +966,4 @@ struct Config {
namespace rad {
int config_parse(int argc, char** argv, Config* c);
void config_usage(const char* argv0);
bool resolve_hf_model(Config& c); /* --model given as an HF repo id: fetch into the cache, rewrite c.model */
}
+4 -1
View File
@@ -577,13 +577,16 @@ int32_t host_sample_into(CandidateSet& s, const SamplingParams& sp, const HostRe
}
if (order == ChainOrder::Radiance) {
host_temp(s, sp.temp);
/* `temp_last` moves temperature behind the cuts, as the device chain moves it onto the
* candidate plane (Sampler::issue); the cuts keep this order either way. */
if (!sp.temp_last) host_temp(s, sp.temp);
host_mask(s, in.bitmask, in.n_words);
host_top_k(s, sp.top_k);
host_top_p(s, sp.top_p, 1);
host_min_p(s, sp.min_p, 1);
host_typical(s, sp.typical_p, 1);
host_xtc(s, sp.xtc_probability, sp.xtc_threshold, 1, sp.seed, in.pos);
if (sp.temp_last) host_temp(s, sp.temp);
} else {
/* llama.cpp's default order, for checking this port against llama.cpp itself. Note the
* absence of top-n-sigma: it is not in SamplingParams and radiance does not ship it, so a
+302 -9
View File
@@ -6,6 +6,7 @@
#include <algorithm>
#include <chrono>
#include <cmath>
#include <cstring>
namespace rad {
@@ -177,6 +178,8 @@ int Sampler::declare(RadBuilder* b, const SamplerConfig& cfg) {
buf_params_ = decl("sampler.params", RAD_U32, rows,
(int64_t)(sizeof(DeviceSampleParams) / 4), RAD_BUF_PERSIST);
buf_params_late_ = decl("sampler.params_late", RAD_U32, rows,
(int64_t)(sizeof(DeviceSampleParams) / 4), RAD_BUF_PERSIST);
buf_hist_ = decl("sampler.history", RAD_I32, rows, cfg_.max_hist, RAD_BUF_PERSIST);
/* One byte beside every history token: nonzero where that token is a whole DRY sequence
* breaker, which DRY never penalises. Resolving a token against the breaker strings needs the
@@ -194,7 +197,16 @@ int Sampler::declare(RadBuilder* b, const SamplerConfig& cfg) {
ncand * cfg_.world_size * 2, RAD_BUF_TRANSIENT);
}
if (!buf_params_ || !buf_hist_ || !buf_brk_ || !buf_mask_ || !buf_cand_i_ || !buf_cand_v_) {
/* THE LOGPROBS SUMMARY, PERSIST for the reason the staging planes are: nothing in the
* declared op list reads it -- rank 0 copies it to the host behind the pick -- so liveness
* over the op list would hand its bytes to the candidate planes the stages after it write. */
buf_lp_ = decl("sampler.logprobs", RAD_F32, rows, lp_width(), RAD_BUF_PERSIST);
if (vocab_parallel())
buf_lp_g_ = decl("sampler.logprobs_gathered", RAD_F32, rows,
lp_width() * cfg_.world_size, RAD_BUF_PERSIST);
if (!buf_params_ || !buf_params_late_ || !buf_hist_ || !buf_brk_ || !buf_mask_ ||
!buf_cand_i_ || !buf_cand_v_ || !buf_lp_) {
RAD_ERR("sampler: a staging buffer failed to declare");
return RAD_E_NOMEM;
}
@@ -252,6 +264,15 @@ int Sampler::declare(RadBuilder* b, const SamplerConfig& cfg) {
op_typical_ = op_cand("sample_typical");
op_xtc_ = op_cand("sample_xtc");
op_pick_ = op_cand("sample_pick");
/* THE SAME TEMPERATURE KERNEL OVER THE CANDIDATE PLANE: its `n_vocab` is the candidate width,
* which is all the kernel reads it as -- a row length. */
{
RadParam p[2] = {
RadParam{ "M", RAD_P_RANGE, 1, rows, nullptr },
RadParam{ "n_vocab", RAD_P_INT, (long long)ncand, 0, nullptr },
};
op_temp_late_ = rad_decl_op(b, "sample_temp", p, 2, nullptr, 0);
}
if (vocab_parallel()) {
/* lm_head is vocab-sharded, so each rank reduces ITS OWN shard and only the candidate
@@ -269,6 +290,31 @@ int Sampler::declare(RadBuilder* b, const SamplerConfig& cfg) {
op_merge_ = op_cand("sample_merge_topk");
}
/* THE RAW DISTRIBUTION'S SUMMARY, at the one width every request's top_logprobs fits in. A
* deployment whose kernels lack it serves every request that does not ask for logprobs;
* check_request refuses the ones that do, by name. */
{
RadParam p[4] = {
RadParam{ "M", RAD_P_RANGE, 1, rows, nullptr },
RadParam{ "n_vocab", RAD_P_INT, (long long)nv, 0, nullptr },
RadParam{ "k", RAD_P_INT, (long long)kLpK, 0, nullptr },
RadParam{ "vocab_off", RAD_P_INT, (long long)cfg_.vocab_off, 0, nullptr },
};
op_logprobs_ = rad_decl_op(b, "sample_logprobs", p, vocab_parallel() ? 4 : 3, nullptr, 0);
}
if (vocab_parallel()) {
/* Each rank summarised its own shard; rank 0 merges them on the host, so every rank's
* row lands beside the others' as the candidate pairs do. */
RadParam ag[4] = {
RadParam{ "world_size", RAD_P_INT, (long long)cfg_.world_size, 0, nullptr },
RadParam{ "numel", RAD_P_INT, (long long)(rows * lp_width()), 0, nullptr },
RadParam{ "dtype", RAD_P_STR, 0, 0, "f32" },
RadParam{ "row", RAD_P_INT, (long long)lp_width(), 0, nullptr },
};
op_lp_gather_ = rad_decl_op(b, "all_gather", ag, 4, nullptr, 0);
if (!op_lp_gather_) op_logprobs_ = RAD_NULL_HANDLE;
}
RAD_TRY(stage_alloc());
declared_ = true;
@@ -288,14 +334,32 @@ int Sampler::stage_alloc() {
rows * (int64_t)sizeof(DeviceSampleParams), RAD_MEM_HOST_PINNED);
greedy_stage_ = (DeviceSampleParams*)rad_dev_alloc(
rows * (int64_t)sizeof(DeviceSampleParams), RAD_MEM_HOST_PINNED);
late_stage_ = (DeviceSampleParams*)rad_dev_alloc(
rows * (int64_t)sizeof(DeviceSampleParams), RAD_MEM_HOST_PINNED);
greedy_ready_ = false;
hist_stage_ = (int32_t*)rad_dev_alloc(rows * cfg_.max_hist * 4, RAD_MEM_HOST_PINNED);
brk_stage_ = (uint8_t*)rad_dev_alloc(rows * cfg_.max_hist, RAD_MEM_HOST_PINNED);
mask_stage_ = (uint32_t*)rad_dev_alloc(rows * mask_words_ * 4, RAD_MEM_HOST_PINNED);
if (!params_stage_ || !greedy_stage_ || !hist_stage_ || !brk_stage_ || !mask_stage_) {
/* Rank 0's landing place for the logprobs copies, and only rank 0's: it is the rank that
* reads them. */
if (cfg_.rank == 0) {
const int64_t w = lp_width() * (vocab_parallel() ? cfg_.world_size : 1);
lp_host_ = (float*)rad_dev_alloc(rows * w * 4, RAD_MEM_HOST_PINNED);
lp_ci_host_ = (int32_t*)rad_dev_alloc(rows * cfg_.max_candidates * 4, RAD_MEM_HOST_PINNED);
lp_cv_host_ = (float*)rad_dev_alloc(rows * cfg_.max_candidates * 4, RAD_MEM_HOST_PINNED);
if (!lp_host_ || !lp_ci_host_ || !lp_cv_host_) {
RAD_ERR("sampler: could not pin %s for the logprobs readback",
humanb(rows * (w + 2 * cfg_.max_candidates) * 4).c_str());
stage_free();
return RAD_E_NOMEM;
}
}
if (!params_stage_ || !greedy_stage_ || !late_stage_ || !hist_stage_ || !brk_stage_ ||
!mask_stage_) {
RAD_ERR("sampler: could not pin %s of staging",
humanb(rows * ((int64_t)sizeof(DeviceSampleParams) + cfg_.max_hist * 5 +
humanb(rows * (3 * (int64_t)sizeof(DeviceSampleParams) + cfg_.max_hist * 5 +
mask_words_ * 4)).c_str());
stage_free();
return RAD_E_NOMEM;
@@ -306,11 +370,19 @@ int Sampler::stage_alloc() {
void Sampler::stage_free() {
if (params_stage_) rad_dev_free(params_stage_, RAD_MEM_HOST_PINNED);
if (greedy_stage_) rad_dev_free(greedy_stage_, RAD_MEM_HOST_PINNED);
if (late_stage_) rad_dev_free(late_stage_, RAD_MEM_HOST_PINNED);
if (hist_stage_) rad_dev_free(hist_stage_, RAD_MEM_HOST_PINNED);
if (brk_stage_) rad_dev_free(brk_stage_, RAD_MEM_HOST_PINNED);
if (mask_stage_) rad_dev_free(mask_stage_, RAD_MEM_HOST_PINNED);
if (lp_host_) rad_dev_free(lp_host_, RAD_MEM_HOST_PINNED);
if (lp_ci_host_) rad_dev_free(lp_ci_host_, RAD_MEM_HOST_PINNED);
if (lp_cv_host_) rad_dev_free(lp_cv_host_, RAD_MEM_HOST_PINNED);
lp_host_ = nullptr;
lp_ci_host_ = nullptr;
lp_cv_host_ = nullptr;
params_stage_ = nullptr;
greedy_stage_ = nullptr;
late_stage_ = nullptr;
cur_stage_ = nullptr;
hist_stage_ = nullptr;
brk_stage_ = nullptr;
@@ -349,6 +421,11 @@ int Sampler::check_request(const SamplingParams& sp, std::string* why) const {
if (sp.top_k > cfg_.max_candidates)
return refuse("top_k exceeds the sampler's candidate width (--max-candidates)",
RAD_E_INVAL);
if (sp.n_probs > RAD_MAX_LOGPROBS) {
if (why) *why = "at most " + std::to_string(RAD_MAX_LOGPROBS) +
" logprobs alternatives may be asked for";
return RAD_E_INVAL;
}
/* Every breaker is a pass over the whole vocabulary on the scheduler thread, and every other
* sequence on the server waits for it; see kDryMaxBreakers. Refused here, before any of that
* work is queued, rather than truncated -- a request whose breakers quietly went missing is a
@@ -366,12 +443,18 @@ int Sampler::check_request(const SamplingParams& sp, std::string* why) const {
return (wanted && !h) ? n : nullptr;
};
/* A SPLIT VOCABULARY MOVES GREEDY ONTO THE CHAIN, so what a greedy request needs moves with
* it: not the argmax, but the top-k, the merge and the pick that build_step's top_k = 1 sends
* it through. Admission has to check what will actually be issued. */
const bool greedy_chain = sp.greedy() && vocab_parallel();
* it: not the argmax, but the temperature stage, the top-k, the merge and the pick that
* build_step's top_k = 1 sends it through -- run() issues the temperature stage for every
* batch with a chain row, even though its kernel leaves a greedy row (temperature 0) as it
* is. Admission has to check what will actually be issued. */
/* AND SO DOES ONE ASKING FOR LOGPROBS, which build_step stages as a top-1 chain row so its
* token comes off a candidate plane (sampler.h). */
const bool lp = sp.n_probs >= 0;
const bool greedy_chain = sp.greedy() && (vocab_parallel() || lp);
const char* missing = nullptr;
if (!missing) missing = need(lp, op_logprobs_, "sample_logprobs");
if (!missing) missing = need(sp.greedy() && !greedy_chain, op_argmax_, "sample_argmax");
if (!missing) missing = need(!sp.greedy(), op_temp_, "sample_temp");
if (!missing) missing = need(!sp.greedy() || greedy_chain, op_temp_, "sample_temp");
if (!missing) missing = need(!sp.greedy() || greedy_chain, op_pick_, "sample_pick");
/* EVERY CHAIN ROW NEEDS THE TOP-K, whatever its own top_k says: it is the stage that writes
* the candidate set every later stage reads. top_k = 0 asks for the whole candidate width,
@@ -381,6 +464,8 @@ int Sampler::check_request(const SamplingParams& sp, std::string* why) const {
if (!missing) missing = need(sp.min_p > 0.0f, op_minp_, "sample_minp");
if (!missing) missing = need(sp.typical_p < 1.0f, op_typical_, "sample_typical");
if (!missing) missing = need(sp.xtc_probability > 0.0f, op_xtc_, "sample_xtc");
if (!missing) missing = need(!sp.greedy() && sp.temp_last, op_temp_late_,
"sample_temp (over the candidates, for temperature last)");
if (!missing) missing = need(dry_on(sp), op_dry_, "sample_dry");
if (!missing) missing = need(!sp.grammar.empty() || sp.thinking_budget >= 0, op_mask_,
"sample_mask");
@@ -514,7 +599,9 @@ int Sampler::build_step(const std::vector<Request*>& reqs) {
const int64_t cap = rows_for(cfg_);
n_seq_ = 0;
any_brk_ = false;
any_late_ = false;
cur_stage_ = params_stage_;
lp_rows_.clear();
/* DRY'S HOST HALF, for one row whose history `h[0, take)` is already staged. The breakers are
* strings resolved against the vocabulary, so what they mean for this window is worked out
@@ -651,11 +738,28 @@ int Sampler::build_step(const std::vector<Request*>& reqs) {
* Such a row is a CHAIN row and does not carry RAD_SP_GREEDY: every candidate stage
* skips a row that does, because in an unsplit batch that flag is what keeps the pick
* from overwriting the argmax's answer with a draw. */
/* A GREEDY ROW ASKING FOR LOGPROBS IS A TOP-1 CHAIN ROW TOO, for a reason of its own:
* its token has to come off a candidate plane, which is where logprobs_for reads the
* value it was drawn at. The argmax's tie rule is the top-k's, so the token is the
* same. */
const bool want_lp = sp.n_probs >= 0;
if (sp.greedy()) {
if (vocab_parallel()) p.top_k = 1;
else p.flags |= RAD_SP_GREEDY;
if (vocab_parallel() || want_lp) p.top_k = 1;
else p.flags |= RAD_SP_GREEDY;
}
if (want_lp) p.flags |= RAD_SP_LOGPROBS;
if (sp.xtc_probability > 0.0f) p.flags |= RAD_SP_XTC;
/* TEMPERATURE LAST: the row's own temperature in the late stage's row, and 1 -- which
* the temperature stage skips -- in whichever of the two it does not run in. Every row
* gets a late row, because the late stage is issued over the whole batch. */
const bool late = sp.temp_last && !sp.greedy() && sp.temp != 1.0f;
DeviceSampleParams& lp = late_stage_[row];
lp = p;
lp.temp = late ? sp.temp : 1.0f;
if (late) {
p.temp = 1.0f;
any_late_ = true;
}
/* THE HISTORY THE PENALTIES AND DRY READ, staged only for a row that runs one of them
* -- the copy is scheduler-thread work and the upload is step-path bytes, and neither
@@ -766,6 +870,23 @@ int Sampler::build_step(const std::vector<Request*>& reqs) {
if (budget && think.inside() && think.body >= sp.thinking_budget)
force_close(p, row, sp.reasoning.close);
if (want_lp) {
/* The temperature the candidate value carries: the early stage's and the late
* one's, each only where its kernel runs (temp > 0 and not 1). */
auto t_of = [](float t) { return t > 0.0f && t != 1.0f ? t : 1.0f; };
LpRow L;
L.row = row;
L.n_top = sp.n_probs;
L.temp = t_of(p.temp) * t_of(late_stage_[row].temp);
L.p = p;
if (p.hist_len > 0) {
const int32_t* h = hist_stage_ + row * cfg_.max_hist;
L.hist.assign(h, h + p.hist_len);
}
L.dry = brk;
lp_rows_.push_back(std::move(L));
}
}
/* Back to where the sequence actually is. The tokens it really accepted are applied by
@@ -881,6 +1002,12 @@ int Sampler::run(RadCtx* c, rad_buf logits, rad_buf out_tokens) {
* number that makes a host-side grammar affordable at all (spec §13). */
RAD_TRY(rad_memcpy_async(rad_buf_ptr(c, buf_params_), cur_stage_,
n_seq_ * (int64_t)sizeof(DeviceSampleParams), s));
/* The late temperature's rows only when this build staged one: a greedy build's rows come
* from greedy_stage_, and late_stage_ then holds an older build's. */
const bool late = any_late_ && cur_stage_ == params_stage_;
if (late)
RAD_TRY(rad_memcpy_async(rad_buf_ptr(c, buf_params_late_), late_stage_,
n_seq_ * (int64_t)sizeof(DeviceSampleParams), s));
if (any_penalty || any_dry)
RAD_TRY(rad_memcpy_async(rad_buf_ptr(c, buf_hist_), hist_stage_,
n_seq_ * cfg_.max_hist * 4, s));
@@ -906,6 +1033,17 @@ int Sampler::run(RadCtx* c, rad_buf logits, rad_buf out_tokens) {
return rad_issue(c, op, v.data(), (int)v.size(), n_seq_);
};
/* THE LOGPROBS SUMMARY, ON THE LOGITS AS THE MODEL WROTE THEM: every stage below writes them in
* place. Only for a trunk build that staged a logprobs row -- a draft pass's greedy build
* stages none, and must not overwrite the summary rank 0 is about to copy back. */
const bool lp = !lp_rows_.empty() && cur_stage_ == params_stage_ && op_logprobs_;
const RadOperand o_lp = opd_rows(buf_lp_, n_seq_);
if (lp) {
RAD_TRY(issue(op_logprobs_, { o_logits, o_params, o_lp }));
if (vocab_parallel())
RAD_TRY(issue(op_lp_gather_, { o_lp, opd_rows(buf_lp_g_, n_seq_) }));
}
/* Penalties act on raw logits, before anything derives a probability from them. DRY takes the
* breaker marks only when some row in the batch has breakers; its fourth operand is optional
* and absent means no token is exempt. */
@@ -962,8 +1100,163 @@ int Sampler::run(RadCtx* c, rad_buf logits, rad_buf out_tokens) {
if (any_minp) RAD_TRY(issue(op_minp_, { o_ci, o_cv, o_params }));
if (any_typ) RAD_TRY(issue(op_typical_, { o_ci, o_cv, o_params }));
if (any_xtc) RAD_TRY(issue(op_xtc_, { o_ci, o_cv, o_params }));
if (late)
RAD_TRY(issue(op_temp_late_, { o_cv, opd_rows(buf_params_late_, n_seq_) }));
RAD_TRY(issue(op_pick_, { o_ci, o_cv, o_params, o_tok }));
/* AND THE LOGPROBS ROWS ON THEIR WAY TO THE HOST, behind the pick on the same stream: the
* summary, and the candidate planes the pick drew from (logprobs_for reads a token's value
* there when the summary does not hold it). Only the rows between the first and the last
* that asked, and only on rank 0, which is the rank collect_step asks. */
if (lp && cfg_.rank == 0) {
lp_lo_ = lp_rows_.front().row;
lp_hi_ = lp_rows_.back().row + 1;
const int64_t w = lp_width() * (vocab_parallel() ? cfg_.world_size : 1);
const int64_t nc = cfg_.max_candidates, n = lp_hi_ - lp_lo_;
const char* sp = (const char*)rad_buf_ptr(c, vocab_parallel() ? buf_lp_g_ : buf_lp_);
const char* ci = (const char*)rad_buf_ptr(c, buf_cand_i_);
const char* cv = (const char*)rad_buf_ptr(c, buf_cand_v_);
if (!sp || !ci || !cv) return RAD_E_STATE;
RAD_TRY(rad_memcpy_async(lp_host_ + lp_lo_ * w, sp + lp_lo_ * w * 4, n * w * 4, s));
RAD_TRY(rad_memcpy_async(lp_ci_host_ + lp_lo_ * nc, ci + lp_lo_ * nc * 4, n * nc * 4, s));
RAD_TRY(rad_memcpy_async(lp_cv_host_ + lp_lo_ * nc, cv + lp_lo_ * nc * 4, n * nc * 4, s));
}
return RAD_OK;
}
/* ================================================================== logprobs */
float Sampler::raw_logit(const LpRow& L, int32_t token, float v) const {
const DeviceSampleParams& p = L.p;
double y = (double)v * (double)L.temp;
/* DRY subtracted a penalty that depends on the token and the window alone, so the host
* reference computes it for this one token: a single candidate at 0 comes back at minus the
* penalty. */
if (p.flags & RAD_SP_DRY) {
static const DryBreakers kNone;
CandidateSet s;
s.c.push_back(Candidate{ token, 0.0f, 0.0f });
DryParams dp;
dp.multiplier = p.dry_multiplier;
dp.base = p.dry_base;
dp.allowed_length = p.dry_allowed_length > 0 ? p.dry_allowed_length : 2;
dp.penalty_last_n = p.dry_penalty_last_n < 0 ? -1 : p.dry_penalty_last_n;
host_dry(s, L.hist.data(), (int64_t)L.hist.size(), (int64_t)L.hist.size(), dp,
L.dry ? *L.dry : kNone);
y -= (double)s.c[0].logit;
}
/* The penalties, inverted: presence and frequency added back, then the repetition penalty
* undone on the side of zero the logit is on -- it never changes sign. The window is the
* stage's: the tail of the staged history, penalty_last_n long when that is positive. */
if (p.flags & RAD_SP_PENALTY) {
int64_t n = (int64_t)L.hist.size(), o = 0;
if (p.penalty_last_n > 0 && n > p.penalty_last_n) { o = n - p.penalty_last_n; n = p.penalty_last_n; }
int64_t count = 0;
for (int64_t i = 0; i < n; ++i) count += L.hist[(size_t)(o + i)] == token;
if (count > 0) {
y += (double)count * p.freq_penalty + p.pres_penalty;
y = y > 0.0 ? y * p.rep_penalty : y / p.rep_penalty;
}
}
return (float)y;
}
int merge_logprob_rows(const float* st, int W, int k, double* log_z, int32_t* ids, float* vals,
int cap) {
const int64_t w = 2 + 2 * (int64_t)k;
auto live = [&](int r) {
const float m = st[r * w], z = st[r * w + 1];
return std::isfinite(m) && std::isfinite(z) && z > 0.0f;
};
double mx = -INFINITY;
for (int r = 0; r < W; ++r)
if (live(r)) mx = std::max(mx, (double)st[r * w]);
double sum = 0.0;
for (int r = 0; r < W; ++r)
if (live(r)) sum += (double)st[r * w + 1] * std::exp((double)st[r * w] - mx);
*log_z = sum > 0.0 ? mx + std::log(sum) : NAN;
/* On the stack for every split the engine runs (eight ranks of 21 pairs is 168); a call for
* more takes the heap rather than a bound. Once per emitted token, on collect_step's path. */
struct Pair { float v; int32_t id; };
Pair buf[256];
std::vector<Pair> heap;
Pair* top = buf;
if ((int64_t)W * k > (int64_t)(sizeof buf / sizeof buf[0])) {
heap.resize((size_t)W * (size_t)k);
top = heap.data();
}
int m = 0;
for (int r = 0; r < W; ++r) {
if (!live(r)) continue;
for (int j = 0; j < k; ++j) {
const int32_t id = (int32_t)st[r * w + 2 + 2 * j];
const float v = st[r * w + 3 + 2 * j];
if (id >= 0 && std::isfinite(v)) top[m++] = Pair{ v, id };
}
}
std::sort(top, top + m, [](const Pair& a, const Pair& b) {
return a.v > b.v || (a.v == b.v && a.id < b.id);
});
const int n = std::min(cap, m);
for (int j = 0; j < n; ++j) {
ids[j] = top[j].id;
vals[j] = top[j].v;
}
return n;
}
int Sampler::logprobs_for(int64_t row, int32_t token, TokenLogprobs* out) const {
if (!out || !lp_host_ || row < lp_lo_ || row >= lp_hi_) return RAD_E_STATE;
const LpRow* L = nullptr;
for (const LpRow& x : lp_rows_)
if (x.row == row) { L = &x; break; }
if (!L) return RAD_E_STATE;
/* Every rank's summary of its shard, merged: the maxima and normalisers by the usual
* rescale, the largest by value with the lower id first. */
const int W = vocab_parallel() ? cfg_.world_size : 1;
double log_z = 0.0;
int32_t ids[kLpK * 8];
float vals[kLpK * 8];
const int n = merge_logprob_rows(lp_host_ + row * W * lp_width(), W, kLpK, &log_z, ids, vals,
(int)(sizeof ids / sizeof ids[0]));
/* A ROW WITH NO FINITE LOGIT HAS NO DISTRIBUTION to report against -- NaN logits out of the
* model, or every one at -inf -- and any number sent for it would be invented. */
if (!std::isfinite(log_z)) {
RAD_WARN("sampler: row %lld has no finite logit; its logprobs cannot be computed",
(long long)row);
out->token = -1;
return RAD_E_INVAL;
}
out->token = token;
out->n_top = std::min(L->n_top, n);
for (int j = 0; j < out->n_top; ++j) {
out->top_id[j] = ids[j];
out->top_lp[j] = (float)((double)vals[j] - log_z);
}
/* The token's own raw logit: exact when it is among the largest, and otherwise recovered
* from the value the pick drew it at. */
double own = NAN;
for (int j = 0; j < n && std::isnan(own); ++j)
if (ids[j] == token) own = (double)vals[j];
if (std::isnan(own)) {
const int64_t nc = cfg_.max_candidates;
const int32_t* ci = lp_ci_host_ + row * nc;
const float* cv = lp_cv_host_ + row * nc;
for (int64_t c = 0; c < nc && std::isnan(own); ++c)
if (ci[c] == token) own = (double)raw_logit(*L, token, cv[c]);
}
if (!std::isfinite(own)) {
RAD_WARN("sampler: row %lld sampled token %d, which has no finite logit on the candidate "
"plane it was drawn from; its logprobs cannot be computed", (long long)row, token);
out->token = -1;
return RAD_E_INVAL;
}
out->logprob = (float)(own - log_z);
return RAD_OK;
}
+74
View File
@@ -18,6 +18,21 @@
* XTC
* the pick
*
* TEMPERATURE MAY RUN AFTER THE CUTS INSTEAD, per sequence: llama.cpp's order, which a request
* names with `samplers` (SamplingParams::temp_last). Such a row's temperature is staged at 1 for
* the stage above, which skips it, and at its own value for a second `sample_temp` over the
* candidate plane after XTC -- the same kernel at the candidate width, so no plugin needs a
* second implementation of it. Every other row is 1 there.
*
* LOGPROBS ARE READ OFF THE RAW LOGITS, before the first stage: `sample_logprobs` summarises each
* row that asks (RAD_SP_LOGPROBS) as its maximum, its normaliser and its kLpK largest (one more
* than RAD_MAX_LOGPROBS, for the row's width below), and rank 0 copies that back behind the pick.
* The emitted token's own logprob is its raw logit less the log normaliser. When it is not among the largest its raw logit is no longer on the card
* -- every stage wrote the logits in place -- so it is recovered from the value the pick drew it
* at, the candidate plane's, by undoing temperature, DRY and the penalties on the host
* (logprobs_for). Such a row is never a greedy-flagged one: a greedy row asking for logprobs is
* staged as a top-1 chain row, so that its token is drawn from a candidate plane too.
*
* A GREEDY SEQUENCE SKIPS ALL OF IT and takes `sample_argmax` -- after penalties and the mask,
* because temperature 0 collapses every other logit to -inf and a mask applied afterwards would
* leave nothing at all. host_ref.cpp makes the same choice for the same reason and the two must
@@ -50,6 +65,7 @@
* sample_xtc M(range) n_cand cand_idx, cand_val, params -> cand_idx, cand_val
* sample_pick M(range) n_cand cand_idx, cand_val, params -> token
* sample_merge_topk M(range) n_cand gathered, params -> cand_idx, cand_val
* sample_logprobs M(range) n_vocab k vocab_off? logits, params -> stats
*
* `M` is the number of SAMPLED POSITIONS, not tokens: one per sequence at decode, n_spec+1 per
* sequence at a verify. `params` is [M] rows of DeviceSampleParams below; `history` is
@@ -196,6 +212,16 @@ public:
* top-k) happens between the top-k and the cuts; full logits are never gathered. */
int run(RadCtx* c, rad_buf logits, rad_buf out_tokens);
/* THE EMITTED TOKEN'S LOGPROBS, after the step the last build_step staged has completed on the
* card: row `row` must have been staged for a request with SamplingParams::n_probs >= 0, and
* `token` is what the step sampled there. Rank 0's sampler only -- it is the one that copies
* the summary back. RAD_E_STATE for a row that was not staged for logprobs; RAD_E_INVAL, with
* `out->token` -1, for one whose numbers are not finite -- a row with no finite logit, or a
* token drawn where none was -- which is a number no client should be sent. */
int logprobs_for(int64_t row, int32_t token, TokenLogprobs* out) const;
/* Did `sample_logprobs` resolve? What the server advertises as logprobs support. */
bool has_logprobs() const { return op_logprobs_ != RAD_NULL_HANDLE; }
/* The parameter rows the last build_step or build_greedy staged, and how many. What `run`
* uploads, readable so the staging can be checked without a device behind it. */
const DeviceSampleParams* staged_params(int64_t* n) const {
@@ -240,6 +266,7 @@ private:
rad_op op_penalties_ = RAD_NULL_HANDLE;
rad_op op_dry_ = RAD_NULL_HANDLE;
rad_op op_temp_ = RAD_NULL_HANDLE;
rad_op op_temp_late_ = RAD_NULL_HANDLE; /* sample_temp over the candidates (temp_last) */
rad_op op_mask_ = RAD_NULL_HANDLE;
rad_op op_topk_ = RAD_NULL_HANDLE;
rad_op op_topp_ = RAD_NULL_HANDLE;
@@ -250,9 +277,12 @@ private:
rad_op op_argmax_ = RAD_NULL_HANDLE;
rad_op op_allgather_ = RAD_NULL_HANDLE;
rad_op op_merge_ = RAD_NULL_HANDLE; /* the candidate merge, under tensor parallel */
rad_op op_logprobs_ = RAD_NULL_HANDLE; /* the raw distribution's summary */
rad_op op_lp_gather_ = RAD_NULL_HANDLE; /* every rank's summary, under a split vocabulary */
/* Device-side buffers, from the ordinary buffer plan. */
rad_buf buf_params_ = RAD_NULL_HANDLE;
rad_buf buf_params_late_ = RAD_NULL_HANDLE; /* the late temperature's rows */
rad_buf buf_hist_ = RAD_NULL_HANDLE;
rad_buf buf_brk_ = RAD_NULL_HANDLE; /* DRY's single-token breaker marks, beside history */
rad_buf buf_mask_ = RAD_NULL_HANDLE;
@@ -260,9 +290,15 @@ private:
rad_buf buf_cand_v_ = RAD_NULL_HANDLE;
rad_buf buf_gather_ = RAD_NULL_HANDLE;
rad_buf buf_pairs_ = RAD_NULL_HANDLE; /* this rank's candidates as (global id, logit) */
rad_buf buf_lp_ = RAD_NULL_HANDLE; /* sample_logprobs' stats, [rows, lp_width()] */
rad_buf buf_lp_g_ = RAD_NULL_HANDLE; /* and every rank's side by side */
/* Pinned staging. One allocation each, at declare, never on the step path. */
DeviceSampleParams* params_stage_ = nullptr;
/* The late temperature's rows: params_stage_'s, with each row's temperature at 1 unless it
* runs last. Uploaded only by a step where some row does (any_late_). */
DeviceSampleParams* late_stage_ = nullptr;
bool any_late_ = false;
/* THE GREEDY ROWS HAVE STAGING OF THEIR OWN, written once. A draft pass is staged while the
* step before it -- whose sampler uploads `params_stage_` when the card reaches it -- may not
* have run yet; rows written into the same staging would reach that step's sampler instead.
@@ -305,6 +341,35 @@ private:
* request must not stop the step loop for everyone else. */
std::vector<uint64_t> failed_;
/* ---------------------------------------------------------- logprobs */
/* THE SUMMARY'S WIDTH: RAD_MAX_LOGPROBS + 1 pairs, not RAD_MAX_LOGPROBS, so that a row is 44
* floats -- whole 16-byte words, which is what the all-gather of a split vocabulary moves (and
* libr4d's refuses anything else). The extra pair is never reported. */
static constexpr int kLpK = RAD_MAX_LOGPROBS + 1;
static int64_t lp_width() { return 2 + 2 * (int64_t)kLpK; }
/* WHAT UNDOING A ROW'S CHAIN NEEDS, kept from build_step for each row staged with
* RAD_SP_LOGPROBS: the staged row itself, the temperature the candidate value carries, the
* history window both history stages read, and the request's DRY breakers. Copied rather
* than pointed at, because the staging is rebuilt by the next step. */
struct LpRow {
int64_t row = -1;
int32_t n_top = 0;
float temp = 1.0f; /* the candidate value is l / temp */
DeviceSampleParams p{};
std::vector<int32_t> hist; /* the staged history row, [0, hist_len) */
const DryBreakers* dry = nullptr; /* lives in seqs_ for the request's lifetime */
};
std::vector<LpRow> lp_rows_;
/* Rank 0's copies, written behind the pick: the summaries ([rows, W * lp_width()], W ranks
* side by side) and the candidate planes the pick drew from. */
float* lp_host_ = nullptr;
int32_t* lp_ci_host_ = nullptr;
float* lp_cv_host_ = nullptr;
int64_t lp_lo_ = 0, lp_hi_ = 0; /* the rows copied, [lo, hi) */
/* A token's raw logit from the value the pick drew it at: temperature, DRY and the penalties
* undone, in the reverse of the order the chain applied them. */
float raw_logit(const LpRow& L, int32_t token, float v) const;
/* Per-request grammar and DRY state, keyed by request id. Held here rather than in Request
* because Request is a frozen struct shared across components and a unique_ptr in it would
* make the scheduler's copies a compile error. */
@@ -314,4 +379,13 @@ private:
void stage_free();
};
/* SPLIT-VOCABULARY SUMMARIES, MERGED: `W` ranks' `sample_logprobs` rows of `k` pairs each, side by
* side in `st` (W * (2 + 2k) floats). Sets the shared log normaliser and fills up to `cap` of the
* largest (id, logit) pairs over every rank, descending, ties to the lower id; returns how many. A
* rank whose maximum or normaliser is not finite contributes nothing, nor does a pair whose logit
* is not finite, and `*log_z` comes back NaN when no rank contributes. One rank is the same
* arithmetic. What Sampler::logprobs_for reads a step's summaries with. */
int merge_logprob_rows(const float* st, int W, int k, double* log_z, int32_t* ids, float* vals,
int cap);
} /* namespace rad */
+1 -1
View File
@@ -374,7 +374,7 @@ struct PCBinding final : IPrefixCache {
/* r.id is the session, and it is the SAME id reserve_checkpoint keys its snapshots by --
* so the tiers' session view and the checkpoint index are talking about one thing. */
media_keys(r, &mm_);
return m->insert(r.id, toks, mm_, blocks, n_tokens);
return m->insert(r.id, toks, mm_, blocks, n_tokens, r.session_label);
}
/* Installed by the engine when the idle tiers are on: lands every host copy that is waiting,
* now, and says whether any landed. Called on the step thread under the scheduler's lock. */
+27 -5
View File
@@ -948,6 +948,7 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget) {
r.state = ReqState::Running;
s.running = true;
server::sink_admitted(r.sink);
server::sink_prompt_progress(r.sink, r.n_computed, (int32_t)r.prompt.size(), r.n_cached);
s.sched_tokens = (int32_t)want;
s.pending_ckpt = ckpt;
++m_.admitted;
@@ -1587,6 +1588,10 @@ int Scheduler::commit(const StepResult& res) {
bool eos = res.eos && res.eos[i] && !r.ignore_eos;
bool overflowed = false;
/* A token whose logprobs the engine could not compute (TokenLogprobs::token -1) for a
* request that asked for them: the request fails with the reason rather than send that
* token without the numbers it was asked for, and nothing after it is sent. */
bool lp_failed = false;
/* THE SNAPSHOT THE ENGINE JUST TOOK IS NOW READABLE. Marking it here rather than at
* reservation is the difference between a checkpoint and a promise: reserve_checkpoint
@@ -1602,6 +1607,8 @@ int Scheduler::commit(const StepResult& res) {
if (e.is_prefill) {
r.n_computed += e.n_tokens;
step_prefill_tok_ += e.n_tokens;
server::sink_prompt_progress(r.sink, r.n_computed, (int32_t)r.prompt.size(),
r.n_cached);
/* Once, when the prompt is fully placed: the admission accounting the usage block
* reports. `n_cached` is what the prefix cache supplied and is not recomputed here. */
if (r.n_computed >= (int64_t)r.prompt.size())
@@ -1613,7 +1620,11 @@ int Scheduler::commit(const StepResult& res) {
} else if (e.produces_token && res.token) {
if (!s.first_tok_us) s.first_tok_us = mono_us();
r.output.push_back(res.token[i]);
overflowed = !server::sink_push(r.sink, res.token[i]);
const TokenLogprobs* lp =
res.lp && res.first_row[i] >= 0 && r.sp.n_probs >= 0
? &res.lp[res.first_row[i]] : nullptr;
if (lp && lp->token < 0) lp_failed = true;
else overflowed = !server::sink_push(r.sink, res.token[i], lp);
/* The conv window absorbed this chunk; the cursor advances by one committed
* position, exactly as it does in decode. */
s.conv_cursor = (int32_t)((s.conv_cursor + 1) % (W ? W : 1));
@@ -1661,15 +1672,21 @@ int Scheduler::commit(const StepResult& res) {
/* AND THE CONTEXT BOUNDS IT WHATEVER max_tokens SAYS, including "no limit": a
* sequence may not grow past the positions this deployment can address. */
if (ctx_limit_ > 0 && ctx_limit_ - s.seq_len() < room) room = ctx_limit_ - s.seq_len();
auto emit = [&](int32_t t) {
/* `j` is the token's place in the step's emission: its logprobs row is the entry's
* j-th, when the request asked for them. */
auto emit = [&](int32_t t, int32_t j) {
if (room <= 0) return;
--room;
if (!s.first_tok_us) s.first_tok_us = mono_us();
r.output.push_back(t);
if (!server::sink_push(r.sink, t)) overflowed = true;
const TokenLogprobs* lp =
res.lp && res.first_row[i] >= 0 && r.sp.n_probs >= 0
? &res.lp[res.first_row[i] + j] : nullptr;
if (lp_failed || (lp && lp->token < 0)) { lp_failed = true; return; }
if (!server::sink_push(r.sink, t, lp)) overflowed = true;
};
for (int32_t j = 0; j < a; ++j) emit(s.draft[j]);
if (res.token) emit(res.token[i]);
for (int32_t j = 0; j < a; ++j) emit(s.draft[j], j);
if (res.token) emit(res.token[i], a);
r.n_computed = valid;
step_decode_tok_ += 1 + a;
@@ -1719,6 +1736,11 @@ int Scheduler::commit(const StepResult& res) {
close_request(s, ReqState::Failed, "sink_overflow", carried);
++m_.failed;
completed_.push_back(r.id);
} else if (lp_failed) {
close_request(s, ReqState::Failed, "logprobs", carried, true, RAD_E_STATE,
"the logprobs of a token it generated could not be computed");
++m_.failed;
completed_.push_back(r.id);
} else if (server::sink_cancelled(r.sink)) {
/* The client hung up. Spec §14: the blocks go back now rather than at the end of a
* generation nobody will read. */
+4
View File
@@ -176,6 +176,10 @@ public:
const int32_t* n_accepted = nullptr; /* [n_seq] drafted tokens accepted, 0..n_spec */
const int32_t* token = nullptr; /* [n_seq] token sampled at the accepted position */
const uint8_t* eos = nullptr; /* [n_seq] 1 when the sequence ended */
/* LOGPROBS, null on a step where no request asked: entry i's j-th emitted token (its
* accepted drafts first, then the sampled token) is lp[first_row[i] + j]. */
const TokenLogprobs* lp = nullptr;
const int32_t* first_row = nullptr; /* [n_seq] */
};
/* `geo` is the already-resolved chunk geometry. The engine resolves it once and passes it,
+26 -1
View File
@@ -142,6 +142,7 @@ public:
SessionStat o;
o.id = s.id;
o.model = s.model;
o.label = s.label;
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;
@@ -319,6 +320,7 @@ public:
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(); }
std::string stop_hit() const override { return d_.stop_hit(); }
void defer_stops_until(const std::string& m) override { d_.defer_stops_until(m); }
private:
Detokenizer d_;
@@ -376,6 +378,14 @@ public:
if (id < 0 || id >= vocab_->n_tokens()) return std::string();
return utf8_sanitize(vocab_->text(id));
}
std::string token_bytes(int32_t id) const override {
if (id < 0 || id >= vocab_->n_tokens()) return std::string();
return tok_.decode({ id }, /*render_special=*/true);
}
std::string reply_bytes(int32_t id) const override {
if (id < 0 || id >= vocab_->n_tokens()) return std::string();
return tok_.decode({ id }, /*render_special=*/false);
}
std::unique_ptr<IDetokenizer> detokenizer(
const std::vector<std::string>& stops,
@@ -549,7 +559,21 @@ public:
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(); }
std::string source() const override { return t_.source(); }
/* Under llama-server's names (its chat_template_caps), from the same probe. */
std::string caps() const override {
const ChatCaps& c = t_.caps();
json o;
o["supports_tools"] = c.tools;
o["supports_tool_calls"] = c.tool_calls;
o["supports_system_role"] = c.system_role;
o["supports_parallel_tool_calls"] = c.parallel_tool_calls;
o["supports_preserve_reasoning"] = c.preserve_reasoning;
o["supports_string_content"] = c.string_content;
o["supports_typed_content"] = c.typed_content;
o["supports_object_arguments"] = c.object_arguments;
return o.dump();
}
int apply(const json& messages, const json& tools, const ChatRenderOptions& opt,
ChatRender* out, std::string* why) const override {
@@ -559,6 +583,7 @@ public:
o.parallel_tool_calls = opt.parallel_tool_calls;
o.tool_choice = opt.tool_choice;
o.reasoning_format = opt.reasoning_format;
o.continue_final = opt.continue_final;
o.grammar = opt.grammar;
o.json_schema = opt.json_schema;
o.template_kwargs = opt.template_kwargs;
+142 -28
View File
@@ -1,6 +1,7 @@
/* core/server/admin.cpp -- vLLM's non-generation endpoints.
/* core/server/admin.cpp -- vLLM's and llama-server's non-generation endpoints.
*
* /version /ping /load /tokenize /detokenize /get_tokenizer_info /server_info /reset_prefix_cache.
* /version /ping /load /tokenize /detokenize /get_tokenizer_info /server_info /reset_prefix_cache
* /props.
*
* 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
@@ -8,15 +9,17 @@
* 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
* /rerank (a classifier or cross-encoder head, which this engine does not load), /sleep, /wake_up
* and /is_sleeping (there is no sleep mode: weights are placed once, see spec §5), the LoRA
* adapter endpoints (no LoRA), /invocations (a SageMaker envelope around the others) and
* /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.
* adapter endpoints (no LoRA), /invocations (a SageMaker envelope around the others) and the
* Responses API's stored responses (retrieved or deleted by id: a conversation store, which is a
* component and not an endpoint); llama-server's carries /slots (its own slot state). Each would
* be a lie in the shape of a 200, so each is absent and answers 404 rather than pretending.
*/
#include "server.h"
#include "rad_internal.h"
#include "text/tokenizer.h"
#include <nlohmann/json.hpp>
@@ -143,8 +146,61 @@ HttpResponse Server::handle_tokenize(const HttpRequest& req) {
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"), req.peer);
auto cont = b.find("content");
if ((msgs != b.end()) + (prom != b.end()) + (cont != b.end()) > 1)
return error_response(err_bad("prompt", "send one of `prompt`, `messages` or `content`"),
req.peer);
/* THE THIRD SHAPE IS llama-server's: `content` -- a string, or strings and token ids mixed,
* as its /completion takes a prompt -- with its own two flags and its own defaults (no BOS,
* control tokens recognised), answered under its own key, `tokens`, as ids or with
* `with_pieces` as {id, piece} objects. A piece that is not whole UTF-8 is its bytes, as
* llama-server sends it. */
if (cont != b.end()) {
const bool add_special = get_bool_or(b, "add_special", false);
const bool parse_special = get_bool_or(b, "parse_special", true);
const bool with_pieces = get_bool_or(b, "with_pieces", false);
auto take = [&](const json& v, bool first) -> bool {
if (v.is_string()) {
const std::vector<int32_t> t =
deps_.tok->encode(v.get<std::string>(), first && add_special, parse_special);
toks.insert(toks.end(), t.begin(), t.end());
return true;
}
int32_t id = 0;
if (!v.is_number_integer() || !token_id(v, &id)) return false;
toks.push_back(id);
return true;
};
bool ok = true;
if (cont->is_array()) {
bool first = true;
for (const json& v : *cont) { ok = ok && take(v, first); first = false; }
} else {
ok = cont->is_string() && take(*cont, true);
}
if (!ok)
return error_response(err_bad("content", "must be a string, or an array of strings "
"and token ids"), req.peer);
json arr = json::array();
for (int32_t t : toks) {
if (!with_pieces) { arr.push_back(t); continue; }
const std::string piece = deps_.tok->token_bytes(t);
json e;
e["id"] = t;
/* A piece that is not whole UTF-8 goes as its bytes, 0-255, as llama-server sends it. */
if (utf8_valid_prefix(piece) == piece.size()) e["piece"] = piece;
else e["piece"] = std::vector<int>((const unsigned char*)piece.data(),
(const unsigned char*)piece.data() + piece.size());
arr.push_back(std::move(e));
}
json o;
o["tokens"] = std::move(arr);
o["count"] = (int64_t)toks.size();
o["max_model_len"] = opt_.max_ctx;
metrics_.observe_http(200);
return HttpResponse::json_body(200, json_dump(o));
}
if (msgs != b.end()) {
if (!deps_.chat)
@@ -227,8 +283,10 @@ HttpResponse Server::handle_detokenize(const HttpRequest& req) {
toks.push_back(id);
}
/* `prompt` is vLLM's key and `content` llama-server's, for the same text. */
json o;
o["prompt"] = deps_.tok->decode(toks);
o["content"] = o["prompt"];
metrics_.observe_http(200);
return HttpResponse::json_body(200, json_dump(o));
}
@@ -239,29 +297,66 @@ HttpResponse Server::handle_detokenize(const HttpRequest& req) {
* and reads what a request that sends no sampler fields inherits. /server_info says all of it and
* more, but nothing written for llama-server knows to ask there.
*
* Only what this server can fill honestly, under llama-server's names: no chat template text
* (the server holds a compiled template, not its source), no GGUF metadata, no per-slot state.
* n_ctx is the context ONE request may use, which is what llama-server's per-slot n_ctx means to
* the clients reading it; left out when the server does not know its length. */
* Only what this server can fill honestly, under llama-server's names: no GGUF metadata, no
* per-slot state. n_ctx is the context ONE request may use, which is what llama-server's per-slot
* n_ctx means to the clients reading it; left out when the server does not know its length. */
HttpResponse Server::handle_props(const HttpRequest&) {
const SamplingParams& sp = opt_.default_sampling;
/* EVERY FIELD llama-server's `params` CARRIES, so a client that reads one does not find it
* missing. The samplers this server does not run are reported at their off values -- which
* is what it serves -- and `samplers` is its own order, temperature first. */
const int64_t n_predict = opt_.default_max_tokens > 0 ? opt_.default_max_tokens : -1;
json params;
params["n_predict"] = opt_.default_max_tokens > 0 ? opt_.default_max_tokens : -1;
params["temperature"] = sp.temp;
params["top_k"] = sp.top_k;
params["top_p"] = sp.top_p;
params["min_p"] = sp.min_p;
params["typical_p"] = sp.typical_p;
params["repeat_last_n"] = sp.penalty_last_n;
params["repeat_penalty"] = sp.rep_penalty;
params["presence_penalty"] = sp.pres_penalty;
params["frequency_penalty"] = sp.freq_penalty;
params["dry_multiplier"] = sp.dry_multiplier;
params["dry_base"] = sp.dry_base;
params["dry_allowed_length"] = sp.dry_allowed_length;
params["dry_penalty_last_n"] = sp.dry_penalty_last_n;
params["xtc_probability"] = sp.xtc_probability;
params["xtc_threshold"] = sp.xtc_threshold;
params["n_predict"] = n_predict;
params["max_tokens"] = n_predict;
params["seed"] = -1;
params["temperature"] = sp.temp;
params["dynatemp_range"] = 0.0;
params["dynatemp_exponent"] = 1.0;
params["top_k"] = sp.top_k;
params["top_p"] = sp.top_p;
params["min_p"] = sp.min_p;
params["top_n_sigma"] = -1.0;
params["typical_p"] = sp.typical_p;
params["typ_p"] = sp.typical_p;
params["xtc_probability"] = sp.xtc_probability;
params["xtc_threshold"] = sp.xtc_threshold;
params["repeat_last_n"] = sp.penalty_last_n;
params["repeat_penalty"] = sp.rep_penalty;
params["presence_penalty"] = sp.pres_penalty;
params["frequency_penalty"] = sp.freq_penalty;
params["dry_multiplier"] = sp.dry_multiplier;
params["dry_base"] = sp.dry_base;
params["dry_allowed_length"] = sp.dry_allowed_length;
params["dry_penalty_last_n"] = sp.dry_penalty_last_n;
params["dry_sequence_breakers"] = sp.dry_seq_breakers.empty() && !opt_.default_dry_breakers_set
? std::vector<std::string>{ "\n", ":", "\"", "*" }
: sp.dry_seq_breakers;
params["mirostat"] = 0;
params["mirostat_tau"] = 5.0;
params["mirostat_eta"] = 0.1;
params["stop"] = json::array();
params["n_keep"] = 0;
params["n_discard"] = 0;
params["ignore_eos"] = false;
params["stream"] = true;
params["logit_bias"] = json::array();
params["n_probs"] = 0;
params["min_keep"] = 0;
params["grammar"] = "";
params["grammar_lazy"] = false;
params["grammar_triggers"] = json::array();
params["preserved_tokens"] = json::array();
params["chat_format"] = "";
params["reasoning_format"] = "auto";
params["reasoning_in_content"] = false;
params["generation_prompt"] = "";
params["samplers"] = { "penalties", "dry", "temperature", "top_k", "top_p", "min_p", "typ_p",
"xtc" };
params["backend_sampling"] = false;
params["timings_per_token"] = false;
params["post_sampling_probs"] = false;
params["lora"] = json::array();
json gen;
if (opt_.max_ctx > 0) gen["n_ctx"] = opt_.max_ctx;
@@ -269,13 +364,32 @@ HttpResponse Server::handle_props(const HttpRequest&) {
json modal;
modal["vision"] = deps_.mm && deps_.mm->accepts(MediaKind::Image);
modal["video"] = deps_.mm && deps_.mm->accepts(MediaKind::Video);
modal["audio"] = deps_.mm && deps_.mm->accepts(MediaKind::Audio);
json o;
o["default_generation_settings"] = std::move(gen);
o["total_slots"] = opt_.max_seqs;
o["model_alias"] = opt_.model_id;
o["model_path"] = opt_.model_path;
o["modalities"] = std::move(modal);
o["endpoint_slots"] = false;
o["endpoint_props"] = false;
o["endpoint_metrics"] = true;
o["chat_template"] = deps_.chat ? deps_.chat->source() : std::string();
o["chat_template_caps"] = json::parse(deps_.chat ? deps_.chat->caps() : std::string("{}"),
nullptr, false);
std::string bos, eos;
if (deps_.tok) {
const ITokenizer::VocabInfo v = deps_.tok->vocab_info();
if (v.bos >= 0) bos = deps_.tok->piece(v.bos);
if (v.eos >= 0) eos = deps_.tok->piece(v.eos);
}
o["bos_token"] = bos;
o["eos_token"] = eos;
o["build_info"] = "radiance " + opt_.version;
o["role"] = "model";
o["is_sleeping"] = false;
metrics_.observe_http(200);
return HttpResponse::json_body(200, json_dump(o));
}
+4
View File
@@ -59,6 +59,7 @@ HttpResponse Server::handle_sessions(const HttpRequest&) {
json e;
e["id"] = s.id;
e["model"] = s.model;
if (!s.label.empty()) e["label"] = s.label;
e["tokens"] = s.n_tokens;
e["bytes"] = s.bytes;
e["idle_s"] = s.idle_s;
@@ -681,6 +682,7 @@ th + th, td + td { padding-left:14px; }
/* Fixed, so the tier column starts at one x in both tables. */
.stbl .ret { width:340px; }
.sid { font-weight:500; }
.slabel { margin-left:8px; color:var(--faint); }
.mv { font:500 10px/1 var(--ui); color:var(--faint); border:1px solid var(--rule);
border-radius:4px; padding:2px 5px; margin-left:6px; }
/* WHERE IT IS, by share of the conversation's context, one colour a tier. A conversation is
@@ -2850,6 +2852,8 @@ function sessRow(r, hybrid, manyModels) {
const tr = el("tr");
const id = tr.appendChild(el("td"));
id.appendChild(el("span", "sid", "#" + r.id));
/* The client's own name for the conversation (`session_id`), when it sent one. */
if (r.label) id.appendChild(el("span", "slabel", r.label));
if (r.moving) id.appendChild(el("span", "mv", "moving"));
if (manyModels) tr.appendChild(el("td", "l", r.model || DASH));
tr.appendChild(el("td", null, cnt3(r.tokens) + " tok"));
+32 -6
View File
@@ -363,10 +363,13 @@ int HttpTransport::serve(const Router& router, const TransportOptions& o) {
* 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) {
if (!api_key.empty() && p != "/health" && p != "/v1/health" && p != "/ping" && p != "/" &&
p != "/dashboard") {
/* `Authorization: Bearer` is OpenAI's spelling and `X-Api-Key` Anthropic's, which
* llama-server takes as well; either one carrying the key is enough. */
const bool ok = hreq.get_header_value("Authorization") == "Bearer " + api_key ||
hreq.get_header_value("X-Api-Key") == api_key;
if (!ok) {
/* Said like every other refusal (Server::error_response), which this one never
* reaches: the gate answers before the router does. */
RAD_INFO("req refused from %s:%d -> 401 authentication_error: invalid api key",
@@ -453,15 +456,38 @@ int HttpTransport::serve(const Router& router, const TransportOptions& o) {
bridge(q, std::move(body), s);
});
}
svr.Options(".*", [cors](const httplib::Request&, httplib::Response& res) {
/* THE PREFLIGHT ALLOWS WHATEVER HEADERS IT IS ASKED ABOUT. A browser client sends more than
* the two this server reads -- the OpenAI SDK adds its x-stainless-* set -- and a preflight
* that does not list one fails the request before it is sent. A wildcard would not do: CORS
* never lets `*` stand for Authorization, so the requested list is echoed back. */
svr.Options(".*", [cors](const httplib::Request& req, httplib::Response& res) {
if (cors) {
const std::string asked = req.get_header_value("Access-Control-Request-Headers");
res.set_header("Access-Control-Allow-Origin", "*");
res.set_header("Access-Control-Allow-Headers", "Content-Type, Authorization");
res.set_header("Access-Control-Allow-Headers",
asked.empty() ? "Content-Type, Authorization, X-Api-Key" : asked);
res.set_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
res.set_header("Access-Control-Max-Age", "86400");
}
res.status = 204;
});
/* A PATH NO ROUTE NAMES is answered by httplib before the router sees it, with no body. Every
* other refusal this server makes is an error object, and a client reading one finds an
* empty 404 unparseable; so an error with no body gets one here. A response that already
* carries a body -- the router's own 404 and 405, the gate's 401 -- is left as it is. */
svr.set_error_handler([cors](const httplib::Request& req, httplib::Response& res) {
if (!res.body.empty()) return httplib::Server::HandlerResponse::Unhandled;
if (cors) res.set_header("Access-Control-Allow-Origin", "*");
const std::string type = res.status == 404 ? "not_found_error"
: res.status >= 500 ? "internal_server_error"
: "invalid_request_error";
const std::string what = res.status == 404 ? "no route for " + req.method + " " + req.path
: httplib::status_message(res.status);
res.set_content(error_body(type.c_str(), what), "application/json");
return httplib::Server::HandlerResponse::Handled;
});
/* Bound once: asking for a named port and then for any port would leave the first socket
* bound and unused. */
const int port = o.port == 0 ? svr.bind_to_any_port(o.host.c_str())
+22
View File
@@ -160,6 +160,7 @@ struct SchedMetrics {
struct SessionStat {
uint64_t id = 0;
std::string model; /* the container it was built against */
std::string label; /* the client's name for it (`session_id`), or "" */
int64_t n_tokens = 0;
int64_t bytes = 0;
double idle_s = 0; /* since its last turn */
@@ -307,6 +308,8 @@ public:
* 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; }
/* The stop string that stopped it, "" when none has. */
virtual std::string stop_hit() const { return std::string(); }
/* Match the stop strings only after `marker` has been generated (core/text Detokenizer::
* defer_stops_until): the reply starts inside its reasoning block. */
virtual void defer_stops_until(const std::string& /*marker*/) {}
@@ -349,6 +352,15 @@ public:
* turned the flag on to see. "" when the id is out of range. */
virtual std::string piece(int32_t /*id*/) const { return std::string(); }
/* THE BYTES ONE ID DECODES TO, unsanitised, control tokens rendered: llama-server's
* `with_pieces`. Not necessarily whole UTF-8 -- a byte-fallback or a split multi-byte
* character is a fragment -- so the caller checks before putting it in a JSON string. */
virtual std::string token_bytes(int32_t /*id*/) const { return std::string(); }
/* The bytes one id adds to a REPLY: token_bytes with control tokens rendered as nothing, as
* the decoder renders them -- what a logprobs entry spells the token as, so the entries'
* texts add up to the reply, as llama-server's do. */
virtual std::string reply_bytes(int32_t id) const { return token_bytes(id); }
/* One incremental decoder per in-flight generation. It is made by the tokenizer rather than
* default-constructed by the caller, because it needs the vocabulary to decode anything.
* `stops` is passed down because core/text's Detokenizer can suppress a stop string that
@@ -382,6 +394,9 @@ struct ChatRenderOptions {
std::string grammar; /* the caller's GBNF, or "" */
std::string json_schema; /* a response_format schema, as JSON text, or "" */
std::string reasoning_format = "auto";
/* ASSISTANT PREFILL: continue the conversation's last (assistant) message rather than open a
* new turn. "" off, else llama.cpp's "auto", "content" or "reasoning_content". */
std::string continue_final;
std::map<std::string, std::string> template_kwargs;
/* A render whose refusal is an answer and not an error -- the startup probes of what the
* template takes -- so the template's refusal is not logged. */
@@ -438,6 +453,13 @@ public:
* 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(); }
/* THE TEMPLATE'S SOURCE TEXT and what the capability probe found in it, for /props: what
* llama-server reports as `chat_template` and `chat_template_caps`, so a client built against
* it can render a prompt the way this server will. "" when unknown; the caps are a JSON
* object as text, "{}" when unknown. */
virtual std::string source() const { return std::string(); }
virtual std::string caps() const { return "{}"; }
};
/* A reply taken apart: what core/text's reply parser gives back once the reply is complete. */
+1785 -238
View File
File diff suppressed because it is too large. Load diff
+216 -31
View File
@@ -8,12 +8,12 @@
* 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.
* A parameter that would change the answer and is not served is a 400 that names it, not a
* silent ignore: a client that sends a `logit_bias` and gets a 200 has been told its bias was
* applied, and the bug report that follows ("the model ignores my bias") is unanswerable from the
* server side. Such a field is accepted at its "off" value, which is what llama.cpp-built clients
* send on every request. A field this server has never heard of is ignored, as llama.cpp and vLLM
* ignore it (oai.cpp, key vetting).
*/
#pragma once
#include "iface.h"
@@ -40,6 +40,11 @@ struct ApiError {
/* The values `param` takes, when the error is a value outside a known set: `supported` in the
* envelope, so a client can retry with one rather than parse the sentence. */
std::vector<std::string> supported;
/* A prompt the context cannot hold: its length and the context's, under llama-server's names,
* so a client that compacts its history on overflow reads the numbers rather than the
* sentence. -1 leaves them out. */
int64_t n_prompt_tokens = -1;
int64_t n_ctx = -1;
std::string dump() const; /* the OpenAI error envelope, as a JSON string */
};
@@ -60,6 +65,11 @@ ApiError err_overloaded(const std::string& why);
enum class Endpoint { Chat, Completion, Embedding };
/* WHICH API A CHAT REQUEST CAME IN THROUGH, and so which shape its answer goes out in. Every shape
* is parsed into the same chat request (Anthropic's is translated first, anthropic_to_chat) and
* served by the same path; only the bytes on the wire differ. */
enum class ApiShape { OpenAI, Anthropic, Responses, LlamaNative };
struct PromptInput {
std::vector<int32_t> tokens;
std::string text; /* the rendered prompt; needed for `echo` and for the logs */
@@ -73,13 +83,36 @@ struct OaiRequest {
std::string id; /* "chatcmpl-..." / "cmpl-..." */
int64_t created = 0; /* unix seconds */
ApiShape shape = ApiShape::OpenAI;
bool stream = false;
bool include_usage = false; /* stream_options.include_usage */
/* llama.cpp's streaming extras: `timings` on every chunk, not only the last; and
* `prompt_progress` chunks while the prompt is read. */
bool timings_per_token = false;
bool return_progress = false;
/* The conversation as the client names it (OpenRouter's `session_id`), "" when it names none:
* a label on /sessions, nothing else. */
std::string session_label;
/* The build, as OpenAI's `system_fingerprint` and llama.cpp's own: what produced the reply. */
std::string system_fingerprint;
int n = 1;
SamplingParams sp;
int32_t max_tokens = 0;
std::vector<std::string> stop;
/* Of `stop`, how many the client sent; the rest are the chat format's own end-of-turn
* markers. A reply cut on one of the first is Anthropic's `stop_sequence`, on the rest its
* `end_turn`. */
size_t n_client_stops = 0;
/* The assistant text a continued conversation ends in (assistant prefill), "" otherwise. The
* OpenAI shape answers the whole message, as llama-server does; Anthropic's answers what
* follows it, as Anthropic's API does. */
std::string continued;
/* The Responses API's request fields its response object echoes (instructions, tools,
* tool_choice, text, reasoning, ...), as a JSON object; "" for the other shapes. */
std::string echo_json;
/* llama-server's native /completion: the generated token ids beside the text. */
bool return_tokens = false;
/* The reasoning block's closer when the reply starts inside the block, else "": the stop
* strings above then apply only after it (IDetokenizer::defer_stops_until). */
std::string stops_after;
@@ -94,6 +127,9 @@ struct OaiRequest {
bool want_logprobs = false;
bool tools_present = false;
/* OpenAI's deprecated functions API: the request sent `functions`, so the reply carries its
* call as `function_call` (one at most) and ends in finish_reason "function_call". */
bool legacy_functions = false;
/* FOR THE REQUEST LOG, counted while the parse walks the body anyway: the messages and tools
* a chat request carried, and the last user message's opening (one line, bounded) that the
* debug level prints so a log line can be matched to what was typed. Completion requests
@@ -126,6 +162,7 @@ struct OaiRequest {
/* What the server needs to know about itself to validate a request. */
struct OaiLimits {
std::string model_id = "radiance";
std::string version; /* the build, for `system_fingerprint` */
int64_t max_ctx = 0; /* 0 = unknown, no length check */
/* What a request that names no max_tokens may generate. 0 is "whatever the context leaves",
* resolved against the prompt in clamp_max_tokens, which needs max_ctx to resolve against.
@@ -250,23 +287,45 @@ struct OaiDeps {
/* Parse. `body` is the raw request body; a malformed body is a 400 that says where. */
int parse_chat_request(const std::string& body, const OaiDeps& d, const OaiLimits& lim,
OaiRequest* out, ApiError* err);
/* `native` is llama-server's /completion: its `return_tokens`, and a prompt array of strings and
* token ids mixed as ONE prompt, as llama-server reads it. */
int parse_completion_request(const std::string& body, const OaiDeps& d, const OaiLimits& lim,
OaiRequest* out, ApiError* err);
OaiRequest* out, ApiError* err, bool native = false);
/* 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 {
/* One emitted token's logprobs as the wire carries them. `bytes` is the token's own bytes and
* `text` is their longest well-formed UTF-8 prefix -- a byte-level token can hold half a
* character, and a JSON string cannot -- llama-server's spelling. `end` is where the token's
* decoded text ends in the choice's text, which is what decides whether it went out before a stop
* string cut the reply. */
struct LogprobAlt {
int32_t token = 0;
std::string text;
std::string text, bytes;
float logprob = 0.0f;
};
struct LogprobEntry {
int32_t token = 0;
std::string text, bytes;
float logprob = 0.0f;
std::vector<LogprobAlt> top;
size_t end = 0;
};
/* The entries as a JSON array's elements, comma-joined, in OpenAI's chat shape with llama-server's
* `id` beside each token -- which is also llama-server's native `completion_probabilities`. */
std::string logprobs_content(const LogprobEntry* e, size_t n);
/* OpenAI's legacy /v1/completions `logprobs` object for the entries, `offset` the text offset of
* the first, with llama-server's `content` array beside the legacy arrays. */
std::string logprobs_legacy(const LogprobEntry* e, size_t n, size_t offset);
struct ChoiceOut {
int index = 0;
std::string text; /* raw generated text */
std::string stop_word; /* the stop string that cut it, "" when none or unknown */
ParsedMessage msg; /* chat: content / reasoning / tool_calls after parsing */
Finish finish = Finish::None;
std::vector<LogprobEntry> logprobs;
@@ -332,9 +391,9 @@ struct ModelCard {
/* What the server loaded (ServerOptions::model_path), vLLM's `root`. Empty leaves it out. */
std::string root;
/* What the model can be asked for -- tools, reasoning, images -- as /server_info reports it.
* There is no field for it in OpenAI's model object, so a client today learns it by sending a
* request and reading the refusal; the entry it already fetches can say so up front. A JSON
* object as text, spliced in as it is; empty leaves it out. */
* There is no field for it in OpenAI's model object, so without this a client learns it by
* sending a request and reading the refusal; the entry it already fetches can say so up
* front. A JSON object as text, spliced in as it is; empty leaves it out. */
std::string capabilities;
};
/* The list, for GET /v1/models. */
@@ -366,42 +425,54 @@ bool calls_complete(const ParsedMessage& m);
* 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.
*
* THE WIRE SHAPE IS THE SUBCLASS'S. Reading the reply -- the reader, the message it adds up to,
* the finish it implies -- is the same for every API this server speaks, so it lives here once;
* what one increment looks like on the wire is OpenAI's chunk (ChatDeltaStream) or Anthropic's
* event (AnthropicStream).
*/
class ChatDeltaStream {
class ReplyStream {
public:
ChatDeltaStream(const OaiRequest& r, int index, const IReplyParser* parser);
ReplyStream(const OaiRequest& r, int index, const IReplyParser* parser);
virtual ~ReplyStream() = default;
/* The `role: assistant` opener OpenAI clients expect before any content. */
std::string first_chunk();
/* What opens the stream: OpenAI's `role: assistant` chunk, Anthropic's message_start. */
virtual std::string first_chunk() = 0;
/* Feed the text generated since the last push; returns zero or more SSE `data:` lines.
/* Feed the text generated since the last push; returns the bytes for what it completed.
* `is_final` says the generation is over, which resolves whatever the reader was holding. */
std::string push(std::string_view appended, bool is_final);
/* The terminating chunk carrying finish_reason, and this choice's `timings` when they are
* valid -- on the final chunk whether or not the request asked for a usage chunk, as
* llama.cpp sends them. The usage chunk is the stream's, not the choice's: chat_usage_chunk. */
std::string final_chunk(Finish f, const TimingsOut& t = TimingsOut());
/* What closes the choice: the finish reason, and this choice's `timings` when they are valid
* (llama.cpp sends them on the final chunk). `u` is the request's usage, for the shapes that
* close a message with it. */
virtual std::string final_chunk(Finish f, const TimingsOut& t, const UsageOut& u) = 0;
/* What closes a choice the engine failed, in place of final_chunk: the shape's own failure,
* so a client reading to the terminal event never takes a truncated reply as complete.
* OpenAI's chunks have none, so theirs is the final chunk with finish_reason "error" and the
* error object after it. */
virtual std::string error_chunk(const ApiError& e, const TimingsOut& t, const UsageOut& u);
/* What the whole generation parsed to -- the non-streaming shape. Complete once push has
* been called with is_final. */
const ParsedMessage& parsed() const { return last_; }
Finish adjusted_finish(Finish f) const;
private:
std::string chunk(json delta, const char* finish_reason, const TimingsOut* t = nullptr);
std::string emit(const std::vector<ReplyDelta>& ev);
/* llama.cpp's `timings_per_token`, for the shapes that carry timings. */
virtual void set_timings(const TimingsOut&) {}
/* Logprobs entries (logprobs_content's elements) for the next chunk this stream writes, for
* the shapes that carry them; the others drop them. */
virtual void add_logprobs(const std::string&) {}
/* A delta's chunk is written, not built: the frame around the delta object is the same in
* every one, so it is serialised once, and the delta between is written with
* json_quote_append. The bytes are the ones chunk() writes for the same delta. */
void delta_open(std::string& out);
void delta_close(std::string& out) const;
protected:
/* The bytes for the increments one push completed. Each emitter folds every increment into
* `last_` through absorb() first. */
virtual std::string emit(const std::vector<ReplyDelta>& ev) = 0;
bool absorb(const ReplyDelta& d);
static void quote(std::string& out, std::string_view s);
std::string head_; /* `data: {...,"choices":[{"index":N,"delta":`, built on first use */
std::unique_ptr<IReplyReader> reader_;
std::string id_, model_;
std::string id_, model_, fingerprint_;
int64_t created_;
int index_;
bool finished_ = false;
@@ -410,6 +481,116 @@ private:
std::vector<ReplyDelta> ev_;
};
/* ANTHROPIC'S MESSAGES API, translated into the chat request it means (`*chat`, a /v1/chat/completions
* body) so that every refusal and default is the chat endpoint's. `*label` is the conversation's
* label if the request carries one (metadata.user_id). Claude Code's per-request billing stamp in
* the system prompt is held constant, as llama-server holds it, or no turn of a conversation could
* reuse the one before it. */
int anthropic_to_chat(const std::string& body, const OaiLimits& lim, std::string* chat,
std::string* label, ApiError* err);
/* The non-streaming answer, and an error, in Anthropic's shapes. */
std::string anthropic_message_body(const OaiRequest& r, const ChoiceOut& c, const UsageOut& u);
std::string anthropic_error_body(const ApiError& e);
/* OPENAI'S RESPONSES API, translated into the chat request it means, as Anthropic's is. `*echo` is
* the request's fields the response object repeats back. previous_response_id needs responses
* stored server-side and is refused; tool types other than function have no chat equivalent and
* are left out, as llama-server leaves them out. */
int responses_to_chat(const std::string& body, const OaiLimits& lim, std::string* chat,
std::string* echo, ApiError* err);
std::string responses_body(const OaiRequest& r, const ChoiceOut& c, const UsageOut& u);
/* Anthropic's stop_reason for a finish and the stop string that caused it. */
const char* anthropic_stop_reason(const OaiRequest& r, Finish f, const std::string& stop_word);
/* OpenAI's chat.completion.chunk. */
class ChatDeltaStream final : public ReplyStream {
public:
ChatDeltaStream(const OaiRequest& r, int index, const IReplyParser* parser)
: ReplyStream(r, index, parser), legacy_(r.legacy_functions) {}
std::string first_chunk() override;
std::string final_chunk(Finish f, const TimingsOut& t, const UsageOut& u) override;
/* llama.cpp's `timings_per_token`: the timings the next pushes' chunks carry, beside
* `choices` as the final chunk carries them. Invalid timings carry nothing. */
void set_timings(const TimingsOut& t) override;
/* OpenAI's `logprobs.content` on the next chunk out: entries wait for one, because a push may
* complete no delta (a tool call's opening, a held-back byte) and the tokens still count. */
void add_logprobs(const std::string& elems) override;
private:
std::string emit(const std::vector<ReplyDelta>& ev) override;
std::string chunk(json delta, const char* finish_reason, const TimingsOut* t = nullptr);
std::string lp_; /* pending logprobs entries, comma-joined */
/* A delta's chunk is written, not built: the frame around the delta object is the same in
* every one, so it is serialised once, and the delta between is written with
* json_quote_append. The bytes are the ones chunk() writes for the same delta. */
void delta_open(std::string& out);
void delta_close(std::string& out);
std::string head_; /* `data: {...,"choices":[{"index":N,"delta":`, built on first use */
std::string timings_; /* `"timings":{...}` for every delta chunk, or "" */
bool legacy_; /* OaiRequest::legacy_functions */
};
/* ANTHROPIC'S EVENTS: message_start, then a content block a kind -- thinking, text, each tool_use
* -- opened, filled by deltas and stopped, then message_delta with the stop reason and the usage,
* and message_stop. The prefill a continued conversation ends in is not repeated (`continued`). */
class AnthropicStream final : public ReplyStream {
public:
AnthropicStream(const OaiRequest& r, int index, const IReplyParser* parser);
std::string first_chunk() override;
std::string final_chunk(Finish f, const TimingsOut& t, const UsageOut& u) override;
/* Anthropic's `error` event, which ends the stream with no message_stop. */
std::string error_chunk(const ApiError& e, const TimingsOut& t, const UsageOut& u) override;
/* The stop string that cut the reply, for stop_reason and stop_sequence. */
void set_stop_word(const std::string& w) { stop_word_ = w; }
private:
enum class Block { None, Thinking, Text, Tool };
std::string emit(const std::vector<ReplyDelta>& ev) override;
void open(std::string& out, Block b, const ToolCall* tc);
void close(std::string& out);
static void event(std::string& out, const char* type, const json& data);
const OaiRequest* r_;
int64_t n_input_ = 0;
std::string skip_; /* the prefill still to be passed over */
std::string stop_word_;
Block block_ = Block::None;
int n_blocks_ = 0; /* blocks opened so far: the next one's index */
};
/* THE RESPONSES API'S EVENTS: response.created and .in_progress; an output item a kind --
* reasoning, the message, each function call -- added, its content part added, filled by deltas,
* and done; then response.completed (or .incomplete at the token limit) with the whole response.
* Every event carries its output_index, content_index and sequence_number, which the OpenAI SDK's
* stream accumulator places deltas by. */
class ResponsesStream final : public ReplyStream {
public:
ResponsesStream(const OaiRequest& r, int index, const IReplyParser* parser);
std::string first_chunk() override;
std::string final_chunk(Finish f, const TimingsOut& t, const UsageOut& u) override;
/* response.failed, with the items finished so far and the error. */
std::string error_chunk(const ApiError& e, const TimingsOut& t, const UsageOut& u) override;
private:
enum class Item { None, Reasoning, Message, Call };
std::string emit(const std::vector<ReplyDelta>& ev) override;
void open(std::string& out, Item k, size_t call);
void close(std::string& out);
void event(std::string& out, const char* type, json data);
json response(const char* status) const;
const OaiRequest* r_;
Item item_ = Item::None;
std::string item_id_, text_; /* the open item's id and its text so far */
size_t call_ = 0; /* the open call's index into last_.tool_calls */
std::vector<std::string> items_; /* every closed item, serialised, in output order */
int64_t seq_ = 0;
UsageOut usage_;
const char* incomplete_ = nullptr;
};
/* The SSE terminator. Written once at the end of every stream, including a failed one, because a
* client blocked on the reader has no other way to learn the stream is over. */
extern const char* const SSE_DONE;
@@ -431,6 +612,10 @@ bool token_id(const json& v, int32_t* out);
* 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);
/* The body of a generation endpoint: parse_json_bounded, and a 400 saying which bound it broke or
* that it is not one JSON object. */
int parse_request_object(const std::string& body, const OaiLimits& lim, json* b,
ApiError* err);
int64_t json_value_budget(int64_t max_ctx);
constexpr int kJsonMaxDepth = 1024;
+612 -32
View File
@@ -3,6 +3,7 @@
#include <cstdio>
#include "json_partial.h"
#include "rad_internal.h"
#include "text/tokenizer.h"
#include <nlohmann/json.hpp>
@@ -19,12 +20,13 @@ namespace server {
struct Server::Generation {
std::shared_ptr<Sink> sink;
std::unique_ptr<IDetokenizer> detok;
std::unique_ptr<ChatDeltaStream> delta; /* chat streaming only */
std::unique_ptr<ReplyStream> delta; /* chat streaming only, in the request's API shape */
uint64_t id = 0;
int index = 0;
int prompt_index = 0;
std::string text;
std::vector<LogprobEntry> logprobs;
size_t lp_sent = 0; /* streaming: how many of `logprobs` a chunk already carried */
/* The reply against its reasoning block, every token the sink delivers: what
* completion_tokens_details.reasoning_tokens reports. */
ReasoningCount think;
@@ -36,7 +38,11 @@ struct Server::Generation {
size_t stops_floor = std::string::npos;
size_t closer_scanned = 0;
size_t stop_cut = std::string::npos;
std::string stop_word; /* the stop string at stop_cut, "" when the decoder cut it */
size_t emitted = 0; /* streaming: text already handed to the delta stream */
std::vector<int32_t> tokens; /* llama-server's native shape: the ids generated */
size_t tokens_sent = 0; /* ...and how many of them a stream chunk carried */
int32_t progress_sent = -1; /* streaming: the prompt_progress last sent, -1 for none */
bool retired = false; /* reap() has been said for this id, at most once */
};
@@ -55,6 +61,7 @@ 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_.version = opt_.version;
lim_.max_ctx = opt_.max_ctx;
lim_.default_max_tokens = opt_.default_max_tokens;
lim_.max_tokens_cap = opt_.max_tokens_cap;
@@ -131,9 +138,37 @@ void Server::register_routes() {
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); });
/* THE SAME ROUTES WITHOUT /v1, as llama-server answers them: a client configured with the
* bare host as its base URL appends the path alone. */
router_.post("/chat/completions", [this](const HttpRequest& q) { return handle_chat(q); });
/* llama-server's native completion, under both of its names: /completions without /v1 is
* the native endpoint there, not OpenAI's. */
router_.post("/completion", [this](const HttpRequest& q) { return handle_native_completion(q); });
router_.post("/completions", [this](const HttpRequest& q) { return handle_native_completion(q); });
router_.post("/infill", [this](const HttpRequest& q) { return handle_infill(q); });
router_.post("/embeddings", [this](const HttpRequest& q) { return handle_embeddings(q); });
router_.get ("/models", [this](const HttpRequest& q) { return handle_models(q); });
/* llama-server's: the prompt a chat request renders to, and how many tokens it is. */
router_.post("/apply-template", [this](const HttpRequest& q) { return handle_apply_template(q); });
router_.post("/v1/chat/completions/input_tokens",
[this](const HttpRequest& q) { return handle_input_tokens(q); });
router_.post("/chat/completions/input_tokens",
[this](const HttpRequest& q) { return handle_input_tokens(q); });
/* Anthropic's Messages API, translated onto the chat path (anthropic_to_chat). */
router_.post("/v1/messages", [this](const HttpRequest& q) { return handle_messages(q); });
router_.post("/v1/messages/count_tokens",
[this](const HttpRequest& q) { return handle_count_tokens(q); });
/* OpenAI's Responses API, translated the same way (responses_to_chat). */
router_.post("/v1/responses", [this](const HttpRequest& q) { return handle_responses(q); });
router_.post("/responses", [this](const HttpRequest& q) { return handle_responses(q); });
router_.post("/v1/responses/input_tokens",
[this](const HttpRequest& q) { return handle_responses_tokens(q); });
router_.post("/responses/input_tokens",
[this](const HttpRequest& q) { return handle_responses_tokens(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 ("/v1/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); });
@@ -309,7 +344,7 @@ static std::string from_peer(const std::string& peer) {
return peer.empty() ? std::string() : " from " + peer;
}
HttpResponse Server::error_response(const ApiError& e, const std::string& peer) {
HttpResponse Server::error_response(const ApiError& e, const std::string& peer, ApiShape shape) {
metrics_.observe_http(e.status);
/* A refusal is the line the operator is looking for when a client says "rejected": the
* status, the type, the message, and who asked. 4xx is the client's doing and said at info;
@@ -320,7 +355,8 @@ HttpResponse Server::error_response(const ApiError& e, const std::string& peer)
else
RAD_INFO("req refused%s -> %d %s: %s", from_peer(peer).c_str(), e.status, e.type.c_str(),
e.message.c_str());
HttpResponse r = HttpResponse::json_body(e.status, e.dump());
HttpResponse r = HttpResponse::json_body(
e.status, shape == ApiShape::Anthropic ? anthropic_error_body(e) : e.dump());
if (e.status == 429) r.set_header("Retry-After", std::to_string(opt_.retry_after_s));
return r;
}
@@ -376,7 +412,7 @@ int Server::submit_all(const OaiRequest& r, std::vector<Generation>* gens, ApiEr
g.index = idx;
g.prompt_index = (int)p;
g.sink = std::make_shared<Sink>();
g.sink->set_has_logprobs(opt_.supports_logprobs);
if (r.want_logprobs) g.sink->enable_logprobs(r.n_logprobs);
g.think.start(r.sp.reasoning);
g.detok = deps_.tok->detokenizer(r.stop, r.preserved_tokens);
if (!g.detok) {
@@ -399,6 +435,7 @@ int Server::submit_all(const OaiRequest& r, std::vector<Generation>* gens, ApiEr
rq.priority = r.priority;
rq.stream = r.stream;
rq.media = r.prompts[p].media;
rq.session_label = r.session_label;
rq.sink = g.sink.get();
rqs.push_back(std::move(rq));
gens->push_back(std::move(g));
@@ -447,9 +484,32 @@ bool Server::all_done(const std::vector<Generation>& gens) const {
return true;
}
/* A token's logprobs entry text: the bytes it adds to the reply, and the readable prefix of them. */
static void lp_text(const ITokenizer& tok, int32_t id, std::string* text, std::string* bytes) {
*bytes = tok.reply_bytes(id);
*text = bytes->substr(0, utf8_valid_prefix(*bytes));
}
/* How many of the entries from `from` went out with the reply: under a stop string, every one
* whose text BEGAN before the cut -- one that straddles it contributed text the client got, and
* the stop string's own tokens did not -- and otherwise all of them. */
static size_t lp_before_cut(const std::vector<LogprobEntry>& lp, size_t from, size_t cut) {
if (cut == std::string::npos) return lp.size() - from;
size_t start = from ? lp[from - 1].end : 0, n = 0;
for (size_t k = from; k < lp.size() && start < cut; ++k, ++n) start = lp[k].end;
return n;
}
static std::vector<LogprobEntry> kept_logprobs(const std::vector<LogprobEntry>& lp, size_t cut) {
return std::vector<LogprobEntry>(lp.begin(), lp.begin() + (long)lp_before_cut(lp, 0, cut));
}
bool Server::pump(std::vector<Generation>& gens, const OaiRequest& r) {
bool progress = false;
SinkToken buf[128];
/* Each read's alternatives; only a request that asked for them sizes this. */
thread_local std::vector<SinkAlt> alts;
if (r.want_logprobs) alts.resize(128 * (size_t)std::max(1, r.n_logprobs));
size_t maxstop = 0;
for (const auto& s : r.stop) maxstop = std::max(maxstop, s.size());
@@ -458,14 +518,28 @@ bool Server::pump(std::vector<Generation>& gens, const OaiRequest& r) {
if (g.closed) continue;
size_t n;
while ((n = g.sink->read(buf, 128)) > 0) {
while ((n = g.sink->read(buf, 128, r.want_logprobs ? alts.data() : nullptr)) > 0) {
progress = true;
for (size_t i = 0; i < n; ++i) {
g.think.push(r.sp.reasoning, buf[i].token);
if (r.shape == ApiShape::LlamaNative) g.tokens.push_back(buf[i].token);
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});
if (!r.want_logprobs) continue;
LogprobEntry e;
e.token = buf[i].token;
e.logprob = buf[i].logprob;
e.end = g.text.size();
lp_text(*deps_.tok, e.token, &e.text, &e.bytes);
const SinkAlt* a = alts.data() + i * (size_t)g.sink->alt_width();
for (int32_t j = 0; j < buf[i].n_alt; ++j) {
LogprobAlt t;
t.token = a[j].id;
t.logprob = a[j].logprob;
lp_text(*deps_.tok, t.token, &t.text, &t.bytes);
e.top.push_back(std::move(t));
}
g.logprobs.push_back(std::move(e));
}
}
@@ -473,6 +547,7 @@ bool Server::pump(std::vector<Generation>& gens, const OaiRequest& r) {
* 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.stop_word = g.detok->stop_hit();
g.finish = Finish::StopString;
g.closed = true;
progress = true;
@@ -506,8 +581,10 @@ bool Server::pump(std::vector<Generation>& gens, const OaiRequest& r) {
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))
if (at != std::string::npos && (g.stop_cut == std::string::npos || at < g.stop_cut)) {
g.stop_cut = at;
g.stop_word = s;
}
}
g.scanned = g.text.size();
if (g.stop_cut != std::string::npos) {
@@ -665,7 +742,7 @@ HttpResponse Server::blocking_completion(const HttpRequest& req, OaiRequest& r)
if (submit_all(r, &gens, &err) < 0) {
retire(gens);
release(r.n_choices());
return error_response(err, req.peer);
return error_response(err, req.peer, r.shape);
}
for (;;) {
@@ -686,7 +763,7 @@ HttpResponse Server::blocking_completion(const HttpRequest& req, OaiRequest& r)
cancel_all(gens, false);
retire(gens);
release(r.n_choices());
return error_response(err_overloaded("the server is shutting down"), req.peer);
return error_response(err_overloaded("the server is shutting down"), req.peer, r.shape);
}
/* 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; }
@@ -702,7 +779,8 @@ HttpResponse Server::blocking_completion(const HttpRequest& req, OaiRequest& r)
ChoiceOut c;
c.index = g.index;
c.finish = g.finish;
c.logprobs = std::move(g.logprobs);
c.stop_word = g.stop_word;
if (r.want_logprobs) c.logprobs = kept_logprobs(g.logprobs, g.stop_cut);
if (r.endpoint == Endpoint::Chat) {
/* Parse whenever there is a parser, not only when tools were sent: the same parser
@@ -757,7 +835,7 @@ HttpResponse Server::blocking_completion(const HttpRequest& req, OaiRequest& r)
e.status = 500;
e.type = "internal_server_error";
e.message = why;
return error_response(e, req.peer);
return error_response(e, req.peer, r.shape);
}
}
@@ -766,32 +844,172 @@ HttpResponse Server::blocking_completion(const HttpRequest& req, OaiRequest& r)
release(r.n_choices());
const TimingsOut timings = timings_of(gens);
std::string body = r.endpoint == Endpoint::Chat
if (r.shape == ApiShape::LlamaNative) {
/* llama-server answers one result, and an array of them for several prompts. */
json res = json::array();
for (const auto& g : gens) res.push_back(native_result(r, g, g.text));
metrics_.observe_http(200);
return HttpResponse::json_body(200, json_dump(res.size() == 1 ? res[0] : res));
}
std::string body = r.shape == ApiShape::Anthropic
? anthropic_message_body(r, choices.front(), usage)
: r.shape == ApiShape::Responses
? responses_body(r, choices.front(), usage)
: r.endpoint == Endpoint::Chat
? chat_completion_body(r, choices, usage, timings)
: text_completion_body(r, choices, usage, timings);
metrics_.observe_http(200);
return HttpResponse::json_body(200, std::move(body));
}
/* ------------------------------------------------------------------ llama-server's native shape */
/* What a request was served with, under llama-server's names: its `generation_settings`. */
static nlohmann::ordered_json native_settings(const OaiRequest& r) {
const SamplingParams& sp = r.sp;
nlohmann::ordered_json p;
p["seed"] = sp.seed;
p["temperature"] = sp.temp;
p["top_k"] = sp.top_k;
p["top_p"] = sp.top_p;
p["min_p"] = sp.min_p;
p["typical_p"] = sp.typical_p;
p["xtc_probability"] = sp.xtc_probability;
p["xtc_threshold"] = sp.xtc_threshold;
p["repeat_last_n"] = sp.penalty_last_n;
p["repeat_penalty"] = sp.rep_penalty;
p["presence_penalty"] = sp.pres_penalty;
p["frequency_penalty"] = sp.freq_penalty;
p["dry_multiplier"] = sp.dry_multiplier;
p["dry_base"] = sp.dry_base;
p["dry_allowed_length"] = sp.dry_allowed_length;
p["dry_penalty_last_n"] = sp.dry_penalty_last_n;
p["dry_sequence_breakers"] = sp.dry_seq_breakers;
p["mirostat"] = 0;
p["stop"] = std::vector<std::string>(r.stop.begin(),
r.stop.begin() + (long)std::min(r.n_client_stops, r.stop.size()));
p["max_tokens"] = r.max_tokens;
p["n_predict"] = r.max_tokens;
p["ignore_eos"] = r.ignore_eos;
p["stream"] = r.stream;
p["grammar"] = sp.grammar;
p["n_probs"] = r.want_logprobs ? r.n_logprobs : 0;
p["post_sampling_probs"] = false;
p["samplers"] = sp.temp_last
? std::vector<std::string>{ "penalties", "dry", "top_k", "top_p", "min_p", "typ_p", "xtc", "temperature" }
: std::vector<std::string>{ "penalties", "dry", "temperature", "top_k", "top_p", "min_p", "typ_p", "xtc" };
return p;
}
static const char* native_stop_type(Finish f) {
switch (f) {
case Finish::Stop: return "eos";
case Finish::Length: return "limit";
case Finish::StopString: return "word";
default: return "none";
}
}
/* llama-server's final result for one choice: the text, how it ended, the prompt it ran on and
* where the time went. A stream's last chunk is this with `content` empty -- the text went out
* 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 int64_t n_prompt = (int64_t)r.prompts[(size_t)g.prompt_index].tokens.size();
nlohmann::ordered_json o;
o["index"] = g.index;
o["content"] = content;
o["tokens"] = r.return_tokens ? g.tokens : std::vector<int32_t>{};
o["id_slot"] = 0;
o["stop"] = true;
o["model"] = r.model;
o["tokens_predicted"] = g.sink->n_produced();
o["tokens_evaluated"] = n_prompt;
o["generation_settings"] = native_settings(r);
o["prompt"] = r.prompts[(size_t)g.prompt_index].text;
o["has_new_line"] = g.text.find('\n') != std::string::npos;
o["truncated"] = false;
o["stop_type"] = native_stop_type(g.finish);
o["stopping_word"] = g.stop_word;
o["tokens_cached"] = n_prompt + g.sink->n_produced();
if (t.valid) o["timings"] = timings_json(t);
/* The whole reply's probabilities on the answer, as llama-server sends them: a stream
* carried them chunk by chunk instead. */
if (r.want_logprobs && !r.stream) {
const std::vector<LogprobEntry> kept = kept_logprobs(g.logprobs, g.stop_cut);
o["completion_probabilities"] =
nlohmann::ordered_json::parse("[" + logprobs_content(kept.data(), kept.size()) + "]");
}
return o;
}
/* ------------------------------------------------------------------ streaming */
static std::string text_chunk(const OaiRequest& r, int index, const std::string& delta,
const char* finish_reason, const TimingsOut* t = nullptr) {
const char* finish_reason, const TimingsOut* t = nullptr,
const std::string& logprobs = std::string()) {
nlohmann::ordered_json ch;
ch["text"] = delta;
ch["index"] = index;
ch["logprobs"] = nullptr;
if (!logprobs.empty()) ch["logprobs"] = nlohmann::ordered_json::parse(logprobs);
else 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;
if (!r.system_fingerprint.empty()) o["system_fingerprint"] = r.system_fingerprint;
o["choices"] = nlohmann::ordered_json::array({ch});
if (t && t->valid) o["timings"] = timings_json(*t);
return sse_event(o.dump());
}
/* llama-server's `prompt_progress` chunk: the endpoint's opening chunk -- an assistant role with
* no content, or an empty text -- carrying how much of the prompt is in the cache, of how much,
* how much of that the prefix cache supplied, and the time since the prompt phase began. */
static std::string progress_chunk(const OaiRequest& r, int index, const Sink& s) {
nlohmann::ordered_json ch;
if (r.shape == ApiShape::LlamaNative) {
/* llama-server's native chunk carries the progress at its top level. */
const int64_t ta = s.t_admitted_ns();
nlohmann::ordered_json o;
o["index"] = index;
o["content"] = "";
o["tokens"] = nlohmann::ordered_json::array();
o["stop"] = false;
o["prompt_progress"] = { { "total", s.progress_total() }, { "cache", s.progress_cached() },
{ "processed", s.progress_processed() },
{ "time_ms", ta >= 0 ? (s.age_ns() - ta) / 1000000 : 0 } };
return sse_event(o.dump());
}
if (r.endpoint == Endpoint::Chat) {
ch["index"] = index;
ch["delta"] = { { "role", "assistant" }, { "content", nullptr } };
} else {
ch["text"] = "";
ch["index"] = index;
ch["logprobs"] = nullptr;
}
ch["finish_reason"] = nullptr;
const int64_t ta = s.t_admitted_ns();
nlohmann::ordered_json pp;
pp["total"] = s.progress_total();
pp["cache"] = s.progress_cached();
pp["processed"] = s.progress_processed();
pp["time_ms"] = ta >= 0 ? (s.age_ns() - ta) / 1000000 : 0;
nlohmann::ordered_json o;
o["id"] = r.id;
o["object"] = r.endpoint == Endpoint::Chat ? "chat.completion.chunk" : "text_completion";
o["created"] = r.created;
o["model"] = r.model;
if (!r.system_fingerprint.empty()) o["system_fingerprint"] = r.system_fingerprint;
o["choices"] = nlohmann::ordered_json::array({ch});
o["prompt_progress"] = std::move(pp);
return sse_event(o.dump());
}
HttpResponse Server::streaming_completion(const HttpRequest& req, OaiRequest& r) {
auto st = std::make_shared<StreamState>();
st->r = r;
@@ -801,11 +1019,16 @@ HttpResponse Server::streaming_completion(const HttpRequest& req, OaiRequest& r)
if (submit_all(st->r, &st->gens, &err) < 0) {
retire(st->gens);
release(r.n_choices());
return error_response(err, req.peer);
return error_response(err, req.peer, r.shape);
}
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()));
g.delta.reset(
st->r.shape == ApiShape::Anthropic
? (ReplyStream*)new AnthropicStream(st->r, g.index, st->r.reply_parser.get())
: st->r.shape == ApiShape::Responses
? (ReplyStream*)new ResponsesStream(st->r, g.index, st->r.reply_parser.get())
: (ReplyStream*)new ChatDeltaStream(st->r, g.index, st->r.reply_parser.get()));
HttpResponse res;
res.status = 200;
@@ -852,6 +1075,15 @@ HttpResponse Server::streaming_completion(const HttpRequest& req, OaiRequest& r)
for (const auto& s : st->r.stop) maxstop = std::max(maxstop, s.size());
for (auto& g : st->gens) {
/* The prompt's progress first, so a client sees it before the first token: every
* advance the scheduler reported, as llama-server sends one a prefill batch. */
if (st->r.return_progress) {
const int32_t done = g.sink->progress_processed();
if (done > g.progress_sent) {
out += progress_chunk(st->r, g.index, *g.sink);
g.progress_sent = done;
}
}
/* 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.
@@ -867,16 +1099,67 @@ HttpResponse Server::streaming_completion(const HttpRequest& req, OaiRequest& r)
if (safe <= g.emitted) continue;
}
/* THE LOGPROBS OF THE TOKENS WHOSE TEXT THIS CHUNK CARRIES: every entry ending inside
* it while the choice runs, and once it is closed the rest of what went out with the
* reply (lp_before_cut). */
size_t lp_n = 0, lp_off = 0;
if (st->r.want_logprobs) {
lp_off = g.lp_sent ? g.logprobs[g.lp_sent - 1].end : 0;
if (g.closed)
lp_n = lp_before_cut(g.logprobs, g.lp_sent, g.stop_cut);
else
while (g.lp_sent + lp_n < g.logprobs.size() &&
g.logprobs[g.lp_sent + lp_n].end <= safe) ++lp_n;
}
const LogprobEntry* lp_at = lp_n ? &g.logprobs[g.lp_sent] : nullptr;
g.lp_sent += lp_n;
/* llama.cpp's `timings_per_token`: this choice's timings so far on every chunk. */
TimingsOut now;
if (st->r.timings_per_token) {
const Sink* one = g.sink.get();
now = timings_of(&one, 1);
if (g.delta) g.delta->set_timings(now);
}
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. */
if (lp_n) g.delta->add_logprobs(logprobs_content(lp_at, lp_n));
out += g.delta->push(std::string_view(g.text).substr(g.emitted, safe - g.emitted),
g.closed);
} else if (safe > g.emitted) {
} else if (st->r.shape == ApiShape::LlamaNative) {
/* llama-server's native chunk: the new text, the ids that made it, the counts. */
if (safe > g.emitted || g.tokens.size() > g.tokens_sent || lp_n) {
nlohmann::ordered_json o;
o["index"] = g.index;
o["content"] = g.text.substr(g.emitted, safe - g.emitted);
o["tokens"] = std::vector<int32_t>(g.tokens.begin() + (long)g.tokens_sent,
g.tokens.end());
o["stop"] = false;
o["id_slot"] = -1;
o["tokens_predicted"] = g.sink->n_produced();
o["tokens_evaluated"] =
(int64_t)st->r.prompts[(size_t)g.prompt_index].tokens.size();
if (st->r.timings_per_token && now.valid) o["timings"] = timings_json(now);
if (lp_n)
o["completion_probabilities"] = nlohmann::ordered_json::parse(
"[" + logprobs_content(lp_at, lp_n) + "]");
out += sse_event(o.dump());
g.tokens_sent = g.tokens.size();
}
} else if (safe > g.emitted || lp_n) {
out += text_chunk(st->r, g.index, g.text.substr(g.emitted, safe - g.emitted),
nullptr);
nullptr, st->r.timings_per_token ? &now : nullptr,
lp_n ? logprobs_legacy(lp_at, lp_n, lp_off) : std::string());
}
g.emitted = safe;
/* A sent entry is read again only as the one before the next, for where that one
* starts; keeping the rest would hold ~1.7 KB a token at 20 alternatives for the
* whole of a long stream. */
if (g.lp_sent > 1) {
g.logprobs.erase(g.logprobs.begin(), g.logprobs.begin() + (long)(g.lp_sent - 1));
g.lp_sent = 1;
}
}
if (self->all_done(st->gens)) {
@@ -887,24 +1170,34 @@ HttpResponse Server::streaming_completion(const HttpRequest& req, OaiRequest& r)
* usage chunk still has them, as llama.cpp sends them. */
const Sink* one = g.sink.get();
const TimingsOut gt = timings_of(&one, 1);
if (st->r.endpoint == Endpoint::Chat) {
out += g.delta->final_chunk(g.finish, gt);
Finish adj = g.delta->adjusted_finish(g.finish);
if (adj == Finish::Error || adj == Finish::Cancelled) overall = adj;
else if (adj == Finish::ToolCalls) overall = adj;
} else {
out += text_chunk(st->r, g.index, "", finish_reason_oai(g.finish), &gt);
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
* 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. */
ApiError e;
if (g.finish == Finish::Error) {
ApiError e;
e.status = 500;
e.type = "internal_server_error";
e.message = engine_failure(*g.sink);
out += sse_error(e);
overall = Finish::Error;
}
if (st->r.endpoint == Endpoint::Chat) {
if (auto* a = dynamic_cast<AnthropicStream*>(g.delta.get()))
a->set_stop_word(g.stop_word);
if (g.finish == Finish::Error) {
out += g.delta->error_chunk(e, gt, u);
} else {
out += g.delta->final_chunk(g.finish, gt, u);
const Finish adj = g.delta->adjusted_finish(g.finish);
if (overall != Finish::Error &&
(adj == Finish::Cancelled || adj == Finish::ToolCalls))
overall = adj;
}
} else if (st->r.shape == ApiShape::LlamaNative) {
out += sse_event(json_dump(self->native_result(st->r, g, "")));
if (g.finish == Finish::Error) out += sse_error(e);
} else {
out += text_chunk(st->r, g.index, "", finish_reason_oai(g.finish), &gt);
if (g.finish == Finish::Error) out += sse_error(e);
}
}
/* THE USAGE CHUNK. `stream_options.include_usage` is parsed and validated on both
@@ -921,7 +1214,9 @@ HttpResponse Server::streaming_completion(const HttpRequest& req, OaiRequest& r)
: text_usage_chunk(st->r, u, t);
}
out += SSE_DONE;
/* Anthropic's stream ends with message_stop and the Responses API's with
* response.completed, which final_chunk wrote; chat completions' with [DONE]. */
if (st->r.shape == ApiShape::OpenAI) out += SSE_DONE;
st->done_sent = true;
self->record(st->r, st->gens, overall);
self->retire(st->gens);
@@ -981,6 +1276,291 @@ HttpResponse Server::handle_chat(const HttpRequest& req) {
return r.stream ? streaming_completion(req, r) : blocking_completion(req, r);
}
/* llama-server's /apply-template and its token count. Both parse the request exactly as
* /v1/chat/completions does -- the same template defaults, the same refusals -- and stop before
* anything is queued, so the prompt they report is the prompt a chat request would run. */
HttpResponse Server::handle_apply_template(const HttpRequest& req) {
if (!deps_.tok || !deps_.chat)
return error_response(err_not_implemented("rendering a chat requires a chat template; "
"this model was loaded without one"), req.peer);
OaiRequest r;
ApiError err;
if (parse_chat_request(req.body, odeps_, lim_, &r, &err) < 0)
return error_response(err, req.peer);
json o;
o["prompt"] = r.prompts.empty() ? std::string() : r.prompts[0].text;
metrics_.observe_http(200);
return HttpResponse::json_body(200, json_dump(o));
}
HttpResponse Server::handle_input_tokens(const HttpRequest& req) {
if (!deps_.tok || !deps_.chat)
return error_response(err_not_implemented("rendering a chat requires a chat template; "
"this model was loaded without one"), req.peer);
OaiRequest r;
ApiError err;
if (parse_chat_request(req.body, odeps_, lim_, &r, &err) < 0)
return error_response(err, req.peer);
json o;
o["object"] = "response.input_tokens";
o["input_tokens"] = r.prompts.empty() ? 0 : (int64_t)r.prompts[0].tokens.size();
metrics_.observe_http(200);
return HttpResponse::json_body(200, json_dump(o));
}
/* ANTHROPIC'S MESSAGES API. The request is translated into the chat request it means and parsed by
* the chat endpoint's own parser, so every default, refusal and template rule is that endpoint's;
* the answer and the errors go out in Anthropic's shapes. */
HttpResponse Server::handle_messages(const HttpRequest& req) {
if (!deps_.sched || !deps_.tok)
return error_response(err_not_implemented("the server has no engine attached"), req.peer,
ApiShape::Anthropic);
if (opt_.embedding_model)
return error_response(err_not_implemented("this is an embedding model: it serves "
"/v1/embeddings and generates no text"),
req.peer, ApiShape::Anthropic);
std::string chat, label;
ApiError err;
OaiRequest r;
if (anthropic_to_chat(req.body, lim_, &chat, &label, &err) < 0 ||
parse_chat_request(chat, odeps_, lim_, &r, &err) < 0)
return error_response(err, req.peer, ApiShape::Anthropic);
r.shape = ApiShape::Anthropic;
r.id = random_id("msg_");
if (r.session_label.empty()) r.session_label = label;
return serve_translated(req, r);
}
HttpResponse Server::serve_translated(const HttpRequest& req, OaiRequest& r) {
r.peer = req.peer;
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"), req.peer, r.shape);
}
log_admitted(r);
return r.stream ? streaming_completion(req, r) : blocking_completion(req, r);
}
/* llama-server's NATIVE /completion: the completions parser with llama-server's prompt forms,
* answered in its shape (native_result). */
HttpResponse Server::handle_native_completion(const HttpRequest& req) {
if (!deps_.sched || !deps_.tok)
return error_response(err_not_implemented("the server has no engine attached"), req.peer);
if (opt_.embedding_model)
return error_response(err_not_implemented("this is an embedding model: it serves "
"/v1/embeddings and generates no text"),
req.peer);
OaiRequest r;
ApiError err;
if (parse_completion_request(req.body, odeps_, lim_, &r, &err, /*native=*/true) < 0)
return error_response(err, req.peer);
r.shape = ApiShape::LlamaNative;
return serve_translated(req, r);
}
/* A control token by the spellings model families give it, or -1: what llama.cpp's vocabulary
* loader recognises the fill-in-the-middle tokens by. A spelling counts only when it is ONE token
* that renders as itself. */
static int32_t special_token(const ITokenizer& tok, std::initializer_list<const char*> names) {
for (const char* n : names) {
const std::vector<int32_t> t = tok.encode(n, false, /*parse_special=*/true);
if (t.size() == 1 && tok.token_bytes(t[0]) == n) return t[0];
}
return -1;
}
/* llama-server's /infill: code completion between a prefix and a suffix, as llama.vim and
* llama.vscode ask for it, in the repository-level FIM layout (arXiv 2409.12186) llama-server
* builds -- the extra files each under its name, then prefix, suffix and middle:
*
* [REPO]myproject\n [SEP]name\n text ... [SEP]filename\n [PRE]prefix+prompt [SUF]suffix [MID]
*
* A model with no fill-in-the-middle tokens cannot do it and is refused. The completion itself is
* a native one, with every native field. */
HttpResponse Server::handle_infill(const HttpRequest& req) {
if (!deps_.sched || !deps_.tok)
return error_response(err_not_implemented("the server has no engine attached"), req.peer);
const ITokenizer& tok = *deps_.tok;
const int32_t pre = special_token(tok, { "<|fim_prefix|>", "<fim_prefix>", "<fim-prefix>",
"<|fim▁begin|>", "<PRE>", "▁<PRE>", "<|code_prefix|>" });
const int32_t suf = special_token(tok, { "<|fim_suffix|>", "<fim_suffix>", "<fim-suffix>",
"<|fim▁hole|>", "<SUF>", "▁<SUF>", "<|code_suffix|>" });
const int32_t mid = special_token(tok, { "<|fim_middle|>", "<fim_middle>", "<fim-middle>",
"<|fim▁end|>", "<MID>", "▁<MID>", "<|code_middle|>" });
if (pre < 0 || suf < 0 || mid < 0)
return error_response(err_not_implemented("this model has no fill-in-the-middle tokens, "
"so /infill cannot be served"), req.peer);
const int32_t rep = special_token(tok, { "<|repo_name|>", "<|fim_repo|>", "<fim-repo>",
"<reponame>", "<REPO>" });
const int32_t sep = special_token(tok, { "<|file_sep|>", "<|fim_sep|>", "<fim-sep>",
"<file_sep>", "<filename>" });
json b;
{
ApiError e;
if (parse_request_object(req.body, lim_, &b, &e) < 0) return error_response(e, req.peer);
}
auto text_of = [&](const char* k, std::vector<int32_t>* out, ApiError* e) {
auto it = b.find(k);
if (it == b.end() || it->is_null()) return true;
if (it->is_string()) {
*out = tok.encode(it->get<std::string>(), false, false);
return true;
}
if (it->is_array()) {
for (const json& v : *it) {
int32_t id = 0;
if (v.is_string()) {
const std::vector<int32_t> t = tok.encode(v.get<std::string>(), false, false);
out->insert(out->end(), t.begin(), t.end());
} else if (v.is_number_integer() && token_id(v, &id)) {
out->push_back(id);
} else {
*e = err_bad(k, "expected a string, or strings and token ids");
return false;
}
}
return true;
}
*e = err_bad(k, "expected a string");
return false;
};
ApiError err;
std::vector<int32_t> prefix, suffix, prompt;
if (!text_of("input_prefix", &prefix, &err) || !text_of("input_suffix", &suffix, &err) ||
!text_of("prompt", &prompt, &err))
return error_response(err, req.peer);
std::vector<int32_t> extra;
if (rep >= 0) {
extra.push_back(rep);
const std::vector<int32_t> t = tok.encode("myproject\n", false, false);
extra.insert(extra.end(), t.begin(), t.end());
}
auto ex = b.find("input_extra");
if (ex != b.end() && ex->is_array()) {
for (const json& c : *ex) {
if (!c.is_object()) continue;
auto fn = c.find("filename"), tx = c.find("text");
if ((fn != c.end() && !fn->is_null() && !fn->is_string()) ||
(tx != c.end() && !tx->is_null() && !tx->is_string()))
return error_response(err_bad("input_extra[]", "filename and text must be strings"),
req.peer);
const std::string name = fn != c.end() && fn->is_string() ? fn->get<std::string>() : "tmp";
std::vector<int32_t> t;
if (sep >= 0) {
extra.push_back(sep);
t = tok.encode(name + "\n", false, false);
} else {
t = tok.encode("\n\n--- snippet ---\n\n", false, false);
}
extra.insert(extra.end(), t.begin(), t.end());
t = tok.encode(tx != c.end() && tx->is_string() ? tx->get<std::string>() : std::string(),
false, false);
extra.insert(extra.end(), t.begin(), t.end());
}
}
if (sep >= 0) {
extra.push_back(sep);
const std::vector<int32_t> t = tok.encode("filename\n", false, false);
extra.insert(extra.end(), t.begin(), t.end());
}
/* THE EXTRA FILES GIVE WAY FIRST, newest kept, when the whole does not fit beside what the
* reply may generate: they are context, and the prefix and suffix are the edit. */
int64_t reserve = 256;
for (const char* k : { "max_tokens", "n_predict" }) {
auto it = b.find(k);
if (it == b.end() || it->is_null()) continue;
if (!it->is_number_integer())
return error_response(err_bad(k, "expected an integer"), req.peer);
reserve = it->get<int64_t>();
}
if (reserve <= 0) reserve = 256;
const ITokenizer::VocabInfo vi = tok.vocab_info();
const int64_t fixed = (int64_t)(prefix.size() + prompt.size() + suffix.size()) + 3 +
(vi.add_bos && vi.bos >= 0 ? 1 : 0);
if (opt_.max_ctx > 0) {
const int64_t room = std::max<int64_t>(opt_.max_ctx - fixed - reserve, 0);
if ((int64_t)extra.size() > room) extra.erase(extra.begin(), extra.end() - room);
}
std::vector<int32_t> ids;
if (vi.add_bos && vi.bos >= 0) ids.push_back(vi.bos);
ids.insert(ids.end(), extra.begin(), extra.end());
ids.push_back(pre);
ids.insert(ids.end(), prefix.begin(), prefix.end());
ids.insert(ids.end(), prompt.begin(), prompt.end());
ids.push_back(suf);
ids.insert(ids.end(), suffix.begin(), suffix.end());
ids.push_back(mid);
for (const char* k : { "input_prefix", "input_suffix", "input_extra", "prompt" }) b.erase(k);
b["prompt"] = ids;
OaiRequest r;
if (parse_completion_request(b.dump(), odeps_, lim_, &r, &err, /*native=*/true) < 0)
return error_response(err, req.peer);
r.shape = ApiShape::LlamaNative;
return serve_translated(req, r);
}
/* OPENAI'S RESPONSES API, as the Messages API: translated into the chat request it means, served
* by the chat path, answered as a response object or its event stream. */
HttpResponse Server::handle_responses(const HttpRequest& req) {
if (!deps_.sched || !deps_.tok)
return error_response(err_not_implemented("the server has no engine attached"), req.peer);
if (opt_.embedding_model)
return error_response(err_not_implemented("this is an embedding model: it serves "
"/v1/embeddings and generates no text"),
req.peer);
std::string chat, echo;
ApiError err;
OaiRequest r;
if (responses_to_chat(req.body, lim_, &chat, &echo, &err) < 0 ||
parse_chat_request(chat, odeps_, lim_, &r, &err) < 0)
return error_response(err, req.peer);
r.shape = ApiShape::Responses;
r.id = random_id("resp_");
r.echo_json = std::move(echo);
return serve_translated(req, r);
}
HttpResponse Server::handle_responses_tokens(const HttpRequest& req) {
if (!deps_.tok || !deps_.chat)
return error_response(err_not_implemented("rendering a chat requires a chat template; "
"this model was loaded without one"), req.peer);
std::string chat;
ApiError err;
OaiRequest r;
if (responses_to_chat(req.body, lim_, &chat, nullptr, &err) < 0 ||
parse_chat_request(chat, odeps_, lim_, &r, &err) < 0)
return error_response(err, req.peer);
json o;
o["object"] = "response.input_tokens";
o["input_tokens"] = r.prompts.empty() ? 0 : (int64_t)r.prompts[0].tokens.size();
metrics_.observe_http(200);
return HttpResponse::json_body(200, json_dump(o));
}
HttpResponse Server::handle_count_tokens(const HttpRequest& req) {
if (!deps_.tok || !deps_.chat)
return error_response(err_not_implemented("rendering a chat requires a chat template; "
"this model was loaded without one"), req.peer,
ApiShape::Anthropic);
std::string chat;
ApiError err;
OaiRequest r;
if (anthropic_to_chat(req.body, lim_, &chat, nullptr, &err) < 0 ||
parse_chat_request(chat, odeps_, lim_, &r, &err) < 0)
return error_response(err, req.peer, ApiShape::Anthropic);
json o;
o["input_tokens"] = r.prompts.empty() ? 0 : (int64_t)r.prompts[0].tokens.size();
metrics_.observe_http(200);
return HttpResponse::json_body(200, json_dump(o));
}
HttpResponse Server::handle_completion(const HttpRequest& req) {
if (!deps_.sched || !deps_.tok)
return error_response(err_not_implemented("the server has no engine attached"), req.peer);
+14 -1
View File
@@ -196,6 +196,18 @@ private:
HttpResponse handle_ping(const HttpRequest& req);
HttpResponse handle_version(const HttpRequest& req);
HttpResponse handle_props(const HttpRequest& req);
HttpResponse handle_apply_template(const HttpRequest& req);
HttpResponse handle_input_tokens(const HttpRequest& req);
HttpResponse handle_messages(const HttpRequest& req);
HttpResponse handle_count_tokens(const HttpRequest& req);
HttpResponse handle_responses(const HttpRequest& req);
HttpResponse handle_responses_tokens(const HttpRequest& req);
/* A request another API's shape was translated into: admitted and served like a chat one,
* answered in `r.shape`. */
HttpResponse serve_translated(const HttpRequest& req, OaiRequest& r);
HttpResponse handle_native_completion(const HttpRequest& req);
HttpResponse handle_infill(const HttpRequest& req);
json native_result(const OaiRequest& r, const Generation& g, const std::string& content);
HttpResponse handle_load(const HttpRequest& req);
HttpResponse handle_tokenize(const HttpRequest& req);
HttpResponse handle_detokenize(const HttpRequest& req);
@@ -213,7 +225,8 @@ private:
HttpResponse handle_stats(const HttpRequest& req);
HttpResponse handle_graph(const HttpRequest& req);
HttpResponse error_response(const ApiError& e, const std::string& peer);
HttpResponse error_response(const ApiError& e, const std::string& peer,
ApiShape shape = ApiShape::OpenAI);
/* THE REQUEST LOG. One line when a request is admitted and one from record() when it ends,
* at the info level, so `docker logs` answers "who asked what, how long, how did it end"
* without the engine's own levels. The debug level adds the last user message's opening. */
+32 -4
View File
@@ -1,5 +1,6 @@
#include "sink.h"
#include <algorithm>
#include <chrono>
#include <thread>
@@ -57,7 +58,13 @@ void Sink::notify() {
cv_.notify_one();
}
bool Sink::push(int32_t token, float logprob) {
void Sink::enable_logprobs(int n) {
alt_w_ = n > 0 ? n : 0;
alts_.assign(ring_.size() * (size_t)alt_w_, SinkAlt{});
alt_n_.assign(ring_.size(), 0);
}
bool Sink::push(int32_t token, const TokenLogprobs* lp) {
const uint64_t h = head_.load(std::memory_order_relaxed);
const uint64_t t = tail_.load(std::memory_order_acquire);
if (h - t > mask_) {
@@ -66,7 +73,14 @@ bool Sink::push(int32_t token, float logprob) {
fail(RAD_E_FULL);
return false;
}
ring_[h & mask_] = SinkToken{token, logprob};
const size_t slot = (size_t)(h & mask_);
ring_[slot] = SinkToken{ token, lp ? lp->logprob : 0.0f, 0 };
if (alt_w_ > 0) {
const int n = lp ? std::min(lp->n_top, alt_w_) : 0;
for (int j = 0; j < n; ++j)
alts_[slot * (size_t)alt_w_ + (size_t)j] = SinkAlt{ lp->top_id[j], lp->top_lp[j] };
alt_n_[slot] = n;
}
head_.store(h + 1, std::memory_order_release);
const int64_t t_now = now_ns() - t_start_ns_;
@@ -100,6 +114,13 @@ void Sink::set_prompt_stats(int32_t n_prompt, int32_t n_cached) {
n_cached_.store(n_cached, std::memory_order_release);
}
void Sink::set_prompt_progress(int32_t processed, int32_t total, int32_t cached) {
prog_total_.store(total, std::memory_order_release);
prog_cached_.store(cached, std::memory_order_release);
prog_done_.store(processed, std::memory_order_release);
notify();
}
void Sink::mark_admitted() {
if (t_admit_.load(std::memory_order_relaxed) < 0)
t_admit_.store(now_ns() - t_start_ns_, std::memory_order_release);
@@ -112,12 +133,19 @@ void Sink::add_drafts(int32_t n, int32_t accepted) {
std::memory_order_release);
}
size_t Sink::read(SinkToken* out, size_t max) {
size_t Sink::read(SinkToken* out, size_t max, SinkAlt* alts) {
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_];
for (size_t i = 0; i < n; ++i) {
const size_t slot = (size_t)((t + i) & mask_);
out[i] = ring_[slot];
if (!alts || alt_w_ <= 0) continue;
out[i].n_alt = alt_n_[slot];
for (int j = 0; j < alt_n_[slot]; ++j)
alts[i * (size_t)alt_w_ + (size_t)j] = alts_[slot * (size_t)alt_w_ + (size_t)j];
}
if (n) tail_.store(t + n, std::memory_order_release);
return n;
}
+38 -13
View File
@@ -49,7 +49,14 @@ 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 */
float logprob = 0.0f; /* the token's logprob; 0 unless the request asked for logprobs */
int32_t n_alt = 0; /* how many alternatives read() wrote for this token */
};
/* One of a token's most likely alternatives, with its logprob. */
struct SinkAlt {
int32_t id = 0;
float logprob = 0.0f;
};
class Sink {
@@ -73,8 +80,9 @@ public:
/* ------------------------------------------------------------------ producer: scheduler */
/* Returns false only on overflow, which also marks the request failed. */
bool push(int32_t token, float logprob = 0.0f);
/* Returns false only on overflow, which also marks the request failed. `lp` is the token's
* logprobs when the request asked for them (enable_logprobs), and null otherwise. */
bool push(int32_t token, const TokenLogprobs* lp = nullptr);
/* Terminal. Idempotent -- the first call wins, so a cancel racing a natural stop does not
* produce two finish reasons. */
@@ -97,11 +105,20 @@ public:
/* A verify step's speculation for this request: `n` tokens proposed, `accepted` of them
* taken. Summed over the request, the per-request half of /metrics' draft counters. */
void add_drafts(int32_t n, int32_t accepted);
/* HOW MUCH OF THE PROMPT IS IN THE CACHE: at admission (what the prefix cache supplied) and
* after every prefill step, of `total`, of which `cached` came from the prefix cache. What
* llama-server streams as `prompt_progress` when a request asks for it; wakes the consumer. */
void set_prompt_progress(int32_t processed, int32_t total, int32_t cached);
int32_t progress_processed() const { return prog_done_.load(std::memory_order_acquire); }
int32_t progress_total() const { return prog_total_.load(std::memory_order_acquire); }
int32_t progress_cached() const { return prog_cached_.load(std::memory_order_acquire); }
/* ------------------------------------------------------------------ consumer: HTTP */
/* Copies up to `max` tokens out. Returns how many. Never blocks. */
size_t read(SinkToken* out, size_t max);
/* Copies up to `max` tokens out. Returns how many. Never blocks. With `alts`, each token's
* alternatives too: token i's n_alt of them at alts[i * alt_width()], which needs room for
* max * alt_width(). */
size_t read(SinkToken* out, size_t max, SinkAlt* alts = nullptr);
/* Sleeps until there is something to read, the request is terminal, or `timeout_ms` elapses.
* Returns true if there is now something to look at. */
@@ -133,11 +150,11 @@ public:
int32_t n_prompt() const { return n_prompt_.load(std::memory_order_acquire); }
int32_t n_cached() const { return n_cached_.load(std::memory_order_acquire); }
/* The 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 ALTERNATIVES' RING, sized for `n` a token, beside the token ring: allocated only for a
* request that asks for them, because at RAD_MAX_LOGPROBS it is twenty times the token ring.
* Called by the consumer before the request is handed to the scheduler. */
void enable_logprobs(int n);
int alt_width() const { return alt_w_; }
/* The engine's request id, so a dropped connection can reach IScheduler::cancel. */
uint64_t id = 0;
@@ -174,7 +191,12 @@ private:
std::atomic<int32_t> n_prompt_{0};
std::atomic<int32_t> n_cached_{0};
bool has_logprobs_ = false;
std::atomic<int32_t> prog_done_{-1};
std::atomic<int32_t> prog_total_{0};
std::atomic<int32_t> prog_cached_{0};
std::vector<SinkAlt> alts_; /* [capacity * alt_w_], parallel to ring_ */
std::vector<int32_t> alt_n_; /* [capacity] */
int alt_w_ = 0;
std::vector<float> embd_;
std::mutex m_;
@@ -183,8 +205,8 @@ private:
/* 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 bool sink_push(void* s, int32_t token, const TokenLogprobs* lp = nullptr) {
return s ? static_cast<Sink*>(s)->push(token, lp) : true;
}
inline void sink_finish(void* s, Finish f) {
if (s) static_cast<Sink*>(s)->finish(f);
@@ -201,6 +223,9 @@ inline void sink_prompt_stats(void* s, int32_t n_prompt, int32_t n_cached) {
inline void sink_admitted(void* s) {
if (s) static_cast<Sink*>(s)->mark_admitted();
}
inline void sink_prompt_progress(void* s, int32_t processed, int32_t total, int32_t cached) {
if (s) static_cast<Sink*>(s)->set_prompt_progress(processed, total, cached);
}
inline void sink_drafts(void* s, int32_t n, int32_t accepted) {
if (s) static_cast<Sink*>(s)->add_drafts(n, accepted);
}
+5
View File
@@ -193,6 +193,11 @@ int ChatTemplate::apply(const ojson& messages, const ojson& tools, const ChatOpt
in.add_bos = opt.add_bos || impl_->add_bos;
in.add_eos = opt.add_eos || impl_->add_eos;
in.reasoning_format = common_reasoning_format_from_name(opt.reasoning_format);
in.continue_final_message =
opt.continue_final.empty() ? COMMON_CHAT_CONTINUATION_NONE
: opt.continue_final == "content" ? COMMON_CHAT_CONTINUATION_CONTENT
: opt.continue_final == "reasoning_content" ? COMMON_CHAT_CONTINUATION_REASONING
: COMMON_CHAT_CONTINUATION_AUTO;
common_chat_params p;
try {
+1
View File
@@ -54,6 +54,7 @@ struct ChatOptions {
bool parallel_tool_calls = false;
std::string tool_choice = "auto"; /* auto | none | required */
std::string reasoning_format = "auto"; /* none | auto | deepseek | deepseek-legacy */
std::string continue_final; /* "" | auto | content | reasoning_content */
std::string grammar; /* a user-supplied GBNF, or empty */
std::string json_schema; /* response_format json_schema, or empty */
bool add_bos = false;
+45 -26
View File
@@ -1534,6 +1534,35 @@ size_t Detokenizer::safe_prefix() const {
* sequence, which is what browsers and every other inference server do. The alternative -- one
* U+FFFD per bad byte -- turns a truncated three-byte character into three replacement
* characters, which reads as three lost characters rather than the one that was actually lost. */
/* The well-formed sequence at s[i], a lead byte: its length, or 0 with `*part` the length of the
* ill-formed one's maximal subpart (never zero). The SECOND byte's range is what rejects overlong
* encodings, surrogates and anything past U+10FFFF without decoding. */
static inline size_t utf8_seq(std::string_view s, size_t i, size_t* part) {
const unsigned char c = (unsigned char)s[i];
size_t len; unsigned char lo, hi;
if (c >= 0xC2 && c <= 0xDF) { len = 2; lo = 0x80; hi = 0xBF; }
else if (c == 0xE0) { len = 3; lo = 0xA0; hi = 0xBF; }
else if (c >= 0xE1 && c <= 0xEC) { len = 3; lo = 0x80; hi = 0xBF; }
else if (c == 0xED) { len = 3; lo = 0x80; hi = 0x9F; } /* no surrogates */
else if (c >= 0xEE && c <= 0xEF) { len = 3; lo = 0x80; hi = 0xBF; }
else if (c == 0xF0) { len = 4; lo = 0x90; hi = 0xBF; }
else if (c >= 0xF1 && c <= 0xF3) { len = 4; lo = 0x80; hi = 0xBF; }
else if (c == 0xF4) { len = 4; lo = 0x80; hi = 0x8F; } /* <= U+10FFFF */
else { len = 0; lo = 0; hi = 0; } /* 0x80-0xC1, 0xF5+ */
size_t k = 1;
if (len) {
for (; k < len && i + k < s.size(); ++k) {
const unsigned char d = (unsigned char)s[i + k];
const unsigned char l = (k == 1) ? lo : 0x80, h = (k == 1) ? hi : 0xBF;
if (d < l || d > h) break;
}
}
if (len && k == len) return len;
*part = k;
return 0;
}
std::string utf8_sanitize(std::string_view s) {
/* The common case is a string that is already valid, and it must not be copied byte by byte. */
std::string out;
@@ -1542,41 +1571,31 @@ std::string utf8_sanitize(std::string_view s) {
auto flush_good = [&] { out.append(s.data() + good, i - good); good = i; };
while (i < n) {
const unsigned char c = (unsigned char)s[i];
if (c < 0x80) { ++i; continue; }
/* Length, and the range the SECOND byte is restricted to. The second-byte bounds are what
* reject overlong encodings, surrogates and anything past U+10FFFF without decoding. */
size_t len; unsigned char lo, hi;
if (c >= 0xC2 && c <= 0xDF) { len = 2; lo = 0x80; hi = 0xBF; }
else if (c == 0xE0) { len = 3; lo = 0xA0; hi = 0xBF; }
else if (c >= 0xE1 && c <= 0xEC) { len = 3; lo = 0x80; hi = 0xBF; }
else if (c == 0xED) { len = 3; lo = 0x80; hi = 0x9F; } /* no surrogates */
else if (c >= 0xEE && c <= 0xEF) { len = 3; lo = 0x80; hi = 0xBF; }
else if (c == 0xF0) { len = 4; lo = 0x90; hi = 0xBF; }
else if (c >= 0xF1 && c <= 0xF3) { len = 4; lo = 0x80; hi = 0xBF; }
else if (c == 0xF4) { len = 4; lo = 0x80; hi = 0x8F; } /* <= U+10FFFF */
else { len = 0; lo = 0; hi = 0; } /* 0x80-0xC1, 0xF5+ */
size_t k = 1;
if (len) {
for (; k < len && i + k < n; ++k) {
const unsigned char d = (unsigned char)s[i + k];
const unsigned char l = (k == 1) ? lo : 0x80, h = (k == 1) ? hi : 0xBF;
if (d < l || d > h) break;
}
}
if (len && k == len) { i += len; continue; }
if ((unsigned char)s[i] < 0x80) { ++i; continue; }
size_t part = 0;
const size_t len = utf8_seq(s, i, &part);
if (len) { i += len; continue; }
flush_good();
out += "\xEF\xBF\xBD"; /* U+FFFD */
i += k; /* the maximal subpart, never zero */
i += part; /* the maximal subpart, never zero */
good = i;
}
flush_good();
return out;
}
size_t utf8_valid_prefix(std::string_view s) {
size_t i = 0, part = 0;
while (i < s.size()) {
if ((unsigned char)s[i] < 0x80) { ++i; continue; }
const size_t len = utf8_seq(s, i, &part);
if (!len) break;
i += len;
}
return i;
}
std::string Detokenizer::push(int32_t token) {
if (!v_ || !v_->ready() || stopped_) return {};
+3
View File
@@ -213,6 +213,9 @@ private:
* would hide that the model produced something undecodable. Well-formed input is returned byte for
* byte, so this is a no-op on every normal completion. */
std::string utf8_sanitize(std::string_view s);
/* How much of `s` is well-formed UTF-8 from its start, by the same rules: what a JSON string can
* carry of a byte-level token that ends inside a character. */
size_t utf8_valid_prefix(std::string_view s);
/* Byte-level BPE emits partial UTF-8 sequences -- a single token can be one byte of a