Skip to content

Conversation

@zhanghaotong
Copy link
Contributor

@zhanghaotong zhanghaotong commented Nov 18, 2025

Summary by CodeRabbit

Release Notes

  • New Features
    • Introduced configurable iteration result size limit (default: 16384) to enable users to optimize memory consumption and control resource allocation during model execution. This enhancement supports bounded-size storage for runtime iteration results, improving memory efficiency across inference workflows while maintaining backward compatibility with existing configurations.

Description

We discovered that when TRT runs without ever calling the /metrics API (which we do not invoke in production), the _iter_stats_result queue in the executor keeps growing indefinitely until it causes an OOM error. To address this, we introduced a max_iteration_result_size parameter to cap the queue size. When the queue reaches its maximum capacity, the oldest results are automatically discarded.

Before the fix, memory utilization kept increasing.
image

After the fix, the results are still under stress testing, coming soon~

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

  • Update tava architecture diagram if there is a significant design change in PR.

  • The reviewers assigned automatically/manually are appropriate for the PR.

  • Please check this after reviewing the above items as appropriate for this PR.

GitHub Bot Help

/bot [-h] ['run', 'kill', 'skip', 'reuse-pipeline'] ...

Provide a user friendly way for developers to interact with a Jenkins server.

Run /bot [-h|--help] to print this help message.

See details below for each supported subcommand.

run [--reuse-test (optional)pipeline-id --disable-fail-fast --skip-test --stage-list "A10-PyTorch-1, xxx" --gpu-type "A30, H100_PCIe" --test-backend "pytorch, cpp" --add-multi-gpu-test --only-multi-gpu-test --disable-multi-gpu-test --post-merge --extra-stage "H100_PCIe-TensorRT-Post-Merge-1, xxx" --detailed-log --debug(experimental)]

Launch build/test pipelines. All previously running jobs will be killed.

--reuse-test (optional)pipeline-id (OPTIONAL) : Allow the new pipeline to reuse build artifacts and skip successful test stages from a specified pipeline or the last pipeline if no pipeline-id is indicated. If the Git commit ID has changed, this option will be always ignored. The DEFAULT behavior of the bot is to reuse build artifacts and successful test results from the last pipeline.

--disable-reuse-test (OPTIONAL) : Explicitly prevent the pipeline from reusing build artifacts and skipping successful test stages from a previous pipeline. Ensure that all builds and tests are run regardless of previous successes.

--disable-fail-fast (OPTIONAL) : Disable fail fast on build/tests/infra failures.

--skip-test (OPTIONAL) : Skip all test stages, but still run build stages, package stages and sanity check stages. Note: Does NOT update GitHub check status.

--stage-list "A10-PyTorch-1, xxx" (OPTIONAL) : Only run the specified test stages. Examples: "A10-PyTorch-1, xxx". Note: Does NOT update GitHub check status.

--gpu-type "A30, H100_PCIe" (OPTIONAL) : Only run the test stages on the specified GPU types. Examples: "A30, H100_PCIe". Note: Does NOT update GitHub check status.

--test-backend "pytorch, cpp" (OPTIONAL) : Skip test stages which don't match the specified backends. Only support [pytorch, cpp, tensorrt, triton]. Examples: "pytorch, cpp" (does not run test stages with tensorrt or triton backend). Note: Does NOT update GitHub pipeline status.

--only-multi-gpu-test (OPTIONAL) : Only run the multi-GPU tests. Note: Does NOT update GitHub check status.

--disable-multi-gpu-test (OPTIONAL) : Disable the multi-GPU tests. Note: Does NOT update GitHub check status.

--add-multi-gpu-test (OPTIONAL) : Force run the multi-GPU tests in addition to running L0 pre-merge pipeline.

--post-merge (OPTIONAL) : Run the L0 post-merge pipeline instead of the ordinary L0 pre-merge pipeline.

