-
Notifications
You must be signed in to change notification settings - Fork 1.7k
[TRTLLM-6409][feat] Enable guided decoding with speculative decoding (part 1: two-model engine) #6300
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
📝 WalkthroughWalkthroughThe 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
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
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
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~45 minutes Possibly related PRs
Suggested labels
Suggested reviewers
Note ⚡️ Unit Test Generation is now available in beta!Learn more here, or try it out under "Finishing Touches" below. 📜 Recent review detailsConfiguration used: .coderabbit.yaml 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
⏰ 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)
✨ Finishing Touches
🧪 Generate unit tests
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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
Documentation and Community
|
There was a problem hiding this 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
📒 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
andis_terminated
methods to theGrammarMatcher
interface is cleanly implemented across all concrete classes. The error checking after rollback inLLGuidanceMatcher
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 underlyingxgrammar.GrammarMatcher
asmax_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.
There was a problem hiding this 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
📒 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 listnum_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
andis_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 asmax_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.
There was a problem hiding this 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
📒 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 thenum_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.
@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:
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)? |
8e17439
to
e3cf182
Compare
e3cf182
to
daa1e01
Compare
/bot run |
PR_Github #13923 [ run ] triggered by Bot |
PR_Github #13923 [ run ] completed with state |
75798c4
to
dcecd34
Compare
/bot run --disable-fail-fast |
PR_Github #13956 [ run ] triggered by Bot |
There was a problem hiding this 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 configThe 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
📒 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
andtorch.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 andGuidedDecoder
import are necessary for the function signature update, and the relative import style forSpecMetadata
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 toModelDrafter
for the appropriate speculative decoding modes. The implementation follows established patterns and maintains backward compatibility with the defaultNone
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 theget_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 Eagle3The 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 decodingThe 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 decoderThe 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 signatureThe refactoring to accept a single
LlmRequest
object improves maintainability and ensures all request attributes (including the newguided_decoding_params
) are consistently propagated to draft requests.
315-322
: LGTM! Well-encapsulated guided decoder executionThe 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 logicThe 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
: Allget_tokens
calls are updated consistently
No occurrences of the oldget_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 tokensrollback_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
PR_Github #14352 [ run ] completed with state |
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]>
93dc7ab
to
d9913e1
Compare
/bot reuse-pipeline --comment "trivial rebase conflict resolved locally" |
PR_Github #14443 [ reuse-pipeline ] triggered by Bot |
PR_Github #14443 [ reuse-pipeline ] completed with state |
…(part 1: two-model engine) (NVIDIA#6300) Signed-off-by: Enwei Zhu <[email protected]>
Summary by CodeRabbit
New Features
Improvements
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 thestage-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.