Skip to content

[None][fix] Fix DeepSeek V4 KV cache warmup handling and serveral other issues - #16466

Merged
liji-nv merged 3 commits into
NVIDIA:mainfrom
liji-nv:fix/dsv4-kvcache-cudagraph-warmup
Jul 20, 2026
Merged

[None][fix] Fix DeepSeek V4 KV cache warmup handling and serveral other issues#16466
liji-nv merged 3 commits into
NVIDIA:mainfrom
liji-nv:fix/dsv4-kvcache-cudagraph-warmup

Conversation

@liji-nv

@liji-nv liji-nv commented Jul 16, 2026

Copy link
Copy Markdown
Collaborator

Summary by CodeRabbit

  • Bug Fixes

    • Improved DeepSeek V4 KV-cache sizing to account for additional KV tokens.
    • Stabilized speculative decoding during CUDA graph capture by preserving KV-length state across warmups and capture.
  • Tests

    • Added coverage for KV-cache capacity and speculative decoding state restoration.
    • Expanded DeepSeek V4 accuracy, boundary, and KV-transfer validation on supported GPUs.

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.

@liji-nv
liji-nv requested review from a team as code owners July 16, 2026 03:30
@liji-nv liji-nv changed the title [None][fix] Fix DeepSeek V4 KV cache warmup handling [None][fix] Fix DeepSeek V4 KV cache warmup handling and serveral other issues Jul 16, 2026
@coderabbitai

coderabbitai Bot commented Jul 16, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

DeepSeek V4 cache sizing now includes extra KV tokens. CUDA graph capture preserves speculative-decode KV-length metadata across warmups and capture. KV-transfer tests now parse indexer-compressed buffers using explicit manager-provided sizes and scale dtypes.

Changes

DeepSeek V4 cache sizing

Layer / File(s) Summary
Extra KV token capacity and validation
tensorrt_llm/_torch/attention_backend/sparse/deepseek_v4/cache_manager.py, tests/unittest/_torch/attention/sparse/deepseek_v4/test_deepseek_v4_cache_manager.py, tests/integration/test_lists/test-db/l0_dgx_b200.yml
Context capacity includes num_extra_kv_tokens; unit and integration coverage was added for DeepSeek V4 behavior.

Speculative decode CUDA graph capture

Layer / File(s) Summary
KV-length capture state helpers
tensorrt_llm/_torch/pyexecutor/cuda_graph_runner.py, tests/unittest/_torch/executor/test_pytorch_model_engine.py
Helpers snapshot and restore speculative-decode KV lengths and invoke metadata updates after restoration.
Capture integration
tensorrt_llm/_torch/pyexecutor/cuda_graph_runner.py, tests/unittest/_torch/executor/test_pytorch_model_engine.py
CUDA graph capture restores KV-length state around warmups and after capture; tests cover repeated warmup restoration.

KV-transfer buffer parsing

Layer / File(s) Summary
Generic compressed-buffer interpretation
tests/unittest/disaggregated/test_deepseek_v4_kv_transfer.py
INDEXER_COMPRESS parsing now uses explicit data size, scale size, and scale dtype instead of fixed FP8 assumptions.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Sequence Diagram(s)

sequenceDiagram
  participant CUDAGraphRunner
  participant attn_metadata
  participant CUDA_Graph
  CUDAGraphRunner->>attn_metadata: Snapshot kv_lens_cuda
  CUDAGraphRunner->>attn_metadata: Restore state before warmup
  CUDAGraphRunner->>CUDA_Graph: Capture warmup and graph operations
  CUDAGraphRunner->>attn_metadata: Restore state after capture
  attn_metadata->>attn_metadata: Call on_update_kv_lens()
Loading

Possibly related PRs

Suggested reviewers: jiaganc, chenfeiz0326

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description is mostly template text and omits the required issue summary and test coverage details. Fill in the Description and Test Coverage sections with the problem, solution, and tests that cover the change.
✅ Passed checks (4 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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 is related to the change and identifies the main DeepSeek V4 KV cache warmup fix.
✨ 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

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/pyexecutor/cuda_graph_runner.py (1)

450-464: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Restore the snapshot on exceptional exits.

If a warmup forward, postprocess_fn, or CUDA graph capture raises, the restore call is skipped and attn_metadata.kv_lens_cuda can remain mutated. Wrap the capture sequence in try/finally, retaining the per-warmup restore while guaranteeing cleanup on failure.

🤖 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/pyexecutor/cuda_graph_runner.py` around lines 450 - 464,
Wrap the warmup loop and CUDA graph capture sequence in a try/finally so
_restore_spec_decode_capture_state(attn_metadata, saved_kv_lens_cuda) always
runs when _setup_spec_decoding_and_forward, postprocess_fn, or graph capture
raises. Keep the existing restore after each warmup iteration, and use the
finally block for the overall cleanup path.
🧹 Nitpick comments (3)
tensorrt_llm/_torch/pyexecutor/cuda_graph_runner.py (1)

42-55: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Use a typed attention-metadata protocol instead of Any.

The new helpers cannot statically verify kv_lens_cuda, num_seqs, or on_update_kv_lens. Define a small Protocol or shared metadata interface for this contract.

As per coding guidelines, avoid Any and use precise type annotations.

🤖 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/pyexecutor/cuda_graph_runner.py` around lines 42 - 55,
Replace the Any annotation in _save_spec_decode_capture_state and define a typed
attention-metadata Protocol or shared interface exposing kv_lens_cuda, num_seqs,
and on_update_kv_lens. Use that type for both helper signatures, preserving the
existing optional-state behavior and restore logic.

Source: Coding guidelines

tests/unittest/_torch/executor/test_pytorch_model_engine.py (1)

152-169: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add capture-level coverage for the integration.

Coverage is currently insufficient: this test exercises only the helpers and would pass even if CUDAGraphRunner.capture omitted restoration or restored at the wrong point. Add a focused test in tests/unittest/_torch/executor/test_pytorch_model_engine.py covering both warmups and the final post-capture restore, or track that integration coverage as follow-up.

As per path instructions, test feedback should identify whether coverage is sufficient and provide a concrete file for follow-up.

🤖 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 `@tests/unittest/_torch/executor/test_pytorch_model_engine.py` around lines 152
- 169, Add an integration-focused test for CUDAGraphRunner.capture in
tests/unittest/_torch/executor/test_pytorch_model_engine.py that verifies
speculative-decode KV lengths are restored before each of the two warmup
forwards and again after capture completes. Exercise the capture flow rather
than only _save_spec_decode_capture_state and
_restore_spec_decode_capture_state, and assert the original metadata remains
intact at every required point.

Source: Path instructions

tests/unittest/_torch/attention/sparse/deepseek_v4/test_deepseek_v4_cache_manager.py (1)

87-113: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Cover the max_num_tokens is None branch.

This test only validates max_num_tokens + num_extra_kv_tokens; the fallback typical_seq_len + num_extra_kv_tokens branch remains uncovered. Add a second case with _max_num_tokens=None and an explicit avg_seq_len, then assert the resulting capacity.

🤖 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
`@tests/unittest/_torch/attention/sparse/deepseek_v4/test_deepseek_v4_cache_manager.py`
around lines 87 - 113, Extend test_mtp_extra_tokens_are_in_context_capacity with
a second setup where _max_num_tokens is None and avg_seq_len is explicitly
provided, then build the cache configuration and assert the capacity uses
avg_seq_len plus num_extra_kv_tokens. Keep the existing max_num_tokens case
unchanged.

Source: Path instructions

🤖 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/attention_backend/sparse/deepseek_v4/cache_manager.py`:
- Around line 891-893: Update the generation descriptor sizing and decode warmup
constraint near the context-capacity calculation to include
self.num_extra_kv_tokens consistently with _get_generation_bytes(). Ensure
generation warmups and pool sizing reserve the same extra-token capacity, rather
than using bare typical_seq_len or max_seq_len.

---

Outside diff comments:
In `@tensorrt_llm/_torch/pyexecutor/cuda_graph_runner.py`:
- Around line 450-464: Wrap the warmup loop and CUDA graph capture sequence in a
try/finally so _restore_spec_decode_capture_state(attn_metadata,
saved_kv_lens_cuda) always runs when _setup_spec_decoding_and_forward,
postprocess_fn, or graph capture raises. Keep the existing restore after each
warmup iteration, and use the finally block for the overall cleanup path.

---

Nitpick comments:
In `@tensorrt_llm/_torch/pyexecutor/cuda_graph_runner.py`:
- Around line 42-55: Replace the Any annotation in
_save_spec_decode_capture_state and define a typed attention-metadata Protocol
or shared interface exposing kv_lens_cuda, num_seqs, and on_update_kv_lens. Use
that type for both helper signatures, preserving the existing optional-state
behavior and restore logic.

In
`@tests/unittest/_torch/attention/sparse/deepseek_v4/test_deepseek_v4_cache_manager.py`:
- Around line 87-113: Extend test_mtp_extra_tokens_are_in_context_capacity with
a second setup where _max_num_tokens is None and avg_seq_len is explicitly
provided, then build the cache configuration and assert the capacity uses
avg_seq_len plus num_extra_kv_tokens. Keep the existing max_num_tokens case
unchanged.

In `@tests/unittest/_torch/executor/test_pytorch_model_engine.py`:
- Around line 152-169: Add an integration-focused test for
CUDAGraphRunner.capture in
tests/unittest/_torch/executor/test_pytorch_model_engine.py that verifies
speculative-decode KV lengths are restored before each of the two warmup
forwards and again after capture completes. Exercise the capture flow rather
than only _save_spec_decode_capture_state and
_restore_spec_decode_capture_state, and assert the original metadata remains
intact at every required point.
🪄 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: ff92d7bd-790b-4ed5-84bb-e8400e305b1e

📥 Commits

Reviewing files that changed from the base of the PR and between 6013944 and 9a8eb6d.

📒 Files selected for processing (6)
  • tensorrt_llm/_torch/attention_backend/sparse/deepseek_v4/cache_manager.py
  • tensorrt_llm/_torch/pyexecutor/cuda_graph_runner.py
  • tests/integration/test_lists/test-db/l0_dgx_b200.yml
  • tests/unittest/_torch/attention/sparse/deepseek_v4/test_deepseek_v4_cache_manager.py
  • tests/unittest/_torch/executor/test_pytorch_model_engine.py
  • tests/unittest/disaggregated/test_deepseek_v4_kv_transfer.py

@liji-nv
liji-nv force-pushed the fix/dsv4-kvcache-cudagraph-warmup branch from 5f73620 to 5330b1f Compare July 16, 2026 05:53
@liji-nv

liji-nv commented Jul 16, 2026

Copy link
Copy Markdown
Collaborator Author

/bot run --disable-fail-fast

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #59632 [ run ] triggered by Bot. Commit: 5330b1f Link to invocation

liji-nv added 2 commits July 16, 2026 05:52
Signed-off-by: Jin Li <59594262+liji-nv@users.noreply.github.com>
Signed-off-by: Jin Li <59594262+liji-nv@users.noreply.github.com>
@liji-nv
liji-nv force-pushed the fix/dsv4-kvcache-cudagraph-warmup branch from 5330b1f to 904a0c9 Compare July 16, 2026 12:52
@liji-nv

liji-nv commented Jul 16, 2026

Copy link
Copy Markdown
Collaborator Author

/bot run --disable-fail-fast

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #59708 [ run ] triggered by Bot. Commit: 904a0c9 Link to invocation

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #59632 [ run ] completed with state ABORTED. Commit: 5330b1f

Link to invocation

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #59708 [ run ] completed with state SUCCESS. Commit: 904a0c9
/LLM/main/L0_MergeRequest_PR pipeline #48135 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

@longlee0622

Copy link
Copy Markdown
Collaborator

/bot run --disable-fail-fast

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #59817 [ run ] triggered by Bot. Commit: 904a0c9 Link to invocation

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #59817 [ run ] completed with state SUCCESS. Commit: 904a0c9
/LLM/main/L0_MergeRequest_PR pipeline #48226 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

@liji-nv

liji-nv commented Jul 17, 2026

Copy link
Copy Markdown
Collaborator Author

/bot run

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #59898 [ run ] completed with state SUCCESS. Commit: 904a0c9
/LLM/main/L0_MergeRequest_PR pipeline #48299 completed with status: 'SUCCESS'

CI Report

Link to invocation

@liji-nv

liji-nv commented Jul 17, 2026

Copy link
Copy Markdown
Collaborator Author

/bot run --disable-fail-fast

1 similar comment
@liji-nv

liji-nv commented Jul 17, 2026

Copy link
Copy Markdown
Collaborator Author

/bot run --disable-fail-fast

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #59918 [ run ] triggered by Bot. Commit: e48967b Link to invocation

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #59918 [ run ] completed with state SUCCESS. Commit: e48967b
/LLM/main/L0_MergeRequest_PR pipeline #48320 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

@liji-nv

liji-nv commented Jul 17, 2026

Copy link
Copy Markdown
Collaborator Author

/bot run --disable-fail-fast

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #59972 [ run ] triggered by Bot. Commit: e48967b Link to invocation

@liji-nv
liji-nv enabled auto-merge (squash) July 17, 2026 13:12
@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

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

@longlee0622

Copy link
Copy Markdown
Collaborator

/bot run --disable-fail-fast

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #59989 [ run ] triggered by Bot. Commit: e48967b Link to invocation

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

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

Comment thread tests/integration/test_lists/test-db/l0_dgx_b200.yml
@longlee0622

Copy link
Copy Markdown
Collaborator

/bot run --disable-fail-fast

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #60065 [ run ] triggered by Bot. Commit: e48967b Link to invocation

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #60065 [ run ] completed with state SUCCESS. Commit: e48967b
/LLM/main/L0_MergeRequest_PR pipeline #48453 completed with status: 'SUCCESS'

CI Report

Link to invocation

@zhaoyangwang-nvidia zhaoyangwang-nvidia 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

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