Skip to content
Merged
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
10 changes: 7 additions & 3 deletions mlx/backend/metal/kernels/sort.h
Original file line number Diff line number Diff line change
Expand Up @@ -388,8 +388,11 @@ template <
using ValT = typename sort_kernel::ValT;
using IdxT = typename sort_kernel::IdxT;

auto in_block_idx = elem_to_loc(tid.y, nc_shape, in_nc_strides, nc_dim);
auto out_block_idx = elem_to_loc(tid.y, nc_shape, out_nc_strides, nc_dim);
// Signed offsets: a non-sorted axis may have a negative stride.
auto in_block_idx =
elem_to_loc<int64_t>(tid.y, nc_shape, in_nc_strides, nc_dim);
auto out_block_idx =
elem_to_loc<int64_t>(tid.y, nc_shape, out_nc_strides, nc_dim);
inp += in_block_idx;
out += out_block_idx;

Expand Down Expand Up @@ -532,7 +535,8 @@ template <
BLOCK_THREADS,
N_PER_THREAD>;

auto block_idx = elem_to_loc(tid.y, nc_shape, nc_strides, nc_dim);
// Signed offset: a non-sorted axis may have a negative stride.
auto block_idx = elem_to_loc<int64_t>(tid.y, nc_shape, nc_strides, nc_dim);
inp += block_idx;
out_vals += tid.y * size_sorted_axis;
out_idxs += tid.y * size_sorted_axis;
Expand Down
21 changes: 21 additions & 0 deletions python/tests/test_ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -2675,6 +2675,27 @@ def test_sort(self):
y_np = np.sort(np.array(a), axis=-1)
self.assertTrue(np.array_equal(y_np, y_mx))

# Negative stride on an axis that is not sorted, single and multi block
np.random.seed(0)
for dtype in ("int32", "float32"):
for size in (4, 32769):
with self.subTest(dtype=dtype, size=size):
a_np = np.random.uniform(0, 100, size=(3, size))
a_np = a_np.astype(getattr(np, dtype))
a_mx = mx.array(a_np)[::-1, :]
a_np = a_np[::-1, :]

b_np = np.sort(a_np, axis=-1)
self.assertTrue(np.array_equal(b_np, mx.sort(a_mx, axis=-1)))

idx = mx.argsort(a_mx, axis=-1)
self.assertTrue(
np.array_equal(b_np, mx.take_along_axis(a_mx, idx, axis=-1))
)

b_mx = mx.partition(a_mx, 1, axis=-1)
self.assertTrue(np.array_equal(b_np[:, 1], np.array(b_mx)[:, 1]))

def test_partition(self):
shape = (3, 4, 5)
for dtype in ("int32", "float32"):
Expand Down
Loading