New Tool Radar

AI Concepts

How to Set Top-K Sampling to Cap Token Choices

Set top-k to keep only the k most likely tokens in play, then check the output stays coherent.

Schematic with three steps: Set top-k to a starting value; Generate and check coherence; Compare with top-p if both are offered.

Top-k sampling restricts choices to the k highest-probability tokens, then samples from those, which prevents completely nonsensical picks by cutting off the long tail. It is a hard count limit, unlike top-p, which adapts to the distribution. Where it is offered, a typical range is 20 to 100, and some serving stacks recommend 20 for thinking mode and 40 for reasoning tasks.

What you need

  • A generation task and a model or API that offers top_k
  • A note of the top_k value you start with
  • A coherence check for the output

Step 1: Set top-k to a starting value

Set top_k to 40, inside the typical 20 to 100 range, or to 20 if the task is a thinking or reasoning task on a stack that recommends it. A value of -1 disables it on some stacks.

Step 2: Generate and check coherence

Generate a reply and check it reads coherently. If the output is too repetitive, raise top-k; if it picks nonsense words, lower it.

Step 3: Compare with top-p if both are offered

If your API offers both, try top-p as the alternative: top-p adapts to the distribution and is generally preferred, while top-k is a hard cap that is simpler to reason about.

Worked example: synthetic top-k test

The table below is a synthetic example. It shows the expected result of a top-k test; no model was run.

Top-k Tokens in play Output
100 Top 100 Varied, coherent
40 Top 40 Coherent, on-topic
20 Top 20 Coherent, narrower
5 Top 5 Repetitive

Expected result (UNTESTED). top-k 40 gives a coherent on-topic reply, 100 is more varied, and 5 is repetitive, so 40 is picked. This check was not run live; the table shows the expected result for the synthetic example.

Limits

  • Top-k is a hard cap; where it is not offered, use top-p instead.
  • A typical range is 20 to 100; below that the output turns repetitive.
  • Top-p adapts to the distribution and is generally preferred to top-k.
  • On some stacks, -1 disables top-k; check your stack default before assuming it is on.

Sources

See all