Skip to content

[None][feat] Add KV cache manager V2 support for DSA - #16060

Open
yizhang-nv wants to merge 8 commits into
NVIDIA:mainfrom
yizhang-nv:codex/dsa-kv-cache-v2-main
Open

[None][feat] Add KV cache manager V2 support for DSA#16060
yizhang-nv wants to merge 8 commits into
NVIDIA:mainfrom
yizhang-nv:codex/dsa-kv-cache-v2-main

Conversation

@yizhang-nv

@yizhang-nv yizhang-nv commented Jul 7, 2026

Copy link
Copy Markdown
Member

Dev Engineer Review

  • Added DSA KV cache manager V2 support while preserving V1 selection.
  • Registered indexer K cache storage as a native per-layer Role.INDEX_KEY buffer.
  • Added V2 page-index conversion for gather, scatter, and paged-logits paths.
  • Added FP8 and FP4 indexer storage accounting for cache sizing, quotas, and warm-up estimates.
  • Added stable representative-layer selection for coalesced KV cache pools.
  • Added draft-cache buffer handling for FlashMLA and DSA CUDA-graph replay.
  • Added model defaults that enable KV cache manager V2 for DeepSeek V3.
  • Updated configuration validation and documentation for unsupported V2 combinations.
  • Updated copyright and license metadata in affected files.
  • No test-list files were changed.
  • Review should confirm V2 page scaling, FP4 byte accounting, draft-buffer restoration, and V1 fallback behavior across all supported context-parallel configurations.

QA Engineer Review

Test code changes are present.

Added or updated coverage includes:

  • DSA V2 manager selection, page mapping, layer masks, cache sizing, and metadata behavior.
  • DSA draft replay and cached full-KV mapping restoration.
  • KV cache V2 stable-layer page-table mapping.
  • DSA with STAR context parallelism validation.
  • Nested model-default preservation.
  • DSA accuracy coverage through TestGLM52.test_nvfp4.
  • C++ custom-op documentation coverage for indexer_k_cache_scatter_op.

No corresponding tests/integration/test_lists/ changes were reported for these tests. Test-list coverage cannot be confirmed from the available changes.

Verdict: needs follow-up.

Description

Port the DSA KV cache manager V2 work from liji-nv@492422b onto the latest main.

This change:

  • Adds DSACacheManagerV2 selection through use_kv_cache_manager_v2 while preserving the V1 path.
  • Registers the indexer K cache as a native per-layer Role.INDEX_KEY buffer managed by V2.
  • Makes indexer gather/scatter and paged-logits paths aware of V2 page-index scaling for coalesced pools.
  • Accounts for FP8/FP4 indexer storage in Role.ALL, runtime quota calculation, and static KV cache warm-up estimation.
  • Adds DSA V2 accuracy coverage and targeted unit tests for cache layout and scaled page indices.

Test Coverage

  • Clean C++ source builds passed for SM80 (A100), SM90 (H100/H200), SM100 (B200), and SM103 (B300).
  • DSA V2 manager selection, FP8/FP4 layout, role sizing, and warm-up quota: 5 passed.
  • Indexer gather/scatter page-index scaling with FP8/FP4: 4 passed.
  • DSA V1 scatter regression: 1 passed.
  • YAPF, Ruff lint/format, and git diff --check passed.

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.

@yizhang-nv
yizhang-nv force-pushed the codex/dsa-kv-cache-v2-main branch from 8ff6b1c to 69404fe Compare July 8, 2026 09:03
@yizhang-nv

Copy link
Copy Markdown
Member Author

/bot run --disable-fail-fast

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #58215 [ run ] triggered by Bot. Commit: 69404fe Link to invocation

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #58215 [ run ] completed with state FAILURE. Commit: 69404fe
/LLM/main/L0_MergeRequest_PR pipeline #46857 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

@yizhang-nv
yizhang-nv force-pushed the codex/dsa-kv-cache-v2-main branch from 69404fe to 767b3be Compare July 20, 2026 05:29
@yizhang-nv

Copy link
Copy Markdown
Member Author

/bot run --disable-fail-fast

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #60273 [ run ] triggered by Bot. Commit: 767b3be Link to invocation

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #60273 [ run ] completed with state FAILURE. Commit: 767b3be
/LLM/main/L0_MergeRequest_PR pipeline #48631 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

