What is the difference between top_k, top_p, and min_p sampling in open-source LLM APIs? | A1Lab@HamzaM to AI & LLMEnglish • 3 days ago

What is the difference between top_k, top_p, and min_p sampling in open-source LLM APIs?

message-square
0

Overview

In open-source LLM runtimes (like vLLM, llama.cpp, or SGLang), top_k, top_p, and min_p filter which candidate tokens survive before sampling the next token. Each rule cuts the long tail differently based on how the model scores its next-token probabilities.

  • Fixed count vs. dynamic mass vs. relative confidence: top_k keeps a fixed number of top tokens, top_p keeps the smallest set reaching cumulative probability p, and min_p keeps tokens with probability at least min_p * max_prob.
  • Why min_p often beats top_k or top_p at higher temperatures: A fixed k is rigid, and top_p can pull in noisy tail tokens when the distribution is flat, while min_p scales the cutoff relative to the top token’s probability.

Steps

  1. Understand the top_k fixed-pool rule: Sort tokens by probability descending and keep only the top K tokens. This ignores whether 2 tokens or 200 tokens are actually plausible at that step.
  2. Understand the top_p cumulative-mass rule: Add highest-probability tokens one by one until their sum reaches p (for example 0.9 or 0.95), then drop the rest. When the model is uncertain, p can include a long tail of weak tokens.
  3. Understand the min_p relative-threshold rule: Multiply the top token’s probability by min_p (for example 0.05 or 0.1), discard tokens below that bar, and renormalize the remaining candidates. When the top token is dominant (0.80 with min_p = 0.1), anything below 0.08 is cut cleanly.
  4. Test settings on your task and avoid stacking too many cutoffs: Start with clean defaults per task—near-zero randomness for structured/code tasks and higher temperature with min_p or top_p for creative tasks—and avoid stacking aggressive cutoffs blindly.

Example

export interface CandidateToken {
  token: string;
  prob: number;
}

export interface SamplingConfig {
  topK?: number;
  topP?: number;
  minP?: number;
}

function normalizeProbs(tokens: CandidateToken[]): CandidateToken[] {
  const sum = tokens.reduce((acc, t) => acc + Math.max(0, t.prob), 0);
  if (sum <= 0) return [];
  return tokens.map((t) => ({
    token: t.token,
    prob: Math.max(0, t.prob) / sum,
  }));
}

export function applyTopK(tokens: CandidateToken[], k: number): CandidateToken[] {
  if (k <= 0) return [];
  const sorted = [...tokens].sort((a, b) => b.prob - a.prob);
  return normalizeProbs(sorted.slice(0, k));
}

export function applyTopP(tokens: CandidateToken[], p: number): CandidateToken[] {
  if (p <= 0) return [];
  if (p >= 1) return normalizeProbs(tokens);

  const sorted = [...tokens].sort((a, b) => b.prob - a.prob);
  const selected: CandidateToken[] = [];
  let cumulative = 0;

  for (const item of sorted) {
    selected.push(item);
    cumulative += item.prob;
    if (cumulative >= p) break;
  }

  return normalizeProbs(selected);
}

export function applyMinP(tokens: CandidateToken[], minP: number): CandidateToken[] {
  if (minP <= 0) return normalizeProbs(tokens);
  if (minP >= 1) {
    const sorted = [...tokens].sort((a, b) => b.prob - a.prob);
    return sorted.length > 0 ? [{ token: sorted[0].token, prob: 1 }] : [];
  }

  const sorted = [...tokens].sort((a, b) => b.prob - a.prob);
  if (sorted.length === 0) return [];

  const maxProb = sorted[0].prob;
  const threshold = maxProb * minP;
  const filtered = sorted.filter((t) => t.prob >= threshold);

  return normalizeProbs(filtered.length > 0 ? filtered : [sorted[0]]);
}

export function filterCandidates(
  tokens: CandidateToken[],
  config: SamplingConfig
): CandidateToken[] {
  let current = normalizeProbs(tokens);

  if (typeof config.topK === "number") {
    current = applyTopK(current, config.topK);
  }
  if (typeof config.topP === "number") {
    current = applyTopP(current, config.topP);
  }
  if (typeof config.minP === "number") {
    current = applyMinP(current, config.minP);
  }

  return current;
}

// Demo comparing how top_k, top_p, and min_p filter the same distribution
const distribution: CandidateToken[] = [
  { token: " Paris", prob: 0.62 },
  { token: " Lyon", prob: 0.18 },
  { token: " Nice", prob: 0.10 },
  { token: " Mars", prob: 0.05 },
  { token: " banana", prob: 0.03 },
  { token: " quantum", prob: 0.02 },
];

console.log("top_k=2:", applyTopK(distribution, 2));
console.log("top_p=0.90:", applyTopP(distribution, 0.90));
console.log("min_p=0.10:", applyMinP(distribution, 0.10));

Tips

  • Check parameter support per inference engine: Not every hosted or self-hosted API exposes min_p or top_k, so verify your runtime’s exact request schema before relying on it.
  • Watch the order of sampler operations in your engine: Applying temperature, penalties, top_k, top_p, and min_p in different orders can change the surviving token set.
  • Tune against real evals rather than guesswork: Compare top_p and min_p on representative prompts to catch weird word choices or repetition early.