mirror of
https://github.com/Niko1221/Strata.git
synced 2026-12-03 19:03:30 +07:00
[PR #3200] [CLOSED] [Engine] OpenAI logprobs / top_logprobs / allowed_token_ids for the CUDA/HIP engine #4497
Labels
No labels
needs-format
pull-request
No milestone
No project
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set.
Reference
Niko1221/Strata#4497
Loading…
Add table
Add a link
Reference in a new issue
No description provided.
Delete branch "%!s()"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
📋 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+)
104becfOpenAI logprobs / top_logprobs / allowed_token_ids for the CUDA/HIP enginea4349ecserve: logprobs lines belong to the request that asked for them; bounded replies; unreadable LP lines skipped900a5b8serve: allowed_token_ids keeps the token when no named id survives the filter597571cdocs: logprobs on the chat API: the keys, the cap, and what allowed_token_ids does22fe518engine: allowed_token_ids: keep the list the request namedb55e9fdserve: logprobs are refused on the --parallel / --batch path26a2d48serve: an allowed_token_ids id past the vocabulary is a 400eca6513serve: a streamed logprobs reply takes any max_tokensd4e8211Merge upstream/main into feat/openai-logprobs4b7339eserve: 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/completionson the CUDA/HIP engine acceptedlogprobs/top_logprobsand returned HTTP 200, butchoices[0].logprobs.contentwas 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: truewithtop_logprobs0..20 (the legacy completions formlogprobs: Nis also accepted) returns one entry per token with its top alternatives, andallowed_token_idsreturns 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 ontomain. #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,
ad3cff8onleonardomurillo:logprobs-own-lines, cherry-picked asa4349ec9with its authorship intact: anLPline 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:
#4056adds logprobs to#3332's legacy/v1/completionsand 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_idsgives 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.#675asked 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.
src/program/generate.cpp:logprobs=Kandallowed=a,b,care two extra keys on the--serveGEN line (an engine that predates them skips them as unknown), and oneLP <logprob> [id:logprob ...]line is written after eachT <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 withoutlogprobsproduces the previous output byte for byte, and the per-token cost is one integer compare.22fe5184):GEN ... allowed=a,b,cparsed the ids intoreq_allowedand then cleared that vector three lines later, next toreq_imgs.clear(), before either decode loop ran.emit_lp_linetherefore always took the top-k branch, andallowed_token_idsonly 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 reply11used to cover 2 and then 8 of the ten positions and now cover all ten in every entry, sorted, summing to 1.serve/server.py:sampling_keysappends the two keys only when asked;generatereads each token'sLPline before yielding the token (a held line is consumed before the next read, so an engine without LP lines loses no lines, and aDONEread while looking for one still ends the request);LogprobEntriesdecodes token bytes incrementally so the entries joined spell the reply;structured_chunksre-aligns the entries whenresponse_format: json_schemarewrites the content and returns no logprobs rather than a set that does not match.a4349ec9): the engine'slp_linesdeque is tagged with the request'scancelEvent — one per request, handed unchanged from the handler throughService.runtoEngine.generate— andLogprobEntries.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 replacedlp_lineswith its own. The tail now reads its own lines and never consumes the next request's.900a5b82): whenallowed_token_idsleft no candidate,_renormalisereturnedNone, the entry was appended all the same, andspell()failed one["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 neverNoneand never dropped, because the reply's tokens have to keep spelling its text; the entry'slogprobis the chosen token's own value, not the first named alternative's; andtop_logprobsis sorted most likely first, as the unfiltered top-k already is.1878675f): a slot'sBTlines carry noLPline, but an admission does — amax_tokens1 request is asked of the engine asBGENand read asGEN 1, the single-token path that printsTand itsLPline in one flush (generate.cpp:12090)._control()takes that line and keeps it on the request's own lines, held on itscancelEvent: the engine'slp_linesis 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.batchtotals 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 theGENpath that does write the lines.batch_slots_on()asks each replica's own figure instead.b55e9fdc,26a2d480, all 400 before anything is generated): logprobs on a--parallel/--batchserver unlessmax_tokensis 1 — a slot printsBT <slot> <id>and writes noLPline, 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 (1878675fanswers themax_tokens1 case; see below); and anallowed_token_idsid at or past the vocabulary, whichemit_lp_linewould use to index a logits row out of bounds.4b7339e1): the 1..4096 bound onmax_tokens/max_completion_tokenswas ours alone — OpenAI's request schema makesmax_tokensoptional and ties no limit to logprobs, and vLLM's defaults to 16 orNoneand itslogprobsonly check themselves. A reply is already bounded bymax_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 nomax_tokensby default. What the constant protected is real, but it is the reply's own length: a reply that is not streamed, or that answers ajson_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.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--parallelis answered for amax_tokens1 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/DETAILS.mdunder "Using it" (597571c8, updated byeca6513b,4b7339e1and1878675f) — the keys, that a reply is bounded bymax_tokensand not by a cap of ours, whatallowed_token_idskeeps and renormalises, that a token whose probability could not be read gets no entry rather than a made-up one, and that--parallelanswers only amax_tokens1 request.Validation.
Branch: 12 commits on
e88ee39d, head1878675f, with two merges ofupstream/main(it moved twice today):d4e8211bonto41cf05a0(992 files, +133057/−12580) and7cbff4fdonto4b9e05a2(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.mdhad 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.pyandsrc/program/generate.cppmerged on their own both times, and main's changes to them contain nologproband touch noLP,BTorGENline format. Against4b9e05a2the 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.cpponly gains lines: the wholeemit_lp_linepath is new here, and thereq_allowedclear that22fe5184takes out was itself introduced by the first commit, so it never shows as a deletion against the base. Nothing else insrc/moves.No conflict with today's
main(7dd5cf18, 24 October): GitHub reports this PRmergeable: true, and the independent run below merged it onto exactly that revision.Passed:
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 after22fe5184and is what the server was started with.eca6513b, the merged4e8211band 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 (104becfdhad 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, anymax_tokenson a reply that holds its entries, and no batch slots behind two replicas). On26a2d480the oneseca6513badded fail with a 400: a streamed reply withmax_tokensof 5000,0and none at all.test_logprobs_take_any_max_tokens(200 / 5000 / 0 / −1 / not sent, not streamed) andtest_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: amax_tokens1 decision through a realStrataEngineandServiceover HTTP with the fake engine ofserve/test_parallel.pybehind them (writing anLPline after eachTwhen theGEN/BGENline asks), thenallowed_token_idson 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 noLPlines 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 carriesmain's new tests, which is why the count is no longer 909). Both are known on a cleanupstream/maincheckout in this environment and touch no logprobs code:serve.test_winjob(running()on a pid this sandbox cannot read) andserve.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.--spec 4 --spec-min-p 0.5 --kv int8 --kv-resident 32768,temperature: 0,chat_template_kwargs.enable_thinking: false:stream: true, plain request → 6 entries,"".join(token)equal to the content character for character.stop: [".!"], which holds the tail — non-streamed and streamed → contentCafe costs 5., 6 entries each, the held5.flushed after the request left the queue with its own entries.allowed_token_ids: [16](the digit1, the id the model chose) → 200, one entry, one candidate at0.0— previously the 400 "the request was malformed", streamed and not.0-9, reply11→ 2 entries, 10 candidates each, most likely first,sum(exp(logprob)) = 1. Only the ended reply settles which of1and11was meant.allowed_token_idsover{0,1}, reply111→ 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 reply11,max_tokensabsent /0/200/4096/5000, each of them streamed and not → 200 ten times, 2 entries each, the tokens spelling11, the non-streamed replies carrying 5 candidates each.4b7339e1,allowed_token_idsover the ten digits15-24withmax_tokens: 5000, streamed → 200, 2 entries of 10 candidates spelling11;allowed_token_ids: [16](the digit the model chose), not streamed → 200, one entry, one candidate at0.0— previously the 400 "the request was malformed".4b7339e1,json_schemawithmax_tokensabsent /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 or5000were 400.4b7339e1,allowed_token_ids: [248320](the vocabulary size) → 400, still.1878675f, the same machine and engine but--parallel 2:max_tokens: 1withtop_logprobs: 5→ 200, one entry spelling the reply (A−0.062427, thenB−2.848,A−7.415);allowed_token_idsover 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 forOdd; four decisions at once on two slots → 200 each, 1.6 s for all four, every entry matching its reply;max_tokens5,max_tokensabsent andmax_completion_tokens: 0→ 400 namingmax_tokens1; a plain request and a 64-token reply unchanged.#3332merged with this branch ontomain7dd5cf18(both merged cleanly), CUDA build fromsetup.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_logprobs28/28 OK (the file had 28 tests at26a2d480);logprobs: true, top_logprobs: 5, max_tokens: 1returnedchoices[0].logprobs.content(B−0.018839, thenB−4.51,A−5.98) where the 0.1.48 engine returned no logprobs for the same request;allowed_token_idsagreed with the unrestricted top-K and the engine's ids matched the Hugging FaceQwen/Qwen3.8-Flash-Nexttokenizer. This is the only run on hardware that covers--mtp: the runs above used--spec 4 --spec-min-p 0.5without it.Failed: none observed.
Not run:
src/program/generate.cppis shared by the CUDA and HIP builds; only the CUDA configuration was built here (no AMD GPU or toolchain on this machine).CONTRIBUTING.mdasks 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.install_logprobsinsycl/serve/server_intel.py), and no Intel or Apple toolchain is present here.BTslot phase of--parallel/--batch: a reply longer than one token there has no entries, and is a 400; see Limits. What is measured is themax_tokens1 decision that works and the 400 for anything longer.Limits.
--parallel/--batch, only amax_tokens1 request carries logprobs; a longer reply is a 400, not a reply whose entries stop halfway. A slot printsBT <slot> <id>and its decode loop never callsemit_lp_line, and the line carries no slot id (LP <logprob> [id:logprob ...]), so with N slots interleaved on one stdout anLPline 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 readsBGEN <slot> 1asGEN 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 theGENpath 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."response_format: json_schemathe returned content may not be spelled by the tokens; in that case no logprobs are returned, by design.LPline 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.contentcan be shorter than the reply, and a client must pair entries by token, not by index.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 ownmax_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.#4056adds logprobs to/v1/completionson top of this and#3332;#4059reports 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.