@yizhang-nv
yizhang-nv marked this pull request as ready for review July 21, 2026 08:38
@yizhang-nv
yizhang-nv requested review from a team as code owners July 21, 2026 08:38
@yizhang-nv
yizhang-nv force-pushed the codex/dsa-kv-cache-v2-main branch from 767b3be to eeadb01 Compare July 21, 2026 08:56
@yizhang-nv

Copy link
Copy Markdown
Member Author

/bot run --disable-fail-fast

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #60657 [ run ] triggered by Bot. Commit: eeadb01 Link to invocation

@coderabbitai

coderabbitai Bot commented Jul 21, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

Walkthrough

The PR adds DSA support for V1 and V2 KV cache managers. It updates indexer cache sizing and mappings, draft replay metadata handling, stable pool mapping, manager selection, model defaults, tests, and documentation.

Changes

DSA cache manager contracts and V2 implementation

Layer / File(s) Summary
DSA cache manager contracts and V2 implementation
tensorrt_llm/_torch/attention_backend/sparse/dsa.py, tests/unittest/_torch/attention/sparse/dsa/test_dsa_indexer.py
DSA adds V2 cache management, indexer cache sizing, page conversion, stable-slot lookup, per-layer accounting, and manager-backed metadata buffers. Tests cover V1 and V2 behavior, page mapping, shared-indexer layers, and cache sizing.

Indexer offsets and full-KV mappings

Layer / File(s) Summary
Indexer offsets and full-KV mappings
tensorrt_llm/_torch/attention_backend/sparse/dsa.py
Indexer preparation uses manager-provided page parameters. Full context-KV gather mappings are recomputed through a shared utility. Packed FP4 gathering uses half the logical head dimension.

KV cache manager selection and compatibility

Layer / File(s) Summary
KV cache manager selection and compatibility
tensorrt_llm/_torch/attention_backend/sparse/utils.py, tensorrt_llm/_torch/pyexecutor/_util.py, tensorrt_llm/_torch/models/modeling_deepseekv3.py, tests/unittest/_torch/executor/test_mamba_cache_manager.py, tests/unittest/llmapi/test_config_database.py, docs/source/features/kvcache.md, tests/integration/defs/accuracy/test_llm_api_pytorch.py
Runtime routing forwards the V2 selection flag and rejects DSA with STAR context parallelism. DeepSeek V3 defaults to V2. Configuration tests preserve nested defaults, and documentation describes V1, V2, and automatic selection.

Stable pool representatives and mapping validation

Layer / File(s) Summary
Stable pool representatives and mapping validation
tensorrt_llm/_torch/pyexecutor/kv_cache_manager_v2.py, tests/unittest/_torch/executor/test_kv_cache_v2_extra_buffers.py
Pool mapping and page-table initialization use configuration-order representative layers. Regression tests verify behavior when internal layer grouping is reordered.

Indexer mappings and draft replay restoration

Layer / File(s) Summary
Indexer mappings and draft replay restoration
tensorrt_llm/_torch/attention_backend/trtllm.py, tensorrt_llm/_torch/speculative/interface.py, tensorrt_llm/_torch/modules/mla.py, tensorrt_llm/_torch/pyexecutor/model_engine.py, tests/unittest/_torch/attention/sparse/dsa/test_dsa_indexer.py
FlashMLA receives dedicated draft buffers. Draft replay swaps and restores FlashMLA and DSA metadata, including cached-KV full mappings. Sparse FlashMLA derives the active layer index from attention metadata.

Kernel documentation and supporting metadata

Layer / File(s) Summary
Kernel documentation and supporting metadata
cpp/tensorrt_llm/kernels/IndexerKCacheGather.h, cpp/tensorrt_llm/kernels/IndexerKCacheScatter.h, cpp/tensorrt_llm/kernels/indexerKCacheGather.cu, cpp/tensorrt_llm/kernels/indexerKCacheScatter.cu, tests/unittest/_torch/attention/sparse/test_cpp_custom_ops.py, tests/unittest/_torch/speculative/test_eagle3.py
Copyright headers and kernel parameter comments are updated. The custom-operator documentation lists the scatter operator.

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

Sequence Diagram(s)

