Skip to content

[None][feat] Batched physical KV-cache compaction for KV cache compression - #16836

Merged
Hudayday merged 8 commits into
NVIDIA:mainfrom
Hudayday:feat/compaction-for-kv-cache-compression
Jul 28, 2026
Merged

[None][feat] Batched physical KV-cache compaction for KV cache compression#16836
Hudayday merged 8 commits into
NVIDIA:mainfrom
Hudayday:feat/compaction-for-kv-cache-compression

Conversation

@Hudayday

@Hudayday Hudayday commented Jul 24, 2026

Copy link
Copy Markdown
Collaborator

Description

First PR of the TriAttention KV-cache compression series (compaction primitive → eviction algorithm).

This adds an algorithm-neutral, batched physical compaction primitive for
KVCacheManagerV2 paged KV pools: given per-request keep decisions (kept token
ordinals plus per-request move offsets), it packs the move sources and compacts
the pools in place, so a KV cache compression method can physically drop evicted
tokens instead of masking them.

CUDA / C++

  • unfusedAttentionKernels_2_template.h: batched in-place compaction kernels —
    one launch covers a uniform group of layer pools; per request and KV head the
    moves are ascending and never overtake their sources, which makes the forward
    tiled in-place copy safe.
  • thop/sparseKvCacheCompactOp.cpp: trtllm::sparse_kv_cache_compact_layers,
    taking device pointer arrays so one call compacts a whole pool group.

Python host API (tensorrt_llm/_torch/kv_cache_compression/compaction.py)

  • build_compaction_params(layout, ...) -> CompactionParams: called once per
    cache geometry; pre-binds every launch argument (a Triton pack kernel plus the
    native compact calls). Supports dense and sliding-window layer families, and
    an optional draft cache co-compacted under the target's keep decision.
  • compact(params, request_count): the per-round entry — pure pre-bound
    launches, no host-side construction on the generation path.

Framework

  • Rename BaseKVCacheCompressionManagerKVCacheCompressionManager.
  • The steady-generation fast path takes the full prepare path when
    kv_compression_manages_history is set (the cache shrinks mid-generation).

Supported surface: BF16 paged pools in the native [pages, K/V, heads, tokens, dim] layout; kernels target SM100 (Blackwell).

Test Coverage

  • tests/unittest/_torch/kv_cache_compression/test_compaction.py — byte-exact
    oracles against torch references: dense keep set + protected tail, SWA window
    rebase, and draft co-compaction broadcast over the draft's own heads/tables.
  • tests/unittest/_torch/thop/serial/test_sparse_kv_cache_compact.py — native
    op contract: supported geometries, argument validation, and CUDA-graph
    capture safety.
  • tests/unittest/_torch/executor/test_kv_cache_compression_manager.py
    manager rename covered by the existing framework tests.

Dev Engineer Review

  • Added an algorithm-neutral, batched physical KV-cache compaction path for KVCacheManagerV2 paged pools, focused on SM100 BF16 “native” pools ([pages, K/V, heads, tokens, dim]).
  • CUDA/C++ native support:
    • Introduced invokeSparseKvCacheCompactLayers kernel entry-point declaration/wiring in cpp/tensorrt_llm/kernels/unfusedAttentionKernels.h and unfusedAttentionKernels_2_template.h.
    • Implemented a BF16 pipelined compaction kernel using cp.async (double-buffered pipeline) for the layered V2 “sparse KV compaction” fast path, including explicit rejection of unsupported launch geometry combinations.
    • Added the new Torch custom op sparse_kv_cache_compact_layers (cpp/tensorrt_llm/thop/sparseKvCacheCompactOp.cpp) with strict runtime validation of tensor dtype/device/shape/contiguity/layout invariants and BF16-only dispatch to the new compact layers kernel path.
    • Updated build wiring to compile and link the op (cpp/tensorrt_llm/thop/CMakeLists.txt) and added the BF16 explicit instantiation needed for symbol availability (unfusedAttentionKernels_2_bf16_bf16.cu).
  • Python/Triton orchestration:
    • Added tensorrt_llm/_torch/kv_cache_compression/compaction.py with build_compaction_params(...) and compact(...) to pre-bind compaction tensors/geometry, run a Triton packing kernel, and invoke the native op per prepared group bundle.
    • Supports dense and masked sliding-window/SWA layer families, plus optional target+draft co-compaction packing/move-offset handling.
  • Compression/history integration:
    • Updated steady-generation “fast path” cache recording guard to skip when the active kv_cache_manager reports kv_compression_manages_history=True (tensorrt_llm/_torch/pyexecutor/model_engine.py).
  • API consistency:
    • Renamed BaseKVCacheCompressionManagerKVCacheCompressionManager and updated related typing/util references and unit tests (tensorrt_llm/_torch/pyexecutor/resource_manager.py, tensorrt_llm/_torch/pyexecutor/_util.py, corresponding unittest updates).

