05Decoding: temperature, top-k, top-p, and a repetition penalty (PyTorch)

mediumtorch
35:00

05 Decoding: temperature, top-k, top-p, and a repetition penalty (PyTorch)

Four levels in solution.py. Read one level at a time and run only its tests until they pass: pytest problems/05_sampling -k level1. Earlier levels must keep passing. logits is (B, V).

Level 1. filter_logits(logits, temperature=1.0) divides by the temperature. sample(logits, temperature=1.0, top_k=None, top_p=None, generator=None) returns one token id per row, shape (B,), drawn from the softmax of the filtered logits with generator (for example torch.multinomial(probs, 1, generator=generator)). sample passes its temperature, top_k and top_p on to filter_logits. temperature == 0 means greedy: the argmax.

Level 2. top_k: after the temperature, set to -inf everything outside the top_k largest.

Level 3. top_p: after top-k, set to -inf everything outside the nucleus, the smallest set of most likely tokens whose probabilities add up to at least top_p. Those probabilities are the softmax of the logits as they stand after the temperature and top-k. Always keep at least one token, and leave every kept logit unchanged.

Level 4. penalize(logits, prev_ids, penalty). prev_ids is (B, T): the token ids each row has already produced. Lower every one of those tokens' logits in its own row, once per token however often it appears: divide a positive logit by penalty and multiply a negative one by it. Return a new tensor and leave logits alone. No Python loop over tokens.

Things to get right: the token that crosses the top_p threshold is kept (the classic off-by-one), sorting for top-p and scattering back to the original order, what temperature does to entropy, and the sign of a repetition penalty. Follow-ups: beam search versus sampling, why greedy decoding loops, and speculative decoding.

solution.py
Run the tests to see which pass.