From 01f4f01fcd014e3d411c42201d89776c98e4997f Mon Sep 17 00:00:00 2001 From: Vladislav Perevezentsev Date: Tue, 7 Apr 2026 04:05:45 -0700 Subject: [PATCH 01/46] Update _accumulation.py doc to Sphinx format --- dpnp/tensor/_accumulation.py | 369 ++++++++++++++++++----------------- 1 file changed, 192 insertions(+), 177 deletions(-) diff --git a/dpnp/tensor/_accumulation.py b/dpnp/tensor/_accumulation.py index 069eb870f78..81baf16a08e 100644 --- a/dpnp/tensor/_accumulation.py +++ b/dpnp/tensor/_accumulation.py @@ -233,67 +233,72 @@ def cumulative_sum( x, /, *, axis=None, dtype=None, include_initial=False, out=None ): """ - cumulative_sum(x, /, *, axis=None, dtype=None, include_initial=False, - out=None) - Calculates the cumulative sum of elements in the input array `x`. - Args: - x (usm_ndarray): - input array. - axis (Optional[int]): - axis along which cumulative sum must be computed. - If `None`, the sum is computed over the entire array. - If `x` is a one-dimensional array, providing an `axis` is optional; - however, if `x` has more than one dimension, providing an `axis` - is required. - Default: `None`. - dtype (Optional[dtype]): - data type of the returned array. If `None`, the default data - type is inferred from the "kind" of the input array data type. - - * If `x` has a real- or complex-valued floating-point data - type, the returned array will have the same data type as - `x`. - * If `x` has signed integral data type, the returned array - will have the default signed integral type for the device - where input array `x` is allocated. - * If `x` has unsigned integral data type, the returned array - will have the default unsigned integral type for the device - where input array `x` is allocated. - * If `x` has a boolean data type, the returned array will - have the default signed integral type for the device - where input array `x` is allocated. - - If the data type (either specified or resolved) differs from the - data type of `x`, the input array elements are cast to the - specified data type before computing the cumulative sum. - Default: `None`. - include_initial (bool): - boolean indicating whether to include the initial value (i.e., the - additive identity, zero) as the first value along the provided axis - in the output. Default: `False`. - out (Optional[usm_ndarray]): - the array into which the result is written. - The data type of `out` must match the expected shape and the - expected data type of the result or (if provided) `dtype`. - If `None` then a new array is returned. Default: `None`. - - Returns: - usm_ndarray: - an array containing cumulative sums. The returned array has the data - type as described in the `dtype` parameter description above. - - The returned array shape is determined as follows: - - * If `include_initial` is `False`, the returned array will - have the same shape as `x` - * If `include_initial` is `True`, the returned array will - have the same shape as `x` except the axis along which the - cumulative sum is calculated, which will have size `N+1` - - where `N` is the size of the axis the cumulative sums are computed - along. + Parameters + ---------- + x : usm_ndarray + input array. + axis : int, optional + axis along which cumulative sum must be computed. + If `None`, the sum is computed over the entire array. + If `x` is a one-dimensional array, providing an `axis` is optional; + however, if `x` has more than one dimension, providing an `axis` + is required. + + Default: ``None``. + dtype : dtype, optional + data type of the returned array. If `None`, the default data + type is inferred from the "kind" of the input array data type. + + * If `x` has a real- or complex-valued floating-point data + type, the returned array will have the same data type as + `x`. + * If `x` has signed integral data type, the returned array + will have the default signed integral type for the device + where input array `x` is allocated. + * If `x` has unsigned integral data type, the returned array + will have the default unsigned integral type for the device + where input array `x` is allocated. + * If `x` has a boolean data type, the returned array will + have the default signed integral type for the device + where input array `x` is allocated. + + If the data type (either specified or resolved) differs from the + data type of `x`, the input array elements are cast to the + specified data type before computing the cumulative sum. + + Default: ``None``. + include_initial : bool, optional + boolean indicating whether to include the initial value (i.e., the + additive identity, zero) as the first value along the provided axis + in the output. + + Default: ``False``. + out : usm_ndarray, optional + the array into which the result is written. + The data type of `out` must match the expected shape and the + expected data type of the result or (if provided) `dtype`. + If `None` then a new array is returned. + + Default: ``None``. + + Returns + ------- + out : usm_ndarray + an array containing cumulative sums. The returned array has the data + type as described in the `dtype` parameter description above. + + The returned array shape is determined as follows: + + * If `include_initial` is `False`, the returned array will + have the same shape as `x` + * If `include_initial` is `True`, the returned array will + have the same shape as `x` except the axis along which the + cumulative sum is calculated, which will have size `N+1` + + where `N` is the size of the axis the cumulative sums are computed + along. """ return _accumulate_common( x, @@ -312,68 +317,73 @@ def cumulative_prod( x, /, *, axis=None, dtype=None, include_initial=False, out=None ): """ - cumulative_prod(x, /, *, axis=None, dtype=None, include_initial=False, - out=None) - Calculates the cumulative product of elements in the input array `x`. - Args: - x (usm_ndarray): - input array. - axis (Optional[int]): - axis along which cumulative product must be computed. - If `None`, the product is computed over the entire array. - If `x` is a one-dimensional array, providing an `axis` is optional; - however, if `x` has more than one dimension, providing an `axis` - is required. - Default: `None`. - dtype (Optional[dtype]): - data type of the returned array. If `None`, the default data - type is inferred from the "kind" of the input array data type. - - * If `x` has a real- or complex-valued floating-point data - type, the returned array will have the same data type as - `x`. - * If `x` has signed integral data type, the returned array - will have the default signed integral type for the device - where input array `x` is allocated. - * If `x` has unsigned integral data type, the returned array - will have the default unsigned integral type for the device - where input array `x` is allocated. - * If `x` has a boolean data type, the returned array will - have the default signed integral type for the device - where input array `x` is allocated. - - If the data type (either specified or resolved) differs from the - data type of `x`, the input array elements are cast to the - specified data type before computing the cumulative product. - Default: `None`. - include_initial (bool): - boolean indicating whether to include the initial value (i.e., the - additive identity, zero) as the first value along the provided - axis in the output. Default: `False`. - out (Optional[usm_ndarray]): - the array into which the result is written. - The data type of `out` must match the expected shape and the - expected data type of the result or (if provided) `dtype`. - If `None` then a new array is returned. Default: `None`. - - Returns: - usm_ndarray: - an array containing cumulative products. The returned array has - the data type as described in the `dtype` parameter description - above. - - The returned array shape is determined as follows: - - * If `include_initial` is `False`, the returned array will - have the same shape as `x` - * If `include_initial` is `True`, the returned array will - have the same shape as `x` except the axis along which the - cumulative product is calculated, which will have size `N+1` - - where `N` is the size of the axis the cumulative products are - computed along. + Parameters + ---------- + x : usm_ndarray + input array. + axis : int, optional + axis along which cumulative product must be computed. + If `None`, the product is computed over the entire array. + If `x` is a one-dimensional array, providing an `axis` is optional; + however, if `x` has more than one dimension, providing an `axis` + is required. + + Default: ``None``. + dtype : dtype, optional + data type of the returned array. If `None`, the default data + type is inferred from the "kind" of the input array data type. + + * If `x` has a real- or complex-valued floating-point data + type, the returned array will have the same data type as + `x`. + * If `x` has signed integral data type, the returned array + will have the default signed integral type for the device + where input array `x` is allocated. + * If `x` has unsigned integral data type, the returned array + will have the default unsigned integral type for the device + where input array `x` is allocated. + * If `x` has a boolean data type, the returned array will + have the default signed integral type for the device + where input array `x` is allocated. + + If the data type (either specified or resolved) differs from the + data type of `x`, the input array elements are cast to the + specified data type before computing the cumulative product. + + Default: ``None``. + include_initial : bool, optional + boolean indicating whether to include the initial value (i.e., the + additive identity, zero) as the first value along the provided + axis in the output. + + Default: ``False``. + out : usm_ndarray, optional + the array into which the result is written. + The data type of `out` must match the expected shape and the + expected data type of the result or (if provided) `dtype`. + If `None` then a new array is returned. + + Default: ``None``. + + Returns + ------- + out : usm_ndarray + an array containing cumulative products. The returned array has + the data type as described in the `dtype` parameter description + above. + + The returned array shape is determined as follows: + + * If `include_initial` is `False`, the returned array will + have the same shape as `x` + * If `include_initial` is `True`, the returned array will + have the same shape as `x` except the axis along which the + cumulative product is calculated, which will have size `N+1` + + where `N` is the size of the axis the cumulative products are + computed along. """ return _accumulate_common( x, @@ -392,66 +402,71 @@ def cumulative_logsumexp( x, /, *, axis=None, dtype=None, include_initial=False, out=None ): """ - cumulative_logsumexp(x, /, *, axis=None, dtype=None, include_initial=False, - out=None) - Calculates the cumulative logsmumexp of elements in the input array `x`. - Args: - x (usm_ndarray): - input array. - axis (Optional[int]): - axis along which cumulative logsumexp must be computed. - If `None`, the logsumexp is computed over the entire array. - If `x` is a one-dimensional array, providing an `axis` is optional; - however, if `x` has more than one dimension, providing an `axis` - is required. - Default: `None`. - dtype (Optional[dtype]): - data type of the returned array. If `None`, the default data - type is inferred from the "kind" of the input array data type. - - * If `x` has a real- or complex-valued floating-point data - type, the returned array will have the same data type as - `x`. - * If `x` has signed integral data type, the returned array - will have the default signed integral type for the device - where input array `x` is allocated. - * If `x` has unsigned integral data type, the returned array - will have the default unsigned integral type for the device - where input array `x` is allocated. - * If `x` has a boolean data type, the returned array will - have the default signed integral type for the device - where input array `x` is allocated. - - If the data type (either specified or resolved) differs from the - data type of `x`, the input array elements are cast to the - specified data type before computing the cumulative logsumexp. - Default: `None`. - include_initial (bool): - boolean indicating whether to include the initial value (i.e., the - additive identity, zero) as the first value along the provided axis - in the output. Default: `False`. - out (Optional[usm_ndarray]): - the array into which the result is written. - The data type of `out` must match the expected shape and the - expected data type of the result or (if provided) `dtype`. - If `None` then a new array is returned. Default: `None`. - - Returns: - usm_ndarray: - an array containing cumulative logsumexp results. The returned - array has the data type as described in the `dtype` parameter - description above. - - The returned array shape is determined as follows: - - * If `include_initial` is `False`, the returned array will - have the same shape as `x` - * If `include_initial` is `True`, the returned array will - have the same shape as `x` except the axis along which the - cumulative logsumexp is calculated, which will have size - `N+1` + Parameters + ---------- + x : usm_ndarray + input array. + axis : int, optional + axis along which cumulative logsumexp must be computed. + If `None`, the logsumexp is computed over the entire array. + If `x` is a one-dimensional array, providing an `axis` is optional; + however, if `x` has more than one dimension, providing an `axis` + is required. + + Default: ``None``. + dtype : dtype, optional + data type of the returned array. If `None`, the default data + type is inferred from the "kind" of the input array data type. + + * If `x` has a real- or complex-valued floating-point data + type, the returned array will have the same data type as + `x`. + * If `x` has signed integral data type, the returned array + will have the default signed integral type for the device + where input array `x` is allocated. + * If `x` has unsigned integral data type, the returned array + will have the default unsigned integral type for the device + where input array `x` is allocated. + * If `x` has a boolean data type, the returned array will + have the default signed integral type for the device + where input array `x` is allocated. + + If the data type (either specified or resolved) differs from the + data type of `x`, the input array elements are cast to the + specified data type before computing the cumulative logsumexp. + + Default: ``None``. + include_initial : bool, optional + boolean indicating whether to include the initial value (i.e., the + additive identity, zero) as the first value along the provided axis + in the output. + + Default: ``False``. + out : usm_ndarray, optional + the array into which the result is written. + The data type of `out` must match the expected shape and the + expected data type of the result or (if provided) `dtype`. + If `None` then a new array is returned. + + Default: ``None``. + + Returns + ------- + out : usm_ndarray + an array containing cumulative logsumexp results. The returned + array has the data type as described in the `dtype` parameter + description above. + + The returned array shape is determined as follows: + + * If `include_initial` is `False`, the returned array will + have the same shape as `x` + * If `include_initial` is `True`, the returned array will + have the same shape as `x` except the axis along which the + cumulative logsumexp is calculated, which will have size + `N+1` """ return _accumulate_common( x, From ce0dbcfa458ee9abde5aba34583d0965ead22f23 Mon Sep 17 00:00:00 2001 From: Vladislav Perevezentsev Date: Tue, 7 Apr 2026 04:14:26 -0700 Subject: [PATCH 02/46] Update _array_api.py doc to Sphinx format --- dpnp/tensor/_array_api.py | 157 +++++++++++++++++--------------------- 1 file changed, 72 insertions(+), 85 deletions(-) diff --git a/dpnp/tensor/_array_api.py b/dpnp/tensor/_array_api.py index a18bc2be182..721449306db 100644 --- a/dpnp/tensor/_array_api.py +++ b/dpnp/tensor/_array_api.py @@ -107,59 +107,55 @@ def __init__(self): def capabilities(self): """ - capabilities() - - Returns a dictionary of ``dpctl``'s capabilities. + Returns a dictionary of ``dpnp.tensor``'s capabilities. The dictionary contains the following keys: ``"boolean indexing"``: - boolean indicating ``dpctl``'s support of boolean indexing. + boolean indicating ``dpnp.tensor``'s support of boolean indexing. Value: ``True`` ``"data-dependent shapes"``: - boolean indicating ``dpctl``'s support of data-dependent shapes. + boolean indicating ``dpnp.tensor``'s support of data-dependent shapes. Value: ``True`` ``max dimensions``: - integer indication the maximum array dimension supported by ``dpctl``. + integer indication the maximum array dimension supported by ``dpnp.tensor``. Value: ``None`` - Returns: - dict: - dictionary of ``dpctl``'s capabilities + Returns + ------- + capabilities : dict + dictionary of ``dpnp.tensor``'s capabilities """ return self._capabilities.copy() def default_device(self): - """ - default_device() - - Returns the default SYCL device. - """ + """Returns the default SYCL device.""" return dpctl.select_default_device() def default_dtypes(self, *, device=None): """ - default_dtypes(*, device=None) - Returns a dictionary of default data types for ``device``. - Args: - device (Optional[:class:`dpctl.SyclDevice`, :class:`dpctl.SyclQueue`, :class:`dpctl.tensor.Device`, str]): - array API concept of device used in getting default data types. - ``device`` can be ``None`` (in which case the default device - is used), an instance of :class:`dpctl.SyclDevice`, an instance - of :class:`dpctl.SyclQueue`, a :class:`dpctl.tensor.Device` - object returned by :attr:`dpctl.tensor.usm_ndarray.device`, or - a filter selector string. - Default: ``None``. - - Returns: - dict: - a dictionary of default data types for ``device``: - - - ``"real floating"``: dtype - - ``"complex floating"``: dtype - - ``"integral"``: dtype - - ``"indexing"``: dtype + Parameters + ---------- + device : {:class:`dpctl.SyclDevice`, :class:`dpctl.SyclQueue`, :class:`dpnp.tensor.Device`, str}, optional + array API concept of device used in getting default data types. + ``device`` can be ``None`` (in which case the default device + is used), an instance of :class:`dpctl.SyclDevice`, an instance + of :class:`dpctl.SyclQueue`, a :class:`dpnp.tensor.Device` + object returned by :attr:`dpnp.tensor.usm_ndarray.device`, or + a filter selector string. + + Default: ``None``. + + Returns + ------- + dtypes : dict + a dictionary of default data types for ``device``: + + - ``"real floating"``: dtype + - ``"complex floating"``: dtype + - ``"integral"``: dtype + - ``"indexing"``: dtype """ device = _get_device_impl(device) return { @@ -171,8 +167,6 @@ def default_dtypes(self, *, device=None): def dtypes(self, *, device=None, kind=None): """ - dtypes(*, device=None, kind=None) - Returns a dictionary of all Array API data types of a specified ``kind`` supported by ``device``. @@ -180,44 +174,46 @@ def dtypes(self, *, device=None, kind=None): `Python Array API `_ specification. - Args: - device (Optional[:class:`dpctl.SyclDevice`, :class:`dpctl.SyclQueue`, :class:`dpctl.tensor.Device`, str]): - array API concept of device used in getting default data types. - ``device`` can be ``None`` (in which case the default device is - used), an instance of :class:`dpctl.SyclDevice`, an instance of - :class:`dpctl.SyclQueue`, a :class:`dpctl.tensor.Device` - object returned by :attr:`dpctl.tensor.usm_ndarray.device`, or - a filter selector string. - Default: ``None``. - - kind (Optional[str, Tuple[str, ...]]): - data type kind. - - - if ``kind`` is ``None``, returns a dictionary of all data - types supported by `device` - - if ``kind`` is a string, returns a dictionary containing the - data types belonging to the data type kind specified. - - Supports: - - * ``"bool"`` - * ``"signed integer"`` - * ``"unsigned integer"`` - * ``"integral"`` - * ``"real floating"`` - * ``"complex floating"`` - * ``"numeric"`` - - - if ``kind`` is a tuple, the tuple represents a union of - ``kind`` strings, and returns a dictionary containing data - types corresponding to the-specified union. - - Default: ``None``. - - Returns: - dict: - a dictionary of the supported data types of the specified - ``kind`` + Parameters + ---------- + device : {:class:`dpctl.SyclDevice`, :class:`dpctl.SyclQueue`, :class:`dpnp.tensor.Device`, str}, optional + array API concept of device used in getting default data types. + ``device`` can be ``None`` (in which case the default device is + used), an instance of :class:`dpctl.SyclDevice`, an instance of + :class:`dpctl.SyclQueue`, a :class:`dpnp.tensor.Device` + object returned by :attr:`dpnp.tensor.usm_ndarray.device`, or + a filter selector string. + + Default: ``None``. + kind : {str, Tuple[str, ...]}, optional + data type kind. + + - if ``kind`` is ``None``, returns a dictionary of all data + types supported by `device` + - if ``kind`` is a string, returns a dictionary containing the + data types belonging to the data type kind specified. + + Supports: + + * ``"bool"`` + * ``"signed integer"`` + * ``"unsigned integer"`` + * ``"integral"`` + * ``"real floating"`` + * ``"complex floating"`` + * ``"numeric"`` + + - if ``kind`` is a tuple, the tuple represents a union of + ``kind`` strings, and returns a dictionary containing data + types corresponding to the-specified union. + + Default: ``None``. + + Returns + ------- + dtypes : dict + a dictionary of the supported data types of the specified + ``kind`` """ device = _get_device_impl(device) _fp64 = device.has_aspect_fp64 @@ -236,19 +232,10 @@ def dtypes(self, *, device=None, kind=None): } def devices(self): - """ - devices() - - Returns a list of supported devices. - """ + """Returns a list of supported devices.""" return dpctl.get_devices() def __array_namespace_info__(): - """ - __array_namespace_info__() - - Returns a namespace with Array API namespace inspection utilities. - - """ + """Returns a namespace with Array API namespace inspection utilities.""" return Info() From bb18a1cf4ab3e6bc5c1fd2b62bcdd28b4a017f38 Mon Sep 17 00:00:00 2001 From: Vladislav Perevezentsev Date: Tue, 7 Apr 2026 04:22:15 -0700 Subject: [PATCH 03/46] Update _clip.py doc to Sphinx format --- dpnp/tensor/_accumulation.py | 6 ++++ dpnp/tensor/_array_api.py | 6 ++++ dpnp/tensor/_clip.py | 63 +++++++++++++++++++++--------------- 3 files changed, 49 insertions(+), 26 deletions(-) diff --git a/dpnp/tensor/_accumulation.py b/dpnp/tensor/_accumulation.py index 81baf16a08e..3f90e18a890 100644 --- a/dpnp/tensor/_accumulation.py +++ b/dpnp/tensor/_accumulation.py @@ -299,7 +299,9 @@ def cumulative_sum( where `N` is the size of the axis the cumulative sums are computed along. + """ + return _accumulate_common( x, axis, @@ -384,7 +386,9 @@ def cumulative_prod( where `N` is the size of the axis the cumulative products are computed along. + """ + return _accumulate_common( x, axis, @@ -467,7 +471,9 @@ def cumulative_logsumexp( have the same shape as `x` except the axis along which the cumulative logsumexp is calculated, which will have size `N+1` + """ + return _accumulate_common( x, axis, diff --git a/dpnp/tensor/_array_api.py b/dpnp/tensor/_array_api.py index 721449306db..9c78611245f 100644 --- a/dpnp/tensor/_array_api.py +++ b/dpnp/tensor/_array_api.py @@ -124,7 +124,9 @@ def capabilities(self): ------- capabilities : dict dictionary of ``dpnp.tensor``'s capabilities + """ + return self._capabilities.copy() def default_device(self): @@ -156,7 +158,9 @@ def default_dtypes(self, *, device=None): - ``"complex floating"``: dtype - ``"integral"``: dtype - ``"indexing"``: dtype + """ + device = _get_device_impl(device) return { "real floating": dpt.dtype(default_device_fp_type(device)), @@ -214,7 +218,9 @@ def dtypes(self, *, device=None, kind=None): dtypes : dict a dictionary of the supported data types of the specified ``kind`` + """ + device = _get_device_impl(device) _fp64 = device.has_aspect_fp64 if kind is None: diff --git a/dpnp/tensor/_clip.py b/dpnp/tensor/_clip.py index 44434fc0bb0..e74fd5b0188 100644 --- a/dpnp/tensor/_clip.py +++ b/dpnp/tensor/_clip.py @@ -271,36 +271,47 @@ def _clip_none(x, val, out, order, _binary_fn): def clip(x, /, min=None, max=None, out=None, order="K"): - """clip(x, min=None, max=None, out=None, order="K") - + """ Clips to the range [`min_i`, `max_i`] for each element `x_i` in `x`. - Args: - x (usm_ndarray): Array containing elements to clip. - Must be compatible with `min` and `max` according - to broadcasting rules. - min ({None, Union[usm_ndarray, bool, int, float, complex]}, optional): - Array containing minimum values. - Must be compatible with `x` and `max` according - to broadcasting rules. - max ({None, Union[usm_ndarray, bool, int, float, complex]}, optional): - Array containing maximum values. - Must be compatible with `x` and `min` according - to broadcasting rules. - out ({None, usm_ndarray}, optional): - Output array to populate. - Array must have the correct shape and the expected data type. - order ("C","F","A","K", optional): - Memory layout of the newly output array, if parameter `out` is - `None`. - Default: "K". - - Returns: - usm_ndarray: - An array with elements clipped to the range [`min`, `max`]. - The returned array has the same data type as `x`. + Parameters + ---------- + x : usm_ndarray + Array containing elements to clip. + Must be compatible with `min` and `max` according + to broadcasting rules. + min : {None, usm_ndarray, bool, int, float, complex}, optional + Array containing minimum values. + Must be compatible with `x` and `max` according + to broadcasting rules. + + Default: ``None``. + max : {None, usm_ndarray, bool, int, float, complex}, optional + Array containing maximum values. + Must be compatible with `x` and `min` according + to broadcasting rules. + + Default: ``None``. + out : {None, usm_ndarray}, optional + Output array to populate. + Array must have the correct shape and the expected data type. + + Default: ``None``. + order : {"C", "F", "A", "K"}, optional + Memory layout of the newly output array, if parameter `out` is + `None`. + + Default: ``"K"``. + + Returns + ------- + out : usm_ndarray + An array with elements clipped to the range [`min`, `max`]. + The returned array has the same data type as `x`. + """ + if not isinstance(x, dpt.usm_ndarray): raise TypeError( "Expected `x` to be of dpnp.tensor.usm_ndarray type, got " From 71aa23043886b8e106941e85294163f7f42370d4 Mon Sep 17 00:00:00 2001 From: Vladislav Perevezentsev Date: Tue, 7 Apr 2026 04:29:31 -0700 Subject: [PATCH 04/46] Update _copy_utils.py doc to Sphinx format --- dpnp/tensor/_copy_utils.py | 235 ++++++++++++++++++++++--------------- 1 file changed, 139 insertions(+), 96 deletions(-) diff --git a/dpnp/tensor/_copy_utils.py b/dpnp/tensor/_copy_utils.py index 39c4e9cf9fe..af0843bcbf1 100644 --- a/dpnp/tensor/_copy_utils.py +++ b/dpnp/tensor/_copy_utils.py @@ -45,7 +45,7 @@ __doc__ = ( "Implementation module for copy- and cast- operations on " - ":class:`dpctl.tensor.usm_ndarray`." + ":class:`dpnp.tensor.usm_ndarray`." ) int32_t_max = 1 + np.iinfo(np.int32).max @@ -96,7 +96,7 @@ def _copy_from_numpy(np_ary, usm_type="device", sycl_queue=None): def _copy_from_numpy_into(dst, np_ary): - """Copies `np_ary` into `dst` of type :class:`dpctl.tensor.usm_ndarray""" + """Copies `np_ary` into `dst` of type :class:`dpnp.tensor.usm_ndarray""" if not isinstance(np_ary, np.ndarray): raise TypeError(f"Expected numpy.ndarray, got {type(np_ary)}") if not isinstance(dst, dpt.usm_ndarray): @@ -137,6 +137,7 @@ def _extract_impl(ary, ary_mask, axis=0): Extract elements of ary by applying mask starting from slot dimension axis """ + if not isinstance(ary, dpt.usm_ndarray): raise TypeError( f"Expecting type dpnp.tensor.usm_ndarray, got {type(ary)}" @@ -205,6 +206,7 @@ def _get_indices_queue_usm_type(inds, queue, usm_type): For each array, the queue and usm type are appended to `queue_list` and `usm_type_list`, respectively. """ + queues = [queue] usm_types = [usm_type] any_array = False @@ -273,6 +275,7 @@ def _prepare_indices_arrays(inds, q, usm_type): with the provided usm type. All arrays are then promoted to a common integral type (if possible) before being broadcast to a common shape. """ + # scalar integers -> arrays inds = tuple( map( @@ -311,6 +314,7 @@ def _place_impl(ary, ary_mask, vals, axis=0): Extract elements of ary by applying mask starting from slot dimension axis. """ + if not isinstance(ary, dpt.usm_ndarray): raise TypeError( f"Expecting type dpnp.tensor.usm_ndarray, got {type(ary)}" @@ -539,77 +543,94 @@ def _take_multi_index(ary, inds, p, mode=0): def from_numpy(np_ary, /, *, device=None, usm_type="device", sycl_queue=None): """ - from_numpy(arg, device=None, usm_type="device", sycl_queue=None) - - Creates :class:`dpctl.tensor.usm_ndarray` from instance of + Creates :class:`dpnp.tensor.usm_ndarray` from instance of :class:`numpy.ndarray`. - Args: - arg: - Input convertible to :class:`numpy.ndarray` - device (object): array API specification of device where the - output array is created. Device can be specified by - a filter selector string, an instance of - :class:`dpctl.SyclDevice`, an instance of - :class:`dpctl.SyclQueue`, or an instance of - :class:`dpctl.tensor.Device`. If the value is ``None``, - returned array is created on the default-selected device. - Default: ``None`` - usm_type (str): The requested USM allocation type for the - output array. Recognized values are ``"device"``, - ``"shared"``, or ``"host"`` - sycl_queue (:class:`dpctl.SyclQueue`, optional): - A SYCL queue that determines output array allocation device - as well as execution placement of data movement operations. - The ``device`` and ``sycl_queue`` arguments - are equivalent. Only one of them should be specified. If both - are provided, they must be consistent and result in using the - same execution queue. Default: ``None`` - - The returned array has the same shape, and the same data type kind. - If the device does not support the data type of input array, a - closest support data type of the same kind may be returned, e.g. - input array of type ``float16`` may be upcast to ``float32`` if the - target device does not support 16-bit floating point type. + Parameters + ---------- + np_ary : array_like + Input convertible to :class:`numpy.ndarray` + device : object, optional + array API specification of device where the + output array is created. Device can be specified by + a filter selector string, an instance of + :class:`dpctl.SyclDevice`, an instance of + :class:`dpctl.SyclQueue`, or an instance of + :class:`dpnp.tensor.Device`. If the value is ``None``, + returned array is created on the default-selected device. + + Default: ``None``. + usm_type : str, optional + The requested USM allocation type for the + output array. Recognized values are ``"device"``, + ``"shared"``, or ``"host"``. + + Default: ``"device"``. + sycl_queue : dpctl.SyclQueue, optional + A SYCL queue that determines output array allocation device + as well as execution placement of data movement operations. + The ``device`` and ``sycl_queue`` arguments + are equivalent. Only one of them should be specified. If both + are provided, they must be consistent and result in using the + same execution queue. + + Default: ``None``. + + Returns + ------- + out : usm_ndarray + The returned array has the same shape, and the same data type kind. + If the device does not support the data type of input array, a + closest support data type of the same kind may be returned, e.g. + input array of type ``float16`` may be upcast to ``float32`` if the + target device does not support 16-bit floating point type. + """ + q = normalize_queue_device(sycl_queue=sycl_queue, device=device) return _copy_from_numpy(np_ary, usm_type=usm_type, sycl_queue=q) def to_numpy(usm_ary, /): """ - to_numpy(usm_ary) - - Copies content of :class:`dpctl.tensor.usm_ndarray` instance ``usm_ary`` + Copies content of :class:`dpnp.tensor.usm_ndarray` instance ``usm_ary`` into :class:`numpy.ndarray` instance of the same shape and same data type. - Args: - usm_ary (usm_ndarray): - Input array - Returns: - :class:`numpy.ndarray`: - An instance of :class:`numpy.ndarray` populated with content of - ``usm_ary`` + Parameters + ---------- + usm_ary : usm_ndarray + Input array + + Returns + ------- + out : numpy.ndarray + An instance of :class:`numpy.ndarray` populated with content of + ``usm_ary`` + """ + return _copy_to_numpy(usm_ary) def asnumpy(usm_ary): """ - asnumpy(usm_ary) - - Copies content of :class:`dpctl.tensor.usm_ndarray` instance ``usm_ary`` + Copies content of :class:`dpnp.tensor.usm_ndarray` instance ``usm_ary`` into :class:`numpy.ndarray` instance of the same shape and same data type. - Args: - usm_ary (usm_ndarray): - Input array - Returns: - :class:`numpy.ndarray`: - An instance of :class:`numpy.ndarray` populated with content - of ``usm_ary`` + Parameters + ---------- + usm_ary : usm_ndarray + Input array + + Returns + ------- + out : numpy.ndarray + An instance of :class:`numpy.ndarray` populated with content + of ``usm_ary`` + """ + return _copy_to_numpy(usm_ary) @@ -773,6 +794,7 @@ def _make_empty_like_orderK(x, dt, usm_type, dev): Returns empty array with shape and strides like `x`, with dtype `dt`, USM type `usm_type`, on device `dev`. """ + st = list(x.strides) perm = sorted( range(x.ndim), @@ -805,6 +827,7 @@ def _empty_like_orderK(x, dt, usm_type=None, dev=None): array the returned array will have the same shape and the same strides as `x`. """ + if not isinstance(x, dpt.usm_ndarray): raise TypeError(f"Expected usm_ndarray, got {type(x)}") if usm_type is None: @@ -831,6 +854,7 @@ def _from_numpy_empty_like_orderK(x, dt, usm_type, dev): array the returned array will have the same shape and the same strides as `x`. """ + if not isinstance(x, np.ndarray): raise TypeError(f"Expected numpy.ndarray, got {type(x)}") fl = x.flags @@ -975,19 +999,25 @@ def _empty_like_triple_orderK(X1, X2, X3, dt, res_shape, usm_type, dev): def copy(usm_ary, /, *, order="K"): - """copy(ary, order="K") + """ + Creates a copy of given instance of :class:`dpnp.tensor.usm_ndarray`. + + Parameters + ---------- + usm_ary : usm_ndarray + Input array + order : {"C", "F", "A", "K"}, optional + Controls the memory layout of the output array - Creates a copy of given instance of :class:`dpctl.tensor.usm_ndarray`. + Default: ``"K"``. - Args: - ary (usm_ndarray): - Input array - order (``"C"``, ``"F"``, ``"A"``, ``"K"``, optional): - Controls the memory layout of the output array - Returns: - usm_ndarray: - A copy of the input array. + Returns + ------- + out : usm_ndarray + A copy of the input array. + Notes + ----- Memory layout of the copy is controlled by ``order`` keyword, following NumPy's conventions. The ``order`` keywords can be one of the following: @@ -1005,6 +1035,7 @@ def copy(usm_ary, /, *, order="K"): - match the layout of ``usm_ary`` as closely as possible. """ + if len(order) == 0 or order[0] not in "KkAaCcFf": raise ValueError( "Unrecognized order keyword value, expecting 'K', 'A', 'F', or 'C'." @@ -1047,44 +1078,56 @@ def copy(usm_ary, /, *, order="K"): def astype( usm_ary, newdtype, /, *, order="K", casting="unsafe", copy=True, device=None ): - """astype(array, new_dtype, order="K", casting="unsafe", \ - copy=True, device=None) - - Returns a copy of the :class:`dpctl.tensor.usm_ndarray`, cast to a + """ + Returns a copy of the :class:`dpnp.tensor.usm_ndarray`, cast to a specified type. - Args: - array (usm_ndarray): - An input array. - new_dtype (dtype): - The data type of the resulting array. If `None`, gives default - floating point type supported by device where the resulting array - will be located. - order ({"C", "F", "A", "K"}, optional): - Controls memory layout of the resulting array if a copy - is returned. - casting ({'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional): - Controls what kind of data casting may occur. Please see - :meth:`numpy.ndarray.astype` for description of casting modes. - copy (bool, optional): - By default, `astype` always returns a newly allocated array. - If this keyword is set to `False`, a view of the input array - may be returned when possible. - device (object): array API specification of device where the - output array is created. Device can be specified by - a filter selector string, an instance of - :class:`dpctl.SyclDevice`, an instance of - :class:`dpctl.SyclQueue`, or an instance of - :class:`dpctl.tensor.Device`. If the value is `None`, - returned array is created on the same device as `array`. - Default: `None`. - - Returns: - usm_ndarray: - An array with requested data type. - + Parameters + ---------- + usm_ary : usm_ndarray + An input array. + newdtype : dtype + The data type of the resulting array. If `None`, gives default + floating point type supported by device where the resulting array + will be located. + order : {"C", "F", "A", "K"}, optional + Controls memory layout of the resulting array if a copy + is returned. + + Default: ``"K"``. + casting : {"no", "equiv", "safe", "same_kind", "unsafe"}, optional + Controls what kind of data casting may occur. Please see + :meth:`numpy.ndarray.astype` for description of casting modes. + + Default: ``"unsafe"``. + copy : bool, optional + By default, `astype` always returns a newly allocated array. + If this keyword is set to `False`, a view of the input array + may be returned when possible. + + Default: ``True``. + device : object, optional + array API specification of device where the + output array is created. Device can be specified by + a filter selector string, an instance of + :class:`dpctl.SyclDevice`, an instance of + :class:`dpctl.SyclQueue`, or an instance of + :class:`dpnp.tensor.Device`. If the value is `None`, + returned array is created on the same device as `usm_ary`. + + Default: ``None``. + + Returns + ------- + out : usm_ndarray + An array with requested data type. + + Notes + ----- A view can be returned, if possible, when `copy=False` is used. + """ + if not isinstance(usm_ary, dpt.usm_ndarray): return TypeError( f"Expected object of type dpt.usm_ndarray, got {type(usm_ary)}" From 550a7f90ad95b602b859dc5086adbb5aed42f90d Mon Sep 17 00:00:00 2001 From: Vladislav Perevezentsev Date: Tue, 7 Apr 2026 05:01:24 -0700 Subject: [PATCH 05/46] Update _ctors.py doc to Sphinx format --- dpnp/tensor/_ctors.py | 1144 ++++++++++++++++++++++++----------------- 1 file changed, 669 insertions(+), 475 deletions(-) diff --git a/dpnp/tensor/_ctors.py b/dpnp/tensor/_ctors.py index bff2a9537e2..cff8610315e 100644 --- a/dpnp/tensor/_ctors.py +++ b/dpnp/tensor/_ctors.py @@ -45,7 +45,7 @@ from ._device import normalize_queue_device from ._usmarray import _is_object_with_buffer_protocol -__doc__ = "Implementation of creation functions in :module:`dpctl.tensor`" +__doc__ = "Implementation of creation functions in :module:`dpnp.tensor`" _empty_tuple = () _host_set = frozenset([None]) @@ -317,6 +317,7 @@ def _cast_fill_val(fill_val, dt): Casts the Python scalar `fill_val` to another Python type coercible to the requested data type `dt`, if necessary. """ + val_type = type(fill_val) if val_type in [float, complex] and np.issubdtype(dt, np.integer): return int(fill_val.real) @@ -422,19 +423,27 @@ def _device_copy_walker(seq_o, res, _manager): def _ensure_native_dtype_device_support(dtype, dev) -> None: - """Check that dtype is natively supported by device. + """ + Check that dtype is natively supported by device. + + Parameters + ---------- + dtype : dtype + Elemental data-type. + dev : dpctl.SyclDevice + The device about which the query is being made. + + Returns + ------- + None + + Raises + ------ + ValueError + if device does not natively support this `dtype`. - Arg: - dtype: - Elemental data-type - dev (:class:`dpctl.SyclDevice`): - The device about which the query is being made. - Returns: - None - Raise: - ValueError: - if device does not natively support this `dtype`. """ + if dtype in [dpt.float64, dpt.complex128] and not dev.has_aspect_fp64: raise ValueError( f"Device {dev.name} does not provide native support " @@ -494,6 +503,7 @@ def _normalize_order(order, arr): Utility function for processing the `order` keyword of array-like constructors, which support `"K"` and `"A"` orders. """ + arr_flags = arr.flags f_contig = arr_flags["F"] c_contig = arr_flags["C"] @@ -516,6 +526,7 @@ def _to_scalar(obj, sc_ty): Raises OverflowError if obj can not be represented using the requested scalar type. """ + zd_arr = np.asarray(obj, dtype=sc_ty) return zd_arr[()] @@ -578,36 +589,53 @@ def arange( Returns evenly spaced values within the half-open interval [start, stop) as a one-dimensional array. - Args: - start: - Starting point of the interval - stop: - Ending point of the interval. Default: ``None`` - step: Increment of the returned sequence. Default: ``1`` - dtype: Output array data type. Default: ``None`` - device (optional): array API concept of device where the output array - is created. ``device`` can be ``None``, a oneAPI filter selector - string, an instance of :class:`dpctl.SyclDevice` corresponding to - a non-partitioned SYCL device, an instance of - :class:`dpctl.SyclQueue`, or a :class:`dpctl.tensor.Device` object - returned by :attr:`dpctl.tensor.usm_ndarray.device`. - Default: ``None`` - usm_type (``"device"``, ``"shared"``, ``"host"``, optional): - The type of SYCL USM allocation for the output array. - Default: ``"device"`` - sycl_queue (:class:`dpctl.SyclQueue`, optional): - The SYCL queue to use - for output array allocation and copying. ``sycl_queue`` and - ``device`` are complementary arguments, i.e. use one or another. - If both are specified, a :exc:`TypeError` is raised unless both - imply the same underlying SYCL queue to be used. If both are - ``None``, a cached queue targeting default-selected device is - used for allocation and population. Default: ``None`` + Parameters + ---------- + start : scalar + Starting point of the interval + stop : scalar, optional + Ending point of the interval. + + Default: ``None``. + step : scalar, optional + Increment of the returned sequence. + + Default: ``1``. + dtype : dtype, optional + Output array data type. + + Default: ``None``. + device : object, optional + array API concept of device where the output array + is created. ``device`` can be ``None``, a oneAPI filter selector + string, an instance of :class:`dpctl.SyclDevice` corresponding to + a non-partitioned SYCL device, an instance of + :class:`dpctl.SyclQueue`, or a :class:`dpnp.tensor.Device` object + returned by :attr:`dpnp.tensor.usm_ndarray.device`. + + Default: ``None``. + usm_type : {"device", "shared", "host"}, optional + The type of SYCL USM allocation for the output array. + + Default: ``"device"``. + sycl_queue : dpctl.SyclQueue, optional + The SYCL queue to use + for output array allocation and copying. ``sycl_queue`` and + ``device`` are complementary arguments, i.e. use one or another. + If both are specified, a :exc:`TypeError` is raised unless both + imply the same underlying SYCL queue to be used. If both are + ``None``, a cached queue targeting default-selected device is + used for allocation and population. + + Default: ``None``. + + Returns + ------- + out : usm_ndarray + Array populated with evenly spaced values. - Returns: - usm_ndarray: - Array populated with evenly spaced values. """ + if stop is None: stop = start start = 0 @@ -686,51 +714,67 @@ def asarray( order="K", ): """ - Converts input object to :class:`dpctl.tensor.usm_ndarray`. - - Args: - obj: Python object to convert. Can be an instance of - :class:`dpctl.tensor.usm_ndarray`, - an object representing SYCL USM allocation and implementing - ``__sycl_usm_array_interface__`` protocol, an instance - of :class:`numpy.ndarray`, an object supporting Python buffer - protocol, a Python scalar, or a (possibly nested) sequence of - Python scalars. - dtype (data type, optional): - output array data type. If ``dtype`` is - ``None``, the output array data type is inferred from data types in - ``obj``. Default: ``None`` - copy (`bool`, optional): - boolean indicating whether or not to copy the - input. If ``True``, always creates a copy. If ``False``, the - need to copy raises :exc:`ValueError`. If ``None``, tries to reuse - existing memory allocations if possible, but allows to perform - a copy otherwise. Default: ``None`` - order (``"C"``, ``"F"``, ``"A"``, ``"K"``, optional): - memory layout of the output array. Default: ``"K"`` - device (optional): array API concept of device where the output array - is created. ``device`` can be ``None``, a oneAPI filter selector - string, an instance of :class:`dpctl.SyclDevice` corresponding to - a non-partitioned SYCL device, an instance of - :class:`dpctl.SyclQueue`, or a :class:`dpctl.tensor.Device` object - returned by :attr:`dpctl.tensor.usm_ndarray.device`. - Default: ``None`` - usm_type (``"device"``, ``"shared"``, ``"host"``, optional): - The type of SYCL USM allocation for the output array. - Default: ``"device"`` - sycl_queue (:class:`dpctl.SyclQueue`, optional): - The SYCL queue to use - for output array allocation and copying. ``sycl_queue`` and - ``device`` are complementary arguments, i.e. use one or another. - If both are specified, a :exc:`TypeError` is raised unless both - imply the same underlying SYCL queue to be used. If both are - ``None``, a cached queue targeting default-selected device is - used for allocation and population. Default: ``None`` + Converts input object to :class:`dpnp.tensor.usm_ndarray`. + + Parameters + ---------- + obj : array_like + Python object to convert. Can be an instance of + :class:`dpnp.tensor.usm_ndarray`, + an object representing SYCL USM allocation and implementing + ``__sycl_usm_array_interface__`` protocol, an instance + of :class:`numpy.ndarray`, an object supporting Python buffer + protocol, a Python scalar, or a (possibly nested) sequence of + Python scalars. + dtype : dtype, optional + output array data type. If ``dtype`` is + ``None``, the output array data type is inferred from data types in + ``obj``. + + Default: ``None``. + copy : bool, optional + boolean indicating whether or not to copy the + input. If ``True``, always creates a copy. If ``False``, the + need to copy raises :exc:`ValueError`. If ``None``, tries to reuse + existing memory allocations if possible, but allows to perform + a copy otherwise. + + Default: ``None``. + order : {"C", "F", "A", "K"}, optional + memory layout of the output array. + + Default: ``"K"``. + device : object, optional + array API concept of device where the output array + is created. ``device`` can be ``None``, a oneAPI filter selector + string, an instance of :class:`dpctl.SyclDevice` corresponding to + a non-partitioned SYCL device, an instance of + :class:`dpctl.SyclQueue`, or a :class:`dpnp.tensor.Device` object + returned by :attr:`dpnp.tensor.usm_ndarray.device`. + + Default: ``None``. + usm_type : {"device", "shared", "host"}, optional + The type of SYCL USM allocation for the output array. + + Default: ``"device"``. + sycl_queue : dpctl.SyclQueue, optional + The SYCL queue to use + for output array allocation and copying. ``sycl_queue`` and + ``device`` are complementary arguments, i.e. use one or another. + If both are specified, a :exc:`TypeError` is raised unless both + imply the same underlying SYCL queue to be used. If both are + ``None``, a cached queue targeting default-selected device is + used for allocation and population. + + Default: ``None``. + + Returns + ------- + out : usm_ndarray + Array created from input object. - Returns: - usm_ndarray: - Array created from input object. """ + # 1. Check that copy is a valid keyword if copy not in [None, True, False]: raise TypeError( @@ -886,42 +930,55 @@ def empty( sycl_queue=None, ): """ - Creates :class:`dpctl.tensor.usm_ndarray` from uninitialized + Creates :class:`dpnp.tensor.usm_ndarray` from uninitialized USM allocation. - Args: - shape (Tuple[int], int): - Dimensions of the array to be created. - dtype (optional): - data type of the array. Can be typestring, - a :class:`numpy.dtype` object, :mod:`numpy` char string, - or a NumPy scalar type. The ``None`` value creates an - array of floating point data type. Default: ``None`` - order (``"C"``, or ``F"``): - memory layout for the array. Default: ``"C"`` - device (optional): array API concept of device where the output array - is created. ``device`` can be ``None``, a oneAPI filter selector - string, an instance of :class:`dpctl.SyclDevice` corresponding to - a non-partitioned SYCL device, an instance of - :class:`dpctl.SyclQueue`, or a :class:`dpctl.tensor.Device` object - returned by :attr:`dpctl.tensor.usm_ndarray.device`. - Default: ``None`` - usm_type (``"device"``, ``"shared"``, ``"host"``, optional): - The type of SYCL USM allocation for the output array. - Default: ``"device"`` - sycl_queue (:class:`dpctl.SyclQueue`, optional): - The SYCL queue to use - for output array allocation and copying. ``sycl_queue`` and - ``device`` are complementary arguments, i.e. use one or another. - If both are specified, a :exc:`TypeError` is raised unless both - imply the same underlying SYCL queue to be used. If both are - ``None``, a cached queue targeting default-selected device is - used for allocation and population. Default: ``None`` + Parameters + ---------- + shape : {int, tuple of ints} + Dimensions of the array to be created. + dtype : dtype, optional + data type of the array. Can be typestring, + a :class:`numpy.dtype` object, :mod:`numpy` char string, + or a NumPy scalar type. The ``None`` value creates an + array of floating point data type. + + Default: ``None``. + order : {"C", "F"}, optional + memory layout for the array. + + Default: ``"C"``. + device : object, optional + array API concept of device where the output array + is created. ``device`` can be ``None``, a oneAPI filter selector + string, an instance of :class:`dpctl.SyclDevice` corresponding to + a non-partitioned SYCL device, an instance of + :class:`dpctl.SyclQueue`, or a :class:`dpnp.tensor.Device` object + returned by :attr:`dpnp.tensor.usm_ndarray.device`. + + Default: ``None``. + usm_type : {"device", "shared", "host"}, optional + The type of SYCL USM allocation for the output array. + + Default: ``"device"``. + sycl_queue : dpctl.SyclQueue, optional + The SYCL queue to use + for output array allocation and copying. ``sycl_queue`` and + ``device`` are complementary arguments, i.e. use one or another. + If both are specified, a :exc:`TypeError` is raised unless both + imply the same underlying SYCL queue to be used. If both are + ``None``, a cached queue targeting default-selected device is + used for allocation and population. + + Default: ``None``. + + Returns + ------- + out : usm_ndarray + Created empty array. - Returns: - usm_ndarray: - Created empty array. """ + if not isinstance(order, str) or len(order) == 0 or order[0] not in "CcFf": raise ValueError( "Unrecognized order keyword value, expecting 'F' or 'C'." @@ -945,41 +1002,54 @@ def empty_like( x, /, *, dtype=None, order="K", device=None, usm_type=None, sycl_queue=None ): """ - Returns an uninitialized :class:`dpctl.tensor.usm_ndarray` with the + Returns an uninitialized :class:`dpnp.tensor.usm_ndarray` with the same `shape` as the input array `x`. - Args: - x (usm_ndarray): - Input array from which to derive the output array shape. - dtype (optional): - data type of the array. Can be a typestring, - a :class:`numpy.dtype` object, NumPy char string, - or a NumPy scalar type. Default: ``None`` - order ("C", "F", "A", or "K"): - memory layout for the array. Default: ``"K"`` - device (optional): array API concept of device where the output array - is created. ``device`` can be ``None``, a oneAPI filter selector - string, an instance of :class:`dpctl.SyclDevice` corresponding to - a non-partitioned SYCL device, an instance of - :class:`dpctl.SyclQueue`, or a :class:`dpctl.tensor.Device` object - returned by :attr:`dpctl.tensor.usm_ndarray.device`. - Default: ``None`` - usm_type (``"device"``, ``"shared"``, ``"host"``, optional): - The type of SYCL USM allocation for the output array. - Default: ``"device"`` - sycl_queue (:class:`dpctl.SyclQueue`, optional): - The SYCL queue to use - for output array allocation and copying. ``sycl_queue`` and - ``device`` are complementary arguments, i.e. use one or another. - If both are specified, a :exc:`TypeError` is raised unless both - imply the same underlying SYCL queue to be used. If both are - ``None``, a cached queue targeting default-selected device is - used for allocation. Default: ``None`` + Parameters + ---------- + x : usm_ndarray + Input array from which to derive the output array shape. + dtype : dtype, optional + data type of the array. Can be a typestring, + a :class:`numpy.dtype` object, NumPy char string, + or a NumPy scalar type. + + Default: ``None``. + order : {"C", "F", "A", "K"}, optional + memory layout for the array. + + Default: ``"K"``. + device : object, optional + array API concept of device where the output array + is created. ``device`` can be ``None``, a oneAPI filter selector + string, an instance of :class:`dpctl.SyclDevice` corresponding to + a non-partitioned SYCL device, an instance of + :class:`dpctl.SyclQueue`, or a :class:`dpnp.tensor.Device` object + returned by :attr:`dpnp.tensor.usm_ndarray.device`. + + Default: ``None``. + usm_type : {"device", "shared", "host"}, optional + The type of SYCL USM allocation for the output array. + + Default: ``"device"``. + sycl_queue : dpctl.SyclQueue, optional + The SYCL queue to use + for output array allocation and copying. ``sycl_queue`` and + ``device`` are complementary arguments, i.e. use one or another. + If both are specified, a :exc:`TypeError` is raised unless both + imply the same underlying SYCL queue to be used. If both are + ``None``, a cached queue targeting default-selected device is + used for allocation. + + Default: ``None``. + + Returns + ------- + out : usm_ndarray + Created empty array with uninitialized memory. - Returns: - usm_ndarray: - Created empty array with uninitialized memory. """ + if not isinstance(x, dpt.usm_ndarray): raise TypeError(f"Expected instance of dpt.usm_ndarray, got {type(x)}.") if ( @@ -1030,54 +1100,66 @@ def eye( sycl_queue=None, ): """ - eye(n_rows, n_cols=None, /, *, k=0, dtype=None, \ - device=None, usm_type="device", sycl_queue=None) - - Creates :class:`dpctl.tensor.usm_ndarray` with ones on the `k`-th + Creates :class:`dpnp.tensor.usm_ndarray` with ones on the `k`-th diagonal. - Args: - n_rows (int): - number of rows in the output array. - n_cols (int, optional): - number of columns in the output array. If ``None``, - ``n_cols = n_rows``. Default: ``None`` - k (int): - index of the diagonal, with ``0`` as the main diagonal. - A positive value of ``k`` is a superdiagonal, a negative value - is a subdiagonal. - Raises :exc:`TypeError` if ``k`` is not an integer. - Default: ``0`` - dtype (optional): - data type of the array. Can be typestring, - a :class:`numpy.dtype` object, :mod:`numpy` char string, or - a NumPy scalar type. Default: ``None`` - order ("C" or "F"): - memory layout for the array. Default: ``"C"`` - device (optional): - array API concept of device where the output array - is created. ``device`` can be ``None``, a oneAPI filter selector - string, an instance of :class:`dpctl.SyclDevice` corresponding to - a non-partitioned SYCL device, an instance of - :class:`dpctl.SyclQueue`, or a :class:`dpctl.tensor.Device` object - returned by :attr:`dpctl.tensor.usm_ndarray.device`. - Default: ``None`` - usm_type (``"device"``, ``"shared"``, ``"host"``, optional): - The type of SYCL USM allocation for the output array. - Default: ``"device"`` - sycl_queue (:class:`dpctl.SyclQueue`, optional): - The SYCL queue to use - for output array allocation and copying. ``sycl_queue`` and - ``device`` are complementary arguments, i.e. use one or another. - If both are specified, a :exc:`TypeError` is raised unless both - imply the same underlying SYCL queue to be used. If both are - ``None``, a cached queue targeting default-selected device is - used for allocation and population. Default: ``None`` + Parameters + ---------- + n_rows : int + number of rows in the output array. + n_cols : int, optional + number of columns in the output array. If ``None``, + ``n_cols = n_rows``. + + Default: ``None``. + k : int, optional + index of the diagonal, with ``0`` as the main diagonal. + A positive value of ``k`` is a superdiagonal, a negative value + is a subdiagonal. + Raises :exc:`TypeError` if ``k`` is not an integer. + + Default: ``0``. + dtype : dtype, optional + data type of the array. Can be typestring, + a :class:`numpy.dtype` object, :mod:`numpy` char string, or + a NumPy scalar type. + + Default: ``None``. + order : {"C", "F"}, optional + memory layout for the array. + + Default: ``"C"``. + device : object, optional + array API concept of device where the output array + is created. ``device`` can be ``None``, a oneAPI filter selector + string, an instance of :class:`dpctl.SyclDevice` corresponding to + a non-partitioned SYCL device, an instance of + :class:`dpctl.SyclQueue`, or a :class:`dpnp.tensor.Device` object + returned by :attr:`dpnp.tensor.usm_ndarray.device`. + + Default: ``None``. + usm_type : {"device", "shared", "host"}, optional + The type of SYCL USM allocation for the output array. + + Default: ``"device"``. + sycl_queue : dpctl.SyclQueue, optional + The SYCL queue to use + for output array allocation and copying. ``sycl_queue`` and + ``device`` are complementary arguments, i.e. use one or another. + If both are specified, a :exc:`TypeError` is raised unless both + imply the same underlying SYCL queue to be used. If both are + ``None``, a cached queue targeting default-selected device is + used for allocation and population. + + Default: ``None``. + + Returns + ------- + out : usm_ndarray + A diagonal matrix. - Returns: - usm_ndarray: - A diagonal matrix. """ + if not isinstance(order, str) or len(order) == 0 or order[0] not in "CcFf": raise ValueError( "Unrecognized order keyword value, expecting 'F' or 'C'." @@ -1135,42 +1217,56 @@ def full( sycl_queue=None, ): """ - Returns a new :class:`dpctl.tensor.usm_ndarray` having a specified + Returns a new :class:`dpnp.tensor.usm_ndarray` having a specified shape and filled with `fill_value`. - Args: - shape (tuple): - Dimensions of the array to be created. - fill_value (int,float,complex,usm_ndarray): - fill value - dtype (optional): data type of the array. Can be typestring, - a :class:`numpy.dtype` object, :mod:`numpy` char string, - or a NumPy scalar type. Default: ``None`` - order ("C", or "F"): - memory layout for the array. Default: ``"C"`` - device (optional): array API concept of device where the output array - is created. ``device`` can be ``None``, a oneAPI filter selector - string, an instance of :class:`dpctl.SyclDevice` corresponding to - a non-partitioned SYCL device, an instance of - :class:`dpctl.SyclQueue`, or a :class:`dpctl.tensor.Device` object - returned by :attr:`dpctl.tensor.usm_ndarray.device`. - Default: ``None`` - usm_type (``"device"``, ``"shared"``, ``"host"``, optional): - The type of SYCL USM allocation for the output array. - Default: ``"device"`` - sycl_queue (:class:`dpctl.SyclQueue`, optional): - The SYCL queue to use - for output array allocation and copying. ``sycl_queue`` and - ``device`` are complementary arguments, i.e. use one or another. - If both are specified, a :exc:`TypeError` is raised unless both - imply the same underlying SYCL queue to be used. If both are - ``None``, a cached queue targeting default-selected device is - used for allocation and population. Default: ``None`` + Parameters + ---------- + shape : {int, tuple of ints} + Dimensions of the array to be created. + fill_value : {int, float, complex, usm_ndarray} + fill value + dtype : dtype, optional + data type of the array. Can be typestring, + a :class:`numpy.dtype` object, :mod:`numpy` char string, + or a NumPy scalar type. + + Default: ``None``. + order : {"C", "F"}, optional + memory layout for the array. + + Default: ``"C"``. + device : object, optional + array API concept of device where the output array + is created. ``device`` can be ``None``, a oneAPI filter selector + string, an instance of :class:`dpctl.SyclDevice` corresponding to + a non-partitioned SYCL device, an instance of + :class:`dpctl.SyclQueue`, or a :class:`dpnp.tensor.Device` object + returned by :attr:`dpnp.tensor.usm_ndarray.device`. + + Default: ``None``. + usm_type : {"device", "shared", "host"}, optional + The type of SYCL USM allocation for the output array. + + Default: ``"device"``. + sycl_queue : dpctl.SyclQueue, optional + The SYCL queue to use + for output array allocation and copying. ``sycl_queue`` and + ``device`` are complementary arguments, i.e. use one or another. + If both are specified, a :exc:`TypeError` is raised unless both + imply the same underlying SYCL queue to be used. If both are + ``None``, a cached queue targeting default-selected device is + used for allocation and population. + + Default: ``None``. + + Returns + ------- + out : usm_ndarray + New array initialized with given value. - Returns: - usm_ndarray: - New array initialized with given value. """ + if not isinstance(order, str) or len(order) == 0 or order[0] not in "CcFf": raise ValueError( "Unrecognized order keyword value, expecting 'F' or 'C'." @@ -1230,47 +1326,59 @@ def full_like( usm_type=None, sycl_queue=None, ): - """full_like(x, fill_value, dtype=None, order="K", \ - device=None, usm_type=None, sycl_queue=None) - - Returns a new :class:`dpctl.tensor.usm_ndarray` filled with `fill_value` + """ + Returns a new :class:`dpnp.tensor.usm_ndarray` filled with `fill_value` and having the same `shape` as the input array `x`. - Args: - x (usm_ndarray): Input array from which to derive the output array - shape. - fill_value: the value to fill output array with - dtype (optional): - data type of the array. Can be typestring, - a :class:`numpy.dtype` object, :mod:`numpy` char string, or a - NumPy scalar type. If ``dtype`` is ``None``, the output array data - type is inferred from ``x``. Default: ``None`` - order ("C", "F", "A", or "K"): - memory layout for the array. Default: ``"K"`` - device (optional): - array API concept of device where the output array - is created. ``device`` can be ``None``, a oneAPI filter selector - string, an instance of :class:`dpctl.SyclDevice` corresponding to - a non-partitioned SYCL device, an instance of - :class:`dpctl.SyclQueue`, or a :class:`dpctl.tensor.Device` object - returned by :attr:`dpctl.tensor.usm_ndarray.device`. - Default: ``None`` - usm_type (``"device"``, ``"shared"``, ``"host"``, optional): - The type of SYCL USM allocation for the output array. - Default: ``"device"`` - sycl_queue (:class:`dpctl.SyclQueue`, optional): - The SYCL queue to use - for output array allocation and copying. ``sycl_queue`` and - ``device`` are complementary arguments, i.e. use one or another. - If both are specified, a :exc:`TypeError` is raised unless both - imply the same underlying SYCL queue to be used. If both are - ``None``, a cached queue targeting default-selected device is - used for allocation and population. Default: ``None`` + Parameters + ---------- + x : usm_ndarray + Input array from which to derive the output array + shape. + fill_value : scalar + the value to fill output array with + dtype : dtype, optional + data type of the array. Can be typestring, + a :class:`numpy.dtype` object, :mod:`numpy` char string, or a + NumPy scalar type. If ``dtype`` is ``None``, the output array data + type is inferred from ``x``. + + Default: ``None``. + order : {"C", "F", "A", "K"}, optional + memory layout for the array. + + Default: ``"K"``. + device : object, optional + array API concept of device where the output array + is created. ``device`` can be ``None``, a oneAPI filter selector + string, an instance of :class:`dpctl.SyclDevice` corresponding to + a non-partitioned SYCL device, an instance of + :class:`dpctl.SyclQueue`, or a :class:`dpnp.tensor.Device` object + returned by :attr:`dpnp.tensor.usm_ndarray.device`. + + Default: ``None``. + usm_type : {"device", "shared", "host"}, optional + The type of SYCL USM allocation for the output array. + + Default: ``"device"``. + sycl_queue : dpctl.SyclQueue, optional + The SYCL queue to use + for output array allocation and copying. ``sycl_queue`` and + ``device`` are complementary arguments, i.e. use one or another. + If both are specified, a :exc:`TypeError` is raised unless both + imply the same underlying SYCL queue to be used. If both are + ``None``, a cached queue targeting default-selected device is + used for allocation and population. + + Default: ``None``. + + Returns + ------- + out : usm_ndarray + New array initialized with given value. - Returns: - usm_ndarray: - New array initialized with given value. """ + if not isinstance(x, dpt.usm_ndarray): raise TypeError(f"Expected instance of dpt.usm_ndarray, got {type(x)}.") if ( @@ -1349,59 +1457,70 @@ def linspace( usm_type="device", ): """ - linspace(start, stop, num, dtype=None, device=None, endpoint=True, \ - sycl_queue=None, usm_type="device") - - Returns :class:`dpctl.tensor.usm_ndarray` array populated with + Returns :class:`dpnp.tensor.usm_ndarray` array populated with evenly spaced numbers of specified interval. - Args: - start: - the start of the interval. - stop: - the end of the interval. If the ``endpoint`` is ``False``, the - function generates ``num+1`` evenly spaced points starting - with ``start`` and ending with ``stop`` and exclude the - ``stop`` from the returned array such that the returned array - consists of evenly spaced numbers over the half-open interval - ``[start, stop)``. If ``endpoint`` is ``True``, the output - array consists of evenly spaced numbers over the closed - interval ``[start, stop]``. Default: ``True`` - num (int): - number of samples. Must be a non-negative integer; otherwise, - the function raises ``ValueError`` exception. - dtype: - output array data type. Should be a floating data type. - If ``dtype`` is ``None``, the output array must be the default - floating point data type for target device. - Default: ``None`` - device (optional): - array API concept of device where the output array - is created. ``device`` can be ``None``, a oneAPI filter selector - string, an instance of :class:`dpctl.SyclDevice` corresponding to - a non-partitioned SYCL device, an instance of - :class:`dpctl.SyclQueue`, or a :class:`dpctl.tensor.Device` object - returned by :attr:`dpctl.tensor.usm_ndarray.device`. - Default: ``None`` - usm_type (``"device"``, ``"shared"``, ``"host"``, optional): - The type of SYCL USM allocation for the output array. - Default: ``"device"`` - sycl_queue (:class:`dpctl.SyclQueue`, optional): - The SYCL queue to use - for output array allocation and copying. ``sycl_queue`` and - ``device`` are complementary arguments, i.e. use one or another. - If both are specified, a :exc:`TypeError` is raised unless both - imply the same underlying SYCL queue to be used. If both are - ``None``, a cached queue targeting default-selected device is - used for allocation and population. Default: ``None`` - endpoint: boolean indicating whether to include ``stop`` in the - interval. Default: ``True`` + Parameters + ---------- + start : scalar + the start of the interval. + stop : scalar + the end of the interval. If the ``endpoint`` is ``False``, the + function generates ``num+1`` evenly spaced points starting + with ``start`` and ending with ``stop`` and exclude the + ``stop`` from the returned array such that the returned array + consists of evenly spaced numbers over the half-open interval + ``[start, stop)``. If ``endpoint`` is ``True``, the output + array consists of evenly spaced numbers over the closed + interval ``[start, stop]``. + + Default: ``True``. + num : int + number of samples. Must be a non-negative integer; otherwise, + the function raises ``ValueError`` exception. + dtype : dtype, optional + output array data type. Should be a floating data type. + If ``dtype`` is ``None``, the output array must be the default + floating point data type for target device. + + Default: ``None``. + device : object, optional + array API concept of device where the output array + is created. ``device`` can be ``None``, a oneAPI filter selector + string, an instance of :class:`dpctl.SyclDevice` corresponding to + a non-partitioned SYCL device, an instance of + :class:`dpctl.SyclQueue`, or a :class:`dpnp.tensor.Device` object + returned by :attr:`dpnp.tensor.usm_ndarray.device`. + + Default: ``None``. + usm_type : {"device", "shared", "host"}, optional + The type of SYCL USM allocation for the output array. + + Default: ``"device"``. + sycl_queue : dpctl.SyclQueue, optional + The SYCL queue to use + for output array allocation and copying. ``sycl_queue`` and + ``device`` are complementary arguments, i.e. use one or another. + If both are specified, a :exc:`TypeError` is raised unless both + imply the same underlying SYCL queue to be used. If both are + ``None``, a cached queue targeting default-selected device is + used for allocation and population. + + Default: ``None``. + endpoint : bool, optional + boolean indicating whether to include ``stop`` in the + interval. + + Default: ``True``. + + Returns + ------- + out : usm_ndarray + Array populated with evenly spaced numbers in the requested + interval. - Returns: - usm_ndarray: - Array populated with evenly spaced numbers in the requested - interval. """ + sycl_queue = normalize_queue_device(sycl_queue=sycl_queue, device=device) dpt.validate_usm_type(usm_type, allow_none=False) if endpoint not in [True, False]: @@ -1444,16 +1563,17 @@ def meshgrid(*arrays, indexing="xy"): Creates tuple of :class:`dpctl.tensor.usm_ndarray` coordinate matrices from vectors. - Args: - arrays (usm_ndarray): - an arbitrary number of one-dimensional arrays - representing grid coordinates. Each array should have the same - numeric data type. - indexing (``"xy"``, or ``"ij"``): - Cartesian (``"xy"``) or matrix (``"ij"``) indexing of output. - If provided zero or one one-dimensional vector(s) (i.e., the - zero- and one-dimensional cases, respectively), the ``indexing`` - keyword has no effect and should be ignored. Default: ``"xy"`` + Parameters + ---------- + *arrays : usm_ndarray + an arbitrary number of one-dimensional usm_ndarrays + representing grid coordinates. Each array should have the same + numeric data type. + indexing : {"xy", "ij"}, optional + Cartesian (``"xy"``) or matrix (``"ij"``) indexing of output. + If provided zero or one one-dimensional vector(s) (i.e., the + zero- and one-dimensional cases, respectively), the ``indexing`` + keyword has no effect and should be ignored. Returns: Tuple[array]: @@ -1467,11 +1587,26 @@ def meshgrid(*arrays, indexing="xy"): ``(N0, N1, N2, ...)``. Default: ``"xy"``. - Raises: - ValueError: If vectors are not of the same data type, or are not - one-dimensional. + Returns + ------- + out : tuple of usm_ndarrays + tuple of ``N`` usm_ndarrays, where ``N`` is the number of + provided one-dimensional input usm_ndarrays. Each returned array must + have rank ``N``. + For a set of ``n`` vectors with lengths ``N0``, ``N1``, ``N2``, ... + The cartesian indexing results in usm_ndarrays of shape + ``(N1, N0, N2, ...)``, while the + matrix indexing results in usm_ndarrays of shape + ``(N0, N1, N2, ...)``. + + Raises + ------ + ValueError + If vectors are not of the same data type, or are not + one-dimensional. """ + ref_dt = None ref_unset = True for array in arrays: @@ -1523,43 +1658,55 @@ def ones( usm_type="device", sycl_queue=None, ): - """ones(shape, dtype=None, order="C", \ - device=None, usm_type="device", sycl_queue=None) - - Returns a new :class:`dpctl.tensor.usm_ndarray` having a specified + """ + Returns a new :class:`dpnp.tensor.usm_ndarray` having a specified shape and filled with ones. - Args: - shape (Tuple[int], int): - Dimensions of the array to be created. - dtype (optional): - data type of the array. Can be typestring, - a :class:`numpy.dtype` object, :mod:`numpy` char string, - or a NumPy scalar type. Default: ``None`` - order ("C", or "F"): memory layout for the array. Default: ``"C"`` - device (optional): array API concept of device where the output array - is created. ``device`` can be ``None``, a oneAPI filter selector - string, an instance of :class:`dpctl.SyclDevice` corresponding to - a non-partitioned SYCL device, an instance of - :class:`dpctl.SyclQueue`, or a :class:`dpctl.tensor.Device` object - returned by :attr:`dpctl.tensor.usm_ndarray.device`. - Default: ``None`` - usm_type (``"device"``, ``"shared"``, ``"host"``, optional): - The type of SYCL USM allocation for the output array. - Default: ``"device"`` - sycl_queue (:class:`dpctl.SyclQueue`, optional): - The SYCL queue to use - for output array allocation and copying. ``sycl_queue`` and - ``device`` are complementary arguments, i.e. use one or another. - If both are specified, a :exc:`TypeError` is raised unless both - imply the same underlying SYCL queue to be used. If both are - ``None``, a cached queue targeting default-selected device is - used for allocation and population. Default: ``None`` + Parameters + ---------- + shape : {int, tuple of ints} + Dimensions of the array to be created. + dtype : dtype, optional + data type of the array. Can be typestring, + a :class:`numpy.dtype` object, :mod:`numpy` char string, + or a NumPy scalar type. + + Default: ``None``. + order : {"C", "F"}, optional + memory layout for the array. + + Default: ``"C"``. + device : object, optional + array API concept of device where the output array + is created. ``device`` can be ``None``, a oneAPI filter selector + string, an instance of :class:`dpctl.SyclDevice` corresponding to + a non-partitioned SYCL device, an instance of + :class:`dpctl.SyclQueue`, or a :class:`dpnp.tensor.Device` object + returned by :attr:`dpnp.tensor.usm_ndarray.device`. + + Default: ``None``. + usm_type : {"device", "shared", "host"}, optional + The type of SYCL USM allocation for the output array. + + Default: ``"device"``. + sycl_queue : dpctl.SyclQueue, optional + The SYCL queue to use + for output array allocation and copying. ``sycl_queue`` and + ``device`` are complementary arguments, i.e. use one or another. + If both are specified, a :exc:`TypeError` is raised unless both + imply the same underlying SYCL queue to be used. If both are + ``None``, a cached queue targeting default-selected device is + used for allocation and population. + + Default: ``None``. + + Returns + ------- + out : usm_ndarray + Created array initialized with ones. - Returns: - usm_ndarray: - Created array initialized with ones. """ + if not isinstance(order, str) or len(order) == 0 or order[0] not in "CcFf": raise ValueError( "Unrecognized order keyword value, expecting 'F' or 'C'." @@ -1586,42 +1733,54 @@ def ones_like( x, /, *, dtype=None, order="K", device=None, usm_type=None, sycl_queue=None ): """ - Returns a new :class:`dpctl.tensor.usm_ndarray` filled with ones and + Returns a new :class:`dpnp.tensor.usm_ndarray` filled with ones and having the same `shape` as the input array `x`. - Args: - x (usm_ndarray): - Input array from which to derive the output array shape - dtype (optional): - data type of the array. Can be typestring, - a :class:`numpy.dtype` object, :mod:`numpy` char string, - or a NumPy scalar type. Default: `None` - order ("C", "F", "A", or "K"): - memory layout for the array. Default: ``"C"`` - device (optional): - array API concept of device where the output array - is created. ``device`` can be ``None``, a oneAPI filter selector - string, an instance of :class:`dpctl.SyclDevice` corresponding to - a non-partitioned SYCL device, an instance of - :class:`dpctl.SyclQueue`, or a :class:`dpctl.tensor.Device` object - returned by :attr:`dpctl.tensor.usm_ndarray.device`. - Default: ``None`` - usm_type (``"device"``, ``"shared"``, ``"host"``, optional): - The type of SYCL USM allocation for the output array. - Default: ``"device"`` - sycl_queue (:class:`dpctl.SyclQueue`, optional): - The SYCL queue to use - for output array allocation and copying. ``sycl_queue`` and - ``device`` are complementary arguments, i.e. use one or another. - If both are specified, a :exc:`TypeError` is raised unless both - imply the same underlying SYCL queue to be used. If both are - ``None``, a cached queue targeting default-selected device is - used for allocation and population. Default: ``None`` + Parameters + ---------- + x : usm_ndarray + Input array from which to derive the output array shape. + dtype : dtype, optional + data type of the array. Can be typestring, + a :class:`numpy.dtype` object, :mod:`numpy` char string, + or a NumPy scalar type. + + Default: ``None``. + order : {"C", "F", "A", "K"}, optional + memory layout for the array. + + Default: ``"K"``. + device : object, optional + array API concept of device where the output array + is created. ``device`` can be ``None``, a oneAPI filter selector + string, an instance of :class:`dpctl.SyclDevice` corresponding to + a non-partitioned SYCL device, an instance of + :class:`dpctl.SyclQueue`, or a :class:`dpnp.tensor.Device` object + returned by :attr:`dpnp.tensor.usm_ndarray.device`. + + Default: ``None``. + usm_type : {"device", "shared", "host"}, optional + The type of SYCL USM allocation for the output array. + + Default: ``None``. + sycl_queue : dpctl.SyclQueue, optional + The SYCL queue to use + for output array allocation and copying. ``sycl_queue`` and + ``device`` are complementary arguments, i.e. use one or another. + If both are specified, a :exc:`TypeError` is raised unless both + imply the same underlying SYCL queue to be used. If both are + ``None``, a cached queue targeting default-selected device is + used for allocation and population. + + Default: ``None``. + + Returns + ------- + out : usm_ndarray + New array initialized with ones. - Returns: - usm_ndarray: - New array initialized with ones. """ + if not isinstance(x, dpt.usm_ndarray): raise TypeError(f"Expected instance of dpt.usm_ndarray, got {type(x)}.") if ( @@ -1671,20 +1830,25 @@ def tril(x, /, *, k=0): The lower triangular part of the matrix is defined as the elements on and below the specified diagonal ``k``. - Args: - x (usm_ndarray): - Input array - k (int, optional): - Specifies the diagonal above which to set - elements to zero. If ``k = 0``, the diagonal is the main diagonal. - If ``k < 0``, the diagonal is below the main diagonal. - If ``k > 0``, the diagonal is above the main diagonal. - Default: ``0`` + Parameters + ---------- + x : usm_ndarray + Input array. + k : int, optional + Specifies the diagonal above which to set + elements to zero. If ``k = 0``, the diagonal is the main diagonal. + If ``k < 0``, the diagonal is below the main diagonal. + If ``k > 0``, the diagonal is above the main diagonal. + + Default: ``0``. + + Returns + ------- + out : usm_ndarray + A lower-triangular array or a stack of lower-triangular arrays. - Returns: - usm_ndarray: - A lower-triangular array or a stack of lower-triangular arrays. """ + if not isinstance(x, dpt.usm_ndarray): raise TypeError( "Expected argument of type dpnp.tensor.usm_ndarray, " @@ -1749,20 +1913,25 @@ def triu(x, /, *, k=0): The upper triangular part of the matrix is defined as the elements on and above the specified diagonal ``k``. - Args: - x (usm_ndarray): - Input array - k (int, optional): - Specifies the diagonal below which to set - elements to zero. If ``k = 0``, the diagonal is the main diagonal. - If ``k < 0``, the diagonal is below the main diagonal. - If ``k > 0``, the diagonal is above the main diagonal. - Default: ``0`` + Parameters + ---------- + x : usm_ndarray + Input array. + k : int, optional + Specifies the diagonal below which to set + elements to zero. If ``k = 0``, the diagonal is the main diagonal. + If ``k < 0``, the diagonal is below the main diagonal. + If ``k > 0``, the diagonal is above the main diagonal. + + Default: ``0``. + + Returns + ------- + out : usm_ndarray + An upper-triangular array or a stack of upper-triangular arrays. - Returns: - usm_ndarray: - An upper-triangular array or a stack of upper-triangular arrays. """ + if not isinstance(x, dpt.usm_ndarray): raise TypeError( "Expected argument of type dpnp.tensor.usm_ndarray, " @@ -1829,41 +1998,54 @@ def zeros( sycl_queue=None, ): """ - Returns a new :class:`dpctl.tensor.usm_ndarray` having a specified + Returns a new :class:`dpnp.tensor.usm_ndarray` having a specified shape and filled with zeros. - Args: - shape (Tuple[int], int): - Dimensions of the array to be created. - dtype (optional): - data type of the array. Can be typestring, - a :class:`numpy.dtype` object, :mod:`numpy` char string, - or a NumPy scalar type. Default: ``None`` - order ("C", or "F"): - memory layout for the array. Default: ``"C"`` - device (optional): array API concept of device where the output array - is created. ``device`` can be ``None``, a oneAPI filter selector - string, an instance of :class:`dpctl.SyclDevice` corresponding to - a non-partitioned SYCL device, an instance of - :class:`dpctl.SyclQueue`, or a :class:`dpctl.tensor.Device` object - returned by :attr:`dpctl.tensor.usm_ndarray.device`. - Default: ``None`` - usm_type (``"device"``, ``"shared"``, ``"host"``, optional): - The type of SYCL USM allocation for the output array. - Default: ``"device"`` - sycl_queue (:class:`dpctl.SyclQueue`, optional): - The SYCL queue to use - for output array allocation and copying. ``sycl_queue`` and - ``device`` are complementary arguments, i.e. use one or another. - If both are specified, a :exc:`TypeError` is raised unless both - imply the same underlying SYCL queue to be used. If both are - ``None``, a cached queue targeting default-selected device is - used for allocation and population. Default: ``None`` + Parameters + ---------- + shape : {int, tuple of ints} + Dimensions of the array to be created. + dtype : dtype, optional + data type of the array. Can be typestring, + a :class:`numpy.dtype` object, :mod:`numpy` char string, + or a NumPy scalar type. + + Default: ``None``. + order : {"C", "F"}, optional + memory layout for the array. + + Default: ``"C"``. + device : object, optional + array API concept of device where the output array + is created. ``device`` can be ``None``, a oneAPI filter selector + string, an instance of :class:`dpctl.SyclDevice` corresponding to + a non-partitioned SYCL device, an instance of + :class:`dpctl.SyclQueue`, or a :class:`dpnp.tensor.Device` object + returned by :attr:`dpnp.tensor.usm_ndarray.device`. + + Default: ``None``. + usm_type : {"device", "shared", "host"}, optional + The type of SYCL USM allocation for the output array. + + Default: ``"device"``. + sycl_queue : dpctl.SyclQueue, optional + The SYCL queue to use + for output array allocation and copying. ``sycl_queue`` and + ``device`` are complementary arguments, i.e. use one or another. + If both are specified, a :exc:`TypeError` is raised unless both + imply the same underlying SYCL queue to be used. If both are + ``None``, a cached queue targeting default-selected device is + used for allocation and population. + + Default: ``None``. + + Returns + ------- + out : usm_ndarray + Constructed array initialized with zeros. - Returns: - usm_ndarray: - Constructed array initialized with zeros. """ + if not isinstance(order, str) or len(order) == 0 or order[0] not in "CcFf": raise ValueError( "Unrecognized order keyword value, expecting 'F' or 'C'." @@ -1892,44 +2074,56 @@ def zeros_like( x, /, *, dtype=None, order="K", device=None, usm_type=None, sycl_queue=None ): """ - Creates :class:`dpctl.tensor.usm_ndarray` from USM allocation + Creates :class:`dpnp.tensor.usm_ndarray` from USM allocation initialized with zeros. - Args: - x (usm_ndarray): - Input array from which to derive the shape of the - output array. - dtype (optional): - data type of the array. Can be typestring, - a :class:`numpy.dtype` object, :mod:`numpy` char string, or a - NumPy scalar type. If `None`, output array has the same data - type as the input array. Default: ``None`` - order ("C", or "F"): - memory layout for the array. Default: ``"C"`` - device (optional): - array API concept of device where the output array - is created. ``device`` can be ``None``, a oneAPI filter selector - string, an instance of :class:`dpctl.SyclDevice` corresponding to - a non-partitioned SYCL device, an instance of - :class:`dpctl.SyclQueue`, or a :class:`dpctl.tensor.Device` object - returned by :attr:`dpctl.tensor.usm_ndarray.device`. - Default: ``None`` - usm_type (``"device"``, ``"shared"``, ``"host"``, optional): - The type of SYCL USM allocation for the output array. - Default: ``"device"`` - sycl_queue (:class:`dpctl.SyclQueue`, optional): - The SYCL queue to use - for output array allocation and copying. ``sycl_queue`` and - ``device`` are complementary arguments, i.e. use one or another. - If both are specified, a :exc:`TypeError` is raised unless both - imply the same underlying SYCL queue to be used. If both are - ``None``, a cached queue targeting default-selected device is - used for allocation and population. Default: ``None`` + Parameters + ---------- + x : usm_ndarray + Input array from which to derive the shape of the + output array. + dtype : dtype, optional + data type of the array. Can be typestring, + a :class:`numpy.dtype` object, :mod:`numpy` char string, or a + NumPy scalar type. If ``None``, output array has the same data + type as the input array. + + Default: ``None``. + order : {"C", "F", "A", "K"}, optional + memory layout for the array. + + Default: ``"K"``. + device : object, optional + array API concept of device where the output array + is created. ``device`` can be ``None``, a oneAPI filter selector + string, an instance of :class:`dpctl.SyclDevice` corresponding to + a non-partitioned SYCL device, an instance of + :class:`dpctl.SyclQueue`, or a :class:`dpnp.tensor.Device` object + returned by :attr:`dpnp.tensor.usm_ndarray.device`. + + Default: ``None``. + usm_type : {"device", "shared", "host"}, optional + The type of SYCL USM allocation for the output array. + + Default: ``None``. + sycl_queue : dpctl.SyclQueue, optional + The SYCL queue to use + for output array allocation and copying. ``sycl_queue`` and + ``device`` are complementary arguments, i.e. use one or another. + If both are specified, a :exc:`TypeError` is raised unless both + imply the same underlying SYCL queue to be used. If both are + ``None``, a cached queue targeting default-selected device is + used for allocation and population. + + Default: ``None``. + + Returns + ------- + out : usm_ndarray + New array initialized with zeros. - Returns: - usm_ndarray: - New array initialized with zeros. """ + if not isinstance(x, dpt.usm_ndarray): raise TypeError(f"Expected instance of dpt.usm_ndarray, got {type(x)}.") if ( From 06da7e12b5f6151a5b70bae7686c2ce8e418209d Mon Sep 17 00:00:00 2001 From: Vladislav Perevezentsev Date: Tue, 7 Apr 2026 05:02:38 -0700 Subject: [PATCH 06/46] Update _data_types.py doc to Sphinx format --- dpnp/tensor/_data_types.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/dpnp/tensor/_data_types.py b/dpnp/tensor/_data_types.py index faf30ffdabd..555a4fe70cf 100644 --- a/dpnp/tensor/_data_types.py +++ b/dpnp/tensor/_data_types.py @@ -63,10 +63,11 @@ def _get_dtype(inp_dt, sycl_obj, ref_type=None): Type inference utility to construct data type object with defaults based on reference type. - _get_dtype is used by dpctl.tensor.asarray + _get_dtype is used by dpnp.tensor.asarray to infer data type of the output array from the input sequence. """ + if inp_dt is None: if ref_type in [None, float] or np_issubdtype(ref_type, np_floating): fp_dt = ti_default_device_fp_type(sycl_obj) From 9df90ee75e916074864ac32a4479a2436a570dc8 Mon Sep 17 00:00:00 2001 From: Vladislav Perevezentsev Date: Tue, 7 Apr 2026 05:05:11 -0700 Subject: [PATCH 07/46] Update _device.py doc to Sphinx format --- dpnp/tensor/_device.py | 80 +++++++++++++++++++++++++----------------- 1 file changed, 48 insertions(+), 32 deletions(-) diff --git a/dpnp/tensor/_device.py b/dpnp/tensor/_device.py index 5f2725c7485..c8490b7331e 100644 --- a/dpnp/tensor/_device.py +++ b/dpnp/tensor/_device.py @@ -57,21 +57,29 @@ def __new__(cls, *args, **kwargs): @classmethod def create_device(cls, device=None): - """Device.create_device(device=None) - + """ Creates instance of Device from argument. - Args: - device: - Device specification, i.e. `None`, :class:`.Device`, - :class:`dpctl.SyclQueue`, or a :class:`dpctl.SyclDevice` - corresponding to a root SYCL device. - Raises: - ValueError: if an instance of :class:`dpctl.SycDevice` corresponding - to a sub-device was specified as the argument - SyclQueueCreationError: if :class:`dpctl.SyclQueue` could not be - created from the argument + Parameters + ---------- + device : {None, Device, dpctl.SyclQueue, dpctl.SyclDevice}, optional + Device specification, i.e. ``None``, :class:`.Device`, + :class:`dpctl.SyclQueue`, or a :class:`dpctl.SyclDevice` + corresponding to a root SYCL device. + + Default: ``None``. + + Raises + ------ + ValueError + if an instance of :class:`dpctl.SyclDevice` corresponding + to a sub-device was specified as the argument. + SyclQueueCreationError + if :class:`dpctl.SyclQueue` could not be + created from the argument. + """ + dev = device obj = super().__new__(cls) if isinstance(dev, Device): @@ -147,33 +155,41 @@ def __hash__(self): def normalize_queue_device(sycl_queue=None, device=None): - """normalize_queue_device(sycl_queue=None, device=None) - + """ Utility to process exclusive keyword arguments 'device' - and 'sycl_queue' in functions of `dpctl.tensor`. - - Args: - sycl_queue (:class:`dpctl.SyclQueue`, optional): - explicitly indicates where USM allocation is done - and the population code (if any) is executed. - Value `None` is interpreted as get the SYCL queue - from `device` keyword, or use default queue. - Default: None - device (string, :class:`dpctl.SyclDevice`, :class:`dpctl.SyclQueue, - :class:`dpctl.tensor.Device`, optional): - array-API keyword indicating non-partitioned SYCL device - where array is allocated. + and 'sycl_queue' in functions of ``dpnp.tensor``. + + Parameters + ---------- + sycl_queue : dpctl.SyclQueue, optional + explicitly indicates where USM allocation is done + and the population code (if any) is executed. + Value ``None`` is interpreted as get the SYCL queue + from ``device`` keyword, or use default queue. + + Default: ``None``. + device : {str, dpctl.SyclDevice, dpctl.SyclQueue, dpnp.tensor.Device}, optional + array-API keyword indicating non-partitioned SYCL device + where array is allocated. + + Default: ``None``. Returns + ------- + out : dpctl.SyclQueue :class:`dpctl.SyclQueue` object implied by either of provided - keywords. If both are None, `dpctl.SyclQueue()` is returned. - If both are specified and imply the same queue, `sycl_queue` + keywords. If both are ``None``, ``dpctl.SyclQueue()`` is returned. + If both are specified and imply the same queue, ``sycl_queue`` is returned. - Raises: - TypeError: if argument is not of the expected type, or keywords - imply incompatible queues. + Raises + ------ + TypeError + if argument is not of the expected type, or keywords + imply incompatible queues. + """ + q = sycl_queue d = device if q is None: From 8c8cc738a45670728bef709205b96c2716e67df4 Mon Sep 17 00:00:00 2001 From: Vladislav Perevezentsev Date: Tue, 7 Apr 2026 05:11:57 -0700 Subject: [PATCH 08/46] Update _dlpack.pyx doc to Sphinx format --- dpnp/tensor/_dlpack.pyx | 400 ++++++++++++++++++++++------------------ 1 file changed, 220 insertions(+), 180 deletions(-) diff --git a/dpnp/tensor/_dlpack.pyx b/dpnp/tensor/_dlpack.pyx index 947377d3a66..f2043d29cd4 100644 --- a/dpnp/tensor/_dlpack.pyx +++ b/dpnp/tensor/_dlpack.pyx @@ -145,17 +145,20 @@ cdef extern from "dlpack/dlpack.h" nogil: def get_build_dlpack_version(): """ - Returns a tuple of integers representing the `major` and `minor` - version of DLPack :module:`dpctl.tensor` was built with. - This tuple can be passed as the `max_version` argument to - `__dlpack__` to guarantee module:`dpctl.tensor` can properly + Returns a tuple of integers representing the ``major`` and ``minor`` + version of DLPack :module:`dpnp.tensor` was built with. + This tuple can be passed as the ``max_version`` argument to + ``__dlpack__`` to guarantee :module:`dpnp.tensor` can properly consume capsule. - Returns: - Tuple[int, int] - A tuple of integers representing the `major` and `minor` - version of DLPack used to build :module:`dpctl.tensor`. + Returns + ------- + out : tuple of ints + A tuple of integers representing the ``major`` and ``minor`` + version of DLPack used to build :module:`dpnp.tensor`. + """ + return (DLPACK_MAJOR_VERSION, DLPACK_MINOR_VERSION) @@ -251,27 +254,37 @@ cdef int get_array_dlpack_device_id( cpdef to_dlpack_capsule(usm_ndarray usm_ary): """ - to_dlpack_capsule(usm_ary) - Constructs named Python capsule object referencing instance of ``DLManagedTensor`` from - :class:`dpctl.tensor.usm_ndarray` instance. + :class:`dpnp.tensor.usm_ndarray` instance. - Args: - usm_ary: An instance of :class:`dpctl.tensor.usm_ndarray` - Returns: + Parameters + ---------- + usm_ary : usm_ndarray + An instance of :class:`dpnp.tensor.usm_ndarray`. + + Returns + ------- + out : PyCapsule A new capsule with name ``"dltensor"`` that contains a pointer to ``DLManagedTensor`` struct. - Raises: - DLPackCreationError: when array can be represented as - DLPack tensor. This may happen when array was allocated - on a partitioned sycl device, or its USM allocation is - not bound to the platform default SYCL context. - MemoryError: when host allocation to needed for ``DLManagedTensor`` - did not succeed. - ValueError: when array elements data type could not be represented - in ``DLManagedTensor``. + + Raises + ------ + DLPackCreationError + when array can be represented as + DLPack tensor. This may happen when array was allocated + on a partitioned sycl device, or its USM allocation is + not bound to the platform default SYCL context. + MemoryError + when host allocation to needed for ``DLManagedTensor`` + did not succeed. + ValueError + when array elements data type could not be represented + in ``DLManagedTensor``. + """ + cdef DLManagedTensor *dlm_tensor = NULL cdef DLTensor *dl_tensor = NULL cdef int nd = usm_ary.get_ndim() @@ -371,30 +384,41 @@ cpdef to_dlpack_capsule(usm_ndarray usm_ary): cpdef to_dlpack_versioned_capsule(usm_ndarray usm_ary, bint copied): """ - to_dlpack_versioned_capsule(usm_ary, copied) - Constructs named Python capsule object referencing instance of ``DLManagedTensorVersioned`` from - :class:`dpctl.tensor.usm_ndarray` instance. - - Args: - usm_ary: An instance of :class:`dpctl.tensor.usm_ndarray` - copied: A bint representing whether the data was previously - copied in order to set the flags with the is-copied - bitmask. - Returns: + :class:`dpnp.tensor.usm_ndarray` instance. + + Parameters + ---------- + usm_ary : usm_ndarray + An instance of :class:`dpnp.tensor.usm_ndarray`. + copied : bool + A boolean representing whether the data was previously + copied in order to set the flags with the is-copied + bitmask. + + Returns + ------- + out : PyCapsule A new capsule with name ``"dltensor_versioned"`` that contains a pointer to ``DLManagedTensorVersioned`` struct. - Raises: - DLPackCreationError: when array can be represented as - DLPack tensor. This may happen when array was allocated - on a partitioned sycl device, or its USM allocation is - not bound to the platform default SYCL context. - MemoryError: when host allocation to needed for - ``DLManagedTensorVersioned`` did not succeed. - ValueError: when array elements data type could not be represented - in ``DLManagedTensorVersioned``. + + Raises + ------ + DLPackCreationError + when array can be represented as + DLPack tensor. This may happen when array was allocated + on a partitioned sycl device, or its USM allocation is + not bound to the platform default SYCL context. + MemoryError + when host allocation to needed for + ``DLManagedTensorVersioned`` did not succeed. + ValueError + when array elements data type could not be represented + in ``DLManagedTensorVersioned``. + """ + cdef DLManagedTensorVersioned *dlmv_tensor = NULL cdef DLTensor *dl_tensor = NULL cdef uint32_t dlmv_flags = 0 @@ -513,28 +537,39 @@ cpdef to_dlpack_versioned_capsule(usm_ndarray usm_ary, bint copied): cpdef numpy_to_dlpack_versioned_capsule(ndarray npy_ary, bint copied): """ - to_dlpack_versioned_capsule(npy_ary, copied) - Constructs named Python capsule object referencing instance of ``DLManagedTensorVersioned`` from :class:`numpy.ndarray` instance. - Args: - npy_ary: An instance of :class:`numpy.ndarray` - copied: A bint representing whether the data was previously - copied in order to set the flags with the is-copied - bitmask. - Returns: + Parameters + ---------- + npy_ary : numpy.ndarray + An instance of :class:`numpy.ndarray`. + copied : bool + A boolean representing whether the data was previously + copied in order to set the flags with the is-copied + bitmask. + + Returns + ------- + out : PyCapsule A new capsule with name ``"dltensor_versioned"`` that contains a pointer to ``DLManagedTensorVersioned`` struct. - Raises: - DLPackCreationError: when array can be represented as - DLPack tensor. - MemoryError: when host allocation to needed for - ``DLManagedTensorVersioned`` did not succeed. - ValueError: when array elements data type could not be represented - in ``DLManagedTensorVersioned``. + + Raises + ------ + DLPackCreationError + when array can be represented as + DLPack tensor. + MemoryError + when host allocation to needed for + ``DLManagedTensorVersioned`` did not succeed. + ValueError + when array elements data type could not be represented + in ``DLManagedTensorVersioned``. + """ + cdef DLManagedTensorVersioned *dlmv_tensor = NULL cdef DLTensor *dl_tensor = NULL cdef uint32_t dlmv_flags = 0 @@ -752,30 +787,36 @@ cdef bint _is_kdlcpu_device(DLDevice *dev): cpdef object from_dlpack_capsule(object py_caps): """ - from_dlpack_capsule(py_caps) - - Reconstructs instance of :class:`dpctl.tensor.usm_ndarray` from + Reconstructs instance of :class:`dpnp.tensor.usm_ndarray` from named Python capsule object referencing instance of ``DLManagedTensor`` without copy. The instance forms a view in the memory of the tensor. - Args: - caps: - Python capsule with name ``"dltensor"`` expected to reference - an instance of ``DLManagedTensor`` struct. - Returns: - Instance of :class:`dpctl.tensor.usm_ndarray` with a view into + Parameters + ---------- + py_caps : PyCapsule + Python capsule with name ``"dltensor"`` expected to reference + an instance of ``DLManagedTensor`` struct. + + Returns + ------- + out : {usm_ndarray, numpy.ndarray} + Instance of :class:`dpnp.tensor.usm_ndarray` with a view into memory of the tensor. Capsule is renamed to ``"used_dltensor"`` upon success. - Raises: - TypeError: - if argument is not a ``"dltensor"`` capsule. - ValueError: - if argument is ``"used_dltensor"`` capsule - BufferError: - if the USM pointer is not bound to the reconstructed - sycl context, or the DLPack's device_type is not supported - by :mod:`dpctl`. + + Raises + ------ + TypeError + if argument is not a ``"dltensor"`` capsule. + ValueError + if argument is ``"used_dltensor"`` capsule. + BufferError + if the USM pointer is not bound to the reconstructed + sycl context, or the DLPack's device_type is not supported + by :mod:`dpnp`. + """ + cdef DLManagedTensorVersioned *dlmv_tensor = NULL cdef DLManagedTensor *dlm_tensor = NULL cdef DLTensor *dl_tensor = NULL @@ -997,115 +1038,114 @@ cdef object _create_device(object device, object dl_device): def from_dlpack(x, /, *, device=None, copy=None): - """from_dlpack(x, /, *, device=None, copy=None) - - Constructs :class:`dpctl.tensor.usm_ndarray` or :class:`numpy.ndarray` + """ + Constructs :class:`dpnp.tensor.usm_ndarray` or :class:`numpy.ndarray` instance from a Python object ``x`` that implements ``__dlpack__`` protocol. - Args: - x (object): - A Python object representing an array that supports - ``__dlpack__`` protocol. - device ( - Optional[str, :class:`dpctl.SyclDevice`, - :class:`dpctl.SyclQueue`, - :class:`dpctl.tensor.Device`, - tuple([:class:`enum.IntEnum`, int])]) - ): - Device where the output array is to be placed. ``device`` keyword - values can be: - - * ``None`` - The data remains on the same device. - * oneAPI filter selector string - SYCL device selected by :ref:`filter selector string - `. - * :class:`dpctl.SyclDevice` - explicit SYCL device that must correspond to - a non-partitioned SYCL device. - * :class:`dpctl.SyclQueue` - implies SYCL device targeted by the SYCL queue. - * :class:`dpctl.tensor.Device` - implies SYCL device `device.sycl_queue`. The `Device` object - is obtained via :attr:`dpctl.tensor.usm_ndarray.device`. - * ``(device_type, device_id)`` - 2-tuple matching the format of the output of the - ``__dlpack_device__`` method: an integer enumerator representing - the device type followed by an integer representing the index of - the device. The only supported :class:`dpctl.tensor.DLDeviceType` - device types are ``"kDLCPU"`` and ``"kDLOneAPI"``. - - Default: ``None``. - - copy (bool, optional) - Boolean indicating whether or not to copy the input. - - * If ``copy`` is ``True``, the input will always be - copied. - * If ``False``, a ``BufferError`` will be raised if a - copy is deemed necessary. - * If ``None``, a copy will be made only if deemed - necessary, otherwise, the existing memory buffer will - be reused. - - Default: ``None``. - - Returns: - Alternative[usm_ndarray, numpy.ndarray]: - An array containing the data in ``x``. When ``copy`` is - ``None`` or ``False``, this may be a view into the original - memory. - - The type of the returned object - depends on where the data backing up input object ``x`` resides. - If it resides in a USM allocation on a SYCL device, the - type :class:`dpctl.tensor.usm_ndarray` is returned, otherwise if it - resides on ``"kDLCPU"`` device the type is :class:`numpy.ndarray`, - and otherwise an exception is raised. - - .. note:: - - If the return type is :class:`dpctl.tensor.usm_ndarray`, the - associated SYCL queue is derived from the ``device`` keyword. - When ``device`` keyword value has type :class:`dpctl.SyclQueue`, - the explicit queue instance is used, when ``device`` keyword - value has type :class:`dpctl.tensor.Device`, the - ``device.sycl_queue`` is used. In all other cases, the cached - SYCL queue corresponding to the implied SYCL device is used. - - Raises: - TypeError: - if ``x`` does not implement ``__dlpack__`` method - ValueError: - if data of the input object resides on an unsupported device - - See https://dmlc.github.io/dlpack/latest/ for more details. - - :Example: - - .. code-block:: python - - import dpctl - import dpnp.tensor as dpt - - class Container: - "Helper class implementing `__dlpack__` protocol" - def __init__(self, array): - self._array = array - - def __dlpack__(self, stream=None): - return self._array.__dlpack__(stream=stream) - - def __dlpack_device__(self): - return self._array.__dlpack_device__() - - C = Container(dpt.linspace(0, 100, num=20, dtype="int16")) - # create usm_ndarray view - X = dpt.from_dlpack(C) - # migrate content of the container to device of type kDLCPU - Y = dpt.from_dlpack(C, device=(dpt.DLDeviceType.kDLCPU, 0)) + Parameters + ---------- + x : object + A Python object representing an array that supports + ``__dlpack__`` protocol. + device : {None, str, dpctl.SyclDevice, dpctl.SyclQueue, dpnp.tensor.Device, tuple}, optional + Device where the output array is to be placed. ``device`` keyword + values can be: + + * ``None`` + The data remains on the same device. + * oneAPI filter selector string + SYCL device selected by :ref:`filter selector string + `. + * :class:`dpctl.SyclDevice` + explicit SYCL device that must correspond to + a non-partitioned SYCL device. + * :class:`dpctl.SyclQueue` + implies SYCL device targeted by the SYCL queue. + * :class:`dpnp.tensor.Device` + implies SYCL device ``device.sycl_queue``. The ``Device`` object + is obtained via :attr:`dpnp.tensor.usm_ndarray.device`. + * ``(device_type, device_id)`` + 2-tuple matching the format of the output of the + ``__dlpack_device__`` method: an integer enumerator representing + the device type followed by an integer representing the index of + the device. The only supported :class:`dpnp.tensor.DLDeviceType` + device types are ``"kDLCPU"`` and ``"kDLOneAPI"``. + + Default: ``None``. + copy : bool, optional + Boolean indicating whether or not to copy the input. + + * If ``copy`` is ``True``, the input will always be + copied. + * If ``False``, a ``BufferError`` will be raised if a + copy is deemed necessary. + * If ``None``, a copy will be made only if deemed + necessary, otherwise, the existing memory buffer will + be reused. + + Default: ``None``. + + Returns + ------- + out : {usm_ndarray, numpy.ndarray} + An array containing the data in ``x``. When ``copy`` is + ``None`` or ``False``, this may be a view into the original + memory. + + The type of the returned object + depends on where the data backing up input object ``x`` resides. + If it resides in a USM allocation on a SYCL device, the + type :class:`dpnp.tensor.usm_ndarray` is returned, otherwise if it + resides on ``"kDLCPU"`` device the type is :class:`numpy.ndarray`, + and otherwise an exception is raised. + + .. note:: + + If the return type is :class:`dpnp.tensor.usm_ndarray`, the + associated SYCL queue is derived from the ``device`` keyword. + When ``device`` keyword value has type :class:`dpctl.SyclQueue`, + the explicit queue instance is used, when ``device`` keyword + value has type :class:`dpnp.tensor.Device`, the + ``device.sycl_queue`` is used. In all other cases, the cached + SYCL queue corresponding to the implied SYCL device is used. + + Raises + ------ + TypeError + if ``x`` does not implement ``__dlpack__`` method. + ValueError + if data of the input object resides on an unsupported device. + + See Also + -------- + https://dmlc.github.io/dlpack/latest/ : DLPack specification. + + Examples + -------- + .. code-block:: python + + import dpctl + import dpnp.tensor as dpt + + class Container: + "Helper class implementing `__dlpack__` protocol" + def __init__(self, array): + self._array = array + + def __dlpack__(self, stream=None): + return self._array.__dlpack__(stream=stream) + + def __dlpack_device__(self): + return self._array.__dlpack_device__() + + C = Container(dpt.linspace(0, 100, num=20, dtype="int16")) + # create usm_ndarray view + X = dpt.from_dlpack(C) + # migrate content of the container to device of type kDLCPU + Y = dpt.from_dlpack(C, device=(dpt.DLDeviceType.kDLCPU, 0)) """ + dlpack_attr = getattr(x, "__dlpack__", None) dlpack_dev_attr = getattr(x, "__dlpack_device__", None) if not callable(dlpack_attr) or not callable(dlpack_dev_attr): From fea68327209aa6db1550696f2548ab528ef19de9 Mon Sep 17 00:00:00 2001 From: Vladislav Perevezentsev Date: Tue, 7 Apr 2026 05:13:04 -0700 Subject: [PATCH 09/46] Update _flags.pyx doc to Sphinx format --- dpnp/tensor/_flags.pyx | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/dpnp/tensor/_flags.pyx b/dpnp/tensor/_flags.pyx index 322d52bd56c..0f3a0e4c73d 100644 --- a/dpnp/tensor/_flags.pyx +++ b/dpnp/tensor/_flags.pyx @@ -46,7 +46,7 @@ cdef cpp_bool _check_bit(int flag, int mask): cdef class Flags: """ - Helper class to query the flags of a :class:`dpctl.tensor.usm_ndarray` + Helper class to query the flags of a :class:`dpnp.tensor.usm_ndarray` instance, which describe how the instance interfaces with its underlying memory. """ @@ -61,7 +61,7 @@ cdef class Flags: def flags(self): """ Integer representation of the memory layout flags of - :class:`dpctl.tensor.usm_ndarray` instance. + :class:`dpnp.tensor.usm_ndarray` instance. """ return self.flags_ @@ -69,7 +69,7 @@ cdef class Flags: def c_contiguous(self): """ True if the memory layout of the - :class:`dpctl.tensor.usm_ndarray` instance is C-contiguous. + :class:`dpnp.tensor.usm_ndarray` instance is C-contiguous. """ return _check_bit(self.flags_, USM_ARRAY_C_CONTIGUOUS) @@ -77,14 +77,14 @@ cdef class Flags: def f_contiguous(self): """ True if the memory layout of the - :class:`dpctl.tensor.usm_ndarray` instance is F-contiguous. + :class:`dpnp.tensor.usm_ndarray` instance is F-contiguous. """ return _check_bit(self.flags_, USM_ARRAY_F_CONTIGUOUS) @property def writable(self): """ - True if :class:`dpctl.tensor.usm_ndarray` instance is writable. + True if :class:`dpnp.tensor.usm_ndarray` instance is writable. """ return _check_bit(self.flags_, USM_ARRAY_WRITABLE) @@ -97,7 +97,7 @@ cdef class Flags: @property def fc(self): """ - True if the memory layout of the :class:`dpctl.tensor.usm_ndarray` + True if the memory layout of the :class:`dpnp.tensor.usm_ndarray` instance is C-contiguous and F-contiguous. """ return ( @@ -108,7 +108,7 @@ cdef class Flags: @property def forc(self): """ - True if the memory layout of the :class:`dpctl.tensor.usm_ndarray` + True if the memory layout of the :class:`dpnp.tensor.usm_ndarray` instance is C-contiguous or F-contiguous. """ return ( @@ -119,7 +119,7 @@ cdef class Flags: @property def fnc(self): """ - True if the memory layout of the :class:`dpctl.tensor.usm_ndarray` + True if the memory layout of the :class:`dpnp.tensor.usm_ndarray` instance is F-contiguous and not C-contiguous. """ return ( @@ -130,7 +130,7 @@ cdef class Flags: @property def contiguous(self): """ - True if the memory layout of the :class:`dpctl.tensor.usm_ndarray` + True if the memory layout of the :class:`dpnp.tensor.usm_ndarray` instance is C-contiguous and F-contiguous. Equivalent to `forc.` """ From 1d021b61820f1a4ee231e9e5fc346d4fa216fd3b Mon Sep 17 00:00:00 2001 From: Vladislav Perevezentsev Date: Tue, 7 Apr 2026 05:19:53 -0700 Subject: [PATCH 10/46] Update _elementwise_common.py doc to Sphinx format --- dpnp/tensor/_elementwise_common.py | 230 ++++++++++++++++------------- 1 file changed, 128 insertions(+), 102 deletions(-) diff --git a/dpnp/tensor/_elementwise_common.py b/dpnp/tensor/_elementwise_common.py index 2eb89b8fb5f..e40e24630c4 100644 --- a/dpnp/tensor/_elementwise_common.py +++ b/dpnp/tensor/_elementwise_common.py @@ -54,41 +54,46 @@ class UnaryElementwiseFunc: """ Class that implements unary element-wise functions. - Args: - name (str): - Name of the unary function - result_type_resovler_fn (callable): - Function that takes dtype of the input and - returns the dtype of the result if the - implementation functions supports it, or - returns `None` otherwise. - unary_dp_impl_fn (callable): - Data-parallel implementation function with signature - `impl_fn(src: usm_ndarray, dst: usm_ndarray, - sycl_queue: SyclQueue, depends: Optional[List[SyclEvent]])` - where the `src` is the argument array, `dst` is the - array to be populated with function values, effectively - evaluating `dst = func(src)`. - The `impl_fn` is expected to return a 2-tuple of `SyclEvent`s. - The first event corresponds to data-management host tasks, - including lifetime management of argument Python objects to ensure - that their associated USM allocation is not freed before offloaded - computational tasks complete execution, while the second event - corresponds to computational tasks associated with function - evaluation. - acceptance_fn (callable, optional): - Function to influence type promotion behavior of this unary - function. The function takes 4 arguments: - arg_dtype - Data type of the first argument - buf_dtype - Data type the argument would be cast to - res_dtype - Data type of the output array with function values - sycl_dev - The :class:`dpctl.SyclDevice` where the function - evaluation is carried out. - The function is invoked when the argument of the unary function - requires casting, e.g. the argument of `dpctl.tensor.log` is an - array with integral data type. - docs (str): - Documentation string for the unary function. + Parameters + ---------- + name : str + Name of the unary function. + result_type_resovler_fn : callable + Function that takes dtype of the input and + returns the dtype of the result if the + implementation functions supports it, or + returns ``None`` otherwise. + unary_dp_impl_fn : callable + Data-parallel implementation function with signature + ``impl_fn(src: usm_ndarray, dst: usm_ndarray, + sycl_queue: SyclQueue, depends: Optional[List[SyclEvent]])`` + where the ``src`` is the argument array, ``dst`` is the + array to be populated with function values, effectively + evaluating ``dst = func(src)``. + The ``impl_fn`` is expected to return a 2-tuple of ``SyclEvent``s. + The first event corresponds to data-management host tasks, + including lifetime management of argument Python objects to ensure + that their associated USM allocation is not freed before offloaded + computational tasks complete execution, while the second event + corresponds to computational tasks associated with function + evaluation. + acceptance_fn : callable, optional + Function to influence type promotion behavior of this unary + function. The function takes 4 arguments: + + * arg_dtype - Data type of the first argument + * buf_dtype - Data type the argument would be cast to + * res_dtype - Data type of the output array with function values + * sycl_dev - The :class:`dpctl.SyclDevice` where the function evaluation is carried out. + + The function is invoked when the argument of the unary function + requires casting, e.g. the argument of ``dpnp.tensor.log`` is an + array with integral data type. + + Default: ``None``. + docs : str + Documentation string for the unary function. + """ def __init__( @@ -142,7 +147,7 @@ def get_type_promotion_path_acceptance_function(self): sycl_dev - The :class:`dpctl.SyclDevice` where the function evaluation is carried out. The function is invoked when the argument of the unary function - requires casting, e.g. the argument of `dpctl.tensor.log` is an + requires casting, e.g. the argument of ``dpnp.tensor.log`` is an array with integral data type. """ return self.acceptance_fn_ @@ -163,12 +168,15 @@ def types(self): implementation function, using NumPy's character encoding for data types, e.g. - :Example: - .. code-block:: python + Examples + -------- + .. code-block:: python + + dpnp.tensor.sin.types + # Outputs: ['e->e', 'f->f', 'd->d', 'F->F', 'D->D'] - dpctl.tensor.sin.types - # Outputs: ['e->e', 'f->f', 'd->d', 'F->F', 'D->D'] """ + types = self.types_ if not types: types = [] @@ -293,55 +301,62 @@ class BinaryElementwiseFunc: """ Class that implements binary element-wise functions. - Args: - name (str): - Name of the unary function - result_type_resovle_fn (callable): - Function that takes dtypes of the input and - returns the dtype of the result if the - implementation functions supports it, or - returns `None` otherwise. - binary_dp_impl_fn (callable): - Data-parallel implementation function with signature - `impl_fn(src1: usm_ndarray, src2: usm_ndarray, dst: usm_ndarray, - sycl_queue: SyclQueue, depends: Optional[List[SyclEvent]])` - where the `src1` and `src2` are the argument arrays, `dst` is the - array to be populated with function values, - i.e. `dst=func(src1, src2)`. - The `impl_fn` is expected to return a 2-tuple of `SyclEvent`s. - The first event corresponds to data-management host tasks, - including lifetime management of argument Python objects to ensure - that their associated USM allocation is not freed before offloaded - computational tasks complete execution, while the second event - corresponds to computational tasks associated with function - evaluation. - docs (str): - Documentation string for the unary function. - binary_inplace_fn (callable, optional): - Data-parallel implementation function with signature - `impl_fn(src: usm_ndarray, dst: usm_ndarray, - sycl_queue: SyclQueue, depends: Optional[List[SyclEvent]])` - where the `src` is the argument array, `dst` is the - array to be populated with function values, - i.e. `dst=func(dst, src)`. - The `impl_fn` is expected to return a 2-tuple of `SyclEvent`s. - The first event corresponds to data-management host tasks, - including async lifetime management of Python arguments, - while the second event corresponds to computational tasks - associated with function evaluation. - acceptance_fn (callable, optional): - Function to influence type promotion behavior of this binary - function. The function takes 6 arguments: - arg1_dtype - Data type of the first argument - arg2_dtype - Data type of the second argument - ret_buf1_dtype - Data type the first argument would be cast to - ret_buf2_dtype - Data type the second argument would be cast to - res_dtype - Data type of the output array with function values - sycl_dev - The :class:`dpctl.SyclDevice` where the function - evaluation is carried out. - The function is only called when both arguments of the binary - function require casting, e.g. both arguments of - `dpctl.tensor.logaddexp` are arrays with integral data type. + Parameters + ---------- + name : str + Name of the unary function. + result_type_resovle_fn : callable + Function that takes dtypes of the input and + returns the dtype of the result if the + implementation functions supports it, or + returns ``None`` otherwise. + binary_dp_impl_fn : callable + Data-parallel implementation function with signature + ``impl_fn(src1: usm_ndarray, src2: usm_ndarray, dst: usm_ndarray, + sycl_queue: SyclQueue, depends: Optional[List[SyclEvent]])`` + where the ``src1`` and ``src2`` are the argument arrays, ``dst`` is the + array to be populated with function values, + i.e. ``dst=func(src1, src2)``. + The ``impl_fn`` is expected to return a 2-tuple of ``SyclEvent``s. + The first event corresponds to data-management host tasks, + including lifetime management of argument Python objects to ensure + that their associated USM allocation is not freed before offloaded + computational tasks complete execution, while the second event + corresponds to computational tasks associated with function + evaluation. + docs : str + Documentation string for the unary function. + binary_inplace_fn : callable, optional + Data-parallel implementation function with signature + ``impl_fn(src: usm_ndarray, dst: usm_ndarray, + sycl_queue: SyclQueue, depends: Optional[List[SyclEvent]])`` + where the ``src`` is the argument array, ``dst`` is the + array to be populated with function values, + i.e. ``dst=func(dst, src)``. + The ``impl_fn`` is expected to return a 2-tuple of ``SyclEvent``s. + The first event corresponds to data-management host tasks, + including async lifetime management of Python arguments, + while the second event corresponds to computational tasks + associated with function evaluation. + + Default: ``None``. + acceptance_fn : callable, optional + Function to influence type promotion behavior of this binary + function. The function takes 6 arguments: + + * arg1_dtype - Data type of the first argument + * arg2_dtype - Data type of the second argument + * ret_buf1_dtype - Data type the first argument would be cast to + * ret_buf2_dtype - Data type the second argument would be cast to + * res_dtype - Data type of the output array with function values + * sycl_dev - The :class:`dpctl.SyclDevice` where the function evaluation is carried out. + + The function is only called when both arguments of the binary + function require casting, e.g. both arguments of + ``dpnp.tensor.logaddexp`` are arrays with integral data type. + + Default: ``None``. + """ def __init__( @@ -381,6 +396,7 @@ def get_implementation_function(self): function for this elementwise binary function. """ + return self.binary_fn_ def get_implementation_inplace_function(self): @@ -388,12 +404,14 @@ def get_implementation_inplace_function(self): function for this elementwise binary function. """ + return self.binary_inplace_fn_ def get_type_result_resolver_function(self): """Returns the type resolver function for this elementwise binary function. """ + return self.result_type_resolver_fn_ def get_type_promotion_path_acceptance_function(self): @@ -413,8 +431,10 @@ def get_type_promotion_path_acceptance_function(self): The acceptance function is only invoked if both input arrays must be cast to intermediary data types, as would happen during call of - `dpctl.tensor.hypot` with both arrays being of integral data type. + ``dpnp.tensor.hypot`` with both arrays being of integral data type. + """ + return self.acceptance_fn_ def get_array_dtype_scalar_type_resolver_function(self): @@ -425,16 +445,19 @@ def get_array_dtype_scalar_type_resolver_function(self): treated as prior to type promotion behavior. The function takes 3 arguments: - Args: - o1_dtype (object, dtype): - A class representing a Python scalar type or a ``dtype`` - o2_dtype (object, dtype): - A class representing a Python scalar type or a ``dtype`` - sycl_dev (:class:`dpctl.SyclDevice`): - Device on which function evaluation is carried out. + Parameters + ---------- + o1_dtype : {type, dtype} + A class representing a Python scalar type or a ``dtype``. + o2_dtype : {type, dtype} + A class representing a Python scalar type or a ``dtype``. + sycl_dev : dpctl.SyclDevice + Device on which function evaluation is carried out. One of ``o1_dtype`` and ``o2_dtype`` must be a ``dtype`` instance. + """ + return self.weak_type_resolver_ @property @@ -453,13 +476,16 @@ def types(self): implementation function, using NumPy's character encoding for data types, e.g. - :Example: - .. code-block:: python + Examples + -------- + .. code-block:: python + + dpnp.tensor.divide.types + # Outputs: ['ee->e', 'ff->f', 'fF->F', 'dd->d', 'dD->D', + # 'Ff->F', 'FF->F', 'Dd->D', 'DD->D'] - dpctl.tensor.divide.types - # Outputs: ['ee->e', 'ff->f', 'fF->F', 'dd->d', 'dD->D', - # 'Ff->F', 'FF->F', 'Dd->D', 'DD->D'] """ + types = self.types_ if not types: types = [] From 6f27c9c8e4c4d4822a78cfae2c4958fbeb0cee97 Mon Sep 17 00:00:00 2001 From: Vladislav Perevezentsev Date: Tue, 7 Apr 2026 05:48:05 -0700 Subject: [PATCH 11/46] Update _indexing_functions.py doc to Sphinx format --- dpnp/tensor/_indexing_functions.py | 430 +++++++++++++++-------------- 1 file changed, 229 insertions(+), 201 deletions(-) diff --git a/dpnp/tensor/_indexing_functions.py b/dpnp/tensor/_indexing_functions.py index 675e770e411..a013a907de9 100644 --- a/dpnp/tensor/_indexing_functions.py +++ b/dpnp/tensor/_indexing_functions.py @@ -59,29 +59,31 @@ def _range(sh_i, i, nd, q, usm_t, dt): def extract(condition, arr): - """extract(condition, arr) - + """ Returns the elements of an array that satisfies the condition. - If ``condition`` is boolean ``dpctl.tensor.extract`` is + If ``condition`` is boolean ``dpnp.tensor.extract`` is equivalent to ``arr[condition]``. - Note that ``dpctl.tensor.place`` does the opposite of - ``dpctl.tensor.extract``. + Note that ``dpnp.tensor.place`` does the opposite of + ``dpnp.tensor.extract``. - Args: - conditions (usm_ndarray): - An array whose non-zero or ``True`` entries indicate the element - of ``arr`` to extract. + Parameters + ---------- + condition : usm_ndarray + An array whose non-zero or ``True`` entries indicate the element + of ``arr`` to extract. + arr : usm_ndarray + Input array of the same size as ``condition``. - arr (usm_ndarray): - Input array of the same size as ``condition``. + Returns + ------- + out : usm_ndarray + Rank 1 array of values from ``arr`` where ``condition`` is + ``True``. - Returns: - usm_ndarray: - Rank 1 array of values from ``arr`` where ``condition`` is - ``True``. """ + if not isinstance(condition, dpt.usm_ndarray): raise TypeError( "Expecting dpnp.tensor.usm_ndarray type, " f"got {type(condition)}" @@ -104,8 +106,7 @@ def extract(condition, arr): def nonzero(arr): - """nonzero(arr) - + """ Return the indices of non-zero elements. Returns a tuple of usm_ndarrays, one for each dimension @@ -113,14 +114,18 @@ def nonzero(arr): in that dimension. The values of ``arr`` are always tested in row-major, C-style order. - Args: - arr (usm_ndarray): - Input array, which has non-zero array rank. + Parameters + ---------- + arr : usm_ndarray + Input array, which has non-zero array rank. + + Returns + ------- + out : tuple of usm_ndarrays + Indices of non-zero array elements. - Returns: - Tuple[usm_ndarray, ...]: - Indices of non-zero array elements. """ + if not isinstance(arr, dpt.usm_ndarray): raise TypeError( "Expecting dpnp.tensor.usm_ndarray type, " f"got {type(arr)}" @@ -131,25 +136,27 @@ def nonzero(arr): def place(arr, mask, vals): - """place(arr, mask, vals) - + """ Change elements of an array based on conditional and input values. - If ``mask`` is boolean ``dpctl.tensor.place`` is + If ``mask`` is boolean ``dpnp.tensor.place`` is equivalent to ``arr[condition] = vals``. - Args: - arr (usm_ndarray): - Array to put data into. - mask (usm_ndarray): - Boolean mask array. Must have the same size as ``arr``. - vals (usm_ndarray, sequence): - Values to put into ``arr``. Only the first N elements are - used, where N is the number of True values in ``mask``. If - ``vals`` is smaller than N, it will be repeated, and if - elements of ``arr`` are to be masked, this sequence must be - non-empty. Array ``vals`` must be one dimensional. + Parameters + ---------- + arr : usm_ndarray + Array to put data into. + mask : usm_ndarray + Boolean mask array. Must have the same size as ``arr``. + vals : {usm_ndarray, sequence} + Values to put into ``arr``. Only the first N elements are + used, where N is the number of True values in ``mask``. If + ``vals`` is smaller than N, it will be repeated, and if + elements of ``arr`` are to be masked, this sequence must be + non-empty. Array ``vals`` must be one dimensional. + """ + if not isinstance(arr, dpt.usm_ndarray): raise TypeError( "Expecting dpnp.tensor.usm_ndarray type, " f"got {type(arr)}" @@ -199,84 +206,88 @@ def place(arr, mask, vals): def put(x, indices, vals, /, *, axis=None, mode="wrap"): - """put(x, indices, vals, axis=None, mode="wrap") - + """ Puts values into an array along a given axis at given indices. - Args: - x (usm_ndarray): - The array the values will be put into. - indices (usm_ndarray): - One-dimensional array of indices. - vals (usm_ndarray): - Array of values to be put into ``x``. - Must be broadcastable to the result shape - ``x.shape[:axis] + indices.shape + x.shape[axis+1:]``. - axis (int, optional): - The axis along which the values will be placed. - If ``x`` is one-dimensional, this argument is optional. - Default: ``None``. - mode (str, optional): - How out-of-bounds indices will be handled. Possible values - are: - - - ``"wrap"``: clamps indices to (``-n <= i < n``), then wraps - negative indices. - - ``"clip"``: clips indices to (``0 <= i < n``). - - Default: ``"wrap"``. - - .. note:: - - If input array ``indices`` contains duplicates, a race condition - occurs, and the value written into corresponding positions in ``x`` - may vary from run to run. Preserving sequential semantics in handing - the duplicates to achieve deterministic behavior requires additional - work, e.g. - - :Example: - - .. code-block:: python - - from dpctl import tensor as dpt - - def put_vec_duplicates(vec, ind, vals): - "Put values into vec, handling possible duplicates in ind" - assert vec.ndim, ind.ndim, vals.ndim == 1, 1, 1 - - # find positions of last occurrences of each - # unique index - ind_flipped = dpt.flip(ind) - ind_uniq = dpt.unique_all(ind_flipped).indices - has_dups = len(ind) != len(ind_uniq) - - if has_dups: - ind_uniq = dpt.subtract(vec.size - 1, ind_uniq) - ind = dpt.take(ind, ind_uniq) - vals = dpt.take(vals, ind_uniq) - - dpt.put(vec, ind, vals) - - n = 512 - ind = dpt.concat((dpt.arange(n), dpt.arange(n, -1, step=-1))) - x = dpt.zeros(ind.size, dtype="int32") - vals = dpt.arange(ind.size, dtype=x.dtype) - - # Values corresponding to last positions of - # duplicate indices are written into the vector x - put_vec_duplicates(x, ind, vals) - - parts = (vals[-1:-n-2:-1], dpt.zeros(n, dtype=x.dtype)) - expected = dpt.concat(parts) - assert dpt.all(x == expected) + Parameters + ---------- + x : usm_ndarray + The array the values will be put into. + indices : usm_ndarray + One-dimensional array of indices. + vals : usm_ndarray + Array of values to be put into ``x``. + Must be broadcastable to the result shape + ``x.shape[:axis] + indices.shape + x.shape[axis+1:]``. + axis : int, optional + The axis along which the values will be placed. + If ``x`` is one-dimensional, this argument is optional. + + Default: ``None``. + mode : {"wrap", "clip"}, optional + How out-of-bounds indices will be handled. Possible values + are: + + * ``"wrap"``: clamps indices to (``-n <= i < n``), then wraps negative indices. + * ``"clip"``: clips indices to (``0 <= i < n``). + + Default: ``"wrap"``. + + Notes + ----- + If input array ``indices`` contains duplicates, a race condition + occurs, and the value written into corresponding positions in ``x`` + may vary from run to run. Preserving sequential semantics in handing + the duplicates to achieve deterministic behavior requires additional + work, e.g. + + Examples + -------- + .. code-block:: python + + import dpnp.tensor as dpt + + def put_vec_duplicates(vec, ind, vals): + "Put values into vec, handling possible duplicates in ind" + assert vec.ndim, ind.ndim, vals.ndim == 1, 1, 1 + + # find positions of last occurrences of each + # unique index + ind_flipped = dpt.flip(ind) + ind_uniq = dpt.unique_all(ind_flipped).indices + has_dups = len(ind) != len(ind_uniq) + + if has_dups: + ind_uniq = dpt.subtract(vec.size - 1, ind_uniq) + ind = dpt.take(ind, ind_uniq) + vals = dpt.take(vals, ind_uniq) + + dpt.put(vec, ind, vals) + + n = 512 + ind = dpt.concat((dpt.arange(n), dpt.arange(n, -1, step=-1))) + x = dpt.zeros(ind.size, dtype="int32") + vals = dpt.arange(ind.size, dtype=x.dtype) + + # Values corresponding to last positions of + # duplicate indices are written into the vector x + put_vec_duplicates(x, ind, vals) + + parts = (vals[-1:-n-2:-1], dpt.zeros(n, dtype=x.dtype)) + expected = dpt.concat(parts) + assert dpt.all(x == expected) + """ + if not isinstance(x, dpt.usm_ndarray): raise TypeError( - "Expected instance of `dpt.usm_ndarray`, got `{}`.".format(type(x)) + "Expected instance of `dpnp.tensor.usm_ndarray`, got `{}`.".format( + type(x) + ) ) if not isinstance(indices, dpt.usm_ndarray): raise TypeError( - "`indices` expected `dpt.usm_ndarray`, got `{}`.".format( + "`indices` expected `dpnp.tensor.usm_ndarray`, got `{}`.".format( type(indices) ) ) @@ -359,38 +370,42 @@ def put_along_axis(x, indices, vals, /, *, axis=-1, mode="wrap"): Puts elements into an array at the one-dimensional indices specified by ``indices`` along a provided ``axis``. - Args: - x (usm_ndarray): - input array. Must be compatible with ``indices``, except for the - axis (dimension) specified by ``axis``. - indices (usm_ndarray): - array indices. Must have the same rank (i.e., number of dimensions) - as ``x``. - vals (usm_ndarray): - Array of values to be put into ``x``. - Must be broadcastable to the shape of ``indices``. - axis: int - axis along which to select values. If ``axis`` is negative, the - function determines the axis along which to select values by - counting from the last dimension. Default: ``-1``. - mode (str, optional): - How out-of-bounds indices will be handled. Possible values - are: - - - ``"wrap"``: clamps indices to (``-n <= i < n``), then wraps - negative indices. - - ``"clip"``: clips indices to (``0 <= i < n``). - - Default: ``"wrap"``. - - .. note:: - - If input array ``indices`` contains duplicates, a race condition - occurs, and the value written into corresponding positions in ``x`` - may vary from run to run. Preserving sequential semantics in handing - the duplicates to achieve deterministic behavior requires additional - work. + Parameters + ---------- + x : usm_ndarray + input array. Must be compatible with ``indices``, except for the + axis (dimension) specified by ``axis``. + indices : usm_ndarray + array indices. Must have the same rank (i.e., number of dimensions) + as ``x``. + vals : usm_ndarray + Array of values to be put into ``x``. + Must be broadcastable to the shape of ``indices``. + axis : int, optional + axis along which to select values. If ``axis`` is negative, the + function determines the axis along which to select values by + counting from the last dimension. + + Default: ``-1``. + mode : {"wrap", "clip"}, optional + How out-of-bounds indices will be handled. Possible values + are: + + * ``"wrap"``: clamps indices to (``-n <= i < n``), then wraps negative indices. + * ``"clip"``: clips indices to (``0 <= i < n``). + + Default: ``"wrap"``. + + Notes + ----- + If input array ``indices`` contains duplicates, a race condition + occurs, and the value written into corresponding positions in ``x`` + may vary from run to run. Preserving sequential semantics in handing + the duplicates to achieve deterministic behavior requires additional + work. + """ + if not isinstance(x, dpt.usm_ndarray): raise TypeError(f"Expected dpnp.tensor.usm_ndarray, got {type(x)}") if not isinstance(indices, dpt.usm_ndarray): @@ -435,46 +450,53 @@ def put_along_axis(x, indices, vals, /, *, axis=-1, mode="wrap"): def take(x, indices, /, *, axis=None, out=None, mode="wrap"): - """take(x, indices, axis=None, out=None, mode="wrap") - + """ Takes elements from an array along a given axis at given indices. - Args: - x (usm_ndarray): - The array that elements will be taken from. - indices (usm_ndarray): - One-dimensional array of indices. - axis (int, optional): - The axis along which the values will be selected. - If ``x`` is one-dimensional, this argument is optional. - Default: ``None``. - out (Optional[usm_ndarray]): - Output array to populate. Array must have the correct - shape and the expected data type. - mode (str, optional): - How out-of-bounds indices will be handled. Possible values - are: - - - ``"wrap"``: clamps indices to (``-n <= i < n``), then wraps - negative indices. - - ``"clip"``: clips indices to (``0 <= i < n``). - - Default: ``"wrap"``. - - Returns: - usm_ndarray: - Array with shape - ``x.shape[:axis] + indices.shape + x.shape[axis + 1:]`` - filled with elements from ``x``. + Parameters + ---------- + x : usm_ndarray + The array that elements will be taken from. + indices : usm_ndarray + One-dimensional array of indices. + axis : int, optional + The axis along which the values will be selected. + If ``x`` is one-dimensional, this argument is optional. + + Default: ``None``. + out : usm_ndarray, optional + Output array to populate. Array must have the correct + shape and the expected data type. + + Default: ``None``. + mode : {"wrap", "clip"}, optional + How out-of-bounds indices will be handled. Possible values + are: + + * ``"wrap"``: clamps indices to (``-n <= i < n``), then wraps negative indices. + * ``"clip"``: clips indices to (``0 <= i < n``). + + Default: ``"wrap"``. + + Returns + ------- + out : usm_ndarray + Array with shape + ``x.shape[:axis] + indices.shape + x.shape[axis + 1:]`` + filled with elements from ``x``. + """ + if not isinstance(x, dpt.usm_ndarray): raise TypeError( - "Expected instance of `dpt.usm_ndarray`, got `{}`.".format(type(x)) + "Expected instance of `dpnp.tensor.usm_ndarray`, got `{}`.".format( + type(x) + ) ) if not isinstance(indices, dpt.usm_ndarray): raise TypeError( - "`indices` expected `dpt.usm_ndarray`, got `{}`.".format( + "`indices` expected `dpnp.tensor.usm_ndarray`, got `{}`.".format( type(indices) ) ) @@ -577,39 +599,45 @@ def take_along_axis(x, indices, /, *, axis=-1, mode="wrap"): Returns elements from an array at the one-dimensional indices specified by ``indices`` along a provided ``axis``. - Args: - x (usm_ndarray): - input array. Must be compatible with ``indices``, except for the - axis (dimension) specified by ``axis``. - indices (usm_ndarray): - array indices. Must have the same rank (i.e., number of dimensions) - as ``x``. - axis: int - axis along which to select values. If ``axis`` is negative, the - function determines the axis along which to select values by - counting from the last dimension. Default: ``-1``. - mode (str, optional): - How out-of-bounds indices will be handled. Possible values - are: - - - ``"wrap"``: clamps indices to (``-n <= i < n``), then wraps - negative indices. - - ``"clip"``: clips indices to (``0 <= i < n``). - - Default: ``"wrap"``. - - Returns: - usm_ndarray: - an array having the same data type as ``x``. The returned array has - the same rank (i.e., number of dimensions) as ``x`` and a shape - determined according to broadcasting rules, except for the axis - (dimension) specified by ``axis`` whose size must equal the size - of the corresponding axis (dimension) in ``indices``. - - Note: - Treatment of the out-of-bound indices in ``indices`` array is controlled - by the value of ``mode`` keyword. + Parameters + ---------- + x : usm_ndarray + input array. Must be compatible with ``indices``, except for the + axis (dimension) specified by ``axis``. + indices : usm_ndarray + array indices. Must have the same rank (i.e., number of dimensions) + as ``x``. + axis : int, optional + axis along which to select values. If ``axis`` is negative, the + function determines the axis along which to select values by + counting from the last dimension. + + Default: ``-1``. + mode : {"wrap", "clip"}, optional + How out-of-bounds indices will be handled. Possible values + are: + + * ``"wrap"``: clamps indices to (``-n <= i < n``), then wraps negative indices. + * ``"clip"``: clips indices to (``0 <= i < n``). + + Default: ``"wrap"``. + + Returns + ------- + out : usm_ndarray + an array having the same data type as ``x``. The returned array has + the same rank (i.e., number of dimensions) as ``x`` and a shape + determined according to broadcasting rules, except for the axis + (dimension) specified by ``axis`` whose size must equal the size + of the corresponding axis (dimension) in ``indices``. + + Notes + ----- + Treatment of the out-of-bound indices in ``indices`` array is controlled + by the value of ``mode`` keyword. + """ + if not isinstance(x, dpt.usm_ndarray): raise TypeError(f"Expected dpnp.tensor.usm_ndarray, got {type(x)}") if not isinstance(indices, dpt.usm_ndarray): From f8db906b48e784e47e6f63594381248a712d454e Mon Sep 17 00:00:00 2001 From: Vladislav Perevezentsev Date: Tue, 7 Apr 2026 05:56:24 -0700 Subject: [PATCH 12/46] Update _elementwise_funcs.py doc to Sphinx format --- dpnp/tensor/_elementwise_funcs.py | 1561 ++++++++++++++++++----------- 1 file changed, 962 insertions(+), 599 deletions(-) diff --git a/dpnp/tensor/_elementwise_funcs.py b/dpnp/tensor/_elementwise_funcs.py index 4040f33bf38..a04a36e0d28 100644 --- a/dpnp/tensor/_elementwise_funcs.py +++ b/dpnp/tensor/_elementwise_funcs.py @@ -40,29 +40,35 @@ # U01: ==== ABS (x) _abs_docstring_ = r""" -abs(x, /, \*, out=None, order='K') Calculates the absolute value for each element `x_i` of input array `x`. -Args: - x (usm_ndarray): +Parameters +---------- + x : usm_ndarray Input array. May have any data type. - out (Union[usm_ndarray, None], optional): + out : {None, usm_ndarray}, optional Output array to populate. Array must have the correct shape and the expected data type. - order ("C","F","A","K", optional): + + Default: ``None``. + order : {"C", "F", "A", "K"}, optional Memory layout of the new output array, if parameter `out` is ``None``. - Default: `"K"`. -Returns: - usm_ndarray: + + Default: ``"K"``. + +Returns +------- + out : usm_ndarray An array containing the element-wise absolute values. For complex input, the absolute value is its magnitude. If `x` has a real-valued data type, the returned array has the same data type as `x`. If `x` has a complex floating-point data type, the returned array has a real-valued floating-point data type whose precision matches the precision of `x`. + """ abs = UnaryElementwiseFunc("abs", ti._abs_result_type, ti._abs, _abs_docstring_) @@ -70,26 +76,31 @@ # U02: ==== ACOS (x) _acos_docstring = r""" -acos(x, /, \*, out=None, order='K') Computes inverse cosine for each element `x_i` for input array `x`. -Args: - x (usm_ndarray): +Parameters +---------- + x : usm_ndarray Input array, expected to have a floating-point data type. - out (Union[usm_ndarray, None], optional): + out : {None, usm_ndarray}, optional Output array to populate. Array must have the correct shape and the expected data type. - order ("C","F","A","K", optional): + + Default: ``None``. + order : {"C", "F", "A", "K"}, optional Memory layout of the new output array, if parameter `out` is ``None``. - Default: "K". -Returns: - usm_ndarray: + Default: ``"K"``. + +Returns +------- + out : usm_ndarray An array containing the element-wise inverse cosine, in radians and in the closed interval :math:`[0, \pi]`. The data type of the returned array is determined by the Type Promotion Rules. + """ acos = UnaryElementwiseFunc( @@ -99,26 +110,31 @@ # U03: ===== ACOSH (x) _acosh_docstring = r""" -acosh(x, /, \*, out=None, order='K') Computes inverse hyperbolic cosine for each element `x_i` for input array `x`. -Args: - x (usm_ndarray): +Parameters +---------- + x : usm_ndarray Input array, expected to have a floating-point data type. - out (Union[usm_ndarray, None], optional): + out : {None, usm_ndarray}, optional Output array to populate. Array must have the correct shape and the expected data type. - order ("C","F","A","K", optional): + + Default: ``None``. + order : {"C", "F", "A", "K"}, optional Memory layout of the new output array, if parameter `out` is ``None``. - Default: "K". -Returns: - usm_ndarray: + Default: ``"K"``. + +Returns +------- + out : usm_ndarray An array containing the element-wise inverse hyperbolic cosine, in radians and in the half-closed interval :math:`[0, \infty)`. The data type of the returned array is determined by the Type Promotion Rules. + """ acosh = UnaryElementwiseFunc( @@ -129,29 +145,35 @@ # B01: ===== ADD (x1, x2) _add_docstring_ = r""" -add(x1, x2, /, \*, out=None, order='K') Calculates the sum for each element `x1_i` of the input array `x1` with the respective element `x2_i` of the input array `x2`. -Args: - x1 (usm_ndarray): +Parameters +---------- + x1 : usm_ndarray First input array. May have any data type. - x2 (usm_ndarray): + x2 : usm_ndarray Second input array. May have any data type. - out (Union[usm_ndarray, None], optional): + out : {None, usm_ndarray}, optional Output array to populate. Array must have the correct shape and the expected data type. - order ("C","F","A","K", optional): + + Default: ``None``. + order : {"C", "F", "A", "K"}, optional Memory layout of the new output array, if parameter `out` is ``None``. - Default: "K". -Returns: - usm_ndarray: + Default: ``"K"``. + +Returns +------- + out : usm_ndarray An array containing the element-wise sums. The data type of the returned array is determined by the Type Promotion Rules. + """ + add = BinaryElementwiseFunc( "add", ti._add_result_type, @@ -163,26 +185,31 @@ # U04: ===== ASIN (x) _asin_docstring = r""" -asin(x, /, \*, out=None, order='K') Computes inverse sine for each element `x_i` for input array `x`. -Args: - x (usm_ndarray): +Parameters +---------- + x : usm_ndarray Input array, expected to have a floating-point data type. - out (Union[usm_ndarray, None], optional): + out : {None, usm_ndarray}, optional Output array to populate. Array must have the correct shape and the expected data type. - order ("C","F","A","K", optional): + + Default: ``None``. + order : {"C", "F", "A", "K"}, optional Memory layout of the new output array, if parameter `out` is ``None``. - Default: "K". -Returns: - usm_ndarray: + Default: ``"K"``. + +Returns +------- + out : usm_ndarray An array containing the element-wise inverse sine, in radians and in the closed interval :math:`[-\pi/2, \pi/2]`. The data type of the returned array is determined by the Type Promotion Rules. + """ asin = UnaryElementwiseFunc( @@ -192,26 +219,31 @@ # U05: ===== ASINH (x) _asinh_docstring = r""" -asinh(x, /, \*, out=None, order='K') Computes inverse hyperbolic sine for each element `x_i` for input array `x`. -Args: - x (usm_ndarray): +Parameters +---------- + x : usm_ndarray Input array, expected to have a floating-point data type. - out (Union[usm_ndarray, None], optional): + out : {None, usm_ndarray}, optional Output array to populate. Array must have the correct shape and the expected data type. - order ("C","F","A","K", optional): + + Default: ``None``. + order : {"C", "F", "A", "K"}, optional Memory layout of the new output array, if parameter `out` is ``None``. - Default: "K". -Returns: - usm_ndarray: + Default: ``"K"``. + +Returns +------- + out : usm_ndarray An array containing the element-wise inverse hyperbolic sine, in radians. The data type of the returned array is determined by the Type Promotion Rules. + """ asinh = UnaryElementwiseFunc( @@ -221,26 +253,31 @@ # U06: ===== ATAN (x) _atan_docstring = r""" -atan(x, /, \*, out=None, order='K') Computes inverse tangent for each element `x_i` for input array `x`. -Args: - x (usm_ndarray): +Parameters +---------- + x : usm_ndarray Input array, expected to have a floating-point data type. - out (Union[usm_ndarray, None], optional): + out : {None, usm_ndarray}, optional Output array to populate. Array must have the correct shape and the expected data type. - order ("C","F","A","K", optional): + + Default: ``None``. + order : {"C", "F", "A", "K"}, optional Memory layout of the new output array, if parameter `out` is ``None``. - Default: "K". -Returns: - usm_ndarray: + Default: ``"K"``. + +Returns +------- + out : usm_ndarray An array containing the element-wise inverse tangent, in radians and in the closed interval :math:`[-\pi/2, \pi/2]`. The data type of the returned array is determined by the Type Promotion Rules. + """ atan = UnaryElementwiseFunc( @@ -250,32 +287,36 @@ # B02: ===== ATAN2 (x1, x2) _atan2_docstring_ = r""" -atan2(x1, x2, /, \*, out=None, order='K') - Calculates the inverse tangent of the quotient `x1_i/x2_i` for each element `x1_i` of the input array `x1` with the respective element `x2_i` of the input array `x2`. Each element-wise result is expressed in radians. -Args: - x1 (usm_ndarray): +Parameters +---------- + x1 : usm_ndarray First input array, expected to have a real-valued floating-point data type. - x2 (usm_ndarray): + x2 : usm_ndarray Second input array, also expected to have a real-valued floating-point data type. - out (Union[usm_ndarray, None], optional): + out : {None, usm_ndarray}, optional Output array to populate. Array must have the correct shape and the expected data type. - order ("C","F","A","K", optional): + + Default: ``None``. + order : {"C", "F", "A", "K"}, optional Memory layout of the new output array, if parameter `out` is ``None``. - Default: "K". -Returns: - usm_ndarray: + Default: ``"K"``. + +Returns +------- + out : usm_ndarray An array containing the inverse tangent of the quotient `x1`/`x2`. The returned array must have a real-valued floating-point data type determined by Type Promotion Rules. + """ atan2 = BinaryElementwiseFunc( @@ -285,26 +326,31 @@ # U07: ===== ATANH (x) _atanh_docstring = r""" -atanh(x, /, \*, out=None, order='K') Computes hyperbolic inverse tangent for each element `x_i` for input array `x`. -Args: - x (usm_ndarray): +Parameters +---------- + x : usm_ndarray Input array, expected to have a floating-point data type. - out (Union[usm_ndarray, None], optional): + out : {None, usm_ndarray}, optional Output array to populate. Array must have the correct shape and the expected data type. - order ("C","F","A","K", optional): + + Default: ``None``. + order : {"C", "F", "A", "K"}, optional Memory layout of the new output array, if parameter `out` is ``None``. - Default: "K". -Returns: - usm_ndarray: + Default: ``"K"``. + +Returns +------- + out : usm_ndarray An array containing the element-wise hyperbolic inverse tangent, in radians. The data type of the returned array is determined by the Type Promotion Rules. + """ atanh = UnaryElementwiseFunc( @@ -314,30 +360,35 @@ # B03: ===== BITWISE_AND (x1, x2) _bitwise_and_docstring_ = r""" -bitwise_and(x1, x2, /, \*, out=None, order='K') Computes the bitwise AND of the underlying binary representation of each element `x1_i` of the input array `x1` with the respective element `x2_i` of the input array `x2`. -Args: - x1 (usm_ndarray): +Parameters +---------- + x1 : usm_ndarray First input array, expected to have integer or boolean data type. - x2 (usm_ndarray): + x2 : usm_ndarray Second input array, also expected to have integer or boolean data type. - out (Union[usm_ndarray, None], optional): + out : {None, usm_ndarray}, optional Output array to populate. Array must have the correct shape and the expected data type. - order ("C","F","A","K", optional): + + Default: ``None``. + order : {"C", "F", "A", "K"}, optional Memory layout of the new output array, if parameter `out` is ``None``. - Default: "K". -Returns: - usm_ndarray: + Default: ``"K"``. + +Returns +------- + out : usm_ndarray An array containing the element-wise results. The data type of the returned array is determined by the Type Promotion Rules. + """ bitwise_and = BinaryElementwiseFunc( @@ -351,30 +402,35 @@ # B04: ===== BITWISE_LEFT_SHIFT (x1, x2) _bitwise_left_shift_docstring_ = r""" -bitwise_left_shift(x1, x2, /, \*, out=None, order='K') Shifts the bits of each element `x1_i` of the input array x1 to the left by appending `x2_i` (i.e., the respective element in the input array `x2`) zeros to the right of `x1_i`. -Args: - x1 (usm_ndarray): +Parameters +---------- + x1 : usm_ndarray First input array, expected to have integer data type. - x2 (usm_ndarray): + x2 : usm_ndarray Second input array, also expected to have integer data type. Each element must be greater than or equal to 0. - out (Union[usm_ndarray, None], optional): + out : {None, usm_ndarray}, optional Output array to populate. Array must have the correct shape and the expected data type. - order ("C","F","A","K", optional): + + Default: ``None``. + order : {"C", "F", "A", "K"}, optional Memory layout of the new output array, if parameter `out` is ``None``. - Default: "K". -Returns: - usm_ndarray: + Default: ``"K"``. + +Returns +------- + out : usm_ndarray An array containing the element-wise results. The data type of the returned array is determined by the Type Promotion Rules. + """ bitwise_left_shift = BinaryElementwiseFunc( @@ -388,26 +444,31 @@ # U08: ===== BITWISE_INVERT (x) _bitwise_invert_docstring = r""" -bitwise_invert(x, /, \*, out=None, order='K') Inverts (flips) each bit for each element `x_i` of the input array `x`. -Args: - x (usm_ndarray): +Parameters +---------- + x : usm_ndarray Input array, expected to have integer or boolean data type. - out (Union[usm_ndarray, None], optional): + out : {None, usm_ndarray}, optional Output array to populate. Array must have the correct shape and the expected data type. - order ("C","F","A","K", optional): + + Default: ``None``. + order : {"C", "F", "A", "K"}, optional Memory layout of the new output array, if parameter `out` is ``None``. - Default: "K". -Returns: - usm_ndarray: + Default: ``"K"``. + +Returns +------- + out : usm_ndarray An array containing the element-wise results. The data type of the returned array is same as the data type of the input array. + """ bitwise_invert = UnaryElementwiseFunc( @@ -420,30 +481,35 @@ # B05: ===== BITWISE_OR (x1, x2) _bitwise_or_docstring_ = r""" -bitwise_or(x1, x2, /, \*, out=None, order='K') Computes the bitwise OR of the underlying binary representation of each element `x1_i` of the input array `x1` with the respective element `x2_i` of the input array `x2`. -Args: - x1 (usm_ndarray): +Parameters +---------- + x1 : usm_ndarray First input array, expected to have integer or boolean data type. - x2 (usm_ndarray): + x2 : usm_ndarray Second input array, also expected to have integer or boolean data type. - out (Union[usm_ndarray, None], optional): + out : {None, usm_ndarray}, optional Output array to populate. Array must have the correct shape and the expected data type. - order ("C","F","A","K", optional): + + Default: ``None``. + order : {"C", "F", "A", "K"}, optional Memory layout of the new output array, if parameter `out` is ``None``. - Default: "K". -Returns: - usm_ndarray: + Default: ``"K"``. + +Returns +------- + out : usm_ndarray An array containing the element-wise results. The data type of the returned array is determined by the Type Promotion Rules. + """ bitwise_or = BinaryElementwiseFunc( @@ -457,29 +523,34 @@ # B06: ===== BITWISE_RIGHT_SHIFT (x1, x2) _bitwise_right_shift_docstring_ = r""" -bitwise_right_shift(x1, x2, /, \*, out=None, order='K') Shifts the bits of each element `x1_i` of the input array `x1` to the right according to the respective element `x2_i` of the input array `x2`. -Args: - x1 (usm_ndarray): +Parameters +---------- + x1 : usm_ndarray First input array, expected to have integer data type. - x2 (usm_ndarray): + x2 : usm_ndarray Second input array, also expected to have integer data type. Each element must be greater than or equal to 0. - out (Union[usm_ndarray, None], optional): + out : {None, usm_ndarray}, optional Output array to populate. Array must have the correct shape and the expected data type. - order ("C","F","A","K", optional): + + Default: ``None``. + order : {"C", "F", "A", "K"}, optional Memory layout of the new output array, if parameter `out` is ``None``. - Default: "K". -Returns: - usm_ndarray: + Default: ``"K"``. + +Returns +------- + out : usm_ndarray An array containing the element-wise results. The data type of the returned array is determined by the Type Promotion Rules. + """ bitwise_right_shift = BinaryElementwiseFunc( @@ -494,30 +565,35 @@ # B07: ===== BITWISE_XOR (x1, x2) _bitwise_xor_docstring_ = r""" -bitwise_xor(x1, x2, /, \*, out=None, order='K') Computes the bitwise XOR of the underlying binary representation of each element `x1_i` of the input array `x1` with the respective element `x2_i` of the input array `x2`. -Args: - x1 (usm_ndarray): +Parameters +---------- + x1 : usm_ndarray First input array, expected to have integer or boolean data type. - x2 (usm_ndarray): + x2 : usm_ndarray Second input array, also expected to have integer or boolean data type. - out (Union[usm_ndarray, None], optional): + out : {None, usm_ndarray}, optional Output array to populate. Array must have the correct shape and the expected data type. - order ("C","F","A","K", optional): + + Default: ``None``. + order : {"C", "F", "A", "K"}, optional Memory layout of the new output array, if parameter `out` is ``None``. - Default: "K". -Returns: - usm_ndarray: + Default: ``"K"``. + +Returns +------- + out : usm_ndarray An array containing the element-wise results. The data type of the returned array is determined by the Type Promotion Rules. + """ bitwise_xor = BinaryElementwiseFunc( @@ -531,26 +607,31 @@ # U09: ==== CEIL (x) _ceil_docstring = r""" -ceil(x, /, \*, out=None, order='K') Returns the ceiling for each element `x_i` for input array `x`. The ceil of `x_i` is the smallest integer `n`, such that `n >= x_i`. -Args: - x (usm_ndarray): +Parameters +---------- + x : usm_ndarray Input array, expected to have a boolean or real-valued data type. - out (Union[usm_ndarray, None], optional): + out : {None, usm_ndarray}, optional Output array to populate. Array must have the correct shape and the expected data type. - order ("C","F","A","K", optional): + + Default: ``None``. + order : {"C", "F", "A", "K"}, optional Memory layout of the new output array, if parameter `out` is ``None``. - Default: "K". -Returns: - usm_ndarray: + Default: ``"K"``. + +Returns +------- + out : usm_ndarray An array containing the element-wise ceiling. + """ ceil = UnaryElementwiseFunc( @@ -560,24 +641,29 @@ # U10: ==== CONJ (x) _conj_docstring = r""" -conj(x, /, \*, out=None, order='K') Computes conjugate of each element `x_i` for input array `x`. -Args: - x (usm_ndarray): +Parameters +---------- + x : usm_ndarray Input array. May have any data type. - out (Union[usm_ndarray, None], optional): + out : {None, usm_ndarray}, optional Output array to populate. Array must have the correct shape and the expected data type. - order ("C","F","A","K", optional): + + Default: ``None``. + order : {"C", "F", "A", "K"}, optional Memory layout of the new output array, if parameter `out` is ``None``. - Default: "K". -Returns: - usm_ndarray: + Default: ``"K"``. + +Returns +------- + out : usm_ndarray An array containing the element-wise conjugate values. + """ conj = UnaryElementwiseFunc( @@ -587,25 +673,30 @@ # U11: ==== COS (x) _cos_docstring = r""" -cos(x, /, \*, out=None, order='K') Computes cosine for each element `x_i` for input array `x`. -Args: - x (usm_ndarray): +Parameters +---------- + x : usm_ndarray Input array, expected to have a floating-point data type. - out (Union[usm_ndarray, None], optional): + out : {None, usm_ndarray}, optional Output array to populate. Array must have the correct shape and the expected data type. - order ("C","F","A","K", optional): + + Default: ``None``. + order : {"C", "F", "A", "K"}, optional Memory layout of the new output array, if parameter `out` is ``None``. - Default: "K". -Returns: - usm_ndarray: + Default: ``"K"``. + +Returns +------- + out : usm_ndarray An array containing the element-wise cosine. The data type of the returned array is determined by the Type Promotion Rules. + """ cos = UnaryElementwiseFunc("cos", ti._cos_result_type, ti._cos, _cos_docstring) @@ -613,25 +704,30 @@ # U12: ==== COSH (x) _cosh_docstring = r""" -cosh(x, /, \*, out=None, order='K') Computes hyperbolic cosine for each element `x_i` for input array `x`. -Args: - x (usm_ndarray): +Parameters +---------- + x : usm_ndarray Input array, expected to have a floating-point data type. - out (Union[usm_ndarray, None], optional): + out : {None, usm_ndarray}, optional Output array to populate. Array must have the correct shape and the expected data type. - order ("C","F","A","K", optional): + + Default: ``None``. + order : {"C", "F", "A", "K"}, optional Memory layout of the new output array, if parameter `out` is ``None``. - Default: "K". -Returns: - usm_ndarray: + Default: ``"K"``. + +Returns +------- + out : usm_ndarray An array containing the element-wise hyperbolic cosine. The data type of the returned array is determined by the Type Promotion Rules. + """ cosh = UnaryElementwiseFunc( @@ -641,28 +737,33 @@ # B08: ==== DIVIDE (x1, x2) _divide_docstring_ = r""" -divide(x1, x2, /, \*, out=None, order='K') Calculates the ratio for each element `x1_i` of the input array `x1` with the respective element `x2_i` of the input array `x2`. -Args: - x1 (usm_ndarray): +Parameters +---------- + x1 : usm_ndarray First input array, expected to have a floating-point data type. - x2 (usm_ndarray): + x2 : usm_ndarray Second input array, also expected to have a floating-point data type. - out (Union[usm_ndarray, None], optional): + out : {None, usm_ndarray}, optional Output array to populate. Array must have the correct shape and the expected data type. - order ("C","F","A","K", optional): + + Default: ``None``. + order : {"C", "F", "A", "K"}, optional Memory layout of the new output array, if parameter `out` is ``None``. - Default: "K". -Returns: - usm_ndarray: + Default: ``"K"``. + +Returns +------- + out : usm_ndarray An array containing the result of element-wise division. The data type of the returned array is determined by the Type Promotion Rules. + """ divide = BinaryElementwiseFunc( @@ -678,28 +779,33 @@ # B09: ==== EQUAL (x1, x2) _equal_docstring_ = r""" -equal(x1, x2, /, \*, out=None, order='K') Calculates equality test results for each element `x1_i` of the input array `x1` with the respective element `x2_i` of the input array `x2`. -Args: - x1 (usm_ndarray): +Parameters +---------- + x1 : usm_ndarray First input array. May have any data type. - x2 (usm_ndarray): + x2 : usm_ndarray Second input array. May have any data type. - out (Union[usm_ndarray, None], optional): + out : {None, usm_ndarray}, optional Output array to populate. Array must have the correct shape and the expected data type. - order ("C","F","A","K", optional): + + Default: ``None``. + order : {"C", "F", "A", "K"}, optional Memory layout of the new output array, if parameter `out` is ``None``. - Default: "K". -Returns: - usm_ndarray: + Default: ``"K"``. + +Returns +------- + out : usm_ndarray An array containing the result of element-wise equality comparison. The returned array has a data type of `bool`. + """ equal = BinaryElementwiseFunc( @@ -713,26 +819,31 @@ # U13: ==== EXP (x) _exp_docstring = r""" -exp(x, /, \*, out=None, order='K') Computes the exponential for each element `x_i` of input array `x`. -Args: - x (usm_ndarray): +Parameters +---------- + x : usm_ndarray Input array, expected to have a floating-point data type. - out (Union[usm_ndarray, None], optional): + out : {None, usm_ndarray}, optional Output array to populate. Array must have the correct shape and the expected data type. - order ("C","F","A","K", optional): + + Default: ``None``. + order : {"C", "F", "A", "K"}, optional Memory layout of the new output array, if parameter `out` is ``None``. - Default: "K". -Returns: - usm_ndarray: + Default: ``"K"``. + +Returns +------- + out : usm_ndarray An array containing the element-wise exponential of `x`. The data type of the returned array is determined by the Type Promotion Rules. + """ exp = UnaryElementwiseFunc("exp", ti._exp_result_type, ti._exp, _exp_docstring) @@ -740,30 +851,35 @@ # B10: ==== FLOOR_DIVIDE (x1, x2) _floor_divide_docstring_ = r""" -floor_divide(x1, x2, /, \*, out=None, order='K') Calculates the ratio for each element `x1_i` of the input array `x1` with the respective element `x2_i` of the input array `x2` to the greatest integer-value number that is not greater than the division result. -Args: - x1 (usm_ndarray): +Parameters +---------- + x1 : usm_ndarray First input array, expected to have a real-valued data type. - x2 (usm_ndarray): + x2 : usm_ndarray Second input array, also expected to have a real-valued data type. - out (Union[usm_ndarray, None], optional): + out : {None, usm_ndarray}, optional Output array to populate. Array must have the correct shape and the expected data type. - order ("C","F","A","K", optional): + + Default: ``None``. + order : {"C", "F", "A", "K"}, optional Memory layout of the new output array, if parameter `out` is ``None``. - Default: "K". -Returns: - usm_ndarray: + Default: ``"K"``. + +Returns +------- + out : usm_ndarray An array containing the result of element-wise floor of division. The data type of the returned array is determined by the Type Promotion Rules. + """ floor_divide = BinaryElementwiseFunc( @@ -777,28 +893,33 @@ # B11: ==== GREATER (x1, x2) _greater_docstring_ = r""" -greater(x1, x2, /, \*, out=None, order='K') Computes the greater-than test results for each element `x1_i` of the input array `x1` with the respective element `x2_i` of the input array `x2`. -Args: - x1 (usm_ndarray): +Parameters +---------- + x1 : usm_ndarray First input array. May have any data type. - x2 (usm_ndarray): + x2 : usm_ndarray Second input array. May have any data type. - out (Union[usm_ndarray, None], optional): + out : {None, usm_ndarray}, optional Output array to populate. Array must have the correct shape and the expected data type. - order ("C","F","A","K", optional): + + Default: ``None``. + order : {"C", "F", "A", "K"}, optional Memory layout of the new output array, if parameter `out` is ``None``. - Default: "K". -Returns: - usm_ndarray: + Default: ``"K"``. + +Returns +------- + out : usm_ndarray An array containing the result of element-wise greater-than comparison. The returned array has a data type of `bool`. + """ greater = BinaryElementwiseFunc( @@ -812,29 +933,34 @@ # B12: ==== GREATER_EQUAL (x1, x2) _greater_equal_docstring_ = r""" -greater_equal(x1, x2, /, \*, out=None, order='K') Computes the greater-than or equal-to test results for each element `x1_i` of the input array `x1` with the respective element `x2_i` of the input array `x2`. -Args: - x1 (usm_ndarray): +Parameters +---------- + x1 : usm_ndarray First input array. May have any data type. - x2 (usm_ndarray): + x2 : usm_ndarray Second input array. May have any data type. - out (Union[usm_ndarray, None], optional): + out : {None, usm_ndarray}, optional Output array to populate. Array must have the correct shape and the expected data type. - order ("C","F","A","K", optional): + + Default: ``None``. + order : {"C", "F", "A", "K"}, optional Memory layout of the new output array, if parameter `out` is ``None``. - Default: "K". -Returns: - usm_ndarray: + Default: ``"K"``. + +Returns +------- + out : usm_ndarray An array containing the result of element-wise greater-than or equal-to comparison. The returned array has a data type of `bool`. + """ greater_equal = BinaryElementwiseFunc( @@ -854,21 +980,26 @@ This function calculates `exp(x) - 1.0` more accurately for small values of `x`. -Args: - x (usm_ndarray): +Parameters +---------- + x : usm_ndarray Input array, expected to have a floating-point data type. - out (usm_ndarray): + out : usm_ndarray Output array to populate. Array must have the correct shape and the expected data type. - order ("C","F","A","K", optional): memory layout of the new - output array, if parameter `out` is ``None``. - Default: "K". + order : {"C", "F", "A", "K"}, optional + Memory layout of the new output array, if parameter + `out` is ``None``. -Returns: - usm_ndarray: + Default: ``"K"``. + +Returns +------- + out : usm_ndarray An array containing the element-wise `exp(x) - 1` results. The data type of the returned array is determined by the Type Promotion Rules. + """ expm1 = UnaryElementwiseFunc( @@ -878,26 +1009,31 @@ # U15: ==== FLOOR (x) _floor_docstring = r""" -floor(x, /, \*, out=None, order='K') Returns the floor for each element `x_i` for input array `x`. The floor of `x_i` is the largest integer `n`, such that `n <= x_i`. -Args: - x (usm_ndarray): +Parameters +---------- + x : usm_ndarray Input array, expected to have a boolean or real-valued data type. - out (Union[usm_ndarray, None], optional): + out : {None, usm_ndarray}, optional Output array to populate. Array must have the correct shape and the expected data type. - order ("C","F","A","K", optional): + + Default: ``None``. + order : {"C", "F", "A", "K"}, optional Memory layout of the new output array, if parameter `out` is ``None``. - Default: "K". -Returns: - usm_ndarray: + Default: ``"K"``. + +Returns +------- + out : usm_ndarray An array containing the element-wise floor. + """ floor = UnaryElementwiseFunc( @@ -907,28 +1043,33 @@ # U16: ==== IMAG (x) _imag_docstring = r""" -imag(x, /, \*, out=None, order='K') Computes imaginary part of each element `x_i` for input array `x`. -Args: - x (usm_ndarray): +Parameters +---------- + x : usm_ndarray Input array. May have any data type. - out (Union[usm_ndarray, None], optional): + out : {None, usm_ndarray}, optional Output array to populate. Array must have the correct shape and the expected data type. - order ("C","F","A","K", optional): + + Default: ``None``. + order : {"C", "F", "A", "K"}, optional Memory layout of the new output array, if parameter `out` is ``None``. - Default: "K". -Returns: - usm_ndarray: + Default: ``"K"``. + +Returns +------- + out : usm_ndarray An array containing the element-wise imaginary component of input. If the input is a real-valued data type, the returned array has the same data type. If the input is a complex floating-point data type, the returned array has a floating-point data type with the same floating-point precision as complex input. + """ imag = UnaryElementwiseFunc( @@ -938,26 +1079,31 @@ # U17: ==== ISFINITE (x) _isfinite_docstring_ = r""" -isfinite(x, /, \*, out=None, order='K') Test if each element of input array is a finite number. -Args: - x (usm_ndarray): +Parameters +---------- + x : usm_ndarray Input array. May have any data type. - out (Union[usm_ndarray, None], optional): + out : {None, usm_ndarray}, optional Output array to populate. Array must have the correct shape and the expected data type. - order ("C","F","A","K", optional): + + Default: ``None``. + order : {"C", "F", "A", "K"}, optional Memory layout of the new output array, if parameter `out` is ``None``. - Default: "K". -Returns: - usm_ndarray: + Default: ``"K"``. + +Returns +------- + out : usm_ndarray An array which is True where `x` is not positive infinity, negative infinity, or NaN, False otherwise. The data type of the returned array is `bool`. + """ isfinite = UnaryElementwiseFunc( @@ -967,25 +1113,30 @@ # U18: ==== ISINF (x) _isinf_docstring_ = r""" -isinf(x, /, \*, out=None, order='K') Test if each element of input array is an infinity. -Args: - x (usm_ndarray): +Parameters +---------- + x : usm_ndarray Input array. May have any data type. - out (Union[usm_ndarray, None], optional): + out : {None, usm_ndarray}, optional Output array to populate. Array must have the correct shape and the expected data type. - order ("C","F","A","K", optional): + + Default: ``None``. + order : {"C", "F", "A", "K"}, optional Memory layout of the new output array, if parameter `out` is ``None``. - Default: "K". -Returns: - usm_ndarray: + Default: ``"K"``. + +Returns +------- + out : usm_ndarray An array which is True where `x` is positive or negative infinity, False otherwise. The data type of the returned array is `bool`. + """ isinf = UnaryElementwiseFunc( @@ -995,25 +1146,30 @@ # U19: ==== ISNAN (x) _isnan_docstring_ = r""" -isnan(x, /, \*, out=None, order='K') Test if each element of an input array is a NaN. -Args: - x (usm_ndarray): +Parameters +---------- + x : usm_ndarray Input array. May have any data type. - out (Union[usm_ndarray, None], optional): + out : {None, usm_ndarray}, optional Output array to populate. Array must have the correct shape and the expected data type. - order ("C","F","A","K", optional): + + Default: ``None``. + order : {"C", "F", "A", "K"}, optional Memory layout of the new output array, if parameter `out` is ``None``. - Default: "K". -Returns: - usm_ndarray: + Default: ``"K"``. + +Returns +------- + out : usm_ndarray An array which is True where x is NaN, False otherwise. The data type of the returned array is `bool`. + """ isnan = UnaryElementwiseFunc( @@ -1023,28 +1179,33 @@ # B13: ==== LESS (x1, x2) _less_docstring_ = r""" -less(x1, x2, /, \*, out=None, order='K') Computes the less-than test results for each element `x1_i` of the input array `x1` with the respective element `x2_i` of the input array `x2`. -Args: - x1 (usm_ndarray): +Parameters +---------- + x1 : usm_ndarray First input array. May have any data type. - x2 (usm_ndarray): + x2 : usm_ndarray Second input array. May have any data type. - out (Union[usm_ndarray, None], optional): + out : {None, usm_ndarray}, optional Output array to populate. Array must have the correct shape and the expected data type. - order ("C","F","A","K", optional): + + Default: ``None``. + order : {"C", "F", "A", "K"}, optional Memory layout of the new output array, if parameter `out` is ``None``. - Default: "K". -Returns: - usm_ndarray: + Default: ``"K"``. + +Returns +------- + out : usm_ndarray An array containing the result of element-wise less-than comparison. The returned array has a data type of `bool`. + """ less = BinaryElementwiseFunc( @@ -1059,28 +1220,33 @@ # B14: ==== LESS_EQUAL (x1, x2) _less_equal_docstring_ = r""" -less_equal(x1, x2, /, \*, out=None, order='K') Computes the less-than or equal-to test results for each element `x1_i` of the input array `x1` with the respective element `x2_i` of the input array `x2`. -Args: - x1 (usm_ndarray): +Parameters +---------- + x1 : usm_ndarray First input array. May have any data type. - x2 (usm_ndarray): + x2 : usm_ndarray Second input array. May have any data type. - out (Union[usm_ndarray, None], optional): + out : {None, usm_ndarray}, optional Output array to populate. Array must have the correct shape and the expected data type. - order ("C","F","A","K", optional): + + Default: ``None``. + order : {"C", "F", "A", "K"}, optional Memory layout of the new output array, if parameter `out` is ``None``. - Default: "K". -Returns: - usm_ndarray: + Default: ``"K"``. + +Returns +------- + out : usm_ndarray An array containing the result of element-wise less-than or equal-to comparison. The returned array has a data type of `bool`. + """ less_equal = BinaryElementwiseFunc( @@ -1094,25 +1260,29 @@ # U20: ==== LOG (x) _log_docstring = r""" -log(x, /, \*, out=None, order='K') Computes the natural logarithm for each element `x_i` of input array `x`. -Args: - x (usm_ndarray): +Parameters +---------- + x : usm_ndarray Input array, expected to have a floating-point data type. - out (usm_ndarray): + out : usm_ndarray Output array to populate. Array must have the correct shape and the expected data type. - order ("C","F","A","K", optional): memory layout of the new - output array, if parameter `out` is ``None``. - Default: "K". + order : {"C", "F", "A", "K"}, optional + Memory layout of the new output array, if parameter + `out` is ``None``. + + Default: ``"K"``. -Returns: - usm_ndarray: +Returns +------- + out : usm_ndarray An array containing the element-wise natural logarithm values. The data type of the returned array is determined by the Type Promotion Rules. + """ log = UnaryElementwiseFunc("log", ti._log_result_type, ti._log, _log_docstring) @@ -1127,20 +1297,25 @@ This function calculates `log(1 + x)` more accurately for small values of `x`. -Args: - x (usm_ndarray): +Parameters +---------- + x : usm_ndarray Input array, expected to have a floating-point data type. - out (usm_ndarray): + out : usm_ndarray Output array to populate. Array must have the correct shape and the expected data type. - order ("C","F","A","K", optional): memory layout of the new - output array, if parameter `out` is ``None``. - Default: "K". + order : {"C", "F", "A", "K"}, optional + Memory layout of the new output array, if parameter + `out` is ``None``. -Returns: - usm_ndarray: + Default: ``"K"``. + +Returns +------- + out : usm_ndarray An array containing the element-wise `log(1 + x)` results. The data type of the returned array is determined by the Type Promotion Rules. + """ log1p = UnaryElementwiseFunc( @@ -1154,22 +1329,28 @@ Computes the base-2 logarithm for each element `x_i` of input array `x`. -Args: - x (usm_ndarray): +Parameters +---------- + x : usm_ndarray Input array, expected to have a floating-point data type. - out (Union[usm_ndarray, None], optional): + out : {None, usm_ndarray}, optional Output array to populate. Array must have the correct shape and the expected data type. - order ("C","F","A","K", optional): + + Default: ``None``. + order : {"C", "F", "A", "K"}, optional Memory layout of the new output array, if parameter `out` is ``None``. - Default: "K". -Returns: - usm_ndarray: + Default: ``"K"``. + +Returns +------- + out : usm_ndarray An array containing the element-wise base-2 logarithm of `x`. The data type of the returned array is determined by the Type Promotion Rules. + """ log2 = UnaryElementwiseFunc( @@ -1183,22 +1364,28 @@ Computes the base-10 logarithm for each element `x_i` of input array `x`. -Args: - x (usm_ndarray): +Parameters +---------- + x : usm_ndarray Input array, expected to have a floating-point data type. - out (Union[usm_ndarray, None], optional): + out : {None, usm_ndarray}, optional Output array to populate. Array must have the correct shape and the expected data type. - order ("C","F","A","K", optional): + + Default: ``None``. + order : {"C", "F", "A", "K"}, optional Memory layout of the new output array, if parameter `out` is ``None``. - Default: `"K"`. -Returns: - usm_ndarray: + Default: ``"K"``. + +Returns +------- + out : usm_ndarray An array containing the element-wise base-10 logarithm of `x`. The data type of the returned array is determined by the Type Promotion Rules. + """ log10 = UnaryElementwiseFunc( @@ -1208,7 +1395,6 @@ # B15: ==== LOGADDEXP (x1, x2) _logaddexp_docstring_ = r""" -logaddexp(x1, x2, /, \*, out=None, order='K') Calculates the natural logarithm of the sum of exponentials for each element `x1_i` of the input array `x1` with the respective element `x2_i` of the input @@ -1217,25 +1403,31 @@ This function calculates `log(exp(x1) + exp(x2))` more accurately for small values of `x`. -Args: - x1 (usm_ndarray): +Parameters +---------- + x1 : usm_ndarray First input array, expected to have a real-valued floating-point data type. - x2 (usm_ndarray): + x2 : usm_ndarray Second input array, also expected to have a real-valued floating-point data type. - out (Union[usm_ndarray, None], optional): + out : {None, usm_ndarray}, optional Output array to populate. Array must have the correct shape and the expected data type. - order ("C","F","A","K", optional): + + Default: ``None``. + order : {"C", "F", "A", "K"}, optional Memory layout of the new output array, if parameter `out` is ``None``. - Default: "K". -Returns: - usm_ndarray: + Default: ``"K"``. + +Returns +------- + out : usm_ndarray An array containing the element-wise results. The data type of the returned array is determined by the Type Promotion Rules. + """ logaddexp = BinaryElementwiseFunc( @@ -1245,28 +1437,34 @@ # B16: ==== LOGICAL_AND (x1, x2) _logical_and_docstring_ = r""" -logical_and(x1, x2, /, \*, out=None, order='K') Computes the logical AND for each element `x1_i` of the input array `x1` with the respective element `x2_i` of the input array `x2`. -Args: - x1 (usm_ndarray): +Parameters +---------- + x1 : usm_ndarray First input array. May have any data type. - x2 (usm_ndarray): + x2 : usm_ndarray Second input array. May have any data type. - out (Union[usm_ndarray, None], optional): + out : {None, usm_ndarray}, optional Output array to populate. Array must have the correct shape and the expected data type. - order ("C","F","A","K", optional): + + Default: ``None``. + order : {"C", "F", "A", "K"}, optional Memory layout of the new output array, if parameter `out` is ``None``. - Default: "K". -Returns: - usm_ndarray: + Default: ``"K"``. + +Returns +------- + out : usm_ndarray An array containing the element-wise logical AND results. + """ + logical_and = BinaryElementwiseFunc( "logical_and", ti._logical_and_result_type, @@ -1277,28 +1475,34 @@ # B17: ==== LOGICAL_OR (x1, x2) _logical_or_docstring_ = r""" -logical_or(x1, x2, /, \*, out=None, order='K') Computes the logical OR for each element `x1_i` of the input array `x1` with the respective element `x2_i` of the input array `x2`. -Args: - x1 (usm_ndarray): +Parameters +---------- + x1 : usm_ndarray First input array. May have any data type. - x2 (usm_ndarray): + x2 : usm_ndarray Second input array. May have any data type. - out (Union[usm_ndarray, None], optional): + out : {None, usm_ndarray}, optional Output array to populate. Array must have the correct shape and the expected data type. - order ("C","F","A","K", optional): + + Default: ``None``. + order : {"C", "F", "A", "K"}, optional Memory layout of the new output array, if parameter `out` is ``None``. - Default: "K". -Returns: - usm_ndarray: + Default: ``"K"``. + +Returns +------- + out : usm_ndarray An array containing the element-wise logical OR results. + """ + logical_or = BinaryElementwiseFunc( "logical_or", ti._logical_or_result_type, @@ -1309,28 +1513,34 @@ # B18: ==== LOGICAL_XOR (x1, x2) _logical_xor_docstring_ = r""" -logical_xor(x1, x2, /, \*, out=None, order='K') Computes the logical XOR for each element `x1_i` of the input array `x1` with the respective element `x2_i` of the input array `x2`. -Args: - x1 (usm_ndarray): +Parameters +---------- + x1 : usm_ndarray First input array. May have any data type. - x2 (usm_ndarray): + x2 : usm_ndarray Second input array. May have any data type. - out (Union[usm_ndarray, None], optional): + out : {None, usm_ndarray}, optional Output array to populate. Array must have the correct shape and the expected data type. - order ("C","F","A","K", optional): + + Default: ``None``. + order : {"C", "F", "A", "K"}, optional Memory layout of the new output array, if parameter `out` is ``None``. - Default: "K". -Returns: - usm_ndarray: + Default: ``"K"``. + +Returns +------- + out : usm_ndarray An array containing the element-wise logical XOR results. + """ + logical_xor = BinaryElementwiseFunc( "logical_xor", ti._logical_xor_result_type, @@ -1341,23 +1551,27 @@ # U24: ==== LOGICAL_NOT (x) _logical_not_docstring = r""" -logical_not(x, /, \*, out=None, order='K') Computes the logical NOT for each element `x_i` of input array `x`. -Args: - x (usm_ndarray): +Parameters +---------- + x : usm_ndarray Input array. May have any data type. - out (usm_ndarray): + out : usm_ndarray Output array to populate. Array must have the correct shape and the expected data type. - order ("C","F","A","K", optional): memory layout of the new - output array, if parameter `out` is ``None``. - Default: "K". + order : {"C", "F", "A", "K"}, optional + Memory layout of the new output array, if parameter + `out` is ``None``. + + Default: ``"K"``. -Returns: - usm_ndarray: +Returns +------- + out : usm_ndarray An array containing the element-wise logical NOT results. + """ logical_not = UnaryElementwiseFunc( @@ -1370,29 +1584,35 @@ # B26: ==== MAXIMUM (x1, x2) _maximum_docstring_ = r""" -maximum(x1, x2, /, \*, out=None, order='K') Compares two input arrays `x1` and `x2` and returns a new array containing the element-wise maxima. -Args: - x1 (usm_ndarray): +Parameters +---------- + x1 : usm_ndarray First input array. May have any data type. - x2 (usm_ndarray): + x2 : usm_ndarray Second input array. May have any data type. - out (Union[usm_ndarray, None], optional): + out : {None, usm_ndarray}, optional Output array to populate. Array must have the correct shape and the expected data type. - order ("C","F","A","K", optional): + + Default: ``None``. + order : {"C", "F", "A", "K"}, optional Memory layout of the new output array, if parameter `out` is ``None``. - Default: "K". -Returns: - usm_ndarray: + Default: ``"K"``. + +Returns +------- + out : usm_ndarray An array containing the element-wise maxima. The data type of the returned array is determined by the Type Promotion Rules. + """ + maximum = BinaryElementwiseFunc( "maximum", ti._maximum_result_type, @@ -1403,29 +1623,35 @@ # B27: ==== MINIMUM (x1, x2) _minimum_docstring_ = r""" -minimum(x1, x2, /, \*, out=None, order='K') Compares two input arrays `x1` and `x2` and returns a new array containing the element-wise minima. -Args: - x1 (usm_ndarray): +Parameters +---------- + x1 : usm_ndarray First input array. May have any data type. - x2 (usm_ndarray): + x2 : usm_ndarray Second input array. May have any data type. - out (Union[usm_ndarray, None], optional): + out : {None, usm_ndarray}, optional Output array to populate. Array must have the correct shape and the expected data type. - order ("C","F","A","K", optional): + + Default: ``None``. + order : {"C", "F", "A", "K"}, optional Memory layout of the new output array, if parameter `out` is ``None``. - Default: "K". -Returns: - usm_ndarray: + Default: ``"K"``. + +Returns +------- + out : usm_ndarray An array containing the element-wise minima. The data type of the returned array is determined by the Type Promotion Rules. + """ + minimum = BinaryElementwiseFunc( "minimum", ti._minimum_result_type, @@ -1436,29 +1662,35 @@ # B19: ==== MULTIPLY (x1, x2) _multiply_docstring_ = r""" -multiply(x1, x2, /, \*, out=None, order='K') Calculates the product for each element `x1_i` of the input array `x1` with the respective element `x2_i` of the input array `x2`. -Args: - x1 (usm_ndarray): +Parameters +---------- + x1 : usm_ndarray First input array. May have any data type. - x2 (usm_ndarray): + x2 : usm_ndarray Second input array. May have any data type. - out (Union[usm_ndarray, None], optional): + out : {None, usm_ndarray}, optional Output array to populate. Array must have the correct shape and the expected data type. - order ("C","F","A","K", optional): + + Default: ``None``. + order : {"C", "F", "A", "K"}, optional Memory layout of the new output array, if parameter `out` is ``None``. - Default: "K". -Returns: - usm_ndarray: + Default: ``"K"``. + +Returns +------- + out : usm_ndarray An array containing the element-wise products. The data type of the returned array is determined by the Type Promotion Rules. + """ + multiply = BinaryElementwiseFunc( "multiply", ti._multiply_result_type, @@ -1470,23 +1702,27 @@ # U25: ==== NEGATIVE (x) _negative_docstring_ = r""" -negative(x, /, \*, out=None, order='K') Computes the numerical negative for each element `x_i` of input array `x`. -Args: - x (usm_ndarray): +Parameters +---------- + x : usm_ndarray Input array, expected to have a numeric data type. - out (usm_ndarray): + out : usm_ndarray Output array to populate. Array must have the correct shape and the expected data type. - order ("C","F","A","K", optional): memory layout of the new - output array, if parameter `out` is ``None``. - Default: "K". + order : {"C", "F", "A", "K"}, optional + Memory layout of the new output array, if parameter + `out` is ``None``. + + Default: ``"K"``. -Returns: - usm_ndarray: +Returns +------- + out : usm_ndarray An array containing the negative of `x`. + """ negative = UnaryElementwiseFunc( @@ -1500,32 +1736,38 @@ # B28: ==== NEXTAFTER (x1, x2) _nextafter_docstring_ = r""" -nextafter(x1, x2, /, \*, out=None, order='K') Calculates the next floating-point value after element `x1_i` of the input array `x1` toward the respective element `x2_i` of the input array `x2`. -Args: - x1 (usm_ndarray): +Parameters +---------- + x1 : usm_ndarray First input array, expected to have a real-valued floating-point data type. - x2 (usm_ndarray): + x2 : usm_ndarray Second input array, expected to have a real-valued floating-point data type. - out (Union[usm_ndarray, None], optional): + out : {None, usm_ndarray}, optional Output array to populate. Array must have the correct shape and the expected data type. - order ("C","F","A","K", optional): + + Default: ``None``. + order : {"C", "F", "A", "K"}, optional Memory layout of the new output array, if parameter `out` is ``None``. - Default: "K". -Returns: - usm_ndarray: + Default: ``"K"``. + +Returns +------- + out : usm_ndarray An array containing the element-wise next representable values of `x1` in the direction of `x2`. The data type of the returned array is determined by the Type Promotion Rules. + """ + nextafter = BinaryElementwiseFunc( "nextafter", ti._nextafter_result_type, @@ -1536,28 +1778,33 @@ # B20: ==== NOT_EQUAL (x1, x2) _not_equal_docstring_ = r""" -not_equal(x1, x2, /, \*, out=None, order='K') Calculates inequality test results for each element `x1_i` of the input array `x1` with the respective element `x2_i` of the input array `x2`. -Args: - x1 (usm_ndarray): +Parameters +---------- + x1 : usm_ndarray First input array. - x2 (usm_ndarray): + x2 : usm_ndarray Second input array. - out (Union[usm_ndarray, None], optional): + out : {None, usm_ndarray}, optional Output array to populate. Array must have the correct shape and the expected data type. - order ("C","F","A","K", optional): + + Default: ``None``. + order : {"C", "F", "A", "K"}, optional Memory layout of the new output array, if parameter `out` is ``None``. - Default: "K". -Returns: - usm_ndarray: + Default: ``"K"``. + +Returns +------- + out : usm_ndarray An array containing the result of element-wise inequality comparison. The returned array has a data type of `bool`. + """ not_equal = BinaryElementwiseFunc( @@ -1571,23 +1818,27 @@ # U26: ==== POSITIVE (x) _positive_docstring_ = r""" -positive(x, /, \*, out=None, order='K') Computes the numerical positive for each element `x_i` of input array `x`. -Args: - x (usm_ndarray): +Parameters +---------- + x : usm_ndarray Input array, expected to have a numeric data type. - out (usm_ndarray): + out : usm_ndarray Output array to populate. Array must have the correct shape and the expected data type. - order ("C","F","A","K", optional): memory layout of the new - output array, if parameter `out` is ``None``. - Default: "K". + order : {"C", "F", "A", "K"}, optional + Memory layout of the new output array, if parameter + `out` is ``None``. + + Default: ``"K"``. -Returns: - usm_ndarray: +Returns +------- + out : usm_ndarray An array containing the positive of `x`. + """ positive = UnaryElementwiseFunc( @@ -1597,29 +1848,34 @@ # B21: ==== POW (x1, x2) _pow_docstring_ = r""" -pow(x1, x2, /, \*, out=None, order='K') Calculates `x1_i` raised to `x2_i` for each element `x1_i` of the input array `x1` with the respective element `x2_i` of the input array `x2`. -Args: - x1 (usm_ndarray): +Parameters +---------- + x1 : usm_ndarray First input array, expected to have a numeric data type. - x2 (usm_ndarray): + x2 : usm_ndarray Second input array, also expected to have a numeric data type. - out (usm_ndarray): + out : usm_ndarray Output array to populate. Array must have the correct shape and the expected data type. - order ("C","F","A","K", optional): memory layout of the new - output array, if parameter `out` is ``None``. - Default: "K". + order : {"C", "F", "A", "K"}, optional + Memory layout of the new output array, if parameter + `out` is ``None``. + + Default: ``"K"``. -Returns: - usm_ndarray: +Returns +------- + out : usm_ndarray An array containing the bases in `x1` raised to the exponents in `x2` element-wise. The data type of the returned array is determined by the Type Promotion Rules. + """ + pow = BinaryElementwiseFunc( "pow", ti._pow_result_type, @@ -1631,28 +1887,33 @@ # U27: ==== REAL (x) _real_docstring = r""" -real(x, /, \*, out=None, order='K') Computes real part of each element `x_i` for input array `x`. -Args: - x (usm_ndarray): +Parameters +---------- + x : usm_ndarray Input array. May have any data type. - out (Union[usm_ndarray, None], optional): + out : {None, usm_ndarray}, optional Output array to populate. Array must have the correct shape and the expected data type. - order ("C","F","A","K", optional): + + Default: ``None``. + order : {"C", "F", "A", "K"}, optional Memory layout of the new output array, if parameter `out` is ``None``. - Default: "K". -Returns: - usm_ndarray: + Default: ``"K"``. + +Returns +------- + out : usm_ndarray An array containing the element-wise real component of input. If the input is a real-valued data type, the returned array has the same data type. If the input is a complex floating-point data type, the returned array has a floating-point data type with the same floating-point precision as complex input. + """ real = UnaryElementwiseFunc( @@ -1662,32 +1923,38 @@ # B22: ==== REMAINDER (x1, x2) _remainder_docstring_ = r""" -remainder(x1, x2, /, \*, out=None, order='K') Calculates the remainder of division for each element `x1_i` of the input array `x1` with the respective element `x2_i` of the input array `x2`. This function is equivalent to the Python modulus operator. -Args: - x1 (usm_ndarray): +Parameters +---------- + x1 : usm_ndarray First input array, expected to have a real-valued data type. - x2 (usm_ndarray): + x2 : usm_ndarray Second input array, also expected to have a real-valued data type. - out (Union[usm_ndarray, None], optional): + out : {None, usm_ndarray}, optional Output array to populate. Array must have the correct shape and the expected data type. - order ("C","F","A","K", optional): + + Default: ``None``. + order : {"C", "F", "A", "K"}, optional Memory layout of the new output array, if parameter `out` is ``None``. - Default: "K". -Returns: - usm_ndarray: + Default: ``"K"``. + +Returns +------- + out : usm_ndarray An array containing the element-wise remainders. Each remainder has the same sign as respective element `x2_i`. The data type of the returned array is determined by the Type Promotion Rules. + """ + remainder = BinaryElementwiseFunc( "remainder", ti._remainder_result_type, @@ -1699,7 +1966,6 @@ # U28: ==== ROUND (x) _round_docstring = r""" -round(x, /, \*, out=None, order='K') Rounds each element `x_i` of the input array `x` to the nearest integer-valued number. @@ -1707,20 +1973,26 @@ When two integers are equally close to `x_i`, the result is the nearest even integer to `x_i`. -Args: - x (usm_ndarray): +Parameters +---------- + x : usm_ndarray Input array, expected to have a numeric data type. - out (Union[usm_ndarray, None], optional): + out : {None, usm_ndarray}, optional Output array to populate. Array must have the correct shape and the expected data type. - order ("C","F","A","K", optional): + + Default: ``None``. + order : {"C", "F", "A", "K"}, optional Memory layout of the new output array, if parameter `out` is ``None``. - Default: "K". -Returns: - usm_ndarray: + Default: ``"K"``. + +Returns +------- + out : usm_ndarray An array containing the element-wise rounded values. + """ round = UnaryElementwiseFunc( @@ -1734,7 +2006,6 @@ # U29: ==== SIGN (x) _sign_docstring = r""" -sign(x, /, \*, out=None, order='K') Computes an indication of the sign of each element `x_i` of input array `x` using the signum function. @@ -1742,22 +2013,28 @@ The signum function returns `-1` if `x_i` is less than `0`, `0` if `x_i` is equal to `0`, and `1` if `x_i` is greater than `0`. -Args: - x (usm_ndarray): +Parameters +---------- + x : usm_ndarray Input array, expected to have a numeric data type. - out (Union[usm_ndarray, None], optional): + out : {None, usm_ndarray}, optional Output array to populate. Array must have the correct shape and the expected data type. - order ("C","F","A","K", optional): + + Default: ``None``. + order : {"C", "F", "A", "K"}, optional Memory layout of the new output array, if parameter `out` is ``None``. - Default: "K". -Returns: - usm_ndarray: + Default: ``"K"``. + +Returns +------- + out : usm_ndarray An array containing the element-wise result of the signum function. The data type of the returned array is determined by the Type Promotion Rules. + """ sign = UnaryElementwiseFunc( @@ -1767,25 +2044,30 @@ # U30: ==== SIN (x) _sin_docstring = r""" -sin(x, /, \*, out=None, order='K') Computes sine for each element `x_i` of input array `x`. -Args: - x (usm_ndarray): +Parameters +---------- + x : usm_ndarray Input array, expected to have a real-valued floating-point data type. - out (Union[usm_ndarray, None], optional): + out : {None, usm_ndarray}, optional Output array to populate. Array must have the correct shape and the expected data type. - order ("C","F","A","K", optional): + + Default: ``None``. + order : {"C", "F", "A", "K"}, optional Memory layout of the new output array, if parameter `out` is ``None``. - Default: "K". -Returns: - usm_ndarray: + Default: ``"K"``. + +Returns +------- + out : usm_ndarray An array containing the element-wise sine. The data type of the returned array is determined by the Type Promotion Rules. + """ sin = UnaryElementwiseFunc("sin", ti._sin_result_type, ti._sin, _sin_docstring) @@ -1793,25 +2075,30 @@ # U31: ==== SINH (x) _sinh_docstring = r""" -sinh(x, /, \*, out=None, order='K') Computes hyperbolic sine for each element `x_i` for input array `x`. -Args: - x (usm_ndarray): +Parameters +---------- + x : usm_ndarray Input array, expected to have a floating-point data type. - out (Union[usm_ndarray, None], optional): + out : {None, usm_ndarray}, optional Output array to populate. Array must have the correct shape and the expected data type. - order ("C","F","A","K", optional): + + Default: ``None``. + order : {"C", "F", "A", "K"}, optional Memory layout of the new output array, if parameter `out` is ``None``. - Default: "K". -Returns: - usm_ndarray: + Default: ``"K"``. + +Returns +------- + out : usm_ndarray An array containing the element-wise hyperbolic sine. The data type of the returned array is determined by the Type Promotion Rules. + """ sinh = UnaryElementwiseFunc( @@ -1821,25 +2108,30 @@ # U32: ==== SQUARE (x) _square_docstring_ = r""" -square(x, /, \*, out=None, order='K') Squares each element `x_i` of input array `x`. -Args: - x (usm_ndarray): +Parameters +---------- + x : usm_ndarray Input array. May have any data type. - out (Union[usm_ndarray, None], optional): + out : {None, usm_ndarray}, optional Output array to populate. Array must have the correct shape and the expected data type. - order ("C","F","A","K", optional): + + Default: ``None``. + order : {"C", "F", "A", "K"}, optional Memory layout of the new output array, if parameter `out` is ``None``. - Default: "K". -Returns: - usm_ndarray: + Default: ``"K"``. + +Returns +------- + out : usm_ndarray An array containing the element-wise squares of `x`. The data type of the returned array is determined by the Type Promotion Rules. + """ square = UnaryElementwiseFunc( @@ -1849,26 +2141,31 @@ # U33: ==== SQRT (x) _sqrt_docstring_ = r""" -sqrt(x, /, \*, out=None, order='K') Computes the positive square-root for each element `x_i` of input array `x`. -Args: - x (usm_ndarray): +Parameters +---------- + x : usm_ndarray Input array, expected to have a floating-point data type. - out (Union[usm_ndarray, None], optional): + out : {None, usm_ndarray}, optional Output array to populate. Array must have the correct shape and the expected data type. - order ("C","F","A","K", optional): + + Default: ``None``. + order : {"C", "F", "A", "K"}, optional Memory layout of the new output array, if parameter `out` is ``None``. - Default: "K". -Returns: - usm_ndarray: + Default: ``"K"``. + +Returns +------- + out : usm_ndarray An array containing the element-wise positive square-roots of `x`. The data type of the returned array is determined by the Type Promotion Rules. + """ sqrt = UnaryElementwiseFunc( @@ -1878,28 +2175,33 @@ # B23: ==== SUBTRACT (x1, x2) _subtract_docstring_ = r""" -subtract(x1, x2, /, \*, out=None, order='K') Calculates the difference between each element `x1_i` of the input array `x1` and the respective element `x2_i` of the input array `x2`. -Args: - x1 (usm_ndarray): +Parameters +---------- + x1 : usm_ndarray First input array, expected to have a numeric data type. - x2 (usm_ndarray): + x2 : usm_ndarray Second input array, also expected to have a numeric data type. - out (Union[usm_ndarray, None], optional): + out : {None, usm_ndarray}, optional Output array to populate. Array must have the correct shape and the expected data type. - order ("C","F","A","K", optional): + + Default: ``None``. + order : {"C", "F", "A", "K"}, optional Memory layout of the new output array, if parameter `out` is ``None``. - Default: "K". -Returns: - usm_ndarray: + Default: ``"K"``. + +Returns +------- + out : usm_ndarray An array containing the element-wise differences. The data type of the returned array is determined by the Type Promotion Rules. + """ subtract = BinaryElementwiseFunc( "subtract", @@ -1913,25 +2215,30 @@ # U34: ==== TAN (x) _tan_docstring = r""" -tan(x, /, \*, out=None, order='K') Computes tangent for each element `x_i` for input array `x`. -Args: - x (usm_ndarray): +Parameters +---------- + x : usm_ndarray Input array, expected to have a floating-point data type. - out (Union[usm_ndarray, None], optional): + out : {None, usm_ndarray}, optional Output array to populate. Array must have the correct shape and the expected data type. - order ("C","F","A","K", optional): + + Default: ``None``. + order : {"C", "F", "A", "K"}, optional Memory layout of the new output array, if parameter `out` is ``None``. - Default: "K". -Returns: - usm_ndarray: + Default: ``"K"``. + +Returns +------- + out : usm_ndarray An array containing the element-wise tangent. The data type of the returned array is determined by the Type Promotion Rules. + """ tan = UnaryElementwiseFunc("tan", ti._tan_result_type, ti._tan, _tan_docstring) @@ -1939,25 +2246,30 @@ # U35: ==== TANH (x) _tanh_docstring = r""" -tanh(x, /, \*, out=None, order='K') Computes hyperbolic tangent for each element `x_i` for input array `x`. -Args: - x (usm_ndarray): +Parameters +---------- + x : usm_ndarray Input array, expected to have a floating-point data type. - out (Union[usm_ndarray, None], optional): + out : {None, usm_ndarray}, optional Output array to populate. Array must have the correct shape and the expected data type. - order ("C","F","A","K", optional): + + Default: ``None``. + order : {"C", "F", "A", "K"}, optional Memory layout of the new output array, if parameter `out` is ``None``. - Default: "K". -Returns: - usm_ndarray: + Default: ``"K"``. + +Returns +------- + out : usm_ndarray An array containing the element-wise hyperbolic tangent. The data type of the returned array is determined by the Type Promotion Rules. + """ tanh = UnaryElementwiseFunc( @@ -1967,7 +2279,6 @@ # U36: ==== TRUNC (x) _trunc_docstring = r""" -trunc(x, /, \*, out=None, order='K') Returns the truncated value for each element `x_i` for input array `x`. @@ -1975,21 +2286,27 @@ closer to zero than `x` is. In short, the fractional part of the signed number `x` is discarded. -Args: - x (usm_ndarray): +Parameters +---------- + x : usm_ndarray Input array, expected to have a boolean or real-valued data type. - out (Union[usm_ndarray, None], optional): + out : {None, usm_ndarray}, optional Output array to populate. Array must have the correct shape and the expected data type. - order ("C","F","A","K", optional): + + Default: ``None``. + order : {"C", "F", "A", "K"}, optional Memory layout of the new output array, if parameter `out` is ``None``. - Default: "K". -Returns: - usm_ndarray: + Default: ``"K"``. + +Returns +------- + out : usm_ndarray An array containing the result of element-wise division. The data type of the returned array is determined by the Type Promotion Rules. + """ trunc = UnaryElementwiseFunc( "trunc", ti._trunc_result_type, ti._trunc, _trunc_docstring @@ -1998,30 +2315,35 @@ # B24: ==== HYPOT (x1, x2) _hypot_docstring_ = r""" -hypot(x1, x2, /, \*, out=None, order='K') Computes the square root of the sum of squares for each element `x1_i` of the input array `x1` with the respective element `x2_i` of the input array `x2`. -Args: - x1 (usm_ndarray): +Parameters +---------- + x1 : usm_ndarray First input array, expected to have a real-valued floating-point data type. - x2 (usm_ndarray): + x2 : usm_ndarray Second input array, also expected to have a real-valued floating-point data type. - out (Union[usm_ndarray, None], optional): + out : {None, usm_ndarray}, optional Output array to populate. Array must have the correct shape and the expected data type. - order ("C","F","A","K", optional): + + Default: ``None``. + order : {"C", "F", "A", "K"}, optional Memory layout of the new output array, if parameter `out` is ``None``. - Default: "K". -Returns: - usm_ndarray: + Default: ``"K"``. + +Returns +------- + out : usm_ndarray An array containing the element-wise hypotenuse. The data type of the returned array is determined by the Type Promotion Rules. + """ hypot = BinaryElementwiseFunc( @@ -2031,26 +2353,31 @@ # U37: ==== CBRT (x) _cbrt_docstring_ = r""" -cbrt(x, /, \*, out=None, order='K') Computes the cube-root for each element `x_i` for input array `x`. -Args: - x (usm_ndarray): +Parameters +---------- + x : usm_ndarray Input array, expected to have a real-valued floating-point data type. - out (Union[usm_ndarray, None], optional): + out : {None, usm_ndarray}, optional Output array to populate. Array have the correct shape and the expected data type. - order ("C","F","A","K", optional): + + Default: ``None``. + order : {"C", "F", "A", "K"}, optional Memory layout of the new output array, if parameter `out` is ``None``. - Default: "K". -Returns: - usm_ndarray: + Default: ``"K"``. + +Returns +------- + out : usm_ndarray An array containing the element-wise cube-root. The data type of the returned array is determined by the Type Promotion Rules. + """ cbrt = UnaryElementwiseFunc( @@ -2064,22 +2391,28 @@ Computes the base-2 exponential for each element `x_i` for input array `x`. -Args: - x (usm_ndarray): +Parameters +---------- + x : usm_ndarray Input array, expected to have a floating-point data type. - out (Union[usm_ndarray, None], optional): + out : {None, usm_ndarray}, optional Output array to populate. Array have the correct shape and the expected data type. - order ("C","F","A","K", optional): + + Default: ``None``. + order : {"C", "F", "A", "K"}, optional Memory layout of the new output array, if parameter `out` is ``None``. - Default: "K". -Returns: - usm_ndarray: + Default: ``"K"``. + +Returns +------- + out : usm_ndarray An array containing the element-wise base-2 exponentials. The data type of the returned array is determined by the Type Promotion Rules. + """ exp2 = UnaryElementwiseFunc( @@ -2089,30 +2422,35 @@ # B25: ==== COPYSIGN (x1, x2) _copysign_docstring_ = r""" -copysign(x1, x2, /, \*, out=None, order='K') Composes a floating-point value with the magnitude of `x1_i` and the sign of `x2_i` for each element of input arrays `x1` and `x2`. -Args: - x1 (usm_ndarray): +Parameters +---------- + x1 : usm_ndarray First input array, expected to have a real-valued floating-point data type. - x2 (usm_ndarray): + x2 : usm_ndarray Second input array, also expected to have a real-valued floating-point data type. - out (Union[usm_ndarray, None], optional): + out : {None, usm_ndarray}, optional Output array to populate. Array have the correct shape and the expected data type. - order ("C","F","A","K", optional): + + Default: ``None``. + order : {"C", "F", "A", "K"}, optional Memory layout of the new output array, if parameter `out` is ``None``. - Default: "K". -Returns: - usm_ndarray: + Default: ``"K"``. + +Returns +------- + out : usm_ndarray An array containing the element-wise results. The data type of the returned array is determined by the Type Promotion Rules. + """ copysign = BinaryElementwiseFunc( "copysign", @@ -2124,26 +2462,31 @@ # U39: ==== RSQRT (x) _rsqrt_docstring_ = r""" -rsqrt(x, /, \*, out=None, order='K') Computes the reciprocal square-root for each element `x_i` for input array `x`. -Args: - x (usm_ndarray): +Parameters +---------- + x : usm_ndarray Input array, expected to have a real-valued floating-point data type. - out (Union[usm_ndarray, None], optional): + out : {None, usm_ndarray}, optional Output array to populate. Array have the correct shape and the expected data type. - order ("C","F","A","K", optional): + + Default: ``None``. + order : {"C", "F", "A", "K"}, optional Memory layout of the new output array, if parameter `out` is ``None``. - Default: "K". -Returns: - usm_ndarray: + Default: ``"K"``. + +Returns +------- + out : usm_ndarray An array containing the element-wise reciprocal square-root. The returned array has a floating-point data type determined by the Type Promotion Rules. + """ rsqrt = UnaryElementwiseFunc( @@ -2153,24 +2496,29 @@ # U40: ==== PROJ (x) _proj_docstring = r""" -proj(x, /, \*, out=None, order='K') Computes projection of each element `x_i` for input array `x`. -Args: - x (usm_ndarray): +Parameters +---------- + x : usm_ndarray Input array, expected to have a complex data type. - out (Union[usm_ndarray, None], optional): + out : {None, usm_ndarray}, optional Output array to populate. Array must have the correct shape and the expected data type. - order ("C","F","A","K", optional): + + Default: ``None``. + order : {"C", "F", "A", "K"}, optional Memory layout of the new output array, if parameter `out` is ``None``. - Default: "K". -Returns: - usm_ndarray: + Default: ``"K"``. + +Returns +------- + out : usm_ndarray An array containing the element-wise projection. + """ proj = UnaryElementwiseFunc( @@ -2180,26 +2528,31 @@ # U41: ==== SIGNBIT (x) _signbit_docstring = r""" -signbit(x, /, \*, out=None, order='K') Computes an indication of whether the sign bit of each element `x_i` of input array `x` is set. -Args: - x (usm_ndarray): +Parameters +---------- + x : usm_ndarray Input array, expected to have a real-valued floating-point data type. - out (Union[usm_ndarray, None], optional): + out : {None, usm_ndarray}, optional Output array to populate. Array must have the correct shape and the expected data type. - order ("C","F","A","K", optional): + + Default: ``None``. + order : {"C", "F", "A", "K"}, optional Memory layout of the new output array, if parameter `out` is ``None``. - Default: "K". -Returns: - usm_ndarray: + Default: ``"K"``. + +Returns +------- + out : usm_ndarray An array containing the element-wise signbit results. The returned array must have a data type of `bool`. + """ signbit = UnaryElementwiseFunc( @@ -2209,26 +2562,31 @@ # U42: ==== RECIPROCAL (x) _reciprocal_docstring = r""" -reciprocal(x, /, \*, out=None, order='K') Computes the reciprocal of each element `x_i` for input array `x`. -Args: - x (usm_ndarray): +Parameters +---------- + x : usm_ndarray Input array, expected to have a floating-point data type. - out (Union[usm_ndarray, None], optional): + out : {None, usm_ndarray}, optional Output array to populate. Array have the correct shape and the expected data type. - order ("C","F","A","K", optional): + + Default: ``None``. + order : {"C", "F", "A", "K"}, optional Memory layout of the new output array, if parameter `out` is ``None``. - Default: "K". -Returns: - usm_ndarray: + Default: ``"K"``. + +Returns +------- + out : usm_ndarray An array containing the element-wise reciprocals. The returned array has a floating-point data type determined by the Type Promotion Rules. + """ reciprocal = UnaryElementwiseFunc( @@ -2242,27 +2600,32 @@ # U43: ==== ANGLE (x) _angle_docstring = r""" -angle(x, /, \*, out=None, order='K') Computes the phase angle (also called the argument) of each element `x_i` for input array `x`. -Args: - x (usm_ndarray): +Parameters +---------- + x : usm_ndarray Input array, expected to have a complex floating-point data type. - out (Union[usm_ndarray, None], optional): + out : {None, usm_ndarray}, optional Output array to populate. Array have the correct shape and the expected data type. - order ("C","F","A","K", optional): + + Default: ``None``. + order : {"C", "F", "A", "K"}, optional Memory layout of the new output array, if parameter `out` is ``None``. - Default: "K". -Returns: - usm_ndarray: + Default: ``"K"``. + +Returns +------- + out : usm_ndarray An array containing the element-wise phase angles. The returned array has a floating-point data type determined by the Type Promotion Rules. + """ angle = UnaryElementwiseFunc( From 4283245d7e5c315c42a2077a9cbdfc55fde9ec63 Mon Sep 17 00:00:00 2001 From: Vladislav Perevezentsev Date: Fri, 10 Apr 2026 10:00:37 -0700 Subject: [PATCH 13/46] Update _linear_algebra_functions.py doc to Sphinx format --- dpnp/tensor/_linear_algebra_functions.py | 288 ++++++++++++----------- 1 file changed, 155 insertions(+), 133 deletions(-) diff --git a/dpnp/tensor/_linear_algebra_functions.py b/dpnp/tensor/_linear_algebra_functions.py index dcaf99b4423..97f3381743b 100644 --- a/dpnp/tensor/_linear_algebra_functions.py +++ b/dpnp/tensor/_linear_algebra_functions.py @@ -46,30 +46,33 @@ def matrix_transpose(x): - r"""matrix_transpose(x) - + """ Transposes the innermost two dimensions of `x`, where `x` is a 2-dimensional matrix or a stack of 2-dimensional matrices. To convert from a 1-dimensional array to a 2-dimensional column vector, use x[:, dpt.newaxis]. - Args: - x (usm_ndarray): - Input array with shape (..., m, n). + Parameters + ---------- + x : usm_ndarray + Input array with shape (..., m, n). + + Returns + ------- + out : usm_ndarray + Array with shape (..., n, m). - Returns: - usm_ndarray: - Array with shape (..., n, m). """ if not isinstance(x, dpt.usm_ndarray): raise TypeError( - "Expected instance of `dpt.usm_ndarray`, got `{}`.".format(type(x)) + "Expected instance of `dpnp.tensor.usm_ndarray`," + " got `{}`.".format(type(x)) ) if x.ndim < 2: raise ValueError( - "dpnp.tensor.matrix_transpose requires array to have" + "dpnp.tensor.matrix_transpose requires array to have " "at least 2 dimensions" ) @@ -77,43 +80,49 @@ def matrix_transpose(x): def tensordot(x1, x2, axes=2): - r"""tensordot(x1, x2, axes=2) - + """ Returns a tensor contraction of `x1` and `x2` over specific axes. - Args: - x1 (usm_ndarray): - first input array, expected to have numeric data type. - x2 (usm_ndarray): - second input array, expected to have numeric data type. - Corresponding contracted axes of `x1` and `x2` must be equal. - axes (Union[int, Tuple[Sequence[int], Sequence[int]]): - number of axes to contract or explicit sequences of axes for - `x1` and `x2`, respectively. If `axes` is an integer equal to `N`, - then the contraction is performed over last `N` axes of `x1` and - the first `N` axis of `x2` in order. The size of each corresponding - axis must match and must be non-negative. - - * if `N` equals `0`, the result is the tensor outer product - * if `N` equals `1`, the result is the tensor dot product - * if `N` equals `2`, the result is the tensor double - contraction (default). - - If `axes` is a tuple of two sequences `(x1_axes, x2_axes)`, the - first sequence applies to `x1` and the second sequence applies - to `x2`. Both sequences must have equal length, and each axis - `x1_axes[i]` for `x1` must have the same size as the respective - axis `x2_axes[i]` for `x2`. Each sequence must consist of unique - integers that specify valid axes for each respective array. - For example, if `x1` has rank `N`, a valid axis must reside on the - half-open interval `[-N, N)`. - Returns: - usm_ndarray: - an array containing the tensor contraction whose shape consists of - the non-contracted axes of the first array `x1`, followed by the - non-contracted axes of the second array `x2`. The returned array - must have a data type determined by Type Promotion Rules. + Parameters + ---------- + x1 : usm_ndarray + First input array, expected to have numeric data type. + x2 : usm_ndarray + Second input array, expected to have numeric data type. + Corresponding contracted axes of `x1` and `x2` must be equal. + axes : {int, tuple}, optional + Number of axes to contract or explicit sequences of axes for + `x1` and `x2`, respectively. If `axes` is an integer equal to `N`, + then the contraction is performed over last `N` axes of `x1` and + the first `N` axis of `x2` in order. The size of each corresponding + axis must match and must be non-negative. + + * if `N` equals `0`, the result is the tensor outer product + * if `N` equals `1`, the result is the tensor dot product + * if `N` equals `2`, the result is the tensor double + contraction (default). + + If `axes` is a tuple of two sequences `(x1_axes, x2_axes)`, the + first sequence applies to `x1` and the second sequence applies + to `x2`. Both sequences must have equal length, and each axis + `x1_axes[i]` for `x1` must have the same size as the respective + axis `x2_axes[i]` for `x2`. Each sequence must consist of unique + integers that specify valid axes for each respective array. + For example, if `x1` has rank `N`, a valid axis must reside on the + half-open interval `[-N, N)`. + + Default: ``2``. + + Returns + ------- + out : usm_ndarray + An array containing the tensor contraction whose shape consists of + the non-contracted axes of the first array `x1`, followed by the + non-contracted axes of the second array `x2`. The returned array + must have a data type determined by Type Promotion Rules. + """ + if not isinstance(x1, dpt.usm_ndarray): raise TypeError(f"Expected dpnp.tensor.usm_ndarray, got {type(x1)}") if not isinstance(x2, dpt.usm_ndarray): @@ -320,36 +329,40 @@ def tensordot(x1, x2, axes=2): def vecdot(x1, x2, axis=-1): - r"""vecdot(x1, x2, axis=-1) - + """ Computes the (vector) dot product of two arrays. - Args: - x1 (usm_ndarray): - first input array. - x2 (usm_ndarray): - second input array. Input arrays must have compatible - shapes along non-contract axes according to broadcasting - rules, and must have the same size along the contracted - axis. Input arrays should be of numeric type. - axis (Optional[int]): - axis over which to compute the dot product. The axis must - be an integer on the interval `[-N, -1]`, where `N` is - ``min(x1.ndim, x2.ndim)``. The axis along which dot product - is performed is counted backward from the last axes - (that is, `-1` refers to the last axis). By default, - dot product is computed over the last axis. - Default: `-1`. - - Returns: - usm_ndarray: - if `x1` and `x2` are both one-dimensional arrays, a - zero-dimensional array containing the dot product value - is returned; otherwise, a non-zero-dimensional array containing - the dot products and having rank `N-1`, where `N` is the rank - of the shape of input arrays after broadcasting rules are applied - to non-contracted axes. + Parameters + ---------- + x1 : usm_ndarray + First input array. + x2 : usm_ndarray + Second input array. Input arrays must have compatible + shapes along non-contract axes according to broadcasting + rules, and must have the same size along the contracted + axis. Input arrays should be of numeric type. + axis : int, optional + Axis over which to compute the dot product. The axis must + be an integer on the interval `[-N, -1]`, where `N` is + ``min(x1.ndim, x2.ndim)``. The axis along which dot product + is performed is counted backward from the last axes + (that is, `-1` refers to the last axis). By default, + dot product is computed over the last axis. + + Default: ``-1``. + + Returns + ------- + out : usm_ndarray + If `x1` and `x2` are both one-dimensional arrays, a + zero-dimensional array containing the dot product value + is returned; otherwise, a non-zero-dimensional array containing + the dot products and having rank `N-1`, where `N` is the rank + of the shape of input arrays after broadcasting rules are applied + to non-contracted axes. + """ + if not isinstance(x1, dpt.usm_ndarray): raise TypeError(f"Expected dpnp.tensor.usm_ndarray, got {type(x1)}") if not isinstance(x2, dpt.usm_ndarray): @@ -586,72 +599,81 @@ def vecdot(x1, x2, axis=-1): def matmul(x1, x2, out=None, dtype=None, order="K"): - r"""matmul(x1, x2, out=None, order="K") - + """ Computes the matrix product. Implements the same semantics as the built-in operator `@`. - Args: - x1 (usm_ndarray): - first input array. Expected to have numeric data type, and - at least one dimension. If `x1` is one-dimensional having - shape `(M,)`, and `x2` has more than one dimension, `x1` is - effectively treated as a two-dimensional array with shape `(1, M)`, - although the prepended dimension is removed from the output array. - If `x1` has shape `(..., M, K)`, the innermost two dimensions form - matrices on which to perform matrix multiplication. - x2 (usm_ndarray): - second input array. Expected to have numeric data type, and - at least one dimension. If `x2` is one-dimensional having - shape `(N,)`, and `x1` has more than one dimension, `x2` is - effectively treated as a two-dimensional array with shape `(N, 1)`, - although the appended dimension is removed from the output array. - If `x2` has shape `(..., K, N)`, the innermost two dimensions form - matrices on which to perform matrix multiplication. - out (Optional[usm_ndarray]): - the array into which the result of the matrix product is written. - The data type of `out` must match the expected data type of the - result or (if provided) `dtype`. - If `None` then a new array is returned. Default: `None`. - dtype (Optional[dtype]): - data type of the returned array. If `None`, the data type of the - returned array is determined by the Type Promotion Rules. - Default: `None`. - order (["K", "C", "F", "A"]): - memory layout of the output array, if `out` is `None`, otherwise - the `order` parameter value is not used. Default: `K`. - Returns: - usm_ndarray: - * if both `x1` and `x2` are one-dimensional arrays with shape - `(N,)`, returned array is a zero-dimensional array containing - inner product as its only element. - * if `x1` is two-dimensional array with shape `(M, K)` and `x2` is - a two-dimensional array with shape `(K, N)`, returned array is a - two-dimensional array with shape `(M, N)` and contains the - conventional matrix product. - * if `x1` is a one-dimensional array with shape `(K,)` and `x2` is - an array with shape `(..., K, N)`, returned array contains the - conventional matrix product and has shape `(..., N)`. - * if `x1` is an array with shape `(..., M, K)` and `x2` is a - one-dimensional array with shape `(K,)`, returned array has shape - `(..., M)` and contains the conventional matrix product. - * if `x1` is a two-dimensional array with shape `(M, K)` and `x2` - is an array with shape `(..., K, N)`, returned array contains - conventional matrix product for each stacked matrix and has shape - `(..., M, N)`. - * if `x1` has shape `(..., M, K)` and `x2` is a two-dimensional - array with shape `(K, N)`, returned array contains conventional - matrix product for each stacked matrix and has shape - `(..., M, N)`. - * if both `x1` and `x2` have more than two dimensions, returned - array contains conventional matrix product for each stacked - matrix and has shape determined by broadcasting rules for - `x1.shape[:-2]` and `x2.shape[:-2]`. - - The data type of the returned array is determined by the Type - Promotion Rules. If either `x1` or `x2` has a complex floating - point type, neither argument is complex conjugated or transposed. + Parameters + ---------- + x1 : usm_ndarray + First input array. Expected to have numeric data type, and + at least one dimension. If `x1` is one-dimensional having + shape `(M,)`, and `x2` has more than one dimension, `x1` is + effectively treated as a two-dimensional array with shape `(1, M)`, + although the prepended dimension is removed from the output array. + If `x1` has shape `(..., M, K)`, the innermost two dimensions form + matrices on which to perform matrix multiplication. + x2 : usm_ndarray + Second input array. Expected to have numeric data type, and + at least one dimension. If `x2` is one-dimensional having + shape `(N,)`, and `x1` has more than one dimension, `x2` is + effectively treated as a two-dimensional array with shape `(N, 1)`, + although the appended dimension is removed from the output array. + If `x2` has shape `(..., K, N)`, the innermost two dimensions form + matrices on which to perform matrix multiplication. + out : {None, usm_ndarray}, optional + The array into which the result of the matrix product is written. + The data type of `out` must match the expected data type of the + result or (if provided) `dtype`. + If `None` then a new array is returned. + + Default: ``None``. + dtype : {None, dtype}, optional + Data type of the returned array. If `None`, the data type of the + returned array is determined by the Type Promotion Rules. + + Default: ``None``. + order : {"K", "C", "F", "A"}, optional + Memory layout of the output array, if `out` is `None`, otherwise + the `order` parameter value is not used. + + Default: ``"K"``. + + Returns + ------- + out : usm_ndarray + * if both `x1` and `x2` are one-dimensional arrays with shape + `(N,)`, returned array is a zero-dimensional array containing + inner product as its only element. + * if `x1` is two-dimensional array with shape `(M, K)` and `x2` is + a two-dimensional array with shape `(K, N)`, returned array is a + two-dimensional array with shape `(M, N)` and contains the + conventional matrix product. + * if `x1` is a one-dimensional array with shape `(K,)` and `x2` is + an array with shape `(..., K, N)`, returned array contains the + conventional matrix product and has shape `(..., N)`. + * if `x1` is an array with shape `(..., M, K)` and `x2` is a + one-dimensional array with shape `(K,)`, returned array has shape + `(..., M)` and contains the conventional matrix product. + * if `x1` is a two-dimensional array with shape `(M, K)` and `x2` + is an array with shape `(..., K, N)`, returned array contains + conventional matrix product for each stacked matrix and has shape + `(..., M, N)`. + * if `x1` has shape `(..., M, K)` and `x2` is a two-dimensional + array with shape `(K, N)`, returned array contains conventional + matrix product for each stacked matrix and has shape + `(..., M, N)`. + * if both `x1` and `x2` have more than two dimensions, returned + array contains conventional matrix product for each stacked + matrix and has shape determined by broadcasting rules for + `x1.shape[:-2]` and `x2.shape[:-2]`. + + The data type of the returned array is determined by the Type + Promotion Rules. If either `x1` or `x2` has a complex floating + point type, neither argument is complex conjugated or transposed. + """ + if not isinstance(x1, dpt.usm_ndarray): raise TypeError(f"Expected dpnp.tensor.usm_ndarray, got {type(x1)}") if not isinstance(x2, dpt.usm_ndarray): From e92de86175d557461e918b8d6ed7d473ceef417d Mon Sep 17 00:00:00 2001 From: Vladislav Perevezentsev Date: Fri, 10 Apr 2026 10:18:30 -0700 Subject: [PATCH 14/46] Update _manipulation_functions.py doc to Sphinx format --- dpnp/tensor/_manipulation_functions.py | 600 ++++++++++++++----------- 1 file changed, 338 insertions(+), 262 deletions(-) diff --git a/dpnp/tensor/_manipulation_functions.py b/dpnp/tensor/_manipulation_functions.py index 7347f62de11..151a6644f0e 100644 --- a/dpnp/tensor/_manipulation_functions.py +++ b/dpnp/tensor/_manipulation_functions.py @@ -40,7 +40,7 @@ __doc__ = ( "Implementation module for array manipulation " - "functions in :module:`dpctl.tensor`" + "functions in :module:`dpnp.tensor`" ) @@ -218,22 +218,25 @@ def _concat_axis_None(arrays): def broadcast_arrays(*args): - """broadcast_arrays(*arrays) - - Broadcasts one or more :class:`dpctl.tensor.usm_ndarrays` against + """ + Broadcasts one or more :class:`dpnp.tensor.usm_ndarrays` against one another. - Args: - arrays (usm_ndarray): an arbitrary number of arrays to be - broadcasted. + Parameters + ---------- + arrays : usm_ndarray + An arbitrary number of arrays to be broadcasted. + + Returns + ------- + out : list of usm_ndarrays + A list of broadcasted arrays. Each array + must have the same shape. Each array must have the same `dtype`, + `device` and `usm_type` attributes as its corresponding input + array. - Returns: - List[usm_ndarray]: - A list of broadcasted arrays. Each array - must have the same shape. Each array must have the same `dtype`, - `device` and `usm_type` attributes as its corresponding input - array. """ + if len(args) == 0: raise ValueError("`broadcast_arrays` requires at least one argument") for X in args: @@ -249,23 +252,28 @@ def broadcast_arrays(*args): def broadcast_to(X, /, shape): - """broadcast_to(x, shape) - + """ Broadcast an array to a new `shape`; returns the broadcasted - :class:`dpctl.tensor.usm_ndarray` as a view. - - Args: - x (usm_ndarray): input array - shape (Tuple[int,...]): array shape. The `shape` must be - compatible with `x` according to broadcasting rules. - - Returns: - usm_ndarray: - An array with the specified `shape`. - The output array is a view of the input array, and - hence has the same data type, USM allocation type and - device attributes. + :class:`dpnp.tensor.usm_ndarray` as a view. + + Parameters + ---------- + x : usm_ndarray + Input array. + shape : tuple of ints + Array shape. The `shape` must be compatible with `x` + according to broadcasting rules. + + Returns + ------- + out : usm_ndarray + An array with the specified `shape`. + The output array is a view of the input array, and + hence has the same data type, USM allocation type and + device attributes. + """ + if not isinstance(X, dpt.usm_ndarray): raise TypeError(f"Expected usm_ndarray type, got {type(X)}.") @@ -286,31 +294,37 @@ def broadcast_to(X, /, shape): def concat(arrays, /, *, axis=0): - """concat(arrays, axis) - + """ Joins a sequence of arrays along an existing axis. - Args: - arrays (Union[List[usm_ndarray, Tuple[usm_ndarray,...]]]): - input arrays to join. The arrays must have the same shape, - except in the dimension specified by `axis`. - axis (Optional[int]): axis along which the arrays will be joined. - If `axis` is `None`, arrays must be flattened before - concatenation. If `axis` is negative, it is understood as - being counted from the last dimension. Default: `0`. - - Returns: - usm_ndarray: - An output array containing the concatenated - values. The output array data type is determined by Type - Promotion Rules of array API. + Parameters + ---------- + arrays : {list of usm_ndarrays, tuple of usm_ndarrays} + Input arrays to join. The arrays must have the same shape, + except in the dimension specified by `axis`. + axis : int, optional + Axis along which the arrays will be joined. + If `axis` is `None`, arrays must be flattened before + concatenation. If `axis` is negative, it is understood as + being counted from the last dimension. + + Default: ``0``. + + Returns + ------- + out : usm_ndarray + An output array containing the concatenated + values. The output array data type is determined by Type + Promotion Rules of array API. All input arrays must have the same device attribute. The output array is allocated on that same device, and data movement operations are scheduled on a queue underlying the device. The USM allocation type of the output array is determined by USM allocation type promotion rules. + """ + if axis is None: return _concat_axis_None(arrays) @@ -356,36 +370,41 @@ def concat(arrays, /, *, axis=0): def expand_dims(X, /, *, axis=0): - """expand_dims(x, axis) - + """ Expands the shape of an array by inserting a new axis (dimension) of size one at the position specified by axis. - Args: - x (usm_ndarray): - input array - axis (Union[int, Tuple[int]]): - axis position in the expanded axes (zero-based). If `x` has rank - (i.e, number of dimensions) `N`, a valid `axis` must reside - in the closed-interval `[-N-1, N]`. If provided a negative - `axis`, the `axis` position at which to insert a singleton - dimension is computed as `N + axis + 1`. Hence, if - provided `-1`, the resolved axis position is `N` (i.e., - a singleton dimension must be appended to the input array `x`). - If provided `-N-1`, the resolved axis position is `0` (i.e., a - singleton dimension is prepended to the input array `x`). - - Returns: - usm_ndarray: - Returns a view, if possible, and a copy otherwise with the number - of dimensions increased. - The expanded array has the same data type as the input array `x`. - The expanded array is located on the same device as the input - array, and has the same USM allocation type. - - Raises: - IndexError: if `axis` value is invalid. + Parameters + ---------- + x : usm_ndarray + Input array. + axis : {int, tuple of ints} + Axis position in the expanded axes (zero-based). If `x` has rank + (i.e, number of dimensions) `N`, a valid `axis` must reside + in the closed-interval `[-N-1, N]`. If provided a negative + `axis`, the `axis` position at which to insert a singleton + dimension is computed as `N + axis + 1`. Hence, if + provided `-1`, the resolved axis position is `N` (i.e., + a singleton dimension must be appended to the input array `x`). + If provided `-N-1`, the resolved axis position is `0` (i.e., a + singleton dimension is prepended to the input array `x`). + + Returns + ------- + out : usm_ndarray + Returns a view, if possible, and a copy otherwise with the number + of dimensions increased. + The expanded array has the same data type as the input array `x`. + The expanded array is located on the same device as the input + array, and has the same USM allocation type. + + Raises + ------ + IndexError + If `axis` value is invalid. + """ + if not isinstance(X, dpt.usm_ndarray): raise TypeError(f"Expected usm_ndarray type, got {type(X)}.") @@ -402,24 +421,30 @@ def expand_dims(X, /, *, axis=0): def flip(X, /, *, axis=None): - """flip(x, axis) - + """ Reverses the order of elements in an array `x` along the given `axis`. The shape of the array is preserved, but the elements are reordered. - Args: - x (usm_ndarray): input array. - axis (Optional[Union[int, Tuple[int,...]]]): axis (or axes) along - which to flip. - If `axis` is `None`, all input array axes are flipped. - If `axis` is negative, the flipped axis is counted from the - last dimension. If provided more than one axis, only the specified - axes are flipped. Default: `None`. - - Returns: - usm_ndarray: - A view of `x` with the entries of `axis` reversed. + Parameters + ---------- + x : usm_ndarray + Input array. + axis : {None, int, tuple of ints}, optional + Axis (or axes) along which to flip. + If `axis` is `None`, all input array axes are flipped. + If `axis` is negative, the flipped axis is counted from the + last dimension. If provided more than one axis, only the specified + axes are flipped. + + Default: ``None``. + + Returns + ------- + out : usm_ndarray + A view of `x` with the entries of `axis` reversed. + """ + if not isinstance(X, dpt.usm_ndarray): raise TypeError(f"Expected usm_ndarray type, got {type(X)}.") X_ndim = X.ndim @@ -434,36 +459,41 @@ def flip(X, /, *, axis=None): def moveaxis(X, source, destination, /): - """moveaxis(x, source, destination) - + """ Moves axes of an array to new positions. - Args: - x (usm_ndarray): input array - - source (int or a sequence of int): - Original positions of the axes to move. - These must be unique. If `x` has rank (i.e., number of - dimensions) `N`, a valid `axis` must be in the - half-open interval `[-N, N)`. - - destination (int or a sequence of int): - Destination positions for each of the original axes. - These must also be unique. If `x` has rank - (i.e., number of dimensions) `N`, a valid `axis` must be - in the half-open interval `[-N, N)`. - - Returns: - usm_ndarray: - Array with moved axes. - The returned array must has the same data type as `x`, - is created on the same device as `x` and has the same - USM allocation type as `x`. - - Raises: - AxisError: if `axis` value is invalid. - ValueError: if `src` and `dst` have not equal number of elements. + Parameters + ---------- + x : usm_ndarray + Input array. + source : {int, sequence of ints} + Original positions of the axes to move. + These must be unique. If `x` has rank (i.e., number of + dimensions) `N`, a valid `axis` must be in the + half-open interval `[-N, N)`. + destination : {int, sequence of ints} + Destination positions for each of the original axes. + These must also be unique. If `x` has rank + (i.e., number of dimensions) `N`, a valid `axis` must be + in the half-open interval `[-N, N)`. + + Returns + ------- + out : usm_ndarray + Array with moved axes. + The returned array must has the same data type as `x`, + is created on the same device as `x` and has the same + USM allocation type as `x`. + + Raises + ------ + AxisError + If `axis` value is invalid. + ValueError + If `src` and `dst` have not equal number of elements. + """ + if not isinstance(X, dpt.usm_ndarray): raise TypeError(f"Expected usm_ndarray type, got {type(X)}.") @@ -485,30 +515,35 @@ def moveaxis(X, source, destination, /): def permute_dims(X, /, axes): - """permute_dims(x, axes) - + """ Permute the axes (dimensions) of an array; returns the permuted array as a view. - Args: - x (usm_ndarray): input array. - axes (Tuple[int, ...]): tuple containing permutation of - `(0,1,...,N-1)` where `N` is the number of axes (dimensions) - of `x`. - Returns: - usm_ndarray: - An array with permuted axes. - The returned array must has the same data type as `x`, - is created on the same device as `x` and has the same USM allocation - type as `x`. + Parameters + ---------- + x : usm_ndarray + Input array. + axes : tuple of ints + Tuple containing permutation of `(0,1,...,N-1)` where `N` is + the number of axes (dimensions) of `x`. + + Returns + ------- + out : usm_ndarray + An array with permuted axes. + The returned array must has the same data type as `x`, + is created on the same device as `x` and has the same USM + allocation type as `x`. + """ + if not isinstance(X, dpt.usm_ndarray): raise TypeError(f"Expected usm_ndarray type, got {type(X)}.") axes = normalize_axis_tuple(axes, X.ndim, "axes") if not X.ndim == len(axes): raise ValueError( "The length of the passed axes does not match " - "to the number of usm_ndarray dimensions." + "to the number of usm_ndarrays dimensions." ) newstrides = tuple(X.strides[i] for i in axes) newshape = tuple(X.shape[i] for i in axes) @@ -522,43 +557,49 @@ def permute_dims(X, /, axes): def repeat(x, repeats, /, *, axis=None): - """repeat(x, repeats, axis=None) - + """ Repeat elements of an array on a per-element basis. - Args: - x (usm_ndarray): input array + Parameters + ---------- + x : usm_ndarray + Input array. + repeats : {int, sequence of ints, usm_ndarray} + The number of repetitions for each element. - repeats (Union[int, Sequence[int, ...], usm_ndarray]): - The number of repetitions for each element. + `repeats` must be broadcast-compatible with `N` where `N` is + `prod(x.shape)` if `axis` is `None` and `x.shape[axis]` + otherwise. - `repeats` must be broadcast-compatible with `N` where `N` is - `prod(x.shape)` if `axis` is `None` and `x.shape[axis]` - otherwise. + If `repeats` is an array, it must have an integer data type. + Otherwise, `repeats` must be a Python integer or sequence of + Python integers (i.e., a tuple, list, or range). + axis : int, optional + The axis along which to repeat values. If `axis` is `None`, the + function repeats elements of the flattened array. - If `repeats` is an array, it must have an integer data type. - Otherwise, `repeats` must be a Python integer or sequence of - Python integers (i.e., a tuple, list, or range). + Default: ``None``. - axis (Optional[int]): - The axis along which to repeat values. If `axis` is `None`, the - function repeats elements of the flattened array. Default: `None`. + Returns + ------- + out : usm_ndarray + Output array with repeated elements. - Returns: - usm_ndarray: - output array with repeated elements. + If `axis` is `None`, the returned array is one-dimensional, + otherwise, it has the same shape as `x`, except for the axis along + which elements were repeated. - If `axis` is `None`, the returned array is one-dimensional, - otherwise, it has the same shape as `x`, except for the axis along - which elements were repeated. + The returned array will have the same data type as `x`. + The returned array will be located on the same device as `x` and + have the same USM allocation type as `x`. - The returned array will have the same data type as `x`. - The returned array will be located on the same device as `x` and - have the same USM allocation type as `x`. + Raises + ------ + AxisError + If `axis` value is invalid. - Raises: - AxisError: if `axis` value is invalid. """ + if not isinstance(x, dpt.usm_ndarray): raise TypeError(f"Expected usm_ndarray type, got {type(x)}.") @@ -750,36 +791,41 @@ def repeat(x, repeats, /, *, axis=None): def roll(x, /, shift, *, axis=None): """ - roll(x, shift, axis) - Rolls array elements along a specified axis. Array elements that roll beyond the last position are re-introduced at the first position. Array elements that roll beyond the first position are re-introduced at the last position. - Args: - x (usm_ndarray): input array - shift (Union[int, Tuple[int,...]]): number of places by which the - elements are shifted. If `shift` is a tuple, then `axis` must be a - tuple of the same size, and each of the given axes must be shifted - by the corresponding element in `shift`. If `shift` is an `int` - and `axis` a tuple, then the same `shift` must be used for all - specified axes. If a `shift` is positive, then array elements is - shifted positively (toward larger indices) along the dimension of - `axis`. - If a `shift` is negative, then array elements must be shifted - negatively (toward smaller indices) along the dimension of `axis`. - axis (Optional[Union[int, Tuple[int,...]]]): axis (or axes) along which - elements to shift. If `axis` is `None`, the array is - flattened, shifted, and then restored to its original shape. - Default: `None`. - - Returns: - usm_ndarray: - An array having the same `dtype`, `usm_type` and - `device` attributes as `x` and whose elements are shifted relative - to `x`. + Parameters + ---------- + x : usm_ndarray + Input array. + shift : {int, tuple of ints} + Number of places by which the elements are shifted. If `shift` + is a tuple, then `axis` must be a tuple of the same size, and + each of the given axes must be shifted by the corresponding + element in `shift`. If `shift` is an `int` and `axis` a tuple, + then the same `shift` must be used for all specified axes. If a + `shift` is positive, then array elements is shifted positively + (toward larger indices) along the dimension of `axis`. + If a `shift` is negative, then array elements must be shifted + negatively (toward smaller indices) along the dimension of `axis`. + axis : {None, int, tuple of ints}, optional + Axis (or axes) along which elements to shift. If `axis` is + `None`, the array is flattened, shifted, and then restored to + its original shape. + + Default: ``None``. + + Returns + ------- + out : usm_ndarray + An array having the same `dtype`, `usm_type` and + `device` attributes as `x` and whose elements are shifted relative + to `x`. + """ + if not isinstance(x, dpt.usm_ndarray): raise TypeError(f"Expected usm_ndarray type, got {type(x)}.") exec_q = x.sycl_queue @@ -825,26 +871,33 @@ def roll(x, /, shift, *, axis=None): def squeeze(X, /, axis=None): - """squeeze(x, axis) - + """ Removes singleton dimensions (axes) from array `x`. - Args: - x (usm_ndarray): input array - axis (Union[int, Tuple[int,...]]): axis (or axes) to squeeze. - - Returns: - usm_ndarray: - Output array is a view, if possible, - and a copy otherwise, but with all or a subset of the - dimensions of length 1 removed. Output has the same data - type as the input, is allocated on the same device as the - input and has the same USM allocation type as the input - array `x`. - - Raises: - ValueError: if the specified axis has a size greater than one. + Parameters + ---------- + x : usm_ndarray + Input array. + axis : {int, tuple of ints} + Axis (or axes) to squeeze. + + Returns + ------- + out : usm_ndarray + Output array is a view, if possible, + and a copy otherwise, but with all or a subset of the + dimensions of length 1 removed. Output has the same data + type as the input, is allocated on the same device as the + input and has the same USM allocation type as the input + array `x`. + + Raises + ------ + ValueError + If the specified axis has a size greater than one. + """ + if not isinstance(X, dpt.usm_ndarray): raise TypeError(f"Expected usm_ndarray type, got {type(X)}.") X_shape = X.shape @@ -871,29 +924,36 @@ def squeeze(X, /, axis=None): def stack(arrays, /, *, axis=0): """ - stack(arrays, axis) - Joins a sequence of arrays along a new axis. - Args: - arrays (Union[List[usm_ndarray], Tuple[usm_ndarray,...]]): - input arrays to join. Each array must have the same shape. - axis (int): axis along which the arrays will be joined. Providing - an `axis` specified the index of the new axis in the dimensions - of the output array. A valid axis must be on the interval - `[-N, N)`, where `N` is the rank (number of dimensions) of `x`. - Default: `0`. - - Returns: - usm_ndarray: - An output array having rank `N+1`, where `N` is - the rank (number of dimensions) of `x`. If the input arrays have - different data types, array API Type Promotion Rules apply. - - Raises: - ValueError: if not all input arrays have the same shape - IndexError: if provided an `axis` outside of the required interval. + Parameters + ---------- + arrays : {list of usm_ndarrays, tuple of usm_ndarrays} + Input arrays to join. Each array must have the same shape. + axis : int, optional + Axis along which the arrays will be joined. Providing + an `axis` specified the index of the new axis in the dimensions + of the output array. A valid axis must be on the interval + `[-N, N)`, where `N` is the rank (number of dimensions) of `x`. + + Default: ``0``. + + Returns + ------- + out : usm_ndarray + An output array having rank `N+1`, where `N` is + the rank (number of dimensions) of `x`. If the input arrays have + different data types, array API Type Promotion Rules apply. + + Raises + ------ + ValueError + If not all input arrays have the same shape. + IndexError + If provided an `axis` outside of the required interval. + """ + res_dtype, res_usm_type, exec_q = _arrays_validation(arrays) n = len(arrays) @@ -931,31 +991,37 @@ def stack(arrays, /, *, axis=0): def swapaxes(X, axis1, axis2): - """swapaxes(x, axis1, axis2) - + """ Interchanges two axes of an array. - Args: - x (usm_ndarray): input array - - axis1 (int): First axis. - If `x` has rank (i.e., number of dimensions) `N`, - a valid `axis` must be in the half-open interval `[-N, N)`. + Parameters + ---------- + x : usm_ndarray + Input array. + axis1 : int + First axis. + If `x` has rank (i.e., number of dimensions) `N`, + a valid `axis` must be in the half-open interval `[-N, N)`. + axis2 : int + Second axis. + If `x` has rank (i.e., number of dimensions) `N`, + a valid `axis` must be in the half-open interval `[-N, N)`. + + Returns + ------- + out : usm_ndarray + Array with swapped axes. + The returned array must has the same data type as `x`, + is created on the same device as `x` and has the same USM + allocation type as `x`. + + Raises + ------ + AxisError + If `axis` value is invalid. - axis2 (int): Second axis. - If `x` has rank (i.e., number of dimensions) `N`, - a valid `axis` must be in the half-open interval `[-N, N)`. - - Returns: - usm_ndarray: - Array with swapped axes. - The returned array must has the same data type as `x`, - is created on the same device as `x` and has the same USM - allocation type as `x`. - - Raises: - AxisError: if `axis` value is invalid. """ + if not isinstance(X, dpt.usm_ndarray): raise TypeError(f"Expected usm_ndarray type, got {type(X)}.") @@ -969,25 +1035,32 @@ def swapaxes(X, axis1, axis2): def unstack(X, /, *, axis=0): - """unstack(x, axis=0) - + """ Splits an array in a sequence of arrays along the given axis. - Args: - x (usm_ndarray): input array + Parameters + ---------- + x : usm_ndarray + Input array. + axis : int, optional + Axis along which `x` is unstacked. + If `x` has rank (i.e, number of dimensions) `N`, + a valid `axis` must reside in the half-open interval `[-N, N)`. - axis (int, optional): axis along which `x` is unstacked. - If `x` has rank (i.e, number of dimensions) `N`, - a valid `axis` must reside in the half-open interval `[-N, N)`. - Default: `0`. + Default: ``0``. - Returns: - Tuple[usm_ndarray,...]: - Output sequence of arrays which are views into the input array. + Returns + ------- + out : tuple of usm_ndarrays + Output sequence of arrays which are views into the input array. + + Raises + ------ + AxisError + If the `axis` value is invalid. - Raises: - AxisError: if the `axis` value is invalid. """ + if not isinstance(X, dpt.usm_ndarray): raise TypeError(f"Expected usm_ndarray type, got {type(X)}.") @@ -998,8 +1071,7 @@ def unstack(X, /, *, axis=0): def tile(x, repetitions, /): - """tile(x, repetitions) - + """ Repeat an input array `x` along each axis a number of times given by `repetitions`. @@ -1008,25 +1080,29 @@ def tile(x, repetitions, /): * If `M < N`, `x` will have `N - M` new axes prepended to its shape * If `M > N`, `repetitions` will have `M - N` ones prepended to it - Args: - x (usm_ndarray): input array + Parameters + ---------- + x : usm_ndarray + Input array. + repetitions : {int, tuple of ints} + The number of repetitions along each dimension of `x`. - repetitions (Union[int, Tuple[int, ...]]): - The number of repetitions along each dimension of `x`. + Returns + ------- + out : usm_ndarray + Tiled output array. - Returns: - usm_ndarray: - tiled output array. + The returned array will have rank `max(M, N)`. If `S` is the + shape of `x` after prepending dimensions and `R` is + `repetitions` after prepending ones, then the shape of the + result will be `S[i] * R[i]` for each dimension `i`. - The returned array will have rank `max(M, N)`. If `S` is the - shape of `x` after prepending dimensions and `R` is - `repetitions` after prepending ones, then the shape of the - result will be `S[i] * R[i]` for each dimension `i`. + The returned array will have the same data type as `x`. + The returned array will be located on the same device as `x` and + have the same USM allocation type as `x`. - The returned array will have the same data type as `x`. - The returned array will be located on the same device as `x` and - have the same USM allocation type as `x`. """ + if not isinstance(x, dpt.usm_ndarray): raise TypeError(f"Expected usm_ndarray type, got {type(x)}.") From 93f14217f6ed78da16b18271eb98365f0296e2b5 Mon Sep 17 00:00:00 2001 From: Vladislav Perevezentsev Date: Fri, 10 Apr 2026 10:22:28 -0700 Subject: [PATCH 15/46] Update _print.py doc to Sphinx format --- dpnp/tensor/_print.py | 384 +++++++++++++++++++++++------------------- 1 file changed, 209 insertions(+), 175 deletions(-) diff --git a/dpnp/tensor/_print.py b/dpnp/tensor/_print.py index e39bf904148..5c77dcf54d0 100644 --- a/dpnp/tensor/_print.py +++ b/dpnp/tensor/_print.py @@ -37,7 +37,7 @@ import dpnp.tensor as dpt import dpnp.tensor._tensor_impl as ti -__doc__ = "Print functions for :class:`dpctl.tensor.usm_ndarray`." +__doc__ = "Print functions for :class:`dpnp.tensor.usm_ndarray`." _print_options = { "linewidth": 75, @@ -131,76 +131,86 @@ def set_print_options( numpy=False, ): """ - set_print_options(linewidth=None, edgeitems=None, threshold=None, - precision=None, floatmode=None, suppress=None, - nanstr=None, infstr=None, sign=None, numpy=False) - - Set options for printing :class:`dpctl.tensor.usm_ndarray` class. - - Args: - linewidth (int, optional): - Number of characters printed per line. - Raises `TypeError` if linewidth is not an integer. - Default: `75`. - edgeitems (int, optional): - Number of elements at the beginning and end - when the printed array is abbreviated. - Raises `TypeError` if edgeitems is not an integer. - Default: `3`. - threshold (int, optional): - Number of elements that triggers array abbreviation. - Raises `TypeError` if threshold is not an integer. - Default: `1000`. - precision (int or None, optional): - Number of digits printed for floating point numbers. - Raises `TypeError` if precision is not an integer. - Default: `8`. - floatmode (str, optional): - Controls how floating point numbers are interpreted. - `"fixed:`: - Always prints exactly `precision` digits. - `"unique"`: - Ignores precision, prints the number of - digits necessary to uniquely specify each number. - `"maxprec"`: - Prints `precision` digits or fewer, - if fewer will uniquely represent a number. - `"maxprec_equal"`: - Prints an equal number of digits - for each number. This number is `precision` digits - or fewer, if fewer will uniquely represent each number. - Raises `ValueError` if floatmode is not one of - `fixed`, `unique`, `maxprec`, or `maxprec_equal`. - Default: "maxprec_equal" - suppress (bool, optional): - If `True,` numbers equal to zero in the current precision - will print as zero. - Default: `False`. - nanstr (str, optional): - String used to represent nan. - Raises `TypeError` if nanstr is not a string. - Default: `"nan"`. - infstr (str, optional): - String used to represent infinity. - Raises `TypeError` if infstr is not a string. - Default: `"inf"`. - sign (str, optional): - Controls the sign of floating point numbers. - `"-"`: - Omit the sign of positive numbers. - `"+"`: - Always print the sign of positive numbers. - `" "`: - Always print a whitespace in place of the - sign of positive numbers. - Raises `ValueError` if sign is not one of - `"-"`, `"+"`, or `" "`. - Default: `"-"`. - numpy (bool, optional): If `True,` then before other specified print - options are set, a dictionary of Numpy's print options - will be used to initialize dpctl's print options. - Default: "False" + Set options for printing :class:`dpnp.tensor.usm_ndarray` class. + + Parameters + ---------- + linewidth : int, optional + Number of characters printed per line. + Raises `TypeError` if linewidth is not an integer. + + Default: ``75``. + edgeitems : int, optional + Number of elements at the beginning and end + when the printed array is abbreviated. + Raises `TypeError` if edgeitems is not an integer. + + Default: ``3``. + threshold : int, optional + Number of elements that triggers array abbreviation. + Raises `TypeError` if threshold is not an integer. + + Default: ``1000``. + precision : int, optional + Number of digits printed for floating point numbers. + Raises `TypeError` if precision is not an integer. + + Default: ``8``. + floatmode : str, optional + Controls how floating point numbers are interpreted. + `"fixed"`: + Always prints exactly `precision` digits. + `"unique"`: + Ignores precision, prints the number of + digits necessary to uniquely specify each number. + `"maxprec"`: + Prints `precision` digits or fewer, + if fewer will uniquely represent a number. + `"maxprec_equal"`: + Prints an equal number of digits + for each number. This number is `precision` digits + or fewer, if fewer will uniquely represent each number. + Raises `ValueError` if floatmode is not one of + `fixed`, `unique`, `maxprec`, or `maxprec_equal`. + + Default: ``"maxprec_equal"``. + suppress : bool, optional + If `True,` numbers equal to zero in the current precision + will print as zero. + + Default: ``False``. + nanstr : str, optional + String used to represent nan. + Raises `TypeError` if nanstr is not a string. + + Default: ``"nan"``. + infstr : str, optional + String used to represent infinity. + Raises `TypeError` if infstr is not a string. + + Default: ``"inf"``. + sign : str, optional + Controls the sign of floating point numbers. + `"-"`: + Omit the sign of positive numbers. + `"+"`: + Always print the sign of positive numbers. + `" "`: + Always print a whitespace in place of the + sign of positive numbers. + Raises `ValueError` if sign is not one of + `"-"`, `"+"`, or `" "`. + + Default: ``"-"``. + numpy : bool, optional + If `True,` then before other specified print + options are set, a dictionary of Numpy's print options + will be used to initialize dpnp.tensor's print options. + + Default: ``False``. + """ + options = _options_dict( linewidth=linewidth, edgeitems=edgeitems, @@ -217,14 +227,14 @@ def set_print_options( def get_print_options(): - """get_print_options() - + """ Returns a copy of current options for printing - :class:`dpctl.tensor.usm_ndarray` class. + :class:`dpnp.tensor.usm_ndarray` class. - Returns: - dict: dictionary with array - printing option settings. + Returns + ------- + out : dict + Dictionary with array printing option settings. Options: - "linewidth" : int, default 75 @@ -236,7 +246,9 @@ def get_print_options(): - "nanstr" : str, default "nan" - "infstr" : str, default "inf" - "sign" : str, default "-" + """ + return _print_options.copy() @@ -247,7 +259,9 @@ def print_options(*args, **kwargs): Set print options for the scope of a `with` block. `as` yields dictionary of print options. + """ + options = dpt.get_print_options() try: dpt.set_print_options(*args, **kwargs) @@ -317,85 +331,96 @@ def usm_ndarray_str( suffix="", ): """ - usm_ndarray_str(x, line_width=None, edgeitems=None, threshold=None, - precision=None, floatmode=None, suppress=None, - sign=None, numpy=False, separator=" ", prefix="", - suffix="") - Returns a string representing the elements of a - :class:`dpctl.tensor.usm_ndarray`. - - Args: - x (usm_ndarray): - Input array. - line_width (int, optional): - Number of characters printed per line. - Raises `TypeError` if line_width is not an integer. - Default: `75`. - edgeitems (int, optional): - Number of elements at the beginning and end - when the printed array is abbreviated. - Raises `TypeError` if edgeitems is not an integer. - Default: `3`. - threshold (int, optional): - Number of elements that triggers array abbreviation. - Raises `TypeError` if threshold is not an integer. - Default: `1000`. - precision (int or None, optional): - Number of digits printed for floating point numbers. - Raises `TypeError` if precision is not an integer. - Default: `8`. - floatmode (str, optional): - Controls how floating point numbers are interpreted. - `"fixed:`: - Always prints exactly `precision` digits. - `"unique"`: - Ignores precision, prints the number of - digits necessary to uniquely specify each number. - `"maxprec"`: - Prints `precision` digits or fewer, - if fewer will uniquely represent a number. - `"maxprec_equal"`: - Prints an equal number of digits for each number. - This number is `precision` digits or fewer, - if fewer will uniquely represent each number. - Raises `ValueError` if floatmode is not one of - `fixed`, `unique`, `maxprec`, or `maxprec_equal`. - Default: "maxprec_equal" - suppress (bool, optional): - If `True,` numbers equal to zero in the current precision - will print as zero. - Default: `False`. - sign (str, optional): - Controls the sign of floating point numbers. - `"-"`: - Omit the sign of positive numbers. - `"+"`: - Always print the sign of positive numbers. - `" "`: - Always print a whitespace in place of the - sign of positive numbers. - Raises `ValueError` if sign is not one of - `"-"`, `"+"`, or `" "`. - Default: `"-"`. - numpy (bool, optional): - If `True,` then before other specified print - options are set, a dictionary of Numpy's print options - will be used to initialize dpctl's print options. - Default: "False" - separator (str, optional): - String inserted between elements of the array string. - Default: " " - prefix (str, optional): - String used to determine spacing to the left of the array string. - Default: "" - suffix (str, optional): - String that determines length of the last line of the array string. - Default: "" - - Returns: - str: string representation of input array. + :class:`dpnp.tensor.usm_ndarray`. + + Parameters + ---------- + x : usm_ndarray + Input array. + line_width : int, optional + Number of characters printed per line. + Raises `TypeError` if line_width is not an integer. + + Default: ``75``. + edgeitems : int, optional + Number of elements at the beginning and end + when the printed array is abbreviated. + Raises `TypeError` if edgeitems is not an integer. + + Default: ``3``. + threshold : int, optional + Number of elements that triggers array abbreviation. + Raises `TypeError` if threshold is not an integer. + + Default: ``1000``. + precision : int, optional + Number of digits printed for floating point numbers. + Raises `TypeError` if precision is not an integer. + + Default: ``8``. + floatmode : str, optional + Controls how floating point numbers are interpreted. + `"fixed"`: + Always prints exactly `precision` digits. + `"unique"`: + Ignores precision, prints the number of + digits necessary to uniquely specify each number. + `"maxprec"`: + Prints `precision` digits or fewer, + if fewer will uniquely represent a number. + `"maxprec_equal"`: + Prints an equal number of digits for each number. + This number is `precision` digits or fewer, + if fewer will uniquely represent each number. + Raises `ValueError` if floatmode is not one of + `fixed`, `unique`, `maxprec`, or `maxprec_equal`. + + Default: ``"maxprec_equal"``. + suppress : bool, optional + If `True,` numbers equal to zero in the current precision + will print as zero. + + Default: ``False``. + sign : str, optional + Controls the sign of floating point numbers. + `"-"`: + Omit the sign of positive numbers. + `"+"`: + Always print the sign of positive numbers. + `" "`: + Always print a whitespace in place of the + sign of positive numbers. + Raises `ValueError` if sign is not one of + `"-"`, `"+"`, or `" "`. + + Default: ``"-"``. + numpy : bool, optional + If `True,` then before other specified print + options are set, a dictionary of Numpy's print options + will be used to initialize dpnp.tensor's print options. + + Default: ``False``. + separator : str, optional + String inserted between elements of the array string. + + Default: ``" "``. + prefix : str, optional + String used to determine spacing to the left of the array string. + + Default: ``""``. + suffix : str, optional + String that determines length of the last line of the array string. + + Default: ``""``. + + Returns + ------- + out : str + String representation of input array. + """ + if not isinstance(x, dpt.usm_ndarray): raise TypeError(f"Expected dpnp.tensor.usm_ndarray, got {type(x)}") @@ -432,32 +457,41 @@ def usm_ndarray_repr( x, line_width=None, precision=None, suppress=None, prefix="usm_ndarray" ): """ - usm_ndarray_repr(x, line_width=None, precision=None, - suppress=None, prefix="") - Returns a formatted string representing the elements - of a :class:`dpctl.tensor.usm_ndarray` and its data type, + of a :class:`dpnp.tensor.usm_ndarray` and its data type, if not a default type. - Args: - x (usm_ndarray): Input array. - line_width (int, optional): Number of characters printed per line. - Raises `TypeError` if line_width is not an integer. - Default: `75`. - precision (int or None, optional): Number of digits printed for - floating point numbers. - Raises `TypeError` if precision is not an integer. - Default: `8`. - suppress (bool, optional): If `True,` numbers equal to zero - in the current precision will print as zero. - Default: `False`. - prefix (str, optional): String inserted at the start of the array - string. - Default: "" - - Returns: - str: formatted string representing the input array + Parameters + ---------- + x : usm_ndarray + Input array. + line_width : int, optional + Number of characters printed per line. + Raises `TypeError` if line_width is not an integer. + + Default: ``75``. + precision : int, optional + Number of digits printed for floating point numbers. + Raises `TypeError` if precision is not an integer. + + Default: ``8``. + suppress : bool, optional + If `True,` numbers equal to zero in the current precision + will print as zero. + + Default: ``False``. + prefix : str, optional + String inserted at the start of the array string. + + Default: ``"usm_ndarray"``. + + Returns + ------- + out : str + Formatted string representing the input array. + """ + if not isinstance(x, dpt.usm_ndarray): raise TypeError(f"Expected dpnp.tensor.usm_ndarray, got {type(x)}") From d44e19871093eefeb2689e9a154a760bfe44f28a Mon Sep 17 00:00:00 2001 From: Vladislav Perevezentsev Date: Fri, 10 Apr 2026 10:26:18 -0700 Subject: [PATCH 16/46] Update _reduction.py doc to Sphinx format --- dpnp/tensor/_reduction.py | 695 +++++++++++++++++++++----------------- 1 file changed, 390 insertions(+), 305 deletions(-) diff --git a/dpnp/tensor/_reduction.py b/dpnp/tensor/_reduction.py index 782fc2b0b44..6444fa05ee7 100644 --- a/dpnp/tensor/_reduction.py +++ b/dpnp/tensor/_reduction.py @@ -403,32 +403,41 @@ def argmax(x, /, *, axis=None, keepdims=False, out=None): When the maximum value occurs multiple times, the indices corresponding to the first occurrence are returned. - Args: - x (usm_ndarray): - input array. - axis (Optional[int]): - axis along which to search. If ``None``, returns the index of the - maximum value of the flattened array. - Default: ``None``. - keepdims (Optional[bool]): - if ``True``, the reduced axes (dimensions) are included in the - result as singleton dimensions, so that the returned array remains - compatible with the input arrays according to Array Broadcasting - rules. Otherwise, if ``False``, the reduced axes are not included - in the returned array. Default: ``False``. - out (Optional[usm_ndarray]): - the array into which the result is written. - The data type of ``out`` must match the expected shape and the - expected data type of the result. - If ``None`` then a new array is returned. Default: ``None``. - - Returns: - usm_ndarray: - an array containing the indices of the first occurrence of the - maximum values. If the entire array was searched, a - zero-dimensional array is returned. The returned array has the - default array index data type for the device of ``x``. + Parameters + ---------- + x : usm_ndarray + Input array. + axis : int, optional + Axis along which to search. If ``None``, returns the index of the + maximum value of the flattened array. + + Default: ``None``. + keepdims : bool, optional + If ``True``, the reduced axes (dimensions) are included in the + result as singleton dimensions, so that the returned array remains + compatible with the input arrays according to Array Broadcasting + rules. Otherwise, if ``False``, the reduced axes are not included + in the returned array. + + Default: ``False``. + out : {None, usm_ndarray}, optional + The array into which the result is written. + The data type of ``out`` must match the expected shape and the + expected data type of the result. + If ``None`` then a new array is returned. + + Default: ``None``. + + Returns + ------- + out : usm_ndarray + An array containing the indices of the first occurrence of the + maximum values. If the entire array was searched, a + zero-dimensional array is returned. The returned array has the + default array index data type for the device of ``x``. + """ + return _search_over_axis(x, axis, keepdims, out, tri._argmax_over_axis) @@ -440,32 +449,41 @@ def argmin(x, /, *, axis=None, keepdims=False, out=None): When the minimum value occurs multiple times, the indices corresponding to the first occurrence are returned. - Args: - x (usm_ndarray): - input array. - axis (Optional[int]): - axis along which to search. If ``None``, returns the index of the - minimum value of the flattened array. - Default: ``None``. - keepdims (Optional[bool]): - if ``True``, the reduced axes (dimensions) are included in the - result as singleton dimensions, so that the returned array remains - compatible with the input arrays according to Array Broadcasting - rules. Otherwise, if ``False``, the reduced axes are not included - in the returned array. Default: ``False``. - out (Optional[usm_ndarray]): - the array into which the result is written. - The data type of ``out`` must match the expected shape and the - expected data type of the result. - If ``None`` then a new array is returned. Default: ``None``. - - Returns: - usm_ndarray: - an array containing the indices of the first occurrence of the - minimum values. If the entire array was searched, a - zero-dimensional array is returned. The returned array has the - default array index data type for the device of ``x``. + Parameters + ---------- + x : usm_ndarray + Input array. + axis : int, optional + Axis along which to search. If ``None``, returns the index of the + minimum value of the flattened array. + + Default: ``None``. + keepdims : bool, optional + If ``True``, the reduced axes (dimensions) are included in the + result as singleton dimensions, so that the returned array remains + compatible with the input arrays according to Array Broadcasting + rules. Otherwise, if ``False``, the reduced axes are not included + in the returned array. + + Default: ``False``. + out : {None, usm_ndarray}, optional + The array into which the result is written. + The data type of ``out`` must match the expected shape and the + expected data type of the result. + If ``None`` then a new array is returned. + + Default: ``None``. + + Returns + ------- + out : usm_ndarray + An array containing the indices of the first occurrence of the + minimum values. If the entire array was searched, a + zero-dimensional array is returned. The returned array has the + default array index data type for the device of ``x``. + """ + return _search_over_axis(x, axis, keepdims, out, tri._argmin_over_axis) @@ -473,34 +491,43 @@ def count_nonzero(x, /, *, axis=None, keepdims=False, out=None): """ Counts the number of elements in the input array ``x`` which are non-zero. - Args: - x (usm_ndarray): - input array. - axis (Optional[int, Tuple[int, ...]]): - axis or axes along which to count. If a tuple of unique integers, - the number of non-zero values are computed over multiple axes. - If ``None``, the number of non-zero values is computed over the - entire array. - Default: ``None``. - keepdims (Optional[bool]): - if ``True``, the reduced axes (dimensions) are included in the - result as singleton dimensions, so that the returned array remains - compatible with the input arrays according to Array Broadcasting - rules. Otherwise, if ``False``, the reduced axes are not included - in the returned array. Default: ``False``. - out (Optional[usm_ndarray]): - the array into which the result is written. - The data type of ``out`` must match the expected shape and data - type. - If ``None`` then a new array is returned. Default: ``None``. - - Returns: - usm_ndarray: - an array containing the count of non-zero values. If the sum was - computed over the entire array, a zero-dimensional array is - returned. The returned array will have the default array index data - type. + Parameters + ---------- + x : usm_ndarray + Input array. + axis : {None, int, tuple of ints}, optional + Axis or axes along which to count. If a tuple of unique integers, + the number of non-zero values are computed over multiple axes. + If ``None``, the number of non-zero values is computed over the + entire array. + + Default: ``None``. + keepdims : bool, optional + If ``True``, the reduced axes (dimensions) are included in the + result as singleton dimensions, so that the returned array remains + compatible with the input arrays according to Array Broadcasting + rules. Otherwise, if ``False``, the reduced axes are not included + in the returned array. + + Default: ``False``. + out : {None, usm_ndarray}, optional + The array into which the result is written. + The data type of ``out`` must match the expected shape and data + type. + If ``None`` then a new array is returned. + + Default: ``None``. + + Returns + ------- + out : usm_ndarray + An array containing the count of non-zero values. If the sum was + computed over the entire array, a zero-dimensional array is + returned. The returned array will have the default array index data + type. + """ + if x.dtype != dpt.bool: x = dpt.astype(x, dpt.bool, copy=False) return sum( @@ -517,49 +544,59 @@ def logsumexp(x, /, *, axis=None, dtype=None, keepdims=False, out=None): Calculates the logarithm of the sum of exponentials of elements in the input array ``x``. - Args: - x (usm_ndarray): - input array. - axis (Optional[int, Tuple[int, ...]]): - axis or axes along which values must be computed. If a tuple - of unique integers, values are computed over multiple axes. - If ``None``, the result is computed over the entire array. - Default: ``None``. - dtype (Optional[dtype]): - data type of the returned array. If ``None``, the default data - type is inferred from the "kind" of the input array data type. - - * If ``x`` has a real-valued floating-point data type, the - returned array will have the same data type as ``x``. - * If ``x`` has a boolean or integral data type, the returned array - will have the default floating point data type for the device - where input array ``x`` is allocated. - * If ``x`` has a complex-valued floating-point data type, - an error is raised. - - If the data type (either specified or resolved) differs from the - data type of ``x``, the input array elements are cast to the - specified data type before computing the result. - Default: ``None``. - keepdims (Optional[bool]): - if ``True``, the reduced axes (dimensions) are included in the - result as singleton dimensions, so that the returned array remains - compatible with the input arrays according to Array Broadcasting - rules. Otherwise, if ``False``, the reduced axes are not included - in the returned array. Default: ``False``. - out (Optional[usm_ndarray]): - the array into which the result is written. - The data type of ``out`` must match the expected shape and the - expected data type of the result or (if provided) ``dtype``. - If ``None`` then a new array is returned. Default: ``None``. - - Returns: - usm_ndarray: - an array containing the results. If the result was computed over - the entire array, a zero-dimensional array is returned. - The returned array has the data type as described in the - ``dtype`` parameter description above. + Parameters + ---------- + x : usm_ndarray + Input array. + axis : {None, int, tuple of ints}, optional + Axis or axes along which values must be computed. If a tuple + of unique integers, values are computed over multiple axes. + If ``None``, the result is computed over the entire array. + + Default: ``None``. + dtype : dtype, optional + Data type of the returned array. If ``None``, the default data + type is inferred from the "kind" of the input array data type. + + * If ``x`` has a real-valued floating-point data type, the + returned array will have the same data type as ``x``. + * If ``x`` has a boolean or integral data type, the returned array + will have the default floating point data type for the device + where input array ``x`` is allocated. + * If ``x`` has a complex-valued floating-point data type, + an error is raised. + + If the data type (either specified or resolved) differs from the + data type of ``x``, the input array elements are cast to the + specified data type before computing the result. + + Default: ``None``. + keepdims : bool, optional + If ``True``, the reduced axes (dimensions) are included in the + result as singleton dimensions, so that the returned array remains + compatible with the input arrays according to Array Broadcasting + rules. Otherwise, if ``False``, the reduced axes are not included + in the returned array. + + Default: ``False``. + out : {None, usm_ndarray}, optional + The array into which the result is written. + The data type of ``out`` must match the expected shape and the + expected data type of the result or (if provided) ``dtype``. + If ``None`` then a new array is returned. + + Default: ``None``. + + Returns + ------- + out : usm_ndarray + An array containing the results. If the result was computed over + the entire array, a zero-dimensional array is returned. + The returned array has the data type as described in the + ``dtype`` parameter description above. + """ + return _reduction_over_axis( x, axis, @@ -578,32 +615,41 @@ def max(x, /, *, axis=None, keepdims=False, out=None): """ Calculates the maximum value of the input array ``x``. - Args: - x (usm_ndarray): - input array. - axis (Optional[int, Tuple[int, ...]]): - axis or axes along which maxima must be computed. If a tuple - of unique integers, the maxima are computed over multiple axes. - If ``None``, the max is computed over the entire array. - Default: ``None``. - keepdims (Optional[bool]): - if ``True``, the reduced axes (dimensions) are included in the - result as singleton dimensions, so that the returned array remains - compatible with the input arrays according to Array Broadcasting - rules. Otherwise, if ``False``, the reduced axes are not included - in the returned array. Default: ``False``. - out (Optional[usm_ndarray]): - the array into which the result is written. - The data type of ``out`` must match the expected shape and the - expected data type of the result. - If ``None`` then a new array is returned. Default: ``None``. - - Returns: - usm_ndarray: - an array containing the maxima. If the max was computed over the - entire array, a zero-dimensional array is returned. The returned - array has the same data type as ``x``. + Parameters + ---------- + x : usm_ndarray + Input array. + axis : {None, int, tuple of ints}, optional + Axis or axes along which maxima must be computed. If a tuple + of unique integers, the maxima are computed over multiple axes. + If ``None``, the max is computed over the entire array. + + Default: ``None``. + keepdims : bool, optional + If ``True``, the reduced axes (dimensions) are included in the + result as singleton dimensions, so that the returned array remains + compatible with the input arrays according to Array Broadcasting + rules. Otherwise, if ``False``, the reduced axes are not included + in the returned array. + + Default: ``False``. + out : {None, usm_ndarray}, optional + The array into which the result is written. + The data type of ``out`` must match the expected shape and the + expected data type of the result. + If ``None`` then a new array is returned. + + Default: ``None``. + + Returns + ------- + out : usm_ndarray + An array containing the maxima. If the max was computed over the + entire array, a zero-dimensional array is returned. The returned + array has the same data type as ``x``. + """ + return _comparison_over_axis(x, axis, keepdims, out, tri._max_over_axis) @@ -611,32 +657,41 @@ def min(x, /, *, axis=None, keepdims=False, out=None): """ Calculates the minimum value of the input array ``x``. - Args: - x (usm_ndarray): - input array. - axis (Optional[int, Tuple[int, ...]]): - axis or axes along which minima must be computed. If a tuple - of unique integers, the minima are computed over multiple axes. - If ``None``, the min is computed over the entire array. - Default: ``None``. - keepdims (Optional[bool]): - if ``True``, the reduced axes (dimensions) are included in the - result as singleton dimensions, so that the returned array remains - compatible with the input arrays according to Array Broadcasting - rules. Otherwise, if ``False``, the reduced axes are not included - in the returned array. Default: ``False``. - out (Optional[usm_ndarray]): - the array into which the result is written. - The data type of ``out`` must match the expected shape and the - expected data type of the result. - If ``None`` then a new array is returned. Default: ``None``. - - Returns: - usm_ndarray: - an array containing the minima. If the min was computed over the - entire array, a zero-dimensional array is returned. The returned - array has the same data type as ``x``. + Parameters + ---------- + x : usm_ndarray + Input array. + axis : {None, int, tuple of ints}, optional + Axis or axes along which minima must be computed. If a tuple + of unique integers, the minima are computed over multiple axes. + If ``None``, the min is computed over the entire array. + + Default: ``None``. + keepdims : bool, optional + If ``True``, the reduced axes (dimensions) are included in the + result as singleton dimensions, so that the returned array remains + compatible with the input arrays according to Array Broadcasting + rules. Otherwise, if ``False``, the reduced axes are not included + in the returned array. + + Default: ``False``. + out : {None, usm_ndarray}, optional + The array into which the result is written. + The data type of ``out`` must match the expected shape and the + expected data type of the result. + If ``None`` then a new array is returned. + + Default: ``None``. + + Returns + ------- + out : usm_ndarray + An array containing the minima. If the min was computed over the + entire array, a zero-dimensional array is returned. The returned + array has the same data type as ``x``. + """ + return _comparison_over_axis(x, axis, keepdims, out, tri._min_over_axis) @@ -644,54 +699,64 @@ def prod(x, /, *, axis=None, dtype=None, keepdims=False, out=None): """ Calculates the product of elements in the input array ``x``. - Args: - x (usm_ndarray): - input array. - axis (Optional[int, Tuple[int, ...]]): - axis or axes along which products must be computed. If a tuple - of unique integers, products are computed over multiple axes. - If ``None``, the product is computed over the entire array. - Default: ``None``. - dtype (Optional[dtype]): - data type of the returned array. If ``None``, the default data - type is inferred from the "kind" of the input array data type. - - * If ``x`` has a real- or complex-valued floating-point data - type, the returned array will have the same data type as - ``x``. - * If ``x`` has signed integral data type, the returned array - will have the default signed integral type for the device - where input array ``x`` is allocated. - * If ``x`` has unsigned integral data type, the returned array - will have the default unsigned integral type for the device - where input array ``x`` is allocated. - * If ``x`` has a boolean data type, the returned array will - have the default signed integral type for the device - where input array ``x`` is allocated. - - If the data type (either specified or resolved) differs from the - data type of ``x``, the input array elements are cast to the - specified data type before computing the product. - Default: ``None``. - keepdims (Optional[bool]): - if ``True``, the reduced axes (dimensions) are included in the - result as singleton dimensions, so that the returned array remains - compatible with the input arrays according to Array Broadcasting - rules. Otherwise, if ``False``, the reduced axes are not included - in the returned array. Default: ``False``. - out (Optional[usm_ndarray]): - the array into which the result is written. - The data type of ``out`` must match the expected shape and the - expected data type of the result or (if provided) ``dtype``. - If ``None`` then a new array is returned. Default: ``None``. - - Returns: - usm_ndarray: - an array containing the products. If the product was computed over - the entire array, a zero-dimensional array is returned. The - returned array has the data type as described in the ``dtype`` - parameter description above. + Parameters + ---------- + x : usm_ndarray + Input array. + axis : {None, int, tuple of ints}, optional + Axis or axes along which products must be computed. If a tuple + of unique integers, products are computed over multiple axes. + If ``None``, the product is computed over the entire array. + + Default: ``None``. + dtype : dtype, optional + Data type of the returned array. If ``None``, the default data + type is inferred from the "kind" of the input array data type. + + * If ``x`` has a real- or complex-valued floating-point data + type, the returned array will have the same data type as + ``x``. + * If ``x`` has signed integral data type, the returned array + will have the default signed integral type for the device + where input array ``x`` is allocated. + * If ``x`` has unsigned integral data type, the returned array + will have the default unsigned integral type for the device + where input array ``x`` is allocated. + * If ``x`` has a boolean data type, the returned array will + have the default signed integral type for the device + where input array ``x`` is allocated. + + If the data type (either specified or resolved) differs from the + data type of ``x``, the input array elements are cast to the + specified data type before computing the product. + + Default: ``None``. + keepdims : bool, optional + If ``True``, the reduced axes (dimensions) are included in the + result as singleton dimensions, so that the returned array remains + compatible with the input arrays according to Array Broadcasting + rules. Otherwise, if ``False``, the reduced axes are not included + in the returned array. + + Default: ``False``. + out : {None, usm_ndarray}, optional + The array into which the result is written. + The data type of ``out`` must match the expected shape and the + expected data type of the result or (if provided) ``dtype``. + If ``None`` then a new array is returned. + + Default: ``None``. + + Returns + ------- + out : usm_ndarray + An array containing the products. If the product was computed over + the entire array, a zero-dimensional array is returned. The + returned array has the data type as described in the ``dtype`` + parameter description above. + """ + return _reduction_over_axis( x, axis, @@ -709,48 +774,59 @@ def reduce_hypot(x, /, *, axis=None, dtype=None, keepdims=False, out=None): Calculates the square root of the sum of squares of elements in the input array ``x``. - Args: - x (usm_ndarray): - input array. - axis (Optional[int, Tuple[int, ...]]): - axis or axes along which values must be computed. If a tuple - of unique integers, values are computed over multiple axes. - If ``None``, the result is computed over the entire array. - Default: ``None``. - dtype (Optional[dtype]): - data type of the returned array. If ``None``, the default data - type is inferred from the "kind" of the input array data type. - - * If ``x`` has a real-valued floating-point data type, the - returned array will have the same data type as ``x``. - * If ``x`` has a boolean or integral data type, the returned array - will have the default floating point data type for the device - where input array ``x`` is allocated. - * If ``x`` has a complex-valued floating-point data type, - an error is raised. - - If the data type (either specified or resolved) differs from the - data type of ``x``, the input array elements are cast to the - specified data type before computing the result. Default: ``None``. - keepdims (Optional[bool]): - if ``True``, the reduced axes (dimensions) are included in the - result as singleton dimensions, so that the returned array remains - compatible with the input arrays according to Array Broadcasting - rules. Otherwise, if ``False``, the reduced axes are not included - in the returned array. Default: ``False``. - out (Optional[usm_ndarray]): - the array into which the result is written. - The data type of ``out`` must match the expected shape and the - expected data type of the result or (if provided) ``dtype``. - If ``None`` then a new array is returned. Default: ``None``. - - Returns: - usm_ndarray: - an array containing the results. If the result was computed over - the entire array, a zero-dimensional array is returned. The - returned array has the data type as described in the ``dtype`` - parameter description above. + Parameters + ---------- + x : usm_ndarray + Input array. + axis : {None, int, tuple of ints}, optional + Axis or axes along which values must be computed. If a tuple + of unique integers, values are computed over multiple axes. + If ``None``, the result is computed over the entire array. + + Default: ``None``. + dtype : dtype, optional + Data type of the returned array. If ``None``, the default data + type is inferred from the "kind" of the input array data type. + + * If ``x`` has a real-valued floating-point data type, the + returned array will have the same data type as ``x``. + * If ``x`` has a boolean or integral data type, the returned array + will have the default floating point data type for the device + where input array ``x`` is allocated. + * If ``x`` has a complex-valued floating-point data type, + an error is raised. + + If the data type (either specified or resolved) differs from the + data type of ``x``, the input array elements are cast to the + specified data type before computing the result. + + Default: ``None``. + keepdims : bool, optional + If ``True``, the reduced axes (dimensions) are included in the + result as singleton dimensions, so that the returned array remains + compatible with the input arrays according to Array Broadcasting + rules. Otherwise, if ``False``, the reduced axes are not included + in the returned array. + + Default: ``False``. + out : {None, usm_ndarray}, optional + The array into which the result is written. + The data type of ``out`` must match the expected shape and the + expected data type of the result or (if provided) ``dtype``. + If ``None`` then a new array is returned. + + Default: ``None``. + + Returns + ------- + out : usm_ndarray + An array containing the results. If the result was computed over + the entire array, a zero-dimensional array is returned. The + returned array has the data type as described in the ``dtype`` + parameter description above. + """ + return _reduction_over_axis( x, axis, @@ -769,55 +845,64 @@ def sum(x, /, *, axis=None, dtype=None, keepdims=False, out=None): """ Calculates the sum of elements in the input array ``x``. - Args: - x (usm_ndarray): - input array. - axis (Optional[int, Tuple[int, ...]]): - axis or axes along which sums must be computed. If a tuple - of unique integers, sums are computed over multiple axes. - If ``None``, the sum is computed over the entire array. - Default: ``None``. - dtype (Optional[dtype]): - data type of the returned array. If ``None``, the default data - type is inferred from the "kind" of the input array data type. - - * If ``x`` has a real- or complex-valued floating-point data - type, the returned array will have the same data type as - ``x``. - * If ``x`` has signed integral data type, the returned array - will have the default signed integral type for the device - where input array ``x`` is allocated. - * If ``x`` has unsigned integral data type, the returned array - will have the default unsigned integral type for the device - where input array ``x`` is allocated. - array ``x`` is allocated. - * If ``x`` has a boolean data type, the returned array will - have the default signed integral type for the device - where input array ``x`` is allocated. - - If the data type (either specified or resolved) differs from the - data type of ``x``, the input array elements are cast to the - specified data type before computing the sum. - Default: ``None``. - keepdims (Optional[bool]): - if ``True``, the reduced axes (dimensions) are included in the - result as singleton dimensions, so that the returned array remains - compatible with the input arrays according to Array Broadcasting - rules. Otherwise, if ``False``, the reduced axes are not included - in the returned array. Default: ``False``. - out (Optional[usm_ndarray]): - the array into which the result is written. - The data type of ``out`` must match the expected shape and the - expected data type of the result or (if provided) ``dtype``. - If ``None`` then a new array is returned. Default: ``None``. - - Returns: - usm_ndarray: - an array containing the sums. If the sum was computed over the - entire array, a zero-dimensional array is returned. The returned - array has the data type as described in the ``dtype`` parameter - description above. + Parameters + ---------- + x : usm_ndarray + Input array. + axis : {None, int, tuple of ints}, optional + Axis or axes along which sums must be computed. If a tuple + of unique integers, sums are computed over multiple axes. + If ``None``, the sum is computed over the entire array. + + Default: ``None``. + dtype : dtype, optional + Data type of the returned array. If ``None``, the default data + type is inferred from the "kind" of the input array data type. + + * If ``x`` has a real- or complex-valued floating-point data + type, the returned array will have the same data type as + ``x``. + * If ``x`` has signed integral data type, the returned array + will have the default signed integral type for the device + where input array ``x`` is allocated. + * If ``x`` has unsigned integral data type, the returned array + will have the default unsigned integral type for the device + where input array ``x`` is allocated. + * If ``x`` has a boolean data type, the returned array will + have the default signed integral type for the device + where input array ``x`` is allocated. + + If the data type (either specified or resolved) differs from the + data type of ``x``, the input array elements are cast to the + specified data type before computing the sum. + + Default: ``None``. + keepdims : bool, optional + If ``True``, the reduced axes (dimensions) are included in the + result as singleton dimensions, so that the returned array remains + compatible with the input arrays according to Array Broadcasting + rules. Otherwise, if ``False``, the reduced axes are not included + in the returned array. + + Default: ``False``. + out : {None, usm_ndarray}, optional + The array into which the result is written. + The data type of ``out`` must match the expected shape and the + expected data type of the result or (if provided) ``dtype``. + If ``None`` then a new array is returned. + + Default: ``None``. + + Returns + ------- + out : usm_ndarray + An array containing the sums. If the sum was computed over the + entire array, a zero-dimensional array is returned. The returned + array has the data type as described in the ``dtype`` parameter + description above. + """ + return _reduction_over_axis( x, axis, From dec97390af7bcfe43a1dfbc7f1830e7c152432c7 Mon Sep 17 00:00:00 2001 From: Vladislav Perevezentsev Date: Fri, 10 Apr 2026 10:27:29 -0700 Subject: [PATCH 17/46] Update _reshape.py doc to Sphinx format --- dpnp/tensor/_reshape.py | 43 +++++++++++++++++++++++------------------ 1 file changed, 24 insertions(+), 19 deletions(-) diff --git a/dpnp/tensor/_reshape.py b/dpnp/tensor/_reshape.py index 0187ae49600..d6043dc3626 100644 --- a/dpnp/tensor/_reshape.py +++ b/dpnp/tensor/_reshape.py @@ -39,7 +39,7 @@ _unravel_index, ) -__doc__ = "Implementation module for :func:`dpctl.tensor.reshape`." +__doc__ = "Implementation module for :func:`dpnp.tensor.reshape`." def _make_unit_indexes(shape): @@ -102,27 +102,32 @@ def reshaped_strides(old_sh, old_sts, new_sh, order="C"): def reshape(X, /, shape, *, order="C", copy=None): - """reshape(x, shape, order="C") - + """ Reshapes array ``x`` into new shape. - Args: - x (usm_ndarray): - input array - shape (Tuple[int]): - the desired shape of the resulting array. - order ("C", "F", optional): - memory layout of the resulting array - if a copy is found to be necessary. Supported - choices are ``"C"`` for C-contiguous, or row-major layout; - and ``"F"`` for F-contiguous, or column-major layout. - - Returns: - usm_ndarray: - Reshaped array is a view, if possible, - and a copy otherwise with memory layout as indicated - by ``order`` keyword. + Parameters + ---------- + x : usm_ndarray + Input array. + shape : tuple of ints + The desired shape of the resulting array. + order : {"C", "F"}, optional + Memory layout of the resulting array + if a copy is found to be necessary. Supported + choices are ``"C"`` for C-contiguous, or row-major layout; + and ``"F"`` for F-contiguous, or column-major layout. + + Default: ``"C"``. + + Returns + ------- + out : usm_ndarray + Reshaped array is a view, if possible, + and a copy otherwise with memory layout as indicated + by ``order`` keyword. + """ + if not isinstance(X, dpt.usm_ndarray): raise TypeError if not isinstance(shape, (list, tuple)): From 022c8d06b1d95349f15215872ee3b16974cb2961 Mon Sep 17 00:00:00 2001 From: Vladislav Perevezentsev Date: Fri, 10 Apr 2026 10:29:16 -0700 Subject: [PATCH 18/46] Update _search_functions.py doc to Sphinx format --- dpnp/tensor/_search_functions.py | 65 ++++++++++++++++++-------------- 1 file changed, 36 insertions(+), 29 deletions(-) diff --git a/dpnp/tensor/_search_functions.py b/dpnp/tensor/_search_functions.py index c1d45ee4bb3..be5c495f6df 100644 --- a/dpnp/tensor/_search_functions.py +++ b/dpnp/tensor/_search_functions.py @@ -125,41 +125,48 @@ def _where_result_type(dt1, dt2, dev): def where(condition, x1, x2, /, *, order="K", out=None): """ - Returns :class:`dpctl.tensor.usm_ndarray` with elements chosen + Returns :class:`dpnp.tensor.usm_ndarray` with elements chosen from ``x1`` or ``x2`` depending on ``condition``. - Args: - condition (usm_ndarray): When ``True`` yields from ``x1``, - and otherwise yields from ``x2``. - Must be compatible with ``x1`` and ``x2`` according - to broadcasting rules. - x1 (Union[usm_ndarray, bool, int, float, complex]): - Array from which values are chosen when ``condition`` is ``True``. - Must be compatible with ``condition`` and ``x2`` according - to broadcasting rules. - x2 (Union[usm_ndarray, bool, int, float, complex]): - Array from which values are chosen when ``condition`` is not - ``True``. - Must be compatible with ``condition`` and ``x2`` according - to broadcasting rules. - order (``"K"``, ``"C"``, ``"F"``, ``"A"``, optional): - Memory layout of the new output array, - if parameter ``out`` is ``None``. - Default: ``"K"``. - out (Optional[usm_ndarray]): - the array into which the result is written. - The data type of `out` must match the expected shape and the - expected data type of the result. - If ``None`` then a new array is returned. Default: ``None``. - - Returns: - usm_ndarray: - An array with elements from ``x1`` where ``condition`` is ``True``, - and elements from ``x2`` elsewhere. + Parameters + ---------- + condition : usm_ndarray + When ``True`` yields from ``x1``, and otherwise yields from ``x2``. + Must be compatible with ``x1`` and ``x2`` according + to broadcasting rules. + x1 : {usm_ndarray, bool, int, float, complex} + Array from which values are chosen when ``condition`` is ``True``. + Must be compatible with ``condition`` and ``x2`` according + to broadcasting rules. + x2 : {usm_ndarray, bool, int, float, complex} + Array from which values are chosen when ``condition`` is not + ``True``. + Must be compatible with ``condition`` and ``x1`` according + to broadcasting rules. + order : {"K", "C", "F", "A"}, optional + Memory layout of the new output array, + if parameter ``out`` is ``None``. + + Default: ``"K"``. + out : {None, usm_ndarray}, optional + The array into which the result is written. + The data type of ``out`` must match the expected shape and the + expected data type of the result. + If ``None`` then a new array is returned. + + Default: ``None``. + + Returns + ------- + out : usm_ndarray + An array with elements from ``x1`` where ``condition`` is ``True``, + and elements from ``x2`` elsewhere. The data type of the returned array is determined by applying the Type Promotion Rules to ``x1`` and ``x2``. + """ + if not isinstance(condition, dpt.usm_ndarray): raise TypeError( "Expecting dpnp.tensor.usm_ndarray type, " f"got {type(condition)}" From 6692c3a77352e3e89c3c493df9888493027b1eac Mon Sep 17 00:00:00 2001 From: Vladislav Perevezentsev Date: Fri, 10 Apr 2026 10:30:58 -0700 Subject: [PATCH 19/46] Update _searchsorted.py doc to Sphinx format --- dpnp/tensor/_searchsorted.py | 62 +++++++++++++++++++++--------------- 1 file changed, 36 insertions(+), 26 deletions(-) diff --git a/dpnp/tensor/_searchsorted.py b/dpnp/tensor/_searchsorted.py index 5776e908ec6..ac982eb6e4b 100644 --- a/dpnp/tensor/_searchsorted.py +++ b/dpnp/tensor/_searchsorted.py @@ -62,37 +62,47 @@ def searchsorted( side: Literal["left", "right"] = "left", sorter: usm_ndarray | None = None, ) -> usm_ndarray: - """searchsorted(x1, x2, side='left', sorter=None) - + """ Finds the indices into `x1` such that, if the corresponding elements in `x2` were inserted before the indices, the order of `x1`, when sorted in ascending order, would be preserved. - Args: - x1 (usm_ndarray): - input array. Must be a one-dimensional array. If `sorter` is - `None`, must be sorted in ascending order; otherwise, `sorter` must - be an array of indices that sort `x1` in ascending order. - x2 (usm_ndarray | int | float | complex | bool): - search value or values. - side (Literal["left", "right]): - argument controlling which index is returned if a value lands - exactly on an edge. If `x2` is an array of rank `N` where - `v = x2[n, m, ..., j]`, the element `ret[n, m, ..., j]` in the - return array `ret` contains the position `i` such that - if `side="left"`, it is the first index such that - `x1[i-1] < v <= x1[i]`, `0` if `v <= x1[0]`, and `x1.size` - if `v > x1[-1]`; - and if `side="right"`, it is the first position `i` such that - `x1[i-1] <= v < x1[i]`, `0` if `v < x1[0]`, and `x1.size` - if `v >= x1[-1]`. Default: `"left"`. - sorter (Optional[usm_ndarray]): - array of indices that sort `x1` in ascending order. The array must - have the same shape as `x1` and have an integral data type. - Out of bound index values of `sorter` array are treated using - `"wrap"` mode documented in :py:func:`dpnp.tensor.take`. - Default: `None`. + Parameters + ---------- + x1 : usm_ndarray + Input array. Must be a one-dimensional array. If `sorter` is + `None`, must be sorted in ascending order; otherwise, `sorter` must + be an array of indices that sort `x1` in ascending order. + x2 : {usm_ndarray, int, float, complex, bool} + Search value or values. + side : {"left", "right"}, optional + Argument controlling which index is returned if a value lands + exactly on an edge. If `x2` is an array of rank `N` where + `v = x2[n, m, ..., j]`, the element `ret[n, m, ..., j]` in the + return array `ret` contains the position `i` such that + if `side="left"`, it is the first index such that + `x1[i-1] < v <= x1[i]`, `0` if `v <= x1[0]`, and `x1.size` + if `v > x1[-1]`; + and if `side="right"`, it is the first position `i` such that + `x1[i-1] <= v < x1[i]`, `0` if `v < x1[0]`, and `x1.size` + if `v >= x1[-1]`. + + Default: ``"left"``. + sorter : {None, usm_ndarray}, optional + Array of indices that sort `x1` in ascending order. The array must + have the same shape as `x1` and have an integral data type. + Out of bound index values of `sorter` array are treated using + `"wrap"` mode documented in :py:func:`dpnp.tensor.take`. + + Default: ``None``. + + Returns + ------- + out : usm_ndarray + An array of indices with the same shape as `x2`. + """ + if not isinstance(x1, usm_ndarray): raise TypeError(f"Expected dpnp.tensor.usm_ndarray, got {type(x1)}") if sorter is not None and not isinstance(sorter, usm_ndarray): From 7517dedf552c25e05535d9cc890b564d32a08aa4 Mon Sep 17 00:00:00 2001 From: Vladislav Perevezentsev Date: Fri, 10 Apr 2026 10:34:59 -0700 Subject: [PATCH 20/46] Update _set_functions.py doc to Sphinx format --- dpnp/tensor/_set_functions.py | 179 ++++++++++++++++++---------------- 1 file changed, 97 insertions(+), 82 deletions(-) diff --git a/dpnp/tensor/_set_functions.py b/dpnp/tensor/_set_functions.py index e2e5851f131..9228a3b8b95 100644 --- a/dpnp/tensor/_set_functions.py +++ b/dpnp/tensor/_set_functions.py @@ -90,17 +90,20 @@ class UniqueInverseResult(NamedTuple): def unique_values(x: dpt.usm_ndarray) -> dpt.usm_ndarray: - """unique_values(x) - + """ Returns the unique elements of an input array `x`. - Args: - x (usm_ndarray): - input array. Inputs with more than one dimension are flattened. - Returns: - usm_ndarray - an array containing the set of unique elements in `x`. The - returned array has the same data type as `x`. + Parameters + ---------- + x : usm_ndarray + Input array. Inputs with more than one dimension are flattened. + + Returns + ------- + out : usm_ndarray + An array containing the set of unique elements in `x`. The + returned array has the same data type as `x`. + """ if not isinstance(x, dpt.usm_ndarray): raise TypeError(f"Expected dpnp.tensor.usm_ndarray, got {type(x)}") @@ -175,25 +178,28 @@ def unique_values(x: dpt.usm_ndarray) -> dpt.usm_ndarray: def unique_counts(x: dpt.usm_ndarray) -> UniqueCountsResult: - """unique_counts(x) - + """ Returns the unique elements of an input array `x` and the corresponding counts for each unique element in `x`. - Args: - x (usm_ndarray): - input array. Inputs with more than one dimension are flattened. - Returns: - tuple[usm_ndarray, usm_ndarray] - a namedtuple `(values, counts)` whose - - * first element is the field name `values` and is an array - containing the unique elements of `x`. This array has the - same data type as `x`. - * second element has the field name `counts` and is an array - containing the number of times each unique element occurs in `x`. - This array has the same shape as `values` and has the default - array index data type. + Parameters + ---------- + x : usm_ndarray + Input array. Inputs with more than one dimension are flattened. + + Returns + ------- + out : tuple of usm_ndarrays + A namedtuple `(values, counts)` whose + + * first element is the field name `values` and is an array + containing the unique elements of `x`. This array has the + same data type as `x`. + * second element has the field name `counts` and is an array + containing the number of times each unique element occurs in `x`. + This array has the same shape as `values` and has the default + array index data type. + """ if not isinstance(x, dpt.usm_ndarray): raise TypeError(f"Expected dpnp.tensor.usm_ndarray, got {type(x)}") @@ -308,25 +314,28 @@ def unique_counts(x: dpt.usm_ndarray) -> UniqueCountsResult: def unique_inverse(x): - """unique_inverse - - Returns the unique elements of an input array x and the indices from the + """ + Returns the unique elements of an input array `x` and the indices from the set of unique elements that reconstruct `x`. - Args: - x (usm_ndarray): - input array. Inputs with more than one dimension are flattened. - Returns: - tuple[usm_ndarray, usm_ndarray] - a namedtuple `(values, inverse_indices)` whose - - * first element has the field name `values` and is an array - containing the unique elements of `x`. The array has the same - data type as `x`. - * second element has the field name `inverse_indices` and is an - array containing the indices of values that reconstruct `x`. - The array has the same shape as `x` and has the default array - index data type. + Parameters + ---------- + x : usm_ndarray + Input array. Inputs with more than one dimension are flattened. + + Returns + ------- + out : tuple of usm_ndarrays + A namedtuple `(values, inverse_indices)` whose + + * first element has the field name `values` and is an array + containing the unique elements of `x`. The array has the same + data type as `x`. + * second element has the field name `inverse_indices` and is an + array containing the indices of values that reconstruct `x`. + The array has the same shape as `x` and has the default array + index data type. + """ if not isinstance(x, dpt.usm_ndarray): raise TypeError(f"Expected dpnp.tensor.usm_ndarray, got {type(x)}") @@ -468,35 +477,38 @@ def unique_inverse(x): def unique_all(x: dpt.usm_ndarray) -> UniqueAllResult: - """unique_all(x) - + """ Returns the unique elements of an input array `x`, the first occurring indices for each unique element in `x`, the indices from the set of unique elements that reconstruct `x`, and the corresponding counts for each unique element in `x`. - Args: - x (usm_ndarray): - input array. Inputs with more than one dimension are flattened. - Returns: - tuple[usm_ndarray, usm_ndarray, usm_ndarray, usm_ndarray] - a namedtuple `(values, indices, inverse_indices, counts)` whose - - * first element has the field name `values` and is an array - containing the unique elements of `x`. The array has the same - data type as `x`. - * second element has the field name `indices` and is an array - the indices (of first occurrences) of `x` that result in - `values`. The array has the same shape as `values` and has the - default array index data type. - * third element has the field name `inverse_indices` and is an - array containing the indices of values that reconstruct `x`. - The array has the same shape as `x` and has the default array - index data type. - * fourth element has the field name `counts` and is an array - containing the number of times each unique element occurs in `x`. - This array has the same shape as `values` and has the default - array index data type. + Parameters + ---------- + x : usm_ndarray + Input array. Inputs with more than one dimension are flattened. + + Returns + ------- + out : tuple of usm_ndarrays + A namedtuple `(values, indices, inverse_indices, counts)` whose + + * first element has the field name `values` and is an array + containing the unique elements of `x`. The array has the same + data type as `x`. + * second element has the field name `indices` and is an array + the indices (of first occurrences) of `x` that result in + `values`. The array has the same shape as `values` and has the + default array index data type. + * third element has the field name `inverse_indices` and is an + array containing the indices of values that reconstruct `x`. + The array has the same shape as `x` and has the default array + index data type. + * fourth element has the field name `counts` and is an array + containing the number of times each unique element occurs in `x`. + This array has the same shape as `values` and has the default + array index data type. + """ if not isinstance(x, dpt.usm_ndarray): raise TypeError(f"Expected dpnp.tensor.usm_ndarray, got {type(x)}") @@ -661,26 +673,29 @@ def isin( *, invert: Optional[bool] = False, ) -> dpt.usm_ndarray: - """isin(x, test_elements, /, *, invert=False) - + """ Tests `x in test_elements` for each element of `x`. Returns a boolean array with the same shape as `x` that is `True` where the element is in `test_elements`, `False` otherwise. - Args: - x (Union[usm_ndarray, bool, int, float, complex]): - input element or elements. - test_elements (Union[usm_ndarray, bool, int, float, complex]): - elements against which to test each value of `x`. - invert (Optional[bool]): - if `True`, the output results are inverted, i.e., are equivalent to - testing `x not in test_elements` for each element of `x`. - Default: `False`. - - Returns: - usm_ndarray: - an array of the inclusion test results. The returned array has a - boolean data type and the same shape as `x`. + Parameters + ---------- + x : {usm_ndarray, bool, int, float, complex} + Input element or elements. + test_elements : {usm_ndarray, bool, int, float, complex} + Elements against which to test each value of `x`. + invert : bool, optional + If `True`, the output results are inverted, i.e., are equivalent to + testing `x not in test_elements` for each element of `x`. + + Default: ``False``. + + Returns + ------- + out : usm_ndarray + An array of the inclusion test results. The returned array has a + boolean data type and the same shape as `x`. + """ q1, x_usm_type = _get_queue_usm_type(x) q2, test_usm_type = _get_queue_usm_type(test_elements) From 59373f7e8dcc2144ac1df62ec753613ca326dfd7 Mon Sep 17 00:00:00 2001 From: Vladislav Perevezentsev Date: Fri, 10 Apr 2026 10:36:32 -0700 Subject: [PATCH 21/46] Update _slicing.pxi doc to Sphinx format --- dpnp/tensor/_set_functions.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/dpnp/tensor/_set_functions.py b/dpnp/tensor/_set_functions.py index 9228a3b8b95..80b83ecda70 100644 --- a/dpnp/tensor/_set_functions.py +++ b/dpnp/tensor/_set_functions.py @@ -105,6 +105,7 @@ def unique_values(x: dpt.usm_ndarray) -> dpt.usm_ndarray: returned array has the same data type as `x`. """ + if not isinstance(x, dpt.usm_ndarray): raise TypeError(f"Expected dpnp.tensor.usm_ndarray, got {type(x)}") array_api_dev = x.device @@ -201,6 +202,7 @@ def unique_counts(x: dpt.usm_ndarray) -> UniqueCountsResult: array index data type. """ + if not isinstance(x, dpt.usm_ndarray): raise TypeError(f"Expected dpnp.tensor.usm_ndarray, got {type(x)}") array_api_dev = x.device @@ -337,6 +339,7 @@ def unique_inverse(x): index data type. """ + if not isinstance(x, dpt.usm_ndarray): raise TypeError(f"Expected dpnp.tensor.usm_ndarray, got {type(x)}") array_api_dev = x.device @@ -510,6 +513,7 @@ def unique_all(x: dpt.usm_ndarray) -> UniqueAllResult: array index data type. """ + if not isinstance(x, dpt.usm_ndarray): raise TypeError(f"Expected dpnp.tensor.usm_ndarray, got {type(x)}") array_api_dev = x.device @@ -697,6 +701,7 @@ def isin( boolean data type and the same shape as `x`. """ + q1, x_usm_type = _get_queue_usm_type(x) q2, test_usm_type = _get_queue_usm_type(test_elements) if q1 is None and q2 is None: From 664e6c1cefbb1dfb344dfcf20a876a3edb898809 Mon Sep 17 00:00:00 2001 From: Vladislav Perevezentsev Date: Fri, 10 Apr 2026 10:38:20 -0700 Subject: [PATCH 22/46] Update _sorting.py doc to Sphinx format --- dpnp/tensor/_sorting.py | 192 +++++++++++++++++++++++----------------- 1 file changed, 110 insertions(+), 82 deletions(-) diff --git a/dpnp/tensor/_sorting.py b/dpnp/tensor/_sorting.py index c912b4f77cd..564c3dd66db 100644 --- a/dpnp/tensor/_sorting.py +++ b/dpnp/tensor/_sorting.py @@ -60,34 +60,46 @@ def _get_radixsort_impl_fn(descending): def sort(x, /, *, axis=-1, descending=False, stable=True, kind=None): - """sort(x, axis=-1, descending=False, stable=True) - + """ Returns a sorted copy of an input array `x`. - Args: - x (usm_ndarray): - input array. - axis (Optional[int]): - axis along which to sort. If set to `-1`, the function - must sort along the last axis. Default: `-1`. - descending (Optional[bool]): - sort order. If `True`, the array must be sorted in descending - order (by value). If `False`, the array must be sorted in - ascending order (by value). Default: `False`. - stable (Optional[bool]): - sort stability. If `True`, the returned array must maintain the - relative order of `x` values which compare as equal. If `False`, - the returned array may or may not maintain the relative order of - `x` values which compare as equal. Default: `True`. - kind (Optional[Literal["stable", "mergesort", "radixsort"]]): - Sorting algorithm. The default is `"stable"`, which uses parallel - merge-sort or parallel radix-sort algorithms depending on the - array data type. - Returns: - usm_ndarray: - a sorted array. The returned array has the same data type and - the same shape as the input array `x`. + Parameters + ---------- + x : usm_ndarray + Input array. + axis : int, optional + Axis along which to sort. If set to `-1`, the function + must sort along the last axis. + + Default: ``-1``. + descending : bool, optional + Sort order. If `True`, the array must be sorted in descending + order (by value). If `False`, the array must be sorted in + ascending order (by value). + + Default: ``False``. + stable : bool, optional + Sort stability. If `True`, the returned array must maintain the + relative order of `x` values which compare as equal. If `False`, + the returned array may or may not maintain the relative order of + `x` values which compare as equal. + + Default: ``True``. + kind : {"stable", "mergesort", "radixsort"}, optional + Sorting algorithm. The default is `"stable"`, which uses parallel + merge-sort or parallel radix-sort algorithms depending on the + array data type. + + Default: ``None``. + + Returns + ------- + out : usm_ndarray + A sorted array. The returned array has the same data type and + the same shape as the input array `x`. + """ + if not isinstance(x, dpt.usm_ndarray): raise TypeError(f"Expected type dpnp.tensor.usm_ndarray, got {type(x)}") nd = x.ndim @@ -172,36 +184,47 @@ def _get_radixargsort_impl_fn(descending): def argsort(x, axis=-1, descending=False, stable=True, kind=None): - """argsort(x, axis=-1, descending=False, stable=True) - + """ Returns the indices that sort an array `x` along a specified axis. - Args: - x (usm_ndarray): - input array. - axis (Optional[int]): - axis along which to sort. If set to `-1`, the function - must sort along the last axis. Default: `-1`. - descending (Optional[bool]): - sort order. If `True`, the array must be sorted in descending - order (by value). If `False`, the array must be sorted in - ascending order (by value). Default: `False`. - stable (Optional[bool]): - sort stability. If `True`, the returned array must maintain the - relative order of `x` values which compare as equal. If `False`, - the returned array may or may not maintain the relative order of - `x` values which compare as equal. Default: `True`. - kind (Optional[Literal["stable", "mergesort", "radixsort"]]): - Sorting algorithm. The default is `"stable"`, which uses parallel - merge-sort or parallel radix-sort algorithms depending on the - array data type. - - Returns: - usm_ndarray: - an array of indices. The returned array has the same shape as - the input array `x`. The return array has default array index - data type. + Parameters + ---------- + x : usm_ndarray + Input array. + axis : int, optional + Axis along which to sort. If set to `-1`, the function + must sort along the last axis. + + Default: ``-1``. + descending : bool, optional + Sort order. If `True`, the array must be sorted in descending + order (by value). If `False`, the array must be sorted in + ascending order (by value). + + Default: ``False``. + stable : bool, optional + Sort stability. If `True`, the returned array must maintain the + relative order of `x` values which compare as equal. If `False`, + the returned array may or may not maintain the relative order of + `x` values which compare as equal. + + Default: ``True``. + kind : {"stable", "mergesort", "radixsort"}, optional + Sorting algorithm. The default is `"stable"`, which uses parallel + merge-sort or parallel radix-sort algorithms depending on the + array data type. + + Default: ``None``. + + Returns + ------- + out : usm_ndarray + An array of indices. The returned array has the same shape as + the input array `x`. The return array has default array index + data type. + """ + if not isinstance(x, dpt.usm_ndarray): raise TypeError(f"Expected type dpnp.tensor.usm_ndarray, got {type(x)}") nd = x.ndim @@ -296,40 +319,45 @@ class TopKResult(NamedTuple): def top_k(x, k, /, *, axis=None, mode="largest"): - """top_k(x, k, axis=None, mode="largest") - + """ Returns the `k` largest or smallest values and their indices in the input array `x` along the specified axis `axis`. - Args: - x (usm_ndarray): - input array. - k (int): - number of elements to find. Must be a positive integer value. - axis (Optional[int]): - axis along which to search. If `None`, the search will be performed - over the flattened array. Default: ``None``. - mode (Literal["largest", "smallest"]): - search mode. Must be one of the following modes: - - - `"largest"`: return the `k` largest elements. - - `"smallest"`: return the `k` smallest elements. - - Default: `"largest"`. - - Returns: - tuple[usm_ndarray, usm_ndarray] - a namedtuple `(values, indices)` whose - - * first element `values` will be an array containing the `k` - largest or smallest elements of `x`. The array has the same data - type as `x`. If `axis` was `None`, `values` will be a - one-dimensional array with shape `(k,)` and otherwise, `values` - will have shape `x.shape[:axis] + (k,) + x.shape[axis+1:]` - * second element `indices` will be an array containing indices of - `x` that result in `values`. The array will have the same shape - as `values` and will have the default array index data type. + Parameters + ---------- + x : usm_ndarray + Input array. + k : int + Number of elements to find. Must be a positive integer value. + axis : int, optional + Axis along which to search. If `None`, the search will be performed + over the flattened array. + + Default: ``None``. + mode : {"largest", "smallest"}, optional + Search mode. Must be one of the following modes: + + - `"largest"`: return the `k` largest elements. + - `"smallest"`: return the `k` smallest elements. + + Default: ``"largest"``. + + Returns + ------- + out : tuple of usm_ndarrays + A namedtuple `(values, indices)` whose + + * first element `values` will be an array containing the `k` + largest or smallest elements of `x`. The array has the same data + type as `x`. If `axis` was `None`, `values` will be a + one-dimensional array with shape `(k,)` and otherwise, `values` + will have shape `x.shape[:axis] + (k,) + x.shape[axis+1:]` + * second element `indices` will be an array containing indices of + `x` that result in `values`. The array will have the same shape + as `values` and will have the default array index data type. + """ + largest = _get_top_k_largest(mode) if not isinstance(x, dpt.usm_ndarray): raise TypeError(f"Expected type dpnp.tensor.usm_ndarray, got {type(x)}") From 39bf99c89798f15e1c364710aeebd8fdd07fadca Mon Sep 17 00:00:00 2001 From: Vladislav Perevezentsev Date: Fri, 10 Apr 2026 10:39:51 -0700 Subject: [PATCH 23/46] Update _statistical_functions.py doc to Sphinx format --- dpnp/tensor/_statistical_functions.py | 203 +++++++++++++++----------- 1 file changed, 114 insertions(+), 89 deletions(-) diff --git a/dpnp/tensor/_statistical_functions.py b/dpnp/tensor/_statistical_functions.py index a2015488aff..ac721fb1e4b 100644 --- a/dpnp/tensor/_statistical_functions.py +++ b/dpnp/tensor/_statistical_functions.py @@ -164,35 +164,42 @@ def _var_impl(x, axis, correction, keepdims): def mean(x, axis=None, keepdims=False): - """mean(x, axis=None, keepdims=False) - + """ Calculates the arithmetic mean of elements in the input array `x`. - Args: - x (usm_ndarray): - input array. - axis (Optional[int, Tuple[int, ...]]): - axis or axes along which the arithmetic means must be computed. If - a tuple of unique integers, the means are computed over multiple - axes. If `None`, the mean is computed over the entire array. - Default: `None`. - keepdims (Optional[bool]): - if `True`, the reduced axes (dimensions) are included in the result - as singleton dimensions, so that the returned array remains - compatible with the input array according to Array Broadcasting - rules. Otherwise, if `False`, the reduced axes are not included in - the returned array. Default: `False`. - Returns: - usm_ndarray: - an array containing the arithmetic means. If the mean was computed - over the entire array, a zero-dimensional array is returned. - - If `x` has a floating-point data type, the returned array will have - the same data type as `x`. - If `x` has a boolean or integral data type, the returned array - will have the default floating point data type for the device - where input array `x` is allocated. + Parameters + ---------- + x : usm_ndarray + Input array. + axis : {None, int, tuple of ints}, optional + Axis or axes along which the arithmetic means must be computed. If + a tuple of unique integers, the means are computed over multiple + axes. If `None`, the mean is computed over the entire array. + + Default: ``None``. + keepdims : bool, optional + If `True`, the reduced axes (dimensions) are included in the result + as singleton dimensions, so that the returned array remains + compatible with the input array according to Array Broadcasting + rules. Otherwise, if `False`, the reduced axes are not included in + the returned array. + + Default: ``False``. + + Returns + ------- + out : usm_ndarray + An array containing the arithmetic means. If the mean was computed + over the entire array, a zero-dimensional array is returned. + + If `x` has a floating-point data type, the returned array will have + the same data type as `x`. + If `x` has a boolean or integral data type, the returned array + will have the default floating point data type for the device + where input array `x` is allocated. + """ + if not isinstance(x, dpt.usm_ndarray): raise TypeError(f"Expected dpnp.tensor.usm_ndarray, got {type(x)}") nd = x.ndim @@ -271,40 +278,48 @@ def mean(x, axis=None, keepdims=False): def var(x, axis=None, correction=0.0, keepdims=False): - """var(x, axis=None, correction=0.0, keepdims=False) - + """ Calculates the variance of elements in the input array `x`. - Args: - x (usm_ndarray): - input array. - axis (Optional[int, Tuple[int, ...]]): - axis or axes along which the variances must be computed. If a tuple - of unique integers, the variances are computed over multiple axes. - If `None`, the variance is computed over the entire array. - Default: `None`. - correction (Optional[float, int]): - degrees of freedom adjustment. The divisor used in calculating the - variance is `N - correction`, where `N` corresponds to the total - number of elements over which the variance is calculated. - Default: `0.0`. - keepdims (Optional[bool]): - if `True`, the reduced axes (dimensions) are included in the result - as singleton dimensions, so that the returned array remains - compatible with the input array according to Array Broadcasting - rules. Otherwise, if `False`, the reduced axes are not included in - the returned array. Default: `False`. - Returns: - usm_ndarray: - an array containing the variances. If the variance was computed - over the entire array, a zero-dimensional array is returned. - - If `x` has a real-valued floating-point data type, the returned - array will have the same data type as `x`. - If `x` has a boolean or integral data type, the returned array - will have the default floating point data type for the device - where input array `x` is allocated. + Parameters + ---------- + x : usm_ndarray + Input array. + axis : {None, int, tuple of ints}, optional + Axis or axes along which the variances must be computed. If a tuple + of unique integers, the variances are computed over multiple axes. + If `None`, the variance is computed over the entire array. + + Default: ``None``. + correction : {float, int}, optional + Degrees of freedom adjustment. The divisor used in calculating the + variance is `N - correction`, where `N` corresponds to the total + number of elements over which the variance is calculated. + + Default: ``0.0``. + keepdims : bool, optional + If `True`, the reduced axes (dimensions) are included in the result + as singleton dimensions, so that the returned array remains + compatible with the input array according to Array Broadcasting + rules. Otherwise, if `False`, the reduced axes are not included in + the returned array. + + Default: ``False``. + + Returns + ------- + out : usm_ndarray + An array containing the variances. If the variance was computed + over the entire array, a zero-dimensional array is returned. + + If `x` has a real-valued floating-point data type, the returned + array will have the same data type as `x`. + If `x` has a boolean or integral data type, the returned array + will have the default floating point data type for the device + where input array `x` is allocated. + """ + if not isinstance(x, dpt.usm_ndarray): raise TypeError(f"Expected dpnp.tensor.usm_ndarray, got {type(x)}") @@ -322,41 +337,51 @@ def var(x, axis=None, correction=0.0, keepdims=False): def std(x, axis=None, correction=0.0, keepdims=False): - """std(x, axis=None, correction=0.0, keepdims=False) - + """ Calculates the standard deviation of elements in the input array `x`. - Args: - x (usm_ndarray): - input array. - axis (Optional[int, Tuple[int, ...]]): - axis or axes along which the standard deviations must be computed. - If a tuple of unique integers, the standard deviations are computed - over multiple axes. If `None`, the standard deviation is computed - over the entire array. Default: `None`. - correction (Optional[float, int]): - degrees of freedom adjustment. The divisor used in calculating the - standard deviation is `N - correction`, where `N` corresponds to the - total number of elements over which the standard deviation is - calculated. Default: `0.0`. - keepdims (Optional[bool]): - if `True`, the reduced axes (dimensions) are included in the result - as singleton dimensions, so that the returned array remains - compatible with the input array according to Array Broadcasting - rules. Otherwise, if `False`, the reduced axes are not included in - the returned array. Default: `False`. - Returns: - usm_ndarray: - an array containing the standard deviations. If the standard - deviation was computed over the entire array, a zero-dimensional - array is returned. - - If `x` has a real-valued floating-point data type, the returned - array will have the same data type as `x`. - If `x` has a boolean or integral data type, the returned array - will have the default floating point data type for the device - where input array `x` is allocated. + Parameters + ---------- + x : usm_ndarray + Input array. + axis : {None, int, tuple of ints}, optional + Axis or axes along which the standard deviations must be computed. + If a tuple of unique integers, the standard deviations are computed + over multiple axes. If `None`, the standard deviation is computed + over the entire array. + + Default: ``None``. + correction : {float, int}, optional + Degrees of freedom adjustment. The divisor used in calculating the + standard deviation is `N - correction`, where `N` corresponds to the + total number of elements over which the standard deviation is + calculated. + + Default: ``0.0``. + keepdims : bool, optional + If `True`, the reduced axes (dimensions) are included in the result + as singleton dimensions, so that the returned array remains + compatible with the input array according to Array Broadcasting + rules. Otherwise, if `False`, the reduced axes are not included in + the returned array. + + Default: ``False``. + + Returns + ------- + out : usm_ndarray + An array containing the standard deviations. If the standard + deviation was computed over the entire array, a zero-dimensional + array is returned. + + If `x` has a real-valued floating-point data type, the returned + array will have the same data type as `x`. + If `x` has a boolean or integral data type, the returned array + will have the default floating point data type for the device + where input array `x` is allocated. + """ + if not isinstance(x, dpt.usm_ndarray): raise TypeError(f"Expected dpnp.tensor.usm_ndarray, got {type(x)}") From 8eaed32753f51fc3ec1a562d98895d3731a335bf Mon Sep 17 00:00:00 2001 From: Vladislav Perevezentsev Date: Fri, 10 Apr 2026 10:41:12 -0700 Subject: [PATCH 24/46] Update _testing.py doc to Sphinx format --- dpnp/tensor/_testing.py | 29 +++++++++++++++++++++++++++-- 1 file changed, 27 insertions(+), 2 deletions(-) diff --git a/dpnp/tensor/_testing.py b/dpnp/tensor/_testing.py index fbec13fdeb3..ac8c9cba3a2 100644 --- a/dpnp/tensor/_testing.py +++ b/dpnp/tensor/_testing.py @@ -111,14 +111,39 @@ def _allclose_others(r1, r2): def allclose(a1, a2, atol=1e-8, rtol=1e-5, equal_nan=False): - """allclose(a1, a2, atol=1e-8, rtol=1e-5, equal_nan=False) - + """ Returns True if two arrays are element-wise equal within tolerances. The testing is based on the following elementwise comparison: abs(a - b) <= max(atol, rtol * max(abs(a), abs(b))) + + Parameters + ---------- + a1 : usm_ndarray + First input array. + a2 : usm_ndarray + Second input array. + atol : float, optional + Absolute tolerance. + + Default: ``1e-8``. + rtol : float, optional + Relative tolerance. + + Default: ``1e-5``. + equal_nan : bool, optional + Whether to compare NaN's as equal. + + Default: ``False``. + + Returns + ------- + out : bool + True if the two arrays are equal within the given tolerances. + """ + if not isinstance(a1, dpt.usm_ndarray): raise TypeError( f"Expected dpnp.tensor.usm_ndarray type, got {type(a1)}." From 95f2a57a5bc8acf8a36db028ea6c116433abb741 Mon Sep 17 00:00:00 2001 From: Vladislav Perevezentsev Date: Fri, 10 Apr 2026 10:43:44 -0700 Subject: [PATCH 25/46] Update _type_util.py doc to Sphinx format --- dpnp/tensor/_type_utils.py | 190 +++++++++++++++++++++---------------- 1 file changed, 106 insertions(+), 84 deletions(-) diff --git a/dpnp/tensor/_type_utils.py b/dpnp/tensor/_type_utils.py index b03ca1e1c79..d45aacfa30d 100644 --- a/dpnp/tensor/_type_utils.py +++ b/dpnp/tensor/_type_utils.py @@ -679,37 +679,40 @@ def __repr__(self): def can_cast(from_, to, /, *, casting="safe") -> bool: - """can_cast(from, to, casting="safe") - - Determines if one data type can be cast to another data type according \ + """ + Determines if one data type can be cast to another data type according to Type Promotion Rules. - Args: - from_ (Union[usm_ndarray, dtype]): - source data type. If `from_` is an array, a device-specific type - promotion rules apply. - to (dtype): - target data type - casting (Optional[str]): - controls what kind of data casting may occur. - - * "no" means data types should not be cast at all. - * "safe" means only casts that preserve values are allowed. - * "same_kind" means only safe casts and casts within a kind, - like `float64` to `float32`, are allowed. - * "unsafe" means any data conversion can be done. - - Default: `"safe"`. - - Returns: - bool: - Gives `True` if cast can occur according to the casting rule. + Parameters + ---------- + from_ : {usm_ndarray, dtype} + Source data type. If `from_` is an array, device-specific type + promotion rules apply. + to : dtype + Target data type. + casting : str, optional + Controls what kind of data casting may occur. + + * "no" means data types should not be cast at all. + * "safe" means only casts that preserve values are allowed. + * "same_kind" means only safe casts and casts within a kind, + like `float64` to `float32`, are allowed. + * "unsafe" means any data conversion can be done. + + Default: ``"safe"``. + + Returns + ------- + out : bool + Gives `True` if cast can occur according to the casting rule. Device-specific type promotion rules take into account which data type are and are not supported by a specific device. + """ + if isinstance(to, dpt.usm_ndarray): - raise TypeError(f"Expected `dpt.dtype` type, got {type(to)}.") + raise TypeError(f"Expected `dpnp.tensor.dtype` type, got {type(to)}.") dtype_to = dpt.dtype(to) _supported_dtype([dtype_to]) @@ -732,20 +735,22 @@ def can_cast(from_, to, /, *, casting="safe") -> bool: def result_type(*arrays_and_dtypes): """ - result_type(*arrays_and_dtypes) + Returns the dtype that results from applying the Type Promotion Rules to + the arguments. - Returns the dtype that results from applying the Type Promotion Rules to \ - the arguments. + Parameters + ---------- + arrays_and_dtypes : {usm_ndarray, dtype} + An arbitrary length sequence of usm_ndarray objects or dtypes. - Args: - arrays_and_dtypes (Union[usm_ndarray, dtype]): - An arbitrary length sequence of usm_ndarray objects or dtypes. + Returns + ------- + out : dtype + The dtype resulting from an operation involving the + input arrays and dtypes. - Returns: - dtype: - The dtype resulting from an operation involving the - input arrays and dtypes. """ + dtypes = [] devices = [] weak_dtypes = [] @@ -814,28 +819,30 @@ def result_type(*arrays_and_dtypes): def iinfo(dtype, /): - """iinfo(dtype) - + """ Returns machine limits for integer data types. - Args: - dtype (dtype, usm_ndarray): - integer dtype or - an array with integer dtype. - - Returns: - iinfo_object: - An object with the following attributes: - - * bits: int - number of bits occupied by the data type - * max: int - largest representable number. - * min: int - smallest representable number. - * dtype: dtype - integer data type. + Parameters + ---------- + dtype : {dtype, usm_ndarray} + Integer dtype or an array with integer dtype. + + Returns + ------- + out : iinfo_object + An object with the following attributes: + + * bits: int + number of bits occupied by the data type + * max: int + largest representable number. + * min: int + smallest representable number. + * dtype: dtype + integer data type. + """ + if isinstance(dtype, dpt.usm_ndarray): dtype = dtype.dtype _supported_dtype([dpt.dtype(dtype)]) @@ -843,37 +850,38 @@ def iinfo(dtype, /): def finfo(dtype, /): - """finfo(type) - + """ Returns machine limits for floating-point data types. - Args: - dtype (dtype, usm_ndarray): floating-point dtype or - an array with floating point data type. - If complex, the information is about its component - data type. - - Returns: - finfo_object: - an object have the following attributes: - - * bits: int - number of bits occupied by dtype. - * eps: float - difference between 1.0 and the next smallest representable - real-valued floating-point number larger than 1.0 according - to the IEEE-754 standard. - * max: float - largest representable real-valued number. - * min: float - smallest representable real-valued number. - * smallest_normal: float - smallest positive real-valued floating-point number with - full precision. - * dtype: dtype - real-valued floating-point data type. + Parameters + ---------- + dtype : {dtype, usm_ndarray} + Floating-point dtype or an array with floating point data type. + If complex, the information is about its component data type. + + Returns + ------- + out : finfo_object + An object with the following attributes: + + * bits: int + number of bits occupied by dtype. + * eps: float + difference between 1.0 and the next smallest representable + real-valued floating-point number larger than 1.0 according + to the IEEE-754 standard. + * max: float + largest representable real-valued number. + * min: float + smallest representable real-valued number. + * smallest_normal: float + smallest positive real-valued floating-point number with + full precision. + * dtype: dtype + real-valued floating-point data type. """ + if isinstance(dtype, dpt.usm_ndarray): dtype = dtype.dtype _supported_dtype([dpt.dtype(dtype)]) @@ -883,23 +891,37 @@ def finfo(dtype, /): def _supported_dtype(dtypes): for dtype in dtypes: if dtype.char not in "?bBhHiIlLqQefdFD": - raise ValueError(f"Dpctl doesn't support dtype {dtype}.") + raise ValueError(f"dpnp.tensor doesn't support dtype {dtype}.") return True def isdtype(dtype, kind): - """isdtype(dtype, kind) - + """ Returns a boolean indicating whether a provided `dtype` is of a specified data type `kind`. See [array API](array_api) for more information. [array_api]: https://data-apis.org/array-api/latest/ + + Parameters + ---------- + dtype : dtype + Data type to test. + kind : {dtype, str, tuple} + Data type kind. + + Returns + ------- + out : bool + Whether the provided `dtype` is of the specified data type `kind`. + """ if not isinstance(dtype, np.dtype): - raise TypeError(f"Expected instance of `dpt.dtype`, got {dtype}") + raise TypeError( + f"Expected instance of `dpnp.tensor.dtype`, got {dtype}" + ) if isinstance(kind, np.dtype): return dtype == kind From ce277cd395db3993f3814de4e096266f69301a9d Mon Sep 17 00:00:00 2001 From: Vladislav Perevezentsev Date: Fri, 10 Apr 2026 10:50:38 -0700 Subject: [PATCH 26/46] Update _usmarray.pyx doc to Sphinx format --- dpnp/tensor/_usmarray.pyx | 359 +++++++++++++++++++++----------------- 1 file changed, 200 insertions(+), 159 deletions(-) diff --git a/dpnp/tensor/_usmarray.pyx b/dpnp/tensor/_usmarray.pyx index 3344f757cf1..c0477c92b4f 100644 --- a/dpnp/tensor/_usmarray.pyx +++ b/dpnp/tensor/_usmarray.pyx @@ -225,18 +225,16 @@ cdef void _validate_and_use_stream( stream.submit_barrier(dependent_events=[ev]) cdef class usm_ndarray: - """ usm_ndarray(shape, dtype=None, strides=None, buffer="device", \ - offset=0, order="C", buffer_ctor_kwargs=dict(), \ - array_namespace=None) - + """ An array object represents a multidimensional tensor of numeric elements stored in a USM allocation on a SYCL device. - Arg: - shape (int, tuple): - Shape of the array to be created. - dtype (str, dtype): - Array data type, i.e. the type of array elements. + Parameters + ---------- + shape : {int, tuple} + Shape of the array to be created. + dtype : {str, dtype}, optional + Array data type, i.e. the type of array elements. If ``dtype`` has the value ``None``, it is determined by default floating point type supported by target device. The supported types are @@ -258,39 +256,46 @@ cdef class usm_ndarray: types, supported if target device's property ``has_aspect_fp64`` is ``True``. - Default: ``None``. - strides (tuple, optional): - Strides of the array to be created in elements. - If ``strides`` has the value ``None``, it is determined by the - ``shape`` of the array and the requested ``order``. - Default: ``None``. - buffer (str, object, optional): - A string corresponding to the type of USM allocation to make, - or a Python object representing a USM memory allocation, i.e. - :class:`dpctl.memory.MemoryUSMDevice`, - :class:`dpctl.memory.MemoryUSMShared`, or - :class:`dpctl.memory.MemoryUSMHost`. Recognized strings are - ``"device"``, ``"shared"``, or ``"host"``. Additional arguments to - the USM memory allocators can be passed in a dictionary specified - via ``buffer_ctor_kwrds`` keyword parameter. - Default: ``"device"``. - offset (int, optional): - Offset of the array element with all zero indexes relative to the - start of the provided `buffer` in elements. The argument is ignored - if the ``buffer`` value is a string and the memory is allocated by - the constructor. Default: ``0``. - order ({"C", "F"}, optional): - The memory layout of the array when constructing using a new - allocation. Value ``"C"`` corresponds to C-contiguous, or row-major - memory layout, while value ``"F"`` corresponds to F-contiguous, or - column-major layout. Default: ``"C"``. - buffer_ctor_kwargs (dict, optional): - Dictionary with keyword parameters to use when creating a new USM - memory allocation. See :class:`dpctl.memory.MemoryUSMShared` for - supported keyword arguments. - array_namespace (module, optional): - Array namespace module associated with this array. - Default: ``None``. + Default: ``None``. + strides : tuple, optional + Strides of the array to be created in elements. + If ``strides`` has the value ``None``, it is determined by the + ``shape`` of the array and the requested ``order``. + + Default: ``None``. + buffer : {str, object}, optional + A string corresponding to the type of USM allocation to make, + or a Python object representing a USM memory allocation, i.e. + :class:`dpctl.memory.MemoryUSMDevice`, + :class:`dpctl.memory.MemoryUSMShared`, or + :class:`dpctl.memory.MemoryUSMHost`. Recognized strings are + ``"device"``, ``"shared"``, or ``"host"``. Additional arguments to + the USM memory allocators can be passed in a dictionary specified + via ``buffer_ctor_kwrds`` keyword parameter. + + Default: ``"device"``. + offset : int, optional + Offset of the array element with all zero indexes relative to the + start of the provided `buffer` in elements. The argument is ignored + if the ``buffer`` value is a string and the memory is allocated by + the constructor. + + Default: ``0``. + order : {"C", "F"}, optional + The memory layout of the array when constructing using a new + allocation. Value ``"C"`` corresponds to C-contiguous, or row-major + memory layout, while value ``"F"`` corresponds to F-contiguous, or + column-major layout. + + Default: ``"C"``. + buffer_ctor_kwargs : dict, optional + Dictionary with keyword parameters to use when creating a new USM + memory allocation. See :class:`dpctl.memory.MemoryUSMShared` for + supported keyword arguments. + array_namespace : module, optional + Array namespace module associated with this array. + + Default: ``None``. ``buffer`` can be ``"shared"``, ``"host"``, ``"device"`` to allocate new device memory by calling respective constructor with @@ -298,8 +303,9 @@ cdef class usm_ndarray: instance of :class:`dpctl.memory.MemoryUSMShared`, :class:`dpctl.memory.MemoryUSMDevice`, or :class:`dpctl.memory.MemoryUSMHost`; ``buffer`` can also be - another :class:`dpctl.tensor.usm_ndarray` instance, in which case its + another :class:`dpnp.tensor.usm_ndarray` instance, in which case its underlying ``MemoryUSM*`` buffer is used. + """ cdef void _reset(usm_ndarray self): @@ -502,9 +508,9 @@ cdef class usm_ndarray: def _byte_bounds(self): """Returns a 2-tuple with pointers to the end-points of the array - :Example: - - .. code-block:: python + Examples + -------- + .. code-block:: python from dpnp import tensor @@ -519,7 +525,9 @@ cdef class usm_ndarray: yc = tensor.copy(y, order="C") beg_pc, end_pc = yc._byte_bounds assert bytes_extent < end_pc - beg_pc + """ + cdef Py_ssize_t min_disp = 0 cdef Py_ssize_t max_disp = 0 cdef Py_ssize_t step_ = 0 @@ -693,18 +701,20 @@ cdef class usm_ndarray: Setting shape is allowed only when reshaping to the requested dimensions can be returned as view, otherwise :exc:`AttributeError` - is raised. Use :func:`dpctl.tensor.reshape` to reshape the array + is raised. Use :func:`dpnp.tensor.reshape` to reshape the array in all cases. - :Example: - - .. code-block:: python + Examples + -------- + .. code-block:: python from dpnp import tensor x = tensor.arange(899) x.shape = (29, 31) + """ + if self.nd_ > 0: return _make_int_tuple(self.nd_, self.shape_) else: @@ -717,17 +727,20 @@ cdef class usm_ndarray: about the shape and the strides of the array, or raises `AttributeError` exception if in-place change is not possible. - Args: - new_shape: (tuple, int) - New shape. Only non-negative values are supported. - The new shape may not lead to the change in the - number of elements in the array. + Parameters + ---------- + new_shape : {tuple, int} + New shape. Only non-negative values are supported. + The new shape may not lead to the change in the + number of elements in the array. Whether the array can be reshape in-place depends on its - strides. Use :func:`dpctl.tensor.reshape` function which + strides. Use :func:`dpnp.tensor.reshape` function which always succeeds to reshape the array by performing a copy if necessary. + """ + cdef int new_nd = -1 cdef Py_ssize_t nelems = -1 cdef int err = 0 @@ -801,9 +814,9 @@ cdef class usm_ndarray: ``(i1, i2, i3)`` position of the respective element relative to zero multi-index element is ``s1*s1 + s2*i2 + s3*i3``. - :Example: - - .. code-block:: python + Examples + -------- + .. code-block:: python from dpnp import tensor @@ -816,7 +829,9 @@ cdef class usm_ndarray: i * s for i, s in zip(multi_id, xv.strides) ) assert byte_displacement == element_displacement * xv.itemsize + """ + if (self.strides_): return _make_int_tuple(self.nd_, self.strides_) else: @@ -830,7 +845,7 @@ cdef class usm_ndarray: @property def flags(self): """ - Returns :class:`dpctl.tensor._flags.Flags` object. + Returns :class:`dpnp.tensor.Flags` object. """ return _flags.Flags(self, self.flags_) @@ -906,7 +921,7 @@ cdef class usm_ndarray: @property def device(self): """ - Returns :class:`dpctl.tensor.Device` object representing + Returns :class:`dpnp.tensor.Device` object representing residence of the array data. The ``Device`` object represents Array API notion of the @@ -914,15 +929,17 @@ cdef class usm_ndarray: with this array. Hence, ``.device`` property provides information distinct from ``.sycl_device`` property. - :Example: - - .. code-block:: python + Examples + -------- + .. code-block:: python >>> from dpnp import tensor >>> x = tensor.ones(10) >>> x.device Device(level_zero:gpu:0) + """ + return Device.create_device(self.sycl_queue) @property @@ -965,9 +982,9 @@ cdef class usm_ndarray: complex data-types and returns itself for all other data-types. - :Example: - - .. code-block:: python + Examples + -------- + .. code-block:: python from dpnp import tensor @@ -980,7 +997,9 @@ cdef class usm_ndarray: z = tensor.empty_like(re, dtype="c8") z.real[:] = re z.imag[:] = im + """ + # explicitly check for UAR_HALF, which is greater than UAR_CFLOAT if (self.typenum_ < UAR_CFLOAT or self.typenum_ == UAR_HALF): # elements are real @@ -994,9 +1013,9 @@ cdef class usm_ndarray: complex data-types and returns new zero array for all other data-types. - :Example: - - .. code-block:: python + Examples + -------- + .. code-block:: python from dpnp import tensor @@ -1004,7 +1023,9 @@ cdef class usm_ndarray: z = tensor.ones(100, dtype="c8") z.imag[:] = dpt.pi/2 + """ + # explicitly check for UAR_HALF, which is greater than UAR_CFLOAT if (self.typenum_ < UAR_CFLOAT or self.typenum_ == UAR_HALF): # elements are real @@ -1082,45 +1103,49 @@ cdef class usm_ndarray: return res def to_device(self, target_device, /, *, stream=None): - """ to_device(target_device, /, *, stream=None) - + """ Transfers this array to specified target device. - :Example: - .. code-block:: python - - import dpctl - import dpnp.tensor as dpt - - x = dpt.full(10**6, 2, dtype="int64") - q_prof = dpctl.SyclQueue( - x.sycl_device, property="enable_profiling") - # return a view with profile-enabled queue - y = x.to_device(q_prof) - timer = dpctl.SyclTimer() - with timer(q_prof): - z = y * y - print(timer.dt) - - Args: - target_device (object): - Array API concept of target device. - It can be a oneAPI filter selector string, - an instance of :class:`dpctl.SyclDevice` corresponding to a - non-partitioned SYCL device, an instance of - :class:`dpctl.SyclQueue`, or a :class:`dpctl.tensor.Device` - object returned by :attr:`dpctl.tensor.usm_ndarray.device`. - stream (:class:`dpctl.SyclQueue`, optional): - Execution queue to synchronize with. If ``None``, - synchronization is not performed. - - Returns: - usm_ndarray: - A view if data copy is not required, and a copy otherwise. - If copying is required, it is done by copying from the original - allocation device to the host, followed by copying from host - to the target device. + Examples + -------- + .. code-block:: python + + import dpctl + import dpnp.tensor as dpt + + x = dpt.full(10**6, 2, dtype="int64") + q_prof = dpctl.SyclQueue( + x.sycl_device, property="enable_profiling") + # return a view with profile-enabled queue + y = x.to_device(q_prof) + timer = dpctl.SyclTimer() + with timer(q_prof): + z = y * y + print(timer.dt) + + Parameters + ---------- + target_device : object + Array API concept of target device. + It can be a oneAPI filter selector string, + an instance of :class:`dpctl.SyclDevice` corresponding to a + non-partitioned SYCL device, an instance of + :class:`dpctl.SyclQueue`, or a :class:`dpnp.tensor.Device` + object returned by :attr:`dpnp.tensor.usm_ndarray.device`. + stream : :class:`dpctl.SyclQueue`, optional + Execution queue to synchronize with. If ``None``, + synchronization is not performed. + + Returns + ------- + out : usm_ndarray + A view if data copy is not required, and a copy otherwise. + If copying is required, it is done by copying from the original + allocation device to the host, followed by copying from host + to the target device. + """ + cdef c_dpctl.DPCTLSyclQueueRef QRef = NULL cdef c_dpmem._Memory arr_buf d = Device.create_device(target_device) @@ -1170,13 +1195,17 @@ cdef class usm_ndarray: Returns array namespace, member functions of which implement data API. - Args: - api_version (str, optional) - Request namespace compliant with given version of - array API. If ``None``, namespace for the most - recent supported version is returned. - Default: ``None``. + Parameters + ---------- + api_version : str, optional + Request namespace compliant with given version of + array API. If ``None``, namespace for the most + recent supported version is returned. + + Default: ``None``. + """ + if api_version is not None: from ._array_api import __array_api_version__ if not isinstance(api_version, str): @@ -1260,50 +1289,57 @@ cdef class usm_ndarray: """ Produces DLPack capsule. - Args: - stream (:class:`dpctl.SyclQueue`, optional): - Execution queue to synchronize with. - If ``None``, synchronization is not performed. - Default: ``None``. - max_version (tuple[int, int], optional): - The maximum DLPack version the consumer (caller of - ``__dlpack__``) supports. As ``__dlpack__`` may not - always return a DLPack capsule with version - `max_version`, the consumer must verify the version - even if this argument is passed. - Default: ``None``. - dl_device (tuple[enum.Enum, int], optional): - The device the returned DLPack capsule will be - placed on. - The device must be a 2-tuple matching the format of - ``__dlpack_device__`` method, an integer enumerator - representing the device type followed by an integer - representing the index of the device. - Default: ``None``. - copy (bool, optional): - Boolean indicating whether or not to copy the input. - - * If ``copy`` is ``True``, the input will always be - copied. - * If ``False``, a ``BufferError`` will be raised if a - copy is deemed necessary. - * If ``None``, a copy will be made only if deemed - necessary, otherwise, the existing memory buffer will - be reused. - - Default: ``None``. - - Raises: - MemoryError: - when host memory can not be allocated. - DLPackCreationError: - when array is allocated on a partitioned - SYCL device, or with a non-default context. - BufferError: - when a copy is deemed necessary but ``copy`` - is ``False`` or when the provided ``dl_device`` - cannot be handled. + Parameters + ---------- + stream : :class:`dpctl.SyclQueue`, optional + Execution queue to synchronize with. + If ``None``, synchronization is not performed. + + Default: ``None``. + max_version : tuple of ints, optional + The maximum DLPack version the consumer (caller of + ``__dlpack__``) supports. As ``__dlpack__`` may not + always return a DLPack capsule with version + `max_version`, the consumer must verify the version + even if this argument is passed. + + Default: ``None``. + dl_device : tuple, optional + The device the returned DLPack capsule will be + placed on. + The device must be a 2-tuple matching the format of + ``__dlpack_device__`` method, an integer enumerator + representing the device type followed by an integer + representing the index of the device. + + Default: ``None``. + copy : bool, optional + Boolean indicating whether or not to copy the input. + + * If ``copy`` is ``True``, the input will always be + copied. + * If ``False``, a ``BufferError`` will be raised if a + copy is deemed necessary. + * If ``None``, a copy will be made only if deemed + necessary, otherwise, the existing memory buffer will + be reused. + + Default: ``None``. + + Raises + ------ + MemoryError + When host memory can not be allocated. + DLPackCreationError + When array is allocated on a partitioned + SYCL device, or with a non-default context. + BufferError + When a copy is deemed necessary but ``copy`` + is ``False`` or when the provided ``dl_device`` + cannot be handled. + """ + if max_version is None: # legacy path for DLManagedTensor # copy kwarg ignored because copy flag can't be set @@ -1391,13 +1427,16 @@ cdef class usm_ndarray: allocated, or the non-partitioned parent device of the allocation device. - See :class:`dpctl.tensor.DLDeviceType` for a list of devices supported + See :class:`dpnp.tensor.DLDeviceType` for a list of devices supported by the DLPack protocol. - Raises: - DLPackCreationError: - when the ``device_id`` could not be determined. + Raises + ------ + DLPackCreationError + When the ``device_id`` could not be determined. + """ + try: dev_id = self.sycl_device.get_device_id() except ValueError as e: @@ -1658,7 +1697,9 @@ cdef class usm_ndarray: and every element being 0d usm_ndarray. https://github.com/IntelPython/dpctl/pull/1384#issuecomment-1707212972 + """ + raise TypeError( "Implicit conversion to a NumPy array is not allowed. " "Use `dpnp.tensor.asnumpy` to copy data from this " From bff1672a604f080c4bcba5c9522a63d1c9aff1b2 Mon Sep 17 00:00:00 2001 From: Vladislav Perevezentsev Date: Fri, 10 Apr 2026 10:52:30 -0700 Subject: [PATCH 27/46] Update _utility_functions.py doc to Sphinx format --- dpnp/tensor/_utility_functions.py | 167 +++++++++++++++++------------- 1 file changed, 93 insertions(+), 74 deletions(-) diff --git a/dpnp/tensor/_utility_functions.py b/dpnp/tensor/_utility_functions.py index 651ce083026..855db66b2a1 100644 --- a/dpnp/tensor/_utility_functions.py +++ b/dpnp/tensor/_utility_functions.py @@ -118,59 +118,71 @@ def _boolean_reduction(x, axis, keepdims, func): def all(x, /, *, axis=None, keepdims=False): """ - all(x, axis=None, keepdims=False) - Tests whether all input array elements evaluate to True along a given axis. - Args: - x (usm_ndarray): Input array. - axis (Optional[Union[int, Tuple[int,...]]]): Axis (or axes) - along which to perform a logical AND reduction. - When `axis` is `None`, a logical AND reduction - is performed over all dimensions of `x`. - If `axis` is negative, the axis is counted from - the last dimension to the first. - Default: `None`. - keepdims (bool, optional): If `True`, the reduced axes are included - in the result as singleton dimensions, and the result is - broadcastable to the input array shape. - If `False`, the reduced axes are not included in the result. - Default: `False`. - - Returns: - usm_ndarray: - An array with a data type of `bool` - containing the results of the logical AND reduction. + Parameters + ---------- + x : usm_ndarray + Input array. + axis : {None, int, tuple of ints}, optional + Axis (or axes) along which to perform a logical AND reduction. + When `axis` is `None`, a logical AND reduction + is performed over all dimensions of `x`. + If `axis` is negative, the axis is counted from + the last dimension to the first. + + Default: ``None``. + keepdims : bool, optional + If `True`, the reduced axes are included in the result as + singleton dimensions, and the result is broadcastable to the + input array shape. + If `False`, the reduced axes are not included in the result. + + Default: ``False``. + + Returns + ------- + out : usm_ndarray + An array with a data type of `bool` + containing the results of the logical AND reduction. + """ + return _boolean_reduction(x, axis, keepdims, tri._all) def any(x, /, *, axis=None, keepdims=False): """ - any(x, axis=None, keepdims=False) - Tests whether any input array elements evaluate to True along a given axis. - Args: - x (usm_ndarray): Input array. - axis (Optional[Union[int, Tuple[int,...]]]): Axis (or axes) - along which to perform a logical OR reduction. - When `axis` is `None`, a logical OR reduction - is performed over all dimensions of `x`. - If `axis` is negative, the axis is counted from - the last dimension to the first. - Default: `None`. - keepdims (bool, optional): If `True`, the reduced axes are included - in the result as singleton dimensions, and the result is - broadcastable to the input array shape. - If `False`, the reduced axes are not included in the result. - Default: `False`. - - Returns: - usm_ndarray: - An array with a data type of `bool` - containing the results of the logical OR reduction. + Parameters + ---------- + x : usm_ndarray + Input array. + axis : {None, int, tuple of ints}, optional + Axis (or axes) along which to perform a logical OR reduction. + When `axis` is `None`, a logical OR reduction + is performed over all dimensions of `x`. + If `axis` is negative, the axis is counted from + the last dimension to the first. + + Default: ``None``. + keepdims : bool, optional + If `True`, the reduced axes are included in the result as + singleton dimensions, and the result is broadcastable to the + input array shape. + If `False`, the reduced axes are not included in the result. + + Default: ``False``. + + Returns + ------- + out : usm_ndarray + An array with a data type of `bool` + containing the results of the logical OR reduction. + """ + return _boolean_reduction(x, axis, keepdims, tri._any) @@ -432,38 +444,45 @@ def diff(x, /, *, axis=-1, n=1, prepend=None, append=None): """ Calculates the `n`-th discrete forward difference of `x` along `axis`. - Args: - x (usm_ndarray): - input array. - axis (int): - axis along which to compute the difference. A valid axis must be on - the interval `[-N, N)`, where `N` is the rank (number of - dimensions) of `x`. - Default: `-1` - n (int): - number of times to recursively compute the difference. - Default: `1`. - prepend (Union[usm_ndarray, bool, int, float, complex]): - value or values to prepend to the specified axis before taking the - difference. - Must have the same shape as `x` except along `axis`, which can have - any shape. - Default: `None`. - append (Union[usm_ndarray, bool, int, float, complex]): - value or values to append to the specified axis before taking the - difference. - Must have the same shape as `x` except along `axis`, which can have - any shape. - Default: `None`. - - Returns: - usm_ndarray: - an array containing the `n`-th differences. The array will have the - same shape as `x`, except along `axis`, which will have shape: - ``prepend.shape[axis] + x.shape[axis] + append.shape[axis] - n`` - - The data type of the returned array is determined by the Type - Promotion Rules. + Parameters + ---------- + x : usm_ndarray + Input array. + axis : int, optional + Axis along which to compute the difference. A valid axis must be on + the interval `[-N, N)`, where `N` is the rank (number of + dimensions) of `x`. + + Default: ``-1``. + n : int, optional + Number of times to recursively compute the difference. + + Default: ``1``. + prepend : {None, usm_ndarray, bool, int, float, complex}, optional + Value or values to prepend to the specified axis before taking the + difference. + Must have the same shape as `x` except along `axis`, which can have + any shape. + + Default: ``None``. + append : {None, usm_ndarray, bool, int, float, complex}, optional + Value or values to append to the specified axis before taking the + difference. + Must have the same shape as `x` except along `axis`, which can have + any shape. + + Default: ``None``. + + Returns + ------- + out : usm_ndarray + An array containing the `n`-th differences. The array will have the + same shape as `x`, except along `axis`, which will have shape: + ``prepend.shape[axis] + x.shape[axis] + append.shape[axis] - n`` + + The data type of the returned array is determined by the Type + Promotion Rules. + """ if not isinstance(x, dpt.usm_ndarray): From 16cf16111d0582edfaddd3ff94d435472e0af5fb Mon Sep 17 00:00:00 2001 From: Vladislav Perevezentsev Date: Thu, 11 Jun 2026 04:57:09 -0700 Subject: [PATCH 28/46] Update _compute_follows_data.pyx. doc to Sphinx format --- dpnp/tensor/_compute_follows_data.pyx | 92 +++++++++++++++------------ 1 file changed, 52 insertions(+), 40 deletions(-) diff --git a/dpnp/tensor/_compute_follows_data.pyx b/dpnp/tensor/_compute_follows_data.pyx index c5028c55090..975f52b4cee 100644 --- a/dpnp/tensor/_compute_follows_data.pyx +++ b/dpnp/tensor/_compute_follows_data.pyx @@ -67,16 +67,20 @@ def get_execution_queue(qs, /): """ Get execution queue from queues associated with input arrays. - Args: - qs (List[:class:`dpctl.SyclQueue`], Tuple[:class:`dpctl.SyclQueue`]): - a list or a tuple of :class:`dpctl.SyclQueue` objects - corresponding to arrays that are being combined. - - Returns: - SyclQueue: - execution queue under compute follows data paradigm, - or ``None`` if queues are not equal. + Parameters + ---------- + qs : list or tuple of :class:`dpctl.SyclQueue` + A list or a tuple of :class:`dpctl.SyclQueue` objects + corresponding to arrays that are being combined. + + Returns + ------- + out : {:class:`dpctl.SyclQueue`, None} + Execution queue under compute follows data paradigm, + or ``None`` if queues are not equal. + """ + if not isinstance(qs, (list, tuple)): raise TypeError( "Expected a list or a tuple, got {}".format(type(qs)) @@ -101,16 +105,20 @@ def get_coerced_usm_type(usm_types, /): arrays of given USM types using compute-follows-data execution model. - Args: - usm_types (List[str], Tuple[str]): - a list or a tuple of strings of ``.usm_types`` attributes - for input arrays + Parameters + ---------- + usm_types : list or tuple of str + A list or a tuple of strings of ``.usm_types`` attributes + for input arrays + + Returns + ------- + out : {str, None} + Type of USM allocation for the output arrays (s). + ``None`` if any of the input strings are not recognized. - Returns: - str - type of USM allocation for the output arrays (s). - ``None`` if any of the input strings are not recognized. """ + if not isinstance(usm_types, (list, tuple)): raise TypeError( "Expected a list or a tuple, got {}".format(type(usm_types)) @@ -159,32 +167,36 @@ def _validate_usm_type_disallow_none(usm_type): def validate_usm_type(usm_type, /, *, allow_none=True): - """ validate_usm_type(usm_type, allow_none=True) - + """ Raises an exception if `usm_type` is invalid. - Args: - usm_type: - Specification for USM allocation type. Valid specifications - are: - - * ``"device"`` - * ``"shared"`` - * ``"host"`` - - If ``allow_none`` keyword argument is set, a value of - ``None`` is also permitted. - allow_none (bool, optional): - Whether ``usm_type`` value of ``None`` is considered valid. - Default: `True`. - - Raises: - ValueError: - if ``usm_type`` is not a recognized string. - TypeError: - if ``usm_type`` is not a string, and ``usm_type`` is - not ``None`` provided ``allow_none`` is ``True``. + Parameters + ---------- + usm_type: {str, None} + Specification for USM allocation type. Valid specifications + are: + + * ``"device"`` + * ``"shared"`` + * ``"host"`` + + If ``allow_none`` keyword argument is set, a value of + ``None`` is also permitted. + allow_none : bool, optional + Whether ``usm_type`` value of ``None`` is considered valid. + + Default: `True`. + + Raises + ------ + ValueError: + If ``usm_type`` is not a recognized string. + TypeError: + If ``usm_type`` is not a string, and ``usm_type`` is + not ``None`` provided ``allow_none`` is ``True``. + """ + if allow_none: _validate_usm_type_allow_none(usm_type) else: From e98a6bf942c1ee9038e7017e05d9fb7a3b81b5fa Mon Sep 17 00:00:00 2001 From: Vladislav Perevezentsev Date: Thu, 11 Jun 2026 05:15:25 -0700 Subject: [PATCH 29/46] Add missing None to parameter type --- dpnp/tensor/_dlpack.pyx | 5 +++-- dpnp/tensor/_elementwise_funcs.py | 14 +++++++------- dpnp/tensor/_indexing_functions.py | 2 +- dpnp/tensor/_manipulation_functions.py | 4 ++-- dpnp/tensor/_sorting.py | 6 +++--- dpnp/tensor/_usmarray.pyx | 18 +++++++++--------- 6 files changed, 25 insertions(+), 24 deletions(-) diff --git a/dpnp/tensor/_dlpack.pyx b/dpnp/tensor/_dlpack.pyx index f2043d29cd4..ecc396f609b 100644 --- a/dpnp/tensor/_dlpack.pyx +++ b/dpnp/tensor/_dlpack.pyx @@ -1047,7 +1047,8 @@ def from_dlpack(x, /, *, device=None, copy=None): x : object A Python object representing an array that supports ``__dlpack__`` protocol. - device : {None, str, dpctl.SyclDevice, dpctl.SyclQueue, dpnp.tensor.Device, tuple}, optional + device : {None, str, dpctl.SyclDevice, dpctl.SyclQueue, + dpnp.tensor.Device, tuple}, optional Device where the output array is to be placed. ``device`` keyword values can be: @@ -1072,7 +1073,7 @@ def from_dlpack(x, /, *, device=None, copy=None): device types are ``"kDLCPU"`` and ``"kDLOneAPI"``. Default: ``None``. - copy : bool, optional + copy : {None, bool}, optional Boolean indicating whether or not to copy the input. * If ``copy`` is ``True``, the input will always be diff --git a/dpnp/tensor/_elementwise_funcs.py b/dpnp/tensor/_elementwise_funcs.py index a04a36e0d28..c191b8c4943 100644 --- a/dpnp/tensor/_elementwise_funcs.py +++ b/dpnp/tensor/_elementwise_funcs.py @@ -984,7 +984,7 @@ ---------- x : usm_ndarray Input array, expected to have a floating-point data type. - out : usm_ndarray + out : {None, usm_ndarray}, optional Output array to populate. Array must have the correct shape and the expected data type. order : {"C", "F", "A", "K"}, optional @@ -1267,7 +1267,7 @@ ---------- x : usm_ndarray Input array, expected to have a floating-point data type. - out : usm_ndarray + out : {None, usm_ndarray}, optional Output array to populate. Array must have the correct shape and the expected data type. order : {"C", "F", "A", "K"}, optional @@ -1301,7 +1301,7 @@ ---------- x : usm_ndarray Input array, expected to have a floating-point data type. - out : usm_ndarray + out : {None, usm_ndarray}, optional Output array to populate. Array must have the correct shape and the expected data type. order : {"C", "F", "A", "K"}, optional @@ -1558,7 +1558,7 @@ ---------- x : usm_ndarray Input array. May have any data type. - out : usm_ndarray + out : {None, usm_ndarray}, optional Output array to populate. Array must have the correct shape and the expected data type. order : {"C", "F", "A", "K"}, optional @@ -1709,7 +1709,7 @@ ---------- x : usm_ndarray Input array, expected to have a numeric data type. - out : usm_ndarray + out : {None, usm_ndarray}, optional Output array to populate. Array must have the correct shape and the expected data type. order : {"C", "F", "A", "K"}, optional @@ -1825,7 +1825,7 @@ ---------- x : usm_ndarray Input array, expected to have a numeric data type. - out : usm_ndarray + out : {None, usm_ndarray}, optional Output array to populate. Array must have the correct shape and the expected data type. order : {"C", "F", "A", "K"}, optional @@ -1858,7 +1858,7 @@ First input array, expected to have a numeric data type. x2 : usm_ndarray Second input array, also expected to have a numeric data type. - out : usm_ndarray + out : {None, usm_ndarray}, optional Output array to populate. Array must have the correct shape and the expected data type. order : {"C", "F", "A", "K"}, optional diff --git a/dpnp/tensor/_indexing_functions.py b/dpnp/tensor/_indexing_functions.py index a013a907de9..85e3a797b69 100644 --- a/dpnp/tensor/_indexing_functions.py +++ b/dpnp/tensor/_indexing_functions.py @@ -464,7 +464,7 @@ def take(x, indices, /, *, axis=None, out=None, mode="wrap"): If ``x`` is one-dimensional, this argument is optional. Default: ``None``. - out : usm_ndarray, optional + out : {None, usm_ndarray}, optional Output array to populate. Array must have the correct shape and the expected data type. diff --git a/dpnp/tensor/_manipulation_functions.py b/dpnp/tensor/_manipulation_functions.py index 151a6644f0e..83513ac8bef 100644 --- a/dpnp/tensor/_manipulation_functions.py +++ b/dpnp/tensor/_manipulation_functions.py @@ -302,7 +302,7 @@ def concat(arrays, /, *, axis=0): arrays : {list of usm_ndarrays, tuple of usm_ndarrays} Input arrays to join. The arrays must have the same shape, except in the dimension specified by `axis`. - axis : int, optional + axis : {None, int}, optional Axis along which the arrays will be joined. If `axis` is `None`, arrays must be flattened before concatenation. If `axis` is negative, it is understood as @@ -574,7 +574,7 @@ def repeat(x, repeats, /, *, axis=None): If `repeats` is an array, it must have an integer data type. Otherwise, `repeats` must be a Python integer or sequence of Python integers (i.e., a tuple, list, or range). - axis : int, optional + axis : {None, int}, optional The axis along which to repeat values. If `axis` is `None`, the function repeats elements of the flattened array. diff --git a/dpnp/tensor/_sorting.py b/dpnp/tensor/_sorting.py index 564c3dd66db..7f4ae364ec3 100644 --- a/dpnp/tensor/_sorting.py +++ b/dpnp/tensor/_sorting.py @@ -85,7 +85,7 @@ def sort(x, /, *, axis=-1, descending=False, stable=True, kind=None): `x` values which compare as equal. Default: ``True``. - kind : {"stable", "mergesort", "radixsort"}, optional + kind : {None, "stable", "mergesort", "radixsort"}, optional Sorting algorithm. The default is `"stable"`, which uses parallel merge-sort or parallel radix-sort algorithms depending on the array data type. @@ -209,7 +209,7 @@ def argsort(x, axis=-1, descending=False, stable=True, kind=None): `x` values which compare as equal. Default: ``True``. - kind : {"stable", "mergesort", "radixsort"}, optional + kind : {None, "stable", "mergesort", "radixsort"}, optional Sorting algorithm. The default is `"stable"`, which uses parallel merge-sort or parallel radix-sort algorithms depending on the array data type. @@ -329,7 +329,7 @@ def top_k(x, k, /, *, axis=None, mode="largest"): Input array. k : int Number of elements to find. Must be a positive integer value. - axis : int, optional + axis : {None, int}, optional Axis along which to search. If `None`, the search will be performed over the flattened array. diff --git a/dpnp/tensor/_usmarray.pyx b/dpnp/tensor/_usmarray.pyx index c0477c92b4f..07716c5d8f3 100644 --- a/dpnp/tensor/_usmarray.pyx +++ b/dpnp/tensor/_usmarray.pyx @@ -233,7 +233,7 @@ cdef class usm_ndarray: ---------- shape : {int, tuple} Shape of the array to be created. - dtype : {str, dtype}, optional + dtype : {None, str, dtype}, optional Array data type, i.e. the type of array elements. If ``dtype`` has the value ``None``, it is determined by default floating point type supported by target device. @@ -257,7 +257,7 @@ cdef class usm_ndarray: ``has_aspect_fp64`` is ``True``. Default: ``None``. - strides : tuple, optional + strides : {None, tuple}, optional Strides of the array to be created in elements. If ``strides`` has the value ``None``, it is determined by the ``shape`` of the array and the requested ``order``. @@ -292,7 +292,7 @@ cdef class usm_ndarray: Dictionary with keyword parameters to use when creating a new USM memory allocation. See :class:`dpctl.memory.MemoryUSMShared` for supported keyword arguments. - array_namespace : module, optional + array_namespace : {None, module}, optional Array namespace module associated with this array. Default: ``None``. @@ -1132,7 +1132,7 @@ cdef class usm_ndarray: non-partitioned SYCL device, an instance of :class:`dpctl.SyclQueue`, or a :class:`dpnp.tensor.Device` object returned by :attr:`dpnp.tensor.usm_ndarray.device`. - stream : :class:`dpctl.SyclQueue`, optional + stream : {None, :class:`dpctl.SyclQueue`}, optional Execution queue to synchronize with. If ``None``, synchronization is not performed. @@ -1197,7 +1197,7 @@ cdef class usm_ndarray: Parameters ---------- - api_version : str, optional + api_version : {None, str}, optional Request namespace compliant with given version of array API. If ``None``, namespace for the most recent supported version is returned. @@ -1291,12 +1291,12 @@ cdef class usm_ndarray: Parameters ---------- - stream : :class:`dpctl.SyclQueue`, optional + stream : {None, :class:`dpctl.SyclQueue`}, optional Execution queue to synchronize with. If ``None``, synchronization is not performed. Default: ``None``. - max_version : tuple of ints, optional + max_version : {None, tuple of ints}, optional The maximum DLPack version the consumer (caller of ``__dlpack__``) supports. As ``__dlpack__`` may not always return a DLPack capsule with version @@ -1304,7 +1304,7 @@ cdef class usm_ndarray: even if this argument is passed. Default: ``None``. - dl_device : tuple, optional + dl_device : {None, tuple}, optional The device the returned DLPack capsule will be placed on. The device must be a 2-tuple matching the format of @@ -1313,7 +1313,7 @@ cdef class usm_ndarray: representing the index of the device. Default: ``None``. - copy : bool, optional + copy : {None, bool}, optional Boolean indicating whether or not to copy the input. * If ``copy`` is ``True``, the input will always be From 68ef2d4221ab8233270c5f352fac177b48abe8c5 Mon Sep 17 00:00:00 2001 From: Vladislav Perevezentsev Date: Thu, 11 Jun 2026 05:21:40 -0700 Subject: [PATCH 30/46] Add missing Default values to parameter docstrings --- dpnp/tensor/_ctors.py | 12 +----------- dpnp/tensor/_elementwise_funcs.py | 14 ++++++++++++++ dpnp/tensor/_manipulation_functions.py | 8 ++++++-- dpnp/tensor/_reshape.py | 6 ++++++ dpnp/tensor/_usmarray.pyx | 4 ++++ 5 files changed, 31 insertions(+), 13 deletions(-) diff --git a/dpnp/tensor/_ctors.py b/dpnp/tensor/_ctors.py index cff8610315e..901d290b628 100644 --- a/dpnp/tensor/_ctors.py +++ b/dpnp/tensor/_ctors.py @@ -1575,17 +1575,7 @@ def meshgrid(*arrays, indexing="xy"): zero- and one-dimensional cases, respectively), the ``indexing`` keyword has no effect and should be ignored. - Returns: - Tuple[array]: - tuple of ``N`` arrays, where ``N`` is the number of - provided one-dimensional input arrays. Each returned array must - have rank ``N``. - For a set of ``n`` vectors with lengths ``N0``, ``N1``, ``N2``, ... - The cartesian indexing results in arrays of shape - ``(N1, N0, N2, ...)``, while the - matrix indexing results in arrays of shape - ``(N0, N1, N2, ...)``. - Default: ``"xy"``. + Default: ``"xy"``. Returns ------- diff --git a/dpnp/tensor/_elementwise_funcs.py b/dpnp/tensor/_elementwise_funcs.py index c191b8c4943..4c935d12eb8 100644 --- a/dpnp/tensor/_elementwise_funcs.py +++ b/dpnp/tensor/_elementwise_funcs.py @@ -987,6 +987,8 @@ out : {None, usm_ndarray}, optional Output array to populate. Array must have the correct shape and the expected data type. + + Default: ``None``. order : {"C", "F", "A", "K"}, optional Memory layout of the new output array, if parameter `out` is ``None``. @@ -1270,6 +1272,8 @@ out : {None, usm_ndarray}, optional Output array to populate. Array must have the correct shape and the expected data type. + + Default: ``None``. order : {"C", "F", "A", "K"}, optional Memory layout of the new output array, if parameter `out` is ``None``. @@ -1304,6 +1308,8 @@ out : {None, usm_ndarray}, optional Output array to populate. Array must have the correct shape and the expected data type. + + Default: ``None``. order : {"C", "F", "A", "K"}, optional Memory layout of the new output array, if parameter `out` is ``None``. @@ -1561,6 +1567,8 @@ out : {None, usm_ndarray}, optional Output array to populate. Array must have the correct shape and the expected data type. + + Default: ``None``. order : {"C", "F", "A", "K"}, optional Memory layout of the new output array, if parameter `out` is ``None``. @@ -1712,6 +1720,8 @@ out : {None, usm_ndarray}, optional Output array to populate. Array must have the correct shape and the expected data type. + + Default: ``None``. order : {"C", "F", "A", "K"}, optional Memory layout of the new output array, if parameter `out` is ``None``. @@ -1828,6 +1838,8 @@ out : {None, usm_ndarray}, optional Output array to populate. Array must have the correct shape and the expected data type. + + Default: ``None``. order : {"C", "F", "A", "K"}, optional Memory layout of the new output array, if parameter `out` is ``None``. @@ -1861,6 +1873,8 @@ out : {None, usm_ndarray}, optional Output array to populate. Array must have the correct shape and the expected data type. + + Default: ``None``. order : {"C", "F", "A", "K"}, optional Memory layout of the new output array, if parameter `out` is ``None``. diff --git a/dpnp/tensor/_manipulation_functions.py b/dpnp/tensor/_manipulation_functions.py index 83513ac8bef..f094f461273 100644 --- a/dpnp/tensor/_manipulation_functions.py +++ b/dpnp/tensor/_manipulation_functions.py @@ -378,7 +378,7 @@ def expand_dims(X, /, *, axis=0): ---------- x : usm_ndarray Input array. - axis : {int, tuple of ints} + axis : {int, tuple of ints}, optional Axis position in the expanded axes (zero-based). If `x` has rank (i.e, number of dimensions) `N`, a valid `axis` must reside in the closed-interval `[-N-1, N]`. If provided a negative @@ -389,6 +389,8 @@ def expand_dims(X, /, *, axis=0): If provided `-N-1`, the resolved axis position is `0` (i.e., a singleton dimension is prepended to the input array `x`). + Default: ``0``. + Returns ------- out : usm_ndarray @@ -878,9 +880,11 @@ def squeeze(X, /, axis=None): ---------- x : usm_ndarray Input array. - axis : {int, tuple of ints} + axis : {None, int, tuple of ints}, optional Axis (or axes) to squeeze. + Default: ``None``. + Returns ------- out : usm_ndarray diff --git a/dpnp/tensor/_reshape.py b/dpnp/tensor/_reshape.py index d6043dc3626..8b6b8dec031 100644 --- a/dpnp/tensor/_reshape.py +++ b/dpnp/tensor/_reshape.py @@ -118,6 +118,12 @@ def reshape(X, /, shape, *, order="C", copy=None): and ``"F"`` for F-contiguous, or column-major layout. Default: ``"C"``. + copy : {None, bool}, optional + Whether or not to copy the input array. If ``True``, always + copies. If ``False``, never copies and raises a ``ValueError`` + if a copy is required. If ``None``, copies only when necessary. + + Default: ``None``. Returns ------- diff --git a/dpnp/tensor/_usmarray.pyx b/dpnp/tensor/_usmarray.pyx index 07716c5d8f3..cc1e9bbf684 100644 --- a/dpnp/tensor/_usmarray.pyx +++ b/dpnp/tensor/_usmarray.pyx @@ -292,6 +292,8 @@ cdef class usm_ndarray: Dictionary with keyword parameters to use when creating a new USM memory allocation. See :class:`dpctl.memory.MemoryUSMShared` for supported keyword arguments. + + Default: ``{}``. array_namespace : {None, module}, optional Array namespace module associated with this array. @@ -1136,6 +1138,8 @@ cdef class usm_ndarray: Execution queue to synchronize with. If ``None``, synchronization is not performed. + Default: ``None``. + Returns ------- out : usm_ndarray From 4d5be4ea834e8f643186bf79a8a08975f55f2a9c Mon Sep 17 00:00:00 2001 From: Vladislav Perevezentsev Date: Thu, 11 Jun 2026 05:34:46 -0700 Subject: [PATCH 31/46] Add missing None to parameter type(2) --- dpnp/tensor/_accumulation.py | 18 ++--- dpnp/tensor/_array_api.py | 6 +- dpnp/tensor/_copy_utils.py | 6 +- dpnp/tensor/_ctors.py | 102 ++++++++++++++--------------- dpnp/tensor/_device.py | 4 +- dpnp/tensor/_elementwise_common.py | 6 +- dpnp/tensor/_indexing_functions.py | 4 +- dpnp/tensor/_reduction.py | 12 ++-- 8 files changed, 79 insertions(+), 79 deletions(-) diff --git a/dpnp/tensor/_accumulation.py b/dpnp/tensor/_accumulation.py index 3f90e18a890..bbc64b3afb6 100644 --- a/dpnp/tensor/_accumulation.py +++ b/dpnp/tensor/_accumulation.py @@ -239,7 +239,7 @@ def cumulative_sum( ---------- x : usm_ndarray input array. - axis : int, optional + axis : {None, int}, optional axis along which cumulative sum must be computed. If `None`, the sum is computed over the entire array. If `x` is a one-dimensional array, providing an `axis` is optional; @@ -247,7 +247,7 @@ def cumulative_sum( is required. Default: ``None``. - dtype : dtype, optional + dtype : {None, dtype}, optional data type of the returned array. If `None`, the default data type is inferred from the "kind" of the input array data type. @@ -275,7 +275,7 @@ def cumulative_sum( in the output. Default: ``False``. - out : usm_ndarray, optional + out : {None, usm_ndarray}, optional the array into which the result is written. The data type of `out` must match the expected shape and the expected data type of the result or (if provided) `dtype`. @@ -325,7 +325,7 @@ def cumulative_prod( ---------- x : usm_ndarray input array. - axis : int, optional + axis : {None, int}, optional axis along which cumulative product must be computed. If `None`, the product is computed over the entire array. If `x` is a one-dimensional array, providing an `axis` is optional; @@ -333,7 +333,7 @@ def cumulative_prod( is required. Default: ``None``. - dtype : dtype, optional + dtype : {None, dtype}, optional data type of the returned array. If `None`, the default data type is inferred from the "kind" of the input array data type. @@ -361,7 +361,7 @@ def cumulative_prod( axis in the output. Default: ``False``. - out : usm_ndarray, optional + out : {None, usm_ndarray}, optional the array into which the result is written. The data type of `out` must match the expected shape and the expected data type of the result or (if provided) `dtype`. @@ -412,7 +412,7 @@ def cumulative_logsumexp( ---------- x : usm_ndarray input array. - axis : int, optional + axis : {None, int}, optional axis along which cumulative logsumexp must be computed. If `None`, the logsumexp is computed over the entire array. If `x` is a one-dimensional array, providing an `axis` is optional; @@ -420,7 +420,7 @@ def cumulative_logsumexp( is required. Default: ``None``. - dtype : dtype, optional + dtype : {None, dtype}, optional data type of the returned array. If `None`, the default data type is inferred from the "kind" of the input array data type. @@ -448,7 +448,7 @@ def cumulative_logsumexp( in the output. Default: ``False``. - out : usm_ndarray, optional + out : {None, usm_ndarray}, optional the array into which the result is written. The data type of `out` must match the expected shape and the expected data type of the result or (if provided) `dtype`. diff --git a/dpnp/tensor/_array_api.py b/dpnp/tensor/_array_api.py index 9c78611245f..53774c18aa2 100644 --- a/dpnp/tensor/_array_api.py +++ b/dpnp/tensor/_array_api.py @@ -139,7 +139,7 @@ def default_dtypes(self, *, device=None): Parameters ---------- - device : {:class:`dpctl.SyclDevice`, :class:`dpctl.SyclQueue`, :class:`dpnp.tensor.Device`, str}, optional + device : {None, :class:`dpctl.SyclDevice`, :class:`dpctl.SyclQueue`, :class:`dpnp.tensor.Device`, str}, optional array API concept of device used in getting default data types. ``device`` can be ``None`` (in which case the default device is used), an instance of :class:`dpctl.SyclDevice`, an instance @@ -180,7 +180,7 @@ def dtypes(self, *, device=None, kind=None): Parameters ---------- - device : {:class:`dpctl.SyclDevice`, :class:`dpctl.SyclQueue`, :class:`dpnp.tensor.Device`, str}, optional + device : {None, :class:`dpctl.SyclDevice`, :class:`dpctl.SyclQueue`, :class:`dpnp.tensor.Device`, str}, optional array API concept of device used in getting default data types. ``device`` can be ``None`` (in which case the default device is used), an instance of :class:`dpctl.SyclDevice`, an instance of @@ -189,7 +189,7 @@ def dtypes(self, *, device=None, kind=None): a filter selector string. Default: ``None``. - kind : {str, Tuple[str, ...]}, optional + kind : {None, str, tuple of str}, optional data type kind. - if ``kind`` is ``None``, returns a dictionary of all data diff --git a/dpnp/tensor/_copy_utils.py b/dpnp/tensor/_copy_utils.py index af0843bcbf1..d956e4f9390 100644 --- a/dpnp/tensor/_copy_utils.py +++ b/dpnp/tensor/_copy_utils.py @@ -550,7 +550,7 @@ def from_numpy(np_ary, /, *, device=None, usm_type="device", sycl_queue=None): ---------- np_ary : array_like Input convertible to :class:`numpy.ndarray` - device : object, optional + device : {None, object}, optional array API specification of device where the output array is created. Device can be specified by a filter selector string, an instance of @@ -566,7 +566,7 @@ def from_numpy(np_ary, /, *, device=None, usm_type="device", sycl_queue=None): ``"shared"``, or ``"host"``. Default: ``"device"``. - sycl_queue : dpctl.SyclQueue, optional + sycl_queue : {None, dpctl.SyclQueue}, optional A SYCL queue that determines output array allocation device as well as execution placement of data movement operations. The ``device`` and ``sycl_queue`` arguments @@ -1106,7 +1106,7 @@ def astype( may be returned when possible. Default: ``True``. - device : object, optional + device : {None, object}, optional array API specification of device where the output array is created. Device can be specified by a filter selector string, an instance of diff --git a/dpnp/tensor/_ctors.py b/dpnp/tensor/_ctors.py index 901d290b628..7a5e76ff7ab 100644 --- a/dpnp/tensor/_ctors.py +++ b/dpnp/tensor/_ctors.py @@ -593,7 +593,7 @@ def arange( ---------- start : scalar Starting point of the interval - stop : scalar, optional + stop : {None, scalar}, optional Ending point of the interval. Default: ``None``. @@ -601,11 +601,11 @@ def arange( Increment of the returned sequence. Default: ``1``. - dtype : dtype, optional + dtype : {None, dtype}, optional Output array data type. Default: ``None``. - device : object, optional + device : {None, object}, optional array API concept of device where the output array is created. ``device`` can be ``None``, a oneAPI filter selector string, an instance of :class:`dpctl.SyclDevice` corresponding to @@ -614,11 +614,11 @@ def arange( returned by :attr:`dpnp.tensor.usm_ndarray.device`. Default: ``None``. - usm_type : {"device", "shared", "host"}, optional + usm_type : {None, "device", "shared", "host"}, optional The type of SYCL USM allocation for the output array. Default: ``"device"``. - sycl_queue : dpctl.SyclQueue, optional + sycl_queue : {None, dpctl.SyclQueue}, optional The SYCL queue to use for output array allocation and copying. ``sycl_queue`` and ``device`` are complementary arguments, i.e. use one or another. @@ -726,13 +726,13 @@ def asarray( of :class:`numpy.ndarray`, an object supporting Python buffer protocol, a Python scalar, or a (possibly nested) sequence of Python scalars. - dtype : dtype, optional + dtype : {None, dtype}, optional output array data type. If ``dtype`` is ``None``, the output array data type is inferred from data types in ``obj``. Default: ``None``. - copy : bool, optional + copy : {None, bool}, optional boolean indicating whether or not to copy the input. If ``True``, always creates a copy. If ``False``, the need to copy raises :exc:`ValueError`. If ``None``, tries to reuse @@ -744,7 +744,7 @@ def asarray( memory layout of the output array. Default: ``"K"``. - device : object, optional + device : {None, object}, optional array API concept of device where the output array is created. ``device`` can be ``None``, a oneAPI filter selector string, an instance of :class:`dpctl.SyclDevice` corresponding to @@ -753,11 +753,11 @@ def asarray( returned by :attr:`dpnp.tensor.usm_ndarray.device`. Default: ``None``. - usm_type : {"device", "shared", "host"}, optional + usm_type : {None, "device", "shared", "host"}, optional The type of SYCL USM allocation for the output array. Default: ``"device"``. - sycl_queue : dpctl.SyclQueue, optional + sycl_queue : {None, dpctl.SyclQueue}, optional The SYCL queue to use for output array allocation and copying. ``sycl_queue`` and ``device`` are complementary arguments, i.e. use one or another. @@ -937,7 +937,7 @@ def empty( ---------- shape : {int, tuple of ints} Dimensions of the array to be created. - dtype : dtype, optional + dtype : {None, dtype}, optional data type of the array. Can be typestring, a :class:`numpy.dtype` object, :mod:`numpy` char string, or a NumPy scalar type. The ``None`` value creates an @@ -948,7 +948,7 @@ def empty( memory layout for the array. Default: ``"C"``. - device : object, optional + device : {None, object}, optional array API concept of device where the output array is created. ``device`` can be ``None``, a oneAPI filter selector string, an instance of :class:`dpctl.SyclDevice` corresponding to @@ -957,11 +957,11 @@ def empty( returned by :attr:`dpnp.tensor.usm_ndarray.device`. Default: ``None``. - usm_type : {"device", "shared", "host"}, optional + usm_type : {None, "device", "shared", "host"}, optional The type of SYCL USM allocation for the output array. Default: ``"device"``. - sycl_queue : dpctl.SyclQueue, optional + sycl_queue : {None, dpctl.SyclQueue}, optional The SYCL queue to use for output array allocation and copying. ``sycl_queue`` and ``device`` are complementary arguments, i.e. use one or another. @@ -1009,7 +1009,7 @@ def empty_like( ---------- x : usm_ndarray Input array from which to derive the output array shape. - dtype : dtype, optional + dtype : {None, dtype}, optional data type of the array. Can be a typestring, a :class:`numpy.dtype` object, NumPy char string, or a NumPy scalar type. @@ -1019,7 +1019,7 @@ def empty_like( memory layout for the array. Default: ``"K"``. - device : object, optional + device : {None, object}, optional array API concept of device where the output array is created. ``device`` can be ``None``, a oneAPI filter selector string, an instance of :class:`dpctl.SyclDevice` corresponding to @@ -1028,11 +1028,11 @@ def empty_like( returned by :attr:`dpnp.tensor.usm_ndarray.device`. Default: ``None``. - usm_type : {"device", "shared", "host"}, optional + usm_type : {None, "device", "shared", "host"}, optional The type of SYCL USM allocation for the output array. Default: ``"device"``. - sycl_queue : dpctl.SyclQueue, optional + sycl_queue : {None, dpctl.SyclQueue}, optional The SYCL queue to use for output array allocation and copying. ``sycl_queue`` and ``device`` are complementary arguments, i.e. use one or another. @@ -1107,7 +1107,7 @@ def eye( ---------- n_rows : int number of rows in the output array. - n_cols : int, optional + n_cols : {None, int}, optional number of columns in the output array. If ``None``, ``n_cols = n_rows``. @@ -1119,7 +1119,7 @@ def eye( Raises :exc:`TypeError` if ``k`` is not an integer. Default: ``0``. - dtype : dtype, optional + dtype : {None, dtype}, optional data type of the array. Can be typestring, a :class:`numpy.dtype` object, :mod:`numpy` char string, or a NumPy scalar type. @@ -1129,7 +1129,7 @@ def eye( memory layout for the array. Default: ``"C"``. - device : object, optional + device : {None, object}, optional array API concept of device where the output array is created. ``device`` can be ``None``, a oneAPI filter selector string, an instance of :class:`dpctl.SyclDevice` corresponding to @@ -1138,11 +1138,11 @@ def eye( returned by :attr:`dpnp.tensor.usm_ndarray.device`. Default: ``None``. - usm_type : {"device", "shared", "host"}, optional + usm_type : {None, "device", "shared", "host"}, optional The type of SYCL USM allocation for the output array. Default: ``"device"``. - sycl_queue : dpctl.SyclQueue, optional + sycl_queue : {None, dpctl.SyclQueue}, optional The SYCL queue to use for output array allocation and copying. ``sycl_queue`` and ``device`` are complementary arguments, i.e. use one or another. @@ -1226,7 +1226,7 @@ def full( Dimensions of the array to be created. fill_value : {int, float, complex, usm_ndarray} fill value - dtype : dtype, optional + dtype : {None, dtype}, optional data type of the array. Can be typestring, a :class:`numpy.dtype` object, :mod:`numpy` char string, or a NumPy scalar type. @@ -1236,7 +1236,7 @@ def full( memory layout for the array. Default: ``"C"``. - device : object, optional + device : {None, object}, optional array API concept of device where the output array is created. ``device`` can be ``None``, a oneAPI filter selector string, an instance of :class:`dpctl.SyclDevice` corresponding to @@ -1245,11 +1245,11 @@ def full( returned by :attr:`dpnp.tensor.usm_ndarray.device`. Default: ``None``. - usm_type : {"device", "shared", "host"}, optional + usm_type : {None, "device", "shared", "host"}, optional The type of SYCL USM allocation for the output array. Default: ``"device"``. - sycl_queue : dpctl.SyclQueue, optional + sycl_queue : {None, dpctl.SyclQueue}, optional The SYCL queue to use for output array allocation and copying. ``sycl_queue`` and ``device`` are complementary arguments, i.e. use one or another. @@ -1337,7 +1337,7 @@ def full_like( shape. fill_value : scalar the value to fill output array with - dtype : dtype, optional + dtype : {None, dtype}, optional data type of the array. Can be typestring, a :class:`numpy.dtype` object, :mod:`numpy` char string, or a NumPy scalar type. If ``dtype`` is ``None``, the output array data @@ -1348,7 +1348,7 @@ def full_like( memory layout for the array. Default: ``"K"``. - device : object, optional + device : {None, object}, optional array API concept of device where the output array is created. ``device`` can be ``None``, a oneAPI filter selector string, an instance of :class:`dpctl.SyclDevice` corresponding to @@ -1357,11 +1357,11 @@ def full_like( returned by :attr:`dpnp.tensor.usm_ndarray.device`. Default: ``None``. - usm_type : {"device", "shared", "host"}, optional + usm_type : {None, "device", "shared", "host"}, optional The type of SYCL USM allocation for the output array. Default: ``"device"``. - sycl_queue : dpctl.SyclQueue, optional + sycl_queue : {None, dpctl.SyclQueue}, optional The SYCL queue to use for output array allocation and copying. ``sycl_queue`` and ``device`` are complementary arguments, i.e. use one or another. @@ -1478,13 +1478,13 @@ def linspace( num : int number of samples. Must be a non-negative integer; otherwise, the function raises ``ValueError`` exception. - dtype : dtype, optional + dtype : {None, dtype}, optional output array data type. Should be a floating data type. If ``dtype`` is ``None``, the output array must be the default floating point data type for target device. Default: ``None``. - device : object, optional + device : {None, object}, optional array API concept of device where the output array is created. ``device`` can be ``None``, a oneAPI filter selector string, an instance of :class:`dpctl.SyclDevice` corresponding to @@ -1493,11 +1493,11 @@ def linspace( returned by :attr:`dpnp.tensor.usm_ndarray.device`. Default: ``None``. - usm_type : {"device", "shared", "host"}, optional + usm_type : {None, "device", "shared", "host"}, optional The type of SYCL USM allocation for the output array. Default: ``"device"``. - sycl_queue : dpctl.SyclQueue, optional + sycl_queue : {None, dpctl.SyclQueue}, optional The SYCL queue to use for output array allocation and copying. ``sycl_queue`` and ``device`` are complementary arguments, i.e. use one or another. @@ -1656,7 +1656,7 @@ def ones( ---------- shape : {int, tuple of ints} Dimensions of the array to be created. - dtype : dtype, optional + dtype : {None, dtype}, optional data type of the array. Can be typestring, a :class:`numpy.dtype` object, :mod:`numpy` char string, or a NumPy scalar type. @@ -1666,7 +1666,7 @@ def ones( memory layout for the array. Default: ``"C"``. - device : object, optional + device : {None, object}, optional array API concept of device where the output array is created. ``device`` can be ``None``, a oneAPI filter selector string, an instance of :class:`dpctl.SyclDevice` corresponding to @@ -1675,11 +1675,11 @@ def ones( returned by :attr:`dpnp.tensor.usm_ndarray.device`. Default: ``None``. - usm_type : {"device", "shared", "host"}, optional + usm_type : {None, "device", "shared", "host"}, optional The type of SYCL USM allocation for the output array. Default: ``"device"``. - sycl_queue : dpctl.SyclQueue, optional + sycl_queue : {None, dpctl.SyclQueue}, optional The SYCL queue to use for output array allocation and copying. ``sycl_queue`` and ``device`` are complementary arguments, i.e. use one or another. @@ -1730,7 +1730,7 @@ def ones_like( ---------- x : usm_ndarray Input array from which to derive the output array shape. - dtype : dtype, optional + dtype : {None, dtype}, optional data type of the array. Can be typestring, a :class:`numpy.dtype` object, :mod:`numpy` char string, or a NumPy scalar type. @@ -1740,7 +1740,7 @@ def ones_like( memory layout for the array. Default: ``"K"``. - device : object, optional + device : {None, object}, optional array API concept of device where the output array is created. ``device`` can be ``None``, a oneAPI filter selector string, an instance of :class:`dpctl.SyclDevice` corresponding to @@ -1749,11 +1749,11 @@ def ones_like( returned by :attr:`dpnp.tensor.usm_ndarray.device`. Default: ``None``. - usm_type : {"device", "shared", "host"}, optional + usm_type : {None, "device", "shared", "host"}, optional The type of SYCL USM allocation for the output array. Default: ``None``. - sycl_queue : dpctl.SyclQueue, optional + sycl_queue : {None, dpctl.SyclQueue}, optional The SYCL queue to use for output array allocation and copying. ``sycl_queue`` and ``device`` are complementary arguments, i.e. use one or another. @@ -1995,7 +1995,7 @@ def zeros( ---------- shape : {int, tuple of ints} Dimensions of the array to be created. - dtype : dtype, optional + dtype : {None, dtype}, optional data type of the array. Can be typestring, a :class:`numpy.dtype` object, :mod:`numpy` char string, or a NumPy scalar type. @@ -2005,7 +2005,7 @@ def zeros( memory layout for the array. Default: ``"C"``. - device : object, optional + device : {None, object}, optional array API concept of device where the output array is created. ``device`` can be ``None``, a oneAPI filter selector string, an instance of :class:`dpctl.SyclDevice` corresponding to @@ -2014,11 +2014,11 @@ def zeros( returned by :attr:`dpnp.tensor.usm_ndarray.device`. Default: ``None``. - usm_type : {"device", "shared", "host"}, optional + usm_type : {None, "device", "shared", "host"}, optional The type of SYCL USM allocation for the output array. Default: ``"device"``. - sycl_queue : dpctl.SyclQueue, optional + sycl_queue : {None, dpctl.SyclQueue}, optional The SYCL queue to use for output array allocation and copying. ``sycl_queue`` and ``device`` are complementary arguments, i.e. use one or another. @@ -2072,7 +2072,7 @@ def zeros_like( x : usm_ndarray Input array from which to derive the shape of the output array. - dtype : dtype, optional + dtype : {None, dtype}, optional data type of the array. Can be typestring, a :class:`numpy.dtype` object, :mod:`numpy` char string, or a NumPy scalar type. If ``None``, output array has the same data @@ -2083,7 +2083,7 @@ def zeros_like( memory layout for the array. Default: ``"K"``. - device : object, optional + device : {None, object}, optional array API concept of device where the output array is created. ``device`` can be ``None``, a oneAPI filter selector string, an instance of :class:`dpctl.SyclDevice` corresponding to @@ -2092,11 +2092,11 @@ def zeros_like( returned by :attr:`dpnp.tensor.usm_ndarray.device`. Default: ``None``. - usm_type : {"device", "shared", "host"}, optional + usm_type : {None, "device", "shared", "host"}, optional The type of SYCL USM allocation for the output array. Default: ``None``. - sycl_queue : dpctl.SyclQueue, optional + sycl_queue : {None, dpctl.SyclQueue}, optional The SYCL queue to use for output array allocation and copying. ``sycl_queue`` and ``device`` are complementary arguments, i.e. use one or another. diff --git a/dpnp/tensor/_device.py b/dpnp/tensor/_device.py index c8490b7331e..4223f205c80 100644 --- a/dpnp/tensor/_device.py +++ b/dpnp/tensor/_device.py @@ -161,14 +161,14 @@ def normalize_queue_device(sycl_queue=None, device=None): Parameters ---------- - sycl_queue : dpctl.SyclQueue, optional + sycl_queue : {None, dpctl.SyclQueue}, optional explicitly indicates where USM allocation is done and the population code (if any) is executed. Value ``None`` is interpreted as get the SYCL queue from ``device`` keyword, or use default queue. Default: ``None``. - device : {str, dpctl.SyclDevice, dpctl.SyclQueue, dpnp.tensor.Device}, optional + device : {None, str, dpctl.SyclDevice, dpctl.SyclQueue, dpnp.tensor.Device}, optional array-API keyword indicating non-partitioned SYCL device where array is allocated. diff --git a/dpnp/tensor/_elementwise_common.py b/dpnp/tensor/_elementwise_common.py index e40e24630c4..f44e7d72d69 100644 --- a/dpnp/tensor/_elementwise_common.py +++ b/dpnp/tensor/_elementwise_common.py @@ -77,7 +77,7 @@ class UnaryElementwiseFunc: computational tasks complete execution, while the second event corresponds to computational tasks associated with function evaluation. - acceptance_fn : callable, optional + acceptance_fn : {None, callable}, optional Function to influence type promotion behavior of this unary function. The function takes 4 arguments: @@ -326,7 +326,7 @@ class BinaryElementwiseFunc: evaluation. docs : str Documentation string for the unary function. - binary_inplace_fn : callable, optional + binary_inplace_fn : {None, callable}, optional Data-parallel implementation function with signature ``impl_fn(src: usm_ndarray, dst: usm_ndarray, sycl_queue: SyclQueue, depends: Optional[List[SyclEvent]])`` @@ -340,7 +340,7 @@ class BinaryElementwiseFunc: associated with function evaluation. Default: ``None``. - acceptance_fn : callable, optional + acceptance_fn : {None, callable}, optional Function to influence type promotion behavior of this binary function. The function takes 6 arguments: diff --git a/dpnp/tensor/_indexing_functions.py b/dpnp/tensor/_indexing_functions.py index 85e3a797b69..fa46cacb694 100644 --- a/dpnp/tensor/_indexing_functions.py +++ b/dpnp/tensor/_indexing_functions.py @@ -219,7 +219,7 @@ def put(x, indices, vals, /, *, axis=None, mode="wrap"): Array of values to be put into ``x``. Must be broadcastable to the result shape ``x.shape[:axis] + indices.shape + x.shape[axis+1:]``. - axis : int, optional + axis : {None, int}, optional The axis along which the values will be placed. If ``x`` is one-dimensional, this argument is optional. @@ -459,7 +459,7 @@ def take(x, indices, /, *, axis=None, out=None, mode="wrap"): The array that elements will be taken from. indices : usm_ndarray One-dimensional array of indices. - axis : int, optional + axis : {None, int}, optional The axis along which the values will be selected. If ``x`` is one-dimensional, this argument is optional. diff --git a/dpnp/tensor/_reduction.py b/dpnp/tensor/_reduction.py index 6444fa05ee7..1ea52ab79dc 100644 --- a/dpnp/tensor/_reduction.py +++ b/dpnp/tensor/_reduction.py @@ -407,7 +407,7 @@ def argmax(x, /, *, axis=None, keepdims=False, out=None): ---------- x : usm_ndarray Input array. - axis : int, optional + axis : {None, int}, optional Axis along which to search. If ``None``, returns the index of the maximum value of the flattened array. @@ -453,7 +453,7 @@ def argmin(x, /, *, axis=None, keepdims=False, out=None): ---------- x : usm_ndarray Input array. - axis : int, optional + axis : {None, int}, optional Axis along which to search. If ``None``, returns the index of the minimum value of the flattened array. @@ -554,7 +554,7 @@ def logsumexp(x, /, *, axis=None, dtype=None, keepdims=False, out=None): If ``None``, the result is computed over the entire array. Default: ``None``. - dtype : dtype, optional + dtype : {None, dtype}, optional Data type of the returned array. If ``None``, the default data type is inferred from the "kind" of the input array data type. @@ -709,7 +709,7 @@ def prod(x, /, *, axis=None, dtype=None, keepdims=False, out=None): If ``None``, the product is computed over the entire array. Default: ``None``. - dtype : dtype, optional + dtype : {None, dtype}, optional Data type of the returned array. If ``None``, the default data type is inferred from the "kind" of the input array data type. @@ -784,7 +784,7 @@ def reduce_hypot(x, /, *, axis=None, dtype=None, keepdims=False, out=None): If ``None``, the result is computed over the entire array. Default: ``None``. - dtype : dtype, optional + dtype : {None, dtype}, optional Data type of the returned array. If ``None``, the default data type is inferred from the "kind" of the input array data type. @@ -855,7 +855,7 @@ def sum(x, /, *, axis=None, dtype=None, keepdims=False, out=None): If ``None``, the sum is computed over the entire array. Default: ``None``. - dtype : dtype, optional + dtype : {None, dtype}, optional Data type of the returned array. If ``None``, the default data type is inferred from the "kind" of the input array data type. From dc3a6c01b409fd7539e32ac14cf6cf32b335b627 Mon Sep 17 00:00:00 2001 From: Vladislav Perevezentsev Date: Thu, 11 Jun 2026 05:50:32 -0700 Subject: [PATCH 32/46] Fix typos in dpnp.tensor docs --- dpnp/tensor/_accumulation.py | 2 +- dpnp/tensor/_elementwise_funcs.py | 12 ++++++------ dpnp/tensor/_manipulation_functions.py | 6 +++--- dpnp/tensor/_usmarray.pyx | 2 +- 4 files changed, 11 insertions(+), 11 deletions(-) diff --git a/dpnp/tensor/_accumulation.py b/dpnp/tensor/_accumulation.py index bbc64b3afb6..930b93e3942 100644 --- a/dpnp/tensor/_accumulation.py +++ b/dpnp/tensor/_accumulation.py @@ -406,7 +406,7 @@ def cumulative_logsumexp( x, /, *, axis=None, dtype=None, include_initial=False, out=None ): """ - Calculates the cumulative logsmumexp of elements in the input array `x`. + Calculates the cumulative logsumexp of elements in the input array `x`. Parameters ---------- diff --git a/dpnp/tensor/_elementwise_funcs.py b/dpnp/tensor/_elementwise_funcs.py index 4c935d12eb8..0f85e39af72 100644 --- a/dpnp/tensor/_elementwise_funcs.py +++ b/dpnp/tensor/_elementwise_funcs.py @@ -2376,7 +2376,7 @@ Input array, expected to have a real-valued floating-point data type. out : {None, usm_ndarray}, optional Output array to populate. - Array have the correct shape and the expected data type. + Array must have the correct shape and the expected data type. Default: ``None``. order : {"C", "F", "A", "K"}, optional @@ -2411,7 +2411,7 @@ Input array, expected to have a floating-point data type. out : {None, usm_ndarray}, optional Output array to populate. - Array have the correct shape and the expected data type. + Array must have the correct shape and the expected data type. Default: ``None``. order : {"C", "F", "A", "K"}, optional @@ -2450,7 +2450,7 @@ data type. out : {None, usm_ndarray}, optional Output array to populate. - Array have the correct shape and the expected data type. + Array must have the correct shape and the expected data type. Default: ``None``. order : {"C", "F", "A", "K"}, optional @@ -2485,7 +2485,7 @@ Input array, expected to have a real-valued floating-point data type. out : {None, usm_ndarray}, optional Output array to populate. - Array have the correct shape and the expected data type. + Array must have the correct shape and the expected data type. Default: ``None``. order : {"C", "F", "A", "K"}, optional @@ -2585,7 +2585,7 @@ Input array, expected to have a floating-point data type. out : {None, usm_ndarray}, optional Output array to populate. - Array have the correct shape and the expected data type. + Array must have the correct shape and the expected data type. Default: ``None``. order : {"C", "F", "A", "K"}, optional @@ -2624,7 +2624,7 @@ Input array, expected to have a complex floating-point data type. out : {None, usm_ndarray}, optional Output array to populate. - Array have the correct shape and the expected data type. + Array must have the correct shape and the expected data type. Default: ``None``. order : {"C", "F", "A", "K"}, optional diff --git a/dpnp/tensor/_manipulation_functions.py b/dpnp/tensor/_manipulation_functions.py index f094f461273..e84777750cc 100644 --- a/dpnp/tensor/_manipulation_functions.py +++ b/dpnp/tensor/_manipulation_functions.py @@ -483,7 +483,7 @@ def moveaxis(X, source, destination, /): ------- out : usm_ndarray Array with moved axes. - The returned array must has the same data type as `x`, + The returned array has the same data type as `x`, is created on the same device as `x` and has the same USM allocation type as `x`. @@ -533,7 +533,7 @@ def permute_dims(X, /, axes): ------- out : usm_ndarray An array with permuted axes. - The returned array must has the same data type as `x`, + The returned array has the same data type as `x`, is created on the same device as `x` and has the same USM allocation type as `x`. @@ -1015,7 +1015,7 @@ def swapaxes(X, axis1, axis2): ------- out : usm_ndarray Array with swapped axes. - The returned array must has the same data type as `x`, + The returned array has the same data type as `x`, is created on the same device as `x` and has the same USM allocation type as `x`. diff --git a/dpnp/tensor/_usmarray.pyx b/dpnp/tensor/_usmarray.pyx index cc1e9bbf684..d0c433ea0e6 100644 --- a/dpnp/tensor/_usmarray.pyx +++ b/dpnp/tensor/_usmarray.pyx @@ -814,7 +814,7 @@ cdef class usm_ndarray: For example, for strides ``(s1, s2, s3)`` and multi-index ``(i1, i2, i3)`` position of the respective element relative - to zero multi-index element is ``s1*s1 + s2*i2 + s3*i3``. + to zero multi-index element is ``s1*i1 + s2*i2 + s3*i3``. Examples -------- From 7d11958cf87363188162d02e490470b8add57660 Mon Sep 17 00:00:00 2001 From: Vladislav Perevezentsev Date: Thu, 11 Jun 2026 05:55:00 -0700 Subject: [PATCH 33/46] Fix wrong rST roles --- dpnp/tensor/_compute_follows_data.pyx | 4 ++-- dpnp/tensor/_copy_utils.py | 2 +- dpnp/tensor/_ctors.py | 2 +- dpnp/tensor/_dlpack.pyx | 6 +++--- dpnp/tensor/_flags.pyx | 2 +- dpnp/tensor/_manipulation_functions.py | 2 +- dpnp/tensor/_type_utils.py | 5 ++--- 7 files changed, 11 insertions(+), 12 deletions(-) diff --git a/dpnp/tensor/_compute_follows_data.pyx b/dpnp/tensor/_compute_follows_data.pyx index 975f52b4cee..44287770ae5 100644 --- a/dpnp/tensor/_compute_follows_data.pyx +++ b/dpnp/tensor/_compute_follows_data.pyx @@ -52,7 +52,7 @@ class ExecutionPlacementError(Exception): Make sure that input arrays are associated with the same :class:`dpctl.SyclQueue`, or migrate data to the same :class:`dpctl.SyclQueue` using - :meth:`dpctl.tensor.usm_ndarray.to_device` method. + :meth:`dpnp.tensor.usm_ndarray.to_device` method. """ pass @@ -185,7 +185,7 @@ def validate_usm_type(usm_type, /, *, allow_none=True): allow_none : bool, optional Whether ``usm_type`` value of ``None`` is considered valid. - Default: `True`. + Default: ``True``. Raises ------ diff --git a/dpnp/tensor/_copy_utils.py b/dpnp/tensor/_copy_utils.py index d956e4f9390..1ba5d0af6d4 100644 --- a/dpnp/tensor/_copy_utils.py +++ b/dpnp/tensor/_copy_utils.py @@ -96,7 +96,7 @@ def _copy_from_numpy(np_ary, usm_type="device", sycl_queue=None): def _copy_from_numpy_into(dst, np_ary): - """Copies `np_ary` into `dst` of type :class:`dpnp.tensor.usm_ndarray""" + """Copies `np_ary` into `dst` of type :class:`dpnp.tensor.usm_ndarray`.""" if not isinstance(np_ary, np.ndarray): raise TypeError(f"Expected numpy.ndarray, got {type(np_ary)}") if not isinstance(dst, dpt.usm_ndarray): diff --git a/dpnp/tensor/_ctors.py b/dpnp/tensor/_ctors.py index 7a5e76ff7ab..68b36e52efe 100644 --- a/dpnp/tensor/_ctors.py +++ b/dpnp/tensor/_ctors.py @@ -45,7 +45,7 @@ from ._device import normalize_queue_device from ._usmarray import _is_object_with_buffer_protocol -__doc__ = "Implementation of creation functions in :module:`dpnp.tensor`" +__doc__ = "Implementation of creation functions in :mod:`dpnp.tensor`" _empty_tuple = () _host_set = frozenset([None]) diff --git a/dpnp/tensor/_dlpack.pyx b/dpnp/tensor/_dlpack.pyx index ecc396f609b..b652a45daa2 100644 --- a/dpnp/tensor/_dlpack.pyx +++ b/dpnp/tensor/_dlpack.pyx @@ -146,16 +146,16 @@ cdef extern from "dlpack/dlpack.h" nogil: def get_build_dlpack_version(): """ Returns a tuple of integers representing the ``major`` and ``minor`` - version of DLPack :module:`dpnp.tensor` was built with. + version of DLPack :mod:`dpnp.tensor` was built with. This tuple can be passed as the ``max_version`` argument to - ``__dlpack__`` to guarantee :module:`dpnp.tensor` can properly + ``__dlpack__`` to guarantee :mod:`dpnp.tensor` can properly consume capsule. Returns ------- out : tuple of ints A tuple of integers representing the ``major`` and ``minor`` - version of DLPack used to build :module:`dpnp.tensor`. + version of DLPack used to build :mod:`dpnp.tensor`. """ diff --git a/dpnp/tensor/_flags.pyx b/dpnp/tensor/_flags.pyx index 0f3a0e4c73d..55f6cb3d152 100644 --- a/dpnp/tensor/_flags.pyx +++ b/dpnp/tensor/_flags.pyx @@ -132,7 +132,7 @@ cdef class Flags: """ True if the memory layout of the :class:`dpnp.tensor.usm_ndarray` instance is C-contiguous and F-contiguous. - Equivalent to `forc.` + Equivalent to ``forc``. """ return self.forc diff --git a/dpnp/tensor/_manipulation_functions.py b/dpnp/tensor/_manipulation_functions.py index e84777750cc..eefe5d47e71 100644 --- a/dpnp/tensor/_manipulation_functions.py +++ b/dpnp/tensor/_manipulation_functions.py @@ -40,7 +40,7 @@ __doc__ = ( "Implementation module for array manipulation " - "functions in :module:`dpnp.tensor`" + "functions in :mod:`dpnp.tensor`" ) diff --git a/dpnp/tensor/_type_utils.py b/dpnp/tensor/_type_utils.py index d45aacfa30d..7eb5918dc13 100644 --- a/dpnp/tensor/_type_utils.py +++ b/dpnp/tensor/_type_utils.py @@ -900,9 +900,8 @@ def isdtype(dtype, kind): Returns a boolean indicating whether a provided `dtype` is of a specified data type `kind`. - See [array API](array_api) for more information. - - [array_api]: https://data-apis.org/array-api/latest/ + See `array API `_ for more + information. Parameters ---------- From b9726ae6af08652f5df9f171ad572360a5c76901 Mon Sep 17 00:00:00 2001 From: Vladislav Perevezentsev Date: Thu, 11 Jun 2026 05:56:42 -0700 Subject: [PATCH 34/46] Replace dpctl.tensor with dpnp.tensor --- dpnp/tensor/_ctors.py | 2 +- dpnp/tensor/_device.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/dpnp/tensor/_ctors.py b/dpnp/tensor/_ctors.py index 68b36e52efe..707f5bcc98f 100644 --- a/dpnp/tensor/_ctors.py +++ b/dpnp/tensor/_ctors.py @@ -1560,7 +1560,7 @@ def linspace( def meshgrid(*arrays, indexing="xy"): """ - Creates tuple of :class:`dpctl.tensor.usm_ndarray` coordinate matrices + Creates tuple of :class:`dpnp.tensor.usm_ndarray` coordinate matrices from vectors. Parameters diff --git a/dpnp/tensor/_device.py b/dpnp/tensor/_device.py index 4223f205c80..1c4a575d9cd 100644 --- a/dpnp/tensor/_device.py +++ b/dpnp/tensor/_device.py @@ -42,7 +42,7 @@ class Device: This is a wrapper around :class:`dpctl.SyclQueue` with custom formatting. The class does not have public constructor, - but a class method :meth:`dpctl.tensor.Device.create_device` to construct + but a class method :meth:`dpnp.tensor.Device.create_device` to construct it from `device` keyword argument in Array-API functions. Instance can be queried for ``sycl_queue``, ``sycl_context``, From 92e26db089afcd32c2b940144b228007e6fd2ca1 Mon Sep 17 00:00:00 2001 From: Vladislav Perevezentsev Date: Thu, 11 Jun 2026 05:58:23 -0700 Subject: [PATCH 35/46] Remove redundant signature lines --- dpnp/tensor/_elementwise_funcs.py | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/dpnp/tensor/_elementwise_funcs.py b/dpnp/tensor/_elementwise_funcs.py index 0f85e39af72..1db8c622af4 100644 --- a/dpnp/tensor/_elementwise_funcs.py +++ b/dpnp/tensor/_elementwise_funcs.py @@ -974,8 +974,6 @@ # U14: ==== EXPM1 (x) _expm1_docstring = r""" -expm1(x, /, \*, out=None, order='K') - Computes the exponential minus 1 for each element `x_i` of input array `x`. This function calculates `exp(x) - 1.0` more accurately for small values of `x`. @@ -1294,8 +1292,6 @@ # U21: ==== LOG1P (x) _log1p_docstring = r""" -log1p(x, /, \*, out=None, order='K') - Computes the natural logarithm of (1 + `x`) for each element `x_i` of input array `x`. @@ -1331,8 +1327,6 @@ # U22: ==== LOG2 (x) _log2_docstring_ = r""" -log2(x, /, \*, out=None, order='K') - Computes the base-2 logarithm for each element `x_i` of input array `x`. Parameters @@ -1366,8 +1360,6 @@ # U23: ==== LOG10 (x) _log10_docstring_ = r""" -log10(x, /, \*, out=None, order='K') - Computes the base-10 logarithm for each element `x_i` of input array `x`. Parameters @@ -2401,8 +2393,6 @@ # U38: ==== EXP2 (x) _exp2_docstring_ = r""" -exp2(x, /, \*, out=None, order='K') - Computes the base-2 exponential for each element `x_i` for input array `x`. Parameters From 7233403d7efcde0428300dfc2b2425832e21e6d3 Mon Sep 17 00:00:00 2001 From: Vladislav Perevezentsev Date: Thu, 11 Jun 2026 06:02:04 -0700 Subject: [PATCH 36/46] Fix parameter name mismatches --- dpnp/tensor/_dlpack.pyx | 16 ++++++++-------- dpnp/tensor/_elementwise_common.py | 4 ++-- dpnp/tensor/_print.py | 8 ++++---- 3 files changed, 14 insertions(+), 14 deletions(-) diff --git a/dpnp/tensor/_dlpack.pyx b/dpnp/tensor/_dlpack.pyx index b652a45daa2..ac9e40734bb 100644 --- a/dpnp/tensor/_dlpack.pyx +++ b/dpnp/tensor/_dlpack.pyx @@ -765,14 +765,14 @@ class _numpy_array_interface_wrapper: Implementation taken from https://github.com/dmlc/dlpack/blob/main/apps/numpy_dlpack/dlpack/to_numpy.py - Args: - array_interface: - A dictionary describing the underlying memory. Formatted - to match `numpy.ndarray.__array_interface__`. - - pycapsule: - A Python capsule wrapping the dlpack tensor that will be - converted to numpy. + Parameters + ---------- + array_interface : dict + A dictionary describing the underlying memory. Formatted + to match ``numpy.ndarray.__array_interface__``. + memory_owner : object + A Python capsule wrapping the dlpack tensor that will be + converted to numpy. """ def __init__(self, array_interface, memory_owner) -> None: diff --git a/dpnp/tensor/_elementwise_common.py b/dpnp/tensor/_elementwise_common.py index f44e7d72d69..6bf3b60b6ba 100644 --- a/dpnp/tensor/_elementwise_common.py +++ b/dpnp/tensor/_elementwise_common.py @@ -58,7 +58,7 @@ class UnaryElementwiseFunc: ---------- name : str Name of the unary function. - result_type_resovler_fn : callable + result_type_resolver_fn : callable Function that takes dtype of the input and returns the dtype of the result if the implementation functions supports it, or @@ -305,7 +305,7 @@ class BinaryElementwiseFunc: ---------- name : str Name of the unary function. - result_type_resovle_fn : callable + result_type_resolver_fn : callable Function that takes dtypes of the input and returns the dtype of the result if the implementation functions supports it, or diff --git a/dpnp/tensor/_print.py b/dpnp/tensor/_print.py index 5c77dcf54d0..5dc90aa0359 100644 --- a/dpnp/tensor/_print.py +++ b/dpnp/tensor/_print.py @@ -140,10 +140,10 @@ def set_print_options( Raises `TypeError` if linewidth is not an integer. Default: ``75``. - edgeitems : int, optional + edge_items : int, optional Number of elements at the beginning and end when the printed array is abbreviated. - Raises `TypeError` if edgeitems is not an integer. + Raises `TypeError` if edge_items is not an integer. Default: ``3``. threshold : int, optional @@ -343,10 +343,10 @@ def usm_ndarray_str( Raises `TypeError` if line_width is not an integer. Default: ``75``. - edgeitems : int, optional + edge_items : int, optional Number of elements at the beginning and end when the printed array is abbreviated. - Raises `TypeError` if edgeitems is not an integer. + Raises `TypeError` if edge_items is not an integer. Default: ``3``. threshold : int, optional From 99a57f93133a7184dd8200422e3f9173043d9451 Mon Sep 17 00:00:00 2001 From: Vladislav Perevezentsev Date: Thu, 11 Jun 2026 06:06:23 -0700 Subject: [PATCH 37/46] Small update _usmarray.pyx to Sphinx format --- dpnp/tensor/_usmarray.pyx | 77 ++++++++++++++++++++++++++------------- 1 file changed, 51 insertions(+), 26 deletions(-) diff --git a/dpnp/tensor/_usmarray.pyx b/dpnp/tensor/_usmarray.pyx index d0c433ea0e6..af5456c8b32 100644 --- a/dpnp/tensor/_usmarray.pyx +++ b/dpnp/tensor/_usmarray.pyx @@ -1888,19 +1888,30 @@ cdef api object UsmNDArray_MakeSimpleFromMemory( ): """Create contiguous usm_ndarray. - Args: - nd: number of dimensions (non-negative) - shape: array of nd non-negative array's sizes along each dimension - typenum: array elemental type number - ptr: pointer to the start of allocation - QRef: DPCTLSyclQueueRef associated with the allocation - offset: distance between element with zero multi-index and the - start of allocation - order: Memory layout of the array. Use 'C' for C-contiguous or - row-major layout; 'F' for F-contiguous or column-major layout - Returns: - Created usm_ndarray instance + Parameters + ---------- + nd : int + Number of dimensions (non-negative). + shape : pointer to Py_ssize_t + Array of ``nd`` non-negative sizes along each dimension. + typenum : int + Array elemental type number. + mobj : _Memory + USM memory object backing the array. + offset : Py_ssize_t + Distance between element with zero multi-index and the + start of allocation. + order : char + Memory layout of the array. Use ``'C'`` for C-contiguous or + row-major layout; ``'F'`` for F-contiguous or column-major layout. + + Returns + ------- + out : usm_ndarray + Created usm_ndarray instance. + """ + cdef object shape_tuple = _make_int_tuple(nd, shape) cdef usm_ndarray arr = usm_ndarray( shape_tuple, @@ -1962,21 +1973,35 @@ cdef api object UsmNDArray_MakeFromPtr( """ General usm_ndarray constructor from externally made USM-allocation. - Args: - nd: number of dimensions (non-negative) - shape: array of nd non-negative array's sizes along each dimension - typenum: array elemental type number - strides: array of nd strides along each dimension in elements - ptr: pointer to the start of allocation - QRef: DPCTLSyclQueueRef associated with the allocation - offset: distance between element with zero multi-index and the - start of allocation - owner: Python object managing lifetime of USM allocation. - Value None implies transfer of USM allocation ownership - to the created array object. - Returns: - Created usm_ndarray instance + Parameters + ---------- + nd : int + Number of dimensions (non-negative). + shape : pointer to Py_ssize_t + Array of ``nd`` non-negative sizes along each dimension. + typenum : int + Array elemental type number. + strides : pointer to Py_ssize_t + Array of ``nd`` strides along each dimension in elements. + ptr : DPCTLSyclUSMRef + Pointer to the start of USM allocation. + QRef : DPCTLSyclQueueRef + SYCL queue reference associated with the allocation. + offset : Py_ssize_t + Distance between element with zero multi-index and the + start of allocation. + owner : object + Python object managing lifetime of USM allocation. + Value ``None`` implies transfer of USM allocation ownership + to the created array object. + + Returns + ------- + out : usm_ndarray + Created usm_ndarray instance. + """ + cdef int itemsize = type_bytesize(typenum) cdef size_t nelems = 1 cdef Py_ssize_t min_disp = 0 From 306bcca41210b87477388d9fcce9b4c7912721f0 Mon Sep 17 00:00:00 2001 From: Vladislav Perevezentsev Date: Thu, 11 Jun 2026 06:12:34 -0700 Subject: [PATCH 38/46] Fix typos in dpnp.tensor docs(2) --- dpnp/tensor/_array_api.py | 2 +- dpnp/tensor/_compute_follows_data.pyx | 2 +- dpnp/tensor/_dlpack.pyx | 12 ++++++------ dpnp/tensor/_print.py | 4 ++-- 4 files changed, 10 insertions(+), 10 deletions(-) diff --git a/dpnp/tensor/_array_api.py b/dpnp/tensor/_array_api.py index 53774c18aa2..edbc68c020f 100644 --- a/dpnp/tensor/_array_api.py +++ b/dpnp/tensor/_array_api.py @@ -117,7 +117,7 @@ def capabilities(self): boolean indicating ``dpnp.tensor``'s support of data-dependent shapes. Value: ``True`` ``max dimensions``: - integer indication the maximum array dimension supported by ``dpnp.tensor``. + integer indicating the maximum array dimension supported by ``dpnp.tensor``. Value: ``None`` Returns diff --git a/dpnp/tensor/_compute_follows_data.pyx b/dpnp/tensor/_compute_follows_data.pyx index 44287770ae5..1c44a5e4ae3 100644 --- a/dpnp/tensor/_compute_follows_data.pyx +++ b/dpnp/tensor/_compute_follows_data.pyx @@ -114,7 +114,7 @@ def get_coerced_usm_type(usm_types, /): Returns ------- out : {str, None} - Type of USM allocation for the output arrays (s). + Type of USM allocation for the output array(s). ``None`` if any of the input strings are not recognized. """ diff --git a/dpnp/tensor/_dlpack.pyx b/dpnp/tensor/_dlpack.pyx index ac9e40734bb..0b882814b76 100644 --- a/dpnp/tensor/_dlpack.pyx +++ b/dpnp/tensor/_dlpack.pyx @@ -272,12 +272,12 @@ cpdef to_dlpack_capsule(usm_ndarray usm_ary): Raises ------ DLPackCreationError - when array can be represented as + when array cannot be represented as DLPack tensor. This may happen when array was allocated on a partitioned sycl device, or its USM allocation is not bound to the platform default SYCL context. MemoryError - when host allocation to needed for ``DLManagedTensor`` + when host allocation needed for ``DLManagedTensor`` did not succeed. ValueError when array elements data type could not be represented @@ -406,12 +406,12 @@ cpdef to_dlpack_versioned_capsule(usm_ndarray usm_ary, bint copied): Raises ------ DLPackCreationError - when array can be represented as + when array cannot be represented as DLPack tensor. This may happen when array was allocated on a partitioned sycl device, or its USM allocation is not bound to the platform default SYCL context. MemoryError - when host allocation to needed for + when host allocation needed for ``DLManagedTensorVersioned`` did not succeed. ValueError when array elements data type could not be represented @@ -559,10 +559,10 @@ cpdef numpy_to_dlpack_versioned_capsule(ndarray npy_ary, bint copied): Raises ------ DLPackCreationError - when array can be represented as + when array cannot be represented as DLPack tensor. MemoryError - when host allocation to needed for + when host allocation needed for ``DLManagedTensorVersioned`` did not succeed. ValueError when array elements data type could not be represented diff --git a/dpnp/tensor/_print.py b/dpnp/tensor/_print.py index 5dc90aa0359..4d6660f3fd6 100644 --- a/dpnp/tensor/_print.py +++ b/dpnp/tensor/_print.py @@ -140,10 +140,10 @@ def set_print_options( Raises `TypeError` if linewidth is not an integer. Default: ``75``. - edge_items : int, optional + edgeitems : int, optional Number of elements at the beginning and end when the printed array is abbreviated. - Raises `TypeError` if edge_items is not an integer. + Raises `TypeError` if edgeitems is not an integer. Default: ``3``. threshold : int, optional From 124386e8a9b57006ab6ee4a28a528726353160c8 Mon Sep 17 00:00:00 2001 From: Vladislav Perevezentsev Date: Fri, 10 Apr 2026 12:46:22 -0700 Subject: [PATCH 39/46] Update usm_ndarray docstrings --- dpnp/tensor/_usmarray.pyx | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/dpnp/tensor/_usmarray.pyx b/dpnp/tensor/_usmarray.pyx index af5456c8b32..259ef42b3b1 100644 --- a/dpnp/tensor/_usmarray.pyx +++ b/dpnp/tensor/_usmarray.pyx @@ -299,13 +299,15 @@ cdef class usm_ndarray: Default: ``None``. - ``buffer`` can be ``"shared"``, ``"host"``, ``"device"`` to allocate - new device memory by calling respective constructor with - the specified ``buffer_ctor_kwrds``; ``buffer`` can be an - instance of :class:`dpctl.memory.MemoryUSMShared`, + Notes + ----- + The ``buffer`` argument accepts string values ``"shared"``, + ``"host"``, or ``"device"`` to allocate new device memory by calling + the respective constructor with the specified ``buffer_ctor_kwrds``. + It can also be an instance of :class:`dpctl.memory.MemoryUSMShared`, :class:`dpctl.memory.MemoryUSMDevice`, or - :class:`dpctl.memory.MemoryUSMHost`; ``buffer`` can also be - another :class:`dpnp.tensor.usm_ndarray` instance, in which case its + :class:`dpctl.memory.MemoryUSMHost`, or another + :class:`dpnp.tensor.usm_ndarray` instance, in which case its underlying ``MemoryUSM*`` buffer is used. """ From 4d67432124add2cb0abce0f1bd9133bc0f584de7 Mon Sep 17 00:00:00 2001 From: Vladislav Perevezentsev Date: Fri, 10 Apr 2026 12:45:52 -0700 Subject: [PATCH 40/46] Add dpnp.tensor API reference documentation --- doc/_templates/autosummary/cython_class.rst | 29 ++++ doc/_templates/autosummary/elementwise.rst | 12 ++ doc/_templates/autosummary/usm_ndarray.rst | 45 +++++++ doc/reference/index.rst | 1 + .../tensor.accumulation_functions.rst | 15 +++ doc/reference/tensor.constants.rst | 35 +++++ doc/reference/tensor.creation_functions.rst | 31 +++++ doc/reference/tensor.data_type_functions.rst | 21 +++ doc/reference/tensor.data_types.rst | 127 ++++++++++++++++++ .../tensor.elementwise_functions.rst | 86 ++++++++++++ doc/reference/tensor.flags.rst | 22 +++ doc/reference/tensor.indexing_functions.rst | 19 +++ doc/reference/tensor.inspection.rst | 21 +++ doc/reference/tensor.linear_algebra.rst | 14 ++ .../tensor.manipulation_functions.rst | 29 ++++ doc/reference/tensor.print_functions.rst | 17 +++ doc/reference/tensor.rst | 55 ++++++++ doc/reference/tensor.searching_functions.rst | 16 +++ doc/reference/tensor.set_functions.rst | 15 +++ doc/reference/tensor.sorting_functions.rst | 13 ++ .../tensor.statistical_functions.rst | 19 +++ doc/reference/tensor.usm_ndarray.rst | 26 ++++ doc/reference/tensor.utility_functions.rst | 29 ++++ 23 files changed, 697 insertions(+) create mode 100644 doc/_templates/autosummary/cython_class.rst create mode 100644 doc/_templates/autosummary/elementwise.rst create mode 100644 doc/_templates/autosummary/usm_ndarray.rst create mode 100644 doc/reference/tensor.accumulation_functions.rst create mode 100644 doc/reference/tensor.constants.rst create mode 100644 doc/reference/tensor.creation_functions.rst create mode 100644 doc/reference/tensor.data_type_functions.rst create mode 100644 doc/reference/tensor.data_types.rst create mode 100644 doc/reference/tensor.elementwise_functions.rst create mode 100644 doc/reference/tensor.flags.rst create mode 100644 doc/reference/tensor.indexing_functions.rst create mode 100644 doc/reference/tensor.inspection.rst create mode 100644 doc/reference/tensor.linear_algebra.rst create mode 100644 doc/reference/tensor.manipulation_functions.rst create mode 100644 doc/reference/tensor.print_functions.rst create mode 100644 doc/reference/tensor.rst create mode 100644 doc/reference/tensor.searching_functions.rst create mode 100644 doc/reference/tensor.set_functions.rst create mode 100644 doc/reference/tensor.sorting_functions.rst create mode 100644 doc/reference/tensor.statistical_functions.rst create mode 100644 doc/reference/tensor.usm_ndarray.rst create mode 100644 doc/reference/tensor.utility_functions.rst diff --git a/doc/_templates/autosummary/cython_class.rst b/doc/_templates/autosummary/cython_class.rst new file mode 100644 index 00000000000..d39cceca002 --- /dev/null +++ b/doc/_templates/autosummary/cython_class.rst @@ -0,0 +1,29 @@ +{{ fullname | escape | underline}} + +.. currentmodule:: {{ module }} + +.. autoclass:: {{ name }} + {% block methods %} + + {% if methods %} + .. rubric:: {{ _('Methods') }} + + .. autosummary:: + :toctree: generated + {% for item in methods if item != "__init__" %} + ~{{ name }}.{{ item }} + {%- endfor %} + {% endif %} + {% endblock %} + + {% block attributes %} + {% if attributes %} + .. rubric:: {{ _('Attributes') }} + + .. autosummary:: + :toctree: generated + {% for item in attributes %} + ~{{ name }}.{{ item }} + {%- endfor %} + {% endif %} + {% endblock %} diff --git a/doc/_templates/autosummary/elementwise.rst b/doc/_templates/autosummary/elementwise.rst new file mode 100644 index 00000000000..47d3dc64159 --- /dev/null +++ b/doc/_templates/autosummary/elementwise.rst @@ -0,0 +1,12 @@ +{{ fullname | escape | underline}} + +.. currentmodule:: {{ module }} + +{% if objtype == "data" %} +.. auto{{ objtype }}:: {{ objname }} + :no-value: +{% endif %} + +{% if objtype == "function" %} +.. auto{{ objtype }}:: {{ objname }} +{% endif %} diff --git a/doc/_templates/autosummary/usm_ndarray.rst b/doc/_templates/autosummary/usm_ndarray.rst new file mode 100644 index 00000000000..81026c7cd72 --- /dev/null +++ b/doc/_templates/autosummary/usm_ndarray.rst @@ -0,0 +1,45 @@ +{{ fullname | escape | underline}} + +.. currentmodule:: {{ module }} + + + +.. autoclass:: {{ name }} + + {% block methods %} + + {% if methods %} + .. rubric:: {{ _('Methods') }} + + .. autosummary:: + :toctree: generated + {% for item in methods if item != "__init__" %} + ~{{ name }}.{{ item }} + {%- endfor %} + {% endif %} + {% endblock %} + + {% block attributes %} + {% if attributes %} + .. rubric:: {{ _('Attributes') }} + + .. autosummary:: + :toctree: generated + {% for item in attributes %} + ~{{ name }}.{{ item }} + {%- endfor %} + + .. rubric:: {{ _('Special attributes') }} + + .. autosummary:: + :toctree: generated + + ~{{name}}.__dlpack_device__ + ~{{name}}.__dlpack__ + ~{{name}}.__sycl_usm_array_interface__ + ~{{name}}._pointer + ~{{name}}._element_offset + ~{{name}}._byte_bounds + + {% endif %} + {% endblock %} diff --git a/doc/reference/index.rst b/doc/reference/index.rst index c6525004f71..84c17bb8b93 100644 --- a/doc/reference/index.rst +++ b/doc/reference/index.rst @@ -13,6 +13,7 @@ API reference of the Data Parallel Extension for NumPy* .. toctree:: :maxdepth: 2 + tensor ndarray ufunc routines diff --git a/doc/reference/tensor.accumulation_functions.rst b/doc/reference/tensor.accumulation_functions.rst new file mode 100644 index 00000000000..de0da7c0189 --- /dev/null +++ b/doc/reference/tensor.accumulation_functions.rst @@ -0,0 +1,15 @@ +.. _dpnp_tensor_accumulation_functions: + +Accumulation functions +====================== + +Accumulation functions compute cumulative results along a given axis of the input array. + +.. currentmodule:: dpnp.tensor + +.. autosummary:: + :toctree: generated + + cumulative_logsumexp + cumulative_prod + cumulative_sum diff --git a/doc/reference/tensor.constants.rst b/doc/reference/tensor.constants.rst new file mode 100644 index 00000000000..6ce5b1155e7 --- /dev/null +++ b/doc/reference/tensor.constants.rst @@ -0,0 +1,35 @@ +.. _dpnp_tensor_constants: + +Constants +========= + +The following constants are defined in :py:mod:`dpnp.tensor`: + +.. currentmodule:: dpnp.tensor + +.. autodata:: DLDeviceType + +.. data:: e + + ``float``: + IEEE 754 floating-point representation of Euler's constant. + +.. data:: inf + + ``float``: + IEEE 754 floating-point representation of (positive) infinity. + +.. data:: nan + + ``float``: + IEEE 754 floating-point representation of Not a Number (NaN). + +.. data:: newaxis + + ``NoneType``: + Alias for ``None`` which is useful for indexing. + +.. data:: pi + + ``float``: + IEEE 754 floating-point representation of the mathematical constant π. diff --git a/doc/reference/tensor.creation_functions.rst b/doc/reference/tensor.creation_functions.rst new file mode 100644 index 00000000000..670c7625843 --- /dev/null +++ b/doc/reference/tensor.creation_functions.rst @@ -0,0 +1,31 @@ +.. _dpnp_tensor_creation_functions: + +Array creation functions +======================== + +The following functions in :py:mod:`dpnp.tensor` can be used +to create new arrays: + +.. currentmodule:: dpnp.tensor + +.. autosummary:: + :toctree: generated + + arange + asarray + empty + empty_like + eye + from_dlpack + full + full_like + linspace + meshgrid + ones + ones_like + tril + triu + zeros + zeros_like + from_numpy + copy diff --git a/doc/reference/tensor.data_type_functions.rst b/doc/reference/tensor.data_type_functions.rst new file mode 100644 index 00000000000..6adca69081b --- /dev/null +++ b/doc/reference/tensor.data_type_functions.rst @@ -0,0 +1,21 @@ +.. _dpnp_tensor_data_type_functions: + +Data type functions +=================== + +The package :py:mod:`dpnp.tensor` contains the following data type functions conforming +to `Python Array API specification `_: + +.. _array_api_data_type_fns: https://data-apis.org/array-api/latest/API_specification/data_type_functions.html + +.. currentmodule:: dpnp.tensor + +.. autosummary:: + :toctree: generated + + astype + can_cast + finfo + iinfo + isdtype + result_type diff --git a/doc/reference/tensor.data_types.rst b/doc/reference/tensor.data_types.rst new file mode 100644 index 00000000000..52230a9f1e8 --- /dev/null +++ b/doc/reference/tensor.data_types.rst @@ -0,0 +1,127 @@ +.. _dpnp_tensor_data_types: + +.. currentmodule:: dpnp.tensor + +Data types +========== + +:py:mod:`dpnp.tensor` supports the following data types: + ++----------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| Data Type | Description | ++================+=========================================================================================================================================================================================+ +| ``bool`` | Boolean (``True`` or ``False``) | ++----------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| ``int8`` | An 8-bit signed integer type capable of representing :math:`v` subject to :math:`-2^7 \le v < 2^7` | ++----------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| ``int16`` | A 16-bit signed integer type capable of representing :math:`v` subject to :math:`-2^{15} \le v < 2^{15}` | ++----------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| ``int32`` | A 32-bit signed integer type capable of representing :math:`v` subject to :math:`-2^{31} \le v < 2^{31}` | ++----------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| ``int64`` | A 64-bit signed integer type capable of representing :math:`v` subject to :math:`-2^{63} \le v < 2^{63}` | ++----------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| ``uint8`` | An 8-bit unsigned integer type capable of representing :math:`v` subject to :math:`0 \le v < 2^8` | ++----------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| ``uint16`` | A 16-bit unsigned integer type capable of representing :math:`v` subject to :math:`0 \le v < 2^{16}` | ++----------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| ``uint32`` | A 32-bit unsigned integer type capable of representing :math:`v` subject to :math:`0 \le v < 2^{32}` | ++----------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| ``uint64`` | A 64-bit unsigned integer type capable of representing :math:`v` subject to :math:`0 \le v < 2^{64}` | ++----------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| ``float16`` | An IEEE-754 half-precision (16-bit) binary floating-point number (see `IEEE 754-2019`_) | ++----------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| ``float32`` | An IEEE-754 single-precision (32-bit) binary floating-point number (see `IEEE 754-2019`_) | ++----------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| ``float64`` | An IEEE-754 double-precision (64-bit) binary floating-point number (see `IEEE 754-2019`_) | ++----------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| ``complex64`` | Single-precision (64-bit) complex floating-point number whose real and imaginary components are IEEE 754 single-precision (32-bit) binary floating-point numbers (see `IEEE 754-2019`_) | ++----------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| ``complex128`` | Double-precision (128-bit) complex floating-point number whose real and imaginary components are IEEE 754 double-precision (64-bit) binary floating-point numbers (see `IEEE 754-2019`_)| ++----------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ + +.. _IEEE 754-2019: https://doi.org/10.1109%2FIEEESTD.2019.8766229 + +Data type support by array object :py:class:`usm_ndarray` depends on capabilities of :class:`dpctl.SyclDevice` where array is allocated. + +Half-precision floating-point type ``float16`` is supported only for devices whose attribute :attr:`dpctl.SyclDevice.has_aspect_fp16` evaluates to ``True``. + +Double-precision floating-point type ``float64`` and double-precision complex floating-point type ``complex128`` are supported only for devices whose attribute :attr:`dpctl.SyclDevice.has_aspect_fp64` +evaluates to ``True``. + +If prerequisites are not met, requests to create an instance of an array object for these types will raise an exception. + +Data type objects are instances of :py:class:`dtype` object, and support equality comparison by implementing +special method :meth:`__eq__`. + +.. py:class:: dtype + + Same as :py:class:`numpy.dtype` + + .. py:method:: __eq__ + + Check if data-type instances are equal. + + +Default integral data type +-------------------------- + +The default integral data type is :attr:`int64` for all supported devices. + +Default indexing data type +-------------------------- + +The default indexing data type is :attr:`int64` for all supported devices. + +Default real floating-point data type +------------------------------------- + +The default real floating-point type depends on the capabilities of device where array is allocated. +If the device support double precision floating-point types, the default real floating-point type +is :attr:`float64`, otherwise :attr:`float32`. + +Make sure to select an appropriately capable device for an application that requires use of double +precision floating-point type. + +Default complex floating-point data type +---------------------------------------- + +Like for the default real floating-point type, the default complex floating-point type depends on +capabilities of device. If the device support double precision real floating-point types, the default +complex floating-point type is :attr:`complex128`, otherwise :attr:`complex64`. + + +Querying default data types programmatically +-------------------------------------------- + +The data type can be discovered programmatically using Array API :ref:`inspection functions `: + +.. code-block:: python + + import dpctl + from dpnp import tensor + + device = dpctl.select_default_device() + # get default data types for default-selected device + default_types = tensor.__array_namespace_info__().default_dtypes(device) + int_dt = default_types["integral"] + ind_dt = default_types["indexing"] + rfp_dt = default_types["real floating"] + cfp_dt = default_types["complex floating"] + + +Type promotion rules +-------------------- + +Type promotion rules govern the behavior of an array library when a function does not have +a dedicated implementation for the data type(s) of the input array(s). + +In such a case, input arrays may be cast to data types for which a dedicated implementation +exists. For example, when :data:`sin` is applied to array of integral values. + +Type promotion rules used in :py:mod:`dpnp.tensor` are consistent with the +Python Array API specification's `type promotion rules `_ +for devices that support double precision floating-point type. + + +For devices that do not support double precision floating-point type, the type promotion rule is +truncated by removing nodes corresponding to unsupported data types and edges that lead to them. diff --git a/doc/reference/tensor.elementwise_functions.rst b/doc/reference/tensor.elementwise_functions.rst new file mode 100644 index 00000000000..291f82abba1 --- /dev/null +++ b/doc/reference/tensor.elementwise_functions.rst @@ -0,0 +1,86 @@ +.. _dpnp_tensor_elementwise_functions: + +Element-wise functions +====================== + +Element-wise functions applied to input array(s) produce an output array of respective +function values computed for every element of input array(s). + +.. currentmodule:: dpnp.tensor + +.. autosummary:: + :toctree: generated + :template: autosummary/elementwise.rst + + abs + acos + acosh + add + angle + asin + asinh + atan + atan2 + atanh + bitwise_and + bitwise_left_shift + bitwise_invert + bitwise_or + bitwise_right_shift + bitwise_xor + cbrt + ceil + clip + conj + copysign + cos + cosh + divide + equal + exp + exp2 + expm1 + floor + floor_divide + greater + greater_equal + hypot + imag + isfinite + isinf + isnan + less + less_equal + log + log1p + log2 + log10 + logaddexp + logical_and + logical_not + logical_or + logical_xor + maximum + minimum + multiply + negative + nextafter + not_equal + positive + pow + proj + real + remainder + reciprocal + round + rsqrt + sign + signbit + sin + sinh + square + sqrt + subtract + tan + tanh + trunc diff --git a/doc/reference/tensor.flags.rst b/doc/reference/tensor.flags.rst new file mode 100644 index 00000000000..3aa9d812e09 --- /dev/null +++ b/doc/reference/tensor.flags.rst @@ -0,0 +1,22 @@ +.. _dpnp_tensor_flags_class: + +``Flags`` class +=================== + +.. autoclass:: dpnp.tensor._flags.Flags + :members: + + Note that dictionary-like access to some members is permitted: + + "C", "C_CONTIGUOUS": + Equivalent to ``c_contiguous`` + "F", "F_CONTIGUOUS": + Equivalent to ``f_contiguous`` + "W", "WRITABLE": + Equivalent to ``writable`` + "FC": + Equivalent to ``fc`` + "FNC": + Equivalent to ``fnc`` + "FORC", "CONTIGUOUS": + Equivalent to ``forc`` and ``contiguous`` diff --git a/doc/reference/tensor.indexing_functions.rst b/doc/reference/tensor.indexing_functions.rst new file mode 100644 index 00000000000..fee0b18a187 --- /dev/null +++ b/doc/reference/tensor.indexing_functions.rst @@ -0,0 +1,19 @@ +.. _dpnp_tensor_indexing_functions: + +Indexing functions +================== + +These functions allow to retrieve or modify array elements indexed +by either integral arrays of indices or boolean mask arrays. + +.. currentmodule:: dpnp.tensor + +.. autosummary:: + :toctree: generated + + extract + place + put + put_along_axis + take + take_along_axis diff --git a/doc/reference/tensor.inspection.rst b/doc/reference/tensor.inspection.rst new file mode 100644 index 00000000000..3e0f7e54d4e --- /dev/null +++ b/doc/reference/tensor.inspection.rst @@ -0,0 +1,21 @@ +.. _dpnp_tensor_inspection: + +Inspection API +============== + + +:mod:`dpnp.tensor` implements a way to introspect implementation- and device- +capabilities of an array library as specified in +`Python Array API standard `_: + +.. currentmodule:: dpnp.tensor + +.. _array_api_inspection: https://data-apis.org/array-api/latest/API_specification/inspection.html + +.. autosummary:: + :toctree: generated + :template: autosummary/cython_class.rst + + __array_api_version__ + __array_namespace_info__ + _array_api.Info diff --git a/doc/reference/tensor.linear_algebra.rst b/doc/reference/tensor.linear_algebra.rst new file mode 100644 index 00000000000..58df8ebebc7 --- /dev/null +++ b/doc/reference/tensor.linear_algebra.rst @@ -0,0 +1,14 @@ +.. _dpnp_tensor_linear_algebra: + +Linear algebra functions +======================== + +.. currentmodule:: dpnp.tensor + +.. autosummary:: + :toctree: generated + + matmul + matrix_transpose + tensordot + vecdot diff --git a/doc/reference/tensor.manipulation_functions.rst b/doc/reference/tensor.manipulation_functions.rst new file mode 100644 index 00000000000..1749e432c66 --- /dev/null +++ b/doc/reference/tensor.manipulation_functions.rst @@ -0,0 +1,29 @@ +.. _dpnp_tensor_manipulation_functions: + +Array manipulation functions +============================ + +The following functions conform to `Python Array API standard `_: + +.. array_api_spec_manipulation_functions: https://data-apis.org/array-api/latest/API_specification/manipulation_functions.html + +.. currentmodule:: dpnp.tensor + +.. autosummary:: + :toctree: generated + + broadcast_arrays + broadcast_to + concat + expand_dims + flip + moveaxis + permute_dims + repeat + reshape + roll + squeeze + stack + swapaxes + tile + unstack diff --git a/doc/reference/tensor.print_functions.rst b/doc/reference/tensor.print_functions.rst new file mode 100644 index 00000000000..7005deafd65 --- /dev/null +++ b/doc/reference/tensor.print_functions.rst @@ -0,0 +1,17 @@ +.. _dpnp_tensor_print_functions: + +Printing functions +================== + +Functions for controlling and customizing the string representation of arrays. + +.. currentmodule:: dpnp.tensor + +.. autosummary:: + :toctree: generated + + get_print_options + set_print_options + print_options + usm_ndarray_repr + usm_ndarray_str diff --git a/doc/reference/tensor.rst b/doc/reference/tensor.rst new file mode 100644 index 00000000000..d482fecb69b --- /dev/null +++ b/doc/reference/tensor.rst @@ -0,0 +1,55 @@ +.. _dpnp_tensor_pyapi: + +Tensor (``dpnp.tensor``) +======================== + +.. py:module:: dpnp.tensor + +.. currentmodule:: dpnp.tensor + +:py:mod:`dpnp.tensor` provides a reference implementation of the +`Python Array API `_ specification. The implementation +uses data-parallel algorithms suitable for execution on accelerators, such as GPUs. + +:py:mod:`dpnp.tensor` is written using C++ and `SYCL `_ +and oneAPI extensions implemented in `Intel(R) oneAPI DPC++ compiler `_. + +This module contains: + +* Array object :py:class:`usm_ndarray` +* :ref:`Accumulation functions ` +* :ref:`Array creation functions ` +* :ref:`Array manipulation functions ` +* :ref:`Elementwise functions ` +* :ref:`Indexing functions ` +* :ref:`Introspection functions ` +* :ref:`Linear algebra functions ` +* :ref:`Searching functions ` +* :ref:`Set functions ` +* :ref:`Sorting functions ` +* :ref:`Statistical functions ` +* :ref:`Utility functions ` +* :ref:`Printing functions ` +* :ref:`Constants ` + + +.. toctree:: + :hidden: + + tensor.creation_functions + tensor.usm_ndarray + tensor.data_type_functions + tensor.data_types + tensor.elementwise_functions + tensor.accumulation_functions + tensor.indexing_functions + tensor.inspection + tensor.linear_algebra + tensor.manipulation_functions + tensor.searching_functions + tensor.set_functions + tensor.sorting_functions + tensor.statistical_functions + tensor.utility_functions + tensor.print_functions + tensor.constants diff --git a/doc/reference/tensor.searching_functions.rst b/doc/reference/tensor.searching_functions.rst new file mode 100644 index 00000000000..f451034672a --- /dev/null +++ b/doc/reference/tensor.searching_functions.rst @@ -0,0 +1,16 @@ +.. _dpnp_tensor_searching_functions: + +Searching functions +=================== + +.. currentmodule:: dpnp.tensor + +.. autosummary:: + :toctree: generated + + argmax + argmin + count_nonzero + nonzero + searchsorted + where diff --git a/doc/reference/tensor.set_functions.rst b/doc/reference/tensor.set_functions.rst new file mode 100644 index 00000000000..0cd2e8a47f1 --- /dev/null +++ b/doc/reference/tensor.set_functions.rst @@ -0,0 +1,15 @@ +.. _dpnp_tensor_set_functions: + +Set Functions +============= + +.. currentmodule:: dpnp.tensor + +.. autosummary:: + :toctree: generated + + isin + unique_all + unique_counts + unique_inverse + unique_values diff --git a/doc/reference/tensor.sorting_functions.rst b/doc/reference/tensor.sorting_functions.rst new file mode 100644 index 00000000000..b3dac1eff44 --- /dev/null +++ b/doc/reference/tensor.sorting_functions.rst @@ -0,0 +1,13 @@ +.. _dpnp_tensor_sorting_functions: + +Sorting functions +================= + +.. currentmodule:: dpnp.tensor + +.. autosummary:: + :toctree: generated + + argsort + sort + top_k diff --git a/doc/reference/tensor.statistical_functions.rst b/doc/reference/tensor.statistical_functions.rst new file mode 100644 index 00000000000..e8c2b26bffa --- /dev/null +++ b/doc/reference/tensor.statistical_functions.rst @@ -0,0 +1,19 @@ +.. _dpnp_tensor_statistical_functions: + +Statistical Functions +===================== + +.. currentmodule:: dpnp.tensor + +.. autosummary:: + :toctree: generated + + max + mean + min + prod + std + sum + var + logsumexp + reduce_hypot diff --git a/doc/reference/tensor.usm_ndarray.rst b/doc/reference/tensor.usm_ndarray.rst new file mode 100644 index 00000000000..5b958d673b2 --- /dev/null +++ b/doc/reference/tensor.usm_ndarray.rst @@ -0,0 +1,26 @@ +.. _dpnp_tensor_array_object: + +USM array object +================ + +.. currentmodule:: dpnp.tensor + +The array object represents a multi-dimensional tensor of uniform elemental datatype allocated on +a :py:class:`Device`. The tensor in stored in a USM allocation, which can be accessed via +:py:attr:`usm_ndarray.base` attribute. + +Implementation of :py:class:`usm_ndarray` conforms to +`Array API standard `_ specification. + +.. array_api_array_object: https://data-apis.org/array-api/latest/API_specification/array_object.html + +.. autosummary:: + :toctree: generated + :template: autosummary/usm_ndarray.rst + + usm_ndarray + +.. toctree:: + :hidden: + + tensor.flags diff --git a/doc/reference/tensor.utility_functions.rst b/doc/reference/tensor.utility_functions.rst new file mode 100644 index 00000000000..5f124667e9f --- /dev/null +++ b/doc/reference/tensor.utility_functions.rst @@ -0,0 +1,29 @@ +.. _dpnp_tensor_utility_functions: + +Utility functions +================= + +.. currentmodule:: dpnp.tensor + +.. autosummary:: + :toctree: generated + + all + any + allclose + diff + asnumpy + to_numpy + +Device object +------------- + +.. autoclass:: Device + + .. autosummary:: + ~create_device + ~sycl_queue + ~sycl_device + ~sycl_context + ~sycl_usm_shared_memory + ~usm_ndarray_to_device From 318c8905f3ac0467064d97dfdadb23f2cc2e48dd Mon Sep 17 00:00:00 2001 From: Vladislav Perevezentsev Date: Fri, 10 Apr 2026 13:07:55 -0700 Subject: [PATCH 41/46] Add user guides for dpnp.tensor module --- doc/index.rst | 1 + doc/user_guides/dlpack.rst | 138 +++++++++++++ doc/user_guides/execution_model.rst | 146 ++++++++++++++ doc/user_guides/index.rst | 12 ++ doc/user_guides/tensor_intro.rst | 287 ++++++++++++++++++++++++++++ 5 files changed, 584 insertions(+) create mode 100644 doc/user_guides/dlpack.rst create mode 100644 doc/user_guides/execution_model.rst create mode 100644 doc/user_guides/index.rst create mode 100644 doc/user_guides/tensor_intro.rst diff --git a/doc/index.rst b/doc/index.rst index 20d0f3ee14d..e54f7e839df 100644 --- a/doc/index.rst +++ b/doc/index.rst @@ -82,6 +82,7 @@ core `NumPy*`_ functions and numerical data types. overview quick_start_guide + user_guides/index reference/index tensor dpnp_backend_api diff --git a/doc/user_guides/dlpack.rst b/doc/user_guides/dlpack.rst new file mode 100644 index 00000000000..38a7778cc4f --- /dev/null +++ b/doc/user_guides/dlpack.rst @@ -0,0 +1,138 @@ +.. _dpnp_tensor_dlpack_support: + +DLPack exchange of USM allocated arrays +======================================= + +DLPack overview +--------------- + +`DLPack `_ is a commonly used C-ABI compatible data structure that allows data exchange +between major frameworks. DLPack strives to be minimal, intentionally leaves allocators API and +device API out of scope. + +Data shared via DLPack are owned by the producer who provides a deleter function stored in the +`DLManagedTensor `_, and are only accessed by consumer. +Python semantics of using the structure is `explained in dlpack docs `_. + +DLPack specifies data location in memory via ``void * data`` field of `DLTensor `_ struct, and via ``DLDevice device`` field. +The `DLDevice `_ struct has two members: an enumeration ``device_type`` and an integer ``device_id``. + +DLPack recognizes enumeration value ``DLDeviceType::kDLOneAPI`` reserved for sharing SYCL USM allocations. +It is not ``kDLSycl`` since importing USM-allocated tensor with this device type relies on oneAPI SYCL extensions +``sycl_ext_oneapi_filter_selector`` and ``sycl_ext_oneapi_default_platform_context`` to operate. + +.. _dlpack_docs: https://dmlc.github.io/dlpack/latest/ +.. _dlpack_managed_tensor: https://dmlc.github.io/dlpack/latest/c_api.html#c.DLManagedTensor +.. _dlpack_dltensor: https://dmlc.github.io/dlpack/latest/c_api.html#c.DLTensor +.. _dlpack_dldevice: https://dmlc.github.io/dlpack/latest/c_api.html#c.DLDevice +.. _dlpack_python_spec: https://dmlc.github.io/dlpack/latest/python_spec.html + +Exporting USM allocation to DLPack +----------------------------------- + +When sharing USM allocation (of any ``sycl::usm::kind``) with ``void * ptr`` bound to ``sycl::context ctx``: + +.. code-block:: cpp + :caption: Protocol for exporting USM allocation as DLPack + + // Input: void *ptr: + // USM allocation pointer + // sycl::context ctx: + // context the pointer is bound to + + // Get device where allocation was originally made + // Keep in mind, the device may be a sub-device + const sycl::device &ptr_dev = sycl::get_pointer_device(ptr, ctx); + + #if SYCL_KHR_DEFAULT_CONTEXT + const sycl::context &default_ctx = ptr_dev.get_platform().khr_get_default_context(); + #else + static_assert(false, "ext_oneapi_default_context extension is required"); + #endif + + // Assert that ctx is the default platform context, or throw + if (ctx != default_ctx) { + throw pybind11::type_error( + "Can not export USM allocations not " + "bound to default platform context." + ); + } + + // Find parent root device if ptr_dev is a sub-device + const sycl::device &parent_root_device = get_parent_root_device(ptr_dev); + + // find position of parent_root_device in sycl::get_devices + const auto &all_root_devs = sycl::device::get_devices(); + auto beg = std::begin(all_root_devs); + auto end = std::end(all_root_devs); + auto selectot_fn = [parent_root_device](const sycl::device &root_d) -> bool { + return parent_root_device == root_d; + }; + auto pos = find_if(beg, end, selector_fn); + + if (pos == end) { + throw pybind11::type_error("Could not produce DLPack: failed finding device_id"); + } + std::ptrdiff_t dev_idx = std::distance(beg, pos); + + // check that dev_idx can fit into int32_t if needed + int32_t device_id = static_cast(dev_idx); + + // populate DLTensor with DLDeviceType::kDLOneAPI and computed device_id + + +Importing DLPack with ``device_type == kDLOneAPI`` +-------------------------------------------------- + +.. code-block:: cpp + :caption: Protocol for recognizing DLPack as a valid USM allocation + + // Input: ptr = dlm_tensor->dl_tensor.data + // device_id = dlm_tensor->dl_tensor.device.device_id + + // Get root_device from device_id + const auto &device_vector = sycl::get_device(); + const sycl::device &root_device = device_vector.at(device_id); + + // Check if the backend of the device is supported by consumer + // Perhaps for certain backends (CUDA, hip, etc.) we should dispatch + // different dlpack importers + + // alternatively + // sycl::device root_device = sycl::device( + // sycl::ext::oneapi::filter_selector{ std::to_string(device_id)} + // ); + + // Get default platform context + #if SYCL_KHR_DEFAULT_CONTEXT + const sycl::context &default_ctx = root_device.get_platform().khr_get_default_context(); + #else + static_assert(false, "ext_oneapi_default_context extension is required"); + #endif + + // Check that pointer is known in the context + const sycl::usm::kind &alloc_type = sycl::get_pointer_type(ptr, ctx); + + if (alloc_type == sycl::usm::kind::unknown) { + throw pybind11::type_error( + "Data pointer in DLPack is not bound to the " + "default platform context of specified device" + ); + } + + // Perform check that USM allocation type is supported by consumer if needed + + // Get sycl::device where the data was allocated + const sycl::device &ptr_dev = sycl::get_pointer_device(ptr, ctx); + + // Create object of consumer's library from ptr, ptr_dev, ctx + +Support of DLPack with ``kDLOneAPI`` device type +------------------------------------------------ + +:py:mod:`dpnp.tensor` supports DLPack v0.8. Exchange of USM allocations made using Level-Zero backend +is supported with ``torch.Tensor(device='xpu')`` for PyTorch when using `intel-extension-for-pytorch `_, +as well as for TensorFlow when `intel-extension-for-tensorflow `_ is used. + +.. _intel_ext_for_torch: https://github.com/intel/intel-extension-for-pytorch +.. _intel_ext_for_tf: https://github.com/intel/intel-extension-for-tensorflow diff --git a/doc/user_guides/execution_model.rst b/doc/user_guides/execution_model.rst new file mode 100644 index 00000000000..1964ef230f8 --- /dev/null +++ b/doc/user_guides/execution_model.rst @@ -0,0 +1,146 @@ +.. _dpnp_execution_model: + +######################## +oneAPI programming model +######################## + +oneAPI library and its Python interface +======================================= + +Using oneAPI libraries, a user calls functions that take ``sycl::queue`` and a collection of +``sycl::event`` objects among other arguments. For example: + +.. code-block:: cpp + :caption: Prototypical call signature of oneMKL function + + sycl::event + compute( + sycl::queue &exec_q, + ..., + const std::vector &dependent_events + ); + +The function ``compute`` inserts computational tasks into the queue ``exec_q`` for DPC++ runtime to +execute on the device the queue targets. The execution may begin only after other tasks whose +execution status is represented by ``sycl::event`` objects in the provided ``dependent_events`` +vector complete. If the vector is empty, the runtime begins the execution as soon as the device is +ready. The function returns a ``sycl::event`` object representing completion of the set of +computational tasks submitted by the ``compute`` function. + +Hence, in the oneAPI programming model, the execution **queue** is used to specify which device the +function will execute on. To create a queue, one must specify a device to target. + +In :mod:`dpctl`, the ``sycl::queue`` is represented by :class:`dpctl.SyclQueue` Python type, +and a Python API to call such a function might look like + +.. code-block:: python + + def call_compute( + exec_q : dpctl.SyclQueue, + ..., + dependent_events : List[dpctl.SyclEvent] = [] + ) -> dpctl.SyclEvent: + ... + +When building Python API for a SYCL offloading function, and you choose to +map the SYCL API to a different API on the Python side, it must still translate to a +similar call under the hood. + +The arguments to the function must be suitable for use in the offloading functions. +Typically these are Python scalars, or objects representing USM allocations, such as +:class:`dpnp.tensor.usm_ndarray`, :class:`dpctl.memory.MemoryUSMDevice` and friends. + +.. note:: + The USM allocations these objects represent must not get deallocated before + offloaded tasks that access them complete. + + This is something authors of DPC++-based Python extensions must take care of, + and users of such extensions should assume assured. + + +USM allocations and compute-follows-data +======================================== + +To make a USM allocation on a device in SYCL, one needs to specify ``sycl::device`` in the +memory of which the allocation is made, and the ``sycl::context`` to which the allocation +is bound. + +A ``sycl::queue`` object is often used instead. In such cases ``sycl::context`` and ``sycl::device`` associated +with the queue are used to make the allocation. + +.. important:: + :mod:`dpnp.tensor` associates a queue object with every USM allocation. + + The associated queue may be queried using ``.sycl_queue`` property of the + Python type representing the USM allocation. + +This design choice allows :mod:`dpnp.tensor` to have a preferred queue to use when operating on any single +USM allocation. For example: + +.. code-block:: python + + def unary_func(x : dpnp.tensor.usm_ndarray): + code1 + _ = _func_impl(x.sycl_queue, ...) + code2 + +When combining several objects representing USM-allocations, the +:ref:`programming model ` +adopted in :mod:`dpnp.tensor` insists that queues associated with each object be the same, in which +case it is the execution queue used. Alternatively :exc:`dpctl.utils.ExecutionPlacementError` is raised. + +.. code-block:: python + + def binary_func( + x1 : dpnp.tensor.usm_ndarray, + x2 : dpnp.tensor.usm_ndarray + ): + exec_q = dpctl.utils.get_execution_queue((x1.sycl_queue, x2.sycl_queue)) + if exec_q is None: + raise dpctl.utils.ExecutionPlacementError + ... + +In order to ensure that compute-follows-data works seamlessly out-of-the-box, :mod:`dpnp.tensor` maintains +a cache with context and device as keys and queues as values used by :class:`dpnp.tensor.Device` class. + +.. code-block:: python + + >>> import dpctl + >>> from dpnp import tensor + + >>> sycl_dev = dpctl.SyclDevice("cpu") + >>> d1 = tensor.Device.create_device(sycl_dev) + >>> d2 = tensor.Device.create_device("cpu") + >>> d3 = tensor.Device.create_device(dpctl.select_cpu_device()) + + >>> d1.sycl_queue == d2.sycl_queue, d1.sycl_queue == d3.sycl_queue, d2.sycl_queue == d3.sycl_queue + (True, True, True) + +Since :class:`dpnp.tensor.Device` class is used by all :ref:`array creation functions ` +in :mod:`dpnp.tensor`, the same value used as ``device`` keyword argument results in array instances that +can be combined together in accordance with compute-follows-data programming model. + +.. code-block:: python + + >>> from dpnp import tensor + >>> import dpctl + + >>> # queue for default-constructed device is used + >>> x1 = tensor.arange(100, dtype="int32") + >>> x2 = tensor.zeros(100, dtype="int32") + >>> x12 = tensor.concat((x1, x2)) + >>> x12.sycl_queue == x1.sycl_queue, x12.sycl_queue == x2.sycl_queue + (True, True) + >>> # default constructors of SyclQueue class create different instance of the queue + >>> q1 = dpctl.SyclQueue() + >>> q2 = dpctl.SyclQueue() + >>> q1 == q2 + False + >>> y1 = tensor.arange(100, dtype="int32", sycl_queue=q1) + >>> y2 = tensor.zeros(100, dtype="int32", sycl_queue=q2) + >>> # this call raises ExecutionPlacementError since compute-follows-data + >>> # rules are not met + >>> tensor.concat((y1, y2)) + +Please refer to the :ref:`array migration ` section of the introduction to +:mod:`dpnp.tensor` for examples on how to resolve ``ExecutionPlacementError`` exceptions. diff --git a/doc/user_guides/index.rst b/doc/user_guides/index.rst new file mode 100644 index 00000000000..aeae74bc859 --- /dev/null +++ b/doc/user_guides/index.rst @@ -0,0 +1,12 @@ +.. _user_guides: + +*********** +User Guides +*********** + +.. toctree:: + :maxdepth: 2 + + tensor_intro + execution_model + dlpack diff --git a/doc/user_guides/tensor_intro.rst b/doc/user_guides/tensor_intro.rst new file mode 100644 index 00000000000..a1f73a5208b --- /dev/null +++ b/doc/user_guides/tensor_intro.rst @@ -0,0 +1,287 @@ +.. _user_guide_tensor_intro: + +Intro to :py:mod:`dpnp.tensor` +=============================== + +Supported array data types +-------------------------- + +The tensor submodule provides an N-dimensional array object for a tensor whose values have the same data type +from the :ref:`following list `: + +.. currentmodule:: dpnp.tensor + +.. list-table:: + + * - + - :attr:`int8` + - :attr:`int16` + - :attr:`int32` + - :attr:`int64` + - + - :attr:`float16` + - :attr:`float32` + - :attr:`complex64` + + * - :attr:`bool` + - :attr:`uint8` + - :attr:`uint16` + - :attr:`uint32` + - :attr:`uint64` + - + - + - :attr:`float64` + - :attr:`complex128` + + +Creating an array +----------------- + +Array :ref:`creation functions ` support keyword arguments that +control the device where the array is allocated as well as aspects of +USM allocation for the array. + +These three keywords are: + +.. list-table:: + :header-rows: 1 + + * - Keyword arguments + - Default value + - Description + * - ``usm_type`` + - ``"device"`` + - type of USM allocation to make + * - ``device`` + - ``None`` + - :py:class:`dpnp.tensor.Device` instance + * - ``sycl_queue`` + - ``None`` + - Instance of :class:`dpctl.SyclQueue` associated with array + +Arguments ``sycl_queue`` and ``device`` are complementary to each other, and +a user need only provide one of these. + +A valid setting for the ``device`` keyword argument is any object that can be passed to :py:meth:`dpnp.tensor.Device.create_device`. +If both ``device`` and ``sycl_queue`` keyword arguments are specified, they must correspond to :class:`dpctl.SyclQueue` instances which +compare equal to one another. + +A created instance of :class:`usm_ndarray` has an associated :class:`dpctl.SyclQueue` instance that can be retrieved +using :attr:`dpnp.tensor.usm_ndarray.sycl_queue` property. The underlying USM allocation +is allocated on :class:`dpctl.SyclDevice` and is bound to :class:`dpctl.SyclContext` targeted by this queue. + +.. _dpnp_tensor_compute_follows_data: + +Execution model +--------------- + +When one of more instances of ``usm_ndarray`` objects are passed to a function in :py:mod:`dpnp.tensor` other than creation function, +a "compute follows data" execution model is followed. + +The model requires that :class:`dpctl.SyclQueue` instances associated with each array compared equal to one another, signifying that +each one corresponds to the same underlying ``sycl::queue`` object. In such a case, the output array is associated with the same +``sycl::queue`` and computations are scheduled for execution using this ``sycl::queue``. + +.. note:: + Two instances :class:`dpctl.SyclQueue` may target the same ``sycl::device`` and be using the same ``sycl::context``, but correspond + to different scheduling entries, and hence be in violation of the compute-follows-data requirement. One common example of this are + ``SyclQueue`` corresponding to default-selected device and using platform default context but created using different properties, e.g. + one with `"enable_profiling"` set and another without it. + +If input arrays do not conform to the compute-follows-data requirements, :py:exc:`dpctl.utils.ExecutionPlacementError` is raised. +User must explicitly migrate the data to unambiguously control the execution placement. + +.. _dpnp_tensor_array_migration: + +Migrating arrays +---------------- + +Array content can be migrated to a different device +using either :meth:`dpnp.tensor.usm_ndarray.to_device` method, or by using :func:`dpnp.tensor.asarray` function. + +The ``arr.to_device(device=target_device)`` method will be zero-copy if the ``arr.sycl_queue`` and the :class:`dpctl.SyclQueue` +instance associated with new target device have the same underlying ``sycl::device`` and ``sycl::context`` instances. + +Here is an example of migration without a copy using ``.to_device`` method: + +.. code-block:: python + :caption: Example: Use ``.to_device`` to zero-copy migrate array content to be associated with a different ``sycl::queue`` + + import dpctl + from dpnp import tensor + + x = tensor.linspace(0, 1, num=10**8) + q_prof = dpctl.SyclQueue(x.sycl_context, x.sycl_device, property="enable_profiling") + + timer = dpctl.SyclTimer() + # no data migration takes place here (zero-copy), + # but x and x1 arrays do not satisfy compute-follows-data requirements + x1 = x.to_device(q_prof) + + with timer(q_prof): + y1 = tensor.sin(2*x1)*tensor.exp(-tensor.square(x1)) + + # also a zero copy operation + y = y1.to_device(x.device) + + host_dt, device_dt = timer.dt + print(f"Execution on device {x.sycl_device.name} took {device_dt} seconds") + print(f"Execution on host took {host_dt} seconds") + +Data migration when the current and the target SYCL contexts are different is performed via host. That means that data are copied from +the current device to the host, and then from the host to the target device: + +.. code-block:: python + :caption: Example: Using ``.to_device`` to migrate data may involve copy via host + + from dpnp import tensor + + x_cpu = tensor.concat((tensor.ones(10, device="cpu"), tensor.zeros(1000, device="cpu"))) + + # data migration is performed via host + x_gpu = x_cpu.to_device("gpu") + +An alternative way to migrate data is to use :py:func:`asarray` and specify device-placement keyword arguments: + +.. code-block:: python + :caption: Example: Using ``asarray`` to migrate data may involve copy via host + + from dpnp import tensor + + x_cpu = tensor.concat((tensor.ones(10, device="cpu"), tensor.zeros(1000, device="cpu"))) + + # data migration is performed via host + x_gpu = tensor.asarray(x_cpu, device="gpu") + +An advantage of using the function ``asarray`` is that migration from ``usm_ndarray`` instances allocated on different +devices as well migration from :py:class:`numpy.ndarray` may be accomplished in a single call: + +.. code-block:: python + :caption: Example: ``asarray`` may migrate multiple arrays + + from dpnp import tensor + import numpy + + x_cpu = tensor.ones((10, 10), device="cpu") + x_gpu = tensor.zeros((10, 10), device="opencl:gpu") + x_np = numpy.random.randn(10, 10) + + # Array w has shape (3, 10, 10) + w = tensor.asarray([x_cpu, x_gpu, x_np], device="level_zero:gpu") + +Migration may also occur during calls to other array creation functions, e.g., :py:func:`full` when the ``fill_value`` parameter is an instance +of :py:class:`usm_ndarray`. In such a case default values of device placement keywords are interpreted to avoid data migration, i.e., the +new array is created on the same device where ``fill_value`` array was allocated. + +.. code-block:: python + :caption: Example: Using ``usm_ndarray`` as arguments to array construction + + from dpnp import tensor + + # Zero-dimensional array allocated on CPU device + pi_on_device = tensor.asarray(tensor.pi, dtype=tensor.float32, device="cpu") + + # x will also be allocated on CPU device + x = tensor.full(shape=(100, 100), fill_value=pi_on_device) + + # Create array on GPU. Migration of `pi_on_device` to GPU via host + # takes place under the hood + y_gpu = tensor.full(shape=(100, 100), fill_value=pi_on_device, device="gpu") + + +Combining arrays with different USM types +----------------------------------------- + +For functions with single argument the returned array has the same ``usm_type`` as the input array. + +Functions that combine several ``usm_ndarray`` instances the ``usm_type`` of the output array is determined +using the following coercion rule: + ++------------+----------+----------+----------+ +| | "device" | "shared" | "host" | ++------------+----------+----------+----------+ +| "device" | "device" | "device" | "device" | ++------------+----------+----------+----------+ +| "shared" | "device" | "shared" | "shared" | ++------------+----------+----------+----------+ +| "host" | "device" | "shared" | "host" | ++------------+----------+----------+----------+ + +If assigning USM-type "device" a score of 0, USM-type "shared" a score of 1, and USM-type "host" a score of 2, +the USM-type of the output array has the smallest score of all its inputs. + +.. currentmodule:: dpctl.utils + +The convenience function :py:func:`get_coerced_usm_type` is a convenience function to determine the USM-type +following this convention: + +.. code-block:: python + + from dpctl.utils import get_coerced_usm_type + + # r1 has value "device" + r1 = get_coerced_usm_type(["device", "shared", "host"]) + + # r2 has value "shared" + r2 = get_coerced_usm_type(["shared", "shared", "host"]) + + # r3 has value "host" + r3 = get_coerced_usm_type(["host", "host", "host"]) + +Sharing data between devices and Python +--------------------------------------- + +Python objects, such as sequences of :class:`int`, :class:`float`, or :class:`complex` objects, +or NumPy arrays can be converted to :class:`dpnp.tensor.usm_ndarray` using :func:`dpnp.tensor.asarray` +function. + +.. code-block:: python + + >>> from dpnp import tensor as dpt + >>> import numpy as np + >>> import mkl_random + + >>> # Sample from true random number generator + >>> rs = mkl_random.RandomState(brng="nondeterm") + >>> x_np = rs.uniform(-1, 1, size=(6, 512)).astype(np.float32) + + >>> # copy data to USM-device (default) allocated array + >>> x_usm = dpt.asarray(x_np) + >>> dpt.max(x_usm, axis=1) + usm_ndarray([0.9998379 , 0.9963589 , 0.99818915, 0.9975991 , 0.9999802 , + 0.99851537], dtype=float32) + >>> np.max(x_np, axis=1) + array([0.9998379 , 0.9963589 , 0.99818915, 0.9975991 , 0.9999802 , + 0.99851537], dtype=float32) + +The content of :class:`dpnp.tensor.usm_ndarray` may be copied into +a NumPy array using :func:`dpnp.tensor.asnumpy` function: + +.. code-block:: python + + from dpnp import tensor as dpt + import numpy as np + + def sieve_pass(r : dpt.usm_ndarray, v : dpt.usm_ndarray) -> dpt.usm_ndarray: + "Single pass of sieve of Eratosthenes" + m = dpt.min(r[r > v]) + r[ (r > m) & (r % m == 0) ] = 0 + return m + + def sieve(n : int) -> dpt.usm_ndarray: + "Find primes <=n using sieve of Erathosthenes" + idt = dpt.int32 + s = dpt.concat(( + dpt.arange(2, 3, dtype=idt), + dpt.arange(3, n + 1, 2, dtype=idt) + )) + lb = dpt.zeros(tuple(), dtype=idt) + while lb * lb < n + 1: + lb = sieve_pass(s, lb) + return s[s > 0] + + # get prime numbers <= a million into NumPy array + # to save to disk + ps_np = dpt.asnumpy(sieve(10**6)) + + np.savetxt("primes.txt", ps_np, fmt="%d") From 8d488397c84b5d48d6c6e33e7dad18bb464fe43b Mon Sep 17 00:00:00 2001 From: Vladislav Perevezentsev Date: Thu, 11 Jun 2026 09:43:36 -0700 Subject: [PATCH 42/46] Fix some typos and gaps --- doc/reference/tensor.manipulation_functions.rst | 2 +- doc/reference/tensor.rst | 2 ++ doc/reference/tensor.sorting_functions.rst | 8 ++++---- doc/reference/tensor.usm_ndarray.rst | 4 ++-- doc/reference/tensor.utility_functions.rst | 4 ++-- 5 files changed, 11 insertions(+), 9 deletions(-) diff --git a/doc/reference/tensor.manipulation_functions.rst b/doc/reference/tensor.manipulation_functions.rst index 1749e432c66..1f140e7f3c5 100644 --- a/doc/reference/tensor.manipulation_functions.rst +++ b/doc/reference/tensor.manipulation_functions.rst @@ -5,7 +5,7 @@ Array manipulation functions The following functions conform to `Python Array API standard `_: -.. array_api_spec_manipulation_functions: https://data-apis.org/array-api/latest/API_specification/manipulation_functions.html +.. _array_api_spec_manipulation_functions: https://data-apis.org/array-api/latest/API_specification/manipulation_functions.html .. currentmodule:: dpnp.tensor diff --git a/doc/reference/tensor.rst b/doc/reference/tensor.rst index d482fecb69b..ad4a9c2ce7d 100644 --- a/doc/reference/tensor.rst +++ b/doc/reference/tensor.rst @@ -20,6 +20,8 @@ This module contains: * :ref:`Accumulation functions ` * :ref:`Array creation functions ` * :ref:`Array manipulation functions ` +* :ref:`Data type functions ` +* :ref:`Data types ` * :ref:`Elementwise functions ` * :ref:`Indexing functions ` * :ref:`Introspection functions ` diff --git a/doc/reference/tensor.sorting_functions.rst b/doc/reference/tensor.sorting_functions.rst index b3dac1eff44..785226583bb 100644 --- a/doc/reference/tensor.sorting_functions.rst +++ b/doc/reference/tensor.sorting_functions.rst @@ -6,8 +6,8 @@ Sorting functions .. currentmodule:: dpnp.tensor .. autosummary:: - :toctree: generated + :toctree: generated - argsort - sort - top_k + argsort + sort + top_k diff --git a/doc/reference/tensor.usm_ndarray.rst b/doc/reference/tensor.usm_ndarray.rst index 5b958d673b2..d6ca4e8a873 100644 --- a/doc/reference/tensor.usm_ndarray.rst +++ b/doc/reference/tensor.usm_ndarray.rst @@ -6,13 +6,13 @@ USM array object .. currentmodule:: dpnp.tensor The array object represents a multi-dimensional tensor of uniform elemental datatype allocated on -a :py:class:`Device`. The tensor in stored in a USM allocation, which can be accessed via +a :py:class:`Device`. The tensor is stored in a USM allocation, which can be accessed via :py:attr:`usm_ndarray.base` attribute. Implementation of :py:class:`usm_ndarray` conforms to `Array API standard `_ specification. -.. array_api_array_object: https://data-apis.org/array-api/latest/API_specification/array_object.html +.. _array_api_array_object: https://data-apis.org/array-api/latest/API_specification/array_object.html .. autosummary:: :toctree: generated diff --git a/doc/reference/tensor.utility_functions.rst b/doc/reference/tensor.utility_functions.rst index 5f124667e9f..47d57139d92 100644 --- a/doc/reference/tensor.utility_functions.rst +++ b/doc/reference/tensor.utility_functions.rst @@ -25,5 +25,5 @@ Device object ~sycl_queue ~sycl_device ~sycl_context - ~sycl_usm_shared_memory - ~usm_ndarray_to_device + ~print_device_info + ~wait From 183e6ba4a9fed6d9871f83bd1375514d4b127a3c Mon Sep 17 00:00:00 2001 From: Vladislav Perevezentsev Date: Thu, 11 Jun 2026 10:00:37 -0700 Subject: [PATCH 43/46] Remove cross-reference fallback for dpnp.tensor to dpctl --- doc/conf.py | 66 ----------------------------------------------------- 1 file changed, 66 deletions(-) diff --git a/doc/conf.py b/doc/conf.py index 107edb8956c..0d7625eac45 100644 --- a/doc/conf.py +++ b/doc/conf.py @@ -6,7 +6,6 @@ # http://www.sphinx-doc.org/en/master/config from datetime import datetime -from urllib.parse import urljoin from sphinx.ext.autodoc import FunctionDocumenter from sphinx.ext.napoleon import NumpyDocstring, docstring @@ -235,9 +234,6 @@ def _can_document_member(member, *args, **kwargs): autosummary_generate = True -_DPCTL_021_BASE = "https://intelpython.github.io/dpctl/0.21.1/" -_DPCTL_021_INV = urljoin(_DPCTL_021_BASE, "objects.inv") - intersphinx_mapping = { "python": ("https://docs.python.org/3/", None), "numpy": ("https://numpy.org/doc/stable/", None), @@ -309,65 +305,3 @@ def _parse_returns_section_patched(self, section: str) -> list[str]: NumpyDocstring._parse_returns_section = _parse_returns_section_patched - - -# TODO: Remove once dpnp.tensor docs are generated in dpnp -def _load_dpctl_tensor_inventory(app): - """Load dpctl 0.21.1 inventory for dpnp.tensor fallback only.""" - from sphinx.ext.intersphinx import fetch_inventory - from sphinx.util import logging - - logger = logging.getLogger(__name__) - - try: - inv = fetch_inventory(app, _DPCTL_021_BASE, _DPCTL_021_INV) - except Exception as exc: - logger.warning( - "Failed to load dpctl 0.21.1 inventory from %s: %s", - _DPCTL_021_INV, - exc, - ) - inv = {} - - app.builder.env._dpctl_tensor_021_inventory = inv - - -# TODO: Remove once dpnp.tensor docs are generated in dpnp -def _resolve_dpnp_tensor_refs(app, env, node, contnode): - """Resolve dpnp.tensor.* references to dpctl 0.21.1 documentation. - - This temporary workaround is needed because dpnp.tensor documentation - is not generated yet, while the corresponding API is still documented - in dpctl 0.21.1. - """ - from docutils import nodes as docutils_nodes - - target = node.get("reftarget", "") - if not target.startswith("dpnp.tensor"): - return None - - dpctl_target = target.replace("dpnp.tensor", "dpctl.tensor", 1) - dpctl_tensor_inv = getattr(env, "_dpctl_tensor_021_inventory", {}) - - for _objtype, objects in dpctl_tensor_inv.items(): - if dpctl_target not in objects: - continue - - item = objects[dpctl_target] - location = item.uri - if location.endswith("$"): - location = location[:-1] + dpctl_target - - refuri = urljoin(_DPCTL_021_BASE, location) - newnode = docutils_nodes.reference( - "", "", internal=False, refuri=refuri - ) - newnode += contnode.deepcopy() - return newnode - - return None - - -def setup(app): - app.connect("builder-inited", _load_dpctl_tensor_inventory, priority=400) - app.connect("missing-reference", _resolve_dpnp_tensor_refs, priority=400) From d49a6638fb1700f7e758e8836dc5ea0bdcabda62 Mon Sep 17 00:00:00 2001 From: Vladislav Perevezentsev Date: Thu, 11 Jun 2026 10:01:22 -0700 Subject: [PATCH 44/46] Add :nosignatures: for dpnp.tensor docs --- doc/_templates/autosummary/usm_ndarray.rst | 3 +++ doc/reference/tensor.accumulation_functions.rst | 1 + doc/reference/tensor.creation_functions.rst | 1 + doc/reference/tensor.data_type_functions.rst | 1 + doc/reference/tensor.elementwise_functions.rst | 1 + doc/reference/tensor.indexing_functions.rst | 1 + doc/reference/tensor.inspection.rst | 1 + doc/reference/tensor.linear_algebra.rst | 1 + doc/reference/tensor.manipulation_functions.rst | 1 + doc/reference/tensor.print_functions.rst | 1 + doc/reference/tensor.searching_functions.rst | 1 + doc/reference/tensor.set_functions.rst | 1 + doc/reference/tensor.sorting_functions.rst | 1 + doc/reference/tensor.statistical_functions.rst | 1 + doc/reference/tensor.usm_ndarray.rst | 1 + doc/reference/tensor.utility_functions.rst | 1 + 16 files changed, 18 insertions(+) diff --git a/doc/_templates/autosummary/usm_ndarray.rst b/doc/_templates/autosummary/usm_ndarray.rst index 81026c7cd72..ba358817e27 100644 --- a/doc/_templates/autosummary/usm_ndarray.rst +++ b/doc/_templates/autosummary/usm_ndarray.rst @@ -13,6 +13,7 @@ .. autosummary:: :toctree: generated + :nosignatures: {% for item in methods if item != "__init__" %} ~{{ name }}.{{ item }} {%- endfor %} @@ -25,6 +26,7 @@ .. autosummary:: :toctree: generated + :nosignatures: {% for item in attributes %} ~{{ name }}.{{ item }} {%- endfor %} @@ -33,6 +35,7 @@ .. autosummary:: :toctree: generated + :nosignatures: ~{{name}}.__dlpack_device__ ~{{name}}.__dlpack__ diff --git a/doc/reference/tensor.accumulation_functions.rst b/doc/reference/tensor.accumulation_functions.rst index de0da7c0189..7050cd74f40 100644 --- a/doc/reference/tensor.accumulation_functions.rst +++ b/doc/reference/tensor.accumulation_functions.rst @@ -9,6 +9,7 @@ Accumulation functions compute cumulative results along a given axis of the inpu .. autosummary:: :toctree: generated + :nosignatures: cumulative_logsumexp cumulative_prod diff --git a/doc/reference/tensor.creation_functions.rst b/doc/reference/tensor.creation_functions.rst index 670c7625843..16186954172 100644 --- a/doc/reference/tensor.creation_functions.rst +++ b/doc/reference/tensor.creation_functions.rst @@ -10,6 +10,7 @@ to create new arrays: .. autosummary:: :toctree: generated + :nosignatures: arange asarray diff --git a/doc/reference/tensor.data_type_functions.rst b/doc/reference/tensor.data_type_functions.rst index 6adca69081b..0eecd0a9d06 100644 --- a/doc/reference/tensor.data_type_functions.rst +++ b/doc/reference/tensor.data_type_functions.rst @@ -12,6 +12,7 @@ to `Python Array API specification `_: .. autosummary:: :toctree: generated + :nosignatures: astype can_cast diff --git a/doc/reference/tensor.elementwise_functions.rst b/doc/reference/tensor.elementwise_functions.rst index 291f82abba1..5aac132e2ea 100644 --- a/doc/reference/tensor.elementwise_functions.rst +++ b/doc/reference/tensor.elementwise_functions.rst @@ -10,6 +10,7 @@ function values computed for every element of input array(s). .. autosummary:: :toctree: generated + :nosignatures: :template: autosummary/elementwise.rst abs diff --git a/doc/reference/tensor.indexing_functions.rst b/doc/reference/tensor.indexing_functions.rst index fee0b18a187..22a3233da0e 100644 --- a/doc/reference/tensor.indexing_functions.rst +++ b/doc/reference/tensor.indexing_functions.rst @@ -10,6 +10,7 @@ by either integral arrays of indices or boolean mask arrays. .. autosummary:: :toctree: generated + :nosignatures: extract place diff --git a/doc/reference/tensor.inspection.rst b/doc/reference/tensor.inspection.rst index 3e0f7e54d4e..da4e92c308e 100644 --- a/doc/reference/tensor.inspection.rst +++ b/doc/reference/tensor.inspection.rst @@ -14,6 +14,7 @@ capabilities of an array library as specified in .. autosummary:: :toctree: generated + :nosignatures: :template: autosummary/cython_class.rst __array_api_version__ diff --git a/doc/reference/tensor.linear_algebra.rst b/doc/reference/tensor.linear_algebra.rst index 58df8ebebc7..1371bbd0b1f 100644 --- a/doc/reference/tensor.linear_algebra.rst +++ b/doc/reference/tensor.linear_algebra.rst @@ -7,6 +7,7 @@ Linear algebra functions .. autosummary:: :toctree: generated + :nosignatures: matmul matrix_transpose diff --git a/doc/reference/tensor.manipulation_functions.rst b/doc/reference/tensor.manipulation_functions.rst index 1f140e7f3c5..10700586aa4 100644 --- a/doc/reference/tensor.manipulation_functions.rst +++ b/doc/reference/tensor.manipulation_functions.rst @@ -11,6 +11,7 @@ The following functions conform to `Python Array API standard Date: Thu, 11 Jun 2026 16:25:36 -0700 Subject: [PATCH 45/46] Remove outdated dpctl.tensor docs link from tensor.rst --- doc/tensor.rst | 23 ++++++++++------------- 1 file changed, 10 insertions(+), 13 deletions(-) diff --git a/doc/tensor.rst b/doc/tensor.rst index 22a1812f38a..f433290637f 100644 --- a/doc/tensor.rst +++ b/doc/tensor.rst @@ -3,7 +3,7 @@ Tensor (``dpnp.tensor``) ======================== -``dpnp.tensor`` provides a reference implementation of the +:mod:`dpnp.tensor` provides a reference implementation of the `Python Array API `_ specification. The implementation uses data-parallel algorithms suitable for execution on accelerators, such as GPUs. @@ -11,7 +11,7 @@ accelerators, such as GPUs. It also provides the underlying Array API-compliant implementation used by ``dpnp``. -``dpnp.tensor`` is written using C++ and +:mod:`dpnp.tensor` is written using C++ and `SYCL `_ and oneAPI extensions implemented in `Intel(R) oneAPI DPC++ compiler `_. @@ -22,7 +22,8 @@ Design and Motivation The tensor implementation was originally developed as a standalone project and later integrated into the `dpctl `_ library as ``dpctl.tensor``. It has since been migrated into ``dpnp``, -making ``dpnp`` the primary owner and development location of the tensor implementation. +making ``dpnp`` the primary owner and development location of the +tensor implementation. This change simplifies maintenance, reduces cross-project dependencies, and enables independent development and release cycles. @@ -31,16 +32,16 @@ Relationship to ``dpnp.ndarray`` -------------------------------- :class:`dpnp.ndarray` is a high-level array object built on top of -``dpnp.tensor.usm_ndarray``, storing array data in Unified Shared Memory +:class:`dpnp.tensor.usm_ndarray`, storing array data in Unified Shared Memory (USM) allocated on a SYCL device. Most users interact with -:class:`dpnp.ndarray` directly; ``dpnp.tensor.usm_ndarray`` may appear in error -messages or type signatures when working with device placement or +:class:`dpnp.ndarray` directly; :class:`dpnp.tensor.usm_ndarray` may appear in +error messages or type signatures when working with device placement or interoperability. Relationship to ``dpctl`` ------------------------- -The migration of ``dpctl.tensor`` into ``dpnp.tensor`` does not replace +The migration of ``dpctl.tensor`` into :mod:`dpnp.tensor` does not replace `dpctl `_ itself. ``dpctl`` remains responsible for device and queue management (:class:`dpctl.SyclDevice`, :class:`dpctl.SyclQueue`) as well as USM memory @@ -61,10 +62,6 @@ Example a = dpnp.asarray([1.0, 2.0, 3.0]) assert isinstance(a.get_array(), dpt.usm_ndarray) -.. note:: +.. seealso:: - The ``dpnp.tensor`` API documentation will be added in a future release. - - The current implementation remains compatible with the original - ``dpctl.tensor`` API. For the complete API reference, see the - `dpctl 0.21.1 tensor documentation `_. + :ref:`dpnp.tensor API Reference ` From 02c8775f7dd8d26b8452700f5346c3071e4f8537 Mon Sep 17 00:00:00 2001 From: Vladislav Perevezentsev Date: Thu, 11 Jun 2026 16:42:37 -0700 Subject: [PATCH 46/46] Update usm_ndarray docs --- dpnp/tensor/_usmarray.pyx | 40 +++++++++++++++++++-------------------- 1 file changed, 20 insertions(+), 20 deletions(-) diff --git a/dpnp/tensor/_usmarray.pyx b/dpnp/tensor/_usmarray.pyx index 259ef42b3b1..f29f662222c 100644 --- a/dpnp/tensor/_usmarray.pyx +++ b/dpnp/tensor/_usmarray.pyx @@ -235,26 +235,26 @@ cdef class usm_ndarray: Shape of the array to be created. dtype : {None, str, dtype}, optional Array data type, i.e. the type of array elements. - If ``dtype`` has the value ``None``, it is determined by default - floating point type supported by target device. - The supported types are - - ``bool``: - boolean type - ``int8``, ``int16``, ``int32``, ``int64``: - signed integer types - ``uint8``, ``uint16``, ``uint32``, ``uint64``: - unsigned integer types - ``float16``: - half-precision floating type, - supported if target device's property - ``has_aspect_fp16`` is ``True`` - ``float32``, ``complex64``: - single-precision real and complex floating types - ``float64``, ``complex128``: - double-precision real and complex floating - types, supported if target device's property - ``has_aspect_fp64`` is ``True``. + If ``dtype`` has the value ``None``, it is determined by default + floating point type supported by target device. + The supported types are + + ``bool``: + boolean type + ``int8``, ``int16``, ``int32``, ``int64``: + signed integer types + ``uint8``, ``uint16``, ``uint32``, ``uint64``: + unsigned integer types + ``float16``: + half-precision floating type, + supported if target device's property + ``has_aspect_fp16`` is ``True`` + ``float32``, ``complex64``: + single-precision real and complex floating types + ``float64``, ``complex128``: + double-precision real and complex floating + types, supported if target device's property + ``has_aspect_fp64`` is ``True``. Default: ``None``. strides : {None, tuple}, optional