Skip to content
fn

topk

→tuple of (Tensor, Tensor)
topk(input: Tensor, k: _int, dim: _int = ..., largest: _bool = ..., sorted: _bool = ...)

Implementing kernel

C++ engine symbols that back this Python API.

Return the k largest (or smallest) values along dim and their indices.

Both outputs have size k along dim; all other dims match input. Values come best first: descending for largest=True, ascending otherwise.

Parameters

inputTensor
Source tensor.
kint
Number of elements to return. Must satisfy 0 < k <= input.size(dim).
dimint= -1
Reduction axis.
largestbool= True
False returns the k smallest instead.

Returns

tuple of (Tensor, Tensor)

(values, indices).

Raises

NotImplementedError
For a bool input, at either end and on every device: which booleans are the largest is not a question topk answers, so cast to an integer dtype first. sort and argsort do take bool.

Notes

largest=False takes the head of the stable ascending order, so equal values keep their input order and NaN is taken only when fewer than k numbers remain. For the k-th order statistic alone, prefer kthvalue.

Examples

>>> import lucid
>>> x = lucid.tensor([1.0, 5.0, 3.0, 4.0, 2.0])
>>> v, i = lucid.topk(x, k=3, dim=0)
>>> v
Tensor([5., 4., 3.])
>>> lucid.topk(x, k=2, dim=0, largest=False)[1]
Tensor([0, 4])