-
Notifications
You must be signed in to change notification settings - Fork 1.9k
[TRTLLM-8377][test] unit tests for TorchSampler batched sampling #9012
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
8613a9a to
e6d6936
Compare
|
/bot run |
|
/bot kill |
|
PR_Github #23855 [ run ] triggered by Bot. Commit: |
|
PR_Github #23857 [ kill ] triggered by Bot. Commit: |
|
PR_Github #23855 [ run ] completed with state |
|
PR_Github #23857 [ kill ] completed with state |
e6d6936 to
3667ad9
Compare
|
/bot run |
|
PR_Github #23861 [ run ] triggered by Bot. Commit: |
|
/bot run --disable-fail-fast |
|
PR_Github #23865 [ run ] triggered by Bot. Commit: |
|
PR_Github #23861 [ run ] completed with state |
|
PR_Github #23865 [ run ] completed with state |
|
/bot run |
|
PR_Github #24011 [ run ] triggered by Bot. Commit: |
|
PR_Github #24011 [ run ] completed with state |
📝 WalkthroughWalkthroughThis PR adds FlashInfer-based sampling support to TensorRT-LLM's Torch executor. It introduces a new sampling utilities module with strategy abstraction, modifies the sampler selection logic to conditionally use FlashInfer when available, and adds a configuration flag to control this behavior via parameter propagation through the executor creation pipeline. Changes
Sequence Diagram(s)sequenceDiagram
participant Client
participant PyExecutor as create_py_executor
participant InstSampler as instantiate_sampler
participant TorchSampler
participant SamplerSel as Sampler Selection
Client->>PyExecutor: llm_args with _disable_flash_infer_sampling
PyExecutor->>InstSampler: disable_flash_infer_sampling from llm_args
InstSampler->>InstSampler: create_torch_sampler_args(disable_flash_infer_sampling)
InstSampler->>TorchSampler: TorchSampler(args with disable_flash_infer_sampling)
alt FlashInfer available & disable_flash_infer_sampling=False
TorchSampler->>SamplerSel: Select FlashInferGroupedStrategySampler
else Fallback (FlashInfer unavailable or disabled)
TorchSampler->>SamplerSel: Select SimpleGroupedStrategySampler
end
SamplerSel->>TorchSampler: _grouped_sampler_cls set
TorchSampler->>Client: Ready for sampling with chosen backend
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Areas requiring extra attention:
Possibly related PRs
Suggested reviewers
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
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: 1
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (7)
tensorrt_llm/_torch/pyexecutor/_util.py(2 hunks)tensorrt_llm/_torch/pyexecutor/py_executor_creator.py(2 hunks)tensorrt_llm/_torch/pyexecutor/sampler.py(9 hunks)tensorrt_llm/_torch/pyexecutor/sampling_utils.py(4 hunks)tensorrt_llm/_torch/pyexecutor/sampling_utils_flashinfer.py(1 hunks)tensorrt_llm/llmapi/llm_args.py(1 hunks)tests/unittest/_torch/sampler/test_torch_sampler.py(3 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
**/*.{h,hpp,hh,hxx,cpp,cxx,cc,cu,cuh,py}
📄 CodeRabbit inference engine (CODING_GUIDELINES.md)
Use only spaces, no tabs; indent with 4 spaces.
Files:
tensorrt_llm/_torch/pyexecutor/py_executor_creator.pytensorrt_llm/llmapi/llm_args.pytensorrt_llm/_torch/pyexecutor/sampling_utils_flashinfer.pytensorrt_llm/_torch/pyexecutor/sampler.pytensorrt_llm/_torch/pyexecutor/sampling_utils.pytests/unittest/_torch/sampler/test_torch_sampler.pytensorrt_llm/_torch/pyexecutor/_util.py
**/*.py
📄 CodeRabbit inference engine (CODING_GUIDELINES.md)
**/*.py: Python code must target Python 3.8+.
Indent Python code with 4 spaces; do not use tabs.
Maintain module namespace when importing; prefer 'from package.subpackage import foo' then 'foo.SomeClass()' instead of importing the class directly.
Python filenames should be snake_case (e.g., some_file.py).
Python classes use PascalCase names.
Functions and methods use snake_case names.
Local variables use snake_case; prefix 'k' for variables that start with a number (e.g., k_99th_percentile).
Global variables use upper SNAKE_CASE prefixed with 'G' (e.g., G_MY_GLOBAL).
Constants use upper SNAKE_CASE (e.g., MY_CONSTANT).
Avoid shadowing variables from an outer scope.
Initialize all externally visible members of a class in the constructor.
Prefer docstrings for interfaces that may be used outside a file; comments for in-function or file-local interfaces.
Use Google-style docstrings for classes and functions (Sphinx-parsable).
Document attributes and variables inline so they render under the class/function docstring.
Avoid reflection when a simpler, explicit approach suffices (e.g., avoid dict(**locals()) patterns).
In try/except, catch the most specific exceptions possible.
For duck-typing try/except, keep the try body minimal and use else for the main logic.
Files:
tensorrt_llm/_torch/pyexecutor/py_executor_creator.pytensorrt_llm/llmapi/llm_args.pytensorrt_llm/_torch/pyexecutor/sampling_utils_flashinfer.pytensorrt_llm/_torch/pyexecutor/sampler.pytensorrt_llm/_torch/pyexecutor/sampling_utils.pytests/unittest/_torch/sampler/test_torch_sampler.pytensorrt_llm/_torch/pyexecutor/_util.py
**/*.{cpp,cxx,cc,h,hpp,hh,hxx,cu,cuh,py}
📄 CodeRabbit inference engine (CODING_GUIDELINES.md)
Prepend the NVIDIA Apache-2.0 copyright header with current year to the top of all source files (e.g., .cpp, .h, .cu, .py).
Files:
tensorrt_llm/_torch/pyexecutor/py_executor_creator.pytensorrt_llm/llmapi/llm_args.pytensorrt_llm/_torch/pyexecutor/sampling_utils_flashinfer.pytensorrt_llm/_torch/pyexecutor/sampler.pytensorrt_llm/_torch/pyexecutor/sampling_utils.pytests/unittest/_torch/sampler/test_torch_sampler.pytensorrt_llm/_torch/pyexecutor/_util.py
🧠 Learnings (6)
📓 Common learnings
Learnt from: ixlmar
Repo: NVIDIA/TensorRT-LLM PR: 7294
File: tensorrt_llm/_torch/pyexecutor/sampler.py:368-392
Timestamp: 2025-08-27T15:03:57.149Z
Learning: In TensorRT-LLM's sampler.py, int32 usage for softmax_indices and related tensor indexing is intentional and should not be changed to int64. The torch.IntTensor type hint is correct for the sample() function's softmax_indices parameter.
📚 Learning: 2025-08-26T09:37:10.463Z
Learnt from: jiaganc
Repo: NVIDIA/TensorRT-LLM PR: 7031
File: tensorrt_llm/bench/dataclasses/configuration.py:90-104
Timestamp: 2025-08-26T09:37:10.463Z
Learning: In TensorRT-LLM, the `get_pytorch_perf_config()` method returns `self.pytorch_config` which can contain default `cuda_graph_config` values, so `llm_args` may already have this config before the extra options processing.
Applied to files:
tensorrt_llm/_torch/pyexecutor/py_executor_creator.pytensorrt_llm/llmapi/llm_args.py
📚 Learning: 2025-08-14T15:38:01.771Z
Learnt from: MatthiasKohl
Repo: NVIDIA/TensorRT-LLM PR: 6904
File: cpp/tensorrt_llm/pybind/thop/bindings.cpp:55-57
Timestamp: 2025-08-14T15:38:01.771Z
Learning: In TensorRT-LLM Python bindings, tensor parameter collections like mla_tensor_params and spec_decoding_tensor_params are kept as required parameters without defaults to maintain API consistency, even when it might affect backward compatibility.
Applied to files:
tensorrt_llm/llmapi/llm_args.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.pytensorrt_llm/_torch/pyexecutor/_util.py
📚 Learning: 2025-08-27T15:03:57.149Z
Learnt from: ixlmar
Repo: NVIDIA/TensorRT-LLM PR: 7294
File: tensorrt_llm/_torch/pyexecutor/sampler.py:368-392
Timestamp: 2025-08-27T15:03:57.149Z
Learning: In TensorRT-LLM's sampler.py, int32 usage for softmax_indices and related tensor indexing is intentional and should not be changed to int64. The torch.IntTensor type hint is correct for the sample() function's softmax_indices parameter.
Applied to files:
tensorrt_llm/_torch/pyexecutor/sampler.pytensorrt_llm/_torch/pyexecutor/sampling_utils.pytensorrt_llm/_torch/pyexecutor/_util.py
📚 Learning: 2025-08-28T10:25:22.370Z
Learnt from: ixlmar
Repo: NVIDIA/TensorRT-LLM PR: 7294
File: tensorrt_llm/_torch/pyexecutor/sampler.py:887-891
Timestamp: 2025-08-28T10:25:22.370Z
Learning: In tensorrt_llm/_torch/pyexecutor/sampler.py, the draft_probs and target_probs tensors have shapes [1, steps] not [steps, vocab_size] as might be expected, making the .squeeze(0) operations appropriate for removing the batch dimension of size 1.
Applied to files:
tests/unittest/_torch/sampler/test_torch_sampler.py
🧬 Code graph analysis (6)
tensorrt_llm/_torch/pyexecutor/py_executor_creator.py (2)
tensorrt_llm/_torch/pyexecutor/_util.py (1)
instantiate_sampler(844-895)tensorrt_llm/_torch/attention_backend/trtllm.py (2)
max_seq_len(612-622)max_seq_len(625-629)
tensorrt_llm/_torch/pyexecutor/sampling_utils_flashinfer.py (1)
tensorrt_llm/_torch/pyexecutor/sampling_utils.py (7)
GroupedStrategySampler(295-312)greedy_search_sampling_batch(197-206)sample(251-289)strategy_grouping_key(298-299)strategy_grouping_key(320-321)sample_grouped_strategies(303-312)sample_grouped_strategies(325-346)
tensorrt_llm/_torch/pyexecutor/sampler.py (4)
tensorrt_llm/_torch/pyexecutor/llm_request.py (2)
LlmRequest(423-643)get_draft_token_length(788-799)tensorrt_llm/_torch/pyexecutor/resource_manager.py (3)
ResourceManager(1291-1334)ResourceManagerType(56-61)get_resource_manager(1303-1304)tensorrt_llm/_torch/pyexecutor/sampling_utils.py (6)
GroupedStrategySampler(295-312)SimpleGroupedStrategySampler(315-346)strategy_grouping_key(298-299)strategy_grouping_key(320-321)sample_grouped_strategies(303-312)sample_grouped_strategies(325-346)tensorrt_llm/_torch/pyexecutor/sampling_utils_flashinfer.py (3)
FlashInferGroupedStrategySampler(515-576)strategy_grouping_key(526-551)sample_grouped_strategies(555-576)
tensorrt_llm/_torch/pyexecutor/sampling_utils.py (1)
tensorrt_llm/_torch/pyexecutor/sampling_utils_flashinfer.py (1)
strategy_grouping_key(526-551)
tests/unittest/_torch/sampler/test_torch_sampler.py (5)
tensorrt_llm/_torch/pyexecutor/llm_request.py (2)
LlmRequest(423-643)get_draft_token_length(788-799)tensorrt_llm/_torch/pyexecutor/scheduler.py (1)
ScheduledRequests(20-41)tensorrt_llm/_torch/pyexecutor/sampling_utils.py (4)
SimpleGroupedStrategySampler(315-346)UtilsSamplingParams(46-51)sample_grouped_strategies(303-312)sample_grouped_strategies(325-346)tensorrt_llm/_torch/pyexecutor/sampler.py (11)
_BatchedSamplingResult(313-317)_request_get_sampling_params(252-262)_request_strategy(265-267)Args(607-613)sample_async(115-122)sample_async(154-162)sample_async(204-213)sample_async(1111-1158)sample_async(2031-2115)get_generator(660-674)_unbatch_sampling_results(1370-1412)tensorrt_llm/_torch/pyexecutor/sampling_utils_flashinfer.py (4)
FlashInferGroupedStrategySampler(515-576)sample_grouped_strategies(555-576)_StrategyImpls(46-512)StrategyImpl(47-169)
tensorrt_llm/_torch/pyexecutor/_util.py (1)
tensorrt_llm/llmapi/llm_args.py (1)
TorchLlmArgs(2404-2838)
🪛 Ruff (0.14.3)
tests/unittest/_torch/sampler/test_torch_sampler.py
912-912: Unpacked variable num_seq_slots is never used
Prefix it with an underscore or any other dummy variable pattern
(RUF059)
962-964: zip() without an explicit strict= parameter
Add explicit value for parameter strict=
(B905)
1139-1139: Unused method argument: allow_zero_draft_len
(ARG002)
1161-1161: zip() without an explicit strict= parameter
Add explicit value for parameter strict=
(B905)
1200-1200: Avoid specifying long messages outside the exception class
(TRY003)
1352-1352: Unused method argument: allow_zero_draft_len
(ARG002)
1672-1676: zip() without an explicit strict= parameter
Add explicit value for parameter strict=
(B905)
1903-1903: Unused method argument: vocab_size
(ARG002)
1906-1906: Unused method argument: use_flashinfer
(ARG002)
🔇 Additional comments (3)
tensorrt_llm/_torch/pyexecutor/sampler.py (1)
648-655: FlashInfer fallback toggle looks solid.Conditional selection between
FlashInferGroupedStrategySamplerandSimpleGroupedStrategySamplerkeeps the legacy path available when FlashInfer is absent or explicitly disabled.tensorrt_llm/_torch/pyexecutor/sampling_utils.py (1)
36-43: Strategy aliases improve clarity.Exposing the concrete strategy tuples via
TypeAliassharpens the type surface and makes downstream pattern matches easier to follow.tensorrt_llm/_torch/pyexecutor/sampling_utils_flashinfer.py (1)
70-118: Async NaN guard is a nice touch.Leveraging
torch._assert_asyncbefore invoking FlashInfer kernels is a good defensive move against the known NaN crash path while keeping the hot loop unsynchronized.
Signed-off-by: ixlmar <[email protected]>
Co-authored-by: Robin Kobus <[email protected]> Signed-off-by: mpikulski <[email protected]>
Signed-off-by: ixlmar <[email protected]>
Signed-off-by: ixlmar <[email protected]>
0ee5be3 to
2eb40a7
Compare
|
/bot run |
|
PR_Github #24179 [ run ] triggered by Bot. Commit: |
Funatiq
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.
I would appreciate more documentation what the methods are actually testing. Cursor seems to do a pretty good job at explaining that but it would be great to verify its output and add it as docstrings.
Signed-off-by: ixlmar <[email protected]>
|
PR_Github #24179 [ run ] completed with state |
|
/bot skip --comment "non-code changes only" |
|
PR_Github #24195 [ skip ] triggered by Bot. Commit: |
|
PR_Github #24195 [ skip ] completed with state |
Description
This PR provides extended test coverage for the code introduced by #7294, #8398, and #8581, as well as for some pre-existing code. With these changes,
test_torch_sampler.pyruns 436 test cases in slightly less than 4' total.Test Coverage
Provided by this PR.
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.
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.
Summary by CodeRabbit
New Features
Tests
Refactor