Skip to content

[None][fix] Fix fused mHC output reuse and extend compressor next_n#16221

Open
heyuhhh wants to merge 3 commits into
NVIDIA:mainfrom
heyuhhh:user/yuhangh/fix_fused_mhc_and_dspark
Open

[None][fix] Fix fused mHC output reuse and extend compressor next_n#16221
heyuhhh wants to merge 3 commits into
NVIDIA:mainfrom
heyuhhh:user/yuhangh/fix_fused_mhc_and_dspark

Conversation

@heyuhhh

@heyuhhh heyuhhh commented Jul 10, 2026

Copy link
Copy Markdown
Collaborator

Summary by CodeRabbit

  • New Features

    • Extended compressed KV-cache decoding to support up to 8 new tokens per batch element.
    • Improved generation position IDs to follow compact compressed-output ordering.
    • Strengthened fused-HC scratch-buffer handling across CUDA graphs and streams.
  • Bug Fixes

    • Added validation and clearer errors for unsupported token counts.
    • Prevented fused-HC output aliasing and improved correctness across chained operations.
  • Tests

    • Added coverage for token counts 5–8, position-ID ordering, CUDA graph replay, and multi-stream execution.

Description

This PR fixes two common correctness issues that affect speculative decoding workloads:

  • Extend the DeepSeek-V4 compressor decode path from next_n <= 4 to next_n <= 8, including explicit THOP/launcher validation and the required CUDA template instantiations.
  • Generate compressed-token position IDs in the same compact cu_new_comp_kv order used by the compressor kernel. This prevents multi-request batches from assigning RoPE positions from the wrong request when requests produce different numbers of compressed tokens.
  • Stop caching fused mHC public outputs across calls. Public outputs are now freshly allocated while only bounded, stream-scoped scratch tensors are reused; CUDA graph capture uses graph-private allocations.
  • Remove the unused fused-HC output allocator helper.

The branch contains common fixes only and does not modify DSpark-specific code.

Test Coverage

Regression coverage added or retained for:

  • Compressor next_n=5..8, including next_n=8 and invalid-range rejection.
  • Compact compressed position IDs for mixed requests and mixed context/generation batches.
  • Chained fused-HC calls, ensuring outputs do not alias or mutate the previous call's live inputs.
  • Three-call CUDA graph replay and cross-stream scratch isolation.

Validation performed on the final main-based branch:

  • Pre-commit and commit-message hooks passed.
  • git diff --check origin/main..HEAD passed.
  • Independent static scope and code-quality reviews passed.
  • Runtime unit tests, build, and GSM8K were not rerun on the final branch per the requested validation scope.

PR Checklist

  • PR description clearly explains what and why.
  • PR follows the TRT-LLM coding guidelines to the best of my knowledge.
  • Test cases are provided for the new code paths.
  • No public API changes are introduced.
  • No new dependencies are introduced.
  • No CODEOWNERS, documentation, or architecture diagram updates are required.

heyuhhh added 3 commits July 10, 2026 06:54
Signed-off-by: yuhangh <58161490+heyuhhh@users.noreply.github.com>
Signed-off-by: yuhangh <58161490+heyuhhh@users.noreply.github.com>
Signed-off-by: yuhangh <58161490+heyuhhh@users.noreply.github.com>
@heyuhhh heyuhhh marked this pull request as ready for review July 10, 2026 07:02
@heyuhhh heyuhhh requested review from a team as code owners July 10, 2026 07:02
@coderabbitai

coderabbitai Bot commented Jul 10, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Changes

Compressed KV execution

Layer / File(s) Summary
Decode dispatch and range validation
cpp/tensorrt_llm/kernels/compressorKernels/compressorKernels.cu, cpp/tensorrt_llm/thop/compressorOp.cpp, tests/unittest/_torch/attention/sparse/deepseek_v4/test_compressor_kernel.py
Decode dispatch now covers next_n values 1–8 with updated reduction-warp matching, runtime validation, and expanded positive and negative tests.
Compact generation position IDs
tensorrt_llm/_torch/attention_backend/sparse/deepseek_v4/deepseek_v4.py, tests/unittest/_torch/attention/sparse/deepseek_v4/test_compressor_module.py
Generation position IDs are reconstructed from compact compressor output indices and validated across compression ratios and mixed context-generation cases.

Fused-HC scratch reuse

Layer / File(s) Summary
Stream-aware scratch cache
tensorrt_llm/_torch/modules/mhc/mhc_cuda.py, cpp/tensorrt_llm/kernels/mhcKernels/mhcFusedHcKernel.cu
Fused-HC caches only internal scratch tensors, keys allocations by CUDA stream, bypasses caching during capture, and allocates public outputs directly.
Aliasing and replay validation
tests/unittest/_torch/modules/test_mhc.py
Tests cover chained output ownership, CUDA-graph replay stability, and scratch isolation across CUDA streams.

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

Sequence Diagram(s)

sequenceDiagram
  participant CompressedKvMetadata
  participant GenerationPositionIds
  participant CuNewCompKv
  CompressedKvMetadata->>GenerationPositionIds: pass cu_new_comp_kv
  GenerationPositionIds->>CuNewCompKv: search compact output ownership
  CuNewCompKv-->>GenerationPositionIds: return request indices and offsets
  GenerationPositionIds-->>CompressedKvMetadata: return compressed position IDs
Loading

Suggested reviewers: mikeiovine, yuxianq, dpitman-nvda, Funatiq, brb-nv, litaotju, QiJune

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 71.43% 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, template-compliant, and accurately summarizes the main fused mHC and compressor changes.
Description check ✅ Passed The description follows the required template and clearly covers the change, tests, and checklist items.
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.