QA Engineer Review

Test files changed/added (unit tests):

  • tests/unittest/_torch/executor/test_kv_cache_compression_manager.py
  • tests/unittest/_torch/kv_cache_compression/conftest.py
  • tests/unittest/_torch/kv_cache_compression/test_compaction.py
  • tests/unittest/_torch/thop/serial/test_sparse_kv_cache_compact.py

New/updated test coverage:

  • Manager rename + lifecycle-hook contract tests and related guards: updated suite in test_kv_cache_compression_manager.py.
  • Compaction correctness:
    • Dense compaction correctness (exact byte preservation + tail oracle) for multiple eviction modes.
    • Masked sliding-window/SWA rebasing correctness with protected tails.
    • Draft co-compaction correctness including packed/kept set alignment and expected draft move offsets.
  • Native op validation (Torch/thop serial):
    • CPU-reference correctness for small and production-shaped geometries.
    • CUDA graph replay safety and invalid launch rejection checks.
    • Kernel-name/event assertions to ensure the intended fast path is exercised.

Coverage in tests/integration/test_lists/:

  • No tests/integration/test_lists/ entries were modified/detected in the workspace check; therefore, CI/manual coverage mapping for these new unit tests needs follow-up.

Verdict: needs follow-up.

Hudayday added 3 commits July 24, 2026 01:57
…ssion

Signed-off-by: tianruih <tianruih@nvidia.com>
Signed-off-by: tianruih <tianruih@nvidia.com>
@Hudayday

Copy link
Copy Markdown
Collaborator Author

/bot run --disable-fail-fast

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #61550 [ run ] triggered by Bot. Commit: 788ff96 Link to invocation

@coderabbitai

coderabbitai Bot commented Jul 24, 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

Adds BF16 sparse KV-cache compaction through a CUDA kernel, Torch operator, Python/Triton orchestration, and validation tests. Also renames the KV compression manager abstraction and guards the executor fast path when compression manages history.

Changes

Sparse KV cache compaction

