-
Notifications
You must be signed in to change notification settings - Fork 1.8k
[None][feat] Add test for speculative rejection sampler (2-model) #6542
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
[None][feat] Add test for speculative rejection sampler (2-model) #6542
Conversation
📝 WalkthroughWalkthroughThis update introduces deterministic sampling via seeded Changes
Sequence Diagram(s)sequenceDiagram
participant User
participant ModelDrafter
participant TorchSampler
participant LlmRequest
User->>ModelDrafter: Initiate draft request
ModelDrafter->>TorchSampler: Check if mixed sampler enabled
TorchSampler-->>ModelDrafter: Return enable_mixed_sampler flag
ModelDrafter->>ModelDrafter: Set _request_draft_logits accordingly
ModelDrafter->>LlmRequest: Create draft request (may request logits)
LlmRequest-->>ModelDrafter: Return draft request
ModelDrafter->>TorchSampler: Process decoded tokens
TorchSampler->>LlmRequest: Use py_draft_logits and py_target_probs for probabilistic acceptance (if present)
TorchSampler-->>ModelDrafter: Return accepted/rejected tokens
Estimated code review effort🎯 4 (Complex) | ⏱️ ~40 minutes Possibly related PRs
Suggested labels
Suggested reviewers
Note ⚡️ Unit Test Generation is now available in beta!Learn more here, or try it out under "Finishing Touches" below. ✨ Finishing Touches
🧪 Generate unit tests
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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
Documentation and Community
|
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: 0
🔭 Outside diff range comments (1)
tensorrt_llm/_torch/pyexecutor/sampler.py (1)
124-157
: Critical: Temperature scaling applied in wrong orderThe temperature scaling is applied after computing cumulative probabilities from the sorted logits, creating a mismatch between the filtering threshold and the final sampling distribution. The cumulative probabilities at line 137 are computed from
sorted_logits
without temperature scaling, but then temperature is applied to the originallogits
at line 141.Apply temperature scaling before sorting:
def top_p_sampling_batch(logits: torch.Tensor, top_p: float = 0.9, temperature: float = 1.0, generator: torch.Generator = None): logits_dim = logits.dim() if logits_dim == 1: logits = logits.unsqueeze(0) assert logits_dim == 2, "logits should be 2D: [batch_size, vocab_size]" + # Apply temperature scaling before sorting + if temperature != 0: + logits = logits / max(temperature, 1e-5) + # sort the logits of each sample in descending order sorted_logits, sorted_indices = torch.sort(logits, descending=True, dim=-1) # compute cumulative probability distribution of each sample cumulative_probs = torch.cumsum(torch.softmax(sorted_logits, dim=-1), dim=-1) - if temperature != 0: - logits = logits / max(temperature, 1e-5) # get the location of top_p sorted_indices_to_remove = cumulative_probs > top_p
🧹 Nitpick comments (3)
tensorrt_llm/_torch/speculative/model_drafter.py (1)
312-313
: Add defensive check for generation_logits availability.While the logic is correct, consider adding a defensive check to ensure
generation_logits
is available before assignment to prevent potential AttributeError.if self._request_draft_logits: - target_model_req.py_draft_logits = req.py_result.generation_logits + if hasattr(req.py_result, 'generation_logits') and req.py_result.generation_logits is not None: + target_model_req.py_draft_logits = req.py_result.generation_logitstensorrt_llm/_torch/pyexecutor/sampler.py (2)
252-269
: Generator initialization is well-implementedThe deterministic generator setup with lazy initialization is correct. The implementation ensures multi-GPU consistency as intended.
Consider making the seed configurable via the
Args
dataclass instead of hardcoding it to 42:@dataclass(frozen=True, kw_only=True) class Args: max_seq_len: int max_draft_len: int max_num_sequences: int max_beam_width: int enable_mixed_sampler: bool + random_seed: int = 42 def __init__(self, args: Args): # ... existing code ... with torch.inference_mode(False): self.store = self.create_store() - # Initialize seed for multi-GPU consistency - self._global_seed = 42 + # Initialize seed for multi-GPU consistency + self._global_seed = args.random_seed self._generator = None
332-411
: Speculative rejection sampling implementation is correctThe probabilistic draft token acceptance logic correctly implements the speculative rejection sampling algorithm with deterministic random generation for multi-GPU consistency.
Consider adding explanatory comments for the complex probability calculations to improve maintainability:
target_probs = request.py_target_probs p = draft_probs[torch.arange(len(request.py_draft_tokens)), request.py_draft_tokens] q = target_probs[:-1] q = q[torch.arange(len(request.py_draft_tokens)), request.py_draft_tokens] + # Accept probability is min(1, target_prob/draft_prob) accept_probs = torch.minimum(torch.ones(()), q / p) # Use deterministic random generation for multi-GPU consistency rejected_indices = (torch.rand(accept_probs.shape, generator=generator, device=accept_probs.device) > accept_probs).nonzero()
Also for the adjusted distribution calculation:
last_draft = draft_probs[num_accepted] last_target = target_probs[num_accepted] + # Sample from adjusted distribution: max(0, target - draft) new = last_target - last_draft new = torch.where(new > 0, new, 0.0)
📜 Review details
Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (3)
tensorrt_llm/_torch/pyexecutor/llm_request.py
(1 hunks)tensorrt_llm/_torch/pyexecutor/sampler.py
(11 hunks)tensorrt_llm/_torch/speculative/model_drafter.py
(4 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.py
📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md)
**/*.py
: Python code 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 Python class in the constructor.
For interfaces that may be used outside a Python file, prefer docstrings over comments.
Comments in Python should be reserved for code within a function, or interfaces that are local to a file.
Use Google style docstrings for Python classes and functions, 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/llm_request.py
tensorrt_llm/_torch/speculative/model_drafter.py
tensorrt_llm/_torch/pyexecutor/sampler.py
**/*.{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. The block should be prepended to the top of all files, including .cpp, .h, .cu, .py, and any other source files which are compiled or interpreted.
Files:
tensorrt_llm/_torch/pyexecutor/llm_request.py
tensorrt_llm/_torch/speculative/model_drafter.py
tensorrt_llm/_torch/pyexecutor/sampler.py
⏰ 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 (9)
tensorrt_llm/_torch/pyexecutor/llm_request.py (1)
306-307
: LGTM! Clean addition of draft logits tracking variables.The new instance variables
py_draft_logits
andpy_target_probs
follow the established naming convention for Python-specific attributes in this class and are properly initialized toNone
.tensorrt_llm/_torch/speculative/model_drafter.py (3)
14-14
: LGTM!The import is correctly added to support the new functionality.
65-67
: LGTM!The conditional initialization of
_request_draft_logits
correctly determines when to request draft generation logits based on the sampler type and its mixed sampling configuration.
80-81
: LGTM!The draft request creation correctly includes the
return_generation_logits
parameter based on the mixed sampler configuration.tensorrt_llm/_torch/pyexecutor/sampler.py (5)
100-120
: Deterministic sampling implementation looks goodThe addition of the optional
generator
parameter and its propagation totorch.multinomial
correctly enables deterministic sampling across multiple GPUs.
168-178
: Type definitions correctly updated for temperature supportThe extension of the
TopP
tuple type and corresponding updates torequest_strategy
properly support the new temperature parameter.
190-200
: Sample function correctly updated for deterministic samplingThe generator parameter is properly propagated to all sampling functions, and the pattern matching correctly handles the extended
TopP
type.
431-435
: Method call correctly updated for new signatureThe
process_draft_tokens
call is properly updated to match the new method signature.
521-542
: Consistent generator usage and probability storage implemented correctlyThe method properly obtains a single generator and passes it to all sampling operations, ensuring deterministic behavior. The target probability storage for draft token processing is correctly implemented with appropriate cloning.
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: 3
🧹 Nitpick comments (2)
tests/unittest/_torch/speculative/test_torch_rejection_sampling.py (1)
9-48
: Solid empirical validation approach with minor optimization opportunity.The test design is excellent - it uses statistical validation via KL divergence to verify that rejection sampling produces the target distribution. The sparse probability setup (keeping only 100/500 tokens non-zero) creates a realistic scenario for testing.
Consider extracting the number of iterations as a constant for better maintainability:
+NUM_ITERATIONS = 50000 + def test_get_rejected_indices(): vocab_size = 500 - num_iter = 50000 + num_iter = NUM_ITERATIONStensorrt_llm/_torch/pyexecutor/sampler.py (1)
280-297
: Consider making global seed configurable.The hard-coded seed value of 42 may not be suitable for all use cases. Consider making it configurable through the constructor.
- def __init__(self, args: Args): + def __init__(self, args: Args, global_seed: int = 42): # ... existing code ... - self._global_seed = 42 + self._global_seed = global_seedAlternatively, add a setter method:
+ def set_global_seed(self, seed: int): + """Set the global seed for deterministic sampling.""" + self._global_seed = seed + self._generator = None # Reset generator to use new seed
📜 Review details
Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
tensorrt_llm/_torch/pyexecutor/sampler.py
(10 hunks)tests/unittest/_torch/speculative/test_torch_rejection_sampling.py
(1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.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:
tests/unittest/_torch/speculative/test_torch_rejection_sampling.py
tensorrt_llm/_torch/pyexecutor/sampler.py
**/*.{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:
tests/unittest/_torch/speculative/test_torch_rejection_sampling.py
tensorrt_llm/_torch/pyexecutor/sampler.py
🪛 Ruff (0.12.2)
tests/unittest/_torch/speculative/test_torch_rejection_sampling.py
51-51: Undefined name unittest
(F821)
⏰ 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 (8)
tests/unittest/_torch/speculative/test_torch_rejection_sampling.py (1)
50-52
: LGTM!The main block correctly enables standalone execution of the test.
tensorrt_llm/_torch/pyexecutor/sampler.py (7)
100-121
: LGTM! Deterministic sampling support added correctly.The addition of the optional
generator
parameter totop_k_sampling_batch
enables deterministic sampling while maintaining backward compatibility through the defaultNone
value.
124-158
: LGTM! Temperature scaling and deterministic sampling properly implemented.The function correctly:
- Adds temperature parameter with proper default value (1.0)
- Applies temperature scaling with numerical stability (max with 1e-5)
- Passes generator to multinomial for determinism
- Maintains backward compatibility
182-193
: LGTM! Rejection sampling implementation is sound.The
sample_rejected
function correctly:
- Computes the residual distribution (target - draft)
- Clips negative values to zero using
torch.where
- Uses deterministic generator for sampling
196-211
: LGTM! Type annotations and strategy handling updated correctly.The changes properly:
- Update
TopP
type to include temperature as third element- Modify
request_strategy
to return temperature from sampling config- Maintain backward compatibility
218-228
: LGTM! Generator parameter propagated correctly to all sampling strategies.The
sample
function properly passes the generator to all sampling methods that support it, while maintaining the existing interface for greedy sampling.
534-565
: LGTM! Generator integration in batch processing is well implemented.The changes correctly:
- Get a single generator per processing call for consistency
- Pass generator to all sampling functions
- Handle draft logits conditionally
- Clone target probabilities when needed
167-179
: Please confirm tensor slicing and generator device setupIt looks like the
q = target_probs[:-1]
slice is intentional (to alignq
’s rows with the length ofdraft_tokens
), and the subsequent indexing (q[arange, draft_tokens]
) matches what’s done forp
. However, one remaining concern is that ifdraft_probs
/target_probs
live on CUDA butgenerator
is a CPUtorch.Generator
, thentorch.rand( accept_probs.shape, generator=generator, # CPU generator device=accept_probs.device # e.g. “cuda” )could raise a device-mismatch error or silently fall back in an unexpected way.
• Ensure that when you build the GPU generator you use
torch.cuda.Generator(device)
if you intend to sample on CUDA.
• Otherwise, explicitly moveaccept_probs
(and inputs) to CPU before sampling with a CPU generator.If you verify that in your multi-GPU setup you always pass a CUDA generator alongside CUDA tensors, no code change is needed here.
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.
Can we ban using ngram when sampling is enabled? We'll need to do more work to enable it
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.
Thank you @IzzyPutterman! The comments are mostly nitpicks.
Will wait for GPT OSS PR to land, then update with these changes. |
/bot run |
PR_Github #14514 [ run ] triggered by Bot |
PR_Github #14514 [ run ] completed with state |
ec80a86
to
4908602
Compare
/bot run |
PR_Github #15179 [ run ] triggered by Bot |
PR_Github #15179 [ run ] completed with state |
/bot run |
PR_Github #15186 [ run ] triggered by Bot |
PR_Github #15186 [ run ] completed with state |
Signed-off-by: Izzy Putterman <[email protected]>
Signed-off-by: Izzy Putterman <[email protected]>
Signed-off-by: Izzy Putterman <[email protected]>
Signed-off-by: Izzy Putterman <[email protected]>
Signed-off-by: Izzy Putterman <[email protected]>
Signed-off-by: Izzy Putterman <[email protected]>
Signed-off-by: Izzy Putterman <[email protected]>
Signed-off-by: Izzy Putterman <[email protected]>
abaa9a8
to
2911df1
Compare
/bot run |
PR_Github #15188 [ run ] triggered by Bot |
PR_Github #15188 [ run ] completed with state |
Summary by CodeRabbit
New Features
Improvements
Tests
Description
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 thestage-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.