Skip to content

Conversation

brb-nv
Copy link
Collaborator

@brb-nv brb-nv commented Oct 5, 2025

Description

Currently on main, we require gen ranks with CP to allocate KV cache for entire sequence length (though they only need KV cache for the portion of sequence length they'll hold) to get cache transmission right. This MR removes the limitation.

Also, previously, cache transmission is such that blocks are transmitted to genCP ranks in a round-robin fashion. This MR updates the transmission to be contiguous.
For example, let's say ctxTpSize=1 and genCpSize=2 and there are 5 blocks to be transmitted with IDs 0, 1, 2, 3, 4 for a given sequence.

Distrubution genCpRank0 genCpRank1
Round-robin 0, 2, 4 1, 3
Contiguous 0, 1, 2 3, 4

We keep around the round-robin distribution as an opt-in functionality by setting an env variable.

Known limitations:

  1. We expect seqLen of every request to be long enough to have at least 1 block to transfer to all genCP ranks.
  2. KV cache reuse for CP might be affected by the change to getBlockRangeForSending. This is ok for now.

Test Coverage

$ TRTLLM_USE_UCX_KVCACHE=1 TLLM_LOG_LEVEL=INFO mpirun -n 8 ./tests/unit_tests/multi_gpu/cacheTransceiverTest --gtest_filter="AsymmetricCaseTest0WithCPForMLA/AsymmetricalCacheTest.TestCase/*"

$ TRTLLM_USE_UCX_KVCACHE=1 TLLM_LOG_LEVEL=INFO mpirun -n 8 ./tests/unit_tests/multi_gpu/cacheTransceiverTest --gtest_filter="AsymmetricCaseTest1WithCPForMLA/AsymmetricalCacheTest.TestCase/*"

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)

  • Any new dependencies have been scanned for license and vulnerabilities

  • CODEOWNERS updated if ownership changes

  • Documentation updated as needed

  • 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

/bot [-h] ['run', 'kill', 'skip', 'reuse-pipeline'] ...

Provide a user friendly way for developers to interact with a Jenkins server.

Run /bot [-h|--help] to print this help message.

See details below for each supported subcommand.

run [--reuse-test (optional)pipeline-id --disable-fail-fast --skip-test --stage-list "A10-PyTorch-1, xxx" --gpu-type "A30, H100_PCIe" --test-backend "pytorch, cpp" --add-multi-gpu-test --only-multi-gpu-test --disable-multi-gpu-test --post-merge --extra-stage "H100_PCIe-TensorRT-Post-Merge-1, xxx" --detailed-log --debug(experimental)]

Launch build/test pipelines. All previously running jobs will be killed.

--reuse-test (optional)pipeline-id (OPTIONAL) : Allow the new pipeline to reuse build artifacts and skip successful test stages from a specified pipeline or the last pipeline if no pipeline-id is indicated. If the Git commit ID has changed, this option will be always ignored. The DEFAULT behavior of the bot is to reuse build artifacts and successful test results from the last pipeline.

--disable-reuse-test (OPTIONAL) : Explicitly prevent the pipeline from reusing build artifacts and skipping successful test stages from a previous pipeline. Ensure that all builds and tests are run regardless of previous successes.

--disable-fail-fast (OPTIONAL) : Disable fail fast on build/tests/infra failures.

--skip-test (OPTIONAL) : Skip all test stages, but still run build stages, package stages and sanity check stages. Note: Does NOT update GitHub check status.

--stage-list "A10-PyTorch-1, xxx" (OPTIONAL) : Only run the specified test stages. Examples: "A10-PyTorch-1, xxx". Note: Does NOT update GitHub check status.

--gpu-type "A30, H100_PCIe" (OPTIONAL) : Only run the test stages on the specified GPU types. Examples: "A30, H100_PCIe". Note: Does NOT update GitHub check status.

--test-backend "pytorch, cpp" (OPTIONAL) : Skip test stages which don't match the specified backends. Only support [pytorch, cpp, tensorrt, triton]. Examples: "pytorch, cpp" (does not run test stages with tensorrt or triton backend). Note: Does NOT update GitHub pipeline status.

--only-multi-gpu-test (OPTIONAL) : Only run the multi-GPU tests. Note: Does NOT update GitHub check status.

--disable-multi-gpu-test (OPTIONAL) : Disable the multi-GPU tests. Note: Does NOT update GitHub check status.

--add-multi-gpu-test (OPTIONAL) : Force run the multi-GPU tests in addition to running L0 pre-merge pipeline.

--post-merge (OPTIONAL) : Run the L0 post-merge pipeline instead of the ordinary L0 pre-merge pipeline.

--extra-stage "H100_PCIe-TensorRT-Post-Merge-1, xxx" (OPTIONAL) : Run the ordinary L0 pre-merge pipeline and specified test stages. Examples: --extra-stage "H100_PCIe-TensorRT-Post-Merge-1, xxx".

--detailed-log (OPTIONAL) : Enable flushing out all logs to the Jenkins console. This will significantly increase the log volume and may slow down the job.

--debug (OPTIONAL) : Experimental feature. Enable access to the CI container for debugging purpose. Note: Specify exactly one stage in the stage-list parameter to access the appropriate container environment. Note: Does NOT update GitHub check status.

For guidance on mapping tests to stage names, see docs/source/reference/ci-overview.md
and the scripts/test_to_stage_mapping.py helper.

kill

kill

Kill all running builds associated with pull request.

skip

skip --comment COMMENT

Skip testing for latest commit on pull request. --comment "Reason for skipping build/test" is required. IMPORTANT NOTE: This is dangerous since lack of user care and validation can cause top of tree to break.

reuse-pipeline

reuse-pipeline

Reuse a previous pipeline to validate current commit. This action will also kill all currently running builds associated with the pull request. IMPORTANT NOTE: This is dangerous since lack of user care and validation can cause top of tree to break.

@brb-nv brb-nv requested a review from a team as a code owner October 5, 2025 00:02
@brb-nv brb-nv requested review from chuangz0 and schetlur-nv October 5, 2025 00:02
Copy link
Contributor

coderabbitai bot commented Oct 5, 2025

📝 Walkthrough

Walkthrough

Adds CP-aware block distribution and transmission behavior. Extends getBlockRangeForSending with recvSideHasCP. Centralizes CP block allocation in executor::kv_cache and exposes env-controlled round-robin behavior. Updates MLA split kernel interfaces and host dispatch to pass CP distribution metadata. Introduces a new env getter. Refactors and expands unit tests for CP-aware flows.

Changes

Cohort / File(s) Summary
Cache formatter API updates
cpp/tensorrt_llm/batch_manager/cacheFormatter.h, cpp/tensorrt_llm/batch_manager/cacheFormatter.cpp
getBlockRangeForSending gains bool recvSideHasCP (default false in header). Logic updated to consider recvSideHasCP when selecting full vs reused block ranges.
MLA cache formatter integration
cpp/tensorrt_llm/batch_manager/mlaCacheFormatter.cpp, cpp/tensorrt_llm/batch_manager/mlaCacheFormatter.h
Removes local getBlockNumAccountingForCP; uses executor::kv_cache::getBlockNumAccountingForCP. Passes recvSideHasCP to getBlockRangeForSending. Adds checks ensuring blockSizePerLayer > 0. Removes declaration from header.
Env utils
cpp/tensorrt_llm/common/envUtils.h, cpp/tensorrt_llm/common/envUtils.cpp
Adds getEnvUseRoundRobinBlockDistForCP(), reading TRTLLM_USE_ROUND_ROBIN_BLOCK_DIST_FOR_CP.
Executor KV-cache split/concat
cpp/tensorrt_llm/executor/cache_transmission/cacheSplitConcat.h, cpp/tensorrt_llm/executor/cache_transmission/cacheSplitConcat.cu
Adds CP-aware helpers: getBlockNumAccountingForCP, getGlobalBlockIdAccountingForCP. Extends splitKVCacheForMLAKernel with isCPRoundRobin and prefixBlockNumDevPtr; updates all launches. Adds device helper to locate block/rank within CP domain. Builds and passes prefix block counts from host using env-controlled strategy.
Unit tests (CP-aware)
cpp/tests/unit_tests/multi_gpu/cacheTransceiverTest.cpp
Introduces CPMetaData and WrappedLlmRequest. Propagates CP metadata through request creation, transport, verification. Adjusts data fill/verify to use global block IDs and CP-aware initial values. Adds rank-aware logging helper. Updates/extends tests including minimal CP MLA case; adjusts MPI assumptions.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant Sender
  participant CacheFormatter as CacheFormatter.getBlockRangeForSending
  participant CacheManager
  participant Receiver

  Sender->>CacheFormatter: getBlockRangeForSending(cacheManager, llmRequest, lastBlockKey, indexFromEnd, recvSideHasCP)
  CacheFormatter->>CacheManager: query block reuse/availability
  alt recvSideHasCP is true
    Note over CacheFormatter: CP on recv side implies full block transfer
    CacheFormatter-->>Sender: BlockRange(full)
  else recvSideHasCP is false
    CacheFormatter-->>Sender: BlockRange(full or reused)
  end
  Sender->>Receiver: transmit blocks per BlockRange
