flashinfer.sampling.top_k_sampling_from_probs

flashinfer.sampling.top_k_sampling_from_probs(probs: Tensor, top_k: Tensor | int, indices: Tensor | None = None, deterministic: bool = True, generator: Generator | None = None, check_nan: bool = False, seed: int | Tensor | None = None, offset: int | Tensor | None = None, return_valid: bool = False, *, batch_invariant: bool = False, out: Tensor | None = None) → Tensor | Tuple[Tensor, Tensor]

Fused GPU kernel for top-k sampling from probabilities. This operator implements GPU-based rejection sampling without explicit sorting. Check the blog post for more details.

With batch_invariant=True the kept set is the batch-invariant class support.row.v1 and the draw over it the class sample.icdf.v1 (flashinfer/batch_invariant/README.md): the threshold is the k-th largest weight (an exact radix selection over the weights’ bit patterns, ties at the cut kept), the token the inverse CDF over the canonical sum tree of the kept weights at the fp32 uniform of a request-keyed stream – the row’s key is (seed, offset) and the token is a function of the row’s values, top_k, its seed and its offset alone, never of its slot in the batch, the batch size or the configuration. The receipt is flashinfer.batch_invariant.fingerprint("top_k_sampling_from_probs", N=, dtype=).

The multiple rounds of rejection sampling are implemented in a single CUDA kernel, which is more efficient than the naive implementation that launches a series of kernels.

Parameters:
  • probs (torch.Tensor) – Probabilities for sampling. When indices is not provided, shape should be (batch_size, num_classes) and the i-th output will be sampled from the i-th row of probabilities. When indices is provided, shape should be (unique_batch_size, num_classes) where unique_batch_size is the number of unique probability distributions.

  • top_k (Union[torch.Tensor, int]) – Either a scalar or a tensor of shape (batch_size,), or (unique_batch_size,) when indices is provided, representing the threshold for top-k sampling. If a scalar, the same threshold is used for all requests. If a tensor, each row of probs has its own threshold, and outputs that indices maps to the same row share it.

  • indices (Optional[torch.Tensor]) – Optional indices tensor of shape (batch_size,), dtype torch.int32 or torch.int64 that maps each output to a row in probs. The output tensor will have the same dtype as indices. For example, if indices[i] = j, then the i-th output will be sampled from probs[j]. This allows reusing the same probability distribution for multiple outputs. If indices is not provided, the i-th output will be sampled from the i-th row of probs and output dtype defaults to torch.int32.

  • deterministic (bool) – Whether to use deterministic kernel implementation, default is True.

  • generator (Optional[torch.Generator]) – A random number generator for the operation.

  • check_nan (bool) – Whether to check for NaNs in probs; the default is False.

  • seed (Optional[Union[int, torch.Tensor]]) –

    Random seed value for the sampling operation. Can be either an integer or a torch.Tensor. When provided as a torch.Tensor, it must be int64 or uint64 dtype and 1D. A length-one tensor broadcasts to all output rows; otherwise, its length must equal the number of output rows, with one value per output row rather than per input distribution row. Using torch.Tensor is required for CUDA graph compatibility.

    The output row index also feeds the Philox subsequence: moving the same seed and offset to a different batch slot changes the RNG stream, so per-row seeds do not make sampling invariant to batch position.

    Warning: If you provide seed and offset explicitly, you are responsible for updating their values between calls to ensure different random samples. Common approaches include: - Incrementing offset by the number of random values consumed - Updating seed based on the number of calls to the operation

  • offset (Optional[Union[int, torch.Tensor]]) –

    Random offset value for the sampling operation. Can be either an integer or a torch.Tensor. When provided as a torch.Tensor, it must be int64 or uint64 dtype and 1D. A length-one tensor broadcasts to all output rows; otherwise, its length must equal the number of output rows, with one value per output row rather than per input distribution row. Using torch.Tensor is required for CUDA graph compatibility.

    Warning: If you provide seed and offset explicitly, you are responsible for updating their values between calls to ensure different random samples. The offset should be incremented based on the number of random values consumed by the operation.

  • return_valid (bool) – When True, the kernel returns an additional boolean mask indicating which rows had a valid (non-degenerate) distribution after the renormalization step. Defaults to False.

  • batch_invariant (bool) – False (default): the operator’s kernel above, unchanged. True: the batch-invariant classes (bf16 / f16 / fp32 probabilities or unnormalised weights >= 0 of shape (..., vocabulary); top_k an int or an int32 / int64 tensor of one value or one per row; seed / offset one key per output row – int64 / uint64 tensors of length batch_size, or a scalar, a length-one tensor or the pair reserved from generator for a single row (a key shared by several rows raises ValueError); SM100 / SM103 / SM107): the token is drawn from the kept set’s renormalised distribution at the row’s key, -1 (and valid False) for a row whose kept weights do not sum to a positive finite number (nothing kept, no positive weight, a non-finite row) or whose index lies outside the source rows. deterministic is ignored (the classes are deterministic by construction). Anything the classes do not cover raises flashinfer.batch_invariant.BatchInvariantUnsupportedError instead of falling back.

  • out (Optional[torch.Tensor]) – Only with batch_invariant=True: a caller-owned buffer for samples – int32 of shape (batch_size,) (the kernel’s own output), or int64 with int64 indices (filled by a cast from the kernel’s int32 tokens, the dtype contract) – written in place and returned, so nothing is allocated (CUDA graphs on caller-owned buffers, a framework’s persistent structures). Refused with ValueError, never copied, when it does not fit.

Returns:

If return_valid is False (default), a 1-D samples tensor of shape (batch_size,). If return_valid is True, (samples, valid) where valid is a boolean tensor of shape (batch_size,) indicating which rows had a valid distribution after renormalization.

Return type:

Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]

Examples

>>> import torch
>>> import flashinfer
>>> torch.manual_seed(42)
>>> batch_size = 4
>>> vocab_size = 5
>>> top_k = 1
>>> pre_norm_prob = torch.rand(batch_size, vocab_size).to(0)
>>> norm_prob = pre_norm_prob / pre_norm_prob.sum(dim=-1, keepdim=True)
>>> norm_prob
tensor([[0.2499, 0.2592, 0.1085, 0.2718, 0.1106],
        [0.2205, 0.0942, 0.2912, 0.3452, 0.0489],
        [0.2522, 0.1602, 0.2346, 0.1532, 0.2000],
        [0.1543, 0.3182, 0.2062, 0.0958, 0.2255]], device='cuda:0')
>>> samples = flashinfer.sampling.top_k_sampling_from_probs(norm_prob, top_k)
>>> samples
tensor([3, 3, 0, 1], device='cuda:0', dtype=torch.int32)

Note

This function expects float32 inputs, and the output is int32.