Skip to content

[TRTLLM-12807][feat] Add multiple FMHA library support to TRTLLM attention backend - #15204

Merged
yuxianq merged 8 commits into
NVIDIA:mainfrom
yuxianq:feat/trtllm-12807-fmha-libs
Jun 18, 2026
Merged

[TRTLLM-12807][feat] Add multiple FMHA library support to TRTLLM attention backend#15204
yuxianq merged 8 commits into
NVIDIA:mainfrom
yuxianq:feat/trtllm-12807-fmha-libs

Conversation

@yuxianq

@yuxianq yuxianq commented Jun 10, 2026

Copy link
Copy Markdown
Collaborator

Description

JIRA: https://jirasw.nvidia.com/browse/TRTLLM-12807

Refactor the TRTLLM PyTorch attention FMHA implementation into explicit FMHA library classes under tensorrt_llm/_torch/attention_backend/fmha/.

This change:

  • Adds the Fmha interface and PhasedFmha helper for context/generation and MHA/MLA dispatch.
  • Moves the FlashInfer TRTLLM-Gen path into FlashInferTrtllmGenFmha.
  • Moves the thop.attention path into FallbackFmha.
  • Adds FMHA library registry support for TLLM_FMHA_LIBS.
  • Removes the old attention_backend/trtllm_gen.py compatibility wrapper.
  • Updates the attention developer guide for the new FMHA package layout.

Test Coverage

  • python3 -m pytest -q tests/unittest/_torch/attention_backend/test_attention_op_sync.py
  • B200: tests/integration/defs/accuracy/test_llm_api_pytorch.py::TestQwen3_8B::test_bf16[latency]

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)

  • If PR introduces API changes, an appropriate PR label is added - either api-compatible or api-breaking. For api-breaking, include BREAKING in the PR title.

  • Any new dependencies have been scanned for license and vulnerabilities

  • CODEOWNERS updated if ownership changes

  • Documentation updated as needed

  • Update tava architecture diagram if there is a significant design change in PR.

  • 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

To see a list of available CI bot commands, please comment /bot help.

@yuxianq
yuxianq marked this pull request as ready for review June 10, 2026 06:58
@yuxianq
yuxianq requested review from a team as code owners June 10, 2026 06:58
@yuxianq
yuxianq requested review from brb-nv and mikeiovine June 10, 2026 06:58
@yuxianq

yuxianq commented Jun 10, 2026

Copy link
Copy Markdown
Collaborator Author

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

@yuxianq
yuxianq requested a review from yihwang-nv June 10, 2026 07:01
@yuxianq yuxianq changed the title [TRTLLM-12807][feat] Refactor TRTLLM attention FMHA libraries [TRTLLM-12807][feat] Add multiple FMHA library support to TRTLLM attention backend Jun 10, 2026
@coderabbitai

coderabbitai Bot commented Jun 10, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR introduces a pluggable FMHA (Fused Multi-Head Attention) backend system to TensorRT-LLM's attention implementation. It replaces the hardcoded TRTLLM-Gen and thop.attention dispatch paths with an ordered registry of backend implementations selected via the TLLM_FMHA_LIBS environment variable. The refactor includes an abstract Fmha interface, a phased dispatcher base class splitting context/generation, concrete implementations (fallback and FlashInfer), and updates to TrtllmAttention.forward to iterate through enabled backends.

Changes

FMHA Backend Architecture & Dispatch