--extra-stage "H100_PCIe-TensorRT-Post-Merge-1, xxx" (OPTIONAL) : Run the ordinary L0 pre-merge pipeline and specified test stages. Examples: --extra-stage "H100_PCIe-TensorRT-Post-Merge-1, xxx".

--detailed-log (OPTIONAL) : Enable flushing out all logs to the Jenkins console. This will significantly increase the log volume and may slow down the job.

--debug (OPTIONAL) : Experimental feature. Enable access to the CI container for debugging purpose. Note: Specify exactly one stage in 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.

@zhanghaotong zhanghaotong requested a review from a team as a code owner November 18, 2025 07:43
@zhanghaotong zhanghaotong requested a review from hchings November 18, 2025 07:43
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Nov 18, 2025

📝 Walkthrough

Walkthrough

A new max_iteration_result_size parameter is propagated through the executor initialization chain from user-facing API configuration down to bounded queue creation in iteration result storage.

Changes

Cohort / File(s) Summary
Configuration Layer
tensorrt_llm/llmapi/llm_args.py
Added max_iteration_result_size: int field to BaseLlmArgs with default value 16384
Executor Configuration
tensorrt_llm/executor/postproc_worker.py
Added max_iteration_result_size: int = 0 field to PostprocWorkerConfig
Parameter Threading
tensorrt_llm/executor/executor.py, tensorrt_llm/executor/proxy.py, tensorrt_llm/executor/rpc_proxy.py
Updated constructor signatures to accept and forward max_iteration_result_size from PostprocWorkerConfig to parent class initialization
Base Worker
tensorrt_llm/executor/base_worker.py
Forwards max_iteration_result_size from PostprocWorkerConfig to parent constructor
Result Storage
tensorrt_llm/executor/result.py
Modified IterationResult.__init__ signature to accept maxsize: int = 0 parameter; queue initialization now respects maxsize for AsyncQueue and standard Queue
Queue Implementation
tensorrt_llm/llmapi/utils.py
Updated AsyncQueue.__init__ to accept maxsize: int = None parameter; deque initialization now uses maxsize
Backend Integration
tensorrt_llm/llmapi/llm.py
Added max_iteration_result_size parameter to PostprocWorkerConfig initialization in both TRT and PyTorch backend paths

Sequence Diagram(s)

sequenceDiagram
    participant User as User Config
    participant LlmArgs as BaseLlmArgs
    participant GenExec as GenerationExecutor
    participant PostConfig as PostprocWorkerConfig
    participant IterResult as IterationResult
    participant Queue as AsyncQueue/Queue

    User->>LlmArgs: max_iteration_result_size: 16384
    LlmArgs->>GenExec: __init__(max_iteration_result_size)
    GenExec->>PostConfig: PostprocWorkerConfig(max_iteration_result_size)
    GenExec->>GenExec: super().__init__(max_iteration_result_size)
    GenExec->>IterResult: IterationResult(maxsize)
    IterResult->>Queue: AsyncQueue(maxsize) or Queue(maxsize)
    Queue->>Queue: collections.deque with bounded capacity
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Areas requiring extra attention:

  • tensorrt_llm/llmapi/utils.py: The AsyncQueue.__init__ modification passes maxsize as the first positional argument to collections.deque(maxsize), but the deque() constructor expects an optional iterable as the first argument and maxlen as a keyword argument. This likely causes a runtime error or unexpected behavior; should be collections.deque(maxlen=maxsize).
  • End-to-end parameter flow: Verify that the max_iteration_result_size value correctly propagates from BaseLlmArgsGenerationExecutorPostprocWorkerConfigIterationResult → queue initialization across all backend paths (TRT and PyTorch).
  • Default value semantics: Confirm that default value 16384 in BaseLlmArgs and 0 in PostprocWorkerConfig are intentional and properly handled throughout the initialization chain.

Pre-merge checks and finishing touches

❌ Failed checks (1 warning, 1 inconclusive)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 10.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
Description check ❓ Inconclusive The PR description addresses the core issue and solution but lacks complete test coverage details and specific test cases that validate the fix. Specify which tests were run or added to validate the max_iteration_result_size parameter and queue bounded behavior. Include details about stress test results mentioned as 'coming soon'.
✅ Passed checks (1 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly describes the main change: introducing max_iteration_result_size to prevent memory leaks.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Tip

📝 Customizable high-level summaries are now available in beta!

You can now customize how CodeRabbit generates the high-level summary in your pull requests — including its content, structure, tone, and formatting.

  • Provide your own instructions using the high_level_summary_instructions setting.
  • Format the summary however you like (bullet lists, tables, multi-section layouts, contributor stats, etc.).
  • Use high_level_summary_in_walkthrough to move the summary from the description to the walkthrough section.

Example instruction:

"Divide the high-level summary into five sections:

  1. 📝 Description — Summarize the main change in 50–60 words, explaining what was done.
  2. 📓 References — List relevant issues, discussions, documentation, or related PRs.
  3. 📦 Dependencies & Requirements — Mention any new/updated dependencies, environment variable changes, or configuration updates.
  4. 📊 Contributor Summary — Include a Markdown table showing contributions:
    | Contributor | Lines Added | Lines Removed | Files Changed |
  5. ✔️ Additional Notes — Add any extra reviewer context.
    Keep each section concise (under 200 words) and use bullet or numbered lists for clarity."

Note: This feature is currently in beta for Pro-tier users, and pricing will be announced later.


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

Caution

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

⚠️ Outside diff range comments (1)
tensorrt_llm/executor/executor.py (1)

243-257: Apply max_iteration_result_size limit to _iter_kv_events_result for consistency and OOM prevention.

The code initializes _iter_stats_result with postproc_config.max_iteration_result_size (line 248), but _iter_kv_events_result is created without any size limit (line 254). Since IterationResult accepts an optional maxsize parameter and both results follow the same pattern of accumulating data when the API is not called, the KV events result should also be bounded to prevent potential memory buildup.

Consider updating line 254 to: self._iter_kv_events_result = IterationResult(self.postproc_config.max_iteration_result_size)

If KV cache events require different handling than stats, document the rationale for unbounded initialization.

🧹 Nitpick comments (3)
tensorrt_llm/llmapi/llm_args.py (1)

1814-1818: Clarify and validate max_iteration_result_size semantics

The new knob is useful, but its semantics aren’t fully specified, especially given PostprocWorkerConfig.max_iteration_result_size defaults to 0.

Consider:

  • Explicitly documenting what values mean (e.g., > 0 = bounded queue, <= 0 = unbounded/disabled) to avoid confusion across backends/configs.
  • Adding a small field_validator("max_iteration_result_size") to reject negatives or normalize <= 0 to the “unbounded” sentinel before it reaches the queue implementation.

This keeps behavior predictable and prevents invalid values from propagating into the runtime.

tensorrt_llm/executor/postproc_worker.py (1)

41-47: Expose max_iteration_result_size semantics in config doc

Adding max_iteration_result_size to PostprocWorkerConfig is consistent with the rest of the plumbing, but its behavior isn’t documented here.

It would help future readers if the class/field docstring clarified:

  • What max_iteration_result_size controls (bounded size of iteration/KV event result queues).
  • How 0 is interpreted (e.g., “use executor default/unbounded”).

This keeps the config self-describing and aligned with BaseLlmArgs.max_iteration_result_size.

tensorrt_llm/llmapi/llm.py (1)

1071-1075: Consider wiring max_iteration_result_size for the TRT backend as well

Here _TorchLLM correctly passes self.args.max_iteration_result_size into PostprocWorkerConfig, so the PyTorch path respects the new bounded-queue knob.

In _TrtLLM._build_model, the PostprocWorkerConfig construction still only sets:

PostprocWorkerConfig(
    num_postprocess_workers=self.args.num_postprocess_workers,
    postprocess_tokenizer_dir=self.args.postprocess_tokenizer_dir,
)

which means the new BaseLlmArgs.max_iteration_result_size is effectively ignored for the TRT backend.

For consistency (and to have the leak fix apply uniformly), it’s worth mirroring this addition in the TRT path, e.g.:

-        self._executor = self._executor_cls.create(
+        self._executor = self._executor_cls.create(
             self._engine_dir,
             executor_config=self._executor_config,
             batched_logits_processor=self.args.batched_logits_processor,
             model_world_size=self.args.parallel_config.world_size,
             mpi_session=self.mpi_session,
             reuse_mpi_comm=external_mpi_comm_available(
                 self.args.parallel_config.world_size),
             return_logits=return_logits,
-            postproc_worker_config=PostprocWorkerConfig(
-                num_postprocess_workers=self.args.num_postprocess_workers,
-                postprocess_tokenizer_dir=self.args.postprocess_tokenizer_dir,
-            ),
+            postproc_worker_config=PostprocWorkerConfig(
+                num_postprocess_workers=self.args.num_postprocess_workers,
+                postprocess_tokenizer_dir=self.args.postprocess_tokenizer_dir,
+                max_iteration_result_size=self.args.max_iteration_result_size,
+            ),
             is_llm_executor=True)

so that max_iteration_result_size behaves the same regardless of backend.

📜 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 43896af and 4121abb.

📒 Files selected for processing (9)
  • tensorrt_llm/executor/base_worker.py (1 hunks)
  • tensorrt_llm/executor/executor.py (2 hunks)
  • tensorrt_llm/executor/postproc_worker.py (1 hunks)
  • tensorrt_llm/executor/proxy.py (1 hunks)
  • tensorrt_llm/executor/result.py (1 hunks)
  • tensorrt_llm/executor/rpc_proxy.py (1 hunks)
  • tensorrt_llm/llmapi/llm.py (1 hunks)
  • tensorrt_llm/llmapi/llm_args.py (1 hunks)
  • tensorrt_llm/llmapi/utils.py (1 hunks)
🧰 Additional context used
🧠 Learnings (5)
📚 Learning: 2025-08-26T09:37:10.463Z
Learnt from: jiaganc
Repo: NVIDIA/TensorRT-LLM PR: 7031
File: tensorrt_llm/bench/dataclasses/configuration.py:90-104
Timestamp: 2025-08-26T09:37:10.463Z
Learning: In TensorRT-LLM, the `get_pytorch_perf_config()` method returns `self.pytorch_config` which can contain default `cuda_graph_config` values, so `llm_args` may already have this config before the extra options processing.

Applied to files:

  • tensorrt_llm/llmapi/llm.py
📚 Learning: 2025-09-23T15:12:38.312Z
Learnt from: nv-lschneider
Repo: NVIDIA/TensorRT-LLM PR: 7910
File: cpp/tensorrt_llm/thop/allreduceOp.cpp:352-446
Timestamp: 2025-09-23T15:12:38.312Z
Learning: In TensorRT-LLM NCCL device implementation, NCCL version 2.28+ requirements are handled at runtime in the nccl_device/config layer rather than with compile-time guards. This allows the allreduceOp to remain version-agnostic and delegates version compatibility validation to the appropriate lower-level components that can gracefully handle unsupported configurations.

Applied to files:

  • tensorrt_llm/llmapi/llm.py
📚 Learning: 2025-08-21T00:16:56.457Z
Learnt from: farshadghodsian
Repo: NVIDIA/TensorRT-LLM PR: 7101
File: docs/source/blogs/tech_blog/blog9_Deploying_GPT_OSS_on_TRTLLM.md:36-36
Timestamp: 2025-08-21T00:16:56.457Z
Learning: TensorRT-LLM container release tags in documentation should only reference published NGC container images. The README badge version may be ahead of the actual published container versions.

Applied to files:

  • tensorrt_llm/llmapi/llm.py
📚 Learning: 2025-08-14T15:38:01.771Z
Learnt from: MatthiasKohl
Repo: NVIDIA/TensorRT-LLM PR: 6904
File: cpp/tensorrt_llm/pybind/thop/bindings.cpp:55-57
Timestamp: 2025-08-14T15:38:01.771Z
Learning: In TensorRT-LLM Python bindings, tensor parameter collections like mla_tensor_params and spec_decoding_tensor_params are kept as required parameters without defaults to maintain API consistency, even when it might affect backward compatibility.

Applied to files:

  • tensorrt_llm/llmapi/llm.py
📚 Learning: 2025-08-06T13:58:07.506Z
Learnt from: galagam
Repo: NVIDIA/TensorRT-LLM PR: 6487
File: tests/unittest/_torch/auto_deploy/unit/singlegpu/test_ad_trtllm_bench.py:1-12
Timestamp: 2025-08-06T13:58:07.506Z
Learning: In TensorRT-LLM, test files (files under tests/ directories) do not require NVIDIA copyright headers, unlike production source code files. Test files typically start directly with imports, docstrings, or code.

Applied to files:

  • tensorrt_llm/llmapi/llm.py
🧬 Code graph analysis (3)
tensorrt_llm/llmapi/llm_args.py (1)
tensorrt_llm/builder.py (1)
  • default (45-50)
tensorrt_llm/executor/result.py (2)
tensorrt_llm/executor/utils.py (1)
  • has_event_loop (68-73)
tensorrt_llm/llmapi/utils.py (2)
  • AsyncQueue (361-445)
  • sync_q (380-381)
tensorrt_llm/executor/executor.py (2)
tensorrt_llm/executor/postproc_worker.py (1)
  • PostprocWorkerConfig (42-50)
tensorrt_llm/executor/result.py (1)
  • IterationResult (951-1001)
🪛 Ruff (0.14.5)
tensorrt_llm/llmapi/utils.py

373-373: PEP 484 prohibits implicit Optional

Convert to T | None

(RUF013)

⏰ 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 (4)
tensorrt_llm/executor/base_worker.py (1)

85-91: Correctly forwarding max_iteration_result_size into GenerationExecutor

Wiring postproc_config.max_iteration_result_size into the base GenerationExecutor ensures the in-process worker path respects the bounded-queue setting; the default PostprocWorkerConfig() fallback keeps behavior well-defined when no config is provided.

tensorrt_llm/executor/proxy.py (1)

48-58: Proxy now respects max_iteration_result_size in iteration/KV queues

Propagating postproc_worker_config.max_iteration_result_size into the base GenerationExecutor here ensures the proxy path uses the same bounded-queue semantics as the in-process worker. Combined with the queue.full()/queue.get() logic in _iteration_result_task, this will naturally drop the oldest stats/events once the configured capacity is reached.

tensorrt_llm/executor/rpc_proxy.py (1)

304-312: LGTM! Clean parameter forwarding.

The max_iteration_result_size parameter is correctly forwarded from the postproc_worker_config to the base class constructor, following the same pattern as the other configuration parameters.

tensorrt_llm/executor/executor.py (1)

80-89: LGTM! Parameter properly integrated.

The max_iteration_result_size parameter is correctly added to the GenerationExecutor.__init__ method and properly stored in the PostprocWorkerConfig. The default value of 0 (unbounded) maintains backward compatibility.

@svc-trtllm-gh-bot svc-trtllm-gh-bot added the Community want to contribute PRs initiated from Community label Nov 18, 2025
@zhanghaotong
Copy link
Contributor Author

All bot issues have been fixed.

@pcastonguay
Copy link
Collaborator

@hchings could you please review? Thanks.

description="The path to the tokenizer directory for postprocessing.",
status="prototype")

max_iteration_result_size: int = Field(
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We will need at least a unit test to verify that this is working as expected. See tests/unittest/llmapi/test_llm_pytorch.py for examples.

"""

def __init__(self):
def __init__(self, maxsize: int = 0):
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use max_size here and in other places.

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

Labels

Community want to contribute PRs initiated from Community

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants