Skip to content

Conversation

@limin2021
Copy link
Collaborator

@limin2021 limin2021 commented Sep 6, 2025

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

    • Improved autotuning reliability with cache-aware, batch-based profiling for more consistent kernel performance measurements.
    • Reduced host-side overhead during profiling, leading to faster and more stable tuning runs.
    • Enhanced logging around profiling shapes and batching strategy for clearer diagnostics.
  • Chores

    • Added low-level error handling and device capability checks to improve runtime robustness during profiling.

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 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.

@limin2021 limin2021 requested a review from a team as a code owner September 6, 2025 11:47
@limin2021 limin2021 requested a review from liji-nv September 6, 2025 11:47
Signed-off-by: Mindy Li <[email protected]>
@limin2021 limin2021 changed the title Feat/autotune cold l2 [None][fix] cold L2 cache when doing autotune benchmarking Sep 6, 2025
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Sep 6, 2025

📝 Walkthrough

Walkthrough

Adds 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

Cohort / File(s) Summary
Autotuner profiling and CUDA utilities
tensorrt_llm/_torch/autotuner.py
- Add batch-based profiling in _profile_single_kernel using rotating input tensor lists and a delay kernel after warmup
- New _prepare_input_tensors_with_batches to create multiple input batches based on L2 cache size and repeat count
- Add CUDA driver helpers: _get_l2_cache_size_in_bytes, _checkCudaErrors, _cudaGetErrorEnum; new import of cuda.bindings.driver
- Logging uses shapes from last prepared batch; loops call runner with tensor_lists[buffer_idx % num_buffers]

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
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Suggested reviewers

  • liji-nv
  • lfr-0531
  • litaotju
  • suyoggupta
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • 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

🧹 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

📥 Commits

Reviewing files that changed from the base of the PR and between caf9b9c and 4dbcaad.

📒 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]>
@limin2021 limin2021 requested review from hyukn and litaotju September 6, 2025 12:03
Signed-off-by: Mindy Li <[email protected]>
Signed-off-by: Mindy Li <[email protected]>
@limin2021
Copy link
Collaborator Author

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #17904 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #17904 [ run ] completed with state SUCCESS
/LLM/main/L0_MergeRequest_PR pipeline #13412 completed with status: 'FAILURE'

@limin2021
Copy link
Collaborator Author

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #17913 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #17913 [ run ] completed with state SUCCESS
/LLM/main/L0_MergeRequest_PR pipeline #13420 completed with status: 'FAILURE'

@hyukn hyukn changed the title [None][fix] cold L2 cache when doing autotune benchmarking [TRTLLM-7963][feat] Cold L2 cache when doing autotune benchmarking Sep 9, 2025
Signed-off-by: Mindy Li <[email protected]>
@limin2021
Copy link
Collaborator Author

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #18168 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #18168 [ run ] completed with state SUCCESS
/LLM/main/L0_MergeRequest_PR pipeline #13614 completed with status: 'FAILURE'

@limin2021
Copy link
Collaborator Author

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #18211 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #18211 [ run ] completed with state SUCCESS
/LLM/main/L0_MergeRequest_PR pipeline #13648 completed with status: 'FAILURE'

for _ in range(self.warmup):
runner(inputs, tactic=tactic, **kwargs)
runner(
input_tensor_baches[-1],
Copy link
Collaborator

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]?

Copy link
Collaborator

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?

Copy link
Collaborator

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):
Copy link
Collaborator

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.

Copy link
Collaborator Author

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.

Copy link
Collaborator

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)

Copy link
Collaborator

@djns99 djns99 left a 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
Copy link
Collaborator

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],
Copy link
Collaborator

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))
Copy link
Collaborator

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):
Copy link
Collaborator

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)

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants