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_kkeeps a fixed number of top tokens,top_pkeeps the smallest set reaching cumulative probabilityp, andmin_pkeeps tokens with probability at leastmin_p * max_prob. - Why
min_poften beatstop_kortop_pat higher temperatures: A fixedkis rigid, andtop_pcan pull in noisy tail tokens when the distribution is flat, whilemin_pscales the cutoff relative to the top token’s probability.
Steps
- Understand the
top_kfixed-pool rule: Sort tokens by probability descending and keep only the topKtokens. This ignores whether 2 tokens or 200 tokens are actually plausible at that step. - Understand the
top_pcumulative-mass rule: Add highest-probability tokens one by one until their sum reachesp(for example0.9or0.95), then drop the rest. When the model is uncertain,pcan include a long tail of weak tokens. - Understand the
min_prelative-threshold rule: Multiply the top token’s probability bymin_p(for example0.05or0.1), discard tokens below that bar, and renormalize the remaining candidates. When the top token is dominant (0.80withmin_p = 0.1), anything below0.08is cut cleanly. - 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_portop_pfor 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_portop_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, andmin_pin different orders can change the surviving token set. - Tune against real evals rather than guesswork: Compare
top_pandmin_pon representative prompts to catch weird word choices or repetition early.
You must log in or register to comment.
