Skip to content

Conversation

@thorjohnsen
Copy link
Collaborator

@thorjohnsen thorjohnsen commented Sep 3, 2025

This PR implements the changes outlined in this document to make KVCacheManager better suited for limited attention layers. The highlights are:

  • Lookup structure has been separated from KV cache blocks
  • All window managers share a common lookup structure
  • True priority based eviction

The old implementation allowed optimal eviction strategy for full attention layers. The new implementation preserves that + allows optimal eviction strategy for reduced attention layers as well.

This work is tracked in TRTLLM-6371.

Note: This is a big PR, but the majority of new lines are debug printouts and comments. I did extensive debugging-by-print-statements while running the unit tests to verify that KV cache manager behaves as expected. The debug printouts are generated when TLLM_LOG_LEVEL == DEBUG. The comments state what the code is expected to do.

Test Coverage

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.

Summary by CodeRabbit

  • New Features

    • Added prompt-prefix lookup to accelerate KV cache reuse across prompts and window sizes.
    • Introduced window-size-aware cache blocks and Sliding Window Awareness (SWA) mode for improved long-context handling.
    • Added human-readable printing of KV cache retention settings for easier debugging.
  • Improvements

    • Streamlined eviction behavior for more predictable block prioritization and release.
    • Enhanced matching and storage pathways to prefer lookup-driven reuse, reducing redundant allocations.
    • Expanded debug logging to aid tracing of cache decisions and retention configurations.

@thorjohnsen thorjohnsen self-assigned this Sep 24, 2025
@thorjohnsen thorjohnsen marked this pull request as ready for review October 10, 2025 16:43
@thorjohnsen thorjohnsen requested review from eopXD and kaiyux October 10, 2025 16:44
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Oct 10, 2025

📝 Walkthrough

Walkthrough

Introduces a lookup-driven prompt-prefix mechanism into KV cache management, adds windowSize awareness to KVCacheBlock and managers, modifies eviction policy internals by removing released-block tracking, and adds print helpers in executor. Tests are updated for new constructor signatures and adjusted eviction/reuse expectations.

Changes

Cohort / File(s) Summary
Eviction policy internals
cpp/include/tensorrt_llm/batch_manager/evictionPolicy.h, cpp/tensorrt_llm/batch_manager/evictionPolicy.cpp
Removed released-block tracking (mReleasedBlocks, isReleasedLeafBlock). Simplified claim/release paths to use per-priority free queues and heap detachment. Added logging; updated priority/duration handling. No public API change.
KV cache manager API surface
cpp/include/tensorrt_llm/batch_manager/kvCacheManager.h
Added KVCachePromptLookup/KVCachePromptLookupNode (forward decls and classes), new pointer/type aliases, LookupResult(s). Extended KVCacheBlock with windowSize and lookup-node linkage; updated signatures (constructors, getters/setters). WindowBlockManager and BlockManager gain isSWA plumbing and lookup-aware methods (addSequence, storeBlocks).
KV cache manager implementation
cpp/tensorrt_llm/batch_manager/kvCacheManager.cpp
Implemented lookup-driven prompt matching across window sizes, with node graph, matching, and printing utilities. Reworked block creation/storage to be windowSize- and lookup-aware. Updated managers to integrate lookup paths and SWA handling.
Executor print helpers
cpp/include/tensorrt_llm/executor/executor.h
Added print() methods for RetentionPriorityAndDuration, TokenRangeRetentionConfig, and KvCacheRetentionConfig for textual serialization.
Unit tests: eviction policy
cpp/tests/unit_tests/batch_manager/evictionPolicyTest.cpp
Updated KVCacheBlock construction to include windowSize parameter across tests.
Unit tests: KV cache manager
cpp/tests/unit_tests/batch_manager/kvCacheManagerTest.cpp
Adjusted expectations for eviction/reuse behavior; added windowSize in block construction; optional logging of KvCacheRetentionConfig; updated context position assertions.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor Client
  participant KM as KVCacheManager
  participant BM as BlockManager
  participant WBM as WindowBlockManager
  participant L as KVCachePromptLookup
  participant N as LookupNode(s)
  participant EP as EvictionPolicy
  participant B as KVCacheBlock

  Client->>KM: addSequence(llmRequest, inputLen, ...)
  KM->>L: lookup(llmRequest, inputLen, allowPartial, enablePartial, create)
  L-->>KM: LookupResults (per-window matches)
  KM->>BM: storeBlocks(lookupResults, blockIds)
  BM->>WBM: addSequence(..., matchedBlocks with LookupNodePtr)
  alt exact/partial matches
    WBM->>N: getBlock(windowSize)
    N-->>WBM: BlockPtr (if existing)
  else new blocks needed
    WBM->>EP: claimBlock(priority, duration)
    EP-->>WBM: free block id
    WBM->>B: construct KVCacheBlock(id, idx, windowSize)
    WBM->>N: setBlock(windowSize, BlockPtr)
  end
  WBM-->>BM: sequence scheduled
  BM-->>KM: stored/linked
  KM-->>Client: sequence added
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~75 minutes

