Sampling Algorithms for Text Generation #
Implements various sampling strategies for autoregressive language model inference.
Sampling Strategies #
1. Greedy Decoding (Deterministic) #
next_token = argmax(logits)
Use case: Reproducible outputs, factual tasks Pros: Deterministic, fast Cons: Repetitive, lacks creativity
2. Top-k Sampling #
top_k_logits, indices = topk(logits, k)
probs = softmax(top_k_logits / temperature)
next_token = sample(indices, probs)
Use case: Creative generation with controlled diversity Pros: Balances quality and diversity Cons: Fixed k may be too restrictive or permissive
3. Nucleus (Top-p) Sampling #
sorted_probs = sort(softmax(logits), descending=True)
cumsum = cumulative_sum(sorted_probs)
nucleus = sorted_probs[cumsum <= p]
next_token = sample(nucleus)
Use case: Adaptive diversity based on distribution Pros: Adapts to confidence (dynamic cutoff) Cons: More compute than top-k
Temperature Scaling #
Temperature τ controls randomness:
scaled_logits = logits / τ
τ → 0: Deterministic (greedy)
τ = 1: Normal distribution
τ > 1: More random/creative
References #
- "The Curious Case of Neural Text Degeneration" (Holtzman et al., 2019) - Nucleus sampling
- "Hierarchical Neural Story Generation" (Fan et al., 2018) - Top-k sampling
- GPT-2: Uses both top-k and top-p
- llama.cpp: common/sampling.cpp
Data Structures #
Equations
- One or more equations did not get rendered due to their size.
Instances For
Core Utilities #
Find argmax (index of maximum value)
@param logits Array of logit scores @return Index of maximum value
Equations
Instances For
Apply temperature scaling
@param logits Original logits @param temperature Temperature value (τ > 0) @return Scaled logits
Equations
Instances For
Compute softmax probabilities
Uses numerically stable version: exp(x - max(x))
@param logits Log-probabilities @return Probabilities (sum to 1.0)
Equations
- One or more equations did not get rendered due to their size.
Instances For
Greedy Sampling #
Greedy sampling: select token with highest probability
Algorithm:
next_token = argmax(logits)
@param logits Logit scores [vocab_size] @return Selected token ID
Equations
Instances For
Top-k Sampling #
Find indices of top-k largest values
@param logits Array of scores @param k Number of top elements @return (top_k_values, top_k_indices)
Equations
- One or more equations did not get rendered due to their size.
Instances For
Sample from categorical distribution
Simple implementation using linear search through cumulative probabilities.
@param probs Probability distribution (must sum to ~1.0) @param randomValue Random value in [0, 1) @return Sampled index
Equations
- Hesper.Inference.Sampling.categoricalSample probs randomValue = Hesper.Inference.Sampling.categoricalSample.loop probs randomValue 0 0.0
Instances For
Top-k sampling: sample from k tokens with highest probability
Algorithm:
1. Find top-k logits and their indices
2. Apply temperature scaling
3. Compute softmax over top-k
4. Sample from categorical distribution
@param logits Logit scores [vocab_size] @param k Number of top candidates @param temperature Sampling temperature @param randomValue Random number in [0, 1) for sampling @return Selected token ID
Equations
- One or more equations did not get rendered due to their size.
Instances For
Nucleus (Top-p) Sampling #
Nucleus (top-p) sampling: sample from smallest set with cumulative probability >= p
Algorithm:
1. Sort logits in descending order
2. Compute softmax probabilities
3. Find nucleus: tokens where cumsum(probs) <= p
4. Renormalize and sample from nucleus
@param logits Logit scores [vocab_size] @param p Cumulative probability threshold (typically 0.9) @param temperature Sampling temperature @param randomValue Random number in [0, 1) for sampling @return Selected token ID
Equations
- One or more equations did not get rendered due to their size.
Instances For
Repetition Penalty #
Apply repetition penalty to logits.
Tokens that appeared in prevTokens have their logits divided (if positive)
or multiplied (if negative) by the penalty factor.
penalty = 1.0 means no penalty. Typical values: 1.1 - 1.3.
Equations
- One or more equations did not get rendered due to their size.
Instances For
High-Level Sampling Interface #
Equations
- One or more equations did not get rendered due to their size.
Instances For
Equations
- One or more equations did not get rendered due to their size.
Sample next token using specified strategy
@param logits Logit scores [vocab_size] @param strategy Sampling strategy @param randomValue Random value in [0, 1) (only used for stochastic strategies) @return Selected token ID
Equations
- Hesper.Inference.Sampling.sample logits Hesper.Inference.Sampling.Strategy.Greedy randomValue = Hesper.Inference.Sampling.sampleGreedy logits
- Hesper.Inference.Sampling.sample logits (Hesper.Inference.Sampling.Strategy.TopK a a_1) randomValue = Hesper.Inference.Sampling.sampleTopK logits a a_1 randomValue
- Hesper.Inference.Sampling.sample logits (Hesper.Inference.Sampling.Strategy.Nucleus a a_1) randomValue = Hesper.Inference.Sampling.sampleNucleus logits a a_1 randomValue
Instances For
Random Number Generation #
Simple linear congruential generator (LCG) for reproducible sampling
Parameters: Numerical Recipes (a = 1664525, c = 1013904223, m = 2^32)
@param seed Current seed @return (random_float in [0,1), new_seed)
Equations
Instances For
Equations
- One or more equations did not get rendered due to their size.
Instances For
Equations
Sampling with RNG #
Sample with automatic RNG threading
@param logits Logit scores @param strategy Sampling strategy @param rng Random number generator state @return (selected_token, new_rng)
Equations
- One or more equations did not get rendered due to their size.
- Hesper.Inference.Sampling.sampleWithRNG logits Hesper.Inference.Sampling.Strategy.Greedy rng = (Hesper.Inference.Sampling.sampleGreedy logits, rng)