Skip to content

Clamp slice bounds in mixed fancy/slice indexing - #4397

Open
Adityaj0 wants to merge 1 commit into
ml-explore:mainfrom
Adityaj0:pr-clamp-slice-bounds-mixed-indexing
Open

Clamp slice bounds in mixed fancy/slice indexing#4397
Adityaj0 wants to merge 1 commit into
ml-explore:mainfrom
Adityaj0:pr-clamp-slice-bounds-mixed-indexing

Conversation

@Adityaj0

@Adityaj0 Adityaj0 commented Aug 25, 2026

Copy link
Copy Markdown
Contributor

Fixes #4399

When a slice is combined with an array/int index (e.g. a[start:stop, idx_array]), the slice bounds were adjusted for negative indices but never clamped into the valid [0, axis_size] range before being passed to arange(). Out-of-range or heavily negative slice bounds produced arrays of the wrong shape containing bogus repeated/garbage data instead of matching NumPy's clamping behavior. Adds a regression test.

mlx_gather_nd (used when a slice is combined with an array/int index,
e.g. a[start:stop, idx_array]) only adjusted negative slice bounds by
a single += axis_size and never clamped them into the valid
[0, axis_size] range before passing them to arange(). This differs
from the general slice() path in mlx/ops.cpp's normalize_slice(),
which does clamp.

As a result, out-of-range or heavily negative slice bounds (e.g.
a[-100:4, idx] or a[0:200, idx] on a size-4 axis) produced arrays of
the wrong shape filled with incorrect/garbage-repeated data instead
of matching NumPy's clamping behavior, and extreme bounds (e.g.
a[-10**9:4, idx]) could allocate huge bogus index arrays.

Fix clamps start/end the same way normalize_slice does before
building the arange, and adds a regression test.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG] Mixed slice + fancy indexing produces wrong shape/garbage data for out-of-range slice bounds

2 participants