Fix segfault on negative out of bounds axes in take_along_axis/put_along_axis - #4118
Merged
Merged
Conversation
…ong_axis
The bounds check in take_along_axis, scatter_axis (which backs put_along_axis
and scatter_add_axis) and linalg::cross was dead code:
if (axis + a.ndim() < 0 || axis >= static_cast<int>(a.ndim()))
array::ndim() returns size_t, so `axis + a.ndim()` is evaluated in unsigned
arithmetic and is never negative. Only the positive half of the check, which
casts to int, actually ran. A negative out of bounds axis therefore flowed
through to broadcast_arrays as `axis - int(a.ndim())` and either raised an
internal "SmallVector out of range" error or, for larger magnitudes,
overwrote the stack and segfaulted inside broadcast_shapes.
Use normalize_axis_index, which does the comparison in int and is already
used for this purpose elsewhere in ops.cpp. It also normalizes, so the later
manual "allow negative axis" adjustments are no longer needed.
Same class of bug as ml-explore#4021.
Adityaj0
force-pushed
the
fix-negative-axis-validation
branch
from
August 10, 2026 02:49
df1da77 to
7535eb1
Compare
Contributor
Author
|
@zcbenz please review this PR. All checks passed. |
Member
|
For most open source projects reviewing contributor PR is a distraction that slows down actual development. |
zcbenz
approved these changes
Aug 11, 2026
This was referenced Aug 16, 2026
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 #4115.
Proposed changes
The bounds check in
take_along_axis,scatter_axis(which backsput_along_axisandscatter_add_axis) andlinalg::crosswas dead code:array::ndim()returnssize_t, soaxis + a.ndim()is evaluated in unsigned arithmetic and is never negative. Only the positive half of the check, which casts toint, actually ran.A negative out of bounds axis therefore passed validation and reached
broadcast_arraysasaxis - int(a.ndim()). For small magnitudes that surfaced as an internalIndexError: SmallVector out of range; for larger ones it overwrote the stack and segfaulted insidebroadcast_shapes:This switches all three call sites to
normalize_axis_index, which does the comparison inintand is already used for exactly this purpose elsewhere inops.cpp(squeeze,expand_dims,flip,concatenate,stack,repeat, ...). Since it also normalizes, the later manual "allow negative axis" adjustments become redundant and are removed.#4021 fixed this same pattern, but only in
squeezeandexpand_dims. It didnot touch these three call sites, which still carry the original expression. On
current
main(which already includes #4021):maintodaymx.expand_dims(x, -9)ValueError: [expand_dims] Axis -9 is out of bounds ...(fixed by #4021)mx.squeeze(x, -9)ValueError: [squeeze] Axis -9 is out of bounds ...(fixed by #4021)mx.take_along_axis(x, i, axis=-4)IndexError: SmallVector out of range.mx.put_along_axis(x, i, v, axis=-4)IndexError: SmallVector out of range.mx.linalg.cross(a, b, axis=-4)IndexError: SmallVector out of range.So this is a follow-up to #4021 covering the remaining call sites, not a
duplicate of it.
Before, on
main:After, all of them raise the same clean error, e.g.
Valid negative axes (
-1,-2,-3) continue to work unchanged.Note this slightly changes the wording of the existing error message for the positive out of bounds case, from "Received invalid axis for array with N dimensions" to
normalize_axis_index's "Axis A is out of bounds for array with N dimensions", which also has the benefit of naming the offending axis. No tests depended on the old wording.Tests
Added
test_along_axis_invalid_axisandtest_cross_invalid_axistopython/tests/test_ops.py, covering positive and negative out of bounds axes fortake_along_axis,put_along_axisandlinalg.cross, plus an assertion that valid negative axes still work. The deep-negative values are excluded from the test bodies only in the sense that they are asserted to raise; they crash on unpatched builds, which is the point.pre-commit run --all-filesto format my code and installed pre-commit prior to committing changesVerified with a CPU-only build (
-DMLX_BUILD_METAL=OFF);test_ops,test_linalg,test_autogradandtest_vmappass. I also confirmed the new tests fail on an unpatched build.