-
Notifications
You must be signed in to change notification settings - Fork 1.8k
[TRTLLM-4500][feat] Add serialization/deserialization options for AutoTuner profiling cache #7738
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
|
/bot run --disable-fail-fast |
|
PR_Github #18649 [ run ] triggered by Bot |
📝 WalkthroughWalkthroughImplements a persistent, rank-scoped autotuning cache and integrates it into the autotuning flow. Adds JSON load/save, new cache APIs, updates non-tuning/tuning paths to use the cache, modifies profiling return values, and wires per-rank cache usage from model engine. Tests updated for new APIs and persistence. Changes
Sequence Diagram(s)sequenceDiagram
autonumber
actor User
participant ModelEngine as PyTorchModelEngine
participant AutoTuner
participant Cache as ProfilingCache
participant Disk as JSON File (.rank{r}.json)
User->>ModelEngine: release_batch(...)
ModelEngine->>AutoTuner: autotune(tune_mode, cache_path, rank)
alt cache_path provided
AutoTuner->>Cache: load_cache(cache_path.rank{rank})
Cache->>Disk: Read JSON (if exists)
Disk-->>Cache: Cache entries (optional)
end
AutoTuner->>Cache: search_cache(custom_op, runners, shapes, cfg)
alt Cache hit (non-tuning)
Cache-->>AutoTuner: (runner_id, tactic, min_time)
AutoTuner-->>ModelEngine: Use cached selection
else Cache miss or tuning enabled
AutoTuner->>AutoTuner: _profile_runners(...) -> (best_runner_id, best_tactic, min_time, failure?)
AutoTuner->>Cache: cache[cache_key]= (best_runner_id, best_tactic, min_time)
alt cache_path provided
Cache->>Disk: Write JSON
end
AutoTuner-->>ModelEngine: Use profiled selection
end
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes ✨ Finishing touches
🧪 Generate unit tests
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.
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. Comment Pre-merge checks❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
|
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 (5)
tensorrt_llm/_torch/pyexecutor/model_engine.py (2)
1-1: Add required NVIDIA Apache-2.0 header (2025).Apply:
+# 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. import bisect
842-847: Avoid re-tuning during CUDA graph warmup; reuse the same cache.This second autotune() runs with default tune_mode=True and no cache path; it may re-profile and won’t persist. Reuse env cache path and rank.
Apply:
- if self.pytorch_backend_config.enable_autotuner: - with self.no_cuda_graph(), autotune(): + if self.pytorch_backend_config.enable_autotuner: + cache_path = os.environ.get("TLLM_AUTOTUNER_CACHE_PATH", None) + with self.no_cuda_graph(), autotune(cache_path=cache_path, rank=self.mapping.rank):tests/unittest/_torch/misc/test_autotuner.py (3)
1-1: Add required NVIDIA Apache-2.0 header (2025).Apply:
+# 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. from typing import Dict, List
141-146: Coerce 0-D Tensor to int before comparisons.check_gemm_tactic_valid expects int; passing a Tensor will error in boolean context.
Apply:
- best_tactic = torch.ops.autotuner_test.get_best_gemm_tactic( - torch.randn(m, 64), w) - check_gemm_tactic_valid(best_tactic, m) + best_tactic = torch.ops.autotuner_test.get_best_gemm_tactic(torch.randn(m, 64), w) + check_gemm_tactic_valid(int(best_tactic.item()), m)
216-219: Same issue: convert Tensors to ints.Apply:
- t1, t2 = torch.ops.autotuner_test.recursive_get_best_gemm_tactic( - torch.randn(m, 64), w1, w2) - check_gemm_tactic_valid(t1, m) - check_gemm_tactic_valid(t2, m) + t1, t2 = torch.ops.autotuner_test.recursive_get_best_gemm_tactic(torch.randn(m, 64), w1, w2) + check_gemm_tactic_valid(int(t1.item()), m) + check_gemm_tactic_valid(int(t2.item()), m)
🧹 Nitpick comments (6)
tensorrt_llm/_torch/autotuner.py (5)
332-344: search_cache signature/docs mismatch the actual return.Currently returns (bool, int, Any, float). Update hints/docstring accordingly.
Apply:
- ) -> Tuple[bool, int, int, Dict[str, Any], OptimizationProfile]: + ) -> Tuple[bool, int, Any, float]: @@ - Returns: - A tuple containing: - [is_cache_hit, runner_id, tactic, stored_profile] + Returns: + (is_cache_hit, runner_id, tactic, min_time)
370-372: Return type of get_specific_custom_op is incorrect.It returns a dict, not a tuple.
Apply:
- def get_specific_custom_op(self, custom_op: str) -> Tuple: + def get_specific_custom_op(self, custom_op: str) -> Dict[Tuple, Tuple]:
630-687: _profile_runners return type annotation is wrong.Function returns 4-tuple, not float.
Apply:
- ) -> float: + ) -> Tuple[Optional[int], Any, float, bool]:Also ensure Optional is imported:
-from typing import Any, Callable, Dict, List, Set, Tuple, Union +from typing import Any, Callable, Dict, List, Set, Tuple, Union, Optional
351-369: Runner identity via hash may break for unhashable attributes.hash(tuple(self.dict.values())) will TypeError if any value is unhashable (e.g., list/dict/tensor). Consider a safer identity.
Example:
- runner.__class__.__name__, - hash(runner), + runner.__class__.__name__, + hash(tuple((k, repr(v)) for k, v in runner.__dict__.items())),
90-97: Use Optional[int] for tune_max_num_tokens.Aligns with PEP 484 (RUF013).
Apply:
- tune_max_num_tokens: int = None + tune_max_num_tokens: Optional[int] = Nonetests/unittest/_torch/misc/test_autotuner.py (1)
307-314: Use secure temp path instead of hardcoded /tmp (S108).Leverage TemporaryDirectory for portability and cleanup.
Apply:
- cache_path = "/tmp/test_multiple_dynamic_shapes.json" - AutoTuner.get().profiling_cache.save_cache(cache_path) - # clear cache to test the load_cache functionality - AutoTuner.get().profiling_cache.clear() - AutoTuner.get().profiling_cache.load_cache(cache_path) + import os, tempfile + with tempfile.TemporaryDirectory() as tmpdir: + cache_path = os.path.join(tmpdir, "test_multiple_dynamic_shapes.json") + AutoTuner.get().profiling_cache.save_cache(cache_path) + AutoTuner.get().profiling_cache.clear() + AutoTuner.get().profiling_cache.load_cache(cache_path) cache_entries = tuner.profiling_cache.get_specific_custom_op( "test_multiple_dynamic_shapes")
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (3)
tensorrt_llm/_torch/autotuner.py(11 hunks)tensorrt_llm/_torch/pyexecutor/model_engine.py(1 hunks)tests/unittest/_torch/misc/test_autotuner.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/pyexecutor/model_engine.pytests/unittest/_torch/misc/test_autotuner.pytensorrt_llm/_torch/autotuner.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/pyexecutor/model_engine.pytests/unittest/_torch/misc/test_autotuner.pytensorrt_llm/_torch/autotuner.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/pyexecutor/model_engine.pytests/unittest/_torch/misc/test_autotuner.pytensorrt_llm/_torch/autotuner.py
🧠 Learnings (1)
📚 Learning: 2025-08-19T12:45:11.997Z
Learnt from: amitz-nv
PR: NVIDIA/TensorRT-LLM#7033
File: tensorrt_llm/_torch/pyexecutor/model_engine.py:0-0
Timestamp: 2025-08-19T12:45:11.997Z
Learning: In tensorrt_llm/_torch/pyexecutor/model_engine.py, DoRA (Delta Orthogonal Rank Adaptation) functionality was removed from the PyTorch flow to eliminate issues with inverted DoRA detection logic. The original is_dora condition was checking if scaling_vec_pointer == 0, which was potentially incorrect.
Applied to files:
tensorrt_llm/_torch/pyexecutor/model_engine.py
🧬 Code graph analysis (3)
tensorrt_llm/_torch/pyexecutor/model_engine.py (2)
tensorrt_llm/_torch/autotuner.py (2)
get(516-519)autotune(208-242)tensorrt_llm/mapping.py (2)
rank(324-325)rank(328-335)
tests/unittest/_torch/misc/test_autotuner.py (1)
tensorrt_llm/_torch/autotuner.py (7)
get_cache_key(351-368)AutoTuner(489-931)get(516-519)save_cache(373-398)clear(319-320)load_cache(400-427)get_specific_custom_op(370-371)
tensorrt_llm/_torch/autotuner.py (1)
tensorrt_llm/logger.py (4)
info(138-139)error(126-127)warning(132-133)debug(144-145)
🪛 Ruff (0.12.2)
tests/unittest/_torch/misc/test_autotuner.py
307-307: Probable insecure usage of temporary file or directory: "/tmp/test_multiple_dynamic_shapes.json"
(S108)
tensorrt_llm/_torch/autotuner.py
208-208: PEP 484 prohibits implicit Optional
Convert to Optional[T]
(RUF013)
416-416: Avoid specifying long messages outside the exception class
(TRY003)
⏰ 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 (5)
tensorrt_llm/_torch/autotuner.py (4)
688-695: _get_input_sizes: LGTM.Graceful handling for None/non-Tensor inputs is correct and consistent with nearest-profile logic.
298-306: Good separation of concerns with AutoTunerProfilingCache.Clear API and persistence helpers improve modularity.
372-399: Robust, readable JSON persistence.Using Path.parent.mkdir and default=str is appropriate.
556-566: logger.warning_once exists — no change required.
Defined in tensorrt_llm/logger.py (line ~135) as a wrapper to log_once; the autotuner call is valid.tensorrt_llm/_torch/pyexecutor/model_engine.py (1)
784-787: Pass cache_path/rank consistently to autotune.Good integration here.
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.
I think this is an ok starting point, but I would like to use this opportunity to properly unify the tuning across all ranks. I consider it a bug if we have different configs on each rank.
Except maybe for pipeline parallel, any differences will just cause a communication bubble
|
PR_Github #18649 [ run ] completed with state |
ed9e69b to
16f814e
Compare
|
/bot run --disable-fail-fast |
|
PR_Github #18912 [ run ] triggered by Bot |
|
PR_Github #18912 [ run ] completed with state |
16f814e to
707abf0
Compare
|
/bot run --disable-fail-fast |
|
PR_Github #19092 [ run ] triggered by Bot |
|
PR_Github #19092 [ run ] completed with state |
|
/bot run --disable-fail-fast |
|
PR_Github #19235 [ run ] triggered by Bot |
|
PR_Github #19235 [ run ] completed with state |
707abf0 to
7fd9f99
Compare
|
/bot run --disable-fail-fast |
|
PR_Github #19952 [ run ] triggered by Bot |
|
PR_Github #19952 [ run ] completed with state |
f4496c1 to
16b5e72
Compare
|
/bot run --disable-fail-fast |
|
PR_Github #20010 [ run ] triggered by Bot |
|
PR_Github #20010 [ run ] completed with state |
|
/bot run --disable-fail-fast |
|
PR_Github #20037 [ run ] triggered by Bot |
|
PR_Github #20037 [ run ] completed with state |
16b5e72 to
0e8a2b8
Compare
|
/bot run --disable-fail-fast |
|
PR_Github #20066 [ run ] triggered by Bot |
|
PR_Github #20066 [ run ] completed with state |
0e8a2b8 to
cf71c44
Compare
|
/bot run --disable-fail-fast |
|
PR_Github #20095 [ run ] triggered by Bot |
|
PR_Github #20095 [ run ] completed with state |
|
/bot run --disable-fail-fast |
|
PR_Github #20151 [ run ] triggered by Bot |
|
PR_Github #20151 [ run ] completed with state |
…oTuner profiling cache. Signed-off-by: Yukun He <23156053+hyukn@users.noreply.github.com>
cf71c44 to
7499641
Compare
|
/bot run --disable-fail-fast |
|
PR_Github #20172 [ run ] triggered by Bot |
|
PR_Github #20172 [ run ] completed with state |
Summary by CodeRabbit
New Features
Bug Fixes
Tests
Description
To achieve determinism for the AutoTuner profiling cache, serialization and deserialization are introduced to store the cache on disk in JSON format.
Use
TLLM_AUTOTUNER_CACHE_PATHto indicate the path where the cache file should be stored: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.