KEMBAR78
[None][refactor] Simplify decoder state initialization for speculative decoding by Funatiq · Pull Request #6869 · NVIDIA/TensorRT-LLM · GitHub
Skip to content

Conversation

@Funatiq
Copy link
Collaborator

@Funatiq Funatiq commented Aug 13, 2025

Summary by CodeRabbit

  • New Features

    • Enhanced speculative decoding with host-side draft logits and token IDs, plus a fast-logits path supporting tensor-parallel broadcasting for higher throughput.
  • Bug Fixes

    • Prevented crashes when draft tokens are absent by returning zero draft count and added safer handling of draft logits transfers.
  • Refactor

    • Modularized speculative-decoding flows into dedicated handlers and centralized dispatch for multiple modes.
  • Chores

    • Removed a deprecated request interface and simplified public surfaces.

Description

  • Mostly moving code around to simplify logic.
  • Remove intermediate decoder_batch::Request.
  • Introduce persistent host buffers for draft tokens and logits (temporary buffer in Request is removed).
  • Please see commit messages for details.

Test Coverage

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.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 13, 2025

📝 Walkthrough

Walkthrough

Removes the legacy runtime::decoder_batch::Request header and usages, refactors CreateNewDecoderRequests into a modular speculative-decoding dispatcher with per-mode builders, adds pinned host draft logits/token buffers and host-copy paths, changes logits thread to write into caller-provided host buffers with explicit dtype, and makes draft-token count access null-safe.

Changes

Cohort / File(s) Summary
Runtime Request removal
cpp/include/tensorrt_llm/runtime/request.h, cpp/include/tensorrt_llm/batch_manager/createNewDecoderRequests.h
Deleted the runtime::decoder_batch::Request header and removed its includes/usages from createNewDecoderRequests declarations.
CreateNewDecoderRequests refactor
cpp/tensorrt_llm/batch_manager/createNewDecoderRequests.cpp, cpp/include/tensorrt_llm/batch_manager/createNewDecoderRequests.h
Reworked createDecoderRequests signature (removed beamWidth, added OptionalRef), introduced OptionalRef alias, added dispatcher newRequestSpeculativeDecoding, modular per-mode builders, moved draft-logits handling into free function retrieveDraftLogits, and rewired speculative-mode wiring and broadcasts.
Host draft buffers addition
cpp/include/tensorrt_llm/runtime/decodingInput.h, .../runtime/decoderState.cpp
Added host-side members draftLogitsHost, draftTokenIdsHost (and numDraftTokensHost), allocate on pinned pool, and mirror reshape logic with device buffers.
Logits thread API change
cpp/tensorrt_llm/batch_manager/utils/logitsThread.h, cpp/tensorrt_llm/batch_manager/utils/logitsThread.cpp
Changed targetModelReceiveLogits to void and write into caller-provided draftLogitsHost with explicit nvinfer1::DataType (removed ModelConfig/std::optional dependency); MPI receive now fills the pinned host buffer in-place.
LlmRequest safety
cpp/include/tensorrt_llm/batch_manager/llmRequest.h
GenericLlmRequest::getNumDraftTokens now returns hasDraftTokens() ? mDraftTokens->size() : 0 to avoid null dereference when draft tokens are absent.
Decoder state speculative buffers
.../runtime/decoderState.cpp
Allocations/reshape updated to create/reshape pinned host buffers for external draft logits, token IDs, and draft-counts; added local nvTokenIdType for token-id dtype selection.

Sequence Diagram(s)

sequenceDiagram
  actor Caller
  participant CNR as CreateNewDecoderRequests
  participant SD as newRequestSpeculativeDecoding
  participant RL as retrieveDraftLogits
  participant LT as targetModelReceiveLogits
  participant H as ModeHandlers (DraftExternal / Medusa / Lookahead / Eagle / Explicit)

  Caller->>CNR: createDecoderRequests(requests, configs, streams, ...)
  CNR->>SD: dispatch per-batch (mode, LlmRequest, buffers, configs, streams)
  alt speculative fast-logits needed
    SD->>RL: request draft logits (reqDraftLogits, configs, flags)
    RL->>LT: receive into host buffer (draftLogitsHost, fastLogitsInfo, logitsDtype)
    LT-->>RL: draftLogitsHost populated
    RL-->>SD: draft logits ready (host/device as needed)
  end
  SD->>H: call newRequest<Mode>(...) to populate DecodingInput/Output
  H-->>CNR: per-batch inputs/outputs filled
  CNR-->>Caller: return aggregated DecodingInput, DecodingOutput, counts
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~40 minutes

Possibly related PRs

Suggested reviewers

  • DomBrown
  • dcampora
  • mikeiovine

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

✨ 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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai or @coderabbitai title anywhere in the PR title to generate the title automatically.

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@Funatiq
Copy link
Collaborator Author

Funatiq commented Aug 13, 2025

/bot run

@coderabbitai coderabbitai bot changed the title [None] @coderabbitai title [None] feat speculative decoding dispatcher; remove decoder_batch API Aug 13, 2025
@tensorrt-cicd
Copy link
Collaborator

PR_Github #15157 [ run ] triggered by Bot

@Funatiq Funatiq changed the title [None] feat speculative decoding dispatcher; remove decoder_batch API [None][refactor] Simplify decoder state initialization for speculative decoding Aug 13, 2025
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: 4

🔭 Outside diff range comments (2)
cpp/tensorrt_llm/batch_manager/utils/logitsThread.cpp (1)

124-165: Add sanity checks and minor MPI argument fix to harden the receive path.

Null and dtype checks protect against misuse; validating dims positivity avoids invalid shapes; passing dims instead of &dims avoids pointer-to-array confusion.

Apply this diff:

-void targetModelReceiveLogits(runtime::ITensor::SharedPtr& draftLogitsHost,
-    executor::SpeculativeDecodingFastLogitsInfo const& fastLogitsInfo, nvinfer1::DataType logitsDtype)
+void targetModelReceiveLogits(runtime::ITensor::SharedPtr& draftLogitsHost,
+    executor::SpeculativeDecodingFastLogitsInfo const& fastLogitsInfo, nvinfer1::DataType logitsDtype)
 {
 #if ENABLE_MULTI_DEVICE
+    TLLM_CHECK(draftLogitsHost && "draftLogitsHost must be non-null");
+    TLLM_CHECK(draftLogitsHost->getDataType() == logitsDtype && "draftLogitsHost dtype must match logitsDtype");
     auto const& worldComm = tensorrt_llm::mpi::MpiComm::world();
@@
-    int64_t dims[2];
-    MPICHECK(MPI_Mrecv(&dims, count, MPI_INT64_T, &msg, &status));
+    int64_t dims[2];
+    MPICHECK(MPI_Mrecv(dims, count, MPI_INT64_T, &msg, &status));
+    TLLM_CHECK(dims[0] > 0 && dims[1] > 0);
@@
-    MPICHECK(MPI_Mrecv(draftLogitsHost->data(), count, MPI_UINT8_T, &msg, &status));
+    MPICHECK(MPI_Mrecv(draftLogitsHost->data(), count, MPI_UINT8_T, &msg, &status));
 #endif // ENABLE_MULTI_DEVICE
 }
cpp/tensorrt_llm/batch_manager/createNewDecoderRequests.cpp (1)

25-36: Add missing standard headers used in this file

This file uses std::transform (Line 122) and std::memcpy (Line 343) but does not include or . Relying on transitive includes is brittle.

Apply this diff to include the required headers:

 #include "tensorrt_llm/common/nvtxUtils.h"
 #include "tensorrt_llm/runtime/common.h"
 #include "tensorrt_llm/runtime/decoderState.h"
 #include "tensorrt_llm/runtime/decodingInput.h"
 #include "tensorrt_llm/runtime/decodingOutput.h"
 #include "tensorrt_llm/runtime/iBuffer.h"
 #include "tensorrt_llm/runtime/runtimeKernels.h"
 #include "tensorrt_llm/runtime/speculativeDecodingMode.h"
 #include "tensorrt_llm/runtime/utils/mpiUtils.h"
 #include "tensorrt_llm/runtime/utils/speculativeChoicesUtils.h"

 #include <NvInferRuntimeBase.h>
+#include <algorithm>
+#include <cstring>
🧹 Nitpick comments (6)
cpp/include/tensorrt_llm/runtime/decodingInput.h (2)

105-105: Add brief docs for new host-side tensor member (shape, location expectations).

Please document the expected memory type (pinned host) and shape conventions of draftLogitsHost to mirror draftLogits. This reduces ambiguity for future maintainers and call sites.

Apply this diff to add a short Doxygen note:

-        TensorPtr draftLogitsHost;
+        //! Host-pinned buffer mirroring draftLogits. Expected shape:
+        //! [batchSize, maxTokensPerEngineStep, vocabSizePadded] on pinned host.
+        TensorPtr draftLogitsHost;

111-111: Add brief docs for new host-side token-ids tensor (shape, location expectations).

Similarly, document draftTokenIdsHost to mirror draftTokenIds and clarify that it lives in pinned host memory and matches device shape.

Apply this diff to add a short Doxygen note:

-        TensorPtr draftTokenIdsHost;
+        //! Host-pinned buffer mirroring draftTokenIds. Expected shape:
+        //! [batchSize, maxTokensPerEngineStep] on pinned host.
+        TensorPtr draftTokenIdsHost;
cpp/tensorrt_llm/batch_manager/utils/logitsThread.h (1)

53-55: API change looks good; add preconditions and usage doc for clarity.

The switch to an in/out buffer is clean and removes optional churn. Please add a short comment describing:

  • draftLogitsHost must be a valid ITensor (host-pinned) view/slice sized 2D by the caller, since the callee reshapes it to [numRows, vocab].
  • logitsDtype must match draftLogitsHost->getDataType().

This helps avoid misuse at call sites.

Apply this diff to document expectations:

-void targetModelReceiveLogits(runtime::ITensor::SharedPtr& draftLogitsHost,
-    executor::SpeculativeDecodingFastLogitsInfo const& fastLogitsInfo, nvinfer1::DataType logitsDtype);
+// Receives fast logits over MPI into a caller-provided host-pinned tensor.
+// Preconditions:
+// - draftLogitsHost is non-null and points to a host-pinned tensor/view; dtype must equal logitsDtype.
+// - The provided tensor may be a 2D slice/view; this function will reshape it to [numRows, vocab].
+void targetModelReceiveLogits(runtime::ITensor::SharedPtr& draftLogitsHost,
+    executor::SpeculativeDecodingFastLogitsInfo const& fastLogitsInfo, nvinfer1::DataType logitsDtype);
cpp/tensorrt_llm/runtime/decoderState.cpp (1)

182-194: Host buffers allocation aligns with device counterparts; consider adding a brief assertion of pinned pool usage where consumed.

Allocating draftLogitsHost/draftTokenIdsHost/numDraftTokensHost with MemoryType::kPINNEDPOOL is correct and consistent. Ensure downstream consumers (e.g., MPI receive) assume host-pinned buffers to enable direct writes.

Optionally add a comment near allocations indicating these are intended for MPI/direct host writes:

-        externalDraftTokensInputs.draftLogitsHost = bufferManager.emptyTensor(MemoryType::kPINNEDPOOL, dtype);
+        // Host-pinned buffer for receiving fast logits via MPI/direct writes.
+        externalDraftTokensInputs.draftLogitsHost = bufferManager.emptyTensor(MemoryType::kPINNEDPOOL, dtype);
...
-        externalDraftTokensInputs.draftTokenIdsHost = bufferManager.emptyTensor(MemoryType::kPINNEDPOOL, nvTokenIdType);
+        // Host-pinned buffer for incoming draft token IDs.
+        externalDraftTokensInputs.draftTokenIdsHost = bufferManager.emptyTensor(MemoryType::kPINNEDPOOL, nvTokenIdType);
cpp/tensorrt_llm/batch_manager/createNewDecoderRequests.cpp (2)

410-420: Ensure draft logits presence and shape match numDraftTokens when provided

If useDraftLogits is true, we should assert that the provided logits buffer is consistent with the number of draft tokens, and clarify expected dtype (matches modelConfig.getLogitsDtype()).

Consider adding checks similar to:

  • reqDraftLogits is non-null
  • reqDraftLogits->getShape().nbDims == 2 and leading dimension equals numDraftTokens
  • reqDraftLogits dtype matches modelConfig.getLogitsDtype() when speculativeDecodingFastLogits is false

Do you want me to generate a patch adding these validations?


569-621: Zeroing speculative outputs per-request may be unnecessary work

The unconditional zeroing of nextDraftTokens (and nextDraftTokensLen when variable length) on every new speculative request adds memory traffic per request. If the downstream kernels overwrite these buffers every step, this can be skipped.

  • Verify whether the first-step kernels always write these buffers entirely; if yes, avoid zeroing for performance.
  • If partial writes occur, limit zeroing to the active span or use a header field indicating valid length.

I can help benchmark the impact if you share typical batch sizes and token counts.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c7e6145 and 011d81c.

📒 Files selected for processing (8)
  • cpp/include/tensorrt_llm/batch_manager/createNewDecoderRequests.h (0 hunks)
  • cpp/include/tensorrt_llm/batch_manager/llmRequest.h (1 hunks)
  • cpp/include/tensorrt_llm/runtime/decodingInput.h (1 hunks)
  • cpp/include/tensorrt_llm/runtime/request.h (0 hunks)
  • cpp/tensorrt_llm/batch_manager/createNewDecoderRequests.cpp (7 hunks)
  • cpp/tensorrt_llm/batch_manager/utils/logitsThread.cpp (3 hunks)
  • cpp/tensorrt_llm/batch_manager/utils/logitsThread.h (1 hunks)
  • cpp/tensorrt_llm/runtime/decoderState.cpp (4 hunks)
💤 Files with no reviewable changes (2)
  • cpp/include/tensorrt_llm/runtime/request.h
  • cpp/include/tensorrt_llm/batch_manager/createNewDecoderRequests.h
🧰 Additional context used
📓 Path-based instructions (5)
**/*.{cpp,cxx,cc,cu,h,hpp,hxx,hh,cuh}

📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md)

**/*.{cpp,cxx,cc,cu,h,hpp,hxx,hh,cuh}: In C++, close namespaces with a comment naming the namespace (e.g., } // namespace foo)
Prefer const/constexpr variables over #define for constants
Declare variables const if not modified after initialization
Use Allman brace style in C++
C++ filenames use lowerCamelCase and must be case-insensitively unique within a build target
C++ type names use UpperCamelCase
Local variables, methods, and namespaces use lowerCamelCase
Global non-static variables not in anonymous namespace use gPrefix lowerCamelCase (e.g., gExample)
Static globals or globals in anonymous namespaces use sPrefix lowerCamelCase
Locally visible static variables start with 's' (e.g., static std::once_flag sFlag;)
Member variables use mPrefix lowerCamelCase; public members may omit but are encouraged to use 'm'
Constants (enums, global/static/function-scope magic numbers) use kPREFIXED_UPPER_SNAKE (e.g., kDIGIT_NUM)
If macros are unavoidable, use UPPER_SNAKE_CASE (prefer constants over #define)
Constructor parameter that conflicts with a public member name gets trailing underscore (foo_)
Literal suffixes should be uppercase (e.g., 1234L not 1234l)
C++: use spaces only; indent 4 spaces
Run clang-format (LLVM style) before submitting; wrap lines at 120 characters
If formatting must be bypassed, use // clang-format off/on around the section
Prefer smart pointers; use unique_ptr for sole ownership, shared_ptr for shared; weak_ptr only in exceptional cases
Do not use deprecated pre-C++11 smart pointers
Use C++ style comments; avoid C comments except special inline cases; prefer // single-line
Capitalize and punctuate full-sentence comments
Follow Doxygen rules: use //! for comments and //!< for members in C++
Disable code with #if/#endif and mnemonic conditions; avoid commented-out code; avoid dead code
Do not throw exceptions across library boundaries
Use least-forceful casts; avoid removing const/volatile; avoid C-style and functional casts (except constructors); p...

Files:

  • cpp/include/tensorrt_llm/batch_manager/llmRequest.h
  • cpp/include/tensorrt_llm/runtime/decodingInput.h
  • cpp/tensorrt_llm/batch_manager/utils/logitsThread.h
  • cpp/tensorrt_llm/batch_manager/utils/logitsThread.cpp
  • cpp/tensorrt_llm/runtime/decoderState.cpp
  • cpp/tensorrt_llm/batch_manager/createNewDecoderRequests.cpp
**/*.{h,hpp,hxx,hh,cuh,cpp,cxx,cc,cu}

📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md)

Parameter names must be consistent between declarations and definitions

Files:

  • cpp/include/tensorrt_llm/batch_manager/llmRequest.h
  • cpp/include/tensorrt_llm/runtime/decodingInput.h
  • cpp/tensorrt_llm/batch_manager/utils/logitsThread.h
  • cpp/tensorrt_llm/batch_manager/utils/logitsThread.cpp
  • cpp/tensorrt_llm/runtime/decoderState.cpp
  • cpp/tensorrt_llm/batch_manager/createNewDecoderRequests.cpp
**/*.{h,hpp,hxx,hh,cuh}

📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md)

Header files must use include guards named TRTLLM__H without underscores prefix/suffix (e.g., TRTLLM_FOO_BAR_HELLO_H)

Files:

  • cpp/include/tensorrt_llm/batch_manager/llmRequest.h
  • cpp/include/tensorrt_llm/runtime/decodingInput.h
  • cpp/tensorrt_llm/batch_manager/utils/logitsThread.h
**/*.{cpp,cxx,cc,cu,h,hpp,hxx,hh,cuh,py}

📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md)

Prepend NVIDIA copyright header (current year) to all source files

Files:

  • cpp/include/tensorrt_llm/batch_manager/llmRequest.h
  • cpp/include/tensorrt_llm/runtime/decodingInput.h
  • cpp/tensorrt_llm/batch_manager/utils/logitsThread.h
  • cpp/tensorrt_llm/batch_manager/utils/logitsThread.cpp
  • cpp/tensorrt_llm/runtime/decoderState.cpp
  • cpp/tensorrt_llm/batch_manager/createNewDecoderRequests.cpp
**/*.{cpp,cxx,cc,cu}

📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md)

**/*.{cpp,cxx,cc,cu}: Avoid literal values except for 0, nullptr, true, false; use named constexpr for other literals
Place semicolon of empty for/while loop on a new line
Always use brace-delimited bodies for switch/while/do-for/if/else
Use inline C comments in argument lists when parameter meaning is unclear (e.g., /* checkForErrors = */ false)
Do not use assignment in subexpressions (e.g., if (x = y) ... is forbidden)
Switch on enums should enumerate all values and omit default to catch new values at compile time
Structure switch statements; prohibit fallthrough except between empty cases; each case ends with break or throw; return at end of case not allowed; put break inside braces for compound case
Prefer anonymous namespaces over static for internal linkage of functions
Every defined function must be called at least once (no unused methods)

Files:

  • cpp/tensorrt_llm/batch_manager/utils/logitsThread.cpp
  • cpp/tensorrt_llm/runtime/decoderState.cpp
  • cpp/tensorrt_llm/batch_manager/createNewDecoderRequests.cpp
🧬 Code Graph Analysis (3)
cpp/tensorrt_llm/batch_manager/utils/logitsThread.h (1)
cpp/tensorrt_llm/batch_manager/utils/logitsThread.cpp (2)
  • targetModelReceiveLogits (124-165)
  • targetModelReceiveLogits (124-125)
cpp/tensorrt_llm/runtime/decoderState.cpp (2)
cpp/tests/unit_tests/kernels/decodingKernelTest.cpp (2)
  • nvTokenIdType (378-511)
  • nvTokenIdType (514-644)
cpp/include/tensorrt_llm/runtime/decoderState.h (1)
  • mMaxDecodingEngineTokens (235-235)
cpp/tensorrt_llm/batch_manager/createNewDecoderRequests.cpp (3)
cpp/tensorrt_llm/batch_manager/utils/logitsThread.cpp (2)
  • targetModelReceiveLogits (124-165)
  • targetModelReceiveLogits (124-125)
triton_backend/inflight_batcher_llm/src/model_instance_state.cc (2)
  • decodingConfig (594-594)
  • eagleConfig (614-614)
cpp/tensorrt_llm/batch_manager/trtGptModelInflightBatching.h (1)
  • mIsLeaderInOrchMode (582-606)
🔇 Additional comments (4)
cpp/include/tensorrt_llm/batch_manager/llmRequest.h (1)

1113-1113: Guard against absent draft tokens: good fix.

Switching to hasDraftTokens() ? size() : 0 prevents null dereferences and aligns with the method name semantics.

cpp/tensorrt_llm/runtime/decoderState.cpp (1)

372-380: 2D slice view is correctly used for MPI receive path
In createNewDecoderRequests.cpp (lines 412–415), you create a 2D view via

auto draftLogitsHostSlice = ITensor::slice(
    externalDraftTokensInputs->draftLogitsHost,
    {batchIdx, 0},
    numDraftTokens);
retrieveDraftLogits(
    draftLogitsHostSlice,
    …);

That slice is what gets passed into targetModelReceiveLogits, so its internal reshape({rows, vocab}) only touches the 2D view—not the full 3D buffer. No changes needed here.

cpp/tensorrt_llm/batch_manager/createNewDecoderRequests.cpp (2)

50-52: Alias OptionalRef locally is clear and consistent

Local aliasing to tensorrt_llm::common::OptionalRef improves readability and keeps signatures concise.


724-737: Lookahead prompt/config extraction LGTM; dispatcher wiring is clear

The lookahead prompt hand-off and per-request algo config extraction are consistent, and the new dispatcher call centralizes per-mode initialization cleanly.

@Funatiq Funatiq force-pushed the dev/refactor_decoder_requests_x branch from 011d81c to 41c675c Compare August 13, 2025 16:05
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

🔭 Outside diff range comments (1)
cpp/tensorrt_llm/batch_manager/utils/logitsThread.cpp (1)

124-166: Harden MPI receive: validate buffer, fix dims receive pointer, and guard against invalid shapes.

Issues:

  • No null/memory-type check for draftLogitsHost; receiving into GPU memory would be invalid.
  • dims receive uses &dims; pass dims to be conventional and avoid type pitfalls.
  • Missing non-negative shape validation; negative dims lead to invalid reshape.
  • expectedSize multiplies mixed signed/unsigned; cast both dims to uint64_t.

Apply this diff:

 #include "logitsThread.h"
 
+#include "tensorrt_llm/runtime/common.h"
@@
-void targetModelReceiveLogits(runtime::ITensor::SharedPtr& draftLogitsHost,
+void targetModelReceiveLogits(runtime::ITensor::SharedPtr& draftLogitsHost,
     executor::SpeculativeDecodingFastLogitsInfo const& fastLogitsInfo, nvinfer1::DataType logitsDtype)
 {
 #if ENABLE_MULTI_DEVICE
     auto const& worldComm = tensorrt_llm::mpi::MpiComm::world();
 
+    TLLM_CHECK_WITH_INFO(draftLogitsHost, "draftLogitsHost must be a valid host tensor.");
+    TLLM_CHECK_WITH_INFO(
+        draftLogitsHost->getMemoryType() != runtime::MemoryType::kGPU,
+        "draftLogitsHost must reside in host/pinned memory.");
@@
-    int64_t dims[2];
-    MPICHECK(MPI_Mrecv(&dims, count, MPI_INT64_T, &msg, &status));
+    int64_t dims[2];
+    MPICHECK(MPI_Mrecv(dims, count, MPI_INT64_T, &msg, &status));
+
+    TLLM_CHECK_WITH_INFO(dims[0] >= 0 && dims[1] >= 0, "Received invalid logits shape: [%ld, %ld].", dims[0], dims[1]);
@@
-    uint64_t const expectedSize = static_cast<uint64_t>(dims[0]) * dims[1] * tc::getDTypeSize(logitsDtype);
+    uint64_t const expectedSize = static_cast<uint64_t>(dims[0]) * static_cast<uint64_t>(dims[1])
+        * tc::getDTypeSize(logitsDtype);
     TLLM_CHECK((uint64_t) count == expectedSize);
 
     MPICHECK(MPI_Mrecv(draftLogitsHost->data(), count, MPI_UINT8_T, &msg, &status));
 #endif // ENABLE_MULTI_DEVICE
 }
♻️ Duplicate comments (3)
cpp/tensorrt_llm/batch_manager/createNewDecoderRequests.cpp (3)

327-369: Guard MPI bcast on non-leader path and validate metadata before memcpy (still unresolved).

Two correctness issues remain (previously flagged):

  • Potential deadlock: Non-leader unconditionally calls COMM_SESSION.bcast. If tensor parallel is disabled, leader doesn’t broadcast and non-leader hangs.
  • Safety: memcpy from reqDraftLogits->data() lacks size and memory-type validation for SpeculativeDecodingFastLogitsInfo.

Fix by validating metadata size and wrapping the non-leader bcast in a worldConfig.isTensorParallel() check; also remove trailing semicolon after the function for consistency.

 void retrieveDraftLogits(TensorPtr& draftLogitsHost, std::shared_ptr<runtime::ITensor> const& reqDraftLogits,
     ModelConfig const& modelConfig, WorldConfig const& worldConfig, bool speculativeDecodingFastLogits,
     bool isLeaderInOrchMode, BufferManager const& bufferManager)
 {
     TLLM_LOG_TRACE("%s start", __PRETTY_FUNCTION__);
 
     if (!speculativeDecodingFastLogits)
     {
         TLLM_LOG_TRACE("%s stop", __PRETTY_FUNCTION__);
         bufferManager.copy(*reqDraftLogits, *draftLogitsHost);
         return;
     }
 
     if (isLeaderInOrchMode)
     {
-        te::SpeculativeDecodingFastLogitsInfo fastLogitsInfo;
-        std::memcpy(&fastLogitsInfo, reqDraftLogits->data(), sizeof(fastLogitsInfo));
+        // Validate metadata buffer
+        TLLM_CHECK_WITH_INFO(
+            reqDraftLogits->getSizeInBytes() >= sizeof(te::SpeculativeDecodingFastLogitsInfo),
+            "Draft logits metadata buffer too small for SpeculativeDecodingFastLogitsInfo.");
+        TLLM_CHECK_WITH_INFO(
+            reqDraftLogits->getMemoryType() != MemoryType::kGPU,
+            "Fast logits metadata must be in host/pinned memory.");
+        te::SpeculativeDecodingFastLogitsInfo fastLogitsInfo{};
+        std::memcpy(&fastLogitsInfo, reqDraftLogits->data(), sizeof(te::SpeculativeDecodingFastLogitsInfo));
         utils::targetModelReceiveLogits(draftLogitsHost, fastLogitsInfo, modelConfig.getLogitsDtype());
 
         // Broadcast to other ranks if needed
         if (worldConfig.isTensorParallel())
         {
             auto const& commSession = COMM_SESSION;
             auto shape = draftLogitsHost->getShape();
             commSession.bcastValue(shape.d[0], 0);
             commSession.bcastValue(shape.d[1], 0);
             commSession.bcast(draftLogitsHost->data(), draftLogitsHost->getSizeInBytes(), mpi::MpiType::kUINT8, 0);
         }
     }
     else
     {
-        // Get logits from leader rank
-        auto const& commSession = COMM_SESSION;
-        int64_t dims[2];
-        commSession.bcastValue(dims[0], 0);
-        commSession.bcastValue(dims[1], 0);
-        draftLogitsHost->reshape(ITensor::makeShape({dims[0], dims[1]}));
-        commSession.bcast(draftLogitsHost->data(), draftLogitsHost->getSizeInBytes(), mpi::MpiType::kUINT8, 0);
+        // Receive logits from leader rank only when TP is enabled
+        if (worldConfig.isTensorParallel())
+        {
+            auto const& commSession = COMM_SESSION;
+            int64_t dims[2];
+            commSession.bcastValue(dims[0], 0);
+            commSession.bcastValue(dims[1], 0);
+            draftLogitsHost->reshape(ITensor::makeShape({dims[0], dims[1]}));
+            commSession.bcast(draftLogitsHost->data(), draftLogitsHost->getSizeInBytes(), mpi::MpiType::kUINT8, 0);
+        }
+        else
+        {
+            TLLM_THROW("Fast logits path requires tensor-parallel broadcast for non-leader ranks.");
+        }
     }
 
     TLLM_LOG_TRACE("%s stop", __PRETTY_FUNCTION__);
-};
+}

672-680: Sanity-check external draft-token availability before deriving numDecodingEngineTokens.

If getNumDraftTokens() > 0 but the external tensor is missing, downstream copies will OOB or null-deref. Fail fast here.

-        SizeType32 numDecodingEngineTokens{1};
+        SizeType32 numDecodingEngineTokens{1};
         if (modelConfig.getSpeculativeDecodingMode().isDraftTokensExternal())
         {
-            numDecodingEngineTokens = llmReq->getNumDraftTokens() + 1;
+            auto const draftLen = llmReq->getNumDraftTokens();
+            TLLM_CHECK_WITH_INFO(draftLen == 0 || llmReq->getDraftTokens(),
+                "External speculative decoding requested with %d draft tokens, but no draft-token tensor provided.",
+                draftLen);
+            numDecodingEngineTokens = draftLen + 1;
         }
         else if (!modelConfig.getSpeculativeDecodingMode().isNone())
         {
             numDecodingEngineTokens = modelConfig.getMaxDecodingTokens();
         }

370-421: Validate presence and shape of external draft tokens before copying.

When numDraftTokens > 0, the code dereferences llmReq.getDraftTokens() without validating presence or shape. This risks OOB copies.

 void newRequestDraftTokensExternal(DecodingInput& jointDecodingInput, SizeType32 batchIdx, LlmRequest const& llmReq,
     SizeType32 numDecodingEngineTokens, runtime::ModelConfig const& modelConfig, WorldConfig const& worldConfig,
     bool speculativeDecodingFastLogits, bool isLeaderInOrchMode, CudaStream const& decoderStream)
 {
@@
     auto const& draftTokens = llmReq.getDraftTokens();
     auto const numDraftTokens = numDecodingEngineTokens - 1;
@@
-    if (numDraftTokens > 0)
+    if (numDraftTokens > 0)
     {
+        TLLM_CHECK_WITH_INFO(draftTokens, "External draft tokens mode expects non-empty draft tokens.");
+        auto const dtShape = draftTokens->getShape();
+        TLLM_CHECK_WITH_INFO(
+            dtShape.nbDims == 2 && dtShape.d[0] == 1 && dtShape.d[1] >= numDraftTokens,
+            tc::fmtstr("Unexpected draft tokens shape. Expected [1, >= %d], got [%d, %d].",
+                numDraftTokens, (dtShape.nbDims > 0 ? (int) dtShape.d[0] : -1),
+                (dtShape.nbDims > 1 ? (int) dtShape.d[1] : -1)));
         TensorPtr draftTokenIdsHostSlice
             = ITensor::slice(externalDraftTokensInputs->draftTokenIdsHost, {batchIdx, 0}, numDraftTokens);
         // Copy to pinned host memory (don't care about stream of bufferManager)
         decoderBufferManager.copy(draftTokens->data(), *draftTokenIdsHostSlice);
@@
     if (useDraftLogits)
     {
         TensorPtr draftLogitsHostSlice
             = ITensor::slice(externalDraftTokensInputs->draftLogitsHost, {batchIdx, 0}, numDraftTokens);
         retrieveDraftLogits(draftLogitsHostSlice, draftLogits.value(), modelConfig, worldConfig,
             speculativeDecodingFastLogits, isLeaderInOrchMode, decoderBufferManager);
🧹 Nitpick comments (3)
cpp/include/tensorrt_llm/runtime/decodingInput.h (1)

104-118: Document memory-type and shape invariants for host draft buffers.

Please add brief Doxygen comments for draftLogitsHost and draftTokenIdsHost clarifying:

  • Expected memory type (pinned host via MemoryType::kPINNEDPOOL).
  • Shape invariants mirroring device tensors (same 2D shapes as draftLogits and draftTokenIds per step).
  • Dtype consistency with logits/token IDs.

This will reduce future misuse and ease maintenance.

 class ExternalDraftTokensInputs
 {
 public:
     TensorPtr draftLogits;
+    //! Host-pinned counterpart of draftLogits. Shape and dtype must mirror draftLogits.
+    //! Allocated from pinned pool (MemoryType::kPINNEDPOOL).
     TensorPtr draftLogitsHost;
@@
     TensorPtr numDraftTokensHost;
     TensorPtr draftTokenIds;
+    //! Host-pinned counterpart of draftTokenIds. Shape must mirror draftTokenIds.
+    //! Allocated from pinned pool (MemoryType::kPINNEDPOOL).
     TensorPtr draftTokenIdsHost;
cpp/tensorrt_llm/batch_manager/createNewDecoderRequests.cpp (2)

505-567: Eagle setup: host-side control tensors and static-tree init are reasonable.

Initialization of ctx/gen request types and lengths, and static-tree path generation with validation against module depth, look sound. Consider adding a brief comment clarifying that dynamic-tree handling is deferred when eagleConfig->useDynamicTree() is true.


569-621: Avoid zeroing large nextDraftTokens buffers unless required.

Zeroing nextDraftTokens (and length) eagerly can be costly at scale. If kernels overwrite these fully, skip zeroing or restrict it to variableDraftLength cases where length buffers are read before write.

-        TensorPtr nextDraftTokens = ITensor::slice(speculativeDecodingOutputs.nextDraftTokens, batchIdx, 1);
-        // FIXME: can we skip this?
-        manager.setZero(*nextDraftTokens);
+        TensorPtr nextDraftTokens = ITensor::slice(speculativeDecodingOutputs.nextDraftTokens, batchIdx, 1);
+        // Zero only if downstream reads before write; otherwise omit to save time.
+        // manager.setZero(*nextDraftTokens);
         if (speculativeDecodingMode.variableDraftLength())
         {
             TensorPtr nextDraftTokensLen = ITensor::slice(speculativeDecodingOutputs.nextDraftTokensLen, batchIdx, 1);
             manager.setZero(*nextDraftTokensLen);
         }
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 011d81c and 41c675c.

📒 Files selected for processing (6)
  • cpp/include/tensorrt_llm/runtime/decodingInput.h (1 hunks)
  • cpp/include/tensorrt_llm/runtime/request.h (0 hunks)
  • cpp/tensorrt_llm/batch_manager/createNewDecoderRequests.cpp (7 hunks)
  • cpp/tensorrt_llm/batch_manager/utils/logitsThread.cpp (3 hunks)
  • cpp/tensorrt_llm/batch_manager/utils/logitsThread.h (1 hunks)
  • cpp/tensorrt_llm/runtime/decoderState.cpp (4 hunks)
💤 Files with no reviewable changes (1)
  • cpp/include/tensorrt_llm/runtime/request.h
🚧 Files skipped from review as they are similar to previous changes (2)
  • cpp/tensorrt_llm/batch_manager/utils/logitsThread.h
  • cpp/tensorrt_llm/runtime/decoderState.cpp
🧰 Additional context used
📓 Path-based instructions (5)
**/*.{cpp,cxx,cc,cu,h,hpp,hxx,hh,cuh}

📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md)

**/*.{cpp,cxx,cc,cu,h,hpp,hxx,hh,cuh}: In C++, close namespaces with a comment naming the namespace (e.g., } // namespace foo)
Prefer const/constexpr variables over #define for constants
Declare variables const if not modified after initialization
Use Allman brace style in C++
C++ filenames use lowerCamelCase and must be case-insensitively unique within a build target
C++ type names use UpperCamelCase
Local variables, methods, and namespaces use lowerCamelCase
Global non-static variables not in anonymous namespace use gPrefix lowerCamelCase (e.g., gExample)
Static globals or globals in anonymous namespaces use sPrefix lowerCamelCase
Locally visible static variables start with 's' (e.g., static std::once_flag sFlag;)
Member variables use mPrefix lowerCamelCase; public members may omit but are encouraged to use 'm'
Constants (enums, global/static/function-scope magic numbers) use kPREFIXED_UPPER_SNAKE (e.g., kDIGIT_NUM)
If macros are unavoidable, use UPPER_SNAKE_CASE (prefer constants over #define)
Constructor parameter that conflicts with a public member name gets trailing underscore (foo_)
Literal suffixes should be uppercase (e.g., 1234L not 1234l)
C++: use spaces only; indent 4 spaces
Run clang-format (LLVM style) before submitting; wrap lines at 120 characters
If formatting must be bypassed, use // clang-format off/on around the section
Prefer smart pointers; use unique_ptr for sole ownership, shared_ptr for shared; weak_ptr only in exceptional cases
Do not use deprecated pre-C++11 smart pointers
Use C++ style comments; avoid C comments except special inline cases; prefer // single-line
Capitalize and punctuate full-sentence comments
Follow Doxygen rules: use //! for comments and //!< for members in C++
Disable code with #if/#endif and mnemonic conditions; avoid commented-out code; avoid dead code
Do not throw exceptions across library boundaries
Use least-forceful casts; avoid removing const/volatile; avoid C-style and functional casts (except constructors); p...

Files:

  • cpp/include/tensorrt_llm/runtime/decodingInput.h
  • cpp/tensorrt_llm/batch_manager/utils/logitsThread.cpp
  • cpp/tensorrt_llm/batch_manager/createNewDecoderRequests.cpp
**/*.{h,hpp,hxx,hh,cuh,cpp,cxx,cc,cu}

📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md)

Parameter names must be consistent between declarations and definitions

Files:

  • cpp/include/tensorrt_llm/runtime/decodingInput.h
  • cpp/tensorrt_llm/batch_manager/utils/logitsThread.cpp
  • cpp/tensorrt_llm/batch_manager/createNewDecoderRequests.cpp
**/*.{h,hpp,hxx,hh,cuh}

📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md)

Header files must use include guards named TRTLLM__H without underscores prefix/suffix (e.g., TRTLLM_FOO_BAR_HELLO_H)

Files:

  • cpp/include/tensorrt_llm/runtime/decodingInput.h
**/*.{cpp,cxx,cc,cu,h,hpp,hxx,hh,cuh,py}

📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md)

Prepend NVIDIA copyright header (current year) to all source files

Files:

  • cpp/include/tensorrt_llm/runtime/decodingInput.h
  • cpp/tensorrt_llm/batch_manager/utils/logitsThread.cpp
  • cpp/tensorrt_llm/batch_manager/createNewDecoderRequests.cpp
**/*.{cpp,cxx,cc,cu}

📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md)

**/*.{cpp,cxx,cc,cu}: Avoid literal values except for 0, nullptr, true, false; use named constexpr for other literals
Place semicolon of empty for/while loop on a new line
Always use brace-delimited bodies for switch/while/do-for/if/else
Use inline C comments in argument lists when parameter meaning is unclear (e.g., /* checkForErrors = */ false)
Do not use assignment in subexpressions (e.g., if (x = y) ... is forbidden)
Switch on enums should enumerate all values and omit default to catch new values at compile time
Structure switch statements; prohibit fallthrough except between empty cases; each case ends with break or throw; return at end of case not allowed; put break inside braces for compound case
Prefer anonymous namespaces over static for internal linkage of functions
Every defined function must be called at least once (no unused methods)

Files:

  • cpp/tensorrt_llm/batch_manager/utils/logitsThread.cpp
  • cpp/tensorrt_llm/batch_manager/createNewDecoderRequests.cpp
⏰ 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)
cpp/include/tensorrt_llm/runtime/decodingInput.h (1)

104-118: Host-side draft buffers addition looks correct and consistent with device counterparts.

Adding draftLogitsHost and draftTokenIdsHost alongside their device counterparts aligns with the PR’s intent and enables in-place host operations for speculative decoding paths.

cpp/tensorrt_llm/batch_manager/createNewDecoderRequests.cpp (4)

25-30: Includes are appropriate for new host/device buffer usage.

Adding runtime/common.h and runtime/iBuffer.h is correct for MemoryType, BufferRange/IBuffer helpers used later.


50-52: Local OptionalRef alias is fine.

The alias reduces verbosity in this TU and keeps linkage local. No concerns.


471-486: Lookahead setup checks and initialization look good.

Presence checks for lookahead inputs/outputs and initializing tokensPerStep to 1 for the first step are correct.


488-501: Explicit draft tokens: initializing positionIdsBase from promptLen is correct.

No issues.

@tensorrt-cicd
Copy link
Collaborator

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

@Funatiq
Copy link
Collaborator Author

Funatiq commented Aug 13, 2025

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #15164 [ run ] triggered by Bot

…space

- Removed several static functions related to request initialization from the public interface.
- Moved speculative decoding setup functions to anonymous namespace.

Signed-off-by: Robin Kobus <19427718+Funatiq@users.noreply.github.com>
- Removed the inputLen parameter from the Request constructor and adjusted related functions to use inputLen directly.
- Updated newRequestLookahead, newRequestExplicitDraftTokens, and newRequestEagle functions to accept inputLen as a parameter instead of the entire Request object.
- Enhanced clarity and maintainability by streamlining function signatures and reducing dependencies on the Request structure.

Signed-off-by: Robin Kobus <19427718+Funatiq@users.noreply.github.com>
…derRequests

- Modified getNumDraftTokens to return 0 if no draft tokens are present, enhancing robustness.
- Updated Request constructor to initialize generatedTokensPerEngineStep directly from the constructor parameter.
- Simplified the creation of decoder requests by removing unnecessary local variables and directly using the updated token count logic.

Signed-off-by: Robin Kobus <19427718+Funatiq@users.noreply.github.com>
…lone function

- Moved the retrieveDraftLogits logic from CreateNewDecoderRequests to a new standalone function, enhancing modularity and readability.
- Updated the function signature to include parameters for speculative decoding and orchestration mode, allowing for more flexible usage.
- Adjusted calls to retrieveDraftLogits within createDecoderRequests to accommodate the new function structure.

Signed-off-by: Robin Kobus <19427718+Funatiq@users.noreply.github.com>
- Introduced draftLogitsHost and draftTokenIdsHost to manage draft logits and token IDs in pinned memory, improving performance during speculative decoding.
- Updated retrieveDraftLogits function to accept draftLogitsHost as a parameter, streamlining the data retrieval process.
- Adjusted the setup of externalDraftTokensInputs in DecoderState to include host tensors, ensuring proper memory management and data flow.

Signed-off-by: Robin Kobus <19427718+Funatiq@users.noreply.github.com>
- Deleted the Request class from the runtime module, simplifying the codebase and reducing dependencies.
- Updated functions in CreateNewDecoderRequests to directly utilize LlmRequest, enhancing clarity and maintainability.
- Adjusted function signatures to accommodate the removal of the Request class, ensuring seamless integration with existing logic.

Signed-off-by: Robin Kobus <19427718+Funatiq@users.noreply.github.com>
…DraftLogits

- Introduced size validation for reqDraftLogits to ensure it can accommodate SpeculativeDecodingFastLogitsInfo, enhancing robustness.
- Added a check for tensor-parallel broadcast requirement for non-leader ranks, improving error handling in the decoding process.

Signed-off-by: Robin Kobus <19427718+Funatiq@users.noreply.github.com>
@Funatiq Funatiq force-pushed the dev/refactor_decoder_requests_x branch from ff9d6f4 to 7ce1635 Compare August 20, 2025 10:31
@Funatiq
Copy link
Collaborator Author

Funatiq commented Aug 20, 2025

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #15913 [ run ] triggered by Bot

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
cpp/include/tensorrt_llm/batch_manager/llmRequest.h (1)

28-36: Include what you use: add and .

This header uses std::list (createListTensor signature) and std::memcpy without including and . It may compile via transitive includes, but it’s fragile and can break across platforms/compilers.

 #include <algorithm>
 #include <cassert>
 #include <chrono>
 #include <cstdint>
+#include <cstring>  // std::memcpy
+#include <list>     // std::list
 #include <memory>
 #include <optional>
 #include <utility>
 #include <vector>
🧹 Nitpick comments (7)
cpp/include/tensorrt_llm/batch_manager/llmRequest.h (7)

1111-1114: Null-safe draft-token count is correct; add explicit cast and noexcept (minor).

Good defensive change. To avoid implicit narrowing warnings and match other trivial getters, add an explicit cast and noexcept.

-    [[nodiscard]] SizeType32 getNumDraftTokens() const
+    [[nodiscard]] SizeType32 getNumDraftTokens() const noexcept
     {
-        return hasDraftTokens() ? mDraftTokens->size() : 0;
+        return hasDraftTokens() ? static_cast<SizeType32>(mDraftTokens->size()) : 0;
     }

1067-1071: Remove redundant check.

The second TLLM_CHECK duplicates the preceding TLLM_CHECK_WITH_INFO on the same condition and adds no value.

         TLLM_CHECK_WITH_INFO(prepopulatedPromptLen < promptLen,
             "Invalid state: prepopulatedPromptLen (%d) >= promptLen (%d) for request %lu", prepopulatedPromptLen,
             promptLen, mRequestId);
-        TLLM_CHECK(prepopulatedPromptLen < promptLen);

1384-1388: Make hasAdditionalOutputs() a const member.

Pure query; should be const.

-    bool hasAdditionalOutputs()
+    bool hasAdditionalOutputs() const
     {
         return !mAdditionalContextOutputTensors.empty() || !mAdditionalGenerationOutputTensors.empty();
     }

1374-1377: Const-correctness and explicit cast for getGenerationLogitsFragmentsSize().

This simple accessor can be const; add explicit cast to SizeType32.

-    SizeType32 getGenerationLogitsFragmentsSize()
+    SizeType32 getGenerationLogitsFragmentsSize() const
     {
-        return mGenerationLogitsFragments.size();
+        return static_cast<SizeType32>(mGenerationLogitsFragments.size());
     }

2156-2165: Prefer std::copy over std::memcpy for type safety.

Avoid C-library functions when possible (guideline). Using std::copy improves type-safety and readability.

-        auto* data = runtime::bufferCast<int32_t>(*tensor);
-        std::memcpy(data, words.data(), numWords * sizeof(int32_t));
-        std::memcpy(data + numWords, offsets.data(), numWords * sizeof(int32_t));
+        auto* data = runtime::bufferCast<int32_t>(*tensor);
+        std::copy(words.begin(), words.end(), data);
+        std::copy(offsets.begin(), offsets.end(), data + numWords);

1-15: Nit: update copyright year.

Guideline asks for current year; consider updating to 2025.

- * Copyright (c) 2022-2024, NVIDIA CORPORATION.  All rights reserved.
+ * Copyright (c) 2022-2025, NVIDIA CORPORATION.  All rights reserved.

17-19: Header guards per guideline (non-blocking).

Project guideline prefers include guards (TRTLLM__H). You currently use #pragma once. Consider adding guards for portability.

+#ifndef TRTLLM_LLMREQUEST_H
+#define TRTLLM_LLMREQUEST_H
 #pragma once
 ...
-} // namespace tensorrt_llm::batch_manager
+} // namespace tensorrt_llm::batch_manager
+
+#endif // TRTLLM_LLMREQUEST_H

Also applies to: 2377-2378

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between ff9d6f4 and 7ce1635.

📒 Files selected for processing (7)
  • cpp/include/tensorrt_llm/batch_manager/createNewDecoderRequests.h (0 hunks)
  • cpp/include/tensorrt_llm/batch_manager/llmRequest.h (1 hunks)
  • cpp/include/tensorrt_llm/runtime/decodingInput.h (1 hunks)
  • cpp/include/tensorrt_llm/runtime/request.h (0 hunks)
  • cpp/tensorrt_llm/batch_manager/createNewDecoderRequests.cpp (7 hunks)
  • cpp/tensorrt_llm/batch_manager/utils/logitsThread.cpp (3 hunks)
  • cpp/tensorrt_llm/batch_manager/utils/logitsThread.h (1 hunks)
💤 Files with no reviewable changes (2)
  • cpp/include/tensorrt_llm/batch_manager/createNewDecoderRequests.h
  • cpp/include/tensorrt_llm/runtime/request.h
🚧 Files skipped from review as they are similar to previous changes (4)
  • cpp/include/tensorrt_llm/runtime/decodingInput.h
  • cpp/tensorrt_llm/batch_manager/utils/logitsThread.h
  • cpp/tensorrt_llm/batch_manager/utils/logitsThread.cpp
  • cpp/tensorrt_llm/batch_manager/createNewDecoderRequests.cpp
