Skip to content

ENH: add top_k#446

Open
ev-br wants to merge 1 commit into
data-apis:mainfrom
ev-br:top_k
Open

ENH: add top_k#446
ev-br wants to merge 1 commit into
data-apis:mainfrom
ev-br:top_k

Conversation

@ev-br

@ev-br ev-br commented Jul 1, 2026

Copy link
Copy Markdown
Member

Add basic top_k wrappers, per data-apis/array-api#722
-tests tracker: data-apis/array-api-tests#438

  • torch
  • numpy
  • cupy
  • dask

Supersedes and closes gh-158

To test locally: with this PR and data-apis/array-api-tests#438, use

$ ARRAY_API_TESTS_SKIP_DTYPES=uint16,uint32,uint64 ARRAY_API_TESTS_VERSION=draft ARRAY_API_TESTS_MODULE=array_api_compat.torch pytest array_api_tests/test_searching_functions.py::test_top_k -s --max-examples=5000

Copilot AI review requested due to automatic review settings July 1, 2026 19:45

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Adds an Array API-compatible top_k wrapper to the array_api_compat.torch namespace, mapping the standardized signature to torch.topk.

Changes:

  • Introduces top_k(a, k, *, axis, mode, **kwargs) wrapper in the Torch backend.
  • Validates mode and forwards arguments to torch.topk.
  • Exports top_k via the Torch backend __all__.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +944 to +961
def top_k(
a: Array,
k: int,
/,
*,
axis: int =-1,
mode: Literal["largest", "smallest"] = "largest",
**kwargs
) -> tuple[Array, Array]:
if mode not in ["largest", "smallest"]:
raise ValueError(f"Invalid {mode = }.")
return torch.topk(
a,
k,
dim=axis,
largest = (mode == "largest"),
**kwargs
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants