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

Conversation

@Funatiq
Copy link
Collaborator

@Funatiq Funatiq commented Aug 1, 2025

Summary by CodeRabbit

  • Refactor

    • Decoder request setup streamlined: external buffer manager removed from public calls and initialization split into smaller modular steps for clearer, more reliable per-call buffer handling.
    • Language bindings updated to reflect the simplified call signature.
  • New Features

    • Added a public API to set beam width for individual decoder requests.
  • Chores

    • Updated tests and internal call sites to match the new interfaces.

Description

  • Remove many parameters from decoder request and remove newRequest function.
  • Instead introduce more fine grained functions to initialize decoder state directly.
  • Now decoder request is only needed for speculative decoding initialization.

Follow up task:

  • Simplify speculative decoding initialization and remove decoder request completely.

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 1, 2025

📝 Walkthrough

Walkthrough

Removes the external BufferManager parameter from CreateNewDecoderRequests APIs and bindings, localizes buffer management inside CreateNewDecoderRequests, refactors request initialization into smaller helpers, simplifies Request by removing several fields, and adds DecoderState::setBeamWidth.

Changes

Cohort / File(s) Change Summary
Batch manager API header
cpp/include/tensorrt_llm/batch_manager/createNewDecoderRequests.h
Removed runtime::BufferManager const& parameter from operator() and createDecoderRequests declarations; removed private static newRequest method.
Batch manager implementation
cpp/tensorrt_llm/batch_manager/createNewDecoderRequests.cpp
Dropped external BufferManager from operator() and createDecoderRequests; created local BufferManager from CUDA stream; replaced large newRequest with modular helpers (initializeInputLengths, initializeRequestIds, initializeBeamSearch, initializeEmbeddingBias, setupWords, initializeLogProbs, initializeOutputs); added internal alias SharedConstPtr; refactored speculative decoding paths to use local buffer manager.
Request type
cpp/include/tensorrt_llm/runtime/request.h
Simplified Request constructor to Request(SizeType32 inputLen) and removed members: ids, maxNewTokens, endId, embeddingBias, badWordsList, stopWordsList.
DecoderState
cpp/include/tensorrt_llm/runtime/decoderState.h, cpp/tensorrt_llm/runtime/decoderState.cpp
Added void setBeamWidth(SizeType32 batchIdx, SizeType32 beamWidth) (bounds-checked) and its implementation.
Call sites & tests
cpp/tensorrt_llm/batch_manager/trtGptModelInflightBatching.cpp, cpp/tests/runtime/gptDecoderBatchedTest.cpp, tensorrt_llm/_torch/pyexecutor/sampler.py
Updated calls to CreateNewDecoderRequests to omit BufferManager and reorder parameters accordingly; removed local BufferManager creation where applicable; adjusted call formatting.
Bindings (nanobind / pybind)
cpp/tensorrt_llm/nanobind/batch_manager/algorithms.cpp, cpp/tensorrt_llm/pybind/batch_manager/algorithms.cpp
Removed bufferManager / buffer_manager parameter from the Python and nanobind bindings for CreateNewDecoderRequests::__call__; updated lambda signatures and exposed argument order.
Python executor
tensorrt_llm/_torch/pyexecutor/sampler.py
Updated create_new_decoder_requests invocation to stop passing buffer_manager and adjusted positional arguments (logits datatype shifted; beam width appended).

Sequence Diagram(s)

sequenceDiagram
    participant Caller
    participant CreateNewDecoderRequests
    participant DecoderState

    Caller->>CreateNewDecoderRequests: operator()(modelCfg, worldCfg, decodingCfg, requests, logitsType, inputBuffers, decoderState, runtimeStream, decoderStream, maxSeqLen, beamWidth, medusa)
    CreateNewDecoderRequests->>CreateNewDecoderRequests: construct local BufferManager(runtimeStream)
    CreateNewDecoderRequests->>CreateNewDecoderRequests: initializeInputLengths(...)
    CreateNewDecoderRequests->>CreateNewDecoderRequests: initializeRequestIds(...)
    CreateNewDecoderRequests->>CreateNewDecoderRequests: initializeBeamSearch(...)
    CreateNewDecoderRequests->>CreateNewDecoderRequests: initializeEmbeddingBias(...)
    CreateNewDecoderRequests->>CreateNewDecoderRequests: setupWords(...)
    CreateNewDecoderRequests->>CreateNewDecoderRequests: initializeLogProbs(...)
    CreateNewDecoderRequests->>CreateNewDecoderRequests: initializeOutputs(...)
    CreateNewDecoderRequests->>DecoderState: setBeamWidth(batchIdx, beamWidth)
    CreateNewDecoderRequests-->>Caller: return (inputTensor, samplingConfigs, requestTensors, lookaheadConfigs)
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested reviewers

  • DomBrown
  • dcampora
  • shaharmor98
  • syuoni
