Skip to content

Conversation

@ziyixiong-nv
Copy link
Collaborator

@ziyixiong-nv ziyixiong-nv commented Dec 23, 2025

Summary by CodeRabbit

Release Notes

  • Refactor
    • Optimized speculative decoding token gathering performance with vectorized tensor operations to reduce loop overhead
    • Enhanced autotuning support for fused drafting loops by enabling dynamic calculation of extra decoding steps and cache allocation
    • Improved warmup request initialization to properly handle speculative decoding parameters and generation configuration
    • Reduced execution overhead in model executor components through selective compilation optimization

✏️ Tip: You can customize this high-level summary in your review settings.

Description

This PR applies several optimizations for two-model spec dec.

  • Enable autotuner warmup for CDL
  • Remove torch.compile to avoid the compilation during inference
  • Optimize the kernel for updating the draft tokens by collecting the indices firstly

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.

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.

@ziyixiong-nv ziyixiong-nv requested review from a team as code owners December 23, 2025 00:54
@ziyixiong-nv
Copy link
Collaborator Author

/bot run

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Dec 23, 2025

📝 Walkthrough

Walkthrough

Changes remove PyTorch compile decorators from speculative execution methods, introduce dynamic extra decoding steps calculation during warmup, make drafting loops conditional based on max_draft_len, and optimize draft token gathering through vectorization instead of per-request loops.

Changes

Cohort / File(s) Summary
Compilation decorator removals
tensorrt_llm/_torch/pyexecutor/py_executor.py, tensorrt_llm/_torch/pyexecutor/model_engine.py, tensorrt_llm/_torch/speculative/drafting_loops.py
Removed @torch.compile(options={"max-autotune": True}) decorators from _accept_draft_tokens, _update_draft_input_tensors, _update_target_input_tensors, _prepare_incremental_update_metadata, and prepare_for_generation methods; changes affect compilation behavior only, not function signatures or APIs.
Extra decoding steps handling
tensorrt_llm/_torch/pyexecutor/model_engine.py
Removed early guard that disabled autotuning; added dynamic calculation of extra_decoding_steps, tokens_per_gen, and blocks_per_gen to determine blocks_to_use; propagated num_extra_decoding_steps into warmup request payloads and dummy requests to ensure proper KV-cache block allocation sizing.
Drafting loop conditionals
tensorrt_llm/_torch/speculative/drafting_loops.py
Introduced guard condition: drafting loop executes only if max_draft_len > 1; moved Eagle3SpecMetadata special handling into local is_eagle3 flag; replaced direct isinstance checks with flag-based conditionals.
Draft token gathering vectorization
tensorrt_llm/_torch/speculative/model_drafter.py
Replaced per-request loop with vectorized approach: collects draft_indices and target_indices for all in-progress requests, performs single index_select on device-resident tensors, and writes gathered results via advanced indexing; reduces Python loop overhead and improves performance.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Pre-merge checks and finishing touches

❌ Failed checks (2 warnings)
Check name Status Explanation Resolution
Description check ⚠️ Warning The description explains what and why (three key optimizations listed), but the Test Coverage section is empty and no specific tests are mentioned to safeguard the changes. Add specific test cases or test suite names in the Test Coverage section that validate the autotuner warmup, torch.compile removal, and draft token optimization changes.
Docstring Coverage ⚠️ Warning Docstring coverage is 60.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (1 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and specifically describes the main changes: optimizations for two-model spec dec, matching the file modifications across model_engine.py, py_executor.py, drafting_loops.py, and model_drafter.py.
✨ 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.

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

🧹 Nitpick comments (1)
tensorrt_llm/_torch/pyexecutor/model_engine.py (1)

867-876: Extra decoding steps handling in warmup looks sound; note the wrapper assertion

The new logic in _create_warmup_request that:

  • derives num_extra_decoding_steps via _get_num_extra_decoding_steps(),
  • inflates blocks_to_use by num_gen_tokens * blocks_per_gen, and
  • passes num_extra_decoding_steps into add_dummy_requests for generation warmup

correctly mirrors the additional KV usage of fused drafting loops (CDL) while remaining a no‑op for non‑wrapped models (where _get_num_extra_decoding_steps returns 0). This should make both torch.compile and CUDA‑graph warmups substantially more faithful to the actual runtime behavior.

One nuance to keep in mind is the assert inside _get_num_extra_decoding_steps:

if isinstance(self.model, BaseDraftingLoopWrapper):
    return self.model.max_total_draft_tokens
else:
    assert not self.model_is_wrapped, (
        f"Please add logic to determine num_extra_decoding_steps for drafting loop {type(self.model)}"
    )
    return 0

This is good for catching unsupported wrapped models early, but it does mean that any future drafting-loop wrapper types must either subclass BaseDraftingLoopWrapper or extend _get_num_extra_decoding_steps, otherwise warmup will assert. If you anticipate additional wrapper types, it may be worth documenting this or relaxing the assertion to a logged warning with num_extra_decoding_steps = 0.

Also applies to: 898-905

📜 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 0d2500c and 8bc701f.

📒 Files selected for processing (4)
  • tensorrt_llm/_torch/pyexecutor/model_engine.py
  • tensorrt_llm/_torch/pyexecutor/py_executor.py
  • tensorrt_llm/_torch/speculative/drafting_loops.py
  • tensorrt_llm/_torch/speculative/model_drafter.py
💤 Files with no reviewable changes (1)
  • tensorrt_llm/_torch/pyexecutor/py_executor.py
🧰 Additional context used
📓 Path-based instructions (2)
**/*.py

📄 CodeRabbit inference engine (CODING_GUIDELINES.md)

**/*.py: Code developed for TensorRT-LLM should conform to Python 3.8+
Indent Python code with 4 spaces. Do not use tabs
Always maintain the namespace when importing in Python, even if only one class or function from a module is used
Python files should use snake_case naming: some_file.py
Python classes should use PascalCase naming: class SomeClass
Python functions and methods should use snake_case naming: def my_awesome_function():
Python local variables should use snake_case naming: my_variable = ...
Python variable names that start with a number should be prefixed with 'k': k_99th_percentile = ...
Python global variables should use upper snake_case with prefix 'G': G_MY_GLOBAL = ...
Python constants should use upper snake_case naming: MY_CONSTANT = ...
Avoid shadowing variables declared in an outer scope in Python
Initialize all externally visible members of a Python class in the constructor
For Python interfaces that may be used outside a file, prefer docstrings over comments
Python comments should be reserved for code within a function, or interfaces that are local to a file
Use Google style docstrings in Python for classes and functions, which can be parsed by Sphinx
Python attributes and variables can be documented inline with type and description
Avoid using reflection in Python when functionality can be easily achieved without reflection
When using try-except blocks in Python, limit the except to the smallest set of errors possible
When using try-except blocks in Python to handle multiple possible variable types (duck-typing), keep the body of the try as small as possible, using the else block for logic

Files:

  • tensorrt_llm/_torch/speculative/model_drafter.py
  • tensorrt_llm/_torch/speculative/drafting_loops.py
  • tensorrt_llm/_torch/pyexecutor/model_engine.py
**/*.{cpp,h,cu,cuh,py}

📄 CodeRabbit inference engine (CODING_GUIDELINES.md)

All TensorRT-LLM Open Source Software code should contain an NVIDIA copyright header that includes the year of its latest meaningful modification

Files:

  • tensorrt_llm/_torch/speculative/model_drafter.py
  • tensorrt_llm/_torch/speculative/drafting_loops.py
  • tensorrt_llm/_torch/pyexecutor/model_engine.py
🧠 Learnings (7)
📚 Learning: 2025-12-12T03:27:18.859Z
Learnt from: tongyuantongyu
Repo: NVIDIA/TensorRT-LLM PR: 9655
File: tensorrt_llm/_torch/pyexecutor/sampler.py:3031-3031
Timestamp: 2025-12-12T03:27:18.859Z
Learning: In tensorrt_llm/_torch/pyexecutor/sampler.py, when reviewing code that iterates through requests, ensure it does not convert excessive data into Python lists. Instead, the code should use torch.gather or indexing to gather only the data that will be used in the for loop before converting to Python lists. This minimizes data movement and improves performance.

Applied to files:

  • tensorrt_llm/_torch/speculative/model_drafter.py
📚 Learning: 2025-12-12T03:27:18.859Z
Learnt from: tongyuantongyu
Repo: NVIDIA/TensorRT-LLM PR: 9655
File: tensorrt_llm/_torch/pyexecutor/sampler.py:3031-3031
Timestamp: 2025-12-12T03:27:18.859Z
Learning: In tensorrt_llm/_torch/pyexecutor/sampler.py, when reviewing code that iterates through requests, ensure it does not access torch.Tensor objects (CPU or GPU) inside the loop. Instead, the code should use .tolist() to convert batched data tensors to Python lists beforehand, and then access the list in the for loop. This is a critical performance consideration.

Applied to files:

  • tensorrt_llm/_torch/speculative/model_drafter.py
📚 Learning: 2025-08-14T21:04:50.248Z
Learnt from: thorjohnsen
Repo: NVIDIA/TensorRT-LLM PR: 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/speculative/model_drafter.py
  • tensorrt_llm/_torch/pyexecutor/model_engine.py
📚 Learning: 2025-08-19T12:45:11.997Z
Learnt from: amitz-nv
Repo: NVIDIA/TensorRT-LLM PR: 7033
File: tensorrt_llm/_torch/pyexecutor/model_engine.py:0-0
Timestamp: 2025-08-19T12:45:11.997Z
Learning: In tensorrt_llm/_torch/pyexecutor/model_engine.py, DoRA (Delta Orthogonal Rank Adaptation) functionality was removed from the PyTorch flow to eliminate issues with inverted DoRA detection logic. The original is_dora condition was checking if scaling_vec_pointer == 0, which was potentially incorrect.

Applied to files:

  • tensorrt_llm/_torch/pyexecutor/model_engine.py
📚 Learning: 2025-08-19T12:45:35.429Z
Learnt from: amitz-nv
Repo: NVIDIA/TensorRT-LLM PR: 7033
File: tensorrt_llm/_torch/pyexecutor/model_engine.py:2086-2092
Timestamp: 2025-08-19T12:45:35.429Z
Learning: DoRA (Delta Orthogonal Rank Adaptation) functionality has been removed from the PyTorch flow in tensorrt_llm/_torch/pyexecutor/model_engine.py. The is_dora field is computed but not used downstream in the PyTorch flow, so converting it to a tensor would be wasteful overhead.

Applied to files:

  • tensorrt_llm/_torch/pyexecutor/model_engine.py
📚 Learning: 2025-08-26T06:07:02.166Z
Learnt from: shaharmor98
Repo: NVIDIA/TensorRT-LLM PR: 7231
File: tensorrt_llm/_torch/pyexecutor/_util.py:504-509
Timestamp: 2025-08-26T06:07:02.166Z
Learning: In tensorrt_llm/_torch/pyexecutor/_util.py, when calling model_engine.set_lora_model_config(), pass model_binding_config.mlp_hidden_size directly without multiplying by mapping.tp_size, as the mlp_hidden_size from get_bindings_model_config() is already the per-TP rank value needed for LoRA weight packaging.

Applied to files:

  • tensorrt_llm/_torch/pyexecutor/model_engine.py
📚 Learning: 2025-12-12T03:27:08.565Z
Learnt from: tongyuantongyu
Repo: NVIDIA/TensorRT-LLM PR: 9655
File: tensorrt_llm/_torch/pyexecutor/sampler.py:3031-3031
Timestamp: 2025-12-12T03:27:08.565Z
Learning: In files under tensorrt_llm/_torch/pyexecutor, avoid accessing torch.Tensor objects inside for-loops when iterating over requests. Convert batched tensors to Python lists beforehand using tensor.tolist(), and then iterate over those lists. This improves performance by reducing tensor-bound operations inside hot loops. Apply this pattern to similar code paths that process batches to access simple Python data structures (lists) inside loops.

Applied to files:

  • tensorrt_llm/_torch/pyexecutor/model_engine.py
🧬 Code graph analysis (3)
tensorrt_llm/_torch/speculative/model_drafter.py (1)
tensorrt_llm/functional.py (1)
  • index_select (2216-2275)
tensorrt_llm/_torch/speculative/drafting_loops.py (2)
tensorrt_llm/_torch/speculative/interface.py (1)
  • is_eagle3 (61-62)
tensorrt_llm/_torch/speculative/eagle3.py (1)
  • Eagle3SpecMetadata (114-276)
tensorrt_llm/_torch/pyexecutor/model_engine.py (1)
tensorrt_llm/_torch/attention_backend/trtllm.py (3)
  • tokens_per_block (712-716)
  • max_seq_len (692-702)
  • max_seq_len (705-709)
⏰ 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/speculative/drafting_loops.py (1)

121-144: Guarding drafting loop on max_draft_len > 1 looks correct

The new if self.max_draft_len > 1: guard and cached is_eagle3 flag preserve behavior while avoiding unnecessary prepare_for_generation / save_metadata_state work when only a single draft token is requested. The Eagle3 index update on the first extra iteration is still applied only when additional iterations actually run, which is consistent with the previous semantics.

@tensorrt-cicd
Copy link
Collaborator

PR_Github #29478 [ run ] triggered by Bot. Commit: 8bc701f

@tensorrt-cicd
Copy link
Collaborator

PR_Github #29478 [ run ] completed with state FAILURE. Commit: 8bc701f
/LLM/main/L0_MergeRequest_PR pipeline #22660 completed with status: 'FAILURE'

⚠️ Action Required:

  • Please check the failed tests and fix your PR
  • If you cannot view the failures, ask the CI triggerer to share details
  • Once fixed, request an NVIDIA team member to trigger CI again

@ziyixiong-nv
Copy link
Collaborator Author

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #29483 [ run ] triggered by Bot. Commit: 8bc701f

@tensorrt-cicd
Copy link
Collaborator

PR_Github #29483 [ run ] completed with state FAILURE. Commit: 8bc701f
/LLM/main/L0_MergeRequest_PR pipeline #22664 completed with status: 'ABORTED'

⚠️ Action Required:

  • Please check the failed tests and fix your PR
  • If you cannot view the failures, ask the CI triggerer to share details
  • Once fixed, request an NVIDIA team member to trigger CI again

@ziyixiong-nv
Copy link
Collaborator Author

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #29564 [ run ] triggered by Bot. Commit: 8bc701f

@tensorrt-cicd
Copy link
Collaborator

PR_Github #29564 [ run ] completed with state SUCCESS. Commit: 8bc701f
/LLM/main/L0_MergeRequest_PR pipeline #22733 completed with status: 'FAILURE'

⚠️ Action Required:

  • Please check the failed tests and fix your PR
  • If you cannot view the failures, ask the CI triggerer to share details
  • Once fixed, request an NVIDIA team member to trigger CI again

@ziyixiong-nv
Copy link
Collaborator Author

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #29717 [ run ] triggered by Bot. Commit: 8170aa0

@ziyixiong-nv ziyixiong-nv enabled auto-merge (squash) December 24, 2025 08:14
@tensorrt-cicd
Copy link
Collaborator

PR_Github #29717 [ run ] completed with state SUCCESS. Commit: 8170aa0
/LLM/main/L0_MergeRequest_PR pipeline #22830 completed with status: 'FAILURE'

⚠️ Action Required:

  • Please check the failed tests and fix your PR
  • If you cannot view the failures, ask the CI triggerer to share details
  • Once fixed, request an NVIDIA team member to trigger CI again

@ziyixiong-nv
Copy link
Collaborator Author

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #29815 [ run ] triggered by Bot. Commit: 8170aa0

@tensorrt-cicd
Copy link
Collaborator

PR_Github #29815 [ run ] completed with state SUCCESS. Commit: 8170aa0
/LLM/main/L0_MergeRequest_PR pipeline #22919 completed with status: 'FAILURE'

⚠️ Action Required:

  • Please check the failed tests and fix your PR
  • If you cannot view the failures, ask the CI triggerer to share details
  • Once fixed, request an NVIDIA team member to trigger CI again

@ziyixiong-nv
Copy link
Collaborator Author

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #29851 [ run ] triggered by Bot. Commit: e159a09

@ziyixiong-nv
Copy link
Collaborator Author

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #29885 [ run ] triggered by Bot. Commit: ea482c6

@tensorrt-cicd
Copy link
Collaborator

PR_Github #29885 [ run ] completed with state SUCCESS. Commit: ea482c6
/LLM/main/L0_MergeRequest_PR pipeline #22982 completed with status: 'FAILURE'

⚠️ Action Required:

  • Please check the failed tests and fix your PR
  • If you cannot view the failures, ask the CI triggerer to share details
  • Once fixed, request an NVIDIA team member to trigger CI again

@ziyixiong-nv
Copy link
Collaborator Author

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #30011 [ run ] triggered by Bot. Commit: 7d6632b

@tensorrt-cicd
Copy link
Collaborator

PR_Github #30011 [ run ] completed with state SUCCESS. Commit: 7d6632b
/LLM/main/L0_MergeRequest_PR pipeline #23089 completed with status: 'SUCCESS'

@ziyixiong-nv ziyixiong-nv merged commit c59aa8b into NVIDIA:main Dec 28, 2025
4 of 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.

5 participants