diff --git a/CMakeLists.txt b/CMakeLists.txt index 35d7521a..f37c769c 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.0.6 LANGUAGES C CXX) +project(radiance VERSION 1.0.7 LANGUAGES C CXX) set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD_REQUIRED ON) diff --git a/abi/rad_types.h b/abi/rad_types.h index e2a07a42..dbf2c99b 100644 --- a/abi/rad_types.h +++ b/abi/rad_types.h @@ -303,6 +303,19 @@ typedef struct RadConstraint { const char* sval; /* IN: space-separated set of admissible strings */ } RadConstraint; +/* A CONSTRAINT ON THE MACHINE rather than on the geometry. A key that starts "device." is matched + * against what the engine measured about the ranks' devices at launch, not against the op's + * parameters: a capability such as reaching another card's memory belongs to the machine, and + * carrying it as a parameter would have every architecture plugin declare it on every op and + * every schema grow a field for it. Such a key is in no geometry, so it changes no tuning key + * and no selection fold. Where nothing measured it -- a tool selecting without an engine -- it is + * absent, and a constraint on an absent key does not hold. + * + * device.p2p 1 when every rank's device can read and write every other rank's memory + * directly; 0 when some pair cannot. One rank has no peer to reach, and is 1. */ +#define RAD_DEVICE_FACT_PREFIX "device." +#define RAD_FACT_P2P "device.p2p" + #define RAD_C(k, o, v) { (k), (o), (long long)(v), 0 } #define RAD_CEQ(k, v) { (k), RAD_C_EQ, (long long)(v), 0 } #define RAD_CLE(k, v) { (k), RAD_C_LE, (long long)(v), 0 } diff --git a/core/config.cpp b/core/config.cpp index 80c4e34f..5df6fc66 100644 --- a/core/config.cpp +++ b/core/config.cpp @@ -114,6 +114,10 @@ static const Flag g_flags[] = { " set is the template's: Qwen3.8 takes xhigh|medium|low and defaults\n" " to xhigh, which on a short task can spend the whole token budget\n" " inside and answer nothing. \"none\" turns thinking off" }, + { "--thinking-token-budget", "N", "default `thinking_token_budget` for chat requests that do not set one: at\n" + " N reasoning tokens the reasoning block is closed and the answer follows,\n" + " so a client's max_tokens is not spent on reasoning alone. Unset is no\n" + " limit. Needs a reasoning block that ends in one token, as is" }, { "--typical-p", "F", "default typical_p, (0, 1]. This flag and the eleven below set the default\n" " for requests that do not name the field; a request that names it wins" }, { "--presence-penalty", "F", "default presence_penalty, [-2, 2]" }, @@ -449,6 +453,10 @@ int config_parse(int argc, char** argv, Config* c) { } else if (S("--reasoning-effort")) { if (!(v = need(i))) return RAD_E_INVAL; c->reasoning_effort = v; } + else if (S("--thinking-token-budget")) { if (!(v = need(i)) || + !parse_int(a.c_str(), v, 0, INT32_MAX, + &c->thinking_token_budget)) + return RAD_E_INVAL; } else if (S("--generation-config")) { if (!(v = need(i))) return RAD_E_INVAL; c->generation_config = v; } else if (S("--override-chat-template")) { if (!(v = need(i))) return RAD_E_INVAL; diff --git a/core/device/device.h b/core/device/device.h index 2001034f..7132ac11 100644 --- a/core/device/device.h +++ b/core/device/device.h @@ -223,6 +223,11 @@ struct DeviceBackend { * as device memory is shared with every process on the machine. Null on a backend with no such * devices, which answers 0. */ int (*integrated)(int device); + + /* ---- 1 when `self` can read and write `peer`'s memory directly, 0 when it cannot, < 0 when + * the backend cannot say. Asked, not enabled: rad_dev_enable_peer is the call that maps the + * memory. Null on a backend whose devices share one address space, which answers 1. */ + int (*peer_access)(int self, int peer); }; @@ -241,6 +246,9 @@ void tape_destroy(RadTape t); int tape_record(RadTape t, int i, int* kind, uint32_t* queue); int tape_set_overlap(RadTape t, int i, bool on); +/* The current backend's DeviceBackend::peer_access. */ +int dev_peer_access(int self, int peer); + /* The current backend's DeviceBackend::vram_used. */ int dev_vram_used(int device, int64_t* out); diff --git a/core/device/dispatch.cpp b/core/device/dispatch.cpp index 1bae7081..7e7a97b4 100644 --- a/core/device/dispatch.cpp +++ b/core/device/dispatch.cpp @@ -430,6 +430,10 @@ int tape_set_overlap(RadTape t, int i, bool on) { return dev()->tape_set_overlap ? dev()->tape_set_overlap(t, i, on ? 1 : 0) : RAD_E_UNSUPPORTED; } bool dev_integrated(int device) { return dev()->integrated && dev()->integrated(device) > 0; } +int dev_peer_access(int self, int peer) { + if (self == peer) return 1; + return dev()->peer_access ? dev()->peer_access(self, peer) : 1; +} size_t dev_code_mark() { return dev()->code_mark ? dev()->code_mark() : 0; } int dev_code_runs(size_t from, size_t to, int device, std::string* why) { if (!dev()->code_runs || from >= to) return 1; diff --git a/core/device/hip.cpp b/core/device/hip.cpp index 4141a3cf..623d78ce 100644 --- a/core/device/hip.cpp +++ b/core/device/hip.cpp @@ -251,6 +251,12 @@ int d_props(int device, RadDeviceProps* out) { return RAD_OK; } +int d_peer_access(int self, int peer) { + int can = 0; + HIP_TRY(hipDeviceCanAccessPeer(&can, self, peer)); + return can ? 1 : 0; +} + int d_enable_peer(int self, int peer) { if (self == peer) return RAD_OK; int can = 0; @@ -370,6 +376,7 @@ const DeviceBackend g_hip = { /* Plugin device code: the AQL backend's, which owns the fat-binary registrations. */ nullptr, nullptr, d_integrated, + d_peer_access, }; } /* namespace */ diff --git a/core/engine.cpp b/core/engine.cpp index 6dc3ed20..9e56ddb4 100644 --- a/core/engine.cpp +++ b/core/engine.cpp @@ -1812,6 +1812,8 @@ std::string request_overrides(const Config& c) { std::to_string(c.max_stop_bytes) + " bytes"); for (const auto& [k, v] : c.chat_template_kwargs) add("template " + k + "=" + v); if (c.reasoning_format != "auto") add("reasoning_format " + c.reasoning_format); + if (c.thinking_token_budget >= 0) + add("thinking_token_budget " + std::to_string(c.thinking_token_budget)); return out; } } /* namespace */ @@ -2029,6 +2031,7 @@ int Engine::run_server() { o.max_n = cfg_.max_n > 0 ? (int)cfg_.max_n : (int)std::max(o.max_n, cfg_.max_seqs); o.max_ctx = cfg_.max_ctx ? cfg_.max_ctx : meta_.n_ctx_train; o.default_reasoning_effort = cfg_.reasoning_effort; + 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(); /* -1 leaves ServerOptions' own default, which is `auto` (0). That is resolved per request @@ -2154,6 +2157,13 @@ int Engine::run_server() { "that sends no reasoning effort of its own will be answered 400: %s", cfg_.reasoning_effort.c_str(), eff_why.c_str()); } + /* A BUDGET THE MODEL CANNOT HOLD STOPS STARTUP, as --chat-template-kwargs does: the default + * would apply to no request at all, and the operator who set it would not find out. */ + if (const std::string why = srv.check_thinking_budget(); !why.empty()) { + RAD_ERR("--thinking-token-budget %lld: %s", (long long)cfg_.thinking_token_budget, + why.c_str()); + return RAD_E_INVAL; + } RAD_INFO("serving on http://%s:%d (/v1/completions%s)%s", o.host.c_str(), o.port, d.chat ? "; /v1/chat/completions with tools and reasoning" : "; chat is 501", o.api_key.empty() ? "" : " -- a bearer key is required"); diff --git a/core/engine_bringup.cpp b/core/engine_bringup.cpp index 66ce0f6f..4c8f078c 100644 --- a/core/engine_bringup.cpp +++ b/core/engine_bringup.cpp @@ -188,6 +188,58 @@ static int usable_devices(std::vector* out, std::string* inventory, std::st return out->empty() ? RAD_E_DEVICE : RAD_OK; } +/* WHY A POOL'S MEMORY WAS REFUSED, from what the machine holds now. The refusal carries the + * driver's own answer; these are the facts that explain most of them. + * + * A card refusing its weights pool after its budget was measured had that memory taken in + * between, and another process on the card is the usual taker -- the budget is measured once, + * before any rank allocates. A host pool is PINNED memory, and the amdgpu driver caps what the + * whole system may pin (ttm.pages_limit, half of RAM unless raised); every rank pins its own + * --host-pool-mib, so a second rank asks for the same amount again. */ +static void report_pool_refusal(int rank, int device, const Pools& pools, const Config& cfg) { + bool card = false, host = false; + for (const Shortfall& f : pools.shortfalls()) (f.pool == "host_pool" ? host : card) = true; + if (card) { + RadDeviceProps p{}; + if (rad_dev_props(device, &p) == RAD_OK) + RAD_ERR("card %d has %s of %s free now. Its budget was measured before any rank " + "allocated, so memory gone since then is another process's; rocm-smi " + "--showpids names it", device, humanb(p.vram_free).c_str(), + humanb(p.vram_bytes).c_str()); + } + if (host) { + int64_t pinned = 0, mapped = 0; + rad_dev_alloc_totals(RAD_MEM_HOST_PINNED, &pinned, nullptr); + rad_dev_alloc_totals(RAD_MEM_HOST_MAPPED, &mapped, nullptr); + int64_t cap = -1, avail = -1; + { + std::ifstream f("/sys/module/ttm/parameters/pages_limit"); + long long pages = 0; + if (f >> pages && pages > 0) cap = (int64_t)pages * (int64_t)sysconf(_SC_PAGESIZE); + } + { + std::ifstream f("/proc/meminfo"); + std::string line; + while (std::getline(f, line)) { + long long kb = 0; + if (std::sscanf(line.c_str(), "MemAvailable: %lld kB", &kb) == 1) { + avail = (int64_t)kb * 1024; + break; + } + } + } + RAD_ERR("host: --host-pool-mib %lld 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. Lower --host-pool-mib, or raise the cap", + (long long)cfg.host_pool_mib, cfg.tp, + humanb((int64_t)cfg.tp * cfg.host_pool_mib * 1024 * 1024).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"); + } +} + /* ================================================================== 2. metadata */ /* The model's metadata ONLY -- architecture id, dimensions, quantisation, vocab. Not the weights: * which weights exist is the architecture plugin's answer, not the container's, and reading them @@ -770,7 +822,10 @@ int Engine::plan() { * much rather than shrinking anything. */ int s = r->pools.configure(cfg_, props.vram_bytes); RAD_INFO("pools:\n%s", r->pools.fit_report().c_str()); - if (s < 0) return s; + if (s < 0) { + report_pool_refusal(r->index, r->device, r->pools, cfg_); + return s; + } /* Under tensor parallel the placement unit is a SHARD of a weight, so each rank plans * against its own card's budget (spec §5.3). */ @@ -2424,6 +2479,40 @@ int Engine::start() { ranks_.push_back(std::move(r)); } + /* PEER ACCESS, MEASURED BEFORE ANYTHING IS SELECTED. A kernel that reads or writes another + * card's memory says so with a constraint on device.p2p (rad_types.h), and the selector reads + * it from here: on a machine where some pair of the ranks' cards cannot reach each other such a + * kernel is not selected, and declare names the constraint instead of the all-reduce faulting + * or hanging on its first message. Every ordered pair, because access is granted one way at a + * time. */ + { + long long p2p = 1; + std::string blocked; + for (int i = 0; i < cfg_.tp; ++i) + for (int j = 0; j < cfg_.tp; ++j) { + if (i == j) continue; + const int a = dev_peer_access(devs[i], devs[j]); + if (a < 0) { + RAD_ERR("device: could not ask whether card %d can reach card %d's memory: %s", + devs[i], devs[j], rad_dev_last_error()); + return a; + } + if (a == 0) { + p2p = 0; + blocked += fmt("%s%d->%d", blocked.empty() ? "" : ", ", devs[i], devs[j]); + } + } + rad_tools_registry().set_device_fact(RAD_FACT_P2P, p2p); + if (cfg_.tp > 1) { + if (p2p) RAD_INFO("device: the %d cards reach each other's memory directly (peer to " + "peer)", cfg_.tp); + else RAD_WARN("device: no peer-to-peer access between cards %s. A kernel that needs " + "it (device.p2p == 1) is not selected; if nothing else implements its " + "op, startup stops below naming it. IOMMU settings and the PCIe " + "topology decide this, not radiance", blocked.c_str()); + } + } + RAD_TRY(declare()); /* --debug-graph stops here on purpose: everything it prints is known between declare and diff --git a/core/mem/pools.cpp b/core/mem/pools.cpp index 168359a3..c3aeec37 100644 --- a/core/mem/pools.cpp +++ b/core/mem/pools.cpp @@ -43,6 +43,9 @@ MemAllocator& rad_malloc_allocator() { static MallocAllocator a; return a; } /* ------------------------------------------------------------------ Shortfall */ std::string Shortfall::str() const { + if (!refused.empty()) + return fmt("%s: %s of %s refused: %s", pool.c_str(), what.c_str(), + humanb(wanted).c_str(), refused.c_str()); return fmt("%s: %s wanted %s, %s available -- short by %s", pool.c_str(), what.c_str(), humanb(wanted).c_str(), humanb(available).c_str(), humanb(missing()).c_str()); @@ -81,8 +84,11 @@ int Pool::init(std::string_view nm, int64_t bytes, int kind, MemAllocator* a, bo base_ = a->alloc(bytes_, kind); if (!base_) { /* Refuse; do not retry smaller. An engine that quietly re-optimises the split is an - * engine whose benchmarks do not reproduce (spec §6). */ - shortfalls_.push_back({name_, "backing allocation", bytes_, 0}); + * engine whose benchmarks do not reproduce (spec §6). The allocator's reason goes with + * it: the device layer says what the driver answered. */ + const char* why = a == &rad_device_allocator() ? rad_dev_last_error() : nullptr; + shortfalls_.push_back({name_, "backing allocation", bytes_, 0, + why && *why ? why : "the allocator returned nothing"}); bytes_ = 0; return RAD_E_NOMEM; } @@ -131,7 +137,9 @@ int Pool::init_elastic(std::string_view nm, int64_t bytes, int kind, MemAllocato /* Refuse; do not retry smaller. An address range is not memory -- a reservation that * fails on a 64-bit card is a bug and not a budget, and quietly halving it would hide the * bug behind a pool that cannot grow to what the operator asked for. */ - shortfalls_.push_back({ name_, "address reservation", bytes_, 0 }); + const char* why = rad_dev_last_error(); + shortfalls_.push_back({ name_, "address reservation", bytes_, 0, + *why ? why : "the device layer gave no reason" }); bytes_ = 0; return rc; } diff --git a/core/mem/pools.h b/core/mem/pools.h index 9bf9288e..e141c71c 100644 --- a/core/mem/pools.h +++ b/core/mem/pools.h @@ -54,6 +54,10 @@ struct Shortfall { std::string what; /* what was being reserved when it ran out */ int64_t wanted = 0; int64_t available = 0; + /* A backing allocation the allocator refused: there is no "available" to report, only the + * allocator's own sentence for why, which is what tells an out-of-memory card from a pinned- + * memory limit from a driver that would not map the range. */ + std::string refused; int64_t missing() const { return wanted - available; } std::string str() const; }; diff --git a/core/plugin/registry.h b/core/plugin/registry.h index c5c31580..9a2af22c 100644 --- a/core/plugin/registry.h +++ b/core/plugin/registry.h @@ -181,6 +181,12 @@ public: * loads anything, once it has chosen its cards. */ void set_code_device(int device) { code_device_ = device; } + /* 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. */ + void set_device_fact(std::string_view key, long long v) { device_facts_.set_i(key, v); } + const Geometry& device_facts() const { return device_facts_; } + void close(); /* fini instances, close hooks, dlclose, forget everything */ const std::vector& plugins() const { return plugins_; } @@ -327,6 +333,7 @@ private: }; int code_device_ = 0; + Geometry device_facts_; TuneCache tune_; int stage_(const std::string& path, Staged* out); diff --git a/core/plugin/select.cpp b/core/plugin/select.cpp index db9c1b96..beb3388d 100644 --- a/core/plugin/select.cpp +++ b/core/plugin/select.cpp @@ -23,14 +23,24 @@ namespace { /* True when every constraint holds. Otherwise `why` names the FIRST one that did not and what it * wanted: "no kernel" on its own is not an answer anyone can act on, and the first failure is the * one a reader can fix -- listing all four of a row's unmet constraints buries it. */ -bool row_matches(const KernelRow& r, const Geometry& g, const std::vector& skip, - std::string* why) { +bool row_matches(const KernelRow& r, const Geometry& g, const Geometry& facts, + const std::vector& skip, std::string* why) { + static const size_t kFact = std::strlen(RAD_DEVICE_FACT_PREFIX); for (int i = 0; i < r.info->n_constraints; ++i) { const RadConstraint& c = r.info->constraints[i]; /* A constraint on a RAD_DERIVED parameter the caller did not name is not a predicate on * the question -- it IS the answer, read back afterwards. Matching on it would make the * kernel unreachable by the only query anyone can ask (rad_abi.h, spec §7.2). */ if (c.key && std::find(skip.begin(), skip.end(), c.key) != skip.end()) continue; + /* A "device." key is a fact about the machine, read from what the engine measured. */ + if (c.key && std::strncmp(c.key, RAD_DEVICE_FACT_PREFIX, kFact) == 0) { + if (constraint_holds(c, facts)) continue; + if (why) + *why = facts.has(c.key) + ? constraint_why(c, facts) + " -- this machine, measured at launch" + : std::string(c.key) + " is not known: nothing measured this machine"; + return false; + } if (!constraint_holds(c, g)) { if (why) *why = constraint_why(c, g); return false; @@ -111,7 +121,7 @@ const KernelRow* Registry::select(std::string_view op, const Geometry& g, int do } std::string whynot; - bool ok = row_matches(*r, g, derived_keys, &whynot); + bool ok = row_matches(*r, g, device_facts_, derived_keys, &whynot); if (ok && accept && *accept) { whynot = (*accept)(*r, g); ok = whynot.empty(); diff --git a/core/plugin/testplugin/testplugin.cc b/core/plugin/testplugin/testplugin.cc index f71df373..c17fe7e8 100644 --- a/core/plugin/testplugin/testplugin.cc +++ b/core/plugin/testplugin/testplugin.cc @@ -159,6 +159,11 @@ static const RadConstraint kCNorm4096[] = { static const RadConstraint kCTie[] = { RAD_CGE("M", 1), }; +/* A kernel that reaches another card's memory: a constraint on the machine, not the geometry. */ +static const RadConstraint kCPeer[] = { + RAD_CGE("M", 1), + RAD_CEQ(RAD_FACT_P2P, 1), +}; /* Constraint ORDER is the order the miss message reports in: the first unmet one is what a reader * is told, so the cheapest and most identifying predicate goes first. */ static const RadConstraint kCAttn[] = { @@ -197,6 +202,10 @@ static const RadOpSchema kSchemas[] = { "a derived key its kernel does not pin" }, { "t_skinny", kPGemm, NELEM(kPGemm), kOpdGemm, NELEM(kOpdGemm), "a range with a hole in it" }, { "t_eq", kPTie, NELEM(kPTie), kOpdNorm, NELEM(kOpdNorm), "an EQ band boundary" }, + { "t_peer", kPTie, NELEM(kPTie), kOpdNorm, NELEM(kOpdNorm), + "a peer kernel with a fallback beneath it" }, + { "t_peer_only", kPTie, NELEM(kPTie), kOpdNorm, NELEM(kOpdNorm), + "a peer kernel and nothing else" }, }; static const RadKernelInfo kKernels[] = { @@ -236,6 +245,20 @@ static const RadKernelInfo kKernels[] = { .computes = "nothing; a registry row", .shape = "any", .dtypes = "any", .domain = RAD_DOMAIN_HOST, .priority = 10, .launch = t_launch }, + /* Peer access is the machine's: the direct row needs it, the staged one does not. */ + { .name = "t_peer_direct", .op = "t_peer", .family = "ar", + .computes = "nothing; a registry row", .shape = "M >= 1, cards reach each other", + .dtypes = "any", .domain = RAD_DOMAIN_DEVICE, .priority = 20, + .constraints = kCPeer, .n_constraints = NELEM(kCPeer), .launch = t_launch }, + { .name = "t_peer_staged", .op = "t_peer", .family = "ar", + .computes = "nothing; a registry row", .shape = "M >= 1", .dtypes = "any", + .domain = RAD_DOMAIN_DEVICE, .priority = 10, + .constraints = kCTie, .n_constraints = NELEM(kCTie), .launch = t_launch }, + { .name = "t_peer_only_direct", .op = "t_peer_only", .family = "ar", + .computes = "nothing; a registry row", .shape = "M >= 1, cards reach each other", + .dtypes = "any", .domain = RAD_DOMAIN_DEVICE, .priority = 10, + .constraints = kCPeer, .n_constraints = NELEM(kCPeer), .launch = t_launch }, + /* Same op, same priority, same constraints. Ties break on declaration order, so t_tie_first * wins -- and if it ever does not, the tie rule has silently changed. */ { .name = "t_tie_first", .op = "t_tie", .family = "norm", diff --git a/core/rad_core.h b/core/rad_core.h index 22984c1c..1366f833 100644 --- a/core/rad_core.h +++ b/core/rad_core.h @@ -373,6 +373,50 @@ public: enum class ReqState { Waiting, Running, Preempted, Finished, Failed, Cancelled }; +/* A CHAT REPLY'S REASONING BLOCK, AS TOKENS. The reply parser reads the block in text + * (core/text/chatparse.h); this is the same block named by token id, so the engine can count it + * and close it without detokenising. It exists only where both markers the reply needs are + * single tokens -- `` and `` are, on every model this engine serves -- and + * `close < 0` says it does not: such a reply's reasoning is still split out as text, but it is + * not counted and no budget can be held on it. + * + * The block is read where the parser reads it: at the start of the reply. It is open from the + * first token when the generation prompt opened it (`starts_open`), or opens on `open` as the + * reply's first token, and the first `close` ends it. A reply that starts any other way has no + * block. */ +struct ReasoningSpan { + int32_t open = -1; /* the token a reply opens its own block with; -1 for none */ + int32_t close = -1; /* the token that ends the block; -1: no countable block */ + bool starts_open = false; /* the generation prompt left the reply inside the block */ + bool known() const { return close >= 0; } +}; + +/* A reply's position relative to its ReasoningSpan, advanced one emitted token at a time. The + * server counts with it and the sampler enforces a budget with it, and both must agree on where + * the block ends, so there is one definition. */ +struct ReasoningCount { + enum State : uint8_t { Lead, Think, Done }; + State st = Lead; + int64_t tokens = 0; /* reasoning tokens: the markers the reply wrote, and the body */ + int64_t body = 0; /* the tokens between the markers, which a budget limits */ + + void start(const ReasoningSpan& s) { + st = !s.known() ? Done : s.starts_open ? Think : Lead; + tokens = body = 0; + } + void push(const ReasoningSpan& s, int32_t tok) { + if (st == Lead) { + if (s.open >= 0 && tok == s.open) { st = Think; ++tokens; } + else st = Done; + } else if (st == Think) { + ++tokens; + if (tok == s.close) st = Done; + else ++body; + } + } + bool inside() const { return st == Think; } +}; + struct SamplingParams { float temp = 1.0f; int top_k = 0; /* 0 = off */ @@ -394,6 +438,13 @@ struct SamplingParams { std::string grammar; /* GBNF, or "" */ std::vector dry_seq_breakers; + /* THE REPLY'S REASONING BLOCK, and how many tokens its body may run to. -1 is no limit. At + * the limit the sampler masks every position still inside the block to `reasoning.close`, so + * the block ends there and the answer follows -- vLLM's `thinking_token_budget`. A budget + * needs a known span; the server refuses one it cannot hold. */ + ReasoningSpan reasoning; + int32_t thinking_budget = -1; + /* A LAZY GRAMMAR CONSTRAINS NOTHING UNTIL A TRIGGER FIRES, and that is the only shape in * which a tool-calling chat template can be enforced: the reply is free prose until the * model starts writing a call, and grammar-shaped from there. Without this a request that @@ -651,6 +702,8 @@ struct Config { /* The chat endpoint's default `reasoning_effort`, empty for the template's own default. * Passed through verbatim: the legal set belongs to the template, not to us. */ std::string reasoning_effort; + /* --thinking-token-budget: the chat endpoint's default `thinking_token_budget`, -1 for none. */ + int64_t thinking_token_budget = -1; int port = 8000; /* --api-key: the bearer key every request but the probes and the dashboard page must carry. * Empty serves without one. */ diff --git a/core/sample/sampler.cpp b/core/sample/sampler.cpp index bba83fc2..98e33c7f 100644 --- a/core/sample/sampler.cpp +++ b/core/sample/sampler.cpp @@ -382,7 +382,8 @@ int Sampler::check_request(const SamplingParams& sp, std::string* why) const { 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(dry_on(sp), op_dry_, "sample_dry"); - if (!missing) missing = need(!sp.grammar.empty(), op_mask_, "sample_mask"); + if (!missing) missing = need(!sp.grammar.empty() || sp.thinking_budget >= 0, op_mask_, + "sample_mask"); if (!missing) missing = need(penalties_on(sp), op_penalties_, "sample_penalties"); if (missing) { if (why) *why = std::string("no kernel resolved for '") + missing + "'"; @@ -456,6 +457,7 @@ int Sampler::begin_request(uint64_t req_id, const SamplingParams& sp, std::strin } } + st.think.start(sp.reasoning); seqs_[req_id] = std::move(st); return RAD_OK; } @@ -591,8 +593,25 @@ int Sampler::build_step(const std::vector& reqs) { if (walk) gr->push_state(); bool dead = false; + /* THE REASONING BUDGET, walked over the window as the grammar is. Position k is inside the + * block or not according to the committed reply and drafts 0..k-1, which is the only + * history under which its token is ever emitted; a draft that ends the block early is + * accepted or rejected like any other. */ + const bool budget = st && sp.thinking_budget >= 0 && sp.reasoning.known(); + ReasoningCount think; + if (budget) { + if (st->think_seen > (size_t)n_out) { + st->think.start(sp.reasoning); + st->think_seen = 0; + } + for (; st->think_seen < (size_t)n_out; ++st->think_seen) + st->think.push(sp.reasoning, r->output[st->think_seen]); + think = st->think; + } + for (int k = 0; k < n_pos; ++k) { if (walk && k > 0 && !dead && gr->accept_token(r->draft[k - 1]) < 0) dead = true; + if (budget && k > 0) think.push(sp.reasoning, r->draft[k - 1]); const int64_t row = n_seq_++; DeviceSampleParams& p = params_stage_[row]; @@ -744,6 +763,9 @@ int Sampler::build_step(const std::vector& reqs) { } } } + + if (budget && think.inside() && think.body >= sp.thinking_budget) + force_close(p, row, sp.reasoning.close); } /* Back to where the sequence actually is. The tokens it really accepted are applied by @@ -767,6 +789,29 @@ int Sampler::build_step(const std::vector& reqs) { return RAD_OK; } +void Sampler::force_close(DeviceSampleParams& p, int64_t row, int32_t close) { + uint32_t* dst = mask_stage_ + row * mask_words_; + const int64_t at = (int64_t)close - cfg_.vocab_off; + const bool local = at >= 0 && at < cfg_.n_vocab_local; + if (p.flags & RAD_SP_MASK) { + /* The grammar's mask for this row. Under a split vocabulary the whole one is still in + * mask_full_, and the close may be another rank's column. */ + const bool admitted = + vocab_parallel() + ? close < (int64_t)mask_full_.size() * 32 && + (mask_full_[(size_t)(close >> 5)] >> (uint32_t)(close & 31)) & 1u + : local && (dst[at >> 5] >> (uint32_t)(at & 31)) & 1u; + if (!admitted) return; + } + /* ONE ADMISSIBLE TOKEN, on whichever rank holds its column. The others mask the whole row + * out, which the candidate merge reads as no candidate from them (the grammar's own masks do + * the same when the admissible set lives on one shard). */ + std::memset(dst, 0, (size_t)mask_words_ * 4); + if (local) dst[at >> 5] |= 1u << (uint32_t)(at & 31); + p.mask_row = (int32_t)row; + p.flags |= RAD_SP_MASK; +} + int Sampler::build_greedy(int64_t n) { if (!declared_) return RAD_E_STATE; if (n < 0) return RAD_E_INVAL; diff --git a/core/sample/sampler.h b/core/sample/sampler.h index 7a60a662..5264fadf 100644 --- a/core/sample/sampler.h +++ b/core/sample/sampler.h @@ -218,8 +218,19 @@ private: struct SeqState { std::unique_ptr grammar; DryBreakers dry; + /* Where the reply stands against its reasoning block, over `output[0, think_seen)`. + * Advanced by build_step over what each commit appended, so a step costs the tokens it + * added and not the reply's length. Read only when the request carries a budget. */ + ReasoningCount think; + size_t think_seen = 0; }; + /* Mask staged row `row` to the reasoning block's close token: the budget is spent and the + * sampled position is still inside the block. A grammar already masking the row keeps the + * last word -- the close is forced only where the grammar admits it, and a row whose grammar + * forbids it is left to the grammar and forced at a later position. */ + void force_close(DeviceSampleParams& p, int64_t row, int32_t close); + SamplerConfig cfg_{}; const VocabView* vocab_ = nullptr; bool declared_ = false; diff --git a/core/sched/scheduler.cpp b/core/sched/scheduler.cpp index 04834a01..5b4cf9d5 100644 --- a/core/sched/scheduler.cpp +++ b/core/sched/scheduler.cpp @@ -257,7 +257,8 @@ int Scheduler::set_draft(uint64_t id, const int32_t* tokens, int n) { * * Appending to `Request::output` is not enough on its own: without a push the engine generates * correctly, step after step, while the HTTP thread waits in `Sink::wait()` until the client times - * out. `sink_push`, `sink_finish` and `sink_prompt_stats` are called from here and nowhere else. + * out. Every sink_* call -- push, finish, prompt stats, admission and drafts -- is made from this + * file and nowhere else. * * A push returns false ONLY on overflow, and an overflowing sink has already failed the request -- * a stream missing tokens in the middle is worse than one that stops and says so -- so the return @@ -826,6 +827,7 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget) { if (s.card < 0) { s.card = free_cards_.back(); free_cards_.pop_back(); } r.state = ReqState::Running; s.running = true; + server::sink_admitted(r.sink); s.sched_tokens = (int32_t)want; s.pending_ckpt = ckpt; ++m_.admitted; @@ -1488,6 +1490,7 @@ int Scheduler::commit(const StepResult& res) { draft_.observe(e.n_spec, a); m_.draft_tokens += e.n_spec; m_.draft_accepted += a; + server::sink_drafts(r.sink, e.n_spec, a); } } s.n_draft = 0; diff --git a/core/server/adapters.h b/core/server/adapters.h index 2c95c305..5be8b770 100644 --- a/core/server/adapters.h +++ b/core/server/adapters.h @@ -618,6 +618,10 @@ public: if (why) *why = perr; return ps; } + const ReasoningMarkers rm = rp->reasoning(); + out->think_open = rm.open; + out->think_close = rm.close; + out->think_starts_open = rm.starts_open; out->parser = std::make_shared(std::move(rp)); return RAD_OK; } diff --git a/core/server/admin.cpp b/core/server/admin.cpp index adbb4820..1d2c331a 100644 --- a/core/server/admin.cpp +++ b/core/server/admin.cpp @@ -321,6 +321,8 @@ HttpResponse Server::handle_server_info(const HttpRequest&) { defs["max_tokens"] = srv["default_max_tokens"]; defs["reasoning_effort"] = opt_.default_reasoning_effort.empty() ? json(nullptr) : json(opt_.default_reasoning_effort); + defs["thinking_token_budget"] = opt_.default_thinking_budget < 0 + ? json(nullptr) : json(opt_.default_thinking_budget); json kw = json::object(); for (const auto& [k, v] : opt_.default_template_kwargs) { json parsed = json::parse(v, nullptr, false); diff --git a/core/server/iface.h b/core/server/iface.h index 59040ba5..d6d8ff39 100644 --- a/core/server/iface.h +++ b/core/server/iface.h @@ -391,6 +391,13 @@ struct ChatRender { /* The tokens that parser must be able to SEE. See ITokenizer::detokenizer. */ std::vector preserved_tokens; + + /* THE REASONING BLOCK THIS RENDER LEAVES THE REPLY FACING, as the parser reads it: the + * markers with their optional whitespace trimmed, and whether the reply starts inside the + * block. Empty `think_close` is a model with no reasoning block. The server turns these into + * token ids (ReasoningSpan) to count the block and to hold a budget on it. */ + std::string think_open, think_close; + bool think_starts_open = false; }; class IChatTemplate { diff --git a/core/server/oai.cpp b/core/server/oai.cpp index 922210bd..c0b96c2f 100644 --- a/core/server/oai.cpp +++ b/core/server/oai.cpp @@ -203,6 +203,7 @@ 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", }; const char* kAcceptedCompletion[] = { "prompt", "echo" }; @@ -1157,6 +1158,74 @@ static int clamp_max_tokens(size_t n_prompt, const OaiLimits& lim, const char* f /* ================================================================== chat */ +/* THE REASONING BLOCK BY TOKEN ID, and the budget on it. + * + * The render names the block's markers as text; the engine counts and closes it by token, so + * the markers are encoded here, once per request. A marker that is not one token leaves the span + * unknown: the reply's reasoning is still split out, but it is not counted and cannot be closed + * by forcing a token. The opener matters only to a reply that must open its own block. + * + * `thinking_token_budget` is vLLM's name for the field and `thinking_budget` Qwen's API's; both + * are read, as max_tokens and max_completion_tokens are. A budget the span cannot hold is a 400 + * naming why -- accepting it and generating unbounded reasoning is the outcome this file's + * header forbids. The deployment's default applies only where it can be held: a reply whose + * block cannot be counted gets none, as it would on a model with no reasoning block at all. */ +static int parse_thinking_budget(const json& b, const OaiDeps& d, const OaiLimits& lim, + const ChatRender& render, SamplingParams* sp, ApiError* err) { + ReasoningSpan span; + size_t n_close = 0, n_open = 0; + if (!render.think_close.empty() && d.tok) { + const std::vector c = d.tok->encode(render.think_close, false, true); + std::vector o; + if (!render.think_open.empty()) o = d.tok->encode(render.think_open, false, true); + n_close = c.size(); + n_open = o.size(); + if (c.size() == 1 && (render.think_starts_open || o.size() == 1)) { + span.close = c[0]; + span.open = o.size() == 1 ? o[0] : -1; + span.starts_open = render.think_starts_open; + } + } + sp->reasoning = span; + + int64_t budget = -1; + const char* named = nullptr; + for (const char* k : { "thinking_token_budget", "thinking_budget" }) { + 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; } + if (named && v != budget) { + *err = err_bad(k, std::string("disagrees with ") + named + ", which is the same field"); + return RAD_E_INVAL; + } + budget = v; + named = k; + } + if (!named) { + if (span.known()) sp->thinking_budget = (int32_t)lim.default_thinking_budget; + return RAD_OK; + } + if (!span.known()) { + std::string why; + if (render.think_close.empty()) + why = "this model's chat template has no reasoning block to hold a budget on"; + else if (n_close != 1) + why = "this model's reasoning block ends in `" + render.think_close + "`, which is " + + std::to_string(n_close) + " tokens, and a budget is held by forcing that end " + "as one token"; + else + why = "this reply has to open its own reasoning block, and the opener `" + + render.think_open + "` is " + std::to_string(n_open) + " tokens, so the block " + "cannot be found by token"; + *err = err_unsupported(named, why); + return RAD_E_UNSUPPORTED; + } + sp->thinking_budget = (int32_t)budget; + return RAD_OK; +} + int parse_chat_request(const std::string& body, const OaiDeps& d, const OaiLimits& lim, OaiRequest* out, ApiError* err) { json b; @@ -1347,6 +1416,7 @@ int parse_chat_request(const std::string& body, const OaiDeps& d, const OaiLimit out->reply_parser = render.parser; out->preserved_tokens = render.preserved_tokens; out->parse_tools = out->tools_present && render.parser != nullptr; + RAD_TRY(parse_thinking_budget(b, d, lim, render, &out->sp, err)); /* 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 @@ -1639,6 +1709,39 @@ static json usage_json(const UsageOut& u) { o["completion_tokens"] = u.completion; o["total_tokens"] = u.prompt + u.completion; o["prompt_tokens_details"] = d; + /* HOW MUCH OF completion_tokens THE CLIENT NEVER SEES AS CONTENT. Without it a reply cut at + * max_tokens inside its reasoning reads as a model that answered nothing; with it the client + * can tell the budget went to reasoning. */ + if (u.reasoning >= 0) { + json c; + c["reasoning_tokens"] = u.reasoning; + o["completion_tokens_details"] = c; + } + return o; +} + +json timings_json(const TimingsOut& t) { + auto per = [](int64_t n, double ms) -> json { + return n > 0 && ms > 0.0 ? json(ms / (double)n) : json(nullptr); + }; + auto rate = [](int64_t n, double ms) -> json { + return n > 0 && ms > 0.0 ? json((double)n * 1000.0 / ms) : json(nullptr); + }; + const json pms = t.prompt_ms >= 0.0 ? json(t.prompt_ms) : json(nullptr); + json o; + o["cache_n"] = t.cache_n; + o["prompt_n"] = t.prompt_n; + o["prompt_ms"] = pms; + o["prompt_per_token_ms"] = per(t.prompt_n, t.prompt_ms); + o["prompt_per_second"] = rate(t.prompt_n, t.prompt_ms); + o["predicted_n"] = t.predicted_n; + o["predicted_ms"] = t.predicted_ms; + o["predicted_per_token_ms"] = per(t.decode_n, t.predicted_ms); + o["predicted_per_second"] = rate(t.decode_n, t.predicted_ms); + if (t.draft_n > 0) { + o["draft_n"] = t.draft_n; + o["draft_n_accepted"] = t.draft_n_accepted; + } return o; } @@ -1650,7 +1753,8 @@ static json usage_json(const UsageOut& u) { * * One contract for both, OpenAI's: an empty choices array, sent after the last content chunk * and before [DONE]. Only the `object` differs, because it is a different endpoint's stream. */ -static std::string usage_chunk(const OaiRequest& r, const UsageOut& u, const char* object) { +static std::string usage_chunk(const OaiRequest& r, const UsageOut& u, const TimingsOut& t, + const char* object) { json o; o["id"] = r.id; o["object"] = object; @@ -1658,15 +1762,16 @@ static std::string usage_chunk(const OaiRequest& r, const UsageOut& u, const cha o["model"] = r.model; o["choices"] = json::array(); o["usage"] = usage_json(u); + if (t.valid) o["timings"] = timings_json(t); return sse_event(o.dump()); } -std::string text_usage_chunk(const OaiRequest& r, const UsageOut& u) { - return usage_chunk(r, u, "text_completion"); +std::string text_usage_chunk(const OaiRequest& r, const UsageOut& u, const TimingsOut& t) { + return usage_chunk(r, u, t, "text_completion"); } -std::string chat_usage_chunk(const OaiRequest& r, const UsageOut& u) { - return usage_chunk(r, u, "chat.completion.chunk"); +std::string chat_usage_chunk(const OaiRequest& r, const UsageOut& u, const TimingsOut& t) { + return usage_chunk(r, u, t, "chat.completion.chunk"); } static json chat_logprobs_json(const std::vector& lp) { @@ -1687,7 +1792,7 @@ static json chat_logprobs_json(const std::vector& lp) { } std::string chat_completion_body(const OaiRequest& r, const std::vector& choices, - const UsageOut& u) { + const UsageOut& u, const TimingsOut& t) { json arr = json::array(); for (const auto& c : choices) { json m; @@ -1712,11 +1817,12 @@ std::string chat_completion_body(const OaiRequest& r, const std::vector& choices, - const UsageOut& u) { + const UsageOut& u, const TimingsOut& t) { json arr = json::array(); for (const auto& c : choices) { json ch; @@ -1750,6 +1856,7 @@ std::string text_completion_body(const OaiRequest& r, const std::vectoropen() : nullptr), id_(r.id), model_(r.model), created_(r.created), index_(index) {} -std::string ChatDeltaStream::chunk(json delta, const char* finish_reason) { +std::string ChatDeltaStream::chunk(json delta, const char* finish_reason, const TimingsOut* t) { json ch; ch["index"] = index_; ch["delta"] = std::move(delta); @@ -1820,6 +1927,7 @@ std::string ChatDeltaStream::chunk(json delta, const char* finish_reason) { 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()); } @@ -1924,11 +2032,11 @@ Finish ChatDeltaStream::adjusted_finish(Finish f) const { return Finish::ToolCalls; } -std::string ChatDeltaStream::final_chunk(Finish f) { +std::string ChatDeltaStream::final_chunk(Finish f, const TimingsOut& t) { /* 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))); + out += chunk(json::object(), finish_reason_oai(adjusted_finish(f)), &t); return out; } diff --git a/core/server/oai.h b/core/server/oai.h index ca054040..52a0904f 100644 --- a/core/server/oai.h +++ b/core/server/oai.h @@ -136,6 +136,13 @@ struct OaiLimits { * dial at all. Seeded only when the request says nothing, so a caller always wins. */ std::string default_reasoning_effort; + /* THE DEPLOYMENT'S DEFAULT `thinking_token_budget`, -1 for none. For the same reason the + * effort default exists: an agent framework sizes max_tokens per turn and sends no budget, and + * a reasoning block that spends the whole of max_tokens returns a turn with no answer in it. + * Applied only to a request that names no budget, and only where the reply's reasoning block + * can be counted. */ + int64_t default_thinking_budget = -1; + /* WHAT A REQUEST THAT SENDS NO SAMPLER FIELDS IS SERVED WITH, field by field. * * The struct's own defaults are an untruncated sampler -- temperature 1, top_k off, top_p 1 @@ -220,12 +227,46 @@ struct UsageOut { int64_t prompt = 0; int64_t completion = 0; int64_t cached = 0; + /* Of `completion`, the tokens inside the reply's reasoning block, its markers included: OpenAI's + * completion_tokens_details.reasoning_tokens. -1 when the block cannot be counted, and the + * breakdown is then left out. */ + int64_t reasoning = -1; }; +/* WHERE ONE REQUEST'S TIME WENT, in llama.cpp's `timings` shape, which proxies and dashboards + * built against llama-server already read (llama-swap's activity view is one). /metrics holds the + * same quantities summed over every request, and two overlapping requests cannot be told apart + * there; this is the per-request half. + * + * prompt_n prompt tokens computed, the prefix cache's excluded; cache_n is those + * prompt_ms from the first step the scheduler gave the request to its first token -- the + * prefill, without the time it waited for admission + * predicted_n tokens generated: usage.completion_tokens + * predicted_ms from the first token to the last + * draft_n, draft_n_accepted + * speculative tokens proposed for this request and accepted; present when any + * were proposed, as llama.cpp does + * + * The rates divide the tokens by the time that produced them: prompt_n by prompt_ms, and the + * predicted_n - 1 tokens after the first by predicted_ms, since the first token is the prompt + * phase's product -- the same figure as /metrics' time per output token. A rate whose count or + * time is zero is null. Over several choices the counts are summed and each time runs from the + * earliest choice's start to the latest choice's end. */ +struct TimingsOut { + bool valid = false; /* some choice produced a token; nothing is reported otherwise */ + int64_t prompt_n = 0, cache_n = 0; + double prompt_ms = -1.0; /* < 0: the engine did not report the admission */ + int64_t predicted_n = 0; + int64_t decode_n = 0; /* of predicted_n, the tokens after each choice's first */ + double predicted_ms = 0.0; + int64_t draft_n = 0, draft_n_accepted = 0; +}; + +/* `timings` is added at the top level when it is valid. */ std::string chat_completion_body(const OaiRequest& r, const std::vector& choices, - const UsageOut& u); + const UsageOut& u, const TimingsOut& t = TimingsOut()); std::string text_completion_body(const OaiRequest& r, const std::vector& choices, - const UsageOut& u); + const UsageOut& u, const TimingsOut& t = TimingsOut()); std::string embeddings_body(const OaiRequest& r, const std::vector>& vecs, const UsageOut& u); std::string models_body(const std::string& model_id, int64_t created); @@ -234,8 +275,12 @@ std::string models_body(const std::string& model_id, int64_t created); * only payload is `usage`. Emitted when the request asked for stream_options.include_usage, ONCE * per stream and after every choice's final chunk -- `n` choices share one prompt and one total, * so a chunk per choice would count the prompt n times and interleave with the choices. */ -std::string text_usage_chunk(const OaiRequest& r, const UsageOut& u); -std::string chat_usage_chunk(const OaiRequest& r, const UsageOut& u); +std::string text_usage_chunk(const OaiRequest& r, const UsageOut& u, + const TimingsOut& t = TimingsOut()); +std::string chat_usage_chunk(const OaiRequest& r, const UsageOut& u, + const TimingsOut& t = TimingsOut()); +/* The `timings` object, for a stream's final chunks. */ +json timings_json(const TimingsOut& t); /* ================================================================== streaming * @@ -256,9 +301,10 @@ public: * `is_final` says the generation is over, which resolves whatever the reader was holding. */ std::string push(std::string_view appended, bool is_final); - /* The terminating chunk carrying finish_reason. The usage chunk is the stream's, not the - * choice's: chat_usage_chunk. */ - std::string final_chunk(Finish f); + /* 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 the whole generation parsed to -- the non-streaming shape. Complete once push has * been called with is_final. */ @@ -266,7 +312,7 @@ public: Finish adjusted_finish(Finish f) const; private: - std::string chunk(json delta, const char* finish_reason); + std::string chunk(json delta, const char* finish_reason, const TimingsOut* t = nullptr); std::string emit(const std::vector& ev); std::unique_ptr reader_; diff --git a/core/server/server.cpp b/core/server/server.cpp index da3c7685..5e542166 100644 --- a/core/server/server.cpp +++ b/core/server/server.cpp @@ -22,6 +22,9 @@ struct Server::Generation { int prompt_index = 0; std::string text; std::vector logprobs; + /* The reply against its reasoning block, every token the sink delivers: what + * completion_tokens_details.reasoning_tokens reports. */ + ReasoningCount think; Finish finish = Finish::None; bool closed = false; /* the server has decided this choice is over */ size_t scanned = 0; /* how far the stop-string scan has reached */ @@ -56,6 +59,7 @@ Server::Server(const Deps& d, const ServerOptions& o) lim_.allow_audio = opt_.allow_audio; lim_.supports_logprobs = opt_.supports_logprobs; lim_.default_reasoning_effort = opt_.default_reasoning_effort; + lim_.default_thinking_budget = opt_.default_thinking_budget; lim_.default_sampling = opt_.default_sampling; lim_.default_dry_breakers_set = opt_.default_dry_breakers_set; lim_.default_template_kwargs = opt_.default_template_kwargs; @@ -193,6 +197,16 @@ void Server::check_template_defaults(std::string* kwargs_why, std::string* effor if (!l.default_reasoning_effort.empty()) render(l, effort_why); } +std::string Server::check_thinking_budget() const { + if (!deps_.chat || lim_.default_thinking_budget < 0) return std::string(); + const std::string body = R"({"messages":[{"role":"user","content":"Hello"}],"max_tokens":1,)" + R"("thinking_token_budget":)" + + std::to_string(lim_.default_thinking_budget) + "}"; + OaiRequest r; + ApiError e; + return parse_chat_request(body, odeps_, lim_, &r, &e) < 0 ? e.message : std::string(); +} + void Server::stop() { stopping_.store(true); transport_.stop(); @@ -273,6 +287,7 @@ int Server::submit_all(const OaiRequest& r, std::vector* gens, ApiEr g.prompt_index = (int)p; g.sink = std::make_shared(); g.sink->set_has_logprobs(opt_.supports_logprobs); + g.think.start(r.sp.reasoning); g.detok = deps_.tok->detokenizer(r.stop, r.preserved_tokens); if (!g.detok) { *err = err_not_implemented("the tokenizer did not supply an incremental decoder"); @@ -353,6 +368,7 @@ bool Server::pump(std::vector& gens, const OaiRequest& r) { while ((n = g.sink->read(buf, 128)) > 0) { progress = true; for (size_t i = 0; i < n; ++i) { + g.think.push(r.sp.reasoning, buf[i].token); std::string piece = g.detok->push(buf[i].token); if (!piece.empty()) g.text += piece; if (r.want_logprobs) @@ -410,6 +426,63 @@ bool Server::pump(std::vector& gens, const OaiRequest& r) { return progress; } +/* ------------------------------------------------------------------ usage */ + +/* THE REQUEST'S TOKENS, ONCE FOR BOTH PATHS. `n` choices share a prompt, so the prompt and its + * cached part are counted once per prompt. Reasoning is reported only where the reply's block can + * be counted by token (ReasoningSpan); a model without one reports no breakdown rather than a + * zero that would claim there was no reasoning. */ +UsageOut Server::usage_of(const OaiRequest& r, const std::vector& gens) { + UsageOut u; + for (const auto& p : r.prompts) u.prompt += (int64_t)p.tokens.size(); + if (r.sp.reasoning.known()) u.reasoning = 0; + for (const auto& g : gens) { + u.completion += g.sink->n_produced(); + if (g.prompt_index * r.n == g.index) u.cached += g.sink->n_cached(); + if (u.reasoning >= 0) u.reasoning += g.think.tokens; + } + return u; +} + +/* WHERE THE REQUEST'S TIME WENT, from its sinks: one for a choice's final chunk, all of them for + * the request. Every time is moved onto one clock first -- each sink counts from its own + * construction. See TimingsOut for what each field means. */ +TimingsOut Server::timings_of(const Sink* const* sinks, size_t n) { + TimingsOut t; + int64_t admit = INT64_MAX, first_lo = INT64_MAX, first_hi = INT64_MIN, last = INT64_MIN; + bool admitted = true; + for (size_t i = 0; i < n; ++i) { + const Sink& s = *sinks[i]; + const int64_t produced = s.n_produced(); + t.predicted_n += produced; + t.draft_n += s.n_drafted(); + t.draft_n_accepted += s.n_draft_accepted(); + const int64_t tf = s.t_first_token_ns(); + if (tf < 0) continue; + t.valid = true; + t.cache_n += s.n_cached(); + t.prompt_n += s.n_prompt() - s.n_cached(); + if (produced > 1) t.decode_n += produced - 1; + const int64_t t0 = s.t_start_ns(), ta = s.t_admitted_ns(); + if (ta < 0) admitted = false; + else admit = std::min(admit, t0 + ta); + first_lo = std::min(first_lo, t0 + tf); + first_hi = std::max(first_hi, t0 + tf); + last = std::max(last, t0 + s.t_last_token_ns()); + } + if (!t.valid) return t; + if (admitted) t.prompt_ms = (double)(first_hi - admit) * 1e-6; + t.predicted_ms = (double)(last - first_lo) * 1e-6; + return t; +} + +TimingsOut Server::timings_of(const std::vector& gens) { + std::vector v; + v.reserve(gens.size()); + for (const auto& g : gens) v.push_back(g.sink.get()); + return timings_of(v.data(), v.size()); +} + /* ------------------------------------------------------------------ metrics bookkeeping */ /* WHAT FAILED, for the client: the sentence the failing component gave, and the status. A failed @@ -494,14 +567,11 @@ HttpResponse Server::blocking_completion(const HttpRequest& req, OaiRequest& r) } Finish overall = Finish::Stop; - UsageOut usage; - for (const auto& p : r.prompts) usage.prompt += (int64_t)p.tokens.size(); + const UsageOut usage = usage_of(r, gens); std::vector choices; choices.reserve(gens.size()); for (auto& g : gens) { - usage.completion += g.sink->n_produced(); - if (g.prompt_index * r.n == g.index) usage.cached += g.sink->n_cached(); ChoiceOut c; c.index = g.index; @@ -562,9 +632,10 @@ HttpResponse Server::blocking_completion(const HttpRequest& req, OaiRequest& r) retire(gens); release(r.n_choices()); + const TimingsOut timings = timings_of(gens); std::string body = r.endpoint == Endpoint::Chat - ? chat_completion_body(r, choices, usage) - : text_completion_body(r, choices, usage); + ? 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)); } @@ -572,7 +643,7 @@ HttpResponse Server::blocking_completion(const HttpRequest& req, OaiRequest& r) /* ------------------------------------------------------------------ streaming */ static std::string text_chunk(const OaiRequest& r, int index, const std::string& delta, - const char* finish_reason) { + const char* finish_reason, const TimingsOut* t = nullptr) { nlohmann::ordered_json ch; ch["text"] = delta; ch["index"] = index; @@ -584,6 +655,7 @@ static std::string text_chunk(const OaiRequest& r, int index, const std::string& o["created"] = r.created; o["model"] = r.model; o["choices"] = nlohmann::ordered_json::array({ch}); + if (t && t->valid) o["timings"] = timings_json(*t); return sse_event(o.dump()); } @@ -675,21 +747,20 @@ HttpResponse Server::streaming_completion(const HttpRequest& req, OaiRequest& r) } if (self->all_done(st->gens)) { - UsageOut u; - for (const auto& p : st->r.prompts) u.prompt += (int64_t)p.tokens.size(); - for (auto& g : st->gens) { - u.completion += g.sink->n_produced(); - if (g.prompt_index * st->r.n == g.index) u.cached += g.sink->n_cached(); - } + const UsageOut u = usage_of(st->r, st->gens); Finish overall = Finish::Stop; for (auto& g : st->gens) { + /* EACH CHOICE'S OWN TIMINGS ON ITS FINAL CHUNK, so a client that asked for no + * usage chunk still has them, as llama.cpp sends them. */ + const Sink* one = g.sink.get(); + const TimingsOut gt = timings_of(&one, 1); if (st->r.endpoint == Endpoint::Chat) { - out += g.delta->final_chunk(g.finish); + 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)); + 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 @@ -711,9 +782,11 @@ HttpResponse Server::streaming_completion(const HttpRequest& req, OaiRequest& r) * it, and once for the request rather than once per choice: `n` completions share one * prompt and one total, so emitting it per generation would count the prompt n times * and interleave usage between the choices' final chunks. */ - if (st->r.include_usage) - out += st->r.endpoint == Endpoint::Chat ? chat_usage_chunk(st->r, u) - : text_usage_chunk(st->r, u); + if (st->r.include_usage) { + const TimingsOut t = timings_of(st->gens); + out += st->r.endpoint == Endpoint::Chat ? chat_usage_chunk(st->r, u, t) + : text_usage_chunk(st->r, u, t); + } out += SSE_DONE; st->done_sent = true; diff --git a/core/server/server.h b/core/server/server.h index 8a357a6d..a5789152 100644 --- a/core/server/server.h +++ b/core/server/server.h @@ -76,6 +76,9 @@ struct ServerOptions { /* The deployment default for `reasoning_effort`, empty for the template's own. See * OaiLimits::default_reasoning_effort for why a server-side default is needed at all. */ std::string default_reasoning_effort; + /* The deployment default for `thinking_token_budget`, -1 for none. See + * OaiLimits::default_thinking_budget. */ + int64_t default_thinking_budget = -1; /* What a request that sends no sampler fields is served with. See * OaiLimits::default_sampling; only the sampler knobs are read from it. */ SamplingParams default_sampling; @@ -141,6 +144,10 @@ public: * A render that fails at the first step says nothing about the defaults and is not reported. * `kwargs_why` / `effort_why` are left empty, or hold the template's refusal at that step. */ void check_template_defaults(std::string* kwargs_why, std::string* effort_why) const; + /* THE DEPLOYMENT'S thinking_token_budget, asked for by a one-message chat the way a request + * would ask for it. Empty when this model's reasoning block can hold one; otherwise the 400 a + * request naming the budget would get, which says why. */ + std::string check_thinking_budget() const; void stop(); int port() const { return transport_.port(); } /* 0 until run() is accepting */ @@ -150,6 +157,10 @@ private: struct Generation; struct StreamState; + static UsageOut usage_of(const OaiRequest& r, const std::vector& gens); + static TimingsOut timings_of(const Sink* const* sinks, size_t n); + static TimingsOut timings_of(const std::vector& gens); + void register_routes(); HttpResponse handle_chat(const HttpRequest& req); diff --git a/core/server/sink.cpp b/core/server/sink.cpp index 54017be0..ae76ed18 100644 --- a/core/server/sink.cpp +++ b/core/server/sink.cpp @@ -100,6 +100,18 @@ void Sink::set_prompt_stats(int32_t n_prompt, int32_t n_cached) { n_cached_.store(n_cached, std::memory_order_release); } +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); +} + +/* One producer, so a load and a store is the whole of the update. */ +void Sink::add_drafts(int32_t n, int32_t accepted) { + n_draft_.store(n_draft_.load(std::memory_order_relaxed) + n, std::memory_order_release); + n_draft_acc_.store(n_draft_acc_.load(std::memory_order_relaxed) + accepted, + std::memory_order_release); +} + size_t Sink::read(SinkToken* out, size_t max) { const uint64_t t = tail_.load(std::memory_order_relaxed); const uint64_t h = head_.load(std::memory_order_acquire); diff --git a/core/server/sink.h b/core/server/sink.h index 7e5a704c..a702d0c4 100644 --- a/core/server/sink.h +++ b/core/server/sink.h @@ -90,6 +90,14 @@ public: /* Admission accounting, set once by the scheduler when the prompt is placed. */ void set_prompt_stats(int32_t n_prompt, int32_t n_cached); + /* THE FIRST TIME THE SCHEDULER GIVES THIS REQUEST A STEP: where its prompt phase starts, so + * the time it waited in the queue is not counted as prefill. A preempted request admitted + * again keeps the first mark. */ + void mark_admitted(); + /* A verify step's speculation for this request: `n` tokens proposed, `accepted` of them + * taken. Summed over the request, the per-request half of /metrics' draft counters. */ + void add_drafts(int32_t n, int32_t accepted); + /* ------------------------------------------------------------------ consumer: HTTP */ /* Copies up to `max` tokens out. Returns how many. Never blocks. */ @@ -112,7 +120,14 @@ public: /* Timings, in steady-clock nanoseconds since the sink was constructed. -1 until observed. */ int64_t t_first_token_ns() const { return t_first_.load(std::memory_order_acquire); } int64_t t_last_token_ns() const { return t_last_.load(std::memory_order_acquire); } + int64_t t_admitted_ns() const { return t_admit_.load(std::memory_order_acquire); } int64_t age_ns() const; + /* The steady clock at construction, which the times above count from: what puts two sinks' + * times on one axis. */ + int64_t t_start_ns() const { return t_start_ns_; } + + int64_t n_drafted() const { return n_draft_.load(std::memory_order_acquire); } + int64_t n_draft_accepted() const { return n_draft_acc_.load(std::memory_order_acquire); } int64_t n_produced() const { return (int64_t)head_.load(std::memory_order_acquire); } int32_t n_prompt() const { return n_prompt_.load(std::memory_order_acquire); } @@ -145,6 +160,9 @@ private: std::atomic t_first_{-1}; std::atomic t_last_{-1}; + std::atomic t_admit_{-1}; + std::atomic n_draft_{0}; + std::atomic n_draft_acc_{0}; int64_t t_start_ns_ = 0; std::atomic n_prompt_{0}; @@ -172,6 +190,12 @@ inline bool sink_cancelled(const void* s) { inline void sink_prompt_stats(void* s, int32_t n_prompt, int32_t n_cached) { if (s) static_cast(s)->set_prompt_stats(n_prompt, n_cached); } +inline void sink_admitted(void* s) { + if (s) static_cast(s)->mark_admitted(); +} +inline void sink_drafts(void* s, int32_t n, int32_t accepted) { + if (s) static_cast(s)->add_drafts(n, accepted); +} } /* namespace server */ } /* namespace rad */ diff --git a/core/text/chatparse.cpp b/core/text/chatparse.cpp index 68cf5afc..e2b2c9b9 100644 --- a/core/text/chatparse.cpp +++ b/core/text/chatparse.cpp @@ -704,6 +704,21 @@ size_t ReplyParser::hold_bound() const { 3 * 3; } +ReasoningMarkers ReplyParser::reasoning() const { + const ReplyFormat::Impl& F = impl_->fmt->impl(); + ReasoningMarkers m; + if (!F.f.has_reasoning()) return m; + m.open = F.open_core; + m.close = F.close_core; + /* `tail` starts at the opener when the prompt holds one, and a prompt that also closed the + * block -- thinking turned off -- leaves the reply after it. With no opener at all the stream + * starts in the block (after_lead). */ + const std::string& t = impl_->tail; + m.starts_open = F.open_core.empty() || + (!t.empty() && t.find(F.close_core, F.open_core.size()) == std::string::npos); + return m; +} + /* Read the tools the way the grammar generator reads them, so a name or a type means the same * thing to the parser as to the grammar that constrained the reply. */ static int bind_tools(const ReplyFormat::Impl& F, const ojson& tools, ReplyParser::Impl* P, diff --git a/core/text/chatparse.h b/core/text/chatparse.h index 6ae4496d..849706a5 100644 --- a/core/text/chatparse.h +++ b/core/text/chatparse.h @@ -118,6 +118,14 @@ struct ReplyOptions { class ReplyStream; +/* The reasoning block as one request's reply meets it: its markers with the optional whitespace + * around them trimmed, and whether the reply starts inside it -- the generation prompt opened it, + * or the format has no opener. Empty `close` is a format with no reasoning block. */ +struct ReasoningMarkers { + std::string open, close; + bool starts_open = false; +}; + /* A format compiled once: its automata and its delimiters. Shared by every request. */ class ReplyFormat { public: @@ -150,6 +158,9 @@ public: * prefix in each place one can be pending at once, a value's undecided head, and an * unfinished UTF-8 sequence on each output. A constant of the format, not of the reply. */ size_t hold_bound() const; + /* Read from the generation prompt exactly as a stream's first bytes are, so a reply this + * says starts in the block is one the stream reads as reasoning from its first byte. */ + ReasoningMarkers reasoning() const; struct Impl; const Impl& impl() const { return *impl_; } diff --git a/docs/GUIDE.md b/docs/GUIDE.md index 0f387632..cacd3116 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -679,6 +679,14 @@ write, with the MoE gather in front of it, on either wire: the rotated forms of worth +5.6–6.3% of prefill at a 2048-token chunk (20K prompt 5556 → 5908 tok/s; a 23K extension at 81K depth 4998 → 5278) and −1.3% of the eight-stream decode step; one-stream decode stays exact. +**The cards must reach each other's memory directly** (peer to peer, P2P). The all-reduce +kernels push into the other card's memory. At launch radiance asks the driver, for every pair of +the cards it will use, whether that works, and logs the answer. When some pair cannot, those +kernels are not selected, and startup stops naming `device.p2p` instead of the first all-reduce +faulting or hanging. Whether P2P works is decided by the platform: the IOMMU setting, the PCIe +topology, and whether the cards sit behind a switch that allows peer traffic. The startup line +names the pairs that failed. + ### 4.8 Finished conversations: copied to host, VRAM given up on demand By default a finished conversation's KV blocks stay in VRAM, held by the prefix cache, until the @@ -792,6 +800,13 @@ refuses is a warning at startup: requests that send their own effort still work. radiance --model m.rad --reasoning-effort medium ``` +**`--thinking-token-budget N`** caps the reasoning instead of its depth. At N tokens inside the +reasoning block the block is closed, by masking the next position to its end token +(``), and the answer follows. This makes a client's `max_tokens` buy an answer, where +otherwise the reasoning could use all of it. It is the default for chat requests that send no +`thinking_token_budget` of their own (§5.2). It needs a reasoning block that ends in a single +token, as Qwen's and MiniCPM's do. On a model whose block does not, startup stops and says why. + **`--reasoning-format none`** leaves a reasoning block inline in `content` instead of returning it as `reasoning_content`, for a client that reads it there. @@ -902,6 +917,7 @@ that names the field wins. | `--max-stop-strings N`, `--max-stop-bytes N` | 64, 4096 | how many stop strings a request may send, and how long each may be | | `--chat-template-kwargs JSON` | — | variables for the chat template on every chat request; a JSON object or `@FILE`, repeatable | | `--reasoning-effort S` | template's own | default `reasoning_effort` for chat | +| `--thinking-token-budget N` | none | default `thinking_token_budget` for chat: the reasoning block is closed at N tokens | | `--reasoning-format MODE` | auto | `auto` returns reasoning as `reasoning_content`; `none` leaves it inline in `content` | **Media** — each replaces what the container's preprocessor configuration states. They do nothing @@ -995,6 +1011,27 @@ so — use `/v1/completions` instead. Reasoning text comes back in `choices[].message.reasoning_content`, separate from `content`. +**Reasoning counts against `max_tokens`**, as in OpenAI's API, vLLM and llama.cpp: every +generated token does. A reply that runs out inside its reasoning comes back with empty +`content` and `finish_reason: "length"`. `usage.completion_tokens_details.reasoning_tokens` says +how many of `completion_tokens` were reasoning, the block's end token included, so a client can +tell that case from a model that answered nothing. + +**Capping the reasoning.** `thinking_token_budget` (vLLM's name; `thinking_budget`, Qwen's, is +read as the same field) is how many tokens the reasoning may run to. At that count the block is +closed and the model answers from what it has reasoned so far: + +```json +{"max_tokens": 4096, "thinking_token_budget": 2048} +``` + +The count starts after the opening ``. A reasoning block that ends sooner is not +affected. The close is forced by the sampler, so it holds under speculative decoding and at any +temperature. A `grammar` or `response_format` that does not allow the close at some position +keeps that position, and the close comes at the next position that allows it. The budget and +`reasoning_tokens` need the block's end to be one token. A model whose end is not one token +reports no `completion_tokens_details` and refuses a budget with a 400 that says why. + ### 5.3 Streaming ```sh @@ -1125,6 +1162,7 @@ curl -s http://localhost:8000/detokenize -H 'Content-Type: application/json' \ | `tools`, `tool_choice`, `parallel_tool_calls` | chat only | | `add_generation_prompt`, `chat_template_kwargs` | chat only | | `reasoning_effort`, `enable_thinking` | chat only | +| `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 | | `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` | | `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 | @@ -1199,6 +1237,42 @@ precisely without running the model. --- +### 5.9 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 +view, for one) reads it unchanged: + +```json +"timings": { + "cache_n": 1024, "prompt_n": 71, "prompt_ms": 284.0, + "prompt_per_token_ms": 4.0, "prompt_per_second": 250.0, + "predicted_n": 64, "predicted_ms": 711.0, + "predicted_per_token_ms": 11.29, "predicted_per_second": 88.6, + "draft_n": 78, "draft_n_accepted": 37 +} +``` + +| field | meaning | +|---|---| +| `prompt_n` | prompt tokens this request computed. Tokens the prefix cache supplied are not in it | +| `cache_n` | prompt tokens the prefix cache supplied. `prompt_n + cache_n` is the prompt | +| `prompt_ms` | from the first step the scheduler gave the request to its first token: the prefill. The time it waited for admission is not in it | +| `prompt_per_second`, `prompt_per_token_ms` | `prompt_n` over `prompt_ms`. A prompt the cache mostly supplied computes few tokens, so this is the speed of the prefill that actually ran, not the prompt length over the time to first token | +| `predicted_n` | tokens generated, the same as `usage.completion_tokens` | +| `predicted_ms` | from the first generated token to the last | +| `predicted_per_second`, `predicted_per_token_ms` | the `predicted_n − 1` tokens after the first, over `predicted_ms`. The first token is the prefill's product. It is the same figure as `/metrics`' time per output token, and with speculative decoding it counts every token a step accepts | +| `draft_n`, `draft_n_accepted` | speculative tokens proposed for this request and how many were accepted. Present when any were proposed, as llama.cpp does | + +Milliseconds are wall-clock milliseconds, and the rates are tokens per second. A rate whose count +or time is zero is `null`. A request with several choices (`n`, or a batch of prompts) sums the +counts, and each time runs from the earliest choice's start to the latest choice's end. + +When streaming, each choice's final chunk (the one with `finish_reason`) carries its own +`timings`, whether or not the request asked for `stream_options.include_usage`. The usage chunk, +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. + ## 6. Operate it ### 6.1 The dashboard @@ -1356,10 +1430,11 @@ released until it does. | The server dies with no log line, on a request it had been serving fine | A kernel whose code object had never been loaded could not be: the card has no room left. HIP faults inside the launch rather than returning an error, so there is nothing to print | A card that never met `--gpu-headroom-mib` — see §4.3. Raise the headroom past the shortfall startup names. `coredumpctl info` names the kernel; `AMD_LOG_LEVEL=1` prints `HSA_STATUS_ERROR_OUT_OF_RESOURCES` just above the fault | | KV in VRAM stays high with one session and nothing moves | The idle tiers are **off** — they are sized, and with no size nothing is copied | Pass `--prefix-cache-host-mib N` | | `out of memory` / `the carve reserved N of address space and the card would not back it` | Something else is holding VRAM | Check with `rocm-smi`; stop the other process. The budget is stated before allocation, so the log says what it asked for | +| `pool allocation refused` with `backing allocation of … refused` on the second card, after the first card's pools succeeded | The VRAM budget is measured before any rank allocates. A card that refuses its weights pool lost that memory to another process in between (the line below the refusal says how much is free now). A refused `host_pool` is pinned memory: **every rank pins its own `--host-pool-mib`**, so `--tp 2` pins it twice, and the amdgpu driver caps pinned memory system-wide at `ttm.pages_limit`, half of RAM by default | Stop the other process (`rocm-smi --showpids`). For the host pool, keep `--tp` × `--host-pool-mib` under the cap the refusal names, or raise it with the kernel parameter `ttm.pages_limit` | | `--draft-model is not implemented` | This engine loads its drafter from the container | `rad-convert --draft-model DIR` at conversion time | | `context_length_exceeded` on a request | The **prompt alone** does not fit the context. `max_tokens` is clamped rather than refused, so this fires only when there is no room left to generate at all | Shorten the prompt by the number of tokens the message names, or raise `--max-model-len` if the model allows it | | `unknown option '--foo'` and the engine exits | Deliberate. A typo in a budget flag is the difference between the plan you asked for and one the planner invented | Check `radiance --help` | -| Empty `content` and `finish_reason: "length"` on short chat turns | The template's default `reasoning_effort` spent the budget inside `` | `--reasoning-effort medium`, or `"reasoning_effort": "none"` per request | +| Empty `content` and `finish_reason: "length"` on short chat turns | The reasoning spent all of `max_tokens` inside ``; `usage.completion_tokens_details.reasoning_tokens` equals `completion_tokens`. Qwen3.8's default `reasoning_effort` is `xhigh` | `--reasoning-effort medium`, or `"reasoning_effort": "none"` per request; or cap the reasoning with `thinking_token_budget` / `--thinking-token-budget` below `max_tokens` | | `401` with `invalid api key` | The server was started with `--api-key` | Send `Authorization: Bearer KEY` (§6.6) | First three things to run when a server will not start: diff --git a/docs/PLUGIN.md b/docs/PLUGIN.md index 723ca8fc..f949cc03 100644 --- a/docs/PLUGIN.md +++ b/docs/PLUGIN.md @@ -97,6 +97,16 @@ Two consequences worth internalising: - **A band you claim and cannot serve is invisible to a single-sequence bench.** It only shows at concurrency, where M is larger. Run the whole ladder, not just C=1. +**A constraint can be on the machine instead of the geometry.** A key that starts with `device.` +is matched against what the engine measured about the ranks' cards at launch, not against the +op's parameters. `RAD_CEQ(RAD_FACT_P2P, 1)` (`device.p2p`) is how a kernel says it reads or writes +another card's memory. On a machine where some pair of the ranks' cards cannot reach each other, +such a kernel is not selected. The next row that does not need it takes the op. With no such row, +startup stops and the selection table names the fact (`device.p2p == 1, have 0 -- this machine, +measured at launch`). Every collective in libr4d carries it. A machine fact is in no geometry, so +it changes no tuning key. A tool that selects without an engine has measured nothing, and such a +kernel is not selected there either. + `priority` breaks ties **within your plugin**, highest first, a tie going to declaration order. Between plugins there is no contest: **the hierarchy is absolute.** The first plugin in `--kernels` order with any matching kernel supplies it, and a later plugin never outbids it however diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index 030a9016..4ceb31ea 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -62,6 +62,11 @@ #define C_DIV(k, v) { (k), RAD_C_DIV, (long long)(v), nullptr } #define C_IN(k, s) { (k), RAD_C_IN, 0, (s) } +/* EVERY KERNEL THAT TOUCHES A PEER'S MEMORY: the collectives push into the other ranks' scratch and + * raise their flags directly, so a machine whose cards cannot reach each other must not select + * them. The engine measures this at launch (rad_types.h, device.p2p). */ +#define C_P2P C_EQ(RAD_FACT_P2P, 1) + /* libr4d's R4D_AR_TWOSHOT_WIDE_MAX_ELEMS, restated because this file must not include r4d.h. * r4d_ar_entry.hip static_asserts the two against each other. */ #define R4D_AR_TWOSHOT_WIDE_MAX_ELEMS 20971520 @@ -2297,32 +2302,40 @@ static const RadConstraint cGdnGatedRmsNorm[] = { * accepts either, so a constraint that took only one would refuse the sampler by a synonym. */ static const RadConstraint cArGather2[] = { C_EQ("world_size", 2), C_IN("dtype", "bf16 fp16 f16 fp32 f32"), + C_P2P, }; static const RadConstraint cArExact[] = { C_EQ("world_size", 2), C_EQ("exact", 1), C_IN("dtype", "bf16 fp16 fp32"), + C_P2P, }; static const RadConstraint cArExact4[] = { C_EQ("world_size", 4), C_EQ("exact", 1), C_IN("dtype", "bf16 fp16 fp32"), + C_P2P, }; static const RadConstraint cArExact8[] = { C_EQ("world_size", 8), C_EQ("exact", 1), C_IN("dtype", "bf16 fp16 fp32"), + C_P2P, }; static const RadConstraint cArTsExact4[] = { C_EQ("world_size", 4), C_EQ("exact", 1), C_EQ("hops", 2), C_IN("dtype", "bf16 fp16 fp32"), C_DIV("numel", 64), C_LE("numel", R4D_AR_TWOSHOT_WIDE_MAX_ELEMS), + C_P2P, }; static const RadConstraint cArTsExact8[] = { C_EQ("world_size", 8), C_EQ("exact", 1), C_EQ("hops", 2), C_IN("dtype", "bf16 fp16 fp32"), C_DIV("numel", 64), C_LE("numel", R4D_AR_TWOSHOT_WIDE_MAX_ELEMS), + C_P2P, }; static const RadConstraint cArWht6[] = { C_EQ("world_size", 2), C_EQ("exact", 0), C_IN("dtype", "bf16 fp16"), C_DIV("numel", 64), + C_P2P, }; static const RadConstraint cArTi8Ts4[] = { C_EQ("world_size", 4), C_EQ("exact", 0), C_IN("dtype", "bf16 fp16"), C_DIV("numel", 128), + C_P2P, }; /* ---- GEMM ------------------------------------------------------------------------------------ @@ -2595,17 +2608,20 @@ static const RadConstraint cRmsNormQuantFp8[] = { static const RadConstraint cArRmsNormQuantFp8[] = { C_DIV("n", 8), C_EQ("group", R4D_FP8_BLOCK), C_IN("dtype", "bf16"), C_EQ("world_size", 2), + C_P2P, }; /* hc_write's own bounds plus the all-reduce's: `n DIV 8` because `y` is pushed as 16B words, and * world_size 2 because the handshake is one peer flag per block. */ static const RadConstraint cArHcWrite[] = { C_GE("M", 1), C_DIV("n", 8), C_GE("hc", 2), C_LE("hc", 8), C_IN("dtype", "bf16"), C_EQ("world_size", 2), + C_P2P, }; /* ar_hc_write's bounds and the gather's: top_k up to the 64 slots a row's table holds in LDS. */ static const RadConstraint cArGatherHcWrite[] = { C_GE("M", 1), C_DIV("n", 8), C_GE("hc", 2), C_LE("hc", 8), C_IN("dtype", "bf16"), C_EQ("world_size", 2), C_GE("top_k", 1), C_LE("top_k", 64), + C_P2P, }; static const RadConstraint cGatedQuantFp8[] = { C_DIV("n", 4), C_EQ("group", R4D_FP8_BLOCK), C_IN("dtype", "bf16"), @@ -2658,6 +2674,7 @@ static const RadConstraint cRmsNormHadQuantI8[] = { static const RadConstraint cArLnHadQuantI8[] = { C_DIV("n", 16), C_DIV("n", 128), C_LE("n", 16256), C_LE("group", 512), C_IN("dtype", "bf16"), C_EQ("world_size", 2), + C_P2P, }; static const RadConstraint cQkNormRopeGate[] = { C_IN("q_dtype", "bf16"), C_LE("head_dim", 256), C_DIV("head_dim", 32), diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index 72852726..2f2c9e5c 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -337,8 +337,11 @@ static void cross_check(const Plugin& pl) { continue; } /* THE CHECK THAT EARNS ITS KEEP. A constraint on a key the op does not declare can never - * be satisfied, so the row is unreachable and nothing says so. */ + * be satisfied, so the row is unreachable and nothing says so. A "device." key is not a + * parameter at all: it is matched against the machine (rad_types.h). */ + static const size_t kFact = std::strlen(RAD_DEVICE_FACT_PREFIX); for (int c = 0; c < r->n_constraints; ++c) { + if (!std::strncmp(r->constraints[c].key, RAD_DEVICE_FACT_PREFIX, kFact)) continue; bool found = false; for (int j = 0; j < sc->n_params; ++j) if (!std::strcmp(sc->params[j].key, r->constraints[c].key)) { found = true; break; } diff --git a/tests/chatparse_test.cpp b/tests/chatparse_test.cpp index b86f0fae..bec9562c 100644 --- a/tests/chatparse_test.cpp +++ b/tests/chatparse_test.cpp @@ -849,6 +849,42 @@ static RadChatFormat qwen_abi() { return c; } +/* WHERE THE REPLY STARTS AGAINST ITS REASONING BLOCK, read from the generation prompt as the stream + * reads it: opened by the prompt, opened and closed again (thinking off), or not opened at all -- + * and the markers trimmed of the whitespace that is optional to match. The engine counts and closes + * the block by these, so a reply this calls open has to be one the stream reads as reasoning. */ +TEST(the_parser_says_whether_a_reply_starts_inside_its_reasoning_block) { + RadChatFormat c = qwen_abi(); + ChatFormat f; + std::string why; + CHECK_OK(chat_format_from_abi(&c, &f, &why)); + std::shared_ptr rf; + CHECK_OK(ReplyFormat::compile(f, &rf, &why)); + struct Case { const char* prompt; bool open; }; + for (const Case& k : { Case{ "<|im_start|>assistant\n\n", true }, + Case{ "<|im_start|>assistant\n\n\n\n\n", false }, + Case{ "<|im_start|>assistant\n", false } }) { + ReplyOptions ro; + ro.generation_prompt = k.prompt; + std::shared_ptr rp; + CHECK_OK(ReplyParser::create(rf, ro, &rp, &why)); + const ReasoningMarkers m = rp->reasoning(); + CHECK_EQ(m.open, std::string("")); + CHECK_EQ(m.close, std::string("")); + CHECK_EQ(m.starts_open, k.open); + const ReplyMessage r = reply_parse(*rp, "x\n\ny"); + CHECK_EQ(r.reasoning.empty(), !k.open); + } + + ChatFormat none; + CHECK_OK(chat_format_from_template("", "", "", &none, &why, &why)); + CHECK_OK(ReplyFormat::compile(none, &rf, &why)); + std::shared_ptr rp; + CHECK_OK(ReplyParser::create(rf, ReplyOptions{}, &rp, &why)); + CHECK(rp->reasoning().close.empty()); + CHECK(!rp->reasoning().starts_open); +} + /* A plugin that declares its model's format gets exactly what the template analysis derives for * the same model: the same parser behaviour and the same grammar. */ TEST(a_declared_format_reads_and_constrains_like_the_derived_one) { diff --git a/tests/config_test.cpp b/tests/config_test.cpp index 788d53cf..9ece1ca3 100644 --- a/tests/config_test.cpp +++ b/tests/config_test.cpp @@ -220,6 +220,23 @@ TEST(the_paths_and_names_reach_their_fields) { CHECK_EQ(c.override_chat_template, std::string("/t.jinja")); } +/* The reasoning budget is a count or nothing: unset is -1, which no request default can mean. */ +TEST(thinking_token_budget_takes_a_count_and_defaults_to_none) { + Config c; + CHECK_EQ(parse({}, &c), RAD_OK); + CHECK_EQ(c.thinking_token_budget, (int64_t)-1); + Config d; + CHECK_EQ(parse({ "--thinking-token-budget", "2048" }, &d), RAD_OK); + CHECK_EQ(d.thinking_token_budget, (int64_t)2048); + Config e; + CHECK_EQ(parse({ "--thinking-token-budget", "0" }, &e), RAD_OK); + CHECK_EQ(e.thinking_token_budget, (int64_t)0); + Config f; + CHECK(parse({ "--thinking-token-budget", "-1" }, &f) < 0); + Config g; + CHECK(parse({ "--thinking-token-budget", "lots" }, &g) < 0); +} + TEST(the_boolean_flags_are_off_until_they_are_given) { Config d; CHECK_EQ(parse({}, &d), RAD_OK); diff --git a/tests/mem_test.cpp b/tests/mem_test.cpp index 32bd6ca4..915bd1f4 100644 --- a/tests/mem_test.cpp +++ b/tests/mem_test.cpp @@ -170,6 +170,25 @@ TEST(pool_reservation_never_falls_through) { CHECK_EQ(p.kv().used(), 512ll << 10); } +/* A BACKING ALLOCATION THE ALLOCATOR REFUSES IS REPORTED AS A REFUSAL, with the allocator's reason + * where it has one -- not as "0 B available", which reads as a measurement of the card and sends + * the reader looking for memory that was never measured. */ +TEST(a_refused_backing_allocation_says_it_was_refused_and_why) { + struct Refuses final : MemAllocator { + void* alloc(int64_t, int) override { return nullptr; } + void free(void*, int) override {} + const char* name() const override { return "refuses"; } + } none; + Config c = small_config(); + Pools p; + CHECK_EQ(p.configure(c, 0, &none, &none), RAD_E_NOMEM); + const std::string& r = p.fit_report(); + CHECK(r.find("backing allocation of") != std::string::npos); + CHECK(r.find("refused: the allocator returned nothing") != std::string::npos); + CHECK(r.find("0 B available") == std::string::npos); + CHECK(!p.configured()); +} + /* ================================================================== the derived budget */ TEST(derived_budget_takes_the_statics_off_the_top_then_divides_the_rest) { diff --git a/tests/plugin_test.cpp b/tests/plugin_test.cpp index 73b30539..cf3b8b6e 100644 --- a/tests/plugin_test.cpp +++ b/tests/plugin_test.cpp @@ -118,8 +118,8 @@ TEST(loading_reads_identity_and_calls_open) { if (!base) return; CHECK_EQ((int)base->kind, RAD_PLUGIN_KERNEL); CHECK_EQ(base->version, "0.1"); - CHECK_EQ(base->n_kernels, 13); - CHECK_EQ(base->n_schemas, 7); + CHECK_EQ(base->n_kernels, 16); + CHECK_EQ(base->n_schemas, 9); /* The optional open hook runs once, after load and before any selection. */ auto open_calls = reinterpret_cast(dlsym(base->handle, "radtest_open_calls")); @@ -285,7 +285,7 @@ TEST(every_row_s_op_has_a_schema) { CHECK_OK(load(r)); CHECK_OK(r.check_complete()); const auto ops = r.op_names(); - CHECK_EQ(ops.size(), (size_t)7); + CHECK_EQ(ops.size(), (size_t)9); CHECK_EQ(ops[0], "t_attn"); } @@ -790,4 +790,31 @@ TEST(the_selection_table_folds_repeats_and_names_the_refusal) { CHECK_EQ(r.n_selections(), (size_t)0); } +/* A "device." CONSTRAINT IS READ FROM THE MACHINE, not from the query: the engine measures peer + * access at launch and the selector holds a kernel that needs it to that. Unmeasured, the kernel + * is not selected and the refusal says nothing measured it; measured absent, the next row in the + * plugin takes the op, and an op with no such row is refused naming the fact. The query never + * carries the key, so no geometry -- and no tuning key -- changes. */ +TEST(a_device_fact_constraint_is_matched_against_the_machine) { + Registry r; + CHECK_OK(load(r)); + Geometry g; + g.set_i("M", 4); + g.set_i("n", 64); + + CHECK_EQ(picked(r.select("t_peer", g, RAD_DOMAIN_DEVICE)), "t_peer_staged"); + CHECK(has(refusal(r, "t_peer_only", g), "device.p2p is not known")); + + r.set_device_fact(RAD_FACT_P2P, 1); + CHECK_EQ(picked(r.select("t_peer", g, RAD_DOMAIN_DEVICE)), "t_peer_direct"); + CHECK_EQ(picked(r.select("t_peer_only", g, RAD_DOMAIN_DEVICE)), "t_peer_only_direct"); + CHECK(!g.has(RAD_FACT_P2P)); + + r.set_device_fact(RAD_FACT_P2P, 0); + CHECK_EQ(picked(r.select("t_peer", g, RAD_DOMAIN_DEVICE)), "t_peer_staged"); + const std::string why = refusal(r, "t_peer_only", g); + CHECK(has(why, "device.p2p == 1, have 0")); + CHECK(has(why, "measured at launch")); +} + RAD_TEST_MAIN() diff --git a/tests/sample_test.cpp b/tests/sample_test.cpp index d3055eb0..d78e64c8 100644 --- a/tests/sample_test.cpp +++ b/tests/sample_test.cpp @@ -1855,4 +1855,129 @@ TEST(admission_resolves_grammar_triggers_and_refuses_a_regular_expression) { CHECK_EQ(ch.s.check_request(sp, &why), RAD_E_UNSUPPORTED); } +/* A THINKING BUDGET CLOSES THE REASONING BLOCK WHERE THE BODY REACHES IT, and it is walked over the + * speculative window as a grammar is: position k counts the committed reply and drafts 0..k-1, so + * a window that crosses the budget is forced from the first position past it, and a draft that + * closes the block itself frees every position behind it. Token 1 wins every row's logits, so a + * row that comes back 5 was forced. */ +TEST(a_thinking_budget_forces_the_close_from_the_position_that_spends_it) { + HostChain ch(8, 1, 2); + NEED_CHAIN(ch) + SamplingParams sp = greedy_params(); + sp.reasoning.close = 5; + sp.reasoning.starts_open = true; + sp.thinking_budget = 2; + std::vector lg(3 * 8, 0.0f); + for (int r = 0; r < 3; ++r) lg[(size_t)r * 8 + 1] = 5.0f; + std::vector tok; + + Request a = make_req(1, { 3 }, sp); + a.output = { 1 }; + int32_t da[2] = { 2, 2 }; + a.n_draft = 2; + a.draft = da; + CHECK_OK(ch.step({ &a }, lg, &tok)); + CHECK_EQ(tok[0], 1); /* one body token: within the budget */ + CHECK_EQ(tok[1], 5); /* behind a draft that makes it two */ + CHECK_EQ(tok[2], 5); + + Request b = make_req(2, { 3 }, sp); + b.output = { 1 }; + int32_t db[2] = { 5, 2 }; + b.n_draft = 2; + b.draft = db; + CHECK_OK(ch.step({ &b }, lg, &tok)); + CHECK_EQ(tok[0], 1); + CHECK_EQ(tok[1], 1); /* the draft closed the block: nothing left to force */ + CHECK_EQ(tok[2], 1); +} + +/* THE COMMITTED REPLY IS COUNTED ACROSS STEPS, and only from where the block opens: a reply that + * opens its own block counts from its opener, and one that starts any other way has no block to + * budget. Sampled, not greedy, so the mask is what decides and not an argmax that happens to + * agree. */ +TEST(a_thinking_budget_counts_the_reply_across_steps_and_only_inside_the_block) { + HostChain ch(8, 2, 0); + NEED_CHAIN(ch) + SamplingParams sp; + sp.temp = 1.0f; + sp.reasoning.open = 4; + sp.reasoning.close = 5; + sp.thinking_budget = 1; + std::vector lg(2 * 8, 0.0f); + lg[1] = 40.0f; + lg[8 + 1] = 40.0f; + std::vector tok; + + Request opens = make_req(1, { 3 }, sp); + Request plain = make_req(2, { 3 }, sp); + opens.output = { 4 }; /* the opener: the block starts, nothing in it yet */ + plain.output = { 2 }; /* no opener first: there is no block */ + CHECK_OK(ch.step({ &opens, &plain }, lg, &tok)); + CHECK_EQ(tok[0], 1); + CHECK_EQ(tok[1], 1); + + opens.output.push_back(1); /* one body token: the budget is spent */ + plain.output.push_back(1); + CHECK_OK(ch.step({ &opens, &plain }, lg, &tok)); + CHECK_EQ(tok[0], 5); + CHECK_EQ(tok[1], 1); + + opens.output.push_back(5); /* closed: the answer is free again */ + CHECK_OK(ch.step({ &opens, &plain }, lg, &tok)); + CHECK_EQ(tok[0], 1); +} + +/* A GRAMMAR KEEPS THE LAST WORD. The close is forced only where the grammar admits it; where it + * does not, the row is the grammar's, and the budget waits for a position the grammar allows. */ +TEST(a_thinking_budget_forces_the_close_only_where_the_grammar_admits_it) { + SimpleVocab v({ "a", "b", "c", "" }); + HostChain ch(4, 1, 0, &v); + NEED_CHAIN(ch) + SamplingParams sp = greedy_params(); + sp.reasoning.close = 3; + sp.reasoning.starts_open = true; + sp.thinking_budget = 0; + std::vector lg = { 9.0f, 0.0f, 0.0f, 0.0f }; + std::vector tok; + + sp.grammar = "root ::= (\"a\" | \"\")+"; + Request admits = make_req(1, { 1 }, sp); + CHECK_OK(ch.step({ &admits }, lg, &tok)); + CHECK_EQ(tok[0], 3); + + sp.grammar = "root ::= \"a\"+"; + Request forbids = make_req(2, { 1 }, sp); + CHECK_OK(ch.step({ &forbids }, lg, &tok)); + CHECK_EQ(tok[0], 0); +} + +/* The count a budget is held against and the count usage reports are one definition. */ +TEST(reasoning_count_follows_the_parser_s_reading_of_the_block) { + ReasoningSpan s; + s.open = 4; + s.close = 5; + ReasoningCount c; + c.start(s); + for (int32_t t : { 4, 1, 1, 5, 1, 4, 1 }) c.push(s, t); + CHECK_EQ(c.tokens, (int64_t)4); /* the opener, two body tokens, the close */ + CHECK_EQ(c.body, (int64_t)2); + CHECK(!c.inside()); + + s.starts_open = true; + c.start(s); + for (int32_t t : { 1, 1, 1 }) c.push(s, t); + CHECK(c.inside()); + CHECK_EQ(c.tokens, (int64_t)3); + + s.starts_open = false; + c.start(s); + for (int32_t t : { 1, 4, 1 }) c.push(s, t); + CHECK_EQ(c.tokens, (int64_t)0); /* a block opened mid-reply is not one */ + + c.start(ReasoningSpan{}); + c.push(ReasoningSpan{}, 1); + CHECK_EQ(c.tokens, (int64_t)0); +} + RAD_TEST_MAIN() diff --git a/tests/sched_test.cpp b/tests/sched_test.cpp index b7d87a10..135fc661 100644 --- a/tests/sched_test.cpp +++ b/tests/sched_test.cpp @@ -2076,4 +2076,49 @@ TEST(shutdown_fails_each_sink_with_the_status_that_stopped_the_engine) { } } +/* A REQUEST'S OWN SPECULATION AND ITS ADMISSION REACH ITS SINK, which is what lets a response say + * how many tokens were drafted for it and when its prefill started: the aggregate counters cannot + * be split between requests that overlap. The count is the drafts each verify step proposed for + * this request and the ones it accepted -- the same numbers /metrics sums. */ +TEST(a_sink_carries_its_requests_admission_and_draft_counts) { + server::Sink sink; + Fixture f; + f.build(/*blocks=*/4096, /*states=*/64); + f.cfg.n_spec = 4; + CHECK_OK(f.start()); + + const uint64_t id = f.submit_to(&sink, 40, 60); + CHECK(id != 0); + CHECK(sink.t_admitted_ns() < 0); + int64_t drafted = 0, accepted = 0; + uint32_t rng = 99; + for (int step = 0; step < 40 && !sink.done(); ++step) { + int32_t draft[4] = { 31, 32, 33, 34 }; + (void)f.sch.set_draft(id, draft, 4); + const RadBatch* b = f.sch.step(); + if (!b) break; + CHECK(sink.t_admitted_ns() >= 0); + const StepPlan& p = f.sch.plan(); + Scheduler::StepResult r; + static int32_t acc[64], tok[64]; + static uint8_t eos[64]; + for (size_t k = 0; k < p.e.size(); ++k) { + rng = rng * 1664525u + 1013904223u; + acc[k] = p.e[k].n_spec > 0 ? (int32_t)((rng >> 16) % (uint32_t)(p.e[k].n_spec + 1)) : 0; + tok[k] = 5; + eos[k] = 0; + if (!p.e[k].is_prefill && p.e[k].n_spec > 0) { + drafted += p.e[k].n_spec; + accepted += acc[k]; + } + } + r.n_seq = (int)p.e.size(); + r.n_accepted = acc; r.token = tok; r.eos = eos; + CHECK_OK(f.sch.commit(r)); + } + CHECK(drafted > 0); + CHECK_EQ(sink.n_drafted(), drafted); + CHECK_EQ(sink.n_draft_accepted(), accepted); +} + RAD_TEST_MAIN() diff --git a/tests/server_test.cpp b/tests/server_test.cpp index 2f18b389..458495da 100644 --- a/tests/server_test.cpp +++ b/tests/server_test.cpp @@ -124,6 +124,9 @@ struct FakeChatTemplate : IChatTemplate { /* The parser is built per render and reads calls only for a request that sent tools -- * the contract the real bridge keeps (IReplyParser). */ if (with_parser) out->parser = std::make_shared(!tools.empty()); + out->think_open = think_open; + out->think_close = think_close; + out->think_starts_open = think_starts_open; return RAD_OK; } bool supports_tools() const override { return tools_ok; } @@ -133,6 +136,9 @@ struct FakeChatTemplate : IChatTemplate { bool with_parser = false; std::string refusal; std::string refuse_kwarg; + /* The reasoning block a render reports. FakeTokenizer makes a one-byte marker one token. */ + std::string think_open, think_close; + bool think_starts_open = false; /* Reads "TOOL::" -- everything after the second colon is the arguments, * however incomplete, and it arrives a piece at a time. That is exactly the shape the @@ -230,10 +236,14 @@ struct FakeScheduler : IScheduler { * fails every request it holds when a step fails. */ int fail_status = 0; const char* fail_why = nullptr; + /* Nonzero: every token after the first is a verify step that proposed this many drafts and + * accepted one, as a speculating engine reports them. */ + int32_t drafts = 0; SchedMetrics m; std::mutex mu; std::vector submitted; + SamplingParams last_sp; /* what the last submitted request was to sample with */ std::vector cancelled; std::vector workers; std::atomic next_id{1}; @@ -250,6 +260,7 @@ struct FakeScheduler : IScheduler { { std::lock_guard lk(mu); submitted.push_back(id); + last_sp = r.sp; } void* sink = r.sink; int32_t cap = r.max_tokens; @@ -257,14 +268,17 @@ struct FakeScheduler : IScheduler { bool h = hang; const int fst = fail_status; const char* fwhy = fail_why; + const int32_t nd = drafts; /* 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] { + workers.emplace_back([sink, cap, text, h, fst, fwhy, nd] { + sink_admitted(sink); sink_prompt_stats(sink, 8, 4); int32_t n = 0; for (char c : text) { 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; ++n; if (h && n >= 3) break; @@ -1647,6 +1661,254 @@ TEST(n_streamed_choices_share_one_usage_chunk_after_every_final_chunk) { } } +/* ================================================================== reasoning */ + +/* HOW MUCH OF completion_tokens WAS REASONING, on both paths: the reply below opens inside the + * block (the render says so), and `|` -- one token to FakeTokenizer -- closes it after three body + * tokens, so four of the seven tokens are reasoning, the close included. A model whose block + * cannot be counted reports no breakdown rather than a zero. */ +TEST(usage_reports_the_reasoning_tokens_inside_completion_tokens) { + { + Fixture f; + f.tmpl.think_close = "|"; + f.tmpl.think_starts_open = true; + f.sched.reply = "abc|xyz"; + HttpResponse r = f.post("/v1/chat/completions", + R"({"messages":[{"role":"user","content":"hi"}]})"); + CHECK_EQ(r.status, 200); + const json j = json::parse(r.body); + CHECK_EQ(j["usage"]["completion_tokens"].get(), 7); + CHECK_EQ(j["usage"]["completion_tokens_details"]["reasoning_tokens"].get(), 4); + + HttpResponse st = f.post("/v1/chat/completions", + R"({"messages":[{"role":"user","content":"hi"}],"stream":true, + "stream_options":{"include_usage":true}})"); + int bad = 0; + auto p = sse_payloads(drain(st), &bad); + CHECK_EQ(bad, 0); + REQUIRE(p.size() >= 2); + const json u = json::parse(p[p.size() - 2]); + CHECK_EQ(u["usage"]["completion_tokens_details"]["reasoning_tokens"].get(), 4); + } + { + Fixture f; + f.tmpl.think_close = ""; /* four tokens: not a countable block */ + f.tmpl.think_starts_open = true; + HttpResponse r = f.post("/v1/chat/completions", + R"({"messages":[{"role":"user","content":"hi"}]})"); + CHECK_EQ(r.status, 200); + CHECK(!json::parse(r.body)["usage"].contains("completion_tokens_details")); + } +} + +/* 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. */ +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" }) { + HttpResponse r = f.post("/v1/chat/completions", + std::string(R"({"messages":[{"role":"user","content":"hi"}],")") + + k + R"(":7})"); + CHECK_EQ(r.status, 200); + f.sched.join_all(); + std::lock_guard lk(f.sched.mu); + CHECK_EQ(f.sched.last_sp.thinking_budget, 7); + CHECK_EQ(f.sched.last_sp.reasoning.close, (int32_t)'|'); + CHECK_EQ(f.sched.last_sp.reasoning.open, (int32_t)'{'); + CHECK(f.sched.last_sp.reasoning.starts_open); + } + + 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)", + "thinking_budget" }, + Case{ R"("thinking_budget":"3")", "thinking_budget" } }) { + HttpResponse r = f.post("/v1/chat/completions", + std::string(R"({"messages":[{"role":"user","content":"hi"}],)") + + c.extra + "}"); + CHECK_EQ(r.status, 400); + CHECK_EQ(json::parse(r.body)["error"]["param"].get(), std::string(c.param)); + } + + Fixture multi; + multi.tmpl.think_close = ""; + multi.tmpl.think_starts_open = true; + HttpResponse r = multi.post("/v1/chat/completions", + R"({"messages":[{"role":"user","content":"hi"}], + "thinking_token_budget":5})"); + CHECK_EQ(r.status, 400); + CHECK(json::parse(r.body)["error"]["message"].get().find("4 tokens") != + std::string::npos); + + Fixture none; + HttpResponse n = none.post("/v1/chat/completions", + R"({"messages":[{"role":"user","content":"hi"}], + "thinking_token_budget":5})"); + CHECK_EQ(n.status, 400); + CHECK(json::parse(n.body)["error"]["message"].get().find("no reasoning block") != + std::string::npos); +} + +/* THE DEPLOYMENT'S BUDGET applies to a request that names none, loses to one that does, and is + * not applied where the block cannot be counted -- it could not be held there. The startup check + * says why a model cannot take it at all. */ +TEST(the_deployment_s_thinking_budget_is_a_default_a_request_can_override) { + Fixture f; + f.tmpl.think_close = "|"; + f.tmpl.think_starts_open = true; + OaiLimits lim = f.limits(); + 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, f.limits(), "").sp.thinking_budget, -1); + + f.tmpl.think_close.clear(); + CHECK_EQ(chat_with(f, lim, "").sp.thinking_budget, -1); + + Fixture g; + ServerOptions o; + o.model_id = "test-model"; + o.default_max_tokens = 32; + o.default_thinking_budget = 64; + Deps d; + d.sched = &g.sched; + d.tok = &g.tok; + d.chat = &g.tmpl; + d.grammar = &g.gram; + Server s(d, o); + CHECK(s.check_thinking_budget().find("no reasoning block") != std::string::npos); + g.tmpl.think_close = "|"; + g.tmpl.think_starts_open = true; + CHECK(s.check_thinking_budget().empty()); +} + +/* ================================================================== timings */ + +/* WHERE THE REQUEST'S TIME WENT, in llama.cpp's shape, on every path a client can take: the + * buffered body, each streamed choice's final chunk whether or not a usage chunk was asked for, + * and the usage chunk when it was. The fake places 8 prompt tokens with 4 from the cache, and + * every token after the first is a verify step that proposed 3 drafts and took 1. */ +TEST(a_response_carries_its_requests_timings_and_draft_counts) { + auto check = [](const json& t, int64_t predicted, bool drafts) { + CHECK_EQ(t["prompt_n"].get(), (int64_t)4); + CHECK_EQ(t["cache_n"].get(), (int64_t)4); + CHECK_EQ(t["predicted_n"].get(), predicted); + CHECK(t["prompt_ms"].is_number()); + CHECK(t["predicted_ms"].is_number()); + CHECK(t["prompt_ms"].get() >= 0.0); + for (const char* k : { "prompt_per_token_ms", "prompt_per_second", + "predicted_per_token_ms", "predicted_per_second" }) + CHECK(t[k].is_number() || t[k].is_null()); + CHECK_EQ(t.contains("draft_n"), drafts); + if (drafts) { + CHECK_EQ(t["draft_n"].get(), (predicted - 1) * 3); + CHECK_EQ(t["draft_n_accepted"].get(), predicted - 1); + } + }; + { + Fixture f; + f.sched.drafts = 3; + HttpResponse r = f.post("/v1/chat/completions", + R"({"messages":[{"role":"user","content":"hi"}]})"); + CHECK_EQ(r.status, 200); + const json j = json::parse(r.body); + REQUIRE(j.contains("timings")); + check(j["timings"], 5, true); + CHECK_EQ(j["timings"]["predicted_n"].get(), + j["usage"]["completion_tokens"].get()); + } + { + Fixture f; + HttpResponse r = f.post("/v1/completions", R"({"prompt":"hi","max_tokens":8})"); + CHECK_EQ(r.status, 200); + const json j = json::parse(r.body); + REQUIRE(j.contains("timings")); + check(j["timings"], 5, false); + } + const char* paths[] = { "/v1/chat/completions", "/v1/completions" }; + const char* bodies[] = { R"({"messages":[{"role":"user","content":"hi"}],"stream":true)", + R"({"prompt":"hi","stream":true)" }; + for (int k = 0; k < 2; ++k) + for (bool usage : { false, true }) { + Fixture f; + f.sched.drafts = 3; + HttpResponse r = f.post(paths[k], std::string(bodies[k]) + + (usage ? R"(,"stream_options":{"include_usage":true}})" + : "}")); + CHECK_EQ(r.status, 200); + int bad = 0; + auto p = sse_payloads(drain(r), &bad); + CHECK_EQ(bad, 0); + int finals = 0, with_timings = 0; + for (size_t i = 0; i + 1 < p.size(); ++i) { + const json j = json::parse(p[i]); + if (j.contains("usage")) { + REQUIRE(j.contains("timings")); + check(j["timings"], 5, true); + ++with_timings; + continue; + } + if (j["choices"][0]["finish_reason"].is_null()) { + CHECK(!j.contains("timings")); + continue; + } + ++finals; + REQUIRE(j.contains("timings")); + check(j["timings"], 5, true); + ++with_timings; + } + CHECK_EQ(finals, 1); + CHECK_EQ(with_timings, usage ? 2 : 1); + } +} + +/* The rates are the tokens over the time that produced them, the first token being the prompt + * phase's; a rate whose count or time is zero is null, and so is a prompt time the engine never + * reported. */ +TEST(timings_rates_divide_the_tokens_by_the_time_that_produced_them) { + TimingsOut t; + t.valid = true; + t.prompt_n = 100; + t.prompt_ms = 50.0; + t.predicted_n = 10; + t.decode_n = 9; + t.predicted_ms = 90.0; + json j = timings_json(t); + CHECK_NEAR(j["prompt_per_second"].get(), 2000.0, 1e-9); + CHECK_NEAR(j["prompt_per_token_ms"].get(), 0.5, 1e-12); + CHECK_NEAR(j["predicted_per_second"].get(), 100.0, 1e-9); + CHECK_NEAR(j["predicted_per_token_ms"].get(), 10.0, 1e-12); + CHECK(!j.contains("draft_n")); + + t.decode_n = 0; + t.predicted_ms = 0.0; + t.prompt_ms = -1.0; + j = timings_json(t); + CHECK(j["predicted_per_second"].is_null()); + CHECK(j["predicted_per_token_ms"].is_null()); + CHECK(j["prompt_ms"].is_null()); + CHECK(j["prompt_per_second"].is_null()); +} + +/* The sink keeps the first admission across a preemption and sums the drafts it is told of. */ +TEST(a_sink_keeps_its_first_admission_and_sums_its_drafts) { + Sink s; + CHECK(s.t_admitted_ns() < 0); + s.mark_admitted(); + const int64_t a = s.t_admitted_ns(); + CHECK(a >= 0); + std::this_thread::sleep_for(std::chrono::milliseconds(2)); + s.mark_admitted(); + CHECK_EQ(s.t_admitted_ns(), a); + s.add_drafts(4, 2); + s.add_drafts(3, 3); + CHECK_EQ(s.n_drafted(), (int64_t)7); + CHECK_EQ(s.n_draft_accepted(), (int64_t)5); +} + /* ================================================================== cancellation */ TEST(a_dropped_stream_cancels_at_the_scheduler) {