Learn the MachineDansk

Explained with an interactive demo

Temperature and top-p in language models

A language model does not simply pick “the right” next word. It gives every possible token a probability, and then one is drawn at random. Temperature and top-p decide how that draw works. Move them below and watch the distribution change.

The demo needs JavaScript. The text below explains what it shows.

Embed this demo on your site

Copy the code into your page. The demo loads from learnthemachine.com, so it stays up to date, and the link under it shows where it comes from.

From logits to probabilities

For every possible next token, the model produces a number, a logit. Softmax turns the logits into probabilities that add up to 100%. With no other settings, a token is then drawn with exactly those probabilities. Those are the light bars in the demo.

Temperature

Temperature divides all logits by the same number before softmax. Below 1 the differences grow, and the distribution concentrates on the most likely tokens. Above 1 the differences shrink, and unlikely tokens get a real chance. At temperature 0 you always pick the most likely token. This is called greedy decoding.

Temperature never changes the order. The most likely token is the same at every temperature; only its distance to the others changes.

Top-p

Top-p, also called nucleus sampling, cuts off the tail. You sort the tokens by probability and keep the top ones until their combined probability reaches p. The rest get 0%, and the kept ones are rescaled to add up to 100%. At top-p 0.9 you only draw among the tokens that together cover 90% of the probability. The advantage is that the number of candidates adapts: when the model is confident there are few, and when it is unsure there are more.

Top-k is a simpler variant that always keeps the k most likely tokens.

Which settings should you choose?

Temperature does not make the model smarter or more knowledgeable. It only changes how it chooses among what it already predicts. Even at temperature 0, answers from a service can vary slightly, for example because of rounding in the calculations.

Try it on a model you train yourself

In the free Tokenization lab you train a small language model in the browser and then draw the next character with your own temperature and top-p, so you can see what the settings do to the text the model writes.

Open the Tokenization lab

More explainers