← Math
Math

Sampling strategies (greedy, top-k, top-p)

Which strategy keeps a teen language app’s sentences clean?

Compare the candidate words each decoding strategy permits before measuring its risk.

Outcome

Build the top-k and top-p candidate sets, renormalise them, and measure what share of each set a content rule would flag.

Terminology (5)Terms used in this lesson

Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.

Greedy decoding
Always taking the most likely next word; deterministic and often repetitive.
Top-k sampling
Sampling only among the k most likely next words.
Top-p sampling Also nucleus sampling
Sampling among the fewest most likely words whose probabilities add up to at least p.
Renormalise
Divide the kept probabilities by their total so they sum to 1 again.
Content rule
A product limit on how likely generated text is to contain flagged words.

Why this matters

A language model gives a probability for every possible next word; the decoding strategy decides which of them can actually be chosen. That choice controls variety, repetition and, for products with rules about what may appear, risk. The same model can meet this particular flagged-word rule with one strategy and fail it with another, and the answer changes from sentence to sentence.

This lesson assumes probability, cumulative sums and sorting.

How decoding selects candidates

A next-word distribution assigns probability to each word in the vocabulary. Greedy decoding takes a word with the largest probability. Top-k keeps a fixed number k of the most likely words, while top-p keeps a prefix in descending probability order until its cumulative probability reaches a threshold.

Top-k and top-p then sample from their retained candidates, with probabilities rescaled to sum to one. Choosing the candidate set and measuring the chance of a flagged word are separate calculations. Here a word is one item in the lesson’s simplified whole-word vocabulary.

01Greedy and top-k

Greedy and top-k

A language-learning app for 13 to 16 year olds generates example sentences with a language model. Its content rule allows at most a 5% chance of a flagged word, such as alcohol, tobacco or weapons, at any position in its simplified whole-word vocabulary. The team has to choose between top-k 4 and top-p 0.9 for the generator.

After “I would like a” the model gives coffee 0.35, table 0.20, ticket 0.15, beer 0.10, room 0.08, cigarette 0.05, refund 0.04 and knife 0.03. Greedy always writes coffee: safe, and every example sentence reads the same. Top-k 4 samples among the four most likely words, which adds variety and includes beer.

Hosted model APIs take top_p (and some take top_k) as request parameters; the arithmetic here is what they apply before each draw.

02Top-p adapts to the distribution

Top-p adapts to the distribution

To test an adaptive alternative, top-p 0.9 adds the most likely words until their total reaches 0.9: coffee, table, ticket, beer and room make 0.88, so cigarette joins and the total is 0.93. After “Can I have the”, where the model gives bill 0.62 and menu 0.25, top-p 0.85 stops at two words. The set is small when probability is concentrated and larger when it is spread out. Exact arithmetic describes the smallest mathematical prefix. This implementation parses probabilities and top as finite binary64 values, keeps input order on equal values, then accumulates the sorted probabilities sequentially from zero and stops at the first computed total ≥ top. With 0.7, 0.1, 0.1, 0.1 and top 0.8, the first two add to about 0.7999999999999999 in binary64, so this computed policy keeps three words. No extra epsilon is used. Renormalise over the kept computed total; the flagged percentage is also a computed binary64 sum compared inclusively with the limit.

03Renormalise what you keep

Renormalise what you keep

Predict the flagged share of each strategy.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
// Next word after "I would like a", sorted by probability.
const words: [string, number][] = [
  ["coffee", 0.35],
  ["table", 0.2],
  ["ticket", 0.15],
  ["beer", 0.1],
  ["room", 0.08],
  ["cigarette", 0.05],
  ["refund", 0.04],
  ["knife", 0.03]
];
const flagged = new Set(["beer", "cigarette", "knife"]);

function report(kept: [string, number][]) {
  const mass = kept.reduce((sum, [, p]) => sum + p, 0);
  const bad = kept.reduce((sum, [w, p]) => sum + (flagged.has(w) ? p : 0), 0);

  console.log(kept.length, mass.toFixed(2), ((bad / mass) * 100).toFixed(2)); // words kept, their mass, flagged share %
}

report(words.slice(0, 4)); // top-k 4
let total = 0;
const nucleus: [string, number][] = [];

for (const word of words) {
  nucleus.push(word);
  total += word[1];

  if (total >= 0.9) break;
}

report(nucleus); // top-p 0.9: include the word that reaches the computed threshold

The sampler draws only from the kept words, so their probabilities are scaled up to sum to 1. Beer’s 0.10 becomes 0.10 / 0.80 = 12.5% under top-k; beer and cigarette together become 0.15 / 0.93 = 16.1% under top-p. Reading the raw probabilities, 10% and 15%, understates both.

04The content rule

The content rule

Flagged share of each set against a 5% rule
ContextTop-k 4Top-pKeeps the rule
“I would like a”, flagged beer, cigarette, knife; p = 0.912.50%16.13%neither
“Can I have the”, flagged wine; p = 0.855.21%0.00%top-p
Do these checks certify either tested configuration for every context?

05Per word, not per sentence

Per word, not per sentence

06Choose the generator’s strategy

Choose the generator’s strategy

Inspect the exact words each truncation would permit before measuring the flagged share. The generator samples from the retained mass, so its content-rule check must use renormalised probabilities for both configurations. A passing check applies to this context and vocabulary, not every generated sentence.

In the frontend A teacher preview of each strategy in Next.js and Svelte Optional

A teacher-facing preview can list the words each strategy could pick for a sentence, with the flagged share of its renormalised set, so a regenerated sentence is explainable.

Estimate.tsx
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
// A teacher preview: which next words each strategy could pick, and the flagged share it carries.
type Word = { text: string; p: number; flagged: boolean };

function keep(words: Word[], strategy: { k: number } | { top: number }): Word[] {
  const sorted = [...words].sort((a, b) => b.p - a.p);

  if ("k" in strategy) return sorted.slice(0, strategy.k);

  let total = 0;
  const kept: Word[] = [];

  for (const word of sorted) {
    kept.push(word);
    total += word.p;

    if (total >= strategy.top) break;
  }

  return kept;
}

export function StrategyPreview({
  words,
  strategy
}: {
  words: Word[];
  strategy: { k: number } | { top: number };
}) {
  const kept = keep(words, strategy);
  const mass = kept.reduce((s, w) => s + w.p, 0);
  const flagged = kept.filter((w) => w.flagged).reduce((s, w) => s + w.p, 0) / mass;

  return (
    <p>
      {kept.map((w) => w.text).join(", ")} ({(flagged * 100).toFixed(1)}% flagged)
    </p>
  );
}

Check this idea later
The model is very sure: the top word has 0.97. How many words does top-p 0.9 keep?
Why measure the flagged share after renormalising?
Sources

Values above were run in Node 22, Go 1.27, Rust 1.99 and Apple clang 17. The sentences and probabilities are a worked model.

Report a problem in this lesson

For typos, mistakes and things that don’t work. We read every report and fix what’s wrong, but we don’t reply here, so a question won’t get an answer.