[https://nvbugs/5451280][fix] Reduce memory fraction problem by warmu… - #8410
[https://nvbugs/5451280][fix] Reduce memory fraction problem by warmu…#8410liji-nv wants to merge 1 commit into
Conversation
NVIDIA#7999) Signed-off-by: Jin Li <59594262+liji-nv@users.noreply.github.com>
📝 WalkthroughWalkthroughRefactors warmup orchestration by introducing a consolidated _general_warmup and updating _create_warmup_request with new guards and a least_requests option. Adjusts KV-cache estimation to account for CUDA graph warmup needs and batch-size floors. Integrates the new warmup path into compile warmup and maintains spec-decode state consistency. Changes
Sequence Diagram(s)sequenceDiagram
autonumber
participant ME as ModelEngine
participant RM as ResourceManager
participant WR as _create_warmup_request
participant SCH as Scheduler
rect rgba(230,240,255,0.5)
note over ME: _general_warmup(reverse=?)
ME->>RM: Query capacities (batch, seq, KV blocks)
ME->>WR: Build warmup batch (num_tokens, num_gen_tokens, least_requests?)
end
alt Validate warmup request
WR->>WR: Check num_gen_tokens ≤ batch
WR->>WR: Compute max_context_requests vs batch/seq
WR->>WR: Guard: autotune/extra steps/KV space
WR-->>ME: None (early return)
else Valid
opt least_requests branch
WR->>WR: Split full sequences and leftovers<br/>Adjust max_seq_len
end
WR-->>ME: ScheduledRequests
ME->>SCH: Submit ScheduledRequests
SCH-->>ME: Warmup execution done
end
note over ME: Restore/keep spec_decode flags
sequenceDiagram
autonumber
participant Util as _util._get_token_num_for_estimation
participant Cfg as Model/Engine Config
Util->>Cfg: Read batch_size, max_seq_len, tokens_per_block, beam_width, max_cuda_graph_bs
Util->>Util: max_cuda_graph_bs = min(model_bs, max_cuda_graph_bs)
Util->>Util: cuda_graph_warmup_block = f(max_seq_len, tokens_per_block, max_cuda_graph_bs)
Util->>Util: num_cache_blocks = max(prev_blocks, cuda_graph_warmup_block, model_bs)
Util-->>Cfg: return num_cache_blocks * tokens_per_block * beam_width
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Pre-merge checks and finishing touches❌ Failed checks (2 warnings)
✅ Passed checks (1 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
|
/bot run |
|
PR_Github #21520 [ run ] triggered by Bot |
There was a problem hiding this comment.
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 (2)
tensorrt_llm/_torch/pyexecutor/_util.py (1)
1-1: Add the 2025 NVIDIA Apache-2.0 copyright header to the top of tensorrt_llm/_torch/pyexecutor/_util.py.The file currently starts directly with imports and is missing the required header. Prepend the Apache-2.0 copyright header (with 2025 as the year) before the first import statement, as required by the coding guidelines.
tensorrt_llm/_torch/pyexecutor/model_engine.py (1)
1-1: Add NVIDIA Apache-2.0 license header
Add the following lines at the very top of tensorrt_llm/_torch/pyexecutor/model_engine.py (before any imports):# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0
🧹 Nitpick comments (2)
tensorrt_llm/_torch/pyexecutor/model_engine.py (2)
714-716: Defensive guard for token accounting.If num_gen_tokens > num_tokens, num_ctx_tokens becomes negative. Add a guard to early-return None.
Apply:
if num_gen_tokens > self.batch_size: return None + if num_gen_tokens > num_tokens: + return NoneAlso applies to: 717-725
726-743: Avoid reusing max_seq_len for per-request lengths.You assign max_seq_len = self.max_seq_len - 1, then repurpose it for per-request ctx length. Rename to avoid confusion.
Example:
- max_seq_len = self.max_seq_len - 1 + max_ctx_seq_len = self.max_seq_len - 1 ... - max_context_requests = self.batch_size - num_gen_tokens - if max_context_requests * max_seq_len < num_ctx_tokens: + max_context_requests = self.batch_size - num_gen_tokens + if max_context_requests * max_ctx_seq_len < num_ctx_tokens: return None ... - num_full_seqs = num_ctx_tokens // max_seq_len - num_left_over_tokens = num_ctx_tokens - num_full_seqs * max_seq_len + num_full_seqs = num_ctx_tokens // max_ctx_seq_len + num_left_over_tokens = num_ctx_tokens - num_full_seqs * max_ctx_seq_len ... - max_seq_len = num_ctx_tokens // num_full_seqs - num_left_over_tokens = num_ctx_tokens - max_seq_len * num_full_seqs + per_seq_ctx_len = num_ctx_tokens // num_full_seqs + num_left_over_tokens = num_ctx_tokens - per_seq_ctx_len * num_full_seqs ... - ctx_token_nums = [max_seq_len] * num_full_seqs + ctx_token_nums = [(per_seq_ctx_len if 'per_seq_ctx_len' in locals() else max_ctx_seq_len)] * num_full_seqs
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
tensorrt_llm/_torch/pyexecutor/_util.py(1 hunks)tensorrt_llm/_torch/pyexecutor/model_engine.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/pyexecutor/_util.pytensorrt_llm/_torch/pyexecutor/model_engine.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/pyexecutor/_util.pytensorrt_llm/_torch/pyexecutor/model_engine.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/pyexecutor/_util.pytensorrt_llm/_torch/pyexecutor/model_engine.py
🧠 Learnings (1)
📚 Learning: 2025-08-14T21:04:50.248Z
Learnt from: thorjohnsen
PR: NVIDIA/TensorRT-LLM#6910
File: cpp/tensorrt_llm/batch_manager/kvCacheManager.cpp:0-0
Timestamp: 2025-08-14T21:04:50.248Z
Learning: In KV cache onboarding logic during prefill in cpp/tensorrt_llm/batch_manager/kvCacheManager.cpp, when calculating which blocks fall within the attention window, use getTokensPerBlock() to advance token indices rather than block->getUniqueTokens().size(), because the calculation needs to consider the post-prefill state where blocks will be filled to capacity, not their current token count.
Applied to files:
tensorrt_llm/_torch/pyexecutor/_util.py
🧬 Code graph analysis (2)
tensorrt_llm/_torch/pyexecutor/_util.py (2)
tensorrt_llm/_torch/pyexecutor/scheduler.py (1)
batch_size(35-36)tensorrt_llm/_torch/attention_backend/trtllm.py (2)
max_seq_len(589-599)max_seq_len(602-606)
tensorrt_llm/_torch/pyexecutor/model_engine.py (2)
tensorrt_llm/_torch/pyexecutor/resource_manager.py (3)
ResourceManager(1118-1153)get_resource_manager(1130-1131)get_num_available_tokens(720-722)tensorrt_llm/_torch/pyexecutor/scheduler.py (2)
batch_size(35-36)ScheduledRequests(18-39)
🪛 Ruff (0.14.0)
tensorrt_llm/_torch/pyexecutor/model_engine.py
469-469: Undefined name warmup_requests_configs
(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 (1)
tensorrt_llm/_torch/pyexecutor/model_engine.py (1)
522-525: LGTM: centralizing torch.compile warmup.Delegating to _general_warmup under no_cuda_graph is correct.
| # Max cuda graph warmup required tokens | ||
| max_cuda_graph_bs = min(self._model_engine.batch_size, | ||
| self._model_engine._max_cuda_graph_batch_size) | ||
| cuda_graph_warmup_block = ( | ||
| self._model_engine.max_seq_len + | ||
| 1) // self._tokens_per_block + max_cuda_graph_bs - 1 | ||
| num_cache_blocks = max(cuda_graph_warmup_block, num_cache_blocks) | ||
|
|
There was a problem hiding this comment.
CUDA-graph warmup blocks undercounted (ceil and batch-scaling bug).
You add (bs - 1) instead of multiplying blocks per sequence by batch size, and miss a ceil. This underestimates required blocks and can break estimation.
Apply:
- cuda_graph_warmup_block = (
- self._model_engine.max_seq_len +
- 1) // self._tokens_per_block + max_cuda_graph_bs - 1
- num_cache_blocks = max(cuda_graph_warmup_block, num_cache_blocks)
+ # Ceil((max_seq_len + 1)/tokens_per_block) per sequence, scaled by batch size
+ blocks_per_seq = (self._model_engine.max_seq_len + 1 + self._tokens_per_block - 1) // self._tokens_per_block
+ cuda_graph_warmup_blocks = max_cuda_graph_bs * blocks_per_seq
+ num_cache_blocks = max(cuda_graph_warmup_blocks, num_cache_blocks)📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| # Max cuda graph warmup required tokens | |
| max_cuda_graph_bs = min(self._model_engine.batch_size, | |
| self._model_engine._max_cuda_graph_batch_size) | |
| cuda_graph_warmup_block = ( | |
| self._model_engine.max_seq_len + | |
| 1) // self._tokens_per_block + max_cuda_graph_bs - 1 | |
| num_cache_blocks = max(cuda_graph_warmup_block, num_cache_blocks) | |
| # Max cuda graph warmup required tokens | |
| max_cuda_graph_bs = min(self._model_engine.batch_size, | |
| self._model_engine._max_cuda_graph_batch_size) | |
| # Ceil((max_seq_len + 1)/tokens_per_block) per sequence, scaled by batch size | |
| blocks_per_seq = (self._model_engine.max_seq_len + 1 | |
| self._tokens_per_block - 1) // self._tokens_per_block | |
| cuda_graph_warmup_blocks = max_cuda_graph_bs * blocks_per_seq | |
| num_cache_blocks = max(cuda_graph_warmup_blocks, num_cache_blocks) |
🤖 Prompt for AI Agents
tensorrt_llm/_torch/pyexecutor/_util.py lines 201-208: the computation
undercounts required CUDA-graph warmup blocks by adding (bs - 1) instead of
scaling blocks per sequence by batch size and missing a proper ceil; compute
blocks_per_sequence = ceil((self._model_engine.max_seq_len + 1) /
self._tokens_per_block) (use integer math (a + b - 1) // b or math.ceil), then
set cuda_graph_warmup_block = blocks_per_sequence * max_cuda_graph_bs (where
max_cuda_graph_bs is unchanged), and finally num_cache_blocks =
max(cuda_graph_warmup_block, num_cache_blocks).
| for num_tokens, num_gen_tokens in warmup_requests_configs: | ||
| with self._release_batch_context( | ||
| self._create_warmup_request(resource_manager, num_tokens, | ||
| num_gen_tokens), | ||
| resource_manager) as batch: | ||
| if batch is None: | ||
| continue # Not enough KV cache space | ||
| logger.info( | ||
| f"Run warmup with {num_tokens} tokens, include {num_gen_tokens} generation tokens" | ||
| ) | ||
| self.forward(batch, | ||
| new_tensors_device=None, | ||
| resource_manager=resource_manager) | ||
| torch.cuda.synchronize() | ||
|
|
There was a problem hiding this comment.
NameError: warmup_requests_configs is undefined.
Loop should iterate the built collection. This will crash at runtime.
Apply:
- for num_tokens, num_gen_tokens in warmup_requests_configs:
+ for num_tokens, num_gen_tokens in (warmup_requests if isinstance(warmup_requests, list) else list(warmup_requests)):Optionally ensure determinism:
- if reverse:
- warmup_requests = sorted(list(warmup_requests), reverse=reverse)
+ warmup_requests = sorted(list(warmup_requests), reverse=reverse)📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| for num_tokens, num_gen_tokens in warmup_requests_configs: | |
| with self._release_batch_context( | |
| self._create_warmup_request(resource_manager, num_tokens, | |
| num_gen_tokens), | |
| resource_manager) as batch: | |
| if batch is None: | |
| continue # Not enough KV cache space | |
| logger.info( | |
| f"Run warmup with {num_tokens} tokens, include {num_gen_tokens} generation tokens" | |
| ) | |
| self.forward(batch, | |
| new_tensors_device=None, | |
| resource_manager=resource_manager) | |
| torch.cuda.synchronize() | |
| for num_tokens, num_gen_tokens in (warmup_requests if isinstance(warmup_requests, list) else list(warmup_requests)): | |
| with self._release_batch_context( | |
| self._create_warmup_request(resource_manager, num_tokens, | |
| num_gen_tokens), | |
| resource_manager) as batch: | |
| if batch is None: | |
| continue # Not enough KV cache space | |
| logger.info( | |
| f"Run warmup with {num_tokens} tokens, include {num_gen_tokens} generation tokens" | |
| ) | |
| self.forward(batch, | |
| new_tensors_device=None, | |
| resource_manager=resource_manager) | |
| torch.cuda.synchronize() |
🧰 Tools
🪛 Ruff (0.14.0)
469-469: Undefined name warmup_requests_configs
(F821)
🤖 Prompt for AI Agents
In tensorrt_llm/_torch/pyexecutor/model_engine.py around lines 469 to 483, the
loop references an undefined name warmup_requests_configs causing a NameError;
update the for-loop to iterate the actual built collection (e.g., for
num_tokens, num_gen_tokens in warmup_requests:) that was created earlier, and
ensure you use that exact variable name present in scope; optionally, to ensure
deterministic warmups, iterate a stable ordering (e.g., sort the collection or
iterate a predefined list) or seed any randomness before running the warmup.
|
PR_Github #21520 [ run ] completed with state |
…… (#7999)
Summary by CodeRabbit
Bug Fixes
Refactor
Description
Test Coverage
PR Checklist
Please review the following before submitting your PR:
PR description clearly explains what and why. If using CodeRabbit's summary, please make sure it makes sense.
PR Follows TRT-LLM CODING GUIDELINES to the best of your knowledge.
Test cases are provided for new code paths (see test instructions)
Any new dependencies have been scanned for license and vulnerabilities
CODEOWNERS updated if ownership changes
Documentation updated as needed
The reviewers assigned automatically/manually are appropriate for the PR.
Please check this after reviewing the above items as appropriate for this PR.
GitHub Bot Help
/bot [-h] ['run', 'kill', 'skip', 'reuse-pipeline'] ...Provide a user friendly way for developers to interact with a Jenkins server.
Run
/bot [-h|--help]to print this help message.See details below for each supported subcommand.
Details
run [--reuse-test (optional)pipeline-id --disable-fail-fast --skip-test --stage-list "A10-PyTorch-1, xxx" --gpu-type "A30, H100_PCIe" --test-backend "pytorch, cpp" --add-multi-gpu-test --only-multi-gpu-test --disable-multi-gpu-test --post-merge --extra-stage "H100_PCIe-TensorRT-Post-Merge-1, xxx" --detailed-log --debug(experimental)]Launch build/test pipelines. All previously running jobs will be killed.
--reuse-test (optional)pipeline-id(OPTIONAL) : Allow the new pipeline to reuse build artifacts and skip successful test stages from a specified pipeline or the last pipeline if no pipeline-id is indicated. If the Git commit ID has changed, this option will be always ignored. The DEFAULT behavior of the bot is to reuse build artifacts and successful test results from the last pipeline.--disable-reuse-test(OPTIONAL) : Explicitly prevent the pipeline from reusing build artifacts and skipping successful test stages from a previous pipeline. Ensure that all builds and tests are run regardless of previous successes.--disable-fail-fast(OPTIONAL) : Disable fail fast on build/tests/infra failures.--skip-test(OPTIONAL) : Skip all test stages, but still run build stages, package stages and sanity check stages. Note: Does NOT update GitHub check status.--stage-list "A10-PyTorch-1, xxx"(OPTIONAL) : Only run the specified test stages. Examples: "A10-PyTorch-1, xxx". Note: Does NOT update GitHub check status.--gpu-type "A30, H100_PCIe"(OPTIONAL) : Only run the test stages on the specified GPU types. Examples: "A30, H100_PCIe". Note: Does NOT update GitHub check status.--test-backend "pytorch, cpp"(OPTIONAL) : Skip test stages which don't match the specified backends. Only support [pytorch, cpp, tensorrt, triton]. Examples: "pytorch, cpp" (does not run test stages with tensorrt or triton backend). Note: Does NOT update GitHub pipeline status.--only-multi-gpu-test(OPTIONAL) : Only run the multi-GPU tests. Note: Does NOT update GitHub check status.--disable-multi-gpu-test(OPTIONAL) : Disable the multi-GPU tests. Note: Does NOT update GitHub check status.--add-multi-gpu-test(OPTIONAL) : Force run the multi-GPU tests in addition to running L0 pre-merge pipeline.--post-merge(OPTIONAL) : Run the L0 post-merge pipeline instead of the ordinary L0 pre-merge pipeline.--extra-stage "H100_PCIe-TensorRT-Post-Merge-1, xxx"(OPTIONAL) : Run the ordinary L0 pre-merge pipeline and specified test stages. Examples: --extra-stage "H100_PCIe-TensorRT-Post-Merge-1, xxx".--detailed-log(OPTIONAL) : Enable flushing out all logs to the Jenkins console. This will significantly increase the log volume and may slow down the job.--debug(OPTIONAL) : Experimental feature. Enable access to the CI container for debugging purpose. Note: Specify exactly one stage in thestage-listparameter to access the appropriate container environment. Note: Does NOT update GitHub check status.For guidance on mapping tests to stage names, see
docs/source/reference/ci-overview.mdand the
scripts/test_to_stage_mapping.pyhelper.kill
killKill all running builds associated with pull request.
skip
skip --comment COMMENTSkip testing for latest commit on pull request.
--comment "Reason for skipping build/test"is required. IMPORTANT NOTE: This is dangerous since lack of user care and validation can cause top of tree to break.reuse-pipeline
reuse-pipelineReuse a previous pipeline to validate current commit. This action will also kill all currently running builds associated with the pull request. IMPORTANT NOTE: This is dangerous since lack of user care and validation can cause top of tree to break.