-
Notifications
You must be signed in to change notification settings - Fork 1.9k
[None][feat] AutoDeploy: refactor memory usage logging #8505
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?
Conversation
📝 WalkthroughWalkthroughThe changes introduce a utility function Changes
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 Pre-merge checks and finishing touches❌ Failed checks (2 warnings)
✅ 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 (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 // MIBBased 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
📒 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.pytensorrt_llm/_torch/auto_deploy/utils/cuda_mem_tracker.pytensorrt_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.pytensorrt_llm/_torch/auto_deploy/utils/cuda_mem_tracker.pytensorrt_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.pytensorrt_llm/_torch/auto_deploy/utils/cuda_mem_tracker.pytensorrt_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
galagam
left a 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.
LGTM
b4ab81d to
b35fa0e
Compare
|
/bot run |
|
/bot run |
|
PR_Github #22513 [ run ] triggered by Bot. Commit: |
|
PR_Github #22513 [ run ] completed with state |
|
/bot run |
|
PR_Github #22529 [ run ] triggered by Bot. Commit: |
bdb9fe2 to
2543f11
Compare
|
PR_Github #22529 [ run ] completed with state |
|
/bot run |
|
PR_Github #22814 [ run ] triggered by Bot. Commit: |
|
PR_Github #22814 [ run ] completed with state |
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]>
742d1dd to
5b2f561
Compare
|
/bot run |
|
PR_Github #22869 [ run ] triggered by Bot. Commit: |
|
PR_Github #22869 [ run ] completed with state |
|
/bot run |
|
PR_Github #22893 [ run ] triggered by Bot. Commit: |
|
PR_Github #22893 [ run ] completed with state |
|
/bot run |
|
PR_Github #25208 [ run ] triggered by Bot. Commit: |
|
PR_Github #25208 [ run ] completed with state |
Summary by CodeRabbit
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 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.