Possibly related PRs

Suggested labels

KV-Cache Management

Suggested reviewers

  • netanel-haber
  • laikhtewari

Pre-merge checks and finishing touches

❌ Failed checks (1 warning, 1 inconclusive)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 12.50% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
Description Check ❓ Inconclusive The PR description includes a clear title following the required format [TRTLLM-6371][feat], a comprehensive description explaining the changes (lookup structure separation, shared window managers, true priority-based eviction) and their purpose (supporting limited attention layers while maintaining optimal eviction for full attention), and a completed checklist. However, the Test Coverage section is incomplete and vague—it contains only HTML comments suggesting conceptual test scenarios rather than clearly listing the actual test files or test cases that provide coverage for these changes, which is explicitly required by the template ("list clearly what are the relevant test(s)"). The author should clarify the Test Coverage section by explicitly naming the test files and specific test cases that validate the changes. Based on the raw summary, tests in evictionPolicyTest.cpp and kvCacheManagerTest.cpp were modified; the author should enumerate which tests provide coverage for the new lookup structure, window manager sharing, and priority-based eviction logic to satisfy the template requirement.
✅ Passed checks (1 passed)
Check name Status Explanation
Title Check ✅ Passed The title accurately reflects the main change of restructuring the C++ KVCacheManager to support limited attention layers, and it follows the project’s JIRA ticket and type conventions, making it clear and concise for reviewers scanning the history.
✨ 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: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
cpp/include/tensorrt_llm/executor/executor.h (1)

19-35: Add <sstream> include for the new print helpers

RetentionPriorityAndDuration::print() (and the other print helpers) use std::stringstream, but this header does not include <sstream>, so the build fails on strict compilers. Please add the missing include.

 #include <map>
+#include <sstream>
 #include <memory>
cpp/include/tensorrt_llm/batch_manager/kvCacheManager.h (1)

17-44: Include <algorithm> for std::sort

KVCachePromptLookupNode::findMatchingNodes uses std::sort, but this header does not include <algorithm>. This causes compilation failures when transitive includes are unavailable. Please add the missing header.

 #include <array>
+#include <algorithm>
 #include <cstdint>
🧹 Nitpick comments (8)
cpp/tests/unit_tests/batch_manager/kvCacheManagerTest.cpp (2)

1788-1792: Name casing and const-qualify the optional; keep test logs tidy

Use lowerCamelCase with correct casing and make it const. This matches our style and avoids accidental mutation. As per coding guidelines

-auto kvCacheRetentionconfig = llmRequest0->getKvCacheRetentionConfig();
-if (kvCacheRetentionconfig.has_value())
+auto const kvCacheRetentionConfig = llmRequest0->getKvCacheRetentionConfig();
+if (kvCacheRetentionConfig.has_value())
 {
-    TLLM_LOG_DEBUG("%s%d - KvCacheRetentionConfig = %s",__FILE__,__LINE__,kvCacheRetentionconfig.value().print().c_str());
+    TLLM_LOG_DEBUG("%s:%d - KvCacheRetentionConfig = %s",
+        __FILE__, __LINE__, kvCacheRetentionConfig.value().print().c_str());
 }

3490-3491: Prefer existing tk alias and uniform initialization

Use tk::KVCacheIndex with braced init to match the rest of the file and improve readability.

