Top-k keeps the k highest scores
Temperature reshapes every token's chance, the bad ones included. Top-k removes the bad ones.
def keep_top_k(logits: torch.Tensor, k: int) -> torch.Tensor:
"""logits: (B, V). Keeps each row's k largest and sets the rest to -inf."""
kth = torch.topk(logits, k, dim=-1).values[..., -1:]
return logits.masked_fill(logits < kth, float("-inf"))
print(torch.topk(row, 3, dim=-1).values)
print(keep_top_k(row, 3))
print(keep_top_k(row, 3).softmax(dim=-1).round(decimals=3))
tensor([[3., 2., 1.]])
tensor([[3., 2., 1., -inf, -inf, -inf]])
tensor([[0.6650, 0.2450, 0.0900, 0.0000, 0.0000, 0.0000]])
With k = 3, mat, floor and sofa stay. The other three become minus infinity.
- Tokens kept
- 3 of 6
- Top token
- 0.67
- Entropy
- 1.20 bits
torch.topk returns the k largest values, largest first. So the last of them is the k-th largest, and that's the threshold: everything strictly below it goes.
Why cut at all? Even a good model gives every token some probability, and over a large vocabulary that adds up. Holtzman et al. call it the unreliable tail: tens of thousands of unlikely tokens that, added together, get more weight than they should. Sample from the full distribution and sooner or later you draw one.
Top-k is the bluntest fix: keep the k largest logits and drop the rest. Fan et al. (2018) sampled their stories from the 10 most likely candidates.
In the editor are keep_top_k from above and row, the six words' scores. Set after: the softmax of keep_top_k(row, 3). Set renorm: the first three probabilities of the full softmax, divided by their sum. Set same: whether renorm matches the first three entries of after. Compare floats with torch.allclose, because == can miss in the last digit.