Skip to content

Document sort stability and NaN handling - #3400

Merged
angeloskath merged 2 commits into
ml-explore:mainfrom
NeuralNoble:docs-sort-stability
Apr 15, 2026
Merged

angeloskath merged 2 commits into
ml-explore:mainfrom
NeuralNoble:docs-sort-stability

Conversation

@NeuralNoble

Copy link
Copy Markdown
Contributor

Summary

Addresses #2057.

Documents that sort and argsort are stable across all backends and place NaN values at the end to match NumPy/JAX.

  • CPU: std::stable_sort with a NaN-aware comparator (mlx/backend/cpu/sort.cpp)
  • Metal/CUDA: merge sort with the same NaN handling (mlx/backend/metal/kernels/sort.h, mlx/backend/cuda/sort.cu)

Both guarantees are true in the current implementation (NaN handling introduced in #2667) but weren't documented, so users couldn't rely on them.

Changes

  • python/src/ops.cpp — add note to sort and argsort docstrings
  • mlx/ops.h — add note to the four C++ declarations
  • mlx/ops.cpp — add note to the four C++ definitions

Test plan

  • pre-commit run --all-files passes
  • C++ build succeeds, ctest passes
  • python -m pytest python/tests/test_ops.py -k sort passes
  • help(mx.sort) renders the new docstring at runtime

NeuralNoble and others added 2 commits April 12, 2026 14:49
Both `sort` and `argsort` are stable across all backends (std::stable_sort
on CPU, merge sort on Metal/CUDA) and place NaN values at the end to match
NumPy/JAX. Add this to the Python docstrings and C++ declarations so users
can rely on these guarantees.

@angeloskath angeloskath left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks.

@angeloskath
angeloskath merged commit fd8e849 into ml-explore:main Apr 15, 2026
16 checks passed
@NeuralNoble
NeuralNoble deleted the docs-sort-stability branch April 16, 2026 20:46
@BrewTestBot BrewTestBot mentioned this pull request Apr 22, 2026
1 task done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants