New Tool Radar

AI Concepts

How to Set Top-K Sampling for Code Generation

Limit code generation to the top-k most likely tokens, so the model writes code that compiles instead of code that surprises you.

Schematic illustration with three step boxes: learn what top-k does, pick a value for code, and check the compile rate.

Top-k limits the model’s choice at each step to the k most probable tokens. A small k is very safe, a large k is more creative, and in llama.cpp the default is 40, with 0 disabling it. For code, where one wrong token can break the whole file, a modest top-k keeps the model on the tokens that belong in code.

Before you start

An API or local inference setup where you can set top-k, and a set of small coding tasks with a way to check whether the code runs.

Learn what top-k does

At each step the model keeps only the k most likely tokens and samples from those. Tokens ranked below k are excluded, however likely they seemed in isolation.

Top-k is a fixed count, unlike top-p, which keeps a fixed probability mass. A top-k of 5 is very safe, 40 is balanced, and 100 is more creative.

Pick a value for code

Use a top-k of 20 to 40 for code generation, with a low temperature alongside it. Published guidance puts code at a temperature of 0.1 to 0.3 with top-k 40.

Do not set top-k to 1 unless you want fully greedy output: it removes all variety, including the variety that picks the better of two valid spellings.

Check the compile rate, not the style

Run the same 10 coding tasks at top-k 20 and at top-k 100, and count how many outputs run without error at each. Style is a matter of taste; a compile error is a fact.

If the low setting wins on compile rate but loses on variety, keep the low setting for production code and use the high one only for brainstorming.

Practice check: fictional Maple Corner coding tasks, 10 tasks

The table below is fictional practice material, worked out by hand from the stated settings. It is the expected result for the practice tasks, not a run of any model.

Top-k Runs without error Correct output Verdict
20 9 of 10 8 of 10 Best balance
40 9 of 10 8 of 10 Tie with 20
100 6 of 10 5 of 10 Fail – too wild

Top-k 20 and 40 tie at 9 of 10 running and 8 of 10 correct, while top-k 100 falls to 6 running and 5 correct. The smaller setting wins by stability, and 40 adds nothing here.

Expected result. UNTESTED: the counts in the practice table are worked out by hand, not measured by running a model. Run your own 10 coding tasks at top-k 20 and 100, count how many run without error, and keep the setting that compiles.

Limits

  • Top-k interacts with temperature: a low temperature with a high top-k can still be wild, so set both deliberately.
  • Some APIs do not expose top-k: check your provider’s parameter list before you plan around it.

Sources

See all