-
Notifications
You must be signed in to change notification settings - Fork 1.8k
[TRTLLM-8832][feat] fully async _select_generated_logits with tests #8628
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?
Conversation
|
/bot run |
|
/bot kill |
52df526 to
08dc6a9
Compare
|
/bot run |
📝 WalkthroughWalkthroughAdded a new num_logits_to_keep parameter to logits selection and propagated it through request processing; enhanced torch_multi_arange with an optional output_length and stricter device/validation logic; replaced scalar tensor updates with in-place copy_; added CUDA test utilities and multiple unit tests for the new behaviors. Changes
Sequence Diagram(s)sequenceDiagram
autonumber
participant Caller
participant _process_requests
participant _select_generated_logits
participant torch_multi_arange
Caller->>_process_requests: submit scheduled requests
_process_requests->>_process_requests: compute sum_steps (total gen steps)
_process_requests->>_select_generated_logits: call(..., num_logits_to_keep=sum_steps)
_select_generated_logits->>torch_multi_arange: call(ends/starts/steps, output_length=num_logits_to_keep)
torch_multi_arange->>torch_multi_arange: validate devices & output_length
torch_multi_arange->>torch_multi_arange: compute constrained multi-range indices
torch_multi_arange-->>_select_generated_logits: return indices (length ≤ output_length)
_select_generated_logits->>_select_generated_logits: index raw_logits with returned indices
_select_generated_logits-->>_process_requests: return selected logits tensor
_process_requests-->>Caller: deliver results
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~30 minutes 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: 3
🧹 Nitpick comments (8)
tests/unittest/_torch/sampler/test_torch_multi_arange.py (3)
112-119: Avoid 4GB allocator warmup; use a small priming buffer.Replace the 4GB allocation with a small pinned/byte buffer to prime the allocator without risking OOM.
- buf = torch.ones((2**30, ), device=device) + # Prime allocator without large footprint (≈16MB) + buf = torch.empty((16 * 1024 * 1024,), device=device, dtype=torch.uint8) del buf
125-131: Shorten the no-sync window to speed up CI.Use a small timeout to cut test time while still catching syncs.
- with torch.cuda.Stream(): - with assert_no_cuda_sync(): + with torch.cuda.Stream(): + with assert_no_cuda_sync(sync_timeout_s=0.2): result = torch_multi_arange(ends_tensor, starts=starts_tensor, steps=steps_tensor, **extra_args)
81-87: Minor: prefer star-expansion over concatenation.Applies Ruff RUF005.
- BASE_CASES + [_build_multi_arange_case()], + [*BASE_CASES, _build_multi_arange_case()],tests/unittest/_torch/sampler/test_torch_sampler.py (1)
474-479: Reduce allocator warmup footprint.4GB warmup is unnecessary and risky; use a small buffer.
- buf = torch.ones((2**30,), device=device) + buf = torch.empty((16 * 1024 * 1024,), device=device, dtype=torch.uint8) del buftests/unittest/utils/util.py (3)
474-484: Consider adding a docstring for clarity.The implementation of
DeviceSleepCtlis correct and follows Python naming conventions. The cancellation flag pattern is appropriate for the use case. Consider adding a class docstring to document its purpose.Apply this diff to add a docstring:
@dataclass class DeviceSleepCtl: + """Control object for cancelling a device_sleep operation.""" _cancellation_requested: bool = False
486-496: Add a docstring to document the function's purpose and parameters.The function implementation is correct, but it lacks a docstring. As per coding guidelines, public functions should have Google-style docstrings.
Apply this diff to add a docstring:
@hostfunc def device_sleep(duration_s: float, *, ctl: DeviceSleepCtl, spin_s: float = 0.1): + """Sleep on the device for a specified duration with cancellation support. + + Args: + duration_s: Total duration to sleep in seconds. + ctl: Control object for cancellation. + spin_s: Interval between cancellation checks in seconds (default: 0.1). + """ spin_iters = math.ceil(duration_s / spin_s)
498-515: Enhance the docstring and assertion message for better clarity.The context manager implementation is correct and the pattern is sound. However, the docstring and assertion message could be more descriptive to help users understand the verification mechanism.
Apply this diff to improve documentation:
@contextmanager def assert_no_cuda_sync( sync_timeout_s: float = 5) -> Generator[None, None, None]: - """Check that the function does not stream synchronize.""" + """Check that the code block does not synchronize the current CUDA stream. + + This context manager launches a long-running sleep operation on the CUDA stream + and verifies that the code block returns before the sleep completes, confirming + that no stream synchronization occurred. + + Args: + sync_timeout_s: Duration of the sleep operation in seconds (default: 5). + + Raises: + AssertionError: If the code block synchronizes the CUDA stream. + """ sleep_finished_event = torch.cuda.Event() torch.cuda.synchronize() sleep_ctl = DeviceSleepCtl() device_sleep(sync_timeout_s, ctl=sleep_ctl) sleep_finished_event.record() yield None assert not sleep_finished_event.query( - ), """sync code should return quickly""" + ), "Code under test synchronized the CUDA stream unexpectedly" sleep_ctl.cancel() sleep_finished_event.synchronize()tensorrt_llm/_torch/pyexecutor/sampling_utils.py (1)
401-401: Consider creating the source tensor on the device or with pinning.The use of
copy_()withnon_blocking=Trueis correct for async operation. However, for non-blocking copies to be effective when copying from CPU to device, the source tensor should ideally be pinned. Consider this approach for consistency with lines 403-406:Apply this diff to ensure proper pinning:
- prev_range_ends[0].copy_(torch.tensor(0, dtype=ends.dtype), non_blocking=True) + prev_range_ends[0].copy_( + torch.tensor(0, dtype=ends.dtype, pin_memory=True), non_blocking=True + )Alternatively, if
endsis already on device, you could create the zero tensor directly on the device:- prev_range_ends[0].copy_(torch.tensor(0, dtype=ends.dtype), non_blocking=True) + zero_scalar = torch.zeros((), dtype=ends.dtype, device=ends.device) + prev_range_ends[0].copy_(zero_scalar, non_blocking=True)
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (7)
tensorrt_llm/_torch/pyexecutor/sampler.py(4 hunks)tensorrt_llm/_torch/pyexecutor/sampling_utils.py(2 hunks)tests/integration/test_lists/test-db/l0_a10.yml(1 hunks)tests/unittest/_torch/sampler/test_torch_multi_arange.py(1 hunks)tests/unittest/_torch/sampler/test_torch_sampler.py(2 hunks)tests/unittest/utils/test_util.py(1 hunks)tests/unittest/utils/util.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:
tests/unittest/_torch/sampler/test_torch_multi_arange.pytensorrt_llm/_torch/pyexecutor/sampler.pytests/unittest/utils/util.pytests/unittest/utils/test_util.pytensorrt_llm/_torch/pyexecutor/sampling_utils.pytests/unittest/_torch/sampler/test_torch_sampler.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:
tests/unittest/_torch/sampler/test_torch_multi_arange.pytensorrt_llm/_torch/pyexecutor/sampler.pytests/unittest/utils/util.pytests/unittest/utils/test_util.pytensorrt_llm/_torch/pyexecutor/sampling_utils.pytests/unittest/_torch/sampler/test_torch_sampler.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:
tests/unittest/_torch/sampler/test_torch_multi_arange.pytensorrt_llm/_torch/pyexecutor/sampler.pytests/unittest/utils/util.pytests/unittest/utils/test_util.pytensorrt_llm/_torch/pyexecutor/sampling_utils.pytests/unittest/_torch/sampler/test_torch_sampler.py
🧬 Code graph analysis (5)
tests/unittest/_torch/sampler/test_torch_multi_arange.py (2)
tests/unittest/utils/util.py (1)
assert_no_cuda_sync(499-515)tensorrt_llm/_torch/pyexecutor/sampling_utils.py (1)
torch_multi_arange(348-432)
tests/unittest/utils/util.py (1)
tensorrt_llm/_torch/hostfunc.py (1)
hostfunc(22-27)
tests/unittest/utils/test_util.py (1)
tests/unittest/utils/util.py (4)
DeviceSleepCtl(475-483)assert_no_cuda_sync(499-515)device_sleep(487-495)cancel(482-483)
tensorrt_llm/_torch/pyexecutor/sampling_utils.py (1)
tensorrt_llm/functional.py (2)
cumsum(2411-2536)repeat_interleave(6312-6336)
tests/unittest/_torch/sampler/test_torch_sampler.py (2)
tests/unittest/utils/util.py (1)
assert_no_cuda_sync(499-515)tensorrt_llm/_torch/pyexecutor/scheduler.py (1)
ScheduledRequests(20-41)
🪛 Ruff (0.14.1)
tests/unittest/_torch/sampler/test_torch_multi_arange.py
81-81: Consider [*BASE_CASES, _build_multi_arange_case()] instead of concatenation
Replace with [*BASE_CASES, _build_multi_arange_case()]
(RUF005)
tensorrt_llm/_torch/pyexecutor/sampling_utils.py
371-371: Avoid specifying long messages outside the exception class
(TRY003)
⏰ 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 (7)
tests/integration/test_lists/test-db/l0_a10.yml (1)
18-19: New tests wired into A10 PyTorch list — looks good.Please keep an eye on runtime on A10; if tests grow, consider splitting CUDA-only checks into a separate list.
tensorrt_llm/_torch/pyexecutor/sampler.py (1)
1420-1424: Good: bounded output length avoids dynamic-shape syncs.Passing output_length to torch_multi_arange enforces fixed output size on device.
tests/unittest/utils/util.py (1)
1-39: LGTM: Copyright header and imports are correct.The Apache-2.0 copyright header with the current year (2025) is properly placed, and the new imports (
math,time,dataclass,hostfunc) are relevant to the added functionality.tensorrt_llm/_torch/pyexecutor/sampling_utils.py (4)
348-374: LGTM: Function signature and validation are well-designed.The addition of the
output_lengthparameter with appropriate validation ensures async-safe operation with device tensors. The device consistency checks and early return for empty tensors are correct defensive programming.Note: Ruff suggests defining long exception messages as class attributes, but the inline message is clear and acceptable for this use case.
391-394: LGTM: Repeat calculation correctly handles negative steps and invalid ranges.The sign-aware repeat calculation and clipping to zero properly handle negative steps and invalid ranges without introducing synchronization points.
407-411: LGTM: Zeros tensor creation follows the correct async pattern.The zeros tensor is created with pinning and non-blocking transfer to the device, matching the pattern used for the ones tensor. This ensures async-safe operation.
418-431: LGTM: Empty range handling and async-safe repeat_interleave are correctly implemented.The jump corrections properly handle empty ranges, and the use of
output_size=output_lengthinrepeat_interleaveis crucial for avoiding synchronization with device tensors. The explicit dtype incumsumensures type consistency throughout the computation.
|
/bot run |
|
PR_Github #22301 [ run ] triggered by Bot. Commit: |
|
PR_Github #22301 [ run ] completed with state |
3f024fe to
d8bfe04
Compare
|
/bot run --stage-list="A10-PyTorch-1" |
|
PR_Github #22396 [ run ] triggered by Bot. Commit: |
|
PR_Github #22396 [ run ] completed with state |
|
/bot run |
|
PR_Github #22424 [ run ] triggered by Bot. Commit: |
Signed-off-by: ixlmar <[email protected]>
d8bfe04 to
e0c3860
Compare
|
/bot run |
|
PR_Github #22445 [ run ] triggered by Bot. Commit: |
|
PR_Github #22424 [ run ] completed with state |
|
PR_Github #22445 [ run ] completed with state |
Description
test_assert_no_cuda_sync, incl. unit teststorch_multi_arangeTorchSampler._select_generated_logitstorch_multi_arangefully asyncTorchSampler._select_generated_logitsfully asyncTest Coverage
Tests included with 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
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
Refactor
Tests