🧹 Nitpick comments (4)
tests/unittest/_torch/attention/sparse/deepseek_v4/test_compressor_kernel.py (2)

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

Add type annotations to the new test.

Annotate both integer parameters and the None return type.

As per coding guidelines, Python functions must always be annotated.

🤖 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_compressor_kernel.py`
at line 1542, Add type annotations to test_decode_rejects_unsupported_next_n,
declaring next_n and storage_next_n as integers and the function return type as
None.

Source: Coding guidelines


1410-1416: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Cover the HD128 single-warp configurations for next_n > 4.

The new 5–8 cases exercise HD512 only, while the dispatch matrix also adds CR=128/HD=128/NRW=1 configurations. Add at least one basic_hd128_next8 case to catch head-dimension-specific dispatch or indexing regressions.

As per path instructions, test changes need actionable coverage follow-up when a changed branch remains unexercised.

🤖 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_compressor_kernel.py`
around lines 1410 - 1416, Add a single-warp HD128 parameterized test case with
next_n greater than 4, preferably `basic_hd128_next8`, to the relevant test
parameter list alongside the existing `basic_hd512_next5`–`next8` cases. Ensure
it uses the HD128 configuration and matches the expected argument shape used by
the test.

Source: Path instructions

tensorrt_llm/_torch/attention_backend/sparse/deepseek_v4/deepseek_v4.py (1)

929-938: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Annotate the compiled helper’s return type.

_compute_gen_compressed_position_ids mutates buffers and returns nothing; add -> None.

As per coding guidelines, Python functions must always be annotated.

🤖 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/attention_backend/sparse/deepseek_v4/deepseek_v4.py`
around lines 929 - 938, The _compute_gen_compressed_position_ids function lacks
a return annotation; add -> None to its signature, since it mutates buffers and
returns no value.

Source: Coding guidelines

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

365-367: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Type-annotate the new helper and tests.

Add parameter annotations, -> list[int] for _active_compressed_position_ids, and -> None for both test functions.

As per coding guidelines, Python functions must always be annotated.

Also applies to: 426-428, 439-440

🤖 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_compressor_module.py`
around lines 365 - 367, The new helper and tests lack required type annotations.
Add appropriate parameter annotations to _active_compressed_position_ids and
declare its return type as list[int]; annotate both test functions with their
parameter types and -> None return types.

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.

Nitpick comments:
In `@tensorrt_llm/_torch/attention_backend/sparse/deepseek_v4/deepseek_v4.py`:
- Around line 929-938: The _compute_gen_compressed_position_ids function lacks a
return annotation; add -> None to its signature, since it mutates buffers and
returns no value.

In
`@tests/unittest/_torch/attention/sparse/deepseek_v4/test_compressor_kernel.py`:
- Line 1542: Add type annotations to test_decode_rejects_unsupported_next_n,
declaring next_n and storage_next_n as integers and the function return type as
None.
- Around line 1410-1416: Add a single-warp HD128 parameterized test case with
next_n greater than 4, preferably `basic_hd128_next8`, to the relevant test
parameter list alongside the existing `basic_hd512_next5`–`next8` cases. Ensure
it uses the HD128 configuration and matches the expected argument shape used by
the test.

In
`@tests/unittest/_torch/attention/sparse/deepseek_v4/test_compressor_module.py`:
- Around line 365-367: The new helper and tests lack required type annotations.
Add appropriate parameter annotations to _active_compressed_position_ids and
declare its return type as list[int]; annotate both test functions with their
parameter types and -> None return types.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Enterprise

Run ID: 0cabe84d-2556-49e3-8c1e-1836df366c34

📥 Commits

Reviewing files that changed from the base of the PR and between e2ce7a6 and 07f9cd0.

📒 Files selected for processing (8)
  • cpp/tensorrt_llm/kernels/compressorKernels/compressorKernels.cu
  • cpp/tensorrt_llm/kernels/mhcKernels/mhcFusedHcKernel.cu
  • cpp/tensorrt_llm/thop/compressorOp.cpp
  • tensorrt_llm/_torch/attention_backend/sparse/deepseek_v4/deepseek_v4.py
  • tensorrt_llm/_torch/modules/mhc/mhc_cuda.py
  • tests/unittest/_torch/attention/sparse/deepseek_v4/test_compressor_kernel.py
  • tests/unittest/_torch/attention/sparse/deepseek_v4/test_compressor_module.py
  • tests/unittest/_torch/modules/test_mhc.py

@heyuhhh

heyuhhh commented Jul 10, 2026

Copy link
Copy Markdown
Collaborator Author

/bot run --disable-fail-fast

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #58629 [ run ] triggered by Bot. Commit: 07f9cd0 Link to invocation

@heyuhhh heyuhhh requested review from dc3671 and liji-nv July 10, 2026 07:35
comb_mix_cur = torch.empty((B, n2), dtype=torch.float32, device=device)
layer_input_cur = torch.empty((B, hidden_size), dtype=torch.bfloat16, device=device)
if ws_ks == 1:
y_acc_ws = torch.empty((B, shape_n), dtype=torch.float32, device=device)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

The remaining size is no longer large, maybe we just remove the cache?

longlee0622 added a commit to longlee0622/TensorRT-LLM that referenced this pull request Jul 10, 2026
Signed-off-by: Jonas Li <6110159+longlee0622@users.noreply.github.com>
@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #58629 [ run ] completed with state SUCCESS. Commit: 07f9cd0
/LLM/main/L0_MergeRequest_PR pipeline #47218 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.

3 participants