Skip to content

Conversation

@FrankD412
Copy link
Collaborator

@FrankD412 FrankD412 commented Aug 20, 2025

Summary by CodeRabbit

  • Bug Fixes

    • Corrects KV-cache memory percentage reporting in world info (now shows configured fraction ×100 as a percentage string).
    • Ensures consistent KV-cache data type handling so all backends, including PyTorch, use the same dtype.
  • Refactor

    • Centralizes KV-cache configuration parsing and validation into a single path to reduce backend divergence.
    • Consolidates dtype and memory extraction for reuse across backends.
  • Chores

    • Adds validation and error handling for invalid KV-cache configuration inputs.
    • No public API changes.

There was a minor bug in the reporting of trtllm-bench where if the KV cache percentage was set in the LLM API extra options, the percentage would not be reflected in the final report out. This PR fixes the issue by directly reporting from the KV cache configuration.

Description

Test Coverage

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.

Details

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.

@FrankD412 FrankD412 self-assigned this Aug 20, 2025
@FrankD412 FrankD412 requested a review from a team as a code owner August 20, 2025 22:25
@FrankD412 FrankD412 requested a review from lucaslie August 20, 2025 22:25
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 20, 2025

📝 Walkthrough

Walkthrough

Centralizes KV-cache configuration handling in tensorrt_llm/bench/dataclasses/reporting.py:get_statistics_dict by reading kv_cache_config from kwargs (accepts KvCacheConfig or dict), deriving kv_cache_dtype and kv_cache_mem_percent (defaulting when absent), converting mem fraction to a percentage string (e.g., "12.34%"), using kv_cache_dtype for PyTorch validation, and raising on invalid types. No public API changes.

Changes

Cohort / File(s) Summary
Reporting KV-cache centralization
tensorrt_llm/bench/dataclasses/reporting.py
Read kv_cache_config from kwargs (accept KvCacheConfig instance or dict, default when missing); raise ValueError for invalid types. Extract kv_cache_dtype and kv_cache_mem_percent; convert mem fraction to a percentage string (e.g., "12.34%") or "None" if absent. PyTorch path now calls validate_and_set_kv_cache_quant using the centralized kv_cache_dtype. TRT/backend behavior remains functionally unchanged but uses the same centralized value. World info now exposes kv_cache_percentage as the percentage string and printing uses that string.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant Caller as Caller
  participant Reporting as reporting.get_statistics_dict
  participant Cfg as kv_cache_config (kwargs)
  participant PT as PyTorch backend
  participant TRT as TRT/backend
  participant Val as validate_and_set_kv_cache_quant
  participant World as world_info

  Caller->>Reporting: get_statistics_dict(kwargs)
  Reporting->>Cfg: read kv_cache_config from kwargs
  alt kv_cache_config valid or absent
    Reporting->>Reporting: derive kv_cache_dtype and kv_cache_mem_percent
    Reporting->>Reporting: convert mem fraction -> percentage string (e.g., "12.34%") or "None"
  else invalid type
    Reporting-->>Caller: raise ValueError
  end

  par Backends
    Reporting->>PT: call validate_and_set_kv_cache_quant(kv_cache_dtype)
    PT->>Val: validate_and_set_kv_cache_quant(kv_cache_dtype)
    Note right of PT: PyTorch uses centralized kv_cache_dtype
  and
    Reporting->>TRT: use pretrained-config sourced kv_cache_dtype (behavior preserved)
  end

  Reporting->>World: set kv_cache_percentage = percentage string
  Reporting-->>Caller: return statistics dict
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested reviewers

  • Superjomn

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • 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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai or @coderabbitai title anywhere in the PR title to generate the title automatically.

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@FrankD412
Copy link
Collaborator Author

/bot run

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

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between e5e4170 and 569356c.

📒 Files selected for processing (1)
  • tensorrt_llm/bench/dataclasses/reporting.py (2 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.py

📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md)

**/*.py: Python code must target Python 3.8+
Python indentation: 4 spaces, no tabs
Maintain module namespace in imports (from package.subpackage import foo; then use foo.SomeClass())
Python file names use snake_case
Python class names use PascalCase
Python functions/methods and local variables use snake_case; variables starting with a number get k_ prefix (e.g., k_99th_percentile)
Global variables use G_ prefixed UPPER_SNAKE_CASE (e.g., G_MY_GLOBAL)
Constants use UPPER_SNAKE_CASE in Python
Avoid shadowing variables from outer scopes in Python
Initialize all externally visible members of a Python class in init
Prefer docstrings for interfaces used outside a file; comments for local code
Use Google-style docstrings for classes and functions (Sphinx-parsable)
Document attributes/variables inline with short docstrings
Avoid reflection when simple alternatives exist (e.g., prefer explicit parameters over dict(**locals()))
In try/except, catch the narrowest exceptions possible
For duck-typing with try/except, keep try body minimal and put logic in else

Files:

  • tensorrt_llm/bench/dataclasses/reporting.py
**/*.{cpp,cxx,cc,cu,h,hpp,hxx,hh,cuh,py}

📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md)

Prepend NVIDIA copyright header (current year) to all source files

Files:

  • tensorrt_llm/bench/dataclasses/reporting.py
🔇 Additional comments (1)
tensorrt_llm/bench/dataclasses/reporting.py (1)

343-343: LGTM: percentage now reflects the configured fraction

Using kv_cache_mem_percent * 100.0 fixes the earlier mismatch and aligns printed/reporting percentage with the LLM API’s free_gpu_memory_fraction.

@tensorrt-cicd
Copy link
Collaborator

PR_Github #15954 [ run ] triggered by Bot

@FrankD412
Copy link
Collaborator Author

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #15955 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #15954 [ run ] completed with state ABORTED

@tensorrt-cicd
Copy link
Collaborator

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

@FrankD412 FrankD412 force-pushed the fdinatale/trtllm-bench/kv_cache_reporting branch from 3edeb3a to eb3dfb0 Compare August 21, 2025 02:22
@FrankD412
Copy link
Collaborator Author

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #15972 [ run ] triggered by Bot

@FrankD412
Copy link
Collaborator Author

@Superjomn -- out of curiosity, I encountered the case where the extra_llm_api_options forced the free_gpu_mem_fraction to None. Why doesn't it have an actual default in the model itself?

@tensorrt-cicd
Copy link
Collaborator

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

@FrankD412 FrankD412 force-pushed the fdinatale/trtllm-bench/kv_cache_reporting branch from b48e16b to a5b8b9f Compare August 21, 2025 04:52
@FrankD412
Copy link
Collaborator Author

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #15991 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

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

@FrankD412
Copy link
Collaborator Author

/bot run

1 similar comment
@FrankD412
Copy link
Collaborator Author

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #16074 [ run ] triggered by Bot

@FrankD412 FrankD412 force-pushed the fdinatale/trtllm-bench/kv_cache_reporting branch from e53eba1 to 6c10ba2 Compare August 21, 2025 19:25
@FrankD412
Copy link
Collaborator Author

/bot run

@tensorrt-cicd
Copy link
Collaborator

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

@tensorrt-cicd
Copy link
Collaborator

PR_Github #16078 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

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

@FrankD412
Copy link
Collaborator Author

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #16084 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

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

Signed-off-by: Frank Di Natale <[email protected]>
Signed-off-by: Frank Di Natale <[email protected]>
Signed-off-by: Frank Di Natale <[email protected]>
Signed-off-by: Frank Di Natale <[email protected]>
Signed-off-by: Frank Di Natale <[email protected]>
Signed-off-by: Frank Di Natale <[email protected]>
@FrankD412 FrankD412 force-pushed the fdinatale/trtllm-bench/kv_cache_reporting branch from 79404b0 to 46449e2 Compare August 22, 2025 06:57
@FrankD412
Copy link
Collaborator Author

/bot run

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: 0

♻️ Duplicate comments (1)
tensorrt_llm/bench/dataclasses/reporting.py (1)

276-291: Prevent crash when kv_cache_config is None or dict missing free_gpu_memory_fraction; coerce and clamp fraction to [0,1]

As written:

  • kv_cache_config=None raises ValueError (Line 286).
  • dict inputs without "free_gpu_memory_fraction" propagate None and cause TypeError at Line 289 when multiplied.
  • Non-numeric strings will also fail at Line 289.

Fix by treating None as “not provided” (use KvCacheConfig() defaults), defaulting missing dict fields, coercing to float when present, and clamping to [0,1]. Also generate the display string only after normalization.

Apply this diff:

-        # Retrieve KV cache information.
-        kv_cache_config = self.kwargs.get("kv_cache_config", KvCacheConfig())
-        if isinstance(kv_cache_config, KvCacheConfig):
-            kv_cache_dtype = kv_cache_config.dtype
-            kv_cache_mem_percent = kv_cache_config.free_gpu_memory_fraction
-        elif isinstance(kv_cache_config, dict):
-            kv_cache_dtype = kv_cache_config.get("dtype", "auto")
-            kv_cache_mem_percent = kv_cache_config.get(
-                "free_gpu_memory_fraction")
-        else:
-            raise ValueError(
-                f"Invalid kv_cache_config type: {type(kv_cache_config)}.")
-
-        kv_cache_mem_percent = f"{kv_cache_mem_percent * 100.0:.2f}%" \
-             if kv_cache_mem_percent is not None else "None"
+        # Retrieve KV cache information and normalize.
+        kv_cache_config = self.kwargs.get("kv_cache_config")
+        if kv_cache_config is None:
+            default_cfg = KvCacheConfig()
+            kv_cache_dtype = default_cfg.dtype
+            kv_cache_mem_fraction = default_cfg.free_gpu_memory_fraction
+        elif isinstance(kv_cache_config, KvCacheConfig):
+            kv_cache_dtype = kv_cache_config.dtype
+            kv_cache_mem_fraction = kv_cache_config.free_gpu_memory_fraction
+        elif isinstance(kv_cache_config, dict):
+            default_cfg = KvCacheConfig()
+            kv_cache_dtype = kv_cache_config.get("dtype", default_cfg.dtype)
+            kv_cache_mem_fraction = kv_cache_config.get(
+                "free_gpu_memory_fraction", default_cfg.free_gpu_memory_fraction)
+        else:
+            raise ValueError(
+                f"Invalid kv_cache_config type: {type(kv_cache_config)}.")
+
+        # Build display string; coerce when present, allow unset (None).
+        if kv_cache_mem_fraction is None:
+            kv_cache_mem_percent = "None"
+        else:
+            try:
+                mem_frac = float(kv_cache_mem_fraction)
+            except (TypeError, ValueError) as exc:
+                raise ValueError(
+                    "kv_cache_config.free_gpu_memory_fraction must be a number in [0, 1]."
+                ) from exc
+            if not (0.0 <= mem_frac <= 1.0):
+                self.logger.warning(
+                    f"free_gpu_memory_fraction={mem_frac} is out of [0,1]; clamping.")
+                mem_frac = max(0.0, min(1.0, mem_frac))
+            kv_cache_mem_percent = f"{mem_frac * 100.0:.2f}%"

To validate callers that may pass None or dicts without the fraction (the scenarios that can currently break), run:

#!/bin/bash
# 1) Find kv_cache_config constructions/usages across the repo.
rg -nP --type=py -C3 '\bkv_cache_config\b'

# 2) Spot dict literals likely passed as kv_cache_config and check for missing 'free_gpu_memory_fraction'.
rg -nP --type=py -C2 '(kv_cache_config\s*=\s*\{|\bkv_cache_config\b[^,\)\n]*\{)' | sed -n '1,200p'

# 3) Locate explicit None assignments to kv_cache_config.
rg -nP --type=py -C2 'kv_cache_config\s*=\s*None'

# 4) Audit for callers that set dtype but omit the fraction (common pitfall).
rg -nP --type=py -C2 'kv_cache_config[^=\n]*\{[^}]*dtype[^}]*\}' | rg -nP --invert-match 'free_gpu_memory_fraction'
🧹 Nitpick comments (1)
tensorrt_llm/bench/dataclasses/reporting.py (1)

535-535: Nit: align the printed label with the key name

Consider making the label match the key and concept (“KV Cache Percentage”) for clarity.

-            f"KV Memory Percentage:   {world_info['kv_cache_percentage']}\n"
+            f"KV Cache Percentage:    {world_info['kv_cache_percentage']}\n"
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 63b26f8 and 46449e2.

📒 Files selected for processing (1)
  • tensorrt_llm/bench/dataclasses/reporting.py (3 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.py

📄 CodeRabbit inference engine (CODING_GUIDELINES.md)

**/*.py: Python code must target Python 3.8+
Python indentation: 4 spaces, no tabs
Maintain module namespace in imports (from package.subpackage import foo; then use foo.SomeClass())
Python file names use snake_case
Python class names use PascalCase
Python functions/methods and local variables use snake_case; variables starting with a number get k_ prefix (e.g., k_99th_percentile)
Global variables use G_ prefixed UPPER_SNAKE_CASE (e.g., G_MY_GLOBAL)
Constants use UPPER_SNAKE_CASE in Python
Avoid shadowing variables from outer scopes in Python
Initialize all externally visible members of a Python class in init
Prefer docstrings for interfaces used outside a file; comments for local code
Use Google-style docstrings for classes and functions (Sphinx-parsable)
Document attributes/variables inline with short docstrings
Avoid reflection when simple alternatives exist (e.g., prefer explicit parameters over dict(**locals()))
In try/except, catch the narrowest exceptions possible
For duck-typing with try/except, keep try body minimal and put logic in else

Files:

  • tensorrt_llm/bench/dataclasses/reporting.py
**/*.{cpp,cxx,cc,cu,h,hpp,hxx,hh,cuh,py}

📄 CodeRabbit inference engine (CODING_GUIDELINES.md)

Prepend NVIDIA copyright header (current year) to all source files

Files:

  • tensorrt_llm/bench/dataclasses/reporting.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
🔇 Additional comments (2)
tensorrt_llm/bench/dataclasses/reporting.py (2)

289-291: Follow-up on percent formatting

Once the normalization above is applied, this formatting is safe and consistent. No additional change needed here.


346-346: LGTM: world_info now reflects configured KV cache percent

This correctly wires the reported percentage to the normalized KV cache configuration rather than the previous settings path, aligning with the PR objective.

@tensorrt-cicd
Copy link
Collaborator

PR_Github #16144 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #16144 [ run ] completed with state SUCCESS
/LLM/main/L0_MergeRequest_PR pipeline #12143 completed with status: 'SUCCESS'
Pipeline passed with automatic retried tests. Check the rerun report for details.

@FrankD412 FrankD412 merged commit 81fd468 into NVIDIA:main Aug 22, 2025
5 checks passed
FrankD412 added a commit to FrankD412/TensorRT-LLM that referenced this pull request Aug 22, 2025
FrankD412 added a commit to FrankD412/TensorRT-LLM that referenced this pull request Aug 26, 2025
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