Concepts / Temperature Scaling for Text Generation

Temperature Scaling for Text Generation

Temperature scaling adjusts how evenly the probabilities are spread within that boundary.

  • Programming

A Tempting Misreading of Top-k

When a text generator produces the next word, it does not simply output one answer. It scores every token in its vocabulary and then draws one token from the scores. Top-k sampling is one way of controlling that draw, and its name suggests something specific: the k largest scores are involved. Many learners read that name and conclude that top-k always returns the single best-scoring token. That reading is incorrect, and the rest of this article is about why.

What do you think happens?

If top-k sampling is run with k set to 3, does it always pick the single highest-scoring token?

  • Yes, it always returns the top-scoring token

  • No, it restricts the choice to the 3 most likely tokens and then samples among them

Reveal answer
Answer:

No, it restricts the choice to the 3 most likely tokens and then samples among them

Top-k sampling restricts the candidate tokens to the k most likely ones. It does not force the single highest-scoring token to be chosen. The final token is drawn from the surviving candidates using probabilities.

Narrowing Versus Choosing

The source makes a sharp distinction between narrowing and choosing. Top-k sampling does narrow the set of options, because it removes every token outside the k most likely ones. But narrowing is not the same as choosing. The k survivors are a pool of allowed candidates. The sampler still has to pick one of them, and it does so according to the probabilities that the candidates receive.

The contrast with greedy decoding makes this clear. Greedy decoding, which is the argmax choice, always returns the single highest-scoring token. Given the same scores, it would return the same token every time. Top-k sampling keeps a small group of plausible tokens open, so a lower-ranked survivor can sometimes be drawn. That is the source of the extra variety that top-k is designed to allow.

everyalways returnedeverycandidateinchescandidateyoucandidateboth allowedboth allowed
Which tokens can the next-token step return under greedy decoding, and which can it return under top-k sampling with k set to 3?

Three Stages: Select, Mask, Softmax

Top-k sampling works on the logits, which are the raw scores the model produces for each vocabulary token before any probabilities are computed. The procedure has three stages. First, find the k largest logits. Second, mask every other logit so that it cannot compete. Third, apply softmax to the result to convert the scores into probabilities. The output is a probability distribution over the surviving candidates, and the next token is drawn from it.

Logitsraw score per tokenSelect top-kfind k largest logitsMask the restother logits set tonegative infinitySoftmaxover unmasked positionsProbabilitiesk survivors, summing to 1scoreseligible positionsmasked vectornormalized
What happens to the logit vector at each step, from selecting the top-k entries to producing the final next-token probabilities?

Read the pipeline from left to right. The logits are the input. The top-k step decides which positions are eligible. The masking step removes the rest by assigning them negative infinity. The softmax step turns the surviving scores into probabilities. The source states that the purpose of this arrangement is that the next token is always sampled from a top-k position.

Key point

The ordering matters. The top-k masking happens before the probabilities are finalized, so the probabilities are computed only over the candidates that were allowed to survive.

Tracing a Logit Vector Through Masking

The source uses a nine-token vocabulary: forward, closer, effort, inches, toward, every, moves, pizza, and you. With k set to 3, only three of those nine positions survive. The source does not list numeric logit values for this vocabulary, so the numbers below are illustrative. They are chosen only to show the mechanics.

Worked example

Selecting and Masking the Top Three Logits

Given illustrative logits for nine tokens, with k set to 3, which tokens survive, and what is the masked logit vector?

  1. 1
    Stage 1: find the top three

    The three largest illustrative logits are every at 4.2, inches at 3.1, and you at 2.6.

  2. 2
    Identify the threshold

    The smallest logit inside the top-k group is 2.6, which belongs to you. This value is the threshold.

  3. 3
    Stage 2: mask the rest

    Any logit below the threshold of 2.6 is replaced with negative infinity. The logits forward at 2.0, closer at 1.5, effort at 0.3, toward at 0.9, moves at 0.1, and pizza at -1.0 all fall below 2.6, so they become negative infinity. Logits at or above the threshold are kept unchanged.

  4. 4
    Stage 3: apply softmax

    Softmax is computed only over the three unmasked logits 4.2, 3.1, and 2.6. The masked positions contribute nothing to the total.

Result

Three candidates survive: every, inches, and you. Their approximate probabilities are 0.65, 0.22, and 0.13, which sum to 1.00. All six masked tokens have probability exactly 0.

forward2.0forward-infcloser1.5closer-infeffort0.3effort-infinches3.1inches3.1toward0.9toward-infevery4.2every4.2moves0.1moves-infpizza-1.0pizza-infyou2.6you2.6
How does each token's logit change after masking, and why does softmax turn those negative infinity entries into exactly zero probability?

Why Negative Infinity Produces Zero

Negative infinity is a deliberate choice. Softmax converts each logit into a probability by exponentiating it and dividing by the total. A masked position therefore contributes nothing once its value is negative infinity, because its exponential is zero. The remaining probabilities still sum to 1, since the normalization runs only over the unmasked positions.

Formula, step by step
  1. 1
    Here $z_i$ is the logit at position $i$ after masking, and $p_i$ is the resulting probability.
  2. 2
    The set $S$ contains only the unmasked positions, which are the k surviving candidates.
  3. 3
    When $z_j$ is set to $-\infty$, the term $e^{z_j}$ equals $0$, so position $j$ adds nothing to the sum.
  4. 4
    A masked position is therefore excluded from the sum and ends with probability $0$, while the surviving probabilities still add to $1$.

Renormalizing Over the Survivors

After the other tokens are zeroed out, the k remaining probabilities must be rescaled so they add up to 1. Softmax handles this automatically. The exponentials of the three survivors are approximately 66.69 for every, 22.20 for inches, and 13.46 for you. Their total is about 102.35. Dividing each by that total gives the probabilities 0.65, 0.22, and 0.13. The rescaling depends only on the survivors, because the masked positions contributed zero to the total.

everye^4 .2 ≈ 66.69every0.65inchese^3 .1 ≈ 22.20inches0.22youe^2 .6 ≈ 13.46you0.13
After the other tokens are zeroed out, how do the remaining k probabilities get rescaled so they sum to 1?

Where Top-k Sits Among Other Controls

The source is clear that top-k sampling is not meant to stand alone. Top-k sets the boundary of the candidate set. Temperature scaling adjusts how evenly the probabilities are spread within that boundary. Multinomial sampling then makes the final draw. A higher temperature spreads the next-token probabilities more evenly, so the model is less likely to keep choosing the single most probable token, which opens the door to less obvious but potentially more creative continuations.

The same flexibility has a cost. Because low-probability tokens still receive some chance of being selected, the output can drift into text that is grammatically broken or plainly nonsensical. The source illustrates this with the phrase every effort moves you pizza. The problem is not that the sampler is random. The problem is that the random choice is allowed to reach tokens that should never have been candidates at that position. Top-k masking is the boundary that keeps those tokens out.

The source says the next step is to modify the text generation function so that temperature scaling and the multinomial function operate on the non-zero probabilities. That modification is beyond the scope of this article. The point to carry forward is the ordering: the top-k masking happens before the probabilities are finalized.

Common Misreadings of Top-k

  • Common mistake

    Thinking top-k always returns the highest-scoring token

    What it looks like

    With k set to 3, a learner assumes every is always the output because it has the largest logit.

    Why it fails

    Top-k restricts the candidates to the k most likely tokens. The final token is drawn from those candidates using their probabilities.

    Do this instead

    Treat top-k as defining a pool of allowed candidates, and remember that sampling still happens inside that pool.

  • Common mistake

    Assuming masked tokens get a small but nonzero probability

    What it looks like

    A learner expects pizza, which was masked, to keep a tiny chance of being drawn.

    Why it fails

    Masked logits are set to negative infinity, and softmax gives them exactly zero probability.

    Do this instead

    A masked position is excluded entirely from the sum and cannot be sampled.

  • Common mistake

    Believing the probabilities are normalized before masking

    What it looks like

    A learner computes softmax over all nine logits, then removes six tokens afterward.

    Why it fails

    The source's ordering is to mask first and then apply softmax, so the probabilities are computed only over the survivors.

    Do this instead

    Mask the non-top-k logits before softmax so the surviving probabilities sum to 1 on their own.

  • Common mistake

    Confusing top-k with temperature scaling, when the two control different things

Tracing a Different Threshold

MEDIUM

Using the same illustrative logits as before (every 4.2, inches 3.1, you 2.6, toward 0.9, forward 2.0, closer 1.5, effort 0.3, moves 0.1, pizza -1.0), suppose k is set to 2. Which two tokens survive, what is the threshold, and which tokens become negative infinity? Then state which two tokens are the only ones that can be sampled.

Hints
  • Find the two largest logits first: every and inches.
  • The threshold is the smaller of the two surviving logits, which is 3.1.
  • Any logit below 3.1 is masked, including you at 2.6. Only every and inches can be drawn.

Putting the Stages Together

  1. 1
    Top-k sampling restricts the candidate tokens to the k most likely ones. It does not force the single highest-scoring token to be chosen.
  2. 2
    The procedure selects the k largest logits, masks every other logit with negative infinity, and then applies softmax over the surviving positions.
  3. 3
    Because $e^{-\infty} = 0$, masked tokens contribute nothing to the softmax sum and end with probability exactly 0.
  4. 4
    The k survivors are rescaled by softmax so their probabilities sum to 1, and the next token is drawn from them.
  5. 5
    Top-k sets the candidate boundary, temperature scaling adjusts how evenly probability is spread inside it, and multinomial sampling makes the final draw.

Key Takeaways

  • Top-k sampling restricts the candidate tokens to the k most likely ones, rather than always selecting the single highest-scoring token.
  • The three stages are selecting the top-k logits, masking the rest with negative infinity, and applying softmax to the surviving positions.
  • Negative infinity makes a masked position's exponential zero, so its probability is exactly 0 after softmax.
  • Softmax renormalizes the k survivors so their probabilities sum to 1, and the next token is drawn from them.
  • Top-k works alongside temperature scaling and multinomial sampling, and its boundary helps prevent nonsensical tokens from being drawn.

Related concepts

More concepts starting with T