- 
                Notifications
    
You must be signed in to change notification settings  - Fork 1.8k
 
[Perf]: Add residual, norm for nemotron_nas models #6455
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
[Perf]: Add residual, norm for nemotron_nas models #6455
Conversation
          
📝 Walkthrough""" WalkthroughThe  Changes
 Sequence Diagram(s)sequenceDiagram
    participant Caller
    participant NemotronNASModel
    participant DecoderLayer
    participant RMSNorm
    Caller->>NemotronNASModel: forward(attn_metadata, input_ids/inputs_embeds, ...)
    alt input_ids provided
        NemotronNASModel->>NemotronNASModel: lookup embeddings
    end
    NemotronNASModel->>NemotronNASModel: residual = None
    loop for each DecoderLayer
        NemotronNASModel->>DecoderLayer: forward(position_ids, hidden_states, attn_metadata, residual, ...)
        DecoderLayer-->>NemotronNASModel: (hidden_states, residual)
    end
    NemotronNASModel->>RMSNorm: forward(hidden_states, residual)
    RMSNorm-->>NemotronNASModel: normalized_hidden_states
    NemotronNASModel-->>Caller: normalized_hidden_states
    Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Note ⚡️ Unit Test Generation is now available in beta!Learn more here, or try it out under "Finishing Touches" below. 📜 Recent review detailsConfiguration used: .coderabbit.yaml 📒 Files selected for processing (1)
 🧰 Additional context used📓 Path-based instructions (2)**/*.py📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md) 
 Files: 
 **/*.{cpp,h,cu,py}📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md) 
 Files: 
 ⏰ 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)
 🔇 Additional comments (3)
 ✨ Finishing Touches
 🧪 Generate unit tests
 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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit: 
 SupportNeed 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)
 Other keywords and placeholders
 Documentation and Community
  | 
    
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
🔭 Outside diff range comments (1)
tensorrt_llm/_torch/models/modeling_nemotron_nas.py (1)
147-154: Fix return type annotation to match the actual return value.The method now returns a tuple
(hidden_states, residual)but the return type annotation still showstorch.Tensor.Apply this diff to fix the return type annotation:
+from typing import Any, Dict, Optional, Tuple def forward( self, position_ids: torch.IntTensor, hidden_states: torch.Tensor, attn_metadata: AttentionMetadata, residual: Optional[torch.Tensor] = None, **kwargs, -) -> torch.Tensor: +) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:Note: Add
Tupleto the imports at the top of the file if not already present.Also applies to: 181-181
🧹 Nitpick comments (1)
tensorrt_llm/_torch/models/modeling_nemotron_nas.py (1)
245-248: Improve error message clarity.The error message could be more precise about the requirement.
Apply this diff to clarify the error message:
if (input_ids is None) ^ (inputs_embeds is not None): raise ValueError( - "You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one" + "You must specify exactly one of input_ids or inputs_embeds" )
📜 Review details
Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
tensorrt_llm/_torch/models/modeling_nemotron_nas.py(2 hunks)
🧰 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/models/modeling_nemotron_nas.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/models/modeling_nemotron_nas.py
🔇 Additional comments (3)
tensorrt_llm/_torch/models/modeling_nemotron_nas.py (3)
157-162: Residual handling implementation looks good!The conditional residual initialization and propagation through normalization layers enables operator fusion while maintaining backward compatibility. This aligns well with the PR's performance optimization goals.
Also applies to: 173-179
235-267: Well-implemented forward method with proper residual propagation!The method correctly manages residual connections through all decoder layers and applies the final normalization. The implementation enables the operator fusion optimizations mentioned in the PR objectives.
161-162: RMSNorm two-argument support confirmedThe
RMSNormimplementation intensorrt_llm/_torch/modules/rms_norm.pydefines:def forward( self, hidden_states: torch.Tensor, residual: Optional[torch.Tensor] = None, ) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]: … if isinstance(residual, torch.Tensor): flashinfer_fused_add_rmsnorm(hidden_states, residual, …) else: hidden_states = flashinfer_rmsnorm(hidden_states, …) …This shows that
forwardaccepts(hidden_states, residual)and correctly dispatches the fused operator.No changes required.
| 
           /bot run  | 
    
| 
           PR_Github #13395 [ run ] triggered by Bot  | 
    
| 
           duplicate of #6157 without extra merge commits  | 
    
| 
           PR_Github #13395 [ run ] completed with state   | 
    
a2f47de    to
    1061c4e      
    Compare
  
    | 
           /bot run  | 
    
| 
           PR_Github #13409 [ run ] triggered by Bot  | 
    
| 
           PR_Github #13409 [ run ] completed with state   | 
    
| 
           /bot run  | 
    
| 
           PR_Github #13546 [ run ] triggered by Bot  | 
    
| 
           PR_Github #13546 [ run ] completed with state   | 
    
1061c4e    to
    f756b0d      
    Compare
  
    | 
           /bot reuse-pipeline  | 
    
| 
           PR_Github #13553 [ reuse-pipeline ] triggered by Bot  | 
    
f756b0d    to
    4132eaa      
    Compare
  
    There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
📜 Review details
Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
tensorrt_llm/_torch/models/modeling_nemotron_nas.py(2 hunks)
🧰 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 Python class in the constructor.
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 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 reflection.
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/models/modeling_nemotron_nas.py
**/*.{cpp,h,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/models/modeling_nemotron_nas.py
🔇 Additional comments (5)
tensorrt_llm/_torch/models/modeling_nemotron_nas.py (5)
173-178: LGTM! Consistent residual handling implementation.The FFN block residual handling follows the same pattern as the attention block, ensuring consistent behavior throughout the layer. This implementation should enable the intended operation fusion for performance gains.
181-181: LGTM! Correct tuple return for residual propagation.The return statement correctly returns both
hidden_statesandresidual, enabling proper residual propagation between decoder layers for the fusion optimization.
250-266: LGTM! Well-implemented forward pass with residual propagation.The forward method correctly implements:
- Embedding lookup from input_ids when inputs_embeds is not provided
 - Proper residual initialization and propagation through decoder layers
 - Final normalization using both hidden_states and residual for fusion benefits
 This implementation should achieve the intended performance improvements through operation fusion, assuming the input validation is fixed.
245-248: Fix the input validation logic.The XOR validation logic is incorrect. The condition
(input_ids is None) ^ (inputs_embeds is not None)will beTruewhen both areNoneor both are provided, but the error message suggests you want exactly one to be provided.Apply this diff to fix the validation logic:
- if (input_ids is None) ^ (inputs_embeds is not None): + if (input_ids is None) == (inputs_embeds is None): raise ValueError( - "You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one" + "You must specify exactly one of input_ids or inputs_embeds" )Likely an incorrect or invalid review comment.
157-162: RMSNorm dual-tensor forward verifiedThe
RMSNorm.forward(self, hidden_states, residual: Optional[Tensor] = None)signature returnsUnion[Tensor, Tuple[Tensor, Tensor]], confirming it supports both single- and dual-tensor inputs. The attention block’s residual handling logic is correct and ready to merge.
| 
           PR_Github #13553 [ reuse-pipeline ] completed with state   | 
    
Signed-off-by: Shreyas Misra <[email protected]>
4132eaa    to
    a65a00b      
    Compare
  
    | 
           /bot reuse-pipeline  | 
    
| 
           PR_Github #13557 [ reuse-pipeline ] triggered by Bot  | 
    
| 
           PR_Github #13557 [ reuse-pipeline ] completed with state   | 
    
Signed-off-by: Shreyas Misra <[email protected]> Signed-off-by: Lanyu Liao <[email protected]>
Signed-off-by: Shreyas Misra <[email protected]>
Summary by CodeRabbit
New Features
Refactor
Description
The nsys profile showed that these ops were not fused so this PR addresses that and improves perf as shown below:
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 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.