-auto primaryBlock = std::make_shared<KVCacheBlock>(0, tensorrt_llm::kernels::KVCacheIndex(0, false), windowSize);
-auto secondaryBlock = std::make_shared<KVCacheBlock>(1, tensorrt_llm::kernels::KVCacheIndex(0, true), windowSize);
+auto primaryBlock = std::make_shared<KVCacheBlock>(0, tk::KVCacheIndex{0, false}, windowSize);
+auto secondaryBlock = std::make_shared<KVCacheBlock>(1, tk::KVCacheIndex{0, true}, windowSize);
cpp/tensorrt_llm/batch_manager/kvCacheManager.cpp (6)

865-867: Comment contradicts sort order.

Comparator sorts by numMatched descending, but comment says ascending.

-        // sort partial matches in ascending order
+        // sort partial matches in descending order

907-923: Clean up setBlock: avoid shadowing and ensure overwrite.

  • Shadowing parameter ‘block’ with a local variable is confusing.
  • emplace won’t overwrite an existing entry; use assignment.
 void KVCachePromptLookupNode::setBlock(SizeType32 windowSize, BlockPtr block)
 {
     if (block == nullptr)
     {
         auto blockItr = mBlocks.find(windowSize);
         if (blockItr != mBlocks.end())
         {
-            auto block = blockItr->second;
             mBlocks.erase(blockItr);
         }
     }
     else
     {
-        mBlocks.emplace(std::make_pair(windowSize, block));
+        mBlocks[windowSize] = block;
     }
 }

1766-1805: Redundant setBlock call; setLookupNode already updates the node.

setLookupNode(matchedNode, block) sets mLookupNode and calls lookupNode->setBlock. The immediate explicit matchedNode->setBlock is redundant.

-            block->setLookupNode(matchedNode, block);
-            matchedNode->setBlock(mWindowSize, block);
+            block->setLookupNode(matchedNode, block);

535-549: Tuple destructuring names are swapped; improve clarity.

The tuple is (partial, numMatched, BlockPtr, LookupNodePtr). Naming the third element “matchedNode” is misleading.

-    [[maybe_unused]] auto const [partialMatch,nuMatched,matchedNode,matchedBlock] = match;
-    if (matchedNode != nullptr)
+    [[maybe_unused]] auto const [partialMatch, numMatched, matchedBlock, matchedNode] = match;
+    if (matchedBlock != nullptr)
     {
-        out << printBlockKey(matchedNode->getBlockKey());
+        out << printBlockKey(matchedBlock->getBlockKey());
     }

872-906: Remove commented-out code or guard with preprocessor.

Large commented-out function violates the “no commented-out code” guideline. Remove it or wrap with #if 0 / feature flag.

As per coding guidelines.


165-182: Tabs found; use spaces only.

Several new lines are indented with tabs. Project guideline: 4 spaces, no tabs.

Run clang-format (LLVM style) and replace tabs with spaces. As per coding guidelines.

Also applies to: 193-201, 436-452, 516-534, 556-565, 572-575

📜 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 f156221 and 42fe938.

📒 Files selected for processing (7)
  • cpp/include/tensorrt_llm/batch_manager/evictionPolicy.h (0 hunks)
  • cpp/include/tensorrt_llm/batch_manager/kvCacheManager.h (16 hunks)
  • cpp/include/tensorrt_llm/executor/executor.h (3 hunks)
  • cpp/tensorrt_llm/batch_manager/evictionPolicy.cpp (2 hunks)
  • cpp/tensorrt_llm/batch_manager/kvCacheManager.cpp (27 hunks)
  • cpp/tests/unit_tests/batch_manager/evictionPolicyTest.cpp (1 hunks)
  • cpp/tests/unit_tests/batch_manager/kvCacheManagerTest.cpp (4 hunks)
💤 Files with no reviewable changes (1)
  • cpp/include/tensorrt_llm/batch_manager/evictionPolicy.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/evictionPolicy.cpp
  • cpp/include/tensorrt_llm/executor/executor.h
  • cpp/tests/unit_tests/batch_manager/kvCacheManagerTest.cpp
  • cpp/tests/unit_tests/batch_manager/evictionPolicyTest.cpp
  • cpp/include/tensorrt_llm/batch_manager/kvCacheManager.h
  • cpp/tensorrt_llm/batch_manager/kvCacheManager.cpp
