New Tool Radar

AI Concepts

How to Limit Token Choices with Top-k in a Local Model

Limit token choices with top-k in a local model so the model only picks from the k most likely next tokens.

Schematic illustration of limit token choices with top-k in a local model: step one find the top-k setting, step two set top-k to 40, step three check the output.

Top-k controls the number of top tokens to consider: with top-k set to 40, the model picks its next token from the 40 most likely tokens only. It is a fixed-size pool, unlike top-p, which adapts to the model’s confidence. Top-k is not exposed by the OpenAI API, but it is available in local runtimes such as llama.cpp and vLLM, and in the NVIDIA NIM sampling parameters.

Prerequisites

  • A local runtime that exposes top_k, such as llama.cpp or vLLM.
  • A prompt where the answer should stay predictable.
  • A way to set sampling parameters in that runtime.

Steps

Step 1: Find the top-k setting

Find where your runtime sets top-k: a command-line flag, a parameter in the request, or a settings page. Note its default, which is often -1, meaning all tokens are considered.

Step 2: Set top-k to 40

Set top_k to 40, a common starting value. Leave temperature and top-p at their defaults for this test, so the change you see comes from top-k alone.

Step 3: Check the output

Run the prompt and read the output. It should be coherent and on topic. If it is repetitive, raise top-k; if it wanders, lower it.

Worked example: Harbor Light library catalogue summary

The fictional Harbor Light library summarises a catalogue note with a local model. At top-k -1 the summary wanders; at 40 it stays on the note.

Setting Tokens considered Summary result
top-k -1 (all tokens) All Wanders off topic
top-k 40 40 most likely Stays on the note
top-k 5 5 most likely Repetitive

Top-k 40 keeps the summary on the note, while all tokens wanders and top-k 5 repeats itself, so 40 is the working value for this task.

Expected result. The output at top-k 40 is coherent and on topic, and you know which direction to adjust if it is not. UNTESTED: this guide was not run against a live model or API. The worked example below is fictional practice material, and its result is the expected result, not a measured one.

Limits

  • Top-k is not available in every API; the OpenAI API does not expose it, so check your runtime first.
  • A very small top-k makes output repetitive; a very large one changes little.
  • This guide does not cover combining top-k with top-p.

Sources

See all