sequenceDiagram
  participant LLMConfig
  participant get_sparse_attn_kv_cache_manager
  participant DSACacheManagerV2
  participant DSAtrtllmAttentionMetadata
  participant prepare_attn_metadata_for_draft_replay
  LLMConfig->>get_sparse_attn_kv_cache_manager: select KV cache manager V2
  get_sparse_attn_kv_cache_manager->>DSACacheManagerV2: construct DSA V2 manager
  DSACacheManagerV2->>DSAtrtllmAttentionMetadata: provide page parameters and cache buffers
  prepare_attn_metadata_for_draft_replay->>DSAtrtllmAttentionMetadata: bind draft buffers and recompute mappings
  DSAtrtllmAttentionMetadata-->>prepare_attn_metadata_for_draft_replay: restore target metadata after replay
Loading

Possibly related PRs

Suggested reviewers: bowenfu, qijune, tburt-nv

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 59.55% 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
Title check ✅ Passed The title clearly identifies the feature and matches the primary change: DSA KV cache manager V2 support.
Description check ✅ Passed The description explains the change, lists relevant test coverage, and includes the required checklist with the review confirmation checked.
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.

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

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

yizhang-nv and others added 3 commits August 6, 2026 23:09
Signed-off-by: yizhang-nv <187001205+yizhang-nv@users.noreply.github.com>
Signed-off-by: Yi Zhang <187001205+yizhang-nv@users.noreply.github.com>
Signed-off-by: Yi Zhang <187001205+yizhang-nv@users.noreply.github.com>
@coderabbitai

coderabbitai Bot commented Aug 7, 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.

@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: 3

🧹 Nitpick comments (2)
tests/unittest/_torch/speculative/test_eagle3.py (1)

344-373: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Consider asserting the draft buffer dtype and device.

The test verifies shapes and distinct storage. It does not verify that the draft buffers use the same dtype and device as the target buffers. A regression that allocates the draft buffers on CPU would still pass. Add dtype and device assertions to close that gap.

♻️ Proposed additional assertions
         assert metadata.draft_block_ids_per_seq.shape == (num_seqs, 7)
         assert metadata.draft_kv_block_ids_per_seq.shape == (num_seqs, 7)
+        assert (metadata.draft_block_ids_per_seq.dtype ==
+                metadata.block_ids_per_seq.dtype)
+        assert (metadata.draft_block_ids_per_seq.device ==
+                metadata.block_ids_per_seq.device)
🤖 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/speculative/test_eagle3.py` around lines 344 - 373,
Extend test_separate_draft_flash_mla_buffers_use_manager_geometry to assert that
draft_block_ids_per_seq and draft_kv_block_ids_per_seq have the same dtype and
device as the corresponding target buffers, while preserving the existing shape
and distinct-storage checks.
tensorrt_llm/_torch/models/modeling_deepseekv3.py (1)

1912-1915: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add precise type annotations to get_model_defaults.

Annotate llm_args with TorchLlmArgs. Replace dict with a parameterized return type that describes the nested default structure. This method is a public model-default interface.

🤖 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/models/modeling_deepseekv3.py` around lines 1912 - 1915,
Update the classmethod get_model_defaults by annotating llm_args with
TorchLlmArgs and replacing the unparameterized dict return annotation with a
precise parameterized type describing the nested kv_cache_config and
use_kv_cache_manager_v2 default structure.

Source: Coding guidelines

🤖 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 `@docs/source/features/kvcache.md`:
- Around line 49-65: Add the repository-standard Markdown-compatible NVIDIA
copyright header at the beginning of docs/source/features/kvcache.md, using 2026
as the latest meaningful-modification year and preserving the existing document
content.

In `@tensorrt_llm/_torch/modules/mla.py`:
- Around line 3055-3059: The local layer index used by
transform_local_topk_and_prepare_pool_view must be recomputed for the currently
active KV-cache manager rather than reused across managers. Update the
trtllm_attention.get_local_layer_idx(attn_metadata) flow to invalidate or
refresh any cached value when speculative decoding switches between target and
draft managers, preserving the correct manager-specific offset.

