Skip to content

Conversation

@nv-guomingz
Copy link
Collaborator

@nv-guomingz nv-guomingz commented Nov 4, 2025

Summary by CodeRabbit

Release Notes

  • Performance

    • Optimized parallel execution paths in model inference computations.
  • Bug Fixes

    • Fixed forward computation flow enabling proper gradient propagation during model inference.
  • Refactor

    • Simplified control flow logic in model routing execution.

Description

Test Coverage

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

@nv-guomingz nv-guomingz requested review from a team as code owners November 4, 2025 06:29
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Nov 4, 2025

📝 Walkthrough

Walkthrough

The changes introduce parallel MoE routing execution in Qwen3-next by wrapping routed and shared expert computation in separate functions coordinated via CUDA events, and implement the ChunkGatedDeltaRuleFunction forward method with conditional l2-norm application and autograd-enabling outputs.

Changes

Cohort / File(s) Summary
Parallel MoE execution coordination
tensorrt_llm/_torch/models/modeling_qwen3_next.py
Refactors Qwen3NextSparseMoeBlock and Qwen3NextGatedDeltaNet to execute routed-expert and shared-expert paths concurrently via maybe_execute_in_parallel, using event_dict for CUDA event synchronization; simplifies conditional dispatch logic (num_prefills > 0) and comments out tensor-parallelism detection calls.
ChunkGatedDeltaRuleFunction implementation
tensorrt_llm/_torch/modules/fla/chunk.py
Replaces placeholder pass statement with functional implementation: conditionally applies l2-norm to queries and keys, computes gate, output, and final state via chunk_gated_delta_rule_fwd, and returns outputs for autograd propagation.

Sequence Diagram(s)

sequenceDiagram
    participant Router as Router Logic
    participant Routed as Routed Expert Path
    participant Shared as Shared Expert Path
    participant Combiner as Output Combination
    
    rect rgb(100, 150, 200)
    note over Router,Shared: Before: Sequential Execution
    Router->>Router: Compute router logits
    Router->>Routed: Route through experts
    Routed->>Combiner: Receive routed output
    Combiner->>Shared: Compute shared experts
    Shared->>Combiner: Combine outputs
    end
    
    rect rgb(150, 200, 100)
    note over Router,Shared: After: Parallel Execution
    Router->>Routed: Route computation (with events)
    Router->>Shared: Shared computation (with events)
    par Parallel Paths
        Routed->>Routed: Execute routed experts
    and
        Shared->>Shared: Execute shared experts
    end
    Routed->>Combiner: Synchronize routed output
    Shared->>Combiner: Synchronize shared output
    Combiner->>Combiner: Combine outputs
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

  • CUDA event synchronization logic: Verify maybe_execute_in_parallel correctly handles event_dict for Main/MoeShared coordination and prevents race conditions
  • MoE routing correctness: Ensure parallelization does not alter expert routing semantics or output correctness under varying batch/sequence configurations
  • Control flow dispatch simplification: Confirm the if/else dispatch (num_prefills > 0) maintains equivalence with the replaced branching logic
  • ChunkGatedDeltaRuleFunction integration: Validate l2-norm conditioning and autograd flow with downstream dtype casting

Pre-merge checks and finishing touches

❌ Failed checks (2 warnings)
Check name Status Explanation Resolution
Title check ⚠️ Warning The PR title appears to contain a typo ('chroe' instead of 'chore') and inadequately describes the substantive changes, which involve parallel MoE routing execution and forward method implementations. Correct the typo to 'chore' and make the title more specific about the main changes, e.g., '[None][chore] Parallelize MoE routing execution and implement chunk gated delta rule forward method.'
Description check ⚠️ Warning The PR description is completely empty of actual content, containing only the template with unfilled placeholder sections for Description and Test Coverage. Fill in the Description section explaining what changes were made and why, and the Test Coverage section listing relevant tests that validate the changes.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • 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

Comment @coderabbitai help to get the list of available commands and usage tips.

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
tensorrt_llm/_torch/models/modeling_qwen3_next.py (1)

373-432: Critical bug: Missing self.aux_stream assignment.

The aux_stream parameter is passed to __init__ (line 376) and forwarded to create_moe (line 407), but is never stored as self.aux_stream. However, line 481 in the forward method references self.aux_stream, which will raise an AttributeError at runtime.

Apply this diff to fix the issue:

     def __init__(
         self,
         model_config: ModelConfig[Qwen3NextConfig],
         aux_stream: torch.cuda.Stream,
         layer_idx: Optional[int] = None,
     ):
         super().__init__()
         config = model_config.pretrained_config
         self.model_config = model_config
+        self.aux_stream = aux_stream
         self.hidden_dim = config.hidden_size
🧹 Nitpick comments (1)
tensorrt_llm/_torch/models/modeling_qwen3_next.py (1)

1138-1138: Consider removing commented-out code.

The commented has_tp lines are explained by the adjacent comments about fusion kernel limitations. However, if this code will not be re-enabled soon, consider removing it to reduce clutter.

Also applies to: 1297-1297

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 67208f1 and 53c6b8a.

📒 Files selected for processing (2)
  • tensorrt_llm/_torch/models/modeling_qwen3_next.py (6 hunks)
  • tensorrt_llm/_torch/modules/fla/chunk.py (0 hunks)
💤 Files with no reviewable changes (1)
  • tensorrt_llm/_torch/modules/fla/chunk.py
🧰 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/models/modeling_qwen3_next.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/models/modeling_qwen3_next.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/models/modeling_qwen3_next.py
🧠 Learnings (5)
📓 Common learnings
Learnt from: venkywonka
Repo: NVIDIA/TensorRT-LLM PR: 6029
File: .github/pull_request_template.md:45-53
Timestamp: 2025-08-27T17:50:13.264Z
Learning: For PR templates in TensorRT-LLM, avoid suggesting changes that would increase developer overhead, such as converting plain bullets to mandatory checkboxes. The team prefers guidance-style bullets that don't require explicit interaction to reduce friction in the PR creation process.
Learnt from: jhaotingc
Repo: NVIDIA/TensorRT-LLM PR: 7856
File: cpp/tensorrt_llm/thop/fp8BlockScaleMoe.cpp:159-166
Timestamp: 2025-09-19T21:28:13.751Z
Learning: In TensorRT-LLM blockScaleMoe routing (cpp/tensorrt_llm/kernels/trtllmGenKernels/blockScaleMoe/runner.cu), the DeepSeek routing method performs reinterpret_cast<float*>(routingLogits) at line 89, which could cause issues if routing_logits are BF16. However, Qwen3-FP8 models use RenormalizeNaive routing method and are not affected by this dtype casting issue.
Learnt from: ChristinaZ
Repo: NVIDIA/TensorRT-LLM PR: 7068
File: cpp/tensorrt_llm/kernels/moeTopKFuncs.cuh:169-172
Timestamp: 2025-08-20T07:43:36.447Z
Learning: In TensorRT-LLM MOE kernels, when processing up to 128 experts across 32 threads, each thread handles at most 4 experts (N < 5 constraint), where N represents candidates per thread rather than total system capacity.
Learnt from: djns99
Repo: NVIDIA/TensorRT-LLM PR: 7104
File: cpp/tensorrt_llm/kernels/cutlass_kernels/moe_gemm/moe_kernels.cu:1475-1480
Timestamp: 2025-08-21T02:39:12.009Z
Learning: The min latency mode functionality in TensorRT-LLM MOE kernels (cpp/tensorrt_llm/kernels/cutlass_kernels/moe_gemm/moe_kernels.cu) is deprecated and no longer being maintained/updated, as confirmed by djns99. Bug reports and optimization suggestions for the computeStridesTmaWarpSpecializedLowLatencyKernel and related min latency code paths should be deprioritized.
📚 Learning: 2025-09-19T21:28:13.751Z
Learnt from: jhaotingc
Repo: NVIDIA/TensorRT-LLM PR: 7856
File: cpp/tensorrt_llm/thop/fp8BlockScaleMoe.cpp:159-166
Timestamp: 2025-09-19T21:28:13.751Z
Learning: In TensorRT-LLM blockScaleMoe routing (cpp/tensorrt_llm/kernels/trtllmGenKernels/blockScaleMoe/runner.cu), the DeepSeek routing method performs reinterpret_cast<float*>(routingLogits) at line 89, which could cause issues if routing_logits are BF16. However, Qwen3-FP8 models use RenormalizeNaive routing method and are not affected by this dtype casting issue.

Applied to files:

  • tensorrt_llm/_torch/models/modeling_qwen3_next.py
📚 Learning: 2025-08-14T23:23:27.449Z
Learnt from: djns99
Repo: NVIDIA/TensorRT-LLM PR: 6915
File: cpp/tensorrt_llm/kernels/cutlass_kernels/moe_gemm/moe_kernels.cu:4010-4012
Timestamp: 2025-08-14T23:23:27.449Z
Learning: For MOE (Mixture of Experts) code reviews in TensorRT-LLM, avoid repeatedly suggesting finalize fusion validation checks and safety assertions. The user djns99 has indicated these suggestions are repetitive and unwanted across multiple MOE-related changes.

Applied to files:

  • tensorrt_llm/_torch/models/modeling_qwen3_next.py
📚 Learning: 2025-08-20T07:43:36.447Z
Learnt from: ChristinaZ
Repo: NVIDIA/TensorRT-LLM PR: 7068
File: cpp/tensorrt_llm/kernels/moeTopKFuncs.cuh:169-172
Timestamp: 2025-08-20T07:43:36.447Z
Learning: In TensorRT-LLM MOE kernels, when processing up to 128 experts across 32 threads, each thread handles at most 4 experts (N < 5 constraint), where N represents candidates per thread rather than total system capacity.

Applied to files:

  • tensorrt_llm/_torch/models/modeling_qwen3_next.py
📚 Learning: 2025-08-19T12:45:11.997Z
Learnt from: amitz-nv
Repo: NVIDIA/TensorRT-LLM PR: 7033
File: tensorrt_llm/_torch/pyexecutor/model_engine.py:0-0
Timestamp: 2025-08-19T12:45:11.997Z
Learning: In tensorrt_llm/_torch/pyexecutor/model_engine.py, DoRA (Delta Orthogonal Rank Adaptation) functionality was removed from the PyTorch flow to eliminate issues with inverted DoRA detection logic. The original is_dora condition was checking if scaling_vec_pointer == 0, which was potentially incorrect.

Applied to files:

  • tensorrt_llm/_torch/models/modeling_qwen3_next.py
🧬 Code graph analysis (1)
tensorrt_llm/_torch/models/modeling_qwen3_next.py (1)
tensorrt_llm/_torch/modules/multi_stream_utils.py (1)
  • maybe_execute_in_parallel (35-74)
⏰ 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/models/modeling_qwen3_next.py (3)

53-53: LGTM - Imports support parallel MoE execution.

The new imports are used correctly to implement parallel routing and shared expert computation.

Also applies to: 56-56


459-482: Well-structured parallel MoE execution pattern.

The refactoring successfully parallelizes routed and shared expert computation using closure functions and event-based synchronization. The logic correctly preserves the original behavior: routed experts and shared experts are computed in parallel, then combined.

Note: This depends on fixing the missing self.aux_stream assignment flagged above.


1079-1083: LGTM - Cleaner dispatch logic.

The simplified conditional correctly dispatches to forward_extend when there are prefills and forward_decode otherwise. This is more readable than the previous branching approach.

@nv-guomingz nv-guomingz force-pushed the user/guomingz/clean_qwen3_next branch from 53c6b8a to 754b793 Compare November 4, 2025 14:29
@nv-guomingz nv-guomingz force-pushed the user/guomingz/clean_qwen3_next branch from 754b793 to 57d412b Compare November 4, 2025 14:56
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.

2 participants