Skip to content

[TRTLLM-10030][chore] promote SampleState to TypeVar + typing fixes#11281

Merged
ixlmar merged 1 commit intoNVIDIA:mainfrom
ixlmar:perf/beam-search-2
Feb 5, 2026
Merged

[TRTLLM-10030][chore] promote SampleState to TypeVar + typing fixes#11281
ixlmar merged 1 commit intoNVIDIA:mainfrom
ixlmar:perf/beam-search-2

Conversation

@ixlmar
Copy link
Collaborator

@ixlmar ixlmar commented Feb 4, 2026

Description

Details:

  • make SampleState a type argument of Sampler
  • more typing fixes
  • simplify relationship between MTPSampler and TorchSampler

Test Coverage

n/a

PR Checklist

Please review the following before submitting your PR:

  • PR description clearly explains what and why. If using CodeRabbit's summary, please make sure it makes sense.

  • PR Follows TRT-LLM CODING GUIDELINES to the best of your knowledge.

  • Test cases are provided for new code paths (see test instructions)

  • Any new dependencies have been scanned for license and vulnerabilities

  • CODEOWNERS updated if ownership changes

  • Documentation updated as needed

  • Update tava architecture diagram if there is a significant design change in PR.

  • The reviewers assigned automatically/manually are appropriate for the PR.

  • Please check this after reviewing the above items as appropriate for this PR.

GitHub Bot Help

/bot [-h] ['run', 'kill', 'skip', 'reuse-pipeline'] ...

Provide a user friendly way for developers to interact with a Jenkins server.

Run /bot [-h|--help] to print this help message.

See details below for each supported subcommand.

Details

run [--reuse-test (optional)pipeline-id --disable-fail-fast --skip-test --stage-list "A10-PyTorch-1, xxx" --gpu-type "A30, H100_PCIe" --test-backend "pytorch, cpp" --add-multi-gpu-test --only-multi-gpu-test --disable-multi-gpu-test --post-merge --extra-stage "H100_PCIe-TensorRT-Post-Merge-1, xxx" --detailed-log --debug(experimental)]

Launch build/test pipelines. All previously running jobs will be killed.

--reuse-test (optional)pipeline-id (OPTIONAL) : Allow the new pipeline to reuse build artifacts and skip successful test stages from a specified pipeline or the last pipeline if no pipeline-id is indicated. If the Git commit ID has changed, this option will be always ignored. The DEFAULT behavior of the bot is to reuse build artifacts and successful test results from the last pipeline.

--disable-reuse-test (OPTIONAL) : Explicitly prevent the pipeline from reusing build artifacts and skipping successful test stages from a previous pipeline. Ensure that all builds and tests are run regardless of previous successes.

--disable-fail-fast (OPTIONAL) : Disable fail fast on build/tests/infra failures.

--skip-test (OPTIONAL) : Skip all test stages, but still run build stages, package stages and sanity check stages. Note: Does NOT update GitHub check status.

--stage-list "A10-PyTorch-1, xxx" (OPTIONAL) : Only run the specified test stages. Examples: "A10-PyTorch-1, xxx". Note: Does NOT update GitHub check status.

--gpu-type "A30, H100_PCIe" (OPTIONAL) : Only run the test stages on the specified GPU types. Examples: "A30, H100_PCIe". Note: Does NOT update GitHub check status.

--test-backend "pytorch, cpp" (OPTIONAL) : Skip test stages which don't match the specified backends. Only support [pytorch, cpp, tensorrt, triton]. Examples: "pytorch, cpp" (does not run test stages with tensorrt or triton backend). Note: Does NOT update GitHub pipeline status.

--only-multi-gpu-test (OPTIONAL) : Only run the multi-GPU tests. Note: Does NOT update GitHub check status.

--disable-multi-gpu-test (OPTIONAL) : Disable the multi-GPU tests. Note: Does NOT update GitHub check status.

--add-multi-gpu-test (OPTIONAL) : Force run the multi-GPU tests in addition to running L0 pre-merge pipeline.

--post-merge (OPTIONAL) : Run the L0 post-merge pipeline instead of the ordinary L0 pre-merge pipeline.

--extra-stage "H100_PCIe-TensorRT-Post-Merge-1, xxx" (OPTIONAL) : Run the ordinary L0 pre-merge pipeline and specified test stages. Examples: --extra-stage "H100_PCIe-TensorRT-Post-Merge-1, xxx".

