flashinfer.sampling.sampling_from_logits

flashinfer.sampling.sampling_from_logits(logits: 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, *, batch_invariant: bool = False, temperature: float | Tensor | None = None, return_logprob: bool = False, out: Tensor | None = None, logprob_out: Tensor | None = None) → Tensor | Tuple[Tensor, Tensor]

Fused GPU kernel for category sampling from logits. It’s equivalent to sampling from the probabilities obtained by applying softmax to logits.

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 e_j = ex2.approx.ftz((x_j - m) log2(e)) (the class lse.row behind log_probs(), so the drawn token’s log-probability under log_probs() is the probability it was drawn with), 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_logits", N=, dtype=).

Parameters:
  • logits (torch.Tensor) – Logits 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 logits. 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 logits. 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 logits[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 logits and output dtype defaults to torch.int32.

  • deterministic (bool) – Since the sampling doesn’t use cub’s BlockScan, it is deterministic. We keep this argument for compatibility with other sampling functions.

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

  • check_nan (bool) – Whether to check for NaNs in logits; 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.

  • batch_invariant (bool) – False (default): the operator’s kernel above, unchanged. True: the batch-invariant class sample.icdf.v1 over the lse.row weights of the logits (bf16 / f16 / fp32 logits 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: token -1). Anything the class does not cover raises flashinfer.batch_invariant.BatchInvariantUnsupportedError instead of falling back.

  • temperature (Optional[Union[torch.Tensor, float]]) – Only with batch_invariant=True (ValueError otherwise: the operator’s kernel takes none). None (no scaling), a positive scalar, or a tensor with one positive value per output row (float16 / bfloat16 / float32 / float64, the last rounded to float32) of shape (batch_size,), applied inside the class’s chain (c = log2(e) / temperature) exactly as softmax() and log_probs() apply it, so the draw is from softmax(logits / temperature) and the returned log-probability is that distribution’s. A scalar is validated on the host; a tensor’s values are not (a 0 yields an invalid row). temperature=1.0 forms the same scale bits as None (div.rn(log2(e), 1)), so the tokens agree, but the receipt differs: whether a temperature enters the scale is a dimension of the fingerprint, as for softmax().

  • return_logprob (bool) – Only with batch_invariant=True. Also return the drawn token’s natural log-probability under the full distribution at the given temperature (fp32, shape (batch_size,), NaN for an invalid row): bit for bit log_probs() (logits, samples, temperature) – the value a trainer re-scoring the token computes, so the rollout’s and the trainer’s log-probabilities are the same bits with no second pass over the row.

  • 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 above) – written in place and returned, so no output is allocated. Refused, never copied, when it does not fit.

  • logprob_out (Optional[torch.Tensor]) – Only with batch_invariant=True: a caller-owned float32 buffer of shape (batch_size,) for the log-probability (it implies return_logprob=True), written in place and returned.

Returns:

samples – Sampled categories, shape (batch_size,). It’s equivalent to sampling from logits after applying softmax. Under batch_invariant=True a row whose weights do not sum to a positive finite number (a row of -inf logits, or with a NaN) draws -1, and with return_logprob the pair (samples, logp) is returned.

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
>>> logits = torch.rand(batch_size, vocab_size).to(0)
>>> logits
tensor([[0.8823, 0.9150, 0.3829, 0.9593, 0.3904],
        [0.6009, 0.2566, 0.7936, 0.9408, 0.1332],
        [0.9346, 0.5936, 0.8694, 0.5677, 0.7411],
        [0.4294, 0.8854, 0.5739, 0.2666, 0.6274]], device='cuda:0')
>>> samples = flashinfer.sampling.sampling_from_logits(logits)
>>> samples
tensor([0, 1, 1, 1], device='cuda:0', dtype=torch.int32)