**/*.{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/evictionPolicy.cpp
  • cpp/include/tensorrt_llm/executor/executor.h
  • cpp/tests/unit_tests/batch_manager/kvCacheManagerTest.cpp
  • cpp/tests/unit_tests/batch_manager/evictionPolicyTest.cpp
  • cpp/include/tensorrt_llm/batch_manager/kvCacheManager.h
  • cpp/tensorrt_llm/batch_manager/kvCacheManager.cpp
**/*.{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/evictionPolicy.cpp
  • cpp/include/tensorrt_llm/executor/executor.h
  • cpp/tests/unit_tests/batch_manager/kvCacheManagerTest.cpp
  • cpp/tests/unit_tests/batch_manager/evictionPolicyTest.cpp
  • cpp/include/tensorrt_llm/batch_manager/kvCacheManager.h
  • cpp/tensorrt_llm/batch_manager/kvCacheManager.cpp
**/*.{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/evictionPolicy.cpp
  • cpp/include/tensorrt_llm/executor/executor.h
  • cpp/tests/unit_tests/batch_manager/kvCacheManagerTest.cpp
  • cpp/tests/unit_tests/batch_manager/evictionPolicyTest.cpp
  • cpp/include/tensorrt_llm/batch_manager/kvCacheManager.h
  • cpp/tensorrt_llm/batch_manager/kvCacheManager.cpp
**/*.{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/evictionPolicy.cpp
  • cpp/include/tensorrt_llm/executor/executor.h
  • cpp/tests/unit_tests/batch_manager/kvCacheManagerTest.cpp
  • cpp/tests/unit_tests/batch_manager/evictionPolicyTest.cpp
  • cpp/include/tensorrt_llm/batch_manager/kvCacheManager.h
  • cpp/tensorrt_llm/batch_manager/kvCacheManager.cpp
**/*.{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/include/tensorrt_llm/executor/executor.h
  • cpp/include/tensorrt_llm/batch_manager/kvCacheManager.h
**/*.{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/include/tensorrt_llm/executor/executor.h
  • cpp/include/tensorrt_llm/batch_manager/kvCacheManager.h
🧠 Learnings (6)
📚 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/evictionPolicy.cpp
  • cpp/tensorrt_llm/batch_manager/kvCacheManager.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/evictionPolicy.cpp
📚 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/tests/unit_tests/batch_manager/kvCacheManagerTest.cpp
  • cpp/include/tensorrt_llm/batch_manager/kvCacheManager.h
  • cpp/tensorrt_llm/batch_manager/kvCacheManager.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/tests/unit_tests/batch_manager/kvCacheManagerTest.cpp
  • cpp/include/tensorrt_llm/batch_manager/kvCacheManager.h
  • cpp/tensorrt_llm/batch_manager/kvCacheManager.cpp
📚 Learning: 2025-08-20T06:56:02.889Z
Learnt from: eopXD
PR: NVIDIA/TensorRT-LLM#6768
File: cpp/tensorrt_llm/batch_manager/kvCacheManager.cpp:577-579
Timestamp: 2025-08-20T06:56:02.889Z
Learning: In cpp/tensorrt_llm/batch_manager/kvCacheManager.cpp, maxSequenceLength is now enforced as a non-optional argument in the BlockManager constructor, so concerns about std::nullopt defaulting to 0 are not applicable. When windowSize > maxSequenceLength, a warning should be added instead of handling optional parameter cases.

Applied to files:

  • cpp/tensorrt_llm/batch_manager/kvCacheManager.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: There is a planned refactoring to move cache block bookkeeping utilities from BlockManager/WindowBlockManager into the GenerationRequest class itself to improve code organization and make responsibilities clearer.

Applied to files:

  • cpp/tensorrt_llm/batch_manager/kvCacheManager.cpp
🧬 Code graph analysis (4)
cpp/include/tensorrt_llm/executor/executor.h (1)
cpp/tensorrt_llm/executor/kvCacheRetentionConfig.cpp (1)
  • TokenRangeRetentionConfig (26-37)
cpp/tests/unit_tests/batch_manager/kvCacheManagerTest.cpp (1)
cpp/tests/unit_tests/batch_manager/evictionPolicyTest.cpp (1)
  • windowSize (42-59)
cpp/include/tensorrt_llm/batch_manager/kvCacheManager.h (1)
cpp/tensorrt_llm/batch_manager/kvCacheManager.cpp (74)
  • KVCachePromptLookupNode (788-795)
  • KVCachePromptLookup (459-464)
  • BlockManager (992-1068)
  • KVCacheManager (2035-2046)
  • KVCacheManager (2048-2063)
  • KVCacheManager (2065-2098)
  • KVCacheManager (2100-2114)
  • WindowBlockManager (1070-1164)
  • WindowBlockManager (1166-1185)
  • KVCacheBlock (275-289)
  • isFull (429-432)
  • isFull (429-429)
  • isFull (942-945)
  • isFull (942-942)
  • setBlockKey (349-353)
  • setBlockKey (349-349)
  • setBlockKey (797-801)
  • setBlockKey (797-797)
  • getBlockKey (355-358)
  • getBlockKey (355-355)
  • getBlockKey (803-806)
  • getBlockKey (803-803)
  • nodiscard (1445-1472)
  • nodiscard (1904-1907)
  • nodiscard (2890-2908)
  • getUniqueTokens (405-408)
  • getUniqueTokens (405-405)
  • getUniqueTokens (808-811)
  • getUniqueTokens (808-808)
  • getPrevNode (813-816)
  • getPrevNode (813-813)
  • setPrevNode (818-821)
  • setPrevNode (818-818)
  • getNextNodes (823-826)
  • getNextNodes (823-823)
  • addNextNode (828-831)
  • addNextNode (828-828)
  • removeNextNode (833-836)
  • removeNextNode (833-833)
  • findMatchingNodes (838-870)
  • findMatchingNodes (838-838)
  • setBlock (907-922)
  • setBlock (907-907)
  • getBlock (924-935)
  • getBlock (924-924)
  • hasBlocks (937-940)
  • hasBlocks (937-937)
  • isLeaf (947-950)
  • isLeaf (947-947)
  • getBlockKeys (579-593)
  • getBlockKeys (579-579)
  • findNewContextBlock (751-786)
  • findNewContextBlock (751-751)
  • findNewContextBlock (1445-1446)
  • findNewContextBlock (2368-2373)
  • findNewContextBlock (2368-2369)
  • lookup (712-748)
  • lookup (712-712)
  • lookupBlocks (599-709)
  • lookupBlocks (599-602)
  • getPrevBlockInSeq (419-422)
  • getPrevBlockInSeq (419-419)
  • setPrevBlockInSeq (424-427)
  • setPrevBlockInSeq (424-424)
  • getPrevBlock (410-417)
  • getPrevBlock (410-410)
  • setLookupNode (434-452)
  • setLookupNode (434-434)
  • getLookupNode (454-457)
  • getLookupNode (454-454)
  • storeBlocks (1766-1805)
  • storeBlocks (1766-1768)
  • loadOrAllocateBlocks (1479-1589)
  • loadOrAllocateBlocks (1479-1481)
cpp/tensorrt_llm/batch_manager/kvCacheManager.cpp (2)
cpp/tests/unit_tests/batch_manager/evictionPolicyTest.cpp (1)
  • windowSize (42-59)
cpp/include/tensorrt_llm/batch_manager/kvCacheManager.h (4)
  • getBlockKey (226-313)
  • partialMatch (153-164)
  • numMatched (155-163)
  • storeBlocks (1016-1020)
🔇 Additional comments (5)
cpp/tests/unit_tests/batch_manager/kvCacheManagerTest.cpp (1)

3472-3472: LGTM: explicit window size improves test clarity

Adding windowSize aligns this test with window-aware blocks and shared lookup.

cpp/tensorrt_llm/batch_manager/kvCacheManager.cpp (4)

338-342: isShared semantics changed; verify intent.

Treating “in lookup” (mLookupNode != nullptr) as shared may cause blocks with refCount == 1 to be considered shared and trigger replaceSharedBlock unexpectedly.

If unintended, revert to refCount-only check or gate on a dedicated flag. As per coding guidelines.


1199-1206: Lookup once, reuse across windows: LGTM.

Centralized lookup, then store per window manager is clean and avoids repeated tree traversal.

Also applies to: 1932-1946, 1981-1989


1479-1590: Partial-reuse and detach flow: LGTM, with one note.

The copy-on-partial then detach via setLookupNode(nullptr) is correct. The reuse counters and offload paths are consistent.

Confirm reusedBlockIds lifetime/scope (not shown here) to avoid ODR or shadowing issues.


1029-1034: Invalid comparison between SizeType32 and std::optional (compile-time error).

windowSize < maxSequenceLength is ill-formed. Check presence and compare the contained value.

-        auto isSWA = windowSize < maxSequenceLength;
+        bool isSWA = maxSequenceLength.has_value() && windowSize < maxSequenceLength.value();

Optionally, warn if maxSequenceLength is present and windowSize > value (Based on learnings).

⛔ Skipped due to learnings
Learnt from: eopXD
PR: NVIDIA/TensorRT-LLM#6768
File: cpp/tensorrt_llm/batch_manager/kvCacheManager.cpp:577-579
Timestamp: 2025-08-20T06:56:02.889Z
Learning: In cpp/tensorrt_llm/batch_manager/kvCacheManager.cpp, maxSequenceLength is now enforced as a non-optional argument in the BlockManager constructor, so concerns about std::nullopt defaulting to 0 are not applicable. When windowSize > maxSequenceLength, a warning should be added instead of handling optional parameter cases.
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.

Copy link
Collaborator

@eopXD eopXD left a comment

Choose a reason for hiding this comment

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

Thank you for illustrating the code with comments. Probably need a rebase for a more clean diff.


void removeNextNode(BlockKey const& blockKey);

//! \brief Find block matching blockKey. If allowPartial is true, the returned block may match only a prefix of
Copy link
Collaborator

Choose a reason for hiding this comment

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

If allowPartial is true -> If enablePartialReuse is true

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

No, these are unrelated, but I will admit they sound (very) related. allowPartial allows blocks that are not completely full to be considered for reuse as long as it is a perfect match for the search blockKey. enablePartialReuse allows blocks where some but not all tokens match the search blockKey to be reused, usually by copying the matching tokens into a new block.

Copy link
Collaborator

Choose a reason for hiding this comment

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

Thank you for the explanation. If so, I recommend to align the comment here to allowPartial -> allowPartiallyFilledBlock.

The ambiguity of "allow partially filled blocks (to be saved for reuse)" and "enable partial reuse of a saved block" should be clarified somewhere.

Signed-off-by: thorjohnsen <[email protected]>
@thorjohnsen
Copy link
Collaborator Author

\bot run --disable-fail-fast

@thorjohnsen
Copy link
Collaborator Author

/bot run --disable-fail-fast

@tensorrt-cicd
Copy link
Collaborator

PR_Github #22477 [ run ] triggered by Bot. Commit: 24dfa89

@thorjohnsen thorjohnsen requested a review from Funatiq October 24, 2025 22:09
@tensorrt-cicd
Copy link
Collaborator

PR_Github #22477 [ run ] completed with state FAILURE. Commit: 24dfa89
/LLM/main/L0_MergeRequest_PR pipeline #16939 completed with status: 'FAILURE'

@thorjohnsen
Copy link
Collaborator Author

/bot run --disable-fail-fast

@tensorrt-cicd
Copy link
Collaborator

PR_Github #22670 [ run ] triggered by Bot. Commit: a8ad970

@tensorrt-cicd
Copy link
Collaborator

PR_Github #22670 [ run ] completed with state SUCCESS. Commit: a8ad970
/LLM/main/L0_MergeRequest_PR pipeline #17090 completed with status: 'FAILURE'

Signed-off-by: thorjohnsen <[email protected]>
@thorjohnsen
Copy link
Collaborator Author

/bot run --disable-fail-fast

@tensorrt-cicd
Copy link
Collaborator

PR_Github #22686 [ run ] triggered by Bot. Commit: 64ef5f3

Copy link
Collaborator

@eopXD eopXD left a comment

Choose a reason for hiding this comment

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

The blocks are well-kept and limited by a pool. On the other hand, does the lookup structure grow indefinitely and not be pruned? This doesn't sound good if the use case is a continue-served server.

blockKey.extraKeys.insert(blockKey.extraKeys.begin(), extraKeys.begin(), extraKeys.end());
blockKey.cacheSaltID = cacheSaltID;
return blockKey;
// TODO: Add unit test verifying correct copy of both partial and full token Ids.
Copy link
Collaborator

Choose a reason for hiding this comment

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

Is this TODO addressed?

return numMatched;
}

//! \brief Deep copy, optionally reducing number of tokens
Copy link
Collaborator

Choose a reason for hiding this comment

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

I would suggest to make this grammatically correct.

Deep copy, optionally reducing number of tokens copied

std::size_t allocatedBytes{};
};

using LookupResult = std::vector<std::tuple<bool, SizeType32, LookupNodePtr>>;
Copy link
Collaborator

Choose a reason for hiding this comment

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

With expecting users to read top down, maybe a comment here is good for comprehensing the code.


void removeNextNode(BlockKey const& blockKey);

//! \brief Find block matching blockKey. If allowPartial is true, the returned block may match only a prefix of
Copy link
Collaborator

Choose a reason for hiding this comment

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

Thank you for the explanation. If so, I recommend to align the comment here to allowPartial -> allowPartiallyFilledBlock.

The ambiguity of "allow partially filled blocks (to be saved for reuse)" and "enable partial reuse of a saved block" should be clarified somewhere.

LookupNodePtr mPrevNode;
// Next node(s) in sequence(s)
NextNodeMap mNextNodes;
// Pointers to blocks holding KV state for this prompt prefix
Copy link
Collaborator

Choose a reason for hiding this comment

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

Reading through this, SizeType32 is a meaningless type-definition in my opinion.

I would rather have an extra layer of

using WindowSizeType = SizeType32;
std::unordered_map<WindowSizeType, BlockPtr> mBlocks;

to make the object explicit that it is a mapping of window size to block pointers.

LlmRequest const& llmRequest, SizeType32 inputLength, bool allowPartiallyFilledBlock) const;

