Skip to content

[None][feat] Add support of scheduling attention dp request #6246

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

Merged
merged 10 commits into from
Aug 2, 2025

Conversation

Shunkangz
Copy link
Collaborator

@Shunkangz Shunkangz commented Jul 22, 2025

Summary by CodeRabbit

  • New Features

    • Added support for advanced scheduling parameters to improve request handling and load balancing in attention data parallelism mode.
    • Introduced a new scheduling_params option for generation methods, allowing finer control over request scheduling.
    • Enhanced API to accept and propagate scheduling parameters for both synchronous and asynchronous generation.
  • Bug Fixes

    • Improved request queue handling to prevent overloading specific ranks and ensure capacity-aware scheduling.
  • Tests

    • Added comprehensive tests covering attention data parallel scheduling scenarios, including rank-aware distribution and capacity constraints.
  • Documentation

    • Updated API references to document the new scheduling_params parameter in generation methods.

Description

In this PR, I add the feature of scheduling attention dp requests. In this implementation, we have three choice.

  1. Do not specify the attention dp rank.
  2. Specify the attention dp rank.
  3. Specify the attention dp rank with relax.

The workflow is as follows: each rank selects the requests routed to it. It then attempts to retrieve requests until it reaches the max_num_active_requests constraint. If a request has the attention_dp_relax flag enabled, the scheduler will try to assign it to other ranks to improve overall throughput. In contrast, requests without the relax flag will be placed back at the front of the waiting queue to await the next round of scheduling.

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 the stage-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.

Copy link
Contributor

coderabbitai bot commented Jul 22, 2025

📝 Walkthrough

Walkthrough

This change introduces a new SchedulingParams dataclass and adds support for attention data parallelism (DP) scheduling throughout the request handling and generation pipeline. The request queue logic is extended to conditionally filter, schedule, and balance requests based on per-rank capacity and scheduling parameters. The LLM API, executor, and worker classes are updated to accept and propagate the new scheduling_params parameter. Unit tests are added to cover the new scheduling logic.

Changes

Cohort / File(s) Change Summary
Attention DP Scheduling Logic
tensorrt_llm/_torch/pyexecutor/executor_request_queue.py
Adds conditional request filtering and scheduling for attention DP, new helper methods, signature updates, and balancing logic for rank-aware request processing.
SchedulingParams Dataclass
tensorrt_llm/scheduling_params.py
Introduces SchedulingParams dataclass with optional attention_dp_rank and attention_dp_relax attributes.
Executor Request Propagation
tensorrt_llm/executor/executor.py, tensorrt_llm/executor/request.py, tensorrt_llm/llmapi/llm.py
Updates method signatures and constructors to accept and propagate scheduling_params through the API, executor, and request objects.
Worker Scheduling Attribute
tensorrt_llm/executor/worker.py
Attaches py_scheduling_params to executor requests for PyTorch backend if provided.
API Reference Update
tests/unittest/api_stability/references/llm.yaml
Documents the new scheduling_params parameter in the API reference for generate and generate_async.
Unit Tests for Attention DP Scheduling
tests/unittest/_torch/test_executor_request_queue.py
Replaces thread safety test with comprehensive tests for attention DP scheduling, filtering, and balancing logic, including new fixtures and parameterized scenarios.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant LLM_API
    participant Executor
    participant Worker
    participant RequestQueue

    User->>LLM_API: generate/generate_async(..., scheduling_params)
    LLM_API->>Executor: generate_async(..., scheduling_params)
    Executor->>RequestQueue: enqueue request (with scheduling_params)
    Worker->>RequestQueue: _enqueue_request (attach py_scheduling_params)
    RequestQueue->>RequestQueue: _get_from_waiting_queue (filter/schedule based on attention DP)
    RequestQueue->>RequestQueue: _schedule_attention_dp_requests (balance requests across ranks)
    RequestQueue-->>Worker: scheduled requests for current rank
    Worker-->>Executor: process scheduled requests
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Suggested labels

Community want to contribute, Documentation

Suggested reviewers

  • pcastonguay
  • Superjomn
  • HuiGao-NV
  • qiaoxj07

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai or @coderabbitai title anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a 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/schedule_params.py (1)

10-11: Fix line length to comply with coding standards.

The docstring line exceeds the 120-character limit. Consider reformatting for better readability.

-        attention_dp_rank (int): The rank of target attention dp
-        attention_dp_relax (bool): Whether to allow the request to be scheduled to other attention dp for better throughput
+        attention_dp_rank (int): The rank of target attention dp
+        attention_dp_relax (bool): Whether to allow the request to be scheduled to other attention dp 
+            for better throughput
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between fddb7f1 and ac0d750.

📒 Files selected for processing (6)
  • tensorrt_llm/_torch/pyexecutor/executor_request_queue.py (1 hunks)
  • tensorrt_llm/executor/executor.py (3 hunks)
  • tensorrt_llm/executor/request.py (3 hunks)
  • tensorrt_llm/executor/worker.py (1 hunks)
  • tensorrt_llm/llmapi/llm.py (5 hunks)
  • tensorrt_llm/schedule_params.py (1 hunks)
🧠 Learnings (1)
tensorrt_llm/executor/worker.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/schedule_params.py

11-11: Line too long (123 > 120)

(E501)

🧰 Additional context used
🧠 Learnings (1)
tensorrt_llm/executor/worker.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/schedule_params.py

11-11: Line too long (123 > 120)

(E501)

🔇 Additional comments (12)
tensorrt_llm/executor/request.py (1)

13-13: Clean integration of ScheduleParams parameter.

The addition of ScheduleParams import and integration into the GenerationRequest constructor follows the established pattern for other optional parameters. The parameter is properly typed and stored as an instance attribute.

Also applies to: 90-90, 115-115

tensorrt_llm/executor/worker.py (1)

511-513: Proper conditional attachment of schedule parameters.

The implementation correctly follows the existing pattern for PyTorch backend-specific parameters (like py_multimodal_data and py_logits_post_processors). The conditional checks ensure that schedule parameters are only attached when using the PyTorch backend and when they are actually provided.

tensorrt_llm/schedule_params.py (1)

5-15: Well-designed dataclass with optimization features.

