Skip to content

Conversation

syuoni
Copy link
Collaborator

@syuoni syuoni commented Jul 23, 2025

Summary by CodeRabbit

  • New Features

    • Added support for rollback and termination status in grammar matcher components, enhancing guided decoding capabilities.
    • Enabled guided decoding to work alongside speculative decoding, supporting multiple draft tokens per request.
    • Introduced JSON schema validation during evaluation, providing grammar accuracy metrics in addition to standard accuracy.
  • Improvements

    • Enhanced guided decoding logic for better handling of draft tokens, bitmask management, and logits processing.
    • Updated evaluation process to report both overall and grammar-specific accuracy.
    • Added tracking of draft token allocation and sequence slot information in request handling.
    • Initialized last tokens in batch requests to the last input token for improved state handling.
    • Integrated guided decoding steps into the speculative drafting workflow for improved draft token generation.
    • Improved logging verbosity and added memory monitoring stage for guided decoder initialization.
    • Refined test coverage with new guided decoding tests and updated test exclusions.
    • Allowed guided decoding with Eagle3 two-model speculative decoding and passed guided decoder to drafter creation.
    • Enhanced request and draft token management with new rollback methods for rejected and draft tokens.
    • Adjusted feature compatibility matrix to reflect guided decoding support with Eagle3 two-model engine.

Description

Test Coverage

GitHub Bot Help

/bot [-h] ['run', 'kill', 'skip', 'reuse-pipeline'] ...

Provide a user friendly way for developers to interact with a Jenkins server.

Run /bot [-h|--help] to print this help message.

See details below for each supported subcommand.

run [--reuse-test (optional)pipeline-id --disable-fail-fast --skip-test --stage-list "A10-PyTorch-1, xxx" --gpu-type "A30, H100_PCIe" --test-backend "pytorch, cpp" --add-multi-gpu-test --only-multi-gpu-test --disable-multi-gpu-test --post-merge --extra-stage "H100_PCIe-TensorRT-Post-Merge-1, xxx" --detailed-log --debug(experimental)]

Launch build/test pipelines. All previously running jobs will be killed.

--reuse-test (optional)pipeline-id (OPTIONAL) : Allow the new pipeline to reuse build artifacts and skip successful test stages from a specified pipeline or the last pipeline if no pipeline-id is indicated. If the Git commit ID has changed, this option will be always ignored. The DEFAULT behavior of the bot is to reuse build artifacts and successful test results from the last pipeline.

--disable-reuse-test (OPTIONAL) : Explicitly prevent the pipeline from reusing build artifacts and skipping successful test stages from a previous pipeline. Ensure that all builds and tests are run regardless of previous successes.

--disable-fail-fast (OPTIONAL) : Disable fail fast on build/tests/infra failures.

--skip-test (OPTIONAL) : Skip all test stages, but still run build stages, package stages and sanity check stages. Note: Does NOT update GitHub check status.

--stage-list "A10-PyTorch-1, xxx" (OPTIONAL) : Only run the specified test stages. Examples: "A10-PyTorch-1, xxx". Note: Does NOT update GitHub check status.

--gpu-type "A30, H100_PCIe" (OPTIONAL) : Only run the test stages on the specified GPU types. Examples: "A30, H100_PCIe". Note: Does NOT update GitHub check status.

--test-backend "pytorch, cpp" (OPTIONAL) : Skip test stages which don't match the specified backends. Only support [pytorch, cpp, tensorrt, triton]. Examples: "pytorch, cpp" (does not run test stages with tensorrt or triton backend). Note: Does NOT update GitHub pipeline status.

--only-multi-gpu-test (OPTIONAL) : Only run the multi-GPU tests. Note: Does NOT update GitHub check status.

--disable-multi-gpu-test (OPTIONAL) : Disable the multi-GPU tests. Note: Does NOT update GitHub check status.

--add-multi-gpu-test (OPTIONAL) : Force run the multi-GPU tests in addition to running L0 pre-merge pipeline.

--post-merge (OPTIONAL) : Run the L0 post-merge pipeline instead of the ordinary L0 pre-merge pipeline.

--extra-stage "H100_PCIe-TensorRT-Post-Merge-1, xxx" (OPTIONAL) : Run the ordinary L0 pre-merge pipeline and specified test stages. Examples: --extra-stage "H100_PCIe-TensorRT-Post-Merge-1, xxx".

--detailed-log (OPTIONAL) : Enable flushing out all logs to the Jenkins console. This will significantly increase the log volume and may slow down the job.

--debug (OPTIONAL) : Experimental feature. Enable access to the CI container for debugging purpose. Note: Specify exactly one stage in the stage-list parameter to access the appropriate container environment. Note: Does NOT update GitHub check status.

For guidance on mapping tests to stage names, see docs/source/reference/ci-overview.md
and the scripts/test_to_stage_mapping.py helper.

kill

kill

Kill all running builds associated with pull request.

skip

skip --comment COMMENT

Skip testing for latest commit on pull request. --comment "Reason for skipping build/test" is required. IMPORTANT NOTE: This is dangerous since lack of user care and validation can cause top of tree to break.

reuse-pipeline

reuse-pipeline

Reuse a previous pipeline to validate current commit. This action will also kill all currently running builds associated with the pull request. IMPORTANT NOTE: This is dangerous since lack of user care and validation can cause top of tree to break.

Copy link
Contributor

coderabbitai bot commented Jul 23, 2025

📝 Walkthrough

Walkthrough

The changes introduce rollback and termination detection capabilities to grammar matcher classes, extend guided decoding to support multiple draft tokens, and enable guided and speculative decoding to coexist. JSON schema validation is added to JSON evaluation, and constructors and method signatures are updated to accommodate the new features and parameters. Additionally, initialization of last tokens in batch requests was refined.

Changes