🧰 Additional context used
📓 Path-based instructions (4)
**/*.{cpp,cxx,cc,cu,h,hpp,hxx,hh,cuh}

📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md)

**/*.{cpp,cxx,cc,cu,h,hpp,hxx,hh,cuh}: In C++, close namespaces with a comment naming the namespace (e.g., } // namespace foo)
Prefer const/constexpr variables over #define for constants
Declare variables const if not modified after initialization
Use Allman brace style in C++
C++ filenames use lowerCamelCase and must be case-insensitively unique within a build target
C++ type names use UpperCamelCase
Local variables, methods, and namespaces use lowerCamelCase
Global non-static variables not in anonymous namespace use gPrefix lowerCamelCase (e.g., gExample)
Static globals or globals in anonymous namespaces use sPrefix lowerCamelCase
Locally visible static variables start with 's' (e.g., static std::once_flag sFlag;)
Member variables use mPrefix lowerCamelCase; public members may omit but are encouraged to use 'm'
Constants (enums, global/static/function-scope magic numbers) use kPREFIXED_UPPER_SNAKE (e.g., kDIGIT_NUM)
If macros are unavoidable, use UPPER_SNAKE_CASE (prefer constants over #define)
Constructor parameter that conflicts with a public member name gets trailing underscore (foo_)
Literal suffixes should be uppercase (e.g., 1234L not 1234l)
C++: use spaces only; indent 4 spaces
Run clang-format (LLVM style) before submitting; wrap lines at 120 characters
If formatting must be bypassed, use // clang-format off/on around the section
Prefer smart pointers; use unique_ptr for sole ownership, shared_ptr for shared; weak_ptr only in exceptional cases
Do not use deprecated pre-C++11 smart pointers
Use C++ style comments; avoid C comments except special inline cases; prefer // single-line
Capitalize and punctuate full-sentence comments
Follow Doxygen rules: use //! for comments and //!< for members in C++
Disable code with #if/#endif and mnemonic conditions; avoid commented-out code; avoid dead code
Do not throw exceptions across library boundaries
Use least-forceful casts; avoid removing const/volatile; avoid C-style and functional casts (except constructors); p...

Files:

  • cpp/include/tensorrt_llm/batch_manager/llmRequest.h
**/*.{h,hpp,hxx,hh,cuh,cpp,cxx,cc,cu}

📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md)

Parameter names must be consistent between declarations and definitions

Files:

  • cpp/include/tensorrt_llm/batch_manager/llmRequest.h
**/*.{h,hpp,hxx,hh,cuh}

📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md)

Header files must use include guards named TRTLLM__H without underscores prefix/suffix (e.g., TRTLLM_FOO_BAR_HELLO_H)

Files:

  • cpp/include/tensorrt_llm/batch_manager/llmRequest.h
**/*.{cpp,cxx,cc,cu,h,hpp,hxx,hh,cuh,py}

📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md)

Prepend NVIDIA copyright header (current year) to all source files

Files:

  • cpp/include/tensorrt_llm/batch_manager/llmRequest.h
⏰ 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

@tensorrt-cicd
Copy link
Collaborator

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

@Funatiq
Copy link
Collaborator Author

Funatiq commented Aug 21, 2025

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #16027 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

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

@Funatiq Funatiq marked this pull request as ready for review August 22, 2025 08:26
@Funatiq Funatiq requested a review from DomBrown August 22, 2025 08:35
@DomBrown DomBrown self-requested a review August 22, 2025 16:27
@Funatiq Funatiq merged commit 37543a9 into NVIDIA:main Aug 22, 2025
6 checks passed
@Funatiq Funatiq deleted the dev/refactor_decoder_requests_x branch August 22, 2025 16:44
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