15.4 Heap top-k in C
The Python sampler in Sampling and logit processors in AI Engineering specifies top- by sorting every logit: process_logits orders all ids by (logit descending, id ascending) and keeps the first . For SmolLM2, . Sorting 49152 floats to keep 40 takes about comparisons where roughly 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 . 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 , 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 comparisons, using a binary heap of size 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- unique, and explain why NaN must be rejected while must not.
- Keep the best entries of a stream in a size- 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.
A total order on entries
Section titled “A total order on entries”The notation for this section:
| Symbol | Meaning | Type / shape |
|---|---|---|
| the input values (logits), at index | float[n] | |
| number of values, for a logit row | int64_t | |
| number of values to keep, | int64_t | |
| an entry: a value and its index | ||
| entry ranks below (“is worse than”) entry | ||
| the outputs: the kept indices and values, best first | int32_t[k], float[k] | |
| the heap’s current size, |
Top- is defined by an order, and values alone do not give one: two logits can be equal, and then “the largest” is ambiguous. The sampling spec (spec/sampling.md step 6) breaks ties by index, so define
Read it as ” is worse than ”. Indices are distinct, so for any two different entries exactly one of and holds: the order is total. The top- set is then unique: the entries that are worse than no more than others. Listing it best first gives values in descending order and, among equal values, ascending indices.
NaN and negative infinity
Section titled “NaN and negative infinity”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.
is different: for every other value, and , so it fits the order and ranks last. A logit masked by constrained decoding is , 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 are and , and its parent is . 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 .
Why the worst at the root? The question asked of every new entry is “does it beat the weakest member of the current top ?” The algorithm scans once, keeping the best entries seen so far in the heap:
- While , append at position and sift it up: swap it with its parent while it is worse than the parent.
- Once , compare with the root, the worst of the 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 best seen so far, and it is dropped.
The correctness argument is an invariant: after processing , the heap holds exactly the top- 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 kept entries and cannot be in the top ; otherwise the root is now ranked below entries (the other 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.
Sorting the result in place
Section titled “Sorting the result in place”After the scan, idx and val hold the top 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 , the second worst at , and position 0 ends with the best.
What it costs
Section titled “What it costs”Each of the values costs one comparison with the root. An entry that gets in costs swaps, and the final sort costs . In the worst case (an increasing array, where every value gets in) the total is . For a logit row the order is close to random, and then the -th value gets in with probability about , so the expected number of insertions is about . For and , that is about 280 insertions and 49152 root comparisons, against comparisons for a full sort.
Quickselect (Hoare) finds the -th value in expected , but it reorders the input, which the contract forbids (x is const), so it would need a copy of all values.
Validate before the first write
Section titled “Validate before the first write”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 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 , which is cheap next to the heap work and keeps the error path simple.
Working it by hand
Section titled “Working it by hand”Take (the logits of the sampling spec’s worked example) and . Entries are written , and the heap as an array, root first.
| Step | Entry | Action | Heap after |
|---|---|---|---|
| : append, nothing to sift | |||
| append at 1; parent is worse, so no swap | |||
| append at 2; parent is worse, no swap | |||
| full; root : replace root. Sift down: children and ; and is not (equal value, smaller index), so swap with | |||
| root is not worse than : drop | unchanged |
Now the heap sort. Swap root and position 2, giving ; sift down in a heap of 2: is not worse than , stop. Swap root and position 1: .
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.
The interface
Section titled “The interface”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.
Building it step by step
Section titled “Building it step by step”Try to predict each step from the heap invariant before reading it.
- The answer must be unique, so the order must be total. Values alone are not (ties), so the index breaks ties: the order . Every comparison in the solution goes through one function,
worse, so the tie rule cannot be applied in one place and forgotten in another. - NaN cannot be ordered, so it must be rejected; can, so it must not be. The test is
isnan, notisfinite. - Rejection must leave the outputs untouched, so every check, including the full NaN scan, runs before the first write.
- Deciding whether belongs to the current top only needs the worst kept entry. That is the minimum under , so the structure is a min-heap of size : the root is the threshold, read in , replaced and repaired in .
- The heap needs slots, and the caller already provides slots (
idx,val). Building the heap there means no allocation, and parallel arrays mean every swap moves a value and its index together. - 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, enters because the root is worse, and is dropped by one comparison. - 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.
The order and the two repairs
Section titled “The order and the two repairs”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
Section titled “Validation”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 scan and the sort
Section titled “The scan and the sort”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.
Why this design
Section titled “Why this design”The cost is one NaN pass plus one scan: comparisons with the root, per insertion, in the worst case and about for random rows; the sort adds . Memory beyond the output buffers is zero.
Each alternative gives something up. Sorting all is , and it needs a copy of (the input is const) plus an allocation. Quickselect is expected , but it reorders its input, so it would need an -sized copy; it still needs a sort of the survivors, and its tie handling depends on pivot choices unless the comparator is the same total order. A max-heap of all (heapify, then pop ) is but needs slots, while the size- min-heap fits in the caller’s slots.
Two tradeoffs are accepted. The NaN check costs a second pass over ; 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.
Testing it and what can go wrong
Section titled “Testing it and what can go wrong”A correct solution handles these cases:
| Case | Kind of check | Checks | Why it matters downstream |
|---|---|---|---|
| The hand example | unit, smoke | the worked example exactly | the definition of top- is the one the sampling spec uses |
| A tie at the cut goes to the lower index | boundary | , keeps ids 0 and 1 | the ordering is deterministic |
| Equal values are listed by ascending index | boundary | all-equal input comes out in index order | top-p walks the kept ids in this order |
| and | boundary | writes nothing; is a full sort; is fine | top_k = 0 means off |
| is an ordinary value | boundary | ranks last, ties by index | masked logits from constrained decoding |
| NaN and bad are rejected without writing | boundary | NaN, , , NULL pointers give TL_EINVAL and leave the outputs as they were | errors instead of garbage |
| Agrees with a full sort | property, differential | 300 random rows with many ties against qsort by , every | heap shapes only random sizes reach |
The pitfalls mostly concern the order and the error path:
| Pitfall | Symptom | How the solution avoids it |
|---|---|---|
| replacing the root when the new value is greater or equal | a tie at the -th place keeps the last tied index | the replace test is worse(val[0], idx[0], x[i], i), strict under |
| comparing values only inside the heap | equal values come out in heap order, not index order | every comparison, in both sifts, goes through worse |
| no NaN check | the result depends on where the NaN sits | an isnan pass rejects the call before the scan |
no k > n check | the heap writes past idx and val (ASan) | 0 <= k <= n is checked first |
| forgetting the final sort | the right set in heap order; top-p (step 7 of the spec) walks it in the wrong order | step 3 heap-sorts the outputs in place |
| a max-heap (best at the root) | the root comparison drops the wrong entries | sift_down and sift_up keep the worst entry at the root |
| treating as an error | a request with top_k = 0 (off) fails | k == 0 returns TL_OK after validation |
| writing before validating | a rejected call has already changed the outputs | all checks run before the first write |
rejecting with !isfinite instead of isnan | every masked request fails | the check is isnan; ranks last |
Warning:
!isfinite(x)looks like a safer NaN check, but it also rejects , and every request that uses constrained decoding masks logits to .
Where this leads
Section titled “Where this leads”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- goes further:
- PyTorch
torch.topkon CPU chooses a partial sort (std::partial_sortornth_element) by and processes many rows in parallel; seeaten/src/ATen/native/TopKImpl.h. - The vLLM and FlashInfer GPU samplers fuse top- and top- with sampling, by rejection instead of sorting; see FlashInfer
sampling.cuh. - llama.cpp’s
llama_sampler_top_kdoes a partial sort over the candidate array, reused by every sampler in the chain; seesrc/llama-sampling.cpp.
Further reading
Section titled “Further reading”- 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).
Key terms
Section titled “Key terms”- 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 : 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 -th element by partitioning, which reorders its input.
Summary
Section titled “Summary”- Top- needs only a heap of size : keep the best seen so far with the worst of them at the root, and each new value costs one comparison against the root, plus 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 -th place (the lower index) and the output order of equal values (ascending index).
- NaN is rejected, is a value: NaN has no place in any order, and a masked logit is and simply ranks last.
- No allocation: the heap is built inside
idxandval, 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.
Review questions
Section titled “Review questions”- Why is the root the worst kept entry rather than the best?
Answer
The 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. - Why does the replace test use
worse(root, new)and not “new value greater than or equal to root value”?Answer
With "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. - Why must the NaN scan finish before any write, even though it costs an extra pass?
Answer
The 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. - Why does the heap sort leave the outputs best first, when it moves the root to the end each time?
Answer
The 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. - About how many heap insertions does a random logit row of cause for ?
Answer
The $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.