Skip to content

Conversation

@Shunkangz
Copy link
Collaborator

@Shunkangz Shunkangz commented Nov 10, 2025

Summary by CodeRabbit

  • New Features
    • Added persistent KV cache connector for TensorRT-LLM that enables caching and reusing model computation blocks across multiple instances
    • Implemented disk-backed caching to optimize GPU memory usage by storing and retrieving cached data
    • Supports cache reuse across separate model runs, producing identical outputs while reducing memory overhead

Description

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

  • Update tava architecture diagram if there is a significant design change in PR.

  • The reviewers assigned automatically/manually are appropriate for the PR.

  • Please check this after reviewing the above items as appropriate for this PR.

GitHub Bot Help

/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.

Signed-off-by: Shunkang <182541032+Shunkangz@users.noreply.github.co>
@Shunkangz Shunkangz requested a review from a team as a code owner November 10, 2025 09:19
@Shunkangz Shunkangz requested a review from QiJune November 10, 2025 09:19
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Nov 10, 2025

📝 Walkthrough

Walkthrough

Introduces a persistent KV cache connector for TensorRT-LLM with a leader component (scheduler) managing token block hashing and a worker component handling disk-backed load/save operations. Enables subsequent LLM instances to reuse cached KV cache blocks from disk.

Changes

Cohort / File(s) Summary
Persistent KV Cache Connector Implementation
examples/llm-api/llm_kv_cache_connector.py
Added PersistentKvCacheConnectorLeader class that hashes token blocks, tracks pending loads, and emits metadata for loads/saves. Added PersistentKvCacheConnectorWorker class that performs disk load/save operations, registers KV cache tensors, and manages synchronization. Integrated KvCacheConnectorConfig and temporary directory-backed cache with environment variable setup. Implements sequential dual-instance execution with cache reuse verification through identical output assertion.

Sequence Diagram(s)

sequenceDiagram
    participant First LLM Instance
    participant PersistentKvCacheConnectorLeader
    participant PersistentKvCacheConnectorWorker
    participant Disk Cache
    participant Second LLM Instance

    First LLM Instance->>PersistentKvCacheConnectorLeader: Process test prompt
    PersistentKvCacheConnectorLeader->>PersistentKvCacheConnectorLeader: Hash token blocks
    PersistentKvCacheConnectorLeader->>PersistentKvCacheConnectorWorker: Emit metadata for saves
    PersistentKvCacheConnectorWorker->>Disk Cache: Save KV cache blocks as .pt files
    Note over Disk Cache: Cache blocks stored with hash-based paths

    Second LLM Instance->>PersistentKvCacheConnectorLeader: Process same prompt
    PersistentKvCacheConnectorLeader->>PersistentKvCacheConnectorLeader: Hash token blocks (matching)
    PersistentKvCacheConnectorLeader->>PersistentKvCacheConnectorWorker: Emit metadata for loads
    PersistentKvCacheConnectorWorker->>Disk Cache: Load cached blocks
    Disk Cache->>PersistentKvCacheConnectorWorker: Return cached KV tensors
    PersistentKvCacheConnectorWorker->>Second LLM Instance: Register tensors to GPU memory
    Note over Second LLM Instance: Produces identical output using cached blocks
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

  • Dual-component architecture: Review interactions between Leader (scheduler) and Worker (executor) for correct metadata emission and synchronization logic.
  • Disk I/O operations: Verify hash-based file path generation, .pt file handling, and proper error handling for missing/corrupted cache files.
  • Cache synchronization: Ensure proper synchronization around save operations and race condition prevention when multiple instances access the cache.
  • Integration correctness: Validate that KvCacheConnectorConfig properly wires components into the LLM flow and that environment variables are correctly set for cache location.

Pre-merge checks and finishing touches

