Skip to content

[None][perf] Avoid Index-K cache materialization for MSA#16856

Open
peihu-nv wants to merge 1 commit into
NVIDIA:mainfrom
peihu-nv:peihengh/m3-index-k-hnd-main
Open

[None][perf] Avoid Index-K cache materialization for MSA#16856
peihu-nv wants to merge 1 commit into
NVIDIA:mainfrom
peihu-nv:peihengh/m3-index-k-hnd-main

Conversation

@peihu-nv

@peihu-nv peihu-nv commented Jul 25, 2026

Copy link
Copy Markdown
Collaborator

@coderabbitai summary

Description

MiniMax-M3 MSA stores its one-head Index-K side cache through KV cache manager
V2. The cache accessor previously exposed only NHD layout, so every sparse
attention layer converted it to HND with permute(...).contiguous() before
invoking the SM100 FMHA kernel.

This change:

  • adds an explicit kv_layout contract to the KV cache manager V2 accessor,
    with NHD retained as the default for existing callers;
  • makes the MiniMax-M3 MSA path request and write Index-K directly in HND;
  • passes the resulting one-head strided HND view directly to fmha_sm100;
  • keeps the coalesced cache-pool page stride intact.

For the one-head Index-K cache, NHD and HND have identical physical bytes
within each page. The change is therefore a metadata/layout-contract change
and avoids materializing a second cache tensor. Existing callers keep NHD as
the default, and no C++ or kernel source changes.

Performance

The original matched GB200 1P1D c64 qualification used 8K input / 1K output
requests. Nsight Systems isolated the following CTX and GEN effects:

Phase Removed copy time Phase result Serving result
CTX / 8K prefill 17.173 ms p50 _forward_step: -3.72% Throughput: +4.25%
GEN / decode replay 12.226 ms Replay period: -13.2% Output throughput: +15.05%

Each measured phase removed 456 Index-K layout copies. In the matched combined
E2E run, Pareto X (1000 / median TPOT) improved 34.17% and Pareto Y (total
token throughput / 8 GPUs) improved 32.08%. Median TPOT improved 25.47%;
median TTFT regressed 2.91%. The focused phase traces above provide the causal
attribution.

Test Coverage

  • Added layout-contract and extra-buffer tests in
    test_kv_cache_v2_extra_buffers.py.
  • Added MiniMax-M3 MSA backend coverage in
    test_minimax_m3_msa_backend.py.
  • Original GB200 validation: 24/24 focused tests passed, strided and packed
    FMHA proxy results were bit-identical, and CUDA Graph replay passed.
  • Current-main changed-file pre-commit checks pass.

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.

Signed-off-by: peihengh <259410613+peihu-nv@users.noreply.github.com>
@peihu-nv

Copy link
Copy Markdown
Collaborator Author

/bot run

@coderabbitai

coderabbitai Bot commented Jul 25, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

Changes

MiniMax-M3 index-K layout handling

Layer / File(s) Summary
Layout-aware index-K cache accessor
tensorrt_llm/_torch/pyexecutor/kv_cache_manager_v2.py, tensorrt_llm/_torch/attention_backend/sparse/minimax_m3/cache_manager.py, tests/unittest/_torch/executor/test_kv_cache_v2_extra_buffers.py
get_index_k_buffer now validates NHD/HND layouts and constructs matching views for coalesced and non-coalesced pools. Tests cover aliasing, strides, writes, and invalid layouts.
Direct HND MSA index-K flow
tensorrt_llm/_torch/attention_backend/sparse/minimax_m3/msa_backend.py, tensorrt_llm/_torch/attention_backend/sparse/minimax_m3/msa_indexer.py, tensorrt_llm/_torch/attention_backend/sparse/minimax_m3/msa_utils.py, tests/unittest/_torch/attention/sparse/test_minimax_m3_msa_backend.py
MSA requests and writes HND index-K views, while MsaIndexer consumes paged index-K tensors directly. Conversion helper removal and strided-view behavior are tested.

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

Sequence Diagram(s)

sequenceDiagram
  participant MSA_backend
  participant KVCacheManagerV2
  participant MsaIndexer
  participant KV_cache
  MSA_backend->>KVCacheManagerV2: get_index_k_buffer(layer_idx, kv_layout="HND")
  KVCacheManagerV2->>KV_cache: create zero-copy HND view
  KV_cache-->>MSA_backend: strided paged index-K
  MSA_backend->>KVCacheManagerV2: write_kv_slots(..., layout="HND")
  MSA_backend->>MsaIndexer: select_blocks(idx_k_paged)
  MsaIndexer-->>MSA_backend: selected blocks
Loading

Suggested reviewers: brb-nv

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% 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 matches the main change: avoiding Index-K cache materialization for MSA.
Description check ✅ Passed The description includes the required sections and clearly explains the change and test coverage.
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.

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

1887-1926: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

HND view is only byte-safe when num_heads == 1; document or assert this.

The NHD/HND view-swap trick relies on TensorWrapper building fresh, default-contiguous strides for the requested logical shape rather than performing a real transpose. That aliases identical bytes only because page_shape collapses to [T, 1, D] vs [1, T, D] when num_heads == 1 — both reduce to the same t*D+d byte offset. For num_heads > 1, requesting kv_layout="HND" would silently reinterpret physically NHD-laid-out bytes as if they were HND, corrupting data without any error. All current callers (MiniMaxM3KVCacheManagerV2.get_index_k_buffer) hardcode num_heads=1, so this is latent today, but the base method is public/generic and doesn't guard against future multi-head callers.

Consider adding an explicit guard and documenting the precondition:

🛡️ Proposed guard
         if kv_layout not in ("NHD", "HND"):
             raise ValueError(f"Unsupported kv_layout: {kv_layout}")
+        if kv_layout == "HND" and num_heads != 1:
+            raise NotImplementedError(
+                "kv_layout='HND' is only supported for num_heads == 1: the "
+                "NHD/HND views only alias identical bytes when the head "
+                "dimension is a singleton."
+            )

Also applies to: 1981-1997

🤖 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/kv_cache_manager_v2.py` around lines 1887 -
1926, Update get_index_k_buffer to reject kv_layout="HND" when num_heads is
greater than one, since the byte-level view is only valid for a single head;
raise a clear ValueError before constructing the tensor view. Document this HND
precondition in the method docstring while preserving NHD behavior and the
existing num_heads=1 callers.
🤖 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.

Outside diff comments:
In `@tensorrt_llm/_torch/pyexecutor/kv_cache_manager_v2.py`:
- Around line 1887-1926: Update get_index_k_buffer to reject kv_layout="HND"
when num_heads is greater than one, since the byte-level view is only valid for
a single head; raise a clear ValueError before constructing the tensor view.
Document this HND precondition in the method docstring while preserving NHD
behavior and the existing num_heads=1 callers.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Enterprise

Run ID: 125b3a2d-5c93-40f0-8b43-65e91261453b

📥 Commits

Reviewing files that changed from the base of the PR and between 4b7d719 and 9b986b9.

📒 Files selected for processing (7)
  • tensorrt_llm/_torch/attention_backend/sparse/minimax_m3/cache_manager.py
  • tensorrt_llm/_torch/attention_backend/sparse/minimax_m3/msa_backend.py
  • tensorrt_llm/_torch/attention_backend/sparse/minimax_m3/msa_indexer.py
  • tensorrt_llm/_torch/attention_backend/sparse/minimax_m3/msa_utils.py
  • tensorrt_llm/_torch/pyexecutor/kv_cache_manager_v2.py
  • tests/unittest/_torch/attention/sparse/test_minimax_m3_msa_backend.py
  • tests/unittest/_torch/executor/test_kv_cache_v2_extra_buffers.py
💤 Files with no reviewable changes (1)
  • tensorrt_llm/_torch/attention_backend/sparse/minimax_m3/msa_utils.py

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #61666 [ run ] triggered by Bot. Commit: 9b986b9 Link to invocation

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #61666 [ run ] completed with state SUCCESS. Commit: 9b986b9
/LLM/main/L0_MergeRequest_PR pipeline #49872 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.

2 participants