Repository navigation
Conversation
This was referenced Sep 28, 2026
Closed
…ecked before a stream opens - The CUDA server reads `stop` (a string or a list) and cuts the reply token by token: at the first token whose text completes a stop string, the reply's tokens end there, on_tokens returns True, and the match and everything after it are left out. Drafted rounds of many tokens and "draft": false rounds of one therefore give the same content, usage and token_sha. With return_token_ids, the ids listed end at the same token. - The 27B (one GPU and two ranks), and Flash Next, Nemotron and Qwen3.6 on one GPU, stop in the round that holds the match; concurrent streams stop after a later round. GLM, and Flash Next and Nemotron on two ranks, decode on to an end token or the reply limit, and the server returns the reply only up to the match. A reply cut at a stop string finishes normally; only a client that has gone raises RequestCancelled. - Streamed deltas hold back an end that may begin a stop string, as on the Mac (StopPolicy.visible); stop strings match the generated text, reasoning included, before it is split; tool calls are parsed from the cut text. - A non-boolean ignore_eos or a malformed stop is refused with HTTP 400 before any stream bytes (stop_options, as on the Mac). - Where the engine reads ignore_eos (GLM), end tokens inside the reply are text, as on the Mac, and finish_reason is "length" unless a stop string or a tool call ended the reply. - StopStrings sits beside StreamDecoder in cuda/reply_text.py. docs/api.md: stop on both backends.
- Qwen27Engine.generate takes stop_eos (default True) and passes it to draft_decode on one GPU and to decode_tp on rank 0 of two. Rank 1 follows rank 0's windows and never reads it, so the request header is unchanged. - With --parallel N, Scheduler.submit takes stop_eos and each Stream carries it; MultiDecoder accepts and ends a stream at end tokens only when its own request stops at them. Rank 1 commits the paths rank 0 sends, so the ADMIT message is unchanged. - The server passes stop_eos=not ignore_eos to an engine whose generate takes it (the signature check it already makes for "draft"), in each run of a reply that tool_choice "required" restarts too. With ignore_eos, end tokens inside the reply are text, as on the Mac, and finish_reason is "length" unless a stop string or a tool call ended the reply. Stop strings stay active. - Serial, drafted and concurrent decoding apply the same end rule, the first token of a concurrent stream's prefill step included; states kept at message starts and prompt ends are taken during prefill, so no token past an end token enters a cache. - docs: ignore_eos on MLX, GLM CUDA and the 27B CUDA engine; Flash Next, Nemotron and Qwen3.6 CUDA still stop at end tokens.
nood-co1
force-pushed
the
contrib/cuda-stop-and-ignore-eos
branch
from
September 28, 2026 18:45
7e78fe4 to
3f5e339
Compare
Owner
|
Stop strings on every CUDA engine and |
BlivionIaG
referenced
this pull request
in BlivionIaG/TensorFold
Oct 20, 2026
…l steps and kept states
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Issue #46 was closed by eea15fd, which brought
ignore_eosand stop strings to the Mac server and changed no file undercuda/. This PR does the same for CUDA, in two commits. The first can be taken without the second:stop, checksstopandignore_eosbefore a stream opens, and cuts the reply token by token, so drafted and"draft": falsereplies return the same content, usage andtoken_sha.ignore_eoson the Qwen3.8-27B CUDA engine, on one GPU, on two ranks and with--parallel N. The Flash Next, Nemotron and Qwen3.6 CUDA engines still stop at end tokens.Why
Q/issrc/tensorfold/families/qwen3_5/cuda/. References are atmain(71377a5, 0.3.6.2).docs/api.md:30listsignore_eosfor "MLX and GLM CUDA",:31listsstopfor "MLX" only, and:36says "Its Qwen engines also ignoreignore_eos."ignore_eos: true(tools/bench_openai.py:26), anddocs/recipes/README.md:49-50warns that "the Qwen CUDA engines can stop at EOS before the requested limit". A 27B cell can therefore time replies shorter than--tokens.cuda/server.pyreads nostop: the only"stop"in it is the finish label (:312). A CUDA client that sendsstopgets the whole reply. The server also accepts a non-booleanignore_eos; the GLM app reads it withbool()(glm5_next/cuda/app.py:55).server/stopping.py:9-55(stop_options,StopPolicy) is used only by the Mac server.stop_eos:serial_decodeanddraft_decode(Q/decode.py:85,:183) anddecode_tp(Q/decode_tp.py:159). The CUDA tests compare drafted with serial atstop_eos=False(tests/cuda/test_qwen27_prefill.py:104-105,tests/cuda/test_qwen27_forward.py:130,:153,tests/cuda/test_qwen27_exl3.py:108,:126). ButQwen27Engine.generatenever passes it (Q/engine.py:175-176,:200-201), andMultiDecodertakes one decoder-wide flag (Q/multi.py:67,:73) that the engine never sets.Change
Commit 1: stop strings on every CUDA engine
App._preparecallsstop_options, the Mac's validator. A non-booleanignore_eosor a malformedstopgets HTTP 400 before any stream bytes, fromprepare,checkandGlmApp.checkalike.PreparedRequestcarriesignore_eosandstop.App.runchecks each new token in order.StopStrings.hitdecodes only the tail that can hold a new match: the longest stop string's UTF-8 length plus 8 tokens. (The Mac keeps its length in characters plus 8, which can miss a match of multi-byte characters when a token is one byte.)StopStringssits besideStreamDecoderincuda/reply_text.py. At the first token whose text completes a stop string:on_tokensreturns True; an engine that calls on after that gets True fromgenerate_gated(0.3.6.2), which does not callon_tokensagain for the reply;finish_reasonisstop;token_shaand the idsreturn_token_idsreturns count the tokens through that token.on_tokens' error capture from fix: the CUDA server stops a request when its client has gone or its per-token work fails #57: a reply cut at a stop string finishes normally, and only a client that has gone raisesRequestCancelled.StopPolicy.visible(partial=True), the Mac's rule). The match and everything after it are left out. Stop strings match the generated text, reasoning included, beforesplit_thinking, as on the Mac (server/app.py:470-476,:495-497). Tool calls are parsed from the cut text.glm5_next/cuda/decode.py:453-454;qwen4_exp/cuda/engine.py:285-286;nemotron_h/cuda/app.py:230-231). The server returns the reply only up to the match.ignore_eoswhere the engine reads it (GLM,GlmApp.reads_ignore_eos): end tokens inside the reply are decoded into its text, andfinish_reasonislengthunless a stop string or a tool call ended the reply. This is the Mac's handling: withignore_eos,StopPolicy.eos_idsis empty (server/stopping.py:26), so no token ends the stream (server/app.py:466) or is stripped from the end (:493).docs/api.md:stopon both backends, and how CUDA applies it.Commit 2:
ignore_eoson the 27B's CUDA engineQwen27Engine.generate(..., draft=True, stop_eos=True)passesstop_eostodraft_decodeon one GPU and todecode_tpon rank 0 of two. Rank 1 never reads it: rank 0 alone decides when the windows end (Q/decode_tp.py:186-188) and which rows are kept (:231). The request header is unchanged.generateand decoders, so the flag reaches them too,<|im_end|>included: since 0.3.6.2 their end tokens include the onesgeneration_config.jsonlists (fix: Qwen3.8 Flash Next and 27B on EXL3 checkpoints stop at the end of the chat turn #69).Q/decode.py,Q/decode_tp.pyandQ/multi.pyhave no EXL3 branch.--parallel N:Scheduler.submit(..., stop_eos=True)stores the flag on the request'sStream.MultiDecoder._ends(s)gives the end tokens for that stream (none when it ignores them). The prefill step that takes a stream's first token,acceptandtakeuse it in place of the decoder-wideself.eos(Q/multi.py:145,:195,:201). Rank 1 builds its streams from the ADMIT message, prefills them in the steps rank 0 names and commits the paths rank 0 sends (Q/multi.py:342-356). The messages are unchanged.stop_eos=not ignore_eosonly to an engine whosegeneratetakes it, with the same signature check it makes fordraft(cuda/server.py:113). It goes through thegeneratethatgenerate_gatedcalls, so each run of a reply thattool_choice: "required"restarts gets it too. GLM keeps its own handling. Withignore_eoson the 27B, end tokens inside the reply are text, andfinish_reasonislengthunless a stop string or a tool call ended it, as in commit 1. Stop strings stay active.ignore_eoson MLX, GLM CUDA and the 27B CUDA engine; Flash Next, Nemotron and Qwen3.6 CUDA still stop at end tokens (docs/api.md,docs/recipes/README.md).docs/recipes/adding-a-cuda-family.mddescribesstop_eosingenerateand thereads_ignore_eosroute GLM takes.Not in this PR:
ignore_eosfor Flash Next, Nemotron and Qwen3.6 on CUDA. Each can follow the 27B's route (stop_eosingenerate).Behaviour changes
stopon any CUDA enginefinish_reasonstopignore_eosnot a boolean, orstopmalformed (CUDA)ignore_eos: trueon the 27B CUDA enginefinish_reasonlengthignore_eos: trueon GLM CUDAfinish_reasonstopif the last token was onefinish_reasonlengthignore_eos: trueon Flash Next, Nemotron or Qwen3.6 CUDAExactness
token_shaafter the cut. No arithmetic changes. An engine that decodes on after the cut changes nothing the client receives.ignore_eos. One flag reaches every 27B decode path, and each applies the same end rule with it: serial (Q/decode.py:94), drafted (Q/decode.py:205,:237), two ranks (Q/decode_tp.py:187,:231) and concurrent (cuda/streams.py:64inaccept,:43intake).stop_eos=Falseis the setting the CUDA tests already compare drafted with serial at. Drafts, verify windows, sampling keys and commits are unchanged.Q/engine.py:167-171;Q/multi.py:159-164), so no token past an end token enters a cache.On GPU, commit 2's tests pass on one Spark, and served
ignore_eosreplies give the sametoken_shadrafted and with"draft": falseon one Spark and on two (GPU status, below). EXL3 packs and a served--parallel 2have not run.Tests
Host: macOS, 36 GiB, Python 3.13.5, PyTorch 2.11.0 CPU, MLX 0.31.1, an import-only stand-in for Triton (no kernel launches). The three new test files also pass without it.
tests/test_cuda_stop_strings.py(commit 1, 168 cases). A byte-level tokenizer (one token per byte, so a character can span tokens) and fake engines that deliver drafted rounds of 1 to 7 tokens, or one token a round for"draft": false. Chat and raw completions, streamed and not.stop,completion_tokensandtoken_sha. The drafted engine ended in the round that holds the match, and the serial one at the matching token.return_token_ids, drafted and serial replies, streamed and not, return the ids through the token that completes the match, with theirtoken_sha.ignore_eosorstop, on the plain and the GLM app: HTTP 400, no stream bytes, no engine call, andcheck()agrees.ignore_eoson an engine that reads it: end tokens are text, finishlength(also when the reply limit falls on an end token), stop strings still apply, and tool calls are parsed from text that keeps the end tokens. On an engine that does not read it, replies are unchanged.tests/test_cuda_27b_ignore_eos.py(commit 2, 27 cases). The server passesstop_eosonly to an engine whosegeneratetakes it, and to each run of atool_choice: "required"reply that the call gate restarts. Stop strings stay active underignore_eos.acceptandtakefollow the end tokens they are given. The 27B'sMultiDecoderruns over a scripted model on the CPU stand-ins oftests/test_cuda_failed_admission.py, with a stream that stops and one that ignores end tokens side by side, drafted and serial, including a first token that is an end token. The scheduler hands the flag to its stream.Qwen27Engine.generatepassesstop_eostodraft_decodeon one GPU, todecode_tpon rank 0 of two, and to its scheduler. The ADMIT message and the header rank 1 reads are unchanged.tests/cuda/test_qwen27_ignore_eos.py(commit 2, GPU, 8 cases). Fixtures are built as intests/cuda/test_qwen27_multi.py, with centred weights (a group's bias is -7.5 times its scale; with that file's biases a greedy path repeats one token). Each path's end token is a token it first produces after its first token and before its last, or its first token when it repeats one token. Each test asserts that at least one of its replies stops after its first token.draft_decodewithstop_eos=Falseand a drafter that proposes the true continuation (chains of 2 to 5, so the end token is accepted mid-round) equalsserial_decodewithstop_eos=False. Withstop_eos=Trueboth stop at the end token.Qwen27Engine.generatewith and withoutstop_eosequals a fresh prefill plusserial_decode: drafted from a fresh prefill,"draft": false, and a longer prompt resumed from the first prompt's kept end.MultiDecoder: three streams (two drafted, one serial), one of them ignoring end tokens, each equal to its serial reference with its own flag.Scheduler: three concurrent requests, one ignoring end tokens, each equal to its serial reference.test_cuda_stop_strings.pyonmain's sources (71377a5)test_cuda_27b_ignore_eos.pyon commit 1ignore_eos: true, and the existingaccept/takerule)testswithouttests/cuda),main(71377a5)The same 154 ids fail or error in all three whole-suite runs, and none is in this PR's test files. Their causes on this host include
transformersclasses that are not installed (AutoTokenizer,GenerationMixin), no Triton backends, MLX 0.31.1 where GLM-5.3-Flash needs 0.32.2, a memory-window test that expects a Mac with 64 GiB or more, and files outsidesrcandtests(tools/,CHANGELOG.md) that the test tree used here did not include. Twenty-two one-line breakages of the change, each applied alone, each fail between 1 and 68 cases of the two host files; they include a stop-string cut that raisesRequestCancelled, atool_choice: "required"re-run withoutstop_eos, and a concurrent stream's first token taken with the decoder's end tokens.GPU status
Step 1, step 2 without its EXL3 file, and step 3 on one Spark and on two Sparks with
--tp 2passed. Surface: DGX Spark (GB10), one for steps 1 and 2 and the one-Spark check, two for the--tp 2check; thetensorfold-benchimage (PyTorch 2.13.0a0, NVIDIA 26.07; CUDA 13.3),TORCH_CUDA_ARCH_LIST=12.1; TensorFold 3f5e339 (commit 2), this branch onmain71377a5, imported from the branch's tree.python3 -m pytest tests/cuda/test_qwen27_ignore_eos.py(toy models)python3 -m pytest tests/cuda/test_qwen27_multi.py tests/cuda/test_qwen27_prefill.py tests/cuda/test_qwen27_forward.py tests/cuda/test_qwen27_client_gone.py(toy models)main(71377a5), in itstests/cudarun: the same 35 passedStep 3: the 27B, Qwen3.8-27B-MLX-4bit (70ae7fac) with the DFlash2 drafter (50307d4c), under
tensorfold serve <Qwen3.8-27B-MLX-4bit directory> --drafter <DFlash2 directory>,--tp 1on one Spark and--tp 2across two. Each request is the chat message "Reply with the single word: yes", greedy (temperature0), thinking off,max_tokens256.--tp 2ignore_eosyes, 2 tokens,finish_reasonstopyes, 2 tokens,stopignore_eos: true, draftedlength,token_shaa9d4bf8e3f47length,643191f611c4ignore_eos: true,"draft": falselength,a9d4bf8e3f47length,643191f611c4stop, a string first found after the model's first end token[" \"yes\".\n"]["d with \""]ignore_eosandstop, draftedstop,3b56ffac2404stop,60287c7e016aignore_eosandstop,"draft": falsestop,3b56ffac2404stop,60287c7e016aignore_eosreply begins withyes, then<|im_end|>and<|endoftext|>as text.ignore_eosreply up to that string, which is left out."draft": false, one round per token after the first (46 and 87).token_shais compared within a rank count. The one-Spark and two-Sparkignore_eosreplies differ: each rank count has its own serial reference (docs/recipes/qwen3.8-27b.md:58-59).Not run:
tests/cuda/test_qwen27_exl3.pywithTENSORFOLD_QWEN27_EXL3andTENSORFOLD_QWEN27_DRAFTERset, so that its checkpoint tests runQwen27Engine.generate: no EXL3 pack of the 27B was on the test machines.--parallel 2repeat (two concurrent requests, one withignore_eos).tools/bench_openai.pyagainst the 27B. Expected: every cell'scompletion_tokensequals--tokens.ignore_eoschange: GLM on two Sparks withignore_eos: trueand a prompt it ends early. Expected: the reply's text holds the end token's text where the model ended,finish_reasonislength, and drafted and"draft": falsegive the sametoken_sha.Evidence
From reading the code at
main, the host tests above and the GPU runs under GPU status. No speed figure is claimed.Overlaps
mainsince 0.3.6.2, this branch's base: the client-disconnect change in fix: the CUDA server stops a request when its client has gone or its per-token work fails #57 (App.run'scancelledandon_tokens' error capture, which the stop-string cut runs inside), the one-stream K/V limit in fix: the 27B's one-stream CUDA engine keeps K/V buffers within the admitted window #58 and the admission fix in fix: a failed admission no longer stops the 27B's concurrent CUDA scheduler #59. Also in 0.3.6.2: concurrent 27B serving with prefill steps and states kept at message starts (DGX Spark, Qwen3.8-27B: exact concurrent serving on the CUDA engine, 156 tok/s at 16 requests in half vLLM's memory (numbers, before a PR) #38), which commit 2'smulti.pyand test stand-ins follow; the CUDA server's text helpers incuda/reply_text.py, whereStopStringsjoins them; Qwen3.6 on CUDA (DGX Spark, Qwen3.6-35B-A3B: a CUDA family for single-Spark deployments? (happy to build it) #45);tool_choice: "required"on the CUDA server (tool_choice: "required" is accepted but not enforced #52); and a tool call inside an unclosed think block (Tool call emitted inside an unclosed think block is dropped (empty turn, finish_reason=stop) #60), parsed here from the cut text.docs/api.mdand 4 incuda/server.py(the imports,PreparedRequest's fields,_prepare's return and thesamplingline inrun). The resolution (both imports;samplingbeforeignore_eosandstopinPreparedRequest; the request built with all three;prepared.samplinginrun) passes both PRs' host test files, 399 tests. The 399 tests ran on that merged tree.engine.py: 2 blocks,inplace=Trueagainststop_eos=, both on keyword lines;multi.pymerges clean. On a merged tree with both sides kept, and with the host-test stand-ins taking the other's keywords (prefill,prefill_tp,prefill_stateandkeptin this PR's file,draft_decodeanddecode_tpin that PR's), both PRs' host files pass (477 passed; 5 skipped, that PR's template tests without the tokenizer files). This PR's GPU testtest_engine_decodes_past_end_tokens_and_keeps_only_prompt_endsexpects whole-prompt entries, so its expectedcachedvalues and entries change with that PR.docs/api.md(itsresponse_formatrow against this PR'signore_eosandstoprows);Scheduler.submit(constraintagainststop_eos); incuda/server.py,PreparedRequest's fields,_prepare's return and thegeneratecall (**extraagainst**options); in the 27B'sengine.py,generate's signature, the scheduler call and thedraft_decodecall; inmulti.py, the commit inround(its grammar step beforetakeagainst_ends(s)).streams.pymerges clean. One region merges without a conflict but does not run: git takes feat(cuda): response_format JSON schemas on the 27B, exact under drafting and --parallel #80's replacement ofrun'sdraft = ...line, which this PR'soptionsreads (an undefined name; with only the blocks resolved, 91 of the host tests below fail). Resolution tested: incuda/server.py,draftandoptionsrestored inrun, feat(cuda): response_format JSON schemas on the 27B, exact under drafting and --parallel #80'sconstraintadded tooptions, and both PRs' fields inPreparedRequestand_prepare's return; indocs/api.md,Scheduler.submitandengine.py, both PRs' rows and keywords; inmulti.py, feat(cuda): response_format JSON schemas on the 27B, exact under drafting and --parallel #80's grammar step, thentake(new, self._ends(s)). This PR's host test of the scheduler call then expectsconstraint=Nonebesidestop_eos. With that, both PRs' host test files pass: 220 passed, 14 skipped (feat(cuda): response_format JSON schemas on the 27B, exact under drafting and --parallel #80's cases that need xgrammar, which is not installed on the test host). Read from the code and not tested on a GPU: on the merged tree, a request with bothignore_eos: trueand a schema keeps decoding after the grammar takes its stop token, unmasked, up tomax_tokens(Constraint.windowleaves rows unconstrained from then on), so the schema does not cover that continuation.cuda/reply_text.py, which merges clean. On the merge, 4 cases of this PR's host tests fail (242 passed):test_tool_calls_are_parsed_from_the_truncated_textandtest_ignore_eos_tool_calls_are_parsed_from_text_that_keeps_end_tokensexpect the integer parametervalueas the text"1", which the CUDA parser then returns as1. With those two expectations changed to1, both PRs' host files pass on the merged tree: 246 tests.cuda/server.py. The merge is clean, and both PRs' host files pass on it: 196 tests.docs/api.mdand merges clean with this branch. fix: say why a CUDA start is silent (SIGUSR1 stack dump, extension builds, stale build locks) #62, CUDA: read the Flash Next NVFP4 (ModelOpt FP4) checkpoint as it ships #67, perf: Flash Next reads a prompt chunk's n-gram rows on 16 threads (same bytes) #73, fix: preserve prefixes when checkpoint cannot fit #74, fix: qwen3_5_moe CUDA graphs capture into a new pool after the buffers grow #78 and perf: Improve cuda startup/loading performance (3-15x faster on DGX spark) #82 share no file with it.return_token_ids) shipped in 0.3.6. InApp.run,return_token_idsreturns the ids cut at a stop string, andparse_tool_calls, which reads GLM calls since fix: parse GLM's <arg_key>/<arg_value> tool calls in both servers #35, receives the cut text.mainsince 0.3.6.2, this branch's base.Submitted by an agent from Blockbrain Labs (https://x.com/blockbrain_labs, https://github.com/blockbrain-ai).