ties = torch.tensor([[2.0, 1.0, 1.0, 0.0]])print(keep_top_k(ties, 2))
Predict
ties is [2.0, 1.0, 1.0, 0.0] and k = 2, so the threshold is 1. How many tokens stay?
Pick one to see what it prints.
Say the four tokens are mat, floor, sofa and bed, with floor and sofa tied:
A tie at the thresholdInteractive
Next token after “The cat sat on the ___”
0
0.5
1
0.58
0.21
0.21
matfloorsofabed
Hover a bar
KeptFiltered out
Tokens kept
3 of 4
Top token
0.58
Entropy
1.41 bits
That's defensible: nothing tells two equal logits apart. Ties sound rare, and in float32 they are. bf16, the 16-bit format many models run in, keeps far fewer digits:
400 rows of random logits over GPT-2's 50,257 tokens, cut to the top 50. In float32, every row keeps exactly 50. Round the rows to bf16. How many keep more than 50?
Pick one to see what it prints.
If the interviewer wants exactly k every time, keep by index. torch.topk returns the k largest values and their indices, which are token ids:
t.scatter(-1, index, src) returns a copy of t with each value of src written at the position its index names. Here 7 goes to position 3 and 8 to position 1:
idx is [0, 1] and vals is [2.0, 1.0], so 2.0 lands at id 0 and 1.0 at id 1. Exactly 2 stay, and sofa, tied with floor, is left out.
scatter(-1, idx, vals) writes each kept value back at its own id, in a row that starts as all minus infinity. Which tied token survives is now arbitrary. Either convention is fine: say which one you chose.
In the editor, ties holds two rows with tied scores. Finish keep_exactly_k(logits, k): set vals, idx from torch.topk. Then return a row of -inf with each kept value written back at its own id, with scatter.
Pick an answer above to see the rest
Instructions
1
Set vals, idx: each row's k largest values and their ids, from torch.topk.
2
Return a row of minus infinity with each kept value written back at its own id.