Each row's 2nd largest value is its threshold. What shapes are values[..., -1:] and values[..., -1]?
Pick one to see what it prints.
values[..., -1:] is (B, 1), a column. Broadcasting stretches it across each row, so each row compares with its own threshold.
values[..., -1] is (B,), a flat list. Broadcasting lines it up with the last axis, the vocabulary, instead of the rows:
When B is 1, it happens to work.
For most other batch sizes, it errors.
When B equals V, it runs, and silently compares each row against other rows' thresholds.
Try all three below. drop is True, shown as yes, where a token goes.
Each row against its own thresholdInteractive
rows (3, 5)
row 0row 1row 2
<
kth (3, 1) stretched to (3, 5)
=
result (3, 5)
row 0row 1row 2
row 1: 2 < 4 is True. The 4 is row 1's 2nd largest.
real numbers copies NumPy acts as if it madeTap a cell to see where its numbers come from.
In the editor, write keep_top_k(logits, k): (B, V) in, the same logits out, with everything below each row's k-th largest set to -inf. A k larger than the vocabulary keeps every token, and torch.topk raises on a k bigger than the axis, so handle that case too.
Pick an answer above to see the rest
Instructions
1
Write keep_top_k(logits, k): (B, V) in, the same logits out, with everything below each row's k-th largest set to -inf. A k larger than the vocabulary keeps every token.