-
Notifications
You must be signed in to change notification settings - Fork 10
ENH: pad
: add delegation
#72
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
Changes from 24 commits
Commits
Show all changes
25 commits
Select commit
Hold shift + click to select a range
d17fd2f
ENH: `pad`: add delegation
lucascolley 38690bb
fix vendor test
lucascolley d4d05b0
fixes
lucascolley ea09206
Merge branch 'main' into pad-delegate
lucascolley 9dcb9e5
finish merge
lucascolley 5db1a93
clean up
lucascolley 486ebef
use an enum
lucascolley 44ec95a
Merge branch 'main' into pad-delegate
lucascolley 303c7fc
Merge branch 'main' into pad-delegate
lucascolley 6f72daf
update lockfile
lucascolley a54357b
fix torch delegation
lucascolley 71edc05
typing
lucascolley fd6b9d8
Merge branch 'main' into pad-delegate
lucascolley 1e59fbd
update lockfile
lucascolley e0046c5
combine enums
lucascolley 2bd8205
green
lucascolley 1531841
update lockfile
lucascolley 64db422
tweak docstring
lucascolley ed7fd25
update docstring
lucascolley 93f2591
Update src/array_api_extra/_delegation.py
lucascolley 47e9b5b
fix CI
lucascolley 4c786a2
fix mypy
lucascolley 9daa33a
address review
lucascolley 3ac8e45
flush ci
lucascolley 82e5258
update index
lucascolley File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -13,6 +13,7 @@ | |
expand_dims | ||
kron | ||
nunique | ||
pad | ||
setdiff1d | ||
sinc | ||
``` |
Large diffs are not rendered by default.
Oops, something went wrong.
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
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,83 @@ | ||
"""Delegation to existing implementations for Public API Functions.""" | ||
|
||
from types import ModuleType | ||
from typing import Literal | ||
|
||
from ._lib import Backend, _funcs | ||
from ._lib._utils._compat import array_namespace | ||
from ._lib._utils._typing import Array | ||
|
||
__all__ = ["pad"] | ||
|
||
|
||
def _delegate(xp: ModuleType, *backends: Backend) -> bool: | ||
""" | ||
Check whether `xp` is one of the `backends` to delegate to. | ||
|
||
Parameters | ||
---------- | ||
xp : array_namespace | ||
Array namespace to check. | ||
*backends : IsNamespace | ||
Arbitrarily many backends (from the ``IsNamespace`` enum) to check. | ||
|
||
Returns | ||
------- | ||
bool | ||
``True`` if `xp` matches one of the `backends`, ``False`` otherwise. | ||
""" | ||
return any(backend.is_namespace(xp) for backend in backends) | ||
|
||
|
||
def pad( | ||
x: Array, | ||
pad_width: int | tuple[int, int] | list[tuple[int, int]], | ||
mode: Literal["constant"] = "constant", | ||
*, | ||
constant_values: bool | int | float | complex = 0, | ||
xp: ModuleType | None = None, | ||
) -> Array: | ||
""" | ||
Pad the input array. | ||
|
||
Parameters | ||
---------- | ||
x : array | ||
Input array. | ||
pad_width : int or tuple of ints or list of pairs of ints | ||
Pad the input array with this many elements from each side. | ||
If a list of tuples, ``[(before_0, after_0), ... (before_N, after_N)]``, | ||
each pair applies to the corresponding axis of ``x``. | ||
A single tuple, ``(before, after)``, is equivalent to a list of ``x.ndim`` | ||
copies of this tuple. | ||
mode : str, optional | ||
Only "constant" mode is currently supported, which pads with | ||
the value passed to `constant_values`. | ||
constant_values : python scalar, optional | ||
Use this value to pad the input. Default is zero. | ||
xp : array_namespace, optional | ||
The standard-compatible namespace for `x`. Default: infer. | ||
|
||
Returns | ||
------- | ||
array | ||
The input array, | ||
padded with ``pad_width`` elements equal to ``constant_values``. | ||
""" | ||
xp = array_namespace(x) if xp is None else xp | ||
|
||
if mode != "constant": | ||
msg = "Only `'constant'` mode is currently supported" | ||
raise NotImplementedError(msg) | ||
|
||
# https://github.com/pytorch/pytorch/blob/cf76c05b4dc629ac989d1fb8e789d4fac04a095a/torch/_numpy/_funcs_impl.py#L2045-L2056 | ||
if _delegate(xp, Backend.TORCH): | ||
pad_width = xp.asarray(pad_width) | ||
pad_width = xp.broadcast_to(pad_width, (x.ndim, 2)) | ||
pad_width = xp.flip(pad_width, axis=(0,)).flatten() | ||
return xp.nn.functional.pad(x, tuple(pad_width), value=constant_values) # type: ignore[arg-type] # pyright: ignore[reportArgumentType] | ||
|
||
if _delegate(xp, Backend.NUMPY, Backend.JAX_NUMPY, Backend.CUPY): | ||
return xp.pad(x, pad_width, mode, constant_values=constant_values) | ||
|
||
return _funcs.pad(x, pad_width, constant_values=constant_values, xp=xp) |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1 +1,5 @@ | ||
"""Modules housing private functions.""" | ||
"""Internals of array-api-extra.""" | ||
|
||
from ._backends import Backend | ||
|
||
__all__ = ["Backend"] |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,59 @@ | ||
"""Backends with which array-api-extra interacts in delegation and testing.""" | ||
|
||
from collections.abc import Callable | ||
from enum import Enum | ||
from types import ModuleType | ||
from typing import cast | ||
|
||
from ._utils import _compat | ||
|
||
__all__ = ["Backend"] | ||
|
||
|
||
class Backend(Enum): # numpydoc ignore=PR01,PR02 # type: ignore[no-subclass-any] | ||
""" | ||
All array library backends explicitly tested by array-api-extra. | ||
|
||
Parameters | ||
---------- | ||
value : str | ||
String describing the backend. | ||
is_namespace : Callable[[ModuleType], bool] | ||
Function to check whether an input module is the array namespace | ||
corresponding to the backend. | ||
module_name : str | ||
Name of the backend's module. | ||
""" | ||
|
||
ARRAY_API_STRICT = ( | ||
"array_api_strict", | ||
_compat.is_array_api_strict_namespace, | ||
"array_api_strict", | ||
) | ||
NUMPY = "numpy", _compat.is_numpy_namespace, "numpy" | ||
NUMPY_READONLY = "numpy_readonly", _compat.is_numpy_namespace, "numpy" | ||
CUPY = "cupy", _compat.is_cupy_namespace, "cupy" | ||
TORCH = "torch", _compat.is_torch_namespace, "torch" | ||
DASK_ARRAY = "dask.array", _compat.is_dask_namespace, "dask.array" | ||
SPARSE = "sparse", _compat.is_pydata_sparse_namespace, "sparse" | ||
JAX_NUMPY = "jax.numpy", _compat.is_jax_namespace, "jax.numpy" | ||
|
||
def __new__( | ||
cls, value: str, _is_namespace: Callable[[ModuleType], bool], _module_name: str | ||
): # numpydoc ignore=GL08 | ||
obj = object.__new__(cls) | ||
obj._value_ = value | ||
return obj | ||
|
||
def __init__( | ||
self, | ||
value: str, # noqa: ARG002 # pylint: disable=unused-argument | ||
is_namespace: Callable[[ModuleType], bool], | ||
module_name: str, | ||
): # numpydoc ignore=GL08 | ||
self.is_namespace = is_namespace | ||
self.module_name = module_name | ||
|
||
def __str__(self) -> str: # type: ignore[explicit-override] # pyright: ignore[reportImplicitOverride] # numpydoc ignore=RT01 | ||
"""Pretty-print parameterized test names.""" | ||
return cast(str, self.value) |
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
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
"""Modules housing private utility functions.""" |
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
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
6 changes: 4 additions & 2 deletions
6
src/array_api_extra/_lib/_utils.py → src/array_api_extra/_lib/_utils/_helpers.py
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
Oops, something went wrong.
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Except.... it isn't agnostic, see for example the special paths in
at
andnunique
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
yes, I would like to split the file structure so that functions which make use of special paths are separate from array-agnostic implementations. I'll save that for a follow-up.