Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion mlx/backend/cuda/sort.cu
Original file line number Diff line number Diff line change
Expand Up @@ -744,7 +744,7 @@ void single_block_sort(
int64_t in_stride_sorted_axis = in.strides()[axis];
int64_t out_stride_sorted_axis = out.strides()[axis];

bool contiguous = in.flags().contiguous;
bool contiguous = in.flags().row_contiguous;
auto check_strides = [](const array& x, int64_t sort_stride) {
int64_t min_stride =
*std::min_element(x.strides().begin(), x.strides().end());
Expand Down
6 changes: 4 additions & 2 deletions mlx/backend/metal/sort.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,10 @@ void single_block_sort(

// We can only use the contiguous kernel if the sorted axis
// has the largest or smallest stride.
// We also need the input to be contiguous
bool contiguous = in.flags().contiguous;
// We also need the input to be row contiguous, since the kernel enumerates
// the rows with a single segment stride, which only holds when the axes
// that are not sorted are laid out row major.
bool contiguous = in.flags().row_contiguous;
auto check_strides = [](array x, int sort_stride) {
int min_stride = *std::min_element(x.strides().begin(), x.strides().end());
int max_stride = *std::max_element(x.strides().begin(), x.strides().end());
Expand Down
18 changes: 18 additions & 0 deletions python/tests/test_ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -3654,6 +3654,24 @@ def test_broadcast_shapes(self):
with self.assertRaises(ValueError):
mx.broadcast_shapes()

def test_sort_transposed(self):
# The sorted axis can keep the smallest or largest stride while the
# axes that are not sorted are no longer laid out row major.
np.random.seed(0)
a_np = np.random.uniform(0, 100, size=(3, 4, 8)).astype(np.float32)
a_mx = mx.array(a_np)
for perm in permutations(range(3)):
b_np = np.transpose(a_np, perm)
b_mx = mx.transpose(a_mx, perm)
for axis in range(3):
with self.subTest(perm=perm, axis=axis):
s_np = np.sort(b_np, axis=axis)
self.assertTrue(np.array_equal(s_np, mx.sort(b_mx, axis=axis)))
idx = np.array(mx.argsort(b_mx, axis=axis))
self.assertTrue(
np.array_equal(s_np, np.take_along_axis(b_np, idx, axis=axis))
)

def test_sort_nan(self):
for dtype in [mx.float32, mx.float16, mx.bfloat16]:
with self.subTest(dtype=dtype):
Expand Down
Loading