Skip to content

[https://nvbugs/6438658][fix] Fix MLA KV cache estimation sizing - #16311

Merged
longlee0622 merged 2 commits into
NVIDIA:mainfrom
jiaganc:codex/pr-16269-trim
Jul 14, 2026
Merged

[https://nvbugs/6438658][fix] Fix MLA KV cache estimation sizing#16311
longlee0622 merged 2 commits into
NVIDIA:mainfrom
jiaganc:codex/pr-16269-trim

Conversation

@jiaganc

@jiaganc jiaganc commented Jul 13, 2026

Copy link
Copy Markdown
Collaborator

Summary by CodeRabbit

  • Bug Fixes

    • Improved KV-cache capacity estimation by temporarily applying inferred sizing values, then restoring configured values afterward.
    • Ensured MLA KV-cache setup receives the maximum token capacity.
    • Added warnings when warmup or CUDA graph capture cannot proceed due to insufficient KV-cache space.
  • Tests

    • Added regression coverage for MLA cache sizing and restoration of user-configured cache settings.

Description

The MLA branch of _create_kv_cache_manager did not forward max_num_tokens, so MLA managers could size the temporary estimation cache from the full token estimate instead of the runtime chunk size.

This change forwards max_num_tokens and makes estimation use inferred pool sizing. User-provided pool_ratio and avg_seq_len can underprovision a pool in the tightly sized temporary manager, causing warmup to hang or fail, so estimation temporarily uses pool_ratio=None and avg_seq_len=max_seq_len. The user values are restored before constructing the final manager. Warnings also make skipped general and CUDA-graph warmup shapes visible.

The change intentionally does not modify warmup batch sizing or KV-cache-manager-v2 internals.

Test Coverage

  • tests/unittest/_torch/executor/test_kv_cache_estimation.py::test_mla_branch_forwards_max_num_tokens_to_manager
  • tests/unittest/_torch/executor/test_kv_cache_estimation.py::test_estimation_temporarily_uses_inferred_pool_sizing
  • Pre-commit and commit-time hooks pass.
  • Python syntax checks pass.
  • Runtime unit tests were not run locally because the host environment does not include the TensorRT-LLM Python runtime dependencies.

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: Xianjie <5410381+qiaoxj07@users.noreply.github.com>
Signed-off-by: Jiagan Cheng <jiaganc@nvidia.com>
@jiaganc jiaganc changed the title [None][fix] Fix MLA KV cache estimation sizing [https://nvbugs/6438658][fix] Fix MLA KV cache estimation sizing Jul 13, 2026
@jiaganc
jiaganc marked this pull request as ready for review July 13, 2026 10:05
@jiaganc
jiaganc requested a review from a team as a code owner July 13, 2026 10:05
@jiaganc
jiaganc requested a review from Tabrizian July 13, 2026 10:05
@coderabbitai

coderabbitai Bot commented Jul 13, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

KvCacheCreator now isolates estimation sizing and restores user configuration, forwards max_num_tokens for MLA cache managers, and logs skipped warmup or CUDA graph shapes caused by insufficient KV cache space.

Changes

KV cache runtime updates

Layer / File(s) Summary
Estimation sizing and restoration
tensorrt_llm/_torch/pyexecutor/_util.py, tests/unittest/_torch/executor/test_kv_cache_estimation.py
Estimation temporarily uses inferred pool sizing, then restores the original pool_ratio, avg_seq_len, and related configuration values.
MLA manager token forwarding
tensorrt_llm/_torch/pyexecutor/_util.py, tests/unittest/_torch/executor/test_kv_cache_estimation.py
The MLA KV cache manager receives max_num_tokens, verified by a regression test.
Warmup capacity warnings
tensorrt_llm/_torch/pyexecutor/model_engine.py
Warmup and CUDA graph capture log warning details when insufficient KV cache space prevents batch creation.

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

Suggested reviewers: arysef, symphonylyh, litaotju, qijune, tabrizian

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title follows the required ticket/type/summary format and matches the PR's main fix.
Description check ✅ Passed The description includes the required Description, Test Coverage, and PR Checklist sections with relevant details.
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.

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

879-888: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Restore pool_ratio/avg_seq_len before calling _cal_max_memory, not after.

_cal_max_memory (L505) calls self._get_kv_size_per_token() while kv_cache_config.pool_ratio/avg_seq_len still hold the estimation-time override values (set in try_prepare_estimation), since the restore at L886-887 happens after the _cal_max_memory call at L880. The returned available_kv_mem doesn't itself depend on kv_size_per_token, so the final max_gpu_total_bytes/max_tokens aren't corrupted — but the kv_size_per_token value baked into the log line at L509-514 ("kv size per token is {kv_size_per_token}") is computed from the wrong config, which is exactly the kind of diagnostic this PR is trying to make trustworthy for KV-cache OOM debugging.

Moving the restore to before the _cal_max_memory call (or to the very top of the function) also incidentally hardens against the case where an exception is raised somewhere between function entry and L884, which currently leaves kv_cache_config in the temporary estimation state.

Note the new test test_estimation_temporarily_uses_inferred_pool_sizing mocks _cal_max_memory entirely, so it wouldn't have caught this.

🩹 Proposed fix: restore before computing max memory
-        # calculate max memory from peak memory and free gpu memory fraction
-        kv_cache_max_memory = self._cal_max_memory(peak_memory,
-                                                   total_gpu_memory, fraction,
-                                                   allocated_bytes)
-
-        # Estimation uses inferred pool sizing; the final manager uses the
-        # user-provided configuration.
-        self._kv_cache_config.pool_ratio = self._pool_ratio_in
-        self._kv_cache_config.avg_seq_len = self._avg_seq_len_in
+        # Estimation uses inferred pool sizing; the final manager uses the
+        # user-provided configuration. Restore before any capacity/logging
+        # computation below reads kv_cache_config, so log output and sizing
+        # reflect the user's real settings.
+        self._kv_cache_config.pool_ratio = self._pool_ratio_in
+        self._kv_cache_config.avg_seq_len = self._avg_seq_len_in
+
+        # calculate max memory from peak memory and free gpu memory fraction
+        kv_cache_max_memory = self._cal_max_memory(peak_memory,
+                                                   total_gpu_memory, fraction,
+                                                   allocated_bytes)
🤖 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/_util.py` around lines 879 - 888, Move the
assignments restoring self._kv_cache_config.pool_ratio and
self._kv_cache_config.avg_seq_len to before the _cal_max_memory call in the
surrounding method. Ensure _cal_max_memory and its kv-size diagnostic use the
user-provided configuration, and preserve the existing restoration values from
_pool_ratio_in and _avg_seq_len_in.
🧹 Nitpick comments (2)
tensorrt_llm/_torch/pyexecutor/model_engine.py (1)

1532-1561: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

LGTM!

The added warning correctly includes label/bs/draft_len context for diagnosing skipped CUDA-graph capture shapes.

Optional/out-of-scope nitpick: _run_attention_warmup (L1240-1244) and _capture_piecewise_cuda_graphs (L1622, L1652) still silently continue on batch is None without a similar warning. Not a defect (PR scope is explicitly "general and CUDA-graph warmup shapes"), but for consistent observability across all warmup skip-paths, the same warning pattern could be applied there in a 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 `@tensorrt_llm/_torch/pyexecutor/model_engine.py` around lines 1532 - 1561,
Optional follow-up: add equivalent warnings before the batch-is-None continue
paths in _run_attention_warmup and _capture_piecewise_cuda_graphs, including the
relevant warmup label and shape context such as batch size and draft length.
Keep the existing skip behavior unchanged.
tests/unittest/_torch/executor/test_kv_cache_estimation.py (1)

548-610: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Good coverage for the V2 override/restore contract; consider extending for the V1 path and the _cal_max_memory interaction.

This test correctly verifies try_prepare_estimation/configure_kv_cache_capacity override-then-restore semantics, but only for the KVCacheManagerV2 path (_get_model_kv_cache_manager_cls is patched to always return KVCacheManagerV2). The override in try_prepare_estimation (L758-759 in _util.py) is unconditional regardless of V1/V2, so a second test using the plain KVCacheManager class would confirm the same restore contract holds there too.

Also, _cal_max_memory is fully mocked here (patch.object(creator, "_cal_max_memory", return_value=512)), so this test can't catch ordering bugs where _cal_max_memory's internals read kv_cache_config before the restore runs (see the corresponding comment in tensorrt_llm/_torch/pyexecutor/_util.py). A follow-up test that lets _cal_max_memory/_get_kv_size_per_token run for real (mocking only torch.cuda/the model config) would give stronger coverage of the restore-ordering contract.

As per path instructions, coverage here is sufficient for the primary regression scenario this PR targets, but could use a follow-up test for the V1 manager path and the _cal_max_memory ordering interaction, ideally in this same file.

🤖 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/executor/test_kv_cache_estimation.py` around lines 548
- 610, Add follow-up coverage in
test_estimation_temporarily_uses_inferred_pool_sizing for the plain
KVCacheManager path by patching _get_model_kv_cache_manager_cls accordingly and
verifying the same override, configure, and restoration contract. Also add
coverage that runs _cal_max_memory and _get_kv_size_per_token without mocking
them, while mocking only CUDA and model-config dependencies, to verify they
observe the temporary estimation configuration before restoration.

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.

Outside diff comments:
In `@tensorrt_llm/_torch/pyexecutor/_util.py`:
- Around line 879-888: Move the assignments restoring
self._kv_cache_config.pool_ratio and self._kv_cache_config.avg_seq_len to before
the _cal_max_memory call in the surrounding method. Ensure _cal_max_memory and
its kv-size diagnostic use the user-provided configuration, and preserve the
existing restoration values from _pool_ratio_in and _avg_seq_len_in.

---

Nitpick comments:
In `@tensorrt_llm/_torch/pyexecutor/model_engine.py`:
- Around line 1532-1561: Optional follow-up: add equivalent warnings before the
batch-is-None continue paths in _run_attention_warmup and
_capture_piecewise_cuda_graphs, including the relevant warmup label and shape
context such as batch size and draft length. Keep the existing skip behavior
unchanged.

In `@tests/unittest/_torch/executor/test_kv_cache_estimation.py`:
- Around line 548-610: Add follow-up coverage in
test_estimation_temporarily_uses_inferred_pool_sizing for the plain
KVCacheManager path by patching _get_model_kv_cache_manager_cls accordingly and
verifying the same override, configure, and restoration contract. Also add
coverage that runs _cal_max_memory and _get_kv_size_per_token without mocking
them, while mocking only CUDA and model-config dependencies, to verify they
observe the temporary estimation configuration before restoration.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Enterprise

Run ID: adb8d732-2df1-4de2-a7fa-0ce2391042b8

📥 Commits

Reviewing files that changed from the base of the PR and between 53d2bde and 7668b78.

📒 Files selected for processing (3)
  • tensorrt_llm/_torch/pyexecutor/_util.py
  • tensorrt_llm/_torch/pyexecutor/model_engine.py
  • tests/unittest/_torch/executor/test_kv_cache_estimation.py

@pcastonguay

Copy link
Copy Markdown
Collaborator

/bot run --disable-fail-fast

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #58969 [ run ] triggered by Bot. Commit: 7668b78 Link to invocation

@longlee0622
longlee0622 enabled auto-merge (squash) July 13, 2026 12:18
@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #58969 [ run ] completed with state SUCCESS. Commit: 7668b78
/LLM/main/L0_MergeRequest_PR pipeline #47500 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

@pcastonguay

Copy link
Copy Markdown
Collaborator

/bot run --disable-fail-fast

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #59002 [ run ] triggered by Bot. Commit: 7668b78 Link to invocation

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #59002 [ run ] completed with state SUCCESS. Commit: 7668b78
/LLM/main/L0_MergeRequest_PR pipeline #47531 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

@pcastonguay

Copy link
Copy Markdown
Collaborator

/bot run --disable-fail-fast

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #59010 [ run ] triggered by Bot. Commit: 7668b78 Link to invocation

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #59010 [ run ] completed with state FAILURE. Commit: 7668b78
/LLM/main/L0_MergeRequest_PR pipeline #47538 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

@pcastonguay

Copy link
Copy Markdown
Collaborator

/bot run --disable-fail-fast

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #59017 [ run ] triggered by Bot. Commit: 49fea42 Link to invocation

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #59017 [ run ] completed with state SUCCESS. Commit: 49fea42
/LLM/main/L0_MergeRequest_PR pipeline #47544 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

@pcastonguay

Copy link
Copy Markdown
Collaborator

/bot run --disable-fail-fast

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #59049 [ run ] triggered by Bot. Commit: 49fea42 Link to invocation

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #59049 [ run ] completed with state SUCCESS. Commit: 49fea42
/LLM/main/L0_MergeRequest_PR pipeline #47576 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

@longlee0622

Copy link
Copy Markdown
Collaborator

/bot run --disable-fail-fast

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #59103 [ run ] triggered by Bot. Commit: 49fea42 Link to invocation

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #59103 [ run ] completed with state SUCCESS. Commit: 49fea42
/LLM/main/L0_MergeRequest_PR pipeline #47617 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

@qiaoxj07

Copy link
Copy Markdown
Collaborator

/bot run --disable-fail-fast

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #59132 [ run ] triggered by Bot. Commit: 49fea42 Link to invocation

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #59132 [ run ] completed with state SUCCESS. Commit: 49fea42
/LLM/main/L0_MergeRequest_PR pipeline #47644 completed with status: 'SUCCESS'

CI Report

Link to invocation

@longlee0622
longlee0622 merged commit 771d385 into NVIDIA:main Jul 14, 2026
7 checks passed
@jiaganc
jiaganc deleted the codex/pr-16269-trim branch July 21, 2026 03:03
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.

5 participants