Skip to content

[https://nvbugs/6441022][fix] Enable CUDA graph for final context token computation - #16746

Merged
SimengLiu-nv merged 4 commits into
NVIDIA:mainfrom
SimengLiu-nv:one-token-context-opt
Jul 31, 2026
Merged

[https://nvbugs/6441022][fix] Enable CUDA graph for final context token computation#16746
SimengLiu-nv merged 4 commits into
NVIDIA:mainfrom
SimengLiu-nv:one-token-context-opt

Conversation

@SimengLiu-nv

@SimengLiu-nv SimengLiu-nv commented Jul 22, 2026

Copy link
Copy Markdown
Collaborator

Summary by CodeRabbit

  • New Features

    • Improved KV-cache reuse when only the final prompt token remains.
    • Added CUDA graph support for promoted final-context requests.
    • Preserved context logits, guided decoding, and multimodal position metadata during reuse.
    • Improved handling when reusable cache data is moved to secondary memory.
  • Bug Fixes

    • Corrected CUDA graph selection and KV-cache restoration synchronization for reused context.
  • Tests

    • Added unit and integration coverage for final-token reuse, guided decoding, multimodal prompts, and CUDA graph replay.

Description

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)

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

@coderabbitai

coderabbitai Bot commented Jul 22, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

The change adds promoted final-context handling for CUDA graph execution, updates graph-key length selection, preserves KV-cache reuse state across boundary cases, and adds unit and integration coverage for guided decoding, multimodal requests, context logits, offload, and stream synchronization.

Changes

Promoted final-context execution

Layer / File(s) Summary
Final-token KV-cache reuse behavior
cpp/tests/unit_tests/batch_manager/kvCacheManagerTest.cpp
Parameterized cache-manager fixtures and tests cover final-token reuse, guided-decoding state, secondary-memory offload, and multimodal metadata.
Promoted context batching and input preparation
tensorrt_llm/_torch/pyexecutor/model_engine.py
Eligible one-token contexts are converted to decode-shaped graph batches, with promoted IDs threaded through input preparation and forward execution.
Promoted-context CUDA graph keying
tensorrt_llm/_torch/pyexecutor/cuda_graph_runner.py
Graph sequence-length modes and keys use context_current_position + 1 for promoted requests.
Model-engine execution validation
tests/unittest/_torch/executor/test_pytorch_model_engine.py
Unit tests cover batching eligibility, fallback behavior, promoted request propagation, MRoPE state, graph hits, and stream dependencies.
Integration and KV-cache restore validation
tests/integration/defs/kv_cache/*, tests/integration/test_lists/test-db/l0_h100.yml, tests/unittest/kv_cache_manager_v2_tests/test_kv_cache_stats_behavior.py
Integration and cache-manager tests validate reused outputs, context logits, guided decoding, graph replay, and restore ordering.

Estimated code review effort: 4 (Complex) | ~60 minutes

Suggested labels: api-compatible

Suggested reviewers: liji-nv, cascade812, 2ez4bz

Sequence Diagram(s)

sequenceDiagram
  participant ScheduledRequests
  participant PyTorchModelEngine
  participant CUDAGraphRunner
  ScheduledRequests->>PyTorchModelEngine: identify final-token context rows
  PyTorchModelEngine->>PyTorchModelEngine: build promoted context graph batch
  PyTorchModelEngine->>CUDAGraphRunner: request graph with promoted context ids
  CUDAGraphRunner-->>PyTorchModelEngine: return graph and execution key
  PyTorchModelEngine->>CUDAGraphRunner: replay promoted-context graph
Loading
🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 15.91% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning The description only repeats the template and does not explain the issue, solution, or test coverage. Fill in the Description and Test Coverage sections with a brief problem summary, the fix, and the relevant tests.
✅ Passed checks (3 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 matches the main change and follows the required ticket/type format.
✨ 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/pyexecutor/model_engine.py`:
- Around line 3721-3731: Move the “the request has no previous tensor”
explanatory comment from above the conditional so it appears immediately before
the `elif new_tokens_device is None or request.is_dummy or request.py_batch_idx
is None` branch. Keep the `is_promoted_context` branch and its logic unchanged.
🪄 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: 01bca682-2dee-4678-bad3-7332ccdbae4d

📥 Commits

Reviewing files that changed from the base of the PR and between 1fbd240 and 039a183.

📒 Files selected for processing (7)
  • cpp/tests/unit_tests/batch_manager/kvCacheManagerTest.cpp
  • tensorrt_llm/_torch/pyexecutor/cuda_graph_runner.py
  • tensorrt_llm/_torch/pyexecutor/model_engine.py
  • tests/integration/defs/kv_cache/test_final_single_token_context_cuda_graph.py
  • tests/integration/test_lists/test-db/l0_h100.yml
  • tests/unittest/_torch/executor/test_pytorch_model_engine.py
  • tests/unittest/kv_cache_manager_v2_tests/test_kv_cache_stats_behavior.py

Comment thread tensorrt_llm/_torch/pyexecutor/model_engine.py
@nvpohanh
nvpohanh requested a review from thorjohnsen July 24, 2026 08:13
@nvpohanh

Copy link
Copy Markdown
Collaborator

[by Codex] @thorjohnsen Could you please review this PR? Thank you!

@SimengLiu-nv
SimengLiu-nv force-pushed the one-token-context-opt branch from 039a183 to c40fdab Compare July 27, 2026 21:10
@SimengLiu-nv
SimengLiu-nv requested a review from a team as a code owner July 27, 2026 21:10
@SimengLiu-nv

Copy link
Copy Markdown
Collaborator Author

/bot run --disable-fail-fast

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

Approval for infra

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

Don't really see the purpose of adding test cases under cpp/tests/unit_tests/batch_manager/kvCacheManagerTest.cpp matters here. My opinion is we don't need them at all.

Promoting the context batch here to enable CUDA graph looks good to me.

It seems like the test cases won't get captured by how you specified them under the .yml files. I think you will need to update them.

Approving to unblock.

@SimengLiu-nv

Copy link
Copy Markdown
Collaborator Author

Don't really see the purpose of adding test cases under cpp/tests/unit_tests/batch_manager/kvCacheManagerTest.cpp matters here. My opinion is we don't need them at all.

Promoting the context batch here to enable CUDA graph looks good to me.

It seems like the test cases won't get captured by how you specified them under the .yml files. I think you will need to update them.

Approving to unblock.

Hi @eopXD , thanks for the feedback. The purpose of the C++ tests is to pin the upstream KV-cache-manager contract that graph promotion depends on: final-token reuse must leave exactly one context token, preserve semantic request state/type and feature metadata, and correctly onboard shared offloaded blocks without breaking ownership or cancellation. Removing all of them would leave that cross-language boundary implicit.
I also rechecked the YAML selectors. The repository stage mapper recognizes all six entries: the five single-GPU tests map through l0_h100.yml to pre-merge PyTorch H100 stages, and the TP2 test maps through l0_dgx_h100.yml to DGX H100 PyTorch stages.

@SimengLiu-nv
SimengLiu-nv requested a review from a team as a code owner July 28, 2026 17:51
@SimengLiu-nv

Copy link
Copy Markdown
Collaborator Author

/bot run --disable-fail-fast

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #62253 [ run ] triggered by Bot. Commit: 5b400eb Link to invocation

Comment thread tensorrt_llm/_torch/pyexecutor/model_engine.py Outdated

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

Overall, this looks good to me, and I’m approving to unblock.

One design consideration for the future: the PR places context requests in generation_requests and passes promoted_context_request_ids through several layers to preserve their original semantics. This works for the current change, though it may be somewhat fragile to maintain—future code may check only which list contains the request and accidentally apply generation behavior.

@SimengLiu-nv

Copy link
Copy Markdown
Collaborator Author

/bot run --disable-fail-fast

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #62327 [ run ] triggered by Bot. Commit: c25ef42 Link to invocation

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #62253 [ run ] completed with state ABORTED. Commit: 5b400eb

Link to invocation

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #62327 [ run ] completed with state FAILURE. Commit: c25ef42
/LLM/main/L0_MergeRequest_PR pipeline #50496 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

…ken contexts

Promote eligible final single-token context rows through a temporary
decode-shaped execution view after KV preparation. Commit the view only when
the existing graph runner finds a matching graph, and retain semantic eager
fallback otherwise.

Preserve request state, request type, KV ownership, sampling order, and
lifecycle updates. Cover context logits, guided decoding, zero-runtime-draft
target execution, overlap token sourcing, sparse graph keys, local offload,
changed-tail reuse, and TP2 rank-local replay.

Tests added:

cpp/tests/unit_tests/batch_manager/kvCacheManagerTest.cpp:
- KVCacheManagerTest.AddSequenceBatchLeavesOneFinalContextTokenAfterReuse
- KVCacheManagerTest.AddSequenceBatchPreservesDraftTokensOnFinalContextAfterReuse
- KVCacheManagerTest.AddSequenceBatchPreservesGuidanceAndContextLogitsAfterReuse
- KVCacheManagerTest.AddSequenceBatchOnboardsOffloadedPrefixForFinalContextToken
- KVCacheManagerTest.AddSequenceBatchLeavesOneFinalMultimodalContextTokenAfterReuse

tests/integration/defs/kv_cache/test_final_single_token_context_cuda_graph.py:
- test_final_token_reuse_cuda_graph
- test_changed_final_token_reuse_cuda_graph
- test_final_token_reuse_cuda_graph_tp2
- test_context_logits_after_final_token_reuse
- test_guided_decoding_after_final_token_reuse
- test_zero_runtime_draft_speculation_after_final_token_reuse

tests/unittest/_torch/executor/test_pytorch_model_engine.py:
- SingleTokenContextGraphBatchTestCase.test_generation_only_is_identity
- SingleTokenContextGraphBatchTestCase.test_eligible_batch_has_independent_lists_and_stable_order
- SingleTokenContextGraphBatchTestCase.test_structural_fallbacks_return_semantic_batch
- SingleTokenContextGraphBatchTestCase.test_context_shape_and_mode_fallback_matrix
- SingleTokenContextGraphBatchTestCase.test_context_logits_use_final_token_graph_candidate
- SingleTokenContextGraphBatchTestCase.test_generation_only_request_in_context_list_falls_back
- SingleTokenContextGraphBatchTestCase.test_generation_shape_fallback_matrix
- SingleTokenContextGraphBatchTestCase.test_mixed_one_and_two_token_contexts_fall_back_together
- SingleTokenContextGraphBatchTestCase.test_mrope_delta_is_supported_by_decode_provider
- SingleTokenContextGraphBatchTestCase.test_multimodal_context_requires_compatible_decode_token
- SingleTokenContextGraphBatchTestCase.test_multimodal_pending_event_is_rechecked
- SingleTokenContextGraphBatchTestCase.test_multimodal_decode_compatibility_uses_final_prompt_token
- SingleTokenContextGraphBatchTestCase.test_sparse_sequence_mode_uses_promoted_context_cursor
- SingleTokenContextGraphBatchTestCase.test_graph_key_forwards_promoted_context_ids
- SingleTokenContextGraphBatchTestCase.test_graph_lookup_forwards_promoted_context_ids
- SingleTokenContextGraphBatchTestCase.test_forward_commits_candidate_only_on_graph_hit
- SingleTokenContextGraphBatchTestCase.test_forward_graph_miss_uses_semantic_eager_batch
- SingleTokenContextGraphBatchTestCase.test_zero_runtime_draft_speculation_commits_graph_candidate
- SingleTokenContextGraphBatchTestCase.test_zero_runtime_draft_speculation_graph_miss_is_semantic_eager
- SingleTokenContextGraphBatchTestCase.test_forward_allows_guided_context_logits_on_graph_hit
- SingleTokenContextGraphBatchTestCase.test_multimodal_graph_miss_preserves_semantic_payload
- SingleTokenContextGraphBatchTestCase.test_generation_only_forward_does_not_call_new_selector
- SingleTokenContextGraphBatchTestCase.test_global_incompatibilities_bypass_candidate_selection
- PyTorchModelEngineTestCase.test_promoted_context_uses_prompt_token_during_overlap
- PyTorchModelEngineTestCase.test_promoted_context_precedes_speculative_overlap_generation
- PyTorchModelEngineTestCase.test_promoted_mrope_context_uses_decode_state_contract
- PyTorchModelEngineTestCase.test_kv_cache_manager_with_execution_stream
- PyTorchModelEngineTestCase.test_cuda_graph_replay_observes_execution_stream_dependency

tests/unittest/kv_cache_manager_v2_tests/test_kv_cache_stats_behavior.py:
- test_v2_resume_restores_offsets_only_after_execution_stream_ready

Signed-off-by: Simeng Liu <simengl@nvidia.com>
Signed-off-by: Simeng Liu <simengl@nvidia.com>
Signed-off-by: Simeng Liu <simengl@nvidia.com>
Signed-off-by: Simeng Liu <simengl@nvidia.com>
@SimengLiu-nv
SimengLiu-nv force-pushed the one-token-context-opt branch from c25ef42 to 7a69bd7 Compare July 29, 2026 18:37
@SimengLiu-nv

Copy link
Copy Markdown
Collaborator Author

/bot run --disable-fail-fast

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #62577 [ run ] triggered by Bot. Commit: 7a69bd7 Link to invocation

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #62577 [ run ] completed with state FAILURE. Commit: 7a69bd7
/LLM/main/L0_MergeRequest_PR pipeline #50721 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

@SimengLiu-nv

Copy link
Copy Markdown
Collaborator Author

/bot run

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #62813 [ run ] triggered by Bot. Commit: 7a69bd7 Link to invocation

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #62813 [ run ] completed with state FAILURE. Commit: 7a69bd7
/LLM/main/L0_MergeRequest_PR pipeline #50938 completed with status: 'ABORTED'

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

@SimengLiu-nv

Copy link
Copy Markdown
Collaborator Author

/bot run

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #63063 [ run ] triggered by Bot. Commit: 7a69bd7 Link to invocation

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #63063 [ run ] completed with state SUCCESS. Commit: 7a69bd7
/LLM/main/L0_MergeRequest_PR pipeline #51162 completed with status: 'SUCCESS'

CI Report

Link to invocation

@SimengLiu-nv
SimengLiu-nv merged commit 3304709 into NVIDIA:main Jul 31, 2026
7 checks passed
yuanjingx87 pushed a commit that referenced this pull request Aug 1, 2026
…en computation (#16746)

Signed-off-by: Simeng Liu <simengl@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.

10 participants