Loading
sequenceDiagram
  autonumber
  participant Host as splitKVCache (host)
  participant Env as envUtils
  participant Exec as executor::kv_cache
  participant Kernel as splitKVCacheForMLA (GPU)

  Host->>Env: getEnvUseRoundRobinBlockDistForCP()
  Env-->>Host: isCPRoundRobin
  loop for each CP rank
    Host->>Exec: getBlockNumAccountingForCP(cpRank, cpSize, numBlocks)
    Exec-->>Host: blocksForRank
  end
  Note over Host: Build prefixBlockNum vector and copy to device
  Host->>Kernel: launch(..., isCPRoundRobin, prefixBlockNumDevPtr)
  alt Round-robin
    Kernel->>Kernel: map local->global via round-robin
  else Non round-robin
    Kernel->>Kernel: map via prefix counts and domain lookup
  end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Suggested reviewers

  • schetlur-nv
  • pcastonguay
  • Shixiaowei02
  • chuangz0

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 9.09% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Title Check ✅ Passed The title clearly summarizes the main change by stating that the PR prevents over-allocation of the KV cache during disaggregated transmission with CP. It is concise, specific to the core improvement, and conveys meaningful information to anyone reviewing the commit history.
Description Check ✅ Passed The PR description includes all required template sections—Description, Test Coverage, PR Checklist, and GitHub Bot Help—with each section clearly populated with the issue context, solution details, relevant test commands, and checklist items. The Description explains what and why, the Test Coverage section lists the safeguarding tests, and the checklist and bot instructions follow the repository’s guidance.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

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)
cpp/tensorrt_llm/batch_manager/cacheFormatter.h (1)

45-46: Fix declaration/implementation mismatch.

The declaration on line 55 defines a 3-parameter overload, but the implementation in cpp/tensorrt_llm/batch_manager/cacheFormatter.cpp (lines 44-58) is a 5-parameter function that extends the existing 4-parameter version on lines 45-46. The correct change is to update lines 45-46 to include the new parameter with a default value, not add a separate 3-parameter overload.

Apply this diff to fix the declarations:

 BlockRange getBlockRangeForSending(BaseKVCacheManager* cacheManager, LlmRequest const& llmRequest,
-    BlockKey const& lastBlockKey, SizeType32 indexFromEnd);
+    BlockKey const& lastBlockKey, SizeType32 indexFromEnd, bool recvSideHasCP=false);

 using DataContext = tensorrt_llm::executor::kv_cache::DataContext;
 using Connection = tensorrt_llm::executor::kv_cache::Connection;
 using SizeType32 = tensorrt_llm::runtime::SizeType32;
 using BaseKVCacheManager = kv_cache_manager::BaseKVCacheManager;
 using CacheTransBufferManager = kv_cache_manager::CacheTransBufferManager;
 using BlockRange = kv_cache_manager::BlockRange;

-BlockRange getBlockRangeForSending(BaseKVCacheManager* cacheManager, LlmRequest const& llmRequest, bool recvSideHasCP=false);

Also applies to: 55-55

🧹 Nitpick comments (2)
cpp/tensorrt_llm/executor/cache_transmission/cacheSplitConcat.h (1)

79-79: Add documentation for getGlobalBlockIdAccountingForCP.

The function declaration lacks Doxygen documentation. Consider adding documentation similar to getBlockNumAccountingForCP above.

Example documentation:

+/**
+ * @brief Calculate the global block ID from a local block index.
+ *
+ * This function maps a local block index on a CP rank to its corresponding global block ID,
+ * accounting for CP distribution strategy (round-robin vs. contiguous).
+ *
+ * @param localBlockIdx The local block index on the current CP rank.
+ * @param cpSize The total number of CP ranks/processes in the parallel group.
+ * @param cpRank The rank (index) of the current CP process. Must be in range [0, cpSize).
+ * @param numTotalBlocks The total number of blocks distributed across all CP ranks.
+ *
+ * @return The global block ID corresponding to the local block index.
+ */
 int getGlobalBlockIdAccountingForCP(int localBlockIdx, int cpSize, int cpRank, int numTotalBlocks);
cpp/tensorrt_llm/executor/cache_transmission/cacheSplitConcat.cu (1)

646-656: Minor: Remove trailing whitespace.

Line 684 has trailing whitespace after the comment.

                 int const headIdInDomainTP = headId;
-                
+

As per coding guidelines, maintain clean formatting.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 744246d and 4ac60c1.

📒 Files selected for processing (9)
  • cpp/tensorrt_llm/batch_manager/cacheFormatter.cpp (1 hunks)
  • cpp/tensorrt_llm/batch_manager/cacheFormatter.h (1 hunks)
  • cpp/tensorrt_llm/batch_manager/mlaCacheFormatter.cpp (3 hunks)
  • cpp/tensorrt_llm/batch_manager/mlaCacheFormatter.h (0 hunks)
  • cpp/tensorrt_llm/common/envUtils.cpp (1 hunks)
  • cpp/tensorrt_llm/common/envUtils.h (1 hunks)
  • cpp/tensorrt_llm/executor/cache_transmission/cacheSplitConcat.cu (13 hunks)
  • cpp/tensorrt_llm/executor/cache_transmission/cacheSplitConcat.h (1 hunks)
  • cpp/tests/unit_tests/multi_gpu/cacheTransceiverTest.cpp (18 hunks)
💤 Files with no reviewable changes (1)
  • cpp/tensorrt_llm/batch_manager/mlaCacheFormatter.h
🧰 Additional context used
📓 Path-based instructions (7)
**/*.{h,hpp,hh,hxx,cpp,cxx,cc,cu,cuh}

📄 CodeRabbit inference engine (CODING_GUIDELINES.md)

**/*.{h,hpp,hh,hxx,cpp,cxx,cc,cu,cuh}: Namespace closing braces must include a trailing comment with the namespace name (e.g., '} // namespace foo').
Prefer const or constexpr variables over #define for constants.
Declare variables that are not modified after initialization as const.
Avoid magic literals in code; except for 0, nullptr, true, false. Use named constants for comparisons and logic.
Use Allman brace style for formatting.
Place the semicolon of an empty for/while loop on a new line.
Bodies of switch/while/do-while/for must be compound statements (brace-delimited), and if/else must always be followed by brace-delimited statements.
Type names (e.g., classes) must be CamelCase starting with an uppercase letter (e.g., FooBar).
Local variables, methods, and namespaces use lowerCamelCase (e.g., localFooBar).
Non-magic-number global variables that are non-static and not in an anonymous namespace must be lowerCamelCase prefixed with 'g' (e.g., gDontUseGlobalFoos).
Non-magic-number globals that are static or in an anonymous namespace use lowerCamelCase prefixed with 's' (e.g., sMutableStaticGlobal).
Locally visible static variables use lowerCamelCase with 's' prefix (e.g., static std::once_flag sFlag).
Private/protected member variables use 'm' prefix with CamelCase (e.g., mNbFooValues). Public members may omit, but 'm' is encouraged for clarity.
Constants (enums, global constants, static constants, and function-scope magic/literal constants) use uppercase SNAKE_CASE with 'k' prefix (e.g., kDIGIT_NUM).
Function-scope constants that are not magic numbers or literals are named like non-constant variables (e.g., bool const pass = a && b).
If macros are necessary, name them in UPPER_SNAKE_CASE (e.g., FOO_VERSION) and prefer constants over #define.
Use LLVM clang-format; wrap lines at a maximum of 120 columns; use '// clang-format off/on' sparingly with justification.
Use smart pointers for heap allocations; prefer unique_ptr for sole ownership, shared_ptr for shared...

Files:

  • cpp/tensorrt_llm/batch_manager/cacheFormatter.h
  • cpp/tensorrt_llm/common/envUtils.h
  • cpp/tensorrt_llm/batch_manager/mlaCacheFormatter.cpp
  • cpp/tensorrt_llm/common/envUtils.cpp
  • cpp/tests/unit_tests/multi_gpu/cacheTransceiverTest.cpp
  • cpp/tensorrt_llm/executor/cache_transmission/cacheSplitConcat.h
  • cpp/tensorrt_llm/batch_manager/cacheFormatter.cpp
  • cpp/tensorrt_llm/executor/cache_transmission/cacheSplitConcat.cu
**/*.{cpp,cxx,cc,cu,h,hpp,hh,hxx,cuh}

📄 CodeRabbit inference engine (CODING_GUIDELINES.md)

C++ filenames should be lowerCamelCase (first letter lowercase) and must be case-insensitive unique within a compilation target.

Files:

  • cpp/tensorrt_llm/batch_manager/cacheFormatter.h
  • cpp/tensorrt_llm/common/envUtils.h
  • cpp/tensorrt_llm/batch_manager/mlaCacheFormatter.cpp
  • cpp/tensorrt_llm/common/envUtils.cpp
  • cpp/tests/unit_tests/multi_gpu/cacheTransceiverTest.cpp
  • cpp/tensorrt_llm/executor/cache_transmission/cacheSplitConcat.h
  • cpp/tensorrt_llm/batch_manager/cacheFormatter.cpp
  • cpp/tensorrt_llm/executor/cache_transmission/cacheSplitConcat.cu
**/*.{h,hpp,hh,hxx,cpp,cxx,cc,cu,cuh,py}

📄 CodeRabbit inference engine (CODING_GUIDELINES.md)

Use only spaces, no tabs; indent with 4 spaces.

Files:

  • cpp/tensorrt_llm/batch_manager/cacheFormatter.h
  • cpp/tensorrt_llm/common/envUtils.h
  • cpp/tensorrt_llm/batch_manager/mlaCacheFormatter.cpp
  • cpp/tensorrt_llm/common/envUtils.cpp
  • cpp/tests/unit_tests/multi_gpu/cacheTransceiverTest.cpp
  • cpp/tensorrt_llm/executor/cache_transmission/cacheSplitConcat.h
  • cpp/tensorrt_llm/batch_manager/cacheFormatter.cpp
  • cpp/tensorrt_llm/executor/cache_transmission/cacheSplitConcat.cu
**/*.{h,hpp,hh,hxx}

📄 CodeRabbit inference engine (CODING_GUIDELINES.md)

Document new class interfaces and function prototypes with Doxygen; use //! for single-line and //!< for members.

Files:

  • cpp/tensorrt_llm/batch_manager/cacheFormatter.h
  • cpp/tensorrt_llm/common/envUtils.h
  • cpp/tensorrt_llm/executor/cache_transmission/cacheSplitConcat.h
**/*.{h,hpp,hh,hxx,cpp,cxx,cc}

📄 CodeRabbit inference engine (CODING_GUIDELINES.md)

**/*.{h,hpp,hh,hxx,cpp,cxx,cc}: Prefer anonymous namespaces over 'static' for internal linkage of functions.
All templates (class/function/member/static) must be instantiated at least once; non-POD classes should have private data members.

Files:

  • cpp/tensorrt_llm/batch_manager/cacheFormatter.h
  • cpp/tensorrt_llm/common/envUtils.h
  • cpp/tensorrt_llm/batch_manager/mlaCacheFormatter.cpp
  • cpp/tensorrt_llm/common/envUtils.cpp
  • cpp/tests/unit_tests/multi_gpu/cacheTransceiverTest.cpp
  • cpp/tensorrt_llm/executor/cache_transmission/cacheSplitConcat.h
  • cpp/tensorrt_llm/batch_manager/cacheFormatter.cpp
**/*.{h,hpp,hh,hxx,cuh}

📄 CodeRabbit inference engine (CODING_GUIDELINES.md)

Use include guards named 'TRTLLM_<FILE_NAME_IN_CAPS_WITH_UNDERSCORES>_H' (no leading or trailing underscore; directory names excluded).

Files:

  • cpp/tensorrt_llm/batch_manager/cacheFormatter.h
  • cpp/tensorrt_llm/common/envUtils.h
  • cpp/tensorrt_llm/executor/cache_transmission/cacheSplitConcat.h