--detailed-log (OPTIONAL) : Enable flushing out all logs to the Jenkins console. This will significantly increase the log volume and may slow down the job.

--debug (OPTIONAL) : Experimental feature. Enable access to the CI container for debugging purpose. Note: Specify exactly one stage in the stage-list parameter to access the appropriate container environment. Note: Does NOT update GitHub check status.

For guidance on mapping tests to stage names, see docs/source/reference/ci-overview.md
and the scripts/test_to_stage_mapping.py helper.

kill

kill

Kill all running builds associated with pull request.

skip

skip --comment COMMENT

Skip testing for latest commit on pull request. --comment "Reason for skipping build/test" is required. IMPORTANT NOTE: This is dangerous since lack of user care and validation can cause top of tree to break.

reuse-pipeline

reuse-pipeline

Reuse a previous pipeline to validate current commit. This action will also kill all currently running builds associated with the pull request. IMPORTANT NOTE: This is dangerous since lack of user care and validation can cause top of tree to break.

Summary by CodeRabbit

  • Refactor
    • Enhanced type safety across the sampling strategy system with comprehensive generic typing support for sampler states and strategies.
    • Streamlined beam search sampling interface through simplified parameter handling and improved consistency in strategy grouping and metadata generation.

@ixlmar
Copy link
Collaborator Author

ixlmar commented Feb 4, 2026

/bot run

@ixlmar
Copy link
Collaborator Author

ixlmar commented Feb 4, 2026

Note: This PR builds on top of #11276

@tensorrt-cicd
Copy link
Collaborator

PR_Github #34799 [ run ] triggered by Bot. Commit: db19c7c

@ixlmar
Copy link
Collaborator Author

ixlmar commented Feb 4, 2026

/bot run --disable-fail-fast

@tensorrt-cicd
Copy link
Collaborator

PR_Github #34823 [ run ] triggered by Bot. Commit: db19c7c

@tensorrt-cicd
Copy link
Collaborator

PR_Github #34823 [ run ] completed with state SUCCESS. Commit: db19c7c
/LLM/main/L0_MergeRequest_PR pipeline #26861 completed with status: 'FAILURE'

⚠️ Action Required:

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

@ixlmar ixlmar force-pushed the perf/beam-search-2 branch from db19c7c to df5ee1e Compare February 5, 2026 08:29
@ixlmar
Copy link
Collaborator Author

ixlmar commented Feb 5, 2026

/bot run --disable-fail-fast

@tensorrt-cicd
Copy link
Collaborator

PR_Github #34948 [ run ] triggered by Bot. Commit: df5ee1e

@ixlmar ixlmar requested review from Funatiq and stnie February 5, 2026 11:08
@ixlmar ixlmar marked this pull request as ready for review February 5, 2026 11:08
@ixlmar ixlmar requested review from a team as code owners February 5, 2026 11:08
@ixlmar ixlmar requested a review from nv-yilinf February 5, 2026 11:08
@ixlmar
Copy link
Collaborator Author

ixlmar commented Feb 5, 2026

Note to reviewers: This PR contains changes from #11276 and is intended to be merged after that one. It should therefore be sufficient to review the newly added commit(s) only.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 5, 2026

📝 Walkthrough

Walkthrough

Multiple files in the PyTorch executor module introduce generic typing for sampler states, simplify strategy grouping interfaces by removing generator and return_probs parameters, and refactor beam search specialization from static factories to runtime key-based dispatch. Changes affect request handling, sampling strategies, and related test infrastructure.

Changes

Cohort / File(s) Summary
Sampler State Generics
tensorrt_llm/_torch/pyexecutor/sampler.py, tensorrt_llm/_torch/speculative/mtp.py
Introduces generic typing across public Sampler base class and SampleState data carrier with TypeVars for host/device tensors. Specific samplers (EarlyStopSampler, EarlyStopWithMMResult, TorchSampler, TRTLLMSampler) and state variants updated to use new generic forms. RequestGroupKey and related grouping structures generified. SampleStateMTP refactored to use generic SampleState base; MTPSampler now extends Sampler[SampleStateMTP] directly.
Strategy Interface Simplification
tensorrt_llm/_torch/pyexecutor/sampling_utils.py, tensorrt_llm/_torch/pyexecutor/sampling_utils_flashinfer.py
Removed generator parameter from beam_search_sampling_batch and return_probs from strategy_grouping_key signatures across abstract and concrete implementations. GenericStrategyKeyType constrained to Hashable. sample_grouped_strategies now returns three values (including optional temperature). Beam search specialization factory _create_beam_search_specialized_cls replaced with runtime key-based dispatch using new _STRATEGY_KEY_TYPE alias. BeamSearchMixin constructor signature updated to accept int beam widths instead of tensors.
Request Sampling Strategy
tensorrt_llm/_torch/pyexecutor/llm_request.py
Added type-checked import for Strategy and new private field `_py_sampling_strategy: Strategy
Test Updates
tests/unittest/_torch/sampler/test_beam_search.py, tests/unittest/_torch/sampler/test_torch_sampler.py
Removed generator parameter from beam_search_sampling_batch call. Mock LlmRequest extended with _py_sampling_strategy field initialization. Mock _sample_grouped_strategies return type expanded to include optional third value; runtime type checks added for new key handling (string or tuple format).

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The pull request title clearly and specifically summarizes the main changes: promoting SampleState to a TypeVar and applying related typing fixes, directly aligned with the primary objectives of the changeset.
Description check ✅ Passed The pull request description covers the key objectives (SampleState as type argument, typing fixes, MTPSampler simplification) and includes the required PR checklist. However, the 'Test Coverage' section states 'n/a' without explaining why no tests are included, and the description lacks detail on the rationale for the changes.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

Caution

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

⚠️ Outside diff range comments (2)
tests/unittest/_torch/sampler/test_torch_sampler.py (1)

1558-1583: ⚠️ Potential issue | 🟡 Minor

Forward group_metadata in the wrapper

The wrapper currently drops group_metadata, which will break beam-search (and any future strategies that rely on metadata). Pass it through to the original method.

🔧 Suggested fix
@@
                 return sample_grouped_strategies_orig(
                     group_key,
                     strategies,
                     logits,
                     group_logit_indices=group_logit_indices,
                     generator=generator,
                     return_probs=return_probs,
+                    group_metadata=group_metadata,
                 )
tensorrt_llm/_torch/speculative/mtp.py (1)

1-30: ⚠️ Potential issue | 🟠 Major

Add NVIDIA copyright header (2026)

This TensorRT-LLM source file currently starts with imports. Please add the standard NVIDIA copyright header with the latest modification year.

📄 Suggested header
+#+#+#+#+ Copyright (c) 2026, NVIDIA CORPORATION. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#    http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
 import sys

As per coding guidelines: All TensorRT-LLM source files (.cpp, .h, .cu, .py, and other source files) should contain an NVIDIA copyright header with the year of latest meaningful modification.

🤖 Fix all issues with AI agents
In `@tensorrt_llm/_torch/pyexecutor/llm_request.py`:
- Line 590: The create_child_request method omits the private attribute
_py_sampling_strategy (it only copies attrs starting with "py_"), causing child
requests to re-resolve an expensive strategy; update create_child_request in
llm_request.py to propagate the cached strategy by explicitly assigning
child._py_sampling_strategy = self._py_sampling_strategy so child requests reuse
the resolved strategy and avoid repeated resolution.

In `@tensorrt_llm/_torch/pyexecutor/sampler.py`:
- Line 3363: The assignment to max_attn_window reads
kv_cache_config.max_attention_window without guarding for kv_cache_config being
None; update the code around the function that accepts the kv_cache_config
parameter to check if kv_cache_config is None before accessing its
attribute—either set a safe default for max_attn_window (e.g., 0 or a configured
fallback) or raise a clear ValueError with context—and then use that guarded
value wherever max_attn_window is used; reference the kv_cache_config parameter
and the max_attn_window variable to locate the change.
🧹 Nitpick comments (5)
tensorrt_llm/_torch/pyexecutor/llm_request.py (1)

3-10: Prefer a module import for the sampler strategy type

The TYPE_CHECKING import pulls Strategy directly; consider importing the module and referencing sampler.Strategy to keep the namespace intact.

🔧 Suggested refactor
@@
-if TYPE_CHECKING:
-    from tensorrt_llm._torch.pyexecutor.sampler import Strategy
+if TYPE_CHECKING:
+    import tensorrt_llm._torch.pyexecutor.sampler as sampler
@@
-        self._py_sampling_strategy: "Strategy | None" = None
+        self._py_sampling_strategy: "sampler.Strategy | None" = None

As per coding guidelines: Always maintain the namespace when importing Python modules, even if only one class or function from a module is used.

Also applies to: 590-590

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

544-561: Use Google-style docstring format here

The new abstract method docstring should follow the project’s Google-style format (Args/Returns).

📝 Suggested docstring format
-        """Sample grouped strategies.
-
-        Returns:
-          - Sampled tokens
-          - Processed probs (whenever return_probs=True)
-          - Temperature (used to compute processed _log_ probs)
-        """
+        """Sample grouped strategies.
+
+        Args:
+            group_key: Strategy grouping key.
+            strategies: Strategies in the group.
+            logits: Input logits.
+            group_logit_indices: Optional indices selecting group logits.
+            generator: Optional RNG.
+            return_probs: Whether to return probabilities.
+            group_metadata: Optional strategy metadata.
+
+        Returns:
+            tuple[torch.Tensor, torch.Tensor | None, float | torch.Tensor | None]:
+                Sampled tokens, processed probabilities (if requested), and temperature.
+        """

As per coding guidelines: Use Google-style docstrings for Python classes and functions, which can be parsed by Sphinx.

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

208-209: Class attribute SampleState shadows module-level SampleState class.

This TypeAlias shadows the outer-scope SampleState class, which can cause confusion. As per coding guidelines, avoid shadowing variables declared in an outer scope. Consider renaming to something like StateTy or _SampleStateAlias.

♻️ Suggested rename to avoid shadowing
-    SampleState: TypeAlias = SampleState[SampleStateTensors, SampleStateTensors]
+    StateTy: TypeAlias = SampleState[SampleStateTensors, SampleStateTensors]

Then update line 219:

-        return self.SampleState(scheduled_requests=scheduled_requests, host=host)
+        return self.StateTy(scheduled_requests=scheduled_requests, host=host)

286-287: Same shadowing issue as in EarlyStopSampler.

Consider applying the same rename pattern here for consistency.


2995-3019: Tensor operations inside nested loops may impact performance.

This section performs tensor allocations (line 3003) and operations (lines 3017-3019) inside nested loops iterating over requests, beams, and steps. Based on learnings, this pattern can impact performance. Consider batch-processing where feasible.

Based on learnings: "avoid accessing torch.Tensor objects inside for-loops when iterating over requests... Convert batched tensors to Python lists beforehand using tensor.tolist()"

@tensorrt-cicd
Copy link
Collaborator

PR_Github #34948 [ run ] completed with state SUCCESS. Commit: df5ee1e
/LLM/main/L0_MergeRequest_PR pipeline #26962 completed with status: 'SUCCESS'

Signed-off-by: ixlmar <206748156+ixlmar@users.noreply.github.com>
@ixlmar ixlmar force-pushed the perf/beam-search-2 branch from df5ee1e to 48d901d Compare February 5, 2026 14:42
@ixlmar
Copy link
Collaborator Author

ixlmar commented Feb 5, 2026

/bot skip --comment "removed commits already merged via #11276"

@tensorrt-cicd
Copy link
Collaborator

PR_Github #34969 [ skip ] triggered by Bot. Commit: 48d901d

@ixlmar ixlmar requested review from zheyuf and removed request for nv-yilinf February 5, 2026 14:59
@tensorrt-cicd
Copy link
Collaborator

PR_Github #34969 [ skip ] completed with state SUCCESS. Commit: 48d901d
Skipping testing for commit 48d901d

@ixlmar ixlmar merged commit 7d235cf into NVIDIA:main Feb 5, 2026
5 checks passed
@ixlmar ixlmar deleted the perf/beam-search-2 branch February 5, 2026 15:33
SchumiDing pushed a commit to SchumiDing/TensorRT-LLM that referenced this pull request Feb 6, 2026
…VIDIA#11281)

Signed-off-by: ixlmar <206748156+ixlmar@users.noreply.github.com>
inciaf pushed a commit to inciaf/trtllm-energy-monitoring that referenced this pull request Feb 18, 2026
…VIDIA#11281)

Signed-off-by: ixlmar <206748156+ixlmar@users.noreply.github.com>
Signed-off-by: Ahmet Inci <ainci@nvidia.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants