Skip to content

Conversation

@nzmora-nvidia
Copy link
Collaborator

@nzmora-nvidia nzmora-nvidia commented Oct 20, 2025

  1. Log model size
  2. Fix the logging of memory used during forward, when reconfiguring the kv-cache
  3. Catch cache-resize OOM to give users a gentler experience

Summary by CodeRabbit

  • Chores
    • Enhanced memory diagnostic logging during weight loading and KV-cache operations.
    • Added peak memory usage tracking during forward passes.
    • Improved error handling and logging for out-of-memory situations with more verbose diagnostics.
    • Standardized memory information retrieval and calculation across memory tracking utilities.

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.

@nzmora-nvidia nzmora-nvidia requested a review from a team as a code owner October 20, 2025 13:09
@nzmora-nvidia nzmora-nvidia requested review from h-guo18 and removed request for nvchenghaoz October 20, 2025 13:10
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Oct 20, 2025

📝 Walkthrough

Walkthrough

The changes introduce a utility function get_mem_info_in_mb() to standardize CUDA memory querying in the auto-deploy module. This function is then integrated into factory.py for memory diagnostics logging and into kvcache.py for enhanced peak/extra memory tracking with error handling during forward passes.

Changes

Cohort / File(s) Summary
New memory tracking utility
tensorrt_llm/_torch/auto_deploy/utils/cuda_mem_tracker.py
Added public function get_mem_info_in_mb() that clears CUDA cache and returns free/total memory in MB. Added Tuple type import for return type annotation.
Memory diagnostics logging
tensorrt_llm/_torch/auto_deploy/models/factory.py
Imported get_mem_info_in_mb. Added logging of free memory before and after weight loading, and computed total parameter size in GB within load_or_random_init().
Enhanced memory tracking with error handling
tensorrt_llm/_torch/auto_deploy/transform/library/kvcache.py
Replaced manual torch.cuda.mem_get_info() calls with get_mem_info_in_mb(). Added peak/extra memory tracking during forward pass (memory_allocated before, peak_memory_allocated during). Added OutOfMemoryError handling with logging during forward pass. Updated memory calculations from multi-step divisions to single 1024**2 division. Added verbose memory diagnostics including "Peak memory usage during forward pass" and "Extra memory used during forward pass" logs. Fixed typo: "Peak memory uasge" → "Peak memory usage".

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

The changes span three files with consistent patterns but introduce meaningful additions: the new utility is straightforward, but kvcache.py requires careful review due to error handling logic, multiple new memory metrics, and changes to memory calculation flows. The homogeneous nature of memory-tracking additions is offset by the density of logic changes in the cache-resizing phase.

Pre-merge checks and finishing touches

❌ Failed checks (2 warnings)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 60.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
Description Check ⚠️ Warning The pull request description is largely incomplete and does not follow the required template structure. While the author provided three high-level bullet points summarizing the changes (log model size, fix memory logging, and catch cache-resize OOM), the required template sections are empty: the Description section contains only an HTML comment placeholder with no actual explanation of the issue or solution, and the Test Coverage section is completely blank with no list of relevant tests. Although the PR Checklist is marked as reviewed, the actual substantive content required by the template—specifically the detailed description explaining what and why the changes are made, and the test coverage details—is missing entirely. The author should fill in the Description section with a clear explanation of the problem being solved and the approach taken, including context on why these memory logging changes are necessary. The Test Coverage section must include a list of specific tests that validate the changes, particularly tests covering the new memory tracking utility, the logging enhancements in the factory module, and the OOM error handling in the kv-cache resizing logic. Additionally, a properly formatted PR title following the specified format should be provided.
✅ Passed checks (1 passed)
Check name Status Explanation
Title Check ✅ Passed The pull request title "[None][feat] AutoDeploy: refactor memory usage logging" clearly and accurately summarizes the main objective of the changeset. It follows the required template format with [None] for the ticket identifier, [feat] to indicate the type of change, and provides a specific, descriptive summary of the refactoring work. The title is concise, avoids vague terminology, and effectively communicates that the changes involve improvements to memory usage logging in the AutoDeploy module. This directly aligns with the three main objectives: logging model size, fixing memory usage logging during kv-cache reconfiguration, and adding OutOfMemoryError handling.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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

❤️ Share

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

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

Caution

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

⚠️ Outside diff range comments (3)
tensorrt_llm/_torch/auto_deploy/models/factory.py (1)

1-1: Missing NVIDIA Apache-2.0 header (2025).

Add the standard header at file top.

+# Copyright (c) 2025, NVIDIA CORPORATION & AFFILIATES.
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#     http://www.apache.org/licenses/LICENSE-2.0
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
 """The model factory interface used by auto-deploy to build custom models."""

As per coding guidelines.

tensorrt_llm/_torch/auto_deploy/transform/library/kvcache.py (2)

1-1: Missing NVIDIA Apache-2.0 header (2025).

Add required header.

