Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow negative indices in Gather op #47

Merged
merged 1 commit into from
Feb 2, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion src/ops/gather.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@ pub fn gather<T: Copy + Default>(
let axis = resolve_axis(input.ndim(), axis)?;

for index in indices.iter().copied() {
if index < 0 || index >= input.size(axis) as i32 {
let size = input.size(axis) as i32;
if index < -size || index >= size {
return Err(OpError::InvalidValue("Entry in `indices` is out of range"));
}
}
Expand Down Expand Up @@ -500,6 +501,13 @@ mod tests {
let result = gather(input.view(), 1, indices.view()).unwrap();
expect_equal(&result, &expected)?;

// Negative index values.
let input = Tensor::from([1, 2, 3]);
let indices = Tensor::from([-1, -2, -3]);
let expected = Tensor::from([3, 2, 1]);
let result = gather(input.view(), 0, indices.view()).unwrap();
assert_eq!(&result, &expected);

Ok(())
}

Expand Down
Loading