Skip to content

The Python sampler in Sampling and logit processors in AI Engineering specifies top-kk by sorting every logit: process_logits orders all VV ids by (logit descending, id ascending) and keeps the first kk. For SmolLM2, V=49152V = 49152. Sorting 49152 floats to keep 40 takes about Vlog⁡2V≈770,000V \log_2 V \approx 770{,}000 comparisons where roughly VV suffice.

Concepts from other sections (8)

This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.

  • Binary heap: a complete binary tree in an array in which no child comes out before its parent. Read more: 15.6 A binary heap with lazy deletion
  • logits: unnormalized log-scores that softmax turns into probabilities; here the table stores ln⁡P(j∣i)\ln P(j \mid i). Read more: 6.1 Byte bigram: counts, logits, safetensors v0 in AI Engineering
  • Complete binary tree: a tree with every level full except possibly the last, which is filled left to right; it is what makes the array layout work. Read more: 18.4 Binary heap
  • Heap property: in a min-heap, every parent’s priority is less than or equal to its children’s. Read more: 18.4 Binary heap
  • tie rule: the fixed backtrace preference (diagonal, deletion, insertion) that makes the S, D, I split deterministic. Read more: 15.5 Multimodal eval metrics: WER, CER, VQA, captions, zero-shot in AI Engineering
  • Heapify (Floyd’s method): building a heap in O(n) by sifting down every internal node from the bottom up. Read more: 18.4 Binary heap
  • Top-p (nucleus): the smallest set of most likely tokens whose mass reaches pp, including the crossing token. Read more: 21.1 Sampling and logit processors in AI Engineering
  • Constrained decoding: masking, at every step, every token that would take the output outside an allowed language. Read more: 23.10 Tool calls and constrained decoding in AI Engineering

This section implements the same ordering in C with about VV comparisons, using a binary heap of size kk that lives entirely in the caller’s output buffers. It is an optional, standalone unit: no engine calls into this C code. Fixture files generated by the Python reference check that the two agree, and the Rust sampler in Candle model runner is checked against the same fixtures independently.

You should know the binary heap from A binary heap with lazy deletion, the chapter’s first heap section, where sift up, sift down, and the array layout are developed. The C allocation and error support comes from C runtime support and arena allocator with marks, and the growable array shows the same block discipline, although the heap itself allocates nothing. The contract is tinyllm/topk.h under the rules in c/ABI.md; the solution is topk.c.

Learning objectives

  • Define a total order on (value, index) entries that makes top-kk unique, and explain why NaN must be rejected while −∞-\infty must not.
  • Keep the best kk entries of a stream in a size-kk min-heap whose root is the threshold.
  • Show that scanning in increasing index resolves ties at the cut to the lower index with no extra code.
  • Turn the heap into best-first output with an in-place heap sort, without allocating.
  • Compare the heap’s cost with a full sort and with quickselect.

The notation for this section:

SymbolMeaningType / shape
x∈Rnx \in \mathbb{R}^nthe input values (logits), xix_i at index iifloat[n]
nnnumber of values, VV for a logit rowint64_t
kknumber of values to keep, 0≤k≤n0 \le k \le nint64_t
(v,i)(v, i)an entry: a value and its index
a≺ba \prec bentry aa ranks below (“is worse than”) entry bb
idx,val\mathit{idx}, \mathit{val}the outputs: the kept indices and values, best firstint32_t[k], float[k]
hhthe heap’s current size, h≤kh \le k

Top-kk is defined by an order, and values alone do not give one: two logits can be equal, and then “the kk largest” is ambiguous. The sampling spec (spec/sampling.md step 6) breaks ties by index, so define

(va,ia)≺(vb,ib)  ⟺  va<vb  or  (va=vb and ia>ib).(v_a, i_a) \prec (v_b, i_b) \iff v_a < v_b \ \text{ or } \ (v_a = v_b \text{ and } i_a > i_b).

Read it as ”aa is worse than bb”. Indices are distinct, so for any two different entries exactly one of a≺ba \prec b and b≺ab \prec a holds: the order is total. The top-kk set is then unique: the kk entries that are worse than no more than k−1k - 1 others. Listing it best first gives values in descending order and, among equal values, ascending indices.

NaN breaks this. IEEE 754 makes every comparison with NaN false, so a NaN entry would be neither worse nor better than anything, and the result would depend on where in the array it happened to sit. The contract therefore rejects any NaN with TL_EINVAL.

−∞-\infty is different: −∞<v-\infty < v for every other value, and −∞=−∞-\infty = -\infty, so it fits the order and ranks last. A logit masked by constrained decoding is −∞-\infty, so rejecting it would break every masked request.

The heap keeps the worst kept entry at the root

Section titled “The heap keeps the worst kept entry at the root”

A binary heap is a complete binary tree stored in an array: the children of position pp are 2p+12p + 1 and 2p+22p + 2, and its parent is ⌊(p−1)/2⌋\lfloor (p - 1)/2 \rfloor. Here the heap property is: no parent is better than its children, so the root is the worst entry in the heap. That is a min-heap under ≺\prec.

Why the worst at the root? The question asked of every new entry is “does it beat the weakest member of the current top kk?” The algorithm scans xx once, keeping the best h≤kh \le k entries seen so far in the heap:

  1. While h<kh < k, append (xi,i)(x_i, i) at position hh and sift it up: swap it with its parent while it is worse than the parent.
  2. Once h=kh = k, compare (xi,i)(x_i, i) with the root, the worst of the kk kept entries. If the root is worse, the new entry replaces it and is sifted down: swapped with its worse child while that child is worse than it. Otherwise the new entry is not among the kk best seen so far, and it is dropped.

The correctness argument is an invariant: after processing x0,…,xix_0, \dots, x_{i}, the heap holds exactly the top-min⁡(k,i+1)\min(k, i+1) entries of that prefix. It holds after step 1 trivially. In step 2, if the new entry ranks below the root, it ranks below all kk kept entries and cannot be in the top kk; otherwise the root is now ranked below kk entries (the other k−1k - 1 and the new one) and must leave.

Ties need no special code. The scan goes in increasing index, so a later entry with the same value as the root has a larger index: it is worse, and it stays out. The lower index wins the last place, as the spec requires.

After the scan, idx and val hold the top kk in heap order. A heap sort turns that into best-first order without extra memory: swap the root (the worst) with the last position, shrink the heap by one, sift the new root down, and repeat. The worst entry ends at position k−1k - 1, the second worst at k−2k - 2, and position 0 ends with the best.

Each of the nn values costs one comparison with the root. An entry that gets in costs O(log⁡k)O(\log k) swaps, and the final sort costs O(klog⁡k)O(k \log k). In the worst case (an increasing array, where every value gets in) the total is O(nlog⁡k)O(n \log k). For a logit row the order is close to random, and then the ii-th value gets in with probability about k/ik / i, so the expected number of insertions is about kln⁡(n/k)k \ln(n/k). For n=49152n = 49152 and k=40k = 40, that is about 280 insertions and 49152 root comparisons, against nlog⁡2n≈770,000n \log_2 n \approx 770{,}000 comparisons for a full sort.

Quickselect (Hoare) finds the kk-th value in expected O(n)O(n), but it reorders the input, which the contract forbids (x is const), so it would need a copy of all nn values.

The contract allows 0 <= k <= n and requires idx and val untouched when it returns TL_EINVAL. So the function checks the ranges and pointers, then scans all of xx for NaN, and only then writes. A NaN at the end of the row is found after the whole scan; that costs one extra pass over xx, which is cheap next to the heap work and keeps the error path simple.

Take x=[1,3,2,3,−1]x = [1, 3, 2, 3, -1] (the logits of the sampling spec’s worked example) and k=3k = 3. Entries are written (v,i)(v, i), and the heap as an array, root first.

StepEntryActionHeap after
i=0i = 0(1,0)(1, 0)h=0<3h = 0 < 3: append, nothing to sift[(1,0)][(1,0)]
i=1i = 1(3,1)(3, 1)append at 1; parent (1,0)(1,0) is worse, so no swap[(1,0),(3,1)][(1,0), (3,1)]
i=2i = 2(2,2)(2, 2)append at 2; parent (1,0)(1,0) is worse, no swap[(1,0),(3,1),(2,2)][(1,0), (3,1), (2,2)]
i=3i = 3(3,3)(3, 3)full; root (1,0)≺(3,3)(1,0) \prec (3,3): replace root. Sift down: children (3,1)(3,1) and (2,2)(2,2); (2,2)≺(3,3)(2,2) \prec (3,3) and (3,1)(3,1) is not (equal value, smaller index), so swap with (2,2)(2,2)[(2,2),(3,1),(3,3)][(2,2), (3,1), (3,3)]
i=4i = 4(−1,4)(-1, 4)root (2,2)(2,2) is not worse than (−1,4)(-1, 4): dropunchanged

Now the heap sort. Swap root and position 2, giving [(3,3),(3,1)∣(2,2)][(3,3), (3,1) \mid (2,2)]; sift down in a heap of 2: (3,1)(3,1) is not worse than (3,3)(3,3), stop. Swap root and position 1: [(3,1)∣(3,3),(2,2)][(3,1) \mid (3,3), (2,2)].

The result is idx = {1, 3, 2}, val = {3, 3, 2}. The two 3s tie, and the lower index comes first. The spec’s own trace keeps ids 1, 3, 2 in that order.

tinyllm/topk.h
tl_status tl_topk_f32(const float *x, int64_t n, int64_t k, int32_t *idx, float *val);
/* The k largest values of x[0..n) and their indices, best first; equal values by
ascending index (and the lower index wins the last place). -inf is a value.
TL_EINVAL, idx and val untouched, for k < 0 or k > n, a NULL pointer that would
be used, or any NaN in x. k == 0 writes nothing. Allocates nothing. */

The C implementation is checked on its own. Python produces the reference fixture rows for parity; it does not load the C implementation.

Try to predict each step from the heap invariant before reading it.

  1. The answer must be unique, so the order must be total. Values alone are not (ties), so the index breaks ties: the order ≺\prec. Every comparison in the solution goes through one function, worse, so the tie rule cannot be applied in one place and forgotten in another.
  2. NaN cannot be ordered, so it must be rejected; −∞-\infty can, so it must not be. The test is isnan, not isfinite.
  3. Rejection must leave the outputs untouched, so every check, including the full NaN scan, runs before the first write.
  4. Deciding whether xix_i belongs to the current top kk only needs the worst kept entry. That is the minimum under ≺\prec, so the structure is a min-heap of size kk: the root is the threshold, read in O(1)O(1), replaced and repaired in O(log⁡k)O(\log k).
  5. The heap needs kk slots, and the caller already provides kk slots (idx, val). Building the heap there means no allocation, and parallel arrays mean every swap moves a value and its index together.
  6. The scan goes in increasing index, so a later entry equal in value to the root is worse (larger index) and the strict test worse(root, new) keeps it out: ties at the cut resolve to the lower index with no extra code. In the worked example, (3,3)(3,3) enters because the root (1,0)(1,0) is worse, and (−1,4)(-1,4) is dropped by one comparison.
  7. The output must be best first, and the heap is in heap order. Repeatedly moving the root (the worst) to the end of a shrinking heap is a heap sort that leaves the worst last and the best first, in the same buffers.

sift_down picks the worse child because the parent must be no better than either child: promoting the worse child keeps that true for the other child too.

/* 1 when entry (va, ia) ranks below entry (vb, ib): the total order. */
static int worse(float va, int32_t ia, float vb, int32_t ib) {
return va < vb || (va == vb && ia > ib); /* equal value: the larger index is worse */
}
/* Restores "no parent is better than its children" below position i. */
static void sift_down(int32_t *idx, float *val, int64_t size, int64_t i) {
for (;;) {
int64_t l = 2 * i + 1, r = l + 1, w = i; /* w: the worst of parent and children */
if (l < size && worse(val[l], idx[l], val[w], idx[w])) w = l;
if (r < size && worse(val[r], idx[r], val[w], idx[w])) w = r;
if (w == i) return; /* parent already the worst: done */
/* swap value and index together: the arrays are one array of pairs */
float tv = val[i];
int32_t ti = idx[i];
val[i] = val[w], idx[i] = idx[w];
val[w] = tv, idx[w] = ti;
i = w;
}
}
/* Moves the entry at position i up while it is worse than its parent. */
static void sift_up(int32_t *idx, float *val, int64_t i) {
while (i > 0) {
int64_t p = (i - 1) / 2;
if (!worse(val[i], idx[i], val[p], idx[p])) return;
/* ... swap i and p, as above ... */
i = p;
}
}

Validation comes first and covers everything a write could depend on. The n > INT32_MAX check exists because indices are stored as int32_t.

tl_status tl_topk_f32(const float *x, int64_t n, int64_t k, int32_t *idx, float *val) {
/* 1. Validate everything before writing anything. */
if (n < 0 || k < 0 || k > n) { /* ... */ return TL_EINVAL; }
if (n > INT32_MAX) { /* ... */ return TL_EINVAL; } /* an index must fit idx[] */
if (n > 0 && x == NULL) { /* ... */ return TL_EINVAL; } /* NULL only when unused */
if (k > 0 && (idx == NULL || val == NULL)) { /* ... */ return TL_EINVAL; }
for (int64_t i = 0; i < n; i++) {
if (isnan(x[i])) { /* ... */ return TL_EINVAL; } /* isnan, not isfinite: -inf is a value */
}
if (k == 0) return TL_OK; /* "off" is valid and writes nothing */

The fill phase uses sift_up because entries arrive one at a time at the end; the replace phase uses sift_down because the change is at the root.

/* 2. Fill with the first k entries, then let each later entry replace the
* root when it ranks above it. A later entry equal to the root has a
* larger index, so it is worse and stays out: ties go to the lower index. */
int64_t size = 0;
for (int64_t i = 0; i < n; i++) {
if (size < k) {
val[size] = x[i], idx[size] = (int32_t)i;
sift_up(idx, val, size);
size++;
} else if (worse(val[0], idx[0], x[i], (int32_t)i)) { /* strict: equal is not enough */
val[0] = x[i], idx[0] = (int32_t)i;
sift_down(idx, val, k, 0);
}
}
/* 3. Heap sort in place: move the worst to the end, shrink, repeat.
* What is left is best first. */
for (int64_t end = k - 1; end > 0; end--) {
/* ... swap positions 0 and end ... */
sift_down(idx, val, end, 0); /* the heap is now positions [0, end) */
}
return TL_OK;
}

The full solution is topk.c.

The cost is one NaN pass plus one scan: O(n)O(n) comparisons with the root, O(log⁡k)O(\log k) per insertion, O(nlog⁡k)O(n \log k) in the worst case and about n+kln⁡(n/k)log⁡kn + k \ln(n/k) \log k for random rows; the sort adds O(klog⁡k)O(k \log k). Memory beyond the output buffers is zero.

Each alternative gives something up. Sorting all nn is O(nlog⁡n)O(n \log n), and it needs a copy of xx (the input is const) plus an allocation. Quickselect is expected O(n)O(n), but it reorders its input, so it would need an nn-sized copy; it still needs a sort of the kk survivors, and its tie handling depends on pivot choices unless the comparator is the same total order. A max-heap of all nn (heapify, then pop kk) is O(n+klog⁡n)O(n + k \log n) but needs nn slots, while the size-kk min-heap fits in the caller’s kk slots.

Two tradeoffs are accepted. The NaN check costs a second pass over xx; in exchange no output is ever written on an error path. Parallel idx and val arrays mean two writes per swap, which is what the contract’s output layout asks for anyway.

A correct solution handles these cases:

CaseKind of checkChecksWhy it matters downstream
The hand exampleunit, smokethe worked example exactlythe definition of top-kk is the one the sampling spec uses
A tie at the cut goes to the lower indexboundary[5,1,1,1,1,0][5, 1, 1, 1, 1, 0], k=2k = 2 keeps ids 0 and 1the ordering is deterministic
Equal values are listed by ascending indexboundaryall-equal input comes out in index ordertop-p walks the kept ids in this order
k=0k = 0 and k=nk = nboundaryk=0k = 0 writes nothing; k=nk = n is a full sort; n=0n = 0 is finetop_k = 0 means off
−∞-\infty is an ordinary valueboundary−∞-\infty ranks last, ties by indexmasked logits from constrained decoding
NaN and bad kk are rejected without writingboundaryNaN, k>nk > n, k<0k < 0, NULL pointers give TL_EINVAL and leave the outputs as they wereerrors instead of garbage
Agrees with a full sortproperty, differential300 random rows with many ties against qsort by ≺\prec, every kkheap shapes only random sizes reach

The pitfalls mostly concern the order and the error path:

PitfallSymptomHow the solution avoids it
replacing the root when the new value is greater or equala tie at the kk-th place keeps the last tied indexthe replace test is worse(val[0], idx[0], x[i], i), strict under ≺\prec
comparing values only inside the heapequal values come out in heap order, not index orderevery comparison, in both sifts, goes through worse
no NaN checkthe result depends on where the NaN sitsan isnan pass rejects the call before the scan
no k > n checkthe heap writes past idx and val (ASan)0 <= k <= n is checked first
forgetting the final sortthe right set in heap order; top-p (step 7 of the spec) walks it in the wrong orderstep 3 heap-sorts the outputs in place
a max-heap (best at the root)the root comparison drops the wrong entriessift_down and sift_up keep the worst entry at the root
treating k=0k = 0 as an errora request with top_k = 0 (off) failsk == 0 returns TL_OK after validation
writing before validatinga rejected call has already changed the outputsall checks run before the first write
rejecting with !isfinite instead of isnanevery masked request failsthe check is isnan; −∞-\infty ranks last

Warning: !isfinite(x) looks like a safer NaN check, but it also rejects −∞-\infty, and every request that uses constrained decoding masks logits to −∞-\infty.

This section is optional and standalone; nothing else in the system depends on it. It looks back to Sampling and logit processors, whose process_logits is the Python reference, and forward to the Candle model runner, whose Rust sampler is implemented independently and checked against the same shared fixture files.

Production top-kk goes further:

  • PyTorch torch.topk on CPU chooses a partial sort (std::partial_sort or nth_element) by k/nk/n and processes many rows in parallel; see aten/src/ATen/native/TopKImpl.h.
  • The vLLM and FlashInfer GPU samplers fuse top-kk and top-pp with sampling, by rejection instead of sorting; see FlashInfer sampling.cuh.
  • llama.cpp’s llama_sampler_top_k does a partial sort over the candidate array, reused by every sampler in the chain; see src/llama-sampling.cpp.
  • Cormen et al., Introduction to Algorithms (4th ed.), chapter 6 (heaps) and section 9.2 (selection in expected linear time).
  • Knuth, TAOCP vol. 3, section 5.3.3 (minimum-comparison selection).
  • Total order: an order in which any two distinct elements compare one way or the other; here, by value and then by index.
  • Min-heap under ≺\prec: a heap whose root is the worst entry, so it serves as the admission threshold.
  • Sift up / sift down: repairs of the heap property after appending at the end or replacing the root.
  • Heap sort: repeatedly moving the root to the end of a shrinking heap to sort in place.
  • Quickselect: expected-linear selection of the kk-th element by partitioning, which reorders its input.
  • Top-kk needs only a heap of size kk: keep the best kk seen so far with the worst of them at the root, and each new value costs one comparison against the root, plus O(log⁡k)O(\log k) swaps only when it gets in.
  • The order is total: a smaller value ranks lower, and among equal values the larger index ranks lower. That one rule settles both who wins a tie at the kk-th place (the lower index) and the output order of equal values (ascending index).
  • NaN is rejected, −∞-\infty is a value: NaN has no place in any order, and a masked logit is −∞-\infty and simply ranks last.
  • No allocation: the heap is built inside idx and val, and a final in-place heap sort leaves them best first.
  • The C implementation and the Python reference agree on the kept set through shared fixture files.
  1. Why is the root the worst kept entry rather than the best?
    AnswerThe question asked of every new entry is "does it beat the weakest member of the current top $k$?". Only the worst kept entry can be evicted, so it is the one that must be at hand in $O(1)$. A max-heap would put the best at the root and give no cheap way to find the entry to drop.
  2. Why does the replace test use worse(root, new) and not “new value greater than or equal to root value”?
    AnswerWith "greater or equal", a later entry tied with the root would replace it, so the last tied index would win the $k$-th place instead of the first. Because the scan runs in increasing index, a later equal value is strictly worse under $\prec$, and the strict test keeps it out.
  3. Why must the NaN scan finish before any write, even though it costs an extra pass?
    AnswerThe contract says a `TL_EINVAL` call leaves `idx` and `val` untouched. A NaN at the last position would be found only after the heap had already been built in the outputs. Scanning first is the only way to keep that promise without a temporary buffer.
  4. Why does the heap sort leave the outputs best first, when it moves the root to the end each time?
    AnswerThe root of a min-heap under $\prec$ is the worst remaining entry. Moving it to position `end` and shrinking fills the array from the back with entries in worst-to-better order, so position $k-1$ holds the worst and position 0 the best: descending value, ascending index among equals.
  5. About how many heap insertions does a random logit row of n=49152n = 49152 cause for k=40k = 40?
    AnswerThe $i$-th value enters with probability about $k/i$, so the expected count is about $k \ln(n/k) = 40 \ln(1228.8) \approx 280$, next to 49152 root comparisons.