+# Copyright (c) 2025, NVIDIA CORPORATION & AFFILIATES.
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#     http://www.apache.org/licenses/LICENSE-2.0
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
 """Graph transformation to automatically add kv cache into fused MHA op."""

As per coding guidelines.


297-305: Guard against divide-by-zero when deriving pages; keep units consistent.

If the cache is empty or current_num_pages == 0, this can crash. Also compute bytes/page via float to avoid premature truncation.

-        new_cache_size = free_mem_post * 1024 * 1024 * free_mem_ratio + current_cache_size
-        new_num_pages = int(new_cache_size // (current_cache_size // current_num_pages))
+        new_cache_size = (free_mem_post * 1024 * 1024 * free_mem_ratio) + current_cache_size
+        # Derive bytes per page safely
+        if current_num_pages <= 0:
+            self._log_info("Current KV cache has zero pages; skipping resize.")
+            return mod, TransformInfo(skipped=True, num_matches=0, is_clean=True, has_valid_shapes=True)
+        bytes_per_page = current_cache_size / current_num_pages
+        if bytes_per_page <= 0:
+            self._log_info("KV cache reports 0 bytes/page; skipping resize.")
+            return mod, TransformInfo(skipped=True, num_matches=0, is_clean=True, has_valid_shapes=True)
+        new_num_pages = max(current_num_pages, int(new_cache_size / bytes_per_page))
🧹 Nitpick comments (3)
tensorrt_llm/_torch/auto_deploy/utils/cuda_mem_tracker.py (1)

30-36: Add CUDA-availability guard and docstring; clarify MiB units.

Make the function robust on non‑CUDA hosts and document units (1024‑based = MiB).

-def get_mem_info_in_mb(empty_cache: bool = True) -> Tuple[int, int]:
-    if empty_cache:
-        # Clear the memory cache to get the exact free memory
-        torch.cuda.empty_cache()
-    free_mem, total_mem = torch.cuda.mem_get_info()
-    MB = 1024**2
-    return free_mem // MB, total_mem // MB
+def get_mem_info_in_mb(empty_cache: bool = True) -> Tuple[int, int]:
+    """Return (free_mib, total_mib) for the current CUDA device.
+
+    Args:
+        empty_cache: If True, call torch.cuda.empty_cache() before measuring.
+    Raises:
+        RuntimeError: If CUDA is unavailable.
+    """
+    if not torch.cuda.is_available():
+        raise RuntimeError("CUDA is not available; cannot query CUDA memory.")
+    if empty_cache:
+        torch.cuda.empty_cache()
+    free_mem, total_mem = torch.cuda.mem_get_info()
+    MIB = 1024**2
+    return free_mem // MIB, total_mem // MIB

Based on coding guidelines.

tensorrt_llm/_torch/auto_deploy/models/factory.py (2)

281-283: Unit label nit: use GiB for 1024-based units.

You divide by 1024**3, so log GiB for clarity/consistency with other logs.

-        total_size_GB = params_size / (1024**3)
-        ad_logger.info(f"Estimated parameters memory: {total_size_GB:.2f} GB")
+        total_size_gib = params_size / (1024**3)
+        ad_logger.info(f"Estimated parameters memory: {total_size_gib:.2f} GiB")

277-279: Consider measuring without emptying cache to reflect steady-state free memory.

Default emptying the cache before every measurement may inflate “free memory” and hide allocator fragmentation. If the goal is a diagnostic snapshot, consider get_mem_info_in_mb(empty_cache=False) here.

-        free_mem_pre, _ = get_mem_info_in_mb()
+        free_mem_pre, _ = get_mem_info_in_mb(empty_cache=False)
...
-        free_mem_post, _ = get_mem_info_in_mb()
+        free_mem_post, _ = get_mem_info_in_mb(empty_cache=False)

Also applies to: 289-290

📜 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 d0663e1 and b4ab81d.

📒 Files selected for processing (3)
  • tensorrt_llm/_torch/auto_deploy/models/factory.py (2 hunks)
  • tensorrt_llm/_torch/auto_deploy/transform/library/kvcache.py (3 hunks)
  • tensorrt_llm/_torch/auto_deploy/utils/cuda_mem_tracker.py (2 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:

  • tensorrt_llm/_torch/auto_deploy/transform/library/kvcache.py
  • tensorrt_llm/_torch/auto_deploy/utils/cuda_mem_tracker.py
  • tensorrt_llm/_torch/auto_deploy/models/factory.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:

  • tensorrt_llm/_torch/auto_deploy/transform/library/kvcache.py
  • tensorrt_llm/_torch/auto_deploy/utils/cuda_mem_tracker.py
  • tensorrt_llm/_torch/auto_deploy/models/factory.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:

  • tensorrt_llm/_torch/auto_deploy/transform/library/kvcache.py
  • tensorrt_llm/_torch/auto_deploy/utils/cuda_mem_tracker.py
  • tensorrt_llm/_torch/auto_deploy/models/factory.py
🧬 Code graph analysis (2)
tensorrt_llm/_torch/auto_deploy/transform/library/kvcache.py (5)
tensorrt_llm/_torch/auto_deploy/utils/cuda_mem_tracker.py (1)
  • get_mem_info_in_mb (30-36)
tensorrt_llm/_torch/auto_deploy/transform/interface.py (1)
  • _log_info (420-422)
tensorrt_llm/_torch/auto_deploy/shim/interface.py (2)
  • current_cache_size_bytes (61-68)
  • named_args (33-35)
tensorrt_llm/_torch/auto_deploy/custom_ops/attention_interface.py (3)
  • num_pages (321-322)
  • num_pages (325-329)
  • named_args (228-237)
tensorrt_llm/logger.py (1)
  • error (126-127)
tensorrt_llm/_torch/auto_deploy/models/factory.py (2)
tensorrt_llm/_torch/auto_deploy/utils/cuda_mem_tracker.py (1)
  • get_mem_info_in_mb (30-36)
tensorrt_llm/_torch/auto_deploy/models/hf.py (1)
  • _load_checkpoint (394-421)
🪛 Ruff (0.14.0)
tensorrt_llm/_torch/auto_deploy/transform/library/kvcache.py

278-280: Use logging.exception instead of logging.error

Replace with exception

(TRY400)


281-281: Use raise without specifying exception name

Remove exception name

(TRY201)

⏰ 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

@galagam galagam left a comment

Choose a reason for hiding this comment

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

LGTM

@nzmora-nvidia nzmora-nvidia force-pushed the user/nzmora/add_mem_logs branch from b4ab81d to b35fa0e Compare October 23, 2025 10:56
@nzmora-nvidia
Copy link
Collaborator Author

/bot run

@suyoggupta
Copy link
Collaborator

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #22513 [ run ] triggered by Bot. Commit: bdb9fe2

@tensorrt-cicd
Copy link
Collaborator

PR_Github #22513 [ run ] completed with state SUCCESS. Commit: bdb9fe2
/LLM/main/L0_MergeRequest_PR pipeline #16970 completed with status: 'FAILURE'

@nzmora-nvidia nzmora-nvidia enabled auto-merge (squash) October 26, 2025 10:55
@nzmora-nvidia
Copy link
Collaborator Author

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #22529 [ run ] triggered by Bot. Commit: bdb9fe2

@nzmora-nvidia nzmora-nvidia force-pushed the user/nzmora/add_mem_logs branch from bdb9fe2 to 2543f11 Compare October 26, 2025 14:24
@tensorrt-cicd
Copy link
Collaborator

PR_Github #22529 [ run ] completed with state SUCCESS. Commit: bdb9fe2
/LLM/main/L0_MergeRequest_PR pipeline #16984 completed with status: 'SUCCESS'

@nzmora-nvidia nzmora-nvidia removed the request for review from h-guo18 October 27, 2025 16:28
@nzmora-nvidia
Copy link
Collaborator Author

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #22814 [ run ] triggered by Bot. Commit: 742d1dd

@tensorrt-cicd
Copy link
Collaborator

PR_Github #22814 [ run ] completed with state SUCCESS. Commit: 742d1dd
/LLM/main/L0_MergeRequest_PR pipeline #17209 completed with status: 'FAILURE'

1. Log model size
2. Fix the logging of memory used during forward, when reconfiguring the kv-cache
3. Catch cache-resize OOM to give users a gentler experience

Signed-off-by: Neta Zmora <[email protected]>
Signed-off-by: Neta Zmora <[email protected]>
@nzmora-nvidia nzmora-nvidia force-pushed the user/nzmora/add_mem_logs branch from 742d1dd to 5b2f561 Compare October 29, 2025 08:15
@nzmora-nvidia
Copy link
Collaborator Author

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #22869 [ run ] triggered by Bot. Commit: 5b2f561

@tensorrt-cicd
Copy link
Collaborator

PR_Github #22869 [ run ] completed with state SUCCESS. Commit: 5b2f561
/LLM/main/L0_MergeRequest_PR pipeline #17248 completed with status: 'FAILURE'

@nzmora-nvidia
Copy link
Collaborator Author

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #22893 [ run ] triggered by Bot. Commit: 5b2f561

@tensorrt-cicd
Copy link
Collaborator

PR_Github #22893 [ run ] completed with state SUCCESS. Commit: 5b2f561
/LLM/main/L0_MergeRequest_PR pipeline #17265 completed with status: 'FAILURE'

@nzmora-nvidia
Copy link
Collaborator Author

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #25208 [ run ] triggered by Bot. Commit: 9ec44db

@tensorrt-cicd
Copy link
Collaborator

PR_Github #25208 [ run ] completed with state SUCCESS. Commit: 9ec44db
/LLM/main/L0_MergeRequest_PR pipeline #19064 completed with status: 'FAILURE'

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

Labels

None yet

Projects

Status: Backlog

Development

Successfully merging this pull request may close these issues.

6 participants