In `@tests/unittest/_torch/executor/test_mamba_cache_manager.py`:
- Around line 688-712: Update
test_dsa_star_rejects_v2_and_keeps_explicit_v1_selection to exercise
get_kv_cache_manager_cls() with use_kv_cache_manager_v2=False, and assert that
it returns DSACacheManager. Keep the existing V2 STAR rejection assertion, but
do not pass KVCacheManager directly because that bypasses the DSA-specific
selector.

---

Nitpick comments:
In `@tensorrt_llm/_torch/models/modeling_deepseekv3.py`:
- Around line 1912-1915: Update the classmethod get_model_defaults by annotating
llm_args with TorchLlmArgs and replacing the unparameterized dict return
annotation with a precise parameterized type describing the nested
kv_cache_config and use_kv_cache_manager_v2 default structure.

In `@tests/unittest/_torch/speculative/test_eagle3.py`:
- Around line 344-373: Extend
test_separate_draft_flash_mla_buffers_use_manager_geometry to assert that
draft_block_ids_per_seq and draft_kv_block_ids_per_seq have the same dtype and
device as the corresponding target buffers, while preserving the existing shape
and distinct-storage checks.
🪄 Autofix

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: 268467b1-518f-4303-8445-ce8cfa4719b1

📥 Commits

Reviewing files that changed from the base of the PR and between 92e7c88 and 67e3234.

📒 Files selected for processing (22)
  • cpp/tensorrt_llm/kernels/IndexerKCacheGather.h
  • cpp/tensorrt_llm/kernels/IndexerKCacheScatter.h
  • cpp/tensorrt_llm/kernels/indexerKCacheGather.cu
  • cpp/tensorrt_llm/kernels/indexerKCacheScatter.cu
  • docs/source/features/kvcache.md
  • tensorrt_llm/_torch/attention_backend/sparse/dsa.py
  • tensorrt_llm/_torch/attention_backend/sparse/utils.py
  • tensorrt_llm/_torch/attention_backend/trtllm.py
  • tensorrt_llm/_torch/models/modeling_deepseekv3.py
  • tensorrt_llm/_torch/modules/mla.py
  • tensorrt_llm/_torch/pyexecutor/_util.py
  • tensorrt_llm/_torch/pyexecutor/kv_cache_manager_v2.py
  • tensorrt_llm/_torch/pyexecutor/model_engine.py
  • tensorrt_llm/_torch/speculative/interface.py
  • tests/integration/defs/accuracy/test_llm_api_pytorch.py
  • tests/unittest/_torch/attention/sparse/dsa/test_dsa_indexer.py
  • tests/unittest/_torch/attention/sparse/test_cpp_custom_ops.py
  • tests/unittest/_torch/executor/test_kv_cache_v2_extra_buffers.py
  • tests/unittest/_torch/executor/test_mamba_cache_manager.py
  • tests/unittest/_torch/speculative/test_eagle3.py
  • tests/unittest/llmapi/test_config_database.py
  • tests/unittest/llmapi/test_llm_args.py
🚧 Files skipped from review as they are similar to previous changes (8)
  • cpp/tensorrt_llm/kernels/indexerKCacheGather.cu
  • tests/unittest/_torch/attention/sparse/test_cpp_custom_ops.py
  • tests/integration/defs/accuracy/test_llm_api_pytorch.py
  • cpp/tensorrt_llm/kernels/IndexerKCacheGather.h
  • cpp/tensorrt_llm/kernels/IndexerKCacheScatter.h
  • tensorrt_llm/_torch/attention_backend/sparse/utils.py
  • cpp/tensorrt_llm/kernels/indexerKCacheScatter.cu
  • tensorrt_llm/_torch/speculative/interface.py

Comment thread docs/source/features/kvcache.md Outdated
Comment thread tensorrt_llm/_torch/modules/mla.py
Comment thread tests/unittest/_torch/executor/test_mamba_cache_manager.py
Signed-off-by: Yi Zhang <187001205+yizhang-nv@users.noreply.github.com>
@yizhang-nv
yizhang-nv force-pushed the codex/dsa-kv-cache-v2-main branch from 67e3234 to 4f86a5e Compare August 7, 2026 06:46
@coderabbitai

coderabbitai Bot commented Aug 7, 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.

@yizhang-nv

Copy link
Copy Markdown
Member Author

/bot run --disable-fail-fast

@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: 2

🧹 Nitpick comments (1)
tensorrt_llm/_torch/models/modeling_deepseekv3.py (1)

1912-1915: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Apply the required type annotations to both new functions.

Both changed functions omit required type information.

  • tensorrt_llm/_torch/models/modeling_deepseekv3.py#L1912-L1915: annotate llm_args and replace bare dict with a precise return type.
  • tests/unittest/llmapi/test_llm_args.py#L4000-L4001: annotate all parameters and add -> None.

As per coding guidelines: annotate every function and use precise types.

🤖 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/models/modeling_deepseekv3.py` around lines 1912 - 1915,
Apply precise type annotations to both new functions: in
tensorrt_llm/_torch/models/modeling_deepseekv3.py:1912-1915, annotate
get_model_defaults’s llm_args parameter and replace the bare dict return type
with the appropriate precise mapping type; in
tests/unittest/llmapi/test_llm_args.py:4000-4001, annotate every parameter of
the affected test function and add -> None.

Source: Coding guidelines

🤖 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/models/modeling_deepseekv3.py`:
- Around line 1-3: Remove the executable permission from the importable module
modeling_deepseekv3.py to resolve Ruff EXE002; do not add a shebang unless
direct execution is intentionally supported.

In `@tests/unittest/llmapi/test_llm_args.py`:
- Around line 3990-4024: Extend the parameterized cases in
test_deepseek_v3_family_kv_cache_manager_v2_default with a non-V3-family
architecture that resolves to a model class without the V2 default, using the
"auto" setting and expected value False. Keep the existing positive and
explicit-False cases unchanged.

---

Nitpick comments:
In `@tensorrt_llm/_torch/models/modeling_deepseekv3.py`:
- Around line 1912-1915: Apply precise type annotations to both new functions:
in tensorrt_llm/_torch/models/modeling_deepseekv3.py:1912-1915, annotate
get_model_defaults’s llm_args parameter and replace the bare dict return type
with the appropriate precise mapping type; in
tests/unittest/llmapi/test_llm_args.py:4000-4001, annotate every parameter of
the affected test function and add -> None.
🪄 Autofix

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: 0e3f9a47-5a20-48b6-b561-17ab55c7b474

📥 Commits

Reviewing files that changed from the base of the PR and between 95e76ba and 4f86a5e.

📒 Files selected for processing (21)
  • cpp/tensorrt_llm/kernels/IndexerKCacheGather.h
  • cpp/tensorrt_llm/kernels/IndexerKCacheScatter.h
  • cpp/tensorrt_llm/kernels/indexerKCacheGather.cu
  • cpp/tensorrt_llm/kernels/indexerKCacheScatter.cu
  • tensorrt_llm/_torch/attention_backend/sparse/dsa.py
  • tensorrt_llm/_torch/attention_backend/sparse/utils.py
  • tensorrt_llm/_torch/attention_backend/trtllm.py
  • tensorrt_llm/_torch/models/modeling_deepseekv3.py
  • tensorrt_llm/_torch/modules/mla.py
  • tensorrt_llm/_torch/pyexecutor/_util.py
  • tensorrt_llm/_torch/pyexecutor/kv_cache_manager_v2.py
  • tensorrt_llm/_torch/pyexecutor/model_engine.py
  • tensorrt_llm/_torch/speculative/interface.py
  • tests/integration/defs/accuracy/test_llm_api_pytorch.py
  • tests/unittest/_torch/attention/sparse/dsa/test_dsa_indexer.py
  • tests/unittest/_torch/attention/sparse/test_cpp_custom_ops.py
  • tests/unittest/_torch/executor/test_kv_cache_v2_extra_buffers.py
  • tests/unittest/_torch/executor/test_mamba_cache_manager.py
  • tests/unittest/_torch/speculative/test_eagle3.py
  • tests/unittest/llmapi/test_config_database.py
  • tests/unittest/llmapi/test_llm_args.py
