Skip to content

Conversation

@MrGeva
Copy link
Collaborator

@MrGeva MrGeva commented Aug 24, 2025

Summary by CodeRabbit

  • Tests
    • Re-enabled backend comparison benchmark to run by default.
    • Added multi-run benchmarking with IQR-based outlier removal and aggregation (average, median, raw values) to reduce variability.
    • Added public test helpers for outlier filtering and robust statistics; per-run aggregated prints emitted when available.
    • Relaxed expected post-forward memory bounds (lowered acceptable free-memory bound by ~2000 MB).
    • Added non-functional commented warmup hints in the benchmark command.

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.

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.

Signed-off-by: Eran Geva <19514940+MrGeva@users.noreply.github.com>
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 24, 2025

📝 Walkthrough

Walkthrough

Added IQR-based outlier removal and multi-run aggregation to the trtllm-bench test: new helpers for outlier filtering and robust stats, a runner that repeats benchmarks and averages results (including KV-cache metrics), widened expected KV-cache free-memory lower bound, and re-enabled the backend comparison test.

Changes

Cohort / File(s) Summary of changes
trtllm-bench test + helpers
tests/unittest/_torch/auto_deploy/unit/singlegpu/test_ad_trtllm_bench.py
- Added IQR outlier removal: remove_outliers_iqr(values: List[float]) and calculate_robust_stats(values: List[float]).
- Added run_multiple_benchmarks_with_outlier_removal(..., num_iterations: int = 10) to run benchmarks repeatedly, collect per-iteration metrics, require a minimum number of successes, average results and KV-cache metrics for autodeploy.
- Modified run_benchmark command construction to include commented warmup flags.
- Relaxed calculate_expected_kv_cache_metrics post-forward free-memory lower bound by 2000 MB.
- Updated trtllm_bench_unified_comparison signature to accept num_iterations and to use the multi-run aggregation for autodeploy and pytorch backends; default backend_relative_tolerance changed from 0.3 to 0.23.
- Expanded prints and outputs to include per-run raw values and aggregated stats; removed previous skip decorator on backend comparison test.
- Added imports: mean, median, List, Tuple.

Sequence Diagram(s)

sequenceDiagram
    participant TestRunner as Test Runner
    participant MultiRun as run_multiple_benchmarks_with_outlier_removal
    participant Bench as run_benchmark
    participant Extract as extract_performance_metric
    participant IQR as remove_outliers_iqr

    TestRunner->>MultiRun: start(model, backend, num_iterations)
    loop each iteration
        MultiRun->>Bench: run_benchmark(...)  %% command includes commented warmup flags
        Bench-->>MultiRun: raw_report.json
        MultiRun->>Extract: extract_performance_metric(raw_report.json)
        Extract-->>MultiRun: metric + kv_cache_metrics
    end
    MultiRun->>IQR: remove_outliers_iqr(all_metrics)
    IQR-->>MultiRun: filtered_metrics
    MultiRun->>MultiRun: calculate_robust_stats(filtered_metrics)
    MultiRun-->>TestRunner: aggregated_report (avg, median, raw_values, kv_cache_averages)
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested reviewers

  • suyoggupta

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 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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai or @coderabbitai title anywhere in the PR title to generate the title automatically.

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@MrGeva MrGeva changed the title [https://nvbugs/5458798][fix] Enlarged the mem reduction threshold post fwd pass Draft: [https://nvbugs/5458798][fix] Enlarged the mem reduction threshold post fwd pass Aug 24, 2025
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: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (3)
tests/unittest/_torch/auto_deploy/unit/singlegpu/test_ad_trtllm_bench.py (3)

1-6: Add NVIDIA copyright header (2025) per repo guidelines.

This file lacks the required NVIDIA header. Please prepend the standard header for 2025 to comply with coding guidelines.

Apply this diff at the top of the file:

+# Copyright (c) 2025, NVIDIA CORPORATION & AFFILIATES. 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.

620-629: Update docstring to reflect the relaxed post-forward memory lower bound.

The docstring still states pre and post are validated against the same range, which is no longer true after widening the post range by 2000 MB. This can mislead future maintainers.

Apply this doc-only diff:

-    1. free_mem_pre_fw_pass and free_mem_post_fw_pass are in:
-       [Total mem - expected_model_size - extra_consumption, Total mem - expected_model_size]
+    1. free_mem_pre_fw_pass is in:
+       [Total mem - expected_model_size - extra_consumption, Total mem - expected_model_size]
+       and free_mem_post_fw_pass is in the same range but with an additional lower-bound slack:
+       [Total mem - expected_model_size - extra_consumption - POST_FWD_FREE_MEM_LOWER_SLACK_MB,
+        Total mem - expected_model_size]

408-419: require_metrics=False still fails the test; fix control flow.

The code promises a soft path (“just warn”) when require_metrics=False, but it unconditionally asserts after printing the warning. This makes the flag ineffective.

Apply this diff:

-    if not kv_cache_metrics:
+    if not kv_cache_metrics:
         message = (
             "KV cache metrics not found! "
             "The autodeploy backend must log memory statistics for this test to pass. "
             f"Expected metrics: {', '.join(required_metrics)}"
         )
-        if require_metrics:
-            assert False, f"REQUIRED {message}"
-        else:
-            print(f"ℹ️ {message}")
-            assert False, "KV cache metrics are missing"
+        if require_metrics:
+            assert False, f"REQUIRED {message}"
+        else:
+            print(f"ℹ️ {message}")
+            return None, None

Do the same for the “missing_metrics” branch (Lines 423-434), returning (None, None) when require_metrics=False instead of asserting.

🧹 Nitpick comments (5)
tests/unittest/_torch/auto_deploy/unit/singlegpu/test_ad_trtllm_bench.py (5)

66-75: Use the current Python interpreter instead of hard-coding python/python3.

Tests should invoke the same interpreter running pytest to avoid environment drift.

Apply these diffs:

@@
-    cmd = [
-        "python",
+    import sys
+    cmd = [
+        sys.executable,
         "-m",
         "tensorrt_llm.commands.bench",
@@
-    command = [
-        "python3",
+    import sys
+    command = [
+        sys.executable,
         f"{dataset_tool}",
         "--stdout",

Also applies to: 239-246


281-286: Elevate magic numbers to named constants and document them.

estimated_model_size_mb = 2200 and extra_consumption_mb = 2700 are critical to range calculations. Promote them to module-level constants with a short comment and reference to the tracking issue for “extra consumption.”

For example:

# TinyLlama model memory footprint estimate (MB). Keep in sync with model/version used.
ESTIMATED_TINYLLAMA_MODEL_SIZE_MB = 2200

# Unexplained overhead observed in CI (MB).
# TODO(egeva): track at https://github.com/NVIDIA/TensorRT-LLM/issues/6335
UNEXPLAINED_EXTRA_CONSUMPTION_MB = 2700

And replace call sites accordingly.


20-23: Make numeric regex more robust to formatted numbers.

If logs ever include thousand separators (commas) or spaces, current patterns will fail. Minor hardening improves resilience without overfitting.

Example tweak:

patterns = {
    "current_cache_size": r"Current cache size:\s*([\d_,]+)",
    "free_mem_pre_mb": r"Free memory before forward pass \(MB\):\s*([\d_,]+)",
    "free_mem_post_mb": r"Free memory after forward pass \(MB\):\s*([\d_,]+)",
}
# and when parsing:
value = int(re.sub(r"[,_]", "", match.group(1)))

101-107: Consider making the benchmark timeout configurable.

A hard 600s timeout can be tight on saturated CI nodes; exposing timeout_s with a sensible default or honoring an env var reduces flakes.

Example:

timeout_s = int(os.getenv("TLLM_BENCH_TIMEOUT_S", "600"))
result = subprocess.run(cmd, capture_output=True, text=True, env=env, timeout=timeout_s)

80-82: Expose warmup via a test parameter and remove dead comments

The --warmup option is already implemented in the benchmarking commands (throughput and low_latency), so we can wire it through the test rather than leaving commented flags.

• File tests/unittest/_torch/auto_deploy/unit/singlegpu/test_ad_trtllm_bench.py, lines 80–82: drop the commented-out warmup args.
• Update the run_benchmark signature (around line 55) to take warmup_iters: int | None = None.
• Immediately after building cmd (right after line 83), append:

if warmup_iters is not None:
    cmd.extend(["--warmup", str(warmup_iters)])

Proposed diff:

--- a/tests/unittest/_torch/auto_deploy/unit/singlegpu/test_ad_trtllm_bench.py
+++ b/tests/unittest/_torch/auto_deploy/unit/singlegpu/test_ad_trtllm_bench.py
@@ -55,7 +55,9 @@ def run_benchmark(..., free_mem_ratio: float = 0.1):
     ...):
         # existing params
+        warmup_iters: int | None = None,
 ):
     cmd = [
         "trtllm-bench",
@@ -76,7 +78,6 @@ def run_benchmark(...):
         "--max_batch_size",
         str(max_batch_size),
-        # "--warmup",
-        # "10",
     ]
+    if warmup_iters is not None:
+        cmd.extend(["--warmup", str(warmup_iters)])
     # rest of test
📜 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.

📥 Commits

Reviewing files that changed from the base of the PR and between 19a0ea3 and 6ce332e.

📒 Files selected for processing (1)
  • tests/unittest/_torch/auto_deploy/unit/singlegpu/test_ad_trtllm_bench.py (2 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.py

📄 CodeRabbit inference engine (CODING_GUIDELINES.md)

**/*.py: Python code must target Python 3.8+
Python indentation: 4 spaces, no tabs
Maintain module namespace in imports (from package.subpackage import foo; then use foo.SomeClass())
Python file names use snake_case
Python class names use PascalCase
Python functions/methods and local variables use snake_case; variables starting with a number get k_ prefix (e.g., k_99th_percentile)
Global variables use G_ prefixed UPPER_SNAKE_CASE (e.g., G_MY_GLOBAL)
Constants use UPPER_SNAKE_CASE in Python
Avoid shadowing variables from outer scopes in Python
Initialize all externally visible members of a Python class in init
Prefer docstrings for interfaces used outside a file; comments for local code
Use Google-style docstrings for classes and functions (Sphinx-parsable)
Document attributes/variables inline with short docstrings
Avoid reflection when simple alternatives exist (e.g., prefer explicit parameters over dict(**locals()))
In try/except, catch the narrowest exceptions possible
For duck-typing with try/except, keep try body minimal and put logic in else

Files:

  • tests/unittest/_torch/auto_deploy/unit/singlegpu/test_ad_trtllm_bench.py
**/*.{cpp,cxx,cc,cu,h,hpp,hxx,hh,cuh,py}

📄 CodeRabbit inference engine (CODING_GUIDELINES.md)

Prepend NVIDIA copyright header (current year) to all source files

Files:

  • tests/unittest/_torch/auto_deploy/unit/singlegpu/test_ad_trtllm_bench.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
⏰ 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

Signed-off-by: Eran Geva <19514940+MrGeva@users.noreply.github.com>
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: 0

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
tests/unittest/_torch/auto_deploy/unit/singlegpu/test_ad_trtllm_bench.py (2)

1-7: Add mandatory NVIDIA copyright header

Per coding guidelines, prepend the NVIDIA copyright header to all source files.

+# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
+
 import json
 import re
 import subprocess
 import tempfile
 from pathlib import Path
-from statistics import mean, median
+from statistics import mean, median
 from typing import List, Tuple

441-495: require_metrics=False still fails via assertion — align behavior with docstring

Docstring says “If False, just warn,” but both the “missing-all” and “missing-some” branches still assert False. Either update the docstring or implement the warning + continue behavior. Suggest implementing the latter by returning (None, None) when non-fatal.

@@ def validate_and_extract_kv_cache_metrics(report_data, free_mem_ratio, require_metrics=True):
-    if not kv_cache_metrics:
+    if not kv_cache_metrics:
         message = (
             "KV cache metrics not found! "
             "The autodeploy backend must log memory statistics for this test to pass. "
             f"Expected metrics: {', '.join(required_metrics)}"
         )
-        if require_metrics:
-            assert False, f"REQUIRED {message}"
-        else:
-            print(f"ℹ️ {message}")
-            assert False, "KV cache metrics are missing"
+        if require_metrics:
+            assert False, f"REQUIRED {message}"
+        else:
+            print(f"ℹ️ {message}")
+            return None, None
@@
-    if missing_metrics:
+    if missing_metrics:
         message = (
             f"Missing required KV cache metrics: {missing_metrics}. "
             f"Found metrics: {list(kv_cache_metrics.keys())}. "
             f"All of {required_metrics} are required for the test to pass."
         )
-        if require_metrics:
-            assert False, message
-        else:
-            print(f"ℹ️ KV cache validation skipped - {message}")
-            assert False, "KV cache metrics are missing"
+        if require_metrics:
+            assert False, message
+        else:
+            print(f"ℹ️ KV cache validation skipped - {message}")
+            return None, None

Follow-up: In call sites that pass require_metrics=False (if any in future), handle (None, None) gracefully.

♻️ Duplicate comments (1)
tests/unittest/_torch/auto_deploy/unit/singlegpu/test_ad_trtllm_bench.py (1)

350-353: Make post-forward free-memory slack explicit and clamped (duplicate of prior feedback)

Reiterating earlier feedback: don’t hard-code 2000 inline. Name the slack and clamp to zero to be safe on small GPUs. Optionally scale by total VRAM if flakiness persists.

-            expected_free_mem_post_range = (
-                expected_free_mem_range[0] - 2000,
-                expected_free_mem_range[1],
-            )
+            lower_slack_mb = POST_FWD_FREE_MEM_LOWER_SLACK_MB
+            expected_free_mem_post_range = (
+                max(0, expected_free_mem_range[0] - lower_slack_mb),
+                expected_free_mem_range[1],
+            )

Add the constant near the imports:

# Tolerance for additional memory reduction after forward pass (MB)
POST_FWD_FREE_MEM_LOWER_SLACK_MB = 2000
🧹 Nitpick comments (6)
tests/unittest/_torch/auto_deploy/unit/singlegpu/test_ad_trtllm_bench.py (6)

16-53: IQR outlier filter: use proper quartiles and handle non-finite values

Current Q1/Q3 calculations use index-based pick which is a rough proxy and can be brittle on small samples. Also, NaN/Inf inputs will propagate and break mean/median later. Use statistics.quantiles and ignore non-finite values. Keep order stability by filtering from the finite list.

 def remove_outliers_iqr(values: List[float]) -> List[float]:
@@
-    if len(values) < 4:  # Need at least 4 values for meaningful IQR
-        return values
-
-    sorted_values = sorted(values)
-    n = len(sorted_values)
-    q1 = sorted_values[n // 4]
-    q3 = sorted_values[3 * n // 4]
+    # Drop non-finite values up-front
+    import math
+    finite_values = [v for v in values if isinstance(v, (int, float)) and math.isfinite(v)]
+    if len(finite_values) < 4:  # Need at least 4 values for meaningful IQR
+        return finite_values
+
+    sorted_values = sorted(finite_values)
+    # Proper quartiles (Python 3.8+); returns [Q1, Q2, Q3] for n=4
+    from statistics import quantiles
+    q1, q3 = quantiles(sorted_values, n=4)[0], quantiles(sorted_values, n=4)[2]
@@
-    filtered_values = [v for v in values if lower_bound <= v <= upper_bound]
+    filtered_values = [v for v in finite_values if lower_bound <= v <= upper_bound]
@@
-    if len(filtered_values) < len(values) // 2:
-        removed_str = f"{len(values) - len(filtered_values)}/{len(values)}"
+    if len(filtered_values) < len(finite_values) // 2:
+        removed_str = f"{len(finite_values) - len(filtered_values)}/{len(finite_values)}"
         print(f"⚠️  IQR filtering would remove too many values ({removed_str}), keeping all")
-        return values
+        return finite_values
@@
-    removed_count = len(values) - len(filtered_values)
+    removed_count = len(finite_values) - len(filtered_values)

If you'd rather avoid an extra import inside the function, we can lift quantiles into the module imports alongside mean, median.


55-67: Guard against empty inputs after filtering

If all values are non-finite or filtered out, mean/median will raise. Be explicit and fail fast with a clear message. Keeps the helper robust.

 def calculate_robust_stats(values: List[float]) -> Tuple[float, float, int]:
@@
-    filtered_values = remove_outliers_iqr(values)
+    filtered_values = remove_outliers_iqr(values)
+    if not filtered_values:
+        raise ValueError("No valid values to compute statistics after outlier removal.")
     return mean(filtered_values), median(filtered_values), len(filtered_values)

133-137: Replace commented warmup flags with a parameter

Commented CLI flags are easy to forget and add noise. Introduce a warmup_steps parameter and append the flags only when non-zero. Default remains no warmup.

 def run_benchmark(
@@
-    free_mem_ratio: float = 0.1,
+    free_mem_ratio: float = 0.1,
+    warmup_steps: int = 0,
 ):
@@
-    cmd = [
+    cmd = [
         "python",
@@
         "--max_batch_size",
         str(max_batch_size),
-        # "--warmup",
-        # "10",
     ]
+    if warmup_steps > 0:
+        cmd.extend(["--warmup", str(warmup_steps)])

534-547: Avoid stale report reads: use per-iteration report_json_path

Reusing the same JSON path across iterations risks reading a stale/partial report if a write fails. Emit a unique file per iteration (e.g., suffix _1.json, _2.json, …).

     for i in range(num_iterations):
         try:
             print(f"🔄 Iteration {i + 1}/{num_iterations}")
-            report_data = run_benchmark(
+            iter_report_path = report_json_path
+            if report_json_path:
+                base = Path(report_json_path)
+                iter_report_path = str(base.with_name(f"{base.stem}_{i + 1}{base.suffix}"))
+            report_data = run_benchmark(
                 model_name,
                 dataset_path,
                 temp_dir,
                 backend,
-                report_json_path,
+                iter_report_path,
                 max_batch_size,
                 num_hidden_layers,
                 free_mem_ratio,
             )

630-651: Make num_iterations adjustable via env to keep CI time reasonable

Ten iterations per backend can be heavy in CI. Allow overrides via an env var while keeping the default. This also makes the docstring’s “default 10” accurate even when overridden.

 def trtllm_bench_unified_comparison(
@@
-    num_iterations=10,
+    num_iterations=10,
 ):
@@
-    Args:
+    Args:
@@
-        num_iterations: Number of benchmark iterations to run (default 10)
+        num_iterations: Number of benchmark iterations to run (default 10; override with env TRTLLM_BENCH_NUM_ITERATIONS)
     """
+    import os
+    num_iterations = int(os.getenv("TRTLLM_BENCH_NUM_ITERATIONS", num_iterations))

806-809: Docstring: don’t hardcode “10 times”

Reflect the parameterized behavior, especially with the suggested env override.

-    This test runs both backends 10 times each, removes outliers using IQR method,
+    This test runs both backends num_iterations times (default 10), removes outliers using IQR method,
📜 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.

📥 Commits

Reviewing files that changed from the base of the PR and between 6ce332e and 9a03004.

📒 Files selected for processing (1)
  • tests/unittest/_torch/auto_deploy/unit/singlegpu/test_ad_trtllm_bench.py (14 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.py

📄 CodeRabbit inference engine (CODING_GUIDELINES.md)

**/*.py: Python code must target Python 3.8+
Python indentation: 4 spaces, no tabs
Maintain module namespace in imports (from package.subpackage import foo; then use foo.SomeClass())
Python file names use snake_case
Python class names use PascalCase
Python functions/methods and local variables use snake_case; variables starting with a number get k_ prefix (e.g., k_99th_percentile)
Global variables use G_ prefixed UPPER_SNAKE_CASE (e.g., G_MY_GLOBAL)
Constants use UPPER_SNAKE_CASE in Python
Avoid shadowing variables from outer scopes in Python
Initialize all externally visible members of a Python class in init
Prefer docstrings for interfaces used outside a file; comments for local code
Use Google-style docstrings for classes and functions (Sphinx-parsable)
Document attributes/variables inline with short docstrings
Avoid reflection when simple alternatives exist (e.g., prefer explicit parameters over dict(**locals()))
In try/except, catch the narrowest exceptions possible
For duck-typing with try/except, keep try body minimal and put logic in else

Files:

  • tests/unittest/_torch/auto_deploy/unit/singlegpu/test_ad_trtllm_bench.py
**/*.{cpp,cxx,cc,cu,h,hpp,hxx,hh,cuh,py}

📄 CodeRabbit inference engine (CODING_GUIDELINES.md)

Prepend NVIDIA copyright header (current year) to all source files

Files:

  • tests/unittest/_torch/auto_deploy/unit/singlegpu/test_ad_trtllm_bench.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 (1)
tests/unittest/_torch/auto_deploy/unit/singlegpu/test_ad_trtllm_bench.py (3)
tests/unittest/llmapi/apps/_test_trtllm_serve_benchmark.py (1)
  • dataset_path (37-42)
tests/unittest/_torch/auto_deploy/unit/singlegpu/utils/test_config.py (1)
  • temp_dir (67-70)
tests/unittest/llmapi/apps/_test_openai_misc.py (1)
  • max_batch_size (30-31)
⏰ 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 (1)
tests/unittest/_torch/auto_deploy/unit/singlegpu/test_ad_trtllm_bench.py (1)

671-683: LGTM: Multi-run with outlier removal for autodeploy is a solid stabilization

Good move to aggregate multiple runs and reduce variance before comparing/validating. The signature and plumbing look coherent.

@MrGeva MrGeva changed the title Draft: [https://nvbugs/5458798][fix] Enlarged the mem reduction threshold post fwd pass [https://nvbugs/5458798][fix] Compare 10 runs perf using IQR method. Enlarged the mem reduction threshold post fwd pass. Aug 24, 2025
@MrGeva MrGeva changed the title [https://nvbugs/5458798][fix] Compare 10 runs perf using IQR method. Enlarged the mem reduction threshold post fwd pass. [https://nvbugs/5458798][fix] AD perf test to compare 10 perf runs using IQR method. Enlarged the mem reduction threshold post fwd pass. Aug 24, 2025
@MrGeva
Copy link
Collaborator Author

MrGeva commented Aug 24, 2025

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #16315 [ run ] triggered by Bot

Signed-off-by: Eran Geva <19514940+MrGeva@users.noreply.github.com>
@MrGeva MrGeva changed the title [https://nvbugs/5458798][fix] AD perf test to compare 10 perf runs using IQR method. Enlarged the mem reduction threshold post fwd pass. [https://nvbugs/5458798][fix] AD perf test to handle outliers, thightened the threshold Aug 24, 2025
@MrGeva MrGeva changed the title [https://nvbugs/5458798][fix] AD perf test to handle outliers, thightened the threshold [https://nvbugs/5458798][fix] AD perf test outliers handling, tightened threshold, re-enabled in CI, fixed mem threshold Aug 24, 2025
@MrGeva
Copy link
Collaborator Author

MrGeva commented Aug 24, 2025

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #16317 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #16315 [ run ] completed with state ABORTED

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: 1

♻️ Duplicate comments (1)
tests/unittest/_torch/auto_deploy/unit/singlegpu/test_ad_trtllm_bench.py (1)

350-353: Make post-forward free-memory slack explicit and safe for small GPUs.

Use a named constant and clamp to zero to prevent negative lower bounds. This also documents intent.

Apply this diff:

-            expected_free_mem_post_range = (
-                expected_free_mem_range[0] - 2000,
-                expected_free_mem_range[1],
-            )
+            expected_free_mem_post_range = (
+                max(0, expected_free_mem_range[0] - POST_FWD_FREE_MEM_LOWER_SLACK_MB),
+                expected_free_mem_range[1],
+            )

And define the constant near the imports:

# Tolerance for additional memory reduction after forward pass (in MB)
POST_FWD_FREE_MEM_LOWER_SLACK_MB = 2000
🧹 Nitpick comments (6)
tests/unittest/_torch/auto_deploy/unit/singlegpu/test_ad_trtllm_bench.py (6)

16-53: Make IQR computation statistically robust and ignore non-finite values.

  • Using positional quartiles via indices (n//4, 3n//4) is sensitive to sample size and distribution; prefer statistics.quantiles for true quartiles.
  • Filter out NaN/Inf before computing IQR to avoid propagating invalid values.

Apply this diff:

-from statistics import mean, median
+from statistics import mean, median, quantiles
+import math
@@
-    sorted_values = sorted(values)
-    n = len(sorted_values)
-    q1 = sorted_values[n // 4]
-    q3 = sorted_values[3 * n // 4]
+    # Drop NaN/Inf to avoid skewing the stats
+    values = [v for v in values if math.isfinite(v)]
+    if len(values) < 4:
+        return values
+    sorted_values = sorted(values)
+    # Use statistics.quantiles for robust quartiles (Q1, Q2, Q3)
+    qs = quantiles(sorted_values, n=4, method="inclusive")
+    q1, q3 = qs[0], qs[2]

55-67: Guard against degenerate filtering and consider returning the filtered sample.

If an extreme distribution still empties filtered_values (e.g., all identical and considered outliers due to upstream error), mean/median would raise. While your >3 successful runs gate makes this unlikely, a defensive fallback helps and retaining the filtered list aids debugging.

Apply this minimal safety net:

-    filtered_values = remove_outliers_iqr(values)
-    return mean(filtered_values), median(filtered_values), len(filtered_values)
+    filtered_values = remove_outliers_iqr(values)
+    if not filtered_values:
+        # Fallback to raw values to avoid StatsError; also signals extreme filtering.
+        filtered_values = values
+    return mean(filtered_values), median(filtered_values), len(filtered_values)

Optionally, return the filtered list so callers can print exactly which values were used.


135-136: Replace commented warmup flags with a parameter.

Commented CLI flags add noise and can rot. Make warmup configurable so you can enable it without editing code.

Apply these changes:

-def run_benchmark(
+from typing import Optional
+
+def run_benchmark(
@@
-    free_mem_ratio: float = 0.1,
+    free_mem_ratio: float = 0.1,
+    warmup_iters: Optional[int] = None,
 ):
@@
-    cmd = [
+    cmd = [
         "python",
         "-m",
         "tensorrt_llm.commands.bench",
@@
-        "--max_batch_size",
+        "--max_batch_size",
         str(max_batch_size),
-        # "--warmup",
-        # "10",
     ]
+    if warmup_iters:
+        cmd.extend(["--warmup", str(warmup_iters)])

If you also adopt the sys.executable suggestion below, replace "python" accordingly.


69-101: Make default free_mem_ratio consistent across helpers.

parse_kv_cache_metrics defaults free_mem_ratio to 0.8, while the rest use 0.1. You pass it explicitly today, but aligning defaults avoids future footguns.

Apply this small change:

-def parse_kv_cache_metrics(log_output: str, free_mem_ratio: float = 0.8):
+def parse_kv_cache_metrics(log_output: str, free_mem_ratio: float = 0.1):

121-157: Use sys.executable for subprocess Python invocations.

Using the current interpreter avoids environment mismatches (e.g., “python” vs “python3”).

Apply this diff:

+import sys
@@
-    cmd = [
-        "python",
+    cmd = [
+        sys.executable,
         "-m",
         "tensorrt_llm.commands.bench",
@@
-    command = [
-        "python3",
+    command = [
+        sys.executable,
         f"{dataset_tool}",

441-489: Docstring says “just warn” when require_metrics=False, but code still fails.

The current implementation asserts even when require_metrics=False. Align behavior and docs to avoid surprises.

Apply this diff:

-    if not kv_cache_metrics:
+    if not kv_cache_metrics:
         message = (
             "KV cache metrics not found! "
             "The autodeploy backend must log memory statistics for this test to pass. "
             f"Expected metrics: {', '.join(required_metrics)}"
         )
-        if require_metrics:
-            assert False, f"REQUIRED {message}"
-        else:
-            print(f"ℹ️ {message}")
-            assert False, "KV cache metrics are missing"
+        if require_metrics:
+            assert False, f"REQUIRED {message}"
+        else:
+            print(f"ℹ️ {message}")
+            return None, None
@@
-    if missing_metrics:
+    if missing_metrics:
         message = (
             f"Missing required KV cache metrics: {missing_metrics}. "
             f"Found metrics: {list(kv_cache_metrics.keys())}. "
             f"All of {required_metrics} are required for the test to pass."
         )
-        if require_metrics:
-            assert False, message
-        else:
-            print(f"ℹ️ KV cache validation skipped - {message}")
-            assert False, "KV cache metrics are missing"
+        if require_metrics:
+            assert False, message
+        else:
+            print(f"ℹ️ KV cache validation skipped - {message}")
+            return None, None
📜 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.

📥 Commits

Reviewing files that changed from the base of the PR and between 9a03004 and 05e3b6f.

📒 Files selected for processing (1)
  • tests/unittest/_torch/auto_deploy/unit/singlegpu/test_ad_trtllm_bench.py (13 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.py

📄 CodeRabbit inference engine (CODING_GUIDELINES.md)

**/*.py: Python code must target Python 3.8+
Python indentation: 4 spaces, no tabs
Maintain module namespace in imports (from package.subpackage import foo; then use foo.SomeClass())
Python file names use snake_case
Python class names use PascalCase
Python functions/methods and local variables use snake_case; variables starting with a number get k_ prefix (e.g., k_99th_percentile)
Global variables use G_ prefixed UPPER_SNAKE_CASE (e.g., G_MY_GLOBAL)
Constants use UPPER_SNAKE_CASE in Python
Avoid shadowing variables from outer scopes in Python
Initialize all externally visible members of a Python class in init
Prefer docstrings for interfaces used outside a file; comments for local code
Use Google-style docstrings for classes and functions (Sphinx-parsable)
Document attributes/variables inline with short docstrings
Avoid reflection when simple alternatives exist (e.g., prefer explicit parameters over dict(**locals()))
In try/except, catch the narrowest exceptions possible
For duck-typing with try/except, keep try body minimal and put logic in else

Files:

  • tests/unittest/_torch/auto_deploy/unit/singlegpu/test_ad_trtllm_bench.py
**/*.{cpp,cxx,cc,cu,h,hpp,hxx,hh,cuh,py}

📄 CodeRabbit inference engine (CODING_GUIDELINES.md)

Prepend NVIDIA copyright header (current year) to all source files

Files:

  • tests/unittest/_torch/auto_deploy/unit/singlegpu/test_ad_trtllm_bench.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 (1)
tests/unittest/_torch/auto_deploy/unit/singlegpu/test_ad_trtllm_bench.py (3)
tests/unittest/llmapi/apps/_test_trtllm_serve_benchmark.py (1)
  • dataset_path (37-42)
tests/unittest/_torch/auto_deploy/unit/singlegpu/utils/test_config.py (1)
  • temp_dir (67-70)
tests/unittest/llmapi/apps/_test_openai_misc.py (1)
  • max_batch_size (30-31)
⏰ 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 (10)
tests/unittest/_torch/auto_deploy/unit/singlegpu/test_ad_trtllm_bench.py (10)

6-7: LGTM: targeted imports for statistics and typing.

Imports are minimal and Python 3.8+ compatible.


671-683: Autodeploy multi-run aggregation: 👍

Switching autodeploy to multi-run with outlier removal before comparison reduces flakiness and improves signal quality.


694-706: PyTorch multi-run aggregation: 👍

Symmetric handling for PyTorch makes the backend comparison fair and robust.


724-737: Helpful reporting of averages and raw values.

Printing both aggregated metrics and raw per-run values is valuable for triaging regressions.


742-745: Golden-mode summary formatting: 👍

Clear, concise output; matches the multi-run semantics.


749-752: Expose raw values in golden mode as well.

Good symmetry with backend mode; keeps debugging easy.


771-774: Final pass messages read well.

Concise end-of-test summary with the averaged performance figure.


806-809: Docstring updates reflect the new multi-run + IQR behavior.

Accurate and helpful for future maintainers.


626-631: Verify tightened backend tolerance and iteration count on CI

The sandbox environment wasn’t able to run the pytest command (pytest: command not found), so please perform the following verifications on your CI (with real GPU SKUs and load) to ensure the new tolerances and iteration count don’t introduce flakiness or excessive runtimes:

• Run the backend comparison test across all supported GPU SKUs:

export AD_BENCH_NUM_ITERATIONS=5
python -m pytest -q tests/unittest/_torch/auto_deploy/unit/singlegpu/test_ad_trtllm_bench.py::test_trtllm_bench_backend_comparison -k backend -s

– Confirm that the relative differences stay within the tightened tolerance (backend_relative_tolerance=0.23) and that runtime remains acceptable.
• If any failures or large variances occur, consider loosening the tolerance or increasing iteration count.
• Once stability is confirmed, merge the change; otherwise, adjust the values to fit your CI variance budget.

Optional refactor to allow CI-driven iteration overrides:

 def trtllm_bench_unified_comparison(
@@
-    num_iterations=10,
+    num_iterations=10,
 ):
@@
     # Allow CI to override iterations without code changes
+    import os as _os
+    try:
+        num_iterations = int(_os.getenv("AD_BENCH_NUM_ITERATIONS", num_iterations))
+    except ValueError:
+        pass

1-1: Prepend NVIDIA Copyright Header

To align with existing test files, add the standard 2025 © NVIDIA header at the very top of tests/unittest/_torch/auto_deploy/unit/singlegpu/test_ad_trtllm_bench.py. For example:

+#!/usr/bin/env python3
+# Copyright 2025, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+# SPDX-License-Identifier: Apache-2.0
+
 import json

Points to verify:

  • Shebang style (#!/usr/bin/env python3) matches other Python tests.

  • Use the exact copyright line from triton_backend/tools/tests/test_llmapi_cancel.py:

    # Copyright 2025, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
    # SPDX-License-Identifier: Apache-2.0
    
  • Ensure a blank line after the header before imports.

Please apply this diff at the top of the file.

@tensorrt-cicd
Copy link
Collaborator

PR_Github #16317 [ run ] completed with state SUCCESS
/LLM/main/L0_MergeRequest_PR pipeline #12269 completed with status: 'SUCCESS'
Pipeline passed with automatic retried tests. Check the rerun report for details.

@MrGeva MrGeva self-assigned this Aug 25, 2025
@MrGeva MrGeva requested review from lucaslie and suyoggupta August 25, 2025 06:16
Signed-off-by: Eran Geva <19514940+MrGeva@users.noreply.github.com>
@MrGeva
Copy link
Collaborator Author

MrGeva commented Aug 26, 2025

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #16565 [ run ] triggered by Bot

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: 0

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
tests/unittest/_torch/auto_deploy/unit/singlegpu/test_ad_trtllm_bench.py (2)

1-1: Missing required NVIDIA copyright header

Per coding guidelines, prepend the NVIDIA copyright header (current year) to all .py files.

Apply this diff at the top of the file:

+# Copyright (c) 2025, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+
 import json
 import re
 import subprocess
 import tempfile
 from pathlib import Path

468-479: Docstring vs behavior mismatch for require_metrics=False — don't assert, return (None, None)

The function promises a non-failing path when require_metrics=False, but it still asserts. Align behavior to docstring and return (None, None) while logging.

-    Returns:
-        Tuple of (kv_cache_metrics, expected_metrics) or (None, None) if validation fails
+    Returns:
+        Tuple of (kv_cache_metrics, expected_metrics) or (None, None) if validation is skipped or fails
@@
     if not kv_cache_metrics:
         message = (
             "KV cache metrics not found! "
             "The autodeploy backend must log memory statistics for this test to pass. "
             f"Expected metrics: {', '.join(required_metrics)}"
         )
         if require_metrics:
             assert False, f"REQUIRED {message}"
         else:
             print(f"ℹ️ {message}")
-            assert False, "KV cache metrics are missing"
+            return None, None
@@
     if missing_metrics:
         message = (
             f"Missing required KV cache metrics: {missing_metrics}. "
             f"Found metrics: {list(kv_cache_metrics.keys())}. "
             f"All of {required_metrics} are required for the test to pass."
         )
         if require_metrics:
             assert False, message
         else:
             print(f"ℹ️ KV cache validation skipped - {message}")
-            assert False, "KV cache metrics are missing"
+            return None, None

Also applies to: 489-494, 456-457

♻️ Duplicate comments (2)
tests/unittest/_torch/auto_deploy/unit/singlegpu/test_ad_trtllm_bench.py (2)

353-358: Nice: headroom slack extracted and lower bound clamped

Using POST_FWD_FREE_MEM_LOWER_SLACK_MB and max(0, ...) clarifies intent and prevents negative ranges. This addresses the earlier suggestion.


539-552: Reuse of a single report_json risks stale/cross-run reads — generate per-iteration paths

If a run fails to write, reusing the same report_json will parse a stale file from a previous iteration. Use a unique file per iteration and optionally clean it up after a successful parse.

     for i in range(num_iterations):
         try:
             print(f"🔄 Iteration {i + 1}/{num_iterations}")
-            report_data = run_benchmark(
+            base = Path(report_json_path) if report_json_path else None
+            iter_report_path = (
+                str(base.with_name(f"{base.stem}.iter{i+1}{base.suffix}"))
+                if base is not None else None
+            )
+            report_data = run_benchmark(
                 model_name,
                 dataset_path,
                 temp_dir,
                 backend,
-                report_json_path,
+                iter_report_path,
                 max_batch_size,
                 num_hidden_layers,
                 free_mem_ratio,
             )
@@
             if report_data and "performance" in report_data:
                 tokens_per_sec = extract_performance_metric(report_data, f"{backend}_iter_{i + 1}")
                 performance_values.append(tokens_per_sec)
@@
                 successful_runs += 1
                 print(f"  ✅ Iteration {i + 1}: {tokens_per_sec:.2f} tokens/sec/user")
+                # Best-effort cleanup of per-iteration report file to avoid clutter
+                try:
+                    if iter_report_path:
+                        Path(iter_report_path).unlink(missing_ok=True)
+                except Exception:
+                    pass
             else:
                 print(f"  ❌ Iteration {i + 1}: Failed to get valid report")

Also applies to: 561-565

🧹 Nitpick comments (5)
tests/unittest/_torch/auto_deploy/unit/singlegpu/test_ad_trtllm_bench.py (5)

6-7: Preserve module namespaces for imports and adjust references accordingly

Guidelines prefer importing modules and accessing members via the module to avoid polluting the global namespace. Switch to module-level imports and update usages.

-from statistics import mean, median
-from typing import List, Tuple
+import statistics as stats
+import typing as t
@@
-def remove_outliers_iqr(values: List[float]) -> List[float]:
+def remove_outliers_iqr(values: t.List[float]) -> t.List[float]:
@@
-def calculate_robust_stats(values: List[float]) -> Tuple[float, float, int]:
+def calculate_robust_stats(values: t.List[float]) -> t.Tuple[float, float, int]:
@@
-    return mean(filtered_values), median(filtered_values), len(filtered_values)
+    return stats.mean(filtered_values), stats.median(filtered_values), len(filtered_values)

Also applies to: 19-19, 58-59, 68-69


33-41: Use robust quartile computation for small-N samples

Computing Q1/Q3 via simple indexing can be unstable for small sample sizes. Use statistics.quantiles with method="inclusive" to improve robustness (Python 3.8+).

-    sorted_values = sorted(values)
-    n = len(sorted_values)
-    q1 = sorted_values[n // 4]
-    q3 = sorted_values[3 * n // 4]
-    iqr = q3 - q1
+    sorted_values = sorted(values)
+    quartiles = stats.quantiles(sorted_values, n=4, method="inclusive")
+    q1, q3 = quartiles[0], quartiles[2]
+    iqr = q3 - q1

138-139: Avoid leaving commented-out CLI flags; make warmup configurable or remove

Commented args add noise and can confuse future readers. Either wire warmup via a parameter or remove the dead code.

Option A (remove now):

-        # "--warmup",
-        # "10",

Option B (if you want it soon): add a warmup_steps: int = 0 param and append only when > 0.


352-353: Clamp pre-forward free-memory lower bound to 0 as well

You already clamp the post-forward lower bound; apply the same to pre-forward to avoid negative ranges on small GPUs.

-            expected_free_mem_pre_range = expected_free_mem_range
+            expected_free_mem_pre_range = (
+                max(0, expected_free_mem_range[0]),
+                expected_free_mem_range[1],
+            )

125-140: Use sys.executable to ensure the same interpreter is used for subprocesses

Calling "python"/"python3" may invoke a different interpreter than the running test. Use sys.executable for portability and hermeticity.

+import sys
@@
-    cmd = [
-        "python",
+    cmd = [
+        sys.executable,
         "-m",
         "tensorrt_llm.commands.bench",
@@
-    command = [
-        "python3",
+    command = [
+        sys.executable,
         f"{dataset_tool}",
         "--stdout",

Also applies to: 297-301

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

📥 Commits

Reviewing files that changed from the base of the PR and between 05e3b6f and 79e8d33.

📒 Files selected for processing (1)
  • tests/unittest/_torch/auto_deploy/unit/singlegpu/test_ad_trtllm_bench.py (12 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.py

📄 CodeRabbit inference engine (CODING_GUIDELINES.md)

**/*.py: Code must target Python 3.8+
Indent Python code with 4 spaces; do not use tabs
Preserve module namespaces when importing; import modules/packages and access members via the module (e.g., from package.subpackage import foo; foo.SomeClass())
Python file names should be snake_case
Python class names should be PascalCase
Python functions/methods and local variables should be snake_case; variables beginning with a number should be prefixed with k_ (e.g., k_99th_percentile)
Global variables should be UPPER_SNAKE_CASE prefixed with G_ (e.g., G_MY_GLOBAL); constants should be UPPER_SNAKE_CASE
Avoid shadowing variables from outer scopes; initialize all externally visible members in init
Prefer docstrings for interfaces used outside a file; comments should be reserved for in-function or file-local interfaces
Use Google-style docstrings for classes and functions; attributes and variables may be documented inline with trailing string literals
Avoid reflection when simpler, explicit code suffices (e.g., avoid dict(**locals()) patterns)
In try/except, catch the narrowest exceptions possible
For duck-typing patterns, keep the try body minimal and move logic to else to avoid masking unrelated failures

Files:

  • tests/unittest/_torch/auto_deploy/unit/singlegpu/test_ad_trtllm_bench.py
**/*.{c,cc,cpp,cxx,h,hh,hpp,hxx,cu,cuh,py}

📄 CodeRabbit inference engine (CODING_GUIDELINES.md)

Prepend the NVIDIA copyright header (current year) to all source files (.cpp, .h, .cu, .py, etc.)

Files:

  • tests/unittest/_torch/auto_deploy/unit/singlegpu/test_ad_trtllm_bench.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 (1)
tests/unittest/_torch/auto_deploy/unit/singlegpu/test_ad_trtllm_bench.py (2)
tests/unittest/_torch/auto_deploy/_utils_test/_model_test_utils.py (1)
  • _hf_model_dir_or_hub_id (266-273)
tests/unittest/_torch/auto_deploy/unit/singlegpu/utils/test_config.py (1)
  • temp_dir (67-70)
⏰ 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 (1)
tests/unittest/_torch/auto_deploy/unit/singlegpu/test_ad_trtllm_bench.py (1)

631-636: Confirm intent: backend_relative_tolerance=0.23 is tighter than 0.30 but looser than compare() default 0.20

If the goal is to tighten relative to the prior test setting (0.30), 0.23 matches the PR title. If the intent was to be as tight or tighter than the compare_backends_performance default (0.20), consider lowering to 0.20.

Would you like me to update this to 0.20, or keep 0.23 as a middle ground given multi-run averaging?

@tensorrt-cicd
Copy link
Collaborator

PR_Github #16565 [ run ] completed with state FAILURE
/LLM/main/L0_MergeRequest_PR pipeline #12439 completed with status: 'FAILURE'

@MrGeva
Copy link
Collaborator Author

MrGeva commented Aug 27, 2025

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #16649 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #16649 [ run ] completed with state SUCCESS
/LLM/main/L0_MergeRequest_PR pipeline #12500 completed with status: 'SUCCESS'

@suyoggupta suyoggupta merged commit 462169b into NVIDIA:main Aug 27, 2025
5 checks passed
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.

3 participants