KEMBAR78
[TRTLLM-6994][feat] FP8 Context MLA integration. by yuxianq · Pull Request #7581 · NVIDIA/TensorRT-LLM · GitHub
Skip to content

Conversation

@yuxianq
Copy link
Collaborator

@yuxianq yuxianq commented Sep 6, 2025

Description

Add FP8 context MLA support for SM100

Compared to FP8 context FMHA, FP8 context MLA needs BF16 output.

Accuracy:
No GSM8K score drop in the DeepSeek V3 Lite + fp8/nvfp4 + fp8 KV cache + enable/disable MTP/chunked_prefill/kv_cache_reuse cases.

Performance (see details in https://docs.google.com/spreadsheets/d/1MJxPZhMCdAV2XUMZ_KL-V21LC9cX9pL1e9cyg9q_eVw/edit?usp=sharing):
E2E Perf improvement on SM100 (DeepSeek R1/Lite + fp8/nvfp4 + fp8 KV cache + MTP=0 + DEP8 + 8k/1 or 4k/1):
total_token_throughput: + 0.66%~5.09%
mean_ttft: - 0.82%~5.63%
p99_ttft: - 1.42%~10%

Summary by CodeRabbit

  • New Features

    • Enable MLA with FP8-context attention and broaden FP8 MLA support to more GPUs (including SM100).
    • Add a toggle for NVFP4 attention output and persist quantization scales across attention/MLA paths.
    • Improve diagnostics with richer attention kernel logging.
  • Bug Fixes

    • Prevent unintended forcing of a specific FP8 output type; honor previously determined output dtype.
    • More consistent FP8/NVFP4 quantization handling across forward paths.
  • Tests

    • Update skips for pre-Hopper devices and add MOE configurations with dynamic backend selection.
  • Refactor

    • Simplify runner construction and initialization ordering.

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.

Signed-off-by: Yuxian Qiu <142763828+yuxianq@users.noreply.github.com>
@yuxianq yuxianq requested review from a team as code owners September 6, 2025 03:01
@yuxianq yuxianq requested review from QiJune and Superjomn September 6, 2025 03:01
@yuxianq
Copy link
Collaborator Author

yuxianq commented Sep 6, 2025

/bot run --disable-fail-fast

@tensorrt-cicd
Copy link
Collaborator

PR_Github #17843 [ run ] triggered by Bot

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Sep 6, 2025

📝 Walkthrough

Walkthrough

The PR updates FP8-context MLA enablement and output dtype handling in C++ AttentionOp, extends FMHA kernel logging, refactors THOP runner creation and MLAsm gating, adds persistent quantization scale state and NVFP4 output gating in PyTorch Attention/MLA, inserts an assertion in executor worker, and adjusts tests for MOE config and pre-Hopper skips.

Changes

Cohort / File(s) Summary
C++ AttentionOp core (MLA/FP8 context)
cpp/tensorrt_llm/common/attentionOp.cpp, cpp/tensorrt_llm/common/attentionOp.h
Relax MLA pre-check to allow MLA with FP8-context FMHA; remove forced E4M3 output under FP8-context FMHA; expand AttentionOp::data() tuple with mFP8ContextMLA (inserted after mFP8ContextFMHA).
THOP Attention runner and MLA gating
cpp/tensorrt_llm/thop/attentionOp.cpp
Use std::make_shared for Runner creation; initialize mKVCacheQuantMode earlier; broaden FP8 MLA context enablement to SM 100 and 120 when hasFp8KvCache() is true; minor structural cleanups.
FMHA kernel logging
cpp/tensorrt_llm/kernels/trtllmGenKernels/fmha/fmhaKernels.h
Expand debug log to include dtypes, SM, and various kernel parameters; no API change.
PyTorch Attention/MLA quantization state
tensorrt_llm/_torch/modules/attention.py
Add enable_attn_nvfp4_output, out_scale, out_scale_sf, has_quant_scale; persist scales in module state; update _attn_impl signature to accept enable_attn_nvfp4_output; propagate scales across forward paths; attn_custom_op_inplace disables NVFP4; MLA.create_weights sets out_scale=None and uses it in forward calls.
Executor worker assertion
tensorrt_llm/executor/worker.py
Add assertion on prompt length vs executor_config.max_seq_len in a code path where max_seq_len may be absent.
Tests: MOE config and skips
tests/integration/defs/accuracy/test_llm_api_pytorch.py
Replace pre-Hopper skip decorators; add moe_config to tests; dynamic MOE backend by SM version; specify CUTEDSL in DSL cases; add WIDEEP load balancer config in a multi-GPU test.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant Py as Attention (PyTorch)
  participant Impl as _attn_impl
  participant Op as TRTLLM Attention Op
  participant Ker as FMHA/MLA Kernels

  Py->>Impl: forward(..., enable_attn_nvfp4_output, out_scale, out_scale_sf)
  note right of Py: has_quant_scale from weights<br/>out_scale / out_scale_sf set in create_weights
  Impl->>Op: enqueue(q,k,v, metadata, scales, flags)
  alt has_quant_scale
    Op->>Ker: Use FP8 output (E4M3) if enabled
    note over Op,Ker: NVFP4 output gated by enable_attn_nvfp4_output
  else
    Op->>Ker: Use non-FP8 output dtype
  end
  Ker-->>Py: output tensor
Loading
sequenceDiagram
  autonumber
  participant Cpp as AttentionOp::initialize
  participant Cfg as Config/Flags
  participant Run as TllmGenFmhaRunner

  Cpp->>Cfg: Check MLA, FP8ContextFMHA, DenseFMHA, SM, hasFp8KvCache
  alt DenseFMHA unsupported
    note right of Cpp: MLA allowed with FP8-context FMHA
    Cpp->>Run: create MLA runner (dtype preserved)
  else
    Cpp-->>Cpp: Use non-MLA path
  end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Suggested reviewers

  • litaotju
  • kaiyux
  • PerkzZheng
✨ 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

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: 1

Caution

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

⚠️ Outside diff range comments (4)
cpp/tensorrt_llm/kernels/trtllmGenKernels/fmha/fmhaKernels.h (1)

529-543: Fix logging call to use printf-style format
Use the variadic macro correctly instead of concatenating a std::string:

-        TLLM_LOG_DEBUG("Searching for kernel traits: " + info);
+        TLLM_LOG_DEBUG("Searching for kernel traits: %s", info.c_str());
tensorrt_llm/executor/worker.py (1)

473-513: Bug: AttributeError/incorrect flow when max_seq_len is absent; use guarded path and explicit validation.

If executor_config lacks max_seq_len and user provides max_tokens, the code still accesses max_seq_len later (and the assert does too), causing AttributeError. Also avoid assert for user input validation.

Apply:

 def _deduce_max_tokens(request: GenerationRequest,
                        executor_config: tllm.ExecutorConfig) -> int:
@@
     max_tokens = request.sampling_params.max_tokens
     query_token_len = len(
         request.query_token_ids) if request.query_token_ids else 0
     cp_size = 1 if (not hasattr(executor_config, "mapping")
                     or executor_config.mapping.cp_size
                     is None) else executor_config.mapping.cp_size
-    if not hasattr(executor_config, "max_seq_len"):
-        logger.warning("`default_max_tokens` cannot be deduced")
-        if max_tokens is None:
-            raise ValueError(
-                "`max_tokens` must be set when `default_max_tokens` cannot be deduced"
-            )
-    assert (
-        len(prompt_token_ids) <= executor_config.max_seq_len
-    ), f"`prompt_token_ids` length ({len(prompt_token_ids)}) is greater than `max_seq_len` ({executor_config.max_seq_len})"
-    splited_prompt_len = int(len(prompt_token_ids) / cp_size)
-    default_max_tokens = executor_config.max_seq_len - splited_prompt_len - query_token_len
+    max_seq_len = getattr(executor_config, "max_seq_len", None)
+    if max_seq_len is None:
+        logger.warning("`default_max_tokens` cannot be deduced")
+        if max_tokens is None:
+            raise ValueError(
+                "`max_tokens` must be set when `default_max_tokens` cannot be deduced"
+            )
+        return max_tokens
+    # Validate prompt length after cp split (ceil divide).
+    split_prompt_len = (len(prompt_token_ids) + cp_size - 1) // cp_size
+    if split_prompt_len > max_seq_len:
+        raise ValueError(
+            f"`prompt_token_ids` length per cp ({split_prompt_len}) exceeds `max_seq_len` ({max_seq_len})"
+        )
+    default_max_tokens = max_seq_len - split_prompt_len - query_token_len
     if default_max_tokens <= 0:
         logger.warning(
             f"`default_max_tokens` ({default_max_tokens}) should be greater than 0, "
-            f"`default_max_tokens` ({default_max_tokens}) = max_seq_len ({executor_config.max_seq_len})"
-            f" - `splited_prompt_len` ({splited_prompt_len}) - `query_token_len` ({query_token_len})"
+            f"`default_max_tokens` ({default_max_tokens}) = max_seq_len ({max_seq_len})"
+            f" - `split_prompt_len` ({split_prompt_len}) - `query_token_len` ({query_token_len})"
         )
         if max_tokens is None:
             raise ValueError(
                 "`max_tokens` must be set when `default_max_tokens` is illegal"
             )
cpp/tensorrt_llm/common/attentionOp.cpp (1)

1667-1687: Ensure FP8 context quantization is fully implemented

  • No definition of invokeMLAContextFp8Quantize was found; add or locate its implementation and confirm it reads quant_scale_o/q/kv and dequant_scale_q/kv from mla_param.
  • Verify that those scale pointers are forwarded into the MLA kernels (e.g. mlaKernels.h) and actually used to quantize/dequantize QKV in the context phase.
tensorrt_llm/_torch/modules/attention.py (1)

1-4: Missing NVIDIA Apache-2.0 header (2025).

Per repo guidelines, prepend the NVIDIA Apache-2.0 copyright header.

Apply this diff at file top:

+# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
+# 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, express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
🧹 Nitpick comments (3)
tests/integration/defs/accuracy/test_llm_api_pytorch.py (1)

1192-1194: Deduplicate dynamic MoE backend selection.

The same DEEPGEMM/CUTLASS selection logic repeats. Define a module-level constant or helper and reuse to reduce churn and risk of divergence.

Add once near imports:

+MOE_BACKEND_DEFAULT = "DEEPGEMM" if get_sm_version() >= 100 else "CUTLASS"

Then replace occurrences like:

-            moe_config=MoeConfig(
-                backend="DEEPGEMM" if get_sm_version() >= 100 else "CUTLASS"),
+            moe_config=MoeConfig(backend=MOE_BACKEND_DEFAULT),

Also applies to: 1282-1284, 1307-1308, 1350-1352

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

288-289: Expose enable_attn_nvfp4_output via config/env to avoid double-gating confusion.

Right now it’s always True and separate from support_nvfp4_output() (backend/env). Consider plumbing a config flag (defaulting to backend support/env) to allow user-level control.


371-385: Pass out_scale_sf=None when NVFP4 output is disabled.

Minor clarity: avoid sending a non-None scale factor when enable_attn_nvfp4_output is False (e.g., torch.compile path).

Apply this diff:

-            out_scale=self.out_scale,
-            out_scale_sf=self.out_scale_sf,
+            out_scale=self.out_scale,
+            out_scale_sf=(self.out_scale_sf if enable_attn_nvfp4_output else None),
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 6a5806b and 2f1bd9c.

📒 Files selected for processing (7)
  • cpp/tensorrt_llm/common/attentionOp.cpp (1 hunks)
  • cpp/tensorrt_llm/common/attentionOp.h (1 hunks)
  • cpp/tensorrt_llm/kernels/trtllmGenKernels/fmha/fmhaKernels.h (1 hunks)
  • cpp/tensorrt_llm/thop/attentionOp.cpp (3 hunks)
  • tensorrt_llm/_torch/modules/attention.py (10 hunks)
  • tensorrt_llm/executor/worker.py (1 hunks)
  • tests/integration/defs/accuracy/test_llm_api_pytorch.py (9 hunks)
🧰 Additional context used
📓 Path-based instructions (8)
**/*.{h,hpp,hh,hxx,cpp,cxx,cc,cu,cuh}

📄 CodeRabbit inference engine (CODING_GUIDELINES.md)

**/*.{h,hpp,hh,hxx,cpp,cxx,cc,cu,cuh}: Namespace closing braces must include a trailing comment with the namespace name (e.g., '} // namespace foo').
Prefer const or constexpr variables over #define for constants.
Declare variables that are not modified after initialization as const.
Avoid magic literals in code; except for 0, nullptr, true, false. Use named constants for comparisons and logic.
Use Allman brace style for formatting.
Place the semicolon of an empty for/while loop on a new line.
Bodies of switch/while/do-while/for must be compound statements (brace-delimited), and if/else must always be followed by brace-delimited statements.
Type names (e.g., classes) must be CamelCase starting with an uppercase letter (e.g., FooBar).
Local variables, methods, and namespaces use lowerCamelCase (e.g., localFooBar).
Non-magic-number global variables that are non-static and not in an anonymous namespace must be lowerCamelCase prefixed with 'g' (e.g., gDontUseGlobalFoos).
Non-magic-number globals that are static or in an anonymous namespace use lowerCamelCase prefixed with 's' (e.g., sMutableStaticGlobal).
Locally visible static variables use lowerCamelCase with 's' prefix (e.g., static std::once_flag sFlag).
Private/protected member variables use 'm' prefix with CamelCase (e.g., mNbFooValues). Public members may omit, but 'm' is encouraged for clarity.
Constants (enums, global constants, static constants, and function-scope magic/literal constants) use uppercase SNAKE_CASE with 'k' prefix (e.g., kDIGIT_NUM).
Function-scope constants that are not magic numbers or literals are named like non-constant variables (e.g., bool const pass = a && b).
If macros are necessary, name them in UPPER_SNAKE_CASE (e.g., FOO_VERSION) and prefer constants over #define.
Use LLVM clang-format; wrap lines at a maximum of 120 columns; use '// clang-format off/on' sparingly with justification.
Use smart pointers for heap allocations; prefer unique_ptr for sole ownership, shared_ptr for shared...

Files:

  • cpp/tensorrt_llm/common/attentionOp.cpp
  • cpp/tensorrt_llm/thop/attentionOp.cpp
  • cpp/tensorrt_llm/kernels/trtllmGenKernels/fmha/fmhaKernels.h
  • cpp/tensorrt_llm/common/attentionOp.h
**/*.{cpp,cxx,cc,cu,h,hpp,hh,hxx,cuh}

📄 CodeRabbit inference engine (CODING_GUIDELINES.md)

C++ filenames should be lowerCamelCase (first letter lowercase) and must be case-insensitive unique within a compilation target.

Files:

  • cpp/tensorrt_llm/common/attentionOp.cpp
  • cpp/tensorrt_llm/thop/attentionOp.cpp
  • cpp/tensorrt_llm/kernels/trtllmGenKernels/fmha/fmhaKernels.h
  • cpp/tensorrt_llm/common/attentionOp.h
**/*.{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:

  • cpp/tensorrt_llm/common/attentionOp.cpp
  • tensorrt_llm/executor/worker.py
  • cpp/tensorrt_llm/thop/attentionOp.cpp
  • cpp/tensorrt_llm/kernels/trtllmGenKernels/fmha/fmhaKernels.h
  • tensorrt_llm/_torch/modules/attention.py
  • tests/integration/defs/accuracy/test_llm_api_pytorch.py
  • cpp/tensorrt_llm/common/attentionOp.h
**/*.{h,hpp,hh,hxx,cpp,cxx,cc}

📄 CodeRabbit inference engine (CODING_GUIDELINES.md)

**/*.{h,hpp,hh,hxx,cpp,cxx,cc}: Prefer anonymous namespaces over 'static' for internal linkage of functions.
All templates (class/function/member/static) must be instantiated at least once; non-POD classes should have private data members.

Files:

  • cpp/tensorrt_llm/common/attentionOp.cpp
  • cpp/tensorrt_llm/thop/attentionOp.cpp
  • cpp/tensorrt_llm/kernels/trtllmGenKernels/fmha/fmhaKernels.h
  • cpp/tensorrt_llm/common/attentionOp.h
**/*.{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:

  • cpp/tensorrt_llm/common/attentionOp.cpp
  • tensorrt_llm/executor/worker.py
  • cpp/tensorrt_llm/thop/attentionOp.cpp
  • cpp/tensorrt_llm/kernels/trtllmGenKernels/fmha/fmhaKernels.h
  • tensorrt_llm/_torch/modules/attention.py
  • tests/integration/defs/accuracy/test_llm_api_pytorch.py
  • cpp/tensorrt_llm/common/attentionOp.h
**/*.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/executor/worker.py
  • tensorrt_llm/_torch/modules/attention.py
  • tests/integration/defs/accuracy/test_llm_api_pytorch.py
**/*.{h,hpp,hh,hxx}

📄 CodeRabbit inference engine (CODING_GUIDELINES.md)

Document new class interfaces and function prototypes with Doxygen; use //! for single-line and //!< for members.

Files:

  • cpp/tensorrt_llm/kernels/trtllmGenKernels/fmha/fmhaKernels.h
  • cpp/tensorrt_llm/common/attentionOp.h
**/*.{h,hpp,hh,hxx,cuh}

📄 CodeRabbit inference engine (CODING_GUIDELINES.md)

Use include guards named 'TRTLLM_<FILE_NAME_IN_CAPS_WITH_UNDERSCORES>_H' (no leading or trailing underscore; directory names excluded).

Files:

  • cpp/tensorrt_llm/kernels/trtllmGenKernels/fmha/fmhaKernels.h
  • cpp/tensorrt_llm/common/attentionOp.h
🧠 Learnings (3)
📚 Learning: 2025-08-14T21:04:50.248Z
Learnt from: thorjohnsen
PR: NVIDIA/TensorRT-LLM#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:

  • cpp/tensorrt_llm/thop/attentionOp.cpp
📚 Learning: 2025-08-26T09:37:10.463Z
Learnt from: jiaganc
PR: NVIDIA/TensorRT-LLM#7031
File: tensorrt_llm/bench/dataclasses/configuration.py:90-104
Timestamp: 2025-08-26T09:37:10.463Z
Learning: In TensorRT-LLM's bench configuration, the `get_pytorch_perf_config()` method returns `self.pytorch_config` which is a Dict[str, Any] that can contain default values including `cuda_graph_config`, making the fallback `llm_args["cuda_graph_config"]` safe to use.

Applied to files:

  • tests/integration/defs/accuracy/test_llm_api_pytorch.py
📚 Learning: 2025-08-26T09:37:10.463Z
Learnt from: jiaganc
PR: NVIDIA/TensorRT-LLM#7031
File: tensorrt_llm/bench/dataclasses/configuration.py:90-104
Timestamp: 2025-08-26T09:37:10.463Z
Learning: In TensorRT-LLM, the `get_pytorch_perf_config()` method returns `self.pytorch_config` which can contain default `cuda_graph_config` values, so `llm_args` may already have this config before the extra options processing.

Applied to files:

  • tests/integration/defs/accuracy/test_llm_api_pytorch.py
🧬 Code graph analysis (4)
tensorrt_llm/executor/worker.py (1)
tensorrt_llm/executor/result.py (1)
  • prompt_token_ids (525-526)
cpp/tensorrt_llm/thop/attentionOp.cpp (1)
tensorrt_llm/models/modeling_utils.py (3)
  • quant_mode (156-163)
  • quant_mode (301-303)
  • quant_mode (543-544)
tensorrt_llm/_torch/modules/attention.py (4)
tensorrt_llm/_torch/modules/linear.py (16)
  • create_weights (218-221)
  • create_weights (273-283)
  • create_weights (316-334)
  • create_weights (452-472)
  • create_weights (553-576)
  • create_weights (665-698)
  • create_weights (821-844)
  • create_weights (933-952)
  • create_weights (1049-1076)
  • create_weights (1192-1232)
  • create_weights (1448-1451)
  • create_weights (1574-1583)
  • has_fp8_qdq (1592-1595)
  • has_nvfp4 (1610-1613)
  • has_fp8_block_scales (1604-1607)
  • has_fp8_rowwise (1598-1601)
tensorrt_llm/_torch/attention_backend/interface.py (1)
  • support_nvfp4_output (621-622)
tensorrt_llm/_torch/attention_backend/trtllm.py (1)
  • support_nvfp4_output (1218-1221)
tensorrt_llm/quantization/mode.py (1)
  • has_fp8_kv_cache (163-164)
tests/integration/defs/accuracy/test_llm_api_pytorch.py (3)
tensorrt_llm/llmapi/llm_args.py (1)
  • MoeConfig (168-196)
tensorrt_llm/layers/moe.py (1)
  • MoeConfig (104-140)
tests/integration/defs/conftest.py (1)
  • get_sm_version (1857-1860)
⏰ 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)
tests/integration/defs/accuracy/test_llm_api_pytorch.py (1)

1168-1168: Decorator change to skip_pre_hopper looks good.

Consistent with other Hopper/Blackwell gates in this file.

Also applies to: 1269-1269, 1294-1294, 1321-1321, 1439-1439

cpp/tensorrt_llm/common/attentionOp.h (2)

398-398: LGTM! Properly integrated FP8 Context MLA flag.

The addition of mFP8ContextMLA flag is consistent with the existing naming convention and aligns with the FP8 MLA support mentioned in the PR objectives.


453-453: No additional initialization needed for mFP8ContextMLA
mFP8ContextMLA has an inline default initializer (= false) in its declaration and no explicit constructors override it. All instances and deserialization paths will use this, so no further action is required.

cpp/tensorrt_llm/common/attentionOp.cpp (2)

2524-2524: Good relaxation for FP8 MLA context support.

The change from checking both mFP8ContextFMHA and mDenseContextFMHA to only checking mDenseContextFMHA properly enables the combination of MLA with FP8 context FMHA, which aligns with the PR's objective to support FP8 Context MLA integration.


2596-2600: Verify and document BF16 output requirement for FP8 Context MLA
Confirm that BF16 output is indeed required when mFP8ContextMLA is enabled and add a code comment or project-level documentation explaining why fmhaParams.dataTypeOut must be set to DATA_TYPE_BF16 in this case, as no existing references were found.

cpp/tensorrt_llm/thop/attentionOp.cpp (3)

492-492: Good modernization with std::make_shared.

Replacing runner.reset(new Runner<...>()) with std::make_shared<Runner<...>>() is a best practice improvement that provides better exception safety and enables potential memory optimizations.

Also applies to: 495-495, 501-501, 507-507, 514-514, 518-518, 523-523


541-541: Verify mKVCacheQuantMode order change
Automated search didn’t reveal any direct dependencies on the previous initialization order; manually confirm that no downstream logic reads mKVCacheQuantMode before it’s assigned here.


590-592: Enable FP8 MLA for SM100
NVIDIA Blackwell (SM100) provides native FP8 mixed-precision tensor-core support (CUDA Toolkit 12.8), so enabling FP8 MLA context for SM100 alongside SM120 is valid.

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

86-99: In-place op correctly disables NVFP4 output under torch.compile.

Good defensive gating for TRTLLM + torch.compile incompatibility. No change requested.


842-844: MLA: explicit BF16 output stance is clear.

Setting self.out_scale = None documents the BF16 output for MLA despite FP8 context/generation. Good.


1057-1059: Consistent out_scale plumbed through MLA paths.

Forward-context/cached/chunked and generation paths consistently pass out_scale=self.out_scale (currently None), aligning with the BF16 decision. LGTM.

Also applies to: 1121-1123, 1215-1225, 1263-1272, 1371-1374


328-331: has_fp8_kv_cache is implemented on both TRTLLM and FLASHINFER backends; no changes required.

Comment on lines 298 to 308
self.out_scale = None
self.out_scale_sf = None
self.o_proj.create_weights()
self.has_quant_scale = (self.o_proj.has_fp8_qdq or self.o_proj.has_nvfp4
or self.o_proj.has_fp8_block_scales
or self.o_proj.has_fp8_rowwise)
if self.has_quant_scale:
self.out_scale = self.o_proj.inv_input_scale.data
if self.o_proj.has_nvfp4 and self.support_nvfp4_output and self.enable_attn_nvfp4_output:
self.out_scale_sf = self.o_proj.input_scale.data

Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Avoid .data; use detach() to prevent autograd pitfalls and stale references.

Accessing parameters via .data is unsafe. Use detach() (or the Parameter tensor directly) so device moves and loads remain coherent.

Apply this diff:

-        self.out_scale = None
-        self.out_scale_sf = None
+        self.out_scale = None
+        self.out_scale_sf = None
         self.o_proj.create_weights()
         self.has_quant_scale = (self.o_proj.has_fp8_qdq or self.o_proj.has_nvfp4
                                 or self.o_proj.has_fp8_block_scales
                                 or self.o_proj.has_fp8_rowwise)
         if self.has_quant_scale:
-            self.out_scale = self.o_proj.inv_input_scale.data
-        if self.o_proj.has_nvfp4 and self.support_nvfp4_output and self.enable_attn_nvfp4_output:
-            self.out_scale_sf = self.o_proj.input_scale.data
+            self.out_scale = self.o_proj.inv_input_scale.detach()
+        if (self.o_proj.has_nvfp4 and self.support_nvfp4_output
+                and self.enable_attn_nvfp4_output):
+            self.out_scale_sf = self.o_proj.input_scale.detach()
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
self.out_scale = None
self.out_scale_sf = None
self.o_proj.create_weights()
self.has_quant_scale = (self.o_proj.has_fp8_qdq or self.o_proj.has_nvfp4
or self.o_proj.has_fp8_block_scales
or self.o_proj.has_fp8_rowwise)
if self.has_quant_scale:
self.out_scale = self.o_proj.inv_input_scale.data
if self.o_proj.has_nvfp4 and self.support_nvfp4_output and self.enable_attn_nvfp4_output:
self.out_scale_sf = self.o_proj.input_scale.data
self.out_scale = None
self.out_scale_sf = None
self.o_proj.create_weights()
self.has_quant_scale = (self.o_proj.has_fp8_qdq or self.o_proj.has_nvfp4
or self.o_proj.has_fp8_block_scales
or self.o_proj.has_fp8_rowwise)
if self.has_quant_scale:
self.out_scale = self.o_proj.inv_input_scale.detach()
if (self.o_proj.has_nvfp4 and self.support_nvfp4_output
and self.enable_attn_nvfp4_output):
self.out_scale_sf = self.o_proj.input_scale.detach()
🤖 Prompt for AI Agents
In tensorrt_llm/_torch/modules/attention.py around lines 298 to 308, the code
reads tensor attributes using the unsafe .data property; replace those usages
with .detach() (or the Parameter tensor directly) to avoid autograd pitfalls and
stale references — specifically set self.out_scale =
self.o_proj.inv_input_scale.detach() when has_quant_scale is true, and set
self.out_scale_sf = self.o_proj.input_scale.detach() when nvfp4 output is used
(optionally .clone() after detach() if you need an independent copy).

@tensorrt-cicd
Copy link
Collaborator

PR_Github #17843 [ run ] completed with state SUCCESS
/LLM/release-1.1.0rc2/L0_MergeRequest_PR pipeline #86 completed with status: 'FAILURE'

Signed-off-by: Yuxian Qiu <142763828+yuxianq@users.noreply.github.com>
@yuxianq yuxianq requested a review from a team as a code owner September 7, 2025 03:41
@yuxianq
Copy link
Collaborator Author

yuxianq commented Sep 7, 2025

/bot run --disable-fail-fast

@tensorrt-cicd
Copy link
Collaborator

PR_Github #17910 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #17910 [ run ] completed with state SUCCESS
/LLM/release-1.1.0rc2/L0_MergeRequest_PR pipeline #88 completed with status: 'SUCCESS'

Copy link
Collaborator

@Superjomn Superjomn left a comment

Choose a reason for hiding this comment

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

LGTM on the llmapi changes

@yuxianq yuxianq requested a review from peaceh-nv September 8, 2025 01:57
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.

5 participants