❌ Failed checks (3 warnings)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
Title check ⚠️ Warning The PR title '[TRTLLM-9159][doc] Add KV Connector docs' indicates documentation additions, but the raw summary shows the changeset actually implements new KV cache connector components with persistent disk-backed caching logic and introduces two new classes, not primarily documentation. Update the title to accurately reflect the main change: something like '[TRTLLM-9159] Add persistent KV cache connector implementation with disk-backed caching' to better represent the substantial code changes rather than framing it as documentation.
Description check ⚠️ Warning The pull request description is incomplete and missing all required content sections including title, description, and test coverage details. Please fill in the PR title following the template format [TICKET][type] Summary, provide a clear description of changes and motivation, and list relevant test coverage details.
✨ 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: 1

🧹 Nitpick comments (5)
examples/llm-api/llm_kv_cache_connector.py (5)

107-151: Add class and method docstrings.

The class and its methods lack docstrings explaining their purpose, parameters, and return values. Since this is an example that developers may reference, adding Google-style docstrings would improve usability.

Example for the class:

class PersistentKvCacheConnectorWorker(KvCacheConnectorWorker):
    """Worker component that handles disk-backed KV cache operations.
    
    Loads cached blocks from disk into GPU memory and saves newly computed
    blocks to disk as .pt files.
    
    Args:
        llm_args: TorchLlmArgs configuration for the LLM.
    """

As per coding guidelines


121-121: Consider using weights_only=True for safer deserialization.

torch.load uses pickle, which can execute arbitrary code. For safer deserialization, consider adding weights_only=True (available in PyTorch 1.13+) to prevent code execution during load.

-            cpu_tensor = torch.load(path, map_location="cpu")
+            cpu_tensor = torch.load(path, map_location="cpu", weights_only=True)

154-213: Add class and method docstrings.

The scheduler class and its methods lack docstrings. As a reference implementation, adding documentation would help developers understand the expected behavior and implementation patterns.

Example:

class PersistentKvCacheConnectorLeader(KvCacheConnectorScheduler):
    """Scheduler component that manages KV cache block identification and scheduling.
    
    Hashes token sequences to create unique identifiers, checks for cached blocks
    on disk, and schedules load/save operations.
    
    Args:
        llm_args: TorchLlmArgs configuration for the LLM.
    """

As per coding guidelines


227-228: Clarify the parameter to get_tokens(0).

The meaning of the 0 parameter passed to get_tokens(0) is unclear. Consider adding a comment explaining what this parameter represents (e.g., beam index, rank, etc.) to improve code readability.

-        remaining_tokens = request.get_tokens(0)[computed_blocks *
-                                                 self.block_size:]
+        # Get tokens for the first beam/sequence (index 0)
+        remaining_tokens = request.get_tokens(0)[computed_blocks *
+                                                 self.block_size:]

272-272: Use Path for more robust module name extraction.

The string slicing approach for extracting the module name is fragile and assumes specific path separators. Consider using Path for more robust parsing.

-    this_module = __file__[__file__.rfind("/") + 1:__file__.rfind(".py")]
+    this_module = Path(__file__).stem
📜 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 7ff0b13 and e482a71.

