-
Notifications
You must be signed in to change notification settings - Fork 2k
[TRTLLM-6794][feat] enable rejection sampler for ngram #7195
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
📝 WalkthroughWalkthroughAdds n-gram speculative decoding support: wraps scheduled requests into LlmRequest-based wrappers with SamplingConfig, tracks context/generation mappings, calls NGramDrafter.prepare_draft_tokens with a request_mapping, and performs a secondary greedy sampling pass when enabled. Updates sampler to use ephemeral token stores and enforce uniform strategies when mixed sampling is off. Changes
Sequence Diagram(s)sequenceDiagram
autonumber
participant Exec as PyExecutor
participant Drafter as NGramDrafter
participant Sampler as TorchSampler
rect rgb(245,245,255)
Note over Exec: Schedule requests
Exec->>Exec: Wrap generation/context into LlmRequest + SamplingConfig
Exec->>Drafter: prepare_draft_tokens(scheduled, request_mapping)
Drafter-->>Exec: draft tokens attached to mapped LlmRequests
end
Exec->>Sampler: sample_async(scheduled, model_outputs)
Sampler-->>Exec: SampleState (primary)
alt n-gram mode active and wrapped generation requests exist
Note over Exec: Secondary greedy pass
Exec->>Sampler: sample_async(greedy_sample_requests, model_outputs)
Sampler-->>Exec: SampleState (greedy)
Exec->>Exec: _update_requests(...)
end
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45–60 minutes Possibly related PRs
Suggested labels
Suggested reviewers
Tip 🔌 Remote MCP (Model Context Protocol) integration is now available!Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats. ✨ 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/Issue comments)Type Other keywords and placeholders
Status, 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
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
tensorrt_llm/_torch/pyexecutor/py_executor.py (1)
1064-1069: Clean up mapping dictionaries to prevent leaks.context_request_mapping and generation_request_mapping live for the executor lifetime and will accumulate entries unless removed when requests complete.
Apply this diff after finished_requests is computed:
finished_requests = self._handle_responses() + # Cleanup ngram request mappings for completed requests + if (self.drafter is not None and hasattr(self.drafter, 'spec_config') + and self.drafter.spec_config.spec_dec_mode.is_ngram()): + for req in finished_requests: + rid = req.py_request_id + generation_request_mapping.pop(rid, None) + context_request_mapping.pop(rid, None)
🧹 Nitpick comments (7)
tensorrt_llm/_torch/pyexecutor/sampler.py (2)
1-1: Add NVIDIA copyright header (2025).Per repo guidelines, prepend the current-year NVIDIA copyright header.
Apply at the top of the file.
539-541: Avoid per-call GPU allocation of new_tokens; reuse the preallocated store.Creating a fresh Store every sample_async() call causes persistent GPU allocations and GC pressure. The class already preallocates self.store in init; reuse it unless you specifically need double-buffering to avoid aliasing.
Apply this diff:
- # new_tokens = self.store.new_tokens - new_tokens = self.create_store().new_tokens + new_tokens = self.store.new_tokensIf aliasing was the motivation, consider a tiny ring-buffer (2 stores) managed by an index rather than allocating every iteration. I can sketch that if helpful.
tensorrt_llm/_torch/speculative/ngram.py (4)
1-1: Add NVIDIA copyright header (2025).Per repo guidelines, prepend the current-year NVIDIA copyright header.
177-183: Harden prepare_draft_tokens() contract and document request_mapping.The new request_mapping arg is required for correctness, but the function doesn't validate it or explain its expectations.
Apply this diff to add input validation (cheap) and a short docstring:
def prepare_draft_tokens( self, scheduled_requests: ScheduledRequests, - request_mapping: dict[int, LlmRequest], + request_mapping: dict[int, LlmRequest], resource_manager: Optional[ResourceManager] = None, ) -> None: + """Populate py_draft_tokens for scheduled generation requests. + + Args: + scheduled_requests: Batch with generation requests to draft for. + request_mapping: Dict keyed by py_request_id that maps to public LlmRequest + wrappers used elsewhere (e.g., greedy pass). All generation requests in + scheduled_requests must exist in this mapping. + resource_manager: Unused here. + """ + # Fail early on missing mappings + missing = [ + r.py_request_id + for r in scheduled_requests.generation_requests + if r.py_request_id not in request_mapping + ] + if missing: + raise KeyError(f"NGramDrafter.prepare_draft_tokens: missing request ids in request_mapping: {missing}")
193-193: Make prefix source robust to mapping misses.Small guard improves resilience and allows graceful fallback during rare desyncs.
Apply this diff:
- prefix = list(request_mapping[request.py_request_id].get_tokens(0)) + wrapper = request_mapping.get(request.py_request_id, request) + prefix = list(wrapper.get_tokens(0))
207-209: Keep a single source of truth for py_draft_tokens.Assigning the same list reference to both objects is fine today, but future code might rebind one side. Prefer setting the mapping’s attribute first, then aliasing request’s to it.
Apply this diff:
- request.py_draft_tokens = draft_tokens - request_mapping[ - request.py_request_id].py_draft_tokens = draft_tokens + mapping_req = request_mapping[request.py_request_id] + mapping_req.py_draft_tokens = draft_tokens + # Share the same list object to avoid divergence. + request.py_draft_tokens = mapping_req.py_draft_tokenstensorrt_llm/_torch/pyexecutor/py_executor.py (1)
1-1: Add NVIDIA copyright header (2025).Per repo guidelines, prepend the current-year NVIDIA copyright header.
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (3)
tensorrt_llm/_torch/pyexecutor/py_executor.py(4 hunks)tensorrt_llm/_torch/pyexecutor/sampler.py(2 hunks)tensorrt_llm/_torch/speculative/ngram.py(3 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.py
📄 CodeRabbit inference engine (CODING_GUIDELINES.md)
**/*.py: Python code must target Python 3.8+
Python indentation: 4 spaces, no tabs
Maintain module namespace in imports (from package.subpackage import foo; then use foo.SomeClass())
Python file names use snake_case
Python class names use PascalCase
Python functions/methods and local variables use snake_case; variables starting with a number get k_ prefix (e.g., k_99th_percentile)
Global variables use G_ prefixed UPPER_SNAKE_CASE (e.g., G_MY_GLOBAL)
Constants use UPPER_SNAKE_CASE in Python
Avoid shadowing variables from outer scopes in Python
Initialize all externally visible members of a Python class in init
Prefer docstrings for interfaces used outside a file; comments for local code
Use Google-style docstrings for classes and functions (Sphinx-parsable)
Document attributes/variables inline with short docstrings
Avoid reflection when simple alternatives exist (e.g., prefer explicit parameters over dict(**locals()))
In try/except, catch the narrowest exceptions possible
For duck-typing with try/except, keep try body minimal and put logic in else
Files:
tensorrt_llm/_torch/speculative/ngram.pytensorrt_llm/_torch/pyexecutor/sampler.pytensorrt_llm/_torch/pyexecutor/py_executor.py
**/*.{cpp,cxx,cc,cu,h,hpp,hxx,hh,cuh,py}
📄 CodeRabbit inference engine (CODING_GUIDELINES.md)
Prepend NVIDIA copyright header (current year) to all source files
Files:
tensorrt_llm/_torch/speculative/ngram.pytensorrt_llm/_torch/pyexecutor/sampler.pytensorrt_llm/_torch/pyexecutor/py_executor.py
🧬 Code graph analysis (3)
tensorrt_llm/_torch/speculative/ngram.py (1)
tensorrt_llm/_torch/pyexecutor/llm_request.py (1)
LlmRequest(271-411)
tensorrt_llm/_torch/pyexecutor/sampler.py (1)
tensorrt_llm/_torch/speculative/mtp.py (1)
create_store(226-235)
tensorrt_llm/_torch/pyexecutor/py_executor.py (5)
tensorrt_llm/_torch/pyexecutor/llm_request.py (4)
LlmResponse(261-268)LlmRequest(271-411)append(78-97)append(124-141)tensorrt_llm/runtime/generation.py (1)
SamplingConfig(658-707)tensorrt_llm/_torch/speculative/interface.py (1)
is_ngram(41-42)tensorrt_llm/_torch/pyexecutor/scheduler.py (1)
ScheduledRequests(18-39)tensorrt_llm/_torch/speculative/ngram.py (1)
prepare_draft_tokens(177-208)
🔇 Additional comments (2)
tensorrt_llm/_torch/pyexecutor/py_executor.py (2)
1035-1038: OK to pass generation_request_mapping into ngram drafter.This matches the updated signature and enables prefix sourcing from wrappers. No action needed here.
1015-1018: Verify SamplingConfig List-Like Fields Before OverridingBefore blindly assigning
SamplingConfig()to a request, confirm that its Python dataclass uses list-shaped defaults fortop_k,top_p, andtemperature—otherwise thelen(... )and[0]usages in
tensorrt_llm/_torch/pyexecutor/sampler.py:252–260will trigger aTypeError.• Open
tensorrt_llm/runtime/generation.pyand verify that in@dataclass class SamplingConfig: # … other fields … top_k: Optional[List[int]] = field(default_factory=list) top_p: Optional[List[float]] = field(default_factory=list) temperature: Optional[List[float]] = field(default_factory=lambda: [1.0]) # … etc. …each of those fields is indeed declared as a list (with a
default_factory) rather than a scalar.
• If they’re not list-typed by default, replace your override ofreq.py_request_id].sampling_config = SamplingConfig()with something like:- req.py_request_id].sampling_config = SamplingConfig() + import copy + cfg = copy.deepcopy(req.py_request_id].sampling_config) + cfg.top_k = [] + cfg.top_p = [] + cfg.temperature = [1.0] + req.py_request_id].sampling_config = cfgso you don’t break the downstream length checks or indexing.
Also apply the same pattern at lines 1028–1031 where you append the greedy config.
| if (self.drafter is not None | ||
| and hasattr(self.drafter, 'spec_config') and | ||
| self.drafter.spec_config.spec_dec_mode.is_ngram()): | ||
| if len(greedy_sample_requests.generation_requests) > 0: | ||
| greedy_sample_state = self._sample_async( | ||
| greedy_sample_requests, batch_outputs) | ||
| self._update_requests(greedy_sample_state) | ||
|
|
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.
Remove the second _sample_async/_update_requests call.
This is the second half of the double-append bug. Even if you kept greedy_sample_requests, you must not call update_requests on them.
Apply this diff:
- if (self.drafter is not None
- and hasattr(self.drafter, 'spec_config') and
- self.drafter.spec_config.spec_dec_mode.is_ngram()):
- if len(greedy_sample_requests.generation_requests) > 0:
- greedy_sample_state = self._sample_async(
- greedy_sample_requests, batch_outputs)
- self._update_requests(greedy_sample_state)
+ # NGram path: no secondary sampling pass; scheduled_batch update below is the sole mutator.📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| if (self.drafter is not None | |
| and hasattr(self.drafter, 'spec_config') and | |
| self.drafter.spec_config.spec_dec_mode.is_ngram()): | |
| if len(greedy_sample_requests.generation_requests) > 0: | |
| greedy_sample_state = self._sample_async( | |
| greedy_sample_requests, batch_outputs) | |
| self._update_requests(greedy_sample_state) | |
| # NGram path: no secondary sampling pass; scheduled_batch update below is the sole mutator. |
🤖 Prompt for AI Agents
In tensorrt_llm/_torch/pyexecutor/py_executor.py around lines 1046 to 1053,
remove the second invocation of _sample_async and the subsequent
_update_requests call on greedy_sample_requests (the block that starts with if
len(greedy_sample_requests.generation_requests) > 0: ...); this prevents the
double-append bug — simply delete that inner call/block so
greedy_sample_requests are not sampled/updated twice.
57b5454 to
b2be73d
Compare
b2be73d to
47d7b61
Compare
|
/bot run |
|
PR_Github #16443 [ run ] triggered by Bot |
|
PR_Github #16443 [ run ] completed with state |
SimengLiu-nv
left a comment
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.
Please also add tests.
| def prepare_draft_tokens( | ||
| self, | ||
| scheduled_requests: ScheduledRequests, | ||
| request_mapping: dict[int, LlmRequest], |
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.
Why having both scheduled_requests and request_mapping?
In addition, if you want to change the function parameters for prepare_draft_tokens, please update the other instances as well.
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.
Please refer to the jira ticket description part.
I will write a detailed description for the PR tomorrow.
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.
Hi @kris1025 , thank you for the update. From your code, request_mapping/generation_request_mapping is parsed from scheduled_requests. Then having both scheduled_requests and request_mapping seems like a duplication and can be optimized.
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.
Inconsistent parameter list again.
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.
I have updated the code. The request_mapping is a global record over all the scheduled_requests, so the prepare_draft_tokens interface needs to be updated.
fbc81ae to
9626ae4
Compare
Signed-off-by: linquanh <[email protected]>
Signed-off-by: linquanh <[email protected]>
Signed-off-by: linquanh <[email protected]>
6f7fb53 to
72c409b
Compare
Signed-off-by: linquanh <[email protected]>
72c409b to
5bd3a1e
Compare
|
/bot run |
|
PR_Github #16557 [ run ] triggered by Bot |
|
PR_Github #16557 [ run ] completed with state |
SimengLiu-nv
left a comment
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.
Minor fixes needed.
| def prepare_draft_tokens( | ||
| self, | ||
| scheduled_requests: ScheduledRequests, | ||
| request_mapping: dict[int, LlmRequest], |
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.
request_mapping is marked optional in drafter.py but not here.
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.
Thanks. The code is updated.
| def prepare_draft_tokens( | ||
| self, | ||
| scheduled_requests: ScheduledRequests, | ||
| request_mapping: dict[int, LlmRequest], |
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.
Inconsistent parameter list again.
Signed-off-by: linquanh <[email protected]>
|
/bot run |
|
Thanks for doing this experiment, it is very useful info to have. Given that AR is not improved as originally expected, shall we just close this one? |
As it is not beneficial to AR, I will close the PR. |
Summary by CodeRabbit
New Features
Bug Fixes
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.
Details
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-listparameter 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.mdand the
scripts/test_to_stage_mapping.pyhelper.kill
killKill all running builds associated with pull request.
skip
skip --comment COMMENTSkip 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-pipelineReuse 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.