KEMBAR78
[TRTLLM-6668][feat] Enable overlap scheduler for two-model spec decoding by ziyixiong-nv · Pull Request #7651 · NVIDIA/TensorRT-LLM · GitHub
Skip to content

Conversation

@ziyixiong-nv
Copy link
Collaborator

@ziyixiong-nv ziyixiong-nv commented Sep 9, 2025

Summary by CodeRabbit

  • New Features

    • Enables overlap scheduling for speculative decoding with draft models (including Eagle3 and draft-target scenarios).
    • Adds extended-context decoding support with correct handling during generation.
    • Improves CUDA graph compatibility via automatic draft token padding.
  • Bug Fixes

    • Corrects token-length accounting and KV cache updates in extended-context and speculative decoding, improving stability and accuracy.
  • Tests

    • Expands Eagle3 test coverage across multiple backends, CUDA graph settings, chunked prefill, and one-model configurations.

Description

To support overlap scheduler with two-model spec decoding, the PR initializes the same input as one-model spec with overlap scheduler (SampleStateTensorsMTP).

With the changes, the workflow of the overlap scheduler without speculative decoding is as below.
overlap_without_spec_dec

The expected workflow when enabling speculative decoding is that "forward draft model" can be done before "sync target sample state". However, the current prepare_draft_batch has a dependency on the input tokens, so it must happen after "sync target sample state". Then the workflow for overlap scheduler with speculative decoding is as below, so we only have overlap for draft-draft and draft-target, but no overlap for target-draft.
overlap_with_spec_dec

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 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
Copy link
Collaborator Author

/bot run --disable-fast-fail

@tensorrt-cicd
Copy link
Collaborator

PR_Github #18234 Bot args parsing error: usage: /bot [-h]
{run,kill,skip,submit,reviewers,reuse-pipeline,reuse-review} ...
/bot: error: unrecognized arguments: --disable-fast-fail

@ziyixiong-nv ziyixiong-nv force-pushed the dev-fxiong-trtllm-6668 branch 3 times, most recently from 1a9bb44 to 921a1cf Compare September 10, 2025 09:54
@ziyixiong-nv ziyixiong-nv marked this pull request as ready for review September 10, 2025 09:55
@ziyixiong-nv ziyixiong-nv requested review from a team as code owners September 10, 2025 09:55
@ziyixiong-nv
Copy link
Collaborator Author

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #18359 [ run ] triggered by Bot

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Sep 10, 2025

📝 Walkthrough

Walkthrough

Introduces extended-context tracking in attention metadata, refactors speculative drafting into a modular pipeline, and rewires executor overlap flow to support speculative decoding with CUDA-graph padding. Updates overlap scheduler capability checks and expands Eagle3 test parameter coverage.

Changes

