-
Notifications
You must be signed in to change notification settings - Fork 2k
[TRTLLM-7963][feat] Cold L2 cache when doing autotune benchmarking #7587
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
…tactic tuning. Signed-off-by: Yukun He <[email protected]>
Signed-off-by: Mindy Li <[email protected]>
Signed-off-by: Mindy Li <[email protected]>
📝 WalkthroughWalkthroughAdds L2 cache-aware, batch-based profiling to AutoTuner’s _profile_single_kernel. Introduces helpers for preparing rotating input batches, querying device L2 cache size via CUDA driver APIs, handling CUDA errors, and inserting a post-warmup delay. Updates warmup and timing loops to operate on prepared tensor batch lists. Changes
Sequence Diagram(s)sequenceDiagram
autonumber
participant AT as AutoTuner
participant CD as CUDA Driver
participant R as Kernel Runner
participant T as Timer
AT->>AT: _prepare_input_tensors_with_batches(inputs)
AT->>CD: Query L2 cache size
CD-->>AT: L2 size (bytes)
AT->>AT: Assemble tensor_lists, num_buffers
rect rgb(235,245,255)
note right of AT: Warmup Phase (rotating batches)
loop warmup_iters
AT->>R: run(tensor_lists[idx % num_buffers])
R-->>AT: complete
AT->>AT: idx++
end
AT->>R: delay_kernel() %% reduce host overhead
end
rect rgb(240,255,240)
note right of AT: Measurement Phase
loop repeat
AT->>T: start()
AT->>R: run(tensor_lists[idx % num_buffers])
R-->>AT: complete
AT->>T: stop()
AT->>AT: idx++
end
end
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Suggested reviewers
✨ 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. 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
🧹 Nitpick comments (4)
tensorrt_llm/_torch/autotuner.py (4)
530-540: Make “cold L2” configurable, not hard-coded.Hard-coding use_cold_l2=True removes control for environments where cloning buffers is undesirable.
Apply this diff in-place:
- use_cold_l2 = True + use_cold_l2 = getattr(self, "use_cold_l2", True)And add this init parameter (outside the selected range):
# in __init__ def __init__(self, warmup=3, repeat=10, stream_delay_micro_secs=1000, use_cold_l2=True): self.repeat = repeat self.warmup = warmup self.stream_delay_micro_secs = stream_delay_micro_secs self.use_cold_l2 = use_cold_l2 ...
543-549: Comment/behavior mismatch in warmup loop.Code rotates batches; comment says “always use the last batch.”
Apply this diff to align the comment:
- # always use the last batch for warmup + # rotate across prepared batches for warmup
777-779: Polish log message wording.Minor readability tweak.
Apply this diff:
- logger.debug( - f"[Autotuner] To cold L2 cache, use {num_buffers} different tensors for profiling" - ) + logger.debug( + f"[Autotuner] Using {num_buffers} distinct input buffers to simulate cold L2 cache during profiling" + )
800-807: Query L2 on the active device, not hard-coded device 0.Ensures correctness in multi-GPU runs.
Apply this diff:
- def _get_l2_cache_size_in_bytes(self, device_id: int = 0) -> int: - device = self._checkCudaErrors(driver.cuDeviceGet(device_id)) + def _get_l2_cache_size_in_bytes(self, device_id: int = None) -> int: + if device_id is None: + device_id = torch.cuda.current_device() + device = self._checkCudaErrors(driver.cuDeviceGet(device_id))
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
tensorrt_llm/_torch/autotuner.py(5 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/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/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/autotuner.py
🪛 Ruff (0.12.2)
tensorrt_llm/_torch/autotuner.py
766-766: Undefined name ceil
(F821)
824-824: Undefined name nvrtc
(F821)
825-825: Undefined name nvrtc
(F821)
⏰ 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/_torch/autotuner.py (2)
561-565: LGTM: rotate batches during timing.Using buffer_idx % num_buffers for measurements matches the cold-L2 intent.
570-573: LGTM: deterministic shape logging.Logging shapes from the last prepared batch is fine since all batches share shapes.
Signed-off-by: Mindy Li <[email protected]>
Signed-off-by: Mindy Li <[email protected]>
Signed-off-by: Mindy Li <[email protected]>
|
/bot run |
|
PR_Github #17904 [ run ] triggered by Bot |
|
PR_Github #17904 [ run ] completed with state |
|
/bot run |
|
PR_Github #17913 [ run ] triggered by Bot |
|
PR_Github #17913 [ run ] completed with state |
Signed-off-by: Mindy Li <[email protected]>
|
/bot run |
|
PR_Github #18168 [ run ] triggered by Bot |
…nts. Signed-off-by: Yukun He <[email protected]>
Signed-off-by: Mindy Li <[email protected]>
|
PR_Github #18168 [ run ] completed with state |
|
/bot run |
|
PR_Github #18211 [ run ] triggered by Bot |
|
PR_Github #18211 [ run ] completed with state |
| for _ in range(self.warmup): | ||
| runner(inputs, tactic=tactic, **kwargs) | ||
| runner( | ||
| input_tensor_baches[-1], |
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 don't understand this one, why [-1]?
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 assume this is so that we don't warm up the cache for the first iteration?
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.
Exactly. Always using the last one is a simple way to guarantee that every profiling has a cold cache.
| num_buffers = min(num_buffers, self.repeat + 1) | ||
|
|
||
| inputs_list = [inputs] | ||
| for _ in range(num_buffers - 1): |
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 will increase the GPU memory a lot, by num_buffersx, can we clear L2 cache in another way? w/o increase the memory usage much.
This matters for TRTLLM because we need to use trace based method to record peak memory and estimate KV cache usage.
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.
But use_cold_l2 is opt in. If we don't setup this config, it means nothing is done for this mr. Still curious why some tests failed.
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 a better approach may be to have a L2 clearing kernel that runs between each iteration. I think you can do this by initialising an auxiliary buffer to maybe 2-3x the size of cache, and then launch a kernel to write random values between iterations (I think it needs to be random)
djns99
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.
I think we should go for a cache clearing approach to minimise memory overhead, and to simplify the implementation.
Theres a couple of problematic interactions with some of the MOE logic we might run into otherwise
| return [inputs] | ||
|
|
||
| num_buffers = self._get_l2_cache_size_in_bytes( | ||
| ) * 3 // one_buffer_bytes + 1 |
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.
This should be at least 2, otherwise we will use the same weights which might still be in the cache
| for _ in range(self.warmup): | ||
| runner(inputs, tactic=tactic, **kwargs) | ||
| runner( | ||
| input_tensor_baches[-1], |
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 assume this is so that we don't warm up the cache for the first iteration?
| for _ in range(num_buffers - 1): | ||
| inputs_list.append( | ||
| list(t.clone() if isinstance(t, torch.Tensor) else t | ||
| for t in inputs)) |
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.
This is not going to work for MOE, for MOE we have pointers referring to the weights in the workspace. We will need to call with do_preperation=True separately for every buffer.
This will need some changes to the preparation logic to support multiple internal workspaces too.
For this reason I think it might be better to go for an L2 clearing based approach that also reduces memory (see other comment)
| num_buffers = min(num_buffers, self.repeat + 1) | ||
|
|
||
| inputs_list = [inputs] | ||
| for _ in range(num_buffers - 1): |
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 a better approach may be to have a L2 clearing kernel that runs between each iteration. I think you can do this by initialising an auxiliary buffer to maybe 2-3x the size of cache, and then launch a kernel to write random values between iterations (I think it needs to be random)
When running ops in models, the L2 cache is usually cold. But in autotune, we don't clear L2 cache when benchmarking. Some kernels may easily been influenced by warm/cold L2 cache. In order to make the kernel selection more accurate, we clear L2 cache (circle buffer method) for autotune benchmark in this MR.
This MR is completed by yukun, I test and update a commit.
Summary by CodeRabbit
Refactor
Chores
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.
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 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.