Skip to content

[None][fix] Kimi K3: eager CUDA-graph buffer allocation and prebuilt fused-verify constants - #17421

Open
brnguyen2 wants to merge 2 commits into
NVIDIA:mainfrom
brnguyen2:fix/k3-graph-buffer-hardening
Open

[None][fix] Kimi K3: eager CUDA-graph buffer allocation and prebuilt fused-verify constants#17421
brnguyen2 wants to merge 2 commits into
NVIDIA:mainfrom
brnguyen2:fix/k3-graph-buffer-hardening

Conversation

@brnguyen2

@brnguyen2 brnguyen2 commented Aug 7, 2026

Copy link
Copy Markdown
Collaborator

Summary

Follow-up to #17269, hardening two CUDA-graph-unsafe lazy-allocation patterns in the Kimi K3 KDA runtime (reviewer feedback on the decode fast path):

  1. _cs_dense silent-realloc hazard. The decode kernel's persistent conv-window staging buffer was lazily allocated with a buf.shape[1] < B regrow branch. Previously captured CUDA graphs hold the old pointer, so if the "first allocation is max-size" invariant ever broke, a regrow would leave those graphs writing into freed memory. The buffer is now allocated exactly once (sized to the conv pool's slot count, which bounds the decode batch: slot_indices are distinct pool rows and this is the plain one-token-per-request path), and a hard assert replaces the regrow so a broken invariant fails loudly instead of corrupting memory. The capture-time fallback to the reference path is kept: a first decode under capture must not allocate.

  2. Lazy fused-verify conv-weight compute. _get_mtp_conv_weights() computed the fp32 conv constants at first use, which under CUDA graph capture would bake capture-pool pointers into the cached tuple (previously guarded by a capture-time-only RuntimeError). The constants are now always prebuilt at weight-load time: load_weights() builds them unconditionally for every KDA layer — closing a gap where FP8 KDA weight read with the fused decode glue disabled ran neither finalize variant yet could still reach the fused verify path — and the getter raises unconditionally if they are missing.

Behavior-neutral by construction: no numeric changes, only allocation timing and failure mode.

Changes

  • tensorrt_llm/_torch/models/modeling_kimi_linear.py
    • _forward_decode: allocate _cs_dense once; hard assert instead of silent realloc.
    • New _build_mtp_conv_weights(); called from _build_decode_kernel_constants() and unconditionally per KDA layer in load_weights().
    • _get_mtp_conv_weights(): unconditional RuntimeError when the constants were not prebuilt.
  • tests/unittest/_torch/modeling/test_kimi_kda_fused_verify_parity.py: the test-built runtime now prebuilds the constants after weight init, mirroring production.

Validation

Validated on a Blackwell (SM103) node:

  • tests/unittest/_torch/modeling/test_kimi_kda_fused_verify_parity.py, test_kimi_kda_verify_parity.py, test_kda_mtp_decode_cute_parity.py and tests/unittest/_torch/modules/kimi_kda/: 50 passed, 1 pre-existing unrelated skip.
  • Truncated-checkpoint (4-layer) TP4 generation smoke with CUDA graphs enabled (exercises _cs_dense under capture): PASS.
  • Same with suffix-automaton speculative decoding (max_draft_len=2, exercises the fused-verify constants end to end): PASS.

Dev Engineer Review

  • Preallocates _cs_dense at conv-pool slot capacity.
  • Replaces silent buffer growth with an assertion when decode demand exceeds capacity.
  • Prebuilds fused-verify convolution constants during weight loading and decode finalization.
  • Makes _get_mtp_conv_weights() fail when required constants are unavailable.
  • Preserves numerical behavior and prevents CUDA-graph-unsafe allocations.
  • No public API, configuration, or test-list changes were identified.

QA Engineer Review

  • Modified _make_runtime in tests/unittest/_torch/modeling/test_kimi_kda_fused_verify_parity.py.
  • The function now builds fused-verify convolution weights after parameter initialization.
  • No corresponding tests/integration/test_lists/ entry was provided.
  • Validation reported 50 passing tests, one pre-existing unrelated skip, and successful CUDA-graph generation smoke tests with and without suffix-automaton speculative decoding.
  • Verdict: sufficient.

…fused-verify constants

Signed-off-by: Brian Nguyen <brnguyen@nvidia.com>
@brnguyen2
brnguyen2 requested a review from a team as a code owner August 7, 2026 15:04
@brnguyen2
brnguyen2 requested a review from WeiHaocheng August 7, 2026 15:04
@brnguyen2

Copy link
Copy Markdown
Collaborator Author

/bot run

@coderabbitai

coderabbitai Bot commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Enterprise

Run ID: 90c8aaf9-aa0b-456c-afb1-7fb5cc067646

📥 Commits

Reviewing files that changed from the base of the PR and between 4f6b608 and bbd7469.

📒 Files selected for processing (1)
  • tensorrt_llm/_torch/models/modeling_kimi_linear.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • tensorrt_llm/_torch/models/modeling_kimi_linear.py

Walkthrough

Kimi KDA decode staging now uses fixed pool-slot capacity. Fused-verification convolution weights are built before decode execution and required from a prebuilt cache. Parity runtime setup now mirrors production weight preparation.

Changes

Kimi KDA capture-safe runtime