**/*.{cpp,cxx,cc,h,hpp,hh,hxx,cu,cuh,py}

📄 CodeRabbit inference engine (CODING_GUIDELINES.md)

Prepend the NVIDIA Apache-2.0 copyright header with current year to the top of all source files (e.g., .cpp, .h, .cu, .py).

Files:

  • cpp/tensorrt_llm/batch_manager/cacheFormatter.h
  • cpp/tensorrt_llm/common/envUtils.h
  • cpp/tensorrt_llm/batch_manager/mlaCacheFormatter.cpp
  • cpp/tensorrt_llm/common/envUtils.cpp
  • cpp/tests/unit_tests/multi_gpu/cacheTransceiverTest.cpp
  • cpp/tensorrt_llm/executor/cache_transmission/cacheSplitConcat.h
  • cpp/tensorrt_llm/batch_manager/cacheFormatter.cpp
  • cpp/tensorrt_llm/executor/cache_transmission/cacheSplitConcat.cu
🧠 Learnings (7)
📚 Learning: 2025-08-21T09:41:49.347Z
Learnt from: eopXD
PR: NVIDIA/TensorRT-LLM#6768
File: cpp/tensorrt_llm/batch_manager/kvCacheManager.cpp:2010-2045
Timestamp: 2025-08-21T09:41:49.347Z
Learning: In cpp/tensorrt_llm/batch_manager/kvCacheManager.cpp, updateSequenceCacheBlockOffsets is specifically for updating bookkeeping when blocks are added during the context phase, not for refreshing offsets after detach operations. During detach operations, GenerationRequest::removeFrontBlock handles the necessary cache block bookkeeping internally.

Applied to files:

  • cpp/tensorrt_llm/batch_manager/cacheFormatter.h
  • cpp/tensorrt_llm/batch_manager/mlaCacheFormatter.cpp
  • cpp/tests/unit_tests/multi_gpu/cacheTransceiverTest.cpp
  • cpp/tensorrt_llm/batch_manager/cacheFormatter.cpp
📚 Learning: 2025-08-14T21:04:50.248Z
Learnt from: thorjohnsen
PR: NVIDIA/TensorRT-LLM#6910
File: cpp/tensorrt_llm/batch_manager/kvCacheManager.cpp:0-0
Timestamp: 2025-08-14T21:04:50.248Z
Learning: In KV cache onboarding logic during prefill in cpp/tensorrt_llm/batch_manager/kvCacheManager.cpp, when calculating which blocks fall within the attention window, use getTokensPerBlock() to advance token indices rather than block->getUniqueTokens().size(), because the calculation needs to consider the post-prefill state where blocks will be filled to capacity, not their current token count.

Applied to files:

  • cpp/tensorrt_llm/batch_manager/mlaCacheFormatter.cpp
  • cpp/tests/unit_tests/multi_gpu/cacheTransceiverTest.cpp
📚 Learning: 2025-08-20T06:48:45.368Z
Learnt from: eopXD
PR: NVIDIA/TensorRT-LLM#6768
File: cpp/include/tensorrt_llm/batch_manager/kvCacheManager.h:0-0
Timestamp: 2025-08-20T06:48:45.368Z
Learning: In cpp/tensorrt_llm/batch_manager/kvCacheManager.cpp, updateSequenceCacheBlockOffsets is only called when adding a sequence, not during detach operations. During detach, the cache block bookkeeping is handled by GenerationRequest::removeFrontBlock.

Applied to files:

  • cpp/tensorrt_llm/batch_manager/mlaCacheFormatter.cpp
📚 Learning: 2025-09-23T14:58:05.372Z
Learnt from: nv-lschneider
PR: NVIDIA/TensorRT-LLM#7910
File: cpp/tensorrt_llm/kernels/nccl_device/config.cu:42-49
Timestamp: 2025-09-23T14:58:05.372Z
Learning: In TensorRT-LLM NCCL device kernels (cpp/tensorrt_llm/kernels/nccl_device/), the token partitioning intentionally uses ceil-like distribution (same token_per_rank for all ranks) to ensure all ranks launch the same number of blocks. This is required for optimal NCCL device API barrier performance, even though it may launch extra blocks for non-existent tokens on later ranks. Runtime bounds checking in the kernel (blockID validation) handles the overshoot cases.

Applied to files:

  • cpp/tensorrt_llm/batch_manager/mlaCacheFormatter.cpp
  • cpp/tensorrt_llm/executor/cache_transmission/cacheSplitConcat.cu
📚 Learning: 2025-08-15T06:46:54.897Z
Learnt from: eopXD
PR: NVIDIA/TensorRT-LLM#6767
File: cpp/tensorrt_llm/batch_manager/kvCacheManager.cpp:0-0
Timestamp: 2025-08-15T06:46:54.897Z
Learning: In cpp/tensorrt_llm/batch_manager/kvCacheManager.cpp addToken function, newly allocated blocks are unshared by design. The beam search path in addToken (when sequence.getNumTokens() > windowSize) is currently broken/non-functional with SWA, so the block allocation doesn't follow a shared-then-unshared pattern.

Applied to files:

  • cpp/tensorrt_llm/batch_manager/mlaCacheFormatter.cpp
  • cpp/tests/unit_tests/multi_gpu/cacheTransceiverTest.cpp
📚 Learning: 2025-09-23T15:01:00.070Z
Learnt from: nv-lschneider
PR: NVIDIA/TensorRT-LLM#7910
File: cpp/tensorrt_llm/kernels/nccl_device/config.cu:15-17
Timestamp: 2025-09-23T15:01:00.070Z
Learning: In TensorRT-LLM NCCL device kernels (cpp/tensorrt_llm/kernels/nccl_device/config.cu), std::ostringstream is used but <sstream> doesn't need to be explicitly included because it's provided transitively through other headers like tensorrt_llm/common/cudaUtils.h or config.h. Local compilation testing confirms this works without the explicit include.

Applied to files:

  • cpp/tensorrt_llm/executor/cache_transmission/cacheSplitConcat.cu
📚 Learning: 2025-09-23T15:13:48.819Z
Learnt from: nv-lschneider
PR: NVIDIA/TensorRT-LLM#7910
File: cpp/tensorrt_llm/kernels/nccl_device/multimem.h:20-30
Timestamp: 2025-09-23T15:13:48.819Z
Learning: TRT-LLM targets modern CUDA toolkits that support FP8 datatypes, so cuda_fp8.h can be included unconditionally without version guards in TRT-LLM code.

Applied to files:

  • cpp/tensorrt_llm/executor/cache_transmission/cacheSplitConcat.cu
🧬 Code graph analysis (6)
cpp/tensorrt_llm/batch_manager/cacheFormatter.h (1)
cpp/tensorrt_llm/batch_manager/cacheFormatter.cpp (2)
  • getBlockRangeForSending (44-58)
  • getBlockRangeForSending (44-45)
cpp/tensorrt_llm/common/envUtils.h (1)
cpp/tensorrt_llm/common/envUtils.cpp (2)
  • getEnvUseRoundRobinBlockDistForCP (281-285)
  • getEnvUseRoundRobinBlockDistForCP (281-281)
cpp/tensorrt_llm/batch_manager/mlaCacheFormatter.cpp (2)
cpp/tensorrt_llm/batch_manager/cacheFormatter.cpp (2)
  • getBlockRangeForSending (44-58)
  • getBlockRangeForSending (44-45)
cpp/tensorrt_llm/executor/cache_transmission/cacheSplitConcat.cu (2)
  • getBlockNumAccountingForCP (49-65)
  • getBlockNumAccountingForCP (49-49)
cpp/tests/unit_tests/multi_gpu/cacheTransceiverTest.cpp (3)
cpp/tensorrt_llm/executor/cache_transmission/cacheSplitConcat.cu (4)
  • getBlockNumAccountingForCP (49-65)
  • getBlockNumAccountingForCP (49-49)
  • getGlobalBlockIdAccountingForCP (67-79)
  • getGlobalBlockIdAccountingForCP (67-67)
cpp/tensorrt_llm/common/envUtils.cpp (2)
  • getEnvUseRoundRobinBlockDistForCP (281-285)
  • getEnvUseRoundRobinBlockDistForCP (281-281)
cpp/include/tensorrt_llm/batch_manager/kvCacheUtils.h (1)
  • fromAllBlockIds (34-41)
cpp/tensorrt_llm/executor/cache_transmission/cacheSplitConcat.h (1)
cpp/tensorrt_llm/executor/cache_transmission/cacheSplitConcat.cu (4)
  • getBlockNumAccountingForCP (49-65)
  • getBlockNumAccountingForCP (49-49)
  • getGlobalBlockIdAccountingForCP (67-79)
  • getGlobalBlockIdAccountingForCP (67-67)
cpp/tensorrt_llm/executor/cache_transmission/cacheSplitConcat.cu (1)
cpp/tensorrt_llm/common/envUtils.cpp (2)
  • getEnvUseRoundRobinBlockDistForCP (281-285)
  • getEnvUseRoundRobinBlockDistForCP (281-281)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Pre-commit Check
🔇 Additional comments (11)
cpp/tensorrt_llm/common/envUtils.h (1)

63-64: LGTM!

The new environment variable getter follows the established pattern and naming conventions consistently.

cpp/tensorrt_llm/common/envUtils.cpp (1)

281-285: LGTM!

The implementation correctly follows the established pattern for environment variable getters, using static const for caching and the appropriate helper function.

cpp/tensorrt_llm/batch_manager/mlaCacheFormatter.cpp (3)

118-119: LGTM!

The CP detection logic and parameter passing to getBlockRangeForSending correctly implements the intended behavior for CP-aware cache transmission.


174-174: LGTM!

The sanity check ensures blockSizePerLayer is valid before use, preventing division-by-zero or invalid memory calculations.


184-184: LGTM!

Using the centralized executor::kv_cache::getBlockNumAccountingForCP aligns with the PR's goal to centralize CP accounting logic and remove local implementations.

cpp/tensorrt_llm/batch_manager/cacheFormatter.cpp (1)

44-58: LGTM!

The implementation correctly adds CP-aware logic with a clear explanatory comment. The condition properly returns all blocks when the receiver has CP, avoiding issues with distributed sequence lengths.

cpp/tensorrt_llm/executor/cache_transmission/cacheSplitConcat.cu (5)

49-65: LGTM!

The block distribution logic correctly implements even distribution with overflow blocks assigned to lower-indexed ranks. The early return for cpSize == 1 optimizes the common case.


67-79: LGTM!

The global block ID calculation correctly handles both round-robin and contiguous distribution modes based on the environment variable. The contiguous calculation properly accounts for overflow blocks on previous ranks.


1157-1163: LGTM!

The prefixBlockNum array is correctly sized as domainCPSize + 1 and populated with a proper prefix sum using getBlockNumAccountingForCP. This matches the device function's access pattern.

Note: This confirms the bounds in the device function getBlockIdInDomainCPandRankInDomainCP are safe.


1239-1239: LGTM!

The environment variable is correctly read once and propagated to all kernel launch sites. The kernel signature extensions properly pass both isCPRoundRobin and prefixBlockNumDevPtr for CP-aware distribution.

Also applies to: 1254-1257, 1279-1282, 1307-1310, 1340-1343, 1369-1372


604-625: Bounds verified – remove TODO
prefixBlockNum is allocated with targetRankInfo.mDomainCPSize + 1, so prefixBlockNumDevPtr[cpRank+1] is always in bounds. Delete the “Verify that these bounds are safe” TODO on line 611.


#pragma unroll 1
// TODO: Verify that these bounds are safe to use.
for (int cpRank = threadIdx.x; cpRank < domainCPSize; cpRank += blockDim.x)
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

@chuangz0, this function closely follows getLayerIdInDomainPPandRankInDomainPP. Can you please verify the bounds for CP rank make sense?

@brb-nv brb-nv force-pushed the user/brb/avoid-overalloc-in-cp-disagg branch 2 times, most recently from 7288056 to 87ba13c Compare October 5, 2025 00:35
@brb-nv brb-nv changed the title User/brb/avoid overalloc in cp disagg [TRTLLM-7731][feat] Avoid over-allocation of KV cache for transmission in disagg with CP Oct 5, 2025
@brb-nv brb-nv force-pushed the user/brb/avoid-overalloc-in-cp-disagg branch from ddf5d34 to 37866c0 Compare October 5, 2025 03:41
@brb-nv brb-nv force-pushed the user/brb/avoid-overalloc-in-cp-disagg branch from 37866c0 to bae9761 Compare October 5, 2025 03:44
@brb-nv
Copy link
Collaborator Author

brb-nv commented Oct 5, 2025

/bot run --disable-fail-fast

@tensorrt-cicd
Copy link
Collaborator

PR_Github #20635 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #20635 [ run ] completed with state SUCCESS
/LLM/main/L0_MergeRequest_PR pipeline #15582 completed with status: 'FAILURE'

@brb-nv
Copy link
Collaborator Author

brb-nv commented Oct 6, 2025

/bot run --disable-fail-fast

@tensorrt-cicd
Copy link
Collaborator

PR_Github #20678 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #20678 [ run ] completed with state SUCCESS
/LLM/main/L0_MergeRequest_PR pipeline #15621 completed with status: 'FAILURE'

@brb-nv brb-nv requested a review from Shixiaowei02 October 7, 2025 01:25
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