From be8f445538f5918a6309614be14355409e5aff47 Mon Sep 17 00:00:00 2001 From: Oleksandr Pavlyk Date: Tue, 14 Mar 2023 11:49:37 -0500 Subject: [PATCH 1/5] Closes gh-1114 A pass through doc-strings of dpctl.tensor functions and classes to improve rendering of the documentation and to expand docstring. --- dpctl/tensor/_copy_utils.py | 19 +- dpctl/tensor/_ctors.py | 407 ++++++++++++++---------- dpctl/tensor/_device.py | 17 +- dpctl/tensor/_indexing_functions.py | 36 ++- dpctl/tensor/_manipulation_functions.py | 263 ++++++++++++--- dpctl/tensor/_usmarray.pyx | 5 +- 6 files changed, 508 insertions(+), 239 deletions(-) diff --git a/dpctl/tensor/_copy_utils.py b/dpctl/tensor/_copy_utils.py index d28b737175..748ad3641d 100644 --- a/dpctl/tensor/_copy_utils.py +++ b/dpctl/tensor/_copy_utils.py @@ -128,11 +128,22 @@ def from_numpy(np_ary, device=None, usm_type="device", sycl_queue=None): `numpy.ndarray`. Args: - arg: An instance of `numpy.ndarray` + arg: An instance of input `numpy.ndarray` device: array API specification of device where the output array - is created. - sycl_queue: a :class:`dpctl.SyclQueue` used to create the output - array is created + is created + usm_type: The requested USM allocation type for the output array + sycl_queue: a :class:`dpctl.SyclQueue` instance that determines + output array allocation device as well as placement of data + movement operation. 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. + + 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) diff --git a/dpctl/tensor/_ctors.py b/dpctl/tensor/_ctors.py index b62816ac95..f03553622f 100644 --- a/dpctl/tensor/_ctors.py +++ b/dpctl/tensor/_ctors.py @@ -296,7 +296,7 @@ def _ensure_native_dtype_device_support(dtype, dev) -> None: Return: None Raise: - ValueError is device does not natively support this dtype. + ValueError if device does not natively support this dtype. """ if dtype in [dpt.float64, dpt.complex128] and not dev.has_aspect_fp64: raise ValueError( @@ -336,7 +336,7 @@ def asarray( 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` + `obj`. Default: `None`. copy (`bool`, optional): boolean indicating whether or not to copy the input. If `True`, always creates a copy. If `False`, need to copy raises `ValueError`. If `None`, try to reuse existing memory @@ -358,9 +358,9 @@ def asarray( for output array allocation and copying. `sycl_queue` and `device` are exclusive keywords, i.e. use one or another. If both are specified, a `TypeError` is raised unless both imply the same - underlying SYCL queue to be used. If both are `None`, the - `dpctl.SyclQueue()` is used for allocation and copying. - Default: `None`. + underlying SYCL queue to be used. If both are `None`, a cached + queue targeting default-selected device is used for allocation and + copying. Default: `None`. """ # 1. Check that copy is a valid keyword if copy not in [None, True, False]: @@ -486,7 +486,8 @@ def empty( shape (tuple): Dimensions of the array to be created. dtype (optional): data type of the array. Can be typestring, a `numpy.dtype` object, `numpy` char string, or a numpy - scalar type. Default: None + 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, @@ -500,9 +501,9 @@ def empty( for output array allocation and copying. `sycl_queue` and `device` are exclusive keywords, i.e. use one or another. If both are specified, a `TypeError` is raised unless both imply the same - underlying SYCL queue to be used. If both are `None`, the - `dpctl.SyclQueue()` is used for allocation and copying. - Default: `None`. + underlying SYCL queue to be used. If both are `None`, a cached + queue targeting default-selected device is used for allocation + and copying. Default: `None`. """ if not isinstance(order, str) or len(order) == 0 or order[0] not in "CcFf": raise ValueError( @@ -573,14 +574,20 @@ def arange( sycl_queue=None, ): """ arange(start, /, stop=None, step=1, *, dtype=None, \ - device=None, usm_type="device", sycl_queue=None) -> usm_ndarray + device=None, usm_type="device", sycl_queue=None) + + Returns evenly spaced values within the half-open interval [start, stop) + as a one-dimensional array. Args: - start: + 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 + 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 `Device` object returned by `dpctl.tensor.usm_array.device`. Default: `None`. usm_type ("device"|"shared"|"host", optional): The type of SYCL USM @@ -589,9 +596,9 @@ def arange( for output array allocation and copying. `sycl_queue` and `device` are exclusive keywords, i.e. use one or another. If both are specified, a `TypeError` is raised unless both imply the same - underlying SYCL queue to be used. If both are `None`, the - `dpctl.SyclQueue()` is used for allocation and copying. - Default: `None`. + underlying SYCL queue to be used. If both are `None`, a cached + queue targeting default-selected device is used for allocation + and copying. Default: `None`. """ if stop is None: stop = start @@ -662,19 +669,21 @@ def zeros( usm_type="device", sycl_queue=None, ): - """ - Creates `usm_ndarray` with zero elements. + """ zeros(shape, dtype=None, order="C", device=None, \ + usm_type="device", sycl_queue=None) + + Returns a new `usm_ndarray` having a specified shape and filled with zeros. Args: shape (tuple): Dimensions of the array to be created. dtype (optional): data type of the array. Can be typestring, a `numpy.dtype` object, `numpy` char string, or a numpy - scalar type. Default: None - order ("C", or F"): memory layout for the array. Default: "C" + 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 + 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 `Device` object returnedby `dpctl.tensor.usm_array.device`. Default: `None`. usm_type ("device"|"shared"|"host", optional): The type of SYCL USM @@ -683,9 +692,9 @@ def zeros( for output array allocation and copying. `sycl_queue` and `device` are exclusive keywords, i.e. use one or another. If both are specified, a `TypeError` is raised unless both imply the same - underlying SYCL queue to be used. If both are `None`, the - `dpctl.SyclQueue()` is used for allocation and copying. - Default: `None`. + underlying SYCL queue to be used. If both are `None`, a cached + queue targeting default-selected device is used for allocation + and copying. Default: `None`. """ if not isinstance(order, str) or len(order) == 0 or order[0] not in "CcFf": raise ValueError( @@ -715,19 +724,22 @@ def ones( usm_type="device", sycl_queue=None, ): - """ - Creates `usm_ndarray` with elements of one. + """ ones(shape, dtype=None, order="C", \ + device=None, usm_type="device", sycl_queue=None) + + Returns a new `usm_ndarray` having a specified `shape` and filled with + ones. Args: shape (tuple): Dimensions of the array to be created. dtype (optional): data type of the array. Can be typestring, a `numpy.dtype` object, `numpy` char string, or a numpy - scalar type. Default: None - order ("C", or F"): memory layout for the array. Default: "C" + 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 + 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 `Device` object returnedby `dpctl.tensor.usm_array.device`. Default: `None`. usm_type ("device"|"shared"|"host", optional): The type of SYCL USM @@ -736,9 +748,9 @@ def ones( for output array allocation and copying. `sycl_queue` and `device` are exclusive keywords, i.e. use one or another. If both are specified, a `TypeError` is raised unless both imply the same - underlying SYCL queue to be used. If both are `None`, the - `dpctl.SyclQueue()` is used for allocation and copying. - Default: `None`. + underlying SYCL queue to be used. If both are `None`, a cached + queue targeting default-selected device is used for allocation + and copying. Default: `None`. """ if not isinstance(order, str) or len(order) == 0 or order[0] not in "CcFf": raise ValueError( @@ -769,31 +781,37 @@ def full( usm_type=None, sycl_queue=None, ): - """ - Creates `usm_ndarray` with elements of one. + """ full(shape, fill_value, dtype=None, order="C", \ + device=None, usm_type=None, sycl_queue=None) + + Returns a new `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): fill value dtype (optional): data type of the array. Can be typestring, a `numpy.dtype` object, `numpy` char string, or a numpy - scalar type. Default: None + 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 + 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 `Device` object returnedby `dpctl.tensor.usm_array.device`. Default: `None`. - usm_type ("device"|"shared"|"host", optional): The type of SYCL USM - allocation for the output array. Default: `"device"`. + usm_type ("device"|"shared"|"host"|None, optional): The type of SYCL + USM allocation for the output array. If `usm_type` is `None`, it is + inferred from `fill_value` input if it is an instance of + `ums_ndarray`, or interpreted as `"device"` otherwise. + Default: `None`. sycl_queue (:class:`dpctl.SyclQueue`, optional): The SYCL queue to use for output array allocation and copying. `sycl_queue` and `device` are exclusive keywords, i.e. use one or another. If both are specified, a `TypeError` is raised unless both imply the same - underlying SYCL queue to be used. If both are `None`, the - `dpctl.SyclQueue()` is used for allocation and copying. - Default: `None`. + underlying SYCL queue to be used. If both are `None`, a cached + queue targeting default-selected device is used for allocation + and copying. Default: `None`. """ if not isinstance(order, str) or len(order) == 0 or order[0] not in "CcFf": raise ValueError( @@ -846,31 +864,35 @@ def full( def empty_like( x, dtype=None, order="C", device=None, usm_type=None, sycl_queue=None ): - """ - Creates `usm_ndarray` from uninitialized USM allocation. + """ empty_like(x, dtype=None, order="C", \ + device=None, usm_type=None, sycl_queue=None) + + Returns an uninitialized `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 typestring, a `numpy.dtype` object, `numpy` char string, or a numpy - scalar type. Default: None - order ("C", or F"): memory layout for the array. Default: "C" + 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 + 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 `Device` object returnedby `dpctl.tensor.usm_array.device`. Default: `None`. - usm_type ("device"|"shared"|"host", optional): The type of SYCL USM - allocation for the output array. Default: `"device"`. + usm_type ("device"|"shared"|"host"|None, optional): The type of SYCL + USM allocation for the output array. If `usm_type` is `None`, the + the `usm_type` is inferred from the input array. Default: `None`. sycl_queue (:class:`dpctl.SyclQueue`, optional): The SYCL queue to use for output array allocation and copying. `sycl_queue` and `device` are exclusive keywords, i.e. use one or another. If both are specified, a `TypeError` is raised unless both imply the same - underlying SYCL queue to be used. If both are `None`, the - `dpctl.SyclQueue()` is used for allocation and copying. - Default: `None`. + underlying SYCL queue to be used. If both are `None`, a cached + queue targeting default-selected device is used for allocation + and copying. Default: `None`. """ if not isinstance(x, dpt.usm_ndarray): raise TypeError(f"Expected instance of dpt.usm_ndarray, got {type(x)}.") @@ -903,31 +925,35 @@ def empty_like( def zeros_like( x, dtype=None, order="C", device=None, usm_type=None, sycl_queue=None ): - """ + """ zeros_like(x, dtype=None, order="C", \ + device=None, usm_type=None, sycl_queue=None) + Creates `usm_ndarray` from USM allocation initialized with zeros. Args: - x (usm_ndarray): Input array from which to derive the output array - shape. + 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 `numpy.dtype` object, `numpy` char string, or a numpy - scalar type. Default: None - order ("C", or F"): memory layout for the array. Default: "C" + 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 + 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 `Device` object returnedby `dpctl.tensor.usm_array.device`. Default: `None`. - usm_type ("device"|"shared"|"host", optional): The type of SYCL USM - allocation for the output array. Default: `"device"`. + usm_type ("device"|"shared"|"host"|None, optional): The type of SYCL + USM allocation for the output array. If `None`, output array has + the same USM allocation type as the input array. Default: `None`. sycl_queue (:class:`dpctl.SyclQueue`, optional): The SYCL queue to use for output array allocation and copying. `sycl_queue` and `device` are exclusive keywords, i.e. use one or another. If both are specified, a `TypeError` is raised unless both imply the same - underlying SYCL queue to be used. If both are `None`, the - `dpctl.SyclQueue()` is used for allocation and copying. - Default: `None`. + underlying SYCL queue to be used. If both are `None`, a cached + queue targeting default-selected device is used for allocation + and copying. Default: `None`. """ if not isinstance(x, dpt.usm_ndarray): raise TypeError(f"Expected instance of dpt.usm_ndarray, got {type(x)}.") @@ -959,31 +985,35 @@ def zeros_like( def ones_like( x, dtype=None, order="C", device=None, usm_type=None, sycl_queue=None ): - """ - Creates `usm_ndarray` from USM allocation initialized with zeros. + """ ones_like(x, dtype=None, order="C", \ + device=None, usm_type=None, sycl_queue=None) + + Returns a new `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 `numpy.dtype` object, `numpy` char string, or a numpy - scalar type. Default: None - order ("C", or F"): memory layout for the array. Default: "C" + 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 + 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 `Device` object returnedby `dpctl.tensor.usm_array.device`. Default: `None`. - usm_type ("device"|"shared"|"host", optional): The type of SYCL USM - allocation for the output array. Default: `"device"`. + usm_type ("device"|"shared"|"host"|None, optional): The type of SYCL + USM allocation for the output array. If `None`, output array has + the same USM allocation type as the input array. Default: `None`. sycl_queue (:class:`dpctl.SyclQueue`, optional): The SYCL queue to use for output array allocation and copying. `sycl_queue` and `device` are exclusive keywords, i.e. use one or another. If both are specified, a `TypeError` is raised unless both imply the same - underlying SYCL queue to be used. If both are `None`, the - `dpctl.SyclQueue()` is used for allocation and copying. - Default: `None`. + underlying SYCL queue to be used. If both are `None`, a cached + queue targeting default-selected device is used for allocation + and copying. Default: `None`. """ if not isinstance(x, dpt.usm_ndarray): raise TypeError(f"Expected instance of dpt.usm_ndarray, got {type(x)}.") @@ -1021,32 +1051,38 @@ def full_like( usm_type=None, sycl_queue=None, ): - """ - Creates `usm_ndarray` from USM allocation initialized with zeros. + """ full_like(x, fill_value, dtype=None, order="C", \ + device=None, usm_type=None, sycl_queue=None) + + Returns a new `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 array with + fill_value: the value to fill output array with dtype (optional): data type of the array. Can be typestring, a `numpy.dtype` object, `numpy` char string, or a numpy - scalar type. Default: None - order ("C", or F"): memory layout for the array. Default: "C" + scalar type. If `dtype` is `None`, the output array data type is + inferred from `x`. 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 + 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 `Device` object returnedby `dpctl.tensor.usm_array.device`. Default: `None`. - usm_type ("device"|"shared"|"host", optional): The type of SYCL USM - allocation for the output array. Default: `"device"`. + usm_type ("device"|"shared"|"host"|None, optional): The type of SYCL + USM allocation for the output array. If `None`, output array has + the same USM allocation type as the input array `x`. + Default: `None`. sycl_queue (:class:`dpctl.SyclQueue`, optional): The SYCL queue to use for output array allocation and copying. `sycl_queue` and `device` are exclusive keywords, i.e. use one or another. If both are specified, a `TypeError` is raised unless both imply the same - underlying SYCL queue to be used. If both are `None`, the - `dpctl.SyclQueue()` is used for allocation and copying. - Default: `None`. + underlying SYCL queue to be used. If both are `None`, a cached + queue targeting default-selected device is used for allocation + and copying. Default: `None`. """ if not isinstance(x, dpt.usm_ndarray): raise TypeError(f"Expected instance of dpt.usm_ndarray, got {type(x)}.") @@ -1089,8 +1125,8 @@ def linspace( usm_type="device", ): """ - linspace(start, stop, num, dtype=None, device=None, endpoint=True, - sycl_queue=None, usm_type=None): usm_ndarray + linspace(start, stop, num, dtype=None, device=None, endpoint=True, \ + sycl_queue=None, usm_type="device") Returns evenly spaced numbers of specified interval. @@ -1105,7 +1141,7 @@ def linspace( array must consist of evenly spaced numbers over the closed interval `[start, stop]`. Default: `True`. num: number of samples. Must be a non-negative integer; otherwise, - the function must raise an exception. + 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. Default: `None`. @@ -1121,9 +1157,9 @@ def linspace( for output array allocation and copying. `sycl_queue` and `device` are exclusive keywords, i.e. use one or another. If both are specified, a `TypeError` is raised unless both imply the same - underlying SYCL queue to be used. If both are `None`, the - `dpctl.SyclQueue()` is used for allocation and copying. - Default: `None`. + underlying SYCL queue to be used. If both are `None`, a cached + queue targeting default-selected device is used for allocation + and copying. Default: `None`. endpoint: boolean indicating whether to include `stop` in the interval. Default: `True`. """ @@ -1171,10 +1207,10 @@ def eye( sycl_queue=None, ): """ - eye(n_rows, n_cols = None, /, *, k = 0, dtype = None, \ - device = None, usm_type="device", sycl_queue=None) -> usm_ndarray + eye(n_rows, n_cols=None, /, *, k=0, dtype=None, \ + device=None, usm_type="device", sycl_queue=None) - Creates `usm_ndarray` with ones on the `k`th diagonal. + Creates `usm_ndarray` with ones on the `k`-th diagonal. Args: n_rows: number of rows in the output array. @@ -1183,16 +1219,16 @@ def eye( k: 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 `TypeError` if k is not an integer. + Raises `TypeError` if `k` is not an integer. Default: `0`. dtype (optional): data type of the array. Can be typestring, a `numpy.dtype` object, `numpy` char string, or a numpy - scalar type. Default: None + 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 + 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 `Device` object returnedby `dpctl.tensor.usm_array.device`. Default: `None`. usm_type ("device"|"shared"|"host", optional): The type of SYCL USM @@ -1201,9 +1237,9 @@ def eye( for output array allocation and copying. `sycl_queue` and `device` are exclusive keywords, i.e. use one or another. If both are specified, a `TypeError` is raised unless both imply the same - underlying SYCL queue to be used. If both are `None`, the - `dpctl.SyclQueue()` is used for allocation and copying. - Default: `None`. + underlying SYCL queue to be used. If both are `None`, a cached + queue targeting default-selected device is used for allocation + and copying. Default: `None`. """ if not isinstance(order, str) or len(order) == 0 or order[0] not in "CcFf": raise ValueError( @@ -1239,134 +1275,167 @@ def eye( return res -def tril(X, k=0): +def tril(x, k=0): """ - tril(X: usm_ndarray, k: int) -> usm_ndarray + tril(x, k=0) + + Returns the lower triangular part of a matrix (or a stack of matrices) `x`. - Returns the lower triangular part of a matrix (or a stack of matrices) X. + 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`. """ - if not isinstance(X, dpt.usm_ndarray): + if not isinstance(x, dpt.usm_ndarray): raise TypeError( "Expected argument of type dpctl.tensor.usm_ndarray, " - f"got {type(X)}." + f"got {type(x)}." ) k = operator.index(k) - order = "F" if (X.flags.f_contiguous) else "C" + order = "F" if (x.flags.f_contiguous) else "C" - shape = X.shape - nd = X.ndim + shape = x.shape + nd = x.ndim if nd < 2: raise ValueError("Array dimensions less than 2.") + q = x.sycl_queue if k >= shape[nd - 1] - 1: res = dpt.empty( - X.shape, - dtype=X.dtype, + x.shape, + dtype=x.dtype, order=order, - usm_type=X.usm_type, - sycl_queue=X.sycl_queue, + usm_type=x.usm_type, + sycl_queue=q, ) hev, _ = ti._copy_usm_ndarray_into_usm_ndarray( - src=X, dst=res, sycl_queue=X.sycl_queue + src=x, dst=res, sycl_queue=q ) hev.wait() elif k < -shape[nd - 2]: res = dpt.zeros( - X.shape, - dtype=X.dtype, + x.shape, + dtype=x.dtype, order=order, - usm_type=X.usm_type, - sycl_queue=X.sycl_queue, + usm_type=x.usm_type, + sycl_queue=q, ) else: res = dpt.empty( - X.shape, - dtype=X.dtype, + x.shape, + dtype=x.dtype, order=order, - usm_type=X.usm_type, - sycl_queue=X.sycl_queue, + usm_type=x.usm_type, + sycl_queue=q, ) - hev, _ = ti._tril(src=X, dst=res, k=k, sycl_queue=X.sycl_queue) + hev, _ = ti._tril(src=x, dst=res, k=k, sycl_queue=q) hev.wait() return res -def triu(X, k=0): +def triu(x, k=0): """ - triu(X: usm_ndarray, k: int) -> usm_ndarray + triu(x, k=0) + + Returns the upper triangular part of a matrix (or a stack of matrices) `x`. - Returns the upper triangular part of a matrix (or a stack of matrices) X. + 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`. """ - if not isinstance(X, dpt.usm_ndarray): + if not isinstance(x, dpt.usm_ndarray): raise TypeError( "Expected argument of type dpctl.tensor.usm_ndarray, " - f"got {type(X)}." + f"got {type(x)}." ) k = operator.index(k) - order = "F" if (X.flags.f_contiguous) else "C" + order = "F" if (x.flags.f_contiguous) else "C" - shape = X.shape - nd = X.ndim + shape = x.shape + nd = x.ndim if nd < 2: raise ValueError("Array dimensions less than 2.") + q = x.sycl_queue if k > shape[nd - 1]: res = dpt.zeros( - X.shape, - dtype=X.dtype, + x.shape, + dtype=x.dtype, order=order, - usm_type=X.usm_type, - sycl_queue=X.sycl_queue, + usm_type=x.usm_type, + sycl_queue=q, ) elif k <= -shape[nd - 2] + 1: res = dpt.empty( - X.shape, - dtype=X.dtype, + x.shape, + dtype=x.dtype, order=order, - usm_type=X.usm_type, - sycl_queue=X.sycl_queue, + usm_type=x.usm_type, + sycl_queue=q, ) hev, _ = ti._copy_usm_ndarray_into_usm_ndarray( - src=X, dst=res, sycl_queue=X.sycl_queue + src=x, dst=res, sycl_queue=q ) hev.wait() else: res = dpt.empty( - X.shape, - dtype=X.dtype, + x.shape, + dtype=x.dtype, order=order, - usm_type=X.usm_type, - sycl_queue=X.sycl_queue, + usm_type=x.usm_type, + sycl_queue=q, ) - hev, _ = ti._triu(src=X, dst=res, k=k, sycl_queue=X.sycl_queue) + hev, _ = ti._triu(src=x, dst=res, k=k, sycl_queue=q) hev.wait() return res def meshgrid(*arrays, indexing="xy"): - - """ - meshgrid(*arrays, indexing="xy") -> list[usm_ndarray] + """meshgrid(*arrays, indexing="xy") Creates list of `usm_ndarray` coordinate matrices from vectors. Args: - arrays: arbitrary number of one-dimensional `USM_ndarray` objects. - If vectors are not of the same data type, - or are not one-dimensional, raises `ValueError.` + arrays (usm_ndarray): an arbitrary number of one-dimensional arrays + representing grid coordinates. Each array should have the same + numeric data type. indexing: Cartesian (`xy`) or matrix (`ij`) indexing of output. - For a set of `n` vectors with lengths N0, N1, N2, ... - Cartesian indexing results in arrays of shape - (N1, N0, N2, ...) + 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`. + + Returns: + out (List[array]): list 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, ...) + `(N0, N1, N2, ...)`. Default: `xy`. + + Raises: + ValueError: If vectors are not of the same data type, or are not + one-dimensional. + """ ref_dt = None ref_unset = True diff --git a/dpctl/tensor/_device.py b/dpctl/tensor/_device.py index 07a3e41e09..af36239f10 100644 --- a/dpctl/tensor/_device.py +++ b/dpctl/tensor/_device.py @@ -39,14 +39,16 @@ def __new__(cls, *args, **kwargs): raise TypeError("No public constructor") @classmethod - def create_device(cls, dev): - """ + def create_device(cls, dev=None): + """Device.create_device(dev=None) + Creates instance of Device from argument. Args: - dev: None, :class:`.Device`, :class:`dpctl.SyclQueue`, or - a :class:`dpctl.SyclDevice` corresponding to a root SYCL - device. + dev: + 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 @@ -135,14 +137,13 @@ def __hash__(self): def normalize_queue_device(sycl_queue=None, device=None): - """ - 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): + 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 diff --git a/dpctl/tensor/_indexing_functions.py b/dpctl/tensor/_indexing_functions.py index ee0587138d..54f1bcca05 100644 --- a/dpctl/tensor/_indexing_functions.py +++ b/dpctl/tensor/_indexing_functions.py @@ -32,18 +32,20 @@ def take(x, indices, /, *, axis=None, mode="clip"): Takes elements from array along a given axis. Args: - x: usm_ndarray + x (usm_ndarray): The array that elements will be taken from. - indices: usm_ndarray + indices (usm_ndarray): One-dimensional array of indices. axis: The axis over which the values will be selected. If x is one-dimensional, this argument is optional. + Default: `None`. mode: How out-of-bounds indices will be handled. - "Clip" - clamps indices to (-n <= i < n), then wraps + "clip" - clamps indices to (-n <= i < n), then wraps negative indices. - "Wrap" - wraps both negative and positive indices. + "wrap" - wraps both negative and positive indices. + Default: `"clip"`. Returns: out: usm_ndarray @@ -119,9 +121,9 @@ def put(x, indices, vals, /, *, axis=None, mode="clip"): along a given axis. Args: - x: usm_ndarray + x (usm_ndarray): The array the values will be put into. - indices: usm_ndarray + indices (usm_ndarray) One-dimensional array of indices. vals: Array of values to be put into `x`. @@ -129,11 +131,13 @@ def put(x, indices, vals, /, *, axis=None, mode="clip"): axis: The axis over which the values will be placed. If x is one-dimensional, this argument is optional. + Default: `None`. mode: How out-of-bounds indices will be handled. - "Clip" - clamps indices to (-axis_size <= i < axis_size), + "clip" - clamps indices to (-axis_size <= i < axis_size), then wraps negative indices. - "Wrap" - wraps both negative and positive indices. + "wrap" - wraps both negative and positive indices. + Default: `"clip"`. """ if not isinstance(x, dpt.usm_ndarray): raise TypeError( @@ -219,14 +223,14 @@ def extract(condition, arr): ``dpctl.tensor.extract``. Args: - conditions: usm_ndarray + conditions (usm_ndarray): An array whose non-zero or True entries indicate the element of `arr` to extract. - arr: usm_ndarray + arr (usm_ndarray): Input array of the same size as `condition`. Returns: - usm_ndarray + out (usm_ndarray): Rank 1 array of values from `arr` where `condition` is True. """ if not isinstance(condition, dpt.usm_ndarray): @@ -259,11 +263,11 @@ def place(arr, mask, vals): equivalent to ``arr[condition] = vals``. Args: - arr: usm_ndarray + arr (usm_ndarray): Array to put data into. - mask: usm_ndarray + mask (usm_ndarray): Boolean mask array. Must have the same size as `arr`. - vals: usm_ndarray + 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 @@ -325,10 +329,10 @@ def nonzero(arr): row-major, C-style order. Args: - arr: usm_ndarray + arr (usm_ndarray): Input array, which has non-zero array rank. Returns: - Tuple[usm_ndarray] + out: Tuple[usm_ndarray, ...] Indices of non-zero array elements. """ if not isinstance(arr, dpt.usm_ndarray): diff --git a/dpctl/tensor/_manipulation_functions.py b/dpctl/tensor/_manipulation_functions.py index 49c401397b..385461b83f 100644 --- a/dpctl/tensor/_manipulation_functions.py +++ b/dpctl/tensor/_manipulation_functions.py @@ -34,7 +34,7 @@ class finfo_object(np.finfo): """ numpy.finfo subclass which returns Python floating-point scalars for - eps, max, min, and smallest_normal. + `eps`, `max`, `min`, and `smallest_normal` attributes. """ def __init__(self, dtype): @@ -118,11 +118,21 @@ def _broadcast_shapes(*args): def permute_dims(X, axes): - """ - permute_dims(X: usm_ndarray, axes: tuple or list) -> usm_ndarray + """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: + out (usm_narray): an array containing the axes permutation. + 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)}.") @@ -146,12 +156,32 @@ def permute_dims(X, axes): def expand_dims(X, axis): - """ - expand_dims(X: usm_ndarray, axis: int or tuple or list) -> usm_ndarray + """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; returns a view, if possible, - a copy otherwise with the number of dimensions increased. + of size one at the position specified by axis. + + Args: + x (usm_ndarray): input array + axis (int): axis position (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, + 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 provided axis position is invalid. """ if not isinstance(X, dpt.usm_ndarray): raise TypeError(f"Expected usm_ndarray type, got {type(X)}.") @@ -168,12 +198,24 @@ def expand_dims(X, axis): def squeeze(X, axis=None): - """ - squeeze(X: usm_ndarray, axis: int or tuple or list) -> usm_ndarray + """squeeze(x, axis) - Removes singleton dimensions (axis) from X; returns a view, if possible, - a copy otherwise, but with all or a subset of the dimensions - of length 1 removed. + Removes singleton dimensions (axes) from array `x`. + + Args: + x (usm_ndarray): input array + axis (Union[int, Tuple[int,...]]): 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)}.") @@ -202,11 +244,21 @@ def squeeze(X, axis=None): def broadcast_to(X, shape): - """ - broadcast_to(X: usm_ndarray, shape: tuple or list) -> usm_ndarray + """broadcast_to(x, shape) - Broadcast an array to a new shape; returns the broadcasted + Broadcast an array to a new `shape`; returns the broadcasted array 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: + 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)}.") @@ -228,10 +280,19 @@ def broadcast_to(X, shape): def broadcast_arrays(*args): - """ - broadcast_arrays(*args: usm_ndarrays) -> list of usm_ndarrays + """broadcast_arrays(*arrays) Broadcasts one or more usm_ndarrays against one another. + + Args: + arrays (usm_ndarray): an arbitrary number of arrays to be + broadcasted. + + Returns: + out (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. """ for X in args: if not isinstance(X, dpt.usm_ndarray): @@ -246,12 +307,22 @@ def broadcast_arrays(*args): def flip(X, axis=None): - """ - flip(X: usm_ndarray, axis: int or tuple or list) -> usm_ndarray + """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`. - Reverses the order of elements in an array along the given axis. - The shape of the array is preserved, but the elements are reordered; - returns a view of X with the entries of axis reversed. + 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)}.") @@ -268,15 +339,34 @@ def flip(X, axis=None): def roll(X, shift, axis=None): """ - roll(X: usm_ndarray, shift: int or tuple or list,\ - axis: int or tuple or list) -> usm_ndarray + 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. - returns an output array having the same data type as X and whose elements, - relative to X, are shifted. + + 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: + 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)}.") @@ -372,10 +462,29 @@ def _check_same_shapes(X0_shape, axis, n, arrays): def concat(arrays, axis=0): - """ - concat(arrays: tuple or list of usm_ndarrays, axis: int) -> usm_ndarray + """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: + 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. """ res_dtype, res_usm_type, exec_q = _arrays_validation(arrays) @@ -419,9 +528,27 @@ def concat(arrays, axis=0): def stack(arrays, axis=0): """ - stack(arrays: tuple or list of usm_ndarrays, axis: int) -> usm_ndarray + 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: + 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) @@ -460,11 +587,19 @@ def stack(arrays, axis=0): def can_cast(from_, to, casting="safe"): - """ - can_cast(from: usm_ndarray or dtype, to: dtype) -> bool + """ can_cast(from, to, casting="safe") Determines if one data type can be cast to another data type according \ - to Type Promotion Rules rules. + to Type Promotion Rules. + + Args: + from (usm_ndarray, dtype): source data type + to (dtype): target data type + casting ({'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional): + controls what kind of data casting may occur. + + Returns: + out (bool): True if cast can occur according to the casting rule. """ if isinstance(to, dpt.usm_ndarray): raise TypeError("Expected dtype type.") @@ -482,11 +617,17 @@ def can_cast(from_, to, casting="safe"): def result_type(*arrays_and_dtypes): """ - result_type(arrays_and_dtypes: an arbitrary number usm_ndarrays or dtypes)\ - -> dtype + result_type(arrays_and_dtypes) Returns the dtype that results from applying the Type Promotion Rules to \ the arguments. + + Args: + arrays_and_dtypes: An arbitrary length sequence of arrays or dtypes. + + Returns: + out (dtype): the dtype resulting from an operation involving the + input arrays and dtypes. """ dtypes = [ X.dtype if isinstance(X, dpt.usm_ndarray) else dpt.dtype(X) @@ -499,25 +640,65 @@ def result_type(*arrays_and_dtypes): def iinfo(dtype): - """ - iinfo(dtype: integer data-type) -> iinfo_object + """iinfo(dtype) Returns machine limits for integer data types. + + Args: + dtype (dtype, usm_ndarray): integer dtype or + an array with integer dtype. + + Returns: + out (iinfo_object): an object with the followign 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): - raise TypeError("Expected dtype type, got {to}.") + dtype = dtype.dtype _supported_dtype([dpt.dtype(dtype)]) return np.iinfo(dtype) def finfo(dtype): - """ - finfo(type: float data-type) -> finfo_object + """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: + out (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. - Returns machine limits for float data types. """ if isinstance(dtype, dpt.usm_ndarray): - raise TypeError("Expected dtype type, got {to}.") + dtype = dtype.dtype + _supported_dtype([dpt.dtype(dtype)]) return finfo_object(dtype) diff --git a/dpctl/tensor/_usmarray.pyx b/dpctl/tensor/_usmarray.pyx index 1abc1e88ac..ea57959cb6 100644 --- a/dpctl/tensor/_usmarray.pyx +++ b/dpctl/tensor/_usmarray.pyx @@ -104,7 +104,10 @@ cdef class InternalUSMArrayError(Exception): cdef class usm_ndarray: - """ usm_ndarray(shape, dtype="|f8", strides=None, buffer="device", offset=0, order="C", buffer_ctor_kwargs=dict(), array_namespace=None) + """ usm_ndarray(shape, dtype="|f8", strides=None, buffer="device", \ + offset=0, order="C", buffer_ctor_kwargs=dict(), \ + array_namespace=None) + See :class:`dpctl.memory.MemoryUSMShared` for allowed keyword arguments. From 65712b81d9cd90d832c9f9f14da0854773d96908 Mon Sep 17 00:00:00 2001 From: Oleksandr Pavlyk Date: Tue, 14 Mar 2023 12:37:25 -0500 Subject: [PATCH 2/5] Ensure clean summary string for array printing functions. --- dpctl/tensor/_print.py | 23 ++++++++++++++++------- 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/dpctl/tensor/_print.py b/dpctl/tensor/_print.py index 15c06a875f..c92172286e 100644 --- a/dpctl/tensor/_print.py +++ b/dpctl/tensor/_print.py @@ -181,12 +181,15 @@ def set_print_options( def get_print_options(): - """ - get_print_options() -> dict + """get_print_options() Returns a copy of current options for printing ``dpctl.tensor.usm_ndarray`` class. + Returns: + out (dict): dictionary with array + printing option settings. + Options: - "linewidth" : int, default 75 - "edgeitems" : int, default 3 @@ -256,7 +259,7 @@ def usm_ndarray_str( usm_ndarray_str(x, line_width=None, edgeitems=None, threshold=None, precision=None, floatmode=None, suppress=None, sign=None, numpy=False, separator=" ", prefix="", - suffix="") -> str + suffix="") Returns a string representing the elements of a ``dpctl.tensor.usm_ndarray``. @@ -317,6 +320,9 @@ def usm_ndarray_str( suffix (str, optional): String that determines length of the last line of the array string. Default: "" + + Returns: + out (str): string representation of intpu array. """ if not isinstance(x, dpt.usm_ndarray): raise TypeError(f"Expected dpctl.tensor.usm_ndarray, got {type(x)}") @@ -356,11 +362,11 @@ def usm_ndarray_repr( ): """ usm_ndarray_repr(x, line_width=None, precision=None, - suppress=None, prefix="") -> str + suppress=None, prefix="") - Returns a formatted string representing the elements - of a ``dpctl.tensor.usm_ndarray`` and its data type, - if not a default type. + Returns a formatted string representing the elements + of a ``dpctl.tensor.usm_ndarray`` and its data type, + if not a default type. Args: x (usm_ndarray): Input array. @@ -377,6 +383,9 @@ def usm_ndarray_repr( prefix (str, optional): String inserted at the start of the array string. Default: "" + + Returns: + out (str): formatted string representing the input array """ if not isinstance(x, dpt.usm_ndarray): raise TypeError(f"Expected dpctl.tensor.usm_ndarray, got {type(x)}") From ad65287f0e903d61cbf65302f1a8dbe78e26be58 Mon Sep 17 00:00:00 2001 From: Oleksandr Pavlyk Date: Tue, 14 Mar 2023 15:17:02 -0500 Subject: [PATCH 3/5] Fixed spacing in docstring of dpt.place --- dpctl/tensor/_indexing_functions.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/dpctl/tensor/_indexing_functions.py b/dpctl/tensor/_indexing_functions.py index 54f1bcca05..f166e94f49 100644 --- a/dpctl/tensor/_indexing_functions.py +++ b/dpctl/tensor/_indexing_functions.py @@ -265,9 +265,9 @@ def place(arr, mask, vals): Args: arr (usm_ndarray): Array to put data into. - mask (usm_ndarray): + mask (usm_ndarray): Boolean mask array. Must have the same size as `arr`. - vals (usm_ndarray, sequence): + 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 From 81bf848b051ae1e1d0ec8f77243fc9a1ded6f4ab Mon Sep 17 00:00:00 2001 From: Oleksandr Pavlyk Date: Tue, 14 Mar 2023 15:17:32 -0500 Subject: [PATCH 4/5] Provided summary to validate_usm_type utility function --- dpctl/utils/_compute_follows_data.pyx | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/dpctl/utils/_compute_follows_data.pyx b/dpctl/utils/_compute_follows_data.pyx index 179fb6f875..92f29b7765 100644 --- a/dpctl/utils/_compute_follows_data.pyx +++ b/dpctl/utils/_compute_follows_data.pyx @@ -123,7 +123,24 @@ def _validate_usm_type_disallow_none(usm_type): def validate_usm_type(usm_type, allow_none=True): - "Validates usm_type argument" + """ 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"`, or `"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 an unrecognized 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 49c3a9cc595be7b0d2ff413f184c4848c6a99876 Mon Sep 17 00:00:00 2001 From: Oleksandr Pavlyk Date: Tue, 14 Mar 2023 16:38:43 -0500 Subject: [PATCH 5/5] Fixed docstrings with remnants of old header style --- dpctl/tensor/_dlpack.pyx | 23 ++++++++++++++--------- dpctl/tensor/_reshape.py | 23 +++++++++++++++++++---- 2 files changed, 33 insertions(+), 13 deletions(-) diff --git a/dpctl/tensor/_dlpack.pyx b/dpctl/tensor/_dlpack.pyx index 1d4d72df2d..eb9849c5e8 100644 --- a/dpctl/tensor/_dlpack.pyx +++ b/dpctl/tensor/_dlpack.pyx @@ -469,13 +469,25 @@ cpdef usm_ndarray from_dlpack_capsule(object py_caps) except +: cpdef from_dlpack(array): - """ - dpctl.tensor.from_dlpack(obj) -> dpctl.tensor.usm_ndarray + """ from_dlpack(obj) Constructs :class:`dpctl.tensor.usm_ndarray` instance from a Python object `obj` that implements `__dlpack__` protocol. The output array is always a zero-copy view of the input. + Args: + obj: A Python object representing an array that supports `__dlpack__` + protocol. + + Returns: + out (usm_ndarray): + An array with a view into the tensor underlying the input `obj`. + + Raises: + TypeError: if `obj` does not implement `__dlpack__` method. + ValueError: if zero copy view can not be constructed because + the input array resides on an unsupported device. + See https://dmlc.github.io/dlpack/latest/ for more details. :Example: @@ -498,13 +510,6 @@ cpdef from_dlpack(array): C = Container(dpt.linspace(0, 100, num=20, dtype="int16")) X = dpt.from_dlpack(C) - Args: - obj: A Python object representing an array that supports `__dlpack__` - protocol. - Raises: - TypeError: if `obj` does not implement `__dlpack__` method. - ValueError: if zero copy view can not be constructed because - the input array resides on an unsupported device. """ if not hasattr(array, "__dlpack__"): raise TypeError( diff --git a/dpctl/tensor/_reshape.py b/dpctl/tensor/_reshape.py index 8b812dcd14..67350c53b6 100644 --- a/dpctl/tensor/_reshape.py +++ b/dpctl/tensor/_reshape.py @@ -76,11 +76,26 @@ def reshaped_strides(old_sh, old_sts, new_sh, order="C"): def reshape(X, shape, order="C", copy=None): - """ - reshape(X: usm_ndarray, shape: tuple, order="C") -> usm_ndarray + """reshape(x, shape, order="C") + + Reshapes array `x` into new shape. + + Args: + x (usm_ndarray): + input array + shape (tuple): + 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. - Reshapes given usm_ndarray into new shape. Returns a view, if possible, - a copy otherwise. Memory layout of the copy is controlled by order keyword. + 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