A language model does not write text. For each position it returns one score per token in its vocabulary, and the scores for the next token are all it offers. This lesson is about the loop that turns those scores into a sequence, and about the settings on that loop. This lesson pairs with Lecture 20 of CMU's 11-785 (Fall 2026), linked under Watch & read. You build the filters, the draw and the generation loop in PyTorch and grade them against plain-Python references.
The loop is: scores, a distribution, one chosen token, append it, ask again. Nothing in it changes the weights, yet every choice in it changes the text. The model here has the interface of the earlier lessons of this course: int64 tokens of shape (N, T) in, logits of shape (N, T, vocab) out. Only the logits at the last position matter for the next token.
The simplest choice is greedy: always take the top token. It is deterministic, and it tends to loop, because a phrase that is the most likely continuation of itself repeats forever. Drawing from the full softmax follows the model instead, but the long tail of unlikely tokens adds up. Take 1,000 tokens whose probability falls like 1/rank:
import numpy as np
weights = 1 / np.arange(1, 1001) # a made-up curve: probability falls like 1/rank
probs = weights / weights.sum()
print(round(probs[:50].sum(), 3), round(probs[50:].sum(), 3))The top 50 hold 0.601 of the probability, so 0.399 lies outside them: about two draws in five land in the tail, and a 100-token text contains about 40 such draws. The filters below exist to cut that tail.
Temperature comes first. Divide the logits by T > 0 before the softmax. Below 1 the gaps between logits grow and the distribution sharpens. At T = 1 nothing changes. Above 1 the gaps shrink and the distribution flattens towards uniform. As T goes to 0 all the probability moves to the top token, which is greedy choice. Dividing by a positive number never changes the order of the logits, so temperature changes how confident the draw is and never which token leads. Here are eight logits at five temperatures, with the entropy in nats (the most it can be for 8 tokens is ln 8 = 2.079):
import numpy as np
def softmax(z):
e = np.exp(z - z.max())
return e / e.sum()
logits = np.array([3.0, 2.0, 1.5, 1.0, 0.5, 0.0, -0.5, -1.0])
for t in [0.25, 0.5, 1.0, 2.0, 4.0]:
p = softmax(logits / t)
print(t, round(p[0], 3), round(-(p * np.log(p)).sum(), 3))Temperature rescales the whole distribution. Top-k and nucleus filtering cut it. Top-k keeps the k best tokens and sets the others to -inf, so they get probability 0 after the softmax. Tokens tied with the k-th best are all kept. A fixed k is too wide when the model is sure, because it admits tokens the model gave almost nothing, and too narrow when the model is unsure.
Nucleus filtering, or top-p, lets the set follow the model. Order the tokens by probability, highest first, and keep the smallest set whose total reaches p. In code that is one rule: keep a token when the total probability of the tokens before it is below p. The token that carries the total across p is therefore kept, and the first token always has 0 before it, so at least one token survives. Below, a confident and an unsure distribution at p = 0.9, and then the order question:
import numpy as np
def softmax(z):
e = np.exp(z - z.max())
return e / e.sum()
def nucleus_size(logits, p):
probs = np.sort(softmax(logits))[::-1]
before = np.cumsum(probs) - probs
return int((before < p).sum())
sure = np.array([6.0, 2.0, 1.0, 0.5, 0.0, -1.0, -2.0, -3.0])
unsure = np.array([1.0, 0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3])
print(nucleus_size(sure, 0.9), nucleus_size(unsure, 0.9))
logits = np.array([3.0, 2.0, 1.5, 1.0, 0.5, 0.0, -0.5, -1.0])
print(nucleus_size(logits / 0.5, 0.85), nucleus_size(logits, 0.85))The first line shows 1 token in the nucleus for the confident model and 7 of 8 for the unsure one. The second shows why order matters. At T = 0.5 and p = 0.85, two tokens reach p when the temperature is applied first, and four when top-p looks at the unscaled scores. The order is a convention. This build uses temperature, then top-k, then top-p, then the draw, and libraries do not all agree, so check the documentation of the one you use.
The context window comes next. A model accepts only its last context_size tokens, so the loop crops the input it feeds, never the output it returns. The loop stops after a maximum number of new tokens, or as soon as the end-of-sequence token is drawn, which stays in the result.
Beam search, covered in a decoding lesson elsewhere on this site, looks for the most probable sequence. That suits translation or recognition, where the output should match something. For open-ended text the most probable sequence is often bland or repetitive, which is why sampling is the usual choice there.
Three mistakes recur. The first is dropping the token that crosses p, by testing the running total including a token against p: a confident model is then left with one token too few, or none. The second is feeding the model the whole text, which fails once it outgrows the window. The third is treating temperature 0 as an ordinary temperature: dividing by 0 is undefined, so sample_next takes the argmax directly and draws nothing, and next_token_probs raises ValueError. Also expect top-k to keep more than k tokens when scores tie.
The tests compare each filter with a plain-Python version, the probabilities with torch.softmax, the draws with the computed distribution over 20,000 samples, and the loop with a table model whose output you can predict by hand. A recording model proves that every call receives only recent tokens. None of this says the text is good: temperature and p are matters of taste. The build handles one prompt at a time, has no repetition penalty, and runs the model on the whole window for every token. Real systems cache the attention keys and values to avoid that.