[PR #3200] [CLOSED] [Engine] OpenAI logprobs / top_logprobs / allowed_token_ids for the CUDA/HIP engine #4497

Closed
opened 2026-11-07 15:36:27 +07:00 by bsakaguchi · 0 comments
Owner

📋 Pull Request Information

Original PR: https://github.com/Niko1221/Strata/pull/3200
Author: @xiezhipeng-git
Created: 10/19/2026
Status: ❌ Closed

Base: main ← Head: feat/openai-logprobs


📝 Commits (10+)

  • 104becf OpenAI logprobs / top_logprobs / allowed_token_ids for the CUDA/HIP engine
  • a4349ec serve: logprobs lines belong to the request that asked for them; bounded replies; unreadable LP lines skipped
  • 900a5b8 serve: allowed_token_ids keeps the token when no named id survives the filter
  • 597571c docs: logprobs on the chat API: the keys, the cap, and what allowed_token_ids does
  • 22fe518 engine: allowed_token_ids: keep the list the request named
  • b55e9fd serve: logprobs are refused on the --parallel / --batch path
  • 26a2d48 serve: an allowed_token_ids id past the vocabulary is a 400
  • eca6513 serve: a streamed logprobs reply takes any max_tokens
  • d4e8211 Merge upstream/main into feat/openai-logprobs
  • 4b7339e serve: a logprobs reply is bounded by max_tokens, not by a cap of 4096

📊 Changes

12 files changed (+1655 additions, -30 deletions)

View changed files

📝 CMakeLists.txt (+11 -0)
📝 docs/DETAILS.md (+18 -0)
📝 include/strata/core/verify.hpp (+12 -0)
➕ include/strata/kernels/logprobs.hpp (+29 -0)
📝 serve/server.py (+367 -28)
📝 serve/structured.py (+5 -2)
➕ serve/test_logprobs.py (+561 -0)
➕ serve/test_logprobs_parallel.py (+117 -0)
📝 src/core/verify.cpp (+80 -0)
➕ src/kernels/cuda/logprobs.cu (+188 -0)
➕ src/kernels/logprobs_parity.cpp (+174 -0)
📝 src/program/generate.cpp (+93 -0)

📄 Description

AI assistance: the implementation, the tests and this description were drafted with an AI coding agent. I checked every claim below against the source, the command output and the logs it came from; every measurement was run on this machine unless the text says otherwise.

Problem and result. /v1/chat/completions on the CUDA/HIP engine accepted logprobs / top_logprobs and returned HTTP 200, but choices[0].logprobs.content was always []. A client that ranks candidate tokens from the model's own distribution — constrained decoding, candidate scoring, tool-choice re-ranking — silently got nothing: the request succeeds, the content is correct, only the field is missing, so the failure is invisible unless the caller asserts on the field. After this change, logprobs: true with top_logprobs 0..20 (the legacy completions form logprobs: N is also accepted) returns one entry per token with its top alternatives, and allowed_token_ids returns a distribution renormalised over exactly the ids the caller named — including the case where the only id named is the one the model chose, which is the one a decision client asks for.

Related discussion. This supersedes #2254, which the 0.2.0-beta tracker reset closed. GitHub will not reopen it (state cannot be changed. The feat/openai-logprobs branch was force-pushed or recreated.), so this PR carries the same change, rebased onto main. #1916 proposed the same feature for CUDA/HIP and is closed. This implementation follows the protocol the SYCL port already speaks (835d30b1) and the Metal port (31f26683), so one server-side reader serves all three backends.

It also carries the fix from the review, ad3cff8 on leonardomurillo:logprobs-own-lines, cherry-picked as a4349ec9 with its authorship intact: an LP line belongs to the request that asked for it, so a reply whose tail is held by a stop string cannot read the next request's lines.

What is already built on it. This is no longer only the field itself:

  • #4056 adds logprobs to #3332's legacy /v1/completions and states that it stacks on this branch and that one; a decision client reads its label's log-probabilities from that endpoint, so the two halves it needs are in two open PRs.
  • #3743 (typed decisions) lists this PR as prior art for the one-token case: allowed_token_ids gives a probability per field, one prompt read per field, and requires the value to be one token. Values longer than one token and several fields per read are what #3743 adds on top.
  • #675 asked for one-token typed decisions via logprobs.

So the surface this PR adds is the one-token baseline the two follow-ups measure against, and the cases below are on the engine they will run on.

Approach.

  • Engine half, src/program/generate.cpp: logprobs=K and allowed=a,b,c are two extra keys on the --serve GEN line (an engine that predates them skips them as unknown), and one LP <logprob> [id:logprob ...] line is written after each T <id> in the same flush. The value comes from the verify window's head logits before sampling, penalties and temperature, so it is the model's distribution rather than the sampler's. Off by default: a request without logprobs produces the previous output byte for byte, and the per-token cost is one integer compare.
  • Engine half, the named ids (22fe5184): GEN ... allowed=a,b,c parsed the ids into req_allowed and then cleared that vector three lines later, next to req_imgs.clear(), before either decode loop ran. emit_lp_line therefore always took the top-k branch, and allowed_token_ids only ever filtered what was already in top-k — an id outside it was silently dropped. The clear is gone. On Swift 1.5 IQ3_XXS, allowed_token_ids: [16] used to return the chosen id twice at 0.5 each and now returns one entry at logprob 0; ten named digits (0-9, ids 15-24) for the reply 11 used to cover 2 and then 8 of the ten positions and now cover all ten in every entry, sorted, summing to 1.
  • Server half, serve/server.py: sampling_keys appends the two keys only when asked; generate reads each token's LP line before yielding the token (a held line is consumed before the next read, so an engine without LP lines loses no lines, and a DONE read while looking for one still ends the request); LogprobEntries decodes token bytes incrementally so the entries joined spell the reply; structured_chunks re-aligns the entries when response_format: json_schema rewrites the content and returns no logprobs rather than a set that does not match.
  • Server half, line ownership (a4349ec9): the engine's lp_lines deque is tagged with the request's cancel Event — one per request, handed unchanged from the handler through Service.run to Engine.generate — and LogprobEntries.take() reads only lines carrying its own. A reply's tail, held by the parser or a stop string, is spelled after the request has released the queue; by then the next request may have replaced lp_lines with its own. The tail now reads its own lines and never consumes the next request's.
  • Server half, the filter (900a5b82): when allowed_token_ids left no candidate, _renormalise returned None, the entry was appended all the same, and spell() failed on e["token"] — an unstreamed reply came back 400 "the request is malformed", a streamed one stopped after the role chunk. The chosen token is put back when the caller named it (the line carries its logprob on the head and never repeats it among the named ids, which is exactly why naming only the chosen id used to leave nothing to renormalise over); an entry is never None and never dropped, because the reply's tokens have to keep spelling its text; the entry's logprob is the chosen token's own value, not the first named alternative's; and top_logprobs is sorted most likely first, as the unfiltered top-k already is.
  • Server half, the batch admission (1878675f): a slot's BT lines carry no LP line, but an admission does — a max_tokens 1 request is asked of the engine as BGEN and read as GEN 1, the single-token path that prints T and its LP line in one flush (generate.cpp:12090). _control() takes that line and keeps it on the request's own lines, held on its cancel Event: the engine's lp_lines is one attribute and several slots read control lines at once, so it cannot be shared between them. A longer reply there is still a 400, for the reason in Limits. The same commit stops refusing logprobs on --replicas: ReplicaEngine.batch totals how many requests its engines run at once and counts a replica without slots as one, so the "does this engine use batch slots" check said yes to a server that has none — every logprobs request got a 400 while its reply was read by the GEN path that does write the lines. batch_slots_on() asks each replica's own figure instead.
  • Refusals (b55e9fdc, 26a2d480, all 400 before anything is generated): logprobs on a --parallel / --batch server unless max_tokens is 1 — a slot prints BT <slot> <id> and writes no LP line, so past the admission's first token a reply's entries would cover a prefix only, which a client cannot tell from the model's own answer (1878675f answers the max_tokens 1 case; see below); and an allowed_token_ids id at or past the vocabulary, which emit_lp_line would use to index a logits row out of bounds.
  • The cap, taken out (4b7339e1): the 1..4096 bound on max_tokens / max_completion_tokens was ours alone — OpenAI's request schema makes max_tokens optional and ties no limit to logprobs, and vLLM's defaults to 16 or None and its logprobs only check themselves. A reply is already bounded by max_tokens, or by the rest of the context when it is not sent, so the constant was a second bound on top of one that exists, and it answered 400 to requests that would have worked — the OpenAI SDKs send no max_tokens by default. What the constant protected is real, but it is the reply's own length: a reply that is not streamed, or that answers a json_schema (buffered to be validated), holds every entry until it ends, while a streamed one hands each entry out with its chunk and keeps none. A client that wants that memory bounded streams. The previous commit on this branch (eca6513b) had narrowed the bound to the held cases; this one removes it.
  • Compatibility: additive and opt-in. A request that does not ask for logprobs gets the same bytes as before, and no default changes. Two client-visible changes, both of them requests that could not have worked: a logprobs request is now answered at any max_tokens — 5000, 0, -1, or the field absent, which is what the OpenAI SDKs send — where before it took a 400 unless it streamed, and logprobs on --parallel is answered for a max_tokens 1 request (the typed decision) where before it was a 400 for every request, with a longer reply there still a 400 rather than a field that comes back missing.
  • Docs: one bullet in docs/DETAILS.md under "Using it" (597571c8, updated by eca6513b, 4b7339e1 and 1878675f) — the keys, that a reply is bounded by max_tokens and not by a cap of ours, what allowed_token_ids keeps and renormalises, that a token whose probability could not be read gets no entry rather than a made-up one, and that --parallel answers only a max_tokens 1 request.

Validation.

Branch: 12 commits on e88ee39d, head 1878675f, with two merges of upstream/main (it moved twice today): d4e8211b onto 41cf05a0 (992 files, +133057/−12580) and 7cbff4fd onto 4b9e05a2 (55 files, +422/−133, the 0.2.6 release). They had to happen — GitHub cannot merge a pull request that has conflicts, and the first one did: docs/DETAILS.md had been restructured (−2162/+1069) around the logprobs bullet, which was put back among the server-behaviour bullets of "Using it". The code never conflicted: serve/server.py and src/program/generate.cpp merged on their own both times, and main's changes to them contain no logprob and touch no LP, BT or GEN line format. Against 4b9e05a2 the diff is 5 files, +1099/−27: src/program/generate.cpp +59/−0, serve/server.py +367/−27, serve/test_logprobs.py +541/−0, serve/test_logprobs_parallel.py +117/−0, docs/DETAILS.md +15/−0. src/program/generate.cpp only gains lines: the whole emit_lp_line path is new here, and the req_allowed clear that 22fe5184 takes out was itself introduced by the first commit, so it never shows as a deletion against the base. Nothing else in src/ moves.

No conflict with today's main (7dd5cf18, 24 October): GitHub reports this PR mergeable: true, and the independent run below merged it onto exactly that revision.

Passed:

  • Full CUDA build and link, revision 104becfd: cmake --build build-lp --target strata — Release, CMAKE_CUDA_ARCHITECTURES=89, CUDA 13.3 (V13.3.73), MSVC 14.41, Windows 11, RTX 4090 (48 GB, driver 610.88). [154/154] Linking CXX executable strata.exe, exit 0. The engine that answered every hardware run below was rebuilt from this branch after 22fe5184 and is what the server was started with. eca6513b, the merge d4e8211b and the cap's removal touch no C++: that binary is what answered the runs added for them.
  • python -m unittest serve.test_logprobs — 32 tests, OK (104becfd had 17; the file now covers the two refusals, the ownership case, unreadable lines, a line whose named ids are all filtered out, naming only the chosen token, a ten-way choice that only the ended reply settles, a held tail of two tokens, any max_tokens on a reply that holds its entries, and no batch slots behind two replicas). On 26a2d480 the ones eca6513b added fail with a 400: a streamed reply with max_tokens of 5000, 0 and none at all. test_logprobs_take_any_max_tokens (200 / 5000 / 0 / −1 / not sent, not streamed) and test_a_json_schema_reply_takes_any_max_tokens (200 / 0 / 5000, streamed and not) replace the two that asserted the 1..4096 400.
  • python -m unittest serve.test_logprobs_parallel — 6 tests, OK: a max_tokens 1 decision through a real StrataEngine and Service over HTTP with the fake engine of serve/test_parallel.py behind them (writing an LP line after each T when the GEN / BGEN line asks), then allowed_token_ids on that admission, four decisions at once each getting its own logprob, a request that does not ask, a longer reply answered 400, and an engine that writes no LP lines at all.
  • python -m unittest discover -s serve -t . -p "test_*.py" — 1073 tests in 386 s, 1 failure, 1 error, 21 skipped (the merged tree carries main's new tests, which is why the count is no longer 909). Both are known on a clean upstream/main checkout in this environment and touch no logprobs code: serve.test_winjob (running() on a pid this sandbox cannot read) and serve.test_responses.test_server_close_ends_the_sampler (1 != 2, order-sensitive — it passes when its file runs alone, which it did in the 83-test run just before this one). The skips are POSIX-only (signals, /proc), unrelated to this change. The only test files that mention logprobs are the two above.
  • Hardware runs, same engine, model Swift-1.5 IQ3_XXS, --spec 4 --spec-min-p 0.5 --kv int8 --kv-resident 32768, temperature: 0, chat_template_kwargs.enable_thinking: false:
    • non-streamed and stream: true, plain request → 6 entries, "".join(token) equal to the content character for character.
    • stop: [".!"], which holds the tail — non-streamed and streamed → content Cafe costs 5., 6 entries each, the held 5. flushed after the request left the queue with its own entries.
    • the review's scenario on the real engine: two overlapping requests, the first one's tail held by its stop string and sent while the second is generating, 4 rounds → 0 mismatched replies, each reply's tokens spelling that reply.
    • allowed_token_ids: [16] (the digit 1, the id the model chose) → 200, one entry, one candidate at 0.0 — previously the 400 "the request was malformed", streamed and not.
    • ten named digits 0-9, reply 11 → 2 entries, 10 candidates each, most likely first, sum(exp(logprob)) = 1. Only the ended reply settles which of 1 and 11 was meant.
    • a three-token label: allowed_token_ids over {0,1}, reply 111 → 3 entries, each over the two named ids, joint path probability 0.999870.
    • 4b7339e1, the reply's length is no longer capped: logprobs: true, top_logprobs: 5, the reply 11, max_tokens absent / 0 / 200 / 4096 / 5000, each of them streamed and not → 200 ten times, 2 entries each, the tokens spelling 11, the non-streamed replies carrying 5 candidates each.
    • 4b7339e1, allowed_token_ids over the ten digits 15-24 with max_tokens: 5000, streamed → 200, 2 entries of 10 candidates spelling 11; allowed_token_ids: [16] (the digit the model chose), not streamed → 200, one entry, one candidate at 0.0 — previously the 400 "the request was malformed".
    • 4b7339e1, json_schema with max_tokens absent / 0 / 200 / 5000, streamed and not → 200 in all eight, 6 or 7 entries spelling {"n":11} / {"n": 11}; before this commit the streamed ones with absent or 5000 were 400.
    • 4b7339e1, allowed_token_ids: [248320] (the vocabulary size) → 400, still.
    • 1878675f, the same machine and engine but --parallel 2: max_tokens: 1 with top_logprobs: 5 → 200, one entry spelling the reply (A −0.062427, then B −2.848, A −7.415); allowed_token_ids over 11 ids → 200, the named ids as the candidates, sum(exp(logprob)) = 1.0, a chosen token outside them keeping its own logprob; max_completion_tokens: 1 → 200 with its entry; stream: true → 200, one chunk carrying the entry for Odd; four decisions at once on two slots → 200 each, 1.6 s for all four, every entry matching its reply; max_tokens 5, max_tokens absent and max_completion_tokens: 0 → 400 naming max_tokens 1; a plain request and a 64-token reply unchanged.
  • Independent run, reported by @gdevenyi in this thread (2026-10-25) — not run by me: #3332 merged with this branch onto main 7dd5cf18 (both merged cleanly), CUDA build from setup.py's flags, RTX 5080 (sm_120), CUDA 13.4, Linux, Qwen3.8-Flash-Next IQ3_S, --spec 4 --mtp, --parallel 1. python -m unittest serve.test_logprobs 28/28 OK (the file had 28 tests at 26a2d480); logprobs: true, top_logprobs: 5, max_tokens: 1 returned choices[0].logprobs.content (B −0.018839, then B −4.51, A −5.98) where the 0.1.48 engine returned no logprobs for the same request; allowed_token_ids agreed with the unrestricted top-K and the engine's ids matched the Hugging Face Qwen/Qwen3.8-Flash-Next tokenizer. This is the only run on hardware that covers --mtp: the runs above used --spec 4 --spec-min-p 0.5 without it.

Failed: none observed.

Not run:

  • HIP backend build. src/program/generate.cpp is shared by the CUDA and HIP builds; only the CUDA configuration was built here (no AMD GPU or toolchain on this machine). CONTRIBUTING.md asks for every backend a touched file is compiled into — if someone with an AMD card can run the HIP build, that closes the last gap in this section.
  • SYCL and Metal builds. Neither is touched: they carry their own implementations (install_logprobs in sycl/serve/server_intel.py), and no Intel or Apple toolchain is present here.
  • The BT slot phase of --parallel / --batch: a reply longer than one token there has no entries, and is a 400; see Limits. What is measured is the max_tokens 1 decision that works and the 400 for anything longer.

Limits.

  • On --parallel / --batch, only a max_tokens 1 request carries logprobs; a longer reply is a 400, not a reply whose entries stop halfway. A slot prints BT <slot> <id> and its decode loop never calls emit_lp_line, and the line carries no slot id (LP <logprob> [id:logprob ...]), so with N slots interleaved on one stdout an LP line could not be attributed to a request even if one were written: that needs a slot-tagged line in the engine plus the matching read in the server. The admission is the one token that does come with a line — the engine reads BGEN <slot> 1 as GEN 1, the single-token path — which is exactly the typed-decision case this feature exists for. A request that stays solo on such a server does run the GEN path too, but a second request arriving moves the running one into a slot mid-reply (generate_batched), so its entries would stop with no way for the client to tell. This is the same line gt50 drew on #1916: "LP lines for the BT slot phase can be a later step."
  • The reported logprob describes the model's distribution before penalties and temperature, not the post-sampling one.
  • With response_format: json_schema the returned content may not be spelled by the tokens; in that case no logprobs are returned, by design.
  • An LP line that does not parse (nan, -nan(ind), a cut line) or carries a non-finite value gives no entry for that token rather than failing the request: logprobs.content can be shorter than the reply, and a client must pair entries by token, not by index.
  • A reply that is not streamed, or that answers a json_schema, holds every entry (its token, bytes and up to 20 alternatives) until it ends, so a long one holds a lot of them in the server's memory. Nothing here caps that: the bound is the reply's own max_tokens, or the rest of the context when it is not sent, as on OpenAI and vLLM, neither of which ties a length limit to logprobs. Streaming is the way to keep that memory off the server's side.
  • CUDA/HIP only; the SYCL and Metal implementations are untouched.
  • #4056 adds logprobs to /v1/completions on top of this and #3332; #4059 reports run-to-run variation on ~100-token prompts, which is a sampling-determinism matter and is not changed here.

🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.

## 📋 Pull Request Information **Original PR:** https://github.com/Niko1221/Strata/pull/3200 **Author:** [@xiezhipeng-git](https://github.com/xiezhipeng-git) **Created:** 10/19/2026 **Status:** ❌ Closed **Base:** `main` ← **Head:** `feat/openai-logprobs` --- ### 📝 Commits (10+) - [`104becf`](https://github.com/Niko1221/Strata/commit/104becfd7cbc342b1cf93c500d42fee3bd182daf) OpenAI logprobs / top_logprobs / allowed_token_ids for the CUDA/HIP engine - [`a4349ec`](https://github.com/Niko1221/Strata/commit/a4349ec95e10da985d62a62968ed71cad2211470) serve: logprobs lines belong to the request that asked for them; bounded replies; unreadable LP lines skipped - [`900a5b8`](https://github.com/Niko1221/Strata/commit/900a5b82867475899525ca3dff6b653bc00cf9b4) serve: allowed_token_ids keeps the token when no named id survives the filter - [`597571c`](https://github.com/Niko1221/Strata/commit/597571c8f140def427316301656ad173387783fb) docs: logprobs on the chat API: the keys, the cap, and what allowed_token_ids does - [`22fe518`](https://github.com/Niko1221/Strata/commit/22fe5184dc45a12e61fd0cc812ba8fc89a866651) engine: allowed_token_ids: keep the list the request named - [`b55e9fd`](https://github.com/Niko1221/Strata/commit/b55e9fdc43381d8d4ea7353e4fb3ca5b0723187d) serve: logprobs are refused on the --parallel / --batch path - [`26a2d48`](https://github.com/Niko1221/Strata/commit/26a2d4803a9db92a6c58de092fac8b774c515fd2) serve: an allowed_token_ids id past the vocabulary is a 400 - [`eca6513`](https://github.com/Niko1221/Strata/commit/eca6513b01188e8dea88901c73c63449656d22c6) serve: a streamed logprobs reply takes any max_tokens - [`d4e8211`](https://github.com/Niko1221/Strata/commit/d4e8211b72f5e31427b2140216c80f1556dc9d71) Merge upstream/main into feat/openai-logprobs - [`4b7339e`](https://github.com/Niko1221/Strata/commit/4b7339e16743745002f946fe3b5e71246ce9804a) serve: a logprobs reply is bounded by max_tokens, not by a cap of 4096 ### 📊 Changes **12 files changed** (+1655 additions, -30 deletions) <details> <summary>View changed files</summary> 📝 `CMakeLists.txt` (+11 -0) 📝 `docs/DETAILS.md` (+18 -0) 📝 `include/strata/core/verify.hpp` (+12 -0) ➕ `include/strata/kernels/logprobs.hpp` (+29 -0) 📝 `serve/server.py` (+367 -28) 📝 `serve/structured.py` (+5 -2) ➕ `serve/test_logprobs.py` (+561 -0) ➕ `serve/test_logprobs_parallel.py` (+117 -0) 📝 `src/core/verify.cpp` (+80 -0) ➕ `src/kernels/cuda/logprobs.cu` (+188 -0) ➕ `src/kernels/logprobs_parity.cpp` (+174 -0) 📝 `src/program/generate.cpp` (+93 -0) </details> ### 📄 Description *AI assistance: the implementation, the tests and this description were drafted with an AI coding agent. I checked every claim below against the source, the command output and the logs it came from; every measurement was run on this machine unless the text says otherwise.* Problem and result. `/v1/chat/completions` on the CUDA/HIP engine accepted `logprobs` / `top_logprobs` and returned HTTP 200, but `choices[0].logprobs.content` was always `[]`. A client that ranks candidate tokens from the model's own distribution — constrained decoding, candidate scoring, tool-choice re-ranking — silently got nothing: the request succeeds, the content is correct, only the field is missing, so the failure is invisible unless the caller asserts on the field. After this change, `logprobs: true` with `top_logprobs` 0..20 (the legacy completions form `logprobs: N` is also accepted) returns one entry per token with its top alternatives, and `allowed_token_ids` returns a distribution renormalised over exactly the ids the caller named — including the case where the only id named is the one the model chose, which is the one a decision client asks for. Related discussion. This supersedes #2254, which the 0.2.0-beta tracker reset closed. GitHub will not reopen it (`state cannot be changed. The feat/openai-logprobs branch was force-pushed or recreated.`), so this PR carries the same change, rebased onto `main`. #1916 proposed the same feature for CUDA/HIP and is closed. This implementation follows the protocol the SYCL port already speaks (835d30b1) and the Metal port (31f26683), so one server-side reader serves all three backends. It also carries the fix from the review, `ad3cff8` on `leonardomurillo:logprobs-own-lines`, cherry-picked as `a4349ec9` with its authorship intact: an `LP` line belongs to the request that asked for it, so a reply whose tail is held by a stop string cannot read the next request's lines. What is already built on it. This is no longer only the field itself: - `#4056` adds logprobs to `#3332`'s legacy `/v1/completions` and states that it stacks on this branch and that one; a decision client reads its label's log-probabilities from that endpoint, so the two halves it needs are in two open PRs. - `#3743` (typed decisions) lists this PR as prior art for the one-token case: `allowed_token_ids` gives a probability per field, one prompt read per field, and requires the value to be one token. Values longer than one token and several fields per read are what #3743 adds on top. - `#675` asked for one-token typed decisions via logprobs. So the surface this PR adds is the one-token baseline the two follow-ups measure against, and the cases below are on the engine they will run on. Approach. - Engine half, `src/program/generate.cpp`: `logprobs=K` and `allowed=a,b,c` are two extra keys on the `--serve` GEN line (an engine that predates them skips them as unknown), and one `LP <logprob> [id:logprob ...]` line is written after each `T <id>` in the same flush. The value comes from the verify window's head logits **before** sampling, penalties and temperature, so it is the model's distribution rather than the sampler's. Off by default: a request without `logprobs` produces the previous output byte for byte, and the per-token cost is one integer compare. - Engine half, the named ids (`22fe5184`): `GEN ... allowed=a,b,c` parsed the ids into `req_allowed` and then cleared that vector three lines later, next to `req_imgs.clear()`, before either decode loop ran. `emit_lp_line` therefore always took the top-k branch, and `allowed_token_ids` only ever filtered what was already in top-k — an id outside it was silently dropped. The clear is gone. On Swift 1.5 IQ3_XXS, `allowed_token_ids: [16]` used to return the chosen id twice at 0.5 each and now returns one entry at logprob 0; ten named digits (`0`-`9`, ids 15-24) for the reply `11` used to cover 2 and then 8 of the ten positions and now cover all ten in every entry, sorted, summing to 1. - Server half, `serve/server.py`: `sampling_keys` appends the two keys only when asked; `generate` reads each token's `LP` line before yielding the token (a held line is consumed before the next read, so an engine without LP lines loses no lines, and a `DONE` read while looking for one still ends the request); `LogprobEntries` decodes token bytes incrementally so the entries joined spell the reply; `structured_chunks` re-aligns the entries when `response_format: json_schema` rewrites the content and returns **no** logprobs rather than a set that does not match. - Server half, line ownership (`a4349ec9`): the engine's `lp_lines` deque is tagged with the request's `cancel` Event — one per request, handed unchanged from the handler through `Service.run` to `Engine.generate` — and `LogprobEntries.take()` reads only lines carrying its own. A reply's tail, held by the parser or a stop string, is spelled after the request has released the queue; by then the next request may have replaced `lp_lines` with its own. The tail now reads its own lines and never consumes the next request's. - Server half, the filter (`900a5b82`): when `allowed_token_ids` left no candidate, `_renormalise` returned `None`, the entry was appended all the same, and `spell()` failed on `e["token"]` — an unstreamed reply came back 400 "the request is malformed", a streamed one stopped after the role chunk. The chosen token is put back when the caller named it (the line carries its logprob on the head and never repeats it among the named ids, which is exactly why naming only the chosen id used to leave nothing to renormalise over); an entry is never `None` and never dropped, because the reply's tokens have to keep spelling its text; the entry's `logprob` is the chosen token's own value, not the first named alternative's; and `top_logprobs` is sorted most likely first, as the unfiltered top-k already is. - Server half, the batch admission (`1878675f`): a slot's `BT` lines carry no `LP` line, but an admission does — a `max_tokens` 1 request is asked of the engine as `BGEN` and read as `GEN 1`, the single-token path that prints `T` and its `LP` line in one flush (`generate.cpp:12090`). `_control()` takes that line and keeps it on the request's own lines, held on its `cancel` Event: the engine's `lp_lines` is one attribute and several slots read control lines at once, so it cannot be shared between them. A longer reply there is still a 400, for the reason in Limits. The same commit stops refusing logprobs on `--replicas`: `ReplicaEngine.batch` totals how many requests its engines run at once and counts a replica without slots as one, so the "does this engine use batch slots" check said yes to a server that has none — every logprobs request got a 400 while its reply was read by the `GEN` path that does write the lines. `batch_slots_on()` asks each replica's own figure instead. - Refusals (`b55e9fdc`, `26a2d480`, all 400 before anything is generated): logprobs on a `--parallel` / `--batch` server unless `max_tokens` is 1 — a slot prints `BT <slot> <id>` and writes no `LP` line, so past the admission's first token a reply's entries would cover a prefix only, which a client cannot tell from the model's own answer (`1878675f` answers the `max_tokens` 1 case; see below); and an `allowed_token_ids` id at or past the vocabulary, which `emit_lp_line` would use to index a logits row out of bounds. - The cap, taken out (`4b7339e1`): the 1..4096 bound on `max_tokens` / `max_completion_tokens` was ours alone — OpenAI's request schema makes `max_tokens` optional and ties no limit to logprobs, and vLLM's defaults to 16 or `None` and its `logprobs` only check themselves. A reply is already bounded by `max_tokens`, or by the rest of the context when it is not sent, so the constant was a second bound on top of one that exists, and it answered 400 to requests that would have worked — the OpenAI SDKs send no `max_tokens` by default. What the constant protected is real, but it is the reply's own length: a reply that is not streamed, or that answers a `json_schema` (buffered to be validated), holds every entry until it ends, while a streamed one hands each entry out with its chunk and keeps none. A client that wants that memory bounded streams. The previous commit on this branch (`eca6513b`) had narrowed the bound to the held cases; this one removes it. - Compatibility: additive and opt-in. A request that does not ask for logprobs gets the same bytes as before, and no default changes. Two client-visible changes, both of them requests that could not have worked: a logprobs request is now answered at any `max_tokens` — 5000, `0`, `-1`, or the field absent, which is what the OpenAI SDKs send — where before it took a 400 unless it streamed, and logprobs on `--parallel` is answered for a `max_tokens` 1 request (the typed decision) where before it was a 400 for every request, with a longer reply there still a 400 rather than a field that comes back missing. - Docs: one bullet in `docs/DETAILS.md` under "Using it" (`597571c8`, updated by `eca6513b`, `4b7339e1` and `1878675f`) — the keys, that a reply is bounded by `max_tokens` and not by a cap of ours, what `allowed_token_ids` keeps and renormalises, that a token whose probability could not be read gets no entry rather than a made-up one, and that `--parallel` answers only a `max_tokens` 1 request. Validation. Branch: 12 commits on `e88ee39d`, head `1878675f`, with two merges of `upstream/main` (it moved twice today): `d4e8211b` onto `41cf05a0` (992 files, +133057/−12580) and `7cbff4fd` onto `4b9e05a2` (55 files, +422/−133, the 0.2.6 release). They had to happen — GitHub cannot merge a pull request that has conflicts, and the first one did: `docs/DETAILS.md` had been restructured (−2162/+1069) around the logprobs bullet, which was put back among the server-behaviour bullets of "Using it". The code never conflicted: `serve/server.py` and `src/program/generate.cpp` merged on their own both times, and main's changes to them contain no `logprob` and touch no `LP`, `BT` or `GEN` line format. Against `4b9e05a2` the diff is 5 files, +1099/−27: `src/program/generate.cpp` +59/−0, `serve/server.py` +367/−27, `serve/test_logprobs.py` +541/−0, `serve/test_logprobs_parallel.py` +117/−0, `docs/DETAILS.md` +15/−0. `src/program/generate.cpp` only gains lines: the whole `emit_lp_line` path is new here, and the `req_allowed` clear that `22fe5184` takes out was itself introduced by the first commit, so it never shows as a deletion against the base. Nothing else in `src/` moves. No conflict with today's `main` (`7dd5cf18`, 24 October): GitHub reports this PR `mergeable: true`, and the independent run below merged it onto exactly that revision. Passed: - Full CUDA build and link, revision `104becfd`: `cmake --build build-lp --target strata` — Release, `CMAKE_CUDA_ARCHITECTURES=89`, CUDA 13.3 (V13.3.73), MSVC 14.41, Windows 11, RTX 4090 (48 GB, driver 610.88). `[154/154] Linking CXX executable strata.exe`, exit 0. The engine that answered every hardware run below was rebuilt from this branch after `22fe5184` and is what the server was started with. `eca6513b`, the merge `d4e8211b` and the cap's removal touch no C++: that binary is what answered the runs added for them. - `python -m unittest serve.test_logprobs` — 32 tests, OK (`104becfd` had 17; the file now covers the two refusals, the ownership case, unreadable lines, a line whose named ids are all filtered out, naming only the chosen token, a ten-way choice that only the ended reply settles, a held tail of two tokens, any `max_tokens` on a reply that holds its entries, and no batch slots behind two replicas). On `26a2d480` the ones `eca6513b` added fail with a 400: a streamed reply with `max_tokens` of 5000, `0` and none at all. `test_logprobs_take_any_max_tokens` (200 / 5000 / 0 / −1 / not sent, not streamed) and `test_a_json_schema_reply_takes_any_max_tokens` (200 / 0 / 5000, streamed and not) replace the two that asserted the 1..4096 400. - `python -m unittest serve.test_logprobs_parallel` — 6 tests, OK: a `max_tokens` 1 decision through a real `StrataEngine` and `Service` over HTTP with the fake engine of `serve/test_parallel.py` behind them (writing an `LP` line after each `T` when the `GEN` / `BGEN` line asks), then `allowed_token_ids` on that admission, four decisions at once each getting its own logprob, a request that does not ask, a longer reply answered 400, and an engine that writes no `LP` lines at all. - `python -m unittest discover -s serve -t . -p "test_*.py"` — 1073 tests in 386 s, 1 failure, 1 error, 21 skipped (the merged tree carries `main`'s new tests, which is why the count is no longer 909). Both are known on a clean `upstream/main` checkout in this environment and touch no logprobs code: `serve.test_winjob` (`running()` on a pid this sandbox cannot read) and `serve.test_responses.test_server_close_ends_the_sampler` (`1 != 2`, order-sensitive — it passes when its file runs alone, which it did in the 83-test run just before this one). The skips are POSIX-only (signals, `/proc`), unrelated to this change. The only test files that mention logprobs are the two above. - Hardware runs, same engine, model Swift-1.5 IQ3_XXS, `--spec 4 --spec-min-p 0.5 --kv int8 --kv-resident 32768`, `temperature: 0`, `chat_template_kwargs.enable_thinking: false`: - non-streamed and `stream: true`, plain request → 6 entries, `"".join(token)` equal to the content character for character. - `stop: [".!"]`, which holds the tail — non-streamed and streamed → content `Cafe costs 5.`, 6 entries each, the held `5.` flushed after the request left the queue with its own entries. - the review's scenario on the real engine: two overlapping requests, the first one's tail held by its stop string and sent while the second is generating, 4 rounds → 0 mismatched replies, each reply's tokens spelling that reply. - `allowed_token_ids: [16]` (the digit `1`, the id the model chose) → 200, one entry, one candidate at `0.0` — previously the 400 "the request was malformed", streamed and not. - ten named digits `0`-`9`, reply `11` → 2 entries, 10 candidates each, most likely first, `sum(exp(logprob)) = 1`. Only the ended reply settles which of `1` and `11` was meant. - a three-token label: `allowed_token_ids` over `{0,1}`, reply `111` → 3 entries, each over the two named ids, joint path probability 0.999870. - `4b7339e1`, the reply's length is no longer capped: `logprobs: true, top_logprobs: 5`, the reply `11`, `max_tokens` absent / `0` / `200` / `4096` / `5000`, each of them streamed and not → 200 ten times, 2 entries each, the tokens spelling `11`, the non-streamed replies carrying 5 candidates each. - `4b7339e1`, `allowed_token_ids` over the ten digits `15`-`24` with `max_tokens: 5000`, streamed → 200, 2 entries of 10 candidates spelling `11`; `allowed_token_ids: [16]` (the digit the model chose), not streamed → 200, one entry, one candidate at `0.0` — previously the 400 "the request was malformed". - `4b7339e1`, `json_schema` with `max_tokens` absent / `0` / `200` / `5000`, streamed and not → 200 in all eight, 6 or 7 entries spelling `{"n":11}` / `{"n": 11}`; before this commit the streamed ones with absent or `5000` were 400. - `4b7339e1`, `allowed_token_ids: [248320]` (the vocabulary size) → 400, still. - `1878675f`, the same machine and engine but `--parallel 2`: `max_tokens: 1` with `top_logprobs: 5` → 200, one entry spelling the reply (`A` −0.062427, then `B` −2.848, ` A` −7.415); `allowed_token_ids` over 11 ids → 200, the named ids as the candidates, `sum(exp(logprob)) = 1.0`, a chosen token outside them keeping its own logprob; `max_completion_tokens: 1` → 200 with its entry; `stream: true` → 200, one chunk carrying the entry for `Odd`; four decisions at once on two slots → 200 each, 1.6 s for all four, every entry matching its reply; `max_tokens` 5, `max_tokens` absent and `max_completion_tokens: 0` → 400 naming `max_tokens` 1; a plain request and a 64-token reply unchanged. - Independent run, reported by @gdevenyi in this thread (2026-10-25) — **not run by me**: `#3332` merged with this branch onto `main` `7dd5cf18` (both merged cleanly), CUDA build from `setup.py`'s flags, RTX 5080 (sm_120), CUDA 13.4, Linux, Qwen3.8-Flash-Next IQ3_S, `--spec 4 --mtp`, `--parallel 1`. `python -m unittest serve.test_logprobs` 28/28 OK (the file had 28 tests at `26a2d480`); `logprobs: true, top_logprobs: 5, max_tokens: 1` returned `choices[0].logprobs.content` (`B` −0.018839, then ` B` −4.51, `A` −5.98) where the 0.1.48 engine returned no logprobs for the same request; `allowed_token_ids` agreed with the unrestricted top-K and the engine's ids matched the Hugging Face `Qwen/Qwen3.8-Flash-Next` tokenizer. This is the only run on hardware that covers `--mtp`: the runs above used `--spec 4 --spec-min-p 0.5` without it. Failed: none observed. Not run: - HIP backend build. `src/program/generate.cpp` is shared by the CUDA and HIP builds; only the CUDA configuration was built here (no AMD GPU or toolchain on this machine). `CONTRIBUTING.md` asks for every backend a touched file is compiled into — if someone with an AMD card can run the HIP build, that closes the last gap in this section. - SYCL and Metal builds. Neither is touched: they carry their own implementations (`install_logprobs` in `sycl/serve/server_intel.py`), and no Intel or Apple toolchain is present here. - The `BT` slot phase of `--parallel` / `--batch`: a reply longer than one token there has no entries, and is a 400; see Limits. What is measured is the `max_tokens` 1 decision that works and the 400 for anything longer. Limits. - On `--parallel` / `--batch`, only a `max_tokens` 1 request carries logprobs; a longer reply is a 400, not a reply whose entries stop halfway. A slot prints `BT <slot> <id>` and its decode loop never calls `emit_lp_line`, and the line carries no slot id (`LP <logprob> [id:logprob ...]`), so with N slots interleaved on one stdout an `LP` line could not be attributed to a request even if one were written: that needs a slot-tagged line in the engine plus the matching read in the server. The admission is the one token that does come with a line — the engine reads `BGEN <slot> 1` as `GEN 1`, the single-token path — which is exactly the typed-decision case this feature exists for. A request that stays solo on such a server does run the `GEN` path too, but a second request arriving moves the running one into a slot mid-reply (`generate_batched`), so its entries would stop with no way for the client to tell. This is the same line gt50 drew on #1916: "LP lines for the BT slot phase can be a later step." - The reported logprob describes the model's distribution before penalties and temperature, not the post-sampling one. - With `response_format: json_schema` the returned content may not be spelled by the tokens; in that case no logprobs are returned, by design. - An `LP` line that does not parse (`nan`, `-nan(ind)`, a cut line) or carries a non-finite value gives no entry for that token rather than failing the request: `logprobs.content` can be shorter than the reply, and a client must pair entries by token, not by index. - A reply that is not streamed, or that answers a `json_schema`, holds every entry (its token, bytes and up to 20 alternatives) until it ends, so a long one holds a lot of them in the server's memory. Nothing here caps that: the bound is the reply's own `max_tokens`, or the rest of the context when it is not sent, as on OpenAI and vLLM, neither of which ties a length limit to logprobs. Streaming is the way to keep that memory off the server's side. - CUDA/HIP only; the SYCL and Metal implementations are untouched. - `#4056` adds logprobs to `/v1/completions` on top of this and `#3332`; `#4059` reports run-to-run variation on ~100-token prompts, which is a sampling-determinism matter and is not changed here. --- <sub>🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.</sub>
bsakaguchi 2026-11-07 15:36:27 +07:00
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
Niko1221/Strata#4497
No description provided.