flashinfer.sampling.sampling_from_probs

flashinfer.sampling.sampling_from_probs(probs: Tensor, 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 category sampling from probabilities.

With batch_invariant=True the draw is the batch-invariant class sample.icdf.v1 (flashinfer/batch_invariant/README.md): the inverse CDF over the canonical sum tree of the row’s weights (the row class’s fixed add.rn tree over the vocabulary), read 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, its seed and its offset alone – never of its slot in the batch, the batch size or the configuration. The fingerprint is flashinfer.batch_invariant.fingerprint("sampling_from_probs", N=, dtype=).

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.

  • 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 (the default path; under batch_invariant=True the key alone decides the stream, see below).

    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. Defaults to False.

  • batch_invariant (bool) – False (default): the operator’s kernel above, unchanged. True: the batch-invariant class sample.icdf.v1 over the given weights (bf16 / f16 / fp32 probabilities or unnormalised weights >= 0 of shape (..., vocabulary), any vocabulary up to 2^21, beyond it only where the row’s alignment admits a configuration within the class’s share bound; SM100 / SM103 / SM107). The RNG is the class’s slot-free stream: the per-row seed / offset tensors as given, one key per output row (a request’s own pair); a scalar, a length-one tensor or the pair reserved from generator exactly as the default path reserves it serves a single row, and with more rows raises ValueError (a shared key would draw every row at the same uniform). The uniform is Philox4x32-10 on the key mix64(seed ^ mix64(offset)) at counter 0, so the same row with the same key draws the same token at any batch position, in any batch – and the uniforms are not those of the default path for any slot. deterministic is ignored (the class is deterministic by construction); check_nan is the same host check; indices is the gather (an index outside the source rows makes its output row invalid); return_valid returns the class’s validity (False, and the token -1, where the row’s weights do not sum to a positive finite number). Anything the class does 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,), or int64 with int64 indices (filled by a cast from the kernel’s int32 tokens) – written in place and returned, so no output is allocated. Refused, 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.

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
>>> 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.sampling_from_probs(norm_prob)
>>> samples
tensor([1, 2, 1, 4], device='cuda:0', dtype=torch.int32)

Note

The default path expects float32 inputs. With batch_invariant=True, inputs may be bfloat16, float16, or float32 probabilities or unnormalised weights. The output is int32 unless indices is provided, in which case the output has the same dtype as indices when out is not supplied. With batch_invariant=True and out supplied, the output has out.dtype.