-
Couldn't load subscription status.
- Fork 1.8k
[TRTLLM-6371][feat] Restructure C++ KVCacheManager to better handle limited attention layers #7510
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
[TRTLLM-6371][feat] Restructure C++ KVCacheManager to better handle limited attention layers #7510
Conversation
Signed-off-by: thorjohnsen <[email protected]>
Signed-off-by: thorjohnsen <[email protected]>
Signed-off-by: thorjohnsen <[email protected]>
Signed-off-by: thorjohnsen <[email protected]>
Signed-off-by: thorjohnsen <[email protected]>
Signed-off-by: thorjohnsen <[email protected]>
Signed-off-by: thorjohnsen <[email protected]>
Signed-off-by: thorjohnsen <[email protected]>
Signed-off-by: thorjohnsen <[email protected]>
Signed-off-by: thorjohnsen <[email protected]>
Signed-off-by: thorjohnsen <[email protected]>
Signed-off-by: thorjohnsen <[email protected]>
Signed-off-by: thorjohnsen <[email protected]>
Signed-off-by: thorjohnsen <[email protected]>
Signed-off-by: thorjohnsen <[email protected]>
Signed-off-by: thorjohnsen <[email protected]>
Signed-off-by: thorjohnsen <[email protected]>
Signed-off-by: thorjohnsen <[email protected]>
Signed-off-by: thorjohnsen <[email protected]>
Signed-off-by: thorjohnsen <[email protected]>
Signed-off-by: thorjohnsen <[email protected]>
📝 WalkthroughWalkthroughIntroduces 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
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
Estimated code review effort🎯 4 (Complex) | ⏱️ ~75 minutes Possibly related PRs
Suggested labels
Suggested reviewers
Pre-merge checks and finishing touches❌ Failed checks (1 warning, 1 inconclusive)
✅ Passed checks (1 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this 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) usestd::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>forstd::sort
KVCachePromptLookupNode::findMatchingNodesusesstd::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 tidyUse 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 initializationUse 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.
emplacewon’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 callslookupNode->setBlock. The immediate explicitmatchedNode->setBlockis 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
📒 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.cppcpp/include/tensorrt_llm/executor/executor.hcpp/tests/unit_tests/batch_manager/kvCacheManagerTest.cppcpp/tests/unit_tests/batch_manager/evictionPolicyTest.cppcpp/include/tensorrt_llm/batch_manager/kvCacheManager.hcpp/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.cppcpp/include/tensorrt_llm/executor/executor.hcpp/tests/unit_tests/batch_manager/kvCacheManagerTest.cppcpp/tests/unit_tests/batch_manager/evictionPolicyTest.cppcpp/include/tensorrt_llm/batch_manager/kvCacheManager.hcpp/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.cppcpp/include/tensorrt_llm/executor/executor.hcpp/tests/unit_tests/batch_manager/kvCacheManagerTest.cppcpp/tests/unit_tests/batch_manager/evictionPolicyTest.cppcpp/include/tensorrt_llm/batch_manager/kvCacheManager.hcpp/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.cppcpp/include/tensorrt_llm/executor/executor.hcpp/tests/unit_tests/batch_manager/kvCacheManagerTest.cppcpp/tests/unit_tests/batch_manager/evictionPolicyTest.cppcpp/include/tensorrt_llm/batch_manager/kvCacheManager.hcpp/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.cppcpp/include/tensorrt_llm/executor/executor.hcpp/tests/unit_tests/batch_manager/kvCacheManagerTest.cppcpp/tests/unit_tests/batch_manager/evictionPolicyTest.cppcpp/include/tensorrt_llm/batch_manager/kvCacheManager.hcpp/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.hcpp/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.hcpp/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.cppcpp/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.cppcpp/include/tensorrt_llm/batch_manager/kvCacheManager.hcpp/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.cppcpp/include/tensorrt_llm/batch_manager/kvCacheManager.hcpp/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 clarityAdding 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
reusedBlockIdslifetime/scope (not shown here) to avoid ODR or shadowing issues.
1029-1034: Invalid comparison between SizeType32 and std::optional (compile-time error).
windowSize < maxSequenceLengthis 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.
Signed-off-by: thorjohnsen <[email protected]>
There was a problem hiding this 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 |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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]>
…ucture_kvcachemanager_for_vswa .
Signed-off-by: thorjohnsen <[email protected]>
Signed-off-by: thorjohnsen <[email protected]>
|
\bot run --disable-fail-fast |
Signed-off-by: thorjohnsen <[email protected]>
Signed-off-by: thorjohnsen <[email protected]>
Signed-off-by: thorjohnsen <[email protected]>
Signed-off-by: thorjohnsen <[email protected]>
Signed-off-by: thorjohnsen <[email protected]>
Signed-off-by: thorjohnsen <[email protected]>
…ucture_kvcachemanager_for_vswa .
|
/bot run --disable-fail-fast |
|
PR_Github #22477 [ run ] triggered by Bot. Commit: |
|
PR_Github #22477 [ run ] completed with state |
Signed-off-by: thorjohnsen <[email protected]>
Signed-off-by: thorjohnsen <[email protected]>
…ucture_kvcachemanager_for_vswa .
Signed-off-by: thorjohnsen <[email protected]>
…ucture_kvcachemanager_for_vswa .
|
/bot run --disable-fail-fast |
|
PR_Github #22670 [ run ] triggered by Bot. Commit: |
…ucture_kvcachemanager_for_vswa .
|
PR_Github #22670 [ run ] completed with state |
Signed-off-by: thorjohnsen <[email protected]>
|
/bot run --disable-fail-fast |
|
PR_Github #22686 [ run ] triggered by Bot. Commit: |
There was a problem hiding this 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. |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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>>; |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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? |
There was a problem hiding this comment.
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? |
There was a problem hiding this comment.
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.
|
PR_Github #22686 [ run ] completed with state |
This PR implements the changes outlined in this document to make KVCacheManager better suited for limited attention layers. The highlights are:
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 thestage-listparameter 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.mdand the
scripts/test_to_stage_mapping.pyhelper.kill
killKill all running builds associated with pull request.
skip
skip --comment COMMENTSkip 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-pipelineReuse 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
Improvements