[TRTLLM-10030][chore] promote SampleState to TypeVar + typing fixes#11281
[TRTLLM-10030][chore] promote SampleState to TypeVar + typing fixes#11281ixlmar merged 1 commit intoNVIDIA:mainfrom
Conversation
|
/bot run |
|
Note: This PR builds on top of #11276 |
|
PR_Github #34799 [ run ] triggered by Bot. Commit: |
|
/bot run --disable-fail-fast |
|
PR_Github #34823 [ run ] triggered by Bot. Commit: |
|
PR_Github #34823 [ run ] completed with state
|
db19c7c to
df5ee1e
Compare
|
/bot run --disable-fail-fast |
|
PR_Github #34948 [ run ] triggered by Bot. Commit: |
|
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. |
📝 WalkthroughWalkthroughMultiple 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
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes 🚥 Pre-merge checks | ✅ 3✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing touches
🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
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 | 🟡 MinorForward
group_metadatain the wrapperThe 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 | 🟠 MajorAdd 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 sysAs 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 typeThe TYPE_CHECKING import pulls
Strategydirectly; consider importing the module and referencingsampler.Strategyto 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" = NoneAs 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 hereThe 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 attributeSampleStateshadows module-levelSampleStateclass.This TypeAlias shadows the outer-scope
SampleStateclass, which can cause confusion. As per coding guidelines, avoid shadowing variables declared in an outer scope. Consider renaming to something likeStateTyor_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 inEarlyStopSampler.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()"
|
PR_Github #34948 [ run ] completed with state |
Signed-off-by: ixlmar <206748156+ixlmar@users.noreply.github.com>
df5ee1e to
48d901d
Compare
|
/bot skip --comment "removed commits already merged via #11276" |
|
PR_Github #34969 [ skip ] triggered by Bot. Commit: |
|
PR_Github #34969 [ skip ] completed with state |
…VIDIA#11281) Signed-off-by: ixlmar <206748156+ixlmar@users.noreply.github.com>
…VIDIA#11281) Signed-off-by: ixlmar <206748156+ixlmar@users.noreply.github.com> Signed-off-by: Ahmet Inci <ainci@nvidia.com>
Description
Details:
SampleStatea type argument ofSamplerMTPSamplerandTorchSamplerTest 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 thestage-listparameter 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.mdand the
scripts/test_to_stage_mapping.pyhelper.kill
killKill all running builds associated with pull request.
skip
skip --comment COMMENTSkip 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-pipelineReuse 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