-
Notifications
You must be signed in to change notification settings - Fork 2k
[TRTLLM-10312][perf] Improve performance of _write_finish_reasons in TorchSampler #10459
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
base: main
Are you sure you want to change the base?
[TRTLLM-10312][perf] Improve performance of _write_finish_reasons in TorchSampler #10459
Conversation
|
/bot run |
|
PR_Github #30754 [ run ] triggered by Bot. Commit: |
|
PR_Github #30754 [ run ] completed with state
|
060564a to
1f9cd59
Compare
|
/bot run --disable-fail-fast |
|
PR_Github #30888 [ run ] triggered by Bot. Commit: |
|
PR_Github #30888 [ run ] completed with state
|
89264aa to
16bdf59
Compare
|
/bot run |
|
PR_Github #31071 [ run ] triggered by Bot. Commit: |
|
PR_Github #31071 [ run ] completed with state |
- Added `max_lengths_tensor` to the `Store` class to cache max_length per request. - Introduced `_is_new_request` method to streamline request state checks. - Updated `setup_sampler_step` to fill `max_lengths_tensor` based on request parameters. - Refactored `_are_max_length` for improved token processing on device. Signed-off-by: Stefan Niebler <[email protected]>
- Introduced `end_ids` tensor in the `Store` class to store end IDs for each request. - Updated `setup_sampler_step` to fill `end_ids` based on request parameters. - Refactored `_are_end_id` method to utilize the new `end_ids` tensor for better performance. Signed-off-by: Stefan Niebler <[email protected]>
…usted override of setup_sampler_step Signed-off-by: Stefan Niebler <[email protected]>
…_tensor Signed-off-by: Stefan Niebler <[email protected]>
16bdf59 to
570094a
Compare
|
/bot run |
|
PR_Github #31228 [ run ] triggered by Bot. Commit: |
|
PR_Github #31228 [ run ] completed with state
|
|
/bot run |
|
PR_Github #31530 [ run ] triggered by Bot. Commit: |
|
PR_Github #31530 [ run ] completed with state |
📝 WalkthroughWalkthroughThe changes introduce per-request buffer tracking to TorchSampler by adding Changes
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes 🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing touches
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. 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.
Actionable comments posted: 0
🧹 Nitpick comments (1)
tensorrt_llm/_torch/pyexecutor/sampler.py (1)
1339-1355: Per-request buffer initialization is functionally correct.The logic correctly initializes
max_lengths_tensorandend_idsfor new requests. However, based on learnings about performance in this file, the current loop with per-elementfill_()calls could be batched for better efficiency when there are many new requests.Consider batching the initialization:
♻️ Optional optimization for batched initialization
@override def setup_sampler_step(self, scheduled_requests: ScheduledRequests): """Setup the sampler step for the requests Args: requests: list[LlmRequest]. The requests to setup the sampler step for """ if self._use_beam_search: self._prepare_beam_search(scheduled_requests.all_requests()) + new_requests = [r for r in scheduled_requests.all_requests() if self._is_new_request(r)] + if new_requests: + seq_slots = torch.tensor([r.py_seq_slot for r in new_requests], dtype=torch.int64, device="cuda") + max_lengths = torch.tensor( + [min(self.max_seq_len, r.orig_prompt_len + r.py_max_new_tokens) for r in new_requests], + dtype=torch.int32, device="cuda" + ) + end_ids_vals = torch.tensor( + [r.py_end_id if r.py_end_id is not None else -1 for r in new_requests], + dtype=torch.int32, device="cuda" + ) + self.store.max_lengths_tensor[seq_slots] = max_lengths + self.store.end_ids[seq_slots] = end_ids_vals - for request in scheduled_requests.all_requests(): - if self._is_new_request(request): - self.store.max_lengths_tensor[request.py_seq_slot].fill_( - min(self.max_seq_len, request.orig_prompt_len + request.py_max_new_tokens) - ) - self.store.end_ids[request.py_seq_slot].fill_( - request.py_end_id if request.py_end_id is not None else -1 - )
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (3)
tensorrt_llm/_torch/pyexecutor/sampler.pytensorrt_llm/_torch/speculative/mtp.pytests/unittest/_torch/sampler/test_torch_sampler.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 Python modules, 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, with prefixkfor variable names that start with a number (e.g.,k_99th_percentile)
Python global variables should use upper snake_case with prefixG(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 Python interfaces that may be used outside a file, prefer docstrings over comments
Use comments in Python for code within a function, or interfaces that are local to a file
Use Google-style docstrings for Python classes and functions, which can be parsed by Sphinx
Python attributes and variables can be documented inline with the format"""<type>: Description"""
Avoid using reflection in Python when functionality can be easily achieved without reflection
When using try-except blocks in Python, limit the except clause to the smallest set of errors possible
When using try-except blocks in Python to handle multiple possible variable types (duck-typing), keep the body of the try as small as possible and use the else block for the main logic
Files:
tests/unittest/_torch/sampler/test_torch_sampler.pytensorrt_llm/_torch/speculative/mtp.pytensorrt_llm/_torch/pyexecutor/sampler.py
**/*.{cpp,cc,cxx,h,hpp,hxx,cu,cuh,py}
📄 CodeRabbit inference engine (CODING_GUIDELINES.md)
All TensorRT-LLM source files (.cpp, .h, .cu, .py, and other source files) should contain an NVIDIA copyright header with the year of latest meaningful modification
Files:
tests/unittest/_torch/sampler/test_torch_sampler.pytensorrt_llm/_torch/speculative/mtp.pytensorrt_llm/_torch/pyexecutor/sampler.py
🧠 Learnings (7)
📓 Common learnings
Learnt from: tongyuantongyu
Repo: NVIDIA/TensorRT-LLM PR: 9655
File: tensorrt_llm/_torch/pyexecutor/sampler.py:3031-3031
Timestamp: 2025-12-12T03:27:18.859Z
Learning: In tensorrt_llm/_torch/pyexecutor/sampler.py, when reviewing code that iterates through requests, ensure it does not convert excessive data into Python lists. Instead, the code should use torch.gather or indexing to gather only the data that will be used in the for loop before converting to Python lists. This minimizes data movement and improves performance.
Learnt from: tongyuantongyu
Repo: NVIDIA/TensorRT-LLM PR: 9655
File: tensorrt_llm/_torch/pyexecutor/sampler.py:3031-3031
Timestamp: 2025-12-12T03:27:18.859Z
Learning: In tensorrt_llm/_torch/pyexecutor/sampler.py, when reviewing code that iterates through requests, ensure it does not access torch.Tensor objects (CPU or GPU) inside the loop. Instead, the code should use .tolist() to convert batched data tensors to Python lists beforehand, and then access the list in the for loop. This is a critical performance consideration.
📚 Learning: 2025-12-12T03:27:18.859Z
Learnt from: tongyuantongyu
Repo: NVIDIA/TensorRT-LLM PR: 9655
File: tensorrt_llm/_torch/pyexecutor/sampler.py:3031-3031
Timestamp: 2025-12-12T03:27:18.859Z
Learning: In tensorrt_llm/_torch/pyexecutor/sampler.py, when reviewing code that iterates through requests, ensure it does not convert excessive data into Python lists. Instead, the code should use torch.gather or indexing to gather only the data that will be used in the for loop before converting to Python lists. This minimizes data movement and improves performance.
Applied to files:
tests/unittest/_torch/sampler/test_torch_sampler.pytensorrt_llm/_torch/pyexecutor/sampler.py
📚 Learning: 2025-12-12T03:27:18.859Z
Learnt from: tongyuantongyu
Repo: NVIDIA/TensorRT-LLM PR: 9655
File: tensorrt_llm/_torch/pyexecutor/sampler.py:3031-3031
Timestamp: 2025-12-12T03:27:18.859Z
Learning: In tensorrt_llm/_torch/pyexecutor/sampler.py, when reviewing code that iterates through requests, ensure it does not access torch.Tensor objects (CPU or GPU) inside the loop. Instead, the code should use .tolist() to convert batched data tensors to Python lists beforehand, and then access the list in the for loop. This is a critical performance consideration.
Applied to files:
tests/unittest/_torch/sampler/test_torch_sampler.py
📚 Learning: 2025-12-12T03:27:08.565Z
Learnt from: tongyuantongyu
Repo: NVIDIA/TensorRT-LLM PR: 9655
File: tensorrt_llm/_torch/pyexecutor/sampler.py:3031-3031
Timestamp: 2025-12-12T03:27:08.565Z
Learning: In files under tensorrt_llm/_torch/pyexecutor, avoid accessing torch.Tensor objects inside for-loops when iterating over requests. Convert batched tensors to Python lists beforehand using tensor.tolist(), and then iterate over those lists. This improves performance by reducing tensor-bound operations inside hot loops. Apply this pattern to similar code paths that process batches to access simple Python data structures (lists) inside loops.
Applied to files:
tensorrt_llm/_torch/pyexecutor/sampler.py
📚 Learning: 2025-08-13T16:20:37.987Z
Learnt from: dcampora
Repo: NVIDIA/TensorRT-LLM PR: 6867
File: tensorrt_llm/_torch/pyexecutor/sampler.py:67-72
Timestamp: 2025-08-13T16:20:37.987Z
Learning: In TensorRT-LLM sampler code, performance is prioritized over additional validation checks. The beam_width helper method intentionally returns the first request's beam_width without validating consistency across all requests to avoid performance overhead from iterating through the entire batch.
Applied to files:
tensorrt_llm/_torch/pyexecutor/sampler.py
📚 Learning: 2025-08-18T08:42:02.640Z
Learnt from: samuellees
Repo: NVIDIA/TensorRT-LLM PR: 6974
File: tensorrt_llm/serve/scripts/benchmark_dataset.py:558-566
Timestamp: 2025-08-18T08:42:02.640Z
Learning: In TensorRT-LLM's RandomDataset (tensorrt_llm/serve/scripts/benchmark_dataset.py), when using --random-token-ids option, sequence length accuracy is prioritized over semantic correctness for benchmarking purposes. The encode/decode operations should use skip_special_tokens=True and add_special_tokens=False to ensure exact target token lengths.
Applied to files:
tensorrt_llm/_torch/pyexecutor/sampler.py
📚 Learning: 2025-08-28T10:22:02.288Z
Learnt from: ixlmar
Repo: NVIDIA/TensorRT-LLM PR: 7294
File: tensorrt_llm/_torch/pyexecutor/sampler.py:1191-1197
Timestamp: 2025-08-28T10:22:02.288Z
Learning: In tensorrt_llm/_torch/pyexecutor/sampler.py, the object identity comparison `softmax_req_indices is not group_req_indices_cuda` on line ~1191 is intentional and used as an optimization to determine whether to reuse an existing indexer or create a new one, based on which code path was taken during tensor assignment.
Applied to files:
tensorrt_llm/_torch/pyexecutor/sampler.py
🧬 Code graph analysis (2)
tests/unittest/_torch/sampler/test_torch_sampler.py (1)
tensorrt_llm/_torch/pyexecutor/sampler.py (1)
_write_finish_reasons(2464-2535)
tensorrt_llm/_torch/pyexecutor/sampler.py (2)
tensorrt_llm/_torch/pyexecutor/llm_request.py (1)
LlmRequest(462-691)tensorrt_llm/_torch/pyexecutor/scheduler.py (1)
ScheduledRequests(21-42)
🔇 Additional comments (10)
tensorrt_llm/_torch/speculative/mtp.py (1)
225-236: LGTM!The interface-compliance fields (
finish_reasons,end_ids,max_lengths_tensor) withNonedefaults and the no-opsetup_sampler_stepoverride correctly satisfy theTorchSampler.Storeinterface without adding unnecessary logic, sinceMTPSamplerhandles finish reasons through its own path inupdate_requests.tests/unittest/_torch/sampler/test_torch_sampler.py (1)
694-728: LGTM!The test setup correctly initializes the new per-request buffers:
seq_lensfrommax_beam_num_tokensrepresents current sequence lengthsmax_seq_lenscalculation mirrors the sampler logic for maximum allowed sequence lengthsend_idswith-1sentinel for None end IDsThis properly exercises the updated
_write_finish_reasonsinterface with device-resident per-request data.tensorrt_llm/_torch/pyexecutor/sampler.py (8)
835-841: LGTM!The new
max_lengths_tensorandend_idsfields are well-documented with clear docstrings describing their shape and usage, following Google-style conventions.
890-898: LGTM!The new tensors are correctly allocated with consistent shape
(max_num_sequences,)in both the beam-search and non-beam-search paths.
1329-1337: LGTM!The
_is_new_requesthelper correctly identifies when to initialize per-request buffers by:
- Excluding finished and draft requests
- Handling both chunked context (last chunk) and disaggregated generation scenarios
This aligns with the commit message about preventing draft requests from modifying
max_lengths_tensor.
1367-1367: LGTM!Good refactoring to use the centralized
_is_new_requesthelper, ensuring consistent logic across beam search preparation and buffer initialization.
1877-1899: LGTM!The
seq_lenstensor is correctly constructed frommax_beam_num_tokens, transferred to CUDA, and passed through to_write_finish_reasonsfor on-device finish reason computation. This aligns with the PR's goal of reducing host-to-device communication.
2486-2524: LGTM!The refactored
_write_finish_reasonsnow:
- Properly validates device consistency with assertions
- Uses pre-stored
max_lengths_tensorandend_idsinstead of per-request iteration- Keeps finish reason computation entirely on device
This achieves the PR's performance improvement goal by eliminating repeated host-to-device reads.
2537-2538: LGTM!The refactored
_are_end_idperforms an efficient batched comparison using tensor broadcasting. Theend_idstensor is correctly reshaped from(batch_size,)to(1, batch_size, 1)and broadcast-compared againsttokensof shape(max_tokens, batch_size, max_beam_width).
2540-2559: LGTM!The refactored
_are_max_lengthcorrectly computes whether each position reaches max length:
lengths_tensoradds step offsets (1 throughmax_tokens) to current sequence lengths- Comparison
>= max_lengths_tensorproperly identifies when sequences reach their limit- All computation stays on device, achieving the performance improvement goal
Summary by CodeRabbit
Enhancements
Tests
✏️ Tip: You can customize this high-level summary in your review settings.
Description
Adjust
_are_end_idand_are_max_lengthfunction in_write_finish_reasonsto omit host to device communication, by storing theend_idsandmax_lengthsinformation of each request in a device buffer. This information is only stored once per request as it is constant over time and therefore does not need to be gathered from the request every iteration.This change is intended to improve overall performance of
_write_finish_reasonsandsample_asyncPerformance Results (Preliminary)
ToT:
Request / second (TinyLlama-1.1B, ISL 1024, OSL 2048, BatchSize 512)
This PR:
NsightSystems measurements:
average runtime in ms (TinyLlama-1.1B, ISL 1024, OSL 2048, BatchSize 512)
ToT:
This PR:
Test Coverage
The general functionality did not change, therefore the following tests continue to cover the functionality.
PR Checklist
Please review the following before submitting your PR:
PR description clearly explains what and why. If using CodeRabbit's summary, please make sure it makes sense.
PR Follows TRT-LLM CODING GUIDELINES to the best of your knowledge.
Test cases are provided for new code paths (see test instructions)
Any new dependencies have been scanned for license and vulnerabilities
CODEOWNERS updated if ownership changes
Documentation updated as needed
Update tava architecture diagram if there is a significant design change in PR.
The reviewers assigned automatically/manually are appropriate for the PR.
Please check this after reviewing the above items as appropriate for this PR.
GitHub Bot Help
/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.