60. Top-p Sampling medium

Write a GPU program that implements top-p (nucleus) sampling for LLM inference.

Top-p sampling is a text generation technique where you sample from the smallest set of tokens whose cumulative probability exceeds threshold p. This balances randomness and quality better than pure top-k or greedy sampling.

Given logits (unnormalized scores) from a language model:

  1. Convert logits to probabilities using softmax
  2. Sort tokens by probability (descending); tokens with equal probability are ordered by increasing index
  3. Find the smallest set where cumulative probability ≥ p (the "nucleus")
  4. Renormalize the nucleus probabilities to sum to 1
  5. Sample a token from the nucleus using the provided random seed, as defined below

The sample is deterministic, so every correct implementation returns the same token. Each token with index i in logits gets a uniform number from the seed and its index, using the PCG hash h on unsigned 32-bit integers. All arithmetic wraps modulo , and seed is reinterpreted as an unsigned 32-bit integer:

uint32 h(uint32 x) {
    uint32 state = x * 747796405u + 2891336453u;
    uint32 word  = ((state >> ((state >> 28u) + 4u)) ^ state) * 277803737u;
    return (word >> 22u) ^ word;
}

u_i = (h(h(seed) + i) + 0.5) / 2^32

The sampled token is the nucleus token with the largest , where is its renormalized probability. This "exponential race" picks token i with probability . Renormalizing scales every score by the same factor, so it does not change which token wins.

Implementation Requirements

  • Use only native features (external libraries are not permitted)
  • The solve function signature must remain unchanged
  • Ensure numerical stability when computing softmax

Example 1:

Input:
  logits = [1.0, 2.0, 3.0, 0.5]
  p = 0.9
  seed = 42

Output:
  sampled_token = 0

  The nucleus is tokens 2, 1, 0 (cumulative probability 0.948 ≥ 0.9), and h(seed) = 1223963391:
  token 2: q = 0.6652, u = 0.0049, q / -ln(u) = 0.1249
  token 1: q = 0.2447, u = 0.2550, q / -ln(u) = 0.1791
  token 0: q = 0.0900, u = 0.6485, q / -ln(u) = 0.2079  (largest)

Example 2:

Input:
  logits = [10.0, 1.0, 1.0]
  p = 0.5
  seed = 123

Output:
  sampled_token = 0
  (single token dominates the probability mass)

Constraints

  • 3 ≤ vocab_size ≤ 50,000
  • -100.0 ≤ logits[i] ≤ 100.0
  • 0.0 < p ≤ 1.0
  • 0 ≤ sampled_token < vocab_size
  • Performance is measured with vocab_size = 50,000

Starter code (CUDA)

#include <cuda_runtime.h>

extern "C" void solve(const float* logits, const float* p, const int* seed, int* sampled_token,
                      int vocab_size) {}

Solve it on your GPU

From LeetGPU, CC BY-NC-ND 4.0.