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.
@nastya236

Copy link
Copy Markdown
Collaborator

Thanks for your contribution. Do you mind rewriting the description using provided template?

@nastya236 nastya236 added the await response This pull request is waiting for response from the author. label Aug 26, 2026
@zcbenz

zcbenz commented Aug 29, 2026

Copy link
Copy Markdown
Member

@Adityaj0 Please notice that not long ago we have added AI policy that now forbids automatic creating PRs from AI and requires disclosing usage of AI, with a simple pull request template that is required to be filled when AI is used: https://github.com/ml-explore/mlx/blob/main/.github/pull_request_template.md

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

await response This pull request is waiting for response from the author. low priority

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

3 participants