✨ 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 1, 2025

/bot run

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: 0

🧹 Nitpick comments (4)
cpp/include/tensorrt_llm/runtime/request.h (1)

40-40: Member variable should follow naming convention with 'm' prefix.

According to the coding guidelines, class member variables should use camelCase prefixed with 'm'. Consider renaming inputLen to mInputLen for consistency.

-    SizeType32 inputLen; // Input length without draft tokens, increasing with generation steps
+    SizeType32 mInputLen; // Input length without draft tokens, increasing with generation steps
cpp/tensorrt_llm/batch_manager/createNewDecoderRequests.cpp (3)

55-56: Consider performance impact of creating BufferManager instances.

Creating a new BufferManager with a shared pointer for each function call may have performance implications if this function is called frequently. Consider if the BufferManager instance could be reused or passed as a member variable.


269-270: Address FIXME: Monotonically growing jointMaxWordsLen.

The comment indicates that jointMaxWordsLen only increases and never decreases, which could lead to inefficient memory usage over time if requests with smaller word lists follow those with larger lists.

Would you like me to open an issue to track implementing a more efficient approach for managing the maximum word list length?


322-337: Consider optimizing repeated setZero calls.

As noted in the comment, the code calls setZero multiple times for single elements. Consider batching these operations or using a more efficient approach to initialize the finishedSteps tensor.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 16febef and e390636.

📒 Files selected for processing (8)
  • cpp/include/tensorrt_llm/batch_manager/createNewDecoderRequests.h (1 hunks)
  • cpp/include/tensorrt_llm/runtime/request.h (1 hunks)
  • cpp/tensorrt_llm/batch_manager/createNewDecoderRequests.cpp (9 hunks)
  • cpp/tensorrt_llm/batch_manager/trtGptModelInflightBatching.cpp (1 hunks)
  • cpp/tensorrt_llm/nanobind/batch_manager/algorithms.cpp (1 hunks)
  • cpp/tensorrt_llm/pybind/batch_manager/algorithms.cpp (1 hunks)
  • cpp/tests/runtime/gptDecoderBatchedTest.cpp (1 hunks)
  • tensorrt_llm/_torch/pyexecutor/sampler.py (1 hunks)
🧰 Additional context used
📓 Path-based instructions (4)
**/*.{cpp,h,hpp,cc,cxx}

📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md)

**/*.{cpp,h,hpp,cc,cxx}: Closing braces of namespaces should have a comment saying the namespace it closes (e.g., } // namespace foo)
Prefer const or constexpr variables over #defines whenever possible, as the latter are not visible to the compiler.
A variable that is not modified after its initialization should be declared as const.
Except 0 (only used in comparison for checking signness/existence/emptiness) and nullptr, true, false, all other literals should only be used for variable initialization.
Use the Allman indentation style for braces.
Put the semicolon for an empty for or while loop in a new line.
The statement forming the body of a switch, while, do .. while or for statement shall be a compound statement (use brace-delimited statements).
If and else should always be followed by brace-delimited statements, even if empty or a single statement.
C++ filenames should use camel case with first letter lowercase (e.g., thisIsAFilename.cpp), and all files involved in the compilation of a target must have filenames that are case-insensitive unique.
All types (including class names) are camel case with uppercase first letter (e.g., FooBarClass).
Local variables, methods, and namespaces use camel case with first letter lowercase (e.g., localFooBar).
Non-magic-number global variables that are non-static and not defined in anonymous namespace use camel case prefixed by a lower case 'g' (e.g., gDontUseGlobalFoos).
Non-magic-number global variables that are static or defined in an anonymous namespace use camel case prefixed by a lower case 's' (e.g., sMutableStaticGlobal).
Locally visible static variable uses camel case with lowercase prefix 's' as the first letter of the name (e.g., static std::once_flag sFlag;).
Class member variables use camel case prefixed with an 'm' (e.g., mNbFooValues). Public member variables do not require the 'm' prefix but it is encouraged for clarity.
Enumerations, global constants, static constants at class-scope, and function-scope magic...

Files:

  • cpp/tensorrt_llm/nanobind/batch_manager/algorithms.cpp
  • cpp/tests/runtime/gptDecoderBatchedTest.cpp
  • cpp/tensorrt_llm/batch_manager/trtGptModelInflightBatching.cpp
  • cpp/tensorrt_llm/pybind/batch_manager/algorithms.cpp
  • cpp/include/tensorrt_llm/runtime/request.h
  • cpp/include/tensorrt_llm/batch_manager/createNewDecoderRequests.h
  • cpp/tensorrt_llm/batch_manager/createNewDecoderRequests.cpp
**/*.{cpp,h,hpp,cc,cxx,cu,py}

📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md)

All TensorRT-LLM Open Source Software code should contain an NVIDIA copyright header that includes the current year. This includes .cpp, .h, .cu, .py, and any other source files which are compiled or interpreted.

Files:

  • cpp/tensorrt_llm/nanobind/batch_manager/algorithms.cpp
  • cpp/tests/runtime/gptDecoderBatchedTest.cpp
  • tensorrt_llm/_torch/pyexecutor/sampler.py
  • cpp/tensorrt_llm/batch_manager/trtGptModelInflightBatching.cpp
  • cpp/tensorrt_llm/pybind/batch_manager/algorithms.cpp
  • cpp/include/tensorrt_llm/runtime/request.h
  • cpp/include/tensorrt_llm/batch_manager/createNewDecoderRequests.h
  • cpp/tensorrt_llm/batch_manager/createNewDecoderRequests.cpp
**/*.py

📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md)

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

Files:

  • tensorrt_llm/_torch/pyexecutor/sampler.py
