Skip to content

Fix the torch.take() wrapper to make axis optional for ndim = 1 #47

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

Merged
merged 1 commit into from
Jul 19, 2023
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
6 changes: 5 additions & 1 deletion array_api_compat/torch/_aliases.py
Original file line number Diff line number Diff line change
Expand Up @@ -681,7 +681,11 @@ def isdtype(
else:
return dtype == kind

def take(x: array, indices: array, /, *, axis: int, **kwargs) -> array:
def take(x: array, indices: array, /, *, axis: Optional[int] = None, **kwargs) -> array:
if axis is None:
if x.ndim != 1:
raise ValueError("axis must be specified when ndim > 1")
axis = 0
Copy link

Choose a reason for hiding this comment

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

Or you can dispatch to torch.take, either should be alright.

Copy link
Member Author

Choose a reason for hiding this comment

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

torch.take doesn't support an axis argument.

Copy link

Choose a reason for hiding this comment

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

exactly :D torch.take() == numpy.take(axis=None)

Copy link

Choose a reason for hiding this comment

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

it's a bit more general, as it sees the whole tensor as a 0dim tensor and indexes into it, so it also works for ndim > 1.

Copy link
Member Author

Choose a reason for hiding this comment

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

Right. The flattening behavior is also there in NumPy, but I think we wanted to avoid that with the array API take. I'm not sure to what degree we should try to avoid that for the compat library, though (c.f. #34 (comment))

return torch.index_select(x, axis, indices, **kwargs)

__all__ = ['result_type', 'can_cast', 'permute_dims', 'bitwise_invert', 'add',
Expand Down