With all three filters written, the order you apply them in matters.
One draw, step by stepInteractive
→
→
→
→
→
→
logits (B, V) = [3, 2, 1, 0.5, 0, -1]. The six candidates, mat to moon, as they leave the model.
The practice problem fixes this order, and it's the standard one. Hugging Face's generate runs temperature, then top-k, then top-p, then min-p, with any repetition penalty applied before all of them.
The sampler comes as two functions. filter_logits(logits, temperature, top_k, top_p) returns the (B, V) logits after all three steps, in that order. sample(logits, temperature, top_k, top_p, generator) softmaxes what filter_logits returns and draws one token id per row, or returns the argmax at temperature == 0. You write both in a few steps. Here is sample on the six words:
g = torch.Generator().manual_seed(0)print(sample(row, temperature=0))print(sample(row.repeat(8, 1), top_k=3, generator=g))
Predict
sample(row, temperature=0), then 8 draws with top_k=3. Which ids can the 8 draws hold?
Pick one to see what it prints.
row again, with mat as id 0. A few details in sample:
torch.multinomial draws one id per row and returns (B, 1). squeeze(-1) makes it the (B,) the practice problem asks for.
Greedy skips the filters, and nothing is lost: both filters always keep the top token.
torch.multinomial accepts weights that don't sum to 1. But every row must be non-negative, finite and have a nonzero total, so a row that came out all NaN makes it raise.
In the editor, sample has this bug. Run it: about 9% of the draws are bed, roof or moon, which top-k 3 removed. Find the line that throws the filtering away, and fix sample.
Pick an answer above to see the rest
Instructions
1
Run the code: about 9% of the draws are bed, roof or moon, which top-k 3 removed.
2
Find the line that throws the filtering away, and fix sample.