**/*.{h,hpp}

📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md)

Use a preprocessor guard in header files. The guard name must have prefix TRTLLM_ followed by the filename, all in caps, and no trailing underscore.

Files:

  • cpp/include/tensorrt_llm/runtime/request.h
  • cpp/include/tensorrt_llm/batch_manager/createNewDecoderRequests.h
🧠 Learnings (1)
📚 Learning: in tensorrt-llm's multimodal processing pipeline, shared tensor recovery using `from_shared_tensor()...
Learnt from: yechank-nvidia
PR: NVIDIA/TensorRT-LLM#6254
File: tensorrt_llm/_torch/pyexecutor/model_engine.py:1201-1204
Timestamp: 2025-07-22T09:22:14.726Z
Learning: In TensorRT-LLM's multimodal processing pipeline, shared tensor recovery using `from_shared_tensor()` is only needed during the context phase. Generation requests reuse the already-recovered tensor data and only need to call `strip_for_generation()` to remove unnecessary multimodal data while preserving the recovered tensors. This avoids redundant tensor recovery operations during generation.

Applied to files:

  • tensorrt_llm/_torch/pyexecutor/sampler.py
  • cpp/tensorrt_llm/batch_manager/trtGptModelInflightBatching.cpp
  • cpp/include/tensorrt_llm/runtime/request.h
  • cpp/tensorrt_llm/batch_manager/createNewDecoderRequests.cpp
🔇 Additional comments (9)
cpp/tests/runtime/gptDecoderBatchedTest.cpp (1)

112-114: LGTM: Clean API simplification

The removal of the BufferManager parameter aligns with the broader refactoring to localize buffer management. The multi-line formatting improves readability of the function call.

cpp/tensorrt_llm/pybind/batch_manager/algorithms.cpp (2)

108-116: LGTM: Correct binding update

The removal of the buffer_manager parameter from both the lambda function signature and the actual call correctly reflects the updated C++ API.


122-123: LGTM: Argument list properly updated

The py::arg list correctly removes the buffer_manager parameter to match the updated function signature.

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

585-585: LGTM: Client code correctly updated

The removal of self.store["buffer_manager"] parameter correctly reflects the API simplification where buffer management is now handled internally.

cpp/tensorrt_llm/nanobind/batch_manager/algorithms.cpp (2)

106-114: LGTM: Nanobind binding correctly updated

The removal of the buffer_manager parameter from both the lambda function signature and the actual call correctly reflects the updated C++ API, maintaining consistency with the pybind11 binding.


120-121: LGTM: Argument list properly updated

The nb::arg list correctly removes the buffer_manager parameter to match the updated function signature.

cpp/tensorrt_llm/batch_manager/trtGptModelInflightBatching.cpp (1)

1869-1871: LGTM! Clean parameter removal as part of interface refactoring.

The removal of the mRuntime->getBufferManager() argument from the mCreateNewDecoderRequests call is correctly executed and aligns with the broader refactoring effort described in the PR summary. The remaining arguments maintain their proper order and the change is syntactically correct.

cpp/include/tensorrt_llm/runtime/request.h (1)

34-37: LGTM! Constructor simplification aligns with refactoring goals.

The removal of input token IDs and optional parameters from the Request constructor is consistent with the broader refactoring to centralize buffer management within the batch manager components.

cpp/include/tensorrt_llm/batch_manager/createNewDecoderRequests.h (1)

78-80: LGTM! API simplification removes explicit buffer manager dependency.

The removal of the BufferManager parameter from both operator() and createDecoderRequests methods successfully simplifies the public API while maintaining the necessary functionality internally.

Also applies to: 86-88

@tensorrt-cicd
Copy link
Collaborator

PR_Github #13816 [ run ] triggered by Bot

@Funatiq
Copy link
Collaborator Author

Funatiq commented Aug 1, 2025

@coderabbitai title

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 1, 2025

Tip

For best results, initiate chat on the files or code changes.

@Funatiq I can help you generate a better title for this PR. Based on the changes in the codebase, here's my suggestion:

Suggested title: refactor: remove BufferManager dependencies and simplify Request class in decoder requests

Alternative titles:

  • refactor(batch_manager): remove BufferManager parameters and modularize decoder request creation
  • refactor: simplify decoder request initialization and remove BufferManager coupling

Why this is better than the current title:

  1. Descriptive: Clearly indicates what was refactored (BufferManager dependencies and Request class)
  2. Follows conventional commits: Uses the refactor: prefix to indicate the type of change
  3. Specific: Mentions the key changes rather than just "refactor decoder requests 2"
  4. Professional: Avoids generic branch-style naming like "Dev/refactor decoder requests 2"

The current changes involve:

  • Removing BufferManager parameters from CreateNewDecoderRequests methods
  • Simplifying the Request class constructor and removing several member variables
  • Breaking down monolithic functions into smaller, focused helper functions
  • Updating all related Python bindings and tests

Would you like me to suggest any other variations of the title?


🧠 Learnings used
Learnt from: moraxu
PR: NVIDIA/TensorRT-LLM#6303
File: tests/integration/test_lists/qa/examples_test_list.txt:494-494
Timestamp: 2025-07-28T17:06:08.621Z
Learning: In TensorRT-LLM testing, it's common to have both CLI flow tests (test_cli_flow.py) and PyTorch API tests (test_llm_api_pytorch.py) for the same model. These serve different purposes: CLI flow tests validate the traditional command-line workflow, while PyTorch API tests validate the newer LLM API backend. Both are legitimate and should coexist.

@Funatiq Funatiq changed the title Dev/refactor decoder requests 2 ]None[[refactor] Simplify decoder request initialization Aug 1, 2025
@Funatiq Funatiq changed the title ]None[[refactor] Simplify decoder request initialization [None][refactor] Simplify decoder request initialization Aug 1, 2025
@tensorrt-cicd
Copy link
Collaborator

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

@Funatiq Funatiq force-pushed the dev/refactor_decoder_requests_2 branch from e390636 to 3830a1e Compare August 2, 2025 14:11
@Funatiq
Copy link
Collaborator Author

Funatiq commented Aug 2, 2025

/bot run

@Funatiq Funatiq changed the title [None][refactor] Simplify decoder request initialization [None][refactor] Simplify decoder state initialization Aug 2, 2025
@tensorrt-cicd
Copy link
Collaborator

PR_Github #13857 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #13857 [ run ] completed with state SUCCESS
/LLM/main/L0_MergeRequest_PR pipeline #10425 completed with status: 'SUCCESS'
Pipeline passed with automatic retried tests. Check the rerun report for details.

@Funatiq Funatiq requested review from DomBrown and dcampora August 2, 2025 21:15
@Funatiq Funatiq marked this pull request as ready for review August 2, 2025 21:15
@Funatiq Funatiq requested a review from a team as a code owner August 2, 2025 21:15
Signed-off-by: Robin Kobus <19427718+Funatiq@users.noreply.github.com>
- Updated CreateNewDecoderRequests class and related methods to remove BufferManager as a parameter.
- CreateNewDecoderRequests already has runtimeStream as a parameter, so we can use it to create the BufferManager.
- This makes it easier to differentiate between the runtime stream and the decoder stream.

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

Signed-off-by: Robin Kobus <19427718+Funatiq@users.noreply.github.com>
- Moved the setupWords logic from a lambda expression into a dedicated function, improving code clarity and maintainability.

Signed-off-by: Robin Kobus <19427718+Funatiq@users.noreply.github.com>
- Moved the setting of numDecodingEngineTokens to the newRequest function for better clarity.
- Reorganized speculative execution logic to improve readability and maintainability.

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

- Moved the speculative decoding logic for Medusa, Lookahead, and Eagle modes into a unified conditional block for improved clarity and maintainability.
- Ensured that the handling of decoder requests is streamlined and easier to follow.

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

- Updated the initializeEmbeddingBias function to accept LlmRequest and logitsType, improving clarity and flexibility.
- Removed direct embedding bias handling from newRequest, streamlining the request creation process.
- Ensured that embedding bias is now consistently initialized using the updated function.

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

- Removed badWordsList and stopWordsList from the request structure, streamlining the request parameters.
- Enhanced setupWords function to handle optional TensorPtr for requestWordsList, improving flexibility.
- Updated calls to setupWords in newRequest to utilize the new structure, ensuring proper memory management and GPU handling.

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

- Added initializeRequestIds function to handle the initialization of request IDs and output IDs, improving code organization.
- Introduced initializeBeamSearch function to encapsulate beam search initialization logic, enhancing clarity and maintainability.
- Updated newRequest to utilize the new functions, streamlining the request handling process.

Signed-off-by: Robin Kobus <19427718+Funatiq@users.noreply.github.com>
- Modified the Request constructor to remove the ids and endId parameters, streamlining the initialization process.
- Updated the newRequest function in CreateNewDecoderRequests to reflect changes in the Request structure, ensuring proper handling of input length and token generation.
- Removed unnecessary checks related to request IDs and endId, enhancing code clarity and maintainability.

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

- Added initializeLogProbs function to encapsulate the initialization of cumulative and output log probabilities, improving code organization and clarity.
- Removed redundant log probability initialization logic from newRequest, streamlining the request handling process.

Signed-off-by: Robin Kobus <19427718+Funatiq@users.noreply.github.com>
- Fix: Use decoder stream instead of runtime stream for request initialization.
- Updated functions in CreateNewDecoderRequests to utilize BufferManager instead of CudaStream for stream management, enhancing code clarity and consistency.
- Streamlined the initialization of request IDs, beam search, and embedding bias by passing BufferManager, improving memory management and GPU handling.

Signed-off-by: Robin Kobus <19427718+Funatiq@users.noreply.github.com>
- Move beam width check to CreateNewDecoderRequests from newRequest.
- Set beam width in CreateNewDecoderRequests instead of newRequest.

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

- Added initializeInputLengths function to encapsulate the logic for setting input lengths and validating constraints, improving code organization and clarity.
- Streamlined the newRequest function by replacing direct input length handling with a call to initializeInputLengths, enhancing maintainability.

Signed-off-by: Robin Kobus <19427718+Funatiq@users.noreply.github.com>
- Moved the initialization of input lengths from newRequest to the createDecoderRequests function.
- Removed the now unnecessary maxNewTokens parameter from the Request constructor, simplifying its initialization.
- Removed the now unnecessary maxSequenceLength parameter from the newRequest function.

Signed-off-by: Robin Kobus <19427718+Funatiq@users.noreply.github.com>
- All other functionality has been moved out of the newRequest function.
- Renamed newRequest to initializeOutputs to better reflect its purpose.

Signed-off-by: Robin Kobus <19427718+Funatiq@users.noreply.github.com>
- Introduced setBeamWidth method in DecoderState to allow setting the beam width for specific requests in a batch.
- Updated CreateNewDecoderRequests to utilize the new setBeamWidth method, improving code clarity and maintainability.

Signed-off-by: Robin Kobus <19427718+Funatiq@users.noreply.github.com>
@Funatiq Funatiq force-pushed the dev/refactor_decoder_requests_2 branch from 2ec14ea to b4d3a69 Compare August 12, 2025 10:43
@Funatiq
Copy link
Collaborator Author

Funatiq commented Aug 12, 2025

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #14963 [ 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: 2

🧹 Nitpick comments (1)
cpp/tensorrt_llm/runtime/decoderState.cpp (1)

647-650: Consider using index bounds check instead of direct .at() access

While .at(batchIdx) provides bounds checking in debug builds, it may throw an exception in release builds. Since this is a runtime component, consider adding explicit bounds validation with a descriptive error message:

 void DecoderState::setBeamWidth(SizeType32 batchIdx, SizeType32 beamWidth)
 {
+    TLLM_CHECK_WITH_INFO(
+        batchIdx < mJointDecodingInput->beamWidths.size(), 
+        "Batch index %d out of bounds (max %lu)", batchIdx, mJointDecodingInput->beamWidths.size());
     mJointDecodingInput->beamWidths.at(batchIdx) = beamWidth;
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2ec14ea and b4d3a69.

📒 Files selected for processing (10)
  • cpp/include/tensorrt_llm/batch_manager/createNewDecoderRequests.h (1 hunks)
  • cpp/include/tensorrt_llm/runtime/decoderState.h (1 hunks)
  • cpp/include/tensorrt_llm/runtime/request.h (1 hunks)
  • cpp/tensorrt_llm/batch_manager/createNewDecoderRequests.cpp (9 hunks)
  • cpp/tensorrt_llm/batch_manager/trtGptModelInflightBatching.cpp (1 hunks)
  • cpp/tensorrt_llm/nanobind/batch_manager/algorithms.cpp (1 hunks)
  • cpp/tensorrt_llm/pybind/batch_manager/algorithms.cpp (1 hunks)
  • cpp/tensorrt_llm/runtime/decoderState.cpp (1 hunks)
  • cpp/tests/runtime/gptDecoderBatchedTest.cpp (1 hunks)
  • tensorrt_llm/_torch/pyexecutor/sampler.py (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (7)
  • cpp/include/tensorrt_llm/runtime/decoderState.h
  • cpp/tensorrt_llm/nanobind/batch_manager/algorithms.cpp
  • cpp/tensorrt_llm/batch_manager/trtGptModelInflightBatching.cpp
  • cpp/include/tensorrt_llm/runtime/request.h
  • tensorrt_llm/_torch/pyexecutor/sampler.py
  • cpp/tests/runtime/gptDecoderBatchedTest.cpp
  • cpp/tensorrt_llm/pybind/batch_manager/algorithms.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/tensorrt_llm/runtime/decoderState.cpp
  • cpp/include/tensorrt_llm/batch_manager/createNewDecoderRequests.h
  • 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/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/tensorrt_llm/runtime/decoderState.cpp
  • cpp/include/tensorrt_llm/batch_manager/createNewDecoderRequests.h
  • cpp/tensorrt_llm/batch_manager/createNewDecoderRequests.cpp
**/*.{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/tensorrt_llm/runtime/decoderState.cpp
  • cpp/include/tensorrt_llm/batch_manager/createNewDecoderRequests.h
  • 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/createNewDecoderRequests.h
🔇 Additional comments (4)
cpp/include/tensorrt_llm/batch_manager/createNewDecoderRequests.h (1)

76-80: LGTM! Clean API refactoring

The removal of the BufferManager parameter from the public API is a positive change that simplifies the interface and properly encapsulates buffer management within the implementation.

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

52-86: LGTM! Good encapsulation of buffer management

Creating a local BufferManager within the function properly encapsulates the buffer management logic and eliminates external dependencies. This is a cleaner design pattern.


550-704: Excellent refactoring into modular helper functions

The decomposition of the monolithic newRequest function into smaller, focused helper functions (initializeInputLengths, initializeRequestIds, initializeBeamSearch, etc.) significantly improves code maintainability and readability. This modular approach makes the initialization flow much clearer and easier to test.


629-632: Beam width initialization confirmed before setting decoding tokens

  • decoderState.setBeamWidth(batchSlot, beamWidth) is called at line 596
  • decoderState.setNumDecodingEngineTokens(batchSlot, numDecodingEngineTokens) follows at line 632

No changes needed here—beam width is properly initialized before setting the decoding engine tokens.

@tensorrt-cicd
Copy link
Collaborator

PR_Github #14963 [ run ] completed with state SUCCESS
/LLM/main/L0_MergeRequest_PR pipeline #11295 completed with status: 'SUCCESS'
Pipeline passed with automatic retried tests. Check the rerun report for details.

@Funatiq Funatiq merged commit 45c7518 into NVIDIA:main Aug 12, 2025
5 checks passed
@Funatiq Funatiq deleted the dev/refactor_decoder_requests_2 branch August 12, 2025 19: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