Skip to content

[https://nvbugs/6322045][fix] In triton_context, when max_q_len == max_kv_len (so cache_lens=0) and… - #15479

Closed
tensorrt-cicd wants to merge 3 commits into
NVIDIA:mainfrom
tensorrt-cicd:repair-bot-bug6322045
Closed

[https://nvbugs/6322045][fix] In triton_context, when max_q_len == max_kv_len (so cache_lens=0) and…#15479
tensorrt-cicd wants to merge 3 commits into
NVIDIA:mainfrom
tensorrt-cicd:repair-bot-bug6322045

Conversation

@tensorrt-cicd

@tensorrt-cicd tensorrt-cicd commented Jun 18, 2026

Copy link
Copy Markdown
Collaborator

Summary

  • Root cause: SDPA with explicit attn_mask + enable_gqa=True forces the math backend, which materializes an 8 GiB fp32 score tensor at the 8192-token Llama-3.1-8B prefill warmup and OOMs on the 44 GiB L40S.
  • Fix: In triton_context, when max_q_len == max_kv_len (so cache_lens=0) and projected scratch > 2 GiB, drop attn_mask and use is_causal=True; keep the explicit-mask path otherwise so numerics are unchanged for short prefills and any cache-reuse case.
  • Automated fix generated by repair-bot

Test plan

  • Verify fix on the same GPU type as the original failure
  • Check for regressions in related tests

Links

Summary

  • Fixes an OOM in the triton_context attention path during Llama-3.1-8B prefill warmup at 8192 tokens on L40S GPUs.
  • Uses fused causal SDPA for equal-length workloads when estimated scratch memory exceeds 2 GiB.
  • Preserves the explicit attention-mask path for shorter prefills and cache-reuse workloads.
  • Removes the L40S test_auto_dtype waivers for the triton-False-1 and trtllm-False-1 configurations.

Dev Engineer Review

  • The SDPA change matches the intended memory optimization.
  • The explicit-mask path remains available for workloads that require padding or cache reuse.
  • The waiver removal is correctly scoped to the two L40S test_auto_dtype entries.
  • Follow-up is required for the trtllm-False-1 waiver because that backend does not exercise triton_context. The full L40S pipeline should validate both configurations.

QA Engineer Review

  • Modified tests/integration/test_lists/waives.txt.
  • Removed the L40S TestLlama3_1_8B::test_auto_dtype entries for triton-False-1 and trtllm-False-1.
  • No test-db or QA coverage data is provided.
  • Verdict: needs follow-up.

@coderabbitai

coderabbitai Bot commented Jun 18, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Enterprise

Run ID: 33e5d310-6574-42ec-94d4-f3051c6d8722

📥 Commits

Reviewing files that changed from the base of the PR and between 369cc0b and 6d28ef4.

📒 Files selected for processing (1)
  • tests/integration/test_lists/waives.txt
💤 Files with no reviewable changes (1)
  • tests/integration/test_lists/waives.txt

Walkthrough

The SDPA path now uses fused causal attention for large equal-length workloads when estimated scratch usage exceeds 2 GiB. Other workloads retain the combined padding and causal mask. Two related L40S test waiver entries are removed.

Changes

SDPA Causal Masking and Test Waiver

Layer / File(s) Summary
Conditional is_causal SDPA masking in triton_context
tensorrt_llm/_torch/auto_deploy/custom_ops/attention/triton_attention.py, tests/integration/test_lists/waives.txt
When query and KV lengths match and estimated scratch usage exceeds 2 GiB, the SDPA call uses attn_mask=None and is_causal=True. Other workloads use the combined GQA-compatible padding and causal mask. The two L40S TestLlama3_1_8B::test_auto_dtype waiver entries are removed.

Estimated code review effort: 2 (Simple) | ~10 minutes

Possibly related PRs

Suggested reviewers: brnguyen2, xinhe-nv, stanleysun639

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title identifies the NVBugs issue, fix type, affected triton_context path, and key condition for the change.
Description check ✅ Passed The description explains the root cause, fix, validation plan, and bug link, but omits the repository checklist.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
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.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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

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

Actionable comments posted: 1

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

Inline comments:
In `@tensorrt_llm/_torch/auto_deploy/custom_ops/attention/triton_attention.py`:
- Around line 1181-1182: The sdpa_scratch_bytes calculation on line 1181
incorrectly uses q.element_size() which reflects the query tensor's dtype (e.g.,
2 bytes for fp16/bf16), but the actual SDPA scratch memory is allocated for fp32
score tensors which use 4 bytes per element. To fix this, replace the
q.element_size() call with a hardcoded 4 bytes (or equivalent like the size of a
float32 element) in the sdpa_scratch_bytes calculation to accurately estimate
the memory requirement and prevent premature selection of the explicit-mask
backend that could cause OOM on memory-constrained GPUs.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Enterprise

Run ID: 07606216-ae91-4e99-93cf-6accb9a55b37

📥 Commits

Reviewing files that changed from the base of the PR and between c25fa74 and 6e60bc4.

📒 Files selected for processing (2)
  • tensorrt_llm/_torch/auto_deploy/custom_ops/attention/triton_attention.py
  • tests/integration/test_lists/waives.txt
💤 Files with no reviewable changes (1)
  • tests/integration/test_lists/waives.txt

Comment on lines +1181 to +1182
sdpa_scratch_bytes = num_seq * n_heads * max_q_len * max_kv_len * q.element_size()
use_is_causal = max_q_len == max_kv_len and sdpa_scratch_bytes > 2 * 1024**3

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.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

# Find PyTorch version pinning
find . -type f \( -name "requirements*.txt" -o -name "pyproject.toml" -o -name "setup.py" \) | head -20

Repository: NVIDIA/TensorRT-LLM

Length of output: 952


🏁 Script executed:

# Read the specific file segment
cat -n tensorrt_llm/_torch/auto_deploy/custom_ops/attention/triton_attention.py | sed -n '1174,1200p'

Repository: NVIDIA/TensorRT-LLM

Length of output: 1788


🏁 Script executed:

# Also check surrounding comments for context on SDPA behavior
cat -n tensorrt_llm/_torch/auto_deploy/custom_ops/attention/triton_attention.py | sed -n '1160,1185p'

Repository: NVIDIA/TensorRT-LLM

Length of output: 1464


🏁 Script executed:

# Find main project configuration
cat pyproject.toml | grep -A 10 "torch\|pytorch" | head -20

Repository: NVIDIA/TensorRT-LLM

Length of output: 1219


🏁 Script executed:

# Also check if there's documentation about SDPA backend behavior
rg -i "sdpa|scaled_dot_product" --type py -B 2 -A 2 | grep -i "dtype\|fp32\|float32" | head -30

Repository: NVIDIA/TensorRT-LLM

Length of output: 3723


🏁 Script executed:

# Check PyTorch documentation link or comments that might clarify the backend
rg "math backend\|flash\|fused kernel" tensorrt_llm/_torch/auto_deploy/custom_ops/attention/ -B 2 -A 2

Repository: NVIDIA/TensorRT-LLM

Length of output: 45


🏁 Script executed:

# Check the main pyproject.toml for torch version
cat pyproject.toml | grep -i "torch" | head -20

Repository: NVIDIA/TensorRT-LLM

Length of output: 1219


🏁 Script executed:

# Look for PyTorch version in the base requirements
find . -name "requirements.txt" -exec grep -l "torch" {} \; | head -5

Repository: NVIDIA/TensorRT-LLM

Length of output: 259


🏁 Script executed:

# Search for any tests or documentation about SDPA math backend behavior
find . -path "./tests/*" -name "*.py" -exec rg "scaled_dot_product_attention" {} + | head -20

Repository: NVIDIA/TensorRT-LLM

Length of output: 3178


🏁 Script executed:

# Check if there are related PRs or comments about fp32 score tensors
rg "fp32.*score|score.*fp32" --type py tensorrt_llm/_torch/

Repository: NVIDIA/TensorRT-LLM

Length of output: 497


🏁 Script executed:

# Check main requirements.txt for torch version
cat requirements.txt | grep -i torch

Repository: NVIDIA/TensorRT-LLM

Length of output: 624


🏁 Script executed:

# Look for test that might reveal SDPA backend behavior with fp16/bf16
cat tests/unittest/auto_deploy/singlegpu/custom_ops/attention/test_triton_attention.py | grep -A 20 "def test\|torch.float16\|torch.bfloat16" | head -80

Repository: NVIDIA/TensorRT-LLM

Length of output: 3109


🏁 Script executed:

# Check if there's documentation about SDPA math backend in the repo
rg "torch.nn.functional.scaled_dot_product_attention" tensorrt_llm/_torch/ -B 5 -A 5 | grep -E "dtype|float32|fp32|math.*backend" | head -20

Repository: NVIDIA/TensorRT-LLM

Length of output: 45


🏁 Script executed:

# Look at the actual test to see if fp16/bf16 queries are tested
cat tests/unittest/auto_deploy/singlegpu/custom_ops/attention/test_triton_attention.py | sed -n '1,150p'

Repository: NVIDIA/TensorRT-LLM

Length of output: 5217


🏁 Script executed:

# Search for PyTorch SDPA documentation or implementation details in the codebase
rg "math.*backend|cuda_flash\|efficient_attention" tensorrt_llm/_torch/ -B 2 -A 5 | head -40

Repository: NVIDIA/TensorRT-LLM

Length of output: 3371


🏁 Script executed:

# Look for any comments about SDPA dtype behavior in tests or implementations
rg -i "sdpa.*dtype|score.*dtype|attention.*math" tensorrt_llm/_torch/auto_deploy/custom_ops/attention/ -B 3 -A 3

Repository: NVIDIA/TensorRT-LLM

Length of output: 6500


🏁 Script executed:

# Check if there are any references to PyTorch SDPA backend selection
cat tensorrt_llm/_torch/auto_deploy/custom_ops/attention/triton_attention.py | sed -n '1100,1200p' | grep -i "backend\|dtype\|flash"

Repository: NVIDIA/TensorRT-LLM

Length of output: 611


🏁 Script executed:

# Verify the proposed constants follow naming guidelines
# Check if similar constants are defined in the file
rg "THRESHOLD|BYTES|SIZE" tensorrt_llm/_torch/auto_deploy/custom_ops/attention/triton_attention.py

Repository: NVIDIA/TensorRT-LLM

Length of output: 1681


🏁 Script executed:

# Verify the fix formatting matches the codebase style
# Check how constants are defined elsewhere in the file
cat tensorrt_llm/_torch/auto_deploy/custom_ops/attention/triton_attention.py | grep -E "^[A-Z_]+\s*=" | head -10

Repository: NVIDIA/TensorRT-LLM

Length of output: 82


🏁 Script executed:

# Verify there are no existing fp32/fp64 element size constants already defined
rg "element_size\|ELEMENT_SIZE" tensorrt_llm/_torch/auto_deploy/custom_ops/attention/triton_attention.py

Repository: NVIDIA/TensorRT-LLM

Length of output: 45


🏁 Script executed:

# Check the context of the _MIN_TL_DOT_K constant to see naming style
cat tensorrt_llm/_torch/auto_deploy/custom_ops/attention/triton_attention.py | grep -B 5 -A 5 "_MIN_TL_DOT_K"

Repository: NVIDIA/TensorRT-LLM

Length of output: 730


🏁 Script executed:

# Check the exact lines and verify the fix makes sense with surrounding code
cat tensorrt_llm/_torch/auto_deploy/custom_ops/attention/triton_attention.py | sed -n '1175,1200p'

Repository: NVIDIA/TensorRT-LLM

Length of output: 1526


Use fp32 bytes for the SDPA scratch threshold.

Line 1181 uses q.element_size(), but the preceding comment describes an fp32 score tensor. For fp16/bf16 queries, this halves the estimate, so the explicit-mask math backend can still be selected when the real fp32 score exceeds the 2 GiB guard—defeating the OOM prevention on memory-tight GPUs like L40S.

Proposed fix
-        sdpa_scratch_bytes = num_seq * n_heads * max_q_len * max_kv_len * q.element_size()
-        use_is_causal = max_q_len == max_kv_len and sdpa_scratch_bytes > 2 * 1024**3
+        FP32_ELEMENT_SIZE_BYTES = 4
+        SDPA_SCRATCH_THRESHOLD_BYTES = 2 * 1024**3
+        sdpa_scratch_bytes = (
+            num_seq * n_heads * max_q_len * max_kv_len * FP32_ELEMENT_SIZE_BYTES
+        )
+        use_is_causal = (
+            max_q_len == max_kv_len and sdpa_scratch_bytes > SDPA_SCRATCH_THRESHOLD_BYTES
+        )
🤖 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/auto_deploy/custom_ops/attention/triton_attention.py`
around lines 1181 - 1182, The sdpa_scratch_bytes calculation on line 1181
incorrectly uses q.element_size() which reflects the query tensor's dtype (e.g.,
2 bytes for fp16/bf16), but the actual SDPA scratch memory is allocated for fp32
score tensors which use 4 bytes per element. To fix this, replace the
q.element_size() call with a hardcoded 4 bytes (or equivalent like the size of a
float32 element) in the sdpa_scratch_bytes calculation to accurately estimate
the memory requirement and prevent premature selection of the explicit-mask
backend that could cause OOM on memory-constrained GPUs.

@tensorrt-cicd
tensorrt-cicd force-pushed the repair-bot-bug6322045 branch from 6e60bc4 to 6e13e27 Compare June 18, 2026 17:21
cache_lens.view(num_seq, 1, 1, 1) + q_positions.view(1, 1, max_q_len, 1)
)
attn_mask = attn_mask & causal_mask
# An explicit attn_mask forces SDPA onto the math backend, which

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

The target test is for trtllm attention too, but it is fixing only triton attention. Seems that this is not the proper fix.

@tensorrt-cicd
tensorrt-cicd force-pushed the repair-bot-bug6322045 branch 2 times, most recently from 6dd0238 to 3094b9b Compare June 29, 2026 11:09
@trtllm-agent
trtllm-agent force-pushed the repair-bot-bug6322045 branch 2 times, most recently from c16425c to 3f754d0 Compare July 11, 2026 10:15
@trtllm-agent
trtllm-agent force-pushed the repair-bot-bug6322045 branch from 3f754d0 to 7fcfa38 Compare July 18, 2026 08:36
@trtllm-agent
trtllm-agent requested review from a team as code owners July 18, 2026 08:36

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

LGTM — AutoDeploy (beta) triton_context: the explicit-mask→is_causal substitution only fires when max_q_len==max_kv_len AND SDPA scratch >2 GiB (the giant fresh-prefill warmup where cache_lens==0 makes the mask exactly lower-triangular). Smaller/normal prefill and any cache-reuse path keep the explicit-mask numerics.

@yufeiwu-nv
yufeiwu-nv removed the request for review from ruodil July 20, 2026 23:31
@fredricz-20070104

Copy link
Copy Markdown
Collaborator

Please resolve @taylor-yb-lee's waiver concern first: this PR only fixes the triton path, but it also removes the waiver for test_auto_dtype[trtllm-False-1], which goes through a separate backend (trtllm_attention.py) that never touches triton_context — so that waiver has no corresponding fix here. Either restore the trtllm-False-1 waiver, or run the full L40S pipeline to prove both variants pass before merging.

@yufeiwu-nv

Copy link
Copy Markdown
Collaborator

Waiting on code owner review from NVIDIA/trt-llm-torch-autodeploy-devs.
——no QA effort currently, remove QAs name from reviewers.

tensorrt-cicd and others added 2 commits August 11, 2026 17:10
…attn

The triton context-attention SDPA fast path passes an explicit attn_mask to
torch.nn.functional.scaled_dot_product_attention, which forces the math
backend and materializes [num_seq, n_heads, max_q_len, max_kv_len] fp32
score and softmax tensors. During piecewise cudagraph warmup at 8192 tokens
for Llama-3.1-8B (1*32*8192*8192*4 = 8 GiB per tensor), this OOMs on
memory-tight GPUs such as L40S (44 GiB).

When the explicit mask reduces to a plain lower-triangular mask (every
sequence has the same q_len under the existing all_same_q_len gate, and
max_q_len == max_kv_len implies all cache_lens are 0), and the projected
scratch would exceed 2 GiB, drop the mask and dispatch via is_causal=True
so SDPA can use the fused flash kernel instead. The original explicit-mask
path is preserved for shorter sequences and any case with cache reuse, so
numerics are unchanged outside the OOM-prone regime.

Signed-off-by: tensorrt-cicd <90828364+tensorrt-cicd@users.noreply.github.com>
Signed-off-by: trtllm-agent <296075020+trtllm-agent@users.noreply.github.com>
@trtllm-agent
trtllm-agent force-pushed the repair-bot-bug6322045 branch from 7fcfa38 to 369cc0b Compare August 12, 2026 00:12
@trtllm-agent
trtllm-agent requested a review from a team as a code owner August 12, 2026 00:12
@coderabbitai

coderabbitai Bot commented Aug 12, 2026

Copy link
Copy Markdown
Contributor

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

@xinhe-nv

Copy link
Copy Markdown
Collaborator

/bot run --only-qa-verify test accuracy/test_llm_api_autodeploy.py::TestLlama3_1_8B::test_auto_dtype[triton-False-1]

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator Author

PR_Github #65470 [ run ] triggered by Bot. Commit: 6d28ef4 Link to invocation

@StanleySun639 StanleySun639 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

LGTM if the target test case can pass.

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator Author

PR_Github #65470 [ run ] completed with state SUCCESS. Commit: 6d28ef4
LLM_FUNCTION_AUTO_V2C #369 completed with status: 'SUCCESS'
QA verify test: accuracy/test_llm_api_autodeploy.py::TestLlama3_1_8B::test_auto_dtype[triton-False-1] (NVBug 6322045, branch repair-bot-bug6322045, fork tensorrt-cicd, dry_run_close=true)

Link to invocation

@taylor-yb-lee

Copy link
Copy Markdown
Collaborator

Thanks for the reviews and apologies for the belated response. Auto Deploy will be deprecated in the TRTLLM, so there is no point to make change here. Let me close this PR and request close the original ticket too.

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.

9 participants