Cohort / File(s) Summary
Attention metadata & model engine wiring
tensorrt_llm/_torch/pyexecutor/model_engine.py
Adds num_extended_ctx_requests to TrtllmAttentionMetadata; conditions kv_lens_cuda updates on extended-context presence; initializes/propagates extended-context counters in _prepare_tp_inputs; tightens speculative input handling and draft/extend token length accounting.
Executor overlap & speculative flow
tensorrt_llm/_torch/pyexecutor/py_executor.py
Removes get_draft_token_length import; adds has_previous_draft_tokens; refactors batch prep to gate draft init; replaces padding with drafter.pad_draft_tokens_for_cuda_graph; adds speculative overlap via _handle_speculative_decoding and _process_draft_results; adjusts event loop guard.
Speculative interface (overlap support gate)
tensorrt_llm/_torch/speculative/interface.py
support_overlap_scheduler now returns true if has_draft_model() in addition to is_mtp() or is_eagle3_one_model().
Model drafter refactor & APIs
tensorrt_llm/_torch/speculative/model_drafter.py
Modularizes drafting: new/renamed public methods (forward_draft_model, sample_async, update_request_states, update_requests, process_decoded_tokens); adds should_forward_draft_model, generate_draft_tokens_with_overlap, pad_draft_tokens_for_cuda_graph; introduces SampleStateTensors and SampleStateTensorsMTP handling; adds helpers for converting, updating target inputs, static/dynamic processing, and iterative draft loops.
Tests expansion
tests/unittest/_torch/speculative/test_eagle3.py
Expands parameter grid for test_llama_eagle3 to cover more combinations of CUDA graph, attention backend, overlap scheduler, block reuse, one-model, and chunked prefill.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant App as Scheduler/Loop
  participant Exec as PyExecutor
  participant Drafter as ModelDrafter
  participant Engine as ModelEngine
  participant Attn as TrtllmAttentionMetadata

  App->>Exec: schedule batch (overlap enabled)
  Exec->>Drafter: should_forward_draft_model(scheduled_batch)
  alt Drafting needed
    Exec->>Drafter: generate_draft_tokens_with_overlap(prev_tensors?, guided_decoder?)
    Drafter->>Drafter: pad_draft_tokens_for_cuda_graph()
    Drafter->>Drafter: forward_draft_model(is_first_draft_token, prev_tensors?)
    Drafter-->>Exec: target_inputs?, draft_outputs, draft_batch
    note over Exec,Drafter: has_previous_draft_tokens updated
  else No drafting
    Exec-->>Exec: use previous_tensors device
  end

  Exec->>Engine: forward(target_inputs or previous device)
  Engine->>Attn: _preprocess_inputs()
  alt Extended-context present
    Attn-->>Attn: update kv_lens_cuda tail using previous_kv_lens_offsets_cuda
  else No extended-context
    Attn-->>Attn: update kv_lens_cuda for gen requests (previous behavior)
  end
  Engine-->>Exec: outputs

  alt Draft outputs produced
    Exec->>Drafter: process_static/dynamic_draft_outputs()
    Drafter-->>Exec: updated requests / target inputs merged
  else No draft outputs
    Exec-->>Exec: normal update of previous batch
  end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Suggested reviewers

  • lfr-0531
  • yweng0828
  • brb-nv

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.

  • Built-in checks – Quickly apply ready-made checks to enforce title conventions, require pull request descriptions that follow templates, validate linked issues for compliance, and more.
  • Custom agentic checks – Define your own rules using CodeRabbit’s advanced agentic capabilities to enforce organization-specific policies and workflows. For example, you can instruct CodeRabbit’s agent to verify that API documentation is updated whenever API schema files are modified in a PR. Note: Upto 5 custom checks are currently allowed during the preview period. Pricing for this feature will be announced in a few weeks.

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.

Pre-merge checks (1 passed, 2 warnings)

❌ Failed checks (2 warnings)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 70.97% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
Description Check ⚠️ Warning The current description includes the “## Description” and “## PR Checklist” sections but omits a filled-in PR title at the top and leaves the “## Test Coverage” section empty, deviating from the required template. Please add a properly formatted PR title following [JIRA ticket/ID][type] Summary at the top and populate the “## Test Coverage” section with the specific tests that safeguard these changes.
✅ Passed checks (1 passed)
Check name Status Explanation
Title Check ✅ Passed The current title “[TRTLLM-6668][feat] Enable overlap scheduler for two-model spec decoding” clearly and succinctly conveys the primary feature addition of the pull request, uses the proper ticket format and type, and omits extraneous details.
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • 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: 3

🧹 Nitpick comments (13)
tensorrt_llm/_torch/speculative/interface.py (1)

1-1: Add NVIDIA Apache-2.0 header.

Per coding guidelines, prepend the 2025 NVIDIA Apache-2.0 copyright header to all source files.

+# 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.
tests/unittest/_torch/speculative/test_eagle3.py (2)

1-1: Add NVIDIA Apache-2.0 header.

Apply the standard 2025 NVIDIA Apache-2.0 header at the 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.

29-39: Param matrix expansion looks good; add IDs and guard against degenerate accept-rate division.

  • Add ids to parametrize for easier triage.
  • Some combinations can yield zero drafted tokens (e.g., early stop); guard accept-rate division.

Apply:

 @pytest.mark.parametrize(
-    "use_cuda_graph,attn_backend,disable_overlap_scheduler,enable_block_reuse,use_one_model,enable_chunked_prefill",
-    [
+    "use_cuda_graph,attn_backend,disable_overlap_scheduler,enable_block_reuse,use_one_model,enable_chunked_prefill",
+    [
       ...
     ])

And later near accept-rate computation:

-    accept_rate = num_accepted / num_drafted
+    accept_rate = (num_accepted / num_drafted) if num_drafted > 0 else 0.0

Optionally:

-@pytest.mark.parametrize(..., [...], [...], ...)
+@pytest.mark.parametrize(
+    "...",
+    [
+        pytest.param(True, "TRTLLM", True,  False, True,  False, id="cg_on_trtllm_overlap_off_one_model"),
+        ...
+    ]
+)
tensorrt_llm/_torch/speculative/model_drafter.py (6)

1-1: Add NVIDIA Apache-2.0 header.

Insert the 2025 NVIDIA Apache-2.0 header at the file 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.

429-433: Docstring arg names do not match function signature.

The docstring mentions draft_sample_state/iteration, but the function takes draft_tensors, draft_position, and draft_length.

-        Args:
-            target_inputs: The target input tensors to update
-            draft_sample_state: The draft sample state containing new tokens
-            iteration: The current iteration index
+        Args:
+            target_inputs: The target input tensors to update.
+            draft_tensors: Draft tokens tensor for this update step.
+            draft_position: Starting draft position to write into.
+            draft_length: Number of draft tokens to write.
+            num_draft_reqs: Number of draft requests in the batch.

368-421: Make SampleStateTensorsMTP fields non-None to avoid downstream None-handling.

SampleStateTensorsMTP defines tensor fields; returning None for new_tokens_lens/next_draft_tokens risks attr errors downstream. Initialize to ones/zeros with expected shapes even when there are no generation requests.

-        new_tokens_lens = None
-        next_draft_tokens = None
+        new_tokens_lens = torch.ones(scheduled_batch.batch_size,
+                                     device=device)
+        next_draft_tokens = torch.zeros(scheduled_batch.batch_size,
+                                        self.max_draft_tokens,
+                                        device=device)
 ...
-            else:
-                # Create new tensors with the correct device
-                # We already updated the target state, so the new_tokens_lens should be all ones.
-                new_tokens_lens = torch.ones(scheduled_batch.batch_size,
-                                             device=device)
-                next_draft_tokens = torch.zeros(scheduled_batch.batch_size,
-                                                self.max_draft_tokens,
-                                                device=device)
+            else:
+                # Shapes already initialized above; just fill per-request entries as needed.
                 num_accepted_tokens = request.py_num_accepted_draft_tokens

383-399: Guard against missing py_num_accepted_draft_tokens on context requests.

On some paths, context requests may not have this attribute set. Default to 0 to avoid AttributeError.

-                num_accepted_tokens = request.py_num_accepted_draft_tokens
+                num_accepted_tokens = getattr(request, "py_num_accepted_draft_tokens", 0)

667-673: guided_decoder.execute signature inconsistency across paths.

Here you call execute(draft_logits, target_logits, d2t=...), while in prepare_draft_tokens it’s execute(logits, d2t=...). Align usage to the expected API to avoid silent misbehavior when guided decoding is enabled.

Would you like me to adjust both call sites to a single signature after confirming the current API?


634-639: Return-type docstring mismatch.

The function returns three values (target_inputs, previous_draft_state, draft_batch), but the docstring lists two.

-        Returns:
-            Tuple[Optional[SampleStateTensorsMTP], Optional[SampleState]]:
-                - Updated target inputs or None
-                - Draft sample state or None
+        Returns:
+            Tuple[Optional[SampleStateTensorsMTP], Optional[Any], Optional[ScheduledRequests]]:
+                - Updated target inputs or None
+                - Final draft sample state or None
+                - Draft batch used for the iteration or None
tensorrt_llm/_torch/pyexecutor/model_engine.py (3)

1304-1307: Improve error message for assertion

The assertion should provide a more informative error message explaining when SampleStateTensorsMTP is expected.

-            assert self.enable_spec_decode and not self.is_draft_model
+            assert self.enable_spec_decode and not self.is_draft_model, \
+                "SampleStateTensorsMTP should only be used with speculative decoding enabled on target model"

1473-1486: Simplify conditional logic for cached tokens calculation

The nested conditions can be simplified for better readability. Also, the comment at line 1474 could be clearer about when this path is taken.

-                if self.spec_config.spec_dec_mode.has_draft_model():
-                    # In the overlap scheduler workflow, if having draft model, we already updated the previous batch before launching the target model,
-                    # so we only need to add the runtime_draft_len to the past_seen_token_num.
-                    num_cached_tokens_per_seq.append(past_seen_token_num +
-                                                     self.runtime_draft_len)
-                else:
-                    num_cached_tokens_per_seq.append(past_seen_token_num +
-                                                     self.runtime_draft_len + 1)
+                # In overlap scheduler with draft model, the previous batch was already updated,
+                # so we only add runtime_draft_len. Without draft model, we add +1 for the current token.
+                offset = self.runtime_draft_len if self.spec_config.spec_dec_mode.has_draft_model() else self.runtime_draft_len + 1
+                num_cached_tokens_per_seq.append(past_seen_token_num + offset)

1667-1674: Consider extracting magic number to a named field

The field num_extended_ctx_requests is initialized here and used in _preprocess_inputs. Consider documenting this field more clearly in the AttentionMetadata class.

Would you like me to help add proper documentation for the num_extended_ctx_requests field in the AttentionMetadata class to clarify its purpose and usage?

tensorrt_llm/_torch/pyexecutor/py_executor.py (1)

282-285: Improve error message clarity

The error message could be more specific about which execution modes are incompatible with drafting.

-                raise NotImplementedError(
-                    "Drafting is not supported for selected executor loop. "
-                    "Please disable disagg/pipeline parallelism scheduler.")
+                raise NotImplementedError(
+                    "Drafting is not supported with pipeline parallelism (_executor_loop_pp). "
+                    "Please disable pipeline parallelism to use drafting.")
📜 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 bf57829 and 921a1cf.

📒 Files selected for processing (5)
  • tensorrt_llm/_torch/pyexecutor/model_engine.py (4 hunks)
  • tensorrt_llm/_torch/pyexecutor/py_executor.py (7 hunks)
  • tensorrt_llm/_torch/speculative/interface.py (1 hunks)
  • tensorrt_llm/_torch/speculative/model_drafter.py (6 hunks)
  • tests/unittest/_torch/speculative/test_eagle3.py (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/speculative/interface.py
  • tensorrt_llm/_torch/pyexecutor/model_engine.py
  • tensorrt_llm/_torch/pyexecutor/py_executor.py
  • tensorrt_llm/_torch/speculative/model_drafter.py
  • tests/unittest/_torch/speculative/test_eagle3.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/speculative/interface.py
  • tensorrt_llm/_torch/pyexecutor/model_engine.py
  • tensorrt_llm/_torch/pyexecutor/py_executor.py
  • tensorrt_llm/_torch/speculative/model_drafter.py
  • tests/unittest/_torch/speculative/test_eagle3.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/speculative/interface.py
  • tensorrt_llm/_torch/pyexecutor/model_engine.py
  • tensorrt_llm/_torch/pyexecutor/py_executor.py
  • tensorrt_llm/_torch/speculative/model_drafter.py
  • tests/unittest/_torch/speculative/test_eagle3.py
🧠 Learnings (2)
📚 Learning: 2025-08-19T12:45:11.997Z
Learnt from: amitz-nv
PR: NVIDIA/TensorRT-LLM#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/py_executor.py
📚 Learning: 2025-09-02T13:43:22.657Z
Learnt from: pcastonguay
PR: NVIDIA/TensorRT-LLM#7455
File: tensorrt_llm/_torch/pyexecutor/py_executor.py:728-731
Timestamp: 2025-09-02T13:43:22.657Z
Learning: The user pcastonguay prefers creating dedicated handler classes to encapsulate complex subsystem logic rather than spreading it across the main class. For disaggregated pipeline parallel termination, they suggest creating a `_disagg_pp_termination_handler` with a `cleanup()` method instead of manually waiting on termination handles during shutdown.

Applied to files:

  • tensorrt_llm/_torch/pyexecutor/py_executor.py
🧬 Code graph analysis (3)
tensorrt_llm/_torch/pyexecutor/model_engine.py (3)
tensorrt_llm/_torch/attention_backend/trtllm.py (1)
  • TrtllmAttentionMetadata (527-1005)
tensorrt_llm/_torch/speculative/mtp.py (1)
  • SampleStateTensorsMTP (26-28)
tensorrt_llm/_torch/speculative/interface.py (2)
  • has_draft_model (69-70)
  • extend_ctx (94-107)
tensorrt_llm/_torch/pyexecutor/py_executor.py (3)
tensorrt_llm/_torch/speculative/model_drafter.py (5)
  • pad_draft_tokens_for_cuda_graph (604-616)
  • should_forward_draft_model (345-366)
  • generate_draft_tokens_with_overlap (618-690)
  • process_static_draft_outputs (476-501)
  • process_dynamic_draft_outputs (503-511)
tensorrt_llm/_torch/pyexecutor/resource_manager.py (1)
  • request_context (115-139)
tensorrt_llm/_torch/pyexecutor/guided_decoder.py (4)
  • add_batch (302-304)
  • add_batch (428-437)
  • rollback_draft_tokens (388-389)
  • rollback_draft_tokens (478-479)
tensorrt_llm/_torch/speculative/model_drafter.py (6)
tensorrt_llm/_torch/pyexecutor/llm_request.py (4)
  • LlmRequest (284-426)
  • get_draft_token_length (574-585)
  • log_probs (228-229)
  • get (102-111)
tensorrt_llm/_torch/pyexecutor/resource_manager.py (4)
  • prepare_resources (72-73)
  • prepare_resources (411-451)
  • prepare_resources (1069-1072)
  • prepare_resources (1172-1188)
tensorrt_llm/_torch/pyexecutor/sampler.py (14)
  • Sampler (52-79)
  • SampleState (43-49)
  • SampleStateTensors (34-39)
  • TorchSampler (405-971)
  • sample_async (63-65)
  • sample_async (88-91)
  • sample_async (126-133)
  • sample_async (595-633)
  • sample_async (1150-1238)
  • update_requests (68-69)
  • update_requests (93-100)
  • update_requests (135-150)
  • update_requests (553-583)
  • update_requests (1241-1254)
tensorrt_llm/_torch/speculative/mtp.py (4)
  • SampleStateTensorsMTP (26-28)
  • sample_async (282-329)
  • update_requests (253-280)
  • prepare_resources (67-75)
tensorrt_llm/_torch/pyexecutor/model_engine.py (1)
  • no_cuda_graph (557-563)
tensorrt_llm/_torch/pyexecutor/guided_decoder.py (3)
  • GuidedDecoder (138-402)
  • rollback_rejected_tokens (384-385)
  • rollback_rejected_tokens (474-475)
⏰ 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 (5)
tensorrt_llm/_torch/speculative/interface.py (1)

60-61: Overlap scheduler enablement now includes has_draft_model — verify two-model EAGLE3/DRAFT_TARGET paths.

This broadens overlap to EAGLE3 (two-model) and DRAFT_TARGET. Confirm executor paths and drafter conversions are exercised for these modes (esp. when extend_ctx=False and needs_kv_cache_recompute=True). Add/confirm tests for DRAFT_TARGET mode.

tensorrt_llm/_torch/speculative/model_drafter.py (1)

245-252: CUDA graph disablement gating looks correct; keep the condition tight.

The check avoids disabling CUDA graphs except on the first draft step and when recompute is needed. This minimizes perf impact while keeping correctness for EAGLE3.

tensorrt_llm/_torch/pyexecutor/model_engine.py (1)

1186-1209: Ignore incorrect KV cache update suggestions The existing slice num_ctx_requests - num_extended_ctx_requests:num_ctx_requests already selects the last num_extended_ctx_requests entries, and using isinstance(inputs['attn_metadata'], TrtllmAttentionMetadata) is the intended guard for accessing kv_lens_cuda. No changes needed.

Likely an incorrect or invalid review comment.

tensorrt_llm/_torch/pyexecutor/py_executor.py (2)

969-977: has_previous_draft_tokens is already initialized and updated
The flag is set to False in __init__ (line 223) and then conditionally updated at lines 1987/1989, so it’s consistently managed—no extra assertions needed.

Likely an incorrect or invalid review comment.


1196-1209: Ensure proper initialization of tensors before use

The code uses previous_tensors and previous_tensors_device but doesn't validate they are properly initialized. Consider adding checks to prevent potential null pointer access.

                    previous_tensors = self.previous_batch and self.previous_batch.sample_state
                    target_inputs = None
                    draft_outputs = None
                    if self.drafter is not None and self.use_spec_decode:
                        target_inputs, draft_outputs, draft_batch = self._handle_speculative_decoding(
                            scheduled_batch, previous_tensors)

                    # Use the draft_model's outputs if we've launched the draft model.
                    # Otherwise, use the previous batch's outputs.
                    if target_inputs is not None:
                        previous_tensors_device = target_inputs
                    else:
-                        previous_tensors_device = self.previous_batch and self.previous_batch.sample_state and self.previous_batch.sample_state.device
+                        previous_tensors_device = None
+                        if self.previous_batch and self.previous_batch.sample_state:
+                            previous_tensors_device = self.previous_batch.sample_state.device

Likely an incorrect or invalid review comment.

@tensorrt-cicd
Copy link
Collaborator

PR_Github #18359 [ run ] completed with state SUCCESS
/LLM/main/L0_MergeRequest_PR pipeline #13770 completed with status: 'FAILURE'

Copy link
Collaborator

@mikeiovine mikeiovine left a comment

Choose a reason for hiding this comment

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

Great! Only have a few minor comments.

On test coverage, we should probably also test 2-model + non-CDL. I don't think it can be turned off right now unless you use non-greedy sampling or something. We can also add a developer flag to turn it off for testing

@ziyixiong-nv
Copy link
Collaborator Author

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #18463 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #18463 [ run ] completed with state FAILURE
/LLM/main/L0_MergeRequest_PR pipeline #13852 completed with status: 'FAILURE'

@ziyixiong-nv
Copy link
Collaborator Author

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #18468 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #18468 [ run ] completed with state SUCCESS
/LLM/main/L0_MergeRequest_PR pipeline #13857 completed with status: 'FAILURE'

@ziyixiong-nv
Copy link
Collaborator Author

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #18503 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #18503 [ run ] completed with state SUCCESS
/LLM/main/L0_MergeRequest_PR pipeline #13888 completed with status: 'FAILURE'

Signed-off-by: ziyixiong-nv <219238287+ziyixiong-nv@users.noreply.github.com>
…ding

Signed-off-by: ziyixiong-nv <219238287+ziyixiong-nv@users.noreply.github.com>
Signed-off-by: ziyixiong-nv <219238287+ziyixiong-nv@users.noreply.github.com>
Signed-off-by: ziyixiong-nv <219238287+ziyixiong-nv@users.noreply.github.com>
Signed-off-by: ziyixiong-nv <219238287+ziyixiong-nv@users.noreply.github.com>
Signed-off-by: ziyixiong-nv <219238287+ziyixiong-nv@users.noreply.github.com>
@ziyixiong-nv
Copy link
Collaborator Author

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #18545 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #18545 [ run ] completed with state SUCCESS
/LLM/main/L0_MergeRequest_PR pipeline #13920 completed with status: 'FAILURE'

@ziyixiong-nv
Copy link
Collaborator Author

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #18635 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #18635 [ run ] completed with state SUCCESS
/LLM/main/L0_MergeRequest_PR pipeline #13993 completed with status: 'SUCCESS'

@ziyixiong-nv ziyixiong-nv merged commit 536e877 into NVIDIA:main Sep 15, 2025
4 of 5 checks passed
Wong4j pushed a commit to Wong4j/TensorRT-LLM that referenced this pull request Sep 20, 2025
…ing (NVIDIA#7651)

Signed-off-by: ziyixiong-nv <219238287+ziyixiong-nv@users.noreply.github.com>
MrGeva pushed a commit to nv-auto-deploy/TensorRT-LLM that referenced this pull request Sep 21, 2025
…ing (NVIDIA#7651)

Signed-off-by: ziyixiong-nv <219238287+ziyixiong-nv@users.noreply.github.com>
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.

3 participants