Skip to content

[BugFix] fix generating endlessly bug when reasoner grammar & spec decoding are enabled#12008

Closed
justadogistaken wants to merge 1 commit intosgl-project:mainfrom
justadogistaken:bug/reasoner-structured-output-with-spec-decoding
Closed

[BugFix] fix generating endlessly bug when reasoner grammar & spec decoding are enabled#12008
justadogistaken wants to merge 1 commit intosgl-project:mainfrom
justadogistaken:bug/reasoner-structured-output-with-spec-decoding

Conversation

@justadogistaken
Copy link

@justadogistaken justadogistaken commented Oct 23, 2025

Motivation

Related to #9187 and #11550.

When reasoner grammar and spec decoding are enabled at the same time.
The model will generate <think> first, and nothing would be generated till reach max_tokens.

I found that the problem comes from allocate_token_bitmask.fill_(0) and reasoner grammar.

def traverse_tree(
    retrieve_next_token: torch.Tensor,
    retrieve_next_sibling: torch.Tensor,
    draft_tokens: torch.Tensor,
    grammar: BaseGrammarObject,
    allocate_token_bitmask: torch.Tensor,
):
    """
    Traverse the tree constructed by the draft model to generate the logits mask.
    """
    assert (
        retrieve_next_token.shape == retrieve_next_sibling.shape == draft_tokens.shape
    )

    allocate_token_bitmask.fill_(0)

    def dfs(
        curr: int,
        retrieve_next_token: torch.Tensor,
        retrieve_next_sibling: torch.Tensor,
        parent_pos: int,
    ):

Modifications

Accuracy Tests

Benchmarking and Profiling

Checklist

@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @justadogistaken, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request resolves a significant bug that caused models to enter an infinite loop of empty string generation when using reasoner grammar alongside speculative decoding. The fix involves refining how grammar states are managed and copied, particularly during vocabulary mask generation, and introducing more precise control over when tokens are masked. These changes ensure that the grammar's state is correctly preserved and that masking logic is applied only when appropriate, leading to more stable and predictable model output.

Highlights

  • Bug Fix: Addresses a critical bug where enabling both reasoner grammar and speculative decoding could lead to the model generating an endless sequence of empty strings ('') until max_tokens is reached. This was traced to incorrect vocabulary masking logic during the reasoning phase.
  • Grammar State Management: Introduced a new abstract method accept_token_length to BaseGrammarObject and implemented it in XGrammarGrammar and ReasonerGrammarObject to accurately track the number of accepted tokens, improving grammar state handling.
  • Precise Vocabulary Masking: Modified ReasonerGrammarObject to correctly manage vocabulary masking based on whether the model is currently in a reasoning phase (is_in_reasoning) or has just generated the </think> end token. This prevents unintended masking during critical reasoning steps.
  • Preventing Side Effects: Ensured that the grammar object is copied (req.grammar.copy()) before being used in the dfs function within generate_token_bitmask. This prevents modifications to the grammar state during bitmask generation from affecting other parts of the system, such as speculative verification.
  • Robust Rollback Logic: Added a condition (grammar.accept_token_length() > 0) to the dfs function's rollback logic to prevent attempting to rollback when no tokens have been accepted by the grammar, enhancing stability.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request effectively addresses a critical bug causing an infinite loop when reasoner grammar and speculative decoding are enabled simultaneously. The core of the fix involves introducing accept_token_length() to prevent erroneous rollbacks on the grammar, and ensuring that a copy of the grammar object is used during speculative tree traversal to preserve its state. The changes to ReasonerGrammarObject to correctly manage its state during the reasoning phase are also well-implemented. Overall, the logic is sound and the fix appears robust. I have a couple of minor suggestions to improve code clarity and consistency.

@justadogistaken justadogistaken changed the title [Bug] fix bug when reasoner grammar & spec decoding are enabled [Bug] fix generating endlessly bug when reasoner grammar & spec decoding are enabled Oct 23, 2025
@justadogistaken justadogistaken force-pushed the bug/reasoner-structured-output-with-spec-decoding branch 5 times, most recently from 290760b to c3acf3c Compare November 3, 2025 04:06
@justadogistaken justadogistaken changed the title [Bug] fix generating endlessly bug when reasoner grammar & spec decoding are enabled [BugFix] fix generating endlessly bug when reasoner grammar & spec decoding are enabled Nov 5, 2025
@justadogistaken
Copy link
Author

Test

Problem Solved with this pr. And this has been deployed in production.

Request

curl 'http://localhost:30000/v1/chat/completions' \
-H 'Content-Type: application/json' \
-d '{
    "model": "Qwen/Qwen3-8B", 
    "messages": [ 
        {
            "role": "system",
            "content": "You are a highly advanced and versatile AI assistant."
        },
        {
            "role": "user",
            "content": "Tell me about the latest advancements in AI."
        }
    ],
    "max_tokens": 1000,
    "response_format": {
        "type": "json_object"
    }
}'
image image image

@justadogistaken justadogistaken force-pushed the bug/reasoner-structured-output-with-spec-decoding branch from c3acf3c to 6c38950 Compare November 6, 2025 10:18
@Leoyzen
Copy link
Contributor

Leoyzen commented Nov 19, 2025

Will this PR being merge?I've use this pr for quite a long time to prevent the hang issues.

@justadogistaken
Copy link
Author

@hnyls2002 @merrymercy @Ying1123 @kssteven418 Hi, could you help review this pr?

@LorrinWWW
Copy link
Collaborator

@justadogistaken could you resolve the conflicts, tysm!

@justadogistaken
Copy link
Author

@LorrinWWW The problem seems to be solved in the latest version. I will close the pr. But I found there is another problem. Could you help review this?

ref #14480

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