TensorRT-LLM icon indicating copy to clipboard operation
TensorRT-LLM copied to clipboard

[None][fix] Prevent memory leaks with max_iteration_result_size

Open zhanghaotong opened this issue 1 month ago โ€ข 3 comments

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.

  • [x] 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 avatar Nov 18 '25 07:11 zhanghaotong

๐Ÿ“ 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

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 BaseLlmArgs โ†’ GenerationExecutor โ†’ PostprocWorkerConfig โ†’ IterationResult โ†’ 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 addresses the core problem (preventing memory leaks) and references the solution mechanism (max_iteration_result_size), directly matching the main objective of capping the _iter_stats_result queue.
โœจ Finishing touches
  • [ ] ๐Ÿ“ Generate docstrings
๐Ÿงช Generate unit tests (beta)
  • [ ] 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.

coderabbitai[bot] avatar Nov 18 '25 07:11 coderabbitai[bot]

All bot issues have been fixed.

zhanghaotong avatar Nov 18 '25 09:11 zhanghaotong

@hchings could you please review? Thanks.

pcastonguay avatar Nov 20 '25 16:11 pcastonguay

@hchings friendly ping. Would you mind reviewing since it looks like you originally implemented the iter stats. Thanks.

pcastonguay avatar Nov 25 '25 14:11 pcastonguay