Skip to content
Medium Framework

Top-K Values

Return the k largest values from a vector, ordered from largest to smallest. Select values by their numerical value, not their absolute magnitude.

Your task

Implement top_k(x, k).

  • x is a one-dimensional tensor of finite values with shape (n,).
  • k is an integer with 0 <= k <= n.
  • Return a tensor of shape (k,) with x's dtype and device. Leave x unchanged.

For x=[-9, 4, 4, 1] and k=3, return [4, 4, 1]. Both occurrences of 4 count: top-k does not remove duplicates. The value -9 is smaller than 1 even though its magnitude is larger.

For k=n, return all values in descending order. For k=0, return an empty vector of shape (0,). For k=1, keep a one-element vector rather than returning a scalar.

torch.topk(x, k) and jax.lax.top_k(x, k) return both values and their original indices. Return only the values. Since indices are not part of the answer, no rule for ordering indices of equal values is needed.

Sorting in descending order and taking the first k values also gives the required result. Do not return the values in their original input order.