radiance 1.0.7

- Chat responses report usage.completion_tokens_details.reasoning_tokens: how much of
  completion_tokens was the reasoning block. A reply that ran out of max_tokens inside <think>
  now reads as that, instead of as a model that answered nothing.
- thinking_token_budget (vLLM's name; thinking_budget is read as the same field) caps the
  reasoning. At that many tokens the block is closed and the model answers from what it has
  reasoned so far. It holds under speculative decoding and at any temperature.
  --thinking-token-budget sets the default for clients that send none.
- Every completion response carries a `timings` object in llama.cpp's shape: prompt and generated
  token counts, times and rates, and the speculative tokens drafted and accepted for that request.
  It is on the buffered response, on each streamed choice's final chunk and on the usage chunk,
  so a proxy such as llama-swap can read per-request speed. /metrics stays the aggregate.
- Peer-to-peer access between the cards is checked at launch. The all-reduce kernels need it; on
  a machine where the cards cannot reach each other's memory, startup stops and names device.p2p
  instead of the first all-reduce faulting or hanging. A kernel library can require it with a
  constraint on the new "device." keys, which match the machine and not the op's parameters.
- A pool allocation the driver refuses says why, with the card's free VRAM at that moment and,
  for the host pool, the pinned memory taken against the amdgpu limit (ttm.pages_limit). Every
  rank pins its own --host-pool-mib, so --tp 2 pins it twice.
This commit is contained in:
Deadcode committed 2026-10-04 21:23:07 +02:00
1 parent 6df26315b9
commit 966bda899a
39 files changed
+1304 -52

No files matched your search

+36
View File
@@ -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<const ReplyFormat> rf;
CHECK_OK(ReplyFormat::compile(f, &rf, &why));
struct Case { const char* prompt; bool open; };
for (const Case& k : { Case{ "<|im_start|>assistant\n<think>\n", true },
Case{ "<|im_start|>assistant\n<think>\n\n</think>\n\n", false },
Case{ "<|im_start|>assistant\n", false } }) {
ReplyOptions ro;
ro.generation_prompt = k.prompt;
std::shared_ptr<const ReplyParser> rp;
CHECK_OK(ReplyParser::create(rf, ro, &rp, &why));
const ReasoningMarkers m = rp->reasoning();
CHECK_EQ(m.open, std::string("<think>"));
CHECK_EQ(m.close, std::string("</think>"));
CHECK_EQ(m.starts_open, k.open);
const ReplyMessage r = reply_parse(*rp, "x</think>\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<const ReplyParser> 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) {
+17
View File
@@ -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);
+19
View File
@@ -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) {
+30 -3
View File
@@ -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<int (*)(void)>(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()
+125
View File
@@ -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<float> lg(3 * 8, 0.0f);
for (int r = 0; r < 3; ++r) lg[(size_t)r * 8 + 1] = 5.0f;
std::vector<int32_t> 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<float> lg(2 * 8, 0.0f);
lg[1] = 40.0f;
lg[8 + 1] = 40.0f;
std::vector<int32_t> 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", "</t>" });
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<float> lg = { 9.0f, 0.0f, 0.0f, 0.0f };
std::vector<int32_t> tok;
sp.grammar = "root ::= (\"a\" | \"</t>\")+";
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()
+45
View File
@@ -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()
+263 -1
View File
@@ -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<FakeReplyParser>(!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:<name>:<json...>" -- 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<uint64_t> submitted;
SamplingParams last_sp; /* what the last submitted request was to sample with */
std::vector<uint64_t> cancelled;
std::vector<std::thread> workers;
std::atomic<uint64_t> next_id{1};
@@ -250,6 +260,7 @@ struct FakeScheduler : IScheduler {
{
std::lock_guard<std::mutex> 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<std::mutex> 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<int>(), 7);
CHECK_EQ(j["usage"]["completion_tokens_details"]["reasoning_tokens"].get<int>(), 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<int>(), 4);
}
{
Fixture f;
f.tmpl.think_close = "</t>"; /* 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<std::mutex> 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>(), std::string(c.param));
}
Fixture multi;
multi.tmpl.think_close = "</t>";
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<std::string>().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<std::string>().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>(), (int64_t)4);
CHECK_EQ(t["cache_n"].get<int64_t>(), (int64_t)4);
CHECK_EQ(t["predicted_n"].get<int64_t>(), predicted);
CHECK(t["prompt_ms"].is_number());
CHECK(t["predicted_ms"].is_number());
CHECK(t["prompt_ms"].get<double>() >= 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<int64_t>(), (predicted - 1) * 3);
CHECK_EQ(t["draft_n_accepted"].get<int64_t>(), 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<int64_t>(),
j["usage"]["completion_tokens"].get<int64_t>());
}
{
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<double>(), 2000.0, 1e-9);
CHECK_NEAR(j["prompt_per_token_ms"].get<double>(), 0.5, 1e-12);
CHECK_NEAR(j["predicted_per_second"].get<double>(), 100.0, 1e-9);
CHECK_NEAR(j["predicted_per_token_ms"].get<double>(), 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) {