-
Notifications
You must be signed in to change notification settings - Fork 1.7k
[https://nvbugs/5485325][fix] Cherry-pick #7373: fix the CUDA graph warmup issue when using speculative decoding #7734
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
…o fix the CUDA graph warmup issue when using speculative decoding (NVIDIA#7373) Signed-off-by: Fanrong Li <[email protected]> Co-authored-by: Tao Li @ NVIDIA <[email protected]>
/bot run |
📝 WalkthroughWalkthroughIntroduces an optional post-capture callback in CUDA graph capture. PyTorchModelEngine adds a _postprocess_inputs method and passes it to CUDAGraphRunner.capture to restore mutated inputs during warmup and capture. New multi-GPU NVFP4 CUDA-graph corner-case test is added and wired into test lists and an 8-GPU CI job. Changes
Sequence Diagram(s)sequenceDiagram
autonumber
participant Engine as PyTorchModelEngine
participant Runner as CUDAGraphRunner
participant Fwd as forward_fn
participant Post as postprocess_fn (optional)
rect rgba(230,240,255,0.6)
note over Engine: Capture setup
Engine->>Runner: capture(batch_size, Fwd, inputs, Post)
end
rect rgba(240,255,230,0.6)
loop Warmup iterations
Runner->>Fwd: forward(inputs)
alt Postprocess provided
Runner->>Post: postprocess_fn(inputs)
end
end
end
rect rgba(255,245,230,0.6)
note over Runner: Graph capture
Runner->>Fwd: forward(inputs) [captured]
alt Postprocess provided
Runner->>Post: postprocess_fn(inputs)
end
note over Engine,Runner: Inputs restored post-capture
end
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Pre-merge checks and finishing touches❌ Failed checks (1 warning, 1 inconclusive)
✅ Passed checks (1 passed)
✨ Finishing touches
🧪 Generate unit tests
Warning Review ran into problems🔥 ProblemsGit: Failed to clone repository. Please run the Tip 👮 Agentic pre-merge checks are now available in preview!Pro plan users can now enable pre-merge checks in their settings to enforce checklists before merging PRs.
Please see the documentation for more information. Example: reviews:
pre_merge_checks:
custom_checks:
- name: "Undocumented Breaking Changes"
mode: "warning"
instructions: |
Pass/fail criteria: All breaking changes to public APIs, CLI flags, environment variables, configuration keys, database schemas, or HTTP/GraphQL endpoints must be documented in the "Breaking Change" section of the PR description and in CHANGELOG.md. Exclude purely internal or private changes (e.g., code not exported from package entry points or explicitly marked as internal). Please share your feedback with us on this Discord post. 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 |
There was a problem hiding this 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 (1)
tensorrt_llm/_torch/pyexecutor/cuda_graph_runner.py (1)
1-1
: Missing NVIDIA Apache-2.0 header.Per repo guidelines, prepend the 2025 NVIDIA Apache-2.0 SPDX header.
Apply:
+# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + import bisect
🧹 Nitpick comments (3)
tensorrt_llm/_torch/pyexecutor/cuda_graph_runner.py (1)
167-171
: Type and doc the new postprocess_fn parameter.Great addition. Please tighten the type hint and document expected side effects (mutate inputs only; no graph-captured ops).
Apply:
- def capture(self, - batch_size: int, - forward_fn: Callable, - initial_inputs: Dict[str, Any], - postprocess_fn: Optional[Callable] = None): + def capture(self, + batch_size: int, + forward_fn: Callable[[Dict[str, Any]], Any], + initial_inputs: Dict[str, Any], + postprocess_fn: Optional[Callable[[Dict[str, Any]], None]] = None): """Captures the forward pass for a given batch size.""" + # postprocess_fn: called after each warmup forward and after the + # captured forward; must only mutate input dict (e.g., restore fields) + # and must not allocate/capture CUDA ops.tensorrt_llm/_torch/pyexecutor/model_engine.py (2)
1-1
: Add NVIDIA Apache-2.0 header (2025).This source file is missing the required NVIDIA Apache-2.0 copyright header with the current year.
Apply at the very top:
+# Copyright (c) 2025, NVIDIA CORPORATION. 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.
1199-1218
: Guard postprocess to capture-only and add minor robustness.Functionally correct. Add light checks to avoid accidental double-subtraction outside capture, keep lookups local, and annotate return type.
Apply:
- def _postprocess_inputs(self, inputs: Dict[str, Any]): + def _postprocess_inputs(self, inputs: Dict[str, Any]) -> None: @@ - if self.enable_spec_decode and not self._disable_overlap_scheduler: - if inputs['attn_metadata'].kv_cache_manager is not None: - num_seqs = inputs['attn_metadata'].num_seqs - num_ctx_requests = inputs['attn_metadata'].num_contexts - num_gen_requests = inputs['attn_metadata'].num_generations - num_ctx_tokens = inputs['attn_metadata'].num_ctx_tokens - previous_batch_tokens = inputs['input_ids'].shape[ - 0] - num_ctx_tokens - inputs['position_ids'][0, num_ctx_tokens:] -= ( - self.previous_pos_id_offsets_cuda[:previous_batch_tokens]) - inputs['attn_metadata'].kv_lens_cuda[ - num_ctx_requests:num_seqs] -= ( - self.previous_kv_lens_offsets_cuda[:num_gen_requests]) + if not (self.enable_spec_decode and not self._disable_overlap_scheduler): + return + attn_md = inputs.get('attn_metadata') + if attn_md is None or attn_md.kv_cache_manager is None: + return + # Defensive: this should run only for CUDA graph capture paths. + if not getattr(attn_md, 'is_cuda_graph', False): + return + num_seqs = attn_md.num_seqs + num_ctx_requests = attn_md.num_contexts + num_gen_requests = attn_md.num_generations + num_ctx_tokens = attn_md.num_ctx_tokens + previous_batch_tokens = inputs['input_ids'].shape[0] - num_ctx_tokens + pos_ids = inputs['position_ids'] + pos_ids[0, num_ctx_tokens:] -= self.previous_pos_id_offsets_cuda[:previous_batch_tokens] + attn_md.kv_lens_cuda[num_ctx_requests:num_seqs] -= self.previous_kv_lens_offsets_cuda[:num_gen_requests]
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (6)
tensorrt_llm/_torch/pyexecutor/cuda_graph_runner.py
(2 hunks)tensorrt_llm/_torch/pyexecutor/model_engine.py
(2 hunks)tests/integration/defs/accuracy/test_llm_api_pytorch.py
(1 hunks)tests/integration/test_lists/qa/llm_function_core.txt
(1 hunks)tests/integration/test_lists/qa/llm_function_core_sanity.txt
(1 hunks)tests/integration/test_lists/test-db/l0_dgx_b200.yml
(1 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/cuda_graph_runner.py
tests/integration/defs/accuracy/test_llm_api_pytorch.py
tensorrt_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/cuda_graph_runner.py
tests/integration/defs/accuracy/test_llm_api_pytorch.py
tensorrt_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/cuda_graph_runner.py
tests/integration/defs/accuracy/test_llm_api_pytorch.py
tensorrt_llm/_torch/pyexecutor/model_engine.py
🧠 Learnings (3)
📚 Learning: 2025-09-09T09:40:45.658Z
Learnt from: fredricz-20070104
PR: NVIDIA/TensorRT-LLM#7645
File: tests/integration/test_lists/qa/llm_function_core.txt:648-648
Timestamp: 2025-09-09T09:40:45.658Z
Learning: In TensorRT-LLM test lists, it's common and intentional for the same test to appear in multiple test list files when they serve different purposes (e.g., llm_function_core.txt for comprehensive core functionality testing and llm_function_core_sanity.txt for quick sanity checks). This duplication allows tests to be run in different testing contexts.
Applied to files:
tests/integration/test_lists/qa/llm_function_core.txt
tests/integration/test_lists/qa/llm_function_core_sanity.txt
📚 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/integration/test_lists/qa/llm_function_core.txt
tests/integration/test_lists/qa/llm_function_core_sanity.txt
📚 Learning: 2025-08-26T09:49:04.956Z
Learnt from: pengbowang-nv
PR: NVIDIA/TensorRT-LLM#7192
File: tests/integration/test_lists/test-db/l0_dgx_b200.yml:56-72
Timestamp: 2025-08-26T09:49:04.956Z
Learning: In TensorRT-LLM test configuration files, the test scheduling system handles wildcard matching with special rules that prevent duplicate test execution even when the same tests appear in multiple yaml files with overlapping GPU wildcards (e.g., "*b200*" and "*gb200*").
Applied to files:
tests/integration/test_lists/test-db/l0_dgx_b200.yml
🔇 Additional comments (5)
tests/integration/test_lists/qa/llm_function_core.txt (1)
491-491
: Corner-case test added to core list—LGTM.Consistent with sanity list and CI wiring. Consider keeping ordering grouped with related DeepSeekR1 entries (optional).
tests/integration/test_lists/qa/llm_function_core_sanity.txt (1)
45-45
: Add corner-case test to sanity list—LGTM.Entry looks correct and duplication across lists is intentional per QA conventions. Please just verify the test path matches the new method name.
Run:
#!/bin/bash rg -n "class\s+TestDeepSeekR1\b" tests/integration/defs/accuracy/test_llm_api_pytorch.py -n -C2 rg -n "def\s+test_nvfp4_multi_gpus_corner_case\b" tests/integration/defs/accuracy/test_llm_api_pytorch.py -n -C2tensorrt_llm/_torch/pyexecutor/cuda_graph_runner.py (1)
209-215
: Postprocess runs outside the capture—LGTM.Placement avoids polluting the graph and fixes the warmup/capture mutation issue.
Please confirm all call sites were updated to pass the callback where needed:
#!/bin/bash rg -nP -C3 '\.capture\s*\(' --type=pytests/integration/test_lists/test-db/l0_dgx_b200.yml (1)
76-90
: 8‑GPU post‑merge block for corner-case test—LGTM.Filters, stage, and timeout look correct; wildcard ‘b200’ will also catch ‘gb200’.
Ensure this doesn’t duplicate in other post_merge 8‑GPU blocks:
#!/bin/bash rg -n "test_nvfp4_multi_gpus_corner_case" tests/integration/test_lists/test-db -n -C2tensorrt_llm/_torch/pyexecutor/model_engine.py (1)
2321-2327
: Passing a post-capture restore hook is the right fix; verify all call sites updated.The hook cleanly reverts in-capture input mutations. Please confirm all
CUDAGraphRunner.capture
call sites use the new 4‑arg signature.Run:
#!/bin/bash set -euo pipefail # Confirm capture() accepts postprocess_fn rg -nC2 -P $'def\\s+capture\\(\\s*self\\s*,\\s*batch_size\\s*:\\s*int\\s*,\\s*forward_fn\\s*:\\s*Callable[\\s\\S]*postprocess_fn\\s*:\\s*Optional\\[' tensorrt_llm/_torch/pyexecutor/cuda_graph_runner.py # List all call sites of .capture( rg -nC2 -P '\.capture\(' --type=py # Ensure _postprocess_inputs is only used via the capture hook rg -nC2 -P '\b_postprocess_inputs\s*\('
PR_Github #18646 [ run ] triggered by Bot |
PR_Github #18646 [ run ] completed with state |
/bot run |
PR_Github #18667 [ run ] triggered by Bot |
PR_Github #18667 [ run ] completed with state |
/bot run |
PR_Github #18854 [ run ] triggered by Bot |
PR_Github #18854 [ run ] completed with state |
…o fix the CUDA graph warmup issue when using speculative decoding (#7373)
Summary by CodeRabbit
Bug Fixes
Tests
Description
Cherry-pick the fix in #7373.
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.
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-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.