Is torch.sort stable?

And what sorting algorithm is used?

1 Like

Same question. Is the code of torch.sort available?

1 Like

Don’t know if it’s still relevant but for people running into this: I had the same question and looked into torch.sort: https://github.com/pytorch/pytorch/blob/v0.4.1/aten/src/THC/generic/THCTensorSort.cu#L330.

It is undocumented behaviour, but if the tensor contains at least 2049 elements, internally the function sortViaThrust is used, which as can be seen in the same file performs a stable sort.

You can therefore easily define a wrapper function that provides a stable sort by padding the tensor if it contains less than 2049 elements, but be aware that this may break in the future.

I would be happy to see if anyone has a stable solution to a stable sort.

2 Likes

Way to find torch.sort @wouter. Thank you. Wish the code was linked to in the docs. I can’t tell from the code which sort is being used. Where is the code for that?