16/29
Part 4 of 5 · Precision and top-kLearn and do

Top-k code has the same shape

The top-k code from the decoding lesson computes a threshold, then masks everything below it:

kth = torch.topk(logits, k, dim=-1).values[..., -1:]
logits.masked_fill(logits < kth, float("-inf"))

The threshold, kth, is the k-th largest score. That's only correct if the threshold and the values it's compared against are the same tensor at the same precision.

Let a compiler run one side in fp32 and the other in bf16, and the k-th token can fall below its own threshold. At k = 1, that's the top token.

In the editor, write merged(p1, p2) and risky_share(steps), to count the near-ties that set up this bug. to_bf16 is written for you, and each row of STEPS holds the two highest probabilities at one decoding step.