1/29
Learn

Decoding with temperature, top-k and top-p

A model's last layer gives a score to every token in its vocabulary, and something has to turn those scores into the next word. That something is the sampler. A fundamentals screen can ask how you'd make a model's output more or less creative, and the answer is the sampler's settings. A coding round can ask you to write it:

logits is a (B, V) tensor: one row per sequence, and one score for each of the V tokens in the vocabulary. Write a sampler in four levels.

  1. filter_logits(logits, temperature=1.0) divides by the temperature, and sample(logits, temperature=1.0, top_k=None, top_p=None, generator=None) returns one token id per row, shape (B,), drawn from the filtered distribution. temperature == 0 means greedy: take the highest score.
  2. top_k: set to -inf every score outside the top_k largest.
  3. top_p: then set to -inf every score outside the nucleus, the smallest set of most likely tokens whose probabilities add up to at least top_p. Always keep at least one token.
  4. penalize(logits, prev_ids, penalty): lower the score of every token already in that row's prev_ids, once each, whatever its sign.

Then tell me why greedy decoding repeats itself, and when you'd pick beam search.

Here are both functions on one row. The model has read The cat sat on the, and six words are left, with the scores [3.0, 2.0, 1.0, 0.5, 0.0, -1.0] for mat, floor, sofa, bed, roof and moon. The probabilities are the softmax of what filter_logits returns:

CallWords left, with their probabilities
filter_logits(row)all six: mat 0.605, floor 0.222, sofa 0.082, bed 0.050, roof 0.030, moon 0.011
filter_logits(row, top_k=3)mat 0.665, floor 0.245, sofa 0.090
filter_logits(row, top_k=3, top_p=0.9)mat 0.731, floor 0.269
filter_logits(row, temperature=2.0, top_p=0.9)mat 0.403, floor 0.244, sofa 0.148, bed 0.115, roof 0.090
sample(row, temperature=0)tensor([0]): mat, every time

Each function is a few lines. The bugs that cost the round raise no error: a knob that turns backwards, a filter that keeps one token too many or too few, a draw from the wrong probabilities. The lesson takes one piece at a time on these six words: greedy, temperature, top-k, top-p, then the whole sampler and the follow-ups. At the end you write all four levels yourself, as the practice problem, in about 35 minutes.