KEMBAR78
[None][feat] add an example of KV cache host offloading by QiJune · Pull Request #7767 · NVIDIA/TensorRT-LLM · GitHub
Skip to content

Conversation

@QiJune
Copy link
Collaborator

@QiJune QiJune commented Sep 16, 2025

Summary by CodeRabbit

  • New Features

    • Added an example demonstrating KV cache host offloading, illustrating eviction vs. reuse under constrained GPU cache. Includes a command-line toggle, step-by-step runs, and log cues to observe cache hits.
  • Documentation

    • Updated KV cache offloading documentation with links to the new example and clearer guidance on enabling host offloading and interpreting behavior.

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

  • 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: junq <22017000+QiJune@users.noreply.github.com>
Signed-off-by: junq <22017000+QiJune@users.noreply.github.com>
Signed-off-by: junq <22017000+QiJune@users.noreply.github.com>
Signed-off-by: junq <22017000+QiJune@users.noreply.github.com>
Signed-off-by: junq <22017000+QiJune@users.noreply.github.com>
Signed-off-by: junq <22017000+QiJune@users.noreply.github.com>
Signed-off-by: junq <22017000+QiJune@users.noreply.github.com>
Signed-off-by: junq <22017000+QiJune@users.noreply.github.com>
Signed-off-by: junq <22017000+QiJune@users.noreply.github.com>
Signed-off-by: junq <22017000+QiJune@users.noreply.github.com>
Signed-off-by: junq <22017000+QiJune@users.noreply.github.com>
Signed-off-by: junq <22017000+QiJune@users.noreply.github.com>
Signed-off-by: junq <22017000+QiJune@users.noreply.github.com>
Signed-off-by: junq <22017000+QiJune@users.noreply.github.com>
Signed-off-by: junq <22017000+QiJune@users.noreply.github.com>
Signed-off-by: junq <22017000+QiJune@users.noreply.github.com>
Signed-off-by: junq <22017000+QiJune@users.noreply.github.com>
Signed-off-by: junq <22017000+QiJune@users.noreply.github.com>
Signed-off-by: junq <22017000+QiJune@users.noreply.github.com>
Signed-off-by: junq <22017000+QiJune@users.noreply.github.com>
Signed-off-by: junq <22017000+QiJune@users.noreply.github.com>
Signed-off-by: junq <22017000+QiJune@users.noreply.github.com>
Signed-off-by: junq <22017000+QiJune@users.noreply.github.com>
@QiJune QiJune requested a review from a team as a code owner September 16, 2025 11:17
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Sep 16, 2025

📝 Walkthrough

Walkthrough

Adds a new example script demonstrating KV cache host offloading behavior and updates documentation to link to it. No production code or public API changes.

Changes

Cohort / File(s) Summary
Docs: KV cache offloading references
docs/source/features/kvcache.md
Adds two lines linking to the new example (llm_kv_cache_offloading.py) in the “Enable Offloading to Host Memory” section.
Example: KV cache offloading demo
examples/llm-api/llm_kv_cache_offloading.py
New script showing KV cache host offloading using KvCacheConfig, a small GPU cache (256 tokens), page size 16, optional 1 GiB host cache toggled via --enable_offloading, and a two-prompt A/B/A/B generation sequence to illustrate eviction vs. reuse. Adds main(args) and CLI parsing.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor User
  participant CLI as CLI/Script
  participant Builder as LLM Builder
  participant KV as KV Cache Manager
  participant Gen as Generator

  User->>CLI: Run llm_kv_cache_offloading.py [--enable_offloading]
  CLI->>Builder: Build LLM with KvCacheConfig<br/>GPU cache=256 tokens, page_size=16,<br/>host cache=1 GiB if enabled else 0
  Builder->>KV: Initialize caches (GPU[, Host])

  rect rgb(235, 245, 255)
    note right of CLI: First Round
    CLI->>Gen: generate(Prompt A, max_tokens=max_seq_len)
    Gen->>KV: Allocate/use pages
    KV-->>Gen: Cache state updated
    CLI->>Gen: generate(Prompt B)
    Gen->>KV: Allocate/evict/reuse pages
  end

  rect rgb(240, 255, 240)
    note right of CLI: Second Round
    CLI->>Gen: generate(Prompt A)
    alt Offloading enabled
      KV-->>Gen: Reuse via host-backed pages (hits)
    else Offloading disabled
      KV-->>Gen: Miss → reallocate (evicted)
    end
    CLI->>Gen: generate(Prompt B)
    Gen->>KV: Similar reuse/evict behavior
  end

  CLI-->>User: Print prompts, outputs, and cache reuse cues
  CLI->>Builder: shutdown()
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Pre-merge checks and finishing touches