Layer / File(s) Summary
Prebuild fused-verification weights
tensorrt_llm/_torch/models/modeling_kimi_linear.py, tests/unittest/_torch/modeling/test_kimi_kda_fused_verify_parity.py
KDA initialization and weight loading now build convolution constants eagerly. Runtime retrieval requires prebuilt tensors. The parity test prepares the same constants.
Enforce decode staging capacity
tensorrt_llm/_torch/models/modeling_kimi_linear.py
Decode staging allocates at convolution pool-slot capacity and asserts when a later batch exceeds that capacity.

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

Possibly related PRs

Suggested reviewers: weihaocheng

Sequence Diagram(s)

sequenceDiagram
  participant WeightLoader
  participant KDAInitializer
  participant ConvWeightCache
  participant DecodeKernel
  WeightLoader->>ConvWeightCache: Build convolution constants
  KDAInitializer->>ConvWeightCache: Require prebuilt weights
  DecodeKernel->>ConvWeightCache: Retrieve prebuilt weights
Loading
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the Kimi K3 fix and summarizes both CUDA-graph buffer allocation and fused-verify constant changes.
Description check ✅ Passed The description explains the problem, solution, affected files, test coverage, and validation results in the required sections.
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.
✨ 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/models/modeling_kimi_linear.py (1)

1351-1376: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Enforce the slot-capacity invariant before the first allocation.

Line 1365 uses max(conv_pool.shape[0], B). If the first decode has B > conv_pool.shape[0], this allocates beyond pool capacity and bypasses the required hard failure. Allocate exactly conv_pool.shape[0] rows and assert B <= conv_pool.shape[0] before allocation.

Proposed fix
+        assert B <= conv_pool.shape[0], (
+            f"KDA decode batch has {B} rows but the conv pool has "
+            f"{conv_pool.shape[0]} slots"
+        )
         buf = self._cs_dense
         if buf is None:
             ...
             buf = torch.empty(
-                3, max(conv_pool.shape[0], B), d, W - 1, dtype=torch.bfloat16, device=x2d.device
+                3, conv_pool.shape[0], d, W - 1, dtype=torch.bfloat16, device=x2d.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 `@tensorrt_llm/_torch/models/modeling_kimi_linear.py` around lines 1351 - 1376,
Update the _cs_dense initialization path to assert B <= conv_pool.shape[0]
before allocating, enforcing the slot-capacity invariant on the first decode.
Allocate the staging buffer with exactly conv_pool.shape[0] rows instead of
max(conv_pool.shape[0], B), while preserving the existing capture-safe fallback
and post-allocation capacity assertion.
🤖 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_kimi_linear.py`:
- Around line 1629-1640: Update the _get_mtp_conv_weights method signature to
include the return type annotation -> Tuple[torch.Tensor, ...], preserving its
existing behavior and error handling.

---

Outside diff comments:
In `@tensorrt_llm/_torch/models/modeling_kimi_linear.py`:
- Around line 1351-1376: Update the _cs_dense initialization path to assert B <=
conv_pool.shape[0] before allocating, enforcing the slot-capacity invariant on
the first decode. Allocate the staging buffer with exactly conv_pool.shape[0]
rows instead of max(conv_pool.shape[0], B), while preserving the existing
capture-safe fallback and post-allocation capacity assertion.
🪄 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: 6e46eb69-4366-4b5f-a439-913d9f4494fd

📥 Commits

Reviewing files that changed from the base of the PR and between 8fa2a6f and 4f6b608.

📒 Files selected for processing (2)
  • tensorrt_llm/_torch/models/modeling_kimi_linear.py
  • tests/unittest/_torch/modeling/test_kimi_kda_fused_verify_parity.py

Comment thread tensorrt_llm/_torch/models/modeling_kimi_linear.py Outdated
@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #64626 [ run ] triggered by Bot. Commit: 4f6b608 Link to invocation

Signed-off-by: Brian Nguyen <brnguyen@nvidia.com>
@brnguyen2

Copy link
Copy Markdown
Collaborator Author

/bot run

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #64635 [ run ] triggered by Bot. Commit: bbd7469 Link to invocation

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #64626 [ run ] completed with state ABORTED. Commit: 4f6b608

Link to invocation

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

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

@brnguyen2

Copy link
Copy Markdown
Collaborator Author

/bot run

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #64658 [ run ] triggered by Bot. Commit: bbd7469 Link to invocation

@brnguyen2

Copy link
Copy Markdown
Collaborator Author

Re CodeRabbit's outside-diff note on the _cs_dense sizing (max(conv_pool.shape[0], B)): B <= conv_pool.shape[0] holds by construction on this path — slot_indices are distinct pool rows and _forward_decode is the one-token-per-request path, so the decode batch cannot exceed the pool slot count (the in-code comment above the allocation documents this). Even in the hypothetical violation, the max() sizing keeps the staging buffer itself in-bounds, and the existing assert already fails loudly on any later batch that would have forced a graph-corrupting realloc. Promoting the invariant to an explicit first-call assert is reasonable extra hardening; deferring it to the post-merge cleanup ticket TRTLLM-15199 rather than invalidating this PR's validated/green state for a defensive check.

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #64658 [ run ] completed with state ABORTED. Commit: bbd7469

Link to invocation

@brnguyen2

Copy link
Copy Markdown
Collaborator Author

/bot run

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #64807 [ run ] triggered by Bot. Commit: bbd7469 Link to invocation

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

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