diff --git a/CMakeLists.txt b/CMakeLists.txt index e2c98f25..0d4b60dd 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2,7 +2,7 @@ cmake_minimum_required(VERSION 3.21) # VERSION is what /version reports and what a client checks compatibility against. It is NOT the # ABI version -- that lives in abi/rad_abi.h and is read out of the header below, because # a plugin contract and a server release do not move together. -project(radiance VERSION 1.2.4 LANGUAGES C CXX) +project(radiance VERSION 1.3.0 LANGUAGES C CXX) set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD_REQUIRED ON) @@ -219,6 +219,14 @@ if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/data/kernels_moe.rkb) install(FILES ${CMAKE_CURRENT_SOURCE_DIR}/data/kernels_moe.rkb DESTINATION ${CMAKE_INSTALL_DATADIR}/radiance) endif() +# THE DOWNLOADER `radiance --model ` RUNS (core/hf_model.cpp). The engine finds it at +# /../libexec/radiance/, so the build puts a copy at the same place under the build tree and +# a binary run from either tree finds it without a path to configure. +configure_file(${CMAKE_CURRENT_SOURCE_DIR}/scripts/hfget.sh + ${CMAKE_BINARY_DIR}/libexec/radiance/hfget.sh COPYONLY) +install(PROGRAMS ${CMAKE_CURRENT_SOURCE_DIR}/scripts/hfget.sh + DESTINATION ${CMAKE_INSTALL_LIBEXECDIR}/radiance) + # rad_add_plugin() and rad_hipify() live in cmake/RadAddPlugin.cmake because the installed package # config includes that same file: a third party building a plugin from their own repository needs # the function, and a second copy of it in the package config would drift from this one. The file diff --git a/NOTICE b/NOTICE index b2776281..50a4c8b1 100644 --- a/NOTICE +++ b/NOTICE @@ -12,8 +12,10 @@ and row groups, the fused router launch, the adaptive draft window, the MoE pref sorted operand's decode kernel), mechkbfan (the token embedding in the pinned host pool), Code000 (the n-gram gather on the card and the MTP head's history-pass skip), baKon (three-rank tensor parallelism, serving any world size from the shipped container, the request log, an uneven world's -per-rank KV and weights split, and --rope-scaling) and hazyumps (static YaRN for the Qwen rotary -paths). +per-rank KV and weights split, --rope-scaling, the model entry's context length, root and +capabilities, /props, the three-rank two-shot all-reduce and tiered-int8 wire, the diagnosis of +the three-rank lossy-wire crash, and cardclock.py), hazyumps (static YaRN for the Qwen rotary +paths) and redxherring (--model taking a Hugging Face repo id). This product includes software from the following projects, each under the MIT License. The license text is in the file named beside each. diff --git a/README.md b/README.md index 9f21a500..99d3a69f 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,8 @@ # radiance -An LLM inference server for AMD GPUs, in C++ and HIP, with an OpenAI-compatible HTTP API. Model -architectures, kernel libraries and quantisers are `.so` plugins; the ones in this tree are built +An LLM inference server for AMD GPUs, in C++ and HIP. Its HTTP API speaks OpenAI's chat, completions +and Responses APIs, Anthropic's Messages API and llama-server's native one, so their clients and +SDKs work unchanged. Model architectures, kernel libraries and quantisers are `.so` plugins; the ones in this tree are built and loaded the same way a third party's are ([`docs/PLUGIN.md`](docs/PLUGIN.md)). The bundled device kernels (`libr4d`) target **AMD RDNA4** (`gfx1200`, `gfx1201`). The serve flags @@ -76,8 +77,14 @@ cmake --install build --prefix /opt/radiance # optional; bin/, include/, share/r ```sh export RADIANCE_HOME=$PWD/build/radiance_home # the plugins; an installed prefix finds its own build/bin/radiance --model /srv/models/rad/minicpm5-2b-fp8.rad --port 8000 +build/bin/radiance --model StillDeadcode/minicpm5-2b-fp8 --port 8000 ``` +`--model` also takes a Hugging Face repo id, as vLLM does. The server fetches the repo with `curl` +and `jq` into `~/.cache/radiance/hf` (`--download-dir` puts it elsewhere), serves the container it +holds, and checks it for changes at every start; a start that cannot reach the hub serves the copy +it has. The Docker image has neither tool, so with Docker download the file as shown above. + These are the flags each model is served with. They match its compose file, minus Flash-Next's prefix-cache tiers: @@ -101,9 +108,9 @@ of it, on decode and verify steps; a prefill chunk runs the unfused chain. That all-reduce is one-shot up to 1 MiB a message and two-shot above that, which sends half the bytes on a prefill chunk; both produce the same bits. The row above runs exact. `--tp-wire wht6` at three and four ranks selects a different lossy wire, tiered int8 over the -two-shot, above `--tp-wire-min-kb`. Eight ranks have no lossy wire, so `--tp 8 --tp-wire wht6` stops at -startup naming the all-reduce. Four ranks is a capacity configuration; its per-step rate against -`--tp 2` on the same cards has not been measured. The +two-shot, above `--tp-wire-min-kb`. Eight ranks have no lossy wire, so `--tp 8 --tp-wire wht6` +stops at startup naming the all-reduce. Four ranks is a capacity configuration; its per-step rate +against `--tp 2` on the same cards has not been measured. The tiering flags are the tp2 recipe carried over. Above two ranks each rank still owns a **slice of every expert's width** — each parity's 128-column blocks are cut contiguously over the ranks and the odd block alternates with the parity, so every rank's share is whole blocks and every block has @@ -114,7 +121,7 @@ above pins 4 × 12 GiB = 48 GiB, and the amdgpu driver caps pinned memory at `tt of RAM by default: that row needs 96 GiB of RAM or a raised limit ([`docs/GUIDE.md`](docs/GUIDE.md) §7). -Add `--api-key KEY` to require `Authorization: Bearer KEY`. Add `--debug-graph` to print every op +Add `--api-key KEY` to require `Authorization: Bearer KEY` (or `X-Api-Key: KEY`). Add `--debug-graph` to print every op and the kernel it resolved to, then exit without serving. Then: ```sh diff --git a/abi/rad_abi.h b/abi/rad_abi.h index 3906fea5..44f87947 100644 --- a/abi/rad_abi.h +++ b/abi/rad_abi.h @@ -602,7 +602,8 @@ typedef int (*RadKernelConcurrentFn)(int i); * other, whatever it is called: * - the loader ranks it below every unnamed kernel library, because a reference matches every * op it declares and would otherwise answer for them ahead of the library serving the card - * (naming it in --kernels still puts it where it is named); + * (naming it in --kernels still puts it where it is named, and a --kernels list that does + * not name it leaves it out); * - the engine refuses to serve a model with an op only a reference library implements, unless * told to with --debug-accept-reference-kernels; * - rad-kbench checks every other library against it. diff --git a/abi/rad_sample.h b/abi/rad_sample.h index cab52fde..34d69ce4 100644 --- a/abi/rad_sample.h +++ b/abi/rad_sample.h @@ -44,7 +44,8 @@ enum { RAD_SP_PENALTY = 1 << 1, /* any of rep / freq / pres is non-identity */ RAD_SP_MASK = 1 << 2, /* a grammar is constraining this sequence this step */ RAD_SP_XTC = 1 << 3, - RAD_SP_DRY = 1 << 4 + RAD_SP_DRY = 1 << 4, + RAD_SP_LOGPROBS = 1 << 5 /* `sample_logprobs` summarises this row's raw logits */ }; /* One row per sampled position. Laid out so the 8-byte fields are aligned and the struct has no diff --git a/arch/qwen35_fp8/qwen35_fp8.cpp b/arch/qwen35_fp8/qwen35_fp8.cpp index 54b0aed4..4af86d8b 100644 --- a/arch/qwen35_fp8/qwen35_fp8.cpp +++ b/arch/qwen35_fp8/qwen35_fp8.cpp @@ -689,7 +689,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c * the 16 attention layers pay it, because the 48 delta-net layers carry fixed-size state * instead. At eight sequences of 16k that is 4.3 GB of read traffic a step, which is most of * what depth costs at that concurrency, and halving the width halves it. It also halves what a - * sequence costs in --vram-kv-mib, which is context and batch size as well as time. + * sequence costs in the KV pool, which is context and batch size as well as time. * * IT IS OFF BY DEFAULT ON A QUALITY ARGUMENT, not as a precaution. Greedy continuations from a * long prompt agree between bf16 and fp8 for the first few hundred tokens and then diverge, diff --git a/core/build/rad_builder.cpp b/core/build/rad_builder.cpp index aa87a95e..09c76aca 100644 --- a/core/build/rad_builder.cpp +++ b/core/build/rad_builder.cpp @@ -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 #include @@ -45,6 +46,26 @@ std::string Program::Miss::line() const { why.c_str()); } +std::vector 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> no_host; + for (const Miss& m : misses) + if (m.domain == RAD_DOMAIN_HOST) no_host.emplace(m.index, m.span); + std::vector 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> 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. */ diff --git a/core/config.cpp b/core/config.cpp index 252c4a53..184a640f 100644 --- a/core/config.cpp +++ b/core/config.cpp @@ -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; diff --git a/core/device/aql.cpp b/core/device/aql.cpp index 47cc1c61..7a54c4fd 100644 --- a/core/device/aql.cpp +++ b/core/device/aql.cpp @@ -57,6 +57,7 @@ #include #include #include +#include #include #include #include @@ -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 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(); diff --git a/core/device/device.h b/core/device/device.h index 7132ac11..136d3130 100644 --- a/core/device/device.h +++ b/core/device/device.h @@ -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 */ diff --git a/core/device/dispatch.cpp b/core/device/dispatch.cpp index 506b452a..01be8ff3 100644 --- a/core/device/dispatch.cpp +++ b/core/device/dispatch.cpp @@ -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; } diff --git a/core/engine.cpp b/core/engine.cpp index 67293bb1..3ba2831d 100644 --- a/core/engine.cpp +++ b/core/engine.cpp @@ -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; diff --git a/core/engine.h b/core/engine.h index 2395284b..ea820186 100644 --- a/core/engine.h +++ b/core/engine.h @@ -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& facts, - const std::vector& emb_bytes, - const std::vector& floor_emb_ram, int64_t kv_floor, + const std::vector& 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 token; /* [n_seq] */ std::vector accepted; /* [n_seq] */ std::vector 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 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. */ diff --git a/core/engine_bringup.cpp b/core/engine_bringup.cpp index d8ae745c..d1bd2222 100644 --- a/core/engine_bringup.cpp +++ b/core/engine_bringup.cpp @@ -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 device; /* one line each; fatal at issue */ + std::vector 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 host_ops; /* in first-seen order */ std::map 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> no_host; + const std::vector holes = p.device_holes(host_backend); + std::set> 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 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& facts, - const std::vector& emb_bytes, - const std::vector& floor_emb_ram, int64_t kv_floor, + const std::vector& 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& 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& 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& 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 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 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(room, 0)); - floor_emb_ram[i] = expert_vram_floor(wfs[i], std::max(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> 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; } diff --git a/core/engine_probe.cpp b/core/engine_probe.cpp index 9d906e0a..4252c038 100644 --- a/core/engine_probe.cpp +++ b/core/engine_probe.cpp @@ -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, diff --git a/core/format/checkpoint.cpp b/core/format/checkpoint.cpp index 101143e3..f53d5fae 100644 --- a/core/format/checkpoint.cpp +++ b/core/format/checkpoint.cpp @@ -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* owner) { shards_.push_back(std::make_unique()); 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* out) { - std::unordered_map map; - const int s = st_load_index(index, &map); + std::vector* out, std::unordered_map* 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 shards; + std::unordered_map 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 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 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; } diff --git a/core/format/checkpoint.h b/core/format/checkpoint.h index 3226b9fd..1b5cf248 100644 --- a/core/format/checkpoint.h +++ b/core/format/checkpoint.h @@ -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* 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> shards_; std::vector tensors_; std::unordered_map index_; + std::unordered_map index_shard_; /* name -> shards_ position */ std::deque sliced_; /* views; a deque never moves what it holds */ int64_t fp8_br_ = 128, fp8_bc_ = 128; Import import_ = Import::None; diff --git a/core/hf_model.cpp b/core/hf_model.cpp index a7780b23..d7f6f787 100644 --- a/core/hf_model.cpp +++ b/core/hf_model.cpp @@ -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 #include -#include +#include #include #include -#include #include +#include +#include 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 /../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; +/* /../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(argv)); - perror("execvp hfget.sh"); + const char* argv[] = { "sh", script.c_str(), repo.c_str(), dest.c_str(), nullptr }; + execv("/bin/sh", const_cast(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 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 + "/"; + 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; } diff --git a/core/hf_model.h b/core/hf_model.h new file mode 100644 index 00000000..d76b75ea --- /dev/null +++ b/core/hf_model.h @@ -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 + +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 */ diff --git a/core/main.cpp b/core/main.cpp index 7add73e8..240d512e 100644 --- a/core/main.cpp +++ b/core/main.cpp @@ -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)); diff --git a/core/mem/kv.cpp b/core/mem/kv.cpp index 95232245..0d78e1ea 100644 --- a/core/mem/kv.cpp +++ b/core/mem/kv.cpp @@ -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; diff --git a/core/mem/kv.h b/core/mem/kv.h index 360a1016..d8869d67 100644 --- a/core/mem/kv.h +++ b/core/mem/kv.h @@ -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& 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& groups, const Config& cfg); int64_t ceiling(int64_t ctx) const; diff --git a/core/mem/kvtier.cpp b/core/mem/kvtier.cpp index f59141e2..4a77ae79 100644 --- a/core/mem/kvtier.cpp +++ b/core/mem/kvtier.cpp @@ -988,7 +988,7 @@ static bool chain_extends(const std::vector& shorter, } void IdleTiers::note_session(uint64_t id, const std::vector& 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& 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& 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& 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& 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& 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::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)); diff --git a/core/mem/kvtier.h b/core/mem/kvtier.h index b5acbbb1..24add901 100644 --- a/core/mem/kvtier.h +++ b/core/mem/kvtier.h @@ -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& 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 chain; + std::string label; }; /* Erase one row and its root index entry together. */ diff --git a/core/mem/pools.cpp b/core/mem/pools.cpp index b28b1d7a..9be5cb2a 100644 --- a/core/mem/pools.cpp +++ b/core/mem/pools.cpp @@ -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 diff --git a/core/mem/prefix.cpp b/core/mem/prefix.cpp index 29e9283a..a2a9c07e 100644 --- a/core/mem/prefix.cpp +++ b/core/mem/prefix.cpp @@ -342,7 +342,7 @@ int PrefixCache::insert(uint64_t session, const std::vector& tokens, const std::vector& mm, const std::vector>& 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 diff --git a/core/mem/prefix.h b/core/mem/prefix.h index 5f00fb72..b1b28275 100644 --- a/core/mem/prefix.h +++ b/core/mem/prefix.h @@ -206,7 +206,8 @@ public: const std::vector& tokens, const std::vector& mm, const std::vector>& 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 diff --git a/core/mem/vram_budget.cpp b/core/mem/vram_budget.cpp index 33726ee0..7a405221 100644 --- a/core/mem/vram_budget.cpp +++ b/core/mem/vram_budget.cpp @@ -82,11 +82,21 @@ static int resolve(Config& cfg, const std::vector& 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(b.statics + b.expert_ceiling, kMiB); + b.kv = std::max(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& per_rank, VramBudg * plugin's init has run and its code object is resident. */ b.already_held = std::max(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& 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& 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& per_rank, VramBudg b.kv = kv; b.weights = b.statics + exp; b.unusable = std::max(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(b.weights, kMiB); /* ---- THE PREFILL STAGING REGION, out of the expert share --------------------------------- * @@ -227,12 +210,12 @@ static int resolve(Config& cfg, const std::vector& 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& 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& 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(b.kv - w_over, 0)) : to_mib(b.kv); + cfg.vram_kv_mib = to_mib(std::max(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& 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& 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; diff --git a/core/mem/vram_budget.h b/core/mem/vram_budget.h index f5c33805..3673c53c 100644 --- a/core/mem/vram_budget.h +++ b/core/mem/vram_budget.h @@ -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 */ }; diff --git a/core/mm/media.cpp b/core/mm/media.cpp index c0d39975..0a16bc0c 100644 --- a/core/mm/media.cpp +++ b/core/mm/media.cpp @@ -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; } diff --git a/core/place/mover.cpp b/core/place/mover.cpp index f29c799f..2de52953 100644 --- a/core/place/mover.cpp +++ b/core/place/mover.cpp @@ -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; diff --git a/core/place/mover.h b/core/place/mover.h index 59e104f9..0c28ba3b 100644 --- a/core/place/mover.h +++ b/core/place/mover.h @@ -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 diff --git a/core/place/planner.cpp b/core/place/planner.cpp index ded8ae94..e7a413db 100644 --- a/core/place/planner.cpp +++ b/core/place/planner.cpp @@ -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, size_t> by_group; std::vector 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 layer_experts; std::set 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; } diff --git a/core/place/planner.h b/core/place/planner.h index ade2fe35..899f9cf3 100644 --- a/core/place/planner.h +++ b/core/place/planner.h @@ -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 diff --git a/core/plugin/loader.cpp b/core/plugin/loader.cpp index 1762659b..27c58866 100644 --- a/core/plugin/loader.cpp +++ b/core/plugin/loader.cpp @@ -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> 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& 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 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 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 idx(staged.size()); for (size_t i = 0; i < idx.size(); ++i) idx[i] = i; diff --git a/core/plugin/registry.h b/core/plugin/registry.h index 9a2af22c..06d07ae4 100644 --- a/core/plugin/registry.h +++ b/core/plugin/registry.h @@ -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_; diff --git a/core/rad_core.h b/core/rad_core.h index 4b4fba76..219cfec9 100644 --- a/core/rad_core.h +++ b/core/rad_core.h @@ -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 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 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 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 */ } diff --git a/core/sample/host_ref.cpp b/core/sample/host_ref.cpp index ebaaa378..72e9f9f7 100644 --- a/core/sample/host_ref.cpp +++ b/core/sample/host_ref.cpp @@ -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 diff --git a/core/sample/sampler.cpp b/core/sample/sampler.cpp index 98e33c7f..1432bc21 100644 --- a/core/sample/sampler.cpp +++ b/core/sample/sampler.cpp @@ -6,6 +6,7 @@ #include #include +#include #include 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& 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& 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& 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 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; } diff --git a/core/sample/sampler.h b/core/sample/sampler.h index 5264fadf..07d02924 100644 --- a/core/sample/sampler.h +++ b/core/sample/sampler.h @@ -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 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 hist; /* the staged history row, [0, hist_len) */ + const DryBreakers* dry = nullptr; /* lives in seqs_ for the request's lifetime */ + }; + std::vector 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 */ diff --git a/core/sched/mem_iface.h b/core/sched/mem_iface.h index 142fd617..8e77fb40 100644 --- a/core/sched/mem_iface.h +++ b/core/sched/mem_iface.h @@ -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. */ diff --git a/core/sched/scheduler.cpp b/core/sched/scheduler.cpp index e49c3531..59e96598 100644 --- a/core/sched/scheduler.cpp +++ b/core/sched/scheduler.cpp @@ -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. */ diff --git a/core/sched/scheduler.h b/core/sched/scheduler.h index 087c93e6..1c1a6454 100644 --- a/core/sched/scheduler.h +++ b/core/sched/scheduler.h @@ -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, diff --git a/core/server/adapters.h b/core/server/adapters.h index 96bd00ac..bc6bcb0a 100644 --- a/core/server/adapters.h +++ b/core/server/adapters.h @@ -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 detokenizer( const std::vector& 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; diff --git a/core/server/admin.cpp b/core/server/admin.cpp index f69fd1c6..4c54f00f 100644 --- a/core/server/admin.cpp +++ b/core/server/admin.cpp @@ -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 @@ -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 t = + deps_.tok->encode(v.get(), 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((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{ "\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)); } diff --git a/core/server/dashboard.cpp b/core/server/dashboard.cpp index 79abf0a9..cce072e3 100644 --- a/core/server/dashboard.cpp +++ b/core/server/dashboard.cpp @@ -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")); diff --git a/core/server/http.cpp b/core/server/http.cpp index 9bb1a8c1..8641965c 100644 --- a/core/server/http.cpp +++ b/core/server/http.cpp @@ -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()) diff --git a/core/server/iface.h b/core/server/iface.h index 1aae8d15..5d100858 100644 --- a/core/server/iface.h +++ b/core/server/iface.h @@ -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 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. */ diff --git a/core/server/oai.cpp b/core/server/oai.cpp index 5fd2196c..9277042e 100644 --- a/core/server/oai.cpp +++ b/core/server/oai.cpp @@ -163,6 +163,8 @@ std::string ApiError::dump() const { if (param.empty()) e["param"] = nullptr; else e["param"] = param; if (code.empty()) e["code"] = nullptr; else e["code"] = code; if (!supported.empty()) e["supported"] = supported; + if (n_prompt_tokens >= 0) e["n_prompt_tokens"] = n_prompt_tokens; + if (n_ctx >= 0) e["n_ctx"] = n_ctx; json o; o["error"] = e; return o.dump(); @@ -201,30 +203,46 @@ ApiError err_overloaded(const std::string& why) { /* ================================================================== key vetting * - * The three lists below are the whole policy. `kAccepted*` is what we read; `kInert` is the - * OpenAI metadata that genuinely does nothing anywhere and would break the official SDKs if it - * 400'd; `kRejected` is the set we know about and do not implement, each with the reason, so the - * error message tells a caller something they can act on rather than "unsupported". + * FOUR KINDS OF FIELD, and the lists below are the whole policy. + * + * `kAccepted*` is what this server reads and honours, in OpenAI's, vLLM's and llama.cpp's + * spellings alike (`repetition_penalty` and `repeat_penalty`, `max_tokens` and `n_predict`). + * + * `kInert` changes nothing about the answer: routing and bookkeeping labels (`user`, `metadata`, + * OpenRouter's `session_id`), and llama.cpp's knobs for its own speed and slot management + * (`cache_prompt`, `id_slot`, `speculative.*`, ...) -- this server caches prefixes and speculates + * on its own terms, and the output is the same either way. Accepted and ignored. + * + * `kGuarded` is what this server knows and does not implement, where honouring it WOULD change + * the answer: mirostat, top-n-sigma, dynamic temperature, a logit bias. llama.cpp-built clients + * send every one of them on every request at its "off" value, so each is accepted at that value + * and refused by name at any other -- a 200 still means every field that could change the answer + * was honoured, and a client that turned mirostat on learns that it was not. + * + * ANYTHING ELSE IS IGNORED, as llama.cpp and vLLM ignore it. A field this server has never heard + * of is a client's own extension far more often than a request it has misunderstood, and refusing + * it breaks the client for nothing (#47). The ignored names are logged at debug. */ namespace { -struct Rejected { const char* key; const char* why; }; - const char* kAcceptedCommon[] = { - "model", "stream", "stream_options", "n", "seed", "stop", "max_tokens", + "model", "stream", "stream_options", "n", "seed", "stop", "max_tokens", "n_predict", "temperature", "top_p", "top_k", "min_p", "typical_p", - "presence_penalty", "frequency_penalty", "repetition_penalty", "repeat_last_n", - "xtc_probability", "xtc_threshold", + "presence_penalty", "frequency_penalty", "repetition_penalty", "repeat_penalty", + "repeat_last_n", "xtc_probability", "xtc_threshold", "dry_multiplier", "dry_base", "dry_allowed_length", "dry_penalty_last_n", - "dry_sequence_breakers", - "grammar", "priority", "logprobs", "ignore_eos", + "dry_sequence_breakers", "samplers", + "grammar", "json_schema", "priority", "logprobs", "ignore_eos", + "timings_per_token", "return_progress", "session_id", "n_probs", }; const char* kAcceptedChat[] = { "messages", "tools", "tool_choice", "response_format", "top_logprobs", "parallel_tool_calls", "add_generation_prompt", "max_completion_tokens", "chat_template_kwargs", "reasoning_effort", "enable_thinking", "preserve_thinking", - "thinking_token_budget", "thinking_budget", + "thinking_token_budget", "thinking_budget", "thinking_budget_tokens", + "reasoning_budget_tokens", "reasoning_format", "continue_final_message", + "functions", "function_call", }; const char* kAcceptedCompletion[] = { "prompt", "echo" }; @@ -232,33 +250,71 @@ const char* kAcceptedCompletion[] = { "prompt", "echo" }; const char* kAcceptedEmbedding[] = { "model", "input", "messages", "encoding_format", "dimensions", "image_tokens", "prompt_name" }; -/* Inert by definition in the OpenAI schema: routing and bookkeeping labels the server is free to - * ignore. Named explicitly so that "we ignore it" is a decision in the source and not an - * accident of a missing branch. */ +/* Named explicitly so that "we ignore it" is a decision in the source and not an accident of a + * missing branch -- and so the debug line of ignored names lists only what nobody decided on. */ const char* kInert[] = { + /* OpenAI's and OpenRouter's bookkeeping */ "user", "metadata", "store", "service_tier", "safety_identifier", "prompt_cache_key", + "prediction", + /* llama.cpp's own speed, slot and transport knobs */ + "cache_prompt", "id_slot", "n_cache_reuse", "backend_sampling", "reasoning_control", + "t_max_prompt_ms", "n_keep", "n_discard", "sse_ping_interval", "verbose", "response_fields", + /* the parameters of a guarded sampler, which mean nothing while it is off */ + "mirostat_tau", "mirostat_eta", "dynatemp_exponent", +}; +/* llama.cpp's speculative-decoding knobs travel as dotted keys ("speculative.n_max"). */ +const char* kInertPrefixes[] = { "speculative." }; + +/* A field this server does not implement and the value at which it does nothing. */ +struct Guarded { + const char* key; + bool (*neutral)(const json& v); + const char* off; /* how a client turns it off, for the refusal */ + const char* why; /* why it is not served */ }; -const Rejected kRejected[] = { - { "logit_bias", - "SamplingParams has no per-token bias stage and the device sampler (spec 13) does not " - "implement one" }, - { "functions", "the deprecated functions API; send `tools` instead" }, - { "function_call", "the deprecated function_call API; send `tool_choice` instead" }, - { "best_of", "sampling n candidates and returning the best is not implemented" }, - { "suffix", "infilling is not implemented" }, - { "mirostat", "mirostat is not one of the device samplers (spec 13)" }, - { "mirostat_tau", "mirostat is not one of the device samplers (spec 13)" }, - { "mirostat_eta", "mirostat is not one of the device samplers (spec 13)" }, - { "top_n_sigma", "top-n-sigma is not one of the device samplers (spec 13)" }, - { "dynatemp_range", "dynamic temperature is not one of the device samplers (spec 13)" }, - { "dynatemp_exponent", "dynamic temperature is not one of the device samplers (spec 13)" }, - { "lora", "LoRA is explicitly out of scope (spec, Scope)" }, - { "modalities", "output modalities other than text are not implemented" }, - { "audio", "audio output is not implemented" }, - { "prediction", "predicted outputs are not implemented" }, - { "continue_final_message", "assistant prefill is not implemented" }, - { "cache_prompt", "prefix caching is a server-wide setting (spec 7.3), not per request" }, +bool is_zero(const json& v) { return v.is_null() || (v.is_number() && v.get() == 0.0); } +bool non_positive(const json& v) { return v.is_null() || (v.is_number() && v.get() <= 0.0); } +bool falsy(const json& v) { return v.is_null() || (v.is_boolean() && !v.get()); } +bool empty_value(const json& v) { + return v.is_null() || ((v.is_object() || v.is_array() || v.is_string()) && v.empty()); +} +bool at_most_one(const json& v) { return v.is_null() || (v.is_number() && v.get() <= 1.0); } +bool text_only(const json& v) { + if (v.is_null()) return true; + if (!v.is_array()) return false; + for (const json& m : v) if (!m.is_string() || m.get() != "text") return false; + return true; +} + +const Guarded kGuarded[] = { + { "logit_bias", empty_value, "an empty object", + "the device sampler (spec 13) has no per-token bias stage" }, + { "mirostat", is_zero, "0", "mirostat is not one of the device samplers (spec 13)" }, + { "top_n_sigma", non_positive, "-1", "top-n-sigma is not one of the device samplers (spec 13)" }, + { "dynatemp_range", non_positive, "0", + "dynamic temperature is not one of the device samplers (spec 13)" }, + { "min_keep", is_zero, "0", "the cut stages keep no minimum candidate count" }, + { "post_sampling_probs", falsy, "false", + "logprobs are the raw distribution's; the distribution after the sampler's stages is not " + "returned" }, + { "best_of", at_most_one, "1", "sampling several candidates and returning the best is not " + "implemented" }, + { "suffix", empty_value, "an empty string", "infilling through /v1/completions is not " + "implemented" }, + { "lora", empty_value, "an empty list", "LoRA is explicitly out of scope (spec, Scope)" }, + { "modalities", text_only, "[\"text\"]", "output modalities other than text are not " + "implemented" }, + { "audio", empty_value, "null", "audio output is not implemented" }, + { "n_indent", is_zero, "0", "indentation-limited infill is not implemented" }, + { "t_max_predict_ms", non_positive, "0", "a generation time limit is not implemented" }, + { "return_tokens", falsy, "false", "token ids are not returned beside the text" }, + { "grammar_lazy", falsy, "false", + "a caller's grammar applies from the first token; the lazy form is the chat format's own" }, + { "grammar_triggers", empty_value, "an empty list", + "a caller's grammar applies from the first token; the lazy form is the chat format's own" }, + { "preserved_tokens", empty_value, "an empty list", + "the chat format names the control tokens a reply keeps" }, }; bool in_list(const char* const* list, size_t n, const std::string& k) { @@ -267,10 +323,14 @@ bool in_list(const char* const* list, size_t n, const std::string& k) { } #define ARRN(a) (sizeof(a) / sizeof((a)[0])) -int vet_keys(const json& body, Endpoint ep, ApiError* err) { +int vet_keys(const json& body, Endpoint ep, ApiError* err, bool native = false) { + std::string ignored; for (auto it = body.begin(); it != body.end(); ++it) { const std::string& k = it.key(); if (in_list(kInert, ARRN(kInert), k)) continue; + bool prefixed = false; + for (const char* p : kInertPrefixes) prefixed = prefixed || k.rfind(p, 0) == 0; + if (prefixed) continue; if (ep == Endpoint::Embedding) { if (in_list(kAcceptedEmbedding, ARRN(kAcceptedEmbedding), k)) continue; } else { @@ -280,15 +340,21 @@ int vet_keys(const json& body, Endpoint ep, ApiError* err) { if (ep == Endpoint::Completion && in_list(kAcceptedCompletion, ARRN(kAcceptedCompletion), k)) continue; } - for (const auto& r : kRejected) { - if (k == r.key) { *err = err_unsupported(k, r.why); return RAD_E_UNSUPPORTED; } + /* llama-server's native completion returns the token ids, so the field is served there. */ + if (native && k == "return_tokens") continue; + bool guarded = false; + for (const Guarded& g : kGuarded) { + if (k != g.key) continue; + guarded = true; + if (!g.neutral(it.value())) { + *err = err_unsupported(k, std::string(g.why) + "; it is accepted only at " + + g.off + ", where it does nothing"); + return RAD_E_UNSUPPORTED; + } } - *err = err_unsupported( - k, "unrecognised parameter for this endpoint. A parameter the server does not " - "implement is refused rather than ignored, so that a request that returns 200 " - "means every field of it was honoured"); - return RAD_E_INVAL; + if (!guarded) ignored += (ignored.empty() ? "" : ", ") + k; } + if (!ignored.empty()) RAD_DEBUG("request fields ignored: %s", ignored.c_str()); return RAD_OK; } @@ -334,7 +400,77 @@ bool get_str(const json& b, const char* k, std::string* out, ApiError* err) { *out = it->get(); return true; } +/* A MEMBER OF A NESTED OBJECT -- a message, a content block, a tool -- read as a string: absent or + * null leaves `*out` as it was, any other type is refused, named by `param`. json::value() throws + * on a type it cannot convert, and a throw out of a handler is a 500 in the library's words. */ +bool member_str(const json& o, const char* k, const char* param, std::string* out, ApiError* err) { + auto it = o.find(k); + if (it == o.end() || it->is_null()) return true; + if (!it->is_string()) { *err = err_bad(param, "expected a string"); return false; } + *out = it->get(); + return true; +} +/* The same read where the type is checked later, by the validation the value goes through: here a + * member that is not a string reads as `def`. */ +std::string str_or(const json& o, const char* k, const std::string& def = std::string()) { + auto it = o.find(k); + return it != o.end() && it->is_string() ? it->get() : def; +} +/* A conversation's label as /sessions shows it: at most 128 bytes, cut where a character starts, + * because the label is serialised into JSON that refuses a string split inside one. */ +static std::string session_label_of(const std::string& s) { + constexpr size_t kMax = 128; + if (s.size() <= kMax) return s; + size_t cut = kMax; + while (cut > 0 && ((unsigned char)s[cut] & 0xC0) == 0x80) --cut; + return s.substr(0, cut); +} + +/* ONE FIELD, SEVERAL SPELLINGS: OpenAI's, vLLM's and llama.cpp's name for the same thing. Any of + * them may be sent; two that disagree are refused, because there is no order in which to read + * them that the caller could have meant. */ +bool get_num_any(const json& b, std::initializer_list keys, double* out, + ApiError* err) { + const char* named = nullptr; + double v = *out; + for (const char* k : keys) { + auto it = b.find(k); + if (it == b.end() || it->is_null()) continue; + double x = 0; + if (!get_num(b, k, &x, err)) return false; + if (named && x != v) { + *err = err_bad(k, std::string("disagrees with ") + named + ", which is the same field"); + return false; + } + v = x; + named = k; + } + *out = v; + return true; +} +bool get_int_any(const json& b, std::initializer_list keys, int64_t* out, + bool* present, ApiError* err) { + const char* named = nullptr; + int64_t v = *out; + for (const char* k : keys) { + auto it = b.find(k); + if (it == b.end() || it->is_null()) continue; + int64_t x = 0; + if (!get_int(b, k, &x, err)) return false; + if (named && x != v) { + *err = err_bad(k, std::string("disagrees with ") + named + ", which is the same field"); + return false; + } + v = x; + named = k; + } + *out = v; + if (present) *present = named != nullptr; + return true; +} + +} /* namespace */ /* The body of every generation endpoint: one JSON object, parsed into a bounded tree. */ int parse_request_object(const std::string& body, const OaiLimits& lim, json* b, ApiError* err) { @@ -360,8 +496,6 @@ int parse_request_object(const std::string& body, const OaiLimits& lim, json* b, return RAD_OK; } -} /* namespace */ - /* ================================================================== sampling params */ namespace { @@ -416,6 +550,141 @@ bool sampler_value_ok(const char* field, double v, std::string* why) { return true; } +/* ================================================================== the sampler order + * + * llama.cpp's `samplers`: which stages run and in what order, as names ("top_k", "temperature", + * with llama.cpp's aliases) or as one string of its letters ("kypmxt"). A stage the list leaves + * out does not run, whatever its own field says -- llama.cpp's meaning, and the reason a client + * sends the list. + * + * THE CHAIN HERE IS FIXED BUT FOR ONE THING (core/sample/sampler.h): penalties, DRY, top-k, then + * top-p, min-p, typical and XTC, with temperature either before the cuts (vLLM's order, the + * default) or after them (llama.cpp's). So a list is honoured when the stages it enables appear in + * that relative order with temperature at either end of the cuts, and refused by name otherwise. + * Only ENABLED stages are compared: a stage at its identity value is the same wherever it sits, + * which is what lets llama.cpp's default list -- typ_p before top_p -- through whenever typical + * is off. top-n-sigma is guarded at its off value (kGuarded), so it is free to appear anywhere. */ +static int apply_sampler_order(const json& b, SamplingParams* sp, ApiError* err) { + auto it = b.find("samplers"); + if (it == b.end() || it->is_null()) return RAD_OK; + + enum { PEN, DRY, TOPK, TOPP, MINP, TYP, XTC, TEMP, SIGMA, N_STAGE }; + static const char* const kName[N_STAGE] = { "penalties", "dry", "top_k", "top_p", "min_p", + "typ_p", "xtc", "temperature", "top_n_sigma" }; + auto by_name = [](std::string n) -> int { + std::replace(n.begin(), n.end(), '-', '_'); + if (n == "penalties") return PEN; + if (n == "dry") return DRY; + if (n == "top_k") return TOPK; + if (n == "top_p" || n == "nucleus") return TOPP; + if (n == "min_p") return MINP; + if (n == "typ_p" || n == "typ" || n == "typical_p" || n == "typical") return TYP; + if (n == "xtc") return XTC; + if (n == "temperature" || n == "temp") return TEMP; + if (n == "top_n_sigma") return SIGMA; + return -1; + }; + auto by_char = [](char c) -> int { + switch (c) { + case 'e': return PEN; case 'd': return DRY; case 'k': return TOPK; + case 'p': return TOPP; case 'm': return MINP; case 'y': return TYP; + case 'x': return XTC; case 't': return TEMP; case 's': return SIGMA; + default: return -1; + } + }; + std::vector list; + if (it->is_string()) { + for (char c : it->get()) { + const int st = by_char(c); + if (st < 0) { + *err = err_unsupported("samplers", std::string("'") + c + "' names no sampler this " + "server runs (infill and adaptive_p are not served)"); + return RAD_E_UNSUPPORTED; + } + list.push_back(st); + } + } else if (it->is_array()) { + for (const json& n : *it) { + if (!n.is_string()) { *err = err_bad("samplers", "expected sampler names"); return RAD_E_INVAL; } + const int st = by_name(n.get()); + if (st < 0) { + *err = err_unsupported("samplers", "\"" + n.get() + "\" names no " + "sampler this server runs (infill and adaptive_p are not " + "served)"); + return RAD_E_UNSUPPORTED; + } + list.push_back(st); + } + } else { + *err = err_bad("samplers", "expected an array of sampler names or a string of letters"); + return RAD_E_INVAL; + } + + auto listed = [&](int st) { return std::find(list.begin(), list.end(), st) != list.end(); }; + /* What the list leaves out is off. Greedy stays greedy: temperature 0 is the argmax in either + * engine whatever surrounds it. */ + if (!listed(PEN)) { sp->rep_penalty = 1.0f; sp->freq_penalty = 0.0f; sp->pres_penalty = 0.0f; } + if (!listed(DRY)) sp->dry_multiplier = 0.0f; + if (!listed(TOPK)) sp->top_k = 0; + if (!listed(TOPP)) sp->top_p = 1.0f; + if (!listed(MINP)) sp->min_p = 0.0f; + if (!listed(TYP)) sp->typical_p = 1.0f; + if (!listed(XTC)) sp->xtc_probability = 0.0f; + if (!listed(TEMP) && sp->temp > 0.0f) sp->temp = 1.0f; + + bool on[N_STAGE] = {}; + on[PEN] = sp->rep_penalty != 1.0f || sp->freq_penalty != 0.0f || sp->pres_penalty != 0.0f; + on[DRY] = sp->dry_multiplier > 0.0f; + on[TOPK] = sp->top_k > 0; + on[TOPP] = sp->top_p < 1.0f; + on[MINP] = sp->min_p > 0.0f; + on[TYP] = sp->typical_p < 1.0f; + on[XTC] = sp->xtc_probability > 0.0f; + on[TEMP] = sp->temp > 0.0f && sp->temp != 1.0f; + if (sp->temp <= 0.0f) return RAD_OK; /* greedy: no order to honour */ + + /* The enabled stages, first occurrence each, in the list's order. */ + std::vector seq; + for (int st : list) + if (on[st] && std::find(seq.begin(), seq.end(), st) == seq.end()) seq.push_back(st); + auto pos = [&](int st) { + return (int)(std::find(seq.begin(), seq.end(), st) - seq.begin()); + }; + auto refuse = [&](int a, int bst) { + *err = err_unsupported("samplers", std::string("\"") + kName[a] + "\" after \"" + + kName[bst] + "\" is an order this server's sampler chain cannot run " + "(penalties, dry, top_k, top_p, min_p, typ_p, xtc, with temperature " + "first or last)"); + return RAD_E_UNSUPPORTED; + }; + /* Everything but temperature in the chain's own relative order. */ + static const int kChain[] = { PEN, DRY, TOPK, TOPP, MINP, TYP, XTC }; + int last = -1, last_st = -1; + for (int st : kChain) { + if (!on[st]) continue; + const int p = pos(st); + if (p < last) return refuse(last_st, st); + last = p; + last_st = st; + } + if (!on[TEMP]) return RAD_OK; + /* Temperature: after the penalties, and before every enabled cut or after every one. top-k + * commutes with it -- a monotone rescale keeps the same k largest -- so it is not a cut here. */ + const int pt = pos(TEMP); + for (int st : { PEN, DRY }) + if (on[st] && pos(st) > pt) return refuse(st, TEMP); + bool before = false, after = false; + int first_cut = -1; + for (int st : { TOPP, MINP, TYP, XTC }) { + if (!on[st]) continue; + if (first_cut < 0) first_cut = st; + (pos(st) > pt ? before : after) = true; + } + if (before && after) return refuse(TEMP, first_cut); + sp->temp_last = after; + return RAD_OK; +} + static int parse_sampling(const json& b, const OaiLimits& lim, OaiRequest* r, ApiError* err) { double d; int64_t i64; @@ -470,7 +739,7 @@ static int parse_sampling(const json& b, const OaiLimits& lim, OaiRequest* r, Ap r->sp.freq_penalty = (float)d; d = r->sp.rep_penalty; - if (!get_num(b, "repetition_penalty", &d, err)) return RAD_E_INVAL; + if (!get_num_any(b, { "repetition_penalty", "repeat_penalty" }, &d, err)) return RAD_E_INVAL; if (!ok("repetition_penalty", d)) return RAD_E_INVAL; r->sp.rep_penalty = (float)d; @@ -556,14 +825,17 @@ static int parse_sampling(const json& b, const OaiLimits& lim, OaiRequest* r, Ap if (!get_int(b, "priority", &i64, err)) return RAD_E_INVAL; r->priority = (int)i64; - /* max_tokens, with max_completion_tokens as the newer OpenAI spelling of the same field. */ + /* max_tokens, with max_completion_tokens as OpenAI's newer spelling and n_predict as + * llama.cpp's. A NEGATIVE VALUE IS llama.cpp's "no limit": whatever the context leaves, which + * is what 0 resolves to in clamp_max_tokens -- and unlike an absent field it does not take the + * deployment's --default-max-tokens. */ int64_t mt = 0; - if (!get_int(b, "max_tokens", &mt, err)) return RAD_E_INVAL; - if (b.contains("max_completion_tokens") && !b.at("max_completion_tokens").is_null()) { - if (!get_int(b, "max_completion_tokens", &mt, err)) return RAD_E_INVAL; - } - if (mt < 0) { *err = err_bad("max_tokens", "must be >= 1"); return RAD_E_INVAL; } - r->max_tokens = (int32_t)(mt > 0 ? mt : lim.default_max_tokens); + bool mt_named = false; + if (!get_int_any(b, { "max_tokens", "max_completion_tokens", "n_predict" }, &mt, &mt_named, + err)) + return RAD_E_INVAL; + if (mt_named && mt == 0) { *err = err_bad("max_tokens", "must be >= 1, or -1 for no limit"); return RAD_E_INVAL; } + r->max_tokens = (int32_t)(mt > 0 ? mt : mt < 0 ? 0 : lim.default_max_tokens); /* ignore_eos: generate to max_tokens whatever the model emits. See Request::ignore_eos. */ if (!get_bool(b, "ignore_eos", &r->ignore_eos, err)) return RAD_E_INVAL; @@ -612,6 +884,19 @@ static int parse_sampling(const json& b, const OaiLimits& lim, OaiRequest* r, Ap if (!get_bool(b, "stream", &bl, err)) return RAD_E_INVAL; r->stream = bl; + /* llama.cpp's streaming extras: the timings on every chunk rather than the last, and the + * prompt's progress as chunks while it is being read. */ + if (!get_bool(b, "timings_per_token", &r->timings_per_token, err)) return RAD_E_INVAL; + if (!get_bool(b, "return_progress", &r->return_progress, err)) return RAD_E_INVAL; + + /* OpenRouter's `session_id`: which conversation the request belongs to, as the client names + * it. It labels the conversation on /sessions and the dashboard and changes nothing else. A + * value that is not a string is not a label and is ignored, as the field is everywhere. */ + auto sid = b.find("session_id"); + if (sid != b.end() && sid->is_string()) r->session_label = session_label_of(sid->get()); + + RAD_TRY(apply_sampler_order(b, &r->sp, err)); + auto so = b.find("stream_options"); if (so != b.end() && !so->is_null()) { if (!so->is_object()) { *err = err_bad("stream_options", "expected an object"); return RAD_E_INVAL; } @@ -824,6 +1109,28 @@ static int parse_output_format(const json& b, const OaiDeps& d, OaiRequest* r, A *err = err_bad("response_format", "cannot be combined with an explicit `grammar`"); return RAD_E_INVAL; } + /* llama.cpp's `json_schema`: the schema itself at the top level, the shorthand for a + * response_format of type json_schema. */ + auto js = b.find("json_schema"); + if (js != b.end() && !js->is_null()) { + if (!gram.empty() || has_rf) { + *err = err_bad("json_schema", "cannot be combined with `grammar` or `response_format`"); + return RAD_E_INVAL; + } + if (!js->is_object()) { *err = err_bad("json_schema", "expected a JSON Schema object"); return RAD_E_INVAL; } + json schema = *js; + if (schema_json) { *schema_json = schema.dump(); return RAD_OK; } + if (!d.grammar) { + *err = err_not_implemented("json_schema requires the JSON-schema to GBNF compiler " + "(spec 13), which this build was wired without"); + return RAD_E_UNSUPPORTED; + } + std::string out, why; + const int st = d.grammar->from_json_schema(schema, out, why); + if (st < 0) { *err = err_bad("json_schema", "could not be compiled to a grammar: " + why); return st; } + r->sp.grammar = out; + return RAD_OK; + } if (!gram.empty()) { r->sp.grammar = gram; return RAD_OK; } if (!has_rf) return RAD_OK; @@ -1249,13 +1556,22 @@ static int clamp_max_tokens(size_t n_prompt, const OaiLimits& lim, const char* f const int64_t room = lim.max_ctx - (int64_t)n_prompt; if (room <= 0) { - char msg[256]; + /* WORDED FOR THE CLIENTS THAT READ IT. An agent compacts its history when a request + * overflows, and it recognises the overflow by the error's text: OpenAI's "maximum + * context length is N tokens" and llama-server's "exceeds the available context size" + * are the two phrases those matchers look for, so the sentence carries both, beside + * OpenAI's code and llama-server's two numbers. */ + char msg[384]; snprintf(msg, sizeof msg, - "%zu prompt tokens does not fit the %lld token context, which leaves nothing to " - "generate into; shorten the prompt by at least %lld tokens", - n_prompt, (long long)lim.max_ctx, (long long)(1 - room)); + "This model's maximum context length is %lld tokens: the request (%zu tokens) " + "exceeds the available context size (%lld tokens) and leaves nothing to generate " + "into; shorten the prompt by at least %lld tokens", + (long long)lim.max_ctx, n_prompt, (long long)lim.max_ctx, (long long)(1 - room)); *err = err_bad(field, msg); + err->message = msg; err->code = "context_length_exceeded"; + err->n_prompt_tokens = (int64_t)n_prompt; + err->n_ctx = lim.max_ctx; return RAD_E_INVAL; } @@ -1307,12 +1623,15 @@ static int parse_thinking_budget(const json& b, const OaiDeps& d, const OaiLimit int64_t budget = -1; const char* named = nullptr; - for (const char* k : { "thinking_token_budget", "thinking_budget" }) { + for (const char* k : { "thinking_token_budget", "thinking_budget", "thinking_budget_tokens", + "reasoning_budget_tokens" }) { auto it = b.find(k); if (it == b.end() || it->is_null()) continue; int64_t v = 0; if (!get_int(b, k, &v, err)) return RAD_E_INVAL; - if (v < 0) { *err = err_bad(k, "must be >= 0"); return RAD_E_INVAL; } + /* llama.cpp's spellings take a negative budget for "none": said, it overrides the + * deployment's default as a number does. */ + if (v < 0) v = -1; if (named && v != budget) { *err = err_bad(k, std::string("disagrees with ") + named + ", which is the same field"); return RAD_E_INVAL; @@ -1324,6 +1643,7 @@ static int parse_thinking_budget(const json& b, const OaiDeps& d, const OaiLimit if (span.known()) sp->thinking_budget = (int32_t)lim.default_thinking_budget; return RAD_OK; } + if (budget < 0) return RAD_OK; if (!span.known()) { std::string why; if (render.think_close.empty()) @@ -1343,6 +1663,65 @@ static int parse_thinking_budget(const json& b, const OaiDeps& d, const OaiLimit return RAD_OK; } +/* LOGPROBS, in each endpoint's spelling, into one count. + * + * chat `logprobs` true, with `top_logprobs` alternatives (0 when absent, OpenAI's default) + * completions `logprobs` the number of alternatives, OpenAI's legacy integer + * any llama-server's `n_probs`, which wins over both + * + * A count of 0 still returns each token's own logprob on chat (OpenAI's meaning) and returns + * nothing on completions (llama-server's: its `logprobs` 0 and `n_probs` 0 are both "off"). The + * numbers are the RAW distribution's, as OpenAI and llama-server report them. */ +static int parse_logprobs(const json& b, const OaiLimits& lim, Endpoint ep, OaiRequest* out, + ApiError* err) { + bool want = false; + int64_t top = 0; + const char* field = "logprobs"; + if (ep == Endpoint::Chat) { + if (!get_bool(b, "logprobs", &want, err)) return RAD_E_INVAL; + if (!get_int(b, "top_logprobs", &top, err)) return RAD_E_INVAL; + auto t = b.find("top_logprobs"); + const bool named = t != b.end() && !t->is_null(); + if (!want && named) { + *err = err_bad("top_logprobs", "requires logprobs to be true"); + return RAD_E_INVAL; + } + if (named) field = "top_logprobs"; + } else { + auto lit = b.find("logprobs"); + if (lit != b.end() && !lit->is_null()) { + if (!lit->is_number_integer()) { + *err = err_bad("logprobs", "expected an integer (the number of alternatives)"); + return RAD_E_INVAL; + } + top = lit->get(); + want = top > 0; + } + } + auto np = b.find("n_probs"); + if (np != b.end() && !np->is_null()) { + if (!np->is_number_integer()) { + *err = err_bad("n_probs", "expected an integer (the number of alternatives)"); + return RAD_E_INVAL; + } + top = np->get(); + want = top > 0; + field = "n_probs"; + } + if (top < 0 || top > RAD_MAX_LOGPROBS) { + *err = err_bad(field, "must be in [0, " + std::to_string(RAD_MAX_LOGPROBS) + "]"); + return RAD_E_INVAL; + } + if (want && !lim.supports_logprobs) { + *err = err_unsupported(field, "the kernel libraries loaded have no sample_logprobs"); + return RAD_E_UNSUPPORTED; + } + out->want_logprobs = want; + out->n_logprobs = (int)top; + out->sp.n_probs = want ? (int)top : -1; + return RAD_OK; +} + int parse_chat_request(const std::string& body, const OaiDeps& d, const OaiLimits& lim, OaiRequest* out, ApiError* err) { json b; @@ -1353,6 +1732,7 @@ int parse_chat_request(const std::string& body, const OaiDeps& d, const OaiLimit out->id = random_id("chatcmpl-"); out->created = unix_now(); out->model = lim.model_id; + if (!lim.version.empty()) out->system_fingerprint = "radiance-" + lim.version; if (!get_str(b, "model", &out->model, err)) return RAD_E_INVAL; if (out->model.empty()) out->model = lim.model_id; @@ -1360,25 +1740,7 @@ int parse_chat_request(const std::string& body, const OaiDeps& d, const OaiLimit std::string schema_json; RAD_TRY(parse_output_format(b, d, out, err, &schema_json)); - /* logprobs. The wire format is implemented; whether the sampler produces the numbers is a - * property of the build, and if it does not we refuse rather than return nulls that look - * like "the model had no opinion". */ - bool want = false; - if (!get_bool(b, "logprobs", &want, err)) return RAD_E_INVAL; - int64_t top = 0; - if (!get_int(b, "top_logprobs", &top, err)) return RAD_E_INVAL; - if (!want && top > 0) { - *err = err_bad("top_logprobs", "requires logprobs to be true"); - return RAD_E_INVAL; - } - if (top < 0 || top > 20) { *err = err_bad("top_logprobs", "must be in [0, 20]"); return RAD_E_INVAL; } - if (want && !lim.supports_logprobs) { - *err = err_unsupported("logprobs", - "this build's sampler does not return per-token probabilities"); - return RAD_E_UNSUPPORTED; - } - out->want_logprobs = want; - out->n_logprobs = (int)top; + RAD_TRY(parse_logprobs(b, lim, Endpoint::Chat, out, err)); if (!d.chat) { *err = err_not_implemented( @@ -1390,6 +1752,26 @@ int parse_chat_request(const std::string& body, const OaiDeps& d, const OaiLimit auto mit = b.find("messages"); if (mit == b.end()) { *err = err_bad("messages", "is required"); return RAD_E_INVAL; } json messages = *mit; + /* The deprecated functions API's turns, as the current API spells them: an assistant + * message's `function_call` is one tool call, and a `function` message is the result of the + * call before it. The call ids pair them; the old API has none. */ + if (messages.is_array()) { + std::string call_id; + int n_calls = 0; + for (json& m : messages) { + const std::string role = str_or(m, "role"); + auto fc = m.find("function_call"); + if (role == "assistant" && fc != m.end() && fc->is_object() && !m.contains("tool_calls")) { + call_id = "call_" + std::to_string(n_calls++); + m["tool_calls"] = json::array( + { json{ { "id", call_id }, { "type", "function" }, { "function", *fc } } }); + m.erase("function_call"); + } else if (role == "function") { + m["role"] = "tool"; + m["tool_call_id"] = call_id; + } + } + } if (messages.is_array()) { out->n_messages = (int)messages.size(); for (auto it = messages.rbegin(); it != messages.rend(); ++it) { @@ -1407,8 +1789,7 @@ int parse_chat_request(const std::string& body, const OaiDeps& d, const OaiLimit if (cit->is_string()) take(cit->get_ref()); else if (cit->is_array()) for (const auto& part : *cit) - if (part.is_object() && part.value("type", "") == "text") - take(part.value("text", "")); + if (str_or(part, "type") == "text") take(str_or(part, "text")); for (char& c : t) if (c == '\n' || c == '\r' || c == '\t') c = ' '; if (t.size() > kKeep) { size_t cut = kKeep - 3; @@ -1421,6 +1802,41 @@ int parse_chat_request(const std::string& body, const OaiDeps& d, const OaiLimit } } + /* OpenAI's DEPRECATED functions API, which older clients still send: `functions` is `tools` + * with each entry unwrapped, and `function_call` is `tool_choice` -- "none", "auto", or + * {"name": ...}. Rewritten into the current fields, and refused beside them. The old API + * answers one call at most, so the grammar admits one. */ + auto fns = b.find("functions"); + if (fns != b.end() && !fns->is_null()) { + if (b.contains("tools") && !b.at("tools").is_null()) { + *err = err_bad("functions", "send `tools` or the deprecated `functions`, not both"); + return RAD_E_INVAL; + } + if (!fns->is_array()) { *err = err_bad("functions", "expected an array"); return RAD_E_INVAL; } + json t = json::array(); + for (const json& f : *fns) t.push_back(json{ { "type", "function" }, { "function", f } }); + b["tools"] = std::move(t); + b["parallel_tool_calls"] = false; + out->legacy_functions = true; + } + auto fcall = b.find("function_call"); + if (fcall != b.end() && !fcall->is_null()) { + if (b.contains("tool_choice") && !b.at("tool_choice").is_null()) { + *err = err_bad("function_call", + "send `tool_choice` or the deprecated `function_call`, not both"); + return RAD_E_INVAL; + } + if (fcall->is_string()) { + b["tool_choice"] = *fcall; + } else if (fcall->is_object() && fcall->contains("name") && fcall->at("name").is_string()) { + b["tool_choice"] = json{ { "type", "function" }, + { "function", { { "name", fcall->at("name") } } } }; + } else { + *err = err_bad("function_call", "expected \"none\", \"auto\" or {\"name\": ...}"); + return RAD_E_INVAL; + } + } + /* tools and tool_choice. */ json tools = json::array(); auto tit = b.find("tools"); @@ -1514,8 +1930,78 @@ int parse_chat_request(const std::string& body, const OaiDeps& d, const OaiLimit opt.tool_choice = tool_choice; opt.tool_name = named; opt.parallel_tool_calls = parallel; + const bool agp_named = b.contains("add_generation_prompt") && !b.at("add_generation_prompt").is_null(); if (!get_bool(b, "add_generation_prompt", &opt.add_generation_prompt, err)) return RAD_E_INVAL; + /* llama.cpp's `reasoning_format`. "none" leaves the reasoning in `content` between the + * template's own markers; "auto" and "deepseek" move it to `reasoning_content`, which is what + * this server does anyway. "deepseek-legacy" -- both at once -- is not served. */ + std::string rfmt; + if (!get_str(b, "reasoning_format", &rfmt, err)) return RAD_E_INVAL; + if (rfmt == "deepseek-legacy") { + *err = err_unsupported("reasoning_format", "\"deepseek-legacy\" keeps the reasoning in " + "`content` and `reasoning_content` both, which is not served; send " + "\"none\" or \"deepseek\""); + return RAD_E_UNSUPPORTED; + } else if (!rfmt.empty() && rfmt != "none" && rfmt != "auto" && rfmt != "deepseek") { + *err = err_bad("reasoning_format", "must be \"none\", \"auto\" or \"deepseek\""); + return RAD_E_INVAL; + } + + /* ASSISTANT PREFILL. A conversation that ends in an assistant message is continued, not + * answered: the reply picks up where that message stops. llama.cpp's default and the + * Anthropic API's meaning; vLLM's `continue_final_message` names it explicitly, true or + * llama.cpp's "content" / "reasoning_content". A request that names `add_generation_prompt` + * true opens a new turn after it instead, as vLLM does; naming that and + * `continue_final_message` both is a contradiction, refused as llama.cpp refuses it. */ + { + std::string cont; + auto cf = b.find("continue_final_message"); + if (cf != b.end() && !cf->is_null()) { + if (cf->is_boolean()) cont = cf->get() ? "auto" : ""; + else if (cf->is_string() && (*cf == "content" || *cf == "reasoning_content")) + cont = cf->get(); + else { + *err = err_bad("continue_final_message", + "expected a boolean, \"content\" or \"reasoning_content\""); + return RAD_E_INVAL; + } + if (!cont.empty() && agp_named && opt.add_generation_prompt) { + *err = err_bad("continue_final_message", + "cannot be combined with add_generation_prompt true"); + return RAD_E_INVAL; + } + } + const json* last = messages.is_array() && !messages.empty() ? &messages.back() : nullptr; + const bool ends_assistant = last && str_or(*last, "role") == "assistant"; + if (cont.empty() && cf == b.end() && ends_assistant && !agp_named) cont = "auto"; + if (!cont.empty()) { + if (!ends_assistant) { + *err = err_bad("continue_final_message", + "the last message is not an assistant message to continue"); + return RAD_E_INVAL; + } + if (last->contains("tool_calls") && !last->at("tool_calls").is_null() && + !last->at("tool_calls").empty()) { + *err = err_bad("messages", "an assistant message that made tool calls cannot be " + "continued"); + return RAD_E_INVAL; + } + if (messages.size() >= 2 && str_or(messages[messages.size() - 2], "role") == "assistant") { + *err = err_bad("messages", "two assistant messages at the end cannot be " + "continued"); + return RAD_E_INVAL; + } + opt.continue_final = cont; + opt.add_generation_prompt = false; + const json& c = last->contains("content") ? last->at("content") : json(); + if (c.is_string()) out->continued = c.get(); + else if (c.is_array()) + for (const json& p : c) + if (str_or(p, "type") == "text") out->continued += str_or(p, "text"); + } + } + /* The template's grammar and the caller's are ONE grammar, not two, and the template is the * one that knows how to combine them -- a tool-calling format has to leave room for the call * syntax around whatever the caller constrained. So both halves go IN and the merged result @@ -1524,6 +2010,9 @@ int parse_chat_request(const std::string& body, const OaiDeps& d, const OaiLimit opt.json_schema = schema_json; RAD_TRY(parse_thinking(b, lim, &opt, err)); + /* The request's reasoning_format over the deployment's (--reasoning-format), which the + * template defaults above have just applied. */ + if (!rfmt.empty()) opt.reasoning_format = rfmt; std::vector>> media; RAD_TRY(lower_content_parts(messages, d, lim, &media, err)); @@ -1568,6 +2057,7 @@ int parse_chat_request(const std::string& body, const OaiDeps& d, const OaiLimit /* The format's own end-of-turn markers join the caller's stop strings rather than living in a * second list: both end the generation and both report `finish_reason: "stop"` (sink.cpp), so * a separate list would be a distinction with no observable difference. */ + out->n_client_stops = out->stop.size(); for (const auto& s : render.additional_stops) if (std::find(out->stop.begin(), out->stop.end(), s) == out->stop.end()) out->stop.push_back(s); @@ -1614,15 +2104,17 @@ int parse_chat_request(const std::string& body, const OaiDeps& d, const OaiLimit /* ================================================================== completions */ int parse_completion_request(const std::string& body, const OaiDeps& d, const OaiLimits& lim, - OaiRequest* out, ApiError* err) { + OaiRequest* out, ApiError* err, bool native) { json b; RAD_TRY(parse_request_object(body, lim, &b, err)); - RAD_TRY(vet_keys(b, Endpoint::Completion, err)); + RAD_TRY(vet_keys(b, Endpoint::Completion, err, native)); + if (native && !get_bool(b, "return_tokens", &out->return_tokens, err)) return RAD_E_INVAL; out->endpoint = Endpoint::Completion; out->id = random_id("cmpl-"); out->created = unix_now(); out->model = lim.model_id; + if (!lim.version.empty()) out->system_fingerprint = "radiance-" + lim.version; if (!get_str(b, "model", &out->model, err)) return RAD_E_INVAL; if (out->model.empty()) out->model = lim.model_id; @@ -1643,22 +2135,13 @@ int parse_completion_request(const std::string& body, const OaiDeps& d, const Oa if (!get_bool(b, "echo", &out->echo, err)) return RAD_E_INVAL; - /* /v1/completions `logprobs` is an integer count, not a boolean. */ - auto lit = b.find("logprobs"); - if (lit != b.end() && !lit->is_null()) { - if (!lit->is_number_integer()) { - *err = err_bad("logprobs", "expected an integer (the number of alternatives)"); - return RAD_E_INVAL; - } - int64_t nl = lit->get(); - if (nl < 0 || nl > 5) { *err = err_bad("logprobs", "must be in [0, 5]"); return RAD_E_INVAL; } - if (nl > 0 && !lim.supports_logprobs) { - *err = err_unsupported("logprobs", - "this build's sampler does not return per-token probabilities"); - return RAD_E_UNSUPPORTED; - } - out->want_logprobs = nl > 0; - out->n_logprobs = (int)nl; + RAD_TRY(parse_logprobs(b, lim, Endpoint::Completion, out, err)); + /* `echo` with logprobs asks for the PROMPT's logprobs too, which are not computed: a prompt + * position's distribution never leaves the card. */ + if (out->echo && out->want_logprobs) { + *err = err_unsupported("echo", "logprobs for the prompt are not returned; send echo " + "without logprobs, or logprobs without echo"); + return RAD_E_UNSUPPORTED; } auto pit = b.find("prompt"); @@ -1697,7 +2180,34 @@ int parse_completion_request(const std::string& body, const OaiDeps& d, const Oa return true; }; - if (pit->is_string()) { + /* llama-server's mixed prompt: strings and token ids in one array are ONE prompt, the strings + * tokenised in place, only the first of them with the BOS. */ + bool mixed = false; + if (native && pit->is_array()) { + bool s = false, n = false; + for (const auto& v : *pit) { s = s || v.is_string(); n = n || v.is_number_integer(); } + mixed = s && n; + } + if (mixed) { + PromptInput p; + bool first = true; + for (const auto& v : *pit) { + if (v.is_string()) { + const std::vector t = d.tok->encode(v.get(), first, true); + p.tokens.insert(p.tokens.end(), t.begin(), t.end()); + } else { + int32_t id = 0; + if (!v.is_number_integer() || !token_id(v, &id)) { + *err = err_bad("prompt", "a mixed prompt holds strings and token ids only"); + return RAD_E_INVAL; + } + p.tokens.push_back(id); + } + first = false; + } + p.text = d.tok->decode(p.tokens); + out->prompts.push_back(std::move(p)); + } else if (pit->is_string()) { push_text(pit->get()); } else if (pit->is_array()) { if (pit->empty()) { *err = err_bad("prompt", "must not be empty"); return RAD_E_INVAL; } @@ -2081,6 +2591,7 @@ static std::string usage_chunk(const OaiRequest& r, const UsageOut& u, const Tim o["object"] = object; o["created"] = r.created; o["model"] = r.model; + if (!r.system_fingerprint.empty()) o["system_fingerprint"] = r.system_fingerprint; o["choices"] = json::array(); o["usage"] = usage_json(u); if (t.valid) o["timings"] = timings_json(t); @@ -2095,20 +2606,65 @@ std::string chat_usage_chunk(const OaiRequest& r, const UsageOut& u, const Timin return usage_chunk(r, u, t, "chat.completion.chunk"); } -static json chat_logprobs_json(const std::vector& lp) { - json content = json::array(); - for (const auto& e : lp) { - json bytes = json::array(); - for (unsigned char c : e.text) bytes.push_back((int)c); - json j; - j["token"] = e.text; - j["logprob"] = e.logprob; - j["bytes"] = bytes; - j["top_logprobs"] = json::array(); - content.push_back(std::move(j)); +static json lp_bytes(const std::string& b) { + json a = json::array(); + for (unsigned char c : b) a.push_back((int)c); + return a; +} + +static json lp_entry(const LogprobEntry& e) { + json top = json::array(); + for (const LogprobAlt& a : e.top) + top.push_back(json{ { "id", a.token }, { "token", a.text }, { "bytes", lp_bytes(a.bytes) }, + { "logprob", a.logprob } }); + return json{ { "id", e.token }, { "token", e.text }, { "bytes", lp_bytes(e.bytes) }, + { "logprob", e.logprob }, { "top_logprobs", std::move(top) } }; +} + +static json lp_content(const LogprobEntry* e, size_t n) { + json a = json::array(); + for (size_t i = 0; i < n; ++i) a.push_back(lp_entry(e[i])); + return a; +} + +std::string logprobs_content(const LogprobEntry* e, size_t n) { + std::string s; + for (size_t i = 0; i < n; ++i) { + if (i) s += ','; + s += lp_entry(e[i]).dump(); } + return s; +} + +/* OpenAI's legacy shape: parallel arrays, and the alternatives as one {text: logprob} object a + * token. Two alternatives with the same text -- distinct ids that decode alike -- collapse to the + * likelier, which is what that shape can say. */ +static json lp_legacy(const LogprobEntry* e, size_t n, size_t offset) { + json toks = json::array(), lps = json::array(), tops = json::array(), offs = json::array(); + for (size_t i = 0; i < n; ++i) { + toks.push_back(e[i].text); + lps.push_back(e[i].logprob); + json t = json::object(); + for (const LogprobAlt& a : e[i].top) + if (!t.contains(a.text)) t[a.text] = a.logprob; + tops.push_back(std::move(t)); + /* Where the token's text starts in the choice's, which is where the one before it ended: + * its own `text` can be shorter than what it added (half a character, held back). */ + offs.push_back(offset); + offset = e[i].end; + } + return json{ { "tokens", std::move(toks) }, { "token_logprobs", std::move(lps) }, + { "top_logprobs", std::move(tops) }, { "text_offset", std::move(offs) }, + { "content", lp_content(e, n) } }; +} + +std::string logprobs_legacy(const LogprobEntry* e, size_t n, size_t offset) { + return lp_legacy(e, n, offset).dump(); +} + +static json chat_logprobs_json(const std::vector& lp) { json o; - o["content"] = content; + o["content"] = lp_content(lp.data(), lp.size()); return o; } @@ -2121,14 +2677,19 @@ std::string chat_completion_body(const OaiRequest& r, const std::vectoropen() : nullptr), id_(r.id), model_(r.model), - created_(r.created), index_(index) {} + fingerprint_(r.system_fingerprint), created_(r.created), index_(index) {} -std::string ChatDeltaStream::chunk(json delta, const char* finish_reason, const TimingsOut* t) { - json ch; - ch["index"] = index_; - ch["delta"] = std::move(delta); - if (finish_reason) ch["finish_reason"] = finish_reason; - else ch["finish_reason"] = nullptr; - json o; - o["id"] = id_; - o["object"] = "chat.completion.chunk"; - o["created"] = created_; - o["model"] = model_; - o["choices"] = json::array({ch}); - if (t && t->valid) o["timings"] = timings_json(*t); - return sse_event(o.dump()); -} - -void ChatDeltaStream::delta_open(std::string& out) { - /* Built from nlohmann's own serialisation of each field, on first use rather than in the - * constructor, so a field nlohmann refuses throws where chunk() would have. */ - if (head_.empty()) - head_ = "data: {\"id\":" + json(id_).dump() + - ",\"object\":\"chat.completion.chunk\",\"created\":" + json(created_).dump() + - ",\"model\":" + json(model_).dump() + ",\"choices\":[{\"index\":" + - json(index_).dump() + ",\"delta\":"; - out += head_; -} - -void ChatDeltaStream::delta_close(std::string& out) const { - out += ",\"finish_reason\":null}]}\n\n"; -} - -/* Text that is not well-formed UTF-8 goes to nlohmann, which refuses it with the exception the - * tree in chunk() raises for it. */ -void ChatDeltaStream::quote(std::string& out, std::string_view s) { - if (!json_quote_append(out, s)) out += json(std::string(s)).dump(); -} - -std::string ChatDeltaStream::first_chunk() { - json d; - d["role"] = "assistant"; - d["content"] = ""; - return chunk(std::move(d), nullptr); -} - -/* One SSE chunk per increment, in the order the reader completed them. A call is announced with - * its id, name and empty arguments before any of its arguments flow -- an entry with no name is - * an index the client can never resolve -- and the id is minted here, because the parser reads - * the model's text and the model writes none. */ -std::string ChatDeltaStream::emit(const std::vector& ev) { - std::string out; - for (const ReplyDelta& d : ev) { - switch (d.kind) { - case ReplyDelta::Reasoning: - if (d.text.empty()) continue; - last_.reasoning += d.text; - delta_open(out); - out += "{\"reasoning_content\":"; - quote(out, d.text); - out += '}'; - break; - case ReplyDelta::Content: - if (d.text.empty()) continue; - last_.content += d.text; - delta_open(out); - out += "{\"content\":"; - quote(out, d.text); - out += '}'; - break; - case ReplyDelta::CallBegin: { - ToolCall tc; - tc.id = random_id("call_"); - tc.name = d.text; - delta_open(out); - out += "{\"tool_calls\":[{\"index\":"; - out += std::to_string((int64_t)d.call); - out += ",\"id\":"; - quote(out, tc.id); - out += ",\"type\":\"function\",\"function\":{\"name\":"; - quote(out, tc.name); - out += ",\"arguments\":\"\"}}]}"; - last_.tool_calls.push_back(std::move(tc)); - break; - } - case ReplyDelta::CallArgs: { - if (d.text.empty() || d.call >= last_.tool_calls.size()) continue; - last_.tool_calls[d.call].arguments += d.text; - delta_open(out); - out += "{\"tool_calls\":[{\"index\":"; - out += std::to_string((int64_t)d.call); - out += ",\"function\":{\"arguments\":"; - quote(out, d.text); - out += "}}]}"; - break; - } - case ReplyDelta::CallEnd: - continue; - } - delta_close(out); +/* What one increment adds to the message the stream adds up to, and the id a call is announced + * with: minted here, because the parser reads the model's text and the model writes none. Returns + * false for an increment that adds nothing and is not sent. */ +bool ReplyStream::absorb(const ReplyDelta& d) { + switch (d.kind) { + case ReplyDelta::Reasoning: + if (d.text.empty()) return false; + last_.reasoning += d.text; + return true; + case ReplyDelta::Content: + if (d.text.empty()) return false; + last_.content += d.text; + return true; + case ReplyDelta::CallBegin: { + ToolCall tc; + tc.id = random_id("call_"); + tc.name = d.text; + last_.tool_calls.push_back(std::move(tc)); + return true; } - return out; + case ReplyDelta::CallArgs: + if (d.text.empty() || d.call >= last_.tool_calls.size()) return false; + last_.tool_calls[d.call].arguments += d.text; + return true; + case ReplyDelta::CallEnd: + return true; + } + return false; } -std::string ChatDeltaStream::push(std::string_view appended, bool is_final) { +std::string ReplyStream::push(std::string_view appended, bool is_final) { if (finished_) return std::string(); std::string out; if (!reader_) { /* Nothing to parse: the text is the answer, as it arrives. */ if (!appended.empty()) { - last_.content.append(appended); - delta_open(out); - out += "{\"content\":"; - quote(out, appended); - out += '}'; - delta_close(out); + ev_.clear(); + ReplyDelta d; + d.kind = ReplyDelta::Content; + d.text = std::string(appended); + ev_.push_back(std::move(d)); + out = emit(ev_); } finished_ = is_final; return out; @@ -2384,6 +2862,10 @@ std::string ChatDeltaStream::push(std::string_view appended, bool is_final) { return out; } +std::string ReplyStream::error_chunk(const ApiError& e, const TimingsOut& t, const UsageOut& u) { + return final_chunk(Finish::Error, t, u) + sse_error(e); +} + bool calls_complete(const ParsedMessage& m) { if (m.tool_calls.empty() || m.open_call) return false; for (const auto& tc : m.tool_calls) @@ -2391,7 +2873,7 @@ bool calls_complete(const ParsedMessage& m) { return true; } -Finish ChatDeltaStream::adjusted_finish(Finish f) const { +Finish ReplyStream::adjusted_finish(Finish f) const { if (f != Finish::Stop && f != Finish::StopString) return f; /* Only claim tool_calls if every call closed and its arguments parse. A truncated arguments * object reported as a tool call is a tool invoked with the wrong arguments (json_partial.h). @@ -2399,11 +2881,1076 @@ Finish ChatDeltaStream::adjusted_finish(Finish f) const { return calls_complete(last_) ? Finish::ToolCalls : f; } -std::string ChatDeltaStream::final_chunk(Finish f, const TimingsOut& t) { +/* ------------------------------------------------------------------ OpenAI's chunks */ + +std::string ChatDeltaStream::chunk(json delta, const char* finish_reason, const TimingsOut* t) { + json ch; + ch["index"] = index_; + ch["delta"] = std::move(delta); + if (!lp_.empty()) { + ch["logprobs"] = json{ { "content", json::parse("[" + lp_ + "]") } }; + lp_.clear(); + } + if (finish_reason) ch["finish_reason"] = finish_reason; + else ch["finish_reason"] = nullptr; + json o; + o["id"] = id_; + o["object"] = "chat.completion.chunk"; + o["created"] = created_; + o["model"] = model_; + if (!fingerprint_.empty()) o["system_fingerprint"] = fingerprint_; + o["choices"] = json::array({ch}); + if (t && t->valid) o["timings"] = timings_json(*t); + return sse_event(o.dump()); +} + +void ChatDeltaStream::delta_open(std::string& out) { + /* Built from nlohmann's own serialisation of each field, on first use rather than in the + * constructor, so a field nlohmann refuses throws where chunk() would have. */ + if (head_.empty()) + head_ = "data: {\"id\":" + json(id_).dump() + + ",\"object\":\"chat.completion.chunk\",\"created\":" + json(created_).dump() + + ",\"model\":" + json(model_).dump() + + (fingerprint_.empty() ? std::string() + : ",\"system_fingerprint\":" + json(fingerprint_).dump()) + + ",\"choices\":[{\"index\":" + + json(index_).dump() + ",\"delta\":"; + out += head_; +} + +void ChatDeltaStream::add_logprobs(const std::string& elems) { + if (elems.empty()) return; + if (!lp_.empty()) lp_ += ','; + lp_ += elems; +} + +void ChatDeltaStream::delta_close(std::string& out) { + if (!lp_.empty()) { + out += ",\"logprobs\":{\"content\":["; + out += lp_; + out += "]}"; + lp_.clear(); + } + if (timings_.empty()) { out += ",\"finish_reason\":null}]}\n\n"; return; } + out += ",\"finish_reason\":null}],"; + out += timings_; + out += "}\n\n"; +} + +void ChatDeltaStream::set_timings(const TimingsOut& t) { + timings_.clear(); + if (t.valid) timings_ = "\"timings\":" + timings_json(t).dump(); +} + +/* Text that is not well-formed UTF-8 goes to nlohmann, which refuses it with the exception the + * tree in chunk() raises for it. */ +void ReplyStream::quote(std::string& out, std::string_view s) { + if (!json_quote_append(out, s)) out += json(std::string(s)).dump(); +} + +std::string ChatDeltaStream::first_chunk() { + json d; + d["role"] = "assistant"; + d["content"] = ""; + return chunk(std::move(d), nullptr); +} + +/* One SSE chunk per increment, in the order the reader completed them. A call is announced with + * its id, name and empty arguments before any of its arguments flow -- an entry with no name is + * an index the client can never resolve. */ +std::string ChatDeltaStream::emit(const std::vector& ev) { + std::string out; + for (const ReplyDelta& d : ev) { + if (!absorb(d) || d.kind == ReplyDelta::CallEnd) continue; + /* The functions API has one call; a second one past the grammar's one is not sent. */ + if (legacy_ && (d.kind == ReplyDelta::CallBegin || d.kind == ReplyDelta::CallArgs) && + (d.kind == ReplyDelta::CallBegin ? last_.tool_calls.size() - 1 : d.call) > 0) + continue; + delta_open(out); + switch (d.kind) { + case ReplyDelta::Reasoning: + out += "{\"reasoning_content\":"; + quote(out, d.text); + out += '}'; + break; + case ReplyDelta::Content: + out += "{\"content\":"; + quote(out, d.text); + out += '}'; + break; + case ReplyDelta::CallBegin: { + const ToolCall& tc = last_.tool_calls.back(); + if (legacy_) { + out += "{\"function_call\":{\"name\":"; + quote(out, tc.name); + out += ",\"arguments\":\"\"}}"; + break; + } + out += "{\"tool_calls\":[{\"index\":"; + out += std::to_string((int64_t)d.call); + out += ",\"id\":"; + quote(out, tc.id); + out += ",\"type\":\"function\",\"function\":{\"name\":"; + quote(out, tc.name); + out += ",\"arguments\":\"\"}}]}"; + break; + } + case ReplyDelta::CallArgs: + if (legacy_) { + out += "{\"function_call\":{\"arguments\":"; + quote(out, d.text); + out += "}}"; + break; + } + out += "{\"tool_calls\":[{\"index\":"; + out += std::to_string((int64_t)d.call); + out += ",\"function\":{\"arguments\":"; + quote(out, d.text); + out += "}}]}"; + break; + case ReplyDelta::CallEnd: + break; + } + delta_close(out); + } + return out; +} + +std::string ChatDeltaStream::final_chunk(Finish f, const TimingsOut& t, const UsageOut&) { /* The generation is over, so whatever the reader was holding is resolved now. A caller that * already said so gets nothing twice. */ std::string out = push(std::string_view(), true); - out += chunk(json::object(), finish_reason_oai(adjusted_finish(f)), &t); + const Finish a = adjusted_finish(f); + out += chunk(json::object(), legacy_ && a == Finish::ToolCalls ? "function_call" + : finish_reason_oai(a), &t); + return out; +} + +/* ================================================================== Anthropic's Messages API */ + +namespace { + +/* CLAUDE CODE STAMPS EVERY REQUEST'S SYSTEM PROMPT. Its first block opens + * `x-anthropic-billing-header: cc_version=...; cc_entrypoint=cli; cch=a5145;` and the cch value + * changes per request, so the very first tokens of the prompt differ every turn and the prefix + * cache can never reuse a conversation. It is an integrity stamp for Anthropic's billing and + * means nothing to a model; held constant, as llama-server holds it. */ +void hold_billing_stamp(std::string& s) { + static const char kHead[] = "x-anthropic-billing-header:"; + if (s.rfind(kHead, 0) != 0) return; + const size_t at = s.find("cch=", sizeof kHead - 1); + if (at == std::string::npos) return; + const size_t end = s.find(';', at + 4); + if (end == std::string::npos) return; + for (size_t i = at + 4; i < end; ++i) s[i] = 'f'; +} + +/* An image block's source as the content part the chat path reads. A URL source stays a URL, + * which the chat path refuses as it refuses every remote fetch (decode_media_url). `at` names the + * block in a refusal. */ +int anthropic_image(const json& block, const std::string& at, json* out, ApiError* err) { + auto sit = block.find("source"); + if (sit == block.end() || !sit->is_object()) { + *err = err_bad(at + ".source", "expected an object"); + return RAD_E_INVAL; + } + const json& src = *sit; + std::string type, url; + if (!member_str(src, "type", (at + ".source.type").c_str(), &type, err)) return RAD_E_INVAL; + if (type == "base64") { + std::string media = "image/jpeg", data; + if (!member_str(src, "media_type", (at + ".source.media_type").c_str(), &media, err) || + !member_str(src, "data", (at + ".source.data").c_str(), &data, err)) + return RAD_E_INVAL; + url = "data:" + media + ";base64," + data; + } else if (!member_str(src, "url", (at + ".source.url").c_str(), &url, err)) { + return RAD_E_INVAL; + } + *out = json{ { "type", "image_url" }, { "image_url", { { "url", url } } } }; + return RAD_OK; +} + +} /* namespace */ + +int anthropic_to_chat(const std::string& body, const OaiLimits& lim, std::string* chat, + std::string* label, ApiError* err) { + json b; + RAD_TRY(parse_request_object(body, lim, &b, err)); + json o = json::object(); + json msgs = json::array(); + + /* The system prompt: a string or text blocks, which become one system message. */ + auto sys = b.find("system"); + if (sys != b.end() && !sys->is_null()) { + std::string text; + if (sys->is_string()) { + text = sys->get(); + hold_billing_stamp(text); + } else if (sys->is_array()) { + for (const json& blk : *sys) { + if (str_or(blk, "type") != "text") { + *err = err_bad("system", "expected a string or text blocks"); + return RAD_E_INVAL; + } + std::string t; + if (!member_str(blk, "text", "system[].text", &t, err)) return RAD_E_INVAL; + hold_billing_stamp(t); + if (!text.empty()) text += "\n"; + text += t; + } + } else { + *err = err_bad("system", "expected a string or text blocks"); + return RAD_E_INVAL; + } + msgs.push_back(json{ { "role", "system" }, { "content", text } }); + } + + auto mit = b.find("messages"); + if (mit == b.end() || !mit->is_array()) { + *err = err_bad("messages", "is required, as an array"); + return RAD_E_INVAL; + } + for (const json& m : *mit) { + if (!m.is_object()) { *err = err_bad("messages[]", "expected an object"); return RAD_E_INVAL; } + std::string role; + if (!member_str(m, "role", "messages[].role", &role, err)) return RAD_E_INVAL; + if (role != "user" && role != "assistant") { + *err = err_bad("messages[].role", "must be \"user\" or \"assistant\", got \"" + role + "\""); + return RAD_E_INVAL; + } + const json content = m.contains("content") ? m.at("content") : json(); + if (content.is_string()) { + msgs.push_back(json{ { "role", role }, { "content", content } }); + continue; + } + if (!content.is_array()) { + *err = err_bad("messages[].content", "expected a string or content blocks"); + return RAD_E_INVAL; + } + /* THE TOOL RESULTS GO FIRST. Anthropic carries them in the user turn that follows the + * calls, beside whatever the user says next; the chat format wants each one as a tool + * message directly after the assistant turn that made the call, and the user's own words + * after them. */ + json parts = json::array(), calls = json::array(), results = json::array(); + std::string reasoning; + for (const json& blk : content) { + if (!blk.is_object()) { + *err = err_bad("messages[].content[]", "expected an object"); + return RAD_E_INVAL; + } + std::string type; + if (!member_str(blk, "type", "messages[].content[].type", &type, err)) return RAD_E_INVAL; + if (type == "text") { + std::string t; + if (!member_str(blk, "text", "messages[].content[].text", &t, err)) return RAD_E_INVAL; + parts.push_back(json{ { "type", "text" }, { "text", t } }); + } else if (type == "image") { + json part; + RAD_TRY(anthropic_image(blk, "messages[].content[]", &part, err)); + parts.push_back(std::move(part)); + } else if (type == "thinking") { + std::string t; + if (!member_str(blk, "thinking", "messages[].content[].thinking", &t, err)) + return RAD_E_INVAL; + reasoning += t; + } else if (type == "redacted_thinking") { + /* Encrypted for Anthropic's own models; nothing here can read it. */ + } else if (type == "tool_use") { + std::string id, name; + if (!member_str(blk, "id", "messages[].content[].id", &id, err) || + !member_str(blk, "name", "messages[].content[].name", &name, err)) + return RAD_E_INVAL; + calls.push_back(json{ { "id", id }, + { "type", "function" }, + { "function", { { "name", name }, + { "arguments", blk.value("input", json::object()).dump() } } } }); + } else if (type == "tool_result") { + std::string use_id; + if (!member_str(blk, "tool_use_id", "messages[].content[].tool_use_id", &use_id, err)) + return RAD_E_INVAL; + json rc = blk.contains("content") ? blk.at("content") : json(""); + json tc; + if (rc.is_string()) { + tc = rc; + } else if (rc.is_array()) { + json rp = json::array(); + bool media = false; + std::string flat; + for (const json& c : rc) { + if (!c.is_object()) { + *err = err_bad("messages[].content[].content[]", "expected an object"); + return RAD_E_INVAL; + } + std::string ct; + if (!member_str(c, "type", "messages[].content[].content[].type", &ct, err)) + return RAD_E_INVAL; + if (ct == "text") { + std::string t; + if (!member_str(c, "text", "messages[].content[].content[].text", &t, err)) + return RAD_E_INVAL; + flat += t; + rp.push_back(json{ { "type", "text" }, { "text", t } }); + } else if (ct == "image") { + json part; + RAD_TRY(anthropic_image(c, "messages[].content[].content[]", &part, err)); + media = true; + rp.push_back(std::move(part)); + } else { + *err = err_unsupported("messages[].content[].content", "a tool result " + "block of type \"" + ct + "\" is not served"); + return RAD_E_UNSUPPORTED; + } + } + tc = media ? rp : json(flat); + } else { + tc = ""; + } + results.push_back(json{ { "role", "tool" }, + { "tool_call_id", use_id }, + { "content", tc } }); + } else { + /* A block that would change the answer and that this server cannot serve -- + * documents, server tools' results -- is refused by name, not dropped. */ + *err = err_unsupported("messages[].content[].type", + "a content block of type \"" + type + "\" is not served"); + return RAD_E_UNSUPPORTED; + } + } + for (json& t : results) msgs.push_back(std::move(t)); + if (parts.empty() && calls.empty() && reasoning.empty()) continue; + json nm = { { "role", role } }; + if (role == "assistant") { + /* An assistant turn's text is one string, which is what every template renders. */ + std::string text; + for (const json& p : parts) + if (p.at("type") == "text") text += p.at("text").get(); + nm["content"] = text; + } else { + nm["content"] = parts.empty() ? json("") : parts; + } + if (!calls.empty()) nm["tool_calls"] = calls; + if (!reasoning.empty()) nm["reasoning_content"] = reasoning; + msgs.push_back(std::move(nm)); + } + o["messages"] = std::move(msgs); + + /* Client tools are functions. A server tool -- Anthropic's own web search or code + * execution, named by `type` -- runs on Anthropic's side and has no counterpart here. */ + auto tit = b.find("tools"); + if (tit != b.end() && tit->is_array() && !tit->empty()) { + json tools = json::array(); + for (const json& t : *tit) { + std::string type = "custom", name; + if (t.is_object() && (!member_str(t, "type", "tools[].type", &type, err) || + !member_str(t, "name", "tools[].name", &name, err))) + return RAD_E_INVAL; + if (!t.is_object() || (type != "custom" && !t.contains("input_schema"))) { + *err = err_unsupported("tools", "the server tool \"" + type + "\" runs on " + "Anthropic's side and is not served; send client tools"); + return RAD_E_UNSUPPORTED; + } + json fn = { { "name", name }, + { "parameters", t.contains("input_schema") ? t.at("input_schema") : json::object() } }; + if (t.contains("description")) fn["description"] = t.at("description"); + tools.push_back(json{ { "type", "function" }, { "function", fn } }); + } + o["tools"] = std::move(tools); + } + auto tc = b.find("tool_choice"); + if (tc != b.end() && tc->is_object()) { + std::string type = "auto", name; + if (!member_str(*tc, "type", "tool_choice.type", &type, err) || + !member_str(*tc, "name", "tool_choice.name", &name, err)) + return RAD_E_INVAL; + if (type == "auto" || type == "none") o["tool_choice"] = type; + else if (type == "any") o["tool_choice"] = "required"; + else if (type == "tool") + o["tool_choice"] = json{ { "type", "function" }, { "function", { { "name", name } } } }; + else { + *err = err_bad("tool_choice.type", "must be auto, any, tool or none"); + return RAD_E_INVAL; + } + bool one = false; + if (!get_bool(*tc, "disable_parallel_tool_use", &one, err)) return RAD_E_INVAL; + if (one) o["parallel_tool_calls"] = false; + } + + /* `model` too, which the reply names back as Anthropic's does. */ + for (const char* k : { "model", "max_tokens", "temperature", "top_p", "top_k", "stream" }) + if (b.contains(k)) o[k] = b.at(k); + if (b.contains("stop_sequences")) o["stop"] = b.at("stop_sequences"); + + /* Extended thinking: on with a budget, off, or on with the template's own judgement. */ + auto th = b.find("thinking"); + if (th != b.end() && th->is_object()) { + std::string type; + if (!member_str(*th, "type", "thinking.type", &type, err)) return RAD_E_INVAL; + if (type == "disabled") { + o["enable_thinking"] = false; + } else if (type == "enabled" || type == "adaptive") { + o["enable_thinking"] = true; + if (th->contains("budget_tokens")) o["thinking_token_budget"] = th->at("budget_tokens"); + } + } + + /* The caller's own name for whoever is asking, which Claude Code fills with its session. */ + auto md = b.find("metadata"); + if (label && md != b.end() && md->is_object() && md->contains("user_id") && + md->at("user_id").is_string()) + *label = session_label_of(md->at("user_id").get()); + + *chat = o.dump(); + return RAD_OK; +} + +const char* anthropic_stop_reason(const OaiRequest& r, Finish f, const std::string& stop_word) { + switch (f) { + case Finish::ToolCalls: return "tool_use"; + case Finish::Length: return "max_tokens"; + case Finish::StopString: { + /* The client's own stop sequence is stop_sequence; the chat format's end-of-turn marker + * is the turn ending, which is end_turn. */ + const auto end = r.stop.begin() + (long)std::min(r.n_client_stops, r.stop.size()); + if (!stop_word.empty() && std::find(r.stop.begin(), end, stop_word) != end) + return "stop_sequence"; + return "end_turn"; + } + default: return "end_turn"; + } +} + +static json anthropic_usage(const UsageOut& u) { + return json{ { "input_tokens", u.prompt - u.cached }, + { "output_tokens", u.completion }, + { "cache_read_input_tokens", u.cached }, + { "cache_creation_input_tokens", 0 } }; +} + +std::string anthropic_message_body(const OaiRequest& r, const ChoiceOut& c, const UsageOut& u) { + json blocks = json::array(); + if (!c.msg.reasoning.empty()) + blocks.push_back(json{ { "type", "thinking" }, { "thinking", c.msg.reasoning }, + { "signature", "" } }); + std::string text = c.msg.content; + if (!r.continued.empty() && text.rfind(r.continued, 0) == 0) text.erase(0, r.continued.size()); + if (!text.empty()) blocks.push_back(json{ { "type", "text" }, { "text", text } }); + for (const ToolCall& tc : c.msg.tool_calls) { + json in = json::parse(tc.arguments, nullptr, false); + if (in.is_discarded() || !in.is_object()) in = json::object(); + blocks.push_back(json{ { "type", "tool_use" }, { "id", tc.id }, { "name", tc.name }, + { "input", in } }); + } + const char* sr = anthropic_stop_reason(r, c.finish, c.stop_word); + json o; + o["id"] = r.id; + o["type"] = "message"; + o["role"] = "assistant"; + o["model"] = r.model; + o["content"] = std::move(blocks); + o["stop_reason"] = sr; + o["stop_sequence"] = std::strcmp(sr, "stop_sequence") == 0 ? json(c.stop_word) : json(nullptr); + o["usage"] = anthropic_usage(u); + return o.dump(); +} + +std::string anthropic_error_body(const ApiError& e) { + const char* type = e.status == 401 ? "authentication_error" + : e.status == 403 ? "permission_error" + : e.status == 404 ? "not_found_error" + : e.status == 413 ? "request_too_large" + : e.status == 429 ? "rate_limit_error" + : e.status >= 500 ? "api_error" + : "invalid_request_error"; + json o; + o["type"] = "error"; + o["error"] = json{ { "type", type }, { "message", e.message } }; + return o.dump(); +} + +AnthropicStream::AnthropicStream(const OaiRequest& r, int index, const IReplyParser* parser) + : ReplyStream(r, index, parser), r_(&r), skip_(r.continued) { + for (const PromptInput& p : r.prompts) n_input_ += (int64_t)p.tokens.size(); +} + +void AnthropicStream::event(std::string& out, const char* type, const json& data) { + out += "event: "; + out += type; + out += "\ndata: "; + out += data.dump(); + out += "\n\n"; +} + +std::string AnthropicStream::first_chunk() { + json m; + m["id"] = id_; + m["type"] = "message"; + m["role"] = "assistant"; + m["model"] = model_; + m["content"] = json::array(); + m["stop_reason"] = nullptr; + m["stop_sequence"] = nullptr; + m["usage"] = json{ { "input_tokens", n_input_ }, { "output_tokens", 0 } }; + std::string out; + event(out, "message_start", json{ { "type", "message_start" }, { "message", m } }); + return out; +} + +void AnthropicStream::open(std::string& out, Block b, const ToolCall* tc) { + close(out); + json cb; + if (b == Block::Thinking) cb = { { "type", "thinking" }, { "thinking", "" } }; + else if (b == Block::Text) cb = { { "type", "text" }, { "text", "" } }; + else cb = { { "type", "tool_use" }, { "id", tc->id }, { "name", tc->name }, + { "input", json::object() } }; + event(out, "content_block_start", + json{ { "type", "content_block_start" }, { "index", n_blocks_ }, { "content_block", cb } }); + ++n_blocks_; + block_ = b; +} + +void AnthropicStream::close(std::string& out) { + if (block_ == Block::None) return; + /* A thinking block ends with its signature, which a client hands back with the block on the + * next turn. Anthropic's is cryptographic and verified by Anthropic; a local model has none, + * and the empty one is what llama-server sends. */ + if (block_ == Block::Thinking) + event(out, "content_block_delta", + json{ { "type", "content_block_delta" }, { "index", n_blocks_ - 1 }, + { "delta", { { "type", "signature_delta" }, { "signature", "" } } } }); + event(out, "content_block_stop", json{ { "type", "content_block_stop" }, { "index", n_blocks_ - 1 } }); + block_ = Block::None; +} + +std::string AnthropicStream::emit(const std::vector& ev) { + std::string out; + for (const ReplyDelta& d : ev) { + if (!absorb(d)) continue; + switch (d.kind) { + case ReplyDelta::Reasoning: + if (block_ != Block::Thinking) open(out, Block::Thinking, nullptr); + event(out, "content_block_delta", + json{ { "type", "content_block_delta" }, { "index", n_blocks_ - 1 }, + { "delta", { { "type", "thinking_delta" }, { "thinking", d.text } } } }); + break; + case ReplyDelta::Content: { + /* The prefill is the caller's own text; Anthropic's API answers what follows it. */ + std::string_view text = d.text; + if (!skip_.empty()) { + const size_t n = std::min(skip_.size(), text.size()); + if (skip_.compare(0, n, text.substr(0, n)) == 0) { + skip_.erase(0, n); + text.remove_prefix(n); + } else { + skip_.clear(); + } + } + if (text.empty()) break; + if (block_ != Block::Text) open(out, Block::Text, nullptr); + event(out, "content_block_delta", + json{ { "type", "content_block_delta" }, { "index", n_blocks_ - 1 }, + { "delta", { { "type", "text_delta" }, { "text", std::string(text) } } } }); + break; + } + case ReplyDelta::CallBegin: + open(out, Block::Tool, &last_.tool_calls.back()); + break; + case ReplyDelta::CallArgs: + event(out, "content_block_delta", + json{ { "type", "content_block_delta" }, { "index", n_blocks_ - 1 }, + { "delta", { { "type", "input_json_delta" }, { "partial_json", d.text } } } }); + break; + case ReplyDelta::CallEnd: + close(out); + break; + } + } + return out; +} + +std::string AnthropicStream::final_chunk(Finish f, const TimingsOut&, const UsageOut& u) { + std::string out = push(std::string_view(), true); + close(out); + const char* sr = anthropic_stop_reason(*r_, adjusted_finish(f), stop_word_); + json delta = { { "stop_reason", sr }, + { "stop_sequence", std::strcmp(sr, "stop_sequence") == 0 ? json(stop_word_) + : json(nullptr) } }; + event(out, "message_delta", + json{ { "type", "message_delta" }, { "delta", delta }, { "usage", anthropic_usage(u) } }); + event(out, "message_stop", json{ { "type", "message_stop" } }); + return out; +} + +std::string AnthropicStream::error_chunk(const ApiError& e, const TimingsOut&, const UsageOut&) { + return "event: error\ndata: " + anthropic_error_body(e) + "\n\n"; +} + +/* ================================================================== OpenAI's Responses API */ + +namespace { + +/* An input content part as the chat path's: text, or an image as an image_url. */ +int responses_part(const json& p, json* out, ApiError* err) { + if (!p.is_object()) { *err = err_bad("input[].content[]", "expected an object"); return RAD_E_INVAL; } + std::string type; + if (!member_str(p, "type", "input[].content[].type", &type, err)) return RAD_E_INVAL; + if (type == "input_text" || type == "output_text" || type == "text") { + std::string text; + if (!member_str(p, "text", "input[].content[].text", &text, err)) return RAD_E_INVAL; + *out = json{ { "type", "text" }, { "text", text } }; + return RAD_OK; + } + if (type == "input_image") { + const json u = p.contains("image_url") ? p.at("image_url") : json(); + std::string url; + if (u.is_string()) url = u.get(); + else if (u.is_object() && !member_str(u, "url", "input[].content[].image_url.url", &url, err)) + return RAD_E_INVAL; + *out = json{ { "type", "image_url" }, { "image_url", { { "url", url } } } }; + return RAD_OK; + } + *err = err_unsupported("input[].content[].type", + "a content part of type \"" + type + "\" is not served"); + return RAD_E_UNSUPPORTED; +} + +/* The id a response item carries for a call, from the call id this server minted ("call_..."). */ +std::string fc_id(const std::string& call_id) { + return "fc_" + (call_id.rfind("call_", 0) == 0 ? call_id.substr(5) : call_id); +} + +json response_usage(const UsageOut& u) { + return json{ { "input_tokens", u.prompt }, + { "input_tokens_details", { { "cached_tokens", u.cached } } }, + { "output_tokens", u.completion }, + { "output_tokens_details", { { "reasoning_tokens", std::max(u.reasoning, 0) } } }, + { "total_tokens", u.prompt + u.completion } }; +} + +json reasoning_item(const std::string& id, const std::string& text, const char* status) { + return json{ { "id", id }, { "type", "reasoning" }, { "summary", json::array() }, + { "content", json::array({ json{ { "type", "reasoning_text" }, { "text", text } } }) }, + { "status", status } }; +} +json text_part(const std::string& text) { + return json{ { "type", "output_text" }, { "text", text }, { "annotations", json::array() }, + { "logprobs", json::array() } }; +} +json message_item(const std::string& id, const std::string& text, const char* status) { + return json{ { "id", id }, { "type", "message" }, { "role", "assistant" }, { "status", status }, + { "content", text.empty() && std::strcmp(status, "in_progress") == 0 + ? json::array() : json::array({ text_part(text) }) } }; +} +json call_item(const ToolCall& tc, const char* status) { + return json{ { "id", fc_id(tc.id) }, { "type", "function_call" }, { "call_id", tc.id }, + { "name", tc.name }, { "arguments", tc.arguments }, { "status", status } }; +} + +/* The response object, around its output items, with the request fields it echoes. */ +json response_object(const OaiRequest& r, const char* status, const json& output, + const UsageOut* u, const char* incomplete) { + json o = r.echo_json.empty() ? json::object() : json::parse(r.echo_json, nullptr, false); + if (!o.is_object()) o = json::object(); + o["id"] = r.id; + o["object"] = "response"; + o["created_at"] = r.created; + o["status"] = status; + o["model"] = r.model; + o["output"] = output; + o["error"] = nullptr; + o["incomplete_details"] = incomplete ? json{ { "reason", incomplete } } : json(nullptr); + if (u) o["usage"] = response_usage(*u); + else o["usage"] = nullptr; + return o; +} + +} /* namespace */ + +int responses_to_chat(const std::string& body, const OaiLimits& lim, std::string* chat, + std::string* echo, ApiError* err) { + json b; + RAD_TRY(parse_request_object(body, lim, &b, err)); + auto prev = b.find("previous_response_id"); + if (prev != b.end() && prev->is_string() && !prev->get().empty()) { + *err = err_unsupported("previous_response_id", "responses are not stored on this server; " + "send the conversation as `input`"); + return RAD_E_UNSUPPORTED; + } + /* WHAT A RESPONSE OBJECT CANNOT CARRY is refused, not computed and dropped: several choices + * (a response is one), and logprobs, which the Responses API reports per output_text part -- + * a split of the reply's tokens this server does not make. */ + { + int64_t n = 1; + if (!get_int(b, "n", &n, err)) return RAD_E_INVAL; + if (n != 1) { + *err = err_unsupported("n", "a response is one reply; send one request a reply"); + return RAD_E_UNSUPPORTED; + } + bool lp = false; + int64_t top = 0, np = -1; + if (!get_bool(b, "logprobs", &lp, err) || !get_int(b, "top_logprobs", &top, err) || + !get_int(b, "n_probs", &np, err)) + return RAD_E_INVAL; + const char* asked = lp ? "logprobs" : top > 0 ? "top_logprobs" : np > 0 ? "n_probs" : nullptr; + auto inc = b.find("include"); + if (inc != b.end() && inc->is_array()) + for (const json& i : *inc) + if (i == "message.output_text.logprobs") asked = "include"; + if (asked) { + *err = err_unsupported(asked, "logprobs are not served on /v1/responses; " + "/v1/chat/completions serves them"); + return RAD_E_UNSUPPORTED; + } + } + /* EVERY FIELD THE RESPONSES API DOES NOT DEFINE PASSES THROUGH to the chat request, as + * llama-server passes it: a client that adds chat_template_kwargs or top_k to a Responses + * request means them. The Responses API's own fields are translated below, and the chat + * stream's own extras -- the usage chunk and the prompt progress chunks, which a Responses + * stream has no frame for -- are dropped: response.completed carries the usage. */ + json o = b; + for (const char* k : { "input", "instructions", "tools", "tool_choice", "max_output_tokens", + "reasoning", "text", "previous_response_id", "store", "metadata", + "include", "truncation", "background", "conversation", "prompt", + "stream_options", "return_progress", "logprobs", "top_logprobs", + "n_probs" }) + o.erase(k); + json msgs = json::array(); + if (b.contains("instructions") && b.at("instructions").is_string()) + msgs.push_back(json{ { "role", "system" }, { "content", b.at("instructions") } }); + + auto in = b.find("input"); + if (in == b.end()) { *err = err_bad("input", "is required"); return RAD_E_INVAL; } + auto last_assistant = [&]() -> json* { + return !msgs.empty() && msgs.back().at("role") == "assistant" ? &msgs.back() : nullptr; + }; + if (in->is_string()) { + msgs.push_back(json{ { "role", "user" }, { "content", *in } }); + } else if (in->is_array()) { + for (const json& item : *in) { + if (!item.is_object()) { *err = err_bad("input[]", "expected an object"); return RAD_E_INVAL; } + std::string type = item.contains("role") ? "message" : ""; + if (!member_str(item, "type", "input[].type", &type, err)) return RAD_E_INVAL; + if (type == "message") { + std::string role; + if (!member_str(item, "role", "input[].role", &role, err)) return RAD_E_INVAL; + const json content = item.contains("content") ? item.at("content") : json(""); + if (role == "assistant") { + /* A turn the model gave earlier: its text, joined to a reasoning item or a + * call of the same turn that came before it. */ + std::string text; + if (content.is_string()) { + text = content.get(); + } else if (content.is_array()) { + for (const json& p : content) { + std::string t; + if (!member_str(p, "text", "input[].content[].text", &t, err)) + return RAD_E_INVAL; + text += t; + } + } + if (json* prev = last_assistant()) { + (*prev)["content"] = prev->at("content").get() + text; + } else { + msgs.push_back(json{ { "role", "assistant" }, { "content", text } }); + } + continue; + } + if (role != "user" && role != "system" && role != "developer") { + *err = err_bad("input[].role", "must be user, system, developer or assistant"); + return RAD_E_INVAL; + } + json parts = json::array(); + if (content.is_string()) { + parts = content; + } else if (content.is_array()) { + for (const json& p : content) { + json part; + RAD_TRY(responses_part(p, &part, err)); + parts.push_back(std::move(part)); + } + } + msgs.push_back(json{ { "role", role }, { "content", parts } }); + } else if (type == "function_call") { + std::string id, name, args = "{}"; + if (!member_str(item, "call_id", "input[].call_id", &id, err) || + !member_str(item, "name", "input[].name", &name, err) || + !member_str(item, "arguments", "input[].arguments", &args, err)) + return RAD_E_INVAL; + json call = { { "id", id }, { "type", "function" }, + { "function", { { "name", name }, { "arguments", args } } } }; + json* prev = last_assistant(); + if (!prev) { + msgs.push_back(json{ { "role", "assistant" }, { "content", "" } }); + prev = &msgs.back(); + } + (*prev)["tool_calls"].push_back(std::move(call)); + } else if (type == "function_call_output") { + const json out = item.contains("output") ? item.at("output") : json(""); + json content; + if (out.is_string()) { + content = out; + } else if (out.is_array()) { + content = json::array(); + for (const json& p : out) { + json part; + RAD_TRY(responses_part(p, &part, err)); + content.push_back(std::move(part)); + } + } else { + content = ""; + } + std::string id; + if (!member_str(item, "call_id", "input[].call_id", &id, err)) return RAD_E_INVAL; + msgs.push_back(json{ { "role", "tool" }, { "tool_call_id", id }, { "content", content } }); + } else if (type == "reasoning") { + /* The reasoning of a turn the model gave earlier, which a template that keeps + * reasoning across turns renders. Its text is the content, else the summary. */ + std::string text; + for (const char* k : { "content", "summary" }) { + if (!text.empty() || !item.contains(k) || !item.at(k).is_array()) continue; + for (const json& p : item.at(k)) { + std::string t; + if (!member_str(p, "text", "input[].content[].text", &t, err)) return RAD_E_INVAL; + text += t; + } + } + msgs.push_back(json{ { "role", "assistant" }, { "content", "" }, + { "reasoning_content", text } }); + } else { + *err = err_unsupported("input[].type", + "an input item of type \"" + type + "\" is not served"); + return RAD_E_UNSUPPORTED; + } + } + } else { + *err = err_bad("input", "expected a string or an array of items"); + return RAD_E_INVAL; + } + o["messages"] = std::move(msgs); + + /* Function tools only. Built-in tools (web search, file search, computer use) and freeform + * custom tools have no chat-completions counterpart; the model is offered what it can call. */ + json echo_tools = json::array(); + auto tit = b.find("tools"); + if (tit != b.end() && tit->is_array()) { + json tools = json::array(); + for (const json& t : *tit) { + if (str_or(t, "type") != "function") { + RAD_DEBUG("responses: tool of type \"%s\" left out: no chat equivalent", + str_or(t, "type", "?").c_str()); + continue; + } + std::string name; + if (!member_str(t, "name", "tools[].name", &name, err)) return RAD_E_INVAL; + json fn = { { "name", name }, + { "parameters", t.contains("parameters") ? t.at("parameters") : json::object() } }; + if (t.contains("description")) fn["description"] = t.at("description"); + tools.push_back(json{ { "type", "function" }, { "function", fn } }); + echo_tools.push_back(t); + } + if (!tools.empty()) o["tools"] = std::move(tools); + } + auto tc = b.find("tool_choice"); + if (tc != b.end() && !tc->is_null()) { + std::string type = "auto", name; + if (tc->is_object() && (!member_str(*tc, "type", "tool_choice.type", &type, err) || + !member_str(*tc, "name", "tool_choice.name", &name, err))) + return RAD_E_INVAL; + if (!tc->is_object()) o["tool_choice"] = *tc; + else if (type == "function") + o["tool_choice"] = json{ { "type", "function" }, { "function", { { "name", name } } } }; + else o["tool_choice"] = type; + } + if (b.contains("max_output_tokens")) o["max_tokens"] = b.at("max_output_tokens"); + auto re = b.find("reasoning"); + if (re != b.end() && re->is_object() && re->contains("effort") && re->at("effort").is_string()) + o["reasoning_effort"] = re->at("effort"); + /* Structured output: text.format is response_format under another name. */ + auto tx = b.find("text"); + if (tx != b.end() && tx->is_object() && tx->contains("format") && tx->at("format").is_object()) { + const json& f = tx->at("format"); + std::string type = "text", name = "schema"; + if (!member_str(f, "type", "text.format.type", &type, err) || + !member_str(f, "name", "text.format.name", &name, err)) + return RAD_E_INVAL; + if (type == "json_schema") + o["response_format"] = json{ { "type", "json_schema" }, + { "json_schema", { { "name", name }, + { "schema", f.contains("schema") ? f.at("schema") : json::object() } } } }; + else if (type == "json_object") + o["response_format"] = json{ { "type", "json_object" } }; + } + *chat = o.dump(); + + json e; + e["instructions"] = b.contains("instructions") ? b.at("instructions") : json(nullptr); + e["tools"] = echo_tools; + e["tool_choice"] = b.contains("tool_choice") ? b.at("tool_choice") : json("auto"); + e["parallel_tool_calls"] = !b.contains("parallel_tool_calls") || b.at("parallel_tool_calls") != false; + e["temperature"] = b.contains("temperature") ? b.at("temperature") : json(nullptr); + e["top_p"] = b.contains("top_p") ? b.at("top_p") : json(nullptr); + e["max_output_tokens"] = b.contains("max_output_tokens") ? b.at("max_output_tokens") : json(nullptr); + e["text"] = b.contains("text") ? b.at("text") : json{ { "format", { { "type", "text" } } } }; + e["reasoning"] = b.contains("reasoning") ? b.at("reasoning") + : json{ { "effort", nullptr }, { "summary", nullptr } }; + e["metadata"] = b.contains("metadata") ? b.at("metadata") : json::object(); + e["previous_response_id"] = nullptr; + e["store"] = false; + e["truncation"] = "disabled"; + if (echo) *echo = e.dump(); + return RAD_OK; +} + +std::string responses_body(const OaiRequest& r, const ChoiceOut& c, const UsageOut& u) { + json out = json::array(); + if (!c.msg.reasoning.empty()) + out.push_back(reasoning_item(random_id("rs_"), c.msg.reasoning, "completed")); + if (!c.msg.content.empty()) + out.push_back(message_item(random_id("msg_"), c.msg.content, "completed")); + for (const ToolCall& tc : c.msg.tool_calls) out.push_back(call_item(tc, "completed")); + const bool cut = c.finish == Finish::Length; + return response_object(r, cut ? "incomplete" : "completed", out, &u, + cut ? "max_output_tokens" : nullptr).dump(); +} + +ResponsesStream::ResponsesStream(const OaiRequest& r, int index, const IReplyParser* parser) + : ReplyStream(r, index, parser), r_(&r) {} + +void ResponsesStream::event(std::string& out, const char* type, json data) { + data["type"] = type; + data["sequence_number"] = seq_++; + out += "event: "; + out += type; + out += "\ndata: "; + out += data.dump(); + out += "\n\n"; +} + +json ResponsesStream::response(const char* status) const { + const bool done = std::strcmp(status, "in_progress") != 0; + json items = json::array(); + for (const std::string& it : items_) items.push_back(json::parse(it)); + return response_object(*r_, status, items, done ? &usage_ : nullptr, incomplete_); +} + +std::string ResponsesStream::first_chunk() { + std::string out; + event(out, "response.created", json{ { "response", response("in_progress") } }); + event(out, "response.in_progress", json{ { "response", response("in_progress") } }); + return out; +} + +void ResponsesStream::open(std::string& out, Item k, size_t call) { + close(out); + item_ = k; + text_.clear(); + const int64_t at = (int64_t)items_.size(); + if (k == Item::Reasoning) { + item_id_ = random_id("rs_"); + json it = reasoning_item(item_id_, "", "in_progress"); + it["content"] = json::array(); + event(out, "response.output_item.added", json{ { "output_index", at }, { "item", it } }); + event(out, "response.content_part.added", + json{ { "item_id", item_id_ }, { "output_index", at }, { "content_index", 0 }, + { "part", { { "type", "reasoning_text" }, { "text", "" } } } }); + } else if (k == Item::Message) { + item_id_ = random_id("msg_"); + event(out, "response.output_item.added", + json{ { "output_index", at }, { "item", message_item(item_id_, "", "in_progress") } }); + event(out, "response.content_part.added", + json{ { "item_id", item_id_ }, { "output_index", at }, { "content_index", 0 }, + { "part", text_part("") } }); + } else { + call_ = call; + const ToolCall& tc = last_.tool_calls[call]; + item_id_ = fc_id(tc.id); + event(out, "response.output_item.added", + json{ { "output_index", at }, { "item", call_item(tc, "in_progress") } }); + } +} + +void ResponsesStream::close(std::string& out) { + if (item_ == Item::None) return; + const int64_t at = (int64_t)items_.size(); + json item; + if (item_ == Item::Reasoning) { + event(out, "response.reasoning_text.done", + json{ { "item_id", item_id_ }, { "output_index", at }, { "content_index", 0 }, + { "text", text_ } }); + event(out, "response.content_part.done", + json{ { "item_id", item_id_ }, { "output_index", at }, { "content_index", 0 }, + { "part", { { "type", "reasoning_text" }, { "text", text_ } } } }); + item = reasoning_item(item_id_, text_, "completed"); + } else if (item_ == Item::Message) { + event(out, "response.output_text.done", + json{ { "item_id", item_id_ }, { "output_index", at }, { "content_index", 0 }, + { "text", text_ }, { "logprobs", json::array() } }); + event(out, "response.content_part.done", + json{ { "item_id", item_id_ }, { "output_index", at }, { "content_index", 0 }, + { "part", text_part(text_) } }); + item = message_item(item_id_, text_, "completed"); + } else { + const ToolCall& tc = last_.tool_calls[call_]; + event(out, "response.function_call_arguments.done", + json{ { "item_id", item_id_ }, { "output_index", at }, { "arguments", tc.arguments } }); + item = call_item(tc, "completed"); + } + event(out, "response.output_item.done", json{ { "output_index", at }, { "item", item } }); + items_.push_back(item.dump()); + item_ = Item::None; +} + +std::string ResponsesStream::emit(const std::vector& ev) { + std::string out; + for (const ReplyDelta& d : ev) { + if (!absorb(d)) continue; + const int64_t at = (int64_t)items_.size(); + switch (d.kind) { + case ReplyDelta::Reasoning: + if (item_ != Item::Reasoning) open(out, Item::Reasoning, 0); + text_ += d.text; + event(out, "response.reasoning_text.delta", + json{ { "item_id", item_id_ }, { "output_index", (int64_t)items_.size() }, + { "content_index", 0 }, { "delta", d.text } }); + break; + case ReplyDelta::Content: + if (item_ != Item::Message) open(out, Item::Message, 0); + text_ += d.text; + event(out, "response.output_text.delta", + json{ { "item_id", item_id_ }, { "output_index", (int64_t)items_.size() }, + { "content_index", 0 }, { "delta", d.text }, { "logprobs", json::array() } }); + break; + case ReplyDelta::CallBegin: + open(out, Item::Call, last_.tool_calls.size() - 1); + break; + case ReplyDelta::CallArgs: + event(out, "response.function_call_arguments.delta", + json{ { "item_id", item_id_ }, { "output_index", at }, { "delta", d.text } }); + break; + case ReplyDelta::CallEnd: + close(out); + break; + } + } + return out; +} + +std::string ResponsesStream::final_chunk(Finish f, const TimingsOut&, const UsageOut& u) { + std::string out = push(std::string_view(), true); + close(out); + usage_ = u; + const bool cut = adjusted_finish(f) == Finish::Length; + incomplete_ = cut ? "max_output_tokens" : nullptr; + event(out, cut ? "response.incomplete" : "response.completed", + json{ { "response", response(cut ? "incomplete" : "completed") } }); + return out; +} + +std::string ResponsesStream::error_chunk(const ApiError& e, const TimingsOut&, const UsageOut& u) { + std::string out; + usage_ = u; + json resp = response("failed"); + resp["error"] = json{ { "code", "server_error" }, { "message", e.message } }; + event(out, "response.failed", json{ { "response", std::move(resp) } }); return out; } diff --git a/core/server/oai.h b/core/server/oai.h index b70a9032..642a65e8 100644 --- a/core/server/oai.h +++ b/core/server/oai.h @@ -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 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 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 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 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 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& 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& 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 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 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& 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& 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& 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 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; diff --git a/core/server/server.cpp b/core/server/server.cpp index 224b6ea5..4b5852f0 100644 --- a/core/server/server.cpp +++ b/core/server/server.cpp @@ -3,6 +3,7 @@ #include #include "json_partial.h" #include "rad_internal.h" +#include "text/tokenizer.h" #include @@ -19,12 +20,13 @@ namespace server { struct Server::Generation { std::shared_ptr sink; std::unique_ptr detok; - std::unique_ptr delta; /* chat streaming only */ + std::unique_ptr 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 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 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* gens, ApiEr g.index = idx; g.prompt_index = (int)p; g.sink = std::make_shared(); - 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* 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& 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& 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 kept_logprobs(const std::vector& lp, size_t cut) { + return std::vector(lp.begin(), lp.begin() + (long)lp_before_cut(lp, 0, cut)); +} + bool Server::pump(std::vector& 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 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& 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& 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& 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(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{ "penalties", "dry", "top_k", "top_p", "min_p", "typ_p", "xtc", "temperature" } + : std::vector{ "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{}; + 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 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(); 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(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), >); - 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(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), >); + 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 names) { + for (const char* n : names) { + const std::vector 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▁begin|>", "
", "▁
", "<|code_prefix|>" });
+    const int32_t suf = special_token(tok, { "<|fim_suffix|>", "", "",
+                                             "<|fim▁hole|>", "", "▁", "<|code_suffix|>" });
+    const int32_t mid = special_token(tok, { "<|fim_middle|>", "", "",
+                                             "<|fim▁end|>", "", "▁", "<|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|>", "",
+                                             "", "" });
+    const int32_t sep = special_token(tok, { "<|file_sep|>", "<|fim_sep|>", "",
+                                             "", "" });
+
+    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* 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(), false, false);
+            return true;
+        }
+        if (it->is_array()) {
+            for (const json& v : *it) {
+                int32_t id = 0;
+                if (v.is_string()) {
+                    const std::vector t = tok.encode(v.get(), 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 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 extra;
+    if (rep >= 0) {
+        extra.push_back(rep);
+        const std::vector 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() : "tmp";
+            std::vector 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(),
+                           false, false);
+            extra.insert(extra.end(), t.begin(), t.end());
+        }
+    }
+    if (sep >= 0) {
+        extra.push_back(sep);
+        const std::vector 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();
+    }
+    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(opt_.max_ctx - fixed - reserve, 0);
+        if ((int64_t)extra.size() > room) extra.erase(extra.begin(), extra.end() - room);
+    }
+    std::vector 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);
diff --git a/core/server/server.h b/core/server/server.h
index faed5255..3f04865d 100644
--- a/core/server/server.h
+++ b/core/server/server.h
@@ -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. */
diff --git a/core/server/sink.cpp b/core/server/sink.cpp
index ae76ed18..85a06d57 100644
--- a/core/server/sink.cpp
+++ b/core/server/sink.cpp
@@ -1,5 +1,6 @@
 #include "sink.h"
 
+#include 
 #include 
 #include 
 
@@ -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;
 }
diff --git a/core/server/sink.h b/core/server/sink.h
index 15cd5b35..dd047812 100644
--- a/core/server/sink.h
+++ b/core/server/sink.h
@@ -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  n_prompt_{0};
     std::atomic  n_cached_{0};
-    bool                  has_logprobs_ = false;
+    std::atomic  prog_done_{-1};
+    std::atomic  prog_total_{0};
+    std::atomic  prog_cached_{0};
+    std::vector  alts_;                 /* [capacity * alt_w_], parallel to ring_ */
+    std::vector  alt_n_;                /* [capacity] */
+    int                   alt_w_ = 0;
     std::vector    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(s)->push(token, logprob) : true;
+inline bool sink_push(void* s, int32_t token, const TokenLogprobs* lp = nullptr) {
+    return s ? static_cast(s)->push(token, lp) : true;
 }
 inline void sink_finish(void* s, Finish f) {
     if (s) static_cast(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(s)->mark_admitted();
 }
+inline void sink_prompt_progress(void* s, int32_t processed, int32_t total, int32_t cached) {
+    if (s) static_cast(s)->set_prompt_progress(processed, total, cached);
+}
 inline void sink_drafts(void* s, int32_t n, int32_t accepted) {
     if (s) static_cast(s)->add_drafts(n, accepted);
 }
diff --git a/core/text/chat.cpp b/core/text/chat.cpp
index 66ec8c77..5b781a07 100644
--- a/core/text/chat.cpp
+++ b/core/text/chat.cpp
@@ -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 {
diff --git a/core/text/chat.h b/core/text/chat.h
index 347f61d7..6192f20a 100644
--- a/core/text/chat.h
+++ b/core/text/chat.h
@@ -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;
diff --git a/core/text/tokenizer.cpp b/core/text/tokenizer.cpp
index 4275ba7e..562f22cb 100644
--- a/core/text/tokenizer.cpp
+++ b/core/text/tokenizer.cpp
@@ -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 {};
 
diff --git a/core/text/tokenizer.h b/core/text/tokenizer.h
index e1e00c7c..f73eff40 100644
--- a/core/text/tokenizer.h
+++ b/core/text/tokenizer.h
@@ -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
diff --git a/data/recipes/q38-27b-fp8block-df2.recipe b/data/recipes/q38-27b-fp8block-df2.recipe
new file mode 100644
index 00000000..37254d9c
--- /dev/null
+++ b/data/recipes/q38-27b-fp8block-df2.recipe
@@ -0,0 +1,40 @@
+# q38-27b-fp8block-df2.recipe -- a bf16 Qwen3.8-27B checkpoint (the base model's bf16 release or a
+# finetune of it) as block fp8 with the DFlash2 drafter, the same weights in the same form as
+# Qwen's own FP8 release, so it serves exactly as q38-27b-fp8-df2.rad does.
+#
+#   rad-convert  --draft-model  \
+#       --recipe data/recipes/q38-27b-fp8block-df2.recipe \
+#       --set quantization_config.quant_method=fp8 --set quantization_config.fmt=e4m3 \
+#       --set "quantization_config.weight_block_size=128 128" \
+#       --set quantization_config.activation_scheme=dynamic -o model.rad
+#
+# The --set keys state the format the container is in, as Qwen's FP8 checkpoint's own config does:
+# they are what selects qwen35_fp8 to serve it, where a bf16 checkpoint selects qwen35.
+#
+# The trunk's linears -- attention q/gate, k, v and output, the delta net's qkv/z and output
+# projections, and the MLP's gate/up and down -- as E4M3 with one bf16 scale a 128x128 block,
+# rounded to nearest: the set and the format Qwen's FP8 checkpoint ships (its quantization_config:
+# fp8, e4m3, weight_block_size [128, 128], bf16 scales). Every fused weight's pieces end on a
+# 128-row boundary, so a block never spans two of them. The delta net's a/b projection, the
+# norms, the embedding and the vision tower stay bf16, as there. The lm_head and the drafter are
+# q38-27b-fp8-df2.recipe's.
+
+blk.*.attn_qg.weight                 rtn  codes=fp8_e4m3 block=128x128 scale=bf16
+blk.*.attn_k.weight                  rtn  codes=fp8_e4m3 block=128x128 scale=bf16
+blk.*.attn_v.weight                  rtn  codes=fp8_e4m3 block=128x128 scale=bf16
+blk.*.attn_output.weight             rtn  codes=fp8_e4m3 block=128x128 scale=bf16
+blk.*.ssm_inz.weight                 rtn  codes=fp8_e4m3 block=128x128 scale=bf16
+blk.*.ssm_out.weight                 rtn  codes=fp8_e4m3 block=128x128 scale=bf16
+blk.*.ffn_gate_up.weight             rtn  codes=fp8_e4m3 block=128x128 scale=bf16
+blk.*.ffn_down.weight                rtn  codes=fp8_e4m3 block=128x128 scale=bf16
+
+output.weight                        rtn  codes=fp8_e4m3 block=128x128 scale=bf16
+dflash.draft_head.weight             rtn  codes=u2 zero=u8 group=128 scale=f16 rule=search
+
+dflash.fc.weight                     rtn  codes=fp4_e2m1 group=32 scale=e8m0
+dflash.blk.*.attn_q.weight           rtn  codes=fp4_e2m1 group=32 scale=e8m0
+dflash.blk.*.attn_k.weight           rtn  codes=fp4_e2m1 group=32 scale=e8m0
+dflash.blk.*.attn_v.weight           rtn  codes=fp4_e2m1 group=32 scale=e8m0
+dflash.blk.*.attn_output.weight      rtn  codes=fp4_e2m1 group=32 scale=e8m0
+dflash.blk.*.ffn_gate_up.weight      rtn  codes=fp4_e2m1 group=32 scale=e8m0
+dflash.blk.*.ffn_down.weight         rtn  codes=fp4_e2m1 group=32 scale=e8m0
diff --git a/data/recipes/swift15-w4nl64-i8-hc8m.recipe b/data/recipes/swift15-w4nl64-i8-hc8m.recipe
new file mode 100644
index 00000000..4b8cf14d
--- /dev/null
+++ b/data/recipes/swift15-w4nl64-i8-hc8m.recipe
@@ -0,0 +1,88 @@
+# swift15-w4nl64-i8-hc8m.recipe -- ukisai's Swift 1.5 finetune of Qwen3.8-Flash-Next by the
+# production recipe (qwen4exp-w4nl64-i8-hc8m.recipe), with the protected experts chosen from the
+# finetune's own recording. Every rule below the protected ones is that recipe's: the routed experts
+# as rotated u4 codes into the w4nl codebook with one E4M3 scale a (row, 64 of K) under a fixed f32
+# of 2^-13 (libr4d's w4nl64a8h), the codes chosen by GPTQ and three sweeps of coordinate descent;
+# sixteen protected experts plain bf16; the trunk's block linears and the lm_head int8, served W8A8;
+# the connections' mixing matrices and the MTP head's fc matrices E4M3; the n-gram table at one
+# fixed E4M3 scale.
+#
+# The base model's KL figures are not this model's; it has not been measured against its bf16 self.
+#
+#   CALIB=DIR rad-convert  \
+#       --recipe data/recipes/swift15-w4nl64-i8-hc8m.recipe -o swift15-w4nl64-i8lm.rad
+#
+# DIR holds the Grams recorded from the finetune's bf16 model at one million tokens of the
+# calibration corpus with the per-expert tap: each layer's pooled Grams and each expert's own down
+# Gram, side by side (docs/MOE-W4.md, "Calibration"). The finetune changed only the attention,
+# delta-net and shared-expert projections; its routed experts are the base model's bytes, so a
+# --reuse of the base container with --changed copies everything else that reads unchanged tensors
+# under unchanged rules, and quantises the experts again against these Grams.
+#
+# Everything not named here is served as the checkpoint holds it; the first rule that matches a
+# weight decides it.
+
+# The protected experts, by the base recipe's rule applied to the finetune's own recording: an
+# expert whose share of its layer's down-input energy is at least 3% and at least three times its
+# share of the routing, and on each half of the layer's experts an even count, by adding that
+# half's next most energetic expert. The finetune's attention drives the early layers' super
+# experts the base model never fired on this corpus -- layer 4's expert 108 carries 15.8% of its
+# layer's down-input energy from 0.18% of the routing, layer 2's 322 6.2% -- and layers 34 and 44
+# drop below the bar; layer 47's 445 carries 67%.
+blk.2.ffn_*_exps.322.weight          cast dtype=bf16
+blk.2.ffn_*_exps.413.weight          cast dtype=bf16
+blk.4.ffn_*_exps.108.weight          cast dtype=bf16
+blk.4.ffn_*_exps.168.weight          cast dtype=bf16
+blk.4.ffn_*_exps.373.weight          cast dtype=bf16
+blk.4.ffn_*_exps.426.weight          cast dtype=bf16
+blk.14.ffn_*_exps.169.weight         cast dtype=bf16
+blk.14.ffn_*_exps.212.weight         cast dtype=bf16
+blk.42.ffn_*_exps.43.weight          cast dtype=bf16
+blk.42.ffn_*_exps.124.weight         cast dtype=bf16
+blk.46.ffn_*_exps.290.weight         cast dtype=bf16
+blk.46.ffn_*_exps.392.weight         cast dtype=bf16
+blk.47.ffn_*_exps.122.weight         cast dtype=bf16
+blk.47.ffn_*_exps.143.weight         cast dtype=bf16
+blk.47.ffn_*_exps.399.weight         cast dtype=bf16
+blk.47.ffn_*_exps.445.weight         cast dtype=bf16
+
+# Every other routed expert, trunk and MTP layer alike: u4 codes into the w4nl table, rotated by
+# the 128-wide Hadamard, an E4M3 scale a group of 64 under the fixed 2^-13 searched for least error
+# as stored, the codes chosen by GPTQ against $CALIB and then swept three times by coordinate
+# descent. The experts' scales sit between 2^-15 and 2^-10.6, inside E4M3's normal range under
+# 2^-13 with four binades either side; one past its top would be held there and said on stderr.
+# The MTP layer has no recording and is rounded to nearest, which libquant says on stderr.
+blk.*.ffn_*_exps.*.weight            gptq table=w4nl group=64 scale=fp8_e4m3 scale2=f32 block2=*x* scale2_value=0.0001220703125 transform=fwht128 rule=search cd=3 calib=$CALIB
+
+# Every connection's two mixing matrices -- the 96 trunk connections, the final mixer and the MTP
+# head's three -- as E4M3 rows with an f32 scale a group of each row. A 128x128 block cannot cover
+# them: lowrank is 320, 2.5 blocks. Down is [320, 10240] and takes a scale every 128 columns; up is
+# [10240, 320] and takes four scales a row, 80 columns each.
+*_hc_down.weight                     rtn  codes=fp8_e4m3 group=128 scale=f32
+*_hc_up.weight                       rtn  codes=fp8_e4m3 group=80 scale=f32
+
+# The MTP head's fc_hidden and fc_embedding, the same rows. They only ever change the drafts.
+mtp.fc_hidden.weight                 rtn  codes=fp8_e4m3 group=128 scale=f32
+mtp.fc_embedding.weight              rtn  codes=fp8_e4m3 group=128 scale=f32
+
+# The trunk's block linears as int8, a scale per 128 columns of a row searched for least error.
+# The QSA indexer's projection is not one of them: its top-k is a hard choice between blocks, and
+# keeping it as the checkpoint holds it costs 20 MB.
+blk.*.attn_qg.weight                 rtn  codes=i8 group=128 scale=bf16 clamp=sym rule=search
+blk.*.attn_k.weight                  rtn  codes=i8 group=128 scale=bf16 clamp=sym rule=search
+blk.*.attn_v.weight                  rtn  codes=i8 group=128 scale=bf16 clamp=sym rule=search
+blk.*.attn_output.weight             rtn  codes=i8 group=128 scale=bf16 clamp=sym rule=search
+blk.*.ssm_inz.weight                 rtn  codes=i8 group=128 scale=bf16 clamp=sym rule=search
+blk.*.ssm_out.weight                 rtn  codes=i8 group=128 scale=bf16 clamp=sym rule=search
+blk.*.ffn_gate_up_shexp.weight       rtn  codes=i8 group=128 scale=bf16 clamp=sym rule=search
+blk.*.ffn_down_shexp.weight          rtn  codes=i8 group=128 scale=bf16 clamp=sym rule=search
+
+# The lm_head, int8 with a bf16 scale a row per 128 columns (logits_gemm_i8): at E4M3 it costs
+# ~0.6 points of top-1 on its own.
+output.weight                        rtn  codes=i8 group=128 scale=bf16 clamp=sym rule=search
+
+# The n-gram table at one fixed E4M3 scale; qwen4exp-w4.recipe says where the value comes from.
+blk.*.ple_ngram.weight               rtn  codes=fp8_e4m3 block=*x* scale=bf16 rule=fixed scale_value=1.99317932128906e-4
+
+# The MTP head's 2-bit draft head.
+mtp.draft_head.weight                rtn  codes=u2 zero=u8 group=128 scale=f16
diff --git a/deploy/compose/.env.example b/deploy/compose/.env.example
index d8f688db..5e2b5eb0 100644
--- a/deploy/compose/.env.example
+++ b/deploy/compose/.env.example
@@ -10,7 +10,8 @@ RADIANCE_MODELS=/srv/models/rad
 # Writable directory mounted at /data: the prefix cache's disk tier lives under it.
 RADIANCE_STATE=/srv/radiance
 
-# Every request but /health, /ping and the dashboard page must carry `Authorization: Bearer `.
+# Every request but /health, /ping and the dashboard page must carry `Authorization: Bearer `
+# (or `X-Api-Key: `).
 RADIANCE_API_KEY=
 
 # The port the server listens on.
diff --git a/docs/GUIDE.md b/docs/GUIDE.md
index 7e4097bb..f7e7a529 100644
--- a/docs/GUIDE.md
+++ b/docs/GUIDE.md
@@ -66,7 +66,9 @@ lifts. There is nothing to `apt install` beyond a toolchain.
 **A machine with no GPU is a supported configuration.** The host backend is a real implementation,
 not a stub: the core, scheduler, planner, tokeniser, server and `libref` all run through it and
 the full test suite passes. It is slow, and it will not serve a production model — but it is a
-complete development and inspection environment.
+complete development and inspection environment. A build with ROCm, or the container image, runs
+the same host backend on a machine where no card is visible: the GPU library's kernels are left out
+there and every op takes its host kernel.
 
 ### 1.2 Build
 
@@ -201,8 +203,9 @@ library can change without a reconvert.
 
 **2. Kernels are plugins, and the order matters.** The engine resolves every op in the model
 against an ordered list of kernel libraries: first one that matches an op wins. `--kernels
-mylib,libref` states that order. With no list, the loader orders what it finds and puts a
-library that declares itself a reference implementation last.
+mylib,libref` names the libraries to use and their order; a library it leaves out is not loaded.
+With no list, every library found loads, and the loader puts one that declares itself a reference
+implementation last.
 
 Three ship with the tree:
 
@@ -251,6 +254,24 @@ skipped and a short one is continued. It also skips duplicate weight formats —
 
 Set `HF_TOKEN` for a gated or private repo. `HFGET_JOBS` sets concurrency (default 4).
 
+A complete fetch records each file's content key (its LFS sha256, or the size of a small file) in
+`.hfget-manifest`, so the next run also fetches a file that changed at the same size. The free-space
+check counts only what is still to fetch.
+
+**The server can do this itself.** `--model` takes a repo id where it would take a path:
+
+```sh
+radiance --model StillDeadcode/minicpm5-2b-fp8 --port 8000
+```
+
+It runs the same script (installed beside the binary, in `libexec/radiance/`) into
+`--download-dir//` before bring-up, then serves the one `.rad` at the repo's top level,
+or the directory as a checkpoint (§3.4) when it holds none. A repo with several containers is
+refused by name; pass the file. Every start checks the hub and fetches what changed. A start that
+cannot read the listing, or whose update does not fit, serves the copy a complete earlier fetch
+left and says so; a transfer that fails part-way stops startup. A path that exists is always a
+path, and a name ending in `.rad`, `.safetensors`, `.gguf` or `.json` is never looked up.
+
 ### 3.2 Convert it
 
 ```sh
@@ -306,8 +327,20 @@ rad-convert $SRC -o out.rad --draft-model ~/models/openbmb/MiniCPM5-2B-DSpark
 
 # Re-quantise some weights and copy the rest from an earlier container
 rad-convert $SRC -o new.rad --recipe new.recipe --reuse old.rad
+
+# A bf16 Qwen3.8-27B -- the base release or a finetune of it -- as Qwen's block fp8: the recipe
+# writes the linears, and --set states the format, which is what selects the fp8 plugin
+rad-convert ~/models/ukisai/Swift-1.5-Qwen3.8-27b -o swift-27b-fp8.rad \
+    --draft-model ~/models/z-lab/Qwen3.8-27B-DFlash2 --recipe data/recipes/q38-27b-fp8block-df2.recipe \
+    --set quantization_config.quant_method=fp8 --set quantization_config.fmt=e4m3 \
+    --set "quantization_config.weight_block_size=128 128" --set quantization_config.activation_scheme=dynamic
 ```
 
+A checkpoint directory's `model.safetensors.index.json` decides which shard each tensor is read
+from. A finetune that changed only some tensors can be assembled from them and the base model: its
+changed tensors in shards of their own, links to the base model's shards for the rest, and an index
+that points each name at its copy. A name two shards hold that no index entry settles is refused.
+
 The conversions of record live in `scripts/convfn.sh` and `scripts/convdspark.sh`, with their
 recipes in `data/recipes/`.
 
@@ -429,15 +462,15 @@ radiance --model m.rad --debug-placement    # just the placement plan
 
 ### 4.3 Memory: how the card gets split
 
-The card is split into **resident weights** and the **paged KV pool**. You can state the split
-outright:
+The card is split into **resident weights** and the **paged KV pool**, and the engine derives the
+split from the card and the model; no flag states either pool. What you move are its inputs:
+`--gpu-headroom-mib` leaves card space alone, `--max-model-len` and `--max-num-seqs` bound the
+cache, and `--host-pool-mib` decides which experts must stay on the card. The startup receipt
+prints every term. On a machine with no visible card (the host backend) half of RAM stands in for
+the card and is split the same way; the weights pool is then host memory, holding the weights a
+host kernel cannot read where the container stores them.
 
-```sh
-radiance --model m.rad --vram-weights-mib 24000 --vram-kv-mib 6000
-```
-
-or leave both unset and let the engine derive it from the card. The non-expert weights come off
-the top of what is claimed. The rest — the `elastic` line of the startup receipt — is shared by
+The non-expert weights come off the top of what is claimed. The rest — the `elastic` line of the startup receipt — is shared by
 the expert slab and the KV cache, and no flag divides it:
 
 - **The cache lends** under `--placement auto` or `expert_tiered`, without `--deterministic`, on a
@@ -457,12 +490,11 @@ off the card and gives the cache more.
 **An uneven world re-splits its cheaper ranks.** The split above is worked out once, for the rank
 whose cache costs most, and one block table serves every rank. Where a rank's cache costs less per
 token -- an attention-zero rank at `--tp 3` keeps no attention cache -- it gets, under
-`expert_tiered` with both pools derived, a KV pool that pages exactly the common token count and the
+`expert_tiered`, a KV pool that pages exactly the common token count and the
 difference in its weights pool, up to every one of its weights resident; the startup log names the
 rank and both sizes (`kv: rank N's cache costs ...`). It holds with or without a lending cache:
 under `--deterministic`, or on a device without virtual memory management, the bytes that rank
-would never page go to its experts all the same. A stated `--vram-kv-mib` or `--vram-weights-mib`
-is applied to every card unchanged, and a rank whose cache costs as much per token as the dearest
+would never page go to its experts all the same. A rank whose cache costs as much per token as the dearest
 rank's is never re-split -- which at `--tp 2` and `--tp 4` is every rank. A rank that costs less and
 keeps the common split says why on the same `kv: rank N's cache costs ...` line. Every rank still
 allocates its whole `--host-pool-mib`, a re-split rank whose weights all fit on the card included,
@@ -508,7 +540,7 @@ Related flags:
 --gpu-headroom-mib 96      # VRAM left unclaimed on every card
 --kv-cache-dtype fp8       # halve what a token of context costs (a real quantisation)
 --host-pool-mib 8192       # pinned host tier for weights
---embedding-placement ram   # the token embedding off the card (below)
+--embedding-placement vram  # keep the token embedding on the card (below)
 --ngram-placement ram       # an n-gram table in RAM instead of read from disk (below)
 --weights-disk-tier       # stream what fits neither from the container; needs O_DIRECT
 ```
@@ -518,25 +550,27 @@ never the whole table, so a tier below the card serves them at little or no cost
 
 | | `vram` | `ram` | `disk` |
 |---|---|---|---|
-| `--embedding-placement` | on the card, with the other weights | the pinned host pool, read over the link in place | refused |
+| `--embedding-placement` | on the card, with the other weights | pinned host memory of its own, read over the link in place (the default) | refused |
 | `--ngram-placement` | on the card, every card holding all of it | a copy in RAM made at load, read by the card over the link | read from the container through a row cache |
 
-Both default to `auto`, the fastest tier that has room once every other weight is placed. Startup
-prints what each resolved to and why. A tier the flag names that cannot be honoured stops the
-server with the reason; nothing falls back quietly.
+The embedding defaults to `ram`; the n-gram table defaults to `auto`, the fastest tier that has
+room once every other weight is placed. Startup prints what each resolved to and why. A tier the
+flag names that cannot be honoured stops the server with the reason.
 
 **The token embedding** is the largest model-level weight a dense model has -- 248320 x 5120 in bf16
-is 1.18 GiB a card at `--tp 2`. With `ram` it is placed in the pinned host pool before any strategy
-runs and the lookup reads it over the link in place, so it costs no VRAM and the KV pool gets its
-share. The pool must hold it (`--host-pool-mib`, every rank its own shard). `auto` keeps it on the
-card unless the card cannot hold the other weights with it, or a derived KV pool could then not
-hold one `--max-model-len` sequence; then it takes `ram` if the host pool can hold it. The table is
-found by what reads it: a model-level weight only `embed_lookup` reads. A head tied to it is read by
-a GEMM too and is never moved, since it would stream whole every step. `disk` is refused: the lookup
-writes activations the card reads, and a host kernel reading the container cannot write them.
+is 1.18 GiB a card at `--tp 2`. By default (`ram`) it is pinned in host memory of its own, every
+rank its own shard, on top of `--host-pool-mib` -- the experts' pool keeps all of that -- and the
+lookup reads a step's rows over the link in place, so the table costs no VRAM and the KV pool and
+the experts get its share. The table is found by what reads it: a model-level weight only
+`embed_lookup` reads. A head tied to it is read by a GEMM too and is never moved, since it would
+stream whole every step, so such a model keeps it on the card; so does a host that cannot pin it
+(available memory and memory cgroups, after the pools, with 4 GiB to spare). Startup says which
+and why. Naming `ram` turns either case into a refusal; `vram` keeps the table on the card.
+`disk` is refused: the lookup writes activations the card reads, and a host kernel reading the
+container cannot write them.
 
 ```sh
-radiance --model m.rad --tp 2 --host-pool-mib 1280 --embedding-placement ram
+radiance --model m.rad --tp 2 --embedding-placement vram   # the table on the cards
 ```
 
 **An n-gram table** (Qwen3.8-Flash-Next's is 47.7 GiB) is read a few rows a token, which is why it
@@ -793,11 +827,11 @@ single-sequence decode exact and compresses prefill, which is where the win is.
 
 At three and four ranks `wht6` selects a different lossy wire with the same floor: tiered int8
 over a two-shot all-reduce, both hops quantised (at three the shards are whole 32-element groups,
-one group uneven where the message does not divide). Eight ranks have no lossy wire, and `--tp 8 --tp-wire
-wht6` stops at startup naming the all-reduce it found no kernel for. The exact wire at four and
-eight ranks is one-shot up to 1 MiB a message and two-shot above it, which sends
-2·(ranks−1)/ranks of the message per rank instead of (ranks−1) times it; the two produce the same
-bits.
+one group uneven where the message does not divide). Eight ranks have no lossy wire, and
+`--tp 8 --tp-wire wht6` stops at startup naming the all-reduce it found no kernel for, and
+`--tp-wire exact`. The exact wire at three, four and eight ranks is one-shot up to 1 MiB a message
+and two-shot above it, which sends 2·(ranks−1)/ranks of the message per rank instead of
+(ranks−1) times it; the two produce the same bits.
 
 On a model with a gated residual (Qwen3.8-Flash-Next) the all-reduce rides inside the residual's
 write, with the MoE gather in front of it. At two ranks that holds on either wire: the rotated
@@ -984,9 +1018,10 @@ one line naming each one the command line moved.
 
 | flag | |
 |---|---|
-| `--model PATH` | the `.rad` container, or a checkpoint served as it stands (§3.4) (**required**) |
+| `--model PATH` | the `.rad` container, a checkpoint served as it stands (§3.4), or a Hugging Face repo id fetched before startup (§3.1) (**required**) |
+| `--download-dir DIR` | where a repo id is fetched to. Default `$XDG_CACHE_HOME/radiance/hf`, else `~/.cache/radiance/hf` |
 | `--radiance-home DIR` | where `kernels/` and `architectures/` live |
-| `--kernels LIST` | kernel plugin hierarchy, comma-separated, first wins |
+| `--kernels LIST` | the kernel libraries to use, comma-separated, first wins; a library not named is not loaded. Default: every library found |
 
 **Batch shape**
 
@@ -1002,11 +1037,9 @@ one line naming each one the command line moved.
 | flag | default | |
 |---|---|---|
 | `--gpu-headroom-mib N` | 96 | VRAM left unclaimed on every card |
-| `--vram-weights-mib N` | derive | the resident weight slab |
-| `--vram-kv-mib N` | derive | the paged KV pool |
 | `--kv-cache-dtype T` | bf16 | `bf16` or `fp8` |
 | `--host-pool-mib N` | 0 | pinned host tier (weights) |
-| `--embedding-placement WHERE` | auto | `auto`, `vram` or `ram`: the token embedding on the card or in the pinned host pool, read in place; `disk` is refused. See §4.3 |
+| `--embedding-placement WHERE` | ram | `ram` or `vram`: the token embedding pinned in host memory beside `--host-pool-mib` and read in place, or on the card. See §4.3 |
 | `--ngram-placement WHERE` | auto | `auto`, `vram`, `ram` or `disk`: an n-gram table on the card, as a copy in RAM made at load and read by the card, or read from the container. See §4.3 |
 | `--weights-disk-tier` | off | read weights that fit neither VRAM nor the host pool from the container (O_DIRECT); routed experts a layer at a time |
 
@@ -1052,7 +1085,7 @@ one line naming each one the command line moved.
 |---|---|---|
 | `--host ADDR` | 0.0.0.0 | listen address |
 | `--port N` | 8000 | listen port |
-| `--api-key KEY` | — | require `Authorization: Bearer KEY` on every request but `/health`, `/ping` and the dashboard page (§6.6) |
+| `--api-key KEY` | — | require `Authorization: Bearer KEY` or `X-Api-Key: KEY` on every request but `/health`, `/v1/health`, `/ping` and the dashboard page (§6.6) |
 | `--served-model-name NAME` | container's name | the model id `/v1/models` lists, the metrics carry and a response names when its request named none. A request may name any model; the one loaded serves it |
 | `--mm-max-patches N` | auto | patches one vision-encoder pass carries, and so the largest image (a patch is 16x16 pixels). `auto` is 16384 when the container carries a vision tower; 0 serves text only and keeps the tower off the card |
 | `--override-chat-template PATH` | container's | a Jinja chat template file served in place of the one the container carries. The reply format (reasoning markers, tool calls) is derived from it too, unless the architecture plugin declares one. An unreadable or empty file stops startup |
@@ -1133,14 +1166,19 @@ for a model that takes no images or video.
 | `POST /v1/chat/completions` | chat, with tools, reasoning and streaming |
 | `POST /v1/completions` | raw text completion |
 | `POST /v1/embeddings` | needs a model with an embedding head, else 501 |
+| `POST /v1/messages`, `POST /v1/messages/count_tokens` | Anthropic's Messages API, for Claude Code and the Anthropic SDKs — §5.9 |
+| `POST /v1/responses`, `POST /v1/responses/input_tokens` | OpenAI's Responses API, for Codex and the OpenAI SDKs' `responses` client — §5.9 |
+| `POST /completion`, `/completions`, `POST /infill` | llama-server's native completion and fill-in-the-middle, for llama.vim, llama.vscode and the clients built on llama-server's own API — §5.9 |
 | `GET /v1/models`, `/v1/models/:id` | what is loaded, with `max_model_len` (the context it serves) and `root` (the `--model` path), as vLLM reports them, and `capabilities` (the same object `/server_info` reports); `:id` answers the entry itself, as OpenAI's retrieve does |
-| `GET /health`, `/ping`, `POST /ping` | liveness |
+| `GET /health`, `/v1/health`, `/ping`, `POST /ping` | liveness |
 | `GET /load` | current load |
 | `GET /version` | server version |
-| `GET /props` | llama-server's props for the clients built against it: `n_ctx`, `total_slots`, `modalities`, the request defaults |
+| `GET /props` | llama-server's props for the clients built against it: `n_ctx`, `total_slots`, `modalities`, `model_path`, the chat template and its capabilities, `bos_token`/`eos_token`, and the request defaults under llama-server's names |
+| `POST /apply-template` | the prompt a chat request renders to, as llama-server answers it |
+| `POST /v1/chat/completions/input_tokens` | how many tokens that prompt is |
 | `GET /server_info` | the whole configuration of the running engine |
 | `GET /metrics` | Prometheus |
-| `POST /tokenize`, `POST /detokenize` | |
+| `POST /tokenize`, `POST /detokenize` | vLLM's shape (`prompt` or `messages` in, `prompt` out) and llama-server's (`content` in and out, `with_pieces`) |
 | `GET /get_tokenizer_info` | |
 | `POST /reset_prefix_cache` | drop every cached prefix |
 | `GET /` or `/dashboard` | the web dashboard |
@@ -1148,7 +1186,9 @@ for a model that takes no images or video.
 
 Method spellings follow vLLM's, including the ones that look odd: `/tokenize` is POST because its
 input is a body, and `/ping` answers both GET and POST because different load balancers send
-different ones.
+different ones. As llama-server does, `/chat/completions`, `/embeddings` and `/models` answer without the `/v1`
+too, for a client configured with the bare host as its base URL -- and `/completions` without it is
+llama-server's native completion, as it is there. A path nothing serves is a JSON 404.
 
 A text prompt to `/v1/completions`, `/v1/embeddings` or `/tokenize` reads the model's control
 tokens as tokens, as vLLM and llama.cpp do: a client that renders its own chat template can send
@@ -1282,7 +1322,8 @@ grammar: this model's chat template produced no grammar for it, so the constrain
 be enforced
 ```
 
-That is the refused-not-ignored rule (§5.8) doing its job: an unconstrained 200 would leave you
+That is §5.8's rule doing its job -- a field that would change the answer is honoured or
+refused, never dropped: an unconstrained 200 would leave you
 parsing free prose against a schema you were told was enforced. `/v1/completions` has no template
 in the way, so the same grammar works there — which is why the example above uses it.
 
@@ -1303,9 +1344,15 @@ curl -s http://localhost:8000/tokenize -H 'Content-Type: application/json' \
 
 curl -s http://localhost:8000/detokenize -H 'Content-Type: application/json' \
   -d '{"tokens":[15339,1917]}'
+
+curl -s http://localhost:8000/tokenize -H 'Content-Type: application/json' \
+  -d '{"content":"hello world","with_pieces":true}'          # llama-server's shape
 ```
 
-`/tokenize` takes `prompt` **or** `messages`, not both.
+`/tokenize` takes one of `prompt`, `messages` or llama-server's `content` (a string, or strings and
+token ids mixed, with its `add_special` and `parse_special` and their defaults); the `content`
+form answers `tokens` as llama-server does, as `{id, piece}` objects with `with_pieces`.
+`/detokenize` answers the text as both `prompt` (vLLM) and `content` (llama-server).
 
 **An embedding model** (EmbeddingGemma 2) serves `/v1/embeddings` and nothing else; completions and
 chat answer 501. One input is one vector, and an input is never split: it has to fit one step
@@ -1352,13 +1399,13 @@ inputs; a model that states a default prompt applies it when the request names n
 |---|---|
 | `model` | accepted and not enforced — one server serves one model |
 | `messages` / `prompt` / `input` | chat / completion / embedding |
-| `max_tokens`, `max_completion_tokens` | default: what the context leaves after the prompt (`--default-max-tokens`). Clamped to what the context leaves, and to `--max-tokens-cap`, rather than refused — see §5.8 |
+| `max_tokens`, `max_completion_tokens`, `n_predict` | default: what the context leaves after the prompt (`--default-max-tokens`); -1 is llama-server's "no limit", the same without the default. Clamped to what the context leaves, and to `--max-tokens-cap`, rather than refused — see §5.8 |
 | `temperature` | [0, 2] |
 | `top_p` | (0, 1] |
 | `top_k` | ≥ 0, 0 disables |
 | `min_p`, `typical_p` | |
 | `presence_penalty`, `frequency_penalty` | [-2, 2] |
-| `repetition_penalty`, `repeat_last_n` | |
+| `repetition_penalty` (or `repeat_penalty`), `repeat_last_n` | |
 | `xtc_probability`, `xtc_threshold` | |
 | `dry_multiplier`, `dry_base`, `dry_allowed_length`, `dry_penalty_last_n`, `dry_sequence_breakers` | |
 | `seed` | absent means "pick one" — **not** seed 0 |
@@ -1367,13 +1414,19 @@ inputs; a model that states a default prompt applies it when the request names n
 | `stop` | a string or an array; at most 64 strings of 4096 bytes (`--max-stop-strings`, `--max-stop-bytes`) |
 | `ignore_eos` | generate to `max_tokens` whatever the model emits |
 | `stream`, `stream_options.include_usage` | |
-| `logprobs`, `top_logprobs` | **not implemented** — refused, not returned as nulls. `/server_info` reports `logprobs: false` |
+| `timings_per_token`, `return_progress` | llama-server's: `timings` on every chunk, and `prompt_progress` chunks while the prompt is read |
+| `samplers` | llama-server's sampler order, names or letters. A stage it leaves out is off. The chain here is penalties, DRY, top-k, top-p, min-p, typical, XTC with temperature first (the default) or last (llama-server's default), so a list in either of those orders is honoured and any other is refused by name |
+| `session_id` | OpenRouter's conversation id: labels the conversation on `/sessions` and the dashboard |
+| `logprobs`, `top_logprobs`, `n_probs` | each generated token's logprob and up to 20 alternatives — see §5.11. Chat: `logprobs: true` with `top_logprobs` alternatives (0 when absent); completions: `logprobs: N`; any endpoint: llama-server's `n_probs: N`, which wins. Not with `echo` (the prompt's logprobs are not computed) |
 | `tools`, `tool_choice`, `parallel_tool_calls` | chat only. `tool_choice` is `auto`, `none`, `required` or `{"type":"function","function":{"name":...}}`; the last two hold the whole reply to calls (after the reasoning block), the named form to that one function, and cannot be combined with `response_format` or `grammar` |
 | `add_generation_prompt`, `chat_template_kwargs` | chat only |
+| `continue_final_message` | chat only. A conversation ending in an assistant message is continued rather than answered, as llama-server and the Anthropic API do -- the reply carries that message's text and what follows it. `true`, `"content"` or `"reasoning_content"` names it explicitly; `add_generation_prompt: true` opens a new turn instead |
+| `reasoning_format` | chat only, llama-server's: `none` keeps the reasoning in `content`; `auto` and `deepseek` split it into `reasoning_content`, the default |
 | `reasoning_effort`, `enable_thinking` | chat only. The levels are the template's (`capabilities.reasoning_efforts` on `/server_info`); `none` and `minimal` turn thinking off |
-| `thinking_token_budget`, `thinking_budget` | chat only. ≥ 0: the reasoning tokens after which the block is closed — see §5.2. Default `--thinking-token-budget`, else none |
+| `thinking_token_budget`, `thinking_budget`, `thinking_budget_tokens`, `reasoning_budget_tokens` | chat only. ≥ 0: the reasoning tokens after which the block is closed — see §5.2; -1 is none. Default `--thinking-token-budget`, else none |
 | `preserve_thinking` | chat only. The chat template variable of that name, as llama.cpp maps it; Qwen3.6 and later keep earlier turns' reasoning in the prompt with it |
-| `response_format` | chat only. Mutually exclusive with `grammar` |
+| `response_format`, `json_schema` | chat only. `json_schema` is llama-server's shorthand: the schema itself. Mutually exclusive with `grammar` |
+| `functions`, `function_call` | chat only: OpenAI's deprecated spellings of `tools` and `tool_choice`. The reply answers in the old shape too: one call at most, as `message.function_call` with `finish_reason: "function_call"`; the next turn's assistant `function_call` and `function` message are read as the call and its result |
 | `grammar` | a GBNF grammar directly. On chat it passes through the chat template and a template that drops it makes the request a refusal — see §5.5 |
 | `echo` | `/v1/completions` only |
 | `encoding_format` | `/v1/embeddings` only: `float` or `base64` |
@@ -1381,41 +1434,44 @@ inputs; a model that states a default prompt applies it when the request names n
 
 Any field the request omits keeps the deployment default (§4.9). A field the request names wins.
 
-### 5.8 A parameter this server does not implement is **refused**, not ignored
+### 5.8 What a field this server does not implement does
 
-This is the one place radiance deliberately differs from what an OpenAI client may expect, and it
-will be the first thing you hit pointing an existing client at it:
+Four kinds of field, and the rule they serve is that **a request that returns 200 had every field
+that could change its answer honoured**:
+
+- **Accepted** — the table above, in OpenAI's, vLLM's and llama-server's spellings.
+- **Inert** — fields that change nothing about the answer, accepted and ignored: OpenAI's and
+  OpenRouter's bookkeeping (`user`, `metadata`, `store`, `service_tier`, `safety_identifier`,
+  `prompt_cache_key`, `prediction`), and llama-server's knobs for its own speed and slots
+  (`cache_prompt`, `id_slot`, `n_cache_reuse`, `backend_sampling`, `reasoning_control`, `n_keep`,
+  `n_discard`, `speculative.*`, ...). The prefix cache and speculation here are the server's own
+  and never change the output.
+- **Guarded** — known, not implemented, and able to change the answer. llama-server's clients send
+  every one of them on every request at its off value, so each is accepted there and refused,
+  naming it, at any other:
 
 ```json
-{"error": {"message": "mirostat: mirostat is not one of the device samplers (spec 13)", ...}}
+{"error": {"message": "mirostat: mirostat is not one of the device samplers (spec 13); it is accepted only at 0, where it does nothing", ...}}
 ```
 
-The rule is that **a request that returns 200 means every field of it was honoured**. Silently
-dropping a sampler setting and answering 200 is how a deployment ends up serving a model at
-settings nobody chose.
+| guarded | accepted at | because |
+|---|---|---|
+| `logit_bias` | empty | the device sampler has no per-token bias stage |
+| `mirostat` | 0 | not one of the device samplers |
+| `top_n_sigma` | ≤ 0 | not one of the device samplers |
+| `dynatemp_range` | 0 | not one of the device samplers |
+| `min_keep` | 0 | the cuts keep no minimum count |
+| `post_sampling_probs` | false | logprobs are the raw distribution's; the sampler's are not returned |
+| `best_of` | 1 | not implemented |
+| `suffix` | empty | infilling through `/v1/completions` is not implemented |
+| `lora` | empty | explicitly out of scope |
+| `modalities`, `audio` | `["text"]`, null | output other than text is not implemented |
+| `n_indent`, `t_max_predict_ms`, `return_tokens` | 0, 0, false | not implemented |
+| `grammar_lazy`, `grammar_triggers`, `preserved_tokens` | off, empty | the chat format decides them |
 
-Three lists decide it:
-
-- **Accepted** — the table above.
-- **Inert** — OpenAI metadata that genuinely does nothing anywhere, accepted and ignored so the
-  official SDKs work: `user`, `metadata`, `store`, `service_tier`, `safety_identifier`,
-  `prompt_cache_key`.
-- **Refused with a reason** — known, not implemented, each named:
-
-| refused | because |
-|---|---|
-| `logit_bias` | the device sampler has no per-token bias stage |
-| `functions`, `function_call` | deprecated — send `tools` / `tool_choice` |
-| `best_of` | sampling n candidates and returning the best is not implemented |
-| `suffix` | infilling is not implemented |
-| `mirostat`, `mirostat_tau`, `mirostat_eta` | not one of the device samplers |
-| `top_n_sigma`, `dynatemp_range`, `dynatemp_exponent` | not one of the device samplers |
-| `lora` | explicitly out of scope |
-| `modalities`, `audio`, `prediction` | not implemented |
-| `continue_final_message` | assistant prefill is not implemented |
-| `cache_prompt` | prefix caching is a server-wide setting, not per request |
-
-Anything else unrecognised is refused too, naming the key.
+- **Anything else is ignored**, as llama-server and vLLM ignore it: a field this server has never
+  heard of is a client's own extension far more often than a request it misunderstood. The names
+  are logged at debug.
 
 **The one exception is `max_tokens`.** If `prompt + max_tokens` would exceed the context, the
 server clamps `max_tokens` to what is left and serves the request:
@@ -1447,7 +1503,56 @@ precisely without running the model.
 
 ---
 
-### 5.9 What a response says about its own speed
+
+### 5.9 Anthropic's, OpenAI's Responses and llama-server's native APIs
+
+`POST /v1/messages` takes Anthropic's request and answers in Anthropic's shapes, streamed
+(`message_start`, content blocks, `message_delta`, `message_stop`) or not, so Claude Code and the
+Anthropic SDKs work against radiance as they do against llama-server:
+
+```sh
+ANTHROPIC_BASE_URL=http://localhost:8000 ANTHROPIC_API_KEY="$KEY" claude
+```
+
+It is translated into the chat request it means and served by the chat path, so the template
+defaults, refusals and limits are the chat endpoint's. `system` (a string or text blocks), text and
+image blocks, `tool_use` and `tool_result`, client tools and `tool_choice`, `stop_sequences`,
+`thinking` (`enabled` with a `budget_tokens`, `disabled`, `adaptive`) and `metadata.user_id` (the
+conversation's label on `/sessions`) are honoured. A conversation that ends in an assistant message
+is continued, and the answer carries what follows it. Thinking blocks come back with an empty
+`signature`. Claude Code's per-request billing stamp at the head of the system prompt is held
+constant, as llama-server holds it, or no turn could reuse the prefix of the one before.
+`document` blocks and Anthropic's server tools (`web_search_…`, `code_execution_…`) run on
+Anthropic's side and are refused by name. `POST /v1/messages/count_tokens` answers the prompt's
+length. The key may come as `X-Api-Key` (§6.6).
+
+`POST /v1/responses` is OpenAI's Responses API, translated the same way: `instructions` and `input`
+(a string, or message, `function_call`, `function_call_output` and `reasoning` items) become the
+conversation, `max_output_tokens` and `reasoning.effort` and `text.format` the chat request's
+fields, and every field the Responses API does not define passes through to the chat request as it
+does in llama-server (`chat_template_kwargs`, `top_k`, ...). The answer is a response object, or
+its event stream with every event's `output_index`, `content_index` and `sequence_number`; a reply
+cut at `max_output_tokens` is `incomplete`. Function tools are offered to the model; the built-in
+tools (web search, file search, computer use) and freeform custom tools have no counterpart here
+and are left out, as llama-server leaves them out. Responses are not stored, so
+`previous_response_id` is refused: send the conversation as `input`. What a response object
+cannot carry is refused rather than computed and dropped: `n` other than 1, and logprobs
+(`include` naming `message.output_text.logprobs`, `top_logprobs`, `logprobs`, `n_probs`) --
+`/v1/chat/completions` serves those. A failed generation ends the stream in
+`response.failed`, as one on `/v1/messages` ends in Anthropic's `error` event.
+
+`POST /completion` (and `/completions` without `/v1`, as llama-server names it) is llama-server's
+native completion: a prompt string, token ids, or strings and ids mixed as one prompt; the
+request fields of §5.7; and llama-server's answer -- `content`, `stop_type` (`eos`, `limit`,
+`word`), `stopping_word`, `tokens_predicted`, `tokens_evaluated`, `generation_settings`,
+`timings`, and the generated ids with `return_tokens`. A stream is its chunks with the ids that
+made each, then the final result, with no `[DONE]`. `POST /infill` completes between
+`input_prefix` and `input_suffix`, with `input_extra` (files, `{filename, text}`) and `prompt`, in
+the repository-level fill-in-the-middle layout llama-server builds, byte for byte. It needs a model
+with fill-in-the-middle tokens (the Qwen, StarCoder, DeepSeek and CodeLlama spellings are
+recognised) and answers 501 without them; the extra files give way first when the prompt does not
+fit.
+### 5.10 What a response says about its own speed
 
 Every chat and completion response carries a top-level `timings` object for the request. It uses
 llama.cpp's field names, so a proxy or dashboard built against llama-server (llama-swap's activity
@@ -1483,6 +1588,47 @@ When streaming, each choice's final chunk (the one with `finish_reason`) carries
 when asked for, carries the request's. `/metrics` stays the aggregate surface (§6.3). It sums
 the same quantities over every request, so it cannot say which request they belong to.
 
+### 5.11 Logprobs
+
+The numbers are the **raw distribution's** — the logits as the model wrote them, before any
+penalty, temperature, grammar mask or cut — which is what OpenAI and llama-server report. Each
+generated token carries its own logprob and its `top_logprobs` most likely alternatives, at most 20.
+
+```bash
+curl -s localhost:8000/v1/chat/completions -H 'Content-Type: application/json' -d '{
+  "messages": [{"role": "user", "content": "Say hi"}], "temperature": 0,
+  "logprobs": true, "top_logprobs": 2, "max_tokens": 4 }' | jq -c '.choices[0].logprobs.content[0]'
+```
+
+Qwen3.5-0.8B, thinking off:
+
+```json
+{"id":9419,"token":"Hello","bytes":[72,101,108,108,111],"logprob":-0.7186,
+ "top_logprobs":[{"id":9419,"token":"Hello","bytes":[72,101,108,108,111],"logprob":-0.7186},
+                 {"id":12675,"token":"Hi","bytes":[72,105],"logprob":-1.3188}]}
+```
+
+- **Chat** answers in OpenAI's shape, with llama-server's `id` beside each token; a stream carries
+  each token's entry on the chunk that carries its text.
+- **`/v1/completions`** answers OpenAI's legacy arrays (`tokens`, `token_logprobs`, `top_logprobs`
+  as one `{text: logprob}` object a token, `text_offset`) and llama-server's `content` array beside
+  them.
+- **`/completion`** (`n_probs`) answers llama-server's `completion_probabilities`.
+- A token that ends inside a UTF-8 character has the readable part as `token` and every byte in
+  `bytes`, as llama-server does. A stop string's own tokens are not reported, since their text never
+  went out.
+
+Speculation is unaffected — every verified position is scored, and an accepted draft is the token
+the model drew there. The cost is a top-k's worth of work for each row that asks
+(`sample_logprobs`, docs/OPS.md): about 0.12 ms a step on an R9700 at a 248K vocabulary, on the
+card. The chosen token's logprob is exact when it is among the raw top 20; otherwise it is
+recovered from the value it was drawn at by undoing temperature, DRY and the penalties, which
+agrees to float rounding.
+
+**Where llama-server differs:** `logprobs: true` without `top_logprobs` returns 20 alternatives
+there and none here, which is OpenAI's default. The values themselves agree with llama-server's to
+bf16 rounding (within 0.1 on Qwen3.5-0.8B, sampled tokens far down the tail included).
+
 ## 6. Operate it
 
 ### 6.1 The dashboard
@@ -1609,12 +1755,13 @@ any origin can call the API from a browser; `--no-cors` turns it off.
 radiance --model m.rad --api-key "$KEY"
 ```
 
-With a key, every request must carry `Authorization: Bearer KEY` or it is answered 401 —
-`/tokenize` and `/server_info` included, since they hand out the vocabulary, the chat template and
-the configuration. Three paths are exempt: `/health` and `/ping`, because a load balancer cannot
-carry a bearer token and an authenticated probe is a server that reports itself down, and the
-dashboard page itself (`/`, `/dashboard`), which holds no data — on a 401 it shows a key field,
-keeps the key in the browser's storage and sends it on every fetch of data it makes.
+With a key, every request must carry `Authorization: Bearer KEY` (or Anthropic's `X-Api-Key: KEY`)
+or it is answered 401 — `/tokenize` and `/server_info` included, since they hand out the
+vocabulary, the chat template and the configuration. Three paths are exempt: `/health` (and
+`/v1/health`) and `/ping`, because a load balancer cannot carry a bearer token and an
+authenticated probe is a server that reports itself down, and the dashboard page itself (`/`,
+`/dashboard`), which holds no data — on a 401 it shows a key field, keeps the key in the browser's
+storage and sends it on every fetch of data it makes.
 
 The key is checked, not encrypted: on any network you do not control, bind to localhost and put a
 TLS-terminating reverse proxy in front:
@@ -1671,10 +1818,11 @@ rad-kbench --home $RADIANCE_HOME --max-cases 1   # are the kernels correct at al
 | | |
 |---|---|
 | `RADIANCE_HOME` | where `kernels/`, `architectures/` and `quantizers/` live; a `:`-separated search path, the first home winning. Same as `--radiance-home` |
-| `RADIANCE_KERNELS` | default kernel hierarchy, comma-separated. Same as `--kernels`, read by the engine *and* every tool, so a plugin validated with `rad-kbench` can be served without editing launchers |
+| `RADIANCE_KERNELS` | default kernel libraries, comma-separated. Same as `--kernels`, read by the engine *and* every tool, so a plugin validated with `rad-kbench` can be served without editing launchers |
 | `RADIANCE_LOG` | `error` \| `warn` \| `info` \| `debug` \| `trace` |
 | `ROCM_PATH` | where ROCm lives, if not `/opt/rocm` |
-| `HF_TOKEN` | for `scripts/hfget.sh` on a gated repo |
+| `HF_TOKEN` | for `scripts/hfget.sh`, and `--model `, on a gated or private repo |
+| `XDG_CACHE_HOME` | where `--model ` fetches to without `--download-dir` (`$XDG_CACHE_HOME/radiance/hf`, else `~/.cache/radiance/hf`) |
 
 **Tooling**
 
diff --git a/docs/IMPLEMENTATION.md b/docs/IMPLEMENTATION.md
index 6c7b4cf0..1df30cde 100644
--- a/docs/IMPLEMENTATION.md
+++ b/docs/IMPLEMENTATION.md
@@ -28,7 +28,7 @@ core/sample/      device sampler dispatch + the host reference chain + grammar b
 core/text/        tokeniser, chat template, tool parsing, detokenisation
 core/mm/          image and video decoding, and the processor that turns frames into patches
 core/format/      the .rad reader and writer, safetensors, recipes, the imatrix, the tune cache
-core/server/      HTTP, OpenAI-compatible endpoints, /metrics, the dashboard
+core/server/      HTTP: the OpenAI, Anthropic and llama-server endpoints, /metrics, the dashboard
 core/kld.*        the KL mode: --kld-record / --kld-ref
 core/engine*      the thing that ties them together, and `radiance` the binary
 libref/           every op, naively, correct, host domain: the fallback and the oracle
diff --git a/docs/KERNELS.md b/docs/KERNELS.md
index 72990a80..81b5bee7 100644
--- a/docs/KERNELS.md
+++ b/docs/KERNELS.md
@@ -252,6 +252,7 @@ not.
 | `sample_argmax` | yes | device | host |
 | `sample_chain` |   | device | - |
 | `sample_dry` | yes | device | host |
+| `sample_logprobs` |   | device | host |
 | `sample_mask` | yes | device | host |
 | `sample_merge_topk` |   | device | host |
 | `sample_minp` | yes | device | host |
diff --git a/docs/MOE-W4.md b/docs/MOE-W4.md
index 354cd8ca..78bc3757 100644
--- a/docs/MOE-W4.md
+++ b/docs/MOE-W4.md
@@ -243,8 +243,7 @@ its Hessians in the model's own domain; a rotated recipe's GPTQ reads them rotat
 Whole experts per rank, which a calibration run wants anyway. A step reads about 100 GiB a rank from
 the drive and grows only slowly with what it carries -- 50 s at ~32K tokens, 59 s at ~55K -- so
 drive it with large prefill steps: `--max-num-batched-tokens 65536 --max-num-seqs 64`, about 96
-requests in flight, with a KV pool that holds 64 sequences' recurrent state (`--vram-kv-mib`
-states it outright). That records ~930 tokens a second, ten million tokens in three hours.
+requests in flight, with a KV pool that holds 64 sequences' recurrent state. That records ~930 tokens a second, ten million tokens in three hours.
 
 **The corpus is what the Hessian is of, so it has to look like the traffic.** A few thousand
 tokens of one repeated sentence gives a Gram whose energy sits in a handful of directions, and GPTQ
diff --git a/docs/OPS.md b/docs/OPS.md
index 22609f66..28d74441 100644
--- a/docs/OPS.md
+++ b/docs/OPS.md
@@ -1196,10 +1196,22 @@ resolutions of one op — which is not something a batch can contain.
 | `sample_pick` | `M`(range) `n_cand` | `cand_idx`, `cand_val`, `params` → `token` |
 | `sample_argmax` | `M`(range) `n_vocab` | `logits`, `params` → `token` |
 | `sample_merge_topk` | `M`(range) `n_cand` | `gathered`, `params` → `cand_idx`, `cand_val` |
+| `sample_logprobs` | `M`(range) `n_vocab` `k` `vocab_off`/opt | `logits`, `params` → `stats` |
 
 `sample_mask` is where a GBNF grammar lands: the state machine stays on host and what crosses is a
 token bitmask per sequence, 19 KiB at a 151K vocab, cheap enough to upload every step.
 
+`sample_logprobs` is what an OpenAI `logprobs` field or llama-server's `n_probs` reads. It runs on
+the RAW logits, before any stage has touched them, and only for a row whose flags carry
+`RAD_SP_LOGPROBS`; other rows are not written. `stats` is `[M, 2 + 2k]` f32: the row's maximum, the
+sum of `exp(l - max)` over it, and its `k` largest as (id, logit) pairs, descending, ties to the
+lower id, the id written as a float (exact below 2^24) and GLOBAL under a split vocabulary
+(`vocab_off` added). A slot past the vocabulary is id -1, logit -infinity. `k` is geometry: the one
+width every request's `top_logprobs` fits in. The engine declares 21 -- OpenAI's bound of 20, plus
+one so that a row is 44 floats, whole 16-byte words, which the vocab-parallel `all_gather` moves. A
+token's logprob is `l - max - log(sum)`; under a split vocabulary the host merges the ranks' rows
+(the maxima and sums by the usual rescale, the pairs by value).
+
 ### Stages the decomposed chain does not carry
 
 | op | params | operands |
diff --git a/docs/PLUGIN.md b/docs/PLUGIN.md
index 6654bc16..28c923a9 100644
--- a/docs/PLUGIN.md
+++ b/docs/PLUGIN.md
@@ -344,8 +344,7 @@ can also decline it with `RAD_E_UNSUPPORTED`.
 **Which devices.** Discrete cards are used when there are any, and of those the ones sharing the
 first one's architecture; integrated graphics only when it is all there is. `ROCR_VISIBLE_DEVICES`
 chooses explicitly. On integrated graphics the device memory is the host's: the budget is bounded by
-what the host has available and leaves an eighth of the host's memory to it; `--vram-kv-mib` and
-`--vram-weights-mib` state the pools outright.
+what the host has available and leaves an eighth of the host's memory to it.
 
 **What the core assumes of a card: nothing about its wave size**, its LDS, its fp8 hardware or its
 links — those are your kernels' business. Three things are worth knowing before you start:
@@ -478,8 +477,12 @@ RADIANCE_HOME=$HOME/radiance-plugins:/opt/radiance/share/radiance radiance --mod
 and the container image takes one the same way, mounted:
 `-v /my/plugins:/plugins -e RADIANCE_HOME=/plugins:/opt/radiance/share/radiance`.
 
-**The kernel hierarchy** is `--kernels` (or `$RADIANCE_KERNELS`), an ordered list: `--kernels
-mykernels,libr4d` puts you in front. An entry matches a plugin's name or its file stem, and **the
-list is comma-separated** — the tools also accept colons, the engine's `--kernels` and
-`$RADIANCE_KERNELS` do not, so write commas everywhere. A library on the search path that nobody
-named loads after everything named, and a reference library (§1) after that.
+**The kernel hierarchy** is `--kernels` (or `$RADIANCE_KERNELS`), an ordered list of the kernel
+libraries to use: `--kernels mykernels,libr4d` puts you in front of libr4d. An entry matches a
+plugin's name or its file (`libr4d`, `r4d`, `libr4d.so` and a path to it are one library), and an
+entry that matches nothing is warned about by name. **The list is comma-separated** — the tools
+also accept colons, the engine's `--kernels` and `$RADIANCE_KERNELS` do not, so write commas
+everywhere. A kernel
+library on the search path that the list does not name is not loaded, so name every library you
+want, the host library (`libavx`) and the reference (`libref`) included. With no list every library
+found loads, a reference library (§1) last.
diff --git a/docs/TOOLS.md b/docs/TOOLS.md
index 86f71552..d0bbcec5 100644
--- a/docs/TOOLS.md
+++ b/docs/TOOLS.md
@@ -89,7 +89,8 @@ rad-convert [options]  -o 
       --list-quantizers  every quantiser loaded and the options it takes
       --arch ID        override the architecture id from the checkpoint
       --home DIR       $RADIANCE_HOME
-      --kernels A:B    kernel plugin hierarchy, first wins. Default $RADIANCE_KERNELS
+      --kernels A:B    the kernel libraries to load, first wins. Default $RADIANCE_KERNELS,
+                       else every library found
       --tokenizer F    tokenizer.json; its declared chain is baked instead of being
                        reconstructed from a pre-tokenizer name
       --imatrix F      llama.cpp imatrix: expert profile, column importances, error weighting
@@ -214,6 +215,13 @@ CALIB= rad-convert  -o flashnext
 # has is wanted (GUIDE §3.4)
 rad-convert  -o q38-27b-fp8.rad
 
+# A bf16 checkpoint of the same model, as that release's block fp8 (the recipe's header has the
+# --set keys that select the fp8 plugin)
+rad-convert  -o q38-27b-fp8.rad --recipe data/recipes/q38-27b-fp8block-df2.recipe \
+    --draft-model  --set quantization_config.quant_method=fp8 \
+    --set quantization_config.fmt=e4m3 --set "quantization_config.weight_block_size=128 128" \
+    --set quantization_config.activation_scheme=dynamic
+
 # Check the plan without writing 166 GiB
 rad-convert $SRC -o /dev/null --recipe r.recipe --plan-only -v
 
@@ -234,7 +242,10 @@ newer repos moved the template out of the JSON, and the symptom of missing it is
 
 **`--set K=V` is how a convert-time choice that must also hold at serve time is stated once.** The
 key is handed to declare *and* written into the container. What a weight is stored as is not such a
-choice: the encoding is in the container, and the plugin reads it from there.
+choice: the encoding is in the container, and the plugin reads it from there. Which plugin serves
+the container is: a `quantization_config.*` key re-derives the descriptor the plugin is chosen by,
+so a bf16 checkpoint whose recipe writes Qwen's block fp8 is stated as that format and converted for
+the fp8 plugin (`data/recipes/q38-27b-fp8block-df2.recipe` has the keys).
 
 **`--max-ctx`.** Some architectures' graphs depend on the context bound: Qwen4-Exp sizes its QSA
 buffers by it, and refuses a `--max-tok` and context pair whose score plane would pass 2 GiB.
@@ -323,7 +334,7 @@ rad-kbench -m moe.rad   --max-cases 1 --record data/kernels_moe.rkb
 | `--fixture FILE` | the recording to replay (default `$RADIANCE_HOME/kernels.rkb`) |
 | `--record FILE` | with `-m`: write a fixture |
 | `-m, --model FILE` | the `.rad` to read weight operands from |
-| `--home DIR`, `--kernels A:B` | plugin home and hierarchy |
+| `--home DIR`, `--kernels A:B` | plugin home, and the kernel libraries to load (default every one found) |
 | `--op NAME` | check only this op (repeatable prefix match) |
 | `--ref NAME` | the oracle plugin's name (default `libref`) |
 | `--seed N` | base seed; every case derives its own, so changing a filter does not change any other case's inputs |
@@ -379,7 +390,7 @@ rad-tune -m  [options]
 
   -m, --model FILE   the .rad whose declared graph supplies the shapes
       --home DIR     $RADIANCE_HOME; the cache is written to /tune/.tune
-      --kernels A:B  kernel plugin hierarchy, first wins
+      --kernels A:B  the kernel libraries to load, first wins; default every library found
       --op NAME      tune only ops whose name starts with NAME
       --machine KEY  override the machine key (for writing a cache for another box)
       --reps N       timing reps, median reported (default 5)
@@ -537,7 +548,7 @@ deliberately disconnects clients from it, which is not the same promise.
 | `fnserve.sh` | Qwen3.8-Flash-Next, the production container `w4nl64-i8lm.rad`, same contract. `P` `TP` `MLEN` `SEQS` `M` `NS` `HOSTPOOL` `KVD` `HR` `MNBT` `WIRE` `KVHOST` `KVDIR` `KVDISK` `EXTRA` `EXTRA_ENV` |
 | `fnstop.sh` | stops whichever is running and **waits for the process to go** |
 | `convdspark.sh`, `convfn.sh` | rebuild the containers those two serve. The conversions of record. `convfn.sh` needs `CALIB=`: the production recipe's expert rule runs GPTQ against the calibration Grams there |
-| `hfget.sh` | fetch a checkpoint from Hugging Face with `curl` and `jq`. Resumable |
+| `hfget.sh` | fetch a checkpoint from Hugging Face with `curl` and `jq`. Resumable; a file changed at the same size is fetched again (`.hfget-manifest`). `radiance --model ` runs it too |
 
 ```sh
 scripts/fnserve.sh                             # defaults: port 8100, tp 2, 200K ctx
diff --git a/docs/TP3.md b/docs/TP3.md
index 2f9daa89..4305b212 100644
--- a/docs/TP3.md
+++ b/docs/TP3.md
@@ -49,9 +49,8 @@ difference into its weights pool, no further than every one of its weights resid
 of the resolved sizes take the rank's own split -- `Pools::configure` and the planner -- so the
 grown pool is planned into, and startup refuses a rank whose plan and weights pool disagree, or
 whose re-sized KV pool pages fewer tokens than it was sized for. The token count, the carve, the
-loan and the attention ranks' pools are unchanged; a stated `--vram-kv-mib` / `--vram-weights-mib`
-keeps meaning "this many on every card", and `auto` keeps the common split (a fully resident rank
-would choose all_vram while its peers spill). `--deterministic` and a device without virtual memory
+loan and the attention ranks' pools are unchanged, and `auto` keeps the common split (a fully
+resident rank would choose all_vram while its peers spill). `--deterministic` and a device without virtual memory
 management re-split like any other: the cache does not lend there, and the bytes the rank never
 pages are as much its experts' as they are under a lending cache. The condition is the cost, not
 the world: a rank is re-split only where its cache costs less per token than the dearest rank's,
diff --git a/libavx/avx_cases.cpp b/libavx/avx_cases.cpp
index b71d5ec0..e0b9589f 100644
--- a/libavx/avx_cases.cpp
+++ b/libavx/avx_cases.cpp
@@ -410,6 +410,11 @@ std::vector build_cases() {
                             "sample_argmax" })
         add(op, { HI("M", 5), HI("n_vocab", 517) });
     add("sample_topk", { HI("M", 5), HI("n_vocab", 517), HI("vocab_off", 0) });
+    /* k 7 and 20 (OpenAI's top_logprobs bound) against 517: the one-pass set starts full after
+     * seven columns, and an offset shard reports global ids. */
+    for (int64_t k : { 7, 20 })
+        add("sample_logprobs", { HI("M", 5), HI("n_vocab", 517), HI("k", k), HI("vocab_off", 0) });
+    add("sample_logprobs", { HI("M", 3), HI("n_vocab", 517), HI("k", 5), HI("vocab_off", 1000) });
     for (const char* op : { "sample_topp", "sample_minp", "sample_typical", "sample_xtc",
                             "sample_pick", "sample_merge_topk" })
         add(op, { HI("M", 5), HI("n_cand", 12) });
@@ -495,6 +500,7 @@ std::vector build_cases() {
     speed("logits_gemm", { HI("M", 1), HI("n_vocab", 32000), HI("n_embd", 2048),
                            HS("dtype", "bf16") }, (double)32000 * 2048 * 2, 2.0 * 32000 * 2048);
     speed("sample_argmax", { HI("M", 1), HI("n_vocab", 32000) }, (double)32000 * 4, 0);
+    speed("sample_logprobs", { HI("M", 1), HI("n_vocab", 32000), HI("k", 20) }, (double)32000 * 4, 0);
     speed("sample_topk", { HI("M", 1), HI("n_vocab", 32000), HI("vocab_off", 0) }, 0, 0);
     /* Decode attention over a real context: 16 query heads in groups of 4, 2048 keys already in
      * the cache. This is the shape a decode step spends its time in. */
diff --git a/libavx/avx_isa.h b/libavx/avx_isa.h
index ff9a10d0..96b4784e 100644
--- a/libavx/avx_isa.h
+++ b/libavx/avx_isa.h
@@ -116,7 +116,7 @@ int         avx_isa_force(int level);
     X(sample_penalties)     X(sample_dry)           X(sample_temp)          X(sample_topk)        \
     X(sample_topp)          X(sample_minp)          X(sample_typical)       X(sample_xtc)         \
     X(sample_merge_topk)    X(sample_mask)          X(sample_pick)          X(sample_argmax)      \
-    X(dflash_select)
+    X(sample_logprobs)      X(dflash_select)
 
 /* The table one ISA level fills. One member per op, same order as AVX_OP_LIST. A missing
  * definition is a link error against the level's own table definition in avx_table.cpp. */
diff --git a/libavx/avx_registry.cpp b/libavx/avx_registry.cpp
index e1302e5d..96137405 100644
--- a/libavx/avx_registry.cpp
+++ b/libavx/avx_registry.cpp
@@ -450,6 +450,9 @@ static const RadParamSpec pTopk[]        = { P_INT("M"), P_INT("n_vocab"), P_INT
 static const RadOperandSpec oTopk[]      = { OPD("logits"), OPD("params"),
                                              OUT("cand_idx"), OUT("cand_val"), OUT_O("pairs") };
 static const RadOperandSpec oArgmax[]    = { OPD("logits"), OPD("params"), OUT("token") };
+static const RadParamSpec pLogprobs[]    = { P_INT("M"), P_INT("n_vocab"), P_INT("k"),
+                                             P_INTO("vocab_off") };
+static const RadOperandSpec oLogprobs[]  = { OPD("logits"), OPD("params"), OUT("stats") };
 static const RadOperandSpec oNarrow[]    = { INOUT("cand_idx"), INOUT("cand_val"), OPD("params") };
 static const RadOperandSpec oPick[]      = { OPD("cand_idx"), OPD("cand_val"), OPD("params"),
                                              OUT("token") };
@@ -636,6 +639,9 @@ static const RadOpSchema kSchemas[] = {
   "stream has to come out of a host reference, a device kernel and a rerun." },
 { "sample_merge_topk", ARR(pMCand), ARR(oMerge), "the vocab-parallel candidate merge." },
 { "sample_argmax", ARR(pMVocab), ARR(oArgmax), "greedy, ties to the lower token id." },
+{ "sample_logprobs", ARR(pLogprobs), ARR(oLogprobs),
+  "the raw logits' max, sum of exp(l - max) and k largest (id, logit) pairs, for a row with "
+  "RAD_SP_LOGPROBS." },
 { "dflash_select", ARR(pDflashSelect), ARR(oDflashSelect),
   "a greedy walk over a candidate lattice: score[l, c] = unary[l, c] + sum_r pred[pid(l)][r] * "
   "hp[l][r] * succ[cand[l, c]][r], pid(0) the anchor and pid(l) the walk's own previous pick. "
@@ -878,6 +884,8 @@ SIMPLE("avx_sample_mask", "sample_mask", "sample", "grammar bitmask application"
 SIMPLE("avx_sample_pick", "sample_pick", "sample", "seeded inverse-CDF draw", DT_FLOAT,
        L(sample_pick)),
 SIMPLE("avx_sample_argmax", "sample_argmax", "sample", "greedy pick", DT_FLOAT, L(sample_argmax)),
+SIMPLE("avx_sample_logprobs", "sample_logprobs", "sample", "the raw distribution's summary",
+       DT_FLOAT, L(sample_logprobs)),
 SIMPLE("avx_dflash_select", "dflash_select", "draft",
        "DFlash2's greedy walk over the candidate lattice",
        "i32 candidates and tokens, float unary and codebooks", L(dflash_select)),
diff --git a/libavx/avx_sample.cpp b/libavx/avx_sample.cpp
index 175506a2..1297e292 100644
--- a/libavx/avx_sample.cpp
+++ b/libavx/avx_sample.cpp
@@ -650,6 +650,100 @@ AVX_KERNEL(sample_argmax) {
     return RAD_OK;
 }
 
+/* ------------------------------------------------------------------ sample_logprobs */
+/* The raw distribution's summary for a row with RAD_SP_LOGPROBS -- max, sum of exp(l - max), and
+ * the k largest as (id, logit) pairs, descending, ties to the lower id -- libref's contract
+ * (ref_sample.cpp). A row without the flag is not written.
+ *
+ * ONE PASS FOR THE k LARGEST, not k passes of topk_next_f32: `k` is the deployment's width (the
+ * largest top_logprobs any request may ask for), and k full sweeps of a 248K row would cost k times
+ * the argmax. The set is seeded with the row's first k columns, kept sorted, and the rest of the
+ * row is compared a vector at a time against its smallest value; a lane strictly above it is
+ * inserted. Strictly, because the scan runs in increasing id, and an equal value further along has
+ * the higher id and loses the tie. After the first few thousand columns almost no vector has such
+ * a lane, so the pass costs what the maximum does.
+ *
+ * The sum is f32 in four vector accumulators. Its terms are all in (0, 1] and the relative error
+ * of the sum is what a logprob carries (log of it), so f32 is ample next to libref's double. */
+AVX_KERNEL(sample_logprobs) {
+    if (!rad_args_have(a, 3)) return RAD_E_INVAL;
+    const RadTensor *lg = &a->t[0], *pr = &a->t[1], *st = &a->t[2];
+    const int64_t n_vocab = p_int(a, "n_vocab", lg->rank >= 2 ? lg->shape[lg->rank - 1] : 0);
+    const int64_t k = p_int(a, "k", 0);
+    const int64_t voff = p_int(a, "vocab_off", 0);
+    if (n_vocab <= 0 || k <= 0) return RAD_E_SHAPE;
+    const int64_t M = numel(lg) / n_vocab;
+    const int64_t w = 2 + 2 * k;
+    if (M <= 0 || numel(st) < M * w) return RAD_E_SHAPE;
+    Rows R;
+    AVX_TRY(rows_of_params(pr, M, &R));
+
+    AVX_PARALLEL_FOR_IF(M * n_vocab >= AVX_PAR_MIN)
+    for (int64_t m = 0; m < M; ++m) {
+        if (!(R.p[m].flags & RAD_SP_LOGPROBS)) continue;
+        float* buf = scratch_f32((size_t)n_vocab + 2 * (size_t)k);
+        const float* v = in_row(lg, rowoff(lg, m, n_vocab), n_vocab, buf);
+        float* tv = buf + n_vocab;                 /* the set's values, descending */
+        int32_t* ti = (int32_t*)(tv + k);          /* and their ids */
+
+        const float mx = row_max(v, n_vocab);
+        float sum = 0.0f;
+        {
+            const vf vmx = vf_set1(mx);
+            vf s0 = vf_zero(), s1 = vf_zero(), s2 = vf_zero(), s3 = vf_zero();
+            int64_t i = 0;
+            for (; i + 4 * VF_N <= n_vocab; i += 4 * VF_N) {
+                s0 = vf_add(s0, vf_exp(vf_sub(vf_loadu(v + i), vmx)));
+                s1 = vf_add(s1, vf_exp(vf_sub(vf_loadu(v + i + VF_N), vmx)));
+                s2 = vf_add(s2, vf_exp(vf_sub(vf_loadu(v + i + 2 * VF_N), vmx)));
+                s3 = vf_add(s3, vf_exp(vf_sub(vf_loadu(v + i + 3 * VF_N), vmx)));
+            }
+            for (; i + VF_N <= n_vocab; i += VF_N) s0 = vf_add(s0, vf_exp(vf_sub(vf_loadu(v + i), vmx)));
+            sum = vf_hsum(vf_add(vf_add(s0, s1), vf_add(s2, s3)));
+            for (; i < n_vocab; ++i) sum += std::exp(v[i] - mx);
+        }
+
+        /* Insert (x, id) into the sorted set of n entries, the set at most k long. */
+        int64_t n = 0;
+        auto insert = [&](float x, int32_t id) {
+            int64_t j = n < k ? n++ : k - 1;
+            while (j > 0 && x > tv[j - 1]) { tv[j] = tv[j - 1]; ti[j] = ti[j - 1]; --j; }
+            tv[j] = x;
+            ti[j] = id;
+        };
+        const int64_t seed = std::min(k, n_vocab);
+        for (int64_t i = 0; i < seed; ++i) insert(v[i], (int32_t)i);
+        int64_t i = seed;
+#if AVX_LEVEL > 0
+        for (; i + VF_N <= n_vocab; i += VF_N) {
+            const vf x = vf_loadu(v + i);
+#if AVX_LEVEL == 3
+            unsigned msk = (unsigned)_mm512_cmp_ps_mask(x, vf_set1(tv[k - 1]), _CMP_GT_OQ);
+#else
+            unsigned msk = (unsigned)_mm256_movemask_ps(_mm256_cmp_ps(x, vf_set1(tv[k - 1]), _CMP_GT_OQ));
+#endif
+            /* Lanes in increasing id; the bar can rise after each insertion. */
+            while (msk) {
+                const int lane = __builtin_ctz(msk);
+                msk &= msk - 1;
+                if (v[i + lane] > tv[k - 1]) insert(v[i + lane], (int32_t)(i + lane));
+            }
+        }
+#endif
+        for (; i < n_vocab; ++i)
+            if (v[i] > tv[k - 1]) insert(v[i], (int32_t)i);
+
+        const int64_t sb = rowoff(st, m, w), ss = laststride(st);
+        stt(st, sb, mx);
+        stt(st, sb + ss, sum);
+        for (int64_t j = 0; j < k; ++j) {
+            stt(st, sb + (2 + 2 * j) * ss, j < n ? (float)(ti[j] + voff) : -1.0f);
+            stt(st, sb + (3 + 2 * j) * ss, j < n ? tv[j] : -INFINITY);
+        }
+    }
+    return RAD_OK;
+}
+
 /* ------------------------------------------------------------------ sample_merge_topk */
 /* THE VOCAB-PARALLEL MERGE. lm_head is vocab-sharded, so each rank runs top-k over ITS OWN shard
  * and the candidate sets are all-gathered -- k * world_size pairs, 2 KiB at k=64 and world_size=4,
diff --git a/libr4d/CMakeLists.txt b/libr4d/CMakeLists.txt
index f4bd2ded..d36d4198 100644
--- a/libr4d/CMakeLists.txt
+++ b/libr4d/CMakeLists.txt
@@ -63,6 +63,9 @@ set(R4D_UNITS
   # Twelve, head_dim 256 only: Qwen3.8-Flash-Next's QSA layers are 24 over 2. Four lines that
   # set the ratio and include the unit above, which is the parameterised body.
   "r4d_attn_paged_h256_gqa12|"
+  # Four, head_dim 256: Qwen3.5-0.8B is 8 over 2 at the 27B's head width. Again the body above
+  # with the ratio set.
+  "r4d_attn_paged_h256_gqa4|"
   # Six, head_dim 256 and the same 4-token page: the same QSA layers at four ranks, where each KV
   # head is replicated across a rank pair. Again four lines that set the ratio and include the body.
   "r4d_attn_paged_h256_gqa6_bs4|"
diff --git a/libr4d/README.md b/libr4d/README.md
index 152faf70..e40be5a2 100644
--- a/libr4d/README.md
+++ b/libr4d/README.md
@@ -66,7 +66,7 @@ target architecture. They are reported by the `r4d_*_dims()` accessors in
 | `gated_had_quant_i8` | `silu(a)*b` or `sigmoid(a)*b`, then the same rotation and quantiser |
 | `gdn_gated_norm_had_quant_i8` | the gdn gated norm with the rotation and quantiser fused onto it |
 | `qk_norm_rope_gate` | q/k rms-norm, rope and the attention gate in one kernel |
-| `ar_oneshot_{4,8}rank_exact`, `ar_twoshot_{4,8}rank_exact`, `ar_twoshot_4rank_ti8` | the wider-world all-reduces (TP4/TP8), exact and int8-wire |
+| `ar_oneshot_{3,4,8}rank_exact`, `ar_twoshot_{3,4,8}rank_exact`, `ar_twoshot_{3,4}rank_ti8`, `ar_gather_3rank` | the wider-world collectives (TP3/TP4/TP8), exact and int8-wire |
 | `p2p_copy2d`, `p2p_copy2d_kernel`, `p2p_fence` | strided peer device-to-device copy, through the copy engines or a kernel |
 ## Asking the library instead of remembering
 
diff --git a/libr4d/r4d_attn_paged_h256_gqa4.hip b/libr4d/r4d_attn_paged_h256_gqa4.hip
new file mode 100644
index 00000000..7a19f4bb
--- /dev/null
+++ b/libr4d/r4d_attn_paged_h256_gqa4.hip
@@ -0,0 +1,18 @@
+// R4D attention at FOUR queries per KV head, head_dim 256 -- Qwen3.5-0.8B and its siblings that
+// keep the 27B's head width with fewer heads (8 query heads over 2 KV heads).
+//
+// The geometry and the dispatch only, as r4d_attn_paged_h256_gqa12.hip is: r4d_attn_paged_gqa8.hip
+// is the parameterised body and its kernels are templates on `gqa`. What the ratio changes is the
+// two bounds, and both are in the ROW table rather than here:
+//
+//   the decode verify width   64 / gqa = 16, against 8 at gqa 8 and 10 at gqa 6. A workgroup holds
+//                             64 (query, head) rows and carries q_len * gqa of them.
+//   a prefill block's width   384 / gqa = 96 query positions, against 48 at gqa 8.
+//
+// NO head_dim 128 LEG. gqa 4 at 128 is the DFlash2 drafter's windowed geometry, which
+// r4d_attn_paged_h128_gqa4.hip serves; R4D_ATTN_H128 leaves those entry points out of this unit.
+// The page is the body's default 16.
+#define R4D_ATTN_GQA  4
+#define R4D_ATTN_H128 0
+
+#include "r4d_attn_paged_gqa8.hip"
diff --git a/libr4d/r4d_plugin.h b/libr4d/r4d_plugin.h
index b139a532..2d227f5a 100644
--- a/libr4d/r4d_plugin.h
+++ b/libr4d/r4d_plugin.h
@@ -104,6 +104,13 @@ int     r4d_rad_attn_prefill_h128_gqa8_bf16(const RadArgs*, RadStream);
 int     r4d_rad_attn_decode_h128_gqa8_fp8  (const RadArgs*, RadStream);
 int     r4d_rad_attn_decode_h128_gqa8_bf16 (const RadArgs*, RadStream);
 int64_t r4d_rad_attn_decode_h128_gqa8_scratch(const RadArgs*);
+/* Four queries a KV head, head_dim 256 only -- Qwen3.5-0.8B. Same body, different
+ * instantiation (r4d_attn_paged_h256_gqa4.hip). */
+int     r4d_rad_attn_prefill_h256_gqa4_fp8 (const RadArgs*, RadStream);
+int     r4d_rad_attn_prefill_h256_gqa4_bf16(const RadArgs*, RadStream);
+int     r4d_rad_attn_decode_h256_gqa4_fp8  (const RadArgs*, RadStream);
+int     r4d_rad_attn_decode_h256_gqa4_bf16 (const RadArgs*, RadStream);
+int64_t r4d_rad_attn_decode_h256_gqa4_scratch(const RadArgs*);
 /* Twelve queries a KV head, head_dim 256 only -- Qwen3.8-Flash-Next's QSA layers. Same body,
  * different instantiation; r4d_attn_paged_h256_gqa12.hip is four lines. */
 int     r4d_rad_attn_prefill_h256_gqa12_fp8 (const RadArgs*, RadStream);
@@ -452,6 +459,7 @@ int r4d_rad_sample_temp      (const RadArgs*, RadStream);
 int r4d_rad_sample_mask      (const RadArgs*, RadStream);
 int r4d_rad_sample_topk      (const RadArgs*, RadStream);
 int r4d_rad_sample_argmax    (const RadArgs*, RadStream);
+int r4d_rad_sample_logprobs  (const RadArgs*, RadStream);
 int r4d_rad_sample_topp      (const RadArgs*, RadStream);
 int r4d_rad_sample_minp      (const RadArgs*, RadStream);
 int r4d_rad_sample_typical   (const RadArgs*, RadStream);
@@ -500,6 +508,7 @@ int r4d_shape_sample_temp      (const RadParam*, int, int operand, RadOpdDesc*);
 int r4d_shape_sample_mask      (const RadParam*, int, int operand, RadOpdDesc*);
 int r4d_shape_sample_topk      (const RadParam*, int, int operand, RadOpdDesc*);
 int r4d_shape_sample_argmax    (const RadParam*, int, int operand, RadOpdDesc*);
+int r4d_shape_sample_logprobs  (const RadParam*, int, int operand, RadOpdDesc*);
 int r4d_shape_sample_narrow    (const RadParam*, int, int operand, RadOpdDesc*);
 int r4d_shape_sample_pick      (const RadParam*, int, int operand, RadOpdDesc*);
 int r4d_shape_sample_chain     (const RadParam*, int, int operand, RadOpdDesc*);
diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp
index ffbd2715..4d13d05a 100644
--- a/libr4d/r4d_rows.cpp
+++ b/libr4d/r4d_rows.cpp
@@ -1907,6 +1907,19 @@ static const RadOperandSpec oArgmax[] = {
     { "params", RAD_OPD_IN,  0 },
     { "token",  RAD_OPD_OUT, 0 },
 };
+/* `stats` is [M, 2 + 2k] f32: max, sum of exp(l - max), then k (id, logit) pairs. `k` is the
+ * deployment's width, `vocab_off` sample_topk's. */
+static const RadParamSpec pLogprobs[] = {
+    { "M",         RAD_P_INT, RAD_REQUIRED },
+    { "n_vocab",   RAD_P_INT, RAD_REQUIRED },
+    { "k",         RAD_P_INT, RAD_REQUIRED },
+    { "vocab_off", RAD_P_INT, RAD_OPTIONAL },
+};
+static const RadOperandSpec oLogprobs[] = {
+    { "logits", RAD_OPD_IN,  0 },
+    { "params", RAD_OPD_IN,  0 },
+    { "stats",  RAD_OPD_OUT, 0 },
+};
 static const RadOperandSpec oNarrow[] = {
     { "cand_idx", RAD_OPD_INOUT, 0 },
     { "cand_val", RAD_OPD_INOUT, 0 },
@@ -2068,6 +2081,9 @@ static const RadOpSchema kSchemas[] = {
            "the exact top-k candidate set, descending, ties to the lower token id. The width is "
            "the buffer's; a row's own top_k may be narrower and leaves holes."),
     SCHEMA("sample_argmax", pMVocab, oArgmax, "greedy, ties to the lower token id."),
+    SCHEMA("sample_logprobs", pLogprobs, oLogprobs,
+           "for a row with RAD_SP_LOGPROBS: the raw logits' max, sum of exp(l - max) and k largest "
+           "(id, logit) pairs, descending, ties to the lower id. Other rows are not written."),
     SCHEMA("sample_topp", pMCand, oNarrow,
            "nucleus: keep the shortest prefix whose cumulative probability reaches top_p, always "
            "at least one. The candidates are assumed descending, as sample_topk leaves them."),
@@ -2434,6 +2450,25 @@ static const RadConstraint cAttnDecodeH256G8Bf16[] = {
     C_EQ("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 8), C_EQ("block_size", 16),
     C_GE("causal", 0), C_LE("q_len", 8), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "bf16"),
 };
+/* FOUR QUERIES PER KV HEAD, head_dim 256 (r4d_attn_paged_h256_gqa4.hip) -- Qwen3.5-0.8B, 8 query
+ * heads over 2. `q_len <= 16` is the same `q_len * gqa <= 64` bound, so every legal speculation
+ * depth is a decode launch at this ratio. */
+static const RadConstraint cAttnPrefillH256G4Fp8[] = {
+    C_EQ("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 4), C_EQ("block_size", 16),
+    C_EQ("causal", 1), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "fp8_e4m3"),
+};
+static const RadConstraint cAttnPrefillH256G4Bf16[] = {
+    C_EQ("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 4), C_EQ("block_size", 16),
+    C_EQ("causal", 1), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "bf16"),
+};
+static const RadConstraint cAttnDecodeH256G4Fp8[] = {
+    C_EQ("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 4), C_EQ("block_size", 16),
+    C_GE("causal", 0), C_LE("q_len", 16), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "fp8_e4m3"),
+};
+static const RadConstraint cAttnDecodeH256G4Bf16[] = {
+    C_EQ("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 4), C_EQ("block_size", 16),
+    C_GE("causal", 0), C_LE("q_len", 16), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "bf16"),
+};
 /* TWELVE QUERIES PER KV HEAD, head_dim 256 (r4d_attn_paged_h256_gqa12.hip) -- Qwen3.8-Flash-Next's
  * QSA layers, 24 query heads over 2. `q_len <= 5` is the same `q_len * gqa <= 64` bound the two
  * ratios above state, and it is TIGHTER than the legal speculation depths: a verify of depth 7 is
@@ -3378,6 +3413,7 @@ static const RadConstraint cGridEmbed[] = { C_GE("n", 1), C_GE("side", 1), C_IN(
 static const RadConstraint cGemmBias[]  = { C_GE("M", 1), C_DIV("K", 8), C_IN("dtype", "bf16") };
 static const RadConstraint cSampleVoc[] = { C_GE("n_vocab", 1) };
 static const RadConstraint cSampleCand[] = { C_GE("n_cand", 1), C_LE("n_cand", 4096) };
+static const RadConstraint cSampleLogprobs[] = { C_GE("n_vocab", 1), C_GE("k", 1), C_LE("k", 64) };
 /* The activation width the column loop vectorises over; M is unbounded -- the kernel chunks rows. */
 static const RadConstraint cLogitsGemm[] = { C_DIV("n_embd", 8), C_IN("dtype", "bf16") };
 /* The fp8 head. n_embd on the 128 block the scales are taken over, and NO CAP ON M -- the row
@@ -3849,6 +3885,17 @@ static const RadKernelInfo kKernels[] = {
   nullptr, nullptr, r4d_rad_sample_argmax, nullptr, nullptr, nullptr,
   r4d_shape_sample_argmax },
 
+{ "sample_logprobs_f32", "sample_logprobs", "sample",
+  "the raw distribution's summary for a logprobs row: max, sum of exp(l - max), the k largest",
+  "any vocabulary; k <= 64, the LDS the sort runs in. sample_topk's radix select at the op's k, so "
+  "the set and its tie rule are the top-k's; the maximum is its first entry and the sum one more "
+  "pass. A row without RAD_SP_LOGPROBS leaves before reading anything",
+  "f32 logits, f32 stats [M, 2 + 2k] with the ids as floats",
+  RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
+  ROW(cSampleLogprobs), NOTUNE,
+  nullptr, nullptr, r4d_rad_sample_logprobs, nullptr, nullptr, nullptr,
+  r4d_shape_sample_logprobs },
+
 { "sample_topp_f32", "sample_topp", "sample",
   "nucleus narrowing in place",
   "n_cand <= 4096; the prefix sum is SEQUENTIAL in f32 in candidate order, because a parallel "
@@ -4012,6 +4059,44 @@ static const RadKernelInfo kKernels[] = {
   nullptr, nullptr,
   r4d_shape_attn_paged },
 
+{ "attn_prefill_h256_gqa4_fp8kv", "attn_paged", "attn",
+  "paged causal attention, query-tiled (prefill / chunked prefill)",
+  "head_dim 256, 4 queries per kv head, paged block 16, varlen",
+  "bf16 query, fp8-e4m3 kv cache with per-(seq,head) descales, bf16 out",
+  RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_PREFILL,
+  ROW(cAttnPrefillH256G4Fp8), NOTUNE,
+  nullptr, nullptr, r4d_rad_attn_prefill_h256_gqa4_fp8, nullptr, nullptr, nullptr,
+  r4d_shape_attn_paged },
+
+{ "attn_prefill_h256_gqa4_bf16kv", "attn_paged", "attn",
+  "paged causal attention, query-tiled (prefill / chunked prefill)",
+  "head_dim 256, 4 queries per kv head, paged block 16, varlen",
+  "bf16 query, bf16 kv cache, bf16 out",
+  RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_PREFILL,
+  ROW(cAttnPrefillH256G4Bf16), NOTUNE,
+  nullptr, nullptr, r4d_rad_attn_prefill_h256_gqa4_bf16, nullptr, nullptr, nullptr,
+  r4d_shape_attn_paged },
+
+{ "attn_decode_h256_gqa4_fp8kv", "attn_paged", "attn",
+  "paged attention, causal or not, split-KV (decode / speculative verify / draft block)",
+  "head_dim 256, 4 queries per kv head, paged block 16, q_len*gqa <= 64, no window",
+  "bf16 query, fp8-e4m3 kv cache with per-(seq,head) descales, bf16 out, f16 partials",
+  RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_DECODE,
+  ROW(cAttnDecodeH256G4Fp8), ROW(tAttnSplit), nullptr,
+  nullptr, nullptr, r4d_rad_attn_decode_h256_gqa4_fp8, r4d_rad_attn_decode_h256_gqa4_scratch,
+  nullptr, nullptr,
+  r4d_shape_attn_paged },
+
+{ "attn_decode_h256_gqa4_bf16kv", "attn_paged", "attn",
+  "paged attention, causal or not, split-KV (decode / speculative verify / draft block)",
+  "head_dim 256, 4 queries per kv head, paged block 16, q_len*gqa <= 64, no window",
+  "bf16 query, bf16 kv cache, bf16 out, f16 partials",
+  RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_DECODE,
+  ROW(cAttnDecodeH256G4Bf16), ROW(tAttnSplit), nullptr,
+  nullptr, nullptr, r4d_rad_attn_decode_h256_gqa4_bf16, r4d_rad_attn_decode_h256_gqa4_scratch,
+  nullptr, nullptr,
+  r4d_shape_attn_paged },
+
 { "attn_prefill_h256_gqa12_fp8kv", "attn_paged", "attn",
   "paged causal attention, query-tiled (prefill / chunked prefill)",
   "head_dim 256, 12 queries per kv head, paged block 4, varlen",
diff --git a/libr4d/r4d_sample_stages_f32.hip b/libr4d/r4d_sample_stages_f32.hip
index 18104d2c..eda985a5 100644
--- a/libr4d/r4d_sample_stages_f32.hip
+++ b/libr4d/r4d_sample_stages_f32.hip
@@ -98,7 +98,8 @@ enum {
     SP_PENALTY = 1 << 1,
     SP_MASK    = 1 << 2,
     SP_XTC     = 1 << 3,
-    SP_DRY     = 1 << 4
+    SP_DRY     = 1 << 4,
+    SP_LOGPROBS = 1 << 5
 };
 
 __device__ __forceinline__ uint64_t splitmix64(uint64_t z) {
@@ -674,6 +675,115 @@ __global__ __launch_bounds__(kTopkThreads) void topk_kernel(
     }
 }
 
+// ---------------------------------------------------------------------------- sample_logprobs
+// ref_sample_logprobs.  For a row with RAD_SP_LOGPROBS: [max, sum of exp(l - max), k (id, logit)
+// pairs], descending, ties to the lower id, ids global (+ vocab_off) and written as floats.  A row
+// without the flag is not written, and its block leaves before reading anything.
+//
+// THE k LARGEST ARE topk_kernel's SELECT, at the op's fixed k rather than a row's top_k: the same
+// radix_select passes, the tie-break pass only when the threshold's tie group is bigger than the
+// set is owed, and the same packed (key, ~id) bitonic sort, so this set and a top-k candidate set
+// over the same row agree to the bit and the tie rule is ref's by construction.  The maximum is
+// the first of them, so it costs nothing; the sum is one more pass, accurate expf, folded wave by
+// wave in a fixed order -- the same row gives the same bits every step.
+//
+// k IS BOUNDED BY kMaxLogprobs, the LDS the sort runs in.  The engine declares 21 (OpenAI's bound on
+// top_logprobs, and one more so a row is whole 16-byte words); the shim refuses a wider op rather
+// than truncating it.
+constexpr uint32_t kMaxLogprobs = 64;
+
+__global__ __launch_bounds__(kTopkThreads) void logprobs_kernel(
+    const float* __restrict__ lg, const SP* __restrict__ sp, float* __restrict__ st,
+    uint32_t n_vocab, uint32_t k, uint32_t lg_ld, uint32_t st_ld, int32_t vocab_off) {
+    __shared__ unsigned long long cand[kMaxLogprobs];
+    __shared__ uint32_t hist[258];
+    __shared__ uint32_t scan[256], wt[256 / kWave];
+    __shared__ uint32_t fill;
+    __shared__ float red[kTopkWaves];
+
+    const uint32_t m = blockIdx.x;
+    if (!(sp[m].flags & SP_LOGPROBS)) return;
+    const float* __restrict__ row = lg + (size_t)m * lg_ld;
+    float* __restrict__ out = st + (size_t)m * st_ld;
+    const uint32_t kk = k < n_vocab ? k : n_vocab;
+
+    uint32_t n_eq = 0, dummy = 0, n_tie = 0;
+    const uint32_t T = radix_select(row, n_vocab, 0, kk, hist, scan, wt, &n_eq, &n_tie);
+    const uint32_t idx_cut = (n_tie == n_eq)
+                                 ? 0xffffffffu
+                                 : radix_select(row, n_vocab, T, n_eq, hist, scan, wt,
+                                                       &dummy, &n_tie);
+    if (threadIdx.x == 0) fill = 0;
+    __syncthreads();
+    auto collect = [&](float f, uint32_t i) {
+        const uint32_t key = fkey(f);
+        if (!(key > T || (key == T && i <= idx_cut))) return;
+        const uint32_t slot = atomicAdd(&fill, 1u);
+        if (slot < kMaxLogprobs) cand[slot] = ((unsigned long long)key << 32) | (unsigned long long)(~i);
+    };
+    const bool v4 = ((uintptr_t)row & 15u) == 0 && (n_vocab & 3u) == 0;
+    if (v4) {
+        const float4* __restrict__ r4 = (const float4*)row;
+        for (uint32_t j = threadIdx.x; j < (n_vocab >> 2); j += kTopkThreads) {
+            const float4 f = r4[j];
+            collect(f.x, 4 * j);
+            collect(f.y, 4 * j + 1);
+            collect(f.z, 4 * j + 2);
+            collect(f.w, 4 * j + 3);
+        }
+    } else {
+        for (uint32_t i = threadIdx.x; i < n_vocab; i += kTopkThreads) collect(row[i], i);
+    }
+    __syncthreads();
+    const uint32_t got = fill < kk ? fill : kk;
+    uint32_t sn = 1;
+    while (sn < got) sn <<= 1;
+    for (uint32_t i = got + threadIdx.x; i < sn; i += kTopkThreads) cand[i] = 0;
+    __syncthreads();
+    for (uint32_t sz = 2; sz <= sn; sz <<= 1) {
+        for (uint32_t stp = sz >> 1; stp > 0; stp >>= 1) {
+            const uint32_t t = threadIdx.x;
+            if (t < sn) {
+                const uint32_t partner = t ^ stp;
+                if (partner > t) {
+                    const bool up = (t & sz) == 0;                 // `up` here means DESCENDING
+                    const unsigned long long a = cand[t], b = cand[partner];
+                    if (up ? (a < b) : (a > b)) { cand[t] = b; cand[partner] = a; }
+                }
+            }
+            __syncthreads();
+        }
+    }
+
+    const float mx = got ? row[~(uint32_t)(cand[0] & 0xffffffffull)] : -INFINITY;
+    float s = 0.0f;
+    if (v4) {
+        const float4* __restrict__ r4 = (const float4*)row;
+        for (uint32_t j = threadIdx.x; j < (n_vocab >> 2); j += kTopkThreads) {
+            const float4 f = r4[j];
+            s += expf(f.x - mx) + expf(f.y - mx) + expf(f.z - mx) + expf(f.w - mx);
+        }
+    } else {
+        for (uint32_t i = threadIdx.x; i < n_vocab; i += kTopkThreads) s += expf(row[i] - mx);
+    }
+    s = r4d_wave_sum(s);
+    const uint32_t lane = threadIdx.x & (kWave - 1), wave = threadIdx.x / kWave;
+    if (lane == 0) red[wave] = s;
+    __syncthreads();
+    if (threadIdx.x == 0) {
+        float sum = 0.0f;
+        for (uint32_t w = 0; w < kTopkWaves; ++w) sum += red[w];
+        out[0] = mx;
+        out[1] = sum;
+    }
+    for (uint32_t r = threadIdx.x; r < k; r += kTopkThreads) {
+        const bool live = r < got;
+        const uint32_t loc = live ? ~(uint32_t)(cand[r] & 0xffffffffull) : 0u;
+        out[2 + 2 * r] = live ? (float)((int32_t)loc + vocab_off) : -1.0f;
+        out[3 + 2 * r] = live ? row[loc] : -INFINITY;
+    }
+}
+
 // ---------------------------------------------------------------------------- the narrowing stages
 //
 // All four read a fixed-width candidate set in place: index -1 and value -infinity mark a hole, and
@@ -1052,6 +1162,20 @@ static int r4d_sample_argmax_f32(long lg, long tok, int M, int n_vocab, int lg_l
     return hipGetLastError() == hipSuccess ? 0 : -4;
 }
 
+static int r4d_sample_logprobs_f32(long lg, long params, long stats, int M, int n_vocab, int k,
+                                   int lg_ld, int st_ld, int vocab_off, long stream) {
+    if (!lg || !params || !stats) return -1;
+    if (M <= 0 || n_vocab <= 0 || k <= 0) return -2;
+    if ((uint32_t)k > kMaxLogprobs) return -3;
+    if (!lg_ld) lg_ld = n_vocab;
+    if (!st_ld) st_ld = 2 + 2 * k;
+    hipLaunchKernelGGL(logprobs_kernel, dim3((uint32_t)M), dim3(kTopkThreads), 0,
+                       (hipStream_t)stream, (const float*)lg, (const SP*)params, (float*)stats,
+                       (uint32_t)n_vocab, (uint32_t)k, (uint32_t)lg_ld, (uint32_t)st_ld,
+                       (int32_t)vocab_off);
+    return hipGetLastError() == hipSuccess ? 0 : -4;
+}
+
 static int r4d_sample_topk_f32(long lg, long params, long cand_idx, long cand_val, long pairs,
                                    int M, int n_vocab, int n_cand,
                                    int lg_ld, int ci_ld, int cv_ld, int pr_ld, int vocab_off,
@@ -1273,6 +1397,28 @@ extern "C" int r4d_rad_sample_argmax(const RadArgs* a, RadStream s) {
                                      (long)(uintptr_t)s));
 }
 
+/* stats [M, 2 + 2k] f32: max, sum of exp(l - max), then k (global id, logit) pairs. */
+extern "C" int r4d_rad_sample_logprobs(const RadArgs* a, RadStream s) {
+    const RadTensor* lg;
+    long long M = 0, nv = 0, ld = 0;
+    R4D_NEED(logits_of(a, &lg, &M, &nv, &ld));
+    const RadTensor* pr = r4d_opt(a, V_PARAMS);
+    R4D_NEED(params_ok(pr, M));
+    const RadTensor* st = r4d_opt(a, 2);
+    if (!st) return R4D_NO(RAD_E_INVAL);
+    R4D_NEED(dt_f32(st));
+    const long long k = r4d_pgeti_or(a->p, a->n_p, "k", 0);
+    if (k <= 0 || k > (long long)kMaxLogprobs) return R4D_NO(RAD_E_SHAPE);
+    long long Ms = 0;
+    const long long st_ld = rows_pitch(st, 2 + 2 * k, &Ms);
+    if (st_ld < 0) return R4D_NO(RAD_E_STRIDE);
+    if (Ms < M) return R4D_NO(RAD_E_SHAPE);
+    const long long voff = r4d_pgeti_or(a->p, a->n_p, "vocab_off", 0);
+    R4D_LAUNCH(r4d_sample_logprobs_f32(r4d_addr(lg), r4d_addr(pr), r4d_addr(st), (int)M, (int)nv,
+                                       (int)k, (int)ld, (int)st_ld, (int)voff,
+                                       (long)(uintptr_t)s));
+}
+
 /* ------------------------------------------------------------------ top-k */
 
 enum { TK_LOGITS = 0, TK_PARAMS, TK_CI, TK_CV, TK_PAIRS };
diff --git a/libr4d/r4d_shapes.cpp b/libr4d/r4d_shapes.cpp
index 34393a7e..6507cd34 100644
--- a/libr4d/r4d_shapes.cpp
+++ b/libr4d/r4d_shapes.cpp
@@ -781,6 +781,20 @@ extern "C" int r4d_shape_sample_argmax(const RadParam* p, int n_p, int operand,
     R4D_PICK(l);
 }
 
+extern "C" int r4d_shape_sample_logprobs(const RadParam* p, int n_p, int operand,
+                                         RadOpdDesc* out) {
+
+    const int64_t M  = pi(p, n_p, "M");
+    const int64_t nv = pi(p, n_p, "n_vocab");
+    const int64_t k  = pi(p, n_p, "k");
+    const RadOpdDesc l[] = {
+        opd((uint32_t)RAD_F32, M, nv),
+        opd_sample_params(M),
+        opd((uint32_t)RAD_F32, M, 2 + 2 * k),
+    };
+    R4D_PICK(l);
+}
+
 /* top_p, min_p, typical and xtc: the same three operands, narrowed in place. */
 extern "C" int r4d_shape_sample_narrow(const RadParam* p, int n_p, int operand,
                                        RadOpdDesc* out) {
diff --git a/libref/ref_ops.h b/libref/ref_ops.h
index 454d76db..276f0209 100644
--- a/libref/ref_ops.h
+++ b/libref/ref_ops.h
@@ -168,6 +168,7 @@ int ref_sample_merge_topk  (const RadArgs*, RadStream);
 int ref_sample_mask        (const RadArgs*, RadStream);
 int ref_sample_pick        (const RadArgs*, RadStream);
 int ref_sample_argmax      (const RadArgs*, RadStream);
+int ref_sample_logprobs    (const RadArgs*, RadStream);
 
 /* ============================== OPERAND DESCRIPTION ==============================
  *
@@ -286,6 +287,7 @@ REF_SHAPE_FN(ref_sample_merge_topk);
 REF_SHAPE_FN(ref_sample_mask);
 REF_SHAPE_FN(ref_sample_pick);
 REF_SHAPE_FN(ref_sample_argmax);
+REF_SHAPE_FN(ref_sample_logprobs);
 
 }  /* extern "C" */
 #endif /* RAD_REF_OPS_H */
diff --git a/libref/ref_registry.cpp b/libref/ref_registry.cpp
index cc6d24d9..abc3ba3c 100644
--- a/libref/ref_registry.cpp
+++ b/libref/ref_registry.cpp
@@ -601,6 +601,12 @@ static const RadParamSpec pTopk[]        = { P_INT("M"), P_INT("n_vocab"), P_INT
 static const RadOperandSpec oTopk[]      = { OPD("logits"), OPD("params"),
                                              OUT("cand_idx"), OUT("cand_val"), OUT_O("pairs") };
 static const RadOperandSpec oArgmax[]    = { OPD("logits"), OPD("params"), OUT("token") };
+/* `stats` is [M, 2 + 2k]: max, sum of exp(l - max), then k (id, logit) pairs. `k` is geometry --
+ * the sampler declares the one width every request's top_logprobs fits in -- and `vocab_off` is
+ * sample_topk's, for global ids under a split vocabulary. */
+static const RadParamSpec pLogprobs[]    = { P_INT("M"), P_INT("n_vocab"), P_INT("k"),
+                                             P_INTO("vocab_off") };
+static const RadOperandSpec oLogprobs[]  = { OPD("logits"), OPD("params"), OUT("stats") };
 static const RadOperandSpec oNarrow[]    = { INOUT("cand_idx"), INOUT("cand_val"), OPD("params") };
 static const RadOperandSpec oPick[]      = { OPD("cand_idx"), OPD("cand_val"), OPD("params"),
                                              OUT("token") };
@@ -1035,6 +1041,9 @@ static const RadOpSchema kSchemas[] = {
   "same descending form the single-rank path produces. Token ids in `gathered` are already "
   "global." },
 { "sample_argmax", ARR(pMVocab), ARR(oArgmax), "Greedy, ties to the lower token id." },
+{ "sample_logprobs", ARR(pLogprobs), ARR(oLogprobs),
+  "For a row with RAD_SP_LOGPROBS: the raw logits' max, sum of exp(l - max) and k largest as (id, "
+  "logit) pairs, descending, ties to the lower id. Other rows are not written." },
 };
 
 /* ================================================================== the kernel table */
@@ -1253,6 +1262,8 @@ SIMPLE("ref_sample_mask", "sample_mask", "sample", "grammar bitmask application"
 SIMPLE("ref_sample_pick", "sample_pick", "sample", "seeded inverse-CDF draw", DT_FLOAT,
        ref_sample_pick),
 SIMPLE("ref_sample_argmax", "sample_argmax", "sample", "greedy pick", DT_FLOAT, ref_sample_argmax),
+SIMPLE("ref_sample_logprobs", "sample_logprobs", "sample", "the raw distribution's summary",
+       DT_FLOAT, ref_sample_logprobs),
 SIMPLE("ref_sample_dry", "sample_dry", "sample", "DRY repetition-suffix penalty", DT_FLOAT,
        ref_sample_dry),
 SIMPLE("ref_sample_typical", "sample_typical", "sample", "locally typical narrowing in place",
diff --git a/libref/ref_sample.cpp b/libref/ref_sample.cpp
index f04a66a2..e7f425f9 100644
--- a/libref/ref_sample.cpp
+++ b/libref/ref_sample.cpp
@@ -46,6 +46,7 @@
 
 #include "rad_sample.h"
 
+#include 
 #include 
 #include 
 
@@ -616,6 +617,58 @@ int ref_sample_argmax(const RadArgs* a, RadStream) {
     return RAD_OK;
 }
 
+/* ------------------------------------------------------------------ sample_logprobs */
+/* THE RAW DISTRIBUTION'S SUMMARY, for a row that asks for logprobs (RAD_SP_LOGPROBS): the row's
+ * maximum, the sum of exp(l - max) over it, and its k largest as (id, logit) pairs, descending,
+ * ties to the lower id, ids as floats (exact below 2^24). Read off the logits before any sampling
+ * stage has touched them, which is the distribution OpenAI's and llama-server's logprobs report.
+ * A row without the flag is not written. Under a split vocabulary the ids are global
+ * (+ `vocab_off`) and the host merges the ranks' summaries; a slot past the row's width is id -1,
+ * logit -infinity. The sum is taken in double here: this is the oracle. */
+int ref_sample_logprobs(const RadArgs* a, RadStream) {
+    if (!have(a, 3)) return RAD_E_INVAL;
+    const RadTensor *lg = &a->t[0], *pr = &a->t[1], *st = &a->t[2];
+    const int64_t n_vocab = p_int(a, "n_vocab", lg->rank >= 2 ? lg->shape[lg->rank - 1] : 0);
+    const int64_t k = p_int(a, "k", 0);
+    const int64_t voff = p_int(a, "vocab_off", 0);
+    if (n_vocab <= 0 || k <= 0) return RAD_E_SHAPE;
+    const int64_t M = numel(lg) / n_vocab;
+    const int64_t w = 2 + 2 * k;
+    if (M <= 0 || numel(st) < M * w) return RAD_E_SHAPE;
+    Rows R;
+    RAD_REF_TRY(rows_of(pr, M, &R));
+
+    #pragma omp parallel for schedule(static)
+    for (int64_t m = 0; m < M; ++m) {
+        if (!(R.p[m].flags & RAD_SP_LOGPROBS)) continue;
+        const int64_t lb = rowoff(lg, m, n_vocab), ls = laststride(lg);
+        const int64_t sb = rowoff(st, m, w), ss = laststride(st);
+        float mx = -INFINITY;
+        for (int64_t i = 0; i < n_vocab; ++i) mx = std::max(mx, ldt(lg, lb + i * ls));
+        double sum = 0.0;
+        for (int64_t i = 0; i < n_vocab; ++i) sum += std::exp((double)ldt(lg, lb + i * ls) - mx);
+        std::vector> top;
+        top.reserve((size_t)k + 1);
+        auto above = [](const std::pair& x, const std::pair& y) {
+            return x.first > y.first || (x.first == y.first && x.second < y.second);
+        };
+        for (int64_t i = 0; i < n_vocab; ++i) {
+            const std::pair e{ ldt(lg, lb + i * ls), i };
+            if ((int64_t)top.size() == k && !above(e, top.back())) continue;
+            top.insert(std::upper_bound(top.begin(), top.end(), e, above), e);
+            if ((int64_t)top.size() > k) top.pop_back();
+        }
+        stt(st, sb, mx);
+        stt(st, sb + ss, (float)sum);
+        for (int64_t j = 0; j < k; ++j) {
+            const bool have_j = j < (int64_t)top.size();
+            stt(st, sb + (2 + 2 * j) * ss, have_j ? (float)(top[(size_t)j].second + voff) : -1.0f);
+            stt(st, sb + (3 + 2 * j) * ss, have_j ? top[(size_t)j].first : -INFINITY);
+        }
+    }
+    return RAD_OK;
+}
+
 /* ------------------------------------------------------------------ sample_merge_topk */
 /* THE VOCAB-PARALLEL MERGE. lm_head is vocab-sharded, so each rank runs top-k over ITS OWN shard
  * and the candidate sets are all-gathered -- k * world_size pairs, 2 KiB at k=64 and world_size=4,
diff --git a/libref/ref_shapes.cpp b/libref/ref_shapes.cpp
index 22d8b4f6..684aa57a 100644
--- a/libref/ref_shapes.cpp
+++ b/libref/ref_shapes.cpp
@@ -1946,6 +1946,18 @@ int ref_sample_argmax_shape(const RadParam* p, int n_p, int operand, RadOpdDesc*
     return o.finish("sample_argmax", operand, out);
 }
 
+int ref_sample_logprobs_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
+    int64_t M = 0, nv = 0;
+    if (sample_vocab(p, n_p, &M, &nv) < 0) return RAD_E_UNSUPPORTED;
+    const int64_t k = gi(p, n_p, "k", 0);
+    if (k <= 0) return RAD_E_UNSUPPORTED;
+    Opd o;
+    o.t((uint32_t)RAD_F32, { M, nv });                              /* logits */
+    o.t((uint32_t)RAD_F32, { M, sample_params_words() });           /* params */
+    o.t((uint32_t)RAD_F32, { M, 2 + 2 * k });                       /* stats */
+    return o.finish("sample_logprobs", operand, out);
+}
+
 int ref_sample_topk_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
     int64_t M = 0, nv = 0;
     if (sample_vocab(p, n_p, &M, &nv) < 0) return RAD_E_UNSUPPORTED;
diff --git a/scripts/dprofd.sh b/scripts/dprofd.sh
index 9fdaa2e7..c16071f6 100755
--- a/scripts/dprofd.sh
+++ b/scripts/dprofd.sh
@@ -20,7 +20,7 @@ GPU_MAX_ALLOC_PERCENT=100 GPU_MAX_HEAP_SIZE=100 RADIANCE_PROFILE_EVERY="$EVERY"
 ./bin/radiance --model "${M:-$HOME/models/rad/q38-27b-fp8-df2.v2.rad}" \
     --radiance-home "$HOME/workspace/radiance/build/radiance_home" \
     --max-num-seqs 8 --max-model-len 24000 --checkpoint-slots 0 --no-prefix-cache \
-    --tp 2 --tp-wire wht6 --tp-wire-min-kb 128 --vram-weights-mib 20000 --vram-kv-mib 8000 \
+    --tp 2 --tp-wire wht6 --tp-wire-min-kb 128 \
     --max-num-batched-tokens 4096 --num-speculative-tokens ${DEPTH:-auto} \
     --profile-ops --port $P >> "$HOME/dprofd.log" 2>&1 &
 for i in $(seq 1 150); do
diff --git a/scripts/hfget.sh b/scripts/hfget.sh
index dd2927cf..52060dcb 100755
--- a/scripts/hfget.sh
+++ b/scripts/hfget.sh
@@ -11,6 +11,16 @@
 # matches the listing is skipped and a short one is continued with `curl -C -`, so an interrupted
 # transfer of a 300 GB checkpoint costs only what it had not finished.
 #
+# A CHANGED FILE IS FETCHED AGAIN even at the same size. A complete run records each file's content
+# key (the LFS sha256, or the size for a small file) in /.hfget-manifest, and a later run
+# compares the listing against it. The manifest is written only when every file arrived, so its
+# presence means the directory is a complete copy of some revision.
+#
+# Exit status: 0 complete; 3 nothing on disk was changed (the listing could not be read, or what is
+# still to fetch does not fit), so a complete earlier copy is intact; anything else, a transfer
+# failed and a file may be partial -- re-run to resume. `radiance --model ` serves the
+# earlier copy on 3 and refuses on the rest.
+#
 # WEIGHT DUPLICATES ARE SKIPPED. Many repos carry the same tensors several times over -- safetensors
 # beside the older pickle .bin, an ONNX export, a GGUF conversion -- and on a large checkpoint each
 # copy is hundreds of gigabytes of the same numbers. When the listing holds any .safetensors, every
@@ -64,6 +74,7 @@ dest=${2:-$HOME/models/$repo}
 rev=${3:-main}
 jobs=${HFGET_JOBS:-4}
 command -v jq >/dev/null || { echo "hfget: jq is required" >&2; exit 2; }
+command -v curl >/dev/null || { echo "hfget: curl is required" >&2; exit 2; }
 
 echo "hfget: listing $repo@$rev"
 # THE LISTING IS PAGINATED AND THE PAGE SIZE IS SMALL. A large checkpoint runs to a hundred-odd
@@ -76,15 +87,22 @@ listing='[]'
 page=0
 while [ -n "$api" ]; do
     hdr=$(mktemp "${TMPDIR:-/tmp}/hfhdr.XXXXXX")
+    # A failed request is reported here rather than by set -e, which would exit with curl's status
+    # and say nothing; and with 3, since nothing has been written yet.
+    st=0
     if [ -n "$HF_TOKEN" ]; then
-        body=$(curl -sSL --fail-with-body -D "$hdr" -H "Authorization: Bearer $HF_TOKEN" "$api")
+        body=$(curl -sSL --fail-with-body -D "$hdr" -H "Authorization: Bearer $HF_TOKEN" "$api") \
+            || st=$?
     else
-        body=$(curl -sSL --fail-with-body -D "$hdr" "$api")
+        body=$(curl -sSL --fail-with-body -D "$hdr" "$api") || st=$?
     fi
-    [ "$(printf '%s' "$body" | jq -r 'type')" = "array" ] || {
+    [ "$(printf '%s' "$body" | jq -r 'type' 2>/dev/null)" = "array" ] || {
         rm -f "$hdr"
-        echo "hfget: $(printf '%s' "$body" | jq -r '.error // .message // .')" >&2
-        echo "hfget: a gated or private repo needs HF_TOKEN in the environment" >&2; exit 1; }
+        echo "hfget: listing $repo@$rev failed (curl exit $st)" >&2
+        [ -n "$body" ] && {
+            echo "hfget: $(printf '%s' "$body" | jq -r '.error // .message // .' 2>/dev/null)" >&2
+            echo "hfget: a gated or private repo needs HF_TOKEN in the environment" >&2; }
+        exit 3; }
     listing=$(printf '%s\n%s' "$listing" "$body" | jq -s 'add')
     api=$(tr -d '\r' < "$hdr" | sed -n 's/^[Ll]ink: *<\([^>]*\)>; *rel="next".*/\1/p' | head -1)
     rm -f "$hdr"
@@ -101,14 +119,33 @@ trap 'rm -f "$list" "$dest/.hfget-manifest.tmp"' EXIT INT TERM
 printf '%s' "$listing" | jq -r "$sel"' | "\(.lfs.oid // "")\t\(.size)\t\(.path)"' > "$list"
 
 n=$(wc -l < "$list")
-[ "$n" -gt 0 ] || { echo "hfget: the listing has no files" >&2; exit 1; }
+[ "$n" -gt 0 ] || { echo "hfget: the listing has no files" >&2; exit 3; }
 need=$(awk -F'\t' '{s += $2} END {printf "%.1f", s / 1073741824}' "$list")
 mkdir -p "$dest"
+: > "$dest/.hfget-manifest.tmp"
+# WHAT IS STILL TO FETCH, not the repo's size: a warm cache of a model larger than the free space
+# left beside it must not read as a download that does not fit. A file is counted from its local
+# length, and whole when the manifest says its content changed.
+todo=0
+# Split by expansion, as the child does: a tab is IFS whitespace, so `read` would merge the empty
+# key of a non-LFS file into the next field.
+while IFS= read -r line; do
+    oid=${line%%	*}; rest=${line#*	}; size=${rest%%	*}; path=${rest#*	}
+    cur=0
+    if [ -f "$dest/$path" ]; then cur=$(wc -c < "$dest/$path"); fi
+    if [ "$cur" = "$size" ] && [ -f "$dest/.hfget-manifest" ]; then
+        rec=$(p="$path" awk -F'\t' '$2==ENVIRON["p"]{print $1; exit}' "$dest/.hfget-manifest")
+        if [ -n "$rec" ] && [ "$rec" != "${oid:-$size}" ]; then cur=0; fi
+    fi
+    if [ "$cur" -lt "$size" ]; then todo=$((todo + size - cur)); fi
+done < "$list"
 free=$(df -BG --output=avail "$dest" | tail -1 | tr -dc '0-9')
 echo "hfget: $n file(s), $need GiB -> $dest"
 [ "$have_st" -gt 0 ] && echo "hfget: safetensors present, pickle weight formats skipped"
-echo "hfget: $free GiB free on the destination filesystem"
-awk -v n="$need" -v f="$free" 'BEGIN { if (n > f) { print "hfget: THE DOWNLOAD DOES NOT FIT"; exit 1 } }'
+echo "hfget: $(awk -v t="$todo" 'BEGIN { printf "%.1f", t / 1073741824 }') GiB to fetch," \
+     "$free GiB free on the destination filesystem"
+awk -v t="$todo" -v f="$free" 'BEGIN { exit !(t / 1073741824 > f) }' \
+    && { echo "hfget: THE DOWNLOAD DOES NOT FIT" >&2; exit 3; }
 
 export HFGET_CHILD=1 HFGET_DEST="$dest" HFGET_REPO="$repo" HFGET_REV="$rev" HFGET_MAN_OUT="$dest/.hfget-manifest.tmp"
 self=$(cd "$(dirname "$0")" && pwd)/$(basename "$0")
diff --git a/scripts/mcserve.sh b/scripts/mcserve.sh
index bde94167..7d111f46 100755
--- a/scripts/mcserve.sh
+++ b/scripts/mcserve.sh
@@ -4,11 +4,6 @@
 # The sibling of scripts/fnserve.sh, for the small dense model. Same contract: start it, wait for
 # /health, print the endpoints, exit with the server still up. Stop it with scripts/fnstop.sh.
 #
-# WHY THE VRAM FLAGS ARE ABSENT. This is a DENSE model, so every weight is static and the
-# planner takes it off the top as a floor; the elastic pool left after it has no expert side to
-# claim it, so all of it goes to the cache. Stating
-# --vram-weights-mib here would only cap what does not need capping.
-#
 # WHY 131072 AND NOT 200000. n_ctx_train is 131072 for this checkpoint; the 200K context
 # scripts/fnserve.sh serves is a property of the Flash-Next model, which a 2B model cannot honour.
 #
diff --git a/spec.md b/spec.md
index 69bd549b..38bfaee8 100644
--- a/spec.md
+++ b/spec.md
@@ -37,7 +37,8 @@ source. An engine you have to fork to change is not extensible; it just has a pa
 
 **In, v1:** continuous batching, paged KV, prefix caching, tensor parallel, speculative decoding,
 hybrid KV (full + sliding-window + linear-attention state in one model), weight placement across
-VRAM / RAM / SSD with runtime re-placement, an OpenAI-compatible server, a quantiser.
+VRAM / RAM / SSD with runtime re-placement, a server for OpenAI, Anthropic and llama-server
+clients, a quantiser.
 
 **Multimodal: pictures and video, on the Qwen plugins (§11).** The vision tower is declared by the
 language model's own architecture plugin, its embeddings travel in the step batch, and an image is
@@ -946,15 +947,13 @@ last-moment rescue. That is the trade, and it buys a run phase with no device ro
 
 ## 6. Memory and budgets
 
-Every pool is budgeted explicitly, and where the operator does not state a budget the engine
-derives one **from the card and prints every term of it**. There is still no profiling pass, no
-utilisation fraction and no inference about what the workload will be:
+Every pool is budgeted explicitly: the engine derives each budget **from the card and prints every
+term of it**, and the operator moves its inputs rather than stating a pool. There is no profiling
+pass, no utilisation fraction and no inference about what the workload will be:
 
 | | |
 |---|---|
 | `--gpu-headroom-mib` | VRAM left unclaimed on every card (default 96) |
-| `--vram-weights-mib` | the resident weight slab; 0 derives it from the card |
-| `--vram-kv-mib` | the paged KV pool; 0 derives it from the card |
 | `--host-pool-mib` | pinned host tier |
 | `--weights-disk-tier` | file tier for weights, read from the container; needs `O_DIRECT` |
 
@@ -1020,9 +1019,9 @@ What *is* a hard limit, and is still checked: the pool must hold **one** max-len
 context no single request can ever complete is a configuration error however much slack the pool
 has, because the API accepts that request and admission then refuses it.
 
-`--vram-weights-mib` and `--vram-kv-mib` win outright wherever they are given, and nothing
-re-optimises a split that was stated. An engine that quietly
-re-optimises is an engine whose benchmarks do not reproduce.
+There is no flag that states either pool: the split is the resolver's, computed once from numbers
+that are all printed, and nothing re-optimises it afterwards. An engine that quietly re-optimises is
+an engine whose benchmarks do not reproduce.
 A fixed weight-slab budget also means dynamic re-placement (§5.4) never competes with the KV pool.
 The mover works inside its own slab and cannot evict a KV block to promote an expert.
 
@@ -1549,9 +1548,15 @@ its state was seen before or not, and compiling happens where the request is adm
 ## 14. Server
 
 `/v1/chat/completions` (streaming and not), `/v1/completions`, `/v1/models` and `/v1/models/:id`,
-a real `/v1/embeddings`, tool calls in and out, and a Prometheus `/metrics` endpoint with
+a real `/v1/embeddings`, tool calls in and out, logprobs, and a Prometheus `/metrics` endpoint with
 vLLM-compatible metric names so existing dashboards work unchanged.
 
+The other clients' own APIs are translated onto the same chat request rather than served by a
+second path: Anthropic's `/v1/messages`, OpenAI's `/v1/responses`, and llama-server's native
+`/completion` and `/infill`, with `/props` and `/apply-template` for the front-ends built against
+llama-server. A request field this server does not implement is ignored when it cannot change the
+output and refused by name when it would, unless it carries its off value (GUIDE §5.8).
+
 Beside those, the operational set: `/health`, `/ping`, `/load`, `/version`, `/server_info`,
 `/tokenize`, `/detokenize`, `/get_tokenizer_info`, `/reset_prefix_cache`. Method spellings follow
 vLLM's, including the ones that look wrong — `/tokenize` and `/detokenize` are POST because their
@@ -1775,11 +1780,13 @@ out of that card's selection at load rather than failing at its first launch.
 `$RADIANCE_HOME` defaults to `share/radiance` under the install prefix, and is a search path of homes
 separated by `:`, the first winning; `architectures/`, `kernels/` and `quantizers/` under each are
 scanned at startup as one set. Kernel hierarchy is configured, not discovered — an ordered list
-(`--kernels`, or `RADIANCE_KERNELS`). A library named there takes that position, one present but
-unnamed loads after every named one, and a library that declares itself a reference implementation
-(`rad_plugin_reference`) sits below every unnamed one, because it matches every op and would
-otherwise shadow whatever ranked behind it. So adding a kernel library is dropping an `.so` in a
-home, and substituting one for another is naming it ahead of the other.
+(`--kernels`, or `RADIANCE_KERNELS`). A library named there takes that position, and one present but
+unnamed is not loaded: the list chooses the libraries as well as ordering them, because selection
+runs per domain and an order alone could not keep a library out of a domain the named ones leave
+empty. With no list every library found loads, and a library that declares itself a reference
+implementation (`rad_plugin_reference`) sits below every other, because it matches every op and
+would otherwise shadow whatever ranked behind it. So adding a kernel library is dropping an `.so`
+in a home, and substituting one for another is naming it ahead of the other.
 
 The plugins that ship are plugins like any other. Each directory builds inside the tree or on its
 own against an installed radiance through `find_package(radiance)` and the same `rad_add_plugin`, and
diff --git a/tests/build_test.cpp b/tests/build_test.cpp
index ae79a6ab..906eb51a 100644
--- a/tests/build_test.cpp
+++ b/tests/build_test.cpp
@@ -622,6 +622,40 @@ TEST(an_op_with_no_host_kernel_is_a_miss_per_band_not_a_failure) {
     CHECK(host_miss);
 }
 
+/* A DEVICE HOLE IS DECIDED PER INSTANCE. Two declarations of one op, one with a weight and one
+ * without, are two instances with bands of their own: the weighted one's device miss is covered
+ * by its host kernel, because the planner moves it to the host by placing its weight there, and
+ * on a card only the weightless instance's miss is a hole. */
+TEST(a_device_hole_is_decided_per_instance) {
+    Program p;
+    p.ops.resize(3);
+    p.ops[1].op = "rmsnorm";                          /* no weight */
+    p.ops[1].index = 1;
+    p.ops[2].op = "rmsnorm";
+    p.ops[2].index = 2;
+    p.ops[2].weights = { 1 };
+    auto miss = [](int32_t index, int domain) {
+        Program::Miss m;
+        m.op = "rmsnorm";
+        m.span = "M <= 64";
+        m.why = "no kernel matched";
+        m.domain = domain;
+        m.index = index;
+        return m;
+    };
+    p.misses.push_back(miss(2, RAD_DOMAIN_DEVICE));   /* the weighted one; its host kernel exists */
+    CHECK_EQ((int)p.device_holes(false).size(), 0);
+
+    p.misses.push_back(miss(1, RAD_DOMAIN_DEVICE));   /* the weightless one */
+    CHECK_EQ((int)p.device_holes(false).size(), 1);
+    CHECK_EQ(p.device_holes(false)[0]->index, 1);
+    CHECK_EQ((int)p.device_holes(true).size(), 0);    /* the host backend runs both on the host */
+
+    p.misses.push_back(miss(2, RAD_DOMAIN_HOST));     /* no host kernel for the weighted one */
+    CHECK_EQ((int)p.device_holes(true).size(), 1);
+    CHECK_EQ(p.device_holes(true)[0]->index, 2);
+}
+
 /* ================================================================== init, after the whole graph */
 TEST(a_refusing_init_becomes_a_miss_and_not_an_abort) {
     NEED_PLUGIN(reg)
diff --git a/tests/chatparse_test.cpp b/tests/chatparse_test.cpp
index ecf25f60..33a8d075 100644
--- a/tests/chatparse_test.cpp
+++ b/tests/chatparse_test.cpp
@@ -1332,7 +1332,7 @@ TEST(what_a_streaming_client_assembles_is_the_buffered_answer) {
             for (size_t i = 0; i < reply.size(); ++i)
                 sse += st.push(std::string_view(reply).substr(i, 1), false);
             sse += st.push(std::string_view(), true);
-            sse += st.final_chunk(server::Finish::Stop);
+            sse += st.final_chunk(server::Finish::Stop, server::TimingsOut(), server::UsageOut());
 
             std::string content, reasoning, finish;
             std::vector ids, names, args;
diff --git a/tests/checkpoint_test.cpp b/tests/checkpoint_test.cpp
index 7f9e7f0e..0711eec5 100644
--- a/tests/checkpoint_test.cpp
+++ b/tests/checkpoint_test.cpp
@@ -36,10 +36,8 @@ std::string dir_path() {
            std::to_string((long long)getpid());
 }
 
-/* One model.safetensors and a config.json in a fresh directory. */
-std::string write_checkpoint(const std::vector& ts, const std::string& config) {
-    const std::string dir = dir_path();
-    ::mkdir(dir.c_str(), 0755);
+/* One safetensors file holding `ts`, in order. */
+void write_shard(const std::string& path, const std::vector& ts) {
     std::string hdr = "{";
     uint64_t off = 0;
     for (size_t i = 0; i < ts.size(); ++i) {
@@ -53,13 +51,20 @@ std::string write_checkpoint(const std::vector& ts, const std::string& config
     }
     hdr += "}";
     while (hdr.size() % 8) hdr += ' ';
-    FILE* f = std::fopen((dir + "/model.safetensors").c_str(), "wb");
+    FILE* f = std::fopen(path.c_str(), "wb");
     const uint64_t n = hdr.size();
     std::fwrite(&n, 8, 1, f);
     std::fwrite(hdr.data(), 1, hdr.size(), f);
     for (const T& t : ts) std::fwrite(t.bytes.data(), 1, t.bytes.size(), f);
     std::fclose(f);
-    f = std::fopen((dir + "/config.json").c_str(), "wb");
+}
+
+/* One model.safetensors and a config.json in a fresh directory. */
+std::string write_checkpoint(const std::vector& ts, const std::string& config) {
+    const std::string dir = dir_path();
+    ::mkdir(dir.c_str(), 0755);
+    write_shard(dir + "/model.safetensors", ts);
+    FILE* f = std::fopen((dir + "/config.json").c_str(), "wb");
     std::fwrite(config.data(), 1, config.size(), f);
     std::fclose(f);
     return dir;
@@ -122,6 +127,23 @@ TEST(the_metadata_names_the_architecture_and_the_quantisation) {
     remove_checkpoint(dir);
 }
 
+/* rad-convert's --set of quantization_config re-derives the descriptor from the same keys, so a
+ * bf16 checkpoint whose recipe writes block fp8 is converted for the fp8 plugin by stating the
+ * format, and the container never states one format while selecting the plugin of another. */
+TEST(the_descriptor_is_quant_method_and_fmt_whoever_set_them) {
+    const std::string dir = write_checkpoint({ bf16("x", { 2, 2 }, 0) },
+                                             "{\"model_type\":\"qwen3_5\",\"hidden_size\":256}");
+    Checkpoint ck;
+    REQUIRE_EQ(ck.open(dir), RAD_OK);
+    CHECK_EQ(ck.meta().quant, std::string());
+    MetaOwn m = ck.meta();
+    m.set("quantization_config.quant_method", "fp8");
+    CHECK_EQ(quant_descriptor(m), std::string("fp8"));
+    m.set("quantization_config.fmt", "e4m3");
+    CHECK_EQ(quant_descriptor(m), std::string("fp8_e4m3"));
+    remove_checkpoint(dir);
+}
+
 TEST(a_plain_tensor_is_its_own_encoding_and_reads_back_as_itself) {
     const std::string dir = write_checkpoint({ bf16("a.weight", { 4, 8 }, 1.0f) }, "{}");
     Checkpoint ck;
@@ -620,3 +642,45 @@ TEST(a_quark_mxfp4_weight_is_its_codes_and_exponents) {
     CHECK(w.trivial && rad_enc_is(&w.enc, "plain"));
     remove_checkpoint(dir);
 }
+
+/* A DIRECTORY THAT MERGES TWO CHECKPOINTS holds some tensors in two shards: a finetune's changed
+ * tensors in shards of its own beside links to every shard of the base model, which still carry
+ * the old copies. The index is what says which copy is the model's, so it is what decides; a name
+ * in two shards that no index entry settles is refused rather than read from whichever shard sorts
+ * first. */
+TEST(the_index_decides_which_shard_a_tensor_is_read_from) {
+    const std::string dir = dir_path();
+    ::mkdir(dir.c_str(), 0755);
+    const T base_x = bf16("x.weight", { 2, 4 }, 1.0f), base_y = bf16("y.weight", { 4 }, 2.0f);
+    const T ft_x = bf16("x.weight", { 2, 4 }, 5.0f);
+    write_shard(dir + "/a.safetensors", { base_x, base_y });   /* sorts first */
+    write_shard(dir + "/b.safetensors", { ft_x });
+    auto put = [&](const char* name, const std::string& body) {
+        FILE* f = std::fopen((dir + "/" + name).c_str(), "wb");
+        std::fwrite(body.data(), 1, body.size(), f);
+        std::fclose(f);
+    };
+    put("config.json", kConfig);
+    put("model.safetensors.index.json",
+        R"({"weight_map":{"x.weight":"b.safetensors","y.weight":"a.safetensors"}})");
+    {
+        Checkpoint ck;
+        REQUIRE_EQ(ck.open(dir), RAD_OK);
+        const SrcTensor* x = ck.find("x.weight");
+        const SrcTensor* y = ck.find("y.weight");
+        REQUIRE(x && y);
+        CHECK_EQ(std::memcmp(x->data, ft_x.bytes.data(), ft_x.bytes.size()), 0);
+        CHECK_EQ(std::memcmp(y->data, base_y.bytes.data(), base_y.bytes.size()), 0);
+    }
+    /* the index names both shards but not x: two copies and nothing to choose between them */
+    put("model.safetensors.index.json",
+        R"({"weight_map":{"y.weight":"a.safetensors","z.weight":"b.safetensors"}})");
+    {
+        Checkpoint ck;
+        CHECK_EQ(ck.open(dir), RAD_E_FORMAT);
+    }
+    for (const char* f : { "a.safetensors", "b.safetensors", "config.json",
+                           "model.safetensors.index.json" })
+        std::remove((dir + "/" + f).c_str());
+    ::rmdir(dir.c_str());
+}
diff --git a/tests/config_test.cpp b/tests/config_test.cpp
index 50f81d3b..283af3c9 100644
--- a/tests/config_test.cpp
+++ b/tests/config_test.cpp
@@ -161,14 +161,21 @@ TEST(the_model_is_required_and_nothing_else_is) {
 
 /* ================================================================== taken */
 
+TEST(the_pool_size_flags_are_gone_and_say_what_replaced_them) {
+    /* The card's split is the resolver's (core/mem/vram_budget.h); a launch line that sizes a
+     * pool is refused by name, not served with a split other than the one it asked for. */
+    Config c;
+    CHECK_EQ(parse({ "--vram-weights-mib", "20480" }, &c), RAD_E_INVAL);
+    Config k;
+    CHECK_EQ(parse({ "--vram-kv-mib", "6144" }, &k), RAD_E_INVAL);
+}
+
 TEST(the_sizes_and_counts_reach_the_fields_they_name) {
     Config c;
     CHECK_EQ(parse({ "--tp", "2",
                      "--max-num-batched-tokens", "512",
                      "--max-num-seqs", "8",
                      "--max-model-len", "200000",
-                     "--vram-weights-mib", "20480",
-                     "--vram-kv-mib", "6144",
                      "--host-pool-mib", "12288",
                      "--prefix-cache-host-mib", "4096",
                      "--prefix-cache-disk-mib", "65536",
@@ -180,8 +187,6 @@ TEST(the_sizes_and_counts_reach_the_fields_they_name) {
     CHECK_EQ(c.max_tok, 512ll);
     CHECK_EQ(c.max_seqs, 8ll);
     CHECK_EQ(c.max_ctx, 200000ll);
-    CHECK_EQ(c.vram_weights_mib, 20480ll);
-    CHECK_EQ(c.vram_kv_mib, 6144ll);
     CHECK_EQ(c.host_pool_mib, 12288ll);
     CHECK_EQ(c.prefix_cache_host_mib, 4096ll);
     CHECK_EQ(c.prefix_cache_disk_mib, 65536ll);
@@ -339,22 +344,32 @@ TEST(the_kv_cache_dtype_is_one_of_two_names) {
     CHECK_EQ(d.kv_cache_dtype, std::string("bf16"));
 }
 
-/* THE TWO TABLE PLACEMENTS take the same four names and nothing else, default to auto, and leave
- * the resolved values to Engine::plan: a parse never decides a tier. Where each table may go is
- * the engine's to refuse, with the model in hand -- not the parser's. */
-TEST(the_table_placements_are_auto_vram_ram_or_disk) {
+/* THE TWO TABLE PLACEMENTS: the embedding takes ram (the default) or vram, the n-gram table auto
+ * (the default), vram, ram or disk, and nothing else. A parse records whether the embedding's was
+ * named and leaves the resolved values to Engine::plan: where each table may go is the engine's to
+ * refuse, with the model in hand -- not the parser's. */
+TEST(the_embedding_is_ram_or_vram_and_the_ngram_table_takes_four) {
     Config d;
     CHECK_EQ(parse({}, &d), RAD_OK);
-    CHECK(d.embedding_placement == TablePlacement::Auto);
+    CHECK(d.embedding_placement == TablePlacement::Ram);
+    CHECK(!d.embedding_placement_given);
     CHECK(d.ngram_placement == TablePlacement::Auto);
+    CHECK_EQ(d.embedding_host_mib, 0ll);                     /* the resolver's */
     Config c;
     CHECK_EQ(parse({ "--embedding-placement", "ram", "--ngram-placement", "disk" }, &c), RAD_OK);
     CHECK(c.embedding_placement == TablePlacement::Ram);
+    CHECK(c.embedding_placement_given);
     CHECK(c.ngram_placement == TablePlacement::Disk);
-    CHECK_EQ(parse({ "--embedding-placement", "vram", "--ngram-placement", "auto" }, &c), RAD_OK);
-    CHECK(c.embedding_placement == TablePlacement::Vram);
-    CHECK(c.ngram_placement == TablePlacement::Auto);
-    CHECK(c.embedding_resolved == TablePlacement::Vram);     /* untouched until plan */
+    Config v;
+    CHECK_EQ(parse({ "--embedding-placement", "vram", "--ngram-placement", "auto" }, &v), RAD_OK);
+    CHECK(v.embedding_placement == TablePlacement::Vram);
+    CHECK(v.embedding_placement_given);
+    CHECK(v.ngram_placement == TablePlacement::Auto);
+    CHECK(v.embedding_resolved == TablePlacement::Vram);     /* untouched until plan */
+    CHECK_EQ(parse({ "--ngram-placement", "ram" }, &v), RAD_OK);
+    CHECK(v.ngram_placement == TablePlacement::Ram);
+    for (const char* bad : { "auto", "disk" })
+        CHECK_EQ(parse({ "--embedding-placement", bad }, &c), RAD_E_INVAL);
     for (const char* bad : { "RAM", "memory", "host", "" }) {
         CHECK_EQ(parse({ "--embedding-placement", bad }, &c), RAD_E_INVAL);
         CHECK_EQ(parse({ "--ngram-placement", bad }, &c), RAD_E_INVAL);
@@ -794,6 +809,17 @@ TEST(the_environment_supplies_what_the_line_left_unsaid) {
 
 /* LATER WINS, for every flag that takes a value. Scripts build these lines by appending, and a
  * parser that kept the first occurrence would make an override a no-op. */
+TEST(the_download_dir_is_taken_and_left_empty_until_given) {
+    /* Empty means "the XDG cache", which hf_model.cpp resolves only when --model is a repo id:
+     * a server started on a local file never reads HOME for it. */
+    Config c;
+    CHECK_EQ(parse({}, &c), 0);
+    CHECK(c.download_dir.empty());
+    Config d;
+    CHECK_EQ(parse({ "--download-dir", "/big/models" }, &d), 0);
+    CHECK_EQ(d.download_dir, std::string("/big/models"));
+}
+
 TEST(a_repeated_flag_takes_the_last_one) {
     Config c;
     CHECK_EQ(parse({ "--port", "1", "--port", "8100" }, &c), RAD_OK);
@@ -844,7 +870,8 @@ TEST(usage_names_every_flag_it_documents) {
                            "--dry-sequence-breakers", "--chat-template-kwargs",
                            "--reasoning-format", "--max-n", "--max-queued-requests",
                            "--max-stop-strings", "--http-threads", "--max-body-mib", "--no-cors",
-                           "--image-max-pixels", "--video-fps", "--max-source-pixels" })
+                           "--image-max-pixels", "--video-fps", "--max-source-pixels",
+                           "--download-dir" })
         CHECK(text.find(f) != std::string::npos);
     CHECK(text.size() > 1000);
 }
diff --git a/tests/data/media/README.md b/tests/data/media/README.md
index 643fcf56..acc8f558 100644
--- a/tests/data/media/README.md
+++ b/tests/data/media/README.md
@@ -11,6 +11,7 @@ V="-f lavfi -i color=c=red:s=64x64:d=1:r=4"
 ffmpeg $I -frames:v 1 red.png
 ffmpeg $I -frames:v 2 -f apng red.apng
 ffmpeg $I -frames:v 1 red.jpg
+ffmpeg -f lavfi -i color=c=red:s=1788x282:d=1:r=1 -frames:v 1 red-1788x282.jpg
 ffmpeg $I -frames:v 1 -c:v libwebp red.webp
 ffmpeg $I -frames:v 1 red.gif
 ffmpeg $I -frames:v 1 red.bmp
@@ -30,5 +31,8 @@ ffmpeg $V -c:v mpeg4 red-mpeg4.avi
 ffmpeg $V -c:v libtheora red-theora.ogv
 ```
 
+`red-1788x282.jpg` is 4:2:0 at a width the scaler's vectors do not divide: converted to RGB it
+is written 12 bytes past width x 3 (`a_picture_of_an_awkward_width_converts_inside_its_buffer`).
+
 The Theora clip repeats its first frame with empty packets, which is how Ogg Theora encodes a frame
 that does not change.
diff --git a/tests/data/media/red-1788x282.jpg b/tests/data/media/red-1788x282.jpg
new file mode 100644
index 00000000..e5f2ad15
Binary files /dev/null and b/tests/data/media/red-1788x282.jpg differ
diff --git a/tests/hf_model_test.cpp b/tests/hf_model_test.cpp
new file mode 100644
index 00000000..931692ea
--- /dev/null
+++ b/tests/hf_model_test.cpp
@@ -0,0 +1,124 @@
+/* hf_model_test.cpp -- a --model that names a Hugging Face repo (core/hf_model.h).
+ *
+ * Two questions, both answered before anything is fetched, and both wrong in a way that costs a
+ * download or a confusing refusal:
+ *
+ *   IS IT A REPO   a path that exists is never looked up, and a missing model FILE is reported as
+ *                  missing rather than sent to the hub as a repo name
+ *   WHAT TO SERVE  the hub's model repos hold one container beside a README, a recipe and a
+ *                  licence; a checkpoint repo holds none and is served as the directory
+ *
+ * No network: the fetch itself is scripts/hfget.sh, which this does not run.
+ */
+#include "rad_test.h"
+
+#include "hf_model.h"
+
+#include 
+#include 
+#include 
+#include 
+#include 
+
+using namespace rad;
+namespace fs = std::filesystem;
+
+namespace {
+
+/* A scratch directory of its own, removed with everything in it. */
+struct TempDir {
+    std::string path;
+    TempDir() {
+        char t[] = "/tmp/hf_model_test.XXXXXX";
+        path = mkdtemp(t) ? t : "";
+    }
+    ~TempDir() {
+        std::error_code ec;
+        if (!path.empty()) fs::remove_all(path, ec);
+    }
+    void touch(const std::string& name) const {
+        if (FILE* f = std::fopen((path + "/" + name).c_str(), "w")) std::fclose(f);
+    }
+};
+
+}  /* namespace */
+
+TEST(a_repo_id_is_two_names_of_the_hubs_characters) {
+    CHECK(hf_repo_id("StillDeadcode/minicpm5-2b-fp8"));
+    CHECK(hf_repo_id("StillDeadcode/qwen3.8-27b-mxfp4"));
+    CHECK(hf_repo_id("Qwen/Qwen3.8-Flash-Next"));
+    CHECK(hf_repo_id("hf-internal-testing/tiny_random.v2"));
+
+    CHECK(!hf_repo_id(""));
+    CHECK(!hf_repo_id("minicpm5-2b-fp8"));               /* no owner */
+    CHECK(!hf_repo_id("/abs/model"));                     /* absolute */
+    CHECK(!hf_repo_id("a/b/c"));                          /* a path, not a repo */
+    CHECK(!hf_repo_id("owner/"));
+    CHECK(!hf_repo_id("/name"));
+    CHECK(!hf_repo_id("../x"));                           /* a relative path, not a name */
+    CHECK(!hf_repo_id("./x"));
+    CHECK(!hf_repo_id("owner/.hidden"));
+    CHECK(!hf_repo_id("-x/y"));                           /* would read as an option */
+    CHECK(!hf_repo_id("owner/name with space"));
+    CHECK(!hf_repo_id("owner/na$me"));
+    CHECK(!hf_repo_id("C:/models"));
+}
+
+TEST(a_missing_model_file_is_not_sent_to_the_hub) {
+    CHECK(!hf_repo_id("models/qwen.rad"));
+    CHECK(!hf_repo_id("ckpt/model.safetensors"));
+    CHECK(!hf_repo_id("ckpt/model.gguf"));
+    CHECK(!hf_repo_id("ckpt/model.safetensors.index.json"));
+}
+
+TEST(a_path_that_exists_is_never_a_repo) {
+    TempDir t;
+    CHECK(!t.path.empty());
+    const std::string cwd = fs::current_path().string();
+    CHECK_EQ(chdir(t.path.c_str()), 0);
+    fs::create_directories("owner/name");
+    CHECK(!hf_repo_id("owner/name"));                     /* exists: a checkpoint directory */
+    CHECK(hf_repo_id("owner/other"));                     /* does not: a repo */
+    CHECK_EQ(chdir(cwd.c_str()), 0);
+}
+
+TEST(the_one_container_in_a_repo_is_what_is_served) {
+    TempDir t;
+    t.touch("README.md");
+    t.touch("LICENSE");
+    t.touch("q38-27b.recipe");
+    t.touch(".hfget-manifest");
+    std::string why;
+    CHECK_EQ(hf_served_path(t.path, &why), t.path);       /* no container: a checkpoint */
+
+    t.touch("qwen3.8-27b-mxfp4.rad");
+    CHECK_EQ(hf_served_path(t.path, &why), t.path + "/qwen3.8-27b-mxfp4.rad");
+
+    fs::create_directories(t.path + "/sub");
+    t.touch("sub/other.rad");                             /* only the top level counts */
+    CHECK_EQ(hf_served_path(t.path, &why), t.path + "/qwen3.8-27b-mxfp4.rad");
+}
+
+TEST(two_containers_are_refused_by_name) {
+    TempDir t;
+    t.touch("a.rad");
+    t.touch("b.rad");
+    std::string why;
+    CHECK_EQ(hf_served_path(t.path, &why), std::string());
+    CHECK(why.find("a.rad") != std::string::npos);
+    CHECK(why.find("b.rad") != std::string::npos);
+    CHECK(why.find("--model") != std::string::npos);
+}
+
+TEST(the_download_dir_defaults_to_the_xdg_cache) {
+    const char* x = std::getenv("XDG_CACHE_HOME");
+    const std::string saved = x ? x : "";
+    setenv("XDG_CACHE_HOME", "/c", 1);
+    CHECK_EQ(hf_default_download_dir(), std::string("/c/radiance/hf"));
+    unsetenv("XDG_CACHE_HOME");
+    if (const char* h = std::getenv("HOME"); h && *h)
+        CHECK_EQ(hf_default_download_dir(), std::string(h) + "/.cache/radiance/hf");
+    if (x) setenv("XDG_CACHE_HOME", saved.c_str(), 1);
+}
+
+RAD_TEST_MAIN()
diff --git a/tests/mem_test.cpp b/tests/mem_test.cpp
index d90df530..cfc9a324 100644
--- a/tests/mem_test.cpp
+++ b/tests/mem_test.cpp
@@ -126,14 +126,14 @@ static void publish(Fixture& f, uint64_t id, const std::vector& tokens,
 
 /* ================================================================== pools */
 
-TEST(pool_budgets_are_stated_not_inferred) {
+TEST(pools_refuse_a_split_the_resolver_never_made) {
     Config c;
-    c.vram_weights_mib = 0;     /* the operator said nothing */
+    c.vram_weights_mib = 0;     /* the resolver never ran */
     c.vram_kv_mib = 0;
     Pools p;
     CHECK_EQ(p.configure(c, 0, &rad_malloc_allocator(), &rad_malloc_allocator()), RAD_E_INVAL);
-    CHECK(p.fit_report().find("--vram-weights-mib") != std::string::npos);
-    CHECK(p.fit_report().find("--vram-kv-mib") != std::string::npos);
+    CHECK(p.fit_report().find("vram_weights resolved to 0 MiB") != std::string::npos);
+    CHECK(p.fit_report().find("vram_kv resolved to 0 MiB") != std::string::npos);
     CHECK(!p.configured());
 }
 
@@ -198,6 +198,44 @@ TEST(a_refused_backing_allocation_says_it_was_refused_and_why) {
 
 /* ================================================================== the derived budget */
 
+TEST(a_device_with_no_capacity_sizes_its_pools_from_the_program) {
+    /* A device that reports no capacity: the pools are still derived, from what the program
+     * needs rather than from a share of anything. */
+    Config c = small_config();
+    c.vram_weights_mib = 0;
+    c.vram_kv_mib      = 0;
+    VramFacts f{};
+    f.statics    = 0;                 /* every op on the host: its weights stay in the mapping */
+    f.kv_ceiling = 300LL << 20;
+    VramBudget b;
+    CHECK_OK(vram_budget_resolve(c, { f }, &b));
+    CHECK_EQ(c.vram_weights_mib, (int64_t)1);           /* a pool nothing is placed in */
+    CHECK_EQ(c.vram_kv_mib, (int64_t)300);              /* every sequence at the full context */
+
+    f.statics = 5LL << 20;                              /* a device-domain op's weights */
+    Config c2 = small_config();
+    c2.vram_weights_mib = 0;
+    c2.vram_kv_mib      = 0;
+    CHECK_OK(vram_budget_resolve(c2, { f }, &b));
+    CHECK_EQ(c2.vram_weights_mib, (int64_t)5);
+}
+
+TEST(a_program_that_copies_no_weight_still_gets_a_weights_pool) {
+    /* Every op on the host -- CPU-only serving -- reads its weights where the container's mapping
+     * has them, so nothing is copied to the weights pool. It still has to exist: a zero budget is
+     * what the pools refuse as a resolver that never ran. */
+    Config c = small_config();
+    VramFacts f{};
+    f.capacity   = 16LL << 30;        /* the host backend presents half the machine as a card */
+    f.free       = f.capacity;
+    f.arena      = 64LL << 20;
+    f.kv_ceiling = 300LL << 20;
+    VramBudget b;
+    CHECK_OK(vram_budget_resolve(c, { f }, &b));
+    CHECK_EQ(c.vram_weights_mib, (int64_t)1);
+    CHECK(c.vram_kv_mib >= 299);
+}
+
 TEST(derived_budget_takes_the_statics_off_the_top_then_divides_the_rest) {
     /* With no lender stated the experts come first; what each side gets is the subject of the
      * cases below. */
@@ -223,7 +261,6 @@ TEST(derived_budget_takes_the_statics_off_the_top_then_divides_the_rest) {
     /* Held, the driver's drift on it, the headroom and the arena. */
     CHECK_EQ(b.drift, 16LL << 20);
     CHECK_EQ(b.claimable, f.capacity - (512LL << 20) - (16LL << 20) - (96LL << 20) - (144LL << 20));
-    CHECK(b.derived_weights && b.derived_kv);
 
     /* THE FLOOR IS NOT A SHARE. The statics come out whole before the split sees anything, so
      * nothing the cache is given can demote an attention projection to host memory. */
@@ -425,25 +462,6 @@ TEST(the_engine_s_queues_come_off_the_card_before_the_split) {
     CHECK(unclaimed < 114 * MiB);
 }
 
-TEST(a_stated_budget_still_wins_and_the_other_side_still_derives) {
-    Config c = small_config();
-    c.vram_weights_mib = 20000;          /* stated */
-    c.vram_kv_mib      = 0;              /* derived */
-    c.gpu_headroom_mib = 96;
-
-    VramFacts f{};
-    f.capacity   = 32LL << 30;
-    f.free       = f.capacity - (512LL << 20);
-    f.arena      = 144LL << 20;
-    f.kv_ceiling = 100LL << 30;
-
-    VramBudget b;
-    CHECK_OK(vram_budget_resolve(c, { f }, &b));
-    CHECK_EQ(c.vram_weights_mib, 20000ll);        /* untouched */
-    CHECK(!b.derived_weights && b.derived_kv);
-    CHECK_EQ(b.kv, b.claimable);                  /* the KV pool gets everything that is left */
-}
-
 TEST(the_smallest_card_binds_and_a_short_one_refuses_by_name) {
     Config c = small_config();
     c.vram_weights_mib = 0;
@@ -756,7 +774,7 @@ TEST(kv_refuses_a_group_with_no_block_size) {
 
 TEST(kv_refuses_when_fixed_costs_do_not_fit) {
     /* --max-seqs 128 at 16 KiB of GDN state each is 2 MiB of fixed cost against a 1 MiB
-     * --vram-kv-mib. Refused by name, with the arithmetic printed; not silently served at fewer
+     * the KV pool. Refused by name, with the arithmetic printed; not silently served at fewer
      * sequences than the operator asked for. */
     Fixture f;
     f.cfg.max_seqs = 128;
diff --git a/tests/mm_test.cpp b/tests/mm_test.cpp
index 11cde127..f2fc81e9 100644
--- a/tests/mm_test.cpp
+++ b/tests/mm_test.cpp
@@ -22,6 +22,7 @@
 #include 
 #include 
 #include 
+#include 
 #include 
 #include 
 #include 
@@ -283,6 +284,31 @@ TEST(every_admitted_picture_format_decodes) {
     }
 }
 
+/* A PICTURE WIDER THAN A WHOLE NUMBER OF THE SCALER'S VECTORS: 4:2:0 at 1788 wide is converted to
+ * RGB 12 bytes past 1788 x 3. Into a buffer of exactly that size those bytes were the next heap
+ * chunk's header, and the server aborted at a later allocation (Codeberg #57). The mmap threshold
+ * is raised so the RGB comes from the heap proper, as it does in a server that has freed large
+ * buffers before; glibc then checks the neighbouring headers on every free below. */
+TEST(a_picture_of_an_awkward_width_converts_inside_its_buffer) {
+    if (!decoder_available()) { std::printf("  SKIP no media decoder in this build\n"); return; }
+    const std::vector b = media_file("red-1788x282.jpg");
+    REQUIRE(!b.empty());
+    mallopt(M_MMAP_THRESHOLD, 64 << 20);
+    for (int i = 0; i < 8; ++i) {
+        Frame f;
+        std::string why;
+        const int rc = decode_image(b.data(), b.size(), int64_t(1) << 24, &f, &why);
+        if (rc != RAD_OK) std::printf("  %s\n", why.c_str());
+        CHECK_EQ(rc, RAD_OK);
+        CHECK_EQ(f.w, 1788);
+        CHECK_EQ(f.h, 282);
+        CHECK(is_red(f));
+        std::vector behind(4096, 1);
+        CHECK_EQ(behind[0], 1);
+    }
+    mallopt(M_MMAP_THRESHOLD, 128 << 10);
+}
+
 TEST(every_admitted_video_format_decodes) {
     if (!decoder_available()) { std::printf("  SKIP no media decoder in this build\n"); return; }
     for (const char* name : { "red-h264.mp4", "red-hevc.mp4", "red-av1.mp4", "red-vp8.webm",
diff --git a/tests/place_test.cpp b/tests/place_test.cpp
index 81b97753..f2c0bb3d 100644
--- a/tests/place_test.cpp
+++ b/tests/place_test.cpp
@@ -392,13 +392,13 @@ TEST(planner_spills_experts_before_dense_weights) {
     CHECK_OK(Planner(in).plan(&p));
 
     /* THREE resident, not four, and the fourth slot is the shadow. Spare slots come out of
-     * --vram-weights-mib like everything else in the slab -- there is nowhere else for them to
+     * the weights pool like everything else in the slab -- there is nowhere else for them to
      * come from, because --gpu-headroom-mib is memory the engine promises not to touch -- so
      * dynamic placement costs a resident unit and the report says how many. */
     CHECK_EQ(p.totals.bytes[(int)Tier::VRAM], 3 * MiB);
     CHECK_EQ(p.totals.bytes[(int)Tier::HostPinned], 6 * MiB);
     CHECK_EQ(p.slab_overhead, 1 * MiB + RAD_ALIGN_UNIT);
-    /* And the whole of it fits the budget the operator stated, which is the property that stops
+    /* And the whole of it fits the budget the plan was given, which is the property that stops
      * the mover overrunning the pool that was sized for it. */
     CHECK(p.totals.bytes[(int)Tier::VRAM] + p.slab_overhead <= p.vram_budget);
 
@@ -475,7 +475,7 @@ TEST(the_expert_floor_places_every_expert) {
         f.op("moe_gemm", d, false);
     }
     WeightFootprint wf;
-    weight_footprint(f.prog, &wf, TablePlacement::Vram, TablePlacement::Disk);
+    weight_footprint(f.prog, &wf, TablePlacement::Vram, TablePlacement::Disk, false, true);
     CHECK(wf.expert_spare > 0);
 
     const int64_t host = 100 * MiB;
@@ -633,7 +633,7 @@ TEST(planner_reads_routed_experts_it_cannot_hold_from_the_container) {
     /* The buffers are the largest layer's file-tier units, twice, at the stager's packing. */
     CHECK_EQ(p.file_layer_max, std::max(per_layer[0], per_layer[1]));
     CHECK(p.file_stage_vram >= 2 * p.file_layer_max + (int64_t)RAD_ALIGN_UNIT);
-    /* And everything the VRAM side holds fits the budget the operator stated -- the residents,
+    /* And everything the VRAM side holds fits the budget the plan was given -- the residents,
      * the shadow slots and the two buffers -- so the mover cannot overrun the pool. */
     CHECK(p.totals.bytes[(int)Tier::VRAM] + p.slab_overhead + p.file_stage_vram <= p.vram_budget);
     /* The exact prefetch's ring is not for these: the file stager reads into its own buffers. */
@@ -2169,7 +2169,7 @@ TEST(the_stager_stages_each_layer_one_layer_ahead_and_releases_it_when_the_next_
 }
 
 TEST(mover_reserves_from_the_weight_pool_rather_than_beside_it) {
-    /* THE PRODUCTION PATH. Pools has already allocated --vram-weights-mib as one block; a mover
+    /* THE PRODUCTION PATH. Pools has already allocated the weights pool as one block; a mover
      * that called the allocator beside it would spend that budget twice and the overrun would
      * surface as an out-of-memory from some unrelated launch much later. Reserving from
      * Pools::weights() is also what makes it structurally impossible for a promotion to reach a
@@ -2189,7 +2189,7 @@ TEST(mover_reserves_from_the_weight_pool_rather_than_beside_it) {
     MoverConfig mc;
     CHECK_OK(m.init(hf.f.prog, hf.plan, mc, &pools));
 
-    /* Every byte the mover took came out of the stated budgets, and none of it out of KV. */
+    /* Every byte the mover took came out of the pools' budgets, and none of it out of KV. */
     CHECK(pools.weights().used() > weights_before);
     CHECK(pools.host_pinned().used() > host_before);
     CHECK_EQ(pools.kv().used(), (int64_t)0);
@@ -2331,7 +2331,7 @@ TEST(the_weight_footprint_splits_statics_from_the_elastic_expert_plane) {
     build_moe(f, /*n=*/4, /*each=*/2 * MiB, &experts);
 
     WeightFootprint fp;
-    weight_footprint(f.prog, &fp, TablePlacement::Vram, TablePlacement::Disk);
+    weight_footprint(f.prog, &fp, TablePlacement::Vram, TablePlacement::Disk, false, true);
 
     /* One model-level weight and four experts: five units. */
     CHECK_EQ(fp.n_units, 5ll);
@@ -2361,12 +2361,12 @@ TEST(weights_in_one_layer_are_one_unit_and_are_aligned_once_each) {
     }
 
     WeightFootprint fp;
-    weight_footprint(f.prog, &fp, TablePlacement::Vram, TablePlacement::Disk);
+    weight_footprint(f.prog, &fp, TablePlacement::Vram, TablePlacement::Disk, false, true);
     CHECK_EQ(fp.n_units, 2ll);              /* the declared group is the unit, not the weight */
 
     /* ONE align_up A UNIT AND ONE INSIDE IT, which is how Mover::init spends the slab. A budget
        that summed raw bytes would be short by an alignment per unit -- on a 512-expert MoE that
-       is real memory, and the failure is an overrun of the pool the operator sized. */
+       is real memory, and the failure is an overrun of the weights pool. */
     const int64_t per_unit = align_up(align_up(odd, RAD_ALIGN_UNIT) + odd, RAD_ALIGN_UNIT);
     CHECK_EQ(fp.statics, 2 * per_unit);
     CHECK(fp.statics > 4 * odd);
@@ -2394,12 +2394,67 @@ TEST(a_weight_with_no_device_band_takes_its_whole_unit_to_the_mapped_tier) {
     f.prog.ops.push_back(host_only);
 
     WeightFootprint fp;
-    weight_footprint(f.prog, &fp, TablePlacement::Vram, TablePlacement::Disk);
+    weight_footprint(f.prog, &fp, TablePlacement::Vram, TablePlacement::Disk, false, true);
     CHECK_EQ(fp.n_units, 1ll);
     CHECK_EQ(fp.statics, 0ll);
     CHECK_EQ(fp.mapped, 6 * MiB);          /* both weights: the unit is what moves */
 }
 
+/* ON THE HOST BACKEND THE WEIGHTS POOL IS HOST MEMORY, so a weight only a host kernel reads stays in
+ * the container's mapping only when it lies there as its kernel reads it. One its host kernel
+ * widened at load has no such place, and CPU-only serving would refuse at load; it takes a copy in
+ * the pool instead, and the footprint the budget sizes that pool from counts it the same way. */
+TEST(on_the_host_backend_a_converted_host_only_weight_takes_a_pool_copy) {
+    Fixture f;
+    const rad_weight direct = f.weight("blk.0.a.weight", 4 * MiB, RAD_ACCESS_PER_TOKEN, 0, -1);
+    const rad_weight widened = f.weight("output_norm.weight", 2 * MiB, RAD_ACCESS_PER_TOKEN, -1, -1);
+    f.prog.weights[widened].widen = true;
+    for (rad_weight w : { direct, widened }) {
+        OpInfo o;
+        o.op = "host_op";
+        o.index = (int32_t)f.prog.ops.size();
+        o.weights = { w };
+        Band hb;
+        hb.hi = 1 << 20;
+        hb.dom[RAD_DOMAIN_HOST].row = &g_host_row;      /* no device band */
+        hb.miss[RAD_DOMAIN_DEVICE] = "no device kernel";
+        o.bands.push_back(hb);
+        f.prog.ops.push_back(o);
+    }
+
+    WeightFootprint card, host;
+    weight_footprint(f.prog, &card, TablePlacement::Vram, TablePlacement::Disk, false, true);
+    weight_footprint(f.prog, &host, TablePlacement::Vram, TablePlacement::Disk, true, true);
+    CHECK_EQ(card.mapped, 6 * MiB);          /* on a card both stay where a host kernel reads them */
+    CHECK_EQ(card.statics, 0ll);
+    CHECK_EQ(host.mapped, 4 * MiB);
+    CHECK_EQ(host.statics, 2 * MiB);         /* the widened one is the pool's */
+
+    Config cfg = base_config();
+    cfg.vram_weights_mib = 8;
+    Plan plan;
+    PlannerInput in{&f.prog, &cfg, 0, 1, nullptr, 0};
+    in.host_backend = true;
+    CHECK_OK(Planner(in).plan(&plan));
+    CHECK(plan.weight[direct].tier == Tier::Mapped);
+    CHECK(plan.weight[widened].tier == Tier::VRAM);   /* the weights pool, host memory here */
+
+    /* A CHECKPOINT SERVED DIRECTLY has no container mapping for either weight to stay in, so on
+     * the host backend both take a pool copy, and the footprint counts both: a budget sized from
+     * a footprint that left one in the mapping is a pool the planner then overfills. */
+    WeightFootprint ckpt;
+    weight_footprint(f.prog, &ckpt, TablePlacement::Vram, TablePlacement::Disk, true, false);
+    CHECK_EQ(ckpt.mapped, 0ll);
+    CHECK_EQ(ckpt.statics, 6 * MiB);
+    Plan cplan;
+    PlannerInput cin{&f.prog, &cfg, 0, 1, nullptr, 0};
+    cin.host_backend = true;
+    cin.container = false;
+    CHECK_OK(Planner(cin).plan(&cplan));
+    CHECK(cplan.weight[direct].tier == Tier::VRAM);
+    CHECK(cplan.weight[widened].tier == Tier::VRAM);
+}
+
 /* --embedding-placement. The fixture's embedding is read by an `embed_lookup`, as every arch
  * declares it, and its head by a GEMM: the first is the table the flag moves, the second never. */
 void build_dense_lookup(Fixture& f, int layers, int64_t per_layer, int64_t emb = 1 * MiB) {
@@ -2441,7 +2496,7 @@ TEST(the_placement_flags_find_their_tables_by_what_reads_them) {
     add_ngram_table(f, 8 * MiB);
 
     WeightFootprint fp;
-    weight_footprint(f.prog, &fp, TablePlacement::Vram, TablePlacement::Disk);
+    weight_footprint(f.prog, &fp, TablePlacement::Vram, TablePlacement::Disk, false, true);
     CHECK_EQ(fp.embedding, 1 * MiB);
     CHECK_EQ(fp.ngram, 8 * MiB);
     CHECK(!fp.ngram_device);
@@ -2449,7 +2504,7 @@ TEST(the_placement_flags_find_their_tables_by_what_reads_them) {
     CHECK_EQ(fp.statics, 2 * 4 * MiB + 2 * MiB);
     CHECK_EQ(fp.mapped, 8 * MiB);
 
-    weight_footprint(f.prog, &fp, TablePlacement::Ram, TablePlacement::Disk);
+    weight_footprint(f.prog, &fp, TablePlacement::Ram, TablePlacement::Disk, false, true);
     CHECK_EQ(fp.embedding, 1 * MiB);
     CHECK_EQ(fp.hosted, 1 * MiB);
     CHECK_EQ(fp.statics, 2 * 4 * MiB + 1 * MiB);
@@ -2466,7 +2521,7 @@ TEST(the_placement_flags_find_their_tables_by_what_reads_them) {
     t.op("embed_lookup", {m}, false);
     t.op("logits_gemm", {m}, false);
     CHECK(!is_embedding_table(t.prog, m));
-    weight_footprint(t.prog, &fp, TablePlacement::Ram, TablePlacement::Disk);
+    weight_footprint(t.prog, &fp, TablePlacement::Ram, TablePlacement::Disk, false, true);
     CHECK_EQ(fp.embedding, 0ll);
     CHECK_EQ(fp.hosted, 0ll);
 }
@@ -2492,7 +2547,7 @@ TEST(embedding_ram_goes_to_the_pinned_pool_read_in_place_and_costs_no_vram) {
     for (rad_weight w = 2; (size_t)w < f.prog.weights.size(); ++w)
         CHECK(plan.weight[w].tier == Tier::VRAM);
 
-    /* Vram, the default, leaves it with the other weights. */
+    /* Vram leaves it with the other weights. */
     cfg.embedding_resolved = TablePlacement::Vram;
     cfg.vram_weights_mib = 10;
     Plan plan2;
@@ -2501,6 +2556,31 @@ TEST(embedding_ram_goes_to_the_pinned_pool_read_in_place_and_costs_no_vram) {
     CHECK_EQ(plan2.embedding_host_bytes, 0ll);
 }
 
+/* THE EMBEDDING'S OWN ROOM: the resolver sizes Config::embedding_host_mib on top of
+ * --host-pool-mib, so a dense model with no pool still places the table, and a pool the experts
+ * share keeps all of --host-pool-mib for them after the table is pinned. */
+TEST(embedding_ram_brings_its_own_room_beside_the_host_pool) {
+    Fixture f;
+    build_dense_lookup(f, /*layers=*/2, /*per_layer=*/4 * MiB);
+    Config cfg = base_config();
+    cfg.placement = "all_vram";
+    cfg.vram_weights_mib = 9;
+    cfg.host_pool_mib = 0;              /* no pool of weights at all */
+    cfg.embedding_host_mib = 1;
+    cfg.embedding_resolved = TablePlacement::Ram;
+    Plan plan;
+    PlannerInput in{&f.prog, &cfg, 0, 1, nullptr, 0};
+    CHECK_OK(Planner(in).plan(&plan));
+    CHECK(plan.weight[1].tier == Tier::HostPinned);
+    CHECK_EQ(plan.host_budget, 0ll);
+
+    cfg.host_pool_mib = 3;
+    Plan plan2;
+    CHECK_OK(Planner(in).plan(&plan2));
+    CHECK(plan2.weight[1].tier == Tier::HostPinned);
+    CHECK_EQ(plan2.host_budget, 3 * MiB);  /* --host-pool-mib, whole */
+}
+
 /* A TABLE THAT IS NOT A WHOLE NUMBER OF PAGES still leaves the report's pinned total at what the
  * pooled units use: the pool slot is charged rounded up and the tier total counts weight bytes, so
  * the report subtracts the same weight bytes it added. */
@@ -2595,14 +2675,14 @@ TEST(an_ngram_table_a_device_kernel_reads_goes_where_the_placement_says) {
     f.op("embed_lookup_q", {t}, /*host_kernel=*/true);
 
     WeightFootprint fp;
-    weight_footprint(f.prog, &fp, TablePlacement::Vram, TablePlacement::Vram);
+    weight_footprint(f.prog, &fp, TablePlacement::Vram, TablePlacement::Vram, false, true);
     CHECK(fp.ngram_device);
     CHECK(fp.ngram_host);
     CHECK_EQ(fp.ngram, 8 * MiB);
     CHECK_EQ(fp.mapped, 0ll);
     CHECK_EQ(fp.statics, 4 * MiB + 2 * MiB + 8 * MiB);
     for (TablePlacement off : { TablePlacement::Ram, TablePlacement::Disk }) {
-        weight_footprint(f.prog, &fp, TablePlacement::Vram, off);
+        weight_footprint(f.prog, &fp, TablePlacement::Vram, off, false, true);
         CHECK_EQ(fp.ngram, 8 * MiB);
         CHECK_EQ(fp.mapped, 8 * MiB);
         CHECK_EQ(fp.statics, 4 * MiB + 2 * MiB);
@@ -2646,7 +2726,7 @@ TEST(an_ngram_table_with_no_host_kernel_cannot_stay_on_disk) {
     const rad_weight t = f.weight("ngram.weight", 8 * MiB, RAD_ACCESS_VOCAB, -1, -1);
     f.op("embed_lookup_q", {t}, /*host_kernel=*/false);
     WeightFootprint fp;
-    weight_footprint(f.prog, &fp, TablePlacement::Vram, TablePlacement::Disk);
+    weight_footprint(f.prog, &fp, TablePlacement::Vram, TablePlacement::Disk, false, true);
     CHECK(fp.ngram_device);
     CHECK(!fp.ngram_host);
 }
@@ -2655,13 +2735,13 @@ TEST(an_empty_program_has_an_empty_footprint) {
     Fixture f;
     WeightFootprint fp;
     fp.statics = 1;                         /* and the out parameter is reset, not accumulated */
-    weight_footprint(f.prog, &fp, TablePlacement::Vram, TablePlacement::Disk);
+    weight_footprint(f.prog, &fp, TablePlacement::Vram, TablePlacement::Disk, false, true);
     CHECK_EQ(fp.statics, 0ll);
     CHECK_EQ(fp.experts, 0ll);
     CHECK_EQ(fp.mapped, 0ll);
     CHECK_EQ(fp.n_units, 0ll);
     /* and a null one is not a crash */
-    weight_footprint(f.prog, nullptr, TablePlacement::Vram, TablePlacement::Disk);
+    weight_footprint(f.prog, nullptr, TablePlacement::Vram, TablePlacement::Disk, false, true);
 }
 
 RAD_TEST_MAIN()
diff --git a/tests/plugin_test.cpp b/tests/plugin_test.cpp
index bfdf4c2f..ebc1d4d9 100644
--- a/tests/plugin_test.cpp
+++ b/tests/plugin_test.cpp
@@ -128,17 +128,22 @@ TEST(loading_reads_identity_and_calls_open) {
     if (open_calls) CHECK(open_calls() >= 1);
 }
 
-/* The hierarchy is CONFIGURED, not discovered: a named plugin takes its position and one present
- * on disk but absent from the list loads at the end, after everything named. */
+/* The hierarchy is CONFIGURED, not discovered: a named plugin takes its position, and a kernel
+ * library present on disk but absent from the list is not loaded at all -- naming the libraries
+ * is choosing them. With no list, everything on disk loads. */
 TEST(hierarchy_order_is_configured) {
     Registry r;
     CHECK_OK(r.load_dir(kernels_dir(), { "radtest_base" }));
     const Plugin* base = r.plugin("radtest_base");
-    const Plugin* over = r.plugin("radtest_over");
-    CHECK(base && over);
-    if (!base || !over) return;
+    CHECK(base != nullptr);
+    if (!base) return;
     CHECK_EQ(base->order, 0);
-    CHECK_EQ(over->order, 1);      /* unnamed, so it loads behind everything named */
+    CHECK(r.plugin("radtest_over") == nullptr);   /* unnamed, so not loaded */
+    for (const KernelRow& row : r.rows()) CHECK(row.plugin != "radtest_over");
+
+    Registry all;
+    CHECK_OK(all.load_dir(kernels_dir(), {}));
+    CHECK(all.plugin("radtest_base") && all.plugin("radtest_over"));
 
     Registry r2;
     CHECK_OK(r2.load_dir(kernels_dir(), { "radtest_over", "radtest_base" }));
@@ -175,9 +180,14 @@ TEST(the_reference_library_sorts_last_with_no_hierarchy) {
     /* Naming it is still an override: an operator comparing a library against the reference puts
      * the reference in front on purpose, and the pin must not defeat that. */
     Registry r2;
-    CHECK_OK(r2.load_dir(order_dir(), { "radtest_reference" }));
+    CHECK_OK(r2.load_dir(order_dir(), { "radtest_reference", "radtest_base" }));
     CHECK_EQ(r2.plugin("radtest_reference")->order, 0);
     CHECK(r2.plugin("radtest_base")->order > 0);
+
+    /* And a list that leaves it out leaves it out: the reference is a library like any other. */
+    Registry r3;
+    CHECK_OK(r3.load_dir(order_dir(), { "radtest_base" }));
+    CHECK(r3.plugin("radtest_reference") == nullptr);
 }
 
 TEST(abi_mismatch_is_refused_by_name_with_both_versions) {
@@ -818,14 +828,37 @@ TEST(a_device_fact_constraint_is_matched_against_the_machine) {
     CHECK(has(why, "measured at launch"));
 }
 
-/* THE SHIPPED libr4d PICKS THE ALL-REDUCE BY MESSAGE SIZE, and the selector is what says so. At 4
- * and 8 ranks the exact sum is a one-shot for a decode-sized message and a two-shot for a prefill
- * chunk; the two-shot rows start one element above the one-shot bound, so that bound is a band
- * edge of the blocks' ranged `numel`. The band at or under the edge has to stay resolvable for
- * every row that places a DIV on `numel` -- the two-rank wht6 wire (64) and the four-rank ti8 wire
- * (128) among them -- or a lossy two-rank serve would lose its decode band. Checked here against
- * the real plugin, because nothing else can run a four- or eight-rank resolution on a two-card
- * machine. Geometry is Qwen3.8-Flash-Next's: 2560 wide, a 2048-token chunk. */
+/* AN ENGINE SERVING WITH NO CARD LEAVES A GPU LIBRARY'S DEVICE ROWS OUT. On the host backend no
+ * GPU code object runs, and a device row that resolved anyway would be launched at the first step
+ * and fail -- CPU-only serving with the shipped libraries installed was exactly that. Only the
+ * engine says so (set_no_device_code); a registry that only selects keeps every row, which the
+ * libr4d tests below rely on wherever they run. First of the libr4d tests in this file, so its
+ * dlopen is the one that registers the library's fat binaries. */
+TEST(an_engine_with_no_card_leaves_a_gpu_librarys_device_rows_out) {
+    const std::string so = home() + "/kernels/libr4d.so";
+    if (access(so.c_str(), R_OK) != 0) {
+        fprintf(stderr, "  SKIP %s: no %s (a build without HIP)\n", ::radtest::current(),
+                so.c_str());
+        return;
+    }
+    Registry r;
+    r.set_no_device_code(true);
+    CHECK(r.load_plugin(so, 0) >= 0);
+    const Plugin* p = r.plugin("libr4d");
+    CHECK(p != nullptr);
+    if (!p) return;
+    CHECK(p->device_code_absent);
+    for (const KernelRow& row : r.rows()) CHECK(row.info->domain != RAD_DOMAIN_DEVICE);
+}
+
+/* THE SHIPPED libr4d PICKS THE ALL-REDUCE BY MESSAGE SIZE, and the selector is what says so. At 3,
+ * 4 and 8 ranks the exact sum is a one-shot for a decode-sized message and a two-shot for a
+ * prefill chunk; the two-shot rows start one element above the one-shot bound, so that bound is a
+ * band edge of the blocks' ranged `numel`. The band at or under the edge has to stay resolvable
+ * for every row that places a DIV on `numel` -- the two-rank wht6 wire (64) and the three- and
+ * four-rank ti8 wires (32, 128) among them -- or a lossy serve would lose its decode band. Checked
+ * here against the real plugin, because nothing else can run a resolution above two ranks on a
+ * two-card machine. Geometry is Qwen3.8-Flash-Next's: 2560 wide, a 2048-token chunk. */
 TEST(libr4d_resolves_the_all_reduce_by_message_size) {
     const std::string so = home() + "/kernels/libr4d.so";
     if (access(so.c_str(), R_OK) != 0) {
@@ -853,10 +886,14 @@ TEST(libr4d_resolves_the_all_reduce_by_message_size) {
         return s;
     };
 
+    CHECK_EQ(names(bands(3, 1, chunk)),
+             "524288:ar_oneshot_3rank_exact 5242880:ar_twoshot_3rank_exact ");
     CHECK_EQ(names(bands(4, 1, chunk)),
              "524288:ar_oneshot_4rank_exact 5242880:ar_twoshot_4rank_exact ");
     CHECK_EQ(names(bands(8, 1, chunk)),
              "524288:ar_oneshot_8rank_exact 5242880:ar_twoshot_8rank_exact ");
+    CHECK_EQ(names(bands(3, 0, chunk)),
+             "524288:ar_twoshot_3rank_ti8 5242880:ar_twoshot_3rank_ti8 ");
     CHECK_EQ(names(bands(4, 0, chunk)),
              "524288:ar_twoshot_4rank_ti8 5242880:ar_twoshot_4rank_ti8 ");
     CHECK_EQ(names(bands(2, 0, chunk)),
@@ -868,6 +905,9 @@ TEST(libr4d_resolves_the_all_reduce_by_message_size) {
     CHECK_EQ(names(bands(4, 1, 16384)),
              "524288:ar_oneshot_4rank_exact 20971520:ar_twoshot_4rank_exact "
              "41943040:ar_oneshot_4rank_exact ");
+    CHECK_EQ(names(bands(3, 1, 16384)),
+             "524288:ar_oneshot_3rank_exact 20971520:ar_twoshot_3rank_exact "
+             "41943040:ar_oneshot_3rank_exact ");
 
     /* A step that never exceeds the bound has one band, and it is the one-shot's. */
     CHECK_EQ(names(bands(4, 1, 128)), "327680:ar_oneshot_4rank_exact ");
diff --git a/tests/ref_test.cpp b/tests/ref_test.cpp
index 82e328d8..ec553ff0 100644
--- a/tests/ref_test.cpp
+++ b/tests/ref_test.cpp
@@ -279,7 +279,7 @@ TEST(op_vocabulary) {
         "embed_lookup", "logits_gemm",
         "sample_penalties", "sample_dry", "sample_temp", "sample_topk", "sample_topp",
         "sample_minp", "sample_typical", "sample_xtc", "sample_mask", "sample_pick",
-        "sample_argmax", "sample_merge_topk",
+        "sample_argmax", "sample_merge_topk", "sample_logprobs",
     };
     for (const char* op : kOps) {
         if (!kern(op)) fprintf(stderr, "    missing op '%s'\n", op);
@@ -3084,6 +3084,27 @@ TEST(op_sample_temp_topk_argmax) {
     CHECK_EQ(lg.at(1), 6.0f);
 }
 
+/* The raw distribution's summary: max, sum of exp(l - max), the k largest with the lower id first
+ * on a tie, slots past the vocabulary as holes, global ids under an offset, and a row without the
+ * flag left as it was. */
+TEST(op_sample_logprobs) {
+    T lg(RAD_F32, {2, 4}); lg.f({1, 3, 2, 3,  0, 0, 0, 0});
+    T st(RAD_F32, {2, 2 + 2 * 5});
+    st.f(std::vector(2 * 12, 9.0f));
+    SP sp(2); sp[0].flags = RAD_SP_LOGPROBS;
+    A a; a.t(lg).t(sp.operand()).t(st).i("M", 2).i("n_vocab", 4).i("k", 5).i("vocab_off", 100);
+    CHECK_OK(run("sample_logprobs", a));
+    CHECK_EQ(st.at(0), 3.0f);
+    CHECK_NEAR(st.at(1), std::exp(-2.0f) + 1.0f + std::exp(-1.0f) + 1.0f, 1e-6);
+    CHECK_EQ(st.at(2), 101.0f); CHECK_EQ(st.at(3), 3.0f);     /* the tie: id 1 before id 3 */
+    CHECK_EQ(st.at(4), 103.0f); CHECK_EQ(st.at(5), 3.0f);
+    CHECK_EQ(st.at(6), 102.0f); CHECK_EQ(st.at(7), 2.0f);
+    CHECK_EQ(st.at(8), 100.0f); CHECK_EQ(st.at(9), 1.0f);
+    CHECK_EQ(st.at(10), -1.0f);                                /* four tokens, five slots */
+    CHECK(st.at(11) == -INFINITY);
+    CHECK_EQ(st.at(12), 9.0f);                                 /* row 1 asked for nothing */
+}
+
 TEST(op_sample_narrowing) {
     /* Two candidates whose probabilities are 3/4 and 1/4. */
     const float ln3 = 1.09861229f;
diff --git a/tests/sample_test.cpp b/tests/sample_test.cpp
index d78e64c8..aaf6c7df 100644
--- a/tests/sample_test.cpp
+++ b/tests/sample_test.cpp
@@ -25,6 +25,7 @@
 #include 
 #include 
 #include 
+#include 
 #include 
 #include 
 
@@ -449,6 +450,33 @@ TEST(chain_order_temperature_before_the_cuts_is_observable) {
     CHECK(a.c.size() != b.c.size());
 }
 
+TEST(temp_last_draws_only_from_the_untempered_nucleus) {
+    /* The same numbers through the whole chain. Temperature last is llama.cpp's order, asked for
+     * with `samplers`: the nucleus is cut on the untempered distribution, so a hot temperature
+     * flattens only what survived the cut and never revives a token it removed. Temperature first
+     * cuts on the flattened distribution and keeps more. */
+    const float logits[3] = { 3.0f, 2.0f, 1.0f };
+    auto b = set_of({ 3.0f, 2.0f, 1.0f });
+    host_top_p(b, 0.5f, 1);
+    std::set nucleus;
+    for (const auto& e : b.c) nucleus.insert(e.id);
+
+    SamplingParams sp;
+    sp.temp = 5.0f;
+    sp.top_p = 0.5f;
+    std::set first, last;
+    for (uint64_t seed = 0; seed < 256; ++seed) {
+        sp.seed = seed;
+        HostRefInput in;
+        sp.temp_last = false;
+        first.insert(host_sample(logits, 3, sp, in));
+        sp.temp_last = true;
+        last.insert(host_sample(logits, 3, sp, in));
+    }
+    for (int32_t t : last) CHECK(nucleus.count(t) == 1);
+    CHECK(first.size() > last.size());
+}
+
 
 /* ================================================================== GBNF */
 
@@ -1685,6 +1713,260 @@ TEST(a_top_k_of_zero_samples_this_steps_candidates) {
     CHECK_EQ(tok[0], 3);
 }
 
+/* LOGPROBS ARE THE RAW DISTRIBUTION'S, read before any stage. A greedy row asking for them is
+ * staged as a top-1 chain row, and its token and alternatives come back against the normaliser of
+ * the logits the model wrote. */
+TEST(logprobs_are_the_raw_distributions) {
+    HostChain ch(32, 1, 0);
+    NEED_CHAIN(ch)
+    SamplingParams sp = greedy_params();
+    sp.n_probs = 3;
+    Request a = make_req(1, { 30 }, sp);
+    std::vector lg(32, 0.0f);
+    lg[7] = 4.0f; lg[3] = 4.0f; lg[9] = 2.0f;
+    std::vector tok;
+    CHECK_OK(ch.step({ &a }, lg, &tok));
+    CHECK_EQ(tok[0], 3);                           /* the tie goes to the lower id */
+
+    int64_t n = 0;
+    const DeviceSampleParams* p = ch.s.staged_params(&n);
+    CHECK((p[0].flags & RAD_SP_LOGPROBS) != 0);
+    CHECK((p[0].flags & RAD_SP_GREEDY) == 0);
+    CHECK_EQ(p[0].top_k, 1);
+
+    double z = 0.0;
+    for (float v : lg) z += std::exp((double)v);
+    const double lz = std::log(z);
+    TokenLogprobs lp;
+    CHECK_OK(ch.s.logprobs_for(0, tok[0], &lp));
+    CHECK_NEAR(lp.logprob, 4.0 - lz, 1e-5);
+    CHECK_EQ(lp.n_top, 3);
+    CHECK_EQ(lp.top_id[0], 3);
+    CHECK_EQ(lp.top_id[1], 7);
+    CHECK_EQ(lp.top_id[2], 9);
+    CHECK_NEAR(lp.top_lp[2], 2.0 - lz, 1e-5);
+    /* A row that was not staged for logprobs has none, and asking is the caller's error. */
+    CHECK_EQ(ch.s.logprobs_for(1, 0, &lp), RAD_E_STATE);
+}
+
+namespace {
+
+/* THE SUMMARY HOLDS 21 PAIRS (RAD_MAX_LOGPROBS + 1), so a token is outside it only behind 21
+ * larger or tied ones: tokens 0..20 at `hi` fill it, and token 21 at `at` is the first outside --
+ * at `hi` too, it loses the tie to every lower id. The rest of a 32-token vocabulary sits at
+ * `rest`. The prompt is `head`, 0..20 twice, then `tail`, so the penalties count each of 0..20
+ * twice. */
+std::vector outside_logits(float hi, float at, float rest) {
+    std::vector lg(32, rest);
+    for (int t = 0; t <= 20; ++t) lg[(size_t)t] = hi;
+    lg[21] = at;
+    return lg;
+}
+std::vector outside_prompt(std::vector head, const std::vector& tail) {
+    for (int k = 0; k < 2; ++k)
+        for (int32_t t = 0; t <= 20; ++t) head.push_back(t);
+    head.insert(head.end(), tail.begin(), tail.end());
+    return head;
+}
+double log_sum_exp(const std::vector& lg) {
+    double z = 0.0;
+    for (float v : lg) z += std::exp((double)v);
+    return std::log(z);
+}
+
+}  /* namespace */
+
+/* A TOKEN OUTSIDE THE RAW SUMMARY IS RECOVERED FROM THE VALUE IT WAS DRAWN AT. Tokens 0..21 tie at
+ * 5, so the summary holds 0..20; the penalties push those to 5/1.25 - 2 = 2 and token 21 to
+ * 5/1.25 - 1 = 3, which is chosen, and its raw logit is the candidate value with temperature,
+ * frequency and repetition undone. */
+TEST(a_chosen_token_outside_the_summary_has_its_raw_logprob) {
+    HostChain ch(32, 1, 0);
+    NEED_CHAIN(ch)
+    SamplingParams sp;
+    sp.top_k = 1;
+    sp.temp = 0.5f;
+    sp.rep_penalty = 1.25f;
+    sp.freq_penalty = 1.0f;
+    sp.n_probs = 0;
+    Request a = make_req(1, outside_prompt({}, { 21 }), sp);
+    const std::vector lg = outside_logits(5.0f, 5.0f, 0.0f);
+    std::vector tok;
+    CHECK_OK(ch.step({ &a }, lg, &tok));
+    CHECK_EQ(tok[0], 21);
+
+    TokenLogprobs lp;
+    CHECK_OK(ch.s.logprobs_for(0, tok[0], &lp));
+    CHECK_NEAR(lp.logprob, 5.0 - log_sum_exp(lg), 1e-5);
+    CHECK_EQ(lp.n_top, 0);
+}
+
+/* A NEGATIVE LOGIT'S REPETITION PENALTY IS UNDONE ON ITS OWN SIDE OF ZERO, and the presence penalty
+ * is added back with the frequency one. Token 21's raw logit is -1: repetition multiplies it to
+ * -1.25, frequency (once) and presence take it to -13.25, and tokens 0..20 (5/1.25 - 20 - 2 = -18)
+ * and the rest (-30) fall below it. Inverting: -13.25 + 10 + 2 = -1.25, divided by 1.25 is -1. */
+TEST(a_negative_penalised_logit_has_its_raw_logprob) {
+    HostChain ch(32, 1, 0);
+    NEED_CHAIN(ch)
+    SamplingParams sp;
+    sp.top_k = 1;
+    sp.temp = 0.5f;
+    sp.rep_penalty = 1.25f;
+    sp.freq_penalty = 10.0f;
+    sp.pres_penalty = 2.0f;
+    sp.n_probs = 2;
+    Request a = make_req(1, outside_prompt({}, { 21 }), sp);
+    const std::vector lg = outside_logits(5.0f, -1.0f, -30.0f);
+    std::vector tok;
+    CHECK_OK(ch.step({ &a }, lg, &tok));
+    CHECK_EQ(tok[0], 21);
+
+    const double lz = log_sum_exp(lg);
+    TokenLogprobs lp;
+    CHECK_OK(ch.s.logprobs_for(0, tok[0], &lp));
+    CHECK_NEAR(lp.logprob, -1.0 - lz, 1e-5);
+    CHECK_EQ(lp.n_top, 2);
+    CHECK_EQ(lp.top_id[0], 0);
+    CHECK_NEAR(lp.top_lp[0], 5.0 - lz, 1e-5);
+}
+
+/* ONLY THE PENALTY WINDOW IS COUNTED BACK. Token 21 opens the history three times, but the last 42
+ * tokens -- penalty_last_n -- are 0..20 twice, so the stage never penalised it: 0..20 drop to 2 and
+ * 21 stays at 5. Counting the whole staged history would add 3 back and multiply by 1.25. */
+TEST(a_logprob_counts_only_the_penalty_window_back) {
+    HostChain ch(32, 1, 0);
+    NEED_CHAIN(ch)
+    SamplingParams sp;
+    sp.top_k = 1;
+    sp.temp = 0.5f;
+    sp.rep_penalty = 1.25f;
+    sp.freq_penalty = 1.0f;
+    sp.penalty_last_n = 42;
+    sp.n_probs = 0;
+    Request a = make_req(1, outside_prompt({ 21, 21, 21 }, {}), sp);
+    const std::vector lg = outside_logits(5.0f, 5.0f, 0.0f);
+    std::vector tok;
+    CHECK_OK(ch.step({ &a }, lg, &tok));
+    CHECK_EQ(tok[0], 21);
+    int64_t n = 0;
+    CHECK_EQ(ch.s.staged_params(&n)[0].hist_len, 45);
+
+    TokenLogprobs lp;
+    CHECK_OK(ch.s.logprobs_for(0, tok[0], &lp));
+    CHECK_NEAR(lp.logprob, 5.0 - log_sum_exp(lg), 1e-5);
+}
+
+/* TEMPERATURE LAST IS UNDONE FROM THE LATE STAGE'S ROW. A sampled row (top_k 2: top_k 1 is greedy,
+ * which has no late stage), so the early row runs at 1 and the late one at 0.5 over the two
+ * candidates: token 21 at (5/1.25 - 20) / 0.5 = -32 against -72 for the runner-up, a draw that
+ * cannot go the other way. Only the late temperature takes -32 back to -16 before the penalties
+ * are undone. */
+TEST(a_temperature_last_row_has_its_raw_logprob) {
+    HostChain ch(32, 1, 0);
+    NEED_CHAIN(ch)
+    SamplingParams sp;
+    sp.top_k = 2;
+    sp.temp = 0.5f;
+    sp.temp_last = true;
+    sp.rep_penalty = 1.25f;
+    sp.freq_penalty = 20.0f;
+    sp.n_probs = 0;
+    Request a = make_req(1, outside_prompt({}, { 21 }), sp);
+    const std::vector lg = outside_logits(5.0f, 5.0f, -100.0f);
+    std::vector tok;
+    CHECK_OK(ch.step({ &a }, lg, &tok));
+    CHECK_EQ(tok[0], 21);
+    int64_t n = 0;
+    CHECK_EQ(ch.s.staged_params(&n)[0].temp, 1.0f);
+
+    TokenLogprobs lp;
+    CHECK_OK(ch.s.logprobs_for(0, tok[0], &lp));
+    CHECK_NEAR(lp.logprob, 5.0 - log_sum_exp(lg), 1e-5);
+}
+
+/* A ROW WITH NO FINITE LOGIT HAS NO LOGPROBS, and says so, rather than reporting -inf or NaN: the
+ * step itself still runs, and the engine fails the one request (Engine::row_logprobs). */
+TEST(a_row_with_no_finite_logit_has_no_logprobs) {
+    HostChain ch(32, 1, 0);
+    NEED_CHAIN(ch)
+    SamplingParams sp = greedy_params();
+    sp.n_probs = 3;
+    Request a = make_req(1, { 1 }, sp);
+    std::vector tok;
+    CHECK_OK(ch.step({ &a }, std::vector(32, -INFINITY), &tok));
+    TokenLogprobs lp;
+    lp.token = 7;
+    CHECK_EQ(ch.s.logprobs_for(0, tok[0], &lp), RAD_E_INVAL);
+    CHECK_EQ(lp.token, -1);
+}
+
+/* THE RANKS' SUMMARIES MERGE BY RESCALING TO THE LARGER MAXIMUM. Rank 0's shard has maximum 2 and
+ * normaliser 3, rank 1's maximum 5 and normaliser 1.5; their pairs interleave by value, a tie
+ * across ranks going to the lower id. A rank whose normaliser is not finite contributes nothing,
+ * and with no rank left there is no normaliser. */
+TEST(split_vocabulary_logprob_summaries_merge_across_ranks) {
+    const float rows[2][8] = {
+        { 2.0f, 3.0f,   5.0f, 2.0f,   1.0f, 1.0f,  -1.0f, -INFINITY },
+        { 5.0f, 1.5f,  40.0f, 5.0f,  41.0f, 2.0f,  42.0f, 0.5f },
+    };
+    double lz = 0.0;
+    int32_t id[8];
+    float   v[8];
+    CHECK_EQ(merge_logprob_rows(&rows[0][0], 2, 3, &lz, id, v, 8), 5);
+    CHECK_NEAR(lz, std::log(3.0 * std::exp(2.0) + 1.5 * std::exp(5.0)), 1e-6);
+    const int32_t want[5] = { 40, 5, 41, 1, 42 };
+    for (int j = 0; j < 5; ++j) CHECK_EQ(id[j], want[j]);
+    CHECK_EQ(v[1], 2.0f);
+    CHECK_EQ(merge_logprob_rows(&rows[0][0], 2, 3, &lz, id, v, 2), 2);
+
+    float dead[2][8];
+    std::memcpy(dead, rows, sizeof dead);
+    dead[1][1] = NAN;
+    CHECK_EQ(merge_logprob_rows(&dead[0][0], 2, 3, &lz, id, v, 8), 2);
+    CHECK_NEAR(lz, 2.0 + std::log(3.0), 1e-6);
+    CHECK_EQ(id[0], 5);
+    dead[0][1] = 0.0f;
+    CHECK_EQ(merge_logprob_rows(&dead[0][0], 2, 3, &lz, id, v, 8), 0);
+    CHECK(std::isnan(lz));
+}
+
+/* AND DRY IS UNDONE TOO. "22 23" ended the history once before, followed by 21, so DRY takes its
+ * multiplier off token 21 (5 - 1 - 0.5 = 3.5); tokens 0..20 appear twice and lose more to the
+ * frequency penalty (5 - 2 = 3), so 21 is chosen from outside the summary and its raw logit needs
+ * DRY, the penalties and temperature all undone. */
+TEST(a_dry_penalised_token_has_its_raw_logprob) {
+    HostChain ch(32, 1, 0);
+    NEED_CHAIN(ch)
+    SamplingParams sp;
+    sp.top_k = 1;
+    sp.temp = 0.8f;
+    sp.freq_penalty = 1.0f;
+    sp.dry_multiplier = 0.5f;
+    sp.dry_base = 1.75f;
+    sp.dry_allowed_length = 2;
+    sp.n_probs = 0;
+    Request a = make_req(1, outside_prompt({ 22, 23, 21 }, { 22, 23 }), sp);
+    const std::vector lg = outside_logits(5.0f, 5.0f, 0.0f);
+    std::vector tok;
+    CHECK_OK(ch.step({ &a }, lg, &tok));
+    CHECK_EQ(tok[0], 21);
+    int64_t n = 0;
+    CHECK((ch.s.staged_params(&n)[0].flags & RAD_SP_DRY) != 0);
+
+    TokenLogprobs lp;
+    CHECK_OK(ch.s.logprobs_for(0, tok[0], &lp));
+    CHECK_NEAR(lp.logprob, 5.0 - log_sum_exp(lg), 1e-5);
+}
+
+TEST(admission_refuses_more_than_twenty_logprobs) {
+    Sampler s;
+    SamplingParams sp;
+    sp.n_probs = RAD_MAX_LOGPROBS + 1;
+    std::string why;
+    CHECK(s.check_request(sp, &why) < 0);
+    CHECK(why.find("logprobs") != std::string::npos);
+}
+
 /* repeat_last_n = 0 TURNS THE PENALTIES OFF, as it does in llama.cpp -- it is not "the whole
  * history". */
 TEST(a_penalty_window_of_zero_leaves_the_logits_alone) {
diff --git a/tests/server_test.cpp b/tests/server_test.cpp
index 9ee8221c..3a9e8f41 100644
--- a/tests/server_test.cpp
+++ b/tests/server_test.cpp
@@ -64,8 +64,16 @@ struct FakeDetok : IDetokenizer {
 
 struct FakeTokenizer : ITokenizer {
     mutable bool last_parse_special = false;
+    /* A vocabulary with llama's three fill-in-the-middle markers as special tokens, for /infill. */
+    bool fim = false;
+    static const char* fim_name(int32_t id) {
+        return id == 1001 ? "
" : id == 1002 ? "" : id == 1003 ? "" : nullptr;
+    }
     std::vector encode(const std::string& s, bool, bool parse_special) const override {
         last_parse_special = parse_special;
+        if (fim && parse_special)
+            for (int32_t id = 1001; id <= 1003; ++id)
+                if (s == fim_name(id)) return { id };
         std::vector v;
         v.reserve(s.size());
         for (unsigned char c : s) v.push_back((int32_t)c);
@@ -73,9 +81,13 @@ struct FakeTokenizer : ITokenizer {
     }
     std::string decode(const std::vector& t) const override {
         std::string s;
-        for (int32_t x : t) if (x > 0) s.push_back((char)x);
+        for (int32_t x : t) if (x > 0) s += token_bytes(x);
         return s;
     }
+    std::string token_bytes(int32_t id) const override {
+        if (fim && fim_name(id)) return fim_name(id);
+        return std::string(1, (char)id);
+    }
     int32_t eos() const override { return 0; }
     int32_t bos() const override { return 1; }
     /* Stop strings are deliberately NOT given to the fake decoder, so the server's own scan is
@@ -268,6 +280,8 @@ struct FakeScheduler : IScheduler {
     std::vector submitted;
     SamplingParams last_sp;              /* what the last submitted request was to sample with */
     std::vector last_stop;  /* ...and the stop strings it was handed */
+    std::string last_label;              /* ...its session label */
+    int32_t last_max_tokens = 0;         /* ...and its max_tokens */
     std::vector cancelled;
     std::vector workers;
     std::atomic next_id{1};
@@ -286,6 +300,8 @@ struct FakeScheduler : IScheduler {
             submitted.push_back(id);
             last_sp = r.sp;
             last_stop = r.stop;
+            last_label = r.session_label;
+            last_max_tokens = r.max_tokens;
         }
         void* sink = r.sink;
         int32_t cap = r.max_tokens;
@@ -294,9 +310,10 @@ struct FakeScheduler : IScheduler {
         const int fst = fail_status;
         const char* fwhy = fail_why;
         const int32_t nd = drafts;
+        const int np = r.sp.n_probs;
         /* Under the lock: over a real socket, submits arrive from several HTTP workers at once. */
         std::lock_guard lk(mu);
-        workers.emplace_back([sink, cap, text, h, fst, fwhy, nd] {
+        workers.emplace_back([sink, cap, text, h, fst, fwhy, nd, np] {
             sink_admitted(sink);
             sink_prompt_stats(sink, 8, 4);
             int32_t n = 0;
@@ -304,7 +321,17 @@ struct FakeScheduler : IScheduler {
                 if (n >= cap) break;
                 if (sink_cancelled(sink)) { sink_finish(sink, Finish::Cancelled); return; }
                 if (n > 0 && nd > 0) sink_drafts(sink, nd, 1);
-                if (!sink_push(sink, (int32_t)(unsigned char)c)) return;
+                /* Logprobs when asked: the n-th token at -(n+1)/4, and alternatives 'x', 'y', ...
+                 * at -1, -2, ... */
+                TokenLogprobs lp;
+                lp.token = (int32_t)(unsigned char)c;
+                lp.logprob = -0.25f * (float)(n + 1);
+                lp.n_top = np > 0 ? np : 0;
+                for (int j = 0; j < lp.n_top; ++j) {
+                    lp.top_id[j] = 'x' + j;
+                    lp.top_lp[j] = -1.0f - (float)j;
+                }
+                if (!sink_push(sink, (int32_t)(unsigned char)c, np >= 0 ? &lp : nullptr)) return;
                 ++n;
                 if (h && n >= 3) break;
             }
@@ -343,7 +370,8 @@ struct Fixture {
     FakeGrammar      gram;
     std::unique_ptr srv;
 
-    explicit Fixture(bool with_tools = true, int64_t max_ctx = 0, const char* model_path = "") {
+    explicit Fixture(bool with_tools = true, int64_t max_ctx = 0, const char* model_path = "",
+                     bool logprobs = false) {
         Deps d;
         d.sched = &sched;
         d.tok = &tok;
@@ -358,6 +386,7 @@ struct Fixture {
         o.max_seqs = 4;
         o.max_ctx = max_ctx;
         o.model_path = model_path;
+        o.supports_logprobs = logprobs;
         srv.reset(new Server(d, o));
     }
 
@@ -842,12 +871,25 @@ TEST(unsupported_parameters_are_400_and_name_themselves) {
     CHECK_EQ(e["error"]["code"].get(), std::string("unsupported_parameter"));
     CHECK(e["error"]["message"].get().find("logit_bias") != std::string::npos);
 
-    /* A parameter nobody has heard of is refused too, rather than silently dropped. */
+    /* A parameter nobody has heard of is a client's own extension, and is ignored as llama.cpp
+     * and vLLM ignore it (#47: OpenRouter's session_id, refused, broke the client). */
     HttpResponse r2 = f.post("/v1/chat/completions",
-                             R"({"messages":[{"role":"user","content":"hi"},{}],
-                                 "wobble":1})");
-    CHECK_EQ(r2.status, 400);
-    CHECK(r2.body.find("wobble") != std::string::npos);
+                             R"({"messages":[{"role":"user","content":"hi"}],
+                                 "wobble":1,"session_id":"abc"})");
+    CHECK_EQ(r2.status, 200);
+
+    /* What llama.cpp-built clients send on every request: the samplers this server does not run,
+     * at their off values. Accepted there, and refused by name the moment one is switched on. */
+    HttpResponse off = f.post("/v1/chat/completions",
+                             R"({"messages":[{"role":"user","content":"hi"}],
+                                 "mirostat":0,"top_n_sigma":-1,"dynatemp_range":0,
+                                 "logit_bias":{},"cache_prompt":true,"id_slot":-1,
+                                 "backend_sampling":false,"speculative.n_max":16})");
+    CHECK_EQ(off.status, 200);
+    HttpResponse on = f.post("/v1/chat/completions",
+                             R"({"messages":[{"role":"user","content":"hi"}],"mirostat":2})");
+    CHECK_EQ(on.status, 400);
+    CHECK_EQ(json::parse(on.body)["error"]["param"].get(), std::string("mirostat"));
 
     /* Out-of-range values name the field and the range. */
     HttpResponse r3 = f.post("/v1/chat/completions",
@@ -1436,9 +1478,10 @@ TEST(preserve_thinking_at_the_top_level_reaches_the_template) {
     CHECK_EQ(parse_chat_request(R"({"messages":[{"role":"user","content":"hi"}],"preserve_thinking":"yes"})",
                                 f.odeps(), lim, &r, &e), RAD_E_INVAL);
     CHECK_EQ(e.param, std::string("preserve_thinking"));
-    /* A chat field, not a completion one: /v1/completions has no template to hand it to. */
+    /* A chat field, not a completion one: /v1/completions has no template to hand it to, and
+     * ignores it as it ignores any field it does not read. */
     CHECK_EQ(parse_completion_request(R"({"prompt":"ab","preserve_thinking":true})", f.odeps(), lim,
-                                      &r, &e), RAD_E_INVAL);
+                                      &r, &e), RAD_OK);
 }
 
 /* parallel_tool_calls reaches the template, because it is the one tool-choice knob the generated
@@ -1969,14 +2012,16 @@ TEST(stop_strings_wait_for_the_reasoning_closer) {
     CHECK(!f.sched.saw_cancel());             /* ended by the reply itself, not cut */
 }
 
-/* THE BUDGET REACHES THE ENGINE in either spelling, with the block it is held on; one the block
- * cannot hold, a negative one, and two spellings that disagree are 400s naming the field. */
+/* THE BUDGET REACHES THE ENGINE in every spelling -- vLLM's, Qwen's and llama.cpp's two -- with
+ * the block it is held on; one the block cannot hold and two spellings that disagree are 400s
+ * naming the field, and a negative one is llama.cpp's "no budget". */
 TEST(a_thinking_budget_reaches_the_engine_or_is_refused_by_name) {
     Fixture f;
     f.tmpl.think_open = "{";
     f.tmpl.think_close = "|";
     f.tmpl.think_starts_open = true;
-    for (const char* k : { "thinking_token_budget", "thinking_budget" }) {
+    for (const char* k : { "thinking_token_budget", "thinking_budget", "thinking_budget_tokens",
+                           "reasoning_budget_tokens" }) {
         HttpResponse r = f.post("/v1/chat/completions",
                                 std::string(R"({"messages":[{"role":"user","content":"hi"}],")") +
                                     k + R"(":7})");
@@ -1990,8 +2035,7 @@ TEST(a_thinking_budget_reaches_the_engine_or_is_refused_by_name) {
     }
 
     struct Case { const char* extra; const char* param; };
-    for (const Case& c : { Case{ R"("thinking_token_budget":-1)", "thinking_token_budget" },
-                           Case{ R"("thinking_token_budget":3,"thinking_budget":4)",
+    for (const Case& c : { Case{ R"("thinking_token_budget":3,"thinking_budget":4)",
                                  "thinking_budget" },
                            Case{ R"("thinking_budget":"3")", "thinking_budget" } }) {
         HttpResponse r = f.post("/v1/chat/completions",
@@ -2001,6 +2045,16 @@ TEST(a_thinking_budget_reaches_the_engine_or_is_refused_by_name) {
         CHECK_EQ(json::parse(r.body)["error"]["param"].get(), std::string(c.param));
     }
 
+    {
+        HttpResponse r = f.post("/v1/chat/completions",
+                                R"({"messages":[{"role":"user","content":"hi"}],
+                                    "reasoning_budget_tokens":-1})");
+        CHECK_EQ(r.status, 200);
+        f.sched.join_all();
+        std::lock_guard lk(f.sched.mu);
+        CHECK_EQ(f.sched.last_sp.thinking_budget, -1);
+    }
+
     Fixture multi;
     multi.tmpl.think_close = "";
     multi.tmpl.think_starts_open = true;
@@ -2031,6 +2085,7 @@ TEST(the_deployment_s_thinking_budget_is_a_default_a_request_can_override) {
     lim.default_thinking_budget = 64;
     CHECK_EQ(chat_with(f, lim, "").sp.thinking_budget, 64);
     CHECK_EQ(chat_with(f, lim, R"("thinking_token_budget":3)").sp.thinking_budget, 3);
+    CHECK_EQ(chat_with(f, lim, R"("reasoning_budget_tokens":-1)").sp.thinking_budget, -1);
     CHECK_EQ(chat_with(f, f.limits(), "").sp.thinking_budget, -1);
 
     f.tmpl.think_close.clear();
@@ -3185,4 +3240,739 @@ TEST(a_429_carries_the_deployments_retry_after) {
     srv.reset();
 }
 
+/* ================================================================== llama-server parity */
+
+/* llama-server's spellings reach the engine as the fields they name, and two spellings of one
+ * field that disagree are refused. -1 is llama-server's "no limit": not the deployment's default
+ * (the fixture's is 32) and not a refusal. */
+TEST(llama_server_spellings_reach_the_engine) {
+    Fixture f;
+    auto post = [&](const std::string& extra) {
+        HttpResponse r = f.post("/v1/chat/completions",
+                                R"({"messages":[{"role":"user","content":"hi"}])" + extra + "}");
+        f.sched.join_all();
+        return r;
+    };
+    CHECK_EQ(post(R"(,"repeat_penalty":1.25,"n_predict":5)").status, 200);
+    {
+        std::lock_guard lk(f.sched.mu);
+        CHECK_NEAR(f.sched.last_sp.rep_penalty, 1.25, 1e-6);
+        CHECK_EQ(f.sched.last_max_tokens, 5);
+    }
+    CHECK_EQ(post(R"(,"repeat_penalty":1.2,"repetition_penalty":1.3)").status, 400);
+    CHECK_EQ(post(R"(,"max_tokens":4,"n_predict":5)").status, 400);
+    CHECK_EQ(post("").status, 200);
+    { std::lock_guard lk(f.sched.mu); CHECK_EQ(f.sched.last_max_tokens, 32); }
+    CHECK_EQ(post(R"(,"max_tokens":-1)").status, 200);
+    { std::lock_guard lk(f.sched.mu); CHECK(f.sched.last_max_tokens != 32); }
+    CHECK_EQ(post(R"(,"max_tokens":0)").status, 400);
+}
+
+/* `samplers`: a stage left out is off, temperature after the cuts sets temp_last, and an order
+ * the chain cannot run is refused by name -- as is a sampler it does not have. */
+TEST(the_sampler_order_is_honoured_or_refused) {
+    Fixture f;
+    auto post = [&](const std::string& extra) {
+        HttpResponse r = f.post("/v1/chat/completions",
+                                R"({"messages":[{"role":"user","content":"hi"}],"temperature":1.5,)"
+                                R"("top_p":0.5,"top_k":40)" + extra + "}");
+        f.sched.join_all();
+        return r;
+    };
+    CHECK_EQ(post(R"(,"samplers":"kpt")").status, 200);
+    { std::lock_guard lk(f.sched.mu); CHECK(f.sched.last_sp.temp_last); }
+    CHECK_EQ(post(R"(,"samplers":["top_k","temperature","top_p"])").status, 200);
+    { std::lock_guard lk(f.sched.mu); CHECK(!f.sched.last_sp.temp_last); }
+    /* llama.cpp's default list, typ_p before top_p: typical is off, so its place is free. */
+    CHECK_EQ(post(R"(,"samplers":["penalties","dry","top_n_sigma","top_k","typ_p","top_p","min_p","xtc","temperature"])").status, 200);
+    { std::lock_guard lk(f.sched.mu); CHECK(f.sched.last_sp.temp_last); }
+    CHECK_EQ(post(R"(,"samplers":["top_p"])").status, 200);
+    {
+        std::lock_guard lk(f.sched.mu);
+        CHECK_EQ(f.sched.last_sp.top_k, 0);                       /* left out: off */
+        CHECK_NEAR(f.sched.last_sp.temp, 1.0, 1e-6);
+    }
+    HttpResponse bad = post(R"(,"min_p":0.1,"samplers":["top_p","temperature","min_p"])");
+    CHECK_EQ(bad.status, 400);
+    CHECK_EQ(json::parse(bad.body)["error"]["param"].get(), std::string("samplers"));
+    CHECK_EQ(post(R"(,"samplers":["infill"])").status, 400);
+}
+
+/* OpenRouter's session_id travels to the engine as the conversation's label, and nothing else. */
+TEST(the_session_id_labels_the_request) {
+    Fixture f;
+    CHECK_EQ(f.post("/v1/chat/completions",
+                    R"({"messages":[{"role":"user","content":"hi"}],"session_id":"conv-7"})").status,
+             200);
+    f.sched.join_all();
+    std::lock_guard lk(f.sched.mu);
+    CHECK_EQ(f.sched.last_label, std::string("conv-7"));
+}
+
+/* ASSISTANT PREFILL: a conversation ending in an assistant message is continued unless the
+ * request asks for a generation prompt; asking for both explicitly is refused. */
+TEST(a_trailing_assistant_message_is_continued) {
+    Fixture f;
+    const std::string msgs =
+        R"("messages":[{"role":"user","content":"hi"},{"role":"assistant","content":"The"}])";
+    CHECK_EQ(f.post("/v1/chat/completions", "{" + msgs + "}").status, 200);
+    CHECK_EQ(f.tmpl.last_opt.continue_final, std::string("auto"));
+    CHECK(!f.tmpl.last_opt.add_generation_prompt);
+    CHECK_EQ(f.post("/v1/chat/completions",
+                    "{" + msgs + R"(,"continue_final_message":"content"})").status, 200);
+    CHECK_EQ(f.tmpl.last_opt.continue_final, std::string("content"));
+    CHECK_EQ(f.post("/v1/chat/completions",
+                    "{" + msgs + R"(,"add_generation_prompt":true})").status, 200);
+    CHECK(f.tmpl.last_opt.continue_final.empty());
+    CHECK(f.tmpl.last_opt.add_generation_prompt);
+    CHECK_EQ(f.post("/v1/chat/completions",
+                    "{" + msgs + R"(,"continue_final_message":true,"add_generation_prompt":true})")
+                 .status, 400);
+    CHECK_EQ(f.post("/v1/chat/completions",
+                    R"({"messages":[{"role":"user","content":"hi"}],"continue_final_message":true})")
+                 .status, 400);
+    f.sched.join_all();
+}
+
+/* The deprecated functions API, llama-server's json_schema and reasoning_format reach the
+ * template as the fields they spell. */
+TEST(older_and_llama_server_chat_spellings_reach_the_template) {
+    Fixture f;
+    CHECK_EQ(f.post("/v1/chat/completions",
+                    R"({"messages":[{"role":"user","content":"hi"}],
+                        "functions":[{"name":"f","parameters":{"type":"object"}}]})").status, 200);
+    CHECK_EQ(f.tmpl.last_n_tools, 1);
+    CHECK_EQ(f.post("/v1/chat/completions",
+                    R"({"messages":[{"role":"user","content":"hi"}],"functions":[],"tools":[]})")
+                 .status, 400);
+    CHECK_EQ(f.post("/v1/chat/completions",
+                    R"({"messages":[{"role":"user","content":"hi"}],"reasoning_format":"none"})")
+                 .status, 200);
+    CHECK_EQ(f.tmpl.last_opt.reasoning_format, std::string("none"));
+    CHECK_EQ(f.post("/v1/chat/completions",
+                    R"({"messages":[{"role":"user","content":"hi"}],
+                        "reasoning_format":"deepseek-legacy"})").status, 400);
+    /* The fake template makes no grammar of a schema, so this one is refused after the render;
+     * what is checked is that the schema reached it. */
+    (void)f.post("/v1/chat/completions",
+                 R"({"messages":[{"role":"user","content":"hi"}],"json_schema":{"type":"object"}})");
+    CHECK_EQ(f.tmpl.last_opt.json_schema, std::string(R"({"type":"object"})"));
+    f.sched.join_all();
+}
+
+/* The routes llama-server answers and this server now does too: without /v1, the token count,
+ * the rendered prompt, and llama-server's /tokenize and /detokenize shapes. */
+TEST(llama_server_routes_answer) {
+    Fixture f;
+    CHECK_EQ(f.post("/chat/completions", R"({"messages":[{"role":"user","content":"hi"}]})").status,
+             200);
+    CHECK_EQ(f.post("/completions", R"({"prompt":"ab"})").status, 200);
+    CHECK_EQ(f.get("/models").status, 200);
+    CHECK_EQ(f.get("/v1/health").status, 200);
+    f.sched.join_all();
+
+    HttpResponse at = f.post("/apply-template", R"({"messages":[{"role":"user","content":"hi"}]})");
+    CHECK_EQ(at.status, 200);
+    const std::string prompt = json::parse(at.body).value("prompt", std::string());
+    CHECK(has(prompt, "hi"));
+    HttpResponse it = f.post("/v1/chat/completions/input_tokens",
+                             R"({"messages":[{"role":"user","content":"hi"}]})");
+    CHECK_EQ(it.status, 200);
+    CHECK_EQ(json::parse(it.body).value("input_tokens", (int64_t)-1), (int64_t)prompt.size());
+
+    HttpResponse t = f.post("/tokenize", R"({"content":["ab",7]})");
+    CHECK_EQ(t.status, 200);
+    CHECK(json::parse(t.body)["tokens"] == json::array({ 97, 98, 7 }));
+    HttpResponse tp = f.post("/tokenize", R"({"content":"a","with_pieces":true})");
+    CHECK_EQ(json::parse(tp.body)["tokens"][0].value("piece", std::string()), std::string("a"));
+    HttpResponse d = f.post("/detokenize", R"({"tokens":[104,105]})");
+    CHECK_EQ(json::parse(d.body).value("content", std::string()), std::string("hi"));
+    CHECK_EQ(json::parse(d.body).value("prompt", std::string()), std::string("hi"));
+
+    const json p = json::parse(f.get("/props").body);
+    CHECK_EQ(p.value("role", std::string()), std::string("model"));
+    CHECK(p["default_generation_settings"]["params"]["samplers"].is_array());
+    CHECK_EQ(p["default_generation_settings"]["params"].value("mirostat", -1), 0);
+}
+
+/* A prompt the context cannot hold names itself in both of the phrasings the agents that compact
+ * on overflow look for, with llama-server's two numbers beside OpenAI's code. */
+TEST(an_overflow_reads_as_one_to_the_clients_that_compact) {
+    FakeScheduler sched;
+    FakeTokenizer tok;
+    FakeChatTemplate tmpl;
+    FakeGrammar gram;
+    Deps d;
+    d.sched = &sched;
+    d.tok = &tok;
+    d.chat = &tmpl;
+    d.grammar = &gram;
+    ServerOptions o;
+    o.model_id = "test-model";
+    o.max_ctx = 8;
+    Server srv(d, o);
+    HttpResponse r = srv.router().call("POST", "/v1/chat/completions",
+                                       R"({"messages":[{"role":"user","content":"a long prompt"}]})");
+    CHECK_EQ(r.status, 400);
+    const json e = json::parse(r.body)["error"];
+    CHECK_EQ(e.value("code", std::string()), std::string("context_length_exceeded"));
+    CHECK(has(e.value("message", std::string()), "maximum context length is 8 tokens"));
+    CHECK(has(e.value("message", std::string()), "exceeds the available context size"));
+    CHECK_EQ(e.value("n_ctx", (int64_t)0), (int64_t)8);
+    CHECK(e.value("n_prompt_tokens", (int64_t)0) > 8);
+    sched.join_all();
+}
+
+/* ================================================================== Anthropic's Messages API */
+
+/* The translation is the chat request the Anthropic one means: the system blocks as one system
+ * message with Claude Code's billing stamp held still, a tool result as a tool message ahead of
+ * the user's own words, the tools and the choice, thinking, stop sequences and the label. */
+TEST(an_anthropic_request_becomes_the_chat_request_it_means) {
+    OaiLimits lim;
+    std::string chat, label;
+    ApiError e;
+    CHECK_OK(anthropic_to_chat(R"({
+        "model":"x","max_tokens":9,"stop_sequences":["END"],
+        "system":[{"type":"text","text":"x-anthropic-billing-header: cc_version=1; cch=a5145;"},
+                  {"type":"text","text":"Be terse.","cache_control":{"type":"ephemeral"}}],
+        "metadata":{"user_id":"user_1_session_9"},
+        "thinking":{"type":"disabled"},
+        "tools":[{"name":"get","description":"d","input_schema":{"type":"object"}}],
+        "tool_choice":{"type":"any","disable_parallel_tool_use":true},
+        "messages":[
+          {"role":"user","content":"weather?"},
+          {"role":"assistant","content":[{"type":"text","text":"Looking."},
+                                         {"type":"tool_use","id":"t1","name":"get","input":{"c":"P"}}]},
+          {"role":"user","content":[{"type":"tool_result","tool_use_id":"t1","content":"sun"},
+                                    {"type":"text","text":"thanks"}]}]})",
+        lim, &chat, &label, &e));
+    const json c = json::parse(chat);
+    CHECK_EQ(c["messages"][0].value("role", ""), std::string("system"));
+    CHECK(has(c["messages"][0].value("content", ""), "cch=fffff;"));
+    CHECK(has(c["messages"][0].value("content", ""), "Be terse."));
+    CHECK_EQ(c["messages"][2]["tool_calls"][0]["function"].value("arguments", ""),
+             std::string(R"({"c":"P"})"));
+    CHECK_EQ(c["messages"][3].value("role", ""), std::string("tool"));        /* result first */
+    CHECK_EQ(c["messages"][3].value("tool_call_id", ""), std::string("t1"));
+    CHECK_EQ(c["messages"][4].value("role", ""), std::string("user"));        /* then the words */
+    CHECK_EQ(c.value("tool_choice", ""), std::string("required"));
+    CHECK(!c.value("parallel_tool_calls", true));
+    CHECK(!c.value("enable_thinking", true));
+    CHECK_EQ(c["stop"][0].get(), std::string("END"));
+    CHECK_EQ(label, std::string("user_1_session_9"));
+
+    /* What would change the answer and cannot be served is refused, by name. */
+    CHECK(anthropic_to_chat(R"({"messages":[{"role":"user","content":[{"type":"document"}]}]})",
+                            lim, &chat, &label, &e) < 0);
+    CHECK(anthropic_to_chat(R"({"messages":[{"role":"user","content":"x"}],
+                                "tools":[{"type":"web_search_20250305","name":"web_search"}]})",
+                            lim, &chat, &label, &e) < 0);
+}
+
+/* The answer and the errors in Anthropic's shapes, through the server. */
+TEST(the_messages_api_answers_in_anthropics_shapes) {
+    Fixture f;
+    HttpResponse r = f.post("/v1/messages",
+                            R"({"model":"x","max_tokens":16,"messages":[{"role":"user","content":"hi"}]})");
+    CHECK_EQ(r.status, 200);
+    const json m = json::parse(r.body);
+    CHECK_EQ(m.value("type", ""), std::string("message"));
+    CHECK(has(m.value("id", ""), "msg_"));
+    CHECK_EQ(m["content"][0].value("type", ""), std::string("text"));
+    CHECK_EQ(m["content"][0].value("text", ""), std::string("hello"));
+    CHECK_EQ(m.value("stop_reason", ""), std::string("end_turn"));
+    CHECK(m["usage"].contains("input_tokens") && m["usage"].contains("output_tokens"));
+    f.sched.join_all();
+
+    HttpResponse bad = f.post("/v1/messages", R"({"model":"x","max_tokens":16})");
+    CHECK_EQ(bad.status, 400);
+    const json e = json::parse(bad.body);
+    CHECK_EQ(e.value("type", ""), std::string("error"));
+    CHECK_EQ(e["error"].value("type", ""), std::string("invalid_request_error"));
+
+    HttpResponse n = f.post("/v1/messages/count_tokens",
+                            R"({"model":"x","messages":[{"role":"user","content":"hi"}]})");
+    CHECK_EQ(n.status, 200);
+    CHECK(json::parse(n.body).value("input_tokens", (int64_t)0) > 0);
+
+    /* The stream: message_start, a text block opened, filled and stopped, then message_delta
+     * and message_stop -- and no [DONE]. */
+    HttpResponse s = f.post("/v1/messages", R"({"model":"x","max_tokens":16,"stream":true,
+                                               "messages":[{"role":"user","content":"hi"}]})");
+    CHECK_EQ(s.status, 200);
+    const std::string body = drain(s);
+    std::vector types;
+    for (size_t at = 0; (at = body.find("event: ", at)) != std::string::npos;) {
+        const size_t nl = body.find('\n', at);
+        types.push_back(body.substr(at + 7, nl - at - 7));
+        at = nl;
+    }
+    CHECK(!types.empty() && types.front() == "message_start");
+    CHECK(types.size() >= 2 && types.back() == "message_stop");
+    CHECK(std::find(types.begin(), types.end(), "content_block_start") != types.end());
+    CHECK(std::find(types.begin(), types.end(), "message_delta") != types.end());
+    CHECK(!has(body, "[DONE]"));
+    f.sched.join_all();
+}
+
+/* ================================================================== OpenAI's Responses API */
+
+/* The translation: instructions as the system message, input items as the turns they are --
+ * a reasoning item and a call joined into one assistant turn, the call's output as a tool message
+ * -- function tools only, max_output_tokens, reasoning.effort, text.format, and every field the
+ * Responses API does not define passed through. */
+TEST(a_responses_request_becomes_the_chat_request_it_means) {
+    OaiLimits lim;
+    std::string chat, echo;
+    ApiError e;
+    CHECK_OK(responses_to_chat(R"({
+        "model":"m","instructions":"Be terse.","max_output_tokens":7,
+        "reasoning":{"effort":"low"},"top_k":5,
+        "text":{"format":{"type":"json_schema","name":"a","schema":{"type":"object"}}},
+        "tools":[{"type":"function","name":"get","parameters":{"type":"object"}},
+                 {"type":"web_search"}],
+        "input":[
+          {"role":"user","content":"weather?"},
+          {"type":"reasoning","summary":[],"content":[{"type":"reasoning_text","text":"think"}]},
+          {"type":"function_call","call_id":"c1","name":"get","arguments":"{}"},
+          {"type":"function_call_output","call_id":"c1","output":"sun"}]})",
+        lim, &chat, &echo, &e));
+    const json c = json::parse(chat);
+    CHECK_EQ(c["messages"][0].value("role", ""), std::string("system"));
+    CHECK_EQ(c["messages"][1].value("role", ""), std::string("user"));
+    CHECK_EQ(c["messages"][2].value("reasoning_content", ""), std::string("think"));
+    CHECK_EQ(c["messages"][2]["tool_calls"][0].value("id", ""), std::string("c1"));
+    CHECK_EQ(c["messages"][3].value("role", ""), std::string("tool"));
+    CHECK_EQ(c["tools"].size(), (size_t)1);                       /* web_search left out */
+    CHECK_EQ(c.value("max_tokens", 0), 7);
+    CHECK_EQ(c.value("reasoning_effort", ""), std::string("low"));
+    CHECK_EQ(c.value("top_k", 0), 5);                             /* passed through */
+    CHECK_EQ(c["response_format"].value("type", ""), std::string("json_schema"));
+    CHECK(!c.contains("input") && !c.contains("text") && !c.contains("instructions"));
+    CHECK_EQ(json::parse(echo).value("instructions", ""), std::string("Be terse."));
+
+    CHECK(responses_to_chat(R"({"input":"x","previous_response_id":"resp_1"})", lim, &chat,
+                            &echo, &e) < 0);
+}
+
+TEST(the_responses_api_answers_with_a_response_object_and_its_events) {
+    Fixture f;
+    HttpResponse r = f.post("/v1/responses", R"({"model":"m","input":"hi"})");
+    CHECK_EQ(r.status, 200);
+    const json o = json::parse(r.body);
+    CHECK_EQ(o.value("object", ""), std::string("response"));
+    CHECK(has(o.value("id", ""), "resp_"));
+    CHECK_EQ(o.value("status", ""), std::string("completed"));
+    CHECK_EQ(o["output"][0].value("type", ""), std::string("message"));
+    CHECK_EQ(o["output"][0]["content"][0].value("text", ""), std::string("hello"));
+    CHECK(o["usage"].contains("total_tokens"));
+    f.sched.join_all();
+
+    HttpResponse n = f.post("/v1/responses/input_tokens", R"({"model":"m","input":"hi"})");
+    CHECK_EQ(json::parse(n.body).value("object", ""), std::string("response.input_tokens"));
+
+    HttpResponse s = f.post("/v1/responses", R"({"model":"m","input":"hi","stream":true})");
+    const std::string body = drain(s);
+    std::vector types;
+    int64_t last_seq = -1;
+    bool ordered = true;
+    for (size_t at = 0; (at = body.find("data: ", at)) != std::string::npos;) {
+        const size_t nl = body.find('\n', at);
+        const json ev = json::parse(body.substr(at + 6, nl - at - 6), nullptr, false);
+        at = nl;
+        if (!ev.is_object()) continue;
+        types.push_back(ev.value("type", ""));
+        const int64_t q = ev.value("sequence_number", (int64_t)-1);
+        ordered = ordered && q == last_seq + 1;
+        last_seq = q;
+    }
+    CHECK(ordered);
+    CHECK(!types.empty() && types.front() == "response.created");
+    CHECK(!types.empty() && types.back() == "response.completed");
+    CHECK(std::find(types.begin(), types.end(), "response.output_text.delta") != types.end());
+    CHECK(!has(body, "[DONE]"));
+    f.sched.join_all();
+}
+
+/* ================================================================== llama-server's native shape */
+
+/* /completion and /completions answer llama-server's native result: the text, how it ended, the
+ * counts, the settings it ran with -- with the generated ids when asked -- and a prompt of strings
+ * and ids mixed is one prompt. */
+TEST(the_native_completion_answers_in_llama_servers_shape) {
+    Fixture f;
+    HttpResponse r = f.post("/completion", R"({"prompt":["a",98],"n_predict":10,"return_tokens":true})");
+    CHECK_EQ(r.status, 200);
+    const json o = json::parse(r.body);
+    CHECK_EQ(o.value("content", ""), std::string("hello"));
+    CHECK(o.value("stop", false));
+    CHECK_EQ(o.value("stop_type", ""), std::string("eos"));
+    CHECK_EQ(o.value("tokens_evaluated", (int64_t)0), (int64_t)2);      /* 'a' and 98: one prompt */
+    CHECK_EQ(o["tokens"].size(), (size_t)5);
+    CHECK(o.contains("generation_settings") && o["generation_settings"].contains("samplers"));
+    f.sched.join_all();
+
+    /* The stream: chunks with the ids that made them, a final result, no [DONE]. */
+    HttpResponse s = f.post("/completions", R"({"prompt":"ab","stream":true})");
+    const std::string body = drain(s);
+    CHECK(has(body, "\"tokens\":["));
+    CHECK(has(body, "\"stop\":true"));
+    CHECK(!has(body, "[DONE]"));
+    f.sched.join_all();
+
+    /* return_tokens is the native endpoint's own; elsewhere it is guarded at its off value. */
+    CHECK_EQ(f.post("/v1/completions", R"({"prompt":"ab","return_tokens":true})").status, 400);
+}
+
+/* ================================================================== logprobs */
+
+/* A sink carries each token's alternatives beside it, for a request that enabled them. */
+TEST(the_sink_carries_a_tokens_alternatives) {
+    Sink s(16);
+    s.enable_logprobs(3);
+    TokenLogprobs lp;
+    lp.logprob = -0.5f;
+    lp.n_top = 2;
+    lp.top_id[0] = 7; lp.top_lp[0] = -0.1f;
+    lp.top_id[1] = 9; lp.top_lp[1] = -2.0f;
+    CHECK(s.push(5, &lp));
+    CHECK(s.push(6));
+    SinkToken buf[4];
+    SinkAlt alts[4 * 3];
+    CHECK_EQ((long long)s.read(buf, 4, alts), 2LL);
+    CHECK_EQ(buf[0].token, 5);
+    CHECK_EQ(buf[0].logprob, -0.5f);
+    CHECK_EQ(buf[0].n_alt, 2);
+    CHECK_EQ(alts[0].id, 7);
+    CHECK_EQ(alts[1].id, 9);
+    CHECK_EQ(alts[1].logprob, -2.0f);
+    CHECK_EQ(buf[1].n_alt, 0);
+}
+
+/* Chat: `logprobs` and `top_logprobs` reach the sampler as n_probs, and every token comes back in
+ * OpenAI's shape with llama-server's id beside it. */
+TEST(chat_logprobs_come_back_per_token_with_their_alternatives) {
+    Fixture f(true, 0, "", true);
+    f.sched.reply = "abc";
+    HttpResponse r = f.post("/v1/chat/completions",
+                            R"({"messages":[{"role":"user","content":"hi"}],
+                                "logprobs":true,"top_logprobs":2})");
+    CHECK_EQ(r.status, 200);
+    CHECK_EQ(f.sched.last_sp.n_probs, 2);
+    const json c = json::parse(r.body)["choices"][0]["logprobs"]["content"];
+    CHECK_EQ(c.size(), (size_t)3);
+    CHECK_EQ(c[1]["token"].get(), std::string("b"));
+    CHECK_EQ(c[1]["id"].get(), (int)'b');
+    CHECK_EQ(c[1]["logprob"].get(), -0.5f);
+    CHECK_EQ(c[1]["bytes"][0].get(), (int)'b');
+    CHECK_EQ(c[1]["top_logprobs"].size(), (size_t)2);
+    CHECK_EQ(c[1]["top_logprobs"][1]["token"].get(), std::string("y"));
+    CHECK_EQ(c[1]["top_logprobs"][1]["logprob"].get(), -2.0f);
+    f.sched.join_all();
+
+    /* `logprobs` alone is the token's own and no alternatives -- OpenAI's default of 0. */
+    HttpResponse z = f.post("/v1/chat/completions",
+                            R"({"messages":[{"role":"user","content":"hi"}],"logprobs":true})");
+    CHECK_EQ(f.sched.last_sp.n_probs, 0);
+    const json zc = json::parse(z.body)["choices"][0]["logprobs"]["content"];
+    CHECK_EQ(zc.size(), (size_t)3);
+    CHECK(zc[0]["top_logprobs"].empty());
+    f.sched.join_all();
+
+    /* Streamed: each token's entry rides a chunk, and together they are the reply's. */
+    HttpResponse s = f.post("/v1/chat/completions",
+                            R"({"messages":[{"role":"user","content":"hi"}],"stream":true,
+                                "logprobs":true,"top_logprobs":1})");
+    const std::string body = drain(s);
+    size_t n = 0;
+    for (size_t at = body.find("data: {"); at != std::string::npos;
+         at = body.find("data: {", at + 1)) {
+        const json ev = json::parse(body.substr(at + 6, body.find("\n\n", at) - at - 6));
+        const json& ch = ev["choices"][0];
+        if (ch.contains("logprobs") && ch["logprobs"].is_object())
+            n += ch["logprobs"]["content"].size();
+    }
+    CHECK_EQ(n, (size_t)3);
+    f.sched.join_all();
+}
+
+TEST(logprobs_are_refused_out_of_range_and_with_echo) {
+    Fixture f(true, 0, "", true);
+    CHECK_EQ(f.post("/v1/chat/completions",
+                    R"({"messages":[{"role":"user","content":"hi"}],"logprobs":true,
+                        "top_logprobs":21})").status, 400);
+    CHECK_EQ(f.post("/v1/chat/completions",
+                    R"({"messages":[{"role":"user","content":"hi"}],"top_logprobs":2})").status,
+             400);
+    CHECK_EQ(f.post("/v1/completions", R"({"prompt":"hi","logprobs":2,"echo":true})").status,
+             400);
+    CHECK_EQ(f.post("/completion", R"({"prompt":"hi","n_probs":2,"post_sampling_probs":true})")
+                 .status, 400);
+}
+
+/* Legacy completions: OpenAI's parallel arrays, with llama-server's content array beside them. */
+TEST(completion_logprobs_have_the_legacy_shape) {
+    Fixture f(true, 0, "", true);
+    f.sched.reply = "abc";
+    HttpResponse r = f.post("/v1/completions", R"({"prompt":"hi","logprobs":2})");
+    CHECK_EQ(r.status, 200);
+    const json lp = json::parse(r.body)["choices"][0]["logprobs"];
+    CHECK_EQ(lp["tokens"].size(), (size_t)3);
+    CHECK_EQ(lp["tokens"][2].get(), std::string("c"));
+    CHECK_EQ(lp["token_logprobs"][2].get(), -0.75f);
+    CHECK_EQ(lp["top_logprobs"][0]["x"].get(), -1.0f);
+    CHECK_EQ(lp["text_offset"][2].get(), 2);
+    CHECK_EQ(lp["content"].size(), (size_t)3);
+    f.sched.join_all();
+}
+
+/* A stop string's own tokens never went out, so their logprobs do not either. */
+TEST(logprobs_end_where_the_stop_string_cut_the_reply) {
+    Fixture f(true, 0, "", true);
+    f.sched.reply = "abXYc";
+    HttpResponse r = f.post("/v1/completions", R"({"prompt":"hi","logprobs":1,"stop":["XY"]})");
+    const json o = json::parse(r.body)["choices"][0];
+    CHECK_EQ(o["text"].get(), std::string("ab"));
+    CHECK_EQ(o["logprobs"]["tokens"].size(), (size_t)2);
+    f.sched.join_all();
+}
+
+/* llama-server's native n_probs: completion_probabilities on the answer, and on each streamed
+ * chunk instead when streaming. */
+TEST(native_n_probs_return_completion_probabilities) {
+    Fixture f(true, 0, "", true);
+    f.sched.reply = "ab";
+    HttpResponse r = f.post("/completion", R"({"prompt":"hi","n_probs":3})");
+    CHECK_EQ(r.status, 200);
+    const json o = json::parse(r.body);
+    CHECK_EQ(o["completion_probabilities"].size(), (size_t)2);
+    CHECK_EQ(o["completion_probabilities"][0]["top_logprobs"].size(), (size_t)3);
+    CHECK_EQ(o["completion_probabilities"][0]["id"].get(), (int)'a');
+    CHECK_EQ(o["generation_settings"]["n_probs"].get(), 3);
+    f.sched.join_all();
+
+    HttpResponse s = f.post("/completion", R"({"prompt":"hi","n_probs":1,"stream":true})");
+    const std::string body = drain(s);
+    CHECK(has(body, "\"completion_probabilities\":[{"));
+    f.sched.join_all();
+}
+
+/* A model with no fill-in-the-middle tokens -- the fixture's -- cannot infill, and says so. */
+TEST(infill_without_fim_tokens_is_refused_by_name) {
+    Fixture f;
+    HttpResponse r = f.post("/infill", R"({"input_prefix":"def f():\n    ","input_suffix":"\n"})");
+    CHECK_EQ(r.status, 501);
+    CHECK(has(r.body, "fill-in-the-middle"));
+}
+
+/* With the markers, a fill is served; a field of the wrong type, or a body nested past the
+ * bound every generation endpoint holds, is a 400. */
+TEST(infill_serves_a_fill_and_refuses_a_malformed_body) {
+    Fixture f;
+    f.tok.fim = true;
+    CHECK_EQ(f.post("/infill", R"({"input_prefix":"a","input_suffix":"b",
+                                   "input_extra":[{"filename":"x.py","text":"y"}]})").status, 200);
+    f.sched.join_all();
+    for (const char* body : { R"({"input_prefix":"a","n_predict":"many"})",
+                              R"({"input_prefix":"a","max_tokens":1.5})",
+                              R"({"input_prefix":"a","input_extra":[{"filename":5}]})",
+                              R"({"input_prefix":"a","input_extra":[{"text":["y"]}]})" })
+        CHECK_EQ(f.post("/infill", body).status, 400);
+    const std::string deep = R"({"input_prefix":"a","input_extra":)" + std::string(2000, '[') +
+                             std::string(2000, ']') + "}";
+    CHECK_EQ(f.post("/infill", deep).status, 400);
+}
+
+/* ================================================================== malformed and failed */
+
+/* A FIELD OF THE WRONG TYPE is a 400 naming it on every API, never a 500: the translators read
+ * the client's fields before the chat parser checks them, and the chat parser reads a few before
+ * its own validation. */
+TEST(a_field_of_the_wrong_type_is_a_400_on_every_api) {
+    Fixture f;
+    struct Case { const char* path; const char* body; const char* param; };
+    for (const Case& c : {
+             Case{ "/v1/messages", R"({"model":"x","max_tokens":9,"messages":[{"role":1,"content":"hi"}]})",
+                   "messages[].role" },
+             Case{ "/v1/messages", R"({"model":"x","max_tokens":9,"messages":[{"role":"user",
+                   "content":[{"type":"text","text":5}]}]})", "messages[].content[].text" },
+             Case{ "/v1/messages", R"({"model":"x","max_tokens":9,"messages":[{"role":"user",
+                   "content":[{"type":"image","source":"x"}]}]})", "messages[].content[].source" },
+             Case{ "/v1/messages", R"({"model":"x","max_tokens":9,"system":[{"type":"text","text":[]}],
+                   "messages":[{"role":"user","content":"hi"}]})", "system[].text" },
+             Case{ "/v1/messages", R"({"model":"x","max_tokens":9,"tool_choice":{"type":"auto",
+                   "disable_parallel_tool_use":"yes"},"messages":[{"role":"user","content":"hi"}]})",
+                   "disable_parallel_tool_use" },
+             Case{ "/v1/chat/completions", R"({"messages":["x",{"role":"assistant","content":"hi"}]})",
+                   "messages[]" },
+             Case{ "/v1/chat/completions", R"({"messages":[{"role":"user",
+                   "content":[{"type":"text","text":5}]}]})", "messages[].content[].text" },
+             Case{ "/v1/responses", R"({"input":[{"type":5}]})", "input[].type" },
+             Case{ "/v1/responses", R"({"input":[{"role":"user","content":[{"type":"input_text",
+                   "text":5}]}]})", "input[].content[].text" },
+             Case{ "/v1/responses", R"({"input":[{"type":"function_call","name":"f","arguments":{}}]})",
+                   "input[].arguments" },
+             Case{ "/v1/responses", R"({"input":"hi","tool_choice":{"type":"function","name":7}})",
+                   "tool_choice.name" } }) {
+        HttpResponse r = f.post(c.path, c.body);
+        CHECK_EQ(r.status, 400);
+        const json e = json::parse(r.body, nullptr, false);
+        CHECK(e.is_object() && e.contains("error"));
+        if (e.is_object() && e["error"].contains("param"))
+            CHECK_EQ(e["error"]["param"].get(), std::string(c.param));
+        else
+            CHECK(has(r.body, c.param));
+    }
+}
+
+/* A STREAM THE ENGINE FAILED ends in its API's own failure, never in its success event: a
+ * client that stops reading at the terminal event must not take the partial reply as whole. */
+TEST(a_failed_stream_ends_in_its_apis_own_failure) {
+    Fixture f;
+    f.sched.reply = "he";
+    f.sched.fail_status = RAD_E_UNSUPPORTED;
+    f.sched.fail_why = "boom";
+
+    HttpResponse a = f.post("/v1/messages", R"({"model":"x","max_tokens":16,"stream":true,
+                                               "messages":[{"role":"user","content":"hi"}]})");
+    const std::string ab = drain(a);
+    CHECK(has(ab, "event: error\ndata: {\"type\":\"error\""));
+    CHECK(has(ab, "boom"));
+    CHECK(!has(ab, "message_delta"));
+    CHECK(!has(ab, "message_stop"));
+    f.sched.join_all();
+
+    HttpResponse r = f.post("/v1/responses", R"({"model":"m","input":"hi","stream":true})");
+    const std::string rb = drain(r);
+    CHECK(has(rb, "event: response.failed"));
+    CHECK(has(rb, "\"status\":\"failed\""));
+    CHECK(has(rb, "boom"));
+    CHECK(!has(rb, "response.completed"));
+    f.sched.join_all();
+
+    HttpResponse c = f.post("/v1/chat/completions", R"({"stream":true,
+                                                       "messages":[{"role":"user","content":"hi"}]})");
+    const std::string cb = drain(c);
+    CHECK(has(cb, "\"finish_reason\":\"error\""));
+    CHECK(has(cb, "boom"));
+    f.sched.join_all();
+}
+
+/* ================================================================== the functions API */
+
+/* OpenAI's DEPRECATED functions API end to end: the reply's call is `function_call` with
+ * finish_reason "function_call", streamed and not, one call at most; and the next turn -- the
+ * assistant's function_call and the `function` message with its result -- is served. */
+TEST(the_functions_api_answers_and_continues_in_its_own_shape) {
+    Fixture f;
+    f.sched.reply = R"(TOOL:get:{"c":"P"})";
+    const std::string fns = R"("functions":[{"name":"get","parameters":{"type":"object"}}],)";
+    HttpResponse r = f.post("/v1/chat/completions",
+                            "{" + fns + R"("messages":[{"role":"user","content":"weather?"}]})");
+    CHECK_EQ(r.status, 200);
+    CHECK(!f.tmpl.last_opt.parallel_tool_calls);
+    const json c = json::parse(r.body)["choices"][0];
+    CHECK_EQ(c["finish_reason"].get(), std::string("function_call"));
+    CHECK_EQ(c["message"]["function_call"]["name"].get(), std::string("get"));
+    CHECK_EQ(c["message"]["function_call"]["arguments"].get(),
+             std::string(R"({"c":"P"})"));
+    CHECK(!c["message"].contains("tool_calls"));
+    f.sched.join_all();
+
+    HttpResponse s = f.post("/v1/chat/completions",
+                            "{" + fns + R"("stream":true,"messages":[{"role":"user","content":"w"}]})");
+    const std::string body = drain(s);
+    CHECK(has(body, R"("delta":{"function_call":{"name":"get","arguments":""}})"));
+    CHECK(has(body, R"("finish_reason":"function_call")"));
+    CHECK(!has(body, "tool_calls"));
+    f.sched.join_all();
+
+    f.sched.reply = "sunny";
+    HttpResponse t = f.post("/v1/chat/completions", "{" + fns + R"("messages":[
+        {"role":"user","content":"weather?"},
+        {"role":"assistant","content":null,"function_call":{"name":"get","arguments":"{\"c\":\"P\"}"}},
+        {"role":"function","name":"get","content":"sun"}]})");
+    CHECK_EQ(t.status, 200);
+    CHECK_EQ(json::parse(t.body)["choices"][0]["message"]["content"].get(),
+             std::string("sunny"));
+    f.sched.join_all();
+}
+
+/* ================================================================== odds and ends */
+
+/* What the Responses API cannot carry is refused rather than computed and dropped: several
+ * choices, and logprobs in any spelling. The chat stream's own extras are dropped. */
+TEST(the_responses_api_refuses_what_a_response_cannot_carry) {
+    Fixture f(true, 0, "", true);
+    for (const char* extra : { R"("n":2)", R"("logprobs":true)", R"("top_logprobs":3)",
+                               R"("n_probs":2)", R"("include":["message.output_text.logprobs"])" })
+        CHECK_EQ(f.post("/v1/responses", std::string(R"({"input":"hi",)") + extra + "}").status, 400);
+    HttpResponse ok = f.post("/v1/responses", R"({"input":"hi","stream":true,"return_progress":true,
+                                                  "stream_options":{"include_usage":true},
+                                                  "include":["reasoning.encrypted_content"]})");
+    CHECK_EQ(ok.status, 200);
+    const std::string body = drain(ok);
+    CHECK(!has(body, "chat.completion.chunk"));
+    CHECK(has(body, "response.completed"));
+    f.sched.join_all();
+}
+
+/* text_offset is where each token's text starts in the reply, streamed or not, even where a token
+ * carries half a character and its own text is empty. */
+TEST(text_offset_is_the_same_streamed_and_not_past_a_split_character) {
+    Fixture f(true, 0, "", true);
+    f.sched.reply = "a\xC3\xA9" "b";
+    HttpResponse r = f.post("/v1/completions", R"({"prompt":"hi","logprobs":1})");
+    CHECK_EQ(r.status, 200);
+    const json want = json::array({ 0, 1, 2, 3 });
+    CHECK(json::parse(r.body)["choices"][0]["logprobs"]["text_offset"] == want);
+    f.sched.join_all();
+
+    HttpResponse s = f.post("/v1/completions", R"({"prompt":"hi","logprobs":1,"stream":true})");
+    json got = json::array();
+    int bad = 0;
+    for (const std::string& p : sse_payloads(drain(s), &bad)) {
+        if (p == "[DONE]") continue;
+        const json j = json::parse(p);
+        const json& lp = j["choices"][0]["logprobs"];
+        if (lp.is_object()) for (const json& o : lp["text_offset"]) got.push_back(o);
+    }
+    CHECK_EQ(bad, 0);
+    CHECK(got == want);
+    f.sched.join_all();
+}
+
+/* A piece that is not whole UTF-8 goes as its bytes, 0 to 255, as llama-server sends it. */
+TEST(tokenize_pieces_carry_bytes_unsigned) {
+    Fixture f;
+    HttpResponse r = f.post("/tokenize", R"({"content":"\u00e9","with_pieces":true})");
+    CHECK_EQ(r.status, 200);
+    const json t = json::parse(r.body)["tokens"];
+    CHECK_EQ(t.size(), (size_t)2);
+    CHECK(t[0]["piece"] == json::array({ 0xC3 }));
+    CHECK(t[1]["piece"] == json::array({ 0xA9 }));
+}
+
+/* A conversation label is cut to 128 bytes where a character starts, so it stays text. */
+TEST(a_long_session_label_is_cut_on_a_character) {
+    Fixture f;
+    const std::string id = std::string(127, 'a') + "\xC3\xA9";
+    CHECK_EQ(f.post("/v1/chat/completions", R"({"messages":[{"role":"user","content":"hi"}],
+                                               "session_id":")" + id + "\"}").status, 200);
+    f.sched.join_all();
+    std::lock_guard lk(f.sched.mu);
+    CHECK_EQ(f.sched.last_label, std::string(127, 'a'));
+}
+
+/* Anthropic's reply names the model the request asked for, as Anthropic's does. */
+TEST(the_messages_api_names_the_requested_model) {
+    Fixture f;
+    HttpResponse r = f.post("/v1/messages", R"({"model":"claude-x","max_tokens":4,
+                                               "messages":[{"role":"user","content":"hi"}]})");
+    CHECK_EQ(r.status, 200);
+    CHECK_EQ(json::parse(r.body).value("model", ""), std::string("claude-x"));
+    f.sched.join_all();
+}
+
 RAD_TEST_MAIN()
diff --git a/tests/wire_test.cpp b/tests/wire_test.cpp
index 50738aa6..befb8629 100644
--- a/tests/wire_test.cpp
+++ b/tests/wire_test.cpp
@@ -546,11 +546,19 @@ TEST(a_text_completion_body_is_the_other_shape_entirely) {
 
 /* THE LOGPROB SHAPES DIFFER BETWEEN THE TWO ENDPOINTS and both are fixed by the schema: chat
  * nests an array of per-token objects under `content`, completions carries four parallel arrays.
- * text_offset is cumulative over the token texts, which is what makes it an offset into `text`. */
+ * text_offset is where each token's text starts in `text`: where the token before it ended. */
 TEST(logprobs_take_each_endpoints_own_shape) {
     ChoiceOut c;
     c.text = "abcd";
-    c.logprobs = { { 1, "ab", -0.5f }, { 2, "cd", -1.5f } };
+    auto entry = [](int32_t id, const char* t, float lp, size_t end) {
+        LogprobEntry e;
+        e.token = id;
+        e.text = e.bytes = t;
+        e.logprob = lp;
+        e.end = end;
+        return e;
+    };
+    c.logprobs = { entry(1, "ab", -0.5f, 2), entry(2, "cd", -1.5f, 4) };
     OaiRequest r = a_request("x", "m");
     r.want_logprobs = true;
 
diff --git a/tools/rad_chatparse.cpp b/tools/rad_chatparse.cpp
index 40531172..c0e0f950 100644
--- a/tools/rad_chatparse.cpp
+++ b/tools/rad_chatparse.cpp
@@ -244,7 +244,7 @@ Timing time_new(const Bench& b, const std::vector& pieces, int reps
             server::ChatDeltaStream st(req, 0, &bridge);
             size_t n = st.first_chunk().size();
             for (const std::string& p : pieces) n += st.push(p, false).size();
-            n += st.final_chunk(server::Finish::Stop).size();
+            n += st.final_chunk(server::Finish::Stop, server::TimingsOut(), server::UsageOut()).size();
             if (n == 0) std::fprintf(stderr, "no output\n");
         }
         best.sse = std::min(best.sse, since(t0));
@@ -463,7 +463,7 @@ int breakdown(const Bench& b, const Tok& tk, const RealView& view, int reps) {
                 std::string c = st.push(p, false);
                 if (r == 0) all += c;
             }
-            o += st.final_chunk(server::Finish::Stop);
+            o += st.final_chunk(server::Finish::Stop, server::TimingsOut(), server::UsageOut());
             if (r == 0) all += o;
         }
         t_stream.push_back(since(c0));
diff --git a/tools/rad_convert.cpp b/tools/rad_convert.cpp
index d822fcbd..9d697203 100644
--- a/tools/rad_convert.cpp
+++ b/tools/rad_convert.cpp
@@ -211,7 +211,8 @@ void usage() {
         "      --list-quantizers  every quantiser loaded and the options each takes, then exit\n"
         "      --arch ID        override the architecture id from the checkpoint\n"
         "      --home DIR       $RADIANCE_HOME (kernels/, architectures/, quantizers/)\n"
-        "      --kernels A:B    kernel plugin hierarchy, first wins. Default $RADIANCE_KERNELS.\n"
+        "      --kernels A:B    the kernel libraries to load, first wins. Default $RADIANCE_KERNELS,\n"
+        "                       else every library found\n"
         "                       Declare checks the recipe against the kernels it resolves\n"
         "      --tokenizer F    tokenizer.json; its declared chain is baked instead of being\n"
         "                       reconstructed from a pre-tokenizer name\n"
@@ -403,6 +404,16 @@ int main(int argc, char** argv) {
      * the last word. Declare reads RadModelMeta and so does the engine's, from the container's
      * header, so a choice that changes the graph is stated once and held at both. */
     for (const auto& kv : set_kv) meta.set(kv.first, kv.second);
+    /* ...AND THE DESCRIPTOR FOLLOWS. The plugin pair is derived from quantization_config, so a
+     * --set of it re-derives the pair rather than leaving the container stating one format and
+     * selecting the plugin of another: a bf16 checkpoint whose recipe writes Qwen's block fp8 is
+     * converted for qwen35_fp8 by stating what that release states. */
+    for (const auto& kv : set_kv)
+        if (kv.first.rfind("quantization_config.", 0) == 0) {
+            meta.quant = quant_descriptor(meta);
+            meta.finish();
+            break;
+        }
 
     /* THE CONTAINER --reuse NAMES, read with pread and never paged through its mapping. */
     RadFile reuse;
diff --git a/tools/rad_kbench.cpp b/tools/rad_kbench.cpp
index 2db4b432..ac6e7430 100644
--- a/tools/rad_kbench.cpp
+++ b/tools/rad_kbench.cpp
@@ -1165,13 +1165,22 @@ int replay_one(const KfCase& c, const Geometry& g, int64_t M,
  */
 /* The library the others are checked against: the one --ref names, else the first kernel library
  * that declared itself a reference implementation (RadPluginReferenceFn) -- by that declaration,
- * never by name, so the library radiance ships is found exactly as one a third party wrote. */
+ * never by name, so the library radiance ships is found exactly as one a third party wrote. A
+ * named one has to be loaded, which --kernels decides: checked against a library that is not
+ * there, every case would come back unchecked. */
 std::string resolve_reference(const Registry& reg, const std::string& named) {
-    if (!named.empty()) return named;
+    if (!named.empty()) {
+        const Plugin* p = reg.plugin(named);
+        if (p && (p->kind & RAD_PLUGIN_KERNEL)) return p->name;
+        RAD_ERR("--ref names '%s', which is not a loaded kernel library: name it in --kernels "
+                "too when that lists the libraries to load", named.c_str());
+        return std::string();
+    }
     for (const Plugin& p : reg.plugins())
         if (p.kind == RAD_PLUGIN_KERNEL && p.reference) return p.name;
-    RAD_ERR("no kernel library on the search path declares itself a reference implementation, so "
-            "there is nothing to check against; name one with --ref");
+    RAD_ERR("no kernel library loaded declares itself a reference implementation, so there is "
+            "nothing to check against: name one with --ref, and in --kernels when that lists the "
+            "libraries to load (libref is the one radiance ships)");
     return std::string();
 }
 
@@ -1487,7 +1496,7 @@ void usage() {
         "                     Attention is swept over DEPTH as well as query length: the paged\n"
         "                     block table, the split over KV and the window all live there.\n"
         "      --home DIR     $RADIANCE_HOME\n"
-        "      --kernels A:B  kernel plugin hierarchy, first wins\n"
+        "      --kernels A:B  the kernel libraries to load, first wins; default every library found\n"
         "      --op NAME      check only this op (repeatable prefix match)\n"
         "      --ref NAME     the oracle plugin's name (default: the library that declares itself a\n"
         "                     reference implementation)\n"
diff --git a/tools/rad_tune.cpp b/tools/rad_tune.cpp
index f8933eca..691c4431 100644
--- a/tools/rad_tune.cpp
+++ b/tools/rad_tune.cpp
@@ -44,7 +44,7 @@ void usage() {
         "\n"
         "  -m, --model FILE   the .rad whose declared graph supplies the shapes\n"
         "      --home DIR     $RADIANCE_HOME; the cache is written to /tune/.tune\n"
-        "      --kernels A:B  kernel plugin hierarchy, first wins\n"
+        "      --kernels A:B  the kernel libraries to load, first wins; default every library found\n"
         "      --op NAME      tune only ops whose name starts with NAME\n"
         "      --machine KEY  override the machine key (for writing a cache for another box)\n"
         "      --reps N       timing reps, median reported (default 5)\n"