Skip to content

BUG: numpy.array_api.argsort(stable=True, descending=True) does not respect relative order  #20778

@honno

Description

@honno

The implementations of xp.sort() and xp.argsort() in numpy.array_api currently flip the resulting array when descending=True.

For stable=True scenarios, this leads to incorrect behaviour as a stable sort should be respecting an equivalent element's relative order of whatever comparison is being used (i.e. < and > operators). To be fair, the concept of respecting relative order of a descending sort is nonsensical for NumPy as there's no actual descending sort to use, but this is an area of non-compliance and might trip array consuming libraries.

This only really affects xp.argsort() as there's no way to distinguish relative order of equivalent elements in xp.sort().

cc @asmeurer @pmeier @lezcano

An example of NumPy acting erroneously:

>>> from numpy import array_api as xp
>>> x = xp.asarray([0, 1, 0])
>>> xp.argsort(x, stable=True)
Array([0, 2, 1], dtype=int64)  # correct
>>> xp.argsort(x, stable=True, descending=True)
Array([1, 2, 0], dtype=int64)  # should be [1, 0, 2]

PyTorch's sort() and the Python sorted() builtin are examples of respecting relative order when descending:

>>> a = [0, 1, 0]
>>> sorted(range(len(a)), key=a.__getitem__)
[0, 2, 1]
>>> sorted(range(len(a)), key=a.__getitem__, reverse=True)
[1, 0, 2]
...
>>> import torch
>>> t = torch.as_tensor([0, 1, 0])
>>> torch.sort(t, stable=True).indices
tensor([0, 2, 1])
>>> torch.sort(t, stable=True, descending=True).indices
tensor([1, 0, 2])

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions