Skip to content

Conversation

@meenchen
Copy link
Collaborator

@meenchen meenchen commented Oct 27, 2025

Summary by CodeRabbit

  • New Features

    • Added NVFP4_AWQ quantization algorithm support for Mixture-of-Experts models with enhanced activation scaling.
  • Improvements

    • Implemented pre-quantization scaling to improve accuracy for AWQ-based quantization across attention and fused components.
    • Added guards to prevent incompatible FP4/FP8 output configurations when pre-quantization scaling is active.

Description

Add NVFP4 AWQ support. Counterpart in ModelOpt: NVIDIA/TensorRT-Model-Optimizer#421.

Adding an optional pre_quant_scale parameter for AWQ.

Test Coverage

Tested Qwen3-8B and 30B Moe with TP/EP.

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.

Signed-off-by: weimingc <[email protected]>
Signed-off-by: weimingc <[email protected]>
@meenchen meenchen requested review from a team as code owners October 27, 2025 21:23
@meenchen meenchen requested review from brb-nv and yuxianq October 27, 2025 21:23
@meenchen meenchen marked this pull request as draft October 27, 2025 21:23
Signed-off-by: weimingc <[email protected]>
@meenchen meenchen changed the title [feat] nvfp4 awq support [OMNIML-2932] [feat] nvfp4 awq support Nov 3, 2025
@meenchen meenchen self-assigned this Nov 3, 2025
@meenchen meenchen marked this pull request as ready for review November 3, 2025 23:28
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Nov 3, 2025

📝 Walkthrough

Walkthrough

This pull request introduces support for pre-quantization activation scaling in NVFP4_AWQ quantization. Changes include: adding NVFP4_AWQ to the quantization algorithm enum, registering pre_quant_scale/fc31_act_scale parameters in attention and linear modules, conditionally applying activation scaling before FP4 quantization in fused MoE and linear layers, and guarding against incompatible configurations.

Changes

Cohort / File(s) Summary
Quantization algorithm extension
tensorrt_llm/quantization/mode.py, tensorrt_llm/quantization/quantize.py
Added NVFP4_AWQ enum to QuantAlgo; extended from_quant_algo to map NVFP4_AWQ to NVFP4 QuantMode; added conditional pre_quant_scale initialization for AWQ-based MoE quantization (W4A16_AWQ, NVFP4_AWQ, W4A8_AWQ).
Attention module pre-quantization scaling
tensorrt_llm/_torch/modules/attention.py
Added guards to prevent FP8 output when o_proj.pre_quant_scale exists; conditioned out_scale assignment on pre_quant_scale being None; explicitly disabled enable_attn_nvfp4_output when pre_quant_scale is present.
Linear module pre-quantization scaling
tensorrt_llm/_torch/modules/linear.py
Initialized pre_quant_scale attribute to None in NVFP4 create_weights paths; added runtime guard raising RuntimeError for FP4QuantizedTensor when pre_quant_scale exists; applied pre_quant_scale multiplication to plain tensor inputs before quantization; loaded pre_quant_scale from checkpoints across NVFP4/AWQ/fused QKV/fused gate-up loading paths.
Fused MoE pre-quantization scaling
tensorrt_llm/_torch/modules/fused_moe/fused_moe_cutlass.py, tensorrt_llm/_torch/modules/fused_moe/fused_moe_trtllm_gen.py, tensorrt_llm/_torch/modules/fused_moe/quantization.py
Applied conditional fc31_act_scale multiplication to input x before FP4 quantization in both post_quant_allgather and non-post_quant_allgather NVFP4 paths; registered fc31_act_scale as module parameter when pre_quant_scale exists; loaded and derived fc31_act_scale from per-expert w3/w1 pre_quant_scale values with max reduction and expert broadcasting.

Sequence Diagram(s)

sequenceDiagram
    participant Layer as Attention/Linear Layer
    participant Input as Input Tensor
    participant PreQuant as Pre-Quant Check
    participant Scale as Apply pre_quant_scale
    participant Quantize as FP4 Quantization
    participant Output as Quantized Output

    Input->>PreQuant: Is pre_quant_scale present?
    alt pre_quant_scale exists
        PreQuant->>Scale: Yes, apply scaling
        Scale->>Input: x = x * pre_quant_scale
        Input->>Quantize: Scaled input
    else pre_quant_scale is None
        PreQuant->>Quantize: No, skip scaling
    end
    Quantize->>Output: FP4 quantized result
Loading
sequenceDiagram
    participant Config as Quantization Config
    participant Quantize as quantize_layers()
    participant CheckAWQ as Check AWQ Algorithm
    participant InitParams as init_params dict
    participant Module as MoE Module

    Config->>Quantize: MoE + AWQ algorithm
    Quantize->>CheckAWQ: Is W4A16_AWQ/NVFP4_AWQ/W4A8_AWQ?
    alt AWQ-based algorithm
        CheckAWQ->>InitParams: Set pre_quant_scale=True
        InitParams->>Module: Register fc31_act_scale parameter
    else Other algorithm
        CheckAWQ->>Module: Skip pre_quant_scale initialization
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

  • tensorrt_llm/_torch/modules/linear.py — Most substantial changes with pre_quant_scale loading across multiple code paths (vanilla, fused QKV, fused gate-up); requires verification of consistent loading patterns and guard logic for error cases
  • tensorrt_llm/_torch/modules/fused_moe/quantization.py — Complex parameter registration and loading logic with per-expert scale aggregation (max reduction); verify fc31_act_scale derivation and broadcasting logic
  • Guard conditions in attention.py and linear.py — Verify RuntimeError conditions are appropriately triggered and that incompatible configurations are caught early
  • Consistency across quantization paths — Ensure pre_quant_scale/fc31_act_scale loading is consistent across different quantization methods (NVFP4, AWQ variants, fused variants)

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Description check ⚠️ Warning The PR description is missing critical required sections from the template including a proper title, detailed description of changes, test coverage details, and PR checklist confirmation. Add a properly formatted PR title following [JIRA/Issue][type] format, expand the Description section with implementation details, provide specific test coverage information, and ensure all PR checklist items are reviewed and marked.
✅ Passed checks (1 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the main feature being added (NVFP4 AWQ support) and follows the repository's template format with a JIRA ticket and feature type marker.
✨ 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/modules/fused_moe/fused_moe_trtllm_gen.py (1)

307-320: Critical: Incorrect scaling of quantized tensor.

Lines 307-309 apply fc31_act_scale unconditionally, even when run_post_quant_allgather=True. This causes the scale to be applied to an already-quantized tensor, corrupting the quantized values.

Flow when run_post_quant_allgather=True and has_nvfp4:

  1. Lines 235-241: Scale x (unquantized)
  2. Line 242: Quantize x
  3. Line 267: Allgather quantized x
  4. Lines 307-309: Scale quantized x again ← BUG
  5. Lines 319-320: Use corrupted quantized tensor

Apply this fix to move the scaling inside the correct conditional:

         scale_factor_use_ue8m0 = False
         is_scale_factor_swizzled = False  # use linear layout here
 
-        if hasattr(self,
-                   'fc31_act_scale') and self.fc31_act_scale is not None:
-            x = x * self.fc31_act_scale
         if not run_post_quant_allgather:
+            if hasattr(self, 'fc31_act_scale') and self.fc31_act_scale is not None:
+                x = x * self.fc31_act_scale
             hidden_states_fp4, hidden_states_scale_linear_fp4 = (
                 torch.ops.trtllm.fp4_quantize(
                     x,

This ensures the scale is only applied to unquantized data before the fp4_quantize call.

🧹 Nitpick comments (3)
tensorrt_llm/_torch/modules/fused_moe/quantization.py (3)

1685-1690: Remove unnecessary f-string prefix.

Line 1689 has an f-string without any placeholders. Remove the f prefix for cleaner code.

Apply this diff:

-            has_pre_quant_scale = f"0.w1.pre_quant_scale" in weights
+            has_pre_quant_scale = "0.w1.pre_quant_scale" in weights

1697-1709: Remove redundant imports and verify device placement.

Two concerns:

  1. Lines 1700-1700: TensorParallelMode and load_weight_shard are already imported at the top of the file (line 19), making this import statement redundant.

  2. Line 1707: The device is hard-coded to 'cuda'. Other parts of this file use the device from the destination tensor (e.g., line 1872: device = dst_w3_w1_weight_scale.device). Consider using a consistent approach, especially since comments mention "online EPLB" which may use CPU.

Apply this diff to remove the redundant import:

         # If pre_quant_scale exists, we need a per-channel act scale for fc31
         # All experts share the same input, so pre_quant_scale should be identical across experts
         if has_pre_quant_scale:
-            from ..linear import TensorParallelMode, load_weight_shard
-
             # Create fc31_act_scale parameter (for gate_up_proj / w3_w1)
             # Shape: (1, hidden_size) - single vector for all experts (they share the same input)
             fc31_act_scale = nn.Parameter(torch.empty(1,

For device placement, verify whether hard-coding to 'cuda' is intentional or should follow the pattern used elsewhere in this file.


1737-1798: Consider adding explicit strict parameter and removing redundant device transfer.

Two minor suggestions for improvement:

  1. Lines 1767-1768: The zip() call lacks an explicit strict= parameter. Since all_w3_pre_quant_scales and all_w1_pre_quant_scales are built from the same module.initial_local_expert_ids, they should have the same length, but adding strict=True makes this requirement explicit and helps catch bugs.

  2. Line 1793: The .to(dtype=module.dtype, device='cuda') call includes a device transfer, but w3_reference and w1_reference are already on CUDA device (loaded with device='cuda' at lines 1751 and 1757). The .to(dtype=module.dtype) is sufficient.

Apply this diff:

             for i, (w3_scale, w1_scale) in enumerate(
                     zip(all_w3_pre_quant_scales[1:],
-                        all_w1_pre_quant_scales[1:]), 1):
+                        all_w1_pre_quant_scales[1:], strict=True), 1):
                 if not torch.allclose(
                         w3_scale, w3_reference, rtol=1e-5, atol=1e-8):
                     max_diff = (w3_scale - w3_reference).abs().max()
@@ -1786,7 +1786,7 @@
                     break
 
             # Take the maximum pre_quant_scale between w3 and w1 from the first expert
             # (all experts should have the same values)
             # Shape: (hidden_size,)
             # Keep on CUDA device (w3_reference and w1_reference are already on CUDA)
             fc31_pre_quant_scale = torch.max(w3_reference, w1_reference).to(
-                dtype=module.dtype, device='cuda')
+                dtype=module.dtype)
📜 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 1401a3c and b4714e1.

📒 Files selected for processing (7)
  • tensorrt_llm/_torch/modules/attention.py (2 hunks)
  • tensorrt_llm/_torch/modules/fused_moe/fused_moe_cutlass.py (1 hunks)
  • tensorrt_llm/_torch/modules/fused_moe/fused_moe_trtllm_gen.py (2 hunks)
  • tensorrt_llm/_torch/modules/fused_moe/quantization.py (3 hunks)
  • tensorrt_llm/_torch/modules/linear.py (4 hunks)
  • tensorrt_llm/quantization/mode.py (2 hunks)
  • tensorrt_llm/quantization/quantize.py (1 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
**/*.{h,hpp,hh,hxx,cpp,cxx,cc,cu,cuh,py}

📄 CodeRabbit inference engine (CODING_GUIDELINES.md)

Use only spaces, no tabs; indent with 4 spaces.

Files:

  • tensorrt_llm/quantization/quantize.py
  • tensorrt_llm/_torch/modules/fused_moe/quantization.py
  • tensorrt_llm/_torch/modules/fused_moe/fused_moe_trtllm_gen.py
  • tensorrt_llm/quantization/mode.py
  • tensorrt_llm/_torch/modules/fused_moe/fused_moe_cutlass.py
  • tensorrt_llm/_torch/modules/attention.py
  • tensorrt_llm/_torch/modules/linear.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/quantization/quantize.py
  • tensorrt_llm/_torch/modules/fused_moe/quantization.py
  • tensorrt_llm/_torch/modules/fused_moe/fused_moe_trtllm_gen.py
  • tensorrt_llm/quantization/mode.py
  • tensorrt_llm/_torch/modules/fused_moe/fused_moe_cutlass.py
  • tensorrt_llm/_torch/modules/attention.py
  • tensorrt_llm/_torch/modules/linear.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/quantization/quantize.py
  • tensorrt_llm/_torch/modules/fused_moe/quantization.py
  • tensorrt_llm/_torch/modules/fused_moe/fused_moe_trtllm_gen.py
  • tensorrt_llm/quantization/mode.py
  • tensorrt_llm/_torch/modules/fused_moe/fused_moe_cutlass.py
  • tensorrt_llm/_torch/modules/attention.py
  • tensorrt_llm/_torch/modules/linear.py
🧠 Learnings (12)
📚 Learning: 2025-08-08T22:03:40.707Z
Learnt from: sklevtsov-nvidia
Repo: NVIDIA/TensorRT-LLM PR: 3294
File: cpp/tensorrt_llm/kernels/cutlass_kernels/moe_gemm/moe_kernels.cu:1198-1209
Timestamp: 2025-08-08T22:03:40.707Z
Learning: In the CUTLASS MoE kernels (cpp/tensorrt_llm/cutlass_extensions), when `layout_info.fusion` is set to `TmaWarpSpecializedGroupedGemmInput::EpilogueFusion::FINALIZE`, the `router_scales` parameter must be non-null by design. The fused finalize kernel epilogue does not perform nullptr checks and requires valid router scales to function correctly. This is an implicit contract that callers must satisfy when enabling the FINALIZE fusion mode.

Applied to files:

  • tensorrt_llm/_torch/modules/fused_moe/quantization.py
  • tensorrt_llm/_torch/modules/fused_moe/fused_moe_trtllm_gen.py
  • tensorrt_llm/_torch/modules/fused_moe/fused_moe_cutlass.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/modules/fused_moe/fused_moe_trtllm_gen.py
📚 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/modules/fused_moe/fused_moe_trtllm_gen.py
  • tensorrt_llm/_torch/modules/fused_moe/fused_moe_cutlass.py
📚 Learning: 2025-08-09T20:57:04.084Z
Learnt from: sklevtsov-nvidia
Repo: NVIDIA/TensorRT-LLM PR: 3294
File: cpp/tensorrt_llm/kernels/cutlass_kernels/moe_gemm/moe_gemm_tma_warp_specialized_input.cu:118-127
Timestamp: 2025-08-09T20:57:04.084Z
Learning: In the CUTLASS MoE finalize fusion implementation (cpp/tensorrt_llm/kernels/cutlass_kernels/moe_gemm/moe_gemm_tma_warp_specialized_input.cu), when setting `fused_finalize_epilogue.stride_final_output` with shape `(hidden_size, num_output_tokens, 1)`, the `num_rows_in_final_output` should be set to `num_output_tokens` (not `hidden_size`) because of a swap+transpose operation that maps rows of the output tensor to `hidden_size` and columns to `num_output_tokens`.

Applied to files:

  • tensorrt_llm/_torch/modules/fused_moe/fused_moe_cutlass.py
📚 Learning: 2025-08-08T05:10:38.906Z
Learnt from: sklevtsov-nvidia
Repo: NVIDIA/TensorRT-LLM PR: 3294
File: cpp/tensorrt_llm/cutlass_extensions/include/cutlass_extensions/epilogue/fusion/sm90_visitor_scatter.hpp:0-0
Timestamp: 2025-08-08T05:10:38.906Z
Learning: The ScaledAccPerRowBiasPerColScaleScatter fusion in CUTLASS extensions (cpp/tensorrt_llm/cutlass_extensions/include/cutlass_extensions/epilogue/fusion/sm90_visitor_scatter.hpp) is specifically designed for per-column scaling factors only, so it uses a fixed Stride<_0,_1,int64_t> rather than conditional stride logic.

Applied to files:

  • tensorrt_llm/_torch/modules/fused_moe/fused_moe_cutlass.py
📚 Learning: 2025-08-21T21:48:35.135Z
Learnt from: djns99
Repo: NVIDIA/TensorRT-LLM PR: 7104
File: cpp/tensorrt_llm/cutlass_extensions/include/cutlass_extensions/epilogue/fusion/sm90_visitor_scatter.hpp:399-417
Timestamp: 2025-08-21T21:48:35.135Z
Learning: CUTLASS extensions in TensorRT-LLM (located under cpp/tensorrt_llm/cutlass_extensions/) are designed to integrate with and extend functionality in the external CUTLASS repository. When analyzing these extensions, their consumers and functionality wiring may exist in the CUTLASS codebase rather than within TensorRT-LLM itself.

Applied to files:

  • tensorrt_llm/_torch/modules/fused_moe/fused_moe_cutlass.py
📚 Learning: 2025-09-29T15:14:28.503Z
Learnt from: amitz-nv
Repo: NVIDIA/TensorRT-LLM PR: 8063
File: tensorrt_llm/lora_manager.py:1080-1112
Timestamp: 2025-09-29T15:14:28.503Z
Learning: In tensorrt_llm/lora_manager.py, when calculating part_sizes for attn_qkv fused LoRA modules, the sizes are correctly multiplied by tp_size because model_config.num_heads and model_config.num_kv_heads are already divided by tp_size (per-TP-rank values), so multiplication is needed to get the original full concatenated dimension size. The interleave_fused_lora_weights_for_tp function provides proper validation with asserts for total size and TP divisibility.

Applied to files:

  • tensorrt_llm/_torch/modules/attention.py
📚 Learning: 2025-09-29T15:14:28.503Z
Learnt from: amitz-nv
Repo: NVIDIA/TensorRT-LLM PR: 8063
File: tensorrt_llm/lora_manager.py:1080-1112
Timestamp: 2025-09-29T15:14:28.503Z
Learning: In tensorrt_llm/lora_manager.py, when calculating part_sizes for attn_qkv fused LoRA modules, the sizes are correctly multiplied by tp_size because model_config.num_heads and model_config.num_kv_heads are already divided by tp_size (per-TP-rank values), so multiplication is needed to get the original full concatenated dimension size. The interleave_fused_lora_weights_for_tp function provides proper validation.

Applied to files:

  • tensorrt_llm/_torch/modules/attention.py
📚 Learning: 2025-08-14T21:04:50.248Z
Learnt from: thorjohnsen
Repo: NVIDIA/TensorRT-LLM PR: 6910
File: cpp/tensorrt_llm/batch_manager/kvCacheManager.cpp:0-0
Timestamp: 2025-08-14T21:04:50.248Z
Learning: In KV cache onboarding logic during prefill in cpp/tensorrt_llm/batch_manager/kvCacheManager.cpp, when calculating which blocks fall within the attention window, use getTokensPerBlock() to advance token indices rather than block->getUniqueTokens().size(), because the calculation needs to consider the post-prefill state where blocks will be filled to capacity, not their current token count.

Applied to files:

  • tensorrt_llm/_torch/modules/attention.py
📚 Learning: 2025-08-14T15:43:23.107Z
Learnt from: MatthiasKohl
Repo: NVIDIA/TensorRT-LLM PR: 6904
File: tensorrt_llm/_torch/attention_backend/trtllm.py:259-262
Timestamp: 2025-08-14T15:43:23.107Z
Learning: In TensorRT-LLM's attention backend, tensor parameters in the plan() method are assigned directly without validation (dtype, device, contiguity checks). This maintains consistency across all tensor inputs and follows the pattern of trusting callers to provide correctly formatted tensors.

Applied to files:

  • tensorrt_llm/_torch/modules/attention.py
📚 Learning: 2025-08-15T06:46:53.813Z
Learnt from: eopXD
Repo: NVIDIA/TensorRT-LLM PR: 6767
File: cpp/tensorrt_llm/batch_manager/kvCacheManager.cpp:0-0
Timestamp: 2025-08-15T06:46:53.813Z
Learning: In the TensorRT-LLM KV cache manager, SWA (Sliding Window Attention) combined with beam search is currently in a broken/non-functional state and is planned for future rework. During preparatory refactoring phases, code related to SWA+beam search may intentionally remain in a non-working state until the broader rework is completed.

Applied to files:

  • tensorrt_llm/_torch/modules/attention.py
📚 Learning: 2025-08-27T16:59:12.325Z
Learnt from: Fridah-nv
Repo: NVIDIA/TensorRT-LLM PR: 7227
File: tests/unittest/_torch/auto_deploy/_utils_test/_model_test_utils.py:269-275
Timestamp: 2025-08-27T16:59:12.325Z
Learning: In FP8 quantized linear layers, bias should be kept in high precision (typically float32) rather than being quantized to FP8 or cast to half precision, as bias is added after the matrix multiplication and high precision bias helps maintain numerical accuracy.

Applied to files:

  • tensorrt_llm/_torch/modules/linear.py
🧬 Code graph analysis (5)
tensorrt_llm/quantization/quantize.py (2)
tensorrt_llm/models/modeling_utils.py (1)
  • quant_algo (550-551)
tensorrt_llm/quantization/mode.py (1)
  • QuantAlgo (23-48)
tensorrt_llm/_torch/modules/fused_moe/quantization.py (4)
tensorrt_llm/module.py (1)
  • register_parameter (186-190)
tensorrt_llm/_torch/modules/fused_moe/interface.py (1)
  • MoEWeightLoadingMode (16-22)
tensorrt_llm/_torch/modules/linear.py (2)
  • TensorParallelMode (47-59)
  • load_weight_shard (62-106)
tensorrt_llm/logger.py (1)
  • warning (132-133)
tensorrt_llm/quantization/mode.py (2)
tensorrt_llm/models/modeling_utils.py (1)
  • quant_algo (550-551)
cpp/include/tensorrt_llm/common/quantization.h (2)
  • QuantMode (28-440)
  • QuantMode (34-35)
tensorrt_llm/_torch/modules/fused_moe/fused_moe_cutlass.py (1)
tensorrt_llm/_torch/utils.py (1)
  • Fp4QuantizedTensor (99-106)
tensorrt_llm/_torch/modules/attention.py (1)
tensorrt_llm/quantization/mode.py (2)
  • has_fp8_kv_cache (167-168)
  • has_fp4_kv_cache (170-171)
🪛 Ruff (0.14.3)
tensorrt_llm/_torch/modules/fused_moe/quantization.py

1689-1689: f-string without any placeholders

Remove extraneous f prefix

(F541)


1767-1768: zip() without an explicit strict= parameter

Add explicit value for parameter strict=

(B905)

tensorrt_llm/_torch/modules/linear.py

793-796: Avoid specifying long messages outside the exception class

(TRY003)


801-804: Avoid specifying long messages outside the exception class

(TRY003)

🔇 Additional comments (12)
tensorrt_llm/_torch/modules/fused_moe/fused_moe_cutlass.py (1)

293-300: LGTM! Pre-quantization scaling correctly applied.

The implementation properly applies the activation scale before FP4 quantization with appropriate guards:

  • Checks attribute existence and None value
  • Asserts input is not already quantized
  • Applied at the correct point in the flow (before fp4_quantize)
tensorrt_llm/quantization/mode.py (2)

47-47: LGTM! Enum member properly added.

The new NVFP4_AWQ quantization algorithm follows existing naming conventions and will be automatically included in QUANT_ALGO_LIST.


414-416: LGTM! Correct QuantMode mapping for NVFP4_AWQ.

The implementation correctly maps NVFP4_AWQ to the same QuantMode as NVFP4, with the distinction maintained at the QuantAlgo level. The clarifying comment is helpful.

tensorrt_llm/_torch/modules/attention.py (2)

361-363: Verify attribute access pattern.

Line 362 directly accesses self.o_proj.pre_quant_scale without checking if the attribute exists, while lines 398-401 use hasattr() for the same attribute. This inconsistency could lead to AttributeError if pre_quant_scale is not always defined on o_proj.

Consider using consistent attribute access:

-        if self.has_quant_scale and self.o_proj.pre_quant_scale is None and (
+        if self.has_quant_scale and getattr(self.o_proj, 'pre_quant_scale', None) is None and (
                 self.attn.has_fp8_kv_cache or self.attn.has_fp4_kv_cache):

Or verify that create_weights() always initializes pre_quant_scale on o_proj to ensure the attribute always exists.


394-401: LGTM! Proper control of output quantization.

The logic correctly prevents FP8/FP4 output when pre_quant_scale is present, maintaining BF16 precision for subsequent scaling. The defensive hasattr check is good practice.

tensorrt_llm/quantization/quantize.py (1)

76-82: LGTM! Correct auto-detection of pre_quant_scale for AWQ.

The implementation properly enables pre_quant_scale for all AWQ-based quantization algorithms when quantizing MixtureOfExperts modules. The logic is clear and aligns with the PR objectives.

tensorrt_llm/_torch/modules/fused_moe/fused_moe_trtllm_gen.py (1)

235-244: LGTM! Correct pre-quantization scaling in allgather path.

The scaling is correctly applied to the unquantized tensor before the fp4_quantize call at line 242. The shape documentation in comments is helpful.

tensorrt_llm/_torch/modules/fused_moe/quantization.py (1)

1579-1581: LGTM!

The optional parameter registration pattern is correct, and the comment clearly explains when this will be initialized.

tensorrt_llm/_torch/modules/linear.py (4)

777-779: LGTM!

The comment clearly explains when pre_quant_scale is present and its relationship with LayerNorm fusion.


899-915: LGTM!

The loading logic correctly:

  • Uses consistent device placement from module.weight.device
  • Applies TensorParallelMode.flip for activation scaling (orthogonal to weight sharding)
  • Creates the parameter with the correct shape and dtype

973-990: LGTM!

The loading logic for fused gate/up projection correctly:

  • Documents that pre_quant_scale is shared between gate and up projections
  • Uses consistent implementation with the vanilla path
  • Properly handles device placement and tensor sharding

787-810: FP4 output disabling mechanism verified—no issues found.

The attention layer (line 394-396 in attention.py) correctly disables FP4/FP8 output by not setting out_scale when pre_quant_scale exists. The linear.py error handling properly enforces this contract by raising errors if FP4 quantized input is unexpectedly received when pre_quant_scale is present. The mechanism is correctly implemented across both modules.

Copy link
Collaborator

@danielafrimi danielafrimi left a comment

Choose a reason for hiding this comment

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

LGTM

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