OpenAI logprobs, top_logprobs and allowed_token_ids on /v1/chat/completions (#3200)

/v1/chat/completions on the CUDA and HIP engine accepted logprobs and
returned an empty choices[0].logprobs.content. Now "logprobs": true with
"top_logprobs" 0 to 20 (and the legacy "logprobs": N) returns one entry
per token with its alternatives, streamed or not, and "allowed_token_ids"
returns a distribution renormalised over exactly the ids the caller named.

Engine (src/program/generate.cpp): the GEN line takes logprobs=K and
allowed=a,b,c. After each "T id" the engine writes one "LP <logprob>
[id:logprob ...]" line from the verify window's head logits before
sampling, penalties and temperature. The SYCL engine already wrote LP
lines for logprobs=K; it now reads allowed= as well, with the same line
format. A request without logprobs reaches none of this: both call sites
are behind "req_logprobs >= 0", a local int of the request, so the default
path prints what it printed before and does no extra work per token.
Changes from the PR: the call sites are guarded instead of calling the
function for every token, the function is static, the token index is
checked against the row, and the Chinese comment is in English.

Server (serve/server.py): LP lines are read before the token is yielded
and belong to the request that asked (tagged with its cancel Event), the
entries spell the reply, json_schema replies return no logprobs rather
than a mismatching set, an allowed id past the vocabulary is a 400, and
logprobs on a --parallel server is answered for max_tokens 1 only (a
slot's BT lines carry no LP line). serve/structured.py: _extract_json is
now extract_json (the logprobs alignment uses it); the two uses added by
the #2893 retry follow the rename.

Left out: the PR's bench and result files (none in the diff). #3332 (/v1/completions) and #4056
(logprobs on it) build on this change; this one needs nothing from them.

Tests: serve.test_logprobs and serve.test_logprobs_parallel (30 tests with
the PR's), serve.test_structured, serve.test_responses: 94 tests OK.
Not covered: no model ran here. The PR author reports 28 of 28 on an RTX
5080 with MTP and on a GTX 1080 Ti; the layer-split pipelined decode path
(the first call site) was not run by anyone, and the LP values were not
compared with a CPU softmax of dumped logits.

Co-authored-by: Leonardo Murillo <4869242+leonardomurillo@users.noreply.github.com>
This commit is contained in:
xiezhipeng-gitandLeonardo Murillo authored and Niko1221 committed 2026-10-26 19:08:35 +01:00
1 parent c966d7ad89
commit 9ea044962a
7 files changed
+1132 -32

No files matched your search

+64
View File
@@ -155,6 +155,51 @@ namespace strata::metal_engine { void set_model_shard(const char* shard1); } /
#include <set>
#include <vector>
// logprobs=K / allowed=...: one `LP` line for the token just emitted, from `ver`'s head
// logits for the window row it came from (before sampling, penalties and temperature).
// Format matches the SYCL port's LP line so one server-side reader serves both.
// Called only when the request asked (`req_logprobs >= 0`): a request without logprobs never reaches it, so the
// default path does no work for this and prints exactly what it printed before.
static void emit_lp_line(const strata::core::Verifier& ver, int t, int32_t token, int k,
const std::vector<int32_t>& allowed) {
if (k < 0) return;
static std::vector<float> row;
row.resize((size_t) ver.vocab());
if (!ver.copy_logits(t, row.data()) || token < 0 || (size_t) token >= row.size()) {
std::printf("LP nan\n");
return;
}
float mx = -INFINITY;
for (const float v : row) mx = std::max(mx, v);
double se = 0.0;
for (const float v : row) se += std::exp((double) v - (double) mx);
const double lse = (double) mx + std::log(se);
std::printf("LP %.6f", (double) row[(size_t) token] - lse);
if (!allowed.empty()) {
// Only the ids the caller named; the server renormalises over them, which is what allowed_token_ids means.
// The server refuses an id past the vocabulary with a 400 only when it can read the vocabulary size from the
// tokenizer. The engine's own vocab() is the authority: an id past it is left off the line, so the logits
// are never read out of bounds.
for (const int32_t id : allowed) {
if (id == token || id < 0 || (int64_t) id >= ver.vocab()) continue;
std::printf(" %d:%.6f", (int) id, (double) row[(size_t) id] - lse);
}
std::printf("\n");
return;
}
if (k > 0) {
static std::vector<int32_t> ord;
ord.resize(row.size());
for (size_t v = 0; v < row.size(); ++v) ord[v] = (int32_t) v;
const int kk = std::min<int>(k, (int) row.size());
std::partial_sort(ord.begin(), ord.begin() + kk, ord.end(),
[&](int32_t a, int32_t b) { return row[(size_t) a] > row[(size_t) b]; });
for (int j = 0; j < kk; ++j)
std::printf(" %d:%.6f", ord[(size_t) j], (double) row[(size_t) ord[(size_t) j]] - lse);
}
std::printf("\n");
}
namespace {
// Windows' WDDM driver model: native Windows, or WSL2 (its GPU goes through /dev/dxg to the Windows driver). There,
// pinning a large arena into two CUDA contexts leaves WDDM refusing every later allocation (the 5080 + 3090 rig);
@@ -12474,6 +12519,11 @@ int main(int argc, char** argv) {
std::string req_bias_text;
bool req_bias_present = false;
int req_cvec = 1; // cvec=0|1: a loaded control vector for this request (on when absent)
// logprobs=K (0..20): after each "T id" an "LP logprob id:logprob ..." line.
// -1 (absent) = no LP lines, so a server that never asks sees today's output.
int req_logprobs = -1;
// allowed=a,b,c: with logprobs, print only these token ids (renormalized server-side).
std::vector<int32_t> req_allowed;
// ckpt=0: a one-shot call whose turn no later request extends. No checkpoint at its last turn boundary
// (so no split there) nor every --prompt-cache-every tokens, and its session is neither continued nor
// parked after it. It still resumes from a checkpoint it matches, and still saves the system-prompt root
@@ -12513,6 +12563,18 @@ int main(int argc, char** argv) {
else if (key == "temperature") req_temperature = fv;
else if (key == "top_p") req_top_p = fv;
else if (key == "top_k") req_top_k = std::atoi(tok.c_str() + eq + 1);
else if (key == "logprobs") req_logprobs = std::atoi(tok.c_str() + eq + 1);
else if (key == "allowed") {
const std::string csv = tok.substr(eq + 1);
size_t p = 0;
while (p < csv.size()) {
const size_t c = csv.find(",", p);
const std::string one = csv.substr(p, c == std::string::npos ? std::string::npos : c - p);
if (!one.empty()) req_allowed.push_back((int32_t) std::atoi(one.c_str()));
if (c == std::string::npos) break;
p = c + 1;
}
}
else if (key == "min_p") req_min_p = fv;
else if (key == "penalty_last_n") req_penalty_last_n = std::atoi(tok.c_str() + eq + 1);
else if (key == "penalty_repeat") req_penalty_repeat = fv;
@@ -14919,6 +14981,7 @@ int main(int argc, char** argv) {
bool eos = false;
for (int i = 0; !nf && i <= a && produced_n < max_new && !eos; ++i) {
std::printf("T %d\n", (int) outp[(size_t) i]);
if (req_logprobs >= 0) emit_lp_line(V1(A), i, outp[(size_t) i], req_logprobs, req_allowed);
strata::core::progress_beat();
++produced_n;
if (o.suffix_draft > 0) sfx.append(outp[(size_t) i]);
@@ -15339,6 +15402,7 @@ int main(int argc, char** argv) {
bool eos = false;
for (int i = merged ? a : 0; i <= a && produced_n < max_new && !eos; ++i) { // (merged: row T-1 only)
std::printf("T %d\n", (int) outv[(size_t) i]);
if (req_logprobs >= 0) emit_lp_line(ver, i, outv[(size_t) i], req_logprobs, req_allowed);
strata::core::progress_beat();
++produced_n;
if (sfx_on) sfx.append(outv[(size_t) i]);