File(s) Change Summary
Grammar Matcher Updates
tensorrt_llm/_torch/pyexecutor/grammar_matcher.py
Added rollback and is_terminated abstract methods to GrammarMatcher; implemented them in XGrammarMatcher and LLGuidanceMatcher. Updated XGrammarMatcherFactory to accept max_num_draft_tokens and pass it as max_rollback_tokens. Enhanced LLGuidanceMatcher to handle EOS token and termination state.
Guided Decoder Enhancements
tensorrt_llm/_torch/pyexecutor/guided_decoder.py
Extended GuidedDecoder to support multiple draft tokens via new max_num_draft_tokens parameter. Updated internal bitmask handling, token acceptance, rollback logic, and logits batching accordingly. Added logging for backend initialization.
LlmRequest State Addition
tensorrt_llm/_torch/pyexecutor/llm_request.py
Added new instance attribute py_draft_pages_allocated initialized to 0 in LlmRequest constructor to track draft token allocation state. Added optional seq_slot and target_seq_slot parameters to constructor and corresponding instance variables.
Executor Creation Logic
tensorrt_llm/_torch/pyexecutor/py_executor_creator.py
Removed previous restriction forbidding guided decoding with speculative decoding. Introduced max_num_draft_tokens parameter, defaulting to zero or set from speculative config, passed to GuidedDecoder constructor. Added new executor creation stage for guided decoder memory monitoring.
Model Drafter Integration
tensorrt_llm/_torch/speculative/model_drafter.py
Added optional guided_decoder parameter to ModelDrafter. Refactored draft request creation to use a single request argument. Integrated guided decoder execution calls during draft token preparation and rollback of draft tokens after generation.
Speculative Drafter Factory Update
tensorrt_llm/_torch/speculative/utils.py
Added optional guided_decoder parameter to get_spec_drafter function and passed it when constructing ModelDrafter instances.
NGram Drafter Minor Fix
tensorrt_llm/_torch/speculative/ngram.py
Changed call to request.get_tokens() from [0] indexing to (0) argument form for consistency.
PyExecutor Guided Decoder Updates
tensorrt_llm/_torch/pyexecutor/py_executor.py
Added type annotations to _execute_guided_decoder. Added rollback call to guided decoder before draft token preparation in executor loop.
JSON Evaluation Schema Validation
tensorrt_llm/evaluate/json_mode_eval.py
Added JSON schema validation for model outputs using jsonschema. Updated generate_samples to yield schema, and compute_score to validate outputs against schemas, computing grammar accuracy alongside correctness.
Batch Manager Initialization Fix
cpp/include/tensorrt_llm/batch_manager/llmRequest.h
Modified initialization of mLastTokens in GenericLlmRequest to fill with the last input token instead of default values, improving initial token state consistency.
Documentation Update
docs/source/torch/features/feature_combination_matrix.md
Updated feature compatibility matrix to indicate "Guided Decoding" support for "EAGLE-3(Two Model Engine)" as "Yes".
Requirements Update
requirements.txt
Added jsonschema package dependency; reordered llguidance version line.
Logging Level Change
tensorrt_llm/_torch/pyexecutor/model_engine.py
Changed logging of use_mrope detection from info to debug level.
Test Additions and Modifications
tests/integration/defs/accuracy/test_llm_api_pytorch.py, tests/integration/defs/accuracy/references/json_mode_eval.yaml, tests/integration/test_lists/test-db/l0_h100.yml
Added new tests for guided decoding with Eagle3 and NGram backends. Updated test exclusion lists to include these new tests. Removed cuda_graph_config argument in some test LLM instantiations. Added accuracy results for Eagle and NGram decoding algorithms in YAML references.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant GuidedDecoder
    participant XGrammarMatcherFactory
    participant XGrammarMatcher

    User->>GuidedDecoder: build(requests)
    GuidedDecoder->>XGrammarMatcherFactory: create(params, max_num_draft_tokens)
    XGrammarMatcherFactory->>XGrammarMatcher: instantiate (max_rollback_tokens)
    GuidedDecoder->>XGrammarMatcher: rollback(num_tokens)
    GuidedDecoder->>XGrammarMatcher: is_terminated()
    GuidedDecoder->>GuidedDecoder: Update bitmask, accept tokens
Loading
sequenceDiagram
    participant JsonModeEval
    participant jsonschema

    JsonModeEval->>JsonModeEval: generate_samples()
    JsonModeEval->>JsonModeEval: compute_score(outputs, references, schemas)
    loop For each output
        JsonModeEval->>jsonschema: validate(output_json, schema)
        jsonschema-->>JsonModeEval: validation result
        JsonModeEval->>JsonModeEval: compute accuracy, grammar accuracy
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~45 minutes

Possibly related PRs

Suggested labels

Community want to contribute, Speculative Decoding, CI

Suggested reviewers

  • HuiGao-NV
  • pcastonguay
  • litaotju
  • yilin-void

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.


📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 93dc7ab and d9913e1.

📒 Files selected for processing (1)
  • cpp/include/tensorrt_llm/batch_manager/llmRequest.h (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • cpp/include/tensorrt_llm/batch_manager/llmRequest.h
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Pre-commit Check
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai or @coderabbitai title anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Nitpick comments (1)
tensorrt_llm/_torch/pyexecutor/guided_decoder.py (1)

133-133: Add a descriptive message to the assertion.

The assertion helps catch offset calculation errors but would be more helpful with a descriptive message.

-assert offset == logits.size(0)
+assert offset == logits.size(0), f"Offset mismatch: expected {logits.size(0)}, got {offset}"
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2486eb7 and fb523e3.

📒 Files selected for processing (5)
  • tensorrt_llm/_torch/pyexecutor/grammar_matcher.py (5 hunks)
  • tensorrt_llm/_torch/pyexecutor/guided_decoder.py (3 hunks)
  • tensorrt_llm/_torch/pyexecutor/llm_request.py (1 hunks)
  • tensorrt_llm/_torch/pyexecutor/py_executor_creator.py (1 hunks)
  • tensorrt_llm/evaluate/json_mode_eval.py (2 hunks)
🧠 Learnings (1)
tensorrt_llm/_torch/pyexecutor/py_executor_creator.py (2)

Learnt from: amitz-nv
PR: #5616
File: tensorrt_llm/executor/worker.py:375-384
Timestamp: 2025-07-17T09:01:27.374Z
Learning: In tensorrt_llm/executor/worker.py, the LoRA adapter cache optimization logic that checks is_adapter_in_cpu_cache() and conditionally passes None for weights/config has a known race condition issue that cannot be solved with simple error handling or verification checks. This is a known limitation that requires a more comprehensive solution.

Learnt from: yechank-nvidia
PR: #6254
File: tensorrt_llm/_torch/pyexecutor/model_engine.py:1201-1204
Timestamp: 2025-07-22T09:22:14.703Z
Learning: In TensorRT-LLM's multimodal processing pipeline, shared tensor recovery using from_shared_tensor() is only needed during the context phase. Generation requests reuse the already-recovered tensor data and only need to call strip_for_generation() to remove unnecessary multimodal data while preserving the recovered tensors. This avoids redundant tensor recovery operations during generation.

🧰 Additional context used
🧠 Learnings (1)
tensorrt_llm/_torch/pyexecutor/py_executor_creator.py (2)

Learnt from: amitz-nv
PR: #5616
File: tensorrt_llm/executor/worker.py:375-384
Timestamp: 2025-07-17T09:01:27.374Z
Learning: In tensorrt_llm/executor/worker.py, the LoRA adapter cache optimization logic that checks is_adapter_in_cpu_cache() and conditionally passes None for weights/config has a known race condition issue that cannot be solved with simple error handling or verification checks. This is a known limitation that requires a more comprehensive solution.

Learnt from: yechank-nvidia
PR: #6254
File: tensorrt_llm/_torch/pyexecutor/model_engine.py:1201-1204
Timestamp: 2025-07-22T09:22:14.703Z
Learning: In TensorRT-LLM's multimodal processing pipeline, shared tensor recovery using from_shared_tensor() is only needed during the context phase. Generation requests reuse the already-recovered tensor data and only need to call strip_for_generation() to remove unnecessary multimodal data while preserving the recovered tensors. This avoids redundant tensor recovery operations during generation.

🔇 Additional comments (6)
tensorrt_llm/_torch/pyexecutor/llm_request.py (1)

304-304: LGTM!

The addition of py_draft_pages_allocated follows the established naming convention for Python-side attributes and appropriately initializes the draft page counter to support the new guided decoding feature.

tensorrt_llm/_torch/pyexecutor/py_executor_creator.py (1)

336-343: Good implementation for enabling guided+speculative decoding coexistence.

The removal of the previous restriction and the addition of max_num_draft_tokens parameter properly enables guided decoding to work alongside speculative decoding. The conditional logic correctly propagates the draft token limit from the speculative configuration.

tensorrt_llm/_torch/pyexecutor/grammar_matcher.py (2)

19-30: Well-designed interface extension for rollback support.

The addition of rollback and is_terminated methods to the GrammarMatcher interface is cleanly implemented across all concrete classes. The error checking after rollback in LLGuidanceMatcher is a good practice.

Also applies to: 50-59, 142-154


63-66: Proper parameter propagation for draft token support.

The max_num_draft_tokens parameter is correctly added to the factory constructor and properly propagated to the underlying xgrammar.GrammarMatcher as max_rollback_tokens.

Also applies to: 91-92, 126-127

tensorrt_llm/_torch/pyexecutor/guided_decoder.py (2)

16-34: Good extension for multi-draft token support.

The constructor properly accepts and propagates the max_num_draft_tokens parameter, and the bitmask tensors are correctly resized to accommodate the additional draft tokens.


99-109: Well-implemented draft token acceptance logic.

The handling of terminated matchers with rollback ensures state consistency, and the early termination on rejection is efficient.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

♻️ Duplicate comments (1)
tensorrt_llm/_torch/pyexecutor/guided_decoder.py (1)

86-92: Consider graceful error handling instead of throwing exceptions.

As noted in the TODO comment, throwing a ValueError when token acceptance fails could crash the service. Consider implementing a proper error response mechanism that allows the request to fail gracefully without affecting other concurrent requests.

🧹 Nitpick comments (2)
tensorrt_llm/_torch/pyexecutor/guided_decoder.py (1)

78-84: Fix line length issue.

Line 82 exceeds the 120-character limit. Consider breaking it into multiple lines for better readability.

-                    if num_rollback_tokens < 0:
-                        raise ValueError(
-                            f"Failed to rollback: num_guided_tokens={self.num_guided_tokens[slot]}, num_accepted_draft_tokens={llm_req.py_num_accepted_draft_tokens}, num_rollback_tokens={num_rollback_tokens}"
-                        )
+                    if num_rollback_tokens < 0:
+                        raise ValueError(
+                            f"Failed to rollback: num_guided_tokens={self.num_guided_tokens[slot]}, "
+                            f"num_accepted_draft_tokens={llm_req.py_num_accepted_draft_tokens}, "
+                            f"num_rollback_tokens={num_rollback_tokens}"
+                        )
tensorrt_llm/_torch/pyexecutor/grammar_matcher.py (1)

139-157: LLGuidanceMatcher termination handling is well-implemented, but API workaround needs attention.

The EOS token acceptance logic and termination state tracking are correct. However, the deep_copy workaround for the llguidance API limitation should be addressed when the upstream issue is resolved.

Would you like me to create an issue to track the removal of this workaround once guidance-ai/llguidance#211 is resolved?

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between fb523e3 and 0577a18.

📒 Files selected for processing (3)
  • tensorrt_llm/_torch/pyexecutor/grammar_matcher.py (5 hunks)
  • tensorrt_llm/_torch/pyexecutor/guided_decoder.py (3 hunks)
  • tensorrt_llm/evaluate/json_mode_eval.py (2 hunks)
🧠 Learnings (1)
tensorrt_llm/_torch/pyexecutor/guided_decoder.py (1)

Learnt from: amitz-nv
PR: #5616
File: tensorrt_llm/executor/worker.py:375-384
Timestamp: 2025-07-17T09:01:27.374Z
Learning: In tensorrt_llm/executor/worker.py, the LoRA adapter cache optimization logic that checks is_adapter_in_cpu_cache() and conditionally passes None for weights/config has a known race condition issue that cannot be solved with simple error handling or verification checks. This is a known limitation that requires a more comprehensive solution.

🪛 Ruff (0.12.2)
tensorrt_llm/_torch/pyexecutor/guided_decoder.py

82-82: Line too long (208 > 120)

(E501)

🚧 Files skipped from review as they are similar to previous changes (1)
  • tensorrt_llm/evaluate/json_mode_eval.py
🧰 Additional context used
🧠 Learnings (1)
tensorrt_llm/_torch/pyexecutor/guided_decoder.py (1)

Learnt from: amitz-nv
PR: #5616
File: tensorrt_llm/executor/worker.py:375-384
Timestamp: 2025-07-17T09:01:27.374Z
Learning: In tensorrt_llm/executor/worker.py, the LoRA adapter cache optimization logic that checks is_adapter_in_cpu_cache() and conditionally passes None for weights/config has a known race condition issue that cannot be solved with simple error handling or verification checks. This is a known limitation that requires a more comprehensive solution.

🪛 Ruff (0.12.2)
tensorrt_llm/_torch/pyexecutor/guided_decoder.py

82-82: Line too long (208 > 120)

(E501)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Pre-commit Check
🔇 Additional comments (9)
tensorrt_llm/_torch/pyexecutor/guided_decoder.py (4)

16-24: Constructor changes for draft token support look good.

The addition of max_num_draft_tokens parameter with a default value of 0 maintains backward compatibility while enabling the new functionality.

Also applies to: 32-34


43-53: Bitmask tensor reshaping correctly supports multiple draft tokens.

The tensors are properly resized to accommodate max_num_draft_tokens + 1 tokens (base + drafts), and the tracking list num_guided_tokens appropriately manages per-sequence state.


96-120: Draft token processing implementation is well-designed.

The logic correctly handles:

  • Iterative token acceptance with termination checks
  • Proper rollback when termination is detected
  • Efficient bitmask management with non-blocking copies

127-137: Execute method correctly handles multiple guided tokens.

The implementation properly:

  • Batches logits and bitmasks for multiple guided tokens
  • Maintains accurate offset tracking with draft tokens
  • Includes assertion for validation
tensorrt_llm/_torch/pyexecutor/grammar_matcher.py (5)

19-22: Abstract method additions are well-designed.

The rollback and is_terminated methods provide the necessary interface for supporting multiple draft tokens in guided decoding.

Also applies to: 28-31


50-52: XGrammarMatcher implementations correctly delegate to underlying matcher.

The implementations maintain consistency with the existing delegation pattern.

Also applies to: 57-59


63-67: XGrammarMatcherFactory properly configures rollback support.

The max_num_draft_tokens parameter is correctly stored and passed as max_rollback_tokens to the underlying matcher.

Also applies to: 91-91, 126-127


158-163: Rollback implementation correctly handles termination state.

The logic properly adjusts the rollback count when the matcher is in terminated state, ensuring correct behavior.


228-228: Factory correctly passes EOS token to matcher.

The change enables proper termination handling in LLGuidanceMatcher.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

♻️ Duplicate comments (1)
tensorrt_llm/_torch/pyexecutor/guided_decoder.py (1)

82-96: Error handling still uses exceptions - consider graceful handling.

The rollback failure and token acceptance failure still throw ValueError exceptions, which could crash the service as noted in the TODO comment.

🧹 Nitpick comments (1)
tensorrt_llm/_torch/pyexecutor/guided_decoder.py (1)

85-87: Fix line length violation.

The error message exceeds the 120-character limit.

-                        raise ValueError(
-                            f"Failed to rollback: num_guided_tokens={self.num_guided_tokens[slot]}, num_accepted_draft_tokens={llm_req.py_num_accepted_draft_tokens}, num_rollback_tokens={num_rollback_tokens}"
-                        )
+                        raise ValueError(
+                            f"Failed to rollback: num_guided_tokens={self.num_guided_tokens[slot]}, "
+                            f"num_accepted_draft_tokens={llm_req.py_num_accepted_draft_tokens}, "
+                            f"num_rollback_tokens={num_rollback_tokens}"
+                        )
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0577a18 and 8e17439.

📒 Files selected for processing (2)
  • tensorrt_llm/_torch/pyexecutor/grammar_matcher.py (5 hunks)
  • tensorrt_llm/_torch/pyexecutor/guided_decoder.py (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • tensorrt_llm/_torch/pyexecutor/grammar_matcher.py
🧰 Additional context used
🧠 Learnings (1)
tensorrt_llm/_torch/pyexecutor/guided_decoder.py (1)

Learnt from: amitz-nv
PR: #5616
File: tensorrt_llm/executor/worker.py:375-384
Timestamp: 2025-07-17T09:01:27.402Z
Learning: In tensorrt_llm/executor/worker.py, the LoRA adapter cache optimization logic that checks is_adapter_in_cpu_cache() and conditionally passes None for weights/config has a known race condition issue that cannot be solved with simple error handling or verification checks. This is a known limitation that requires a more comprehensive solution.

🪛 Ruff (0.12.2)
tensorrt_llm/_torch/pyexecutor/guided_decoder.py

86-86: Line too long (208 > 120)

(E501)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Pre-commit Check
🔇 Additional comments (4)
tensorrt_llm/_torch/pyexecutor/guided_decoder.py (4)

17-45: LGTM! Constructor properly extended for draft token support.

The addition of max_num_draft_tokens parameter with sensible defaults, proper factory parameter passing, and helpful logging statement are well implemented.


47-57: LGTM! Tensor dimensions properly updated for multi-token support.

The bitmask tensor dimensions are correctly expanded to accommodate max_num_draft_tokens + 1, and the num_guided_tokens tracking list is appropriately added.


100-123: Well-structured draft token processing logic.

The draft token processing correctly handles termination states, rollback scenarios, and memory transfers with proper stream synchronization.


131-140: LGTM! Batching logic correctly handles variable guided tokens per request.

The offset tracking and assertion provide good validation that all logits are processed, while properly handling the variable number of guided tokens per request.

@hudson-ai
Copy link

hudson-ai commented Jul 29, 2025

@syuoni do you have any plans to support fast-forwarded tokens in this feat (or another in the near-future)? The constraint engine can often efficiently compute a sequence of tokens that must be consumed -- you may be able to leverage the same machinery used for accepting a sequence of tokens from a draft model. We've found that the speedups from these fast-forwarded tokens can be quite substantial

@syuoni
Copy link
Collaborator Author

syuoni commented Jul 31, 2025

@syuoni do you have any plans to support fast-forwarded tokens in this feat (or another in the near-future)? The constraint engine can often efficiently compute a sequence of tokens that must be consumed -- you may be able to leverage the same machinery used for accepting a sequence of tokens from a draft model. We've found that the speedups from these fast-forwarded tokens can be quite substantial

Hi @hudson-ai , thanks for the reminder! Actually, this feature was planned when TRT-LLM initially introduced guided decoding, namely in Nov. 2024. But my bandwidth was shifted to other stuff so I didn't have a chance to implement it.

Currently, the top priority is making guided decoding work with other features:

  • Overlap scheduler (Done)
  • Speculative decoding (In progress)
  • Disagg serving (TODO)

I will take a closer look at the fast-forward tokens once the above work is done.

It's quite interesting to me -- on average, how many fast-forward tokens can the grammar engine generate (on any typical dataset)?

@syuoni syuoni force-pushed the guided-with-spec branch from 8e17439 to e3cf182 Compare August 1, 2025 14:36
@syuoni syuoni force-pushed the guided-with-spec branch from e3cf182 to daa1e01 Compare August 4, 2025 03:35
@syuoni syuoni changed the title [TRTLLM-6409] feat: Enable guided decoding with speculative decoding (part 1: two-model engine) [TRTLLM-6409][feat] Enable guided decoding with speculative decoding (part 1: two-model engine) Aug 4, 2025
@syuoni syuoni self-assigned this Aug 4, 2025
@syuoni
Copy link
Collaborator Author

syuoni commented Aug 4, 2025

/bot run

@syuoni syuoni marked this pull request as ready for review August 4, 2025 04:38
@syuoni syuoni requested review from a team as code owners August 4, 2025 04:38
@tensorrt-cicd
Copy link
Collaborator

PR_Github #13923 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #13923 [ run ] completed with state SUCCESS
/LLM/main/L0_MergeRequest_PR pipeline #10485 completed with status: 'FAILURE'

@syuoni syuoni force-pushed the guided-with-spec branch from 75798c4 to dcecd34 Compare August 4, 2025 06:54
@syuoni
Copy link
Collaborator Author

syuoni commented Aug 4, 2025

/bot run --disable-fail-fast

@tensorrt-cicd
Copy link
Collaborator

PR_Github #13956 [ run ] triggered by Bot

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (3)
tests/integration/test_lists/test-db/l0_h100.yml (1)

212-214: LGTM! Comprehensive test exclusions for guided decoding variants.

The exclusions for guided decoding tests with different backends (llguidance, xgrammar) and speculative decoding modes (Eagle3, NGram) are appropriate during the development phase. These should be re-enabled once the features are stable and ready for CI validation.

Consider adding a tracking issue or timeline for when these test exclusions can be removed to ensure they don't remain excluded indefinitely.

tensorrt_llm/_torch/pyexecutor/py_executor_creator.py (1)

330-347: LGTM! Guided decoder integration with proper compatibility checks.

The implementation correctly:

  • Uses memory monitoring for the guided decoder creation stage
  • Restricts guided decoding to two-model speculative engines only
  • Creates the decoder only on the last pipeline parallel rank
  • Properly configures max_num_draft_tokens based on speculative config

The error message clearly explains the limitation, which aligns with the PR's focus on two-model engine support.

Fix the line length issue flagged by static analysis:

-                raise ValueError(
-                    "Guided decoding is only supported with speculative decoding that has a dedicated drafter (two-model engine)."
-                )
+                raise ValueError(
+                    "Guided decoding is only supported with speculative decoding "
+                    "that has a dedicated drafter (two-model engine)."
+                )
tensorrt_llm/_torch/pyexecutor/guided_decoder.py (1)

206-210: Fix line length violation.

Line 208 exceeds the 120-character limit. Break the error message across multiple lines for better readability.

-                raise ValueError(
-                    f"Failed to rollback: num_advanced_tokens={self.num_advanced_tokens[slot]}, num_accepted_draft_tokens={llm_req.py_num_accepted_draft_tokens}, num_rollback_tokens={num_rollback_tokens}"
-                )
+                raise ValueError(
+                    f"Failed to rollback: num_advanced_tokens={self.num_advanced_tokens[slot]}, "
+                    f"num_accepted_draft_tokens={llm_req.py_num_accepted_draft_tokens}, "
+                    f"num_rollback_tokens={num_rollback_tokens}"
+                )
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 75798c4 and dcecd34.

📒 Files selected for processing (16)
  • cpp/include/tensorrt_llm/batch_manager/llmRequest.h (1 hunks)
  • docs/source/torch/features/feature_combination_matrix.md (1 hunks)
  • requirements.txt (1 hunks)
  • tensorrt_llm/_torch/pyexecutor/grammar_matcher.py (5 hunks)
  • tensorrt_llm/_torch/pyexecutor/guided_decoder.py (1 hunks)
  • tensorrt_llm/_torch/pyexecutor/llm_request.py (3 hunks)
  • tensorrt_llm/_torch/pyexecutor/model_engine.py (1 hunks)
  • tensorrt_llm/_torch/pyexecutor/py_executor.py (2 hunks)
  • tensorrt_llm/_torch/pyexecutor/py_executor_creator.py (3 hunks)
  • tensorrt_llm/_torch/speculative/model_drafter.py (12 hunks)
  • tensorrt_llm/_torch/speculative/ngram.py (3 hunks)
  • tensorrt_llm/_torch/speculative/utils.py (3 hunks)
  • tensorrt_llm/evaluate/json_mode_eval.py (2 hunks)
  • tests/integration/defs/accuracy/references/json_mode_eval.yaml (1 hunks)
  • tests/integration/defs/accuracy/test_llm_api_pytorch.py (2 hunks)
  • tests/integration/test_lists/test-db/l0_h100.yml (2 hunks)
✅ Files skipped from review due to trivial changes (4)
  • tensorrt_llm/_torch/pyexecutor/model_engine.py
  • requirements.txt
  • tensorrt_llm/_torch/speculative/ngram.py
  • tests/integration/defs/accuracy/references/json_mode_eval.yaml
🚧 Files skipped from review as they are similar to previous changes (4)
  • tensorrt_llm/_torch/pyexecutor/llm_request.py
  • tensorrt_llm/evaluate/json_mode_eval.py
  • cpp/include/tensorrt_llm/batch_manager/llmRequest.h
  • tensorrt_llm/_torch/pyexecutor/grammar_matcher.py
🧰 Additional context used
📓 Path-based instructions (2)
**/*.py

📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md)

**/*.py: The code developed for TensorRT-LLM should conform to Python 3.8+.
Indent Python code with 4 spaces. Do not use tabs.
Always maintain the namespace when importing in Python, even if only one class or function from a module is used.
Python filenames should use snake_case (e.g., some_file.py).
Python classes should use PascalCase (e.g., class SomeClass).
Python functions and methods should use snake_case (e.g., def my_awesome_function():).
Python local variables should use snake_case. Prefix k for variable names that start with a number (e.g., k_99th_percentile = ...).
Python global variables should use upper snake_case and prefix G (e.g., G_MY_GLOBAL = ...).
Python constants should use upper snake_case (e.g., MY_CONSTANT = ...).
Avoid shadowing variables declared in an outer scope in Python.
Initialize all externally visible members of a Python class in the constructor.
For interfaces that may be used outside a file, prefer docstrings over comments in Python.
Comments in Python should be reserved for code within a function, or interfaces that are local to a file.
Use Google style docstrings for classes and functions in Python, which can be parsed by Sphinx.
Attributes and variables in Python can be documented inline; attribute docstrings will be rendered under the docstring for the class.
Avoid using reflection in Python when functionality can be easily achieved without it.
When using try-except blocks in Python, limit the except to the smallest set of errors possible.
When using try-except blocks to handle multiple possible variable types in Python, keep the body of the try as small as possible, using the else block to implement the logic.

Files:

  • tensorrt_llm/_torch/pyexecutor/py_executor.py
  • tensorrt_llm/_torch/speculative/utils.py
  • tests/integration/defs/accuracy/test_llm_api_pytorch.py
  • tensorrt_llm/_torch/speculative/model_drafter.py
  • tensorrt_llm/_torch/pyexecutor/guided_decoder.py
  • tensorrt_llm/_torch/pyexecutor/py_executor_creator.py
**/*.{cpp,h,hpp,cc,cxx,cu,py}

📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md)

All TensorRT-LLM Open Source Software code should contain an NVIDIA copyright header that includes the current year. This includes .cpp, .h, .cu, .py, and any other source files which are compiled or interpreted.

Files:

  • tensorrt_llm/_torch/pyexecutor/py_executor.py
  • tensorrt_llm/_torch/speculative/utils.py
  • tests/integration/defs/accuracy/test_llm_api_pytorch.py
  • tensorrt_llm/_torch/speculative/model_drafter.py
  • tensorrt_llm/_torch/pyexecutor/guided_decoder.py
  • tensorrt_llm/_torch/pyexecutor/py_executor_creator.py
🧠 Learnings (6)
📓 Common learnings
Learnt from: moraxu
PR: NVIDIA/TensorRT-LLM#6303
File: tests/integration/test_lists/qa/examples_test_list.txt:494-494
Timestamp: 2025-07-28T17:06:08.621Z
Learning: In TensorRT-LLM testing, it's common to have both CLI flow tests (test_cli_flow.py) and PyTorch API tests (test_llm_api_pytorch.py) for the same model. These serve different purposes: CLI flow tests validate the traditional command-line workflow, while PyTorch API tests validate the newer LLM API backend. Both are legitimate and should coexist.
📚 Learning: in tensorrt-llm testing, it's common to have both cli flow tests (test_cli_flow.py) and pytorch api ...
Learnt from: moraxu
PR: NVIDIA/TensorRT-LLM#6303
File: tests/integration/test_lists/qa/examples_test_list.txt:494-494
Timestamp: 2025-07-28T17:06:08.621Z
Learning: In TensorRT-LLM testing, it's common to have both CLI flow tests (test_cli_flow.py) and PyTorch API tests (test_llm_api_pytorch.py) for the same model. These serve different purposes: CLI flow tests validate the traditional command-line workflow, while PyTorch API tests validate the newer LLM API backend. Both are legitimate and should coexist.

Applied to files:

  • docs/source/torch/features/feature_combination_matrix.md
  • tests/integration/defs/accuracy/test_llm_api_pytorch.py
  • tests/integration/test_lists/test-db/l0_h100.yml
📚 Learning: in tensorrt-llm, examples directory can have different dependency versions than the root requirement...
Learnt from: yibinl-nvidia
PR: NVIDIA/TensorRT-LLM#6506
File: examples/models/core/mixtral/requirements.txt:3-3
Timestamp: 2025-08-01T15:14:45.673Z
Learning: In TensorRT-LLM, examples directory can have different dependency versions than the root requirements.txt file. Version conflicts between root and examples dependencies are acceptable because examples are designed to be standalone and self-contained.

Applied to files:

  • tensorrt_llm/_torch/speculative/utils.py
📚 Learning: applies to **/*.py : the code developed for tensorrt-llm should conform to python 3.8+....
Learnt from: CR
PR: NVIDIA/TensorRT-LLM#0
File: CODING_GUIDELINES.md:0-0
Timestamp: 2025-08-04T02:12:17.582Z
Learning: Applies to **/*.py : The code developed for TensorRT-LLM should conform to Python 3.8+.

Applied to files:

  • tests/integration/test_lists/test-db/l0_h100.yml
📚 Learning: in tensorrt-llm's multimodal processing pipeline, shared tensor recovery using `from_shared_tensor()...
Learnt from: yechank-nvidia
PR: NVIDIA/TensorRT-LLM#6254
File: tensorrt_llm/_torch/pyexecutor/model_engine.py:1201-1204
Timestamp: 2025-07-22T09:22:14.726Z
Learning: In TensorRT-LLM's multimodal processing pipeline, shared tensor recovery using `from_shared_tensor()` is only needed during the context phase. Generation requests reuse the already-recovered tensor data and only need to call `strip_for_generation()` to remove unnecessary multimodal data while preserving the recovered tensors. This avoids redundant tensor recovery operations during generation.

Applied to files:

  • tensorrt_llm/_torch/speculative/model_drafter.py
📚 Learning: in tensorrt_llm/executor/worker.py, the lora adapter cache optimization logic that checks `is_adapte...
Learnt from: amitz-nv
PR: NVIDIA/TensorRT-LLM#5616
File: tensorrt_llm/executor/worker.py:375-384
Timestamp: 2025-07-17T09:01:27.402Z
Learning: In tensorrt_llm/executor/worker.py, the LoRA adapter cache optimization logic that checks `is_adapter_in_cpu_cache()` and conditionally passes None for weights/config has a known race condition issue that cannot be solved with simple error handling or verification checks. This is a known limitation that requires a more comprehensive solution.

Applied to files:

  • tensorrt_llm/_torch/pyexecutor/guided_decoder.py
🧬 Code Graph Analysis (3)
tensorrt_llm/_torch/pyexecutor/py_executor.py (2)
tensorrt_llm/_torch/pyexecutor/scheduler.py (1)
  • ScheduledRequests (18-39)
tensorrt_llm/_torch/pyexecutor/guided_decoder.py (1)
  • rollback_rejected_tokens (188-210)
tests/integration/defs/accuracy/test_llm_api_pytorch.py (3)
tensorrt_llm/llmapi/llm_args.py (3)
  • EagleDecodingConfig (389-415)
  • speculative_model_dir (1304-1305)
  • NGramDecodingConfig (430-465)
tests/integration/defs/conftest.py (1)
  • llm_models_root (77-83)
tests/integration/defs/accuracy/accuracy_core.py (3)
  • JsonModeEval (318-333)
  • evaluate (146-199)
  • evaluate (678-688)
tensorrt_llm/_torch/pyexecutor/guided_decoder.py (5)
tensorrt_llm/_torch/pyexecutor/grammar_matcher.py (19)
  • GrammarMatcher (13-30)
  • GrammarMatcherFactory (33-38)
  • LLGuidanceMatcherFactory (174-222)
  • XGrammarMatcherFactory (61-128)
  • create (36-38)
  • create (93-128)
  • create (195-222)
  • is_terminated (29-30)
  • is_terminated (57-58)
  • is_terminated (165-166)
  • accept_token (16-17)
  • accept_token (47-48)
  • accept_token (139-150)
  • fill_next_token_bitmask (24-26)
  • fill_next_token_bitmask (53-55)
  • fill_next_token_bitmask (159-163)
  • rollback (20-21)
  • rollback (50-51)
  • rollback (152-157)
tensorrt_llm/_torch/pyexecutor/llm_request.py (1)
  • LlmRequest (264-356)
tensorrt_llm/_torch/pyexecutor/scheduler.py (2)
  • ScheduledRequests (18-39)
  • all_requests (38-39)
tensorrt_llm/_utils.py (1)
  • nvtx_range (834-853)
tensorrt_llm/logger.py (1)
  • debug (143-144)
🪛 Ruff (0.12.2)
tensorrt_llm/_torch/pyexecutor/guided_decoder.py

208-208: Line too long (204 > 120)

(E501)

tensorrt_llm/_torch/pyexecutor/py_executor_creator.py

336-336: Line too long (130 > 120)

(E501)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Pre-commit Check
🔇 Additional comments (21)
docs/source/torch/features/feature_combination_matrix.md (2)

11-12: LGTM! Minor formatting improvements.

The spacing fixes for "Yes" entries under "Chunked Prefill" improve consistency in the table formatting.


18-18: LGTM! Compatibility update aligns with PR objectives.

The update changing "Guided Decoding" compatibility with "EAGLE-3(Two Model Engine)" from "No" to "Yes" correctly reflects the new functionality introduced in this PR for enabling guided decoding with speculative decoding.

tensorrt_llm/_torch/pyexecutor/py_executor.py (2)

897-898: LGTM! Well-defined method signature with proper type annotations.

The _execute_guided_decoder method has clear parameter types (ScheduledRequests and torch.Tensor) that align with the guided decoder interface. The implementation properly guards against null guided decoder instances.


936-938: LGTM! Proper integration of guided decoder rollback with speculative decoding.

The rollback of rejected tokens is correctly placed before draft token preparation, ensuring the guided decoder state is synchronized with the speculative decoding workflow. The null check prevents issues when guided decoding is not enabled.

tests/integration/test_lists/test-db/l0_h100.yml (1)

33-33: LGTM! Appropriate test exclusion for new guided decoding feature.

The exclusion of test_guided_decoding_with_eagle3[xgrammar] is appropriate for the pre_merge stage while the guided decoding with Eagle3 feature is being developed and stabilized.

tensorrt_llm/_torch/speculative/utils.py (2)

1-6: LGTM! Import changes support the new guided decoder integration.

The addition of Optional typing and GuidedDecoder import are necessary for the function signature update, and the relative import style for SpecMetadata maintains consistency.


119-140: LGTM! Clean integration of guided decoder with speculative drafter.

The function signature properly accepts the optional guided_decoder parameter and passes it through to ModelDrafter for the appropriate speculative decoding modes. The implementation follows established patterns and maintains backward compatibility with the default None value.

tensorrt_llm/_torch/pyexecutor/py_executor_creator.py (2)

36-36: LGTM! New execution stage follows established pattern.

The addition of GUIDED_DECODER stage for memory monitoring is consistent with the existing enum structure and naming conventions.


379-383: LGTM! Completes the guided decoder integration.

The addition of the guided_decoder parameter to the get_spec_drafter call properly passes the created guided decoder instance to enable the integration with speculative drafting.

tests/integration/defs/accuracy/test_llm_api_pytorch.py (2)

322-338: LGTM! Well-structured test for guided decoding with Eagle3

The test properly integrates guided decoding with Eagle3 speculative decoding. The configuration choices are appropriate:

  • Setting TRTLLM_XGUIDANCE_LENIENT aligns with other guided decoding tests
  • Disabling overlap scheduler is correct for this integration
  • Using eagle3_one_model=False ensures testing the two-model engine approach mentioned in the PR objectives

339-352: LGTM! Consistent test structure for NGram speculative decoding

The test maintains consistency with the Eagle3 test while properly configuring NGram-specific parameters. This provides good coverage for different speculative decoding approaches with guided decoding.

tensorrt_llm/_torch/speculative/model_drafter.py (5)

49-50: LGTM! Clean integration of guided decoder

The optional guided_decoder parameter maintains backward compatibility while enabling the new guided decoding functionality.

Also applies to: 67-67


69-80: Good refactoring! Simplified method signature

The refactoring to accept a single LlmRequest object improves maintainability and ensures all request attributes (including the new guided_decoding_params) are consistently propagated to draft requests.


315-322: LGTM! Well-encapsulated guided decoder execution

The method properly handles the guided decoder execution with appropriate null checking and support for optional d2t tensor data.


400-402: LGTM! Appropriate placement of rollback logic

The rollback ensures proper state management by resetting draft tokens before the target model build phase, maintaining consistency between draft token acceptance and rejection flows.


132-132: All get_tokens calls are updated consistently
No occurrences of the old get_tokens()[index] pattern remain in the repository.

tensorrt_llm/_torch/pyexecutor/guided_decoder.py (5)

18-46: LGTM! Constructor properly extends to support draft tokens.

The constructor changes correctly:

  • Add the max_num_draft_tokens parameter and pass it to the XGrammarMatcherFactory
  • Resize bitmask tensors to accommodate draft tokens with the +1 dimension for the initial token
  • Initialize new state tracking lists for draft token handling
  • Add helpful logging for backend initialization

74-89: LGTM! Helper methods clearly encapsulate matcher state logic.

The helper methods properly determine matcher state:

  • _is_matcher_init correctly identifies context initialization requests that need matcher creation
  • _is_matcher_in_progress appropriately handles both draft and generation requests
  • Logic is clear and follows expected guided decoding flow patterns

90-151: LGTM! Build method properly implements draft token support.

The build method refactoring correctly:

  • Uses appropriate slot assignment for draft vs non-draft requests
  • Handles token acceptance failures gracefully for draft requests while maintaining strict validation for non-draft
  • Implements proper draft token processing with termination checks
  • Updates state tracking accurately throughout the process
  • Uses asynchronous copying for performance optimization

The existing TODO comment about error responses is already noted in past reviews and doesn't block this implementation.


152-186: LGTM! Execute method properly handles draft-to-target logits mapping.

The execute method updates correctly:

  • Implements proper draft-to-target (d2t) tensor remapping when needed
  • Handles batched processing of multiple guided tokens per slot
  • Maintains accurate offset tracking for logits tensor indexing
  • Uses appropriate PyTorch operations for index copying and selection

187-231: LGTM! Rollback methods properly implement draft token state management.

The rollback methods are well-designed:

  • Clear documentation explains the calling context for each method
  • rollback_rejected_tokens correctly calculates rollback count based on accepted vs advanced tokens
  • rollback_draft_tokens properly resets all draft state after rollback
  • Early returns for non-draft scenarios optimize performance
  • Error handling maintains system integrity while noting future improvements

@syuoni syuoni changed the title [TRTLLM-6409][feat] Enable guided decoding with speculative decoding (part 1: two-model engine) [TRTLLM-6454, TRTLLM-6409][feat] Enable guided decoding with speculative decoding (part 1: two-model engine) Aug 4, 2025
@syuoni syuoni changed the title [TRTLLM-6454, TRTLLM-6409][feat] Enable guided decoding with speculative decoding (part 1: two-model engine) [TRTLLM-6409][feat] Enable guided decoding with speculative decoding (part 1: two-model engine) Aug 4, 2025
@tensorrt-cicd
Copy link
Collaborator

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

syuoni added 13 commits August 7, 2025 09:29
Signed-off-by: Enwei Zhu <[email protected]>
Signed-off-by: Enwei Zhu <[email protected]>
Signed-off-by: Enwei Zhu <[email protected]>
Signed-off-by: Enwei Zhu <[email protected]>
Signed-off-by: Enwei Zhu <[email protected]>
Signed-off-by: Enwei Zhu <[email protected]>
Signed-off-by: Enwei Zhu <[email protected]>
Signed-off-by: Enwei Zhu <[email protected]>
Signed-off-by: Enwei Zhu <[email protected]>
Signed-off-by: Enwei Zhu <[email protected]>
Signed-off-by: Enwei Zhu <[email protected]>
Signed-off-by: Enwei Zhu <[email protected]>
Signed-off-by: Enwei Zhu <[email protected]>
@syuoni syuoni force-pushed the guided-with-spec branch from 93dc7ab to d9913e1 Compare August 7, 2025 09:35
@syuoni
Copy link
Collaborator Author

syuoni commented Aug 7, 2025

/bot reuse-pipeline --comment "trivial rebase conflict resolved locally"

@tensorrt-cicd
Copy link
Collaborator

PR_Github #14443 [ reuse-pipeline ] triggered by Bot

@syuoni syuoni enabled auto-merge (squash) August 7, 2025 09:44
@tensorrt-cicd
Copy link
Collaborator

PR_Github #14443 [ reuse-pipeline ] completed with state SUCCESS
Reusing PR_Github #14352 for commit d9913e1

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.

7 participants