📒 Files selected for processing (1)
  • examples/llm-api/llm_kv_cache_connector.py (5 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
**/*.{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:

  • examples/llm-api/llm_kv_cache_connector.py
**/*.py

📄 CodeRabbit inference engine (CODING_GUIDELINES.md)

**/*.py: Python code must target Python 3.8+.
Indent Python code with 4 spaces; do not use tabs.
Maintain module namespace when importing; prefer 'from package.subpackage import foo' then 'foo.SomeClass()' instead of importing the class directly.
Python filenames should be snake_case (e.g., some_file.py).
Python classes use PascalCase names.
Functions and methods use snake_case names.
Local variables use snake_case; prefix 'k' for variables that start with a number (e.g., k_99th_percentile).
Global variables use upper SNAKE_CASE prefixed with 'G' (e.g., G_MY_GLOBAL).
Constants use upper SNAKE_CASE (e.g., MY_CONSTANT).
Avoid shadowing variables from an outer scope.
Initialize all externally visible members of a class in the constructor.
Prefer docstrings for interfaces that may be used outside a file; comments for in-function or file-local interfaces.
Use Google-style docstrings for classes and functions (Sphinx-parsable).
Document attributes and variables inline so they render under the class/function docstring.
Avoid reflection when a simpler, explicit approach suffices (e.g., avoid dict(**locals()) patterns).
In try/except, catch the most specific exceptions possible.
For duck-typing try/except, keep the try body minimal and use else for the main logic.

Files:

  • examples/llm-api/llm_kv_cache_connector.py
**/*.{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:

  • examples/llm-api/llm_kv_cache_connector.py
🧠 Learnings (4)
📓 Common learnings
Learnt from: eopXD
Repo: NVIDIA/TensorRT-LLM PR: 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.
Learnt from: eopXD
Repo: NVIDIA/TensorRT-LLM PR: 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.
Learnt from: eopXD
Repo: NVIDIA/TensorRT-LLM PR: 6767
File: cpp/tensorrt_llm/batch_manager/kvCacheManager.cpp:0-0
Timestamp: 2025-08-15T06:46:53.813Z
Learning: In the TensorRT-LLM KV cache manager, SWA (Sliding Window Attention) combined with beam search is currently in a broken/non-functional state and is planned for future rework. During preparatory refactoring phases, code related to SWA+beam search may intentionally remain in a non-working state until the broader rework is completed.
Learnt from: thorjohnsen
Repo: NVIDIA/TensorRT-LLM PR: 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.
Learnt from: nv-lschneider
Repo: NVIDIA/TensorRT-LLM PR: 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.
Learnt from: amitz-nv
Repo: NVIDIA/TensorRT-LLM PR: 5616
File: tensorrt_llm/executor/worker.py:375-384
Timestamp: 2025-07-17T09:01:27.402Z
Learning: In tensorrt_llm/executor/worker.py, the LoRA adapter cache optimization logic that checks `is_adapter_in_cpu_cache()` and conditionally passes None for weights/config has a known race condition issue that cannot be solved with simple error handling or verification checks. This is a known limitation that requires a more comprehensive solution.
📚 Learning: 2025-08-14T21:04:50.248Z
Learnt from: thorjohnsen
Repo: NVIDIA/TensorRT-LLM PR: 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:

  • examples/llm-api/llm_kv_cache_connector.py
📚 Learning: 2025-08-15T06:46:54.897Z
Learnt from: eopXD
Repo: NVIDIA/TensorRT-LLM PR: 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:

  • examples/llm-api/llm_kv_cache_connector.py
📚 Learning: 2025-08-21T09:41:49.347Z
Learnt from: eopXD
Repo: NVIDIA/TensorRT-LLM PR: 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:

  • examples/llm-api/llm_kv_cache_connector.py
🧬 Code graph analysis (1)
examples/llm-api/llm_kv_cache_connector.py (1)
tensorrt_llm/llmapi/llm.py (2)
  • LLM (1052-1068)
  • generate (241-319)
⏰ 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

Copy link
Collaborator

@QiJune QiJune left a comment

Choose a reason for hiding this comment

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

LGTM

@QiJune QiJune added the Doc <NV>TRTLLM's textual/illustrative materials: API refs, guides, tutorials. Improvement & clarity. label Nov 11, 2025
@QiJune QiJune changed the title [TRTLLM-9159][Doc] Add KV Connector docs [TRTLLM-9159][doc] Add KV Connector docs Nov 11, 2025
@QiJune
Copy link
Collaborator

QiJune commented Nov 11, 2025

/bot skip --comment "doc changes"

@tensorrt-cicd
Copy link
Collaborator

PR_Github #24070 [ skip ] triggered by Bot. Commit: e482a71

@tensorrt-cicd
Copy link
Collaborator

PR_Github #24070 [ skip ] completed with state SUCCESS. Commit: e482a71
Skipping testing for commit e482a71

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Doc <NV>TRTLLM's textual/illustrative materials: API refs, guides, tutorials. Improvement & clarity.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants