← Reference · Nestor G Pestelos Jr · Print this page

Algorithms · Machine Learning

Top-k Selection and Sampling

Reference entry · last updated September 11, 2026

Top-k is an algorithmic selection operation that identifies the \(k\) largest (or smallest) elements from an ordered or score-ranked set of \(n\) elements, as well as a stochastic decoding heuristic that truncates a probability distribution to its \(k\) highest-probability outcomes prior to renormalization and sampling.[1, 2] Originating in classical order statistics and selection algorithms, top-k selection operates across computer science in priority queue scheduling, database query processing, information retrieval ranking, sparse conditional routing in Mixture-of-Experts architectures, and autoregressive language model generation.

1. First Principles: The Selection Problem and Order Statistics

The top-k operation originates in the fundamental selection problem of theoretical computer science: given a collection of \(n\) elements from a totally ordered universe and an integer \(k \le n\), identify the subset of elements that occupy the first \(k\) positions under that total order.[1]

1.1 Formal Definition

Let \(S = \{x_1, x_2, \dots, x_n\}\) be a multiset of \(n\) items equipped with a strict weak ordering or total preorder \(\le\). The sorted order statistics of \(S\) are denoted:

$$x_{(1)} \le x_{(2)} \le \dots \le x_{(n)}$$

The top-k selection problem requires computing the subset \(T_k \subseteq S\) of cardinality \(|T_k| = k\) such that:

$$\forall u \in T_k, \; \forall v \in (S \setminus T_k), \quad u \ge v$$

When ordered output is required, the problem becomes sorted top-k, producing the sequence \((x_{(n)}, x_{(n-1)}, \dots, x_{(n-k+1)})\). When relative order among the chosen items is unneeded, the problem is unsorted top-k.

1.2 Information-Theoretic Lower Bounds

In the comparison-based model of computation, sorting all \(n\) items requires \(\Omega(n \log n)\) comparisons. However, selecting the single \(k\)-th order statistic (e.g. median selection where \(k = \lfloor n/2 \rfloor\)) requires only \(\Theta(n)\) comparisons.[3]

For arbitrary \(k\), the comparison lower bound for unsorted top-k selection is:

$$C(n, k) = n + \min(k, n-k) \cdot \log\left(\frac{n}{\min(k, n-k)}\right) - O(k)$$

For sorted top-k selection, the information-theoretic lower bound is \(\Omega(n + k \log k)\). Sorting the entire input array is inefficient when \(k \ll n\).

2. Classical Selection Algorithms and Data Structures

Standard selection algorithms partition or filter datasets without computing complete orderings.[1]

2.1 Quickselect and Median-of-Medians

Quickselect (Hoare's Selection Algorithm): Adapts the Quicksort partitioning scheme. A pivot element is selected, and the array is partitioned into elements greater than the pivot and elements less than or equal to the pivot. Unlike Quicksort, which recurses into both partitions, Quickselect recurses only into the partition containing the target rank.[4]

Median-of-Medians (BFPRT Algorithm): Blum, Floyd, Pratt, Rivest, and Tarjan (1973) established a deterministic pivot selection strategy that divides elements into blocks of 5, finds their medians, and recursively chooses the median of those medians.[3] This guarantees a balanced partition and achieves a worst-case time complexity of \(O(n)\).

2.2 Bounded Min-Heaps and Priority Queues

When processing streaming data or unindexed collections where \(k \ll n\), maintaining an online bounded min-heap provides optimal memory efficiency:

2.3 Radix Selection and Bucket Partitions

For integer or fixed-point floating-point representations, non-comparison selection operates in linear time. Radix select inspects bits from most-significant to least-significant, counting elements falling into high-bit buckets. Once a bucket boundary encloses the \(k\)-th rank, search continues recursively within that bucket, eliminating comparisons entirely.

3. Top-k Sampling in Autoregressive Language Models

In natural language processing and neural sequence generation, the final decoder layer emits an unnormalized vector of logits \(z \in \mathbb{R}^{|V|}\) over a vocabulary \(V\) (often \(|V| \ge 32{,}000\) to \(128{,}000\)). Softmax transforms these logits into a categorical probability distribution.[2]

3.1 Mathematical Formulation and Renormalization

Pure greedy decoding (\(k = 1\)) selects the single token with the highest conditional probability \(\operatorname{argmax}_i P(w_i \mid w_{[9] while in code generation, repeated temperature sampling evaluated via \(\text{pass}@k\) metrics yields higher task completion than greedy selection alone.[10] In open-ended creative generation, greedy selection also frequently induces degenerative repetition loops and generic phrasing.

Top-k sampling (introduced by Fan, Lewis, and Dauphin in 2018) restricts sampling to the \(k\) tokens with the highest probabilities.[2] Let \(V^{(k)} \subset V\) be the subset of \(k\) tokens that maximize \(P(w)\). The truncated distribution \(P'(w)\) is formed by setting the probability of all other tokens to zero and renormalizing across \(V^{(k)}\):

$$P'(w_i) = \begin{cases} \dfrac{P(w_i)}{\sum_{w_j \in V^{(k)}} P(w_j)} & \text{if } w_i \in V^{(k)} \\[1em] 0 & \text{otherwise} \end{cases}$$

A random sample is then drawn from \(P'(w)\).

3.2 Mitigating Degeneration and Unreliable Tails

Neural language models often assign non-zero probability mass to contextually implausible, ungrammatical, or nonsensical tokens in the long tail of the vocabulary distribution. Because vocabulary sizes are large, the cumulative probability mass in this tail can be substantial. Top-k sampling truncates this tail entirely, preventing the generator from sampling low-probability artifacts while preserving stochastic diversity among plausible candidates.

3.3 Comparison with Top-p (Nucleus) and Temperature

While top-k sampling enforces a static candidate count \(k\), related decoding parameters adapt dynamically:[5]

Method Mechanism Behavior on Peaked Logits Behavior on Flat Logits
Top-k Selects fixed count \(k\) highest tokens May include low-probability tokens if \(k\) is larger than the true confidence set Truncates plausible alternatives beyond position \(k\)
Top-p (Nucleus) Selects smallest subset with cumulative probability \(\ge p\) Shrinks to 1 or 2 tokens when confidence is high Expands to hundreds of tokens when distribution is diffuse
Temperature (\(T\)) Divides logits by \(T\) before Softmax: \(\frac{z_i}{T}\) Flattens or sharpens relative probabilities without altering vocabulary support Does not hard-truncate low-probability tail tokens

Modern serving systems commonly compose these methods in pipeline sequence: apply temperature scaling, filter via top-k, filter via top-p, and finally execute categorical sampling.

4. Top-k Routing in Sparse Architectures and Retrieval

Beyond token decoding, top-k selection serves as a structural gating mechanism in modern deep learning architectures and retrieval engines.[6, 7]

4.1 Mixture-of-Experts (MoE) Gating

Sparse Mixture-of-Experts architectures (such as Shazeer et al., 2017, Switch Transformer, Mixtral, and DeepSeek-V2/V3) replace dense feed-forward network (FFN) layers with \(E\) parallel expert networks. For each input token representation \(x\), a router network computes gating scores \(H(x) = x \cdot W_g\).[6]

To bound compute per token, a Top-k gating function activates only the \(k\) highest-scoring experts (commonly \(k = 1\) or \(k = 2\) out of \(E = 8\) to \(256\)):

$$\text{Gate}(x) = \operatorname{Softmax}(\operatorname{KeepTopK}(H(x), k))$$

where \(\operatorname{KeepTopK}(v, k)_i = v_i\) if \(v_i\) is among the top \(k\) values of \(v\), and \(-\infty\) otherwise. The token is dispatched exclusively to the selected \(k\) experts, scaling total parameter capacity without increasing active FLOPs per token.

4.2 Vector Search and Nearest Neighbor Ranking

In Retrieval-Augmented Generation (RAG) and dense vector search, retrieval engines match a query embedding vector \(q \in \mathbb{R}^d\) against millions of stored document vectors \(\{d_1, \dots, d_N\}\). The retrieval pipeline computes similarity scores (such as cosine similarity or inner product) and extracts the top-k nearest neighbors.[7] Approximate Nearest Neighbor (ANN) index structures like Hierarchical Navigable Small World (HNSW) graphs use beam searches bounded by dynamic priority queues to return top-k matches in logarithmic \(O(\log N)\) time.

5. Accelerator Implementation and Systems Considerations

Selection on massively parallel GPU and TPU architectures encounters distinct hardware bottlenecks compared to sequential CPU algorithms.[8]

5.1 Parallel Bitonic Sort and Radix Select on GPUs

Standard Quickselect is inherently branch-heavy and poorly suited to Single Instruction, Multiple Threads (SIMT) architectures. Modern GPU frameworks (such as CUDA CUB and FlashAttention) execute top-k selection using:

5.2 Continuous and Differentiable Relaxations (Soft Top-k)

The standard top-k operator is non-differentiable because its output consists of discrete indices and step-function indicators, resulting in zero gradients almost everywhere. In end-to-end differentiable learning (such as learning-to-rank, neural memory addressing, or differentiable subset selection), practitioners separate stochastic discrete sampling from continuous gradient relaxations:

See Also

References

  1. T. H. Cormen, C. E. Leiserson, R. L. Rivest, and C. Stein, Introduction to Algorithms, 3rd ed. Cambridge, MA: MIT Press, 2009.
  2. A. Fan, M. Lewis, and Y. Dauphin, "Hierarchical Neural Story Generation," in Proceedings of the 56th Annual Meeting of the Association for Computational Linguistics (ACL), 2018, pp. 889–898. Free full text: https://arxiv.org/abs/1805.04833
  3. M. Blum, R. W. Floyd, V. Pratt, R. L. Rivest, and R. E. Tarjan, "Time bounds for selection," Journal of Computer and System Sciences, vol. 7, no. 4, pp. 448–461, 1973. DOI: 10.1016/S0022-0000(73)80033-9
  4. C. A. R. Hoare, "Algorithm 65: Find," Communications of the ACM, vol. 4, no. 7, pp. 321–322, 1961. DOI: 10.1145/366622.366644
  5. A. Holtzman, J. Buys, L. Du, M. Forbes, and Y. Choi, "The Curious Case of Neural Text Degeneration," in International Conference on Learning Representations (ICLR), 2020. Free full text: https://arxiv.org/abs/1909.05858
  6. N. Shazeer et al., "Outrageously Large Neural Networks: The Sparsely-Gated Mixture-of-Experts Layer," in International Conference on Learning Representations (ICLR), 2017. Free full text: https://arxiv.org/abs/1701.06538
  7. P. Lewis et al., "Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks," in Advances in Neural Information Processing Systems (NeurIPS), vol. 33, 2020, pp. 9459–9474. Free full text: https://arxiv.org/abs/2005.11401
  8. J. L. Hennessy and D. A. Patterson, Computer Architecture: A Quantitative Approach, 6th ed. Cambridge, MA: Morgan Kaufmann, 2017.
  9. X. Wang et al., "Self-Consistency Improves Chain of Thought Reasoning in Language Models," in International Conference on Learning Representations (ICLR), 2023. Free full text: https://arxiv.org/abs/2203.11171
  10. M. Chen et al., "Evaluating Large Language Models Trained on Code," arXiv preprint arXiv:2107.03374, 2021. Free full text: https://arxiv.org/abs/2107.03374
  11. W. Kool, H. van Hoof, and M. Welling, "Stochastic Beams and Where to Find Them: The Gumbel-Top-k Trick for Sampling Sequences Without Replacement," in Proceedings of the 36th International Conference on Machine Learning (ICML), 2019, pp. 3499–3508. Free full text: https://proceedings.mlr.press/v97/kool19a.html
  12. S. Xie and S. Ermon, "Reparameterizable Subset Sampling via Continuous Relaxations," in International Joint Conference on Artificial Intelligence (IJCAI), 2019, pp. 3919–3925. Free full text: https://arxiv.org/abs/1901.10517