Archived
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:
1 parent
6df26315b9
commit
966bda899a
39 files changed
+1304
-52
No files matched your search
@@ -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<ReplyParserBridge>(std::move(rp));
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -391,6 +391,13 @@ struct ChatRender {
|
||||
|
||||
/* The tokens that parser must be able to SEE. See ITokenizer::detokenizer. */
|
||||
std::vector<std::string> 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 {
|
||||
|
||||
+118
-10
@@ -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<int32_t> c = d.tok->encode(render.think_close, false, true);
|
||||
std::vector<int32_t> 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<LogprobEntry>& lp) {
|
||||
@@ -1687,7 +1792,7 @@ static json chat_logprobs_json(const std::vector<LogprobEntry>& lp) {
|
||||
}
|
||||
|
||||
std::string chat_completion_body(const OaiRequest& r, const std::vector<ChoiceOut>& 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<ChoiceOu
|
||||
o["model"] = r.model;
|
||||
o["choices"] = std::move(arr);
|
||||
o["usage"] = usage_json(u);
|
||||
if (t.valid) o["timings"] = timings_json(t);
|
||||
return o.dump();
|
||||
}
|
||||
|
||||
std::string text_completion_body(const OaiRequest& r, const std::vector<ChoiceOut>& 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::vector<ChoiceOu
|
||||
o["model"] = r.model;
|
||||
o["choices"] = std::move(arr);
|
||||
o["usage"] = usage_json(u);
|
||||
if (t.valid) o["timings"] = timings_json(t);
|
||||
return o.dump();
|
||||
}
|
||||
|
||||
@@ -1808,7 +1915,7 @@ ChatDeltaStream::ChatDeltaStream(const OaiRequest& r, int index, const IReplyPar
|
||||
: reader_(parser ? parser->open() : 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;
|
||||
}
|
||||
|
||||
|
||||
+54
-8
@@ -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<ChoiceOut>& choices,
|
||||
const UsageOut& u);
|
||||
const UsageOut& u, const TimingsOut& t = TimingsOut());
|
||||
std::string text_completion_body(const OaiRequest& r, const std::vector<ChoiceOut>& choices,
|
||||
const UsageOut& u);
|
||||
const UsageOut& u, const TimingsOut& t = TimingsOut());
|
||||
std::string embeddings_body(const OaiRequest& r, const std::vector<std::vector<float>>& 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<ReplyDelta>& ev);
|
||||
|
||||
std::unique_ptr<IReplyReader> reader_;
|
||||
|
||||
+91
-18
@@ -22,6 +22,9 @@ struct Server::Generation {
|
||||
int prompt_index = 0;
|
||||
std::string text;
|
||||
std::vector<LogprobEntry> 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<Generation>* gens, ApiEr
|
||||
g.prompt_index = (int)p;
|
||||
g.sink = std::make_shared<Sink>();
|
||||
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<Generation>& 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<Generation>& 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<Generation>& 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<Generation>& gens) {
|
||||
std::vector<const Sink*> 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<ChoiceOut> 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;
|
||||
|
||||
@@ -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<Generation>& gens);
|
||||
static TimingsOut timings_of(const Sink* const* sinks, size_t n);
|
||||
static TimingsOut timings_of(const std::vector<Generation>& gens);
|
||||
|
||||
void register_routes();
|
||||
|
||||
HttpResponse handle_chat(const HttpRequest& req);
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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<int64_t> t_first_{-1};
|
||||
std::atomic<int64_t> t_last_{-1};
|
||||
std::atomic<int64_t> t_admit_{-1};
|
||||
std::atomic<int64_t> n_draft_{0};
|
||||
std::atomic<int64_t> n_draft_acc_{0};
|
||||
int64_t t_start_ns_ = 0;
|
||||
|
||||
std::atomic<int32_t> 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<Sink*>(s)->set_prompt_stats(n_prompt, n_cached);
|
||||
}
|
||||
inline void sink_admitted(void* s) {
|
||||
if (s) static_cast<Sink*>(s)->mark_admitted();
|
||||
}
|
||||
inline void sink_drafts(void* s, int32_t n, int32_t accepted) {
|
||||
if (s) static_cast<Sink*>(s)->add_drafts(n, accepted);
|
||||
}
|
||||
|
||||
} /* namespace server */
|
||||
} /* namespace rad */
|
||||
Reference in new issue
Block a user