-
Notifications
You must be signed in to change notification settings - Fork 1.8k
[TRTLLM-6142][feat] Reland: set torch recompile_limit based on cuda_graph_batch_sizes and refactored #7219
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
Conversation
Signed-off-by: Eran Geva <19514940+MrGeva@users.noreply.github.com> removed changes made to TorchCompileCompiler Signed-off-by: Eran Geva <19514940+MrGeva@users.noreply.github.com> set cache_size_limit in TorchCompileCompiler Signed-off-by: Eran Geva <19514940+MrGeva@users.noreply.github.com>
Signed-off-by: Eran Geva <19514940+MrGeva@users.noreply.github.com>
📝 WalkthroughWalkthroughIntroduces logging in torch-compile and torch-opt compilers; adjusts TorchOpt to set Dynamo recompile_limit. Refactors CUDA graph handling: CapturedGraph now requires explicit cuda_graph_batch_sizes and derives max_batch_size internally; heuristic for batch sizes moved to TorchCudagraphCompiler. Tests parameterize compile_backends and expand batch sizes and max_batch_size. Changes
Sequence Diagram(s)sequenceDiagram
autonumber
participant TCC as TorchCudagraphCompiler
participant CFG as CapturedGraph
participant Dyn as torch._dynamo.config
participant Log as ad_logger
rect rgba(200,220,255,0.25)
note over TCC: Initialization
TCC->>TCC: __init__(..., compiler_kwargs)
alt cuda_graph_batch_sizes provided
TCC->>Log: info("configured cuda_graph_batch_sizes=...")
else compute via heuristic
TCC->>TCC: _get_graph_batch_sizes(max_bs, extra, multiplier)
TCC->>Log: info("computed max_bs and batch sizes")
end
end
rect rgba(200,255,200,0.25)
note over TCC,CFG: CapturedGraph setup
TCC->>CFG: __init__(model, in_spec, out_spec, cuda_graph_batch_sizes)
CFG->>CFG: max_batch_size = max(cuda_graph_batch_sizes)
CFG->>Log: info("derived max_batch_size=...")
end
rect rgba(255,240,200,0.25)
note over Dyn: TorchOptCompiler init
participant TOC as TorchOptCompiler
TOC->>Dyn: recompile_limit = max(len(cuda_graph_batch_sizes), recompile_limit)
TOC->>Log: info("recompile_limit, cache_size_limit")
end
rect rgba(240,240,255,0.25)
note over Log: TorchCompileCompiler init
participant TCom as TorchCompileCompiler
TCom->>Log: info("Torch Dynamo cache_size_limit")
end
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
Suggested reviewers
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 unit tests
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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR/Issue comments)Type Other keywords and placeholders
Status, Documentation and Community
|
|
/bot run |
|
PR_Github #16455 [ run ] triggered by Bot |
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: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (5)
tensorrt_llm/_torch/auto_deploy/compile/backends/torch_cudagraph.py (2)
1-1: Add NVIDIA Apache-2.0 license header (2025).All source files must prepend the NVIDIA Apache-2.0 copyright header per guidelines. Please add it here.
Apply at the very top:
+# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. +# +# 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.
43-53: round_to_cuda_batch_size can return None; fix signature and guard.
round_up_to_closestreturnsOptional[int].round_to_cuda_batch_sizeshould mirror that; otherwise mypy/pyright will complain and downstream code may mis-handleNone.Apply:
- def round_to_cuda_batch_size(self, bs: int) -> int: + def round_to_cuda_batch_size(self, bs: int) -> Optional[int]: """Round batch size to the nearest cuda batch size.""" return self.round_up_to_closest(self.cuda_graph_batch_sizes, bs)And short-circuit in forward when any rounded bs is None (see next comment).
tensorrt_llm/_torch/auto_deploy/compile/backends/torch_compile.py (1)
1-1: Add NVIDIA Apache-2.0 license header (2025).Required by coding guidelines.
Apply:
+# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. +# Licensed under the Apache License, Version 2.0 ...tensorrt_llm/_torch/auto_deploy/compile/backends/torch_opt.py (1)
1-1: Add NVIDIA Apache-2.0 license header (2025).Please prepend the standard header.
+# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. +# Licensed under the Apache License, Version 2.0 ...tests/unittest/_torch/auto_deploy/unit/singlegpu/test_ad_trtllm_bench.py (1)
1-1: Add NVIDIA Apache-2.0 license header (2025).Tests are in scope of the header requirement.
+# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. +# Licensed under the Apache License, Version 2.0 ...
🧹 Nitpick comments (7)
tensorrt_llm/_torch/auto_deploy/compile/backends/torch_cudagraph.py (4)
35-37: Type annotation: _out_buffer_flat can be None.
self._out_buffer_flatis initialized toNonebut annotated asList[torch.Tensor]. This trips type-checkers and can mask bugs.Apply:
- self._out_buffer_flat: List[torch.Tensor] = None + from typing import Optional + self._out_buffer_flat: Optional[List[torch.Tensor]] = NoneOptionally assert before use:
- out_flat = [o_b[:bs].detach().clone() for o_b in self._out_buffer_flat] + assert self._out_buffer_flat is not None, "Output buffer not initialized; call capture_graph() first." + out_flat = [o_b[:bs].detach().clone() for o_b in self._out_buffer_flat]
134-144: Graceful fallback when no captured size ≥ requested bs.If
bs > max(cuda_graph_batch_sizes),round_to_cuda_batch_sizereturnsNoneand you currently construct shapes containingNone. While this works due to the key-miss branch, it's clearer and cheaper to bail out early.Apply:
- rounded_shapes = [ - (self.round_to_cuda_batch_size(input.shape[0]),) + input.shape[1:] - for input in args_batched - ] + rounded_bs = [self.round_to_cuda_batch_size(input.shape[0]) for input in args_batched] + if any(rb is None for rb in rounded_bs): + return self.model(*args, **kwargs) + rounded_shapes = [(rb,) + input.shape[1:] for rb, input in zip(rounded_bs, args_batched)]
109-121: Avoid redundant captures when cuda_graph_batch_sizes contain values > max_batch_size.If a provided batch size exceeds
self.max_batch_size,in_buffer[:bs]equalsin_buffer[:], leading to duplicate combined_shape keys and redundant capture attempts.Two options:
- Clamp once in the compiler init (preferred; see next comment).
- Or guard here:
- for bs in self.cuda_graph_batch_sizes: + for bs in self.cuda_graph_batch_sizes: + if bs > self.max_batch_size: + ad_logger.info(f"Skipping capture for bs={bs} > max_batch_size={self.max_batch_size}") + continue
190-203: Heuristic helper looks good; add minimal input validation.Tiny nit: guard invalid inputs and document multiplier behavior for non-divisors of max_bs.
Apply:
def _get_graph_batch_sizes( max_bs: int, extra: Optional[List[int]] = None, multiplier: int = 128 ) -> List[int]: - """Heuristic to set batch sizes for graph capture.""" + """Heuristic to set batch sizes for graph capture. + + Returns unique sizes in descending order, including 1, max_bs, any `extra`, + and all multiples of `multiplier` up to `max_bs`. + """ + assert max_bs >= 1, "max_bs must be >= 1" + assert multiplier >= 1, "multiplier must be >= 1" # do 1, max_bs, and extra as special batch sizes batch_sizes = {1, max_bs, *(extra or [])}tensorrt_llm/_torch/auto_deploy/compile/backends/torch_compile.py (1)
6-6: Consistency: unify ad_logger import style across backends.Other backends use relative imports (
from ...utils.logger import ad_logger). Consider standardizing on a single absolute style (this one) repo-wide for clarity.tensorrt_llm/_torch/auto_deploy/compile/backends/torch_opt.py (1)
15-24: Deriving Dynamo recompile_limit from cuda_graph_batch_sizes is sensible; consider headroom.Setting
recompile_limit = max(len(cuda_graph_batch_sizes), existing)avoids premature bailouts, but workloads may still trigger a few extra specializations (e.g., uncommon prompt shapes). Add a small headroom and make it tunable viacompiler_kwargs.Apply:
- torch._dynamo.config.recompile_limit = max( - len(self.cuda_graph_batch_sizes), torch._dynamo.config.recompile_limit - ) + headroom = int(self.compiler_kwargs.get("dynamo_recompile_headroom", 2)) + target_limit = len(self.cuda_graph_batch_sizes) + max(0, headroom) + torch._dynamo.config.recompile_limit = max(target_limit, torch._dynamo.config.recompile_limit)Keep the informative log (already present).
tests/unittest/_torch/auto_deploy/unit/singlegpu/test_ad_trtllm_bench.py (1)
590-598: Potential config vs CLI mismatch for max_batch_size.You set
max_batch_size: 128in YAML, butrun_benchmark()is called below without overridingmax_batch_size(defaults to 32) and passes--max_batch_size 32on the CLI. Depending on precedence insidetensorrt_llm.commands.bench, this may cause confusion or unintended overrides.Consider aligning both sources by passing 128 to
run_benchmarkhere:- run_benchmark(model_name, dataset_path, temp_dir) + run_benchmark(model_name, dataset_path, temp_dir, max_batch_size=128)Or drop
--max_batch_sizefor_autodeploymode insiderun_benchmark()and rely solely on YAML to avoid split-brain configuration.
📜 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.
📒 Files selected for processing (5)
examples/auto_deploy/build_and_run_ad.py(0 hunks)tensorrt_llm/_torch/auto_deploy/compile/backends/torch_compile.py(1 hunks)tensorrt_llm/_torch/auto_deploy/compile/backends/torch_cudagraph.py(3 hunks)tensorrt_llm/_torch/auto_deploy/compile/backends/torch_opt.py(2 hunks)tests/unittest/_torch/auto_deploy/unit/singlegpu/test_ad_trtllm_bench.py(2 hunks)
💤 Files with no reviewable changes (1)
- examples/auto_deploy/build_and_run_ad.py
🧰 Additional context used
📓 Path-based instructions (2)
**/*.py
📄 CodeRabbit inference engine (CODING_GUIDELINES.md)
**/*.py: Code must target Python 3.8+
Indent with 4 spaces; do not use tabs
Preserve module namespace when importing: from package.subpackage import foo; then use foo.SomeClass()
Python filenames use snake_case (e.g., some_file.py)
Class names use PascalCase
Function and method names use snake_case
Local variables use snake_case; prefix k for names starting with a number (e.g., k_99th_percentile)
Global variables are UPPER_SNAKE_CASE prefixed with G (e.g., G_MY_GLOBAL)
Constants are UPPER_SNAKE_CASE
Avoid shadowing variables from an outer scope
Initialize all externally visible members of a class in init
For interfaces used outside a file, prefer docstrings over comments; comments for internal code or local interfaces
Use Google-style docstrings for classes and functions (Sphinx-parsable)
Attributes and variables can be documented inline with trailing docstrings under the class or module
Avoid using reflection when easily avoidable; prefer explicit parameters/constructs over dict(**locals())
In try/except, catch the narrowest exception types possible
For duck-typing try/except, keep try body minimal and place logic in else after attribute existence checks
Files:
tensorrt_llm/_torch/auto_deploy/compile/backends/torch_compile.pytensorrt_llm/_torch/auto_deploy/compile/backends/torch_opt.pytests/unittest/_torch/auto_deploy/unit/singlegpu/test_ad_trtllm_bench.pytensorrt_llm/_torch/auto_deploy/compile/backends/torch_cudagraph.py
**/*.{h,hpp,hxx,hh,c,cc,cpp,cxx,cu,cuh,py}
📄 CodeRabbit inference engine (CODING_GUIDELINES.md)
Prepend NVIDIA Apache-2.0 copyright header with current year to all source files
Files:
tensorrt_llm/_torch/auto_deploy/compile/backends/torch_compile.pytensorrt_llm/_torch/auto_deploy/compile/backends/torch_opt.pytests/unittest/_torch/auto_deploy/unit/singlegpu/test_ad_trtllm_bench.pytensorrt_llm/_torch/auto_deploy/compile/backends/torch_cudagraph.py
🧠 Learnings (1)
📚 Learning: 2025-07-28T17:06:08.621Z
Learnt from: moraxu
PR: NVIDIA/TensorRT-LLM#6303
File: tests/integration/test_lists/qa/examples_test_list.txt:494-494
Timestamp: 2025-07-28T17:06:08.621Z
Learning: In TensorRT-LLM testing, it's common to have both CLI flow tests (test_cli_flow.py) and PyTorch API tests (test_llm_api_pytorch.py) for the same model. These serve different purposes: CLI flow tests validate the traditional command-line workflow, while PyTorch API tests validate the newer LLM API backend. Both are legitimate and should coexist.
Applied to files:
tests/unittest/_torch/auto_deploy/unit/singlegpu/test_ad_trtllm_bench.py
🧬 Code graph analysis (2)
tensorrt_llm/_torch/auto_deploy/compile/backends/torch_compile.py (1)
tensorrt_llm/_torch/auto_deploy/compile/compiler.py (3)
BackendCompiler(46-72)BackendRegistry(24-43)register(28-34)
tensorrt_llm/_torch/auto_deploy/compile/backends/torch_cudagraph.py (2)
tensorrt_llm/_torch/auto_deploy/compile/compiler.py (1)
get(37-39)tensorrt_llm/_torch/auto_deploy/compile/backends/torch_opt.py (1)
_init_captured_graph(25-27)
⏰ 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 (3)
tensorrt_llm/_torch/auto_deploy/compile/backends/torch_compile.py (1)
13-16: Init-time visibility into Dynamo cache configuration — good addition.Logging
torch._dynamo.config.cache_size_limiton init helps correlate perf with cache pressure. No issues.tensorrt_llm/_torch/auto_deploy/compile/backends/torch_opt.py (1)
25-27: LGTM on compile-and-wrap flow.Compiling
gmwithtorch.compile(..., dynamic=True)before delegating to CUDA graph capture is consistent with the mixed backend goals.tests/unittest/_torch/auto_deploy/unit/singlegpu/test_ad_trtllm_bench.py (1)
584-598: Parametrizing compile_backend across torch-compile/opt/cudagraph — good coverage increase.Writing the selected backend into
extra_llm_api_options.yamlis the right way to exercise the autodeploy path. 👍
|
PR_Github #16455 [ run ] completed with state |
Signed-off-by: Eran Geva <19514940+MrGeva@users.noreply.github.com>
|
/bot run |
|
PR_Github #17370 [ run ] triggered by Bot |
|
PR_Github #17370 [ run ] completed with state |
|
/bot run |
|
PR_Github #17652 [ run ] triggered by Bot |
|
PR_Github #17652 [ run ] completed with state |
|
/bot run |
|
PR_Github #17694 [ run ] triggered by Bot |
|
PR_Github #17694 [ run ] completed with state |
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.
looks great
|
/bot run |
|
PR_Github #17914 [ run ] triggered by Bot |
|
PR_Github #17914 [ run ] completed with state |
|
/bot run |
|
PR_Github #17930 [ run ] triggered by Bot |
Signed-off-by: Eran Geva <19514940+MrGeva@users.noreply.github.com>
|
/bot run |
|
PR_Github #17946 [ run ] triggered by Bot |
|
PR_Github #17930 [ run ] completed with state |
|
PR_Github #17946 [ run ] completed with state |
…da_graph_batch_sizes and refactored (NVIDIA#7219) Signed-off-by: Eran Geva <19514940+MrGeva@users.noreply.github.com>
Re-Introducing this change after fixing the perf regression it had caused, this time I do not set the torch._dynamo.config.cache_size_limit as it caused a perf regression because it re-compiled instead of running eager. only setting torch._dynamo.config.recompile_limit
Adjusted a unit test to work with the new CapturedGraph API which no longer contains max_batch_size - cuda_graph_batch_sizes is used instead.
when processing user cuda_graph_batch_sizes, added logic to validate the values, and clamp if needed.
this was the original PR description, still relevant:
torch._dynamo.config.recompile_limit was not set, so the default value 8 was used, sometimes leading to eager execution.
This change sets it based on the len(cuda_graph_batch_sizes).
Additionally, moved the cuda_graph_batch_sizes calculation (if not set by the user) heuristic to TorchCudagraphCompiler,
have it be a mandatory param to CapturedGraph and removed max_batch_size param (because it is now inferred from cuda_graph_batch_sizes).
Also, moved cache_size_limit from build_and_run_ad.py to the torch-opt and torch-compile BEs.
Added all 3 backends to the test_trtllm_bench and extended the cuda_graph_batch_sizes because cuda graph asserts in small batch size and also it compares it to the input shape batch dim.
Summary by CodeRabbit
New Features
Refactor
Tests
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.
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.