From 8ddb77e03c092342a8544483ec21a17ea04ae612 Mon Sep 17 00:00:00 2001 From: Deadcode Date: Sun, 4 Oct 2026 15:07:32 +0200 Subject: [PATCH] radiance 1.0.1 - Up to 32 sequences a step on every model. The DSpark drafter (MiniCPM5) no longer rejects every draft from the tenth sequence on, and the step batch's block tables and media staging are charged to the VRAM budget instead of the headroom kernels load into. - A tool parameter whose schema accepts no value ({"not": {}}, as TypeBox and Arktype export `never`) is an argument no call writes, instead of failing the request. oh-my-pi's task tool works. - --served-model-name NAME and --override-chat-template PATH. - The startup session count counts only the part of the KV pool that holds context. - Compose files and README run --max-num-seqs 32 where it keeps a 200K-token request. --- CMakeLists.txt | 2 +- README.md | 11 +- arch/common/rad_block_dspark.h | 28 +++- core/config.cpp | 9 ++ core/engine.cpp | 6 +- core/engine_bringup.cpp | 65 +++++++- core/mem/kv.h | 3 + core/mem/vram_budget.cpp | 28 +++- core/mem/vram_budget.h | 7 +- core/rad_core.h | 9 ++ core/sched/batch.cpp | 76 +++++++--- core/sched/batch.h | 11 ++ core/text/chatfmt.cpp | 6 + deploy/compose/minicpm5-2b-bf16.yaml | 2 +- deploy/compose/minicpm5-2b.yaml | 2 +- deploy/compose/qwen3.6-35b-a3b.yaml | 2 +- deploy/compose/qwen3.8-27b-fp8.yaml | 2 +- docs/GUIDE.md | 30 +++- spec.md | 3 +- tests/chatparse_test.cpp | 31 ++++ tests/config_test.cpp | 6 +- tests/gbnf_test.cpp | 86 +++++++++++ vendor/UPSTREAM | 18 +++ .../common/chat-auto-parser-generator.cpp | 11 ++ vendor/llama/common/chat.cpp | 5 + .../llama/common/json-schema-to-grammar.cpp | 52 ++++++- vendor/llama/common/json-schema-to-grammar.h | 2 + ...n-schema-a-schema-no-value-satisfies.patch | 142 ++++++++++++++++++ 28 files changed, 595 insertions(+), 60 deletions(-) create mode 100644 vendor/patches/0012-json-schema-a-schema-no-value-satisfies.patch diff --git a/CMakeLists.txt b/CMakeLists.txt index 20a54527..07707eb3 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.0 LANGUAGES C CXX) +project(radiance VERSION 1.0.1 LANGUAGES C CXX) set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD_REQUIRED ON) diff --git a/README.md b/README.md index ee7e8a56..8128c4e0 100644 --- a/README.md +++ b/README.md @@ -77,10 +77,17 @@ prefix-cache tiers: | model | flags | |---|---| | Qwen3.8-Flash-Next | `--tp 2 --tp-wire wht6 --max-num-seqs 8 --max-model-len 200000 --placement expert_tiered --host-pool-mib 12288 --gpu-headroom-mib 96 --expert-vs-cache-ratio 0.82 --kv-cache-dtype fp8 --num-speculative-tokens 3 --max-num-batched-tokens 2048` | -| Qwen3.8-27B FP8 and bf16, Qwen3.6-35B-A3B | `--tp 2 --max-num-seqs 8 --max-model-len 200000 --kv-cache-dtype fp8` | -| MiniCPM5-2B FP8 and bf16 | `--tp 2 --max-num-seqs 8 --max-model-len 131072 --kv-cache-dtype fp8 --gpu-headroom-mib 160 --max-num-batched-tokens 512` | +| Qwen3.8-27B FP8, Qwen3.6-35B-A3B | `--tp 2 --max-num-seqs 32 --max-model-len 200000 --kv-cache-dtype fp8` | +| Qwen3.8-27B bf16 | `--tp 2 --max-num-seqs 8 --max-model-len 200000 --kv-cache-dtype fp8` | +| MiniCPM5-2B FP8 and bf16 | `--tp 2 --max-num-seqs 32 --max-model-len 131072 --kv-cache-dtype fp8 --gpu-headroom-mib 160 --max-num-batched-tokens 512` | | Qwen3.8-Flash-Next bf16 | `--tp 2 --max-model-len 32768 --placement expert_tiered --weights-disk-tier --host-pool-mib 12288 --gpu-headroom-mib 768 --deterministic --max-num-seqs 32 --max-num-batched-tokens 32768 --num-speculative-tokens 0` | +Every model serves up to 32 sequences a step. Two rows keep 8, because on a hybrid model each +sequence holds its own recurrent state and 32 of them leave the attention cache short of one +200K-token request: Flash-Next at ratio 0.82 (`--max-num-seqs 32 --expert-vs-cache-ratio 0.78` +keeps the 200K request and costs single-stream decode about 15%) and the 27B in bf16. See +[`docs/GUIDE.md`](docs/GUIDE.md) §4.4. + Add `--api-key KEY` to require `Authorization: Bearer KEY`. Add `--debug-graph` to print every op and the kernel it resolved to, then exit without serving. Then: diff --git a/arch/common/rad_block_dspark.h b/arch/common/rad_block_dspark.h index 7495d4fe..a913b002 100644 --- a/arch/common/rad_block_dspark.h +++ b/arch/common/rad_block_dspark.h @@ -573,22 +573,30 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con rad_op_writes(b, h, wr, fold ? 4 : 3); return h; }; - for (int64_t l = 0; l < g.n_layer; ++l) { - const int i = (int)l; - op_anorm[i] = decl_norm(w_anorm[i], i != 0); - op_fnorm[i] = decl_norm(w_fnorm[i], true); - if (!op_anorm[i] || !op_fnorm[i]) return RAD_E_INVAL; - } - op_outnorm = decl_norm(w_norm, true); op_qat = rw(b, RAD_OP(b, "quant_act_fp8", RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", qd), RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)), RAD_NOWEIGHTS), {w.attn.x}, {w.attn.q, w.attn.s}); - if (!op_outnorm || !op_qat) return RAD_E_INVAL; + if (!op_qat) return RAD_E_INVAL; + /* THE NORMS ARE DECLARED WHERE step() ISSUES THEM, because declaration order is the buffer + * planner's liveness: a transient lives over the op indices that touch it, and two whose spans + * are disjoint may share bytes (core/build/rad_bufplan.cpp). The stream `x` and the norm + * outputs `h` are live across every layer, and the norms are the only ops that touch the + * stream after the embedding, so their positions are the stream's lifetime. Each layer's two + * norms sit inside the loop and the final one after every op the layers issue -- the shared + * rope, store, silu_mul and quantiser handles below included. + * + * Declared together ahead of the layers, the stream's lifetime ended before the first layer's + * temporaries began, and the packer put a feed-forward temporary on top of it. The fused gated + * GEMM never writes those, so the overlap stayed silent up to 64 rows a pass; past 64 the + * unfused pair writes `gate_up` and `ffn.x`, and every draft was rejected from the tenth + * sequence on. */ for (int64_t l = 0; l < g.n_layer; ++l) { const int i = (int)l; + op_anorm[i] = decl_norm(w_anorm[i], i != 0); + if (!op_anorm[i]) return RAD_E_INVAL; op_qp[i] = rw(b, RAD_OP(b, "gemm_nt_q", RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", qd), RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK), @@ -625,6 +633,8 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con RAD_STR("dtype", "fp8a8")), RAD_WEIGHTS(w_o[i].w, w_o[i].s)), {w.attn.q, w.attn.s}, {w.h.x}); + op_fnorm[i] = decl_norm(w_fnorm[i], true); + if (!op_fnorm[i]) return RAD_E_INVAL; op_gu[i] = rw(b, RAD_OP(b, "gemm_nt_q", RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("N", 2 * g.n_ff), RAD_INT("K", g.n_embd), RAD_INT("group", RAD_FP8_BLOCK), @@ -701,6 +711,8 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con RAD_INT("min_bytes", g.wire_min_bytes)), RAD_NOWEIGHTS), {w.h.x}, {w.h.x}); + op_outnorm = decl_norm(w_norm, true); + if (!op_outnorm) return RAD_E_INVAL; /* ---------------------------------------------------------------- the head and the walk * diff --git a/core/config.cpp b/core/config.cpp index a040318f..d4c7cf64 100644 --- a/core/config.cpp +++ b/core/config.cpp @@ -84,6 +84,7 @@ static const Flag g_flags[] = { { "--host", "ADDR", "listen address" }, { "--port", "N", "listen port" }, { "--api-key", "KEY", "require `Authorization: Bearer KEY` on every request but /health, /ping and the dashboard page" }, + { "--served-model-name", "NAME", "the model id /v1/models lists and responses carry; default the container's name" }, { "--mm-max-patches", "N", "patches one encoder pass carries, and so the largest image (a patch is 16x16\n" "pixels). Default `auto`: 16384 when the container carries a vision tower. 0\n" "serves text only and keeps the tower off the card" }, @@ -91,6 +92,7 @@ static const Flag g_flags[] = { " for requests that send none. Without it the container's own\n" " `generation.*` metadata is used, then a .generation.json\n" " beside the container, then the built-in defaults" }, + { "--override-chat-template", "PATH", "a Jinja chat template file, used in place of the one the container carries" }, { "--temp", "F", "default temperature for requests that do not set one" }, { "--top-k", "N", "default top_k (0 = off) for requests that do not set one" }, { "--top-p", "F", "default top_p for requests that do not set one" }, @@ -267,6 +269,11 @@ int config_parse(int argc, char** argv, Config* c) { else if (S("--host")) { if (!(v = need(i))) return RAD_E_INVAL; c->host = v; } else if (S("--port")) { if (!(v = need(i))) return RAD_E_INVAL; c->port = atoi(v); } else if (S("--api-key")) { if (!(v = need(i))) return RAD_E_INVAL; c->api_key = v; } + else if (S("--served-model-name")) { + if (!(v = need(i))) return RAD_E_INVAL; + if (!*v) { RAD_ERR("--served-model-name takes a non-empty name"); return RAD_E_INVAL; } + c->served_model_name = v; + } else if (S("--mm-max-patches")) { if (!(v = need(i))) return RAD_E_INVAL; if (!std::strcmp(v, "auto")) c->mm_max_patches = -1; @@ -284,6 +291,8 @@ int config_parse(int argc, char** argv, Config* c) { c->reasoning_effort = v; } 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; + c->override_chat_template = v; } /* A NEGATIVE VALUE IS REFUSED HERE, not left to the range checks below: the fields use * a negative number to mean "not set", so `--temp -0.5` would otherwise be read as no * flag at all and the container's default served in its place. */ diff --git a/core/engine.cpp b/core/engine.cpp index 0f3111c2..adbc63a1 100644 --- a/core/engine.cpp +++ b/core/engine.cpp @@ -1959,11 +1959,15 @@ int Engine::run_server() { } server::ServerOptions o{}; - o.model_id = meta_.name && *meta_.name ? meta_.name : "radiance"; + o.model_id = !cfg_.served_model_name.empty() ? cfg_.served_model_name + : meta_.name && *meta_.name ? meta_.name : "radiance"; o.host = cfg_.host; o.port = cfg_.port; o.api_key = cfg_.api_key; o.max_seqs = cfg_.max_seqs; + /* `n` fans one request out over the batch, so a server that runs more sequences a step takes + * more choices a request; the floor keeps a small batch from refusing what it would queue. */ + o.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_sampling = resolve_sampling_defaults(meta_, file_ != nullptr, cfg_); diff --git a/core/engine_bringup.cpp b/core/engine_bringup.cpp index ee0361a4..7e9d88d1 100644 --- a/core/engine_bringup.cpp +++ b/core/engine_bringup.cpp @@ -26,6 +26,8 @@ #include #include +#include +#include #include #include #include @@ -445,12 +447,20 @@ int Engine::declare() { nullptr, sources()); }); } - if (cfg_.tp > 1 && !cfg_.tp_wire_exact) - RAD_WARN("tp wire: LOSSY (--tp-wire wht6) above %lld KiB a message. A cross-rank " - "all-reduce at or over that size carries a Walsh-Hadamard-rotated 6-bit payload " - "instead of bf16, so this process does not compute the same function the exact " - "wire does; smaller messages -- which is every decode step -- are still exact.", - (long long)cfg_.tp_wire_min_kb); + /* A message is a step's rows of the residual stream in bf16, so the floor is a ROW COUNT: a + * decode step's rows are its sequences times one plus the speculative depth, and concurrency + * alone decides whether a decode step is under it. */ + if (cfg_.tp > 1 && !cfg_.tp_wire_exact) { + const int64_t row_bytes = meta_.n_embd > 0 ? meta_.n_embd * 2 : 1; + const int64_t exact_rows = (cfg_.tp_wire_min_kb * 1024 + row_bytes - 1) / row_bytes - 1; + RAD_WARN("tp wire: LOSSY (--tp-wire wht6) at %lld KiB a message and above. A cross-rank " + "all-reduce of that size carries a Walsh-Hadamard-rotated 6-bit payload instead " + "of bf16, so this process does not compute the same function the exact wire " + "does. Steps of at most %lld rows are exact: single-sequence decode, and a " + "decode step until sequences x (1 + speculative depth) passes that; prefill and " + "a busy decode step are lossy. --tp-wire-min-kb moves the floor.", + (long long)cfg_.tp_wire_min_kb, (long long)exact_rows); + } for (auto& t : th) t.join(); @@ -677,8 +687,21 @@ int Engine::plan() { * no memory and no pool; it is the half of configure() that is pure arithmetic on the * declaration, split out for exactly this caller. */ KVManager probe; - if (probe.plan_groups(r->program.kv_groups, cfg_) == RAD_OK) + if (probe.plan_groups(r->program.kv_groups, cfg_) == RAD_OK) { f.kv_ceiling = probe.ceiling(ctx); + f.kv_fixed = probe.fixed_bytes(); + } + /* THE STEP BATCH'S DEVICE STAGING, which the scheduler reserves after this split: its + * block tables are carved for max_seqs sequences at max_ctx and its media staging for + * max_tok encoder rows. The state-index widths are the probe's, as the scheduler takes + * them from the configured manager. */ + KVGeom kg = KVGeom::of(r->program.kv_groups); + for (size_t i = 0; i < kg.g.size(); ++i) { + const int64_t w = probe.state_index_width((int32_t)i); + if (w > 0) kg.g[i].sidx_width = w; + } + f.staging = BatchBuilder::device_bytes(r->program, cfg_, kg); + if (f.staging < 0) return RAD_E_INVAL; facts.push_back(f); } VramBudget vb; @@ -2818,6 +2841,34 @@ int Engine::load_vocab() { } } + /* THE OPERATOR'S TEMPLATE REPLACES THE CONTAINER'S before anything reads it, so the chat + * endpoint and the reply format derived from the template agree about which one is served. An + * unreadable or empty file is refused: serving the container's template in its place would be + * the silent fallback the flag exists to rule out. */ + if (!cfg_.override_chat_template.empty()) { + std::ifstream f(cfg_.override_chat_template); + if (!f) { + RAD_ERR("--override-chat-template %s: cannot read the file", + cfg_.override_chat_template.c_str()); + return RAD_E_IO; + } + std::ostringstream ss; + ss << f.rdbuf(); + std::string t = ss.str(); + /* Trailing newlines go, as they do for a checkpoint's own chat_template.jinja, so one file + * renders the same prompt whichever way it reaches the server. */ + while (!t.empty() && (t.back() == '\n' || t.back() == '\r')) t.pop_back(); + if (t.find_first_not_of(" \t\r\n") == std::string::npos) { + RAD_ERR("--override-chat-template %s: the file is empty", + cfg_.override_chat_template.c_str()); + return RAD_E_INVAL; + } + RAD_INFO("chat: template from %s (%zu bytes), in place of the container's%s", + cfg_.override_chat_template.c_str(), t.size(), + vb.chat_template.empty() ? ", which carries none" : ""); + vb.chat_template = std::move(t); + } + auto v = std::make_shared(); RAD_TRY(v->load(std::move(vb))); vocab_ = v; diff --git a/core/mem/kv.h b/core/mem/kv.h index b05244ed..52d17280 100644 --- a/core/mem/kv.h +++ b/core/mem/kv.h @@ -165,6 +165,9 @@ public: * and nothing else (core/mem/vram_budget.cpp). carve() spends the pool it is given. */ int plan_groups(const std::vector& groups, const Config& cfg); int64_t ceiling(int64_t ctx) const; + /* The part of every ceiling that is not context: recurrent and conv state for max_seqs + * sequences, the checkpoint slots and the padding. Set by plan_groups(). */ + int64_t fixed_bytes() const { return fixed_; } int carve(Pool& kv_pool); const std::vector& plans() const { return plans_; } diff --git a/core/mem/vram_budget.cpp b/core/mem/vram_budget.cpp index 07cb0ead..685a621b 100644 --- a/core/mem/vram_budget.cpp +++ b/core/mem/vram_budget.cpp @@ -24,6 +24,15 @@ int64_t to_mib(int64_t bytes) { return bytes > 0 ? bytes / kMiB : 0; } int64_t to_mib_up(int64_t bytes) { return bytes > 0 ? (bytes + kMiB - 1) / kMiB : 0; } } /* namespace */ +/* WHAT THE CACHE BACKS, counted on its PAGED part. The ceiling is the recurrent and conv state of + * max_seqs sequences plus their context, and the state is spent before a single token is cached -- + * on a hybrid model at a few dozen sequences it is gigabytes a card. A ratio over the whole + * ceiling counts that state as context and reports full-length sessions the cache cannot hold. */ +static double paged_share(const VramBudget& b) { + const double ctx = (double)(b.kv_ceiling - b.kv_fixed); + return ctx > 0 ? std::max(0.0, (double)(b.kv - b.kv_fixed)) / ctx : 0.0; +} + int vram_budget_resolve(Config& cfg, const std::vector& per_rank, VramBudget* out) { VramBudget b; if (per_rank.empty()) { if (out) *out = b; return RAD_OK; } @@ -39,7 +48,9 @@ int vram_budget_resolve(Config& cfg, const std::vector& per_rank, Vra b.capacity = std::min(b.capacity, f.capacity); freeb = std::min(freeb, f.free); b.arena = std::max(b.arena, f.arena); + b.staging = std::max(b.staging, f.staging); b.kv_ceiling = std::max(b.kv_ceiling, f.kv_ceiling); + b.kv_fixed = std::max(b.kv_fixed, f.kv_fixed); b.statics = std::max(b.statics, f.statics); b.expert_ceiling = std::max(b.expert_ceiling, f.experts); layer_max = std::max(layer_max, f.expert_layer_max); @@ -72,7 +83,7 @@ int vram_budget_resolve(Config& cfg, const std::vector& per_rank, Vra b.derived_kv = want_kv; /* What is left after the terms nobody gets to spend. */ - int64_t fixed = b.already_held + b.headroom + b.arena; + int64_t fixed = b.already_held + b.headroom + b.arena + b.staging; if (!want_w) fixed += cfg.vram_weights_mib * kMiB; /* a stated pool is fixed too */ if (!want_kv) fixed += cfg.vram_kv_mib * kMiB; b.claimable = b.capacity - fixed; @@ -84,13 +95,14 @@ int vram_budget_resolve(Config& cfg, const std::vector& per_rank, Vra " already held %10s (driver context, code objects, anything else on the card)\n" " --gpu-headroom-mib %10s\n" " activation arena %10s (buffer plan + kernel scratch)\n" + " step staging %10s (block tables + media staging)\n" "%s%s" " ------------------------------\n" " SHORT BY %10s\n" "Lower --gpu-headroom-mib, lower --max-num-batched-tokens (the arena scales with it), " "or free the card.\n", humanb(b.capacity).c_str(), humanb(b.already_held).c_str(), - humanb(b.headroom).c_str(), humanb(b.arena).c_str(), + humanb(b.headroom).c_str(), humanb(b.arena).c_str(), humanb(b.staging).c_str(), want_w ? "" : fmt(" --vram-weights-mib %10s (stated)\n", humanb(cfg.vram_weights_mib * kMiB).c_str()).c_str(), want_kv ? "" : fmt(" --vram-kv-mib %10s (stated)\n", @@ -223,9 +235,9 @@ int vram_budget_resolve(Config& cfg, const std::vector& per_rank, Vra "live SESSIONS and not running requests -- when they do not all fit, the cache " "evicts prefixes the next turn wanted and that turn re-prefills its whole " "context. --expert-vs-cache-ratio moves it.", - 100.0 * (double)b.kv / (double)b.kv_ceiling, + 100.0 * paged_share(b), (long long)cfg.max_seqs, (long long)cfg.max_ctx, - (double)cfg.max_seqs * (double)b.kv / (double)b.kv_ceiling); + (double)cfg.max_seqs * paged_share(b)); /* Rounding the floor up claims up to a MiB the split did not hand out. Take it back from the * cache where the cache is ours to size -- a paged pool a MiB smaller addresses a handful * fewer tokens and nothing else -- so the headroom stays whole. Where the KV budget was @@ -240,13 +252,14 @@ int vram_budget_resolve(Config& cfg, const std::vector& per_rank, Vra * line is not padding: to_mib truncates, and what it drops is real VRAM that ends up beside * the headroom. */ const int64_t granted = cfg.vram_weights_mib * kMiB + cfg.vram_kv_mib * kMiB; - const int64_t unclaimed = b.capacity - b.already_held - b.arena - b.stage - granted; + const int64_t unclaimed = b.capacity - b.already_held - b.arena - b.staging - b.stage - granted; const double ela = b.elastic > 0 ? (double)b.elastic : 1.0; b.report = fmt( "VRAM budget, per card:\n" " card total %10s\n" " already held %10s measured: driver context, code objects, anything else resident\n" " activation arena %10s computed from the buffer plan\n" + " step staging %10s the step batch's block tables and media staging\n" " %-18s %10s %s\n" " ------------------------------\n" " claimable %10s\n" @@ -263,6 +276,7 @@ int vram_budget_resolve(Config& cfg, const std::vector& per_rank, Vra " unclaimed %10s the headroom, the unusable above, and what MiB rounding\n" " could not place\n", humanb(b.capacity).c_str(), humanb(b.already_held).c_str(), humanb(b.arena).c_str(), + humanb(b.staging).c_str(), shared ? "left to the host" : "--gpu-headroom-mib", humanb(b.headroom).c_str(), shared ? "integrated graphics: this memory is the host's; --vram-kv-mib states a pool " "outright" @@ -302,9 +316,9 @@ int vram_budget_resolve(Config& cfg, const std::vector& per_rank, Vra "finished sequence's blocks stay held\n" " for reuse, so the demand is LIVE " "SESSIONS and not running requests", - 100.0 * (double)b.kv / (double)b.kv_ceiling, + 100.0 * paged_share(b), (long long)cfg.max_seqs, (long long)cfg.max_ctx, - (double)cfg.max_seqs * (double)b.kv / (double)b.kv_ceiling).c_str() + (double)cfg.max_seqs * paged_share(b)).c_str() : ""), b.unusable > 0 ? fmt(" unusable %10s neither side could take it: both are at their " diff --git a/core/mem/vram_budget.h b/core/mem/vram_budget.h index 0273f7c9..0da3ca7e 100644 --- a/core/mem/vram_budget.h +++ b/core/mem/vram_budget.h @@ -60,7 +60,9 @@ struct VramFacts { int64_t capacity = 0; /* RadDeviceProps::vram_bytes -- totalGlobalMem */ int64_t free = 0; /* RadDeviceProps::vram_free, measured now */ int64_t arena = 0; /* arena_plan_bytes() for this rank's program, total incl. scratch */ + int64_t staging = 0; /* BatchBuilder::device_bytes(): the step slab and the media staging */ int64_t kv_ceiling = 0; /* KVManager::ceiling(max_ctx) for this rank's declared groups */ + int64_t kv_fixed = 0; /* KVManager::fixed_bytes(): the part of the ceiling that is state */ /* weight_footprint() for this rank, which under tensor parallel is already this card's even * share: declare runs per rank with every dimension already divided. */ int64_t statics = 0; /* non-expert weights -- the floor, not a share of anything */ @@ -75,11 +77,12 @@ struct VramFacts { /* The resolved split, in bytes, beside every term it came from. Always filled, including when the * operator stated the budgets -- the placement report and the pool report both want the totals. */ struct VramBudget { - int64_t capacity = 0, already_held = 0, headroom = 0, arena = 0; - int64_t claimable = 0; /* after the four fixed terms above */ + int64_t capacity = 0, already_held = 0, headroom = 0, arena = 0, staging = 0; + int64_t claimable = 0; /* after the fixed terms above */ int64_t statics = 0; /* off the top, before the ratio sees anything */ int64_t elastic = 0; /* claimable - statics: what the ratio divides */ int64_t kv_ceiling = 0, expert_ceiling = 0; + int64_t kv_fixed = 0; /* the state part of kv_ceiling, which no context uses */ int64_t experts = 0, kv = 0; /* the two shares, each capped at its ceiling */ int64_t unusable = 0; /* elastic neither side could take -- both were full */ /* THE PREFILL STAGING REGION: two buffers, each one layer's share of the experts the budget diff --git a/core/rad_core.h b/core/rad_core.h index 45598ccf..512052f4 100644 --- a/core/rad_core.h +++ b/core/rad_core.h @@ -653,6 +653,10 @@ struct Config { /* --api-key: the bearer key every request but the probes and the dashboard page must carry. * Empty serves without one. */ std::string api_key; + /* --served-model-name: the id /v1/models lists, a response names when its request named none, + * and the metrics carry. Empty takes the container's own name. A request may still name any + * model: one model is loaded and every request is served by it. */ + std::string served_model_name; /* WHAT A REQUEST THAT SENDS NO SAMPLER SETTINGS IS SERVED WITH. * @@ -671,6 +675,11 @@ struct Config { float sample_min_p = -1.0f; /* An operator-supplied generation_config.json, overriding the search described above. */ std::string generation_config; + /* --override-chat-template: a Jinja file whose text replaces the chat template the container + * (or the checkpoint directory) carries. Everything that reads the template reads this one: + * the chat endpoint's rendering, and the reply format derived from it -- reasoning markers and + * tool calls. Empty serves the container's. */ + std::string override_chat_template; bool debug_graph = false; bool debug_selection = false; diff --git a/core/sched/batch.cpp b/core/sched/batch.cpp index e194eb82..b91a8e95 100644 --- a/core/sched/batch.cpp +++ b/core/sched/batch.cpp @@ -177,7 +177,7 @@ void BatchBuilder::carve(Set& s, char* h) { s.dev_bytes = od; } -int BatchBuilder::alloc_set(Set& s, const std::vector& groups) { +void BatchBuilder::size_set(Set& s, const std::vector& groups) { s.groups.resize(groups.size()); for (size_t gi = 0; gi < groups.size(); ++gi) { const KVGeom::G& e = kvgeom_.g[gi]; @@ -192,8 +192,11 @@ int BatchBuilder::alloc_set(Set& s, const std::vector& groups) { s.groups[gi].max_blocks = mb; s.groups[gi].sidx_pitch = e.sidx_width > 0 ? e.sidx_width : 1; } - carve(s, nullptr); +} + +int BatchBuilder::alloc_set(Set& s, const std::vector& groups) { + size_set(s, groups); /* ONE SLAB PER RANK, on that rank's card. rad_dev_alloc has no device argument and uses the * current one, so the bind is part of the allocation. */ @@ -340,6 +343,43 @@ int BatchBuilder::init(Program& prog, const Config& cfg, const ChunkGeometry& ge * buffer would have no arena to land in. */ for (const RankIO& r : ranks_) if (!r.prog) return RAD_E_INVAL; + RAD_TRY(layout(prog, cfg)); + RAD_TRY(alloc_set(set_, prog.kv_groups)); + out_next_ = 0; + out_last_ = -1; + if (mm_on_) RAD_TRY(alloc_media()); + + /* THE RESERVATION AND WHAT ACTUALLY CROSSES ARE DIFFERENT NUMBERS, so the line says both. + * Nearly all of the slab is block-table rectangles carved for the worst step, and a step + * copies only the rows it filled -- an operator reading the reservation alone would price + * the per-step cost far above what it is. */ + RAD_INFO("step batch: %s pinned staging ring + %s device slab a rank, %d KV group(s), " + "%d derived buffer(s); of the slab, %s is block tables carved for the worst step " + "and only the filled rows cross", + humanb(ring_.bytes).c_str(), humanb(set_.dev_bytes).c_str(), + (int)prog.kv_groups.size(), (int)derived_.size(), + humanb(set_.dev_bytes - set_.bt_base).c_str()); + return RAD_OK; +} + +/* WHAT init() WILL ALLOCATE ON EVERY RANK'S CARD, before any of it exists: the VRAM budget is + * resolved before the builder is, and a reservation it does not charge comes out of + * --gpu-headroom-mib -- the room a kernel's first launch allocates from, where running out is a + * fault inside the HIP runtime rather than an error. The slab's block tables grow with + * --max-num-seqs and the media staging with --max-num-batched-tokens, so neither is small enough + * to leave to the headroom. The same layout() and carve walk as init(), so the two cannot drift. */ +int64_t BatchBuilder::device_bytes(Program& prog, const Config& cfg, const KVGeom& kvg) { + BatchBuilder b; + b.prog_ = &prog; + b.cfg_ = cfg; + b.kvgeom_ = kvg; + if (b.layout(prog, cfg) < 0) return -1; + b.size_set(b.set_, prog.kv_groups); + const MediaBytes m = b.mm_on_ ? b.media_bytes() : MediaBytes{}; + return b.set_.dev_bytes + m.mm + m.pix + m.crd + m.cu; +} + +int BatchBuilder::layout(Program& prog, const Config& cfg) { max_tok_ = cfg.max_tok; max_seqs_ = cfg.max_seqs; @@ -456,36 +496,28 @@ int BatchBuilder::init(Program& prog, const Config& cfg, const ChunkGeometry& ge }); mm_on_ = prog.encoder.modalities != 0; - RAD_TRY(alloc_set(set_, prog.kv_groups)); - out_next_ = 0; - out_last_ = -1; - if (mm_on_) RAD_TRY(alloc_media()); - - /* THE RESERVATION AND WHAT ACTUALLY CROSSES ARE DIFFERENT NUMBERS, so the line says both. - * Nearly all of the slab is block-table rectangles carved for the worst step, and a step - * copies only the rows it filled -- an operator reading the reservation alone would price - * the per-step cost far above what it is. */ - RAD_INFO("step batch: %s pinned staging ring + %s device slab a rank, %d KV group(s), " - "%d derived buffer(s); of the slab, %s is block tables carved for the worst step " - "and only the filled rows cross", - humanb(ring_.bytes).c_str(), humanb(set_.dev_bytes).c_str(), - (int)prog.kv_groups.size(), (int)derived_.size(), - humanb(set_.dev_bytes - set_.bt_base).c_str()); return RAD_OK; } /* ------------------------------------------------------------------ media staging */ -int BatchBuilder::alloc_media() { +BatchBuilder::MediaBytes BatchBuilder::media_bytes() { const RadEncoderDecl& e = prog_->encoder; n_embd_ = e.n_embd; enc_patches_ = e.max_patches; enc_dim_ = e.patch_dim; /* The most segments one pass can hold: a segment is at least one output row, `merge` patches. */ enc_segs_ = e.max_patches / (e.merge > 0 ? e.merge : 1) + 1; - const int64_t mm_bytes = max_tok_ * n_embd_ * (int64_t)sizeof(uint16_t); - const int64_t pix_bytes = enc_patches_ * enc_dim_ * (int64_t)sizeof(uint16_t); - const int64_t crd_bytes = 4 * enc_patches_ * (int64_t)sizeof(int32_t); - const int64_t cu_bytes = (enc_segs_ + 1) * (int64_t)sizeof(int32_t); + MediaBytes m; + m.mm = max_tok_ * n_embd_ * (int64_t)sizeof(uint16_t); + m.pix = enc_patches_ * enc_dim_ * (int64_t)sizeof(uint16_t); + m.crd = 4 * enc_patches_ * (int64_t)sizeof(int32_t); + m.cu = (enc_segs_ + 1) * (int64_t)sizeof(int32_t); + return m; +} + +int BatchBuilder::alloc_media() { + const MediaBytes m = media_bytes(); + const int64_t mm_bytes = m.mm, pix_bytes = m.pix, crd_bytes = m.crd, cu_bytes = m.cu; mm_dev_.assign(ranks_.size(), nullptr); enc_pix_dev_.assign(ranks_.size(), nullptr); enc_coord_dev_.assign(ranks_.size(), nullptr); diff --git a/core/sched/batch.h b/core/sched/batch.h index d9b7633d..bfacbfcb 100644 --- a/core/sched/batch.h +++ b/core/sched/batch.h @@ -132,6 +132,11 @@ public: const KVGeom& kvg, const std::vector& ranks); void fini(); + /* The bytes init() allocates on each rank's card -- the step slab and, with an encoder, the + * media staging -- computed without allocating, for the VRAM budget. -1 when the program is + * one init() would refuse. */ + static int64_t device_bytes(Program& prog, const Config& cfg, const KVGeom& kvg); + /* Build the batch for this step. The returned pointer is stable until the kOut-th next call * and is the pointer the rank threads share -- because the ranks share an address space, the * batch is shared by pointer rather than broadcast (spec §1). Null on a device failure, which @@ -365,6 +370,8 @@ private: int32_t* enc_coord_host_ = nullptr; int32_t* enc_cu_host_ = nullptr; int64_t last_n_tok_ = 0; + struct MediaBytes { int64_t mm = 0, pix = 0, crd = 0, cu = 0; }; + MediaBytes media_bytes(); /* the four device regions alloc_media reserves, per rank */ int alloc_media(); void free_media(); /* The encoder rows of one entry: the media tokens among its positions, their rows copied into @@ -372,6 +379,10 @@ private: int64_t stage_mm_rows(const StepEntry& e, int64_t k, int64_t shift, int64_t n_rows, int32_t* rows); + /* The members init() derives from the program and the config, allocating nothing. */ + int layout(Program& prog, const Config& cfg); + /* The set's groups and its carve with no base: dev_bytes and host_bytes, nothing reserved. */ + void size_set(Set& s, const std::vector& groups); int alloc_set(Set& s, const std::vector& groups); void free_set(Set& s); /* Point every h_* at host staging based at `base`, and every d_* at rank 0's slab. */ diff --git a/core/text/chatfmt.cpp b/core/text/chatfmt.cpp index a00f0c93..2f7f69bb 100644 --- a/core/text/chatfmt.cpp +++ b/core/text/chatfmt.cpp @@ -640,6 +640,12 @@ int chat_format_grammar(const ChatFormat& f, const ChatGrammarRequest& req, Chat std::vector req_arms, opt_arms; for (const auto& [pname, pschema] : properties.items()) { + /* An optional argument no value satisfies -- `false`, or `{"not": {}}`, an + * Arktype or TypeBox `never` -- is one no call writes, so it gets no arm; a + * model that writes it anyway reaches the undeclared arm below. The template + * path does the same (vendor/patches/0012); required, it goes through the + * schema and is refused there by name. */ + if (!required.count(pname) && info.unsatisfiable(pschema)) continue; G value; if (f.other_value != ChatValue::Json || info.resolves_to_string(pschema)) { value = wrap(rule_ref("until-suffix")); diff --git a/deploy/compose/minicpm5-2b-bf16.yaml b/deploy/compose/minicpm5-2b-bf16.yaml index 3b8fc69e..d29d3a19 100644 --- a/deploy/compose/minicpm5-2b-bf16.yaml +++ b/deploy/compose/minicpm5-2b-bf16.yaml @@ -8,5 +8,5 @@ services: command: > --model /models/minicpm5-2b-bf16.rad --host :: --port ${PORT:-8000} --api-key ${RADIANCE_API_KEY:?set RADIANCE_API_KEY in .env} - --tp 2 --max-num-seqs 8 --max-model-len 131072 --kv-cache-dtype fp8 + --tp 2 --max-num-seqs 32 --max-model-len 131072 --kv-cache-dtype fp8 --gpu-headroom-mib 160 --max-num-batched-tokens 512 diff --git a/deploy/compose/minicpm5-2b.yaml b/deploy/compose/minicpm5-2b.yaml index 2110b287..fc3d26c8 100644 --- a/deploy/compose/minicpm5-2b.yaml +++ b/deploy/compose/minicpm5-2b.yaml @@ -8,5 +8,5 @@ services: command: > --model /models/minicpm5-2b-fp8.rad --host :: --port ${PORT:-8000} --api-key ${RADIANCE_API_KEY:?set RADIANCE_API_KEY in .env} - --tp 2 --max-num-seqs 8 --max-model-len 131072 --kv-cache-dtype fp8 + --tp 2 --max-num-seqs 32 --max-model-len 131072 --kv-cache-dtype fp8 --gpu-headroom-mib 160 --max-num-batched-tokens 512 diff --git a/deploy/compose/qwen3.6-35b-a3b.yaml b/deploy/compose/qwen3.6-35b-a3b.yaml index fc93c97c..74c37da1 100644 --- a/deploy/compose/qwen3.6-35b-a3b.yaml +++ b/deploy/compose/qwen3.6-35b-a3b.yaml @@ -7,4 +7,4 @@ services: command: > --model /models/qwen3.6-35b-a3b-fp8.rad --host :: --port ${PORT:-8000} --api-key ${RADIANCE_API_KEY:?set RADIANCE_API_KEY in .env} - --tp 2 --max-num-seqs 8 --max-model-len 200000 --kv-cache-dtype fp8 + --tp 2 --max-num-seqs 32 --max-model-len 200000 --kv-cache-dtype fp8 diff --git a/deploy/compose/qwen3.8-27b-fp8.yaml b/deploy/compose/qwen3.8-27b-fp8.yaml index 098f24fd..7fff4e97 100644 --- a/deploy/compose/qwen3.8-27b-fp8.yaml +++ b/deploy/compose/qwen3.8-27b-fp8.yaml @@ -8,4 +8,4 @@ services: command: > --model /models/qwen3.8-27b-fp8.rad --host :: --port ${PORT:-8000} --api-key ${RADIANCE_API_KEY:?set RADIANCE_API_KEY in .env} - --tp 2 --max-num-seqs 8 --max-model-len 200000 --kv-cache-dtype fp8 + --tp 2 --max-num-seqs 32 --max-model-len 200000 --kv-cache-dtype fp8 diff --git a/docs/GUIDE.md b/docs/GUIDE.md index 452bd78b..6db4b5e4 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -530,6 +530,27 @@ Every architecture serves both widths, and the flag sets every attention cache o a drafter's (DSpark, DFlash2) as well as the trunk's. The delta-net state and the QSA indexer's key tail are recurrent state rather than an attention cache and keep their own widths. +**Many sequences against a long context.** `--max-num-seqs` runs to 32 on every model here, and +what it costs is not context — a sequence holds only the blocks its tokens occupy — but what exists +per sequence whether it is used or not: + +- **Recurrent state.** On a hybrid model every sequence owns its delta-net state, and with + speculation two copies of it. Qwen3.8-Flash-Next keeps 54 MiB a copy on each card, so 32 + sequences take 3.4 GiB of the cache share before a single token is cached. At + `--expert-vs-cache-ratio 0.82` the attention cache then holds about 116K tokens, less than one + 200K request, and startup warns that a longer one would be refused; 0.78 brings it back, and the + experts it moves off the card cost single-stream decode about 15%. The 27B in bf16 lands at + 117K the same way. The 27B in FP8 holds 2.8 full-length sessions at 32, the 35B-A3B ten. +- **Block tables.** The step batch's tables are carved for every sequence at the full context. + They are charged to the VRAM budget (`step staging` in the startup receipt), so they come out of + the cache share and not out of `--gpu-headroom-mib`. + +The startup line `the pool backs N% of the worst case ... M full-length sessions` counts only the +part of the pool that holds context, so M is the number to compare with the sessions you expect +to keep live. With `--tp-wire wht6`, a decode step above the row count startup names is +all-reduced lossily like a prefill chunk, which a busy step reaches: at 8 sequences and depth 3, +Flash-Next's decode steps are already over it. + ### 4.5 Prefill speed: the chunk A long prompt is prefilled in chunks, and `--max-num-batched-tokens` is how big one is. It is the @@ -786,8 +807,10 @@ radiance --model m.rad --reasoning-effort medium | `--host ADDR` | 0.0.0.0 | listen address | | `--port N` | 8000 | listen port | | `--api-key KEY` | — | require `Authorization: Bearer KEY` on every request but `/health`, `/ping` and the dashboard page (§6.6) | +| `--served-model-name NAME` | container's name | the model id `/v1/models` lists, the metrics carry and a response names when its request named none. A request may name any model; the one loaded serves it | | `--mm-max-patches N` | auto | patches one vision-encoder pass carries, and so the largest image (a patch is 16x16 pixels). `auto` is 16384 when the container carries a vision tower; 0 serves text only and keeps the tower off the card | | `--generation-config PATH` | — | sampler defaults from a `generation_config.json` | +| `--override-chat-template PATH` | container's | a Jinja chat template file served in place of the one the container carries. The reply format (reasoning markers, tool calls) is derived from it too, unless the architecture plugin declares one. An unreadable or empty file stops startup | | `--temp F`, `--top-k N`, `--top-p F`, `--min-p F` | from container | sampler defaults | | `--reasoning-effort S` | template's own | default `reasoning_effort` for chat | @@ -905,6 +928,11 @@ Calls come back in `message.tool_calls` with `finish_reason: "tool_calls"`. No ` exactly that, including on raw streamed fragments — content cannot be retracted once sent, so a repair applied at the end is not a fix. +A tool's `parameters` schema shapes the grammar the call is written under. A property whose schema +accepts no value — `false`, or `{"not": {}}`, which is how TypeBox and Arktype export `never` — is +an argument no call writes. Any other `not` is refused with a 400 naming it: the grammar cannot +express a complement, and dropping the constraint silently would serve a call the tool forbids. + ### 5.5 Constrained output ```sh @@ -974,7 +1002,7 @@ curl -s http://localhost:8000/detokenize -H 'Content-Type: application/json' \ | `xtc_probability`, `xtc_threshold` | | | `dry_multiplier`, `dry_base`, `dry_allowed_length`, `dry_penalty_last_n`, `dry_sequence_breakers` | | | `seed` | absent means "pick one" — **not** seed 0 | -| `n` | 1–8. Fan-out over the same prompt; the prefix cache makes it nearly free after the first | +| `n` | 1 to the larger of 8 and `--max-num-seqs`. Fan-out over the same prompt; the prefix cache makes it nearly free after the first | | `priority` | | | `stop` | a string or an array | | `ignore_eos` | generate to `max_tokens` whatever the model emits | diff --git a/spec.md b/spec.md index 2c5a16e9..9326d3a9 100644 --- a/spec.md +++ b/spec.md @@ -968,6 +968,7 @@ and what is left is spent in **two steps**, because only one of the two is a tra card total 31.86 GiB the part's totalGlobalMem already held 442.84 MiB MEASURED once, after every plugin's code object is resident activation arena 144.47 MiB computed from the buffer plan, by the call that allocates it + step staging 18.02 MiB the step batch's block tables and media staging, the same walk --gpu-headroom-mib 96.00 MiB stated ------------------------------ claimable 31.19 GiB @@ -1018,7 +1019,7 @@ The mover works inside its own slab and cannot evict a KV block to promote an ex **What the budget cannot compute, it measures and reports.** `Engine::start` reads the card back once everything has allocated and says what settled there against what `--gpu-headroom-mib` asked to keep. The engine's own device allocations are ledgered (`rad_dev_alloc_totals`) and are, on a -served model, exactly the two pools plus the activation arena; the difference between that and the +served model, exactly the two pools, the activation arena and the step staging; the difference between that and the card is the driver's context, its code objects, and any kernel plugin that calls `hipMalloc` for itself. That difference is the one thing the headroom exists to cover, and it is printed rather than assumed. diff --git a/tests/chatparse_test.cpp b/tests/chatparse_test.cpp index ee513c0f..3f27b0e3 100644 --- a/tests/chatparse_test.cpp +++ b/tests/chatparse_test.cpp @@ -885,6 +885,37 @@ TEST(a_declared_format_reads_and_constrains_like_the_derived_one) { CHECK_EQ(g.text, b->prompt().grammar); } +/* oh-my-pi's `task` tool in its batch form: `"model?": "never"`, which Arktype exports as + * `{"not": {}}`. A schema no value satisfies needs no arm, and the declared format and the derived + * one agree about that as they agree about everything else. Before, both refused the tool and the + * request with it. */ +TEST(an_argument_no_value_satisfies_has_no_arm_in_either_grammar) { + const json tools = json::parse(R"([{"type":"function","function":{"name":"task", + "description":"Spawn subagents.","parameters":{"type":"object","properties":{ + "context":{"type":"string"},"model":{"not":{}}, + "tasks":{"type":"array","items":{"type":"object","properties":{ + "agent":{"type":"string"},"task":{"type":"string"},"solutionSpace":{"type":"string"}, + "model":{"anyOf":[{"type":"string"},{"type":"array","items":{"type":"string"}}]}}, + "required":["agent","solutionSpace","task"]}}}, + "required":["context","tasks"]}}}])"); + RadChatFormat c = qwen_abi(); + ChatFormat declared; + std::string why; + CHECK_OK(chat_format_from_abi(&c, &declared, &why)); + ChatGrammarRequest gq; + gq.tools = &tools; + ChatGrammar g; + CHECK_OK(chat_format_grammar(declared, gq, &g, &why)); + CHECK(!g.text.empty()); + CHECK(g.text.find("task-arg-model") == std::string::npos); + + Bench* b = bench(models()[0], ChatRequest{}, tools); + if (!b) return; + gq.generation_prompt = b->prompt().generation_prompt; + CHECK_OK(chat_format_grammar(declared, gq, &g, &why)); + CHECK_EQ(g.text, b->prompt().grammar); +} + /* THE STRUCT GROWS AT ITS END. A plugin built against a header with fewer fields reports a smaller * struct_size, and the fields past it read as zero; one built against a larger header has its * extra fields ignored. Nothing is read past what the plugin said it has. */ diff --git a/tests/config_test.cpp b/tests/config_test.cpp index 479e0537..c188b412 100644 --- a/tests/config_test.cpp +++ b/tests/config_test.cpp @@ -198,7 +198,9 @@ TEST(the_paths_and_names_reach_their_fields) { "--placement", "expert_tiered", "--host", "0.0.0.0", "--generation-config", "/g.json", - "--reasoning-effort", "medium" }, &c), RAD_OK); + "--reasoning-effort", "medium", + "--served-model-name", "qwen-coder", + "--override-chat-template", "/t.jinja" }, &c), RAD_OK); CHECK_EQ(c.radiance_home, std::string("/rh")); CHECK(c.weights_disk_tier); CHECK_EQ(c.prefix_cache_dir, std::string("/kvdir")); @@ -206,6 +208,8 @@ TEST(the_paths_and_names_reach_their_fields) { CHECK_EQ(c.host, std::string("0.0.0.0")); CHECK_EQ(c.generation_config, std::string("/g.json")); CHECK_EQ(c.reasoning_effort, std::string("medium")); + CHECK_EQ(c.served_model_name, std::string("qwen-coder")); + CHECK_EQ(c.override_chat_template, std::string("/t.jinja")); } TEST(the_boolean_flags_are_off_until_they_are_given) { diff --git a/tests/gbnf_test.cpp b/tests/gbnf_test.cpp index 78292354..e4ae1a6e 100644 --- a/tests/gbnf_test.cpp +++ b/tests/gbnf_test.cpp @@ -764,6 +764,92 @@ TEST(gbnf_json_schema_grammars_agree_with_the_oracle) { CHECK(t.masks > 1200); } +/* A SCHEMA NO VALUE SATISFIES, which vendor/patches/0012 represents rather than refuses. oh-my-pi's + * `task` tool declares `"model?": "never"` in its batch form and Arktype exports that as + * `{"not": {}}`, the same schema as JSON Schema's `false`. Refused, it failed the tool-call grammar + * of every request that carried the tool. Represented, it is a key the object never holds. */ +TEST(gbnf_a_property_no_value_satisfies_is_a_key_never_written) { + auto bv = bpe_like(23, 1500); + /* A whole value, from a fresh grammar: every byte taken and the parse at an end. */ + auto whole = [&](const std::string& gbnf, const std::string& text) { + std::unique_ptr g; + std::string err; + if (GbnfGrammar::create(gbnf, "root", &bv->v, false, {}, {}, &g, &err) < 0) return false; + return g->accept_str(text) >= 0 && g->complete(); + }; + + for (const char* never : { "{\"not\":{}}", "false" }) { + const std::string schema = std::string("{\"type\":\"object\",\"properties\":{" + "\"context\":{\"type\":\"string\"},\"model\":") + + never + "},\"required\":[\"context\"]}"; + std::string gbnf, err; + CHECK_OK(grammar_from_json_schema(schema, "root", &gbnf, &err)); + CHECK(whole(gbnf, "{\"context\": \"x\"}")); + CHECK(!whole(gbnf, "{\"context\": \"x\", \"model\": \"y\"}")); + CHECK(!whole(gbnf, "{\"model\": \"y\", \"context\": \"x\"}")); + } + + /* additionalProperties must not readmit the key with a value of its own. */ + { + std::string gbnf, err; + CHECK_OK(grammar_from_json_schema( + R"({"type":"object","properties":{"model":{"not":{}}},"additionalProperties":true})", + "root", &gbnf, &err)); + CHECK(whole(gbnf, "{\"other\": 1}")); + CHECK(!whole(gbnf, "{\"model\": 1}")); + } + + /* A union alternative of that kind contributes nothing to the union. */ + { + std::string gbnf, err; + CHECK_OK(grammar_from_json_schema(R"({"anyOf":[{"type":"string"},{"not":{}}]})", "root", + &gbnf, &err)); + CHECK(whole(gbnf, "\"a\"")); + CHECK(!whole(gbnf, "1")); + } + + /* Where a value is required there is nothing to write, and that is refused by name. */ + for (const char* schema : { + R"({"type":"object","properties":{"model":{"not":{}}},"required":["model"]})", + R"({"not":{}})", + R"({"anyOf":[{"not":{}},false]})" }) { + std::string gbnf, err; + CHECK(grammar_from_json_schema(schema, "root", &gbnf, &err) < 0); + CHECK(!err.empty()); + } + + /* And the tool as oh-my-pi sends it, through each served template's tool-call grammar. */ + const char* tools = R"([{"type":"function","function":{"name":"task", + "description":"Spawn subagents.","parameters":{"type":"object","properties":{ + "context":{"type":"string"},"model":{"not":{}}, + "tasks":{"type":"array","items":{"type":"object","properties":{ + "name":{"type":"string"},"agent":{"type":"string","default":"task"}, + "task":{"type":"string"},"solutionSpace":{"type":"string"}, + "model":{"anyOf":[{"type":"string"},{"type":"array","items":{"type":"string"}}]}, + "schemaMode":{"enum":["permissive","strict"]}, + "tools":{"type":"array","items":{"type":"string"}}}, + "required":["agent","solutionSpace","task"]}}}, + "required":["context","tasks"]}}}])"; + const ojson messages = ojson::array({ ojson{ { "role", "user" }, { "content", "hi" } } }); + /* "auto" is the choice the server serves (it refuses "required"), with parallel calls on -- + * the server's default -- and off. Under "auto" a template may leave the reply unconstrained + * and produce no grammar at all; what must not happen is a refusal. */ + int built = 0; + for (const TemplateCase& tc : kTemplates) { + ChatTemplate ct; + REQUIRE(ct.load(slurp(fixture(tc.file)), tc.bos, tc.eos) >= 0); + for (int par = 0; par < 2; ++par) { + ChatOptions opt; + opt.tool_choice = "auto"; + opt.parallel_tool_calls = par != 0; + ChatPrompt cp; + CHECK(ct.apply(messages, ojson::parse(tools), opt, &cp) >= 0); + if (!cp.grammar.empty()) ++built; + } + } + CHECK(built >= 3); +} + /* The grammars a chat template writes for its own tool-call syntax, from the three templates the * engine serves: walked, and replayed over four agent calls wherever the syntax is the one the * calls are written in. */ diff --git a/vendor/UPSTREAM b/vendor/UPSTREAM index c07494af..9462f63d 100644 --- a/vendor/UPSTREAM +++ b/vendor/UPSTREAM @@ -97,6 +97,7 @@ vendor/llama/common/regex-partial.{h,cpp} <- llama.cpp common/* patches/0008-autoparser-tagged-calls-separate-on-space-and-named-args-in-any-order.patch patches/0009-chat-a-cdata-section-is-punctuation-not-content.patch patches/0011-chat-add_bos-must-come-from-the-inputs.patch + patches/0012-json-schema-a-schema-no-value-satisfies.patch On 0003: a `pattern` in a `response_format` reaches _visit_pattern() as client data, and three of its paths do not survive that. `front()`/`back()` run on an empty string; `seq.back()` runs @@ -414,3 +415,20 @@ PATCH SERIES common_chat_format_example -- assign `inputs.add_bos = tmpls->add_bos` immediately before calling apply, which is the redundancy you would expect if apply were meant to read the inputs. The fix ORs the two, so those two callers behave exactly as before. + + patches/0012-json-schema-a-schema-no-value-satisfies.patch + + oh-my-pi's `task` tool declares `"model?": "never"` in its batch form, and Arktype exports + `never` as `{"not": {}}` -- as TypeBox does Type.Never. 0004 refuses `not` outright, so the + tool-call grammar for every request carrying that tool failed to build and the request with + it. `not` of the empty schema is not a constraint that has to be complemented: it makes the + schema unsatisfiable, the same schema as `false`, and that is exactly representable where it + occurs. An object property of that kind is a key the object never carries -- no rule, and + its name kept out of an additionalProperties rule -- and a union alternative of that kind is + dropped. The tagged-argument builders (chat-auto-parser-generator.cpp, and chat.cpp's + `string="true|false"` format), which give every argument an arm of its own and so never see + the object, give an optional one of that kind no arm; a model that writes it reaches the + undeclared-argument arm of 0010 where the format has one. core/text/chatfmt.cpp, the + declared-format grammar, does the same outside this tree. Where a value is required (a required property, the root, an array's items, a union + with no alternative left) it is still refused, by name. Every other `not` is refused as 0004 + refuses it. diff --git a/vendor/llama/common/chat-auto-parser-generator.cpp b/vendor/llama/common/chat-auto-parser-generator.cpp index b682578c..71520dbf 100644 --- a/vendor/llama/common/chat-auto-parser-generator.cpp +++ b/vendor/llama/common/chat-auto-parser-generator.cpp @@ -447,6 +447,17 @@ common_peg_parser analyze_tools::build_tool_parser_tag_tagged(parser_build_conte for (const auto & [param_name, param_schema] : properties.items()) { bool is_required = required.find(param_name) != required.end(); + /* RADIANCE: AN OPTIONAL ARGUMENT NO VALUE SATISFIES IS ONE NO CALL WRITES -- an + * Arktype "never", exported as `{"not": {}}` (oh-my-pi's `task` tool declares its batch + * form's `model` so). It gets no arm: a schema-checked arm for it is a grammar for a + * value that does not exist, and the converter refuses to build one. A model that + * writes it anyway reaches the undeclared-argument arm below, as any name outside the + * schema does, and the tool says what is wrong. Required, it goes through the schema + * and is refused there by name. */ + if (!is_required && schema_info.unsatisfiable(param_schema)) { + continue; + } + /* RADIANCE: A NON-STRING ARGUMENT THAT IS NOT VALID JSON IS STILL AN ARGUMENT. * * An array or object parameter is matched by a schema-constrained JSON parser, and diff --git a/vendor/llama/common/chat.cpp b/vendor/llama/common/chat.cpp index 13981528..5bc91ebd 100644 --- a/vendor/llama/common/chat.cpp +++ b/vendor/llama/common/chat.cpp @@ -1955,6 +1955,11 @@ static common_chat_params common_chat_params_init_deepseek_v3_2(const common_cha std::vector optional_parsers; for (const auto & [param_name, param_schema] : props.items()) { bool is_required = required.find(param_name) != required.end(); + // RADIANCE: an optional argument no value satisfies is one no call writes, so it + // gets no arm (see chat-auto-parser-generator.cpp); required, it is refused by name. + if (!is_required && schema_info.unsatisfiable(param_schema)) { + continue; + } bool is_string = schema_info.resolves_to_string(param_schema); auto arg = p.tool_arg( diff --git a/vendor/llama/common/json-schema-to-grammar.cpp b/vendor/llama/common/json-schema-to-grammar.cpp index ccf857a5..95640fb1 100644 --- a/vendor/llama/common/json-schema-to-grammar.cpp +++ b/vendor/llama/common/json-schema-to-grammar.cpp @@ -697,6 +697,19 @@ private: const auto &prop_name = kv.first; const auto &prop_schema = kv.second; + // RADIANCE: a property no value satisfies is a key the object never carries, which the + // grammar states exactly by having no rule for it. Its name stays in prop_names, so an + // additionalProperties rule cannot readmit the key with a value of its own. Required, + // it makes the whole object unsatisfiable, and that is refused. + if (is_unsatisfiable(prop_schema)) { + if (required.find(prop_name) != required.end()) { + _errors.push_back("Property \"" + prop_name + "\" is required, but its schema " + "accepts no value"); + } + prop_names.push_back(prop_name); + continue; + } + std::string prop_rule_name = visit(prop_schema, name + (name.empty() ? "" : "-") + prop_name); prop_kv_rule_names[prop_name] = _add_rule( name + (name.empty() ? "" : "-") + prop_name + "-kv", @@ -887,6 +900,17 @@ public: visit_refs(schema); } + // RADIANCE: the schema no value satisfies. JSON Schema spells it `false`, and `{"not": {}}` -- + // which is how TypeBox's Type.Never and Arktype's "never" are exported, the latter as an + // optional property no call may set. A `not` of the empty schema makes its whole schema + // unsatisfiable whatever sits beside it, so the sibling keywords do not matter. + static bool is_unsatisfiable(const json & schema) { + if (schema.is_boolean()) return !schema.get(); + if (!schema.is_object() || !schema.contains("not")) return false; + const json & n = schema["not"]; + return (n.is_object() && n.empty()) || (n.is_boolean() && n.get()); + } + static std::string _generate_constant_rule(const json & value) { return format_literal(value.dump()); } @@ -896,9 +920,19 @@ public: std::string schema_format = schema.contains("format") ? schema["format"].get() : ""; std::string rule_name = is_reserved_name(name) ? name + "-" : name.empty() ? "root" : name; - // RADIANCE: "not" has no case below, so it falls through to a rule that accepts anything - // -- a constraint the caller asked for, did not get, and is not told about. Complementing - // a regular language is representable but the blowup is real; refusing beats pretending. + // RADIANCE: an unsatisfiable schema in a place that must hold a value -- the root, an array's + // items, a $ref target -- has no grammar: GBNF has no empty language to give it. An object + // property and a union alternative of this kind are handled where they occur. + if (is_unsatisfiable(schema)) { + _errors.push_back("Schema \"" + (name.empty() ? std::string("root") : name) + "\" accepts no " + "value, where a value is required"); + return ""; + } + + // RADIANCE: any other "not" has no case below, so it would fall through to a rule that + // accepts anything -- a constraint the caller asked for, did not get, and is not told + // about. Complementing a regular language is representable but the blowup is real; + // refusing beats pretending. if (schema.is_object() && schema.contains("not")) { _errors.push_back("Unsupported schema keyword \"not\": this converter cannot " "complement a grammar, and accepting the schema without it would " @@ -911,6 +945,14 @@ public: } if (schema.contains("oneOf") || schema.contains("anyOf")) { std::vector alt_schemas = schema.contains("oneOf") ? schema["oneOf"].get>() : schema["anyOf"].get>(); + // RADIANCE: an alternative no value satisfies contributes nothing to the union. + alt_schemas.erase(std::remove_if(alt_schemas.begin(), alt_schemas.end(), is_unsatisfiable), + alt_schemas.end()); + if (alt_schemas.empty()) { + _errors.push_back("Schema \"" + (name.empty() ? std::string("root") : name) + "\": no " + "alternative of its union accepts a value"); + return ""; + } return _add_rule(rule_name, _generate_union_rule(name, alt_schemas)); } if (schema_type.is_array()) { @@ -1108,6 +1150,10 @@ void common_schema_info::resolve_refs(nlohmann::ordered_json & schema) { impl_->resolve_refs(schema, ""); } +bool common_schema_info::unsatisfiable(const nlohmann::ordered_json & schema) const { + return common_schema_converter::is_unsatisfiable(schema); +} + // Determines if a JSON schema can resolve to a string type through any path. // Some models emit raw string values rather than JSON-encoded strings for string parameters. // If any branch of the schema (via oneOf, anyOf, $ref, etc.) permits a string, this returns diff --git a/vendor/llama/common/json-schema-to-grammar.h b/vendor/llama/common/json-schema-to-grammar.h index 240d6423..86c78f3a 100644 --- a/vendor/llama/common/json-schema-to-grammar.h +++ b/vendor/llama/common/json-schema-to-grammar.h @@ -26,6 +26,8 @@ class common_schema_info { void resolve_refs(nlohmann::ordered_json & schema); bool resolves_to_string(const nlohmann::ordered_json & schema); + // RADIANCE: whether no value satisfies the schema -- `false`, or `{"not": {}}`. + bool unsatisfiable(const nlohmann::ordered_json & schema) const; }; struct common_grammar_builder { diff --git a/vendor/patches/0012-json-schema-a-schema-no-value-satisfies.patch b/vendor/patches/0012-json-schema-a-schema-no-value-satisfies.patch new file mode 100644 index 00000000..c11041cb --- /dev/null +++ b/vendor/patches/0012-json-schema-a-schema-no-value-satisfies.patch @@ -0,0 +1,142 @@ +diff --git a/common/chat-auto-parser-generator.cpp b/common/chat-auto-parser-generator.cpp +index b682578..71520db 100644 +--- a/common/chat-auto-parser-generator.cpp ++++ b/common/chat-auto-parser-generator.cpp +@@ -447,6 +447,17 @@ common_peg_parser analyze_tools::build_tool_parser_tag_tagged(parser_build_conte + for (const auto & [param_name, param_schema] : properties.items()) { + bool is_required = required.find(param_name) != required.end(); + ++ /* RADIANCE: AN OPTIONAL ARGUMENT NO VALUE SATISFIES IS ONE NO CALL WRITES -- an ++ * Arktype "never", exported as `{"not": {}}` (oh-my-pi's `task` tool declares its batch ++ * form's `model` so). It gets no arm: a schema-checked arm for it is a grammar for a ++ * value that does not exist, and the converter refuses to build one. A model that ++ * writes it anyway reaches the undeclared-argument arm below, as any name outside the ++ * schema does, and the tool says what is wrong. Required, it goes through the schema ++ * and is refused there by name. */ ++ if (!is_required && schema_info.unsatisfiable(param_schema)) { ++ continue; ++ } ++ + /* RADIANCE: A NON-STRING ARGUMENT THAT IS NOT VALID JSON IS STILL AN ARGUMENT. + * + * An array or object parameter is matched by a schema-constrained JSON parser, and +diff --git a/common/chat.cpp b/common/chat.cpp +index 1398152..5bc91eb 100644 +--- a/common/chat.cpp ++++ b/common/chat.cpp +@@ -1955,6 +1955,11 @@ static common_chat_params common_chat_params_init_deepseek_v3_2(const common_cha + std::vector optional_parsers; + for (const auto & [param_name, param_schema] : props.items()) { + bool is_required = required.find(param_name) != required.end(); ++ // RADIANCE: an optional argument no value satisfies is one no call writes, so it ++ // gets no arm (see chat-auto-parser-generator.cpp); required, it is refused by name. ++ if (!is_required && schema_info.unsatisfiable(param_schema)) { ++ continue; ++ } + bool is_string = schema_info.resolves_to_string(param_schema); + + auto arg = p.tool_arg( +diff --git a/common/json-schema-to-grammar.cpp b/common/json-schema-to-grammar.cpp +index ccf857a..95640fb 100644 +--- a/common/json-schema-to-grammar.cpp ++++ b/common/json-schema-to-grammar.cpp +@@ -697,6 +697,19 @@ private: + const auto &prop_name = kv.first; + const auto &prop_schema = kv.second; + ++ // RADIANCE: a property no value satisfies is a key the object never carries, which the ++ // grammar states exactly by having no rule for it. Its name stays in prop_names, so an ++ // additionalProperties rule cannot readmit the key with a value of its own. Required, ++ // it makes the whole object unsatisfiable, and that is refused. ++ if (is_unsatisfiable(prop_schema)) { ++ if (required.find(prop_name) != required.end()) { ++ _errors.push_back("Property \"" + prop_name + "\" is required, but its schema " ++ "accepts no value"); ++ } ++ prop_names.push_back(prop_name); ++ continue; ++ } ++ + std::string prop_rule_name = visit(prop_schema, name + (name.empty() ? "" : "-") + prop_name); + prop_kv_rule_names[prop_name] = _add_rule( + name + (name.empty() ? "" : "-") + prop_name + "-kv", +@@ -887,6 +900,17 @@ public: + visit_refs(schema); + } + ++ // RADIANCE: the schema no value satisfies. JSON Schema spells it `false`, and `{"not": {}}` -- ++ // which is how TypeBox's Type.Never and Arktype's "never" are exported, the latter as an ++ // optional property no call may set. A `not` of the empty schema makes its whole schema ++ // unsatisfiable whatever sits beside it, so the sibling keywords do not matter. ++ static bool is_unsatisfiable(const json & schema) { ++ if (schema.is_boolean()) return !schema.get(); ++ if (!schema.is_object() || !schema.contains("not")) return false; ++ const json & n = schema["not"]; ++ return (n.is_object() && n.empty()) || (n.is_boolean() && n.get()); ++ } ++ + static std::string _generate_constant_rule(const json & value) { + return format_literal(value.dump()); + } +@@ -896,9 +920,19 @@ public: + std::string schema_format = schema.contains("format") ? schema["format"].get() : ""; + std::string rule_name = is_reserved_name(name) ? name + "-" : name.empty() ? "root" : name; + +- // RADIANCE: "not" has no case below, so it falls through to a rule that accepts anything +- // -- a constraint the caller asked for, did not get, and is not told about. Complementing +- // a regular language is representable but the blowup is real; refusing beats pretending. ++ // RADIANCE: an unsatisfiable schema in a place that must hold a value -- the root, an array's ++ // items, a $ref target -- has no grammar: GBNF has no empty language to give it. An object ++ // property and a union alternative of this kind are handled where they occur. ++ if (is_unsatisfiable(schema)) { ++ _errors.push_back("Schema \"" + (name.empty() ? std::string("root") : name) + "\" accepts no " ++ "value, where a value is required"); ++ return ""; ++ } ++ ++ // RADIANCE: any other "not" has no case below, so it would fall through to a rule that ++ // accepts anything -- a constraint the caller asked for, did not get, and is not told ++ // about. Complementing a regular language is representable but the blowup is real; ++ // refusing beats pretending. + if (schema.is_object() && schema.contains("not")) { + _errors.push_back("Unsupported schema keyword \"not\": this converter cannot " + "complement a grammar, and accepting the schema without it would " +@@ -911,6 +945,14 @@ public: + } + if (schema.contains("oneOf") || schema.contains("anyOf")) { + std::vector alt_schemas = schema.contains("oneOf") ? schema["oneOf"].get>() : schema["anyOf"].get>(); ++ // RADIANCE: an alternative no value satisfies contributes nothing to the union. ++ alt_schemas.erase(std::remove_if(alt_schemas.begin(), alt_schemas.end(), is_unsatisfiable), ++ alt_schemas.end()); ++ if (alt_schemas.empty()) { ++ _errors.push_back("Schema \"" + (name.empty() ? std::string("root") : name) + "\": no " ++ "alternative of its union accepts a value"); ++ return ""; ++ } + return _add_rule(rule_name, _generate_union_rule(name, alt_schemas)); + } + if (schema_type.is_array()) { +@@ -1108,6 +1150,10 @@ void common_schema_info::resolve_refs(nlohmann::ordered_json & schema) { + impl_->resolve_refs(schema, ""); + } + ++bool common_schema_info::unsatisfiable(const nlohmann::ordered_json & schema) const { ++ return common_schema_converter::is_unsatisfiable(schema); ++} ++ + // Determines if a JSON schema can resolve to a string type through any path. + // Some models emit raw string values rather than JSON-encoded strings for string parameters. + // If any branch of the schema (via oneOf, anyOf, $ref, etc.) permits a string, this returns +diff --git a/common/json-schema-to-grammar.h b/common/json-schema-to-grammar.h +index 240d642..86c78f3 100644 +--- a/common/json-schema-to-grammar.h ++++ b/common/json-schema-to-grammar.h +@@ -26,6 +26,8 @@ class common_schema_info { + + void resolve_refs(nlohmann::ordered_json & schema); + bool resolves_to_string(const nlohmann::ordered_json & schema); ++ // RADIANCE: whether no value satisfies the schema -- `false`, or `{"not": {}}`. ++ bool unsatisfiable(const nlohmann::ordered_json & schema) const; + }; + + struct common_grammar_builder {