//! \brief Find last valid block for prefix given in blockKey.
//! \details Seems like blockKey contains a full prefix, not just key for an individual block. This is very hacky
Copy link
Collaborator

Choose a reason for hiding this comment

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

Fix comment, multiple \details.

I guess it is a design decision upon whether the hash needs to take the full prefix into account since we already operate upon a radix tree. What specific bug do you mean here?

auto searchRoot = mRoot;
for (auto const& blockKey : blockKeys)
{
auto matches = searchRoot != nullptr ? searchRoot->findMatchingNodes(blockKey, enablePartialReuse, false)
Copy link
Collaborator

Choose a reason for hiding this comment

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

Why is ignoreNodesWithoutBlocks = false here and not true?


//! \brief Find last valid block for prefix given in blockKey.
//! \details Seems like blockKey contains a full prefix, not just key for an individual block. This is very hacky and
//! will lead to hilarious bugs. \details Since all KV cache manager bugs eventually gets reassigned to me, THIS MUST BE
Copy link
Collaborator

Choose a reason for hiding this comment

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

Ditto as header file, fix comment.

auto blockedUniqueTokens
= chopVectorIntoBlocks<UniqueToken>(blockKey.uniqueTokens, blockKey.uniqueTokens.size(), mTokensPerBlock, true);

// TODO: Can buildBlockKeys(...) replace this paragraph?
Copy link
Collaborator

Choose a reason for hiding this comment

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

Should TODO this be addressed?

= chopVectorIntoBlocks<UniqueToken>(uniqueTokens, uniqueTokens.size() - 1, getTokensPerBlock(), false);
auto blockKeys = buildBlockKeys(blockedUniqueTokens, llmRequest);
(void) mWindowBlockManagers.at(windowSize).storeBlocks(std::move(blockKeys), cacheBlockIds[beamIdx]);
// TODO: Should we return these values?
Copy link
Collaborator

Choose a reason for hiding this comment

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

Ideally this should be logged.

@tensorrt-cicd
Copy link
Collaborator

PR_Github #22686 [ run ] completed with state SUCCESS. Commit: 64ef5f3
/LLM/main/L0_MergeRequest_PR pipeline #17105 completed with status: 'FAILURE'

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