❌ Failed checks (2 warnings)
Check name Status Explanation Resolution
Description Check ⚠️ Warning The PR description is essentially the untouched template and lacks the required content: the Description and Test Coverage sections are empty and do not summarize the actual changes (which add examples/llm-api/llm_kv_cache_offloading.py and small docs edits in docs/source/features/kvcache.md), nor do they state how the change should be validated or what tests (if any) accompany it. Because the template placeholders were not filled, the PR does not provide reviewers with the necessary context to evaluate behavior, testing, or release impact. Please replace the template placeholders with a short Description that lists the files changed and the purpose (example demonstrating KV cache host offloading and two doc link additions), a Test Coverage section describing how to run and verify the example (expected logs/verification cues and any manual steps), and update the PR Checklist items (tests added or justification if none, CODEOWNERS if ownership changed). Including these details will make the review actionable and satisfy the repository's PR template requirements.
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.
✅ Passed checks (1 passed)
Check name Status Explanation
Title Check ✅ Passed The title "[None][feat] add an example of KV cache host offloading" is concise, follows the repo template (ticket/type), and accurately describes the primary change — adding an example demonstrating KV cache host offloading (examples/llm-api/llm_kv_cache_offloading.py and related docs updates). It is specific and clear enough for a reviewer scanning PR history to understand the main intent.
✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Tip

👮 Agentic pre-merge checks are now available in preview!

Pro plan users can now enable pre-merge checks in their settings to enforce checklists before merging PRs.

  • Built-in checks – Quickly apply ready-made checks to enforce title conventions, require pull request descriptions that follow templates, validate linked issues for compliance, and more.
  • Custom agentic checks – Define your own rules using CodeRabbit’s advanced agentic capabilities to enforce organization-specific policies and workflows. For example, you can instruct CodeRabbit’s agent to verify that API documentation is updated whenever API schema files are modified in a PR. Note: Upto 5 custom checks are currently allowed during the preview period. Pricing for this feature will be announced in a few weeks.

Please see the documentation for more information.

Example:

reviews:
  pre_merge_checks:
    custom_checks:
      - name: "Undocumented Breaking Changes"
        mode: "warning"
        instructions: |
          Pass/fail criteria: All breaking changes to public APIs, CLI flags, environment variables, configuration keys, database schemas, or HTTP/GraphQL endpoints must be documented in the "Breaking Change" section of the PR description and in CHANGELOG.md. Exclude purely internal or private changes (e.g., code not exported from package entry points or explicitly marked as internal).

Please share your feedback with us on this Discord post.


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

❤️ Share

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

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (6)
examples/llm-api/llm_kv_cache_offloading.py (6)

49-51: Follow import guideline: keep module namespaces.

Avoid importing classes directly; import modules/submodules and reference via namespace.

Apply:

-import argparse
-
-from tensorrt_llm import LLM, SamplingParams
-from tensorrt_llm.llmapi import KvCacheConfig
+import argparse
+import tensorrt_llm as trtllm
+from tensorrt_llm import llmapi

And update usages below:

-    sampling_params = SamplingParams(max_tokens=max_seq_len)
+    sampling_params = trtllm.SamplingParams(max_tokens=max_seq_len)
@@
-    llm = LLM(
+    llm = trtllm.LLM(
@@
-        kv_cache_config=KvCacheConfig(
+        kv_cache_config=llmapi.KvCacheConfig(

53-60: Add a concise docstring and type hints to main().

Improves clarity and aligns with docstring guidelines.

-def main(args):
+def main(args: argparse.Namespace) -> None:
+    """Run the KV cache offloading demo.
+    Args:
+        args: Parsed CLI arguments (see --enable_offloading, --model).
+    """

66-75: Name alignment: “page size” vs tokens_per_block.

Use a name aligned with the API to avoid confusion.

-    kv_cache_page_size = 16
+    kv_cache_tokens_per_block = 16
@@
-            tokens_per_block=kv_cache_page_size,
+            tokens_per_block=kv_cache_tokens_per_block,

79-87: Make the model configurable (8B default is heavy).

Allow overriding via CLI; keeps the example runnable on modest GPUs.

-    llm = trtllm.LLM(
-        model="Qwen/Qwen3-8B",
+    llm = trtllm.LLM(
+        model=args.model,
         max_batch_size=max_batch_size,
         max_seq_len=max_seq_len,
         kv_cache_config=llmapi.KvCacheConfig(

And extend the CLI:

     parser = argparse.ArgumentParser(
@@
     parser.add_argument('--enable_offloading',
                         action='store_true',
                         help='Enable host RAM for KV cache offloading.')
+    parser.add_argument(
+        '--model',
+        default='Qwen/Qwen3-8B',
+        help='HF model identifier to load (use a smaller one for quick runs).')

91-117: Minor: consider clearer logs for reuse/eviction cues.

Add brief hints to correlate with DEBUG logs.

-    print("--- First Round ---")
+    print("--- First Round --- (expect A cached on GPU; B causes A to evict/offload)")
@@
-    print("\n--- Second Round ---")
+    print("\n--- Second Round --- (A then B to observe reuse from host if offloading)")

76-77: SamplingParams.max_tokens is "new tokens" — don't set it to max_seq_len

SamplingParams.max_tokens is the number of tokens to generate; setting it to max_seq_len can exceed the engine limit once prompt tokens are included. File: examples/llm-api/llm_kv_cache_offloading.py:76-77.

  • Use a conservative or deduced value instead (e.g. SamplingParams(max_tokens=min(128, max_seq_len // 2)) or compute available_new = max_seq_len - prompt_len and use that).
📜 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 8226ef2 and 9594bf7.

📒 Files selected for processing (2)
  • docs/source/features/kvcache.md (1 hunks)
  • examples/llm-api/llm_kv_cache_offloading.py (1 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_offloading.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_offloading.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_offloading.py
⏰ 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

@thorjohnsen
Copy link
Collaborator

I get one error message when I run this example. It does not appear related to your example code. The error is

Exception ignored in atexit callback: <function move_cutlass_compiled_cache at 0x7f2bcbf496c0>
Traceback (most recent call last):
  File "/usr/local/lib/python3.12/dist-packages/torch/_inductor/codegen/cuda/cutlass_utils.py", line 39, in move_cutlass_compiled_cache
    if not os.path.exists(cutlass.CACHE_FILE):
                          ^^^^^^^^^^^^^^^^^^

Copy link
Collaborator

@thorjohnsen thorjohnsen left a comment

Choose a reason for hiding this comment

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

LGTM. My only niggle is that it prints an error message. Example runs fine, so error does not appear to be fatal and I don't think it is related to your code.

@QiJune
Copy link
Collaborator Author

QiJune commented Sep 17, 2025

/bot skip --comment "example and doc change"

@tensorrt-cicd
Copy link
Collaborator

PR_Github #18852 [ skip ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #18852 [ skip ] completed with state SUCCESS
Skipping testing for commit 9594bf7

@QiJune QiJune merged commit 3924832 into NVIDIA:main Sep 17, 2025
8 of 9 checks passed
Wong4j pushed a commit to Wong4j/TensorRT-LLM that referenced this pull request Sep 20, 2025
Signed-off-by: junq <22017000+QiJune@users.noreply.github.com>
MrGeva pushed a commit to nv-auto-deploy/TensorRT-LLM that referenced this pull request Sep 21, 2025
Signed-off-by: junq <22017000+QiJune@users.noreply.github.com>
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.

4 participants