|
| 1 | +### Helpers borrowed from array-api-compat |
| 2 | + |
| 3 | +from __future__ import annotations # https://github.com/pylint-dev/pylint/pull/9990 |
| 4 | + |
| 5 | +import inspect |
| 6 | +import sys |
| 7 | +import typing |
| 8 | + |
| 9 | +if typing.TYPE_CHECKING: |
| 10 | + from ._typing import Array, Device |
| 11 | + |
| 12 | +__all__ = ["device"] |
| 13 | + |
| 14 | + |
| 15 | +# Placeholder object to represent the dask device |
| 16 | +# when the array backend is not the CPU. |
| 17 | +# (since it is not easy to tell which device a dask array is on) |
| 18 | +class _dask_device: # pylint: disable=invalid-name |
| 19 | + def __repr__(self) -> str: |
| 20 | + return "DASK_DEVICE" |
| 21 | + |
| 22 | + |
| 23 | +_DASK_DEVICE = _dask_device() |
| 24 | + |
| 25 | + |
| 26 | +# device() is not on numpy.ndarray or dask.array and to_device() is not on numpy.ndarray |
| 27 | +# or cupy.ndarray. They are not included in array objects of this library |
| 28 | +# because this library just reuses the respective ndarray classes without |
| 29 | +# wrapping or subclassing them. These helper functions can be used instead of |
| 30 | +# the wrapper functions for libraries that need to support both NumPy/CuPy and |
| 31 | +# other libraries that use devices. |
| 32 | +def device(x: Array, /) -> Device: |
| 33 | + """ |
| 34 | + Hardware device the array data resides on. |
| 35 | +
|
| 36 | + This is equivalent to `x.device` according to the `standard |
| 37 | + <https://data-apis.org/array-api/latest/API_specification/generated/array_api.array.device.html>`__. |
| 38 | + This helper is included because some array libraries either do not have |
| 39 | + the `device` attribute or include it with an incompatible API. |
| 40 | +
|
| 41 | + Parameters |
| 42 | + ---------- |
| 43 | + x: array |
| 44 | + array instance from an array API compatible library. |
| 45 | +
|
| 46 | + Returns |
| 47 | + ------- |
| 48 | + out: device |
| 49 | + a ``device`` object (see the `Device Support <https://data-apis.org/array-api/latest/design_topics/device_support.html>`__ |
| 50 | + section of the array API specification). |
| 51 | +
|
| 52 | + Notes |
| 53 | + ----- |
| 54 | +
|
| 55 | + For NumPy the device is always `"cpu"`. For Dask, the device is always a |
| 56 | + special `DASK_DEVICE` object. |
| 57 | +
|
| 58 | + See Also |
| 59 | + -------- |
| 60 | +
|
| 61 | + to_device : Move array data to a different device. |
| 62 | +
|
| 63 | + """ |
| 64 | + if _is_numpy_array(x): |
| 65 | + return "cpu" |
| 66 | + if _is_dask_array(x): |
| 67 | + # Peek at the metadata of the jax array to determine type |
| 68 | + try: |
| 69 | + import numpy as np # pylint: disable=import-outside-toplevel |
| 70 | + |
| 71 | + if isinstance(x._meta, np.ndarray): # pylint: disable=protected-access |
| 72 | + # Must be on CPU since backed by numpy |
| 73 | + return "cpu" |
| 74 | + except ImportError: |
| 75 | + pass |
| 76 | + return _DASK_DEVICE |
| 77 | + if _is_jax_array(x): |
| 78 | + # JAX has .device() as a method, but it is being deprecated so that it |
| 79 | + # can become a property, in accordance with the standard. In order for |
| 80 | + # this function to not break when JAX makes the flip, we check for |
| 81 | + # both here. |
| 82 | + if inspect.ismethod(x.device): |
| 83 | + return x.device() |
| 84 | + return x.device |
| 85 | + if _is_pydata_sparse_array(x): |
| 86 | + # `sparse` will gain `.device`, so check for this first. |
| 87 | + x_device = getattr(x, "device", None) |
| 88 | + if x_device is not None: |
| 89 | + return x_device |
| 90 | + # Everything but DOK has this attr. |
| 91 | + try: |
| 92 | + inner = x.data |
| 93 | + except AttributeError: |
| 94 | + return "cpu" |
| 95 | + # Return the device of the constituent array |
| 96 | + return device(inner) |
| 97 | + return x.device |
| 98 | + |
| 99 | + |
| 100 | +def _is_numpy_array(x: Array) -> bool: |
| 101 | + """Return True if `x` is a NumPy array.""" |
| 102 | + # Avoid importing NumPy if it isn't already |
| 103 | + if "numpy" not in sys.modules: |
| 104 | + return False |
| 105 | + |
| 106 | + import numpy as np # pylint: disable=import-outside-toplevel |
| 107 | + |
| 108 | + # TODO: Should we reject ndarray subclasses? |
| 109 | + return isinstance(x, (np.ndarray, np.generic)) and not _is_jax_zero_gradient_array( |
| 110 | + x |
| 111 | + ) |
| 112 | + |
| 113 | + |
| 114 | +def _is_dask_array(x: Array) -> bool: |
| 115 | + """Return True if `x` is a dask.array Array.""" |
| 116 | + # Avoid importing dask if it isn't already |
| 117 | + if "dask.array" not in sys.modules: |
| 118 | + return False |
| 119 | + |
| 120 | + # pylint: disable=import-error, import-outside-toplevel |
| 121 | + import dask.array # type: ignore[import-not-found] |
| 122 | + |
| 123 | + return isinstance(x, dask.array.Array) |
| 124 | + |
| 125 | + |
| 126 | +def _is_jax_zero_gradient_array(x: Array) -> bool: |
| 127 | + """Return True if `x` is a zero-gradient array. |
| 128 | +
|
| 129 | + These arrays are a design quirk of Jax that may one day be removed. |
| 130 | + See https://github.com/google/jax/issues/20620. |
| 131 | + """ |
| 132 | + if "numpy" not in sys.modules or "jax" not in sys.modules: |
| 133 | + return False |
| 134 | + |
| 135 | + # pylint: disable=import-error, import-outside-toplevel |
| 136 | + import jax # type: ignore[import-not-found] |
| 137 | + import numpy as np # pylint: disable=import-outside-toplevel |
| 138 | + |
| 139 | + return isinstance(x, np.ndarray) and x.dtype == jax.float0 |
| 140 | + |
| 141 | + |
| 142 | +def _is_jax_array(x: Array) -> bool: |
| 143 | + """Return True if `x` is a JAX array.""" |
| 144 | + # Avoid importing jax if it isn't already |
| 145 | + if "jax" not in sys.modules: |
| 146 | + return False |
| 147 | + |
| 148 | + # pylint: disable=import-error, import-outside-toplevel |
| 149 | + import jax |
| 150 | + |
| 151 | + return isinstance(x, jax.Array) or _is_jax_zero_gradient_array(x) |
| 152 | + |
| 153 | + |
| 154 | +def _is_pydata_sparse_array(x: Array) -> bool: |
| 155 | + """Return True if `x` is an array from the `sparse` package.""" |
| 156 | + |
| 157 | + # Avoid importing jax if it isn't already |
| 158 | + if "sparse" not in sys.modules: |
| 159 | + return False |
| 160 | + |
| 161 | + # pylint: disable=import-error, import-outside-toplevel |
| 162 | + import sparse # type: ignore[import-not-found] |
| 163 | + |
| 164 | + # TODO: Account for other backends. |
| 165 | + return isinstance(x, sparse.SparseArray) |
0 commit comments