Skip to content

Conversation

IzzyPutterman
Copy link
Collaborator

@IzzyPutterman IzzyPutterman commented Aug 1, 2025

Summary by CodeRabbit

  • New Features

    • Added support for deterministic sampling using seeded random generators, ensuring consistent results across multi-GPU setups.
    • Introduced temperature control for top-p sampling, allowing more flexible sampling strategies.
    • Implemented probabilistic acceptance of draft tokens based on model confidence, improving speculative decoding.
  • Improvements

    • Enhanced handling of draft logits and probabilities for more accurate and controlled token generation.
  • Tests

    • Added unit tests validating the rejection sampling mechanism to ensure accurate probabilistic token acceptance.

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 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.

Copy link
Contributor

coderabbitai bot commented Aug 1, 2025

📝 Walkthrough

Walkthrough

This update introduces deterministic sampling via seeded torch.Generator for multi-GPU consistency, adds temperature scaling to top-p sampling, and implements probabilistic draft token acceptance using draft and target logits. New instance variables are added to LlmRequest, and ModelDrafter is updated to manage draft logits conditionally when using a mixed sampler.

Changes

Cohort / File(s) Change Summary
LlmRequest Draft Logits Variables
tensorrt_llm/_torch/pyexecutor/llm_request.py
Adds py_draft_logits and py_target_probs instance variables to LlmRequest for draft token processing.
Deterministic Sampling, Draft Token Acceptance, and API Extensions
tensorrt_llm/_torch/pyexecutor/sampler.py
Introduces seeded sampling with torch.Generator, temperature for top-p sampling, probabilistic draft token acceptance using logits, API signature changes, and internal logic updates to support deterministic and probabilistic draft workflows.
Conditional Draft Logits in ModelDrafter
tensorrt_llm/_torch/speculative/model_drafter.py
Adds _request_draft_logits flag to ModelDrafter, conditionally requests and propagates draft logits when using a mixed sampler, and updates draft request/result handling accordingly.
Rejection Sampling Unit Test
tests/unittest/_torch/speculative/test_torch_rejection_sampling.py
Adds a new unit test validating rejection sampling correctness by comparing KL divergence between rejection-sampled and target distributions over many iterations.

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
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~40 minutes

Possibly related PRs

Suggested labels

Community want to contribute

Suggested reviewers

  • HuiGao-NV
  • mikeiovine
  • syuoni
  • lfr-0531

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.

✨ 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.
    • Explain this complex logic.
    • 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. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • 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 src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need 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)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

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.

Documentation and Community

  • 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.

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

🔭 Outside diff range comments (1)
tensorrt_llm/_torch/pyexecutor/sampler.py (1)

124-157: Critical: Temperature scaling applied in wrong order

The 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 original logits 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_logits
tensorrt_llm/_torch/pyexecutor/sampler.py (2)

252-269: Generator initialization is well-implemented

The 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 correct

The 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

📥 Commits

Reviewing files that changed from the base of the PR and between aee35e2 and 66c3317.

📒 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 and py_target_probs follow the established naming convention for Python-specific attributes in this class and are properly initialized to None.

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 good

The addition of the optional generator parameter and its propagation to torch.multinomial correctly enables deterministic sampling across multiple GPUs.


168-178: Type definitions correctly updated for temperature support

The extension of the TopP tuple type and corresponding updates to request_strategy properly support the new temperature parameter.


190-200: Sample function correctly updated for deterministic sampling

The 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 signature

The process_draft_tokens call is properly updated to match the new method signature.


521-542: Consistent generator usage and probability storage implemented correctly

The 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.

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: 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_ITERATIONS
tensorrt_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_seed

Alternatively, 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

📥 Commits

Reviewing files that changed from the base of the PR and between 67c3e24 and 5babf3f.

📒 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 to top_k_sampling_batch enables deterministic sampling while maintaining backward compatibility through the default None 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 setup

It looks like the q = target_probs[:-1] slice is intentional (to align q’s rows with the length of draft_tokens), and the subsequent indexing (q[arange, draft_tokens]) matches what’s done for p. However, one remaining concern is that if draft_probs/target_probs live on CUDA but generator is a CPU torch.Generator, then

torch.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 move accept_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.

Copy link
Collaborator

@mikeiovine mikeiovine left a 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

Copy link
Collaborator

@mikeiovine mikeiovine left a 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.

@IzzyPutterman
Copy link
Collaborator Author

Will wait for GPT OSS PR to land, then update with these changes.

@IzzyPutterman
Copy link
Collaborator Author

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #14514 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #14514 [ run ] completed with state SUCCESS
/LLM/main/L0_MergeRequest_PR pipeline #10962 completed with status: 'FAILURE'

@IzzyPutterman IzzyPutterman force-pushed the iputterman/torch-rejection-sampling branch from ec80a86 to 4908602 Compare August 13, 2025 20:13
@IzzyPutterman
Copy link
Collaborator Author

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #15179 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #15179 [ run ] completed with state FAILURE
/LLM/main/L0_MergeRequest_PR pipeline #11462 completed with status: 'FAILURE'

@IzzyPutterman
Copy link
Collaborator Author

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #15186 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #15186 [ run ] completed with state FAILURE
/LLM/main/L0_MergeRequest_PR pipeline #11468 completed with status: 'FAILURE'

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]>
@IzzyPutterman IzzyPutterman force-pushed the iputterman/torch-rejection-sampling branch from abaa9a8 to 2911df1 Compare August 13, 2025 21:26
@IzzyPutterman
Copy link
Collaborator Author

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #15188 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

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

@mikeiovine mikeiovine changed the title Speculative Rejection Sampler for 2 model [None][feat] Add test for speculative rejection sampler (2-model) Aug 14, 2025
@mikeiovine mikeiovine merged commit ef53de8 into NVIDIA:main Aug 14, 2025
4 of 5 checks passed
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