🚧 Files skipped from review as they are similar to previous changes (18)
  • tests/unittest/_torch/attention/sparse/test_cpp_custom_ops.py
  • tensorrt_llm/_torch/pyexecutor/model_engine.py
  • tests/unittest/_torch/executor/test_mamba_cache_manager.py
  • tests/integration/defs/accuracy/test_llm_api_pytorch.py
  • tensorrt_llm/_torch/modules/mla.py
  • tensorrt_llm/_torch/attention_backend/sparse/utils.py
  • tests/unittest/_torch/speculative/test_eagle3.py
  • tests/unittest/llmapi/test_config_database.py
  • cpp/tensorrt_llm/kernels/IndexerKCacheGather.h
  • tensorrt_llm/_torch/pyexecutor/kv_cache_manager_v2.py
  • tests/unittest/_torch/executor/test_kv_cache_v2_extra_buffers.py
  • cpp/tensorrt_llm/kernels/indexerKCacheGather.cu
  • cpp/tensorrt_llm/kernels/indexerKCacheScatter.cu
  • cpp/tensorrt_llm/kernels/IndexerKCacheScatter.h
  • tensorrt_llm/_torch/speculative/interface.py
  • tensorrt_llm/_torch/attention_backend/trtllm.py
  • tensorrt_llm/_torch/pyexecutor/_util.py
  • tensorrt_llm/_torch/attention_backend/sparse/dsa.py

Comment thread tensorrt_llm/_torch/models/modeling_deepseekv3.py
Comment thread tests/unittest/llmapi/test_llm_args.py Outdated
@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #64538 [ run ] triggered by Bot. Commit: 4f86a5e Link to invocation

Comment thread tensorrt_llm/_torch/pyexecutor/kv_cache_manager_v2.py Outdated
Signed-off-by: Yi Zhang <187001205+yizhang-nv@users.noreply.github.com>

@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 `@docs/source/features/kvcache.md`:
- Around line 54-70: The KV Cache Manager Version section incorrectly describes
universal V2 selection and error behavior. Update the documentation to state
that use_kv_cache_manager_v2 only selects V1 versus V2 for DSA, while other
sparse algorithms ignore it; document NotImplementedError for connectors, beam
width greater than one, and DSA with STAR, and the base KVCacheManagerV2
AssertionError for STAR in other V2 managers.
🪄 Autofix

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: 8735da93-714c-4e5f-8a00-36fc84d53cd6

📥 Commits

Reviewing files that changed from the base of the PR and between 4f86a5e and 8a891d7.

📒 Files selected for processing (6)
  • docs/source/features/kvcache.md
  • tensorrt_llm/_torch/models/modeling_deepseekv3.py
  • tensorrt_llm/_torch/pyexecutor/kv_cache_manager_v2.py
  • tests/unittest/_torch/attention/sparse/dsa/test_dsa_indexer.py
  • tests/unittest/_torch/executor/test_kv_cache_v2_extra_buffers.py
  • tests/unittest/_torch/speculative/test_eagle3.py
💤 Files with no reviewable changes (2)
  • tests/unittest/_torch/speculative/test_eagle3.py
  • tests/unittest/_torch/attention/sparse/dsa/test_dsa_indexer.py
🚧 Files skipped from review as they are similar to previous changes (3)
  • tensorrt_llm/_torch/pyexecutor/kv_cache_manager_v2.py
  • tests/unittest/_torch/executor/test_kv_cache_v2_extra_buffers.py
  • tensorrt_llm/_torch/models/modeling_deepseekv3.py

Comment thread docs/source/features/kvcache.md Outdated
Comment on lines +54 to +70
### KV Cache Manager Version

`KvCacheConfig.use_kv_cache_manager_v2` selects the V2 manager; `"auto"` uses
the model-specific default. When a sparse-attention model selects V2,
TensorRT LLM raises `NotImplementedError` for V2-incompatible features instead
of silently falling back to the V1 manager.

`DeepseekV3ForCausalLM`, `DeepseekV32ForCausalLM`,
`GlmMoeDsaForCausalLM`, and `MistralLarge3ForCausalLM` select V2 by default
when this option is `"auto"`. Set the option to `false` to select V1
explicitly.

For DSA, KV cache manager V2 does not support STAR context parallelism. Use
another context-parallel mode, or set
`kv_cache_config.use_kv_cache_manager_v2: false` to use the DSA V1 cache
manager with STAR.

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.

🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

rg -n -C 8 \
  'use_kv_cache_manager_v2|NotImplementedError|STAR|context_parallel' \
  tensorrt_llm/_torch/attention_backend/sparse/utils.py \
  tensorrt_llm/_torch/pyexecutor/_util.py \
  tensorrt_llm/_torch/models/modeling_deepseekv3.py

rg -n -C 5 \
  'get_model_defaults|use_kv_cache_manager_v2' \
  tensorrt_llm/_torch/models

Repository: NVIDIA/TensorRT-LLM

Length of output: 50375


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- documented section ---'
sed -n '1,95p' docs/source/features/kvcache.md

printf '%s\n' '--- V2 validation path ---'
sed -n '600,675p' tensorrt_llm/_torch/pyexecutor/_util.py

printf '%s\n' '--- sparse manager selection ---'
sed -n '1,55p' tensorrt_llm/_torch/attention_backend/sparse/utils.py

printf '%s\n' '--- listed model registrations and defaults ---'
rg -n -C 4 \
  'DeepseekV3ForCausalLM|DeepseekV32ForCausalLM|GlmMoeDsaForCausalLM|MistralLarge3ForCausalLM|use_kv_cache_manager_v2' \
  tensorrt_llm/_torch/models \
  -g '*.py' | head -n 240

printf '%s\n' '--- relevant call sites and config semantics ---'
rg -n -C 5 \
  '_kv_cache_manager_v2|use_kv_cache_manager_v2.*False|use_kv_cache_manager_v2.*True|_create_kv_cache_manager' \
  tensorrt_llm/_torch/pyexecutor/_util.py \
  tensorrt_llm/_torch \
  -g '*.py' | head -n 300

Repository: NVIDIA/TensorRT-LLM

Length of output: 50377


🏁 Script executed:

#!/bin/bash
set -euo pipefail

python3 - <<'PY'
import ast
from pathlib import Path

files = [
    Path("tensorrt_llm/_torch/models/modeling_deepseekv3.py"),
    Path("tensorrt_llm/_torch/models/modeling_mistral_large3.py"),
    Path("tensorrt_llm/_torch/pyexecutor/_util.py"),
    Path("tensorrt_llm/_torch/attention_backend/sparse/utils.py"),
]
trees = {p: ast.parse(p.read_text()) for p in files}

print("--- registered model names and inherited defaults ---")
for path, tree in trees.items():
    for node in ast.walk(tree):
        if isinstance(node, ast.ClassDef):
            registrations = []
            for dec in node.decorator_list:
                if (isinstance(dec, ast.Call) and isinstance(dec.func, ast.Name)
                        and dec.func.id == "register_auto_model"
                        and dec.args and isinstance(dec.args[0], ast.Constant)):
                    registrations.append(dec.args[0].value)
            if registrations or node.name == "MistralLarge3ForCausalLM":
                methods = {n.name for n in node.body if isinstance(n, ast.FunctionDef)}
                print(path, node.name, "bases=", [
                    ast.unparse(base) for base in node.bases
                ], "registered=", registrations,
                      "defines_get_model_defaults=",
                      "get_model_defaults" in methods)

print("--- sparse manager branches ---")
sparse_tree = trees[Path("tensorrt_llm/_torch/attention_backend/sparse/utils.py")]
for node in ast.walk(sparse_tree):
    if isinstance(node, ast.FunctionDef) and node.name == "get_sparse_attn_kv_cache_manager":
        for child in ast.walk(node):
            if isinstance(child, ast.Return):
                print(ast.unparse(child.value))

print("--- V2 validation exception branches ---")
util_tree = trees[Path("tensorrt_llm/_torch/pyexecutor/_util.py")]
for node in ast.walk(util_tree):
    if isinstance(node, ast.FunctionDef) and node.name == "_validate_or_fallback_kv_cache_manager_v2":
        for child in ast.walk(node):
            if isinstance(child, ast.Raise):
                print(ast.unparse(child))
PY

printf '%s\n' '--- option declaration and auto-resolution references ---'
rg -n -C 6 \
  'use_kv_cache_manager_v2\s*:|use_kv_cache_manager_v2.*auto|model defaults|model_defaults|get_model_defaults' \
  tensorrt_llm/llmapi tensorrt_llm/_torch \
  -g '*.py' | head -n 260

Repository: NVIDIA/TensorRT-LLM

Length of output: 22923


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- DSA cache-manager STAR handling ---'
rg -n -C 8 \
  'class DSACacheManager|class DSACacheManagerV2|CpType\.STAR|cp_type|context_parallel' \
  tensorrt_llm/_torch/attention_backend/sparse \
  tensorrt_llm/_torch/pyexecutor \
  -g '*.py' | head -n 360

printf '%s\n' '--- DSA and STAR tests/configuration ---'
rg -n -C 5 \
  'dsa|DSA|STAR|use_kv_cache_manager_v2' \
  tests \
  docs \
  examples \
  -g '*.py' -g '*.yaml' -g '*.yml' -g '*.md' | head -n 360

Repository: NVIDIA/TensorRT-LLM

Length of output: 50375


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- MiniMax V2 construction and STAR path ---'
rg -n -C 18 \
  'class MiniMaxM3KVCacheManagerV2|class DeepseekV4CacheManager|super\(\).__init__|CpType\.STAR|Star attention is not supported' \
  tensorrt_llm/_torch/attention_backend/sparse/minimax_m3.py \
  tensorrt_llm/_torch/attention_backend/sparse/deepseek_v4.py \
  tensorrt_llm/_torch/pyexecutor/kv_cache_manager_v2.py \
  -g '*.py'

printf '%s\n' '--- sparse algorithms and V2 manager classes ---'
python3 - <<'PY'
import ast
from pathlib import Path

path = Path("tensorrt_llm/_torch/attention_backend/sparse/utils.py")
tree = ast.parse(path.read_text())
for node in ast.walk(tree):
    if isinstance(node, ast.FunctionDef) and node.name == "get_sparse_attn_kv_cache_manager":
        for branch in node.body:
            if isinstance(branch, ast.If):
                print(ast.unparse(branch.test), "=>", ast.unparse(branch.body[-1]))
            elif isinstance(branch, ast.Return):
                print("return", ast.unparse(branch.value))
PY

printf '%s\n' '--- exact sparse V2 incompatibility gate ---'
sed -n '611,665p' tensorrt_llm/_torch/pyexecutor/_util.py

Repository: NVIDIA/TensorRT-LLM

Length of output: 4150


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- locate sparse manager implementations ---'
fd -t f -i 'minimax.*m3|deepseek.*v4|dsa' tensorrt_llm/_torch/attention_backend
fd -t f 'minimax_m3.py' 'deepseek_v4.py' tensorrt_llm/_torch

printf '%s\n' '--- locate V2 subclasses and constructors ---'
rg -l 'class MiniMaxM3KVCacheManagerV2|class DeepseekV4CacheManager' \
  tensorrt_llm/_torch/attention_backend/sparse
rg -n -C 15 \
  'class MiniMaxM3KVCacheManagerV2|class DeepseekV4CacheManager|super\(\).__init__' \
  tensorrt_llm/_torch/attention_backend/sparse \
  -g '*.py' | head -n 260

Repository: NVIDIA/TensorRT-LLM

Length of output: 28827


Align the section with sparse-manager routing.

  • NotImplementedError covers KV connectors, beam width greater than one, and DSA with STAR. Other V2 managers can reach a base KVCacheManagerV2 AssertionError for STAR.
  • use_kv_cache_manager_v2 selects between V1 and V2 only for DSA. Other sparse algorithms ignore this option.
  • Update the documentation or expand validation to provide one consistent error contract.
🤖 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 `@docs/source/features/kvcache.md` around lines 54 - 70, The KV Cache Manager
Version section incorrectly describes universal V2 selection and error behavior.
Update the documentation to state that use_kv_cache_manager_v2 only selects V1
versus V2 for DSA, while other sparse algorithms ignore it; document
NotImplementedError for connectors, beam width greater than one, and DSA with
STAR, and the base KVCacheManagerV2 AssertionError for STAR in other V2
managers.

Signed-off-by: Yi Zhang <187001205+yizhang-nv@users.noreply.github.com>
@yizhang-nv

Copy link
Copy Markdown
Member Author

/bot run --disable-fail-fast

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #64549 [ run ] triggered by Bot. Commit: 4282bb1 Link to invocation

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #64538 [ run ] completed with state ABORTED. Commit: 4f86a5e

Link to invocation

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #64549 [ run ] completed with state FAILURE. Commit: 4282bb1
/LLM/main/L0_MergeRequest_PR pipeline #52414 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

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.

7 participants