Skip to content

Fix guided generation: include <|endoftext|> as stop token#117

Merged
stikves merged 2 commits into
apple:mainfrom
stikves:fix/endoftext-stop-token
Jul 22, 2026
Merged

Fix guided generation: include <|endoftext|> as stop token#117
stikves merged 2 commits into
apple:mainfrom
stikves:fix/endoftext-stop-token

Conversation

@stikves

@stikves stikves commented Jul 20, 2026

Copy link
Copy Markdown
Contributor

Qwen3 models declare eos_token as <|im_end|> (151645) but the grammar (xgrammar) can also produce <|endoftext|> (151643) as a valid terminal. Since 151643 wasn't in the stop sequences, it passed through to the output as literal text, corrupting structured generation results.

Add 'endoftext' to the turnEndPatterns so it's picked up from added_tokens_decoder alongside im_end, end_of_turn, and eot_id.

@stikves
stikves force-pushed the fix/endoftext-stop-token branch from e46255c to 0af57a8 Compare July 20, 2026 18:41
@stikves
stikves marked this pull request as ready for review July 21, 2026 19:27
@stikves
stikves requested review from alejandro-isaza, carinapeng, kevchengcodes and tjia1818 and removed request for alejandro-isaza July 21, 2026 19:27
…xt|>

Two fixes for the same bug (defense in depth):

1. When the grammar session terminates (isTerminated), return nil
   immediately instead of emitting the terminal token's decoded text.
   This prevents ANY special token from leaking into structured output,
   regardless of whether it's in the stop sequences list.

2. Add 'endoftext' to turnEndPatterns so <|endoftext|> (token 151643)
   is picked up from added_tokens_decoder as an additional stop token.
   Qwen3 declares eos_token as <|im_end|> (151645) but xgrammar can
   also produce <|endoftext|> as a valid grammar terminal.
@stikves
stikves force-pushed the fix/endoftext-stop-token branch from fe08dc7 to 30ec088 Compare July 21, 2026 19:30
@stikves
stikves merged commit cba2c84 into apple:main Jul 22, 2026
3 checks passed
@stikves
stikves deleted the fix/endoftext-stop-token branch July 22, 2026 03:22
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants