Fix Metal sort for arrays with negative strides - #4226
Closed
reckylurker wants to merge 1 commit into
Closed
Conversation
reckylurker
force-pushed
the
fix/metal-sort-negative-strides
branch
from
August 13, 2026 06:32
ae419b3 to
4469d04
Compare
zcbenz
requested changes
Aug 13, 2026
zcbenz
left a comment
Member
There was a problem hiding this comment.
The bug is true but a correct fix should get the root cause fixed rather than working around the problem by doing a copy.
4 tasks
Member
|
Closing in favor of #4252. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #4225.
Proposed changes
mx.sort,mx.topk, andmx.partitionon Metal GPU returned zeros for non-first rows when called on arrays with negative strides (e.g.x[::-1, :]).In
single_block_sortandmulti_block_sort,set_input_arraybinds Metal buffer 0 starting ata_buf + in.offset(). When non-sorted axes have negative strides,elem_to_locin MSL computes negative relative pointer offsets for subsequent rows (tid.y = 1 -> -4 elements), attempting to read memory prior to Metal's bound buffer window. Metal's GPU memory protection traps these out-of-bounds reads and outputs0.0f.Matching NumPy's behavior when sorting negative-strided views,
gpu_merge_sortnow checks for negative strides and creates a temporary contiguous GPU copy viacontiguous_copy_gpu(in, s). Zero-copy execution is fully preserved for standard contiguous arrays, transposed arrays (x.T), and positive strided views (x[::2, :]).Added
test_strided_negative_stride_sortinpython/tests/test_ops.py.Checklist
pre-commit run --all-filesto format my code / installed pre-commit prior to committing changes