Layer / File(s) Summary
BF16 compaction kernel
cpp/tensorrt_llm/kernels/unfusedAttentionKernels*
Adds the compaction contract and BF16 cp.async-pipelined kernel for supported geometries.
Torch operator integration
cpp/tensorrt_llm/thop/*, tests/unittest/_torch/thop/serial/*
Registers, builds, validates, dispatches, and tests the sparse KV compaction operator.
Python compaction planning
tensorrt_llm/_torch/kv_cache_compression/compaction.py
Adds Triton move-source packing, grouped launch preparation, and native compaction execution.
Python compaction validation
tests/unittest/_torch/kv_cache_compression/*
Tests selected-token ordering, protected tails, SWA rebasing, draft pools, and move offsets.
Compression manager integration
tensorrt_llm/_torch/pyexecutor/*, tests/unittest/_torch/executor/*
Renames the compression manager, updates typing and tests, and excludes history-managed compression from the steady-generation fast path.

Estimated code review effort: 5 (Critical) | ~120 minutes

Suggested reviewers: bowenfu, zhaoyangwang-nvidia, junyixu-nv, reasonsolo, brnguyen2

Sequence Diagram(s)

sequenceDiagram
  participant PythonCompaction
  participant TritonPackKernel
  participant sparse_kv_cache_compact_layers
  participant BF16CompactionKernel
  PythonCompaction->>TritonPackKernel: pack keep decisions into move sources
  PythonCompaction->>sparse_kv_cache_compact_layers: submit grouped pool compaction
  sparse_kv_cache_compact_layers->>BF16CompactionKernel: launch validated BF16 geometry
  BF16CompactionKernel->>BF16CompactionKernel: copy selected K/V tiles into destination pages
Loading
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 32.56% 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 is concise and accurately summarizes the main change: batched physical KV-cache compaction.
Description check ✅ Passed The description covers the feature, implementation details, and test coverage, matching the template well.
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: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
tests/unittest/_torch/kv_cache_compression/test_compaction.py (1)

1-325: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Add the new compaction tests to CI/QA lists and guard the SM100-only cases.

  • Added test functions: test_eager_compaction_preserves_exact_selected_bytes_and_tail, test_eager_compaction_rebases_masked_swa_window_and_tail, test_draft_moves_and_pack_match_keep_broadcast_and_tail_oracle.
  • I don’t see entries for tests/unittest/_torch/kv_cache_compression/test_compaction.py in tests/integration/test_lists/test-db/ or qa/; add this file there.
  • Add @requires_sm100 to test_eager_compaction_preserves_exact_selected_bytes_and_tail and test_draft_moves_and_pack_match_keep_broadcast_and_tail_oracle; only the SWA test is currently guarded.

Coverage verdict: needs 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/kv_cache_compression/test_compaction.py` around lines 1
- 325, Add tests/unittest/_torch/kv_cache_compression/test_compaction.py to the
relevant CI/QA test lists under tests/integration/test_lists/test-db/ and qa/.
Apply the existing requires_sm100 marker to
test_eager_compaction_preserves_exact_selected_bytes_and_tail and
test_draft_moves_and_pack_match_keep_broadcast_and_tail_oracle, matching the
guard already used by test_eager_compaction_rebases_masked_swa_window_and_tail.

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 `@tests/unittest/_torch/kv_cache_compression/test_compaction.py`:
- Around line 30-31: Add the existing `@requires_sm100` decorator to
test_eager_compaction_preserves_exact_selected_bytes_and_tail and
test_draft_moves_and_pack_match_keep_broadcast_and_tail_oracle. Keep their
current parametrization and test bodies unchanged so both GPU-only tests skip on
non-SM100 or unavailable CUDA environments.

In `@tests/unittest/_torch/thop/serial/test_sparse_kv_cache_compact.py`:
- Around line 189-442: Add the four new test
functions—test_sparse_kv_cache_compact_layers,
test_sparse_kv_cache_compact_layers_cuda_graph_replay,
test_sparse_kv_cache_compact_layers_fast_geometry, and
test_sparse_kv_cache_compact_layers_rejects_invalid_launch—to the appropriate
integration test-list entries under the test-db and QA lists. Preserve the
existing list format and ensure each test is registered for CI/manual QA
execution.

---

Outside diff comments:
In `@tests/unittest/_torch/kv_cache_compression/test_compaction.py`:
- Around line 1-325: Add
tests/unittest/_torch/kv_cache_compression/test_compaction.py to the relevant
CI/QA test lists under tests/integration/test_lists/test-db/ and qa/. Apply the
existing requires_sm100 marker to
test_eager_compaction_preserves_exact_selected_bytes_and_tail and
test_draft_moves_and_pack_match_keep_broadcast_and_tail_oracle, matching the
guard already used by test_eager_compaction_rebases_masked_swa_window_and_tail.
🪄 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: adf9b668-beac-434e-9638-815dd2f8713e

📥 Commits

Reviewing files that changed from the base of the PR and between 75b39d4 and 788ff96.

📒 Files selected for processing (12)
  • cpp/tensorrt_llm/kernels/unfusedAttentionKernels.h
  • cpp/tensorrt_llm/kernels/unfusedAttentionKernels/unfusedAttentionKernels_2_template.h
  • cpp/tensorrt_llm/thop/CMakeLists.txt
  • cpp/tensorrt_llm/thop/sparseKvCacheCompactOp.cpp
  • tensorrt_llm/_torch/kv_cache_compression/compaction.py
  • tensorrt_llm/_torch/pyexecutor/_util.py
  • tensorrt_llm/_torch/pyexecutor/model_engine.py
  • tensorrt_llm/_torch/pyexecutor/resource_manager.py
  • tests/unittest/_torch/executor/test_kv_cache_compression_manager.py
  • tests/unittest/_torch/kv_cache_compression/conftest.py
  • tests/unittest/_torch/kv_cache_compression/test_compaction.py
  • tests/unittest/_torch/thop/serial/test_sparse_kv_cache_compact.py

Comment thread tests/unittest/_torch/kv_cache_compression/test_compaction.py
Comment thread tests/unittest/_torch/thop/serial/test_sparse_kv_cache_compact.py
Signed-off-by: tianruih <tianruih@nvidia.com>
Comment thread tensorrt_llm/_torch/kv_cache_compression/compaction.py
Comment thread tensorrt_llm/_torch/kv_cache_compression/compaction.py
Comment thread tensorrt_llm/_torch/pyexecutor/resource_manager.py
Comment thread tensorrt_llm/_torch/pyexecutor/model_engine.py
@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #61550 [ run ] completed with state FAILURE. Commit: 788ff96
/LLM/main/L0_MergeRequest_PR pipeline #49763 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

…drop stale comment

Signed-off-by: tianruih <tianruih@nvidia.com>
Comment thread tensorrt_llm/_torch/kv_cache_compression/compaction.py
Comment thread tensorrt_llm/_torch/kv_cache_compression/compaction.py
Hudayday added 3 commits July 26, 2026 20:21
The kernel entry point is a function template defined only in the
template header; without an explicit instantiation no CUDA TU emits
invokeSparseKvCacheCompactLayers<__nv_bfloat16>, so a fresh build fails
to resolve the symbol used by sparseKvCacheCompactOp.cpp.

Signed-off-by: tianruih <tianruih@nvidia.com>
… geometry

Signed-off-by: tianruih <tianruih@nvidia.com>
…undary

Reject kept-ordinal row counts that do not divide the request count
evenly and decision layouts other than broadcast, per-head, or
per-layer-per-head, so a mismatched cache geometry fails loudly instead
of packing uninitialized move indices.

Signed-off-by: tianruih <tianruih@nvidia.com>
@Hudayday

Copy link
Copy Markdown
Collaborator Author

/bot run --disable-fail-fast

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #61814 [ run ] triggered by Bot. Commit: a9452cf Link to invocation

@Hudayday
Hudayday requested review from lfr-0531 and mingyangHao July 27, 2026 05:49
@Hudayday
Hudayday requested a review from zongfeijing July 27, 2026 06:56

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

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

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

@Hudayday

Copy link
Copy Markdown
Collaborator Author

/bot run --disable-fail-fast

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #61889 [ run ] triggered by Bot. Commit: a9452cf Link to invocation

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

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

@Hudayday

Copy link
Copy Markdown
Collaborator Author

/bot run --disable-fail-fast

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #61924 [ run ] triggered by Bot. Commit: a9452cf Link to invocation

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

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

@Hudayday

Copy link
Copy Markdown
Collaborator Author

/bot run --disable-fail-fast

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #62051 [ run ] triggered by Bot. Commit: a9452cf Link to invocation

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #62051 [ run ] completed with state SUCCESS. Commit: a9452cf
/LLM/main/L0_MergeRequest_PR pipeline #50238 completed with status: 'SUCCESS'
Pipeline passed with automatic retried tests. Check the rerun report for details.

CI Report

Link to invocation

@BowenFu BowenFu left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Regression axis checks out: C++ is purely additive (only - lines are copyright bumps), and the one shared-path change — the kv_compression_manages_history guard in model_engine.py — defaults False, so no existing manager changes behavior.

Not assessing kernel numerics — leaving that to the attention/runtime owners.

@Hudayday
Hudayday enabled auto-merge (squash) July 28, 2026 05:57

@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

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

Attention part LGTM

@Hudayday
Hudayday merged commit 5ac2259 into NVIDIA:main Jul 28, 2026
8 checks passed
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