-
Notifications
You must be signed in to change notification settings - Fork 1.8k
[TRTLLM-8414][chore] BREAKING CHANGE: refine sampling strategy selection #8132
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
|
/bot run |
a789ace to
e1de3d5
Compare
|
PR_Github #20583 [ run ] triggered by Bot |
e1de3d5 to
90ef0c7
Compare
|
/bot run |
|
PR_Github #20583 [ run ] completed with state |
|
PR_Github #20589 [ run ] triggered by Bot |
|
/bot run |
|
PR_Github #20589 [ run ] completed with state |
|
PR_Github #20592 [ run ] triggered by Bot |
90ef0c7 to
79b93c4
Compare
|
/bot run --disable-fail-fast |
|
PR_Github #20601 [ run ] triggered by Bot |
|
PR_Github #20592 [ run ] completed with state |
|
PR_Github #20601 [ run ] completed with state |
79b93c4 to
6f3abc2
Compare
|
/bot run --disable-fail-fast |
|
PR_Github #20665 [ run ] triggered by Bot |
6f3abc2 to
53d6e5b
Compare
|
/bot run --disable-fail-fast |
|
PR_Github #20666 [ run ] triggered by Bot |
|
PR_Github #20665 [ run ] completed with state |
|
Release checks to be fixed by #8152 |
53d6e5b to
2ac8b7a
Compare
|
/bot run --disable-fail-fast |
|
PR_Github #20668 [ run ] triggered by Bot |
|
PR_Github #20666 [ run ] completed with state |
2ac8b7a to
fa467a0
Compare
📝 WalkthroughWalkthroughRefactors Torch sampler to a unified strategy-based dispatch (top-k, top-p, temperature, greedy), updates validation in SamplingParams, adjusts a shim’s sampling decision, adds comprehensive unit tests for the new sampler behavior, tweaks an existing TRT-LLM sampler test, updates integration test list, and modifies tooling and pytest skip-trace behavior. Changes
Sequence Diagram(s)sequenceDiagram
autonumber
actor Client
participant Sampler as TorchSampler
participant Strat as Strategy Resolver
participant Exec as Sampler Exec (top_k/top_p/temp/greedy)
Client->>Sampler: sample(requests, logits, vocab_size)
Sampler->>Strat: _request_get_sampling_params(request)
Strat-->>Sampler: TorchSamplerSamplingParams
Sampler->>Strat: _request_strategy(request, vocab_size)
Strat-->>Sampler: Strategy (Greedy | TopK | TopP | TopKTopP | TemperatureOnly)
alt Greedy
Sampler->>Exec: greedy_search_sampling_batch(logits)
else TopK
Sampler->>Exec: top_k_sampling_batch(logits, top_k, temperature)
else TopP
Sampler->>Exec: top_p_sampling_batch(logits, top_p, temperature)
else TopKTopP
Sampler->>Exec: top_k_top_p_sampling_batch(logits, top_k, top_p, temperature)
else TemperatureOnly
Sampler->>Exec: temperature_sampling_batch(logits, temperature)
end
Exec-->>Sampler: next_token_ids, probs
Sampler-->>Client: batched tokens/probs
sequenceDiagram
autonumber
actor Caller
participant Shim as demollm._sample
participant Exec as Sampler Exec
Caller->>Shim: _sample(logits, top_k)
alt top_k is int > 1
Shim->>Exec: top_k_sampling_batch(logits, top_k, temperature=1.0)
else otherwise
Shim->>Exec: greedy_search_sampling_batch(logits)
end
Exec-->>Shim: token_ids, probs
Shim-->>Caller: token_ids, probs
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✨ 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.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 4
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (3)
tensorrt_llm/_torch/auto_deploy/shim/demollm.py (1)
16-17: Sampling defaults ignore top_p/temperature pathsWith the new semantics, any request that only tweaks
temperatureortop_p(leavingtop_kunset/≤1) should still perform stochastic sampling. This branch forces those cases down the greedy path, so temperature-only or top-p-only configs silently stop sampling. Please route through the full strategy logic (greedy vs temperature vs top-p vs top-k vs top-k+top-p) instead of keying solely ontop_k > 1.Apply this diff to align the shim with the dispatcher logic:
-from ....sampling_params import SamplingParams -from ...pyexecutor.sampler import greedy_search_sampling_batch, top_k_sampling_batch +from ....sampling_params import SamplingParams +from ...pyexecutor.sampler import ( + greedy_search_sampling_batch, + temperature_sampling_batch, + top_k_sampling_batch, + top_k_top_p_sampling_batch, + top_p_sampling_batch, +) @@ - if isinstance(sampling_params.top_k, int) and sampling_params.top_k > 1: - idx_next, probs = top_k_sampling_batch( - logits, top_k=sampling_params.top_k, temperature=1.0 - ) - else: - idx_next, probs = greedy_search_sampling_batch(logits) + if SamplingParams.params_imply_greedy_decoding( + temperature=sampling_params.temperature, + top_p=sampling_params.top_p, + top_k=sampling_params.top_k, + ): + idx_next, probs = greedy_search_sampling_batch(logits) + else: + vocab_size = logits.size(-1) + temperature = sampling_params.temperature or 1.0 + top_p = sampling_params.top_p or 1.0 + top_k = sampling_params.top_k or vocab_size + + if top_p < 1 and top_k < vocab_size: + idx_next, probs = top_k_top_p_sampling_batch( + logits, top_k=top_k, top_p=top_p, temperature=temperature + ) + elif top_p < 1: + idx_next, probs = top_p_sampling_batch( + logits, top_p=top_p, temperature=temperature + ) + elif top_k < vocab_size: + idx_next, probs = top_k_sampling_batch( + logits, top_k=top_k, temperature=temperature + ) + else: + idx_next, probs = temperature_sampling_batch( + logits, temperature=temperature + )Also applies to: 237-244
tensorrt_llm/_torch/pyexecutor/sampler.py (2)
502-504: Advanced indexing requires Long indices.softmax[...] with an index tensor needs dtype=torch.long. Casting to device alone isn’t enough when current dtype is int32.
- if filter_softmax and softmax_indices is not None: - softmax = softmax[softmax_indices.to(softmax.device, non_blocking=True)] + if filter_softmax and softmax_indices is not None: + idx = softmax_indices.to(dtype=torch.long, + device=softmax.device, + non_blocking=True) + softmax = softmax[idx]
1-1: Add NVIDIA Apache-2.0 license headerThe file
tensorrt_llm/_torch/pyexecutor/sampler.pyis missing the required NVIDIA Apache-2.0 header; prepend it as per CODING_GUIDELINES.md:+# Copyright (c) 2025, NVIDIA CORPORATION & AFFILIATES. 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.
🧹 Nitpick comments (3)
tests/unittest/_torch/sampler/test_torch_sampler.py (1)
1-28: Silence RUF012 by marking class constants as ClassVar tuplesRuff flags these mutable class attributes (RUF012). Converting them to immutable tuples and annotating them as
ClassVaraddresses the lint failure without changing semantics.Apply this diff:
-from typing import Optional, cast +from typing import ClassVar, Optional, Tuple, cast @@ - VOCAB_SIZE = 1000 - TOP_K_VALS = [None, 0, 1, 42, 1000] - TOP_P_VALS = [None, 0, 0.42, 1] - TEMPERATURE_VALS = [None, 0, 1.42] - - # For non-greedy sampling, the following choices have no effect. - TOP_P_NEUTRAL_VALS = [None, 1] - TOP_K_NEUTRAL_VALS = [None, 0, VOCAB_SIZE] - TEMPERATURE_NEUTRAL_VALS = [None, 1] - - TEMPERATURE_NOT_GREEDY = [0.42] + [t for t in TEMPERATURE_NEUTRAL_VALS if t is not None] + VOCAB_SIZE: ClassVar[int] = 1000 + TOP_K_VALS: ClassVar[Tuple[Optional[int], ...]] = (None, 0, 1, 42, 1000) + TOP_P_VALS: ClassVar[Tuple[Optional[float], ...]] = (None, 0, 0.42, 1) + TEMPERATURE_VALS: ClassVar[Tuple[Optional[float], ...]] = (None, 0, 1.42) + + # For non-greedy sampling, the following choices have no effect. + TOP_P_NEUTRAL_VALS: ClassVar[Tuple[Optional[float], ...]] = (None, 1) + TOP_K_NEUTRAL_VALS: ClassVar[Tuple[Optional[int], ...]] = (None, 0, VOCAB_SIZE) + TEMPERATURE_NEUTRAL_VALS: ClassVar[Tuple[Optional[float], ...]] = (None, 1) + + TEMPERATURE_NOT_GREEDY: ClassVar[Tuple[float, ...]] = ( + (0.42,) + tuple(t for t in TEMPERATURE_NEUTRAL_VALS if t is not None) + )tensorrt_llm/_torch/pyexecutor/sampler.py (2)
257-265: Input validation and top‑p boundary handling.
- Use explicit exceptions instead of asserts (asserts can be stripped with -O).
- The temperature clamp via max(temperature, 1e-5) silently alters semantics; either validate a minimum or document it.
- For deterministic top‑p cut at ties, consider stable sorting (or argsort with stable=True) as noted in the comment.
Suggested tweaks:
- assert temperature > 0, "non-greedy sampling requires valid temperature" - logits = logits / max(temperature, 1e-5) + if not (temperature > 0): + raise ValueError("non-greedy sampling requires temperature > 0") + logits = logits / max(temperature, 1e-5) # consider documenting EPS - assert top_k > 1, "non-greedy sampling requires valid top_k" + if not (top_k > 1): + raise ValueError("non-greedy sampling requires top_k > 1") need_top_k = top_k < vocab_size - assert top_p > 0, "non-greedy sampling requires valid top_p" + if not (top_p > 0): + raise ValueError("non-greedy sampling requires top_p > 0") need_top_p = top_p < 1 - sorted_logits, sorted_indices = torch.sort(logits, - descending=True, - dim=-1) + # Prefer stable ordering at ties for deterministic behavior if available: + sorted_logits, sorted_indices = torch.sort( + logits, descending=True, dim=-1, stable=True) # if supportedIf torch.sort(stable=...) isn’t available in your minimum torch, switch to:
- idx = torch.argsort(logits, dim=-1, descending=True, stable=True)
- sorted_logits = torch.gather(logits, -1, idx)
- sorted_indices = idx
Also applies to: 266-297
1133-1138: Use actual vocab_size for strategy derivation in rejection sampling.Passing 2**31 can select suboptimal paths and extra work. Use draft logits’ vocab dimension.
- sampling_strategy = _request_strategy(request, vocab_size=2**31) + sampling_strategy = _request_strategy( + request, vocab_size=request.py_draft_logits.size(-1))
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (8)
pyproject.toml(3 hunks)tensorrt_llm/_torch/auto_deploy/shim/demollm.py(1 hunks)tensorrt_llm/_torch/pyexecutor/sampler.py(8 hunks)tensorrt_llm/sampling_params.py(3 hunks)tests/integration/test_lists/test-db/l0_a10.yml(1 hunks)tests/unittest/_torch/sampler/test_torch_sampler.py(1 hunks)tests/unittest/_torch/sampler/test_trtllm_sampler.py(1 hunks)tests/unittest/conftest.py(2 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
**/*.{h,hpp,hh,hxx,cpp,cxx,cc,cu,cuh,py}
📄 CodeRabbit inference engine (CODING_GUIDELINES.md)
Use only spaces, no tabs; indent with 4 spaces.
Files:
tests/unittest/_torch/sampler/test_torch_sampler.pytests/unittest/_torch/sampler/test_trtllm_sampler.pytests/unittest/conftest.pytensorrt_llm/_torch/auto_deploy/shim/demollm.pytensorrt_llm/sampling_params.pytensorrt_llm/_torch/pyexecutor/sampler.py
**/*.py
📄 CodeRabbit inference engine (CODING_GUIDELINES.md)
**/*.py: Python code must target Python 3.8+.
Indent Python code with 4 spaces; do not use tabs.
Maintain module namespace when importing; prefer 'from package.subpackage import foo' then 'foo.SomeClass()' instead of importing the class directly.
Python filenames should be snake_case (e.g., some_file.py).
Python classes use PascalCase names.
Functions and methods use snake_case names.
Local variables use snake_case; prefix 'k' for variables that start with a number (e.g., k_99th_percentile).
Global variables use upper SNAKE_CASE prefixed with 'G' (e.g., G_MY_GLOBAL).
Constants use upper SNAKE_CASE (e.g., MY_CONSTANT).
Avoid shadowing variables from an outer scope.
Initialize all externally visible members of a class in the constructor.
Prefer docstrings for interfaces that may be used outside a file; comments for in-function or file-local interfaces.
Use Google-style docstrings for classes and functions (Sphinx-parsable).
Document attributes and variables inline so they render under the class/function docstring.
Avoid reflection when a simpler, explicit approach suffices (e.g., avoid dict(**locals()) patterns).
In try/except, catch the most specific exceptions possible.
For duck-typing try/except, keep the try body minimal and use else for the main logic.
Files:
tests/unittest/_torch/sampler/test_torch_sampler.pytests/unittest/_torch/sampler/test_trtllm_sampler.pytests/unittest/conftest.pytensorrt_llm/_torch/auto_deploy/shim/demollm.pytensorrt_llm/sampling_params.pytensorrt_llm/_torch/pyexecutor/sampler.py
**/*.{cpp,cxx,cc,h,hpp,hh,hxx,cu,cuh,py}
📄 CodeRabbit inference engine (CODING_GUIDELINES.md)
Prepend the NVIDIA Apache-2.0 copyright header with current year to the top of all source files (e.g., .cpp, .h, .cu, .py).
Files:
tests/unittest/_torch/sampler/test_torch_sampler.pytests/unittest/_torch/sampler/test_trtllm_sampler.pytests/unittest/conftest.pytensorrt_llm/_torch/auto_deploy/shim/demollm.pytensorrt_llm/sampling_params.pytensorrt_llm/_torch/pyexecutor/sampler.py
🧬 Code graph analysis (4)
tests/unittest/_torch/sampler/test_torch_sampler.py (2)
tensorrt_llm/_torch/pyexecutor/sampler.py (3)
_request_strategy(406-442)should_provide_draft_probs(98-100)should_provide_draft_probs(1772-1783)tensorrt_llm/sampling_params.py (2)
SamplingParams(126-545)_get_sampling_config(453-483)
tensorrt_llm/_torch/auto_deploy/shim/demollm.py (1)
tensorrt_llm/_torch/pyexecutor/sampler.py (1)
top_k_sampling_batch(197-211)
tensorrt_llm/sampling_params.py (2)
cpp/tensorrt_llm/kernels/trtllmGenKernels/blockScaleMoe/runner.h (1)
top_k(233-233)tensorrt_llm/_torch/pyexecutor/model_engine.py (1)
use_beam_search(414-415)
tensorrt_llm/_torch/pyexecutor/sampler.py (1)
tensorrt_llm/sampling_params.py (2)
SamplingParams(126-545)params_imply_greedy_decoding(350-358)
🪛 Ruff (0.13.3)
tests/unittest/_torch/sampler/test_torch_sampler.py
18-18: Mutable class attributes should be annotated with typing.ClassVar
(RUF012)
19-19: Mutable class attributes should be annotated with typing.ClassVar
(RUF012)
20-20: Mutable class attributes should be annotated with typing.ClassVar
(RUF012)
23-23: Mutable class attributes should be annotated with typing.ClassVar
(RUF012)
24-24: Mutable class attributes should be annotated with typing.ClassVar
(RUF012)
25-25: Mutable class attributes should be annotated with typing.ClassVar
(RUF012)
tensorrt_llm/sampling_params.py
312-312: Avoid specifying long messages outside the exception class
(TRY003)
314-314: Avoid specifying long messages outside the exception class
(TRY003)
316-316: Avoid specifying long messages outside the exception class
(TRY003)
319-319: Avoid specifying long messages outside the exception class
(TRY003)
⏰ 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 (6)
tensorrt_llm/_torch/pyexecutor/sampler.py (6)
197-212: Unifying wrappers look good.Routing top_k/top_p/temperature to the unified top_k_top_p path is clean and consistent.
214-229: Good: top_p entry-point delegating to unified path.Reasonable defaults (top_k=vocab_size) and signature are clear.
231-245: Good: temperature-only entry-point.Delegation and defaults are consistent with semantics.
406-443: Strategy resolution aligns with documented semantics.Defaults (temperature=1, top_p=1, top_k=vocab_size) and greedy gating are correct. Nice.
448-455: Good: group by strategy now vocab‑size aware.Passing vocab_size avoids misclassification of top_k==0/None cases.
1396-1397: Good: grouping uses logits’ vocab_size.Prevents unnecessary top‑k masking and aligns with runtime logits shape.
8961beb to
a690b05
Compare
|
/bot run --disable-fail-fast |
|
PR_Github #20673 [ run ] triggered by Bot |
|
PR_Github #20672 [ run ] completed with state |
|
PR_Github #20673 [ run ] completed with state |
a690b05 to
b04513a
Compare
|
/bot run --disable-fail-fast |
|
PR_Github #20716 [ run ] triggered by Bot |
|
PR_Github #20716 [ run ] completed with state |
|
/bot run |
Signed-off-by: ixlmar <206748156+ixlmar@users.noreply.github.com>
b04513a to
064b6dd
Compare
|
PR_Github #20727 [ run ] triggered by Bot |
|
/bot run --add-multi-gpu-test |
|
PR_Github #20727 [ run ] completed with state |
|
PR_Github #20730 [ run ] triggered by Bot |
|
PR_Github #20730 [ run ] completed with state |
|
/bot run --add-multi-gpu-test |
|
PR_Github #20789 [ run ] triggered by Bot |
|
PR_Github #20789 [ run ] completed with state |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
lgtm
…ion (NVIDIA#8132) Signed-off-by: ixlmar <206748156+ixlmar@users.noreply.github.com>
Description
NOTE: These changes specify the sampling behavior in some previously undefined cases. While the new behavior should be in line with the examples in the documentation, it does differ from the base-branch behavior in certain cases.
Roughly, the new semantics are (see TRTLLM-8414 for complete background):
top_k = top_p = temperature = None(the default if the respective parameters are not specified), sampling is greedy (torch.argmax).top_k,top_p, and/ortemperatureis provided, sampling proceeds accordingly. In this case, unspecified parameters default totop_k = 0,top_p = 1,temperature = 1.0.temperature = 0,top_p = 0, and/ortop_k = 1, is specified, sampling is greedy, irrespective of the values of the remaining parameters.Test Coverage
Unit tests for the sampling strategy selection are implemented as part of this PR.
PR Checklist
Please review the following before submitting your PR:
PR description clearly explains what and why. If using CodeRabbit's summary, please make sure it makes sense.
PR Follows TRT-LLM CODING GUIDELINES to the best of your knowledge.
Test cases are provided for new code paths (see test instructions)
Any new dependencies have been scanned for license and vulnerabilities
CODEOWNERS updated if ownership changes
Documentation updated as needed
The reviewers assigned automatically/manually are appropriate for the PR.
Please check this after reviewing the above items as appropriate for this PR.
GitHub Bot Help
/bot [-h] ['run', 'kill', 'skip', 'reuse-pipeline'] ...Provide a user friendly way for developers to interact with a Jenkins server.
Run
/bot [-h|--help]to print this help message.See details below for each supported subcommand.
run [--reuse-test (optional)pipeline-id --disable-fail-fast --skip-test --stage-list "A10-PyTorch-1, xxx" --gpu-type "A30, H100_PCIe" --test-backend "pytorch, cpp" --add-multi-gpu-test --only-multi-gpu-test --disable-multi-gpu-test --post-merge --extra-stage "H100_PCIe-TensorRT-Post-Merge-1, xxx" --detailed-log --debug(experimental)]Launch build/test pipelines. All previously running jobs will be killed.
--reuse-test (optional)pipeline-id(OPTIONAL) : Allow the new pipeline to reuse build artifacts and skip successful test stages from a specified pipeline or the last pipeline if no pipeline-id is indicated. If the Git commit ID has changed, this option will be always ignored. The DEFAULT behavior of the bot is to reuse build artifacts and successful test results from the last pipeline.--disable-reuse-test(OPTIONAL) : Explicitly prevent the pipeline from reusing build artifacts and skipping successful test stages from a previous pipeline. Ensure that all builds and tests are run regardless of previous successes.--disable-fail-fast(OPTIONAL) : Disable fail fast on build/tests/infra failures.--skip-test(OPTIONAL) : Skip all test stages, but still run build stages, package stages and sanity check stages. Note: Does NOT update GitHub check status.--stage-list "A10-PyTorch-1, xxx"(OPTIONAL) : Only run the specified test stages. Examples: "A10-PyTorch-1, xxx". Note: Does NOT update GitHub check status.--gpu-type "A30, H100_PCIe"(OPTIONAL) : Only run the test stages on the specified GPU types. Examples: "A30, H100_PCIe". Note: Does NOT update GitHub check status.--test-backend "pytorch, cpp"(OPTIONAL) : Skip test stages which don't match the specified backends. Only support [pytorch, cpp, tensorrt, triton]. Examples: "pytorch, cpp" (does not run test stages with tensorrt or triton backend). Note: Does NOT update GitHub pipeline status.--only-multi-gpu-test(OPTIONAL) : Only run the multi-GPU tests. Note: Does NOT update GitHub check status.--disable-multi-gpu-test(OPTIONAL) : Disable the multi-GPU tests. Note: Does NOT update GitHub check status.--add-multi-gpu-test(OPTIONAL) : Force run the multi-GPU tests in addition to running L0 pre-merge pipeline.--post-merge(OPTIONAL) : Run the L0 post-merge pipeline instead of the ordinary L0 pre-merge pipeline.--extra-stage "H100_PCIe-TensorRT-Post-Merge-1, xxx"(OPTIONAL) : Run the ordinary L0 pre-merge pipeline and specified test stages. Examples: --extra-stage "H100_PCIe-TensorRT-Post-Merge-1, xxx".--detailed-log(OPTIONAL) : Enable flushing out all logs to the Jenkins console. This will significantly increase the log volume and may slow down the job.--debug(OPTIONAL) : Experimental feature. Enable access to the CI container for debugging purpose. Note: Specify exactly one stage in 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