Skip to content

[None][fix] Replay generated tokens into the guided-decoding matcher after a recompute - #22382

Closed
arusli-nv wants to merge 2 commits into
NVIDIA:mainfrom
arusli-nv:ft/F2a-guided-recompute-replay
Closed

arusli-nv wants to merge 2 commits into
NVIDIA:mainfrom
arusli-nv:ft/F2a-guided-recompute-replay

Conversation

@arusli-nv

@arusli-nv arusli-nv commented Nov 16, 2026 •

Copy link
Copy Markdown
Collaborator

Dev Engineer Review

  • GuidedRequest.from_llm_request sets tokens_to_replay only when all three conditions hold: the request is on its last context chunk, it has guided decoding params, and prompt_len > orig_prompt_len. The tokens are get_tokens(0)[orig_prompt_len:prompt_len]. Other requests keep tokens_to_replay = None.
  • GuidedDecoder._build replays these tokens only inside the branch that creates a new matcher. The loop stops when matcher.is_terminated() is true. A rejected token raises ValueError with the request ID, slot, and token.
  • The tests expect a rejected replay to mark only that request as failed. The diff does not show how _build handles the exception. The test asserts the failure, but the handling itself is not in the diff.
  • CapturableGuidedDecoder subclasses GuidedDecoder and does not define its own _build. It therefore uses the same replay path through inheritance.
  • A matcher is created only inside the creation branch. Confirm that a matcher is always created on the last context chunk, where tokens_to_replay is set. Otherwise, replay is skipped silently. This path is not verified in the diff.
  • test_warmup.py adds prompt_len=1 and orig_prompt_len=1 to the fake guided request. Without these fields, the new from_llm_request comparison fails on the fake request. This change is required and does not expand scope.

QA Engineer Review

Test files changed:

  • tests/unittest/_torch/misc/test_guided_decoder_bitmask.py adds three GPU-gated tests:
    • test_recompute_replays_generated_tokens_into_matcher[accepted]: expects no failed requests, matcher.accepted == [10, 11], and a next-token mask value of 1.
    • test_recompute_replays_generated_tokens_into_matcher[rejected]: expects request 7 to fail with text containing rejected token 10, and a mask value of 0.
    • test_recompute_replay_stops_at_terminated_matcher: uses a matcher that terminates after accepting EOS token 10. Expects replay to stop, matcher.accepted == [10], and a mask value of 0.
  • The helper _build_recomputed_request calls reset_for_recompute with _UNBOUNDED_PAUSE_MAX_INPUT_LEN. The file also imports this constant from py_executor.
  • tests/unittest/_torch/pyexecutor/engine/runners/decoder/test_warmup.py adds prompt_len=1 and orig_prompt_len=1 to the guided-batch fake request in test_general_warmup_oom_restores_guided_batch_queue.
  • The diff does not change tests/integration/test_lists/test-db/ or qa/. Whether these tests run in CI test-db lists is not verified.
  • Coverage verdict: needs follow-up. The accept, reject, and terminated-matcher paths are covered. Not covered: a guided request without recompute, a recomputed request that is not on its last context chunk, and the CapturableGuidedDecoder path directly.

Per-File QA Perspective

  • tensorrt_llm/_torch/pyexecutor/guided_decoder.py: Recomputed guided requests now replay generated tokens into a newly created matcher. Verify that a rejected replay fails only that request and that the error names the rejected token. Verify that non-guided requests and guided requests without recompute behave as before.
  • tests/unittest/_torch/misc/test_guided_decoder_bitmask.py: Adds accepted, rejected, and terminated-matcher recompute tests. All three require a GPU. Their CI placement is not verified.
  • tests/unittest/_torch/pyexecutor/engine/runners/decoder/test_warmup.py: The fake guided request gains prompt length fields. This change alters no runtime behavior.

Description

Bug. When the KV cache runs short, the executor pauses a running request and prefills it again later, with
its generated tokens moved into the prompt (PyExecutor._pause_recompute_request,
LlmRequest.reset_for_recompute). Guided decoding then creates a fresh grammar matcher at the last context chunk.
That matcher has not seen the tokens already generated, so the next-token mask is built as if no output existed,
and a structured-output request can produce output that its grammar rejects.

Who hits it. Guided decoding / structured output requests (JSON schema, regex, EBNF grammar, structural tag)
that are paused and recomputed because of KV cache pressure.

Fixes #18891. Same approach as #19307 by @Ritabanm, rebased on current main.

Fix.

  • GuidedRequest.tokens_to_replay holds the tokens past the C++ orig_prompt_len, taken at the last context
    chunk of a guided request whose prompt grew, that is, a recomputed request. The C++ orig_prompt_len keeps the
    user's prompt length across a recompute, while py_orig_prompt_len is reset to the longer prompt, so the tokens
    past orig_prompt_len are exactly the ones to replay.
  • GuidedDecoder._build accepts those tokens into the matcher it creates, before it fills the mask. A token the
    grammar rejects fails only that request, with the token in the error message. CapturableGuidedDecoder runs the
    same _build, so it replays them as well.
 reset_for_recompute: prompt := prompt + generated   (C++ orig_prompt_len keeps the user's prompt length)
 last context chunk of a guided request with prompt_len > orig_prompt_len
   GuidedRequest.tokens_to_replay = tokens[orig_prompt_len:prompt_len]
   GuidedDecoder._build: new matcher --accept_token(each replayed token)--> fill bitmask
                                      --rejected--> that request fails

Risk. Low. Without a recompute tokens_to_replay is None and nothing changes; requests without guided
decoding are unaffected.

Test Coverage

  • tests/unittest/_torch/misc/test_guided_decoder_bitmask.py::test_recompute_replays_generated_tokens_into_matcher[accepted],
    [rejected] (GPU): a real LlmRequest recomputed with reset_for_recompute; the new matcher accepts the
    generated tokens and the request gets a next-token mask, or a matcher that rejects a replayed token fails only
    that request and it gets no mask.
  • tests/unittest/_torch/pyexecutor/engine/runners/decoder/test_warmup.py: the fake request of
    test_general_warmup_oom_restores_guided_batch_queue gains prompt_len and orig_prompt_len, which every real
    LlmRequest has.

With and without the fix: both cases of the new test fail on main and pass with the fix. The changed
test_warmup.py test passes on main and with the fix.

pytest tests/unittest/_torch/misc/test_guided_decoder_bitmask.py -k recompute
pytest tests/unittest/_torch/pyexecutor/engine/runners/decoder/test_warmup.py

PR Checklist

Please review the following before submitting your PR:

  • PR description clearly explains what and why. If using CodeRabbit's summary, please make sure it makes sense.

  • PR Follows TRT-LLM CODING GUIDELINES to the best of your knowledge.

  • Test cases are provided for new code paths (see test instructions)

  • If PR introduces API changes, an appropriate PR label is added - either api-compatible or api-breaking. For api-breaking, include BREAKING in the PR title.

  • Any new dependencies have been scanned for license and vulnerabilities

  • CODEOWNERS updated if ownership changes

  • Documentation updated as needed

  • Update tava architecture diagram if there is a significant design change in PR.

  • The reviewers assigned automatically/manually are appropriate for the PR.

  • Please check this after reviewing the above items as appropriate for this PR.

GitHub Bot Help

To see a list of available CI bot commands, please comment /bot help.

…after a recompute

A recompute moves the generated tokens into the prompt, and the new grammar matcher started from the
start of the grammar. Accept those tokens into the new matcher first, and fail the request on a rejected one.

Signed-off-by: Andrew Rusli <[email protected]>
@arusli-nv

Copy link
Copy Markdown
Collaborator Author

/bot run

@coderabbitai

coderabbitai Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

The guided decoder captures tokens added to a guided request’s prompt during recompute. When it creates a matcher, it replays those tokens in order, stops if the matcher terminates, and reports an error if the matcher rejects a token.

Changes

Guided decoding recompute

Layer / File(s) Summary
Capture recompute tokens
tensorrt_llm/_torch/pyexecutor/guided_decoder.py
GuidedRequest stores tokens between orig_prompt_len and prompt_len when a guided request reaches its last context chunk.
Replay tokens and validate outcomes
tensorrt_llm/_torch/pyexecutor/guided_decoder.py, tests/unittest/_torch/misc/test_guided_decoder_bitmask.py, tests/unittest/_torch/pyexecutor/engine/runners/decoder/test_warmup.py
_build replays stored tokens through the matcher, stops when the matcher terminates, and reports rejected tokens as request errors. Tests check accepted and rejected tokens, EOS termination, next-token masks, and the warmup fixture’s prompt lengths.

Estimated code review effort: 2 (Simple) | ~15 minutes

Change: Bug fix · Severity of issue fixed: Medium

Merge Risk: Minimal · up to 38910

This change restores guided-decoding grammar progress after a request is paused and recomputed under KV-cache pressure. It affects only guided requests that were recomputed, and no actionable merge-blocking risk was identified.

Security architecture risk: Minimal · up to 38910

The change restores structured-output constraints when a request resumes after recomputation. The inspected change preserves existing failure handling and introduces no identified expansion of access or authority.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The changed flow operates on the recomputed request’s own token snapshot and sequence-slot matcher. The inspected delta does not introduce cross-request token sharing, an additional caller authority or a new external execution sink.

Trust Boundaries and Controls

  • observed — Replayed token IDs must pass the existing matcher’s acceptance control before mask construction. Rejection records a failure against the request ID. The executor routes that failure through its existing handler with charge_budget disabled; the normal nonfatal path marks the request complete, creates an error response and removes it from active requests, subject to existing transfer-ownership deferral.

Resilience and Maintainability Implications

  • observed — The capturable path reports replay failures through its existing batch-numbered queue. Collection retains failures from later batches, and the executor’s completed-batch handling specifies synchronization before response handling, preserving the existing asynchronous failure-ordering mechanism.
Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title names the main change: replaying generated tokens into the guided-decoding matcher after a recompute. It follows the [None][fix] template, is one sentence, and matches the linked fix for iss…
Description check Passed The description covers the bug, the affected requests, the fix, the risk, and the test coverage, and it links issue #18891. It follows the repository template sections (Description, Test Coverage, PR …
Linked Issues check Passed [#18891] The issue requires that guided decoding keep committed grammar progress after a KV-cache recompute. At the reviewed head, GuidedRequest.from_llm_request sets tokens_to_replay to `get_toke…
Out of Scope Changes check Passed All changes are tied to the guided-decoding recompute fix. guided_decoder.py adds the tokens_to_replay field, its population in from_llm_request, and the replay loop in _build. `test_guided_de…
Full details: Title check

Explanation

The title names the main change: replaying generated tokens into the guided-decoding matcher after a recompute. It follows the [None][fix] template, is one sentence, and matches the linked fix for issue #18891 and the code changes in guided_decoder.py.

Full details: Description check

Explanation

The description covers the bug, the affected requests, the fix, the risk, and the test coverage, and it links issue #18891. It follows the repository template sections (Description, Test Coverage, PR Checklist). The Description section does not use the template's short explanation format. It also does not name the template's title-format ticket field beyond the title itself. These gaps are minor.

Full details: Linked Issues check

Explanation

[#18891] The issue requires that guided decoding keep committed grammar progress after a KV-cache recompute. At the reviewed head, GuidedRequest.from_llm_request sets tokens_to_replay to get_tokens(0)[orig_prompt_len:prompt_len] for a guided request at its last context chunk when prompt_len &gt; orig_prompt_len. GuidedDecoder._build creates a new matcher and calls accept_token on each replayed token before fill_next_token_bitmask. The replay stops when the matcher is terminated. A rejected token raises ValueError with the token in the message, and the existing build error path marks that request failed. The matcher at the last context chunk therefore reflects the output generated before the pause. For a recompute, require_matcher_advance is false in the context step, so the last generated token is not accepted twice. The code path matches the issue's expected behavior. The reviewed evidence is source-level. I did not run the reproduction script or the added GPU tests. I did not verify the CapturableGuidedDecoder path, which the PR description says reuses _build.

Full details: Out of Scope Changes check

Explanation

All changes are tied to the guided-decoding recompute fix. guided_decoder.py adds the tokens_to_replay field, its population in from_llm_request, and the replay loop in _build. test_guided_decoder_bitmask.py adds the recompute tests for accepted, rejected, and terminated-matcher cases. test_warmup.py adds prompt_len and orig_prompt_len to a fake request so that it matches the attributes the new code reads. Non-guided requests are unaffected, because tokens_to_replay is set only for guided requests and defaults to None. No unrelated change was found in the inspected diff.

Finishing Touches

Generate unit tests (beta)

  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Recent review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between a1e2c77 and 3891063.

Files selected for processing: 2

  • tensorrt_llm/_torch/pyexecutor/guided_decoder.py
  • tests/unittest/_torch/misc/test_guided_decoder_bitmask.py

Included review availability: This review used your included allowance. Your plan provides up to 12 included reviews per hour; 11 remain after this review.

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #85231 [ run ] triggered by Bot. Commit: a1e2c77 Link to invocation

A guided request can keep generating after its grammar matcher accepted a
stop token, for example with ignore_eos, and the matcher then rejects every
further token. The replay after a recompute fed those tokens to the new
matcher and failed the request. Stop the replay once the matcher is
terminated, as the generation-step advance already does.

Signed-off-by: Andrew Rusli <[email protected]>
@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #85231 [ run ] completed with state SUCCESS. Commit: a1e2c77
/LLM/main/L0_MergeRequest_PR pipeline #70551 completed with status: 'SUCCESS'

CI Report

Link to invocation

@arusli-nv

Copy link
Copy Markdown
Collaborator Author

/bot run

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #85279 [ run ] triggered by Bot. Commit: 3891063 Link to invocation

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #85279 [ run ] completed with state SUCCESS. Commit: 3891063
/LLM/main/L0_MergeRequest_PR pipeline #70595 completed with status: 'SUCCESS'
Pipeline passed with automatic retried tests. Check the rerun report for details.

CI Report

Link to invocation

@arusli-nv

Copy link
Copy Markdown
Collaborator Author

Superseded by #22507, which combines the runtime and serving fixes (#22381, #22382, #22384, #22386, #22392, #22393) for one review.

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.

[Bug]: Guided decoding restarts its grammar after KV-cache recomputation

2 participants