Layer / File(s) Summary
FMHA Interface & Registry
tensorrt_llm/_torch/attention_backend/fmha/interface.py, tensorrt_llm/_torch/attention_backend/fmha/registry.py, tensorrt_llm/_torch/attention_backend/fmha/__init__.py
Abstract Fmha base class defines the common contract: is_available(), is_supported(), and forward(). Registry system (FMHA_LIBS, DEFAULT_FMHA_LIBS, get_enabled_fmha_lib_classes()) parses TLLM_FMHA_LIBS to select enabled backends from the registered set. Package __init__.py re-exports all public symbols.
Phased Attention Dispatcher
tensorrt_llm/_torch/attention_backend/fmha/phased.py
FmhaParams dataclass packages attention inputs, outputs, and runtime shape/windowing. PhasedFmha base dispatcher splits attention into context and generation phases based on token counts, computes per-phase tensors and parameters, and delegates execution to phase-specific runner methods (currently NotImplementedError stubs).
Concrete FMHA Backends
tensorrt_llm/_torch/attention_backend/fmha/fallback.py, tensorrt_llm/_torch/attention_backend/fmha/flashinfer_trtllm_gen.py
FallbackFmha maps attention metadata and args to a direct thop.attention() call. FlashInferTrtllmGenFmha (refactored from old in-file class) extends PhasedFmha with FlashInfer-specific support checking (is_available gates environment/ops/SM/head-count; is_supported validates dtype/config), and workspace preparation.
TrtllmAttention Integration
tensorrt_llm/_torch/attention_backend/trtllm.py
create_fmha_libs() instantiates enabled backend objects during init. forward() refactored to enforce SM90 paged-context, run sparse/MLA setup, then dispatch through enabled FMHA libraries, calling the first that reports support or raising RuntimeError if none match. Removes prior hardcoded _run path and TRTLLM-Gen/thop constants.
Documentation & Tests
tensorrt_llm/_torch/modules/ATTENTION_DEVELOPER_GUIDE.md, tests/unittest/_torch/attention_backend/test_attention_op_sync.py
Developer guide updated to explain FMHA library dispatch, TLLM_FMHA_LIBS selection, and internal module structure. Sync test refactored to verify thop.attention() call site within FallbackFmha.forward and updated AST resolution to target attn, metadata, and forward_args parameter roots.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Suggested reviewers

  • schetlur-nv
  • tcherckez-nvidia
  • bo-nv
  • fredricz-20070104
  • juney-nvidia
  • venkywonka
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 20.93% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly summarizes the main change: adding multiple FMHA library support to the TRTLLM attention backend through refactoring.
Description check ✅ Passed The description covers the main objectives, key changes, test coverage examples, and includes a completed PR checklist addressing guidelines, testing, and documentation.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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/attention_backend/fmha/flashinfer_trtllm_gen.py (1)

689-695: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Dead code: sink_token_length check is always False.

sink_token_length is hardcoded to 0, making the subsequent check if sink_token_length != 0 unreachable. Either remove this dead code or replace with actual StreamingLLM detection.

🧹 Proposed fix (remove dead code)
-            sink_token_length = 0
-            if sink_token_length != 0:
-                return (
-                    False,
-                    f"[Generation] StreamingLLM "
-                    f"(sink_token_length={sink_token_length}) is not supported.",
-                )
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tensorrt_llm/_torch/attention_backend/fmha/flashinfer_trtllm_gen.py` around
lines 689 - 695, The check for streaming support contains dead code: the local
variable sink_token_length is hardcoded to 0 so the subsequent if
(sink_token_length != 0) is unreachable; either remove the sink_token_length
declaration and the entire conditional branch, or replace it with a real
StreamingLLM detection (e.g., inspect the LLM instance or a passed-in parameter
such as sink_token_length/streaming flag) so the code actually detects streaming
LLMs; update references around the sink_token_length conditional in
flashinfer_trtllm_gen.py accordingly and ensure any returned message still uses
the same wording if you keep the branch.
🧹 Nitpick comments (2)
tensorrt_llm/_torch/attention_backend/fmha/registry.py (1)

72-73: 💤 Low value

Consider caching the parsed result for hot-path efficiency.

get_enabled_fmha_lib_classes() re-parses TLLM_FMHA_LIBS on every call. If the registry dispatch iterates through backends per-forward, this could add overhead. Consider caching the result (e.g., via @lru_cache(maxsize=1) or a module-level singleton) if the env var is not expected to change at runtime.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tensorrt_llm/_torch/attention_backend/fmha/registry.py` around lines 72 - 73,
get_enabled_fmha_lib_classes currently calls _parse_fmha_libs_env on every
invocation which can be expensive on hot paths; modify it to cache the parsed
result (e.g., decorate get_enabled_fmha_lib_classes with
functools.lru_cache(maxsize=1) or compute once into a module-level variable) so
subsequent calls return the cached list of FMHA classes from FMHA_LIBS without
re-parsing the TLLM_FMHA_LIBS env; ensure the cached value is a list of FmhaCls
as returned today and reference get_enabled_fmha_lib_classes,
_parse_fmha_libs_env and FMHA_LIBS when locating the code to change.
tensorrt_llm/_torch/attention_backend/trtllm.py (1)

1591-1593: 💤 Low value

Optional: Remove extraneous space in f-string format spec.

The format spec {skipped_blocks / total_blocks * 100: .2f} includes a space before .2f, which renders as " 12.34%" with a leading space. Consider :.2f for cleaner output unless the space is intentional for alignment.

♻️ Proposed formatting tweak
-                print(f"SKIP_SOFTMAX_STAT: layer{self.layer_idx}: "
-                      f"{skipped_blocks} / {total_blocks}"
-                      f" = {skipped_blocks / total_blocks * 100: .2f}%")
+                print(f"SKIP_SOFTMAX_STAT: layer{self.layer_idx}: "
+                      f"{skipped_blocks} / {total_blocks}"
+                      f" = {skipped_blocks / total_blocks * 100:.2f}%")
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tensorrt_llm/_torch/attention_backend/trtllm.py` around lines 1591 - 1593,
The f-string used in the logging print currently uses a space in the format
specifier "{skipped_blocks / total_blocks * 100: .2f}" which yields a leading
space; update that f-string to use "{skipped_blocks / total_blocks * 100:.2f}"
(referencing the same print that includes self.layer_idx, skipped_blocks and
total_blocks) so the percentage renders without the extra leading space.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@tensorrt_llm/_torch/attention_backend/fmha/flashinfer_trtllm_gen.py`:
- Around line 689-695: The check for streaming support contains dead code: the
local variable sink_token_length is hardcoded to 0 so the subsequent if
(sink_token_length != 0) is unreachable; either remove the sink_token_length
declaration and the entire conditional branch, or replace it with a real
StreamingLLM detection (e.g., inspect the LLM instance or a passed-in parameter
such as sink_token_length/streaming flag) so the code actually detects streaming
LLMs; update references around the sink_token_length conditional in
flashinfer_trtllm_gen.py accordingly and ensure any returned message still uses
the same wording if you keep the branch.

---

Nitpick comments:
In `@tensorrt_llm/_torch/attention_backend/fmha/registry.py`:
- Around line 72-73: get_enabled_fmha_lib_classes currently calls
_parse_fmha_libs_env on every invocation which can be expensive on hot paths;
modify it to cache the parsed result (e.g., decorate
get_enabled_fmha_lib_classes with functools.lru_cache(maxsize=1) or compute once
into a module-level variable) so subsequent calls return the cached list of FMHA
classes from FMHA_LIBS without re-parsing the TLLM_FMHA_LIBS env; ensure the
cached value is a list of FmhaCls as returned today and reference
get_enabled_fmha_lib_classes, _parse_fmha_libs_env and FMHA_LIBS when locating
the code to change.

In `@tensorrt_llm/_torch/attention_backend/trtllm.py`:
- Around line 1591-1593: The f-string used in the logging print currently uses a
space in the format specifier "{skipped_blocks / total_blocks * 100: .2f}" which
yields a leading space; update that f-string to use "{skipped_blocks /
total_blocks * 100:.2f}" (referencing the same print that includes
self.layer_idx, skipped_blocks and total_blocks) so the percentage renders
without the extra leading space.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Enterprise

Run ID: 0b24c50a-926b-48db-b498-d0d3fa0c8dd1

📥 Commits

Reviewing files that changed from the base of the PR and between 31e730a and 5afc19b.

📒 Files selected for processing (9)
  • tensorrt_llm/_torch/attention_backend/fmha/__init__.py
  • tensorrt_llm/_torch/attention_backend/fmha/fallback.py
  • tensorrt_llm/_torch/attention_backend/fmha/flashinfer_trtllm_gen.py
  • tensorrt_llm/_torch/attention_backend/fmha/interface.py
  • tensorrt_llm/_torch/attention_backend/fmha/phased.py
  • tensorrt_llm/_torch/attention_backend/fmha/registry.py
  • tensorrt_llm/_torch/attention_backend/trtllm.py
  • tensorrt_llm/_torch/modules/ATTENTION_DEVELOPER_GUIDE.md
  • tests/unittest/_torch/attention_backend/test_attention_op_sync.py

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #53256 [ run ] triggered by Bot. Commit: 5afc19b Link to invocation

@yuxianq
yuxianq requested review from DanBlanaru, QiJune and bobboli and removed request for brb-nv and mikeiovine June 10, 2026 07:37
Comment thread tensorrt_llm/_torch/attention_backend/fmha/phased.py Outdated
@yuxianq
yuxianq force-pushed the feat/trtllm-12807-fmha-libs branch from 5afc19b to 36d5f74 Compare June 10, 2026 08:36
@yuxianq

yuxianq commented Jun 10, 2026

Copy link
Copy Markdown
Collaborator Author

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

@yuxianq
yuxianq force-pushed the feat/trtllm-12807-fmha-libs branch from 36d5f74 to 2b6564c Compare June 10, 2026 08:38
@yuxianq

yuxianq commented Jun 10, 2026

Copy link
Copy Markdown
Collaborator Author

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

Comment thread tensorrt_llm/_torch/attention_backend/fmha/phased.py
Comment thread tensorrt_llm/_torch/attention_backend/fmha/phased.py Outdated
@bobboli

bobboli commented Jun 10, 2026

Copy link
Copy Markdown
Collaborator

If FlashInferTrtllmGenFmha and FallbackFmha are meant to be internal to TRTLLM attention backend, should we consider file name like fmha/_fallback.py fmha/_flashinfer_trtllm_gen.py, or maybe consider making a dir for trtllm and put them underneath?

@bobboli

bobboli commented Jun 10, 2026

Copy link
Copy Markdown
Collaborator

And what about fmha_v2? Will it be scoped in this design?

@yuxianq
yuxianq force-pushed the feat/trtllm-12807-fmha-libs branch from 2b6564c to aad1559 Compare June 10, 2026 08:50
@yuxianq

yuxianq commented Jun 10, 2026

Copy link
Copy Markdown
Collaborator Author

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

Comment thread tensorrt_llm/_torch/attention_backend/fmha/phased.py Outdated
@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #53277 [ run ] triggered by Bot. Commit: aad1559 Link to invocation

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #54751 [ run ] completed with state FAILURE. Commit: e868fec
/LLM/main/L0_MergeRequest_PR pipeline #43770 completed with status: 'FAILURE'

CI Report

⚠️ Action Required:

  • Please check the failed tests and fix your PR
  • If you cannot view the failures, ask the CI triggerer to share details
  • Once fixed, request an NVIDIA team member to trigger CI again

CI Agent Failure Analysis

Link to invocation

@yuxianq
yuxianq requested a review from a team as a code owner June 17, 2026 08:49
@yuxianq
yuxianq requested a review from joyang-nv June 17, 2026 08:49

yuxianq commented Jun 17, 2026

Copy link
Copy Markdown
Collaborator Author

/bot run --disable-fail-fast

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #54813 [ run ] triggered by Bot. Commit: ff1973c Link to invocation

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #54813 [ run ] completed with state SUCCESS. Commit: ff1973c
/LLM/main/L0_MergeRequest_PR pipeline #43827 completed with status: 'FAILURE'

CI Report

⚠️ Action Required:

  • Please check the failed tests and fix your PR
  • If you cannot view the failures, ask the CI triggerer to share details
  • Once fixed, request an NVIDIA team member to trigger CI again

Link to invocation

yuxianq added 8 commits June 18, 2026 02:18
Signed-off-by: Yuxian Qiu <142763828+yuxianq@users.noreply.github.com>
Signed-off-by: Yuxian Qiu <142763828+yuxianq@users.noreply.github.com>
Signed-off-by: Yuxian Qiu <142763828+yuxianq@users.noreply.github.com>
Signed-off-by: Yuxian Qiu <142763828+yuxianq@users.noreply.github.com>
Signed-off-by: Yuxian Qiu <142763828+yuxianq@users.noreply.github.com>
Signed-off-by: Yuxian Qiu <142763828+yuxianq@users.noreply.github.com>
Signed-off-by: Yuxian Qiu <142763828+yuxianq@users.noreply.github.com>
Signed-off-by: Yuxian Qiu <142763828+yuxianq@users.noreply.github.com>
@yuxianq
yuxianq force-pushed the feat/trtllm-12807-fmha-libs branch from ff1973c to 79d1e09 Compare June 18, 2026 02:19

yuxianq commented Jun 18, 2026

Copy link
Copy Markdown
Collaborator Author

/bot run --disable-fail-fast

@yuxianq
yuxianq removed request for a team and joyang-nv June 18, 2026 02:21
@yuxianq
yuxianq enabled auto-merge (squash) June 18, 2026 02:23
@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #54900 [ run ] triggered by Bot. Commit: 79d1e09 Link to invocation

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #54900 [ run ] completed with state FAILURE. Commit: 79d1e09
/LLM/main/L0_MergeRequest_PR pipeline #43904 completed with status: 'FAILURE'

CI Report

⚠️ Action Required:

  • Please check the failed tests and fix your PR
  • If you cannot view the failures, ask the CI triggerer to share details
  • Once fixed, request an NVIDIA team member to trigger CI again

CI Agent Failure Analysis

Link to invocation

@yuxianq

yuxianq commented Jun 18, 2026

Copy link
Copy Markdown
Collaborator Author

/bot run --disable-fail-fast

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #54919 [ run ] triggered by Bot. Commit: 79d1e09 Link to invocation

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #54919 [ run ] completed with state SUCCESS. Commit: 79d1e09
/LLM/main/L0_MergeRequest_PR pipeline #43920 completed with status: 'SUCCESS'

CI Report

Link to invocation

@yuxianq
yuxianq merged commit 1aa232a into NVIDIA:main Jun 18, 2026
8 checks passed
xinhe-nv pushed a commit to tensorrt-cicd/TensorRT-LLM that referenced this pull request Jun 23, 2026
…ntion backend (NVIDIA#15204)

Signed-off-by: Yuxian Qiu <142763828+yuxianq@users.noreply.github.com>
Signed-off-by: GitLab CI Bot <gitlab-ci@nvidia.com>
xinhe-nv pushed a commit to tensorrt-cicd/TensorRT-LLM that referenced this pull request Jun 24, 2026
…ntion backend (NVIDIA#15204)

Signed-off-by: Yuxian Qiu <142763828+yuxianq@users.noreply.github.com>
Signed-off-by: GitLab CI Bot <gitlab-ci@nvidia.com>
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