The implementation uses slots=True for memory efficiency and kw_only=True to enforce keyword-only arguments, which is excellent for API clarity. The optional typing and clear docstring make the parameters self-documenting.

tensorrt_llm/llmapi/llm.py (3)

33-33: Proper import of ScheduleParams.

The import is correctly placed with other parameter-related imports.


239-240: Consistent parameter handling in synchronous generate method.

The schedule_params parameter is properly integrated into the method signature and correctly handled in the batching logic using the _item_at helper function, following the established pattern for other optional parameters.

Also applies to: 288-288


314-314: Clean integration in asynchronous generate method.

The parameter is properly typed and forwarded through the call chain to the executor's generate_async method, maintaining the parameter propagation pattern throughout the system.

Also applies to: 425-425

tensorrt_llm/executor/executor.py (3)

32-32: LGTM: Clean import addition

The import of ScheduleParams is properly placed with other related imports.


124-124: LGTM: Consistent parameter addition

The schedule_params parameter follows the established pattern of other optional parameters in the method signature.


147-148: LGTM: Proper parameter propagation

The schedule_params is correctly passed to the GenerationRequest constructor, maintaining the parameter flow through the system.

tensorrt_llm/_torch/pyexecutor/executor_request_queue.py (3)

247-249: LGTM: Clean method call delegation

The replacement of direct balancing logic with a dedicated scheduling method improves code organization and readability.


257-257: LGTM: Consistent counter update

The counter update properly tracks the total number of new requests processed.


264-344: Ignore the logic-error suggestion for attention_dp_rank

The comparison

req_item.request.schedule_params.attention_dp_rank == self.dist.tp_rank

is intentional—“dp” here refers to the dimension-parallel (attention) split, which is driven by the tensor-parallel rank (tp_rank). There is no separate dp_rank in the dist context, so the existing check is correct.

Likely an incorrect or invalid review comment.

@Shunkangz Shunkangz self-assigned this Jul 22, 2025
@Shunkangz Shunkangz force-pushed the attention_dp_rank_route branch from ac0d750 to fb1dd7f Compare July 22, 2025 05:03
Copy link
Contributor

@coderabbitai coderabbitai bot left a 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

🧹 Nitpick comments (2)
tensorrt_llm/_torch/pyexecutor/executor_request_queue.py (2)

312-317: Optimize communication overhead.

The padding approach for allgather creates unnecessary communication overhead as noted in the TODO. Consider using variable-length communication or a more efficient serialization approach.

Would you like me to suggest an alternative implementation that reduces communication overhead?


327-330: Simplify the condition logic.

The nested condition can be simplified for better readability.

-            elif req_item.request.schedule_params is None or \
-                req_item.request.schedule_params is not None and \
-                req_item.request.schedule_params.attention_dp_rank is None:
+            elif (req_item.request.schedule_params is None or 
+                  req_item.request.schedule_params.attention_dp_rank is None):
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ac0d750 and fb1dd7f.

📒 Files selected for processing (1)
  • tensorrt_llm/_torch/pyexecutor/executor_request_queue.py (4 hunks)
⏰ 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 (3)
tensorrt_llm/_torch/pyexecutor/executor_request_queue.py (3)

247-249: LGTM! Clean refactoring of scheduling logic.

The extraction of scheduling logic into a dedicated _schedule_attention_dp_requests method improves code organization and readability. The method call and parameter passing are correct.

Also applies to: 257-257


406-406: LGTM! Clean integration of pre-scheduled requests.

The method signature update to accept new_requests_cur_rank and the subsequent merging logic correctly integrate pre-scheduled requests with the load balancing algorithm. The variable renaming to new_scheduled_requests improves code clarity.

Also applies to: 410-410, 424-424, 457-457, 462-462, 464-465


274-275: DP rank comparison is correct
The ExecutorRequestQueue uses the tensor-parallel group as the attention-DP group—there is no dist.dp_rank. Comparing schedule_params.attention_dp_rank against self.dist.tp_rank and coordinating via tp_allgather is the intended behavior.

Likely an incorrect or invalid review comment.

@Shunkangz Shunkangz marked this pull request as ready for review July 22, 2025 07:56
@Shunkangz Shunkangz requested review from a team as code owners July 22, 2025 07:56
@Shunkangz Shunkangz requested a review from syuoni July 22, 2025 07:56
Copy link
Contributor

@coderabbitai coderabbitai bot left a 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: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between fb1dd7f and 8b7483b.

📒 Files selected for processing (1)
  • tests/unittest/_torch/test_executor_request_queue.py (1 hunks)
🪛 Ruff (0.12.2)
tests/unittest/_torch/test_executor_request_queue.py

835-835: Local variable req_id is assigned to but never used

Remove assignment to unused variable req_id

(F841)

🧰 Additional context used
🪛 Ruff (0.12.2)
tests/unittest/_torch/test_executor_request_queue.py

835-835: Local variable req_id is assigned to but never used

Remove assignment to unused variable req_id

(F841)

⏰ 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

@Shunkangz
Copy link
Collaborator Author

/bot run --disable-fail-fast

@tensorrt-cicd
Copy link
Collaborator

PR_Github #12549 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #12549 [ run ] completed with state SUCCESS
/LLM/main/L0_MergeRequest_PR pipeline #9331 completed with status: 'FAILURE'

@Shunkangz Shunkangz force-pushed the attention_dp_rank_route branch from 8b7483b to 537de6d Compare July 23, 2025 03:06
@Shunkangz Shunkangz requested a review from a team as a code owner July 23, 2025 03:06
@Shunkangz
Copy link
Collaborator Author

/bot run --disable-fail-fast

Copy link
Contributor

@coderabbitai coderabbitai bot left a 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 (2)
tensorrt_llm/_torch/pyexecutor/executor_request_queue.py (1)

305-305: Fix potential request order reversal.

Using extendleft will reverse the order of waiting requests. If maintaining FIFO order is important, consider using extend and reversing the list first, or use a different approach.

-        self.waiting_queue.extendleft(new_requests_cur_rank_waiting)
+        # Maintain FIFO order by extending from the right
+        self.waiting_queue.extend(reversed(new_requests_cur_rank_waiting))
tests/unittest/_torch/test_executor_request_queue.py (1)

835-835: Remove unused variable assignment.

The variable req_id is assigned but never used in this test.

-    req_id = schedule_queue.enqueue_request(mock_request)
+    schedule_queue.enqueue_request(mock_request)
🧹 Nitpick comments (2)
tensorrt_llm/schedule_params.py (1)

11-11: Fix line length to comply with style guide.

Line exceeds the 120 character limit.

-        attention_dp_relax (bool): Whether to allow the request to be scheduled to other attention dp for better throughput
+        attention_dp_relax (bool): Whether to allow the request to be scheduled to other attention dp for better
+            throughput
tensorrt_llm/_torch/pyexecutor/executor_request_queue.py (1)

327-330: Simplify complex conditional logic.

The nested conditions for identifying non-scheduled requests can be simplified for better readability.

-            elif req_item.request.py_schedule_params is None or \
-                req_item.request.py_schedule_params is not None and \
-                req_item.request.py_schedule_params.attention_dp_rank is None:
+            elif (req_item.request.py_schedule_params is None or 
+                  req_item.request.py_schedule_params.attention_dp_rank is None):
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8b7483b and 537de6d.

📒 Files selected for processing (8)
  • tensorrt_llm/_torch/pyexecutor/executor_request_queue.py (4 hunks)
  • tensorrt_llm/executor/executor.py (3 hunks)
  • tensorrt_llm/executor/request.py (3 hunks)
  • tensorrt_llm/executor/worker.py (1 hunks)
  • tensorrt_llm/llmapi/llm.py (5 hunks)
  • tensorrt_llm/schedule_params.py (1 hunks)
  • tests/unittest/_torch/test_executor_request_queue.py (1 hunks)
  • tests/unittest/api_stability/references/llm.yaml (1 hunks)
🧠 Learnings (1)
tensorrt_llm/_torch/pyexecutor/executor_request_queue.py (1)

Learnt from: yiqingy0
PR: #5198
File: jenkins/mergeWaiveList.py:0-0
Timestamp: 2025-07-22T08:33:49.076Z
Learning: In the TensorRT-LLM waive list merging system, removed lines are always located at the end of the merge waive lists, which is why the mergeWaiveList.py script uses reverse traversal - it's an optimization for this specific domain constraint.

🧬 Code Graph Analysis (1)
tensorrt_llm/_torch/pyexecutor/executor_request_queue.py (1)
tensorrt_llm/_torch/distributed/communicator.py (2)
  • tp_allgather (138-139)
  • tp_size (46-47)
🪛 Ruff (0.12.2)
tests/unittest/_torch/test_executor_request_queue.py

835-835: Local variable req_id is assigned to but never used

Remove assignment to unused variable req_id

(F841)

tensorrt_llm/schedule_params.py

11-11: Line too long (123 > 120)

(E501)

🚧 Files skipped from review as they are similar to previous changes (4)
  • tensorrt_llm/executor/request.py
  • tensorrt_llm/executor/worker.py
  • tensorrt_llm/executor/executor.py
  • tensorrt_llm/llmapi/llm.py
🧰 Additional context used
🧠 Learnings (1)
tensorrt_llm/_torch/pyexecutor/executor_request_queue.py (1)

Learnt from: yiqingy0
PR: #5198
File: jenkins/mergeWaiveList.py:0-0
Timestamp: 2025-07-22T08:33:49.076Z
Learning: In the TensorRT-LLM waive list merging system, removed lines are always located at the end of the merge waive lists, which is why the mergeWaiveList.py script uses reverse traversal - it's an optimization for this specific domain constraint.

🧬 Code Graph Analysis (1)
tensorrt_llm/_torch/pyexecutor/executor_request_queue.py (1)
tensorrt_llm/_torch/distributed/communicator.py (2)
  • tp_allgather (138-139)
  • tp_size (46-47)
🪛 Ruff (0.12.2)
tests/unittest/_torch/test_executor_request_queue.py

835-835: Local variable req_id is assigned to but never used

Remove assignment to unused variable req_id

(F841)

tensorrt_llm/schedule_params.py

11-11: Line too long (123 > 120)

(E501)

🔇 Additional comments (3)
tests/unittest/api_stability/references/llm.yaml (1)

138-140: LGTM!

The addition of the optional schedule_params parameter to generate_async maintains backward compatibility while enabling the new scheduling functionality.

tensorrt_llm/_torch/pyexecutor/executor_request_queue.py (1)

274-276: Ignore incorrect renaming suggestion: .py_schedule_params is intentional
The py_schedule_params attribute is explicitly set on the executor request in tensorrt_llm/executor/worker.py:

if self._is_pytorch_backend and request.schedule_params is not None:
    executor_request.py_schedule_params = request.schedule_params

All usages of req_item.request.py_schedule_params in tensorrt_llm/_torch/pyexecutor/executor_request_queue.py are therefore correct and should remain unchanged.

Likely an incorrect or invalid review comment.

tests/unittest/_torch/test_executor_request_queue.py (1)

459-857: Excellent test coverage!

The comprehensive test suite effectively covers all major scheduling scenarios including rank filtering, capacity limits, relax flag prioritization, edge cases, and integration with the LLM API. The use of mocked distributed operations and helper functions makes the tests clear and maintainable.

@tensorrt-cicd
Copy link
Collaborator

PR_Github #12641 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #12641 [ run ] completed with state SUCCESS
/LLM/main/L0_MergeRequest_PR pipeline #9397 completed with status: 'FAILURE'

Copy link
Contributor

@coderabbitai coderabbitai bot left a 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

♻️ Duplicate comments (1)
tensorrt_llm/_torch/pyexecutor/executor_request_queue.py (1)

301-301: Fix potential request order reversal.

Using extendleft will reverse the order of pending requests, potentially breaking FIFO ordering when these requests are processed in the next scheduling round.

-        self.waiting_queue.extendleft(pending_requests)
+        # Maintain FIFO order by extending from the right
+        self.waiting_queue.extend(reversed(pending_requests))
🧹 Nitpick comments (1)
tensorrt_llm/_torch/pyexecutor/executor_request_queue.py (1)

324-331: Optimize request removal for better performance.

Using remove() in a loop over a potentially large list is inefficient (O(n²) complexity). Consider using a more efficient approach.

-        # Try to put the unscheduled requests to the target dp rank until the max_num_active_requests is reached
-        for req_item in unscheduled_requests[:]:
-            if req_item.request.py_schedule_params is not None:
-                target_dp_rank = req_item.request.py_schedule_params.attention_dp_rank
-                if self.all_ranks_num_active_requests[
-                        target_dp_rank] < self.max_num_active_requests:
-                    self.all_ranks_num_active_requests[target_dp_rank] += 1
-                    # Ensure all ranks have the same unscheduled requests
-                    unscheduled_requests.remove(req_item)
-
-                    # If the target dp rank is the current rank, add it to the new_requests_cur_rank
-                    if target_dp_rank == self.dist.tp_rank:
-                        new_requests_cur_rank.append(req_item)
+        # Try to put the unscheduled requests to the target dp rank until the max_num_active_requests is reached
+        remaining_unscheduled = []
+        for req_item in unscheduled_requests:
+            if req_item.request.py_schedule_params is not None:
+                target_dp_rank = req_item.request.py_schedule_params.attention_dp_rank
+                if self.all_ranks_num_active_requests[
+                        target_dp_rank] < self.max_num_active_requests:
+                    self.all_ranks_num_active_requests[target_dp_rank] += 1
+
+                    # If the target dp rank is the current rank, add it to the new_requests_cur_rank
+                    if target_dp_rank == self.dist.tp_rank:
+                        new_requests_cur_rank.append(req_item)
+                else:
+                    remaining_unscheduled.append(req_item)
+            else:
+                remaining_unscheduled.append(req_item)
+        unscheduled_requests[:] = remaining_unscheduled
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 537de6d and 8b4a728.

📒 Files selected for processing (2)
  • tensorrt_llm/_torch/pyexecutor/executor_request_queue.py (5 hunks)
  • tensorrt_llm/executor/worker.py (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • tensorrt_llm/executor/worker.py
🧰 Additional context used
🧠 Learnings (1)
tensorrt_llm/_torch/pyexecutor/executor_request_queue.py (2)

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.

Learnt from: yiqingy0
PR: #5198
File: jenkins/mergeWaiveList.py:0-0
Timestamp: 2025-07-22T08:33:49.109Z
Learning: In the TensorRT-LLM waive list merging system, removed lines are always located at the end of the merge waive lists, which is why the mergeWaiveList.py script uses reverse traversal - it's an optimization for this specific domain constraint.

🪛 Ruff (0.12.2)
tensorrt_llm/_torch/pyexecutor/executor_request_queue.py

316-316: Line too long (133 > 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 (3)
tensorrt_llm/_torch/pyexecutor/executor_request_queue.py (3)

223-225: LGTM! Improved performance metrics accuracy.

Moving the performance metrics update to the specific fetch methods ensures metrics are calculated after all filtering and scheduling steps, providing more accurate measurements.


235-241: LGTM! Necessary refactoring for scheduling logic.

Converting to an instance variable allows the scheduling methods to access and modify active request counts across ranks. The allgather operation correctly synchronizes state across all ranks.


400-459: LGTM! Proper integration of pre-scheduled requests.

The method signature change correctly allows merging of pre-scheduled attention DP requests with load-balanced requests. The heap-based balancing logic is preserved and the final merge ensures all scheduled requests are returned together.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 6

♻️ Duplicate comments (3)
tensorrt_llm/_torch/pyexecutor/executor_request_queue.py (2)

303-303: Fix potential request order reversal.

Using extendleft will reverse the order of waiting requests. If maintaining FIFO order is important, consider using extend and reversing the list first, or use a different approach.

-        self.waiting_queue.extendleft(pending_requests)
+        # Maintain FIFO order by extending from the right
+        self.waiting_queue.extend(reversed(pending_requests))

315-319: Strengthen error handling for scheduling assertion.

The assertion provides good validation but could fail unexpectedly if there are bugs in the filtering logic. Consider adding more descriptive error handling.

-            assert self.all_ranks_num_active_requests[target_dp_rank] <= self.max_num_active_requests, \
-                f"The number of active requests on rank {target_dp_rank} is {self.all_ranks_num_active_requests[target_dp_rank]}, " \
-                f"which is greater than the max_num_active_requests {self.max_num_active_requests}"
+            if self.all_ranks_num_active_requests[target_dp_rank] > self.max_num_active_requests:
+                raise RuntimeError(
+                    f"Scheduling inconsistency: rank {target_dp_rank} has "
+                    f"{self.all_ranks_num_active_requests[target_dp_rank]} active requests, "
+                    f"exceeding limit of {self.max_num_active_requests}. "
+                    f"This indicates a bug in the filtering logic."
+                )
tests/unittest/_torch/test_executor_request_queue.py (1)

698-699: Remove unused variable assignment.

The variable result is assigned but never used in this test.

-        result = attention_dp_queue._schedule_attention_dp_requests(
-            scheduled_requests, unscheduled_requests)
+        attention_dp_queue._schedule_attention_dp_requests(
+            scheduled_requests, unscheduled_requests)
🧹 Nitpick comments (1)
tests/unittest/_torch/test_executor_request_queue.py (1)

726-728: Improve test documentation.

The comment doesn't accurately describe what's being tested. The test is checking that an assertion is raised when trying to schedule a request to a rank that's already over capacity.

-    # Should raise assertion error because we're trying to schedule a request when rank is at capacity
+    # Should raise assertion error because rank 0 already exceeds max capacity (9 > 8)
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8b4a728 and d01a546.

📒 Files selected for processing (2)
  • tensorrt_llm/_torch/pyexecutor/executor_request_queue.py (5 hunks)
  • tests/unittest/_torch/test_executor_request_queue.py (1 hunks)
🧰 Additional context used
🧠 Learnings (1)
tensorrt_llm/_torch/pyexecutor/executor_request_queue.py (2)

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.

Learnt from: yiqingy0
PR: #5198
File: jenkins/mergeWaiveList.py:0-0
Timestamp: 2025-07-22T08:33:49.109Z
Learning: In the TensorRT-LLM waive list merging system, removed lines are always located at the end of the merge waive lists, which is why the mergeWaiveList.py script uses reverse traversal - it's an optimization for this specific domain constraint.

🪛 Ruff (0.12.2)
tests/unittest/_torch/test_executor_request_queue.py

677-677: Local variable result is assigned to but never used

Remove assignment to unused variable result

(F841)


698-698: Local variable result is assigned to but never used

Remove assignment to unused variable result

(F841)

tensorrt_llm/_torch/pyexecutor/executor_request_queue.py

318-318: Line too long (133 > 120)

(E501)

🔇 Additional comments (1)
tensorrt_llm/_torch/pyexecutor/executor_request_queue.py (1)

460-460: Consider the order when merging scheduled requests.

The order of extending new_scheduled_requests with new_requests_cur_rank may affect processing order. Ensure this aligns with the expected behavior - typically, pre-scheduled requests should be processed before newly balanced ones.

-        new_scheduled_requests.extend(new_requests_cur_rank)
+        # Process pre-scheduled requests first, then newly balanced ones
+        result = new_requests_cur_rank + new_scheduled_requests
+        return result

@Shunkangz Shunkangz requested a review from pcastonguay July 25, 2025 01:45
@Shunkangz Shunkangz force-pushed the attention_dp_rank_route branch from d01a546 to f783e2c Compare July 25, 2025 06:06
Copy link
Contributor

@coderabbitai coderabbitai bot left a 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

🔭 Outside diff range comments (1)
tensorrt_llm/schedule_params.py (1)

1-16: Add NVIDIA copyright header.

All TensorRT-LLM source files must contain an NVIDIA copyright header that includes the current year.

Add the copyright header at the beginning of the file:

+# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+# SPDX-License-Identifier: Apache-2.0
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
 from dataclasses import dataclass
 from typing import Optional
♻️ Duplicate comments (8)
tensorrt_llm/_torch/pyexecutor/executor_request_queue.py (5)

249-254: Fix duplicate performance metrics update.

The performance metrics are updated twice for the same requests, causing inflated latency measurements as noted in past reviews.

Remove the duplicate metric updates:

-        # Update performance metrics
-        # TODO: Check whether we should update the performance metrics for all ranks
-        if self.enable_iter_perf_stats and self.dist.rank == 0:
-            self._update_new_active_requests_queue_latency(scheduled_requests)
-            self._update_new_active_requests_queue_latency(unscheduled_requests)
-

280-281: Fix misleading comment about copying.

The comment says "avoid modifying the original" but the code doesn't create a proper copy.

-        # Create a copy to avoid modifying the original all_ranks_num_active_requests
-        all_ranks_num_active_requests = self.all_ranks_num_active_requests.copy()
+        # Create a copy to avoid modifying the original all_ranks_num_active_requests
+        all_ranks_num_active_requests = self.all_ranks_num_active_requests.copy()

302-302: Fix potential request order reversal with extendleft.

Using extendleft reverses the order of pending requests, breaking FIFO order.

-        self.waiting_queue.extendleft(pending_requests)
+        # Maintain FIFO order by extending from the right
+        self.waiting_queue.extend(reversed(pending_requests))

315-319: Replace assertion with proper error handling.

The assertion could fail unexpectedly and should be replaced with descriptive error handling.

-            assert self.all_ranks_num_active_requests[target_dp_rank] <= self.max_num_active_requests, \
-                f"The number of active requests on rank {target_dp_rank}" \
-                f"is {self.all_ranks_num_active_requests[target_dp_rank]}, " \
-                f"which is greater than the max_num_active_requests {self.max_num_active_requests}"
+            if self.all_ranks_num_active_requests[target_dp_rank] > self.max_num_active_requests:
+                raise RuntimeError(
+                    f"Scheduling inconsistency: rank {target_dp_rank} has "
+                    f"{self.all_ranks_num_active_requests[target_dp_rank]} active requests, "
+                    f"exceeding limit of {self.max_num_active_requests}. "
+                    f"This indicates a bug in the filtering logic."
+                )

233-236: Consider using local variable for active request counts.

The instance variable self.all_ranks_num_active_requests could lead to side effects if methods are called in different orders.

Consider passing the active request counts as a parameter between methods instead of storing as an instance variable to avoid potential side effects and improve thread safety.

tests/unittest/_torch/test_executor_request_queue.py (3)

677-679: Remove unused variable assignment.

The variable result is assigned but never used in this test.

-    result = attention_dp_queue._schedule_attention_dp_requests(
-        scheduled_requests, unscheduled_requests)
+    attention_dp_queue._schedule_attention_dp_requests(
+        scheduled_requests, unscheduled_requests)

764-766: Add assertion to verify scheduling result.

The test schedules requests but doesn't verify the final result.

     result = attention_dp_queue._schedule_attention_dp_requests(
         scheduled, unscheduled)
+    
+    # Verify that all requests were scheduled successfully
+    assert len(unscheduled) == 0  # All should have been scheduled
+    assert req_no_params not in result  # Only requests for current rank

698-700: Remove another unused variable assignment.

The variable result is assigned but never used in this test.

-        result = attention_dp_queue._schedule_attention_dp_requests(
-            scheduled_requests, unscheduled_requests)
+        attention_dp_queue._schedule_attention_dp_requests(
+            scheduled_requests, unscheduled_requests)
🧹 Nitpick comments (4)
tensorrt_llm/schedule_params.py (1)

7-12: Improve docstring format and clarity.

The docstring could benefit from following Google style more closely and providing clearer parameter descriptions.

-    """Schedule parameters.
-
-    Args:
-        attention_dp_rank (int): The rank of target attention dp
-        attention_dp_relax (bool): Whether to allow the request to be scheduled to other attention dp for better throughput
-    """
+    """Parameters for controlling attention data parallel scheduling behavior.
+
+    Args:
+        attention_dp_rank: The target rank for attention data parallelism. If None, the request
+            can be scheduled to any available rank.
+        attention_dp_relax: Whether to allow relaxed scheduling. If True, the request can be
+            scheduled to other attention dp ranks for better throughput when the target rank
+            is at capacity. If None or False, strict scheduling is enforced.
+    """
tensorrt_llm/_torch/pyexecutor/executor_request_queue.py (1)

265-266: Clarify counter semantics for filtered requests.

The counter num_fetch_requests includes all new requests but some may be filtered out and put back to waiting queue. Consider tracking scheduled vs unscheduled separately.

         # Update counters
         self.num_fetch_requests += len(new_requests)
         self.num_fetch_requests_cur_rank += len(new_requests_cur_rank)
+        # TODO: Consider tracking num_scheduled_requests and num_pending_requests separately
tests/unittest/_torch/test_executor_request_queue.py (2)

319-805: Consider adding edge case tests.

The test coverage is comprehensive but could benefit from additional edge cases.

Consider adding tests for:

  1. Concurrent access scenarios with multiple threads
  2. Very large request queues to test scalability
  3. Invalid attention_dp_rank values (negative, >= tp_size)
  4. Mixed relax=True/False requests for the same rank
  5. Boundary conditions when all ranks are at capacity

349-351: Remove hardcoded initialization of all_ranks_num_active_requests.

The test fixture hardcodes all_ranks_num_active_requests which might not reflect real scenarios where this is populated via allgather.

Consider creating a helper method to properly initialize this based on test requirements:

-    # Initialize all_ranks_num_active_requests
-    queue.all_ranks_num_active_requests = [2, 1, 3, 0]  # 4 ranks
+    # Initialize via a helper method that simulates allgather
+    queue.all_ranks_num_active_requests = []  # Will be set per test
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d01a546 and f783e2c.

📒 Files selected for processing (7)
  • tensorrt_llm/_torch/pyexecutor/executor_request_queue.py (5 hunks)
  • tensorrt_llm/executor/executor.py (3 hunks)
  • tensorrt_llm/executor/request.py (3 hunks)
  • tensorrt_llm/executor/worker.py (1 hunks)
  • tensorrt_llm/llmapi/llm.py (5 hunks)
  • tensorrt_llm/schedule_params.py (1 hunks)
  • tests/unittest/_torch/test_executor_request_queue.py (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (4)
  • tensorrt_llm/executor/worker.py
  • tensorrt_llm/executor/request.py
  • tensorrt_llm/llmapi/llm.py
  • tensorrt_llm/executor/executor.py
🧰 Additional context used
📓 Path-based instructions (2)
**/*.py

📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md)

**/*.py: Python code 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 Python file, prefer docstrings over comments.
Comments in Python should be reserved 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.
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/executor_request_queue.py
  • tests/unittest/_torch/test_executor_request_queue.py
  • tensorrt_llm/schedule_params.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/executor_request_queue.py
  • tests/unittest/_torch/test_executor_request_queue.py
  • tensorrt_llm/schedule_params.py
🪛 Ruff (0.12.2)
tests/unittest/_torch/test_executor_request_queue.py

677-677: Local variable result is assigned to but never used

Remove assignment to unused variable result

(F841)


698-698: Local variable result is assigned to but never used

Remove assignment to unused variable result

(F841)

tensorrt_llm/schedule_params.py

11-11: Line too long (123 > 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

@coderabbitai coderabbitai bot requested a review from HuiGao-NV July 27, 2025 03:45
@Superjomn Superjomn changed the title [None][feat]: Add support of scheduling attention dp request [feat]: Add support of scheduling attention dp request Aug 1, 2025
@Shunkangz Shunkangz changed the title [feat]: Add support of scheduling attention dp request [None][feat] Add support of scheduling attention dp request Aug 1, 2025
Copy link
Contributor

@coderabbitai coderabbitai bot left a 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/llmapi/llm.py (1)

331-331: Fix line length violation in documentation.

The documentation line exceeds the 120-character limit. Consider breaking it into multiple lines.

-            scheduling_params (tensorrt_llm.scheduling_params.SchedulingParams, optional): Scheduling parameters. Defaults to None.
+            scheduling_params (tensorrt_llm.scheduling_params.SchedulingParams, optional): 
+                Scheduling parameters. Defaults to None.
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9264c28 and 4e872d2.

📒 Files selected for processing (2)
  • tensorrt_llm/llmapi/llm.py (7 hunks)
  • tests/unittest/api_stability/references/llm.yaml (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • tests/unittest/api_stability/references/llm.yaml
🧰 Additional context used
📓 Path-based instructions (2)
**/*.py

📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md)

**/*.py: Python code 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 Python file, prefer docstrings over comments.
Comments in Python should be reserved 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.
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/llmapi/llm.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. The block should be prepended to the top of all files, including .cpp, .h, .cu, .py, and any other source files which are compiled or interpreted.

Files:

  • tensorrt_llm/llmapi/llm.py
🧬 Code Graph Analysis (1)
tensorrt_llm/llmapi/llm.py (1)
tensorrt_llm/scheduling_params.py (1)
  • SchedulingParams (6-15)
🪛 Ruff (0.12.2)
tensorrt_llm/llmapi/llm.py

331-331: Line too long (131 > 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 (6)
tensorrt_llm/llmapi/llm.py (6)

33-33: LGTM: Import statement follows established patterns.

The import of SchedulingParams is correctly placed and follows the same pattern as other parameter imports in the file.


240-241: LGTM: Method signature follows established patterns.

The scheduling_params parameter addition is consistent with other optional batched parameters in the method signature.


260-261: LGTM: Documentation follows established format.

The parameter documentation is consistent with other parameters and provides appropriate type and description information.


291-291: LGTM: Parameter forwarding follows established pattern.

The scheduling_params forwarding uses the same _item_at helper pattern as other batched parameters, maintaining consistency.


317-317: LGTM: Async method signature is correctly updated.

The scheduling_params parameter is properly typed as a single optional parameter, which is appropriate for the async method that handles individual requests.


429-429: LGTM: Parameter forwarding to executor is correct.

The scheduling_params parameter is properly forwarded to the executor's generate_async method, maintaining consistency with other parameter forwarding.

@tensorrt-cicd
Copy link
Collaborator

PR_Github #13773 [ run ] triggered by Bot

Copy link
Collaborator

@QiJune QiJune left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@pcastonguay
Copy link
Collaborator

/bot kill

Shunkang and others added 10 commits August 1, 2025 13:01
Signed-off-by: Shunkang <[email protected]>
Signed-off-by: Shunkang <[email protected]>
Signed-off-by: Shunkang <[email protected]>
Signed-off-by: Patrice Castonguay <[email protected]>
Signed-off-by: Patrice Castonguay <[email protected]>
Signed-off-by: Patrice Castonguay <[email protected]>
Signed-off-by: Shunkang <[email protected]>
Signed-off-by: Shunkang <[email protected]>
@pcastonguay pcastonguay force-pushed the attention_dp_rank_route branch from 4e872d2 to d7bde53 Compare August 1, 2025 17:01
@pcastonguay
Copy link
Collaborator

/bot run --disable-fail-fast --add-multi-gpu-test

Copy link
Contributor

@coderabbitai coderabbitai bot left a 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 (6)
tensorrt_llm/_torch/pyexecutor/executor_request_queue.py (5)

136-137: Fix incorrect attribute name.

The attribute name should be py_schedule_params, not py_scheduling_params. This was flagged in previous reviews.

-        scheduling_params = getattr(req_item.request, 'py_scheduling_params',
-                                    None)
+        scheduling_params = getattr(req_item.request, 'py_schedule_params',
+                                    None)

325-333: Fix incorrect sorting logic for relax mode prioritization.

The sorting with reverse=True puts relax=True requests first, which contradicts the comment. This was flagged in previous reviews.

-        new_requests = sorted(new_requests, key=get_relax_value, reverse=True)
+        new_requests = sorted(new_requests, key=get_relax_value)

327-328: Fix incorrect attribute name.

Same issue as previous - should use py_schedule_params instead of py_scheduling_params.


339-340: Fix incorrect attribute name.

Same issue as previous - should use py_schedule_params instead of py_scheduling_params.


375-376: Fix incorrect attribute name in broadcasting.

Should use py_schedule_params instead of py_scheduling_params for consistency.

-            py_scheduling_params = self._collect_py_objects_from_requests(
-                new_requests, "py_scheduling_params")
+            py_scheduling_params = self._collect_py_objects_from_requests(
+                new_requests, "py_schedule_params")
tests/unittest/_torch/test_executor_request_queue.py (1)

371-373: Fix incorrect attribute name in mock request creation.

The mock should use py_schedule_params to match the actual implementation, not py_scheduling_params. This was flagged in previous reviews.

-        mock_request.py_scheduling_params = mock_schedule_params
+        mock_request.py_schedule_params = mock_schedule_params
     else:
-        mock_request.py_scheduling_params = None
+        mock_request.py_schedule_params = None
🧹 Nitpick comments (7)
tensorrt_llm/scheduling_params.py (1)

10-11: Fix line length violation in docstring.

The docstring line exceeds the 120-character limit specified in the coding guidelines.

-        attention_dp_rank (int): The rank of target attention dp
-        attention_dp_relax (bool): Whether to allow the request to be scheduled to other attention dp for better throughput
+        attention_dp_rank (int): The rank of target attention dp.
+        attention_dp_relax (bool): Whether to allow the request to be scheduled to 
+            other attention dp for better throughput.
tensorrt_llm/llmapi/llm.py (1)

317-317: Fix line length violation in parameter list.

The parameter addition is correct, but line 331 exceeds the 120-character limit.

-            scheduling_params (tensorrt_llm.scheduling_params.SchedulingParams, optional): Scheduling parameters. Defaults to None.
+            scheduling_params (tensorrt_llm.scheduling_params.SchedulingParams, optional): 
+                Scheduling parameters. Defaults to None.

Also applies to: 331-331

tensorrt_llm/_torch/pyexecutor/executor_request_queue.py (1)

378-381: Fix variable name for consistency.

The variable should be named py_schedule_params for consistency with the correct attribute name.

            py_request_objects = tuple(
                filter(None, [
                    py_logits_post_processors, py_multimodal_data,
-                    py_scheduling_params
+                    py_schedule_params
                ]))
tests/unittest/_torch/test_executor_request_queue.py (4)

672-673: Simplify boolean comparison.

Avoid explicit comparison to True. Use the boolean expression directly.

-    assert attention_dp_queue._can_process_attention_dp_request(
-        req_no_params, [0, 0, 0, 0]) == True
+    assert attention_dp_queue._can_process_attention_dp_request(
+        req_no_params, [0, 0, 0, 0])

679-680: Simplify boolean comparison.

Avoid explicit comparison to True. Use the boolean expression directly.

-    assert attention_dp_queue._can_process_attention_dp_request(
-        req_relax, [0, 0, 0, 0]) == True
+    assert attention_dp_queue._can_process_attention_dp_request(
+        req_relax, [0, 0, 0, 0])

687-688: Simplify boolean comparison.

Avoid explicit comparison to True. Use the boolean expression directly.

-    assert attention_dp_queue._can_process_attention_dp_request(
-        req_target, all_ranks) == True
+    assert attention_dp_queue._can_process_attention_dp_request(
+        req_target, all_ranks)

696-697: Simplify boolean comparison.

Avoid explicit comparison to False. Use not for false checks.

-    assert attention_dp_queue._can_process_attention_dp_request(
-        req_no_capacity, all_ranks_full) == False
+    assert not attention_dp_queue._can_process_attention_dp_request(
+        req_no_capacity, all_ranks_full)
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4e872d2 and d7bde53.

📒 Files selected for processing (8)
  • tensorrt_llm/_torch/pyexecutor/executor_request_queue.py (8 hunks)
  • tensorrt_llm/executor/executor.py (3 hunks)
  • tensorrt_llm/executor/request.py (3 hunks)
  • tensorrt_llm/executor/worker.py (1 hunks)
  • tensorrt_llm/llmapi/llm.py (7 hunks)
  • tensorrt_llm/scheduling_params.py (1 hunks)
  • tests/unittest/_torch/test_executor_request_queue.py (3 hunks)
  • tests/unittest/api_stability/references/llm.yaml (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (4)
  • tensorrt_llm/executor/request.py
  • tensorrt_llm/executor/worker.py
  • tests/unittest/api_stability/references/llm.yaml
  • tensorrt_llm/executor/executor.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 class in the constructor in Python.
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/executor_request_queue.py
  • tests/unittest/_torch/test_executor_request_queue.py
  • tensorrt_llm/llmapi/llm.py
  • tensorrt_llm/scheduling_params.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/executor_request_queue.py
  • tests/unittest/_torch/test_executor_request_queue.py
  • tensorrt_llm/llmapi/llm.py
  • tensorrt_llm/scheduling_params.py
🧠 Learnings (3)
📚 Learning: in the tensorrt-llm waive list merging system, removed lines are always located at the end of the me...
Learnt from: yiqingy0
PR: NVIDIA/TensorRT-LLM#5198
File: jenkins/mergeWaiveList.py:0-0
Timestamp: 2025-07-22T08:33:49.109Z
Learning: In the TensorRT-LLM waive list merging system, removed lines are always located at the end of the merge waive lists, which is why the mergeWaiveList.py script uses reverse traversal - it's an optimization for this specific domain constraint.

Applied to files:

  • tensorrt_llm/_torch/pyexecutor/executor_request_queue.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/executor_request_queue.py
📚 Learning: applies to **/*.py : for interfaces that may be used outside a file, prefer docstrings over comments...
Learnt from: CR
PR: NVIDIA/TensorRT-LLM#0
File: CODING_GUIDELINES.md:0-0
Timestamp: 2025-08-01T07:34:42.734Z
Learning: Applies to **/*.py : For interfaces that may be used outside a file, prefer docstrings over comments in Python.

Applied to files:

  • tensorrt_llm/_torch/pyexecutor/executor_request_queue.py
🪛 Ruff (0.12.2)
tests/unittest/_torch/test_executor_request_queue.py

672-673: Avoid equality comparisons to True; use ...: for truth checks

Replace comparison

(E712)


679-680: Avoid equality comparisons to True; use ...: for truth checks

Replace comparison

(E712)


687-688: Avoid equality comparisons to True; use ...: for truth checks

Replace comparison

(E712)


696-697: Avoid equality comparisons to False; use not ...: for false checks

Replace comparison

(E712)

tensorrt_llm/llmapi/llm.py

331-331: Line too long (131 > 120)

(E501)

tensorrt_llm/scheduling_params.py

11-11: Line too long (123 > 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 (12)
tensorrt_llm/scheduling_params.py (1)

5-15: LGTM! Well-structured dataclass implementation.

The dataclass is properly implemented with appropriate use of slots=True for performance and kw_only=True for API clarity. The optional attributes with proper type hints align well with the attention data parallelism scheduling requirements.

tensorrt_llm/llmapi/llm.py (4)

33-33: LGTM! Proper import of SchedulingParams.

The import follows the established pattern and maintains namespace consistency as required by the coding guidelines.


240-241: LGTM! Consistent parameter addition to synchronous generate method.

The scheduling_params parameter is properly added to both the method signature and docstring, following the same pattern as other optional parameters.

Also applies to: 260-261


291-291: LGTM! Proper parameter forwarding in batch processing.

The scheduling_params is correctly extracted using the _item_at helper function and forwarded to generate_async, maintaining consistency with other batched parameters.


437-437: LGTM! Proper parameter forwarding to executor.

The scheduling_params is correctly passed through to the executor's generate_async method, completing the parameter propagation chain.

tensorrt_llm/_torch/pyexecutor/executor_request_queue.py (3)

90-91: LGTM: Method signature follows previous feedback.

The addition of enable_attention_dp and all_ranks_num_active_requests parameters aligns with past review suggestions to extend the existing method rather than creating separate methods.


213-215: LGTM: Consistent parameter addition.

The method signature correctly includes the attention DP parameters, maintaining consistency with the overall design approach.


420-474: LGTM: Improved method flexibility.

The refactoring of _balance_requests_across_ranks to accept a dictionary of pre-scheduled requests and merge balanced requests improves the method's flexibility and makes the scheduling logic more modular.

tests/unittest/_torch/test_executor_request_queue.py (4)

319-356: LGTM: Well-designed test fixtures.

The test fixtures provide appropriate mocking for distributed environments and create clean test isolation. The multi-rank setup properly simulates the attention DP environment.


739-845: LGTM: Comprehensive parameterized test coverage.

The parameterized test cases provide excellent coverage of various attention DP scheduling scenarios, including balanced distribution, capacity limits, rank targeting, and edge cases. The test data is well-structured and validates the scheduling logic thoroughly.


358-377: LGTM: Well-designed helper function.

The helper function provides good abstraction for creating mock requests with scheduling parameters. The logic correctly handles both cases with and without scheduling parameters.


575-625: LGTM: Valuable integration tests.

The integration tests effectively verify end-to-end behavior by combining filtering and scheduling operations. They test realistic scenarios with proper capacity constraints and mixed request types.

@tensorrt-cicd
Copy link
Collaborator

PR_Github #13821 [ kill ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #13773 [ run ] completed with state ABORTED
/LLM/main/L0_MergeRequest_PR pipeline #10353 completed with status: 'FAILURE'

@tensorrt-cicd
Copy link
Collaborator

PR_Github #13821 [ kill ] completed with state SUCCESS
Successfully killed previous jobs for commit d7bde53

@tensorrt-cicd
Copy link
Collaborator

PR_Github #13822 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #13822 [ run ] completed with state SUCCESS
/LLM/main/L0_MergeRequest_PR pipeline #10392 completed with status: 'SUCCESS'

@pcastonguay pcastonguay merged commit 67a3fd8 into NVIDIA:main Aug 2, 2025
4 checks passed
lancelly pushed a commit to lancelly/TensorRT-LLM that referenced this pull request Aug 6, 2025
)

Signed-off-by: Shunkang <[email protected]>
Signed-off-by: Patrice Castonguay <[email protected]>
Co-authored-by: Shunkang <[email protected]>
Co-authored-by: Patrice Castonguay <[email protected]>
Signed-off-by: Lanyu Liao <[email protected]>
jain-ria pushed a commit to jain-ria/TensorRT-LLM that referenced this pull request Aug 7, 2025
)

Signed-off-by: Shunkang <[email protected]>
Signed-off-by: Patrice Castonguay <[email protected]>
Co-authored-by: Shunkang <[email protected]>
Co-authored-by: Patrice Castonguay <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

6 participants