AI Dictionary of Terms

Sampling

The process of selecting the next token from a language model’s probability distribution during text generation, with various strategies (greedy, random, top-k, top-p) controlling the trade-off between determinism and diversity.

The Simple Version

Imagine you’re at an ice cream shop with 100 flavors. The shop ranks them by popularity:

Sampling is how the AI picks the next word. Different strategies give different balances of predictability and creativity.

Detailed Explanation

After a language model processes input, it outputs a probability distribution over its entire vocabulary (e.g., 50,000 tokens). Sampling selects which token to generate next.

Sampling Strategies:

1. Greedy (Argmax):

2. Random (Multinomial):

3. Top-k:

4. Top-p (Nucleus):

5. Typical Sampling:

Parameters:

Key Characteristics

Business Context

Sampling strategy directly impacts AI output quality and user experience:

Use Cases by Strategy:

Best Practices:

Real-World Analogy

A jazz musician choosing the next note. Greedy sampling always plays the most expected note (safe but predictable). Random sampling plays any note (creative but possibly chaotic). Top-p sampling plays from a curated set of musically appropriate notes (balanced creativity and coherence).

Code Example

# Comparing sampling strategies
from transformers import AutoModelForCausalLM, AutoTokenizer

model = AutoModelForCausalLM.from_pretrained("gpt2")
tokenizer = AutoTokenizer.from_pretrained("gpt2")

prompt = "Once upon a time"
inputs = tokenizer(prompt, return_tensors="pt")

# Greedy (deterministic)
greedy = model.generate(**inputs, max_new_tokens=20, do_sample=False)
print("Greedy:", tokenizer.decode(greedy[0]))

# Random with temperature
random = model.generate(**inputs, max_new_tokens=20, do_sample=True, temperature=1.0)
print("Random:", tokenizer.decode(random[0]))

# Top-k sampling
topk = model.generate(**inputs, max_new_tokens=20, do_sample=True, top_k=50)
print("Top-k=50:", tokenizer.decode(topk[0]))

# Top-p (nucleus) sampling
topp = model.generate(**inputs, max_new_tokens=20, do_sample=True, top_p=0.9)
print("Top-p=0.9:", tokenizer.decode(topp[0